How to
Turn a Unix Computer into a
Router and Firewall Using
IPTables
by Dr. Milica Barjaktarovic
Assistant Professor of Computer Science at HPU
Lecture from CENT370 Advanced Unix System
Linux Access Lists:
IP Tables Firewalls
References:
Red Hat Linux Bible, Ch.16
Practical Guide to RH Linux, Ch.25
Red Hat Linux Firewalls, Red Hat Press 2003
Assumptions
You know some Unix?
Syntax of Unix commands:
command [options] [arguments]
Basic Unix commands:
ls, vi, cat, chmod, >, …
You know some networking?
The issue: Protect
Networks
SOHO solution: network
behind the main
router/firewall
More secure solution:
DMZ configuration,
private network
behind the NAT
Any Unix machine can
be turned into a
(100% software-based)router
Step 1:
Turn your Unix box into a router
•
Make sure the computer has at least two NICs
installed and configured
•
Enable routing
• Different syntax on different Unixes. Examples below.
• Temporary change:
echo 1 > /proc/sys/net/ipv4/ip_forward
• Permanent change:
Set net.ipv4.ip_forward = 1 in /etc/sysctl.conf OR:
# cat /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE="eth0" NM_CONTROLLED=“no" ONBOOT=yes TYPE=Ethernet BOOTPROTO=none DEFROUTE=yes IPV4_FAILURE_FATAL=yes IPV6INIT=no NAME="System eth0" IPADDR=xxx.yyy.204.43 PREFIX=24 GATEWAY=xxx.yyy.204.1 DNS1=xxx.yyy.1.4 DNS2=xxx.yyy.8.3 DOMAIN="mydomain.net" HWADDR=00:25:90:60:27:96 UUID=5fb06bd0-0bb0-7ffb-45f1-d6edd65f3e03 # cat /etc/sysconfig/network-scripts/ifcfg-eth1 DEVICE="eth1" NM_CONTROLLED=“no" ONBOOT=yes TYPE=Ethernet BOOTPROTO=none IPADDR=192.168.1.1 PREFIX=24 DEFROUTE=yes IPV4_FAILURE_FATAL=yes IPV6INIT=no NAME="System eth1" UUID=9c92fad9-6ecb-3e6c-eb4d-8a47c6f50c04 GATEWAY=xxx.yyy.204.1 HWADDR=00:25:90:60:27:97 # cat /etc/sysconfig/network NETWORKING=yes HOSTNAME=myhost.mydomain.net FORWARD_IPv4=“yes”
CentOS6 Example
Step 2:
Turn your Unix box into a firewall
• The firewall is implemented in software, using IPTables
access lists
• Logically, “IPTables is a generic table structure that
defines rules and commands as part of the netfilter
framework that facilitates Network Address Translation (NAT), packet filtering, and packet mangling in the Linux 2.4 and later operating systems.”
i.e. IP tables is a set of access rules used for routing,
firewalls, NAT, proxy servers, etc.
• Physically, IPTables is implemented using iptables
• If iptables service is on, the default firewall is running! • The default firewall allows everything
• The default IPTables is implemented as the script located in
/etc/sysconfig/iptables file
• Default IPTables can be configured: • via GUI
• use System Settings | Security Level utility, or /
usr/bin/redhat-config-securitylevel GUI tool to choose a preconfigured firewall (High, Medium or no firewall) OR
• manually
• the default configuration file with firewall rules is
/etc/sysconfig/iptables, read by the init script /etc/rc.d/init.d/iptables
Best:
Create Custom IPTables scripts
• Create and/or manipulate IPTables manually from the
command line using the iptables command
• Put commands into a script, chmod u+x
• Manually configuring IPTables is a better choice bc: • It allows more control than default firewall, which
provides a limited number of configuration options
• Default firewall will automatically override any
The history: Linux Access
Lists in RH Family
• IP Chains
• Default access list technology before Red Hat Linux 7.1 • Provides basic syntax for access lists
• Not included in Fedora
• IP Tables
• Default access list mechanism for Linux kernel 2.4.x-2.6.x, Red Hat Linux 7.1-9 and Fedora 1,2,3
• More complex access list syntax => more capabilities • General purpose tool that experienced system
Basics of Packet-Filtering Firewalls
•
Inspect every packet passing through firewall
•
Check access list rules against the packet
•
Each rule is in form:
if packet satisfies condition, then action
•
Typically, action is: pass or drop the packet
•
Typically, there are several dozen rules
•
Rules are executed from top to bottom
•
The first rule that fires is taken
Example
Conceptually
If packet is going out, pass it Else
If packet is coming in, drop it Else
If packet is passing through, drop it
IPTables implementation
iptables –P OUTPUT –j ACCEPT iptables –P INPUT –j DROP
iptables –P FORWARD –j DROP
In IPTables, there are default rules for packets
going out (OUTPUT), coming in (INPUT) and
Sneak Preview:
IPTables examples
Example: default firewall lets everything in /out /through
iptables -P INPUT –j ACCEPT iptables -P FORWARD ACCEPT iptables -P OUTPUT ACCEPT
Example: block pings
SERVER_IP="202.54.10.20"
iptables -A INPUT -p icmp --icmp-type 8 -s 0/0 -d $SERVER_IP -j DROP
iptables -P INPUT –j ACCEPT iptables -P FORWARD ACCEPT iptables -P OUTPUT ACCEPT
The consequence:
must specifically address every item to be dropped – unrealistic…
Example: real firewall lets only allowed packets in
iptables -P INPUT –j DROPiptables -P FORWARD DROP iptables -P OUTPUT ACCEPT
# Accept packets from trusted IP addresses iptables -A INPUT -s 192.168.0.4 -j ACCEPT # Accept tcp packets on destination port 22 (SSH) iptables -A INPUT -p tcp --dport 22 -j ACCEPT iptables -A INPUT -i lo -j ACCEPT
Example: desktop firewall lets in only responses initiated by requests from the inside net
iptables -P INPUT –j DROP
iptables -P FORWARD –j DROP iptables -P OUTPUT –j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j
ACCEPT #allow internal users to get response from outside servers
iptables -A INPUT -i lo -j ACCEPT
IPTables Syntax:
IPTables Chains
•
A chain is a list of rules, i.e. an access list, to be
applied to certain packets
•
A rule has a condition to match and a target action
to perform
•
IPTables inherits chains from IPChains, so there
are total of 6 chains, including 3 main
user-defined chains:
• INPUT – for packets coming in from outside • OUTPUT - for packets going outside
• FORWARD – for packets being forwarded
IPTables tables ;)
•3 tables used
• filter table (default table for firewalls)
• used for packet filtering access lists
• used to control forwarding packets between network interfaces
• nat table
• used for network address translation (destination NAT aka DNAT source NAT aka SNAT, and masquerading)
• mangle table
• used for modifying packet header fields
• enables modifying Type of Service and Time To Live fields of packet header
Filter Table
•
Used to create firewalls based on packet
filtering
•
Uses 3 chains similar to the main chains:
– INPUT, OUTPUT, FORWARD
•
Rules are stateful
• They can test whether a packet is associated
NAT Table
•
Used for source and destination NAT
(SNAT and DNAT) and masquerading
•
DNAT: proxying, port forwarding
•SNAT: accessing host on private net
•Masquerading: simple case of SNAT
•NAT table uses 2 chains:
– PREROUTING – for DNAT operations (i.e. modify the destination IP address or port)
– POSTROUTING – for SNAT and
IPTables Packet Paths
Syntax for IPTables Rules
iptables -A INPUT -i eth0 -p tcp -s 10.0.0.0/8 -d 192.168.1.0/24 -j DROP
• Command name: iptables
• Operation to perform: -A, -I, -D, -R • Chain to apply operation to:
INPUT,OUTPUT,FORWARD
• Interface to apply rule to: -i eth0 • Protocol to test: -p tcp
• Source address/network: -s 10.0.0.0/8
IPTables Operations (evoked via
options of iptables command)
• Chain Operations
• List the rules associated with a chain (-L) • Flush a chain (i.e., delete its rules) (-F) • Zero counters associated with a chain (-Z)
• Create a user chain (must be associated with a table) (-N) • Delete a user chain (-X)
• Set the default policy associated with a chain (-P) • Rename a user chain (-E)
• Rule Operations
Operations for Chains
• List a chain
iptables -L chain
iptables -L --line-numbers chain iptables -L -v chain
• List and display line-numbers
iptables -L --line-numbers chain
• Flush a chain - delete all associated rules
iptables -F chain
• Set default policy (ACCEPT, REJECT, DROP)
iptables -P chain policy (e.g. iptables -P INPUT DROP)
• Create a user-defined chain
iptables -N chain
• Delete a user-defined chain
Operations for Rules
• Insert a rule at the head of the chain
iptables -I INPUT specifiers target
• Add a rule at the end of the chain
iptables -A INPUT specifiers target
• Delete a rule
iptables -D INPUT specifiers target iptables -D chain line-number
• Replace a rule
iptables specifiers
Packet characteristics For example:
Protocol (-p) -p tcp, -p udp, -p icmp Source IP address (-s) -s 10.10.10.0/24
Destination IP address (-d) -d 166.122.23.130 Input interface (-i) -i eth0, -i lo
Output interface (-o) -o lo, -o eth0 Header characteristics
TCP datagrams:
Source port (--sport), destination port (--dport), SYN or other TCP flags, TCP options
UDP datagrams:
Source port (--sport), destination port (--dport) ICMP Messages
ICMP type and code
Use ! to indicate negation or exclusion (spaces required) -p ! tcp
IPTables Targets
(actions to perform)
• Possible actions for IPTables rules
ACCEPT - packet is passed to next chain
DROP - packet is discarded aka blocked without any response aka in stealth mode)
REJECT - sends an error packet to sender - unsafe LOG - logs packet using syslog
RETURN - returns from user chain SNAT, DNAT, MASQUERADE
Invoke chain using -j chain-name
• Examples
IPTables Rules
Options
• Specify Protocol -p tcp, -p udp • Specify Source/Destination -s 192.168.0.1/255.255.255.0 or -s ! 10.0.0.0/8 -d 192.168.0.5/255.255.255.0 or -d ! 10.0.0.0/8 • Specify Interface-i eth0 or -i eth+ (input, forward chains) -o eth0 or -o eth+ (output, forward chains) • Specify Fragment Flag
IPTables Rules
Options
• Protocols and Ports
-p udp --sport 53 or -p udp -dport 53
-p tcp, udp --sport 0:1023 or -p tcp, udp --dport 0:1023 -p tcp, udp --sport :1023 or -p tcp, udp --dport :1023 -p tcp, udp --sport 1024: or -p tcp, udp -dport 1024: • Protocol and control flags
-p tcp --syn (SYN set, but ACK and FIN not set)
-p tcp ! --syn (SYN not set, or SYN and ACK or FIN set) -p tcp --tcp-flags SYN, ACK, FIN SYN (same as --syn) -p tcp --tcp-flags ALL NONE
IPTables Rules
Options
•
ICMP protocol
-p icmp --icmp-type echo-request
-p icmp --icmp-type echo-reply
IPTables Rules
Connection State
•Connection States
• NEW - no connection established yet
• ESTABLISHED - 2-way exchange completed • RELATED - associated with a new connection
related to an established connection (e.g., ftp)
• INVALID - associated with a connection that
has a problem (malformed packet or header)
•
To test for connection state, do:
MAC source address
•
use in filter FORWARD and INPUT chains
Multiple ports
Time to Live
Process owner
•
-m owner --uid-owner uid-owner-id
User Chains
• User chains are user-defined chains and must be associated with the FILTER, NAT, or MANGLE table.
• User chains can be used to create chain components that can be called from other chains to perform specific actions. • To create a user chain use
iptables -N chain
where chain is the name of the chain being created. • To delete a user chain use:
iptables -X chain
• To rename a user chain, use
Creating a User Chain
(log_badip)
# create a chain to log and drop bad IP addresses iptables -N log_badip
Creating a User Chain
(using a script)
#create a chain to test for bad IP addresses BADIP="0.0.0.0/8 10.0.0.0/8 127.0.0.0/8 169.254.0.0/16 \ 172.16.0.0/12 192.0.0.0/24 192.168.0.0/16 \ 224.0.0.0/4 240.0.0.0/5 255.255.255.255" iptables -N test_badip for ip in $BADIP do
Invoking User-Chains from
INPUT chain
#Uses INPUT chain to invoke the
# user-defined chains, test_badip and log_badip iptables -A INPUT -i lo -j ACCEPT
Starting and Stopping
IPTables service
•
To start/stop/restart (pick only one
choice) the IPTables service use:
/sbin/service iptables start/stop/restart
•
To save the IPTables rules for reuse:
Setting IPTables to
Start by default
•
display iptables runlevel settings
/sbin/chkconfig --level iptables
•
change iptables runlevel settings
IPTables as a shell script
•
Can create very complex, operational firewalls
using the iptables command with shell variables
and shell scripts
•
The IP tables rules and configuration are stored in
file
/etc/sysconfig/iptables
•
This file must exist in order to use the iptables
command to modify the rules in your access list.
Creating IPTables rules
•Method 1 (recommended)
• Use the iptables command.
Put all commands into a custom script and run it. The first command should be flushing the existing default IPTables with iptables –F.
• Review: how do we make and run a script?
•
Method 2 (NOT recommended)
• Edit the default iptables file
Put all rules into a script:
(too) Simple IPTables Firewall
#flush old rules iptables -F
iptables –X
# Replace xxx.xxx.xxx.xxx with IP address of name server MYSERVER=“xxx.xxx.xxx.xxx”
#these rules are checked first, in exactly this order; packet is treated according to the first rule that matches
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p udp -s $MYSERVER --sport 53 -j ACCEPT iptables -A INPUT -p tcp --syn -j REJECT
iptables -A INPUT -p udp -j REJECT
#default rules, applied last (usually they are specified on top of file) iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT iptables -P FORWARD ACCEPT
Simple IPTables Firewall:
allow in only DNS responses
#flush old rules iptables -F
iptables –X
# Replace xxx.xxx.xxx.xxx with IP address of name server
MYSERVER=“xxx.xxx.xxx.xxx” #no hardwiring; work with variables #these rules are checked first, in exactly this order; packet is treated
according to the first rule that matches iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p udp -s $MYSERVER --sport 53 -j ACCEPT #iptables -A INPUT -p tcp --syn -j REJECT
#iptables -A INPUT -p udp -j REJECT
#default rules, applied last (usually they are specified on top of file) iptables -P INPUT DROP
Advanced IPTables Firewall
Implementation
•
Two basic network flavors: private network
behind a NAT, or servers in DMZ
•
IPTables can do:
• Packet Forwarding
• Network Address Translation (NAT)
• Destination NAT
• Source NAT
• Masquerading
Public and Private
Firewall F has:
prF: private IP on internal interface IIF
pubF: public IP on external interface EIF
Server S is DNATed; it has:
prS: private IP
pubS: public IP
where pubS = pubF
Client C is SNATed; it has:
prC: private IP
pubC: public IP
Packet Forwarding
Multi-homed hosts
Filter packets traversing network interfaces Routing host or router
Forwarded packets traverse the IPTables FORWARD chain associated with the filter table.
Add rules to the FORWARD chain to control flow of traffic between networks.
IIF=eth0 #internal interface EIF=eth1 #external interface
iptables -P FORWARD DROP
Packet Forwarding
Example
iptables -P FORWARD –j DROP
iptables -A FORWARD -i eth0 -o eth1 -s
112.0.34.1 -d 192.168.1.12 -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -s
192.168.1.12 -d 112.0.34.1 -j ACCEPT
Another Packet Forwarding
Example
iptables -P FORWARD –j DROP
Network Address
Translation (NAT) Flavors
NAT
Modifies either source or destination IP addresses.
Source NAT (SNAT)
Modifies the source IP address of a packet
Performed in POSTROUTING chain of the nat table (outbound direction)
Destination NAT (DNAT)
Modifies the destination IP address of a packet
Uses for Destination NAT
(DNAT)
Transparent proxying
Clients request services using surrogate IP address
Port forwarding
Modification of destination port
Enables clients to access a service via a surrogate destination port
Load balancing
Specify multiple IP addresses in DNAT rule
DNAT General Form
iptables -t nat -A PREROUTING -i intf specifiers \ -j DNAT --to-destination ip[-ip][:port[-port]]
Example:
iptables -t nat -A PREROUTING -i eth0 -o eth1 \
-p tcp -d 112.0.34.1 --dport 80 -j DNAT \
--to-destination 192.168.1.12:8080
DNAT
1. Transparent proxying: access a host on a private
network
E.g. Client refers to server as 112.0.34.72, the actual address is 192.168.1.72:
iptables -t nat -A PREROUTING -i eth0 \
-d 112.0.34.72 -j DNAT --to-destination 192.168.1.72
2. Port forwarding
E.g. Reach a web server running on port 8080 via destination port 80:
iptables -t nat -A PREROUTING -i eth0 -p tcp \
-d 112.0.34.72 –dport 80 -j DNAT \ -- to-destination 192.168.1.72:8080
Uses of Source NAT
(SNAT)
Enable hosts with nonroutable addresses to
communicate with Internet hosts
Enable multiple hosts to share a single IP
address
Hide the true IP address of a host
SNAT
Enabling private IPs to access Internet; hiding the
true IP; enabling multiple clients to share a
single IP
E.g. Client's actual address is 192.168.1.1; firewall performs NAT; servers sees client as 112.0.34.72: iptables -t nat -A POSTROUTING -o eth0 \ -s 192.168.1.1 -j SNAT --to-source 112.0.34.72
Many clients can share one (or more) SNATs:
iptables -t nat -A POSTROUTING -o eth0 \ -s 192.168.1.0/24 -j SNAT \
SNAT Examples
iptables -t nat -A POSTRTOUTING -o eth0 \
-s 192.168.1.1 -j SNAT --to-source 192.1.34.254 iptables -t nat -A POSTROUTING -o eth0 \
-s 192.168.1.0/24 -j SNAT --to-source 192.0.34. 254 iptables -t nat -A POSTROUTING -o eth0 \
-s 192.168.1.0/24 -j SNAT --to-source 192.0.34.242-192.0.34.254 iptables -t nat -A POSTROUTING -o eth0 \
-s 192.168.1.0/24 -j SNAT --to-source 192.0.34.254:32768-65535 iptables -t nat -A POSTROUTING -o eth0 \
-s 192.168.1.0/24 -j MASQUERADE [--to-ports 32768-65535]
IP Masquerading
Simplified form of SNAT, but slower-to-run
Packets receive IP address of output interface as their source address.
Useful when the IP address of the output interface is not fixed (i.e., obtained via DHCP) and cannot be embedded in firewall rules.
Example (applied on routing host):
E.g. Client's actual address is 192.168.1.1; firewall's actual address is 192.0.34.72; server sees client's
packets as coming from 192.0.34.72:
Reply Packets
IPTables automatically de-NATs reply packets
associated with a connection established via
SNAT.
Accessing a DNAT Host from
the local network
I
f a local host can be accessed from Internet, it can
be a problem to access it from the LAN
For example:
If internal client accesses WebServer using the WebServer's public address, the routing host performs DNAT and forwards request to WebServer.
WebServer sees unmodified source address and sends replies directly to the requestor.
Accessing a DNAT Host from the local
network, cntd.
Example: server at 192.168.1.1 is DNATed as 112.0.34.1. So: When a local host contacts the server at 112.0.34.1,
firewall DNATs it to 192.168.1.1 and gives it to the server; the server replies directly to the client instead of replying via the firewall, using source IP of 112.168.1.1, so the
client cannot associate this reply with its original request. Fixes
Split-horizon DNS
DNS server configured to handle internal requests differently from external requests.
Accessing a DNAT Host from the local
network
cntd.
Solution1: substitute the IP address of the
firewall as the source IP of packets destined
to the server; server replies to firewall
192.168.1.1; firewall gives to the client
iptables -t nat -A PREROUTING \
-i eth0 -o eth1 -d 192.0.34.72 \
-j DNAT --to-destination 192.168.1.72
iptables -t nat -A POSTROUTING
Accessing a DNAT Host from the
local network – general formula
In general:
Firewall F has private IP prF and public IP pubF
Server S is DNATed; it has private IP prS and
public IP pubS, where pubS = pubF
Client C is SNATed; it has private IP prC and
public IP pubC, where pubC = pubF
Problem: Client C contacts server at pubS, so the
packet ends at F and F forwards to prS. Since
Accessing a DNAT Host from the local
network – general formula cntd.
Recap: Firewall F has private IP prF and public IP
pubF
Server S is DNATed; it has private IP prS and
public IP pubS, where pubS = pubF
Client C is SNATed; it has private IP prC and
public IP pubC, where pubC = pubF
Solution: Client C contacts server at pubS but
Firewall Maintenance
Maintain record of changes to firewall Keep backup copy of firewall code
Include a command in firewall script that mails a copy of the firewall to a designated user on your local network.
mail -s "Firewall backup" [email protected] < script
Encrypt the file before sending
Flush old rules first; if the firewall is accessed
remotely, put in a rule for allowing incoming SSH packets, in case you flush the IPTables and lock yourself out
Enabling Linux Routing
Define a default gateway or default gateway device in
the /etc/sysconfig/network file
GATEWAY=192.0.34.72 GATEWAYDEV=eth0
Turn on IP packet forwarding in
/etc/sysctl.conf file:
net.ipv4.ip_forward = 1
Restart network and iptables
/etc/init.d/network restart /etc/init.d/iptables restart
Verify network
Summary of Forwarding
Define forwarding rules (FORWARD chain) Define NAT translation rules
nat table, PREROUTING and POSTROUTING chains
Save changes to iptables
service iptables save #if you are working with default
Define default gateway or gateway device Enable packet forwarding
IPTables Specifics
To use NAT, we must set up forwarding first:
•
the firewall has forwarding enabled
•
IPTables has FORWARD chain rules that specify
from interface to what interface we want to forward
and how to deal with forwarded packets
Local hosts have to be configured to have the private
side of the firewall listed as their gateway (and the
DNS server is the DNS server of the firewall -
IPTables at-a-glance
1.
Put all iptables commands into a script:
1) flush all old iptables and also nat iptables (those are separate options)
2) Specify INPUT, OUTPUT, FORWARD, and/or nat rules (nat requires FORWARD rules first)
3) Specify default policy
1) If default policy is to DROP then the rules should be about ACCEPT, and vice versa. Why?