Upload
opa
View
35
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Packet Filtering. Prabhaker Mateti. Packet Filters .. “Firewalls”. Packet-filters work at the network layer Application-level gateways work at the application layer A “Firewall” …. Packet Filtering. Should arriving packet be allowed in? Should a departing packet be let out? - PowerPoint PPT Presentation
Citation preview
Mateti/PacketFiltersMateti/PacketFilters 11
Packet FilteringPacket Filtering
Prabhaker MatetiPrabhaker Mateti
Mateti/PacketFiltersMateti/PacketFilters 22
Packet Filters .. “Firewalls”Packet Filters .. “Firewalls”
Packet-filters work at Packet-filters work at the network layerthe network layer
Application-level Application-level gateways work at the gateways work at the application layerapplication layer
A “Firewall” …A “Firewall” …
Communication LayersCommunication Layers
ApplicationApplication
PresentationPresentation
SessionSession
TransportTransport
NetworkNetwork
Data LinkData Link
PhysicalPhysical
Mateti/PacketFiltersMateti/PacketFilters 33
Packet FilteringPacket Filtering
Should arriving packet be allowed in? Should a Should arriving packet be allowed in? Should a departing packet be let out?departing packet be let out?
Filter packet-by-packet, making decisions to Filter packet-by-packet, making decisions to forward/drop a packet based on:forward/drop a packet based on: source IP address, destination IP addresssource IP address, destination IP address TCP/UDP source and destination port numbersTCP/UDP source and destination port numbers ICMP message typeICMP message type TCP SYN and ACK bitsTCP SYN and ACK bits ......
Mateti/PacketFiltersMateti/PacketFilters 44
Functions of Packet FilterFunctions of Packet Filter
Control: Allow only those packets that Control: Allow only those packets that you are interested in to pass through.you are interested in to pass through.
Security: Reject packets from malicious Security: Reject packets from malicious outsidersoutsiders
Watchfulness: Log packets to/from Watchfulness: Log packets to/from outside worldoutside world
Mateti/PacketFiltersMateti/PacketFilters 55
Packet Filtering: ControlPacket Filtering: Control
Example: Block incoming and outgoing Example: Block incoming and outgoing datagrams with IP protocol field = 17 and datagrams with IP protocol field = 17 and with either source or dest port = 23.with either source or dest port = 23.
Mateti/PacketFiltersMateti/PacketFilters 66
Packet Filtering: SecurityPacket Filtering: Security
Example 2: Block inbound TCP segments Example 2: Block inbound TCP segments with ACK=0.with ACK=0.Prevents external clients from making TCP Prevents external clients from making TCP
connections with internal clients, but allows connections with internal clients, but allows internal clients to connect to outside.internal clients to connect to outside.
Mateti/PacketFiltersMateti/PacketFilters 77
Packet Filtering LimitationsPacket Filtering Limitations
Cannot Do: Allow only certain users in Cannot Do: Allow only certain users in (requires application-specific information)(requires application-specific information)
Can do: Allow or deny entire services Can do: Allow or deny entire services (protocols) (protocols)
Cannot Do: Allow, e.g., only certain files to Cannot Do: Allow, e.g., only certain files to be ftp’edbe ftp’ed
Mateti/PacketFiltersMateti/PacketFilters 88
Packet “filtering”Packet “filtering”
Packet filtering is not just “filtering”Packet filtering is not just “filtering”Changing Packets: Filters often able to Changing Packets: Filters often able to
rewrite packet headersrewrite packet headersExamine/modify IP packet contents only? Examine/modify IP packet contents only?
Or entire Ethernet frames?Or entire Ethernet frames?Monitor TCP state?Monitor TCP state?
Mateti/PacketFiltersMateti/PacketFilters 99
Goals for this LectureGoals for this Lecture
Two goals: general filtering concepts and Two goals: general filtering concepts and techniquestechniques
Also, concrete how to do it in Linux/ Also, concrete how to do it in Linux/ iptablesiptables
Similar tools/ideas exist in all modern OS.Similar tools/ideas exist in all modern OS.The design of a well-considered packet The design of a well-considered packet
filter is postponed to next lecture.filter is postponed to next lecture.
Mateti/PacketFiltersMateti/PacketFilters 1010
Packet Filtering in LinuxPacket Filtering in Linux netfilternetfilter and and iptablesiptables are the building blocks of a are the building blocks of a
framework inside Linux kernel. framework inside Linux kernel. netfilter is a set of hooks that allow kernel modules to netfilter is a set of hooks that allow kernel modules to
register callback functions with the network stack. Such register callback functions with the network stack. Such a function is called back for every packet that traverses a function is called back for every packet that traverses the respective hook. the respective hook.
iptables is a generic table structure for the definition of iptables is a generic table structure for the definition of rule sets. Each rule within an iptable consists of a rule sets. Each rule within an iptable consists of a number of classifiers (iptables matches) and one number of classifiers (iptables matches) and one connected action (iptables target). connected action (iptables target).
netfilter, iptables, connection tracking, and the NAT netfilter, iptables, connection tracking, and the NAT subsystem together build the whole framework. subsystem together build the whole framework.
Mateti/PacketFiltersMateti/PacketFilters 1111
Packet Filtering in Linux HistoryPacket Filtering in Linux History
11st generation: ipfw (from BSD)st generation: ipfw (from BSD)2nd generation: ipfwadm (Linux 2.0)2nd generation: ipfwadm (Linux 2.0)3rd generation: ipchains (Linux 2.2)3rd generation: ipchains (Linux 2.2)4th generation: iptable (Linux 2.4, 2.6)4th generation: iptable (Linux 2.4, 2.6) In this lecture, we will concentrate on In this lecture, we will concentrate on
iptables.iptables.
Mateti/PacketFiltersMateti/PacketFilters 1212
ipfilter, ipchains and, iptablesipfilter, ipchains and, iptables
UNIX, Linux, NetBSD, OpenBSD, …UNIX, Linux, NetBSD, OpenBSD, …FreeBSD (ipfw)FreeBSD (ipfw) http://http://www.freebsd.orgwww.freebsd.org// OpenBSD (pf) OpenBSD (pf) http://http://www.benzedrine.cxwww.benzedrine.cx/pf/pf
The kernel does all the routing decisionsThe kernel does all the routing decisionsThere are “userspace” (non-kernel) tools There are “userspace” (non-kernel) tools
that interact with the kernelthat interact with the kernel iptableiptableHave to be root userHave to be root user
Mateti/PacketFiltersMateti/PacketFilters 1313
Netfilter/ iptables CapabilitiesNetfilter/ iptables Capabilities
Build Internet firewalls based on Build Internet firewalls based on statelessstateless and and statefulstateful packet filtering. packet filtering.
Use NAT and masquerading for sharing Use NAT and masquerading for sharing internet access where you don't have enough internet access where you don't have enough addresses. addresses.
Use NAT for implementing transparent proxies Use NAT for implementing transparent proxies Mangling (packet manipulation) such as Mangling (packet manipulation) such as
altering the TOS/DSCP/ECN bits of the IP altering the TOS/DSCP/ECN bits of the IP headerheader
Mateti/PacketFiltersMateti/PacketFilters 1414
Linux Iptables/NetfilterLinux Iptables/Netfilter
In Linux kernel 2.4 and 2.6, we use the In Linux kernel 2.4 and 2.6, we use the netfilter package with netfilter package with iptablesiptables commands to setup the firewall.commands to setup the firewall.
The old package called IPchains is The old package called IPchains is deprecated.deprecated.
http://http://www.netfilter.orgwww.netfilter.org//
Mateti/PacketFiltersMateti/PacketFilters 1515
Iptables - Features (1)Iptables - Features (1)
Stateful filtering of TCP & UDP trafficStateful filtering of TCP & UDP trafficPorts opened & closed as clients use the Ports opened & closed as clients use the
InternetInternetPresents a (mostly) “blank wall” to attackersPresents a (mostly) “blank wall” to attackers
““Related” option for complex applicationsRelated” option for complex applicationsActive mode FTPActive mode FTPMultimedia applications (Real Audio, etc.)Multimedia applications (Real Audio, etc.)
Can filter on fragmentsCan filter on fragments
Mateti/PacketFiltersMateti/PacketFilters 1616
Iptables - Features (2)Iptables - Features (2)
Improved logging optionsImproved logging options User-defined logging prefixesUser-defined logging prefixes Log selected packets (e.g., handshake packets)Log selected packets (e.g., handshake packets)
Port Address Translation (PAT)Port Address Translation (PAT) Network Address Translation (NAT)Network Address Translation (NAT)
InboundInbound Redirect to DMZ web server, mail server, etc.Redirect to DMZ web server, mail server, etc.
OutboundOutbound Group outbound traffic and/or use static assignmentGroup outbound traffic and/or use static assignment
Mateti/PacketFiltersMateti/PacketFilters 1717
Packet Traversal in LinuxPacket Traversal in Linux
Input OutputLocalProcesses
ForwardRoutingDecision
Pre-Routing
Post-Routing
Mateti/PacketFiltersMateti/PacketFilters 1818
IPtables “chains”IPtables “chains”
A A chainchain is a sequence of filtering rules. is a sequence of filtering rules.Rules are checked in order. First match Rules are checked in order. First match
wins. Every chain has a default rule.wins. Every chain has a default rule. If no rules match the packet, chain policy If no rules match the packet, chain policy
is applied.is applied.Chains are dynamically inserted/ deleted.Chains are dynamically inserted/ deleted.
Mateti/PacketFiltersMateti/PacketFilters 1919
Built-in chainsBuilt-in chains
1.1. INPUT: packets for local processes INPUT: packets for local processes 1.1. No output interface No output interface
2.2. OUTPUT: packets produced by local processesOUTPUT: packets produced by local processes1.1. No input interface No input interface 2.2. All packets to and from lo (loopback) interface traverse All packets to and from lo (loopback) interface traverse
input and output chainsinput and output chains
3.3. FORWARD: for all transiting packetsFORWARD: for all transiting packets1.1. Do not traverse INPUT or OUTPUTDo not traverse INPUT or OUTPUT2.2. Has input and output interfaceHas input and output interface
4.4. PREROUTINGPREROUTING5.5. POSTROUTINGPOSTROUTING
Mateti/PacketFiltersMateti/PacketFilters 2020
A Packet Filtering Rule …A Packet Filtering Rule … Specifies matching criteriaSpecifies matching criteria
Source and Destination IP addresses, portsSource and Destination IP addresses, ports Source MAC AddressSource MAC Address StatesStates Invalid PacketsInvalid Packets
CRC error, fragments, ...CRC error, fragments, ... TCP flagsTCP flags
SYN, FIN, ACK, RST, URG, PSH, ALL, NONESYN, FIN, ACK, RST, URG, PSH, ALL, NONE Rate limitRate limit
What to doWhat to do Accept, Reject. Drop, take/jump them to another chain, …Accept, Reject. Drop, take/jump them to another chain, …
Rules remain in kernel memoryRules remain in kernel memory Save all rules into a file, if you wish, and insert them on Save all rules into a file, if you wish, and insert them on
rebootreboot
”
Mateti/PacketFiltersMateti/PacketFilters 2121
Targets/JumpsTargets/Jumps ACCEPT – ACCEPT – let the packet throughlet the packet through REJECT – sends ICMP error messageREJECT – sends ICMP error message DROP – reject, but don’t send ICMP messageDROP – reject, but don’t send ICMP message MASQ – masqueradeMASQ – masquerade RETURN – end of chain; RETURN – end of chain; stop traversing this stop traversing this
chain and resume the calling chainchain and resume the calling chain QUEUE QUEUE – – pass the packet to the user spacepass the packet to the user space User defined chainsUser defined chains (none) – rule’s counters incremented and packet (none) – rule’s counters incremented and packet
passed on (used for accounting)passed on (used for accounting)
Mateti/PacketFiltersMateti/PacketFilters 2222
Syntax of iptables commandSyntax of iptables command iptables –t TABLE –A CHAIN –[i|o] IFACE –iptables –t TABLE –A CHAIN –[i|o] IFACE –s w.x.y.z –d a.b.c.d –p PROT –m state --s w.x.y.z –d a.b.c.d –p PROT –m state --state STATE –j ACTIONstate STATE –j ACTION
TABLE = nat | filter | mangleTABLE = nat | filter | mangle CHAIN = INPUT | OUTPUT | FORWARD | CHAIN = INPUT | OUTPUT | FORWARD | PREROUTING| POSTROUTINGPREROUTING| POSTROUTING
IFACE = eth0 | eth1 | ppp0 | ... IFACE = eth0 | eth1 | ppp0 | ... PROT = tcp | icmp | udp | …PROT = tcp | icmp | udp | … STATE = NEW | ESTABLISHED | RELATED | …STATE = NEW | ESTABLISHED | RELATED | … ACTION = DROP | ACCEPT | REJECT | DNAT | ACTION = DROP | ACCEPT | REJECT | DNAT | SNAT |SNAT | … …
Mateti/PacketFiltersMateti/PacketFilters 2323
Specifying IP addressesSpecifying IP addresses Source: -s, --source or –srcSource: -s, --source or –src Destination: -d, --destination or –dstDestination: -d, --destination or –dst IP address can be specified in four ways.IP address can be specified in four ways.
(Fully qualified) host name (e.g., floyd, (Fully qualified) host name (e.g., floyd, floyd.osis.cs.wright.edufloyd.osis.cs.wright.edu
IP address (e.g., 127.0.0.1)IP address (e.g., 127.0.0.1) Group specification (e.g., 130.108.27.0/24)Group specification (e.g., 130.108.27.0/24) Group specification Group specification (e.g., 130.108.27.0/255.255.255.0)(e.g., 130.108.27.0/255.255.255.0)
‘–‘–s ! IPaddress’ and ‘–d ! IPaddress’: Match s ! IPaddress’ and ‘–d ! IPaddress’: Match address not equal to the given.address not equal to the given.
Mateti/PacketFiltersMateti/PacketFilters 2424
Specifying an InterfaceSpecifying an Interface
Physical device for packets to come inPhysical device for packets to come in -i, --in-interface-i, --in-interface -i eth0-i eth0
Physical device for packets to go outPhysical device for packets to go out -o, --out-interface-o, --out-interface -o eth3-o eth3
INPUT chain has no output interfaceINPUT chain has no output interface Rule using ‘-o’ in this chain will never match.Rule using ‘-o’ in this chain will never match.
OUPUT chain has no input interfaceOUPUT chain has no input interface Rule using ‘-i’ in this chain will never match.Rule using ‘-i’ in this chain will never match.
Mateti/PacketFiltersMateti/PacketFilters 2525
Specifying ProtocolSpecifying Protocol
-p protocol-p protocolProtocol numberProtocol number
1717
Protocol can be a nameProtocol can be a nameTCPTCPUDPUDPICMPICMP
––p ! protocolp ! protocol
Mateti/PacketFiltersMateti/PacketFilters 2626
““-t Table”-t Table” nat tablenat table
Chains: PREROUTING, POSTROUTING, and OUTPUT. Chains: PREROUTING, POSTROUTING, and OUTPUT. used to translate the packet's source or destination. used to translate the packet's source or destination.
Addresses and portsAddresses and ports Packets traverse this table only once. Packets traverse this table only once. should not do any filtering in this table should not do any filtering in this table
filter tablefilter table Chains: INPUT, OUTPUT, and FORWARD. Chains: INPUT, OUTPUT, and FORWARD. Almost all targets are usable Almost all targets are usable take action against packets and look at what they contain and DROP or take action against packets and look at what they contain and DROP or
/ACCEPT them, /ACCEPT them, mangle tablemangle table
Chains: PREROUTING, POSTROUTING, INPUT, OUTPUT, and Chains: PREROUTING, POSTROUTING, INPUT, OUTPUT, and FORWARD. FORWARD.
Can alter values of several fields of a packetCan alter values of several fields of a packet Not for filtering; nor will any DNAT, SNAT or Masquerading work in this Not for filtering; nor will any DNAT, SNAT or Masquerading work in this
table. table.
Mateti/PacketFiltersMateti/PacketFilters 2727
iptables examplesiptables examples
1.1. iptables --flushiptables --flush Delete all rulesDelete all rules
2.2. iptables -A INPUT -i lo -j ACCEPTiptables -A INPUT -i lo -j ACCEPT Accept all packets arriving on lo for local processesAccept all packets arriving on lo for local processes
3.3. iptables -A OUTPUT -o lo -j ACCEPTiptables -A OUTPUT -o lo -j ACCEPT4.4. iptables --policy INPUT DROPiptables --policy INPUT DROP
Unless other rules apply, drop all INPUT packetsUnless other rules apply, drop all INPUT packets
5.5. iptables --policy OUTPUT DROPiptables --policy OUTPUT DROP6.6. iptables --policy FORWARD DROPiptables --policy FORWARD DROP7.7. iptables -L -v -niptables -L -v -n
List all rules, verbosely, using numeric IP addresses etc.List all rules, verbosely, using numeric IP addresses etc.
Mateti/PacketFiltersMateti/PacketFilters 2828
The LOG TargetThe LOG Target LOGLOG
--log-level--log-level --log-prefix--log-prefix --log-tcp-sequence--log-tcp-sequence --log-tcp-options--log-tcp-options --log-ip-options--log-ip-options
1.1. iptables -A OUTPUT -o eth0 -j LOGiptables -A OUTPUT -o eth0 -j LOG Jump the packets that are on OUTPUT chain intending to leave Jump the packets that are on OUTPUT chain intending to leave
from eth0 interface to LOGfrom eth0 interface to LOG
2.2. iptables -A INPUT -m state --state INVALID -j LOG iptables -A INPUT -m state --state INVALID -j LOG --log-prefix “INVALID input: ”--log-prefix “INVALID input: ”
Jump the packets that are on INPUT chain with an INVALID state Jump the packets that are on INPUT chain with an INVALID state to to LOG and have the logged text begin with “INVALID input: ”to to LOG and have the logged text begin with “INVALID input: ”
Mateti/PacketFiltersMateti/PacketFilters 2929
iptables syntax examplesiptables syntax examples
1.1. iptables -A INPUT -i eth1 -p tcp -s iptables -A INPUT -i eth1 -p tcp -s 192.168.17.1 --sport 1024:65535 -d 192.168.17.1 --sport 1024:65535 -d 192.168.17.2 --dport 22 -j ACCEPT192.168.17.2 --dport 22 -j ACCEPT
Accept all TCP packets arriving on eth1 for local Accept all TCP packets arriving on eth1 for local processes from 192.168.17.1 with any source port processes from 192.168.17.1 with any source port higher than 1023 to 192.168.17.2 and destination higher than 1023 to 192.168.17.2 and destination port 22.port 22.
2. iptables -t nat -A PREROUTING -p TCP -i eth0 -d 128.168.60.12 --dport 80 -j DNAT --to-destination 192.168.10.2
Change the destination address of all TCP packets Change the destination address of all TCP packets arriving on eth0 aimed at arriving on eth0 aimed at 128.168.60.12 port 80 to 192.168.10.2 port 80.
Mateti/PacketFiltersMateti/PacketFilters 3030
iptables syntax examplesiptables syntax examples
1.1. iptables –A INPUT –p tcp –s 0/0 –d 0/0 –dport iptables –A INPUT –p tcp –s 0/0 –d 0/0 –dport 0:1023 –j REJECT0:1023 –j REJECT
Reject all incoming TCP traffic destined for ports 0 to 1023Reject all incoming TCP traffic destined for ports 0 to 1023
2.2. iptables –A OUTPUT –p tcp –s 0/0 –d ! osis110 –j iptables –A OUTPUT –p tcp –s 0/0 –d ! osis110 –j REJECT REJECT
Reject all outgoing TCP traffic except the one destined for osis110 Reject all outgoing TCP traffic except the one destined for osis110
3.3. iptables –A INPUT –p TCP –s osis110 --syn –j iptables –A INPUT –p TCP –s osis110 --syn –j DROPDROP
Drop all SYN packets from host osis110Drop all SYN packets from host osis110
4. iptables -A PREROUTING -t nat -p icmp -d 130.108.0.0/24 -j DNAT --to 130.108.2.10
Redirect all ICMP packets aimed at any host in the range 130.108.0.0/24 to 130.108.2.10
Mateti/PacketFiltersMateti/PacketFilters 3131
Operations on chainsOperations on chains
Operations to manage whole chainsOperations to manage whole chainsN: create a new chainN: create a new chainP: change the policy of built-in chainP: change the policy of built-in chainL:list the rules in a chainL:list the rules in a chainF: flush the rules out of a chainF: flush the rules out of a chain
Manipulate rules inside a chainManipulate rules inside a chainA: append a new rule to a chainA: append a new rule to a chain I: insert a new rule at some position in a chainI: insert a new rule at some position in a chainR: Replace a rule at some position in a chainR: Replace a rule at some position in a chainD: delete a rule in a chainD: delete a rule in a chain
Mateti/PacketFiltersMateti/PacketFilters 3232
Defining New ChainsDefining New Chains iptables -A INPUT -i eth1 –d IPaddress \iptables -A INPUT -i eth1 –d IPaddress \
-j EXT-input-j EXT-input iptables -A EXT-input -p udp --sport 53 \iptables -A EXT-input -p udp --sport 53 \
--dport 53 -j EXT-dns-server-in--dport 53 -j EXT-dns-server-in iptables -A EXT-input -p tcp ! --syn \iptables -A EXT-input -p tcp ! --syn \
--sport 53 --dport 1024:65535\--sport 53 --dport 1024:65535\-j EXT-dns-server-in-j EXT-dns-server-in
iptables -A EXT-dns-server-in\iptables -A EXT-dns-server-in\–s hostName -j ACCEPT–s hostName -j ACCEPT
Mateti/PacketFiltersMateti/PacketFilters 3333
User ChainsUser Chains
-j userChainName-j userChainName User-defined chains can jump to other user-User-defined chains can jump to other user-
defined chains.defined chains. Packets will be dropped if they are found to be in Packets will be dropped if they are found to be in
a rule/chain-loop.a rule/chain-loop. If there are no matches, returns to calling chain.If there are no matches, returns to calling chain. Packets that were not accepted/dropped resume Packets that were not accepted/dropped resume
traversal on the next rule on the chain. traversal on the next rule on the chain. -j REJECT causes failure-j REJECT causes failure
Mateti/PacketFiltersMateti/PacketFilters 3434
Specifying FragmentsSpecifying Fragments iptables -A OUTPUT -f -d 192.168.1.1 -j DROPiptables -A OUTPUT -f -d 192.168.1.1 -j DROP
First fragment is treated like any other packet. First fragment is treated like any other packet. Second and further fragments won’t be.Second and further fragments won’t be.
Specify a rule specifically for second and further Specify a rule specifically for second and further fragments, using the ‘-f’ fragments, using the ‘-f’
““Impossible” to look inside the packet for Impossible” to look inside the packet for protocol headers such as TCP, UDP, ICMP.protocol headers such as TCP, UDP, ICMP.
E.g., “E.g., “-p TCP -sport www”-p TCP -sport www” will never match will never match a fragment other than the first fragment.a fragment other than the first fragment.
Mateti/PacketFiltersMateti/PacketFilters 3535
Match Extensions: MACMatch Extensions: MAC
Specified with ‘-m mac’ or --match mac’Specified with ‘-m mac’ or --match mac’match incoming packet's source Ethernet match incoming packet's source Ethernet
address (MAC).address (MAC).--mac-source 00:60:08:91:CC:B7--mac-source 00:60:08:91:CC:B7
Mateti/PacketFiltersMateti/PacketFilters 3636
Match Extensions: LimitMatch Extensions: Limit
-m limit’ or --match limit-m limit’ or --match limit Restrict the rate of matches, such as for suppressing Restrict the rate of matches, such as for suppressing
log messages.log messages. --limit 5/second --limit 5/second
Specifies the maximum average number of matches to allow Specifies the maximum average number of matches to allow per second as 5per second as 5
--limit-burst 12--limit-burst 12 The maximum initial number of packets to match is 12The maximum initial number of packets to match is 12
This number gets recharged by one every time the limit This number gets recharged by one every time the limit specified above is not reached.specified above is not reached.
Default 3 matches per hour, with a burst of 5Default 3 matches per hour, with a burst of 5
Mateti/PacketFiltersMateti/PacketFilters 3737
Match Extensions: StateMatch Extensions: State -m state’ allows ‘--state’ option.-m state’ allows ‘--state’ option. NEWNEW
A packet which can create a new connection.A packet which can create a new connection. ESTABLISHEDESTABLISHED
A packet which belongs to an existing connectionA packet which belongs to an existing connection RELATEDRELATED
A packet which is related to, but not part of, an existing A packet which is related to, but not part of, an existing connection such as ICMP error.connection such as ICMP error.
INVALIDINVALID A packet which could not be identified for some reasons.A packet which could not be identified for some reasons.
iptables -A FORWARD -i eth0 -o eth1 -m state --state iptables -A FORWARD -i eth0 -o eth1 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPTNEW,ESTABLISHED,RELATED -j ACCEPT
Mateti/PacketFiltersMateti/PacketFilters 3838
Network Address Translation Network Address Translation (NAT)(NAT)
IP addresses are replaced at the boundary IP addresses are replaced at the boundary of a private networkof a private network
Enables hosts on private networks to Enables hosts on private networks to communicate with hosts on the Internetcommunicate with hosts on the Internet
NAT is run on routers that connect private NAT is run on routers that connect private networks to the public Internetnetworks to the public Internet
Mangles both inbound and outbound Mangles both inbound and outbound packetspacketsRouters don’t normally do thisRouters don’t normally do this
Mateti/PacketFiltersMateti/PacketFilters 3939
Basic operation of NATBasic operation of NAT
NAT device has address translation tableNAT device has address translation table
H1
private address: 10.0.1.2public address: 128.143.71.21
H5
Privatenetwork
Internet
Source = 10.0.1.2Destination = 213.168.112.3
Source = 128.143.71.21Destination = 213.168.112.3
public address: 213.168.112.3NATdevice
Source = 213.168.112.3Destination = 128.143.71.21
Source = 213.168.112.3Destination = 10.0.1.2
PrivateAddress
PublicAddress
10.0.1.2 128.143.71.21
Mateti/PacketFiltersMateti/PacketFilters 4040
Uses of NATUses of NAT Pooling of IP addressesPooling of IP addresses Supporting migration between network service providersSupporting migration between network service providers IP masqueradingIP masquerading Load balancing of serversLoad balancing of servers
iptables -t nat -A PREROUTING -i eth1 -j DNAT --to-destination iptables -t nat -A PREROUTING -i eth1 -j DNAT --to-destination 10.0.1.2-10.0.1.4 10.0.1.2-10.0.1.4
Client-only site (SOHO)Client-only site (SOHO) Multiple serversMultiple servers
Can get into otherwise “hidden” LANsCan get into otherwise “hidden” LANs Can also load share as NAT round robins connectionCan also load share as NAT round robins connection
Transparent proxyingTransparent proxying
Mateti/PacketFiltersMateti/PacketFilters 4141
NAT: Pooling of IP addressesNAT: Pooling of IP addresses
Scenario:Scenario: Corporate network has many hosts Corporate network has many hosts but only a small number of public IP addressesbut only a small number of public IP addresses
NAT solution:NAT solution: Corporate network is managed with a private address Corporate network is managed with a private address
spacespace NAT device, located at the boundary between the NAT device, located at the boundary between the
corporate network and the public Internet, manages a corporate network and the public Internet, manages a pool of public IP addresses pool of public IP addresses
When a host from the corporate network sends an IP When a host from the corporate network sends an IP datagram to a host in the public Internet, the NAT datagram to a host in the public Internet, the NAT device device dynamicallydynamically picks a public IP address from the picks a public IP address from the address pool, and binds this address to the private address pool, and binds this address to the private address of the hostaddress of the host
Mateti/PacketFiltersMateti/PacketFilters 4242
NAT: Pooling of IP addressesNAT: Pooling of IP addresses
iptables –t nat –A POSTROUTING –s iptables –t nat –A POSTROUTING –s 10.0.1.0/24 –j SNAT --to-source 10.0.1.0/24 –j SNAT --to-source 128.128.71.0–128.143.71.30128.128.71.0–128.143.71.30
H1
private address: 10.0.1.2public address:
H5
Privatenetwork
Internet
Source = 10.0.1.2Destination = 213.168.112.3
Source = 128.143.71.21Destination = 213.168.112.3
public address: 213.168.112.3NATdevice
PrivateAddress
PublicAddress
10.0.1.2
Pool of addresses: 128.143.71.0-128.143.71.30
Mateti/PacketFiltersMateti/PacketFilters 4343
NAT: Migration to a new ISPNAT: Migration to a new ISP
Scenario:Scenario: In Classless Inter-Domain Routing (CIDR), In Classless Inter-Domain Routing (CIDR), the IP addresses in a corporate network are obtained the IP addresses in a corporate network are obtained from the service provider. Changing the service provider from the service provider. Changing the service provider requires changing all IP addresses in the network. requires changing all IP addresses in the network.
NAT solution:NAT solution: Assign private addresses to the hosts of the corporate networkAssign private addresses to the hosts of the corporate network NAT device has NAT device has staticstatic address translation entries which bind the address translation entries which bind the
private address of a host to the public address. private address of a host to the public address. Migration to a new network service provider merely requires an Migration to a new network service provider merely requires an
update of the NAT device. The migration is not noticeable to the update of the NAT device. The migration is not noticeable to the hosts on the network. hosts on the network.
Mateti/PacketFiltersMateti/PacketFilters 4444
NAT: Migration to new ISPNAT: Migration to new ISP
H1
private address: 10.0.1.2public address: 128.143.71.21
128.195.4.120
Source = 10.0.1.2Destination = 213.168.112.3
NATdevice
PrivateAddress
PublicAddress
10.0.1.2128.143.71.21128.195.4.120
128.143.71.21
128.195.4.120
Source = 128.143.71.21Destination = 213.168.112.3
Source = 128.195.4.120Destination = 213.168.112.3
ISP 2allocates address block
128.195.4.0/24 to privatenetwork:
Privatenetwork
ISP 1allocates address block
128.143.71.0/24 to privatenetwork:
Mateti/PacketFiltersMateti/PacketFilters 4545
Concerns about NAT: Concerns about NAT: Performance:Performance:
Modifying the IP header by changing the Modifying the IP header by changing the IP address requires that NAT boxes IP address requires that NAT boxes recalculate the IP header checksumrecalculate the IP header checksum
Modifying port number requires that NAT Modifying port number requires that NAT boxes recalculate TCP checksumboxes recalculate TCP checksum
Mateti/PacketFiltersMateti/PacketFilters 4646
Concerns about NAT: Concerns about NAT: FragmentationFragmentation
Care must be taken that a datagram that is Care must be taken that a datagram that is not fragmented before it reaches the NAT not fragmented before it reaches the NAT device, is not assigned a different IP device, is not assigned a different IP address or different port numbers for each address or different port numbers for each of the fragments. of the fragments.
Mateti/PacketFiltersMateti/PacketFilters 4747
Concerns about NAT: End-to-Concerns about NAT: End-to-end connectivity:end connectivity:
NAT destroys universal end-to-end NAT destroys universal end-to-end reachability of hosts on the Internet. reachability of hosts on the Internet.
A host in the public Internet cannot initiate A host in the public Internet cannot initiate communication to a host in a private communication to a host in a private network. network.
Mateti/PacketFiltersMateti/PacketFilters 4848
Concerns about NAT: IP Concerns about NAT: IP address in application dataaddress in application data
Applications that carry IP addresses in the Applications that carry IP addresses in the payload of the application data generally payload of the application data generally do not work across a private-public do not work across a private-public network boundary. network boundary.
Some NAT devices inspect and adjust the Some NAT devices inspect and adjust the payload of widely used application layer payload of widely used application layer protocols if an IP address is detected.protocols if an IP address is detected.
Mateti/PacketFiltersMateti/PacketFilters 4949
Source NAT (SNAT)Source NAT (SNAT) Mangle the source IP address of a packetMangle the source IP address of a packet Used for internal Used for internal external connections external connections Done on Done on POSTROUTINGPOSTROUTING, just before packet , just before packet
leavesleaves Masquerading is a form of thisMasquerading is a form of this iptables –t nat –A POSTROUTING –o iptables –t nat –A POSTROUTING –o eth1 –j SNAT –-to-source eth1 –j SNAT –-to-source 10.252.49.23110.252.49.231
iptables –t nat –A POSTROUTING –s iptables –t nat –A POSTROUTING –s 10.0.1.2 -j SNAT --to-source 10.0.1.2 -j SNAT --to-source 128.143.71.21 128.143.71.21
Mateti/PacketFiltersMateti/PacketFilters 5050
Destination NAT (DNAT)Destination NAT (DNAT) Alters the destination IP address of the packetAlters the destination IP address of the packet Done on Done on OUTPUT or OUTPUT or PREROUTING PREROUTING Load sharing, transparent proxying are forms of thisLoad sharing, transparent proxying are forms of this iptables -t nat -A PREROUTING -i eth0 -p tcp --iptables -t nat -A PREROUTING -i eth0 -p tcp --
sport 1024:65535 -d 130.108.17.115 --dport 80 -j sport 1024:65535 -d 130.108.17.115 --dport 80 -j DNAT --to-destination 130.108.17.111DNAT --to-destination 130.108.17.111
iptables -t nat -A PREROUTING -i eth0 -p tcp --iptables -t nat -A PREROUTING -i eth0 -p tcp --sport 1024:65535 -d 130.108.17.111 --dport 80 -j sport 1024:65535 -d 130.108.17.111 --dport 80 -j DNAT --to-destination 192.168.17.111:81DNAT --to-destination 192.168.17.111:81
iptables -t nat -A PREROUTING -i eth0 -p tcp --sport 1024:65535 -d 130.108.17.111130.108.17.111 --dport 80 -j DNAT --to-destination 192.168.56.10-192.168.56.15
Mateti/PacketFiltersMateti/PacketFilters 5151
IP masqueradingIP masquerading
Special case of NAT, Network address and port Special case of NAT, Network address and port translation (NAPT), port address translation translation (NAPT), port address translation (PAT).(PAT).
Scenario: Single public IP address is mapped to Scenario: Single public IP address is mapped to multiple hosts in a private network. multiple hosts in a private network.
NAT solution:NAT solution: Assign private addresses to the hosts of the corporate Assign private addresses to the hosts of the corporate
networknetwork NAT device modifies the port numbers for outgoing NAT device modifies the port numbers for outgoing
traffictraffic
Mateti/PacketFiltersMateti/PacketFilters 5252
Networking at Home: Networking at Home: MasqueradingMasquerading
Modem connections/DHCPModem connections/DHCP Doesn’t drop connections when address changesDoesn’t drop connections when address changes Makes all packets from internal look like they are Makes all packets from internal look like they are
coming from the modem machine/DHCP address coming from the modem machine/DHCP address (outgoing interface’s address):(outgoing interface’s address):
## Masquerade everything out ppp0.## Masquerade everything out ppp0.echo 1 > /proc/sys/net/ipv4/ip_forwardecho 1 > /proc/sys/net/ipv4/ip_forward
modprobe iptable_natmodprobe iptable_nat
iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADEiptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
Mateti/PacketFiltersMateti/PacketFilters 5353
IP masqueradingIP masquerading
H1
private address: 10.0.1.2
Private network
Source = 10.0.1.2Source port = 2001
Source = 128.143.71.21Source port = 2100
NATdevice
PrivateAddress
PublicAddress
10.0.1.2/2001 128.143.71.21/2100
10.0.1.3/3020 128.143.71.21/4444
H2
private address: 10.0.1.3
Source = 10.0.1.3Source port = 3020
Internet
Source = 128.143.71.21Source Port = 4444
128.143.71.21
Mateti/PacketFiltersMateti/PacketFilters 5454
SNAT vs. MASQUERADESNAT vs. MASQUERADE
SNAT SNAT translates only the source IP addresses, the port translates only the source IP addresses, the port
number is preserved unchanged. number is preserved unchanged. requires that you have equal number of outgoing IP requires that you have equal number of outgoing IP
addresses as IP address in your intranet addresses as IP address in your intranet does not have to search for the available port or does not have to search for the available port or
available IP address (Hence, SNAT is faster than available IP address (Hence, SNAT is faster than MASQUERADE)MASQUERADE)
When you have only a few static IP addresses, When you have only a few static IP addresses, MASQUERADE is the preferred method.MASQUERADE is the preferred method.
Mateti/PacketFiltersMateti/PacketFilters 5555
IPtable OptimizationIPtable Optimization
Place loopback rules as early as possible.Place loopback rules as early as possible. Place forwarding rules as early as possible.Place forwarding rules as early as possible. Use the state and connection-tracking Use the state and connection-tracking
modules to bypass the firewall for established modules to bypass the firewall for established connections.connections.
Combine rules to standard TCP client-server Combine rules to standard TCP client-server connections into a single rule using port lists.connections into a single rule using port lists.
Place rules for heavy traffic services as early Place rules for heavy traffic services as early as possible.as possible.
Mateti/PacketFiltersMateti/PacketFilters 5656
State MatchingState Matching
When tracking connectionsWhen tracking connectionsNEW – for a new connectionNEW – for a new connectionESTABLISHED – for packets in an ESTABLISHED – for packets in an
existing connectionexisting connectionRELATED – for packets related to an RELATED – for packets related to an
existing connection (ICMP errors, FTP)existing connection (ICMP errors, FTP) INVALID – unrelated to existing INVALID – unrelated to existing
connections (should drop)connections (should drop)
Mateti/PacketFiltersMateti/PacketFilters 5757
Stateful FilteringStateful Filtering
When router keeps track of “connections”When router keeps track of “connections”Accept TCP packets when connection Accept TCP packets when connection
initiated from insideinitiated from insideAccept UDP packets when part of response to Accept UDP packets when part of response to
internal requestinternal requestAlso called Also called dynamicdynamic as firewall rules as firewall rules
change over timechange over time
Mateti/PacketFiltersMateti/PacketFilters 5858
Stateful Filtering ContinuedStateful Filtering Continued
Increases load on routerIncreases load on routerPossible DoS pointPossible DoS pointRouter reboots can drop connectionsRouter reboots can drop connectionsDifficult to know if/when response comingDifficult to know if/when response coming
Remote machine may be downRemote machine may be downHole opened in any caseHole opened in any case
Mateti/PacketFiltersMateti/PacketFilters 5959
Stateful Filtering ContinuedStateful Filtering Continued
May be able to check for protocol May be able to check for protocol correctnesscorrectnessE.g., DNS query to DNS portE.g., DNS query to DNS port
LoggingLoggingProbably don’t want to log every packetProbably don’t want to log every packetMaybeMaybe
FirstFirstBadBadAttacksAttacks
Mateti/PacketFiltersMateti/PacketFilters 6060
Transparent ProxiesTransparent Proxies
Proxy: software setup on firewall machineProxy: software setup on firewall machineEach client must know how to connect to Each client must know how to connect to
proxyproxyProxy then performs connection and relays Proxy then performs connection and relays
informationinformationOnly proxy machine needs DNSOnly proxy machine needs DNSSquid a likely candidateSquid a likely candidate
Mateti/PacketFiltersMateti/PacketFilters 6161
Transparent Proxies ContinuedTransparent Proxies Continued
Another approach: firewall chain intercepts Another approach: firewall chain intercepts external requests and sends them to proxyexternal requests and sends them to proxyClients need not know about proxyingClients need not know about proxyingClients do need DNSClients do need DNSNeed proxy for each serviceNeed proxy for each service
Mateti/PacketFiltersMateti/PacketFilters 6262
Error CodesError Codes
If deny (reject), ICMP error message sent If deny (reject), ICMP error message sent backback
Helps remote machine stop attempting to Helps remote machine stop attempting to connectconnectReduces number of packetsReduces number of packets
But: may give too much information to But: may give too much information to attackerattacker
Mateti/PacketFiltersMateti/PacketFilters 6363
Error Codes ContinuedError Codes Continued
Host and network unreachableHost and network unreachableProblem: some OS’s drop Problem: some OS’s drop allall connections to connections to
remote machine if receivedremote machine if receivedE.g., if connected to web server and attempt E.g., if connected to web server and attempt
to connect to non-existent mail server on to connect to non-existent mail server on same machine, web connection severedsame machine, web connection severed
Also: administratively unreachableAlso: administratively unreachable
Mateti/PacketFiltersMateti/PacketFilters 6464
ReferencesReferences
Oskar Andreasson, “Iptables Tutorial,” 2003, Oskar Andreasson, “Iptables Tutorial,” 2003, about 150 pages, about 150 pages, iptables-iptables-tutorial.frozentux.nettutorial.frozentux.net//
Comprehensive, but poorly written.Comprehensive, but poorly written.
David Coulson, iptables, parts 1 and 2, 2003, David Coulson, iptables, parts 1 and 2, 2003, about 8 pages, about 8 pages, www.davidcoulson.net/writing/lxfwww.davidcoulson.net/writing/lxf/38/iptables.pdf/38/iptables.pdf ; ... ; ... /39/iptables.pdf/39/iptables.pdf
Shallow, but well writtenShallow, but well written
Linux (iptables)Linux (iptables) http://www.netfilter.org/http://www.netfilter.org/ FreeBSD (ipfw)FreeBSD (ipfw) http://www.freebsd.org/http://www.freebsd.org/ OpenBSD (pf) OpenBSD (pf) http://www.benzedrine.cx/pfhttp://www.benzedrine.cx/pf