iptables-essentials

repository·master·Indexed 23 days ago

https://github.com/trimstray/iptables-essentials

A collection of essential iptables rules, commands, and sysctl kernel settings for securing Linux systems. It provides practical examples for rule management, security hardening (SYN flood and SSH brute-force protection), and advanced configurations including packet handling in Python using the NFQUEUE target and port knocking implementations.

Tokens
3.2K
Snippets
8
Records
16
Agent score
32%

What's inside iptables-essentials

  1. Overview of Iptables Essentials

    master
    Iptables Essentials is a repository providing common firewall rules, commands, and kernel configuration settings for managing Linux firewalls via iptables. It includes practical examples for rule management, security hardening (such as SYN flood protection and SSH brute-force protection), and advanced configuration like packet handling in Python using the NFQUEUE target.
  2. Flush and reset iptables rules

    master

    To clear your firewall configuration, you can flush specific chains or reset the entire system.

    Warning: Flushing rules can leave your system unprotected. It is recommended to set default policies to ACCEPT before flushing to prevent being locked out of a remote system.

    # 1. Set default policies to ACCEPT to prevent lockout
    iptables -P INPUT ACCEPT
    iptables -P FORWARD ACCEPT
    iptables -P OUTPUT ACCEPT
    
    # 2. Flush NAT and Mangle tables
    iptables -t nat -F
    iptables -t mangle -F
    
    # 3. Flush Filter table and delete all custom chains
    iptables -F
    iptables -X
    
    # Alternatively, flush a single chain
    iptables -F INPUT
  3. Configure kernel security settings via sysctl

    master

    You can harden your network stack by configuring kernel parameters using sysctl. These settings are applied by adding them to a configuration file in /etc/sysctl.d/ (e.g., /etc/sysctl.d/40-custom.conf).

    Common security hardening tasks include:

    • Enabling Reverse Path Filtering (rp_filter): Protects against IP spoofing by ensuring responses go out the same interface they arrived on.
    • Logging Martian Packets (log_martians): Enables logging for packets with malformed IP addresses.
    • Disabling ICMP Redirects: Prevents the system from sending (send_redirects = 0) or accepting (accept_redirects = 0) ICMP redirect packets.
    • Disabling Source Routing (accept_source_route): Prevents the use of Strict Source Route (SSR) or Loose Source Routing (LSR) options.
    • Enabling SYN-flood Protection (tcp_syncookies): Protects against Denial of Service (DoS) attacks.
    • Ignoring ICMP Broadcasts (icmp_echo_ignore_broadcasts): Prevents the system from responding to ping broadcasts.
    • Enabling IP Forwarding (ip_forward): Required if the machine acts as a router or performs NAT.
    # Example: Enable SYN-flood protection
    cat << EOF >> /etc/sysctl.d/40-custom.conf
    net/ipv4/tcp_syncookies = 1
    EOF
    
    # Example: Disable ICMP redirects
    cat << EOF >> /etc/sysctl.d/40-custom.conf
    net/ipv4/conf/all/send_redirects = 0
    EOF
  4. Configure common service access (SSH, HTTP, MySQL, etc.)

    master

    These patterns allow traffic for specific services by matching the protocol (-p), destination port (--dport), and connection state (-m conntrack --ctstate).

    Note: For bidirectional communication, you often need to allow the incoming request on the service port and the outgoing response on the source port (--sport).

    # Allow All Incoming SSH
    iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
    iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT
    
    # Allow Incoming HTTP and HTTPS (using multiport)
    iptables -A INPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
    iptables -A OUTPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate ESTABLISHED -j ACCEPT
    
    # Allow MySQL from a specific subnet
    iptables -A INPUT -p tcp -s 192.168.240.0/24 --dport 3306 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
    iptables -A OUTPUT -p tcp --sport 3306 -m conntrack --ctstate ESTABLISHED -j ACCEPT
  5. Save iptables rules

    master

    To ensure your firewall rules persist after a reboot, use the command appropriate for your Linux distribution:

    • Debian-based systems: Use netfilter-persistent save.
    • RedHat-based systems: Use service iptables save.
    # Debian Based
    netfilter-persistent save
    
    # RedHat Based
    service iptables save
  6. Protect against SYN floods and port scanning

    master

    Use custom chains and the limit module to mitigate common network attacks.

    SYN Flood Protection

    Create a syn_flood chain that limits the rate of incoming SYN packets.

    Port Scanning Protection

    Create a port-scanning chain that uses the limit module to drop rapid connection attempts.

    SSH Brute-force Protection

    Use the recent module to track connection attempts and drop IPs that exceed a threshold (e.g., 10 attempts in 60 seconds).

    # SSH brute-force protection
    iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --set
    iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 10 -j DROP
    
    # SYN-flood protection
    iptables -N syn_flood
    iptables -A INPUT -p tcp --syn -j syn_flood
    iptables -A syn_flood -m limit --limit 1/s --limit-burst 3 -j RETURN
    iptables -A syn_flood -j DROP
  7. Handle packets in userspace using the NFQUEUE target

    master

    The NFQUEUE target allows you to pass packets from the kernel to a userspace application using the nfnetlink_queue handler. Packets are assigned to a specific 16-bit queue number. The userspace application can inspect, modify, drop, or reinject the packet back into the kernel.

    To forward all filter:INPUT packets to queue 1, use the following command:

    iptables -A INPUT -j NFQUEUE --queue-num 1
  8. Implement Port Knocking to secure SSH access

    master

    Port knocking secures services like SSH by dropping all standard requests and only allowing access after a specific sequence of packets (a "knock") is detected in userspace.

    1. Configure Iptables

    First, drop all incoming SSH requests on port 22, then redirect specific secret port traffic to NFQUEUE queue 1:

    iptables -t filter -I INPUT -p tcp --dport 22 -j DROP
    iptables -t raw -I PREROUTING -p tcp --sport 65534 --dport 65535 -j NFQUEUE --queue-num 1

    2. Userspace Port Knocking Script

    The following Python script monitors queue 1. When it detects a packet with the correct SOURCEPORT (65534) and SECRETPORT (65535), it dynamically inserts an iptables rule to allow that source IP to access SSH for a defined EXPIRETIME (default 30 minutes).

    #!/usr/bin/python3
    
    from os	import system
    from netfilterqueue import NetfilterQueue
    from scapy.layers.inet import IP
    from time import time
    
    SOURCEPORT=65534
    SECRETPORT=65535
    EXPIRETIME=30
    ALLOWED={}
    
    def portknocking(pkt):
        packet=IP(pkt.get_payload())
        currtime=time()
        for item in list(ALLOWED):
            if(currtime-ALLOWED[item] >= EXPIRETIME*60):
                del ALLOWED[item]
        if(packet.sport==SOURCEPORT and packet.dport==SECRETPORT and packet.src not in ALLOWED):
            print(f"Port {packet.dport} knocked by {packet.src}:{packet.sport}")
            system(f"iptables -I INPUT -p tcp --dport 22 -s {packet.src} -j ACCEPT")
            system(f"echo 'iptables -D INPUT -p tcp --dport 22 -s {packet.src} -j ACCEPT' | at now + {EXPIRETIME} minutes")
            ALLOWED[packet.src]=time()
            pkt.drop()
    
    nfqueue=NetfilterQueue()
    nfqueue.bind(1, portknocking)
    
    try:
        nfqueue.run()
    except KeyboardInterrupt:
        print("\nExit with Keyboard Interrupt")

    3. Perform the Knock

    To trigger the access from a client machine, use nc (netcat) to send a packet to the server's secret ports:

    nc -p 65534 SERVER 65535
  9. Analyze and filter packets with Python and NFQUEUE

    master

    You can use the netfilterqueue and scapy libraries in Python to inspect packets arriving via an NFQUEUE target. In the example below, the script binds to queue 1 and accepts packets only if they originate from a specific IP address (192.168.122.1), dropping all others.

    #!/usr/bin/python3
    
    from netfilterqueue import NetfilterQueue
    from scapy.all import *
    
    def packetanalyzer(pkt):
        ip=IP(pkt.get_payload())
        if(ip.src=="192.168.122.1"):
            print(f"New packet from {ip.src}")
            pkt.accept()
        else:
    	pkt.drop()
    
    nfqueue=NetfilterQueue()
    nfqueue.bind(1, packetanalyzer)
    nfqueue.run()
  10. External resources for Iptables learning

    master

    For in-depth learning and best practices, refer to these external guides:

    • Best practices: iptables by Major Hayden
    • An In-Depth Guide to Iptables, the Linux Firewall (Boolean World)
    • Advanced Features of netfilter/iptables (Linux Gazette)
    • Linux Firewalls Using iptables (Linux Home Networking)
    • Debugging iptables and common firewall pitfalls? (Server Fault)
    • Netfilter Hacking HOWTO (Netfilter.org)
    • Per-IP rate limiting with iptables (Pusher)
  11. List and inspect active iptables rules

    master

    Use the following commands to view your current firewall configuration:

    • Verbose list: iptables -n -L -v (shows packet counts and interface details).
    • Verbose list with line numbers: iptables -n -L -v --line-numbers (useful for identifying which rule to delete).
    • Print rule specifications: iptables -S (shows the exact commands used to create the rules).
    • List rules for a specific chain: Use iptables -L <CHAIN_NAME> (e.g., iptables -L INPUT) or iptables -S <CHAIN_NAME>.