You are on page 1of 9

IPTables HowTo - Community Ubuntu Documentation

https://help.ubuntu.com/community/IptablesHowTo

LogintoEdit
UbuntuDocumentation>CommunityDocumentation>IptablesHowTo

IptablesHowTo
Basiciptableshowto

Iptablesisafirewall,installedbydefaultonallofficialUbuntudistributions
(Ubuntu,Kubuntu,Xubuntu).WhenyouinstallUbuntu,iptablesisthere,
butitallowsalltrafficbydefault.Ubuntu8.04Comeswithufw-aprogram
formanagingtheiptablesfirewalleasily.
Thereisawealthofinformationavailableaboutiptables,butmuchofitis
fairlycomplex,andifyouwanttodoafewbasicthings,thisHowToisfor
you.

Sommaire
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

BasicCommands
Typing
#iptables-L

11.
12.

listsyourcurrentrulesiniptables.Ifyouhavejustsetupyourserver,you
willhavenorules,andyoushouldsee
ChainINPUT(policyACCEPT)
targetprotoptsourcedestination
ChainFORWARD(policyACCEPT)
targetprotoptsourcedestination

13.
14.
15.

Basiciptableshowto
BasicCommands
BasicIptablesOptions
AllowingEstablishedSessions
AllowingIncomingTrafficonSpecificPorts
BlockingTraffic
Editingiptables
Logging
Savingiptables
Configurationonstartup
1. Solution#1-/etc/network/interfaces
2. Solution#2/etc/network/if-pre-up.dand
../if-post-down.d
ConfigurationonStartupforNetworkManager
Tips
1. Ifyoumanuallyeditiptablesona
regularbasis
2. Usingiptables-save/restoretotestrules
3. MoredetailedLogging
4. Disablingthefirewall
EasyconfigurationviaGUI
FurtherInformation
Credits

ChainOUTPUT(policyACCEPT)
targetprotoptsourcedestination

BasicIptablesOptions
Hereareexplanationsforsomeoftheiptablesoptionsyouwillseeinthistutorial.Don'tworryaboutunderstandingeverything
herenow,butremembertocomebackandlookatthislistasyouencounternewoptionslateron.
-A-Appendthisruletoarulechain.Validchainsforwhatwe'redoingareINPUT,FORWARDandOUTPUT,butwe
mostlydealwithINPUTinthistutorial,whichaffectsonlyincomingtraffic.
-L-Listthecurrentfilterrules.
-m conntrack-Allowfilterrulestomatchbasedonconnectionstate.Permitstheuseofthe--ctstateoption.
--ctstate-Definethelistofstatesfortheruletomatchon.Validstatesare:
NEW-Theconnectionhasnotyetbeenseen.
RELATED-Theconnectionisnew,butisrelatedtoanotherconnectionalreadypermitted.
ESTABLISHED-Theconnectionisalreadyestablished.
INVALID-Thetrafficcouldn'tbeidentifiedforsomereason.
-m limit-Requiretheruletomatchonlyalimitednumberoftimes.Allowstheuseofthe--limitoption.Usefulfor
limitingloggingrules.
--limit-Themaximummatchingrate,givenasanumberfollowedby"/second","/minute","/hour",or"/day"
dependingonhowoftenyouwanttheruletomatch.Ifthisoptionisnotusedand-m limitisused,thedefaultis
"3/hour".
-p-Theconnectionprotocolused.

1 sur 9

19/11/2010 17:30

IPTables HowTo - Community Ubuntu Documentation

https://help.ubuntu.com/community/IptablesHowTo

--dport-Thedestinationport(s)requiredforthisrule.Asingleportmaybegiven,orarangemaybegivenas
start:end,whichwillmatchallportsfromstarttoend,inclusive.
-j-Jumptothespecifiedtarget.Bydefault,iptablesallowsfourtargets:
ACCEPT-Acceptthepacketandstopprocessingrulesinthischain.
REJECT-Rejectthepacketandnotifythesenderthatwedidso,andstopprocessingrulesinthischain.
DROP-Silentlyignorethepacket,andstopprocessingrulesinthischain.
LOG-Logthepacket,andcontinueprocessingmorerulesinthischain.Allowstheuseofthe--log-prefixand
--log-leveloptions.
--log-prefix-Whenlogging,putthistextbeforethelogmessage.Usedoublequotesaroundthetexttouse.
--log-level-Logusingthespecifiedsysloglevel.7isagoodchoiceunlessyouspecificallyneedsomethingelse.
-i-Onlymatchifthepacketiscominginonthespecifiedinterface.
-I-Insertsarule.Takestwooptions,thechaintoinserttheruleinto,andtherulenumberitshouldbe.
th
-I INPUT 5wouldinserttheruleintotheINPUTchainandmakeitthe5 ruleinthelist.

-v-Displaymoreinformationintheoutput.Usefulforifyouhaverulesthatlooksimilarwithoutusing-v.
-s--source-address[/mask]sourcespecification
-d--destination-address[/mask]destinationspecification
-o--out-interface-outputname[+]networkinterfacename([+]forwildcard)

AllowingEstablishedSessions
Wecanallowestablishedsessionstoreceivetraffic:
#iptables-AINPUT-mconntrack--ctstateESTABLISHED,RELATED-jACCEPT

TheaboverulehasnospaceseithersideofthecommainESTABLISHED,RELATED
Ifthelineabovedoesn'twork,youmaybeonaVPSthatusesOpenVZordoesn'thavesomekernelextensionsinstalled.Inthat
case,trythislineinstead:
#iptables-AINPUT-mstate--stateESTABLISHED,RELATED-jACCEPT

AllowingIncomingTrafficonSpecificPorts
Youcouldstartbyblockingtraffic,butyoumightbeworkingoverSSH,whereyouwouldneedtoallowSSHbeforeblocking
everythingelse.
ToallowincomingtrafficonthedefaultSSHport(22),youcouldtelliptablestoallowallTCPtrafficonthatporttocomein.
#iptables-AINPUT-ptcp--dportssh-jACCEPT

Referringbacktothelistabove,youcanseethatthistellsiptables:
appendthisruletotheinputchain(-AINPUT)sowelookatincomingtraffic
checktoseeifitisTCP(-ptcp).
ifso,checktoseeiftheinputgoestotheSSHport(--dportssh).
ifso,accepttheinput(-jACCEPT).
Letschecktherules:(onlythefirstfewlinesshown,youwillseemore)
#iptables-L
ChainINPUT(policyACCEPT)
targetprotoptsourcedestination
ACCEPTall--anywhereanywherestateRELATED,ESTABLISHED
ACCEPTtcp--anywhereanywheretcpdpt:ssh

Now,let'sallowallincomingwebtraffic

2 sur 9

19/11/2010 17:30

IPTables HowTo - Community Ubuntu Documentation

https://help.ubuntu.com/community/IptablesHowTo

#iptables-AINPUT-ptcp--dport80-jACCEPT

Checkingourrules,wehave
#iptables-L
ChainINPUT(policyACCEPT)
targetprotoptsourcedestination
ACCEPTall--anywhereanywherestateRELATED,ESTABLISHED
ACCEPTtcp--anywhereanywheretcpdpt:ssh
ACCEPTtcp--anywhereanywheretcpdpt:www

Wehavespecificallyallowedtcptraffictothesshandwebports,butaswehavenotblockedanything,alltrafficcanstillcomein.

BlockingTraffic
Onceadecisionismadetoacceptapacket,nomorerulesaffectit.Asourrulesallowingsshandwebtrafficcomefirst,aslongas
ourruletoblockalltrafficcomesafterthem,wecanstillacceptthetrafficwewant.Allweneedtodoisputtheruletoblockall
trafficattheend.
#iptables-AINPUT-jDROP
#iptables-L
ChainINPUT(policyACCEPT)
targetprotoptsourcedestination
ACCEPTall--anywhereanywherestateRELATED,ESTABLISHED
ACCEPTtcp--anywhereanywheretcpdpt:ssh
ACCEPTtcp--anywhereanywheretcpdpt:www
DROPall--anywhereanywhere

Becausewedidn'tspecifyaninterfaceoraprotocol,anytrafficforanyportonanyinterfaceisblocked,exceptforwebandssh.

Editingiptables
Theonlyproblemwithoursetupsofaristhateventheloopbackportisblocked.Wecouldhavewrittenthedropruleforjusteth0
byspecifying-ieth0,butwecouldalsoaddarulefortheloopback.Ifweappendthisrule,itwillcometoolate-afterallthetraffic
hasbeendropped.Weneedtoinsertthisrulebeforethat.Sincethisisalotoftraffic,we'llinsertitasthefirstrulesoit'sprocessed
first.
#iptables-IINPUT1-ilo-jACCEPT
#iptables-L
ChainINPUT(policyACCEPT)
targetprotoptsourcedestination
ACCEPTall--anywhereanywhere
ACCEPTall--anywhereanywherestateRELATED,ESTABLISHED
ACCEPTtcp--anywhereanywheretcpdpt:ssh
ACCEPTtcp--anywhereanywheretcpdpt:www
DROPall--anywhereanywhere

Thefirstandlastlineslooknearlythesame,sowewilllistiptablesingreaterdetail.
#iptables-L-v
ChainINPUT(policyACCEPT0packets,0bytes)
pktsbytestargetprotoptinoutsourcedestination
00ACCEPTall--loanyanywhereanywhere
00ACCEPTall--anyanyanywhereanywherestate
RELATED,ESTABLISHED
00ACCEPTtcp--anyanyanywhereanywheretcpdpt:ssh
00ACCEPTtcp--anyanyanywhereanywheretcpdpt:www
00DROPall--anyanyanywhereanywhere

Youcannowseealotmoreinformation.Thisruleisactuallyveryimportant,sincemanyprogramsusetheloopbackinterfaceto
communicatewitheachother.Ifyoudon'tallowthemtotalk,youcouldbreakthoseprograms!

Logging

3 sur 9

19/11/2010 17:30

IPTables HowTo - Community Ubuntu Documentation

https://help.ubuntu.com/community/IptablesHowTo

Intheaboveexamplesnoneofthetrafficwillbelogged.Ifyouwouldliketologdroppedpacketstosyslog,thiswouldbethe
quickestway:
#iptables-IINPUT5-mlimit--limit5/min-jLOG--log-prefix"iptablesdenied:"--log-level7

SeeTipssectionformoreideasonlogging.

Savingiptables
Ifyouweretorebootyourmachinerightnow,youriptablesconfigurationwoulddisappear.Ratherthantypethiseachtimeyou
reboot,however,youcansavetheconfiguration,andhaveitstartupautomatically.Tosavetheconfiguration,youcanuse
iptables-saveandiptables-restore.

Configurationonstartup
WARNING:IptablesandUbuntu:NetworkManagerseemtohaveaconflict.HoweverNetworkManagerisstillinBeta.Ifyouare
concernedenoughaboutsecuritytoinstallafirewallyoumightnotwanttotrustNetworkManagertomanageityet.Alsonote
NetworkManagerandiptableshaveoppositeaims.Iptablesaimstokeepanyquestionablenetworktrafficout.NetworkManager
aimstokeepyouconnectedatalltimes.Thereforeifyouwantsecurityallthetime,runiptablesatboottime.Ifyouwantsecurity
someofthetimethenNetworkManagermightbetherightchoice.
WARNING:IfyouuseUbuntu:NetworkManager(installedbydefaultonFeistyandlater)thesestepswillleaveyouunabletouse
Ubuntu:NetworkManagerfortheinterfacesyoumodify.Pleasefollowthestepsinthenextsectioninstead.
NOTE:ItappearsonHardy,Ubuntu:NetworkManagerhasanissuewithproperlyonsavingandrestoringtheiptableruleswhen
usingthemethodinthenextsection.Usingthisfirstmethodappearstowork.Ifyoufindotherwise,pleaseupdatethisnote.
Saveyourfirewallrulestoafile
#sudobash-c"iptables-save>/etc/iptables.rules"

Atthispointyouhaveseveraloptions.Youcanmakechangesto/etc/network/interfacesoraddscriptsto
/etc/network/if-pre-up.d/and/etc/network/if-post-down.d/toachievesimilarends.Thescriptsolution
allowsforslightlymoreflexibility.

Solution#1-/etc/network/interfaces
(NB:Ifollowedthedirectionsinthissectionandthisdisabledmost(all?)ofmyscriptsin/etc/rc2.d/:polipo,dnsmasq,bluetooth,
etc.Irecommendusingufw/gufwinstead.~gasull)
Modifythe/etc/network/interfacesconfigurationfiletoapplytherulesautomatically.Youwillneedtoknowthe
interfacethatyouareusinginordertoapplytherules-ifyoudonotknow,youareprobablyusingtheinterfaceeth0,althoughyou
shouldcheckwiththefollowingcommandfirsttoseeifthereareanywirelesscards:
$iwconfig

Ifyougetoutputsimilartothefollowing,thenyoudonothaveanywirelesscardsatallandyourbestbetisprobablyeth0.
$iwconfig
lonowirelessextensions.
eth0nowirelessextensions.
$

Whenyouhavefoundouttheinterfaceyouareusing,pleaseopenyour/etc/network/interfacesfiledependingonwhat
editoryouwantand/orwhatdistributionyouhave:
Commandline:

4 sur 9

19/11/2010 17:30

IPTables HowTo - Community Ubuntu Documentation

https://help.ubuntu.com/community/IptablesHowTo

#nano/etc/network/interfaces

ForUbuntuandXubuntu:typeALT+F2,theninthewindowthatpopsup,type:
gksudogedit/etc/network/interfaces

andpressEnter.
ForKubuntu:typeALT+F2,theninthewindowthatpopsup,type:
kdesukate/etc/network/interfaces

andpressenter.
Wheninthefile,searchfortheinterfaceyoufound,andattheendofthenetworkrelatedlinesforthatinterface,addtheline:
pre-upiptables-restore</etc/iptables.rules

Youcanalsoprepareasetofdownrules,savethemintosecondfile/etc/iptables.downrulesandapplyitautomatically
usingtheabovesteps:
post-downiptables-restore</etc/iptables.downrules

Afullyworkingexampleusingbothfromabove:
autoeth0
ifaceeth0inetdhcp
pre-upiptables-restore</etc/iptables.rules
post-downiptables-restore</etc/iptables.downrules

Youmayalsowanttokeepinformationfrombyteandpacketcounters.
iptables-save-c>/etc/iptables.rules

Theabovecommandwillsavethewholerule-settoafilecalled/etc/iptables.ruleswithbyteandpacketcountersstill
intact.

Solution#2/etc/network/if-pre-up.dand../if-post-down.d
NOTE:Thissolutionusesiptables-save -ctosavethecounters.Justremovethe-ctoonlysavetherules.
Alternativelyyoucouldaddtheiptables-restoreandiptables-savetotheif-pre-up.dandif-post-down.d
directoriesinthe/etc/networkdirectoryinsteadofmodifying/etc/network/interfacedirectly.
Thescript/etc/network/if-pre-up.d/iptablesloadwillcontain:
#!/bin/sh
iptables-restore</etc/iptables.rules
exit0

and/etc/network/if-post-down.d/iptablessavewillcontain:
#!/bin/sh
iptables-save-c>/etc/iptables.rules
if[-f/etc/iptables.downrules];then
iptables-restore</etc/iptables.downrules
fi
exit0

Thenbesuretogivebothscriptsexecutepermissions:
#chmod+x/etc/network/if-post-down.d/iptablessave

5 sur 9

19/11/2010 17:30

IPTables HowTo - Community Ubuntu Documentation

https://help.ubuntu.com/community/IptablesHowTo

#chmod+x/etc/network/if-pre-up.d/iptablesload

ConfigurationonStartupforNetworkManager
Ubuntu:NetworkManagerincludestheabilitytorunscriptswhenitactivatesordeactivatesaninterface.Tosaveiptablesruleson
shutdown,andtorestorethemonstartup,wearegoingtocreatesuchascript.Tobegin,pressAlt+F2andenterthiscommand:
ForUbuntu:
$gksudogedit/etc/NetworkManager/dispatcher.d/01firewall

ForKubuntu:
kdesukate/etc/NetworkManager/dispatcher.d/01firewall

Then,pastethisscriptintoyoureditor,save,andexittheeditor.
if[-x/usr/bin/logger];then
LOGGER="/usr/bin/logger-s-pdaemon.info-tFirewallHandler"
else
LOGGER=echo
fi
case"$2"in
up)
if[!-r/etc/iptables.rules];then
${LOGGER}"Noiptablesrulesexisttorestore."
return
fi
if[!-x/sbin/iptables-restore];then
${LOGGER}"Noprogramexiststorestoreiptablesrules."
return
fi
${LOGGER}"Restoringiptablesrules"
/sbin/iptables-restore-c</etc/iptables.rules
;;
down)
if[!-x/sbin/iptables-save];then
${LOGGER}"Noprogramexiststosaveiptablesrules."
return
fi
${LOGGER}"Savingiptablesrules."
/sbin/iptables-save-c>/etc/iptables.rules
;;
*)
;;
esac

Finally,weneedtomakesureUbuntu:NetworkManagercanexecutethisscript.Inaterminalwindow,enterthiscommand:
#chmod+x/etc/NetworkManager/dispatcher.d/01firewall

Tips
Ifyoumanuallyeditiptablesonaregularbasis
Theabovestepsgooverhowtosetupyourfirewallrulesandpresumetheywillberelativelystatic(andformostpeoplethey
shouldbe).Butifyoudoalotofdevelopmentwork,youmaywanttohaveyouriptablessavedeverytimeyoureboot.Youcould
addalinelikethisonein/etc/network/interfaces:
pre-upiptables-restore</etc/iptables.rules
post-downiptables-save>/etc/iptables.rules

Theline"post-downiptables-save>/etc/iptables.rules"willsavetherulestobeusedonthenextboot.

Usingiptables-save/restoretotestrules

6 sur 9

19/11/2010 17:30

IPTables HowTo - Community Ubuntu Documentation

https://help.ubuntu.com/community/IptablesHowTo

Ifyouedityouriptablesbeyondthistutorial,youmaywanttousetheiptables-saveandiptables-restorefeatureto
editandtestyourrules.Todothisopentherulesfileinyourfavoritetexteditor(inthisexamplegedit).
$sudoiptables-save>/etc/iptables.rules
$gksudogedit/etc/iptables.rules

Youwillhaveafilethatappearssimiliarto(followingtheexampleabove):
#Generatedbyiptables-savev1.3.1onSunApr2306:19:532006
*filter
:INPUTACCEPT[368:102354]
:FORWARDACCEPT[0:0]
:OUTPUTACCEPT[92952:20764374]
-AINPUT-ilo-jACCEPT
-AINPUT-mconntrack--ctstateRELATED,ESTABLISHED-jACCEPT
-AINPUT-ieth0-ptcp-mtcp--dport22-jACCEPT
-AINPUT-ieth0-ptcp-mtcp--dport80-jACCEPT
-AINPUT-mlimit--limit5/min-jLOG--log-prefix"iptablesdenied:"--log-level7
-AINPUT-jDROP
COMMIT
#CompletedonSunApr2306:19:532006

Noticethattheseareiptablescommandsminustheiptablecommand.Feelfreetoeditthistofileandsavewhencomplete.Then
totestsimply:
#iptables-restore</etc/iptables.rules

NOTE:Withiptables1.4.1.1-1andabove,ascriptallowyoutotestyournewruleswithoutriskingtobrickyourremoteserver.If
youareapplyingtherulesonaremoteserver,youshouldconsidertestingitwith:
#iptables-apply/etc/iptables.rules

Aftertesting,ifyouhavenotaddedtheiptables-savecommandabovetoyour/etc/network/interfacesremember
nottoloseyourchanges:
#iptables-save>/etc/iptables.rules

MoredetailedLogging
ForfurtherdetailinyoursyslogyoumaywantcreateanadditionalChain.Thiswillbeaverybriefexampleofmy
/etc/iptables.rulesshowinghowIsetupmyiptablestologtosyslog:
#Generatedbyiptables-savev1.3.1onSunApr2305:32:092006
*filter
:INPUTACCEPT[273:55355]
:FORWARDACCEPT[0:0]
:LOGNDROP-[0:0]
:OUTPUTACCEPT[92376:20668252]
-AINPUT-mconntrack--ctstateRELATED,ESTABLISHED-jACCEPT
-AINPUT-ieth0-ptcp-mtcp--dport22-jACCEPT
-AINPUT-ieth0-ptcp-mtcp--dport80-jACCEPT
-AINPUT-ilo-jACCEPT
-AINPUT-jLOGNDROP
-ALOGNDROP-ptcp-mlimit--limit5/min-jLOG--log-prefix"DeniedTCP:"--log-level7
-ALOGNDROP-pudp-mlimit--limit5/min-jLOG--log-prefix"DeniedUDP:"--log-level7
-ALOGNDROP-picmp-mlimit--limit5/min-jLOG--log-prefix"DeniedICMP:"--log-level7
-ALOGNDROP-jDROP
COMMIT
#CompletedonSunApr2305:32:092006

NoteanewCHAINcalledLOGNDROPatthetopofthefile.Also,thestandardDROPatthebottomoftheINPUTchainisreplaced
withLOGNDROPandaddprotocoldescriptionssoitmakessenselookingatthelog.Lastlywedropthetrafficattheendofthe
LOGNDROPchain.Thefollowinggivessomeideaofwhatishappening:
--limitsetsthenumberoftimestologthesameruletosyslog

7 sur 9

19/11/2010 17:30

IPTables HowTo - Community Ubuntu Documentation

https://help.ubuntu.com/community/IptablesHowTo

--log-prefix "Denied..."addsaprefixtomakefindinginthesyslogeasier
--log-level 7setsthesyslogleveltoinformational(seemansyslogformoredetail,butyoucanprobablyleavethis)

Disablingthefirewall
Ifyouneedtodisablethefirewalltemporarily,youcanflushalltherulesusing
#iptables-F

orcreateascriptusingtexteditorsuchasnano
#nano-w/root/fw.stop
echo"Stoppingfirewallandallowingeveryone..."
iptables-F
iptables-X
iptables-tnat-F
iptables-tnat-X
iptables-tmangle-F
iptables-tmangle-X
iptables-PINPUTACCEPT
iptables-PFORWARDACCEPT
iptables-POUTPUTACCEPT

Makesureyoucanexecutethescript
$chmod+x/root/fw.stop

Youcanrunthescript
$/root/fw.stop

EasyconfigurationviaGUI
GUFW-GufwisagraphicalfrontendtoUFW(UncomplicatedFirewall).
AnewusercanuseFirestarter(agui),availableinrepositories(Synapticorapt-get)toconfigureher/hisiptablerules,without
needingthecommandlineknowledge.Pleaseseethetutorialthough...Configurationiseasy,butmaynotbeenoughforthe
advanceduser.However,itshouldbeenoughforthemosthomeusers...The(read:my)suggestedoutboundconfigurationis
"restrictive",withwhitelistingeachconnectiontypewheneveryouneedit(port80forhttp,443forsecurehttp-https-,1863for
msnchatetc)fromthe"policy"tabwithinfirestarter.Youcanalsouseittoseeactiveconnectionsfromandtoyourcomputer...
Thefirewallstaysuponceitisconfiguredusingthewizard.Dial-upuserswillhavetospecifyittostartautomaticallyondialupin
thewizard.
Homepageforfirestarter:http://www.fs-security.com/(again,availableinrepositories,nocompilingrequired)Tutorial:
http://www.fs-security.com/docs/tutorial.php

Pleasenotethatitconflictswithufw.

FurtherInformation
IptablesTutorial
IptablesHowTo
NetfilterandIptablesMultilingualDocumentation
EasyFirewallGeneratorforIPTables
ForsomereasontheUbuntuwikipageonFirestarterdoesnotcomeuponsearches,sohereisalink:

8 sur 9

19/11/2010 17:30

IPTables HowTo - Community Ubuntu Documentation

https://help.ubuntu.com/community/IptablesHowTo

UbuntuWikiFirestarter
FirestarterisaguitooltohelpconfigureIPTables.

Pleasenotethatitconflictswithufw.

Credits
ThankstoRustyRussellandhisHow-To,asmuchofthisisbasedoffthat.
CategorySecurity
IptablesHowTo(dernireditionle2010-09-2912:49:18parhttps://login.launchpad.net/+id/cAfxADx@
d54C0600F.access.telenet.be[84.192.96.15]:JanCelis)

PageHistory

9 sur 9

19/11/2010 17:30

You might also like