firewall.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Pure builders for firewall rules (ufw + nftables) from a port list.
  2. export type PortProtocol = 'tcp' | 'udp' | 'both';
  3. export interface PortRule {
  4. port: number;
  5. protocol: PortProtocol;
  6. label?: string;
  7. }
  8. export interface FirewallOptions {
  9. ports: PortRule[];
  10. allowSsh: boolean;
  11. sshPort: number;
  12. }
  13. function expand(protocol: PortProtocol): ('tcp' | 'udp')[] {
  14. return protocol === 'both' ? ['tcp', 'udp'] : [protocol];
  15. }
  16. export function buildUfwCommands(o: FirewallOptions): string {
  17. const lines: string[] = [];
  18. if (o.allowSsh) lines.push(`ufw allow ${o.sshPort}/tcp # SSH`);
  19. for (const rule of o.ports) {
  20. for (const proto of expand(rule.protocol)) {
  21. const comment = rule.label ? ` # ${rule.label}` : '';
  22. lines.push(`ufw allow ${rule.port}/${proto}${comment}`);
  23. }
  24. }
  25. lines.push('ufw enable');
  26. return lines.join('\n');
  27. }
  28. export function buildNftablesRuleset(o: FirewallOptions): string {
  29. const accepts: string[] = [];
  30. if (o.allowSsh) accepts.push(` tcp dport ${o.sshPort} accept # SSH`);
  31. for (const rule of o.ports) {
  32. for (const proto of expand(rule.protocol)) {
  33. const comment = rule.label ? ` # ${rule.label}` : '';
  34. accepts.push(` ${proto} dport ${rule.port} accept${comment}`);
  35. }
  36. }
  37. return `#!/usr/sbin/nft -f
  38. flush ruleset
  39. table inet filter {
  40. chain input {
  41. type filter hook input priority 0; policy drop;
  42. iif "lo" accept
  43. ct state established,related accept
  44. icmp type echo-request accept
  45. ${accepts.join('\n')}
  46. }
  47. chain forward {
  48. type filter hook forward priority 0; policy drop;
  49. }
  50. chain output {
  51. type filter hook output priority 0; policy accept;
  52. }
  53. }`;
  54. }