> ## Content Index
> Fetch the complete content index at: https://www.novea.cc/llms.txt
> Use this file to discover other available public pages before exploring further.

# iptables from Scratch: Part 2 | Writing a Policy
- URL: https://www.novea.cc/iptables-from-scratch-part-2-writing-a-policy/
- Published: 2026-09-05T17:44:44.000Z
- Updated: 2026-09-05T17:44:44.000Z
- Description: Default deny, state tracking and the exact commands that turn a bare VPS into a closed box.
- Author: Ethan Nicolas
- Tags: Linux, Networking, Security

Part 1 covered tables, chains and targets. Now we write a real policy — the kind that makes a fresh VPS stop being an open door. The philosophy in one line: deny by default, then open exactly what you use.

## Set the default to no

```
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
```

OUTPUT stays open so your box can reach updates and DNS. Everything inbound now dies unless a rule says otherwise. If you run this over SSH, your next command had better be the SSH rule.

## Allow the conversation, not the knock

```
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
```

The first rule is the one that makes a stateful firewall usable: replies to connections you started are allowed, without opening any port. The second keeps loopback working — half of localhost debugging is a firewall that forgot this line.

## Then open the doors you actually use

```
iptables -A INPUT -p tcp --dport 22 -j ACCEPT    # ssh
iptables -A INPUT -p tcp --dport 80 -j ACCEPT    # http
iptables -A INPUT -p tcp --dport 443 -j ACCEPT   # https
```

Every extra port is surface area. When a service is temporary, remove its rule when you remove the service — a firewall full of forgotten allowances is a firewall that lied to you.

## Test like the internet is watching

```
iptables -L -n -v                 # what is actually loaded
iptables -Z                       # zero the counters, wait a day, re-check
```

Counter columns tell you which rules ever matched. A rule with zero hits after a week is either protecting nothing or wrong. Also test from outside, not from the box: local traffic takes a different path and will not tell you what the internet sees.

## Make it survive the reboot

```
apt install iptables-persistent
netfilter-persistent save
```

A firewall that vanishes on reboot is a firewall you will forget you had — until the day it matters. Save the ruleset, and re-save it every time you change it.

That is a complete, boring, working policy. Part 3 takes the same policy and turns it into NAT, port forwarding and the rules that let one public IP serve several machines.