Salta al contenuto
Note per Studenti Firewall Configuration with iptables in Katharà Report

Firewall Configuration with iptables in Katharà

In questa pagina 6

See also: NAT and Private AddressesPrivate networks (intranets) use TCP/IP with private address blocks (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) that may be reused by different intranets but are never routed in the public Internet; to reach the Internet an intranet needs an application proxy or NAT, a router that translates private to public addresses using a NAT table and per-session mappings: Basic NAT translates only the IP address one to one, NAPT also translates the port so many sessions share one public IP, and Twice NAT adds DNS support and static mappings so sessions can also start from outside.NAT and Private Addresses →, Transport Layer - Ports and MultiplexingThe transport layer provides logical end-to-end communication between application processes on different hosts and exists only in end hosts; the network layer delivers to the right computer (IP address) and transport to the right process (16-bit port number, 0 to 65535); an IP address plus a port is a socket and the four-tuple of IPs and ports identifies a connection, with multiplexing and demultiplexing done by UDP on the destination socket and by TCP on the whole four-tuple, and the protocols are UDP (connectionless, unreliable), TCP (connection-oriented, reliable) and SCTP.Transport Layer - Ports and Multiplexing →.

Laboratory 6 shows how to build a packet-filter firewall on Linux. Theory is in FirewallsA firewall blocks unauthorised traffic between networks using header information of layers 2-4: stateless packet filters apply ordered rules per packet, stateful firewalls track connections (NEW, ESTABLISHED, RELATED, INVALID), application firewalls act as proxies; in Linux netfilter provides five hooks and iptables organises rules in tables and chains.Firewalls →; the lab is started as in Emulating Networks with KatharàKatharà is a network emulator where every device is a Docker container joined to virtual collision domains; a lab is a folder with lab.conf (topology), one .startup file per machine and optional per-device folders; machines are configured with ifconfig, tested with ping and observed with tcpdump and Wireshark.Emulating Networks with Katharà →.

Firewalls and packet filters

A firewall implements access control between networks, typically protecting a trusted LAN (Intranet) from the Internet and allowing limited access only to authorised hosts and applications. The family includes proxies and application-level firewalls and packet filters, which check incoming and outgoing packets against fixed criteria.

  • Stateless filter: examines each packet alone (protocol, source and destination addresses and ports); packets not allowed are dropped (drop, silently) or rejected (reject, with an error message).
  • Stateful filter: goes up to the transport layer, remembers packets already seen, recognises whether a packet belongs to an ongoing "conversation" or starts a new one. A conversation does not need a connection-oriented protocol: for UDP a flow is recognised, e.g. by the time between a packet and its reply. Multi-flow protocols such as FTP need deep packet inspection.

NAT (NAPT with a single public address) also helps filtering: private addresses are not routable from outside, and changing address and port keeps the state of the conversation.

NetFilter and iptables

iptables is a user-space program commanding NetFilter in the kernel, implementing a stateful filter plus NAPT (newer distributions use nftables). NetFilter has tables, containing chains, containing rules.

table purpose predefined chains
filter basic filtering INPUT, OUTPUT, FORWARD
nat translation of addresses and ports (NAPT) PREROUTING, OUTPUT, POSTROUTING
mangle packet modification (e.g. TTL) all five
raw exceptions to conversation tracking PREROUTING, OUTPUT

mangle and raw are not used in the course. Each chain is a list of rules, each with a match criterion and an action (target). The packet is handled by the first matching rule; if none matches the chain's default policy applies.

Definition (target). Action of a rule. In filter: ACCEPT; DROP (silent discard); REJECT (discard and send an error, e.g. --reject-with icmp-host-unreachable, icmp-net-unreachable, icmp-port-unreachable); a user-defined chain; RETURN; LOG (records the packet, does not end the chain, --log-level, --log-prefix). In nat: DNAT (change destination), SNAT (change source), MASQUERADE (SNAT for a dynamic public address), REDIRECT.

Example. With DROP a client connecting to a closed port waits and times out; with REJECT it gets an ICMP error immediately.

Path of a packet

Incoming (for the machine):
 interface -> nat PREROUTING (DNAT) -> routing -> filter INPUT -> local process

Outgoing (generated by the machine):
 local process -> filter OUTPUT -> routing -> nat POSTROUTING (SNAT) -> interface

Forwarded (the machine is a router):
 interface -> nat PREROUTING (DNAT) -> routing -> filter FORWARD -> nat POSTROUTING (SNAT) -> interface
  • DNAT happens before routing: INPUT and FORWARD see the "true" destination.
  • SNAT happens after the filters: they see the "true" source address.
  • Forwarded packets follow a different path from those for the machine itself. Protecting the machine is done in INPUT, protecting what is behind the router in FORWARD.

Commands

bash
iptables [--table name] --append  chain criteria --jump target     # add a rule at the end
iptables [--table name] --delete  chain criteria --jump target     # delete a rule
iptables [--table name] --insert  chain [n] criteria --jump target # insert at position n
iptables [--table name] --replace chain n criteria --jump target   # replace rule n
iptables [--table name] --list [chain]                             # show rules
iptables [--table name] --flush [chain]                            # empty a chain (or all)
iptables [--table name] --new-chain name                           # create a user chain
iptables [--table name] --delete-chain [name]                      # delete an empty user chain
iptables [--table name] --policy chain target                      # change default policy

Without --table the table is filter. Short forms: -t, -A, -I, -D, -L, -F, -P, -j, -i, -o, -s, -d, -p.

criterion option
input interface (eth0, lo for loopback) --in-interface name
output interface --out-interface name
source address or network --source address or network/mask
destination address or network --destination address or network/mask
protocol (tcp, udp, icmp) --protocol name
ICMP message type --protocol icmp --icmp-type echo-request
TCP/UDP ports --source-port n, --destination-port n
TCP flags --protocol tcp --tcp-flags SYN,ACK,FIN,RST SYN
conversation state --match state --state NEW / ESTABLISHED / RELATED

Reading network/mask. A packet matches if address AND mask=network\text{address}\ \text{AND}\ \text{mask}=\text{network}. 192.168.10.111 AND 255.255.0.0 == 192.168.0.0, so the host falls in 192.168.0.0/16 (with /24 the network would be 192.168.10.0); 203.0.113.9 gives 203.0.0.0 and does not match. An address without mask equals /32. A network covers 232−prefix2^{32-\text{prefix}} addresses: /24 256256, /16 65 53665\,536, /30 44.

States: NEW opens a conversation, ESTABLISHED belongs to an existing one, RELATED opens a conversation linked to an existing one (e.g. the FTP data channel). The conversation state is not the TCP connection state.

Formula (filter rule). iptables --table filter --append CHAIN [criteria] --jump TARGET: adds at the end of the chain a rule applying the target to packets satisfying all the criteria.

Example. iptables --table filter --append INPUT --protocol tcp --destination-port 22 --jump ACCEPT accepts incoming TCP packets to port 2222 (SSH). nat targets: --jump DNAT --to-destination address[:port], --jump SNAT --to-source address[:port], --jump MASQUERADE.

Example 1: the firewall on the machine to protect

Goal. The computer can use any Internet service, but nobody from outside can reach it except ping and ssh.

Topology. vpc and r1 in domain MYNET; ws and r2 in REMOTENET; r1 and r2 linked by domain INTERNET.

 lab.conf:
   vpc[0]=MYNET   ws[0]=REMOTENET
   r1[0]=MYNET    r1[1]=INTERNET
   r2[0]=REMOTENET r2[1]=INTERNET

 vpc 147.162.13.111/24 --- 147.162.13.254 [r1] 159.173.25.254/30 === 159.173.25.253/30 [r2] 148.163.14.254 --- 148.163.14.240 ws

159.173.25.252/30 has two hosts, .253 and .254: the smallest network for a point-to-point link.

bash
# vpc.startup
/sbin/ifconfig eth0 147.162.13.111 netmask 255.255.255.0 up
/sbin/route add default gw 147.162.13.254
/etc/init.d/apache2 start                                     # web server
/etc/init.d/ssh start                                         # SSH server
# r1.startup
ifconfig eth0 147.162.13.254 netmask 255.255.255.0 up
ifconfig eth1 159.173.25.254 netmask 255.255.255.252 up
route add -net 148.163.14.0/24 gw 159.173.25.253              # ws network is behind r2

r2 and ws are symmetric (r2 has route add -net 147.162.13.0/24 gw 159.173.25.254; ws starts only Apache). Web pages are in vpc/var/www/index.html and ws/var/www/index.html. SSH: on vpc set PermitRootLogin yes in /etc/ssh/sshd_config, restart with /etc/init.d/ssh restart and set the password with passwd (rootpwd in the lab).

Exercise 1. links 127.0.0.1 on vpc opens vpc web server works!. From ws, links 147.162.13.111 shows the same page (default policy ACCEPT); ssh [email protected] asks the password. To clear a table: iptables --table filter --flush and --delete-chain. Rules on vpc:

bash
iptables --table filter --policy INPUT DROP        # 1. everything entering is dropped...
iptables --table filter --policy OUTPUT ACCEPT     #    ...everything leaving is allowed
iptables --table filter --append INPUT --in-interface lo --jump ACCEPT   # 2. loopback exception
iptables --table filter --append INPUT --protocol icmp --icmp-type echo-request --jump ACCEPT  # 3. vpc answers ping
iptables --table filter --append INPUT --protocol tcp --destination-port 22 --jump ACCEPT      # 4. SSH allowed
iptables --table filter --append INPUT --match state --state ESTABLISHED,RELATED --jump ACCEPT # 5. replies to connections opened by vpc
after step links 127.0.0.1 on vpc ping vpc from ws ssh to vpc from ws links to vpc from ws vpc browses ws
1 (policy DROP) no (loopback blocked too) no no no no
2 (loopback) yes no no no no
3 (echo-request) yes yes no no no
4 (port 22) yes yes yes no no
5 (ESTABLISHED) yes yes yes no yes
  • Step 1. DROP blocks even local processes: without the lo exception links 127.0.0.1 fails.
  • Step 5. Even if OUTPUT is ACCEPT, the reply of ws re-enters INPUT and would be dropped; ESTABLISHED,RELATED accepts packets of conversations started by vpc. A ping from vpc works for the same reason.
  • A packet blocked by DROP produces no answer: links towards vpc waits until timeout.

Following a packet (after step 5, chain INPUT, policy DROP):

packet entering vpc rule 2 (lo) rule 3 (ICMP) rule 4 (TCP 22) rule 5 (state) outcome
ping from ws no (from eth0) yes ACCEPT
SYN from ws to port 22 no no yes ACCEPT
SYN from ws to port 80 no no no no (NEW) policy DROP
reply of ws to a web request of vpc no no no yes ACCEPT

Property (restrictive policy). Start with INPUT in DROP and add exceptions for what is needed (whitelist): whatever was not planned stays closed.

Example 2: the firewall on a LAN router

Goal. R1 lets in traffic to the public web server LANWS, but not to the other LAN hosts (LANPC1, LANPC2), while LAN computers stay free to reach the Internet. Incoming SSH is blocked except requests from LANPC1 and LANPC2 to R1.

Topology: lanpc1 (147.162.13.111), lanpc2 (.112), lanws (.240) on MYNET with r1.eth0 (147.162.13.254/24); r1.eth1 (159.173.25.254/30) linked to r2.eth1 (.253); ws (148.163.14.240) behind r2. r1 and r2 have a default route to each other and r1 runs SSH.

Exercise 2. Before any rule, from WS: ssh [email protected] enters R1 and ping 147.162.13.111 reaches LANPC1.

bash
iptables --table filter --policy INPUT DROP         # R1 accepts nothing for itself...
iptables --table filter --policy OUTPUT ACCEPT      # ...but can send
iptables --table filter --append INPUT --in-interface lo --jump ACCEPT
iptables --table filter --policy FORWARD DROP       # nothing crosses the router: the LAN is isolated both ways

Then reopen only what is needed:

bash
# 1. from the LAN to outside: everything
iptables --table filter --append FORWARD --in-interface eth0 --out-interface eth1 --jump ACCEPT
# 2. from outside to the LAN: only replies
iptables --table filter --append FORWARD --in-interface eth1 --out-interface eth0 --match state --state ESTABLISHED,RELATED --jump ACCEPT

Exercise 3. LANPC1 now reaches WS, but WS does not reach the web service of LANWS (first packet is NEW). To publish it:

bash
iptables --table filter --append FORWARD --protocol tcp --destination-port 80 --in-interface eth1 --out-interface eth0 --destination 147.162.13.240 --jump ACCEPT

The rule has four criteria together. SSH management:

bash
iptables --table filter --append INPUT --protocol tcp --destination-port 22 --in-interface eth0 --source 147.162.13.111 --jump ACCEPT
iptables --table filter --append INPUT --protocol tcp --destination-port 22 --in-interface eth0 --source 147.162.13.112 --jump ACCEPT

LANWS has no rule and cannot enter the router, nor can WS from outside (eth1).

traffic outcome rule
LAN →\to Internet (any) passes FORWARD eth0→\toeth1
Internet →\to LANWS TCP 80 passes FORWARD with --destination 147.162.13.240
Internet →\to other LAN hosts dropped FORWARD DROP policy
Internet →\to LAN, replies pass FORWARD ESTABLISHED,RELATED
LANPC1/LANPC2 →\to R1 SSH passes INPUT port 22 and source
LANWS, WS →\to R1 dropped INPUT DROP policy

Example 3: NAT (advanced exercise)

The LAN now uses private addresses (192.168.10.0/24) and R1 must also translate them.

 private LAN 192.168.10.0/24          Internet (public networks)                      network of ws
 lanpc1 .111, lanpc2 .112, lanws .240

 --- eth0 .254 [r1] eth1 .253 ---- .254 eth0 [r] eth1 .253 ---- .254 eth1 [r2] eth0 .254 --- ws .240
            161.175.30.252/30 (INTERNET1)     162.176.31.252/30 (INTERNET2)       148.163.14.0/24

r1 and r2 have a default route to r; r has route add -net 148.163.14.0/24 gw 162.176.31.254 and route add default gw 161.175.30.253, and two rules:

bash
iptables --table filter --append INPUT --source 192.168.0.0/16 --jump DROP     # drop packets for r with private source
iptables --table filter --append FORWARD --source 192.168.0.0/16 --jump DROP   # drop forwarded packets with private source

192.168.0.0/16 is private space that must not circulate on the Internet, so at first the LANs cannot reach WS. The solution is NAT on R1.

SNAT for outgoing traffic.

bash
iptables --table nat --append POSTROUTING --source 192.168.10.0/24 --out-interface eth1 --jump SNAT --to 161.175.30.253

In table nat, chain POSTROUTING, for packets with source in the LAN leaving from eth1, the source is replaced with 161.175.30.253 (R1's public address). Replies return to R1's public address, and NetFilter, which remembers the conversation, restores the private address. nat rules apply only to the first packet of each connection.

Translation example. LANPC1 opens a web connection to WS: the packet leaves from 192.168.10.111:40000 to 148.163.14.240:80. On eth1 SNAT rewrites the source to 161.175.30.253:40000 and connection tracking records the pair. The reply to 161.175.30.253:40000 is rewritten back to 192.168.10.111:40000. If two LAN hosts used the same source port, R1 would also change the port (NAPT).

Exercise 4. links 148.163.14.240 from LANPC1 works. With tcpdump on r the source seen is 161.175.30.253, not 192.168.10.111.

DNAT to expose the web server.

bash
iptables --table nat --append PREROUTING --protocol tcp --destination 161.175.30.253 --destination-port 80 --in-interface eth1 --jump DNAT --to 192.168.10.240:80

In PREROUTING (before routing) TCP packets to 161.175.30.253 port 8080 from eth1 get destination 192.168.10.240:80; being before routing, the packet is routed to the LAN and filtered in FORWARD with the true destination. WS can now reach the web service (links 161.175.30.253) but cannot ping LAN machines (ping 161.175.30.253 is answered by R1 itself).

Exercise 5. SSH to R1 from inside:

bash
iptables --table filter --policy INPUT DROP
iptables --table filter --append INPUT --in-interface lo --jump ACCEPT
iptables --table filter --append INPUT --protocol tcp --destination-port 22 --in-interface eth0 --source 192.168.10.111 --jump ACCEPT
iptables --table filter --append INPUT --protocol tcp --destination-port 22 --in-interface eth0 --source 192.168.10.112 --jump ACCEPT

Common mistakes

  • Forgetting the lo exception with INPUT DROP: local processes stop working.
  • Forgetting ESTABLISHED,RELATED: replies to connections opened from inside are dropped.
  • Filtering in INPUT traffic crossing the router (it goes in FORWARD), or vice versa.
  • Thinking the private source can be filtered after SNAT: the filter comes before.
  • Confusing DROP (silence, timeout) with REJECT (error).
  • Changing the policy before adding the exceptions when working via SSH: you lock yourself out.
  • Rules live in the kernel and are lost at every lab restart: put them in a .startup.

Versione ripasso

bash
iptables --table filter --policy INPUT DROP
iptables --table filter --append INPUT --in-interface lo --jump ACCEPT
iptables --table filter --append INPUT --protocol icmp --icmp-type echo-request --jump ACCEPT
iptables --table filter --append INPUT --protocol tcp --destination-port 22 --jump ACCEPT
iptables --table filter --append INPUT --match state --state ESTABLISHED,RELATED --jump ACCEPT
  • Example 1 (vpc 147.162.13.111). Browses, but outside only ping and ssh. DROP blocks loopback (needs the lo exception) and, without the last rule, replies to visited sites. Ping from ws works after rule 3, SSH after 4, browsing from vpc after 5; the vpc web server stays closed.
  • Example 2 (router r1, LAN 147.162.13.0/24). INPUT and FORWARD DROP; allow FORWARD eth0→\toeth1; eth1→\toeth0 only ESTABLISHED,RELATED; web of LANWS: --protocol tcp --destination-port 80 --in-interface eth1 --out-interface eth0 --destination 147.162.13.240 --jump ACCEPT; SSH to r1 only from .111 and .112 with --in-interface eth0 --source.
  • Example 3 (NAT, 192.168.10.0/24). r drops private source 192.168.0.0/16 in INPUT and FORWARD. SNAT: --table nat --append POSTROUTING --source 192.168.10.0/24 --out-interface eth1 --jump SNAT --to 161.175.30.253; tracking restores the private address in replies; rule applies to the first packet. DNAT: --table nat --append PREROUTING --protocol tcp --destination 161.175.30.253 --destination-port 80 --in-interface eth1 --jump DNAT --to 192.168.10.240:80; ping to 161.175.30.253 is answered by r1. tcpdump on r shows source 161.175.30.253.
  • Targets. filter: ACCEPT, DROP, REJECT (--reject-with icmp-host-unreachable, icmp-net-unreachable, icmp-port-unreachable), RETURN, LOG. nat: DNAT, SNAT, MASQUERADE, REDIRECT.
  • Whitelist. INPUT DROP plus necessary exceptions only.
  • Mistakes: forgetting lo; forgetting ESTABLISHED,RELATED; INPUT vs FORWARD; filtering the private source after SNAT; DROP vs REJECT; policy before exceptions via SSH; rules lost at restart (use .startup).

Teoria collegata