Skip to main content

Lesson 10 of 10

Practice & Quiz - Network Security Controls

Test your network security knowledge: firewall rule analysis, IDS/IPS tuning, VPN protocols, DDoS mitigation, and network segmentation with a practical iptables exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - iptables & Network Security Automation

Practical Exercise - iptables & Network Security Automation
#!/usr/bin/env python3
"""Generate and validate iptables firewall rules with Python."""
import subprocess, ipaddress, re
from dataclasses import dataclass, field
from enum import Enum

class Action(Enum):
    ACCEPT = 'ACCEPT'
    DROP   = 'DROP'
    REJECT = 'REJECT'  # REJECT sends RST; DROP silently discards
    LOG    = 'LOG'

@dataclass
class FirewallRule:
    """Represents an iptables rule with validation."""
    chain:      str            # INPUT, OUTPUT, FORWARD
    action:     Action
    protocol:   str = 'all'   # tcp, udp, icmp, all
    src_ip:     str = '0.0.0.0/0'
    dst_ip:     str = '0.0.0.0/0'
    dst_port:   int | None = None
    comment:    str = ''

    def __post_init__(self):
        # Validate IP ranges
        ipaddress.ip_network(self.src_ip, strict=False)
        ipaddress.ip_network(self.dst_ip, strict=False)
        if self.dst_port and not (1 <= self.dst_port <= 65535):
            raise ValueError(f'Invalid port: {self.dst_port}')

    def to_iptables(self) -> str:
        """Generate the iptables command string."""
        parts = ['iptables', '-A', self.chain]
        if self.protocol != 'all':
            parts.extend(['-p', self.protocol])
        if self.src_ip != '0.0.0.0/0':
            parts.extend(['-s', self.src_ip])
        if self.dst_ip != '0.0.0.0/0':
            parts.extend(['-d', self.dst_ip])
        if self.dst_port:
            parts.extend(['--dport', str(self.dst_port)])
        if self.comment:
            parts.extend(['-m', 'comment', '--comment', f'"{self.comment}"'])
        parts.extend(['-j', self.action.value])
        return ' '.join(parts)

def build_secure_firewall(server_ip: str, allowed_admin_ips: list[str]) -> list[FirewallRule]:
    """Production-grade server firewall ruleset."""
    rules = [
        # ─── 1. Default-deny base rules ──────────────────────
        # Always flush and set default DROP before adding allow rules
        # (applied via iptables -P INPUT DROP)

        # ─── 2. Stateful connection tracking ─────────────────
        # Allow established/related connections (return traffic for outbound)
        # This rule: iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

        # ─── 3. Loopback ──────────────────────────────────────
        FirewallRule('INPUT', Action.ACCEPT, src_ip='127.0.0.1', comment='allow loopback'),

        # ─── 4. ICMP (ping) - limited ─────────────────────────
        # Allow ping but rate-limit to prevent ping floods
        FirewallRule('INPUT', Action.ACCEPT, protocol='icmp', comment='allow ICMP ping'),

        # ─── 5. SSH - restricted to admin IPs ─────────────────
        *[FirewallRule('INPUT', Action.ACCEPT, protocol='tcp',
                       src_ip=admin_ip, dst_port=22,
                       comment=f'SSH from admin {admin_ip}')
          for admin_ip in allowed_admin_ips],

        # ─── 6. Web traffic ───────────────────────────────────
        FirewallRule('INPUT', Action.ACCEPT, protocol='tcp', dst_port=80,  comment='HTTP'),
        FirewallRule('INPUT', Action.ACCEPT, protocol='tcp', dst_port=443, comment='HTTPS'),

        # ─── 7. Block known bad actors ────────────────────────
        # In production: regularly update from threat intel feeds
        FirewallRule('INPUT', Action.DROP, src_ip='185.220.0.0/16', comment='Tor exit nodes'),
        FirewallRule('INPUT', Action.DROP, src_ip='192.42.116.0/24', comment='Known scanner'),

        # ─── 8. Rate limiting - prevent brute force ───────────
        # iptables -A INPUT -p tcp --dport 22 -m limit --limit 3/min -j ACCEPT
        # (hashlimit for per-IP limiting)

        # ─── 9. Log dropped packets ───────────────────────────
        FirewallRule('INPUT', Action.LOG, comment='log dropped input'),
        FirewallRule('INPUT', Action.DROP, comment='default deny input'),
    ]
    return rules

# Generate and print ruleset
admin_ips = ['10.0.0.1/32', '192.168.1.100/32']
rules = build_secure_firewall('10.0.1.50', admin_ips)

print('=== Generated iptables Ruleset ===')
print('# Flush and set defaults')
print('iptables -F && iptables -X')
print('iptables -P INPUT DROP && iptables -P FORWARD DROP && iptables -P OUTPUT ACCEPT')
print('iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT')
print()
for rule in rules:
    cmd = rule.to_iptables()
    print(f'{cmd}  # {rule.comment}')

# ─── Snort rule analysis ──────────────────────────────────────
snort_rules = [
    'alert tcp any any -> $HTTP_SERVERS 80 (msg:"SQL Injection attempt"; content:"UNION SELECT"; nocase; sid:1000001;)',
    'alert icmp any any -> any any (msg:"ICMP Ping Sweep"; detection_filter:track by_src,count 10,seconds 5; sid:1000002;)',
    'alert tcp $EXTERNAL_NET any -> $HOME_NET 22 (msg:"SSH brute force"; detection_filter:track by_src,count 5,seconds 60; sid:1000003;)',
]
print('\n=== Snort Rules ===')
for rule in snort_rules:
    print(f'  {rule}')

Module Quiz

Module Quiz
Question 1 of 5

What is the difference between a stateful and stateless firewall?

Tip

Tip

Practice Practice Quiz Network Security Controls in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Network Security Controls from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz Network Security Controls is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/10 done