TExcelTAD
Home › Network Security: Discovery, Segmentation, Firewalls, VPN & IDS › iptables, ufw, firewalld and Cloud Security Groups

iptables, ufw, firewalld and Cloud Security Groups

A reviewer rarely meets only hand-written nftables. On Linux hosts you find iptables rules (often translated to nftables underneath), front-ends such as ufw and firewalld that generate rules from simpler commands, and container runtimes adding their own chains. In the cloud the firewall is an API object: security groups and network ACLs with their own evaluation rules. The security questions are always the same (what is allowed, from where, in which order, with what default), but each system answers them differently, and misreading the evaluation model is a common source of findings.

iptables: the legacy you still read

iptables organises rules in tables (filter, nat, mangle, raw) and built-in chains (INPUT, FORWARD, OUTPUT, PREROUTING, POSTROUTING), each with a policy. A typical host export (iptables-save):

text
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -m conntrack --ctstate INVALID -j DROP
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
-A INPUT -s 10.10.5.0/26 -p tcp --dport 22 -j ACCEPT
-A INPUT -m limit --limit 10/sec -j LOG --log-prefix "in-drop: "
COMMIT

It is the nftables ruleset of Reading and Writing nftables Rulesets in older words: same order rules, same connection tracking. Three review facts specific to iptables:

  • IPv6 is a separate ruleset (ip6tables-save). An IPv4 policy with no IPv6 rules and an ACCEPT IPv6 policy is a classic finding.
  • On current distributions iptables is usually iptables-nft, which writes nftables tables named ip filter etc.; iptables -V says (nf_tables) or (legacy). Mixing legacy and nft back-ends on one host gives two rulesets that both apply. iptables-translate converts rules to nft syntax for migration.
  • Docker inserts chains (DOCKER, DOCKER-USER) into FORWARD and nat: published container ports bypass rules in INPUT. Put your restrictions in DOCKER-USER.

ufw and firewalld: front-ends

ufw (Ubuntu) firewalld (RHEL, Fedora, SUSE)
Model allow/deny rules on top of a default policy zones (trust levels) with services and ports; interfaces and sources are assigned to zones
Inspect ufw status verbose, ufw show added firewall-cmd --get-active-zones, --list-all --zone=…
Review traps ufw allow 22 allows from anywhere, IPv4 and IPv6; rules are ordered as added; ufw rules don't apply to Docker-published ports runtime vs permanent configuration differ until --runtime-to-permanent; an interface in the trusted zone accepts everything; rich rules add order-sensitive exceptions

Both are fine tools; the review always ends with the generated rules (nft list ruleset) because that is what the kernel enforces. Usage is in ufw and firewalld.

Cloud firewalls: two evaluation models

Cloud providers offer two kinds of network filters, and they are evaluated very differently:

Security group (AWS SG, also Azure NSG/GCP firewall in spirit) Network ACL (AWS NACL)
Attached to an instance's network interface a subnet
State stateful: replies are allowed automatically stateless: return traffic needs its own rule (ephemeral ports)
Rules allow only; all rules are evaluated, any match allows allow and deny, numbered, lowest number first, first match wins
Default deny inbound, allow outbound (AWS default SG allows traffic from members of the same group) the default NACL allows all; custom NACLs deny all until rules are added
Source can be CIDR, or another security group (members of that group) CIDR only

Azure NSGs and GCP VPC firewall rules use numeric priorities with allow and deny, first match by priority, and are stateful. Always check which model you are reading.

The program evaluates the same packets against an AWS-style security group and NACL for the lab's web tier, to show the two models side by side (a simplified model, not any provider's code).

python · try it yourself
import ipaddress

def inside(ip, cidr):
    return ipaddress.ip_address(ip) in ipaddress.ip_network(cidr)

# Security group for the web instances: allow-only, stateful, sources may be CIDRs or other groups.
SG_WEB = [("tcp", 443, "0.0.0.0/0"), ("tcp", 22, "sg-bastion")]
MEMBERS = {"sg-bastion": {"10.10.5.20"}}
def sg_allows(proto, port, src):
    for p, prt, source in SG_WEB:                         # any matching rule allows; order is irrelevant
        if p == proto and prt == port and (src in MEMBERS.get(source, ()) if source.startswith("sg-") else inside(src, source)):
            return True
    return False

# NACL on the web subnet: numbered, first match wins, stateless (inbound rules shown).
NACL_IN = [(100, "tcp", (443, 443), "0.0.0.0/0", "allow"),
           (110, "tcp", (22, 22), "10.10.5.0/26", "allow"),
           (120, "tcp", (1024, 65535), "0.0.0.0/0", "allow"),      # return traffic for outbound calls
           (90,  "tcp", (0, 65535), "198.51.100.0/24", "deny"),   # block a known-bad range
           (32767, "all", (0, 65535), "0.0.0.0/0", "deny")]       # the implicit final deny ("*")
def nacl(proto, port, src):
    for num, p, (lo, hi), cidr, action in sorted(NACL_IN):
        if p in (proto, "all") and lo <= port <= hi and inside(src, cidr):
            return f"{action} (rule {num})"

packets = [("tcp", 443, "203.0.113.7", "HTTPS visitor"), ("tcp", 22, "10.10.5.20", "SSH from bastion"),
           ("tcp", 22, "10.10.5.21", "SSH from another admin PC"), ("tcp", 443, "198.51.100.9", "HTTPS from bad range"),
           ("tcp", 3306, "203.0.113.7", "MySQL probe"), ("tcp", 50514, "192.0.2.80", "reply to our download")]
print(f"{'packet':28} {'NACL (subnet)':16} {'SG (instance)':14} result")
for proto, port, src, what in packets:
    n = nacl(proto, port, src)
    reply = what.startswith("reply")
    s = True if reply else sg_allows(proto, port, src)      # the SG is stateful: replies pass
    result = "delivered" if n.startswith("allow") and s else "blocked"
    print(f"{what:28} {n:16} {'allow' if s else 'deny':14} {result}")
packet                       NACL (subnet)    SG (instance)  result
HTTPS visitor                allow (rule 100) allow          delivered
SSH from bastion             allow (rule 110) allow          delivered
SSH from another admin PC    allow (rule 110) deny           blocked
HTTPS from bad range         deny (rule 90)   allow          blocked
MySQL probe                  allow (rule 120) deny           blocked
reply to our download        allow (rule 120) allow          delivered

Read the rows carefully:

  • The bad range is blocked only because NACL rule 90 comes before rule 100; renumber it to 130 and the HTTPS rule lets it in first.
  • The MySQL probe passes the NACL (rule 120, the ephemeral-port allow needed for return traffic, matches port 3306 too) and is stopped only by the security group. Stateless ephemeral-port rules are broad by nature; the stateful layer does the real work.
  • SSH from another admin PC in the admin network passes the NACL but not the security group, whose source is the bastion's group, not a CIDR. Group references are the cloud's version of microsegmentation labels (Microsegmentation).

How cloud firewall issues are found

  • Export and review: aws ec2 describe-security-groups / describe-network-acls, az network nsg list, gcloud compute firewall-rules list, or the provider's config inventory.
  • Look for 0.0.0.0/0 (and ::/0) on admin and database ports, unused groups, groups attached to more instances than intended, and NACL rule numbers that put allows before denies.
  • Cloud security posture management (CSPM) tools and the providers' own analysers (reachability analysers, firewall insights) automate these checks; the planned Cloud & Container Security course goes further.
  • Flow logs (VPC flow logs, NSG flow logs) show what actually crosses, accepted and rejected.

Pitfalls

  • Reviewing the security group and forgetting the host firewall and the NACL (or the other way round): the effective policy is the intersection.
  • ::/0 rules nobody notices because the review filtered for 0.0.0.0/0.
  • Infrastructure-as-code drift: the console was changed by hand and the Terraform no longer describes reality.
  • ufw or firewalld "active" while Docker publishes ports past them.

Practice

1. Change NACL rule 90 to 130 in the program. What happens to the HTTPS request from the bad range?

Rule 100 (allow 443 from anywhere) now matches first, so the NACL allows it, and the security group allows 443 from anywhere too: the request is delivered. NACL order is by rule number, not by position in the list.

2. An iptables-save shows a tight IPv4 policy; ip6tables-save shows only :INPUT ACCEPT. The server has a global IPv6 address. What is the finding?

Every service on the host is reachable over IPv6 without filtering. Apply the same policy to IPv6 (ideally one inet nftables table for both) or disable IPv6 on the interface if it isn't used.

3. Why does a NACL need an inbound rule for ports 1024–65535 when the instance makes outbound HTTPS calls?

NACLs are stateless: the reply from the remote server arrives on the ephemeral source port the instance chose, and without an inbound allow for that range the reply is dropped.

Test yourself

How are AWS security group rules evaluated?

  1. First match by number
  2. All rules are allow rules and any match allows; replies are allowed automatically
  3. Deny rules first
  4. Last match wins

How are AWS network ACL rules evaluated?

  1. Any match allows
  2. By rule number, lowest first, first match wins; stateless
  3. Randomly
  4. Only deny rules count

Why do Docker-published ports often bypass ufw rules?

  1. Docker uses UDP
  2. Docker inserts its own rules in the FORWARD/nat path, which INPUT rules from ufw don't see
  3. ufw doesn't support TCP
  4. Docker disables the firewall

In the program, what stopped the MySQL probe?

  1. The NACL
  2. The security group (no rule for 3306)
  3. Nothing, it was delivered
  4. The host firewall