Sub topic 16
Ports in Firewall Rules
This chapter assumes you know what a port is, how TCP and UDP differ, what ephemeral client ports are, and the default ports of common protocols from the earlier chapters. You should be comfortable reading a short Python script and running commands in a terminal.
What a port-based rule matches
A packet filter looks at packet headers and compares them to an ordered list of rules. The fields most rules use are:
- The transport protocol (TCP, UDP, or ICMP, which has no ports).
- The source and destination IP addresses.
- The source and destination ports.
- The direction: inbound to the host, outbound from it, or forwarded through it.
A rule such as "allow TCP to destination port 443" says nothing about HTTPS. It matches any TCP packet addressed to port 443. The firewall does not read the payload. This matters later, when we look at non-standard ports.
Most rules constrain the destination port, because that is the port a server listens on. The source port of a client is an ephemeral port chosen by its operating system, so matching on it is rarely useful.
Default deny and the allow-list
A sound policy starts from "drop everything" and adds a rule for each service you intend to expose. This is called default deny. Each open port is a reachable piece of software, so the rule set should be as short as the service list.
A service inventory turns directly into rules:
| Service on the host | Rule (inbound) | Notes |
|---|---|---|
| Web server | TCP 80, TCP 443 | Port 80 is often kept only to redirect to HTTPS |
| SSH | TCP 22 from admin network only | Restrict by source address |
| Authoritative DNS | UDP 53 and TCP 53 | Both are needed |
| DHCP server | UDP 67 | Clients send from UDP 68 |
| Database | TCP 5432 from the app subnet only | Never open to the internet |
Stateful and stateless filtering
A stateless filter judges each packet alone. To allow a client to browse the web, you would need an outbound rule for destination port 443 and an inbound rule that accepts replies from source port 443 to the client's ephemeral port. Because ephemeral ports span a large range, such as 32768-60999 on Linux, that inbound rule is wide.
A stateful filter tracks connections. It records an outbound connection and automatically accepts the matching replies. You only write rules for new connections, and the return traffic is allowed as part of the tracked flow. Linux netfilter, most commercial firewalls and cloud security groups work this way. Cloud network ACLs are a common stateless exception.
A working rule set with nftables
This example uses nftables, the current packet filter on most Linux distributions. It protects a host that serves web pages and accepts SSH only from one admin network. Save it as /etc/nftables.conf:
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
ct state established,related accept
ct state invalid drop
iif "lo" accept
ip protocol icmp accept
ip6 nexthdr ipv6-icmp accept
tcp dport 22 ip saddr 192.0.2.0/24 accept
tcp dport { 80, 443 } accept
}
}Read it from the top:
policy dropsets default deny for inbound traffic.ct state established,related acceptis the stateful part. It admits replies to connections the host started and connections already accepted.iif "lo" acceptkeeps local services, such as a database listening on localhost, working.- ICMP is accepted because path MTU discovery and IPv6 neighbor discovery depend on it. Blocking all ICMP is a classic cause of mysterious hangs.
- The last two rules are the actual port allow-list. The SSH rule also matches a source network, so it is narrower than the web rule.
Load and inspect it with:
sudo nft -f /etc/nftables.conf
sudo nft list rulesetOutbound rules and returning traffic
Inbound filtering is the minimum. Outbound (egress) filtering limits what a compromised host can do, such as sending spam or contacting a command server. Typical egress decisions are:
- Allow DNS (UDP and TCP 53) only to your own resolvers.
- Allow TCP 443 and 80 to the internet, or only to a proxy.
- Block outbound TCP 25 from ordinary workstations and servers. Only designated mail servers should send mail directly. Users submit mail on port 587.
- Block outbound SMB (TCP 445) and Telnet (TCP 23) to the internet.
Protocols that complicate port rules
Some protocols do not fit the "one port, one rule" idea.
- DNS uses UDP 53 for most queries and TCP 53 for large responses and zone transfers. Allowing only UDP breaks some lookups in ways that are hard to trace.
- FTP uses TCP 21 for control, but the data connection uses a second port. In passive mode the server picks a high port, so you must pin that range in the server configuration and open it. Many firewalls have an FTP helper that reads the control channel and opens the port, which fails once the control channel is encrypted.
- DHCP clients have no IP address yet. They broadcast from UDP 68 to UDP 67, so a rule that matches on a source subnet will not match them.
- NAT and port forwarding rewrite destination ports. A forward from public TCP 8443 to an internal host's TCP 443 means the firewall sees one port and the server sees another. Write the filter rule against the address and port as it appears at the point where the rule is evaluated.
Drop versus reject
A firewall can silently drop a packet or actively reject it. A reject sends a TCP reset (RST) or an ICMP unreachable message. The difference is visible from the client:
| Server state | What the client sees |
|---|---|
| Port open, service listening | Connection succeeds |
| Port closed, no firewall block, or a reject rule | Immediate "connection refused" |
| Packet dropped by firewall | Timeout after several seconds |
The following script uses that difference to report what it sees. Run it only against hosts you own or are authorized to test.
import socket
import sys
def probe(host, port, timeout=3.0):
try:
with socket.create_connection((host, port), timeout=timeout):
return "open"
except ConnectionRefusedError:
return "closed (connection refused)"
except socket.timeout:
return "filtered or host unreachable (timeout)"
except OSError as exc:
return f"error: {exc}"
if __name__ == "__main__":
host = sys.argv[1]
for port in (22, 80, 443, 3306):
print(f"{host}:{port} -> {probe(host, port)}")A timeout does not prove a firewall exists. A powered-off host or a bad route gives the same result. Compare with a port you know is open to separate those cases.
Non-standard ports and the limits of port rules
Changing a service to another port, such as SSH on 2222, removes traffic from automated scans of the default port. It does not stop a determined attacker, who can scan all 65535 ports. Treat it as noise reduction, not as a security control.
The reverse also holds. A rule that allows TCP 443 permits any protocol that uses it, including tunnels and proxies, because the firewall only sees the port number. Blocking a protocol by port therefore fails when the protocol moves. To control applications rather than ports you need a proxy, deep packet inspection, or identity-based policy.
Common mistakes
- Opening a database port to
0.0.0.0/0instead of the application subnet. - Allowing UDP 53 but not TCP 53.
- Forgetting the
established,relatedrule, so replies are dropped. - Blocking all ICMP.
- Adding an allow rule after a broader drop rule in a first-match rule set. Order matters in most firewalls.
- Opening the port in the network firewall but not in the host firewall, or the reverse. Both layers must permit the traffic.
Exercise
A server runs HTTPS on TCP 443. From a client, connecting to port 443 times out, but connecting to a closed port on the same server returns "connection refused" immediately. What does this suggest, and what do you check first?
Show answer
A timeout on 443 while a closed port refuses at once suggests that something drops packets to 443 specifically, such as a firewall rule or a security group, rather than the service being down. If the service were stopped and nothing filtered the port, 443 would also refuse. Check the network firewall or cloud security group for an allow rule for TCP 443 from the client's address, then the host firewall (for example sudo nft list ruleset), then confirm with ss -tlnp that something is listening on 443.
Exercise
Write the allow rules (protocol, port, source) for a host that serves a website to everyone, accepts SSH only from 198.51.100.0/24, and acts as a DNS resolver for that same /24 network only.
Show answer
TCP 80 and TCP 443 from any source. TCP 22 from 198.51.100.0/24. UDP 53 and TCP 53 from 198.51.100.0/24. Everything else is dropped by the default policy, with established and related return traffic accepted by the state rule.