Firewall Rule Generator

Generate firewall rules for iptables, UFW, macOS pf, and Windows Defender Firewall.

Common Ports

Часто задаваемые вопросы

Реализация кода

#!/usr/bin/env python3
"""Firewall rule generator — outputs iptables and UFW commands."""

def iptables_allow(port: int, protocol: str = "tcp", source: str = None) -> str:
    src = f"-s {source} " if source else ""
    return f"sudo iptables -A INPUT {src}-p {protocol} --dport {port} -j ACCEPT"

def iptables_block(port: int = None, source: str = None, protocol: str = "tcp") -> str:
    parts = ["sudo iptables -I INPUT"]
    if source:
        parts.append(f"-s {source}")
    if port:
        parts.extend([f"-p {protocol}", f"--dport {port}"])
    parts.append("-j DROP")
    return " ".join(parts)

def ufw_allow(port: int, protocol: str = "tcp", source: str = None) -> str:
    if source:
        return f"sudo ufw allow from {source} to any port {port} proto {protocol}"
    return f"sudo ufw allow {port}/{protocol}"

def ufw_deny(port: int = None, source: str = None) -> str:
    if source and not port:
        return f"sudo ufw deny from {source}"
    if port:
        return f"sudo ufw deny {port}/tcp"
    return "sudo ufw deny from any"

# Examples
print("=== Allow SSH from specific IP ===")
print(iptables_allow(22, "tcp", "192.168.1.0/24"))
print(ufw_allow(22, "tcp", "192.168.1.0/24"))

print("\n=== Allow HTTP and HTTPS ===")
for port in [80, 443]:
    print(iptables_allow(port, "tcp"))
    print(ufw_allow(port, "tcp"))

print("\n=== Block IP ===")
print(iptables_block(source="10.0.0.5"))
print(ufw_deny(source="10.0.0.5"))

print("\n=== Save iptables rules (Ubuntu/Debian) ===")
print("sudo netfilter-persistent save")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.