Vous êtes sur la page 1sur 41

Linuxdays 2008

Netfilters
and
QOS
http://www.lilux.lu/presentations/2008/LinuxDays/Netfilters_QOS/

ThierryCoutelier<Thierry.Coutelier@l

ilux.lu

>

AlainKnaff<Alain@lilux.lu>

LiLuxasbl

LinuxDays2008

TableofContents
1Netfilters.............................................................................................................................................3
1.1WhatareNetfilters......................................................................................................................3
1.2WhatisNeeded...........................................................................................................................3
1.3Networkhooksandpackettraversal...........................................................................................5
1.4Howtousetheiptables...............................................................................................................5
1.5Whatisconnectiontracking?.....................................................................................................6
1.6Examples:....................................................................................................................................6
2QOS....................................................................................................................................................7
2.1WhatisQOS...............................................................................................................................7
2.2WhatyoucandowithQOS:.......................................................................................................7
2.3WhatisNeeded...........................................................................................................................7
2.4Kernelmodulesneeded:..............................................................................................................8
2.5Thetccommands........................................................................................................................8
2.5.1Queuedisciplines:...............................................................................................................9
2.5.2Classes:................................................................................................................................9
2.5.3Filters:.................................................................................................................................9
2.6Queuingdisciplines...................................................................................................................10
2.7Usagewithiptables...................................................................................................................10
2.7.1UsingtheNetfilterCLASSIFYTarget.............................................................................10
2.7.2UsingtheNetfilterMARKTarget....................................................................................11
2.8Testingtools..............................................................................................................................11
2.8.1Netem................................................................................................................................11
2.8.2IPTraf................................................................................................................................11
2.8.3Netcat................................................................................................................................12
2.8.4iperf...................................................................................................................................12
2.9Example....................................................................................................................................12
2.10Exercise...................................................................................................................................13
3Links.................................................................................................................................................13
4AppendixA:iptablesmanpage........................................................................................................14
5AppendixB:tcmanpages:...............................................................................................................29
6AppendixC:Afirewallsample........................................................................................................35

LiLuxasbl

LinuxDays2008

1 Netfilters
1.1WhatareNetfilters.

NetfiltersisasetofhooksintheLinuxKernelthatallowtocatchpacketsandfilter,change
(mangle)ortransform(NAT)them.
WhatyoucandowithNetfilters:

Selectpacketsbasedonmanyparameterslikesource/destinationIPaddressorport,state
ofthepacket,ownerofthepacketorflag.
Drop,accept,rejectpackets
Manglepackets,thatismarkthemorchangesomeoftheirflags
NAT(NetworkAddressTranslation)whichmeanschangingtheirIPaddress(sourceor
destination).
Classifypackets.

1.2WhatisNeeded

Theiptablestools.ThoseareincludedinmostGNU/Linuxdistributions.

ALinuxkernelwithaversion2.2orabove.

ThenetfiltersneedtobeenabledinaLinuxKernel(version2.2orabove)Thisisdoneobmostof
thedistributions.
Options for 2.6.23 Kernel (make menuconfig):
-> Networking
-> Networking options
-> Network packet filtering framework (Netfilter)
-> Core Netfilter Configuration

LiLuxasbl

LinuxDays2008

<M>Netfilternetlinkinterface
<M>NetfilterNFQUEUEoverNFNETLINKinterface
<M>NetfilterLOGoverNFNETLINKinterface
<M>Netfilterconnectiontrackingsupport
Connectiontrackingflowaccounting
Connectionmarktrackingsupport
[*]Connectiontrackingsecuritymarksupport
[*]Connectiontrackingevents(EXPERIMENTAL)
<M>SCTPprotocolconnectiontrackingsupport(EXPERIMENTAL)
Liteprotocolconnectiontrackingsupport(EXPERIMENTAL)
<M>Amandabackupprotocolsupport
<M>FTPprotocolsupport
<M>H.323protocolsupport(EXPERIMENTAL)
<M>IRCprotocolsupport
<M>NetBIOSnameserviceprotocolsupport(EXPERIMENTAL)
<M>PPtPprotocolsupport
<M>SANEprotocolsupport(EXPERIMENTAL)
<M>SIPprotocolsupport(EXPERIMENTAL)
<M>TFTPprotocolsupport
<M>Connectiontrackingnetlinkinterface(EXPERIMENTAL)
<M>NetfilterXtablessupport(requiredforip_tables)
<M>"CLASSIFY"targetsupport
<M>"CONNMARK"targetsupport
<M>"DSCP"targetsupport
<M>"MARK"targetsupport
<M>"NFQUEUE"targetSupport
<M>"NFLOG"targetsupport
<M>"NOTRACK"targetsupport
<M>"TRACE"targetsupport
<M>"SECMARK"targetsupport
<M>"CONNSECMARK"targetsupport
<M>"TCPMSS"targetsupport
<M>"comment"matchsupport
connectioncountermatchsupport
<M>"connlimit"matchsupport"
<M>"connmark"connectionmarkmatchsupport
<M>"conntrack"connectiontrackingmatchsupport
<M>"DCCP"protocolmatchsupport
<M>"DSCP"matchsupport
<M>"ESP"matchsupport
<M>"helper"matchsupport
<M>"length"matchsupport
<M>"limit"matchsupport
<M>"mac"addressmatchsupport
<M>"mark"matchsupport
<M>IPsec"policy"matchsupport
<M>Multipleportmatchsupport
<M>"physdev"matchsupport
<M>"pkttype"packettypematchsupport
<M>"quota"matchsupport
<M>"realm"matchsupport
<M>"sctp"protocolmatchsupport(EXPERIMENTAL)
<M>"state"matchsupport
<M>"statistic"matchsupport
<M>"string"matchsupport
<M>"tcpmss"matchsupport
<M>"u32"matchsupport
<M>"hashlimit"matchsupport

LiLuxasbl

LinuxDays2008

And:
->
->
->
->

Networking
Networking options
Network packet filtering framework (Netfilter)
IP: Netfilter Configuration
<M>IPv4connectiontrackingsupport(requiredforNAT)
[]proc/sysctlcompatibilitywitholdconnectiontracking
<M>IPUserspacequeueingviaNETLINK(OBSOLETE)
<M>IPtablessupport(requiredforfiltering/masq/NAT)
<M>IPrangematchsupport
<M>TOSmatchsupport
<M>recentmatchsupport
<M>ECNmatchsupport
<M>AHmatchsupport
<M>TTLmatchsupport
<M>Ownermatchsupport
<M>addresstypematchsupport
<M>Packetfiltering
<M>REJECTtargetsupport
<M>LOGtargetsupport
<M>ULOGtargetsupport
<M>FullNAT
<M>MASQUERADEtargetsupport
<M>REDIRECTtargetsupport
<M>NETMAPtargetsupport
<M>SAMEtargetsupport(OBSOLETE)
<M>BasicSNMPALGsupport(EXPERIMENTAL)
<M>Packetmangling
<M>TOStargetsupport
<M>ECNtargetsupport
<M>TTLtargetsupport
<M>CLUSTERIPtargetsupport(EXPERIMENTAL)
<M>rawtablesupport(requiredforNOTRACK/TRACE)
<M>ARPtablessupport
<M>ARPpacketfiltering
<M>ARPpayloadmangling

LiLuxasbl

LinuxDays2008

1.3Networkhooksandpackettraversal.

Illustration1

1.4Howtousetheiptables

Firstyouneedtoknowwhereyouwanttodosomething.
Thisisdonebyselectingthetableandachain.
Thetablesyoumayuseare:filter(default),natormangle.
Thechainmayeitherbeoneofthebuiltinonesoronecreatedbyyourself.
Builtinchainsare:INPUT,OUTPUT,FORWARD,PREROUTINGandPOSTROUTING(see
diagramabove).
Thenyouwillhavetodecidewhatthecriteriaarethathavetomatch.Thisisdonebygivingrules.
Nexttoyouneedtodecidewhattodo.Thisisdonebyselectingatarget.Atargetmaybeauser
definedchainoroneofthespecialvalues:ACCEPT,DROP,QUEUEorRETURN.
Youcaneitherappend(A),insert(I)ordelete(D)arule.Rulesmaybenumbered.
Youmayflush(F)achain,thatisdeletealltherulesinachain.
Youmaysetthepolicy(P)ofachain.Thepolicy,forexampleDROPorACCEPT(default),is
appliedwhenthereisnomatchingrulesinachain.
6

LiLuxasbl

LinuxDays2008

Thebestdocumentationisthemanpage!SeeAppendixA.

1.5Whatisconnectiontracking?

Connectiontrackingreferstotheabilitytomaintainstateinformationaboutaconnectionin
memorytables,suchassourceanddestinationipaddressandportnumberpairs(knownassocket
pairs),protocoltypes,connectionstateandtimeouts.Firewallsthatdothisareknownasstateful.
Statefulfirewallingisinherentlymoresecurethanits"stateless"counterpart...simplepacket
filtering.
Connectiontrackingisaccomplishedwiththestateoptioniniptables.
ConnectiontrackingisdoneeitherinthePREROUTINGchain,ortheOUTPUTchainforlocally
generatedpackets.
Connectiontrackingdefragmentsallpacketsbeforetrackingtheirstate.Thisexplainswhythereis
noip_always_defragswitchastherewasinthe2.2kernel.
Thestatetableforudpandtcpconnectionsismaintainedin/proc/net/ip_conntrack.
Themaximumnumberofconnectionsthestatetablecancontainisstoredin
/proc/sys/net/ipv4/ip_conntrack_max.Thisvalueisdeterminedinitiallybyhowmuchphysical
memoryyouhave(onmy512Mbmachine,ip_conntrack_max=32760bydefault).

1.6Examples:

SeeappendixCforacompletesamplescripttodofirewalling.

LiLuxasbl

LinuxDays2008

2 QOS
2.1WhatisQOS

QOSstandsforQualityofServiceandpermitsasetofoperationsbasedonnetworkpackets.The
operationsincludeenqueuing,policing,classifying,scheduling,shapinganddropping.
QOSisgenerallyconfiguredonanetworkinterface.

2.2WhatyoucandowithQOS:

Limittotalbandwidthtoaknownrate;TBF,HTBwithchildclass(es).

Limitthebandwidthofaparticularuser,serviceorclient;HTBclassesandclassifyingwith
afilter.traffic.

MaximizeTCPthroughputonanasymmetriclink;prioritizetransmissionofACKpackets,
wondershaper.

Reservebandwidthforaparticularapplicationoruser;HTBwithchildrenclassesand
classifying.

Preferlatencysensitivetraffic;PRIOinsideanHTBclass.

Managedoversubscribedbandwidth;HTBwithborrowing.

Allowequitabledistributionofunreservedbandwidth;HTBwithborrowing.

Ensurethataparticulartypeoftrafficisdropped;policerattachedtoafilterwitha
dropaction.

2.3WhatisNeeded.

ALinux2.4.xor2.6kernel.
QOSenabledinthekernel(mostoftheGNU/Linuxdistributionsincludesuchakernel).
Theiproute2package(alsoincludedinmostdistributions).

2.4Kernelmodulesneeded:

Fora2.6.23kernel.
in/usr/src/linux(orwhereyourkernelresides)
makemenuconfig
>Networking
>Networkingoptions
>QoSand/orfairqueueing
8

LiLuxasbl

LinuxDays2008

[*]QoSand/orfairqueueing
<M>CBQpacketscheduler
<M>HTBpacketscheduler
<M>HFSCpacketscheduler
<M>CSZpacketsched
<*>ATMpseudoscheduler
<M>ThesimplestPRIOpseudoscheduler
<M>REDqueue
<M>SFQqueue
<M>TEQLqueue
<M>TBFqueue
<M>GREDqueue
<M>Diffservfieldmarker
<M>Delaysimulator
<M>IngressQdisc
[*]QoSsupport
[*]Rateestimator
[*]PacketclassifierAPI
<M>TCindexclassifier
<M>Routingtablebasedclassifier
<M>Firewallbasedclassifier
<M>U32classifier
<M>SpecialRSVPclassifier
<M>SpecialRSVPclassifierforIpv6
[*]Trafficpolicing(neededforin/egress)[*]QoSand/or
fairqueueing
Queueing/Scheduling
<M>ClassBasedQueueing(CBQ)
<M>HierarchicalTokenBucket(HTB)
<M>HierarchicalFairServiceCurve(HFSC)
<M>ATMVirtualCircuits(ATM)
<M>MultiBandPriorityQueueing(PRIO)
<M>MultiBandRoundRobinQueuing(RR)
<M>RandomEarlyDetection(RED)
<M>StochasticFairnessQueueing(SFQ)
<M>TrueLinkEqualizer(TEQL)
<M>TokenBucketFilter(TBF)
<M>GenericRandomEarlyDetection(GRED)
<M>DifferentiatedServicesmarker(DSMARK)
<M>Networkemulator(NETEM)
<M>IngressQdisc
Classification
<M>Elementaryclassification(BASIC)
ControlIndex(TCINDEX)
<M>Routingdecision(ROUTE)
<M>Netfiltermark(FW)
<M>Universal32bitcomparisonsw/hashing(U32)
[*]Performancecounterssupport
[*]Netfiltermarkssupport
<M>IPv4ResourceReservationProtocol(RSVP)
<M>IPv6ResourceReservationProtocol(RSVP6)
[*]ExtendedMatches
(32)Stacksize
<M>Simplepacketdatacomparison
<M>Multibytecomparison
<M>U32key
<M>Metadata
<M>Textsearch
Actions
TrafficPolicing

LiLuxasbl

LinuxDays2008

2.5Thetccommands

Fromtheuserspacetheiproute2packagesofferstwomajorcommands:
ip>thisisusedtoconfigureroutingtablesandnetworklinks(networkadapters)
tc>thisistheoneusedtoconfigurethedifferentpartsoftheQOS.
Thetccommandtakesasafirstparametertheobjectyouwanttoworkon:
Either:qdisc,classorfilter.
tchelp
Usage:tc[OPTIONS]OBJECT{COMMAND|help}
tc[force]batchfile
whereOBJECT:={qdisc|class|filter|action|monitor}
OPTIONS:={s[tatistics]|d[etails]|r[aw]|b[atch][file]}

2.5.1Queuedisciplines:
Thisisusedtosetthekindofqueueyouwanttouseonaspecificinterface.
Dependingonthequeuetypetheparameterswillbedifferent.
Itisthefirstcommandyouwilluse.
tcqdischelp
Usage:tcqdisc[add|del|replace|change|get]devSTRING
[handleQHANDLE][root|ingress|parentCLASSID]
[estimatorINTERVALTIME_CONSTANT]
[[QDISC_KIND][help|OPTIONS]]
tcqdiscshow[devSTRING][ingress]
Where:
QDISC_KIND:={[p|b]fifo|tbf|prio|cbq|red|etc.}
OPTIONS:=...trytcqdiscadd<desiredQDISC_KIND>help

2.5.2Classes:
tcclassisusedtoconfigureaclasses.
tcclasshelp
Usage:tcclass[add|del|change|get]devSTRING
[classidCLASSID][root|parentCLASSID]
[[QDISC_KIND][help|OPTIONS]]
tcclassshow[devSTRING][root|parentCLASSID]
Where:
10

LiLuxasbl

LinuxDays2008

QDISC_KIND:={prio|cbq|etc.}
OPTIONS:=...trytcclassadd<desiredQDISC_KIND>help

2.5.3Filters:
Usedtoclassifypacketsdependingontheircontents.
tcfilterhelp
Usage:tcfilter[add|del|change|get]devSTRING
[prefPRIO][protocolPROTO]
[estimatorINTERVALTIME_CONSTANT]
[root|classidCLASSID][handleFILTERID]
[[FILTER_TYPE][help|OPTIONS]]
tcfiltershow[devSTRING][root|parentCLASSID]
Where:
FILTER_TYPE:={rsvp|u32|fw|route|etc.}
FILTERID:=...formatdependsonclassifier,seethere
OPTIONS:=...trytcfilteradd<desiredFILTER_KIND>help

2.6Queuingdisciplines

Therearetwotypesofqdisc.
1. Classlessqueuingdisciplines.Likepfifo,prio,sfq...thosereorderpacketsbasedonsome
criteria.
2. Classfulqueuingdisciplines.LikeCQB,HTB...forthosepacketsmaybeswitchedtodifferent
classes.
ThemostusedqdiscsareHTBtodobandwidthlimitation,pfifowhichisthedefaultofanyqueue,
andsfqwhichisusedtodofairqueuingonaninterface.

2.7Usagewithiptables

2.7.1UsingtheNetfilterCLASSIFYTarget
SinceLinux2.6theCLASSIFYtargethasbeenpartofthestandarddistribution,soyouneednot
patchyourkernel.TheCLASSIFYextensionwasaddedtoNetfilterinversion1.2.9.
iptables -t mangle -A POSTROUTING -o eth2 -p tcp --sport 80 -j CLASSIFY --set-

11

LiLuxasbl

LinuxDays2008

class 1:10

Briefly,iptablesisbeinginstructedtoappendaruletothePOSTROUTINGsectionofmangle
table.TherulematchesTCPpacketswithasourceportof80thatarepassingoutoftheeth2
networkinterface.ThetargetofthisruleistheCLASSIFYextension,whichisdirectedtoclassify
thistrafficintotheclassdescribedbythemajornodenumber1andtheminornodenumber10.The
carefulreaderwillnoticethat,basedontheminornodenumberbeinggreaterthanzero,thetarget
mustbeaclassassignedtoaclassfulqdisc.
YoucanonlyuseCLASSIFYfromthePOSTROUTINGchainofthemangletable.Itisprohibited
elsewhere.Ifyoufindyouneedtoclassifypacketselsewhere,youmayneedtousetheMARK
targetinstead.

2.7.2UsingtheNetfilterMARKTarget
IfyoucannotusetheCLASSIFYtarget,youcanusethemarktargetinconjunctionwithtcto
classifyflows.
iptables -t mangle -A POSTROUTING -o eth2 -p tcp --sport 80 -j MARK --set-mark 1

Theaboveiptablesrulewillsetaninvisiblemarkonanypacketitmatches.Themarkexistsin
kernelspaceonly.Thepacketisnotactuallymodified.Thetcbinarycanbeusedtoclassifyflows
basedonthesemarks.
tc filter add dev eth0 protocol ip parent 1:0 prio 1 handle 1 fw classid 1:10

Theabovetccommandisnotunlikethefamiliarqdiscandclassvariants,exceptnowyou'readding
afilterinstead.Theparentparameterwillalwaysrefertotherootqdiscforthegiveninterface,
whichmustexistpriortocreatingthefilter.Theactualparameterhandlereferstothemarkthatyou
gavetheflowearlier.Theparameterclassidrefersto,unsurprisingly,thehandleoftheclassyou
wishtoassignthisflowto.It'sgenerallyonlyusefultoaddfiltersforinterfaceswhichhaveclassful
qdiscsconfigured.

2.8Testingtools

2.8.1Netem
Netemallowsemulatingthepropertiesofwideareanetworks.Thecurrentversionemulatesvariable
delay,loss,duplicationandreordering.networkemulator.
http://linuxnet.osdl.org/index.php/Netem

2.8.2IPTraf
IPTrafisaconsolebasednetworkstatisticsutilityforLinux.Itgathersavarietyoffiguressuchas
12

LiLuxasbl

LinuxDays2008

TCPconnectionpacketandbytecounts,interfacestatisticsandactivityindicators,TCP/UDPtraffic
breakdowns,andLANstationpacketandbytecounts.
http://iptraf.seul.org/

2.8.3Netcat
Netcatisafeaturednetworkingutilitywhichreadsandwritesdataacrossnetworkconnections,
usingtheTCP/IPprotocol.
Itisdesignedtobeareliable"backend"toolthatcanbeuseddirectlyoreasilydrivenbyother
programsandscripts.Atthesametime,itisafeaturerichnetworkdebuggingandexplorationtool,
sinceitcancreatealmostanykindofconnectionyouwouldneedandhasseveralinterestingbuiltin
capabilities.
http://netcat.sourceforge.net/

2.8.4iperf
IperfisatooltomeasuremaximumTCPbandwidth,allowingthetuningofvariousparametersand
UDPcharacteristics.Iperfreportsbandwidth,delayjitter,datagramloss.
http://dast.nlanr.net/Projects/Iperf/

2.9Example

tc
tc
tc
tc
tc

qdisc
class
class
class
qdisc

add
add
add
add
add

dev
dev
dev
dev
dev

eth2
eth2
eth2
eth2
eth2

parent
parent
parent
parent
parent

root handle
1:0 classid
1:1 classid
1:1 classid
1:20 handle

1:0 htb default 20


1:1 htb rate 1000kbit
1:10 htb rate 500kbit
1:20 htb rate 500kbit
2:0 sfq

Wehaveanestedstructure,withahtbclassfulqdiscassignedtotheroothook,threehtbclasses,
andasfqqdiscasaleafqdiscforonehtbclass.Theotherhasanimplicitpfifoattached.The
carefulreaderwillnoticeeachqdischasaminornodenumberofzero,asisrequired.
Atthetopofthehierarchyisahtbqdisc.Threeclassesareassignedtoit.Onlythefirstis
immediatelyattachedtoit,usingtheparent1:0.Theothertwoclassesarechildrenofthefirstclass.
Ifyouexaminethetccommandwiththeclassoption,youwillseethattheparentreferstothe
parentclassinthehierarchyviaitsclassid.
Eachofthethreehtbclassesattachedtothehtbqdiscareassignedamajornodenumberof1for
theclassid,astheqdisctheyareattachedtohasahandlewith1asthemajornodenumber.The
minornodenumberforeachclassidmustmerelybeauniquenumberbetween1andffffin
hexadecimal.
Finally,asfqqdiscisattachedtotheleafclasswithclassid1:20.Noticetheqdiscisaddednearly
thesameasthehtb.However,insteadofbeingassignedtothemagicroothook,thetargetis1:20.
Thehandleischosenbasedontherulesdiscussedearlier.Briefly,themajornodenumbermustbea
13

LiLuxasbl

LinuxDays2008

uniquenumberbetween1andffffandtheminornodemustbe0.
Last,thewholestructurecanbedeletedsimplybydeletingtheroothookasdemonstratedbelow.
tc qdisc del dev eth2 root

2.10Exercise

Setthemainoutgoingmaxrateforthefirstinterfaceto600kbit/s
Limitoutgoingport6667trafficto100kbit/s
Limitoutgoingport6668trafficto200kbit/s
Limittherestofthetrafficto500kbit/s
Useonefilterandoneiptablesrule.
Tools:iperf
Onthedestinationserver:
./iperfsp6667i1
./iperfsp6668i1
./iperfsp6669i1
OnthesourcePC(wheretherulesareadded)
./iperfcdestination.hostp6667
./iperfcdestination.hostp6668
./iperfcdestination.hostp6669

3 Links

Thebasicmustreadforallnetworking:http://lartc.org/
Completedocumentationaboutlinuxnetworking:http://www.faqs.org/docs/linux_network/
DetaileddescriptionofQOS:
http://www.trekweb.com/~jasonb/articles/traffic_shaping/index.html
Goodexamples:http://www.docum.org/docum.org/
IndepthQOS:http://luxik.cdi.cz/~devik/qos/htb/manual/theory.htm

4 AppendixA:iptablesmanpage
IPTABLES(8)IPTABLES(8)

NAME
iptablesadministrationtoolforIPv4packetfiltering
andNAT
SYNOPSIS
iptables[ttable][AD]chainrulespecification
[options]
iptables[ttable]Ichain[rulenum]rulespecification

14

LiLuxasbl

LinuxDays2008

[options]
iptables[ttable]Rchainrulenumrulespecification
[options]
iptables[ttable]Dchainrulenum[options]
iptables[ttable][LFZ][chain][options]
iptables[ttable]Nchain
iptables[ttable]X[chain]
iptables[ttable]Pchaintarget[options]
iptables[ttable]Eoldchainnamenewchainname
DESCRIPTION
Iptablesisusedtosetup,maintain,andinspectthe
tablesofIPpacketfilterrulesintheLinuxkernel.
Severaldifferenttablesmaybedefined.Eachtablecon
tainsanumberofbuiltinchainsandmayalsocontain
userdefinedchains.
Eachchainisalistofruleswhichcanmatchasetof
packets.Eachrulespecifieswhattodowithapacket
thatmatches.Thisiscalledatarget',whichmaybea
jumptoauserdefinedchaininthesametable.
TARGETS
Afirewallrulespecifiescriteriaforapacket,anda
target.Ifthepacketdoesnotmatch,thenextrulein
thechainistheexamined;ifitdoesmatch,thenthenext
ruleisspecifiedbythevalueofthetarget,whichcanbe
thenameofauserdefinedchainoroneofthespecial
valuesACCEPT,DROP,QUEUE,orRETURN.
ACCEPTmeanstoletthepacketthrough.DROPmeansto
dropthepacketonthefloor.QUEUEmeanstopassthe
packettouserspace(ifsupportedbythekernel).RETURN
meansstoptraversingthischainandresumeatthenext
ruleintheprevious(calling)chain.Iftheendofa
builtinchainisreachedoraruleinabuiltinchain
withtargetRETURNismatched,thetargetspecifiedbythe
chainpolicydeterminesthefateofthepacket.
TABLES
Therearecurrentlythreeindependenttables(whichtables
arepresentatanytimedependsonthekernelconfigura
tionoptionsandwhichmodulesarepresent).
t,tabletable
Thisoptionspecifiesthepacketmatchingtable
whichthecommandshouldoperateon.Ifthekernel
isconfiguredwithautomaticmoduleloading,an
attemptwillbemadetoloadtheappropriatemodule
forthattableifitisnotalreadythere.
Thetablesareasfollows:
filter:
Thisisthedefaulttable(ifnotoptionis
passed).ItcontainsthebuiltinchainsINPUT
(forpacketscomingintotheboxitself),FOR
WARD(forpacketsbeingroutedthroughthe
box),andOUTPUT(forlocallygeneratedpack
ets).
nat:
Thistableisconsultedwhenapacketthatcre
atesanewconnectionisencountered.Itcon
sistsofthreebuiltins:PREROUTING(for

15

LiLuxasbl

LinuxDays2008

alteringpacketsassoonastheycomein),OUT
PUT(foralteringlocallygeneratedpackets
beforerouting),andPOSTROUTING(foraltering
packetsastheyareabouttogoout).
mangle:
Thistableisusedforspecializedpacket
alteration.Untilkernel2.4.17ithadtwo
builtinchains:PREROUTING(foraltering
incomingpacketsbeforerouting)andOUTPUT
(foralteringlocallygeneratedpacketsbefore
routing).Sincekernel2.4.18,threeother
builtinchainsarealsosupported:INPUT(for
packetscomingintotheboxitself),FORWARD
(foralteringpacketsbeingroutedthroughthe
box),andPOSTROUTING(foralteringpacketsas
theyareabouttogoout).
OPTIONS
Theoptionsthatarerecognizedbyiptablescanbedivided
intoseveraldifferentgroups.
COMMANDS
Theseoptionsspecifythespecificactiontoperform.
Onlyoneofthemcanbespecifiedonthecommandline
unlessotherwisespecifiedbelow.Forallthelongver
sionsofthecommandandoptionnames,youneedtouse
onlyenoughletterstoensurethatiptablescandifferen
tiateitfromallotheroptions.
A,appendchainrulespecification
Appendoneormorerulestotheendoftheselected
chain.Whenthesourceand/ordestinationnames
resolvetomorethanoneaddress,arulewillbe
addedforeachpossibleaddresscombination.
D,deletechainrulespecification
D,deletechainrulenum
Deleteoneormorerulesfromtheselectedchain.
Therearetwoversionsofthiscommand:therule
canbespecifiedasanumberinthechain(starting
at1forthefirstrule)oraruletomatch.
I,insertchain[rulenum]rulespecification
Insertoneormorerulesintheselectedchainas
thegivenrulenumber.So,iftherulenumberis
1,theruleorrulesareinsertedattheheadof
thechain.Thisisalsothedefaultifnorule
numberisspecified.
R,replacechainrulenumrulespecification
Replacearuleintheselectedchain.Ifthe
sourceand/ordestinationnamesresolvetomultiple
addresses,thecommandwillfail.Rulesare
numberedstartingat1.
L,list[chain]
Listallrulesintheselectedchain.Ifnochain
isselected,allchainsarelisted.Aseveryother
iptablescommand,itappliestothespecifiedtable
(filteristhedefault),soNATrulesgetlistedby
iptablestnatnL
Pleasenotethatitisoftenusedwiththen
option,inordertoavoidlongreverseDNSlookups.
ItislegaltospecifytheZ(zero)optionas
well,inwhichcasethechain(s)willbeatomically

16

LiLuxasbl

LinuxDays2008

listedandzeroed.Theexactoutputisaffectedby
theotherargumentsgiven.Theexactrulesaresup
presseduntilyouuse
iptablesLv
F,flush[chain]
Flushtheselectedchain(allthechainsinthe
tableifnoneisgiven).Thisisequivalentto
deletingalltherulesonebyone.
Z,zero[chain]
Zerothepacketandbytecountersinallchains.
ItislegaltospecifytheL,list(list)option
aswell,toseethecountersimmediatelybefore
theyarecleared.(Seeabove.)
N,newchainchain
Createanewuserdefinedchainbythegivenname.
Theremustbenotargetofthatnamealready.
X,deletechain[chain]
Deletetheoptionaluserdefinedchainspecified.
Theremustbenoreferencestothechain.Ifthere
are,youmustdeleteorreplacethereferringrules
beforethechaincanbedeleted.Ifnoargumentis
given,itwillattempttodeleteeverynonbuiltin
chaininthetable.
P,policychaintarget
Setthepolicyforthechaintothegiventarget.
SeethesectionTARGETSforthelegaltargets.
Onlybuiltin(nonuserdefined)chainscanhave
policies,andneitherbuiltinnoruserdefined
chainscanbepolicytargets.
E,renamechainoldchainnewchain
Renametheuserspecifiedchaintotheusersup
pliedname.Thisiscosmetic,andhasnoeffecton
thestructureofthetable.
hHelp.Givea(currentlyverybrief)descriptionof
thecommandsyntax.
PARAMETERS
Thefollowingparametersmakeuparulespecification(as
usedintheadd,delete,insert,replaceandappendcom
mands).
p,protocol[!]protocol
Theprotocoloftheruleorofthepackettocheck.
Thespecifiedprotocolcanbeoneoftcp,udp,
icmp,orall,oritcanbeanumericvalue,repre
sentingoneoftheseprotocolsoradifferentone.
Aprotocolnamefrom/etc/protocolsisalso
allowed.A"!"argumentbeforetheprotocol
invertsthetest.Thenumberzeroisequivalentto
all.Protocolallwillmatchwithallprotocols
andistakenasdefaultwhenthisoptionisomit
ted.
s,source[!]address[/mask]
Sourcespecification.Addresscanbeeitheranet
workname,ahostname(pleasenotethatspecifying
anynametoberesolvedwitharemotequerysuchas
DNSisareallybadidea),anetworkIPaddress
(with/mask),oraplainIPaddress.Themaskcan

17

LiLuxasbl

LinuxDays2008

beeitheranetworkmaskoraplainnumber,speci
fyingthenumberof1'sattheleftsideofthe
networkmask.Thus,amaskof24isequivalentto
255.255.255.0.A"!"argumentbeforetheaddress
specificationinvertsthesenseoftheaddress.The
flagsrcisanaliasforthisoption.
d,destination[!]address[/mask]
Destinationspecification.Seethedescriptionof
thes(source)flagforadetaileddescriptionof
thesyntax.Theflagdstisanaliasforthis
option.
j,jumptarget
Thisspecifiesthetargetoftherule;i.e.,what
todoifthepacketmatchesit.Thetargetcanbe
auserdefinedchain(otherthantheonethisrule
isin),oneofthespecialbuiltintargetswhich
decidethefateofthepacketimmediately,oran
extension(seeEXTENSIONSbelow).Ifthisoption
isomittedinarule,thenmatchingtherulewill
havenoeffectonthepacket'sfate,butthecoun
tersontherulewillbeincremented.
i,ininterface[!]name
Nameofaninterfaceviawhichapacketisgoingto
bereceived(onlyforpacketsenteringtheINPUT,
FORWARDandPREROUTINGchains).Whenthe"!"argu
mentisusedbeforetheinterfacename,thesense
isinverted.Iftheinterfacenameendsina"+",
thenanyinterfacewhichbeginswiththisnamewill
match.Ifthisoptionisomitted,anyinterface
namewillmatch.
o,outinterface[!]name
Nameofaninterfaceviawhichapacketisgoingto
besent(forpacketsenteringtheFORWARD,OUTPUT
andPOSTROUTINGchains).Whenthe"!"argumentis
usedbeforetheinterfacename,thesenseis
inverted.Iftheinterfacenameendsina"+",
thenanyinterfacewhichbeginswiththisnamewill
match.Ifthisoptionisomitted,anyinterface
namewillmatch.
[!]f,fragment
Thismeansthattheruleonlyreferstosecondand
furtherfragmentsoffragmentedpackets.Since
thereisnowaytotellthesourceordestination
portsofsuchapacket(orICMPtype),sucha
packetwillnotmatchanyruleswhichspecifythem.
Whenthe"!"argumentprecedesthe"f"flag,the
rulewillonlymatchheadfragments,orunfrag
mentedpackets.
c,setcountersPKTSBYTES
Thisenablestheadministratortoinitializethe
packetandbytecountersofarule(duringINSERT,
APPEND,REPLACEoperations).
OTHEROPTIONS
Thefollowingadditionaloptionscanbespecified:
v,verbose
Verboseoutput.Thisoptionmakesthelistcommand
showtheinterfacename,theruleoptions(ifany),
andtheTOSmasks.Thepacketandbytecounters

18

LiLuxasbl

LinuxDays2008

arealsolisted,withthesuffix'K','M'or'G'
for1000,1,000,000and1,000,000,000multipliers
respectively(butseethexflagtochangethis).
Forappending,insertion,deletionandreplacement,
thiscausesdetailedinformationontheruleor
rulestobeprinted.
n,numeric
Numericoutput.IPaddressesandportnumberswill
beprintedinnumericformat.Bydefault,thepro
gramwilltrytodisplaythemashostnames,net
worknames,orservices(wheneverapplicable).
x,exact
Expandnumbers.Displaytheexactvalueofthe
packetandbytecounters,insteadofonlythe
roundednumberinK's(multiplesof1000)M's(mul
tiplesof1000K)orG's(multiplesof1000M).This
optionisonlyrelevantfortheLcommand.
linenumbers
Whenlistingrules,addlinenumberstothebegin
ningofeachrule,correspondingtothatrule's
positioninthechain.
modprobe=command
Whenaddingorinsertingrulesintoachain,use
commandtoloadanynecessarymodules(targets,
matchextensions,etc).
MATCHEXTENSIONS
iptablescanuseextendedpacketmatchingmodules.These
areloadedintwoways:implicitly,whenporprotocol
isspecified,orwiththemormatchoptions,followed
bythematchingmodulename;afterthese,variousextra
commandlineoptionsbecomeavailable,dependingonthe
specificmodule.Youcanspecifymultipleextendedmatch
modulesinoneline,andyoucanusethehorhelp
optionsafterthemodulehasbeenspecifiedtoreceive
helpspecifictothatmodule.
Thefollowingareincludedinthebasepackage,andmost
ofthesecanbeprecededbya!toinvertthesenseof
thematch.
ah
ThismodulematchestheSPIsinAHheaderofIPSecpack
ets.
ahspi[!]spi[:spi]
conntrack
Thismodule,whencombinedwithconnectiontracking,
allowsaccesstomoreconnectiontrackinginformationthan
the"state"match.(thismoduleispresentonlyifipta
bleswascompiledunderakernelsupportingthisfeature)
ctstatestate
Wherestateisacommaseparatedlistofthecon
nectionstatestomatch.Possiblestatesare
INVALIDmeaningthatthepacketisassociatedwith
noknownconnection,ESTABLISHEDmeaningthatthe
packetisassociatedwithaconnectionwhichhas
seenpacketsinbothdirections,NEWmeaningthat
thepackethasstartedanewconnection,orother
wiseassociatedwithaconnectionwhichhasnot

19

LiLuxasbl

LinuxDays2008

seenpacketsinbothdirections,andRELATEDmean
ingthatthepacketisstartinganewconnection,
butisassociatedwithanexistingconnection,such
asanFTPdatatransfer,oranICMPerror.SNATA
virtualstate,matchingiftheoriginalsource
addressdiffersfromthereplydestination.DNATA
virtualstate,matchingiftheoriginaldestination
differsfromthereplysource.
ctprotoproto
Protocoltomatch(bynumberorname)
ctorigsrc[!]address[/mask]
Matchagainstoriginalsourceaddress
ctorigdst[!]address[/mask]
Matchagainstoriginaldestinationaddress
ctreplsrc[!]address[/mask]
Matchagainstreplysourceaddress
ctrepldst[!]address[/mask]
Matchagainstreplydestinationaddress
ctstatus[NONE|EXPECTED|SEEN_REPLY|ASSURED][,...]
Matchagainstinternalconntrackstates
ctexpiretime[:time]
Matchremaininglifetimeinsecondsagainstgiven
valueorrangeofvalues(inclusive)
dscp
Thismodulematchesthe6bitDSCPfieldwithintheTOS
fieldintheIPheader.DSCPhassupersededTOSwithin
theIETF.
dscpvalue
Matchagainstanumeric(decimalorhex)value
[032].
dscpclassDiffServClass
MatchtheDiffServclass.Thisvaluemaybeanyof
theBE,EF,AFxxorCSxclasses.Itwillthenbe
convertedintoit'saccordingnumericvalue.
esp
ThismodulematchestheSPIsinESPheaderofIPSecpack
ets.
espspi[!]spi[:spi]
helper
Thismodulematchespacketsrelatedtoaspecificcon
ntrackhelper.
helperstring
Matchespacketsrelatedtothespecifiedconntrack
helper.
stringcanbe"ftp"forpacketsrelatedtoaftp
sessionondefaultport.Forotherportsappend
portnrtothevalue,ie."ftp2121".
Samerulesapplyforotherconntrackhelpers.
icmp

20

LiLuxasbl

LinuxDays2008

Thisextensionisloadedifprotocolicmp'isspeci
fied.Itprovidesthefollowingoption:
icmptype[!]typename
ThisallowsspecificationoftheICMPtype,which
canbeanumericICMPtype,oroneoftheICMPtype
namesshownbythecommand
iptablespicmph
length
Thismodulematchesthelengthofapacketagainstaspe
cificvalueorrangeofvalues.
lengthlength[:length]
limit
Thismodulematchesatalimitedrateusingatokenbucket
filter.Aruleusingthisextensionwillmatchuntilthis
limitisreached(unlessthe!'flagisused).Itcanbe
usedincombinationwiththeLOGtargettogivelimited
logging,forexample.
limitrate
Maximumaveragematchingrate:specifiedasanum
ber,withanoptional/second',/minute',
/hour',or/day'suffix;thedefaultis3/hour.
limitburstnumber
Maximuminitialnumberofpacketstomatch:this
numbergetsrechargedbyoneeverytimethelimit
specifiedaboveisnotreached,uptothisnumber;
thedefaultis5.
mac
macsource[!]address
MatchsourceMACaddress.Itmustbeoftheform
XX:XX:XX:XX:XX:XX.Notethatthisonlymakessense
forpacketscomingfromanEthernetdeviceand
enteringthePREROUTING,FORWARDorINPUTchains.
mark
Thismodulematchesthenetfiltermarkfieldassociated
withapacket(whichcanbesetusingtheMARKtarget
below).
markvalue[/mask]
Matchespacketswiththegivenunsignedmarkvalue
(ifamaskisspecified,thisislogicallyANDed
withthemaskbeforethecomparison).
multiport
Thismodulematchesasetofsourceordestinationports.
Upto15portscanbespecified.Itcanonlybeusedin
conjunctionwithptcporpudp.
sourceportsport[,port[,port...]]
Matchifthesourceportisoneofthegivenports.
Theflagsportsisaconvenientaliasforthis
option.
destinationportsport[,port[,port...]]
Matchifthedestinationportisoneofthegiven
ports.Theflagdportsisaconvenientaliasfor
thisoption.
portsport[,port[,port...]]

21

LiLuxasbl

LinuxDays2008

Matchiftheboththesourceanddestinationports
areequaltoeachotherandtooneofthegiven
ports.
owner
Thismoduleattemptstomatchvariouscharacteristicsof
thepacketcreator,forlocallygeneratedpackets.Itis
onlyvalidintheOUTPUTchain,andeventhissomepackets
(suchasICMPpingresponses)mayhavenoowner,andhence
nevermatch.
uidowneruserid
Matchesifthepacketwascreatedbyaprocesswith
thegiveneffectiveuserid.
gidownergroupid
Matchesifthepacketwascreatedbyaprocesswith
thegiveneffectivegroupid.
pidownerprocessid
Matchesifthepacketwascreatedbyaprocesswith
thegivenprocessid.
sidownersessionid
Matchesifthepacketwascreatedbyaprocessin
thegivensessiongroup.
cmdownername
Matchesifthepacketwascreatedbyaprocesswith
thegivencommandname.(thisoptionispresent
onlyifiptableswascompiledunderakernelsup
portingthisfeature)
physdev
Thismodulematchesonthebridgeportinputandoutput
devicesenslavedtoabridgedevice.Thismoduleisapart
oftheinfrastructurethatenablesatransparentbridging
IPfirewallandisonlyusefulforkernelversionsabove
version2.5.44.
physdevinname
Nameofabridgeportviawhichapacketis
received(onlyforpacketsenteringtheINPUT,FOR
WARDandPREROUTINGchains).Iftheinterfacename
endsina"+",thenanyinterfacewhichbeginswith
thisnamewillmatch.Ifthepacketdidn'tarrive
throughabridgedevice,thispacketwon'tmatch
thisoption,unless'!'isused.
physdevoutname
Nameofabridgeportviawhichapacketisgoing
tobesent(forpacketsenteringtheFORWARD,OUT
PUTandPOSTROUTINGchains).Iftheinterfacename
endsina"+",thenanyinterfacewhichbeginswith
thisnamewillmatch.Notethatinthenatandman
gleOUTPUTchainsonecannotmatchonthebridge
outputport,howeveronecaninthefilterOUTPUT
chain.Ifthepacketwon'tleavebyabridgedevice
oritisyetunknownwhattheoutputdevicewill
be,thenthepacketwon'tmatchthisoption,unless
physdevisin
Matchesifthepackethasenteredthroughabridge
interface.
physdevisout

22

LiLuxasbl

LinuxDays2008

Matchesifthepacketwillleavethroughabridge
interface.
physdevisbridged
Matchesifthepacketisbeingbridgedandthere
foreisnotbeingrouted.Thisisonlyusefulin
theFORWARDandPOSTROUTINGchains.
pkttype
Thismodulematchesthelinklayerpackettype.
pkttype[unicast|broadcast|multicast]
state
Thismodule,whencombinedwithconnectiontracking,
allowsaccesstotheconnectiontrackingstateforthis
packet.
statestate
Wherestateisacommaseparatedlistofthecon
nectionstatestomatch.Possiblestatesare
INVALIDmeaningthatthepacketcouldnotbeiden
tifiedforsomereasonwhichincludesrunningout
ofmemoryandICMPerrorswhichdon'tcorrespondto
anyknownconnection,ESTABLISHEDmeaningthatthe
packetisassociatedwithaconnectionwhichhas
seenpacketsinbothdirections,NEWmeaningthat
thepackethasstartedanewconnection,orother
wiseassociatedwithaconnectionwhichhasnot
seenpacketsinbothdirections,andRELATEDmean
ingthatthepacketisstartinganewconnection,
butisassociatedwithanexistingconnection,such
asanFTPdatatransfer,oranICMPerror.
tcp
Theseextensionsareloadedifprotocoltcp'isspeci
fied.Itprovidesthefollowingoptions:
sourceport[!]port[:port]
Sourceportorportrangespecification.Thiscan
eitherbeaservicenameoraportnumber.An
inclusiverangecanalsobespecified,usingthe
formatport:port.Ifthefirstportisomitted,
"0"isassumed;ifthelastisomitted,"65535"is
assumed.Ifthesecondportgreaterthenthefirst
theywillbeswapped.Theflagsportisaconve
nientaliasforthisoption.
destinationport[!]port[:port]
Destinationportorportrangespecification.The
flagdportisaconvenientaliasforthisoption.
tcpflags[!]maskcomp
MatchwhentheTCPflagsareasspecified.The
firstargumentistheflagswhichweshouldexam
ine,writtenasacommaseparatedlist,andthe
secondargumentisacommaseparatedlistofflags
whichmustbeset.Flagsare:SYNACKFINRSTURG
PSHALLNONE.Hencethecommand
iptablesAFORWARDptcptcpflagsSYN,ACK,FIN,RSTSYN
willonlymatchpacketswiththeSYNflagset,and
theACK,FINandRSTflagsunset.
[!]syn
OnlymatchTCPpacketswiththeSYNbitsetandthe
ACKandRSTbitscleared.Suchpacketsareusedto

23

LiLuxasbl

LinuxDays2008

requestTCPconnectioninitiation;forexample,
blockingsuchpacketscominginaninterfacewill
preventincomingTCPconnections,butoutgoingTCP
connectionswillbeunaffected.Itisequivalent
totcpflagsSYN,RST,ACKSYN.Ifthe"!"flag
precedesthe"syn",thesenseoftheoptionis
inverted.
tcpoption[!]number
MatchifTCPoptionset.
mssvalue[:value]
MatchTCPSYNorSYN/ACKpacketswiththespecified
MSSvalue(orrange),whichcontrolthemaximum
packetsizeforthatconnection.
tos
Thismodulematchesthe8bitsofTypeofServicefieldin
theIPheader(ie.includingtheprecedencebits).
tostos
Theargumentiseitherastandardname,(use
iptablesmtosh
toseethelist),oranumericvaluetomatch.
ttl
ThismodulematchesthetimetolivefieldintheIP
header.
ttlttl
MatchesthegivenTTLvalue.
udp
Theseextensionsareloadedifprotocoludp'isspeci
fied.Itprovidesthefollowingoptions:
sourceport[!]port[:port]
Sourceportorportrangespecification.Seethe
descriptionofthesourceportoptionoftheTCP
extensionfordetails.
destinationport[!]port[:port]
Destinationportorportrangespecification.See
thedescriptionofthedestinationportoptionof
theTCPextensionfordetails.
unclean
Thismoduletakesnooptions,butattemptstomatchpack
etswhichseemmalformedorunusual.Thisisregardedas
experimental.
TARGETEXTENSIONS
iptablescanuseextendedtargetmodules:thefollowing
areincludedinthestandarddistribution.
DNAT
Thistargetisonlyvalidinthenattable,inthePRE
ROUTINGandOUTPUTchains,anduserdefinedchainswhich
areonlycalledfromthosechains.Itspecifiesthatthe
destinationaddressofthepacketshouldbemodified(and
allfuturepacketsinthisconnectionwillalsobeman
gled),andrulesshouldceasebeingexamined.Ittakes
onetypeofoption:
todestinationipaddr[ipaddr][:portport]
whichcanspecifyasinglenewdestinationIP

24

LiLuxasbl

LinuxDays2008

address,aninclusiverangeofIPaddresses,and
optionally,aportrange(whichisonlyvalidif
therulealsospecifiesptcporpudp).Ifno
portrangeisspecified,thenthedestinationport
willneverbemodified.
Youcanaddseveraltodestinationoptions.If
youspecifymorethanonedestinationaddress,
eitherviaanaddressrangeormultipletodesti
nationoptions,asimpleroundrobin(oneafter
anotherincycle)loadbalancingtakesplace
betweentheseadresses.
DSCP
ThistargetallowstoalterthevalueoftheDSCPbits
withintheTOSheaderoftheIPv4packet.Asthismanipu
latesapacket,itcanonlybeusedinthemangletable.
setdscpvalue
SettheDSCPfieldtoanumericalvalue(canbe
decimalorhex)
setdscpclassclass
SettheDSCPfieldtoaDiffServclass.
ECN
ThistargetallowstoselectivelyworkaroundknownECN
blackholes.Itcanonlybeusedinthemangletable.
ecntcpremove
RemoveallECNbitsfromtheTCPheader.Of
course,itcanonlybeusedinconjunctionwithp
tcp.
LOG
Turnonkernelloggingofmatchingpackets.Whenthis
optionissetforarule,theLinuxkernelwillprintsome
informationonallmatchingpackets(likemostIPheader
fields)viathekernellog(whereitcanbereadwith
dmesgorsyslogd(8)).Thisisa"nonterminatingtarget",
i.e.ruletraversalcontinuesatthenextrule.Soifyou
wanttoLOGthepacketsyourefuse,usetwoseparaterules
withthesamematchingcriteria,firstusingtargetLOG
thenDROP(orREJECT).
loglevellevel
Leveloflogging(numericorseesyslog.conf(5)).
logprefixprefix
Prefixlogmessageswiththespecifiedprefix;up
to29letterslong,andusefulfordistinguishing
messagesinthelogs.
logtcpsequence
LogTCPsequencenumbers.Thisisasecurityrisk
ifthelogisreadablebyusers.
logtcpoptions
LogoptionsfromtheTCPpacketheader.
logipoptions
LogoptionsfromtheIPpacketheader.
MARK
Thisisusedtosetthenetfiltermarkvalueassociated
withthepacket.Itisonlyvalidinthemangletable.

25

LiLuxasbl

LinuxDays2008

Itcanforexamplebeusedinconjunctionwithiproute2.
setmarkmark
MASQUERADE
Thistargetisonlyvalidinthenattable,inthe
POSTROUTINGchain.Itshouldonlybeusedwithdynami
callyassignedIP(dialup)connections:ifyouhavea
staticIPaddress,youshouldusetheSNATtarget.Mas
queradingisequivalenttospecifyingamappingtotheIP
addressoftheinterfacethepacketisgoingout,butalso
hastheeffectthatconnectionsareforgottenwhenthe
interfacegoesdown.Thisisthecorrectbehaviorwhen
thenextdialupisunlikelytohavethesameinterface
address(andhenceanyestablishedconnectionsarelost
anyway).Ittakesoneoption:
toportsport[port]
Thisspecifiesarangeofsourceportstouse,
overridingthedefaultSNATsourceportselection
heuristics(seeabove).Thisisonlyvalidifthe
rulealsospecifiesptcporpudp.
MIRROR
Thisisanexperimentaldemonstrationtargetwhichinverts
thesourceanddestinationfieldsintheIPheaderand
retransmitsthepacket.ItisonlyvalidintheINPUT,
FORWARDandPREROUTINGchains,anduserdefinedchains
whichareonlycalledfromthosechains.Notethatthe
outgoingpacketsareNOTseenbyanypacketfiltering
chains,connectiontrackingorNAT,toavoidloopsand
otherproblems.
REDIRECT
Thistargetisonlyvalidinthenattable,inthePRE
ROUTINGandOUTPUTchains,anduserdefinedchainswhich
areonlycalledfromthosechains.Italtersthedestina
tionIPaddresstosendthepackettothemachineitself
(locallygeneratedpacketsaremappedtothe127.0.0.1
address).Ittakesoneoption:
toportsport[port]
Thisspecifiesadestinationportorrangeofports
touse:withoutthis,thedestinationportisnever
altered.Thisisonlyvalidiftherulealsospec
ifiesptcporpudp.
REJECT
Thisisusedtosendbackanerrorpacketinresponseto
thematchedpacket:otherwiseitisequivalenttoDROPso
itisaterminatingTARGET,endingruletraversal.This
targetisonlyvalidintheINPUT,FORWARDandOUTPUT
chains,anduserdefinedchainswhichareonlycalledfrom
thosechains.Thefollowingoptioncontrolsthenatureof
theerrorpacketreturned:
rejectwithtype
Thetypegivencanbe
icmpnetunreachable
icmphostunreachable
icmpportunreachable
icmpprotounreachable
icmpnetprohibited
icmphostprohibitedor
icmpadminprohibited(*)
whichreturntheappropriateICMPerrormessage

26

LiLuxasbl

LinuxDays2008

(portunreachableisthedefault).Theoptiontcp
resetcanbeusedonruleswhichonlymatchtheTCP
protocol:thiscausesaTCPRSTpackettobesent
back.Thisismainlyusefulforblockingident
(113/tcp)probeswhichfrequentlyoccurwhensend
ingmailtobrokenmailhosts(whichwon'taccept
yourmailotherwise).
(*)Usingicmpadminprohibitedwithkernelsthatdonot
supportitwillresultinaplainDROPinsteadofREJECT
SNAT
Thistargetisonlyvalidinthenattable,inthe
POSTROUTINGchain.Itspecifiesthatthesourceaddress
ofthepacketshouldbemodified(andallfuturepackets
inthisconnectionwillalsobemangled),andrulesshould
ceasebeingexamined.Ittakesonetypeofoption:
tosourceipaddr[ipaddr][:portport]
whichcanspecifyasinglenewsourceIPaddress,
aninclusiverangeofIPaddresses,andoptionally,
aportrange(whichisonlyvalidiftherulealso
specifiesptcporpudp).Ifnoportrangeis
specified,thensourceportsbelow512willbe
mappedtootherportsbelow512:thosebetween512
and1023inclusivewillbemappedtoportsbelow
1024,andotherportswillbemappedto1024or
above.Wherepossible,noportalterationwill
occur.
Youcanaddseveraltosourceoptions.Ifyou
specifymorethanonesourceaddress,eitherviaan
addressrangeormultipletosourceoptions,a
simpleroundrobin(oneafteranotherincycle)
takesplacebetweentheseadresses.
TCPMSS
ThistargetallowstoaltertheMSSvalueofTCPSYNpack
ets,tocontrolthemaximumsizeforthatconnection(usu
allylimitingittoyouroutgoinginterface'sMTUminus
40).Ofcourse,itcanonlybeusedinconjunctionwith
ptcp.
ThistargetisusedtoovercomecriminallybraindeadISPs
orserverswhichblockICMPFragmentationNeededpackets.
Thesymptomsofthisproblemarethateverythingworks
finefromyourLinuxfirewall/router,butmachinesbehind
itcanneverexchangelargepackets:
1)Webbrowsersconnect,thenhangwithnodatareceived.
2)Smallmailworksfine,butlargeemailshang.
3)sshworksfine,butscphangsafterinitialhandshak
ing.
Workaround:activatethisoptionandaddaruletoyour
firewallconfigurationlike:
iptablesAFORWARDptcptcpflagsSYN,RSTSYN\
jTCPMSSclampmsstopmtu
setmssvalue
ExplicitlysetMSSoptiontospecifiedvalue.
clampmsstopmtu
AutomaticallyclampMSSvalueto(path_MTU40).
Theseoptionsaremutuallyexclusive.
TOS
Thisisusedtosetthe8bitTypeofServicefieldinthe

27

LiLuxasbl

LinuxDays2008

IPheader.Itisonlyvalidinthemangletable.
settostos
YoucanuseanumericTOSvalues,oruse
iptablesjTOSh
toseethelistofvalidTOSnames.
ULOG
Thistargetprovidesuserspaceloggingofmatchingpack
ets.Whenthistargetissetforarule,theLinuxkernel
willmulticastthispacketthroughanetlinksocket.One
ormoreuserspaceprocessesmaythensubscribetovarious
multicastgroupsandreceivethepackets.LikeLOG,this
isa"nonterminatingtarget",i.e.ruletraversalcontin
uesatthenextrule.
ulognlgroupnlgroup
Thisspecifiesthenetlinkgroup(132)towhich
thepacketissent.Defaultvalueis1.
ulogprefixprefix
Prefixlogmessageswiththespecifiedprefix;up
to32characterslong,andusefulfordistinguish
ingmessagesinthelogs.
ulogcprangesize
Numberofbytestobecopiedtouserspace.Avalue
of0alwayscopiestheentirepacket,regardlessof
itssize.Defaultis0.
ulogqthresholdsize
Numberofpackettoqueueinsidekernel.Setting
thisvalueto,e.g.10accumulatestenpackets
insidethekernelandtransmitsthemasonenetlink
multipartmessagetouserspace.Defaultis1(for
backwardscompatibility).
DIAGNOSTICS
Variouserrormessagesareprintedtostandarderror.The
exitcodeis0forcorrectfunctioning.Errorswhich
appeartobecausedbyinvalidorabusedcommandline
parameterscauseanexitcodeof2,andothererrorscause
anexitcodeof1.
BUGS
Bugs?What'sthis?;)Well...thecountersarenotreli
ableonsparc64.
COMPATIBILITYWITHIPCHAINS
ThisiptablesisverysimilartoipchainsbyRustyRus
sell.ThemaindifferenceisthatthechainsINPUTand
OUTPUTareonlytraversedforpacketscomingintothe
localhostandoriginatingfromthelocalhostrespec
tively.Henceeverypacketonlypassesthroughoneofthe
threechains(exceptloopbacktraffic,whichinvolvesboth
INPUTandOUTPUTchains);previouslyaforwardedpacket
wouldpassthroughallthree.
Theothermaindifferenceisthatireferstotheinput
interface;oreferstotheoutputinterface,andbothare
availableforpacketsenteringtheFORWARDchain.
iptablesisapurepacketfilterwhenusingthedefault
filter'table,withoptionalextensionmodules.This
shouldsimplifymuchofthepreviousconfusionoverthe
combinationofIPmasqueradingandpacketfilteringseen

28

LiLuxasbl

LinuxDays2008

previously.Sothefollowingoptionsarehandleddiffer
ently:
jMASQ
MS
ML
Thereareseveralotherchangesiniptables.
SEEALSO
iptablessave(8),iptablesrestore(8),ip6tables(8),
ip6tablessave(8),ip6tablesrestore(8).
ThepacketfilteringHOWTOdetailsiptablesusagefor
packetfiltering,theNATHOWTOdetailsNAT,thenetfil
terextensionsHOWTOdetailstheextensionsthatarenot
inthestandarddistribution,andthenetfilterhacking
HOWTOdetailsthenetfilterinternals.
Seehttp://www.netfilter.org/.
AUTHORS
RustyRussellwroteiptables,inearlyconsultationwith
MichaelNeuling.
MarcBouchermadeRustyabandonipnatctlbylobbyingfora
genericpacketselectionframeworkiniptables,thenwrote
themangletable,theownermatch,themarkstuff,andran
arounddoingcoolstuffeverywhere.
JamesMorriswrotetheTOStarget,andtosmatch.
JozsefKadlecsikwrotetheREJECTtarget.
HaraldWeltewrotetheULOGtarget,TTL,DSCP,ECNmatches
andtargets.
TheNetfilterCoreTeamis:MarcBoucher,MartinJosefs
son,JozsefKadlecsik,JamesMorris,HaraldWelteand
RustyRussell.
ManpagewrittenbyHerveEychenne<rv@wallfire.org>.

Mar09,2002IPTABLES(8)

29

LiLuxasbl

LinuxDays2008

5 AppendixB:tcmanpages:
TC(8)LinuxTC(8)

NAME
tcshow/manipulatetrafficcontrolsettings
SYNOPSIS
tcqdisc[add|change|replace|link]devDEV[par
entqdiscid|root][handleqdiscid]qdisc[qdisc
specificparameters]
tcclass[add|change|replace]devDEVparentqdisc
id[classidclassid]qdisc[qdiscspecificparameters
]
tcfilter[add|change|replace]devDEV[parent
qdiscid|root]protocolprotocolpriopriorityfilter
type[filtertypespecificparameters]flowidflowid
tc[s|d]qdiscshow[devDEV]
tc[s|d]classshowdevDEV
tcfiltershowdevDEV
DESCRIPTION
TcisusedtoconfigureTrafficControlintheLinuxker
nel.TrafficControlconsistsofthefollowing:
SHAPING
Whentrafficisshaped,itsrateoftransmissionis
undercontrol.Shapingmaybemorethanlowering
theavailablebandwidthitisalsousedtosmooth
outburstsintrafficforbetternetworkbehaviour.
Shapingoccursonegress.
SCHEDULING
Byschedulingthetransmissionofpacketsitis
possibletoimproveinteractivityfortrafficthat
needsitwhilestillguaranteeingbandwidthtobulk
transfers.Reorderingisalsocalledprioritizing,
andhappensonlyonegress.
POLICING
Whereshapingdealswithtransmissionoftraffic,
policingpertainstotrafficarriving.Policing
thusoccursoningress.
DROPPING
Trafficexceedingasetbandwidthmayalsobe
droppedforthwith,bothoningressandonegress.

30

LiLuxasbl

LinuxDays2008

Processingoftrafficiscontrolledbythreekindsof
objects:qdiscs,classesandfilters.
QDISCS
qdiscisshortfor'queueingdiscipline'anditiselemen
tarytounderstandingtrafficcontrol.Wheneverthekernel
needstosendapackettoaninterface,itisenqueuedto
theqdiscconfiguredforthatinterface.Immediately
afterwards,thekerneltriestogetasmanypacketsas
possiblefromtheqdisc,forgivingthemtothenetwork
adaptordriver.
AsimpleQDISCisthe'pfifo'one,whichdoesnoprocess
ingatallandisapureFirstIn,FirstOutqueue.It
doeshoweverstoretrafficwhenthenetworkinterface
can'thandleitmomentarily.
CLASSES
Someqdiscscancontainclasses,whichcontainfurther
qdiscstrafficmaythenbeenqueuedinanyoftheinner
qdiscs,whicharewithintheclasses.Whenthekernel
triestodequeueapacketfromsuchaclassfulqdiscit
cancomefromanyoftheclasses.Aqdiscmayforexample
prioritizecertainkindsoftrafficbytryingtodequeue
fromcertainclassesbeforeothers.
FILTERS
Afilterisusedbyaclassfulqdisctodetermineinwhich
classapacketwillbeenqueued.Whenevertrafficarrives
ataclasswithsubclasses,itneedstobeclassified.
Variousmethodsmaybeemployedtodoso,oneoftheseare
thefilters.Allfiltersattachedtotheclassarecalled,
untiloneofthemreturnswithaverdict.Ifnoverdict
wasmade,othercriteriamaybeavailable.Thisdiffers
perqdisc.
Itisimportanttonoticethatfiltersresidewithin
qdiscstheyarenotmastersofwhathappens.
CLASSLESSQDISCS
Theclasslessqdiscsare:
[p|b]fifo
Simplestusableqdisc,pureFirstIn,FirstOut
behaviour.Limitedinpacketsorinbytes.
pfifo_fast
Standardqdiscfor'AdvancedRouter'enabledker
nels.Consistsofathreebandqueuewhichhonors
TypeofServiceflags,aswellastheprioritythat
maybeassignedtoapacket.
redRandomEarlyDetectionsimulatesphysicalconges
tionbyrandomlydroppingpacketswhennearingcon
figuredbandwidthallocation.Wellsuitedtovery
largebandwidthapplications.
sfqStochasticFairnessQueueingreordersqueuedtraf
ficsoeach'session'getstosendapacketin
turn.

31

LiLuxasbl

LinuxDays2008

tbfTheTokenBucketFilterissuitedforslowingtraf
ficdowntoapreciselyconfiguredrate.Scales
welltolargebandwidths.
CONFIGURINGCLASSLESSQDISCS
Intheabsenceofclassfulqdiscs,classlessqdiscscan
onlybeattachedattherootofadevice.Fullsyntax:
tcqdiscadddevDEVrootQDISCQDISCPARAMETERS
Toremove,issue
tcqdiscdeldevDEVroot
Thepfifo_fastqdiscistheautomaticdefaultinthe
absenceofaconfiguredqdisc.
CLASSFULQDISCS
Theclassfulqdiscsare:
CBQClassBasedQueueingimplementsarichlinksharing
hierarchyofclasses.Itcontainsshapingelements
aswellasprioritizingcapabilities.Shapingis
performedusinglinkidletimecalculationsbased
onaveragepacketsizeandunderlyinglinkband
width.Thelattermaybeilldefinedforsome
interfaces.
HTBTheHierarchyTokenBucketimplementsarich
linksharinghierarchyofclasseswithanemphasis
onconformingtoexistingpractices.HTBfacili
tatesguaranteeingbandwidthtoclasses,whilealso
allowingspecificationofupperlimitstointer
classsharing.Itcontainsshapingelements,based
onTBFandcanprioritizeclasses.
PRIOThePRIOqdiscisanonshapingcontainerfora
configurablenumberofclasseswhicharedequeued
inorder.Thisallowsforeasyprioritizationof
traffic,wherelowerclassesareonlyabletosend
ifhigheroneshavenopacketsavailable.Tofacil
itateconfiguration,TypeOfServicebitsarehon
oredbydefault.
THEORYOFOPERATION
Classesformatree,whereeachclasshasasingleparent.
Aclassmayhavemultiplechildren.Someqdiscsallowfor
runtimeadditionofclasses(CBQ,HTB)whileothers(PRIO)
arecreatedwithastaticnumberofchildren.
Qdiscswhichallowdynamicadditionofclassescanhave
zeroormoresubclassestowhichtrafficmaybeenqueued.
Furthermore,eachclasscontainsaleafqdiscwhichby
defaulthaspfifobehaviourthoughanotherqdisccanbe
attachedinplace.Thisqdiscmayagaincontainclasses,
buteachclasscanhaveonlyoneleafqdisc.
Whenapacketentersaclassfulqdiscitcanbeclassified
tooneoftheclasseswithin.Threecriteriaareavail
able,althoughnotallqdiscswilluseallthree:
tcfilters
Iftcfiltersareattachedtoaclass,theyare

32

LiLuxasbl

LinuxDays2008

consultedfirstforrelevantinstructions.Filters
canmatchonallfieldsofapacketheader,aswell
asonthefirewallmarkappliedbyipchainsoript
ables.Seetcfilters(8).
TypeofService
Someqdiscshavebuiltinrulesforclassifying
packetsbasedontheTOSfield.
skb>priority
Userspaceprogramscanencodeaclassidinthe
'skb>priority'fieldusingtheSO_PRIORITYoption.
Eachnodewithinthetreecanhaveitsownfiltersbut
higherlevelfiltersmayalsopointdirectlytolower
classes.
Ifclassificationdidnotsucceed,packetsareenqueuedto
theleafqdiscattachedtothatclass.Checkqdiscspe
cificmanpagesfordetails,however.
NAMING
Allqdiscs,classesandfiltershaveIDs,whichcaneither
bespecifiedorbeautomaticallyassigned.
IDsconsistofamajornumberandaminornumber,sepa
ratedbyacolon.
QDISCSAqdisc,whichpotentiallycanhavechildren,gets
assignedamajornumber,calleda'handle',leaving
theminornumbernamespaceavailableforclasses.
Thehandleisexpressedas'10:'.Itiscustomary
toexplicitlyassignahandletoqdiscsexpectedto
havechildren.
CLASSES
Classesresidingunderaqdiscsharetheirqdisc
majornumber,buteachhaveaseparateminornumber
calleda'classid'thathasnorelationtotheir
parentclasses,onlytotheirparentqdisc.The
samenamingcustomasforqdiscsapplies.
FILTERS
FiltershaveathreepartID,whichisonlyneeded
whenusingahashedfilterhierarchy,forwhichsee
tcfilters(8).
UNITS
Allparametersacceptafloatingpointnumber,possibly
followedbyaunit.
Bandwidthsorratescanbespecifiedin:
kbpsKilobytespersecond
mbpsMegabytespersecond
kbitKilobitspersecond
mbitMegabitspersecond
bpsorabarenumber

33

LiLuxasbl

LinuxDays2008

Bytespersecond
Amountsofdatacanbespecifiedin:
kbork
Kilobytes
mborm
Megabytes
mbitMegabits
kbitKilobits
borabarenumber
Bytes.
Lengthsoftimecanbespecifiedin:
s,secorsecs
Wholeseconds
ms,msecormsecs
Milliseconds
us,usec,usecsorabarenumber
Microseconds.
TCCOMMANDS
Thefollowingcommandsareavailableforqdiscs,classes
andfilter:
addAddaqdisc,classorfiltertoanode.Forall
entities,aparentmustbepassed,eitherbypass
ingitsIDorbyattachingdirectlytotherootof
adevice.Whencreatingaqdiscorafilter,it
canbenamedwiththehandleparameter.Aclassis
namedwiththeclassidparameter.
removeAqdisccanberemovedbyspecifyingitshandle,
whichmayalsobe'root'.Allsubclassesandtheir
leafqdiscsareautomaticallydeleted,aswellas
anyfiltersattachedtothem.
changeSomeentitiescanbemodified'inplace'.Shares
thesyntaxof'add',withtheexceptionthatthe
handlecannotbechangedandneithercanthepar
ent.Inotherwords,changecannotmoveanode.
replace
Performsanearlyatomicremove/addonanexisting
nodeid.Ifthenodedoesnotexistyetitiscre
ated.
linkOnlyavailableforqdiscsandperformsareplace
wherethenodemustexistalready.

HISTORY
tcwaswrittenbyAlexeyN.KuznetsovandaddedinLinux

34

LiLuxasbl

LinuxDays2008

2.2.
SEEALSO
tccbq(8),tchtb(8),tcsfq(8),tcred(8),tctbf(8),tc
pfifo(8),tcbfifo(8),tcpfifo_fast(8),tcfilters(8)
AUTHOR
Manpagemaintainedbyberthubert(ahu@ds9a.nl)

iproute216December2001TC(8)

35

LiLuxasbl

LinuxDays2008

6 AppendixC:Afirewallsample.
Configfile(/etc/firewall.cfg:
#!/bin/bash
#SomeFWrulesforthismachine
#Therealcommands
IPT=/sbin/iptables
IPR=/sbin/ip
#Totestthescript
#IPT="echo/sbin/iptables"
#IPR="echo/sbin/ip"
sf=1
#Startfiltering
sn=1
#Startnat
WRITE_LOG=1#Writetosyslog
#InformationaboutInternetconnection:
INTER="200.1.1.0/29"
IP_INTER="200.1.1.2"
IF_INTER=eth0
#InformationaboutIntranet:
INTRA="192.168.1.0/24"
IP_INTRA="192.168.1.1"
IF_INTRA=eth2
#InformationaboutWLAN:
WLAN="192.169.1.0/24"
IP_WLAN="192.169.1.1"
IF_WLAN=eth1
#Proxyserverwemayuse
PROXY_PORT="3128"
PROXY_IP="158.2.2.3"
PROXY="$PROXY_IP:$PROXY_PORT"
#Shortcuts:
LOCALNET="$INTRA$WLAN$PPPC$VMLAN"
#Insideservers
ISRV="MUROSCHERECK"
#Rulesforthoseservers
MUROS_IP="200.1.1.3"
MUROS_TCPSERVICES="sshhttpsftp"
MUROS_FROMINTER="rsync"
CHERECK_IP="200.1.1.4"
CHERECK_TCPSERVICES="ssh"
CHERECK_FROMINTER="rsync"
#TCPandUDPserviceswerunandwanttobeaccessiblefromoutside
TCPSERVICES="ftpftpdatasshsftptelnetdomain
smtpsmtpspop3pop3simapimap3imaps
httphttpsauthsubmissionrsync3128
4000:41009696"
UDPSERVICES="domainntp46628221"
#Portsweallowtobeforwardedfromtheinternettootherservers
TCPFORWARD="ftpftpdatasshpop3imapimap3httpspgpkeyserver$PROXY_PORT"
#Serviceslocalusersmaydo
TCPOUT="ftpftpdatasshsftptelnetdomain
smtpsmtpspop3pop3simapimap3imaps
httphttpsauthsubmissionrsync
x11x11sshoffset
submissionsunrpccvspserver
6666$PROXY_PORT"
UDPOUT="domainntpsnmp"
#ShouldaccesstotheIntranetbeallowedfromtheserver
ALLOW_ACCESS_TO_LOCAL=0

36

LiLuxasbl

LinuxDays2008

#Shouldicmpbeallowedtogoout
ALLOW_ICMP_OUT=1
#MyIPaddressatwork
TCATWORK=212.1.1.2

Theactualscript(/usr/local/sbin/firewall):
#!/bin/bash
#SomeFWrulesforthismachine
#Loadconfiguration
./etc/sendar.fw.cfg
start(){
if[$sfeq1];then
start_filters
fi
if[$sneq1];then
start_nat
fi
}
##############
#NAT#
##############
start_nat(){
modprobeip_conntrack
modprobeip_conntrack_ftp
#Flushalltherules
$IPTtnatFPREROUTING
$IPTtnatFPOSTROUTING
#ReroutetelnettoMUD
$IPTtnatIPREROUTINGptcpdestinationport23jREDIRECTtoports4000
#Redirectallinsidetrafficthroughaproxy
$IPTtnatIPREROUTINGs$INTRAd!$MYNETptcpdport80jDNATto
destination$PROXY
#Masqueradewhengoingout
forSRCin$LOCALNET;do
$IPTtnatAPOSTROUTINGs$SRCd!$IP_INTERjMASQUERADE
done
}
##############
#Filers#
##############
start_filters(){
#Flushalltherules
$IPTFINPUT
$IPTFFORWARD
$IPTFOUTPUT
#Policydenyall
$IPTPFORWARDDROP
$IPTPINPUTDROP
$IPTPOUTPUTDROP
#INPUT
#AcceptmetodoallIwantfromwork
$IPTAINPUTs$TCATWORKjACCEPT
#Synfloodprotection:
$IPTAINPUTptcpsynmlimitlimit140/sjACCEPT

37

LiLuxasbl

LinuxDays2008

#Furtiveportscanner:
$IPTAINPUTptcptcpflagsSYN,ACK,FIN,RSTRSTmlimitlimit150/sj
ACCEPT
#Pingofdeath:
$IPTAINPUTpicmpmlimitlimit5/sjACCEPT
#Allowtotalktomyself
$IPTAINPUTs127.0.0.1d127.0.0.1jACCEPT
$IPTAINPUTs$IP_INTERd$IP_INTERjACCEPT
$IPTAINPUTs$IP_INTRAd$IP_INTRAjACCEPT
#Localservices
forPORTin$TCPSERVICES;do
$IPTAINPUTptcpdestinationport$PORT jACCEPT
done
forPORTin$UDPSERVICES;do
$IPTAINPUTpudpdestinationport$PORT jACCEPT
done

#tcp
#udp

#Allowmetousemyownserverfromhome
$IPTAINPUTi$IF_INTRAs$INTRAjACCEPT
#AllowdhcpfromintranetandWLAN
$IPTAINPUTi$IF_INTRApudpdestinationport67:68jACCEPT
$IPTAINPUTi$IF_WLANpudpdestinationport67:68jACCEPT
#Allowrelatedandestablishedtraffic
$IPTAINPUTmstatestateESTABLISHED,RELATEDjACCEPT
#Addsomelogging:
if[$WRITE_LOGeq1];then
$IPTAINPUTpudpdestinationport137jDROP#Smallerlogs
$IPTAINPUTptcpdestinationport137jDROP#Smallerlogs
$IPTAINPUTptcpdestinationport138jDROP#Smallerlogs
$IPTAINPUTptcpdestinationport139jDROP#Smallerlogs
$IPTAINPUTjLOGloglevelnoticelogprefix"IPTINPUT"
fi
#logtcpsequencelogtcpoptionslogipoptions
#OUTPUT
#Hereiswhatneedstogoout
$IPTAOUTPUTs127.0.0.1d127.0.0.1jACCEPT
$IPTAOUTPUTs$IP_INTERd$IP_INTERjACCEPT
if[$ALLOW_ACCESS_TO_LOCALeq1];then
forSRCin$LOCALNET;do
$IPTAOUTPUTd$INTRAjACCEPT
done
fi

#alllocal

#Onlyallowifnecessary

#allowmetodowhatIwant
$IPTAOUTPUTmowneruidowner500jACCEPT
#Addratelimitedicmpout
if[$ALLOW_ICMP_OUTeq1];then
$IPTAOUTPUTpicmpmlimitlimit3/sjACCEPT
fi
#Allowuserstodosomestuff
forPORTin$TCPOUT;do
$IPTAOUTPUTptcpdestinationport$PORT
done
forPORTin$UDPOUT;do

38

LiLuxasbl

jACCEPT

#tcp

LinuxDays2008

$IPTAOUTPUTpudpdestinationport$PORT
jACCEPT
#udp
$IPTAOUTPUTpudpsourceport$PORT
jACCEPT
#udp
done
#Protectotherserversfromourself
$IPTAOUTPUTo$IF_INTERs!$INTERjDROP
$IPTAOUTPUTmstatestateESTABLISHED,RELATEDjACCEPT
#Logwhatshouldnotgetout
if[$WRITE_LOGeq1];then
$IPTAOUTPUTpudpdestinationport137jDROP#Smallerlogs
$IPTAOUTPUTptcpdestinationport137jDROP#Smallerlogs
$IPTAOUTPUTptcpdestinationport138jDROP#Smallerlogs
$IPTAOUTPUTptcpdestinationport139jDROP#Smallerlogs
$IPTAOUTPUTjLOGloglevelnoticelogprefix"IPTOUTPUT"#
logtcpsequence
fi
#FORWARD
#Allowalltrafficfromtheinside
$IPTAFORWARDi$IF_INTRAs$INTRAjACCEPT
#Synfloodprotection:
$IPTAFORWARDptcpsynmlimitlimit140/sjACCEPT
#Furtiveportscanner:
$IPTAFORWARDptcptcpflagsSYN,ACK,FIN,RSTRSTmlimitlimit150/sj
ACCEPT
#Pingofdeath:
$IPTAFORWARDpicmpmlimitlimit3/sjACCEPT
#WLANandotherlocalserverswithpublicIPhavenomorerightsthanlocalusers
forPORTin$TCPOUT;do
$IPTAFORWARDi$IF_WLANs$WLANd!$INTRAptcpdestinationport
$PORTjACCEPT
$IPTAFORWARDs$INTERd!$INTRAptcpdestinationport$PORT
j
ACCEPT
$IPTAFORWARDs$PPPCd!$INTRAptcpdestinationport$PORT
j
ACCEPT
done
forPORTin$UDPOUT;do
$IPTAFORWARDi$IF_WLANs$WLANd!$INTRApudpdestinationport
$PORTjACCEPT
$IPTAFORWARDs$INTERd!$INTRApudpdestinationport$PORT
j
ACCEPT
$IPTAFORWARDs$PPPCd!$INTRApudpdestinationport$PORT
j
ACCEPT
done
#DonotallowIPspoofingfromWLAN
$IPTAFORWARDi$IF_WLANs!$WLANjLOGloglevelnoticelogprefix
"WLANIPSpoofing"
$IPTAFORWARDi$IF_WLANs!$WLANjDROP
#nowallowotherservicestoworkforinsideservers
forSRVin$ISRV;do
IP=`evalecho'$'${SRV}_IP`
SERVICES=`evalecho'$'${SRV}_TCPSERVICES`
FROMINTER=`evalecho'$'${SRV}_FROMINTER`
forPORTin$SERVICES;do
$IPTAFORWARDd$IPptcpdestinationport$PORTjACCEPT
done

39

LiLuxasbl

LinuxDays2008

forPORTin$FROMINTER;do
$IPTAFORWARDs$INTERd$IPptcpdestinationport$PORTj
ACCEPT
done
done
$IPTAFORWARDmstatestateESTABLISHED,RELATEDjACCEPT
#Logwhatshouldnotgetthrough
if[$WRITE_LOGeq1];then
$IPTAFORWARDpudpdestinationport137jDROP#Smallerlogs
$IPTAFORWARDptcpdestinationport137jDROP#Smallerlogs
$IPTAFORWARDptcpdestinationport138jDROP#Smallerlogs
$IPTAFORWARDptcpdestinationport139jDROP#Smallerlogs
$IPTAFORWARDjLOGloglevelnoticelogprefix"IPTFORWARD"
fi
#Allowforwardingnow
echo1>/proc/sys/net/ipv4/ip_forward
#ForwardotherpublicIP'stocorrectserver
echo1>/proc/sys/net/ipv4/conf/all/proxy_arp
#Weneedtoroutetotheinternalservers
forIPin$OTHER_SERVERS;do
$IPRrouteadd$IPdev$IF_INTRA
done
}
stop(){
$IPTPINPUTACCEPT
$IPTPOUTPUTACCEPT
$IPTPFORWARDACCEPT
$IPTFINPUT
$IPTFFORWARD
$IPTFOUTPUT
#Removenattoo
$IPTtnatFPREROUTING
$IPTtnatFPOSTROUTING
$IPTtnatFOUTPUT
#allowipforwarding
echo1>/proc/sys/net/ipv4/ip_forward
}
case"$1"in
start)
start
;;
stop)
stop
;;
status)
$IPTLn
$IPTLntnat
;;
restart)
stop
start
;;
*)
echo$"Usage:$0{start|stop|restart|status}"

40

LiLuxasbl

LinuxDays2008

exit1
esac
exit$RETVAL

41

LiLuxasbl

LinuxDays2008