|
| 1 | +from core import Port, PortType |
| 2 | +from typing import Iterable |
| 3 | + |
| 4 | +__all__ = ["generate_firewall_rules"] |
| 5 | + |
| 6 | + |
| 7 | +def fw_rule(port: int, protocol: str, name: str, description: str) -> str: |
| 8 | + """ |
| 9 | + Returns a single New-NetFirewallRule command string. |
| 10 | + """ |
| 11 | + cmd = ( |
| 12 | + f'New-NetFirewallRule ' |
| 13 | + f'-DisplayName "{name}" ' |
| 14 | + f'-Direction Inbound ' |
| 15 | + f'-Action Allow ' |
| 16 | + f'-Protocol {protocol} ' |
| 17 | + f'-LocalPort {port} ' |
| 18 | + f'-Profile Any ' |
| 19 | + f'-Description "{description}"' |
| 20 | + ) |
| 21 | + return cmd |
| 22 | + |
| 23 | +def generate_firewall_rules(ports: Iterable[Port]) -> str: |
| 24 | + """ |
| 25 | + Write a PowerShell script that adds inbound rules for the given ports. |
| 26 | + """ |
| 27 | + lines = [ |
| 28 | + "# ------------------------------------------------------------", |
| 29 | + "# Auto‑generated PowerShell script to add inbound firewall rules", |
| 30 | + "# Run this script **as Administrator** in PowerShell.", |
| 31 | + "# ------------------------------------------------------------", |
| 32 | + "", |
| 33 | + "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force", |
| 34 | + "" |
| 35 | + ] |
| 36 | + |
| 37 | + for p in ports: |
| 38 | + if p.typ is PortType.BOTH: |
| 39 | + # Create two separate rules |
| 40 | + for proto in (PortType.TCP, PortType.UDP): |
| 41 | + name = f"Allow {p.port}/{proto.value.lower()}" |
| 42 | + desc = f"Auto‑generated rule for inbound {p.port}/{proto.value.lower()}" |
| 43 | + lines.append(fw_rule(p.port, proto.value, name, desc)) |
| 44 | + lines.append("") # blank line for readability |
| 45 | + else: |
| 46 | + name = f"Allow {p.port}/{p.typ.value.lower()}" |
| 47 | + desc = f"Auto‑generated rule for inbound {p.port}/{p.typ.value.lower()}" |
| 48 | + lines.append(fw_rule(p.port, p.typ.value, name, desc)) |
| 49 | + lines.append("") |
| 50 | + |
| 51 | + return "\n".join(lines) |
0 commit comments