You are on page 1of 5

BerkeleyPacketFiltersTheBasics JeffStebelton

Introduction WhatareBerkeleyPacketFilters?BPFsarearaw(protocolindependent)socket interfacetothedatalinklayerthatallowsfilteringofpacketsinaverygranularfashion1. SupportforBPFiscompiledintothekernelinUNIXlikehosts,orifnot,libpcap/Winpcap allowsthistobedoneatusermodelevel.Ifdoneviausermode,allpacketsarecopied upfromtheinterfaceandnotjusttheonesthefilterspecifies. BPFwerefirstintroducedin1990byStevenMcCanneofLawrenceBerkeleyLaboratory, accordingtheFreeBSDmanpageonbpf2. WorkingwithBPF Ifyouusetcpdumpforverylong,youencounterwhatarecalledprimitives,filter expressionstotuneyourresultstoonlyseecertaintraffic.Examplesofprimitivesare net,portaddrandqualifierstothosesuchassrcordst. Withthesewecanlimitourresultsusingfilterssuchassrchost10.10.1.1ornet 10.10.Therearemanyofthese(seethemanpageoftcpdumpforthefulllist) Youcanalsospecifyprotocols,suchasip,tcp,oricmp.Someevenmake comparisons,suchaslessandgreaterforpacketlength. TheseprimitivesareshortcutsforBPFs.Eachonereferencessomefieldorfieldsinone ofthenetworkprotocolheaders.Forexample,theembeddedprotocolfieldintheIP headeristhe9thbyteoffsetfrom0.Ifthevaluecontainedthereisa6,thepacketisTCP. SotheprimitivetcpreallymeansshowmeallthepacketsintheIPheaderwhose9th byteoffsetfrom0containsa6.IfwewrotethisasaBPF,itwouldlooklikethis:ip[9]= 6orusinghex,ip[9]=0x06. BPFscangofarbeyondthebuiltinprimitives,allowingustogetasgranularasneeded, downthesinglebitlevel.Ifafielddoesnotspantheentirebyte,wellneedtowritea BPFtolookatthebitsinquestiontodeterminethevaluethere.

LetslookatthefirstlineoftheIPheader3toseeanexample.
Byte1 Byte2

Byte

Byte3

IPVersion

IPHeader length

TypeofService

TotalLength

Weseebyte0(westartcountingfrom0,whichiswhatwemeanbyoffsetfrom0)that therearetwofieldsinthebyte,theIPVersionfieldandtheIPHeaderLengthField. IfwewantedtoseewhattheIPversionofthepacketis,howwewoulddothis?Weonly wantthevalueinthehighordernibble(highorder=leftmostaswecountbitsfrom righttoleft,andanibbleis4bits,orhalfabyte).Toseethatvaluewehavetoextractit fromthebyteofdatasomehowandlookatitsingularly.Todothis,weemploya methodknowasbitmasking.Bitmaskingissimplyfilteringoutthebitswedontwishto lookatandretainingtheoneswedo. Toaccomplishthis,wellperformabitwiseANDoperationonallofthebitsinthebyte. IfweANDthebits,onlytheoneswithavalueof1willberetained.Letslookatthis. HeresabinaryrepresentationofatypicalfirstbyteintheIPheader: 01000101 Weveseparatedthetwonibbleshereforclarity.Weseethelowordernibble(right most)has0101.ThisisourIPheaderlength.Wewanttocheckthehighordernibble, whichhasthevalue0100.Todothiswewilladd1toeachbit.InabitwiseAND,any valuesexcepttwo1sequal0.Two1sequalone. Sotomanipulatethebitstoseethefirstnibbleonly,wewanttoadd1stothehigh ordernibbleand0stothelowerorder.Sinceall1swillequalFinhex,wewillwritean expressionaddinghexFtothefirstnibbleand0tothesecond. HereswhattheBPFwilllooklike:

ip[0]&0xF0=0x04(oursearchvalue). Brokendown,wearetellingtcpdumptolookattheIPheader(ip),firstbyteoffsetfrom 0([0]),retainallthebitsinthefirstnibbleanddiscardallthebitsintheloworder nibble(&0xF0)andshowusallthepacketswithavalueof4inthatnibble(=4). Heresourbitwiseoperation 01000101 11110000 01000000 Wenowseethelowordernibblehasbeenfiltered(all0s)andwehavethehighorder nibbleleft.Binary0100=decimal4,sothisshowsusthepackethasvalueof4inthe highordernibbleofthefirstbyte;theIPheaderissettoIPv4. SampleFilters NowthatweseehowBPFswork,herearesomesamplesoffilterswecansearchon: 'ip[9]=0x11' 'ip[9]=0x01' 'tcp[2:2]' udp icmp 2ndbyte,spanning twobytes echorequestpacket tcpdestport<20

'icmp[0]=0x08' 'tcp[2:2]<0x14'

Letscreateafilterforoneofthemorecommonandmorecomplexuses:TCPFlags

TheflagsfieldinTCPisfoundatthe13thbyteoffsetfrom0.Theflagsthemselvesinhabit allofthelowerordernibble,andthetwolowerorderbitsofthehighordernibble. ThetwohighorderbitsofthehighordernibbleareusedforECN(ExplicitCongestion Notification).Heresourlayout TCPByte13 Flags BinaryValues LetsassumewewishtoseeallpacketswiththeSYNandFINflagsset.Thisisanomalous behaviorandusuallyindicativeofaportscanningmethod. Wewouldneedtolookatthewholebyteandretainallbitsexceptthetwohighest ordersinthehighordernibble.Todothisweneedamaskretainingallofthelower ordernibbleandthelowerorderbitsofthehighordernibble.Heresourbitwise operationmask: Highorder CWR ECE Urg Loworder Fin 128 64 32 16 8 4 2 1 CWR ECE Urg Ack Push Reset Syn Fin

AckPush Reset Syn

00111111 So,wewouldhaveahexFinthelowordernibble(all1s),anda3inthehighorder nibble(a1inthe0column,whichis1,andaoneinthe2scolumn,whichis2,equaling 3). Soourmaskwouldbe0x3F.ThatwouldshowusonlythebitsthatcontainTCPflags.

Ifweusethatfilterandlookforavalueof3,meaningthetwolowestorderbitsareset, theFinandSynbit,wewouldendupwiththis: ip[13]&0x3f=0x03 Thisfiltertellsthesystemtofilteronthe13thbyteoffsetfrom0,discardingthetwo highestorderbits,andshowingpacketsthehaveatotalvalueof3inthesixremaining bits,whichwouldmeantheFinandtheSynflagswerebothflippedon. Nowthatweknowhowtolookatonlythebitsweneed,wecanapplythistoanyfield, inanynetworkheader.Youcan,ofcourse,stringmultiplefilterstogethertogetas specificasneeded.HeresatcpdumpquerytoshowusallpacketswiththeSynflagset, andadatagram(packet)sizegreaterthan134bytes(probabledataontheSynpacket), andanIPversionthatisNOT4: tcpdumpnnieth0tcp[13]&0x02=2andip[2:2]>0x86andip[0]&0xF0!=4 Summary BerkeleyPacketFiltersareapowerfultoolfortheintrusiondetectionanalysis.Using themwillallowtheanalysttoquicklydrilldowntothespecificpacketshe/sheneedsto seeandreducelargepacketcapturesdowntotheessentials.Evenabasicknowledgeof howtousethemwillsavehoursoftimeduringtheinvestigationofpackets,orgive insightintomalicioustrafficthatwasntdetectedusingothermethods. References 1. http://en.wikipedia.org/wiki/Berkeley_Packet_Filter 2. http://www.gsp.com/cgibin/man.cgi?section=4&topic=bpf 3. http://en.wikipedia.org/wiki/IPv4