Packet Sniffing and Spoofingchester/courses/19e_ns/slides/2...ether[0] & 1 = 0 and ip[16] >= 224 IP...
Transcript of Packet Sniffing and Spoofingchester/courses/19e_ns/slides/2...ether[0] & 1 = 0 and ip[16] >= 224 IP...
Packet Sniffing and Spoofing ChesterRebeiroIITMadras
Someoftheslidesborrowedfromthebook‘ComputerSecurity:AHandsonApproach’byWenliangDu
Shared Networks Everynetworkpacketreacheseverycomputer'snetworkInterfacecard,whichthenfilterspacketsbasedontheMACaddress.
Anetworkpackethasmultipleconcatenatedcomponents.
Packet Flow in the System
NetworkCard
networkpacket
checkifdestinationaddressmatchesthecard'sMACaddress
DMAtransferofpackettokernelmemory
Hardware
Kernelbuffer
LinkLevelDriver
ProtocolStackProtocolStack
Kernel
UserSpaceApplicationsonlyreceivepacketsthataremeantfortheCPUandtheregisteredport
KernelonlyreceivepacketsthataremeantfortheCPU
Allpacketsonthenetworkarrivehere
From the Software
From Software Domain:IPV4.OtheralternativesareAF_INET6andmanymore
Type:datagram,connectionless,fixedlength,unreliable
associateanaddresswiththesocketwiththebindcall
From Software
htons():unsignedshortfromhostordertonetworkorderhtonl():unsignedlongfromhostordertonetworkorderntohs():unsignedshortnetworktohostorderntohl():unsignedlong,networktohostorder
Promiscuous Mode
NetworkCard(P)
networkpacket
Nofilteringdoneifthenetworkcardisworkinginpromiscuousmode
DMAtransferofpackettokernelmemory
Hardware
Kernelbuffer
LinkLevelDriver
ProtocolStack
Kernel
UserSpaceApplicationcanreceivesallpacketsthattheNICreceives.
KernelreceiveallpacketsthattheNICreceives
Allpacketsonthenetworkarrivehere
Packet Sniffers
• Applicationsthatregisterwiththekernelsoastocaptureallpacketsseeninthenetwork.
• Typicallyrequiressuperuserpermissions
Packet Sniffers SpecifythatthesocketyouwanttocreateisaRAWsocket.
Protocolfamily:AF_PACKETimplieslowlevelprotocol
Packet Sniffers Whattypeofpacketsshouldwereceive?ETH_P_ALL,impliesallprotocols.Otheroptionsareforinstance,ETH_P_IP,foronlyIPpackets.
Packet Sniffers ConfiguretheNICtoensurethatallpacketsareacceptedandpassedtothekernel.Ignorethedestinationfieldinthepackets.
Packet Sniffers SpecifythatthesocketyouwanttocreateisaRAWsocket.
RAWSOCKETAnapplicationcreatinganormalsocketlikeastreamordatagram,willnotreceivethepacketheaders.InformationlikeMACaddress,sourceIP,etc.isnotreceived.Insteadonlythepayloadpresentineachpacket.Inrawsockets,theheadersarenotclipped.Applicationobtainsanuninterceptedpacket.
Flooding of Packets in User Space
• Applicationsthatregisterwiththekernelsoastocaptureallpacketsseeninthenetwork.
• Typically,sniffersareonlyinterestedinasmallsubsetofpackets,alltheotherpacketsarediscarded.
• Improvesperformanceconsiderably(lessprocessingtime)• Wouldrequiremuchlessexpensivehardware
• Filtering:BSDpacketfiltering(BPF)providesameansbywhichsnifferscanspecifytothekernel,thepacketstheyareinterestedin.
Filter Requirements
• Mustbeprogrammable• Eachsniffermaybeinterestedinadifferentsetofpackets.
• MustbeasclosetotheNICaspossible(filterasearlyaspossible)• Rulesoutuser-spacefiltering• Kernelbasedfiltering• Hardwarebasedfiltering
Operating System Filters
NetworkCard(P)
networkpacket
Nofilteringdone,ifthenetworkcardisworkinginpromiscuousmode
DMAtransferofpackettokernelmemory
Hardware
Kernelbuffer
LinkLevelDriver
ProtocolStack
Kernel
UserSpace
SnifferonlyreceivesallpacketsthattheNICreceivesANDthatpassthefilter.
KernelreceiveallpacketsthattheNICreceives
Allpacketsonthenetworkarrivehere
Filter
Sniffer
buffer
Filter
tcpdump
buffer
BSD Packet Filters (BPF)
• 1992,StevenMcCanneandVanJacobsonfromLawrenceBerkeleyLaboratory
• IncorporatedinLinuxkernelin1997• Variantsstillusedinlatestversions
• JITengine• Lowlevellanguagedefined• Userlevelapplicationwritesfilterrulesusingthislanguageandattachesittoasocket
• Thekernel,verifiessanityoftheserulesandthenappliesthemtoallpacketsitreceives.
bpf architecture
https://www.kernel.org/doc/Documentation/networking/filter.txt
Architecture
bpf architecture
https://www.kernel.org/doc/Documentation/networking/filter.txt
InstructionSet
bpf architecture
https://www.kernel.org/doc/Documentation/networking/filter.txt
AddressingModes
bpf architecture
https://www.kernel.org/doc/Documentation/networking/filter.txt
Extensions
bpf asm example Load2bytes(halfword)fromthe12thoffsetinthepacket
https://en.wikipedia.org/wiki/EtherType
Avalueof0x0800indicatesthatdataisanIPv4packet
bpf asm example ReacheshereonlyifitisanIPv4packet.WenowcheckifitisaTCPpacket
https://en.wikipedia.org/wiki/EtherType
Atoffset23,avalueof6indicatesthatdataisaTCPpacket
14
IPV4Header
bpf asm another example
Randomlysample25%oftheICMPpackets
bpf_asm
bpf_asm
Bpfassembly
Bpfopcode
bpf in the Linux kernel
• JITcompilerbuiltintotheLinuxkernel• Canbeenabledasfollows:
• Internally64-bitkernelsuseanenhancedBPF(eBPF)format• Internally32-bitkernelsusetheclassicalBPFformat
echo1>/proc/sys/net/core/bpf_jit_enable
Usage in Linux
filtertodumppacketsoninterfaceem1port22.
Createarawsocketandattachthefilter.
setsockopt
• SO_ATTACH_FILTER:attachafiltertoasocket• SO_DETACH_FILTER:detachafilterfromasocket.• SO_LOCK_FILTER:lockafiltertoasocket.Thefiltercannotbedetachedormodified.Anyattempttodetachalockedfilterwillresultinanerror.
Enhanced BPF • Instructionslooksmorelikethatofthenativearchitecture(makescodingsimpler)
• 10registers(R0toR9)insteadof2registers(A,X)witheachregister64bitinsteadof32bit
• AFrameRegister(R10)
Enhanced BPF
• RestrictedCcompiledtoeBPF(C->eBPF->nativecode).• Closer(1-to-1)mappingfromeBPFtonativecode• Instructionslooksmorelikethatofthenativearchitecture(makescodingsimpler)
• 10registers(R0toR9)insteadof2registers(A,X)witheachregister64bitinsteadof32bit
• AFrameRegister(R10)• jt/jfreplacedwithjf/fall-through• bpf_callinstructionwhichcancallotherkernelfunctions
Checks in the Kernel
• Beforeattachingafilter,thefollowingchecksneedtobeperformed.• BPFprogramterminates(doesnothaveanyloops)
• Depthfirstsearchoftheprogram'scontrolflowgraph• Unreachableinstructionsareprohibited
• VerifybysinglesteppingthrougheachlineintheBPFprogram• Ensurevirtualmachinestateandcheckifthestackisvalid• Preventout-of-boundjumpsandout-of-rangedata
• Ensurenopointerarithmetic• Ensureregistersarenotreadbeforebeingaccessed
Limitations
• Notportable.ProgramswrittenforoneoperatingsystemmaynotworkonanotherOS(NocommonAPI)
• Optimizationsinthefilteringnoteasilyachieved.TheJITcompilerintheOScannotextractoptimizations.
• Usabilityisnoteasy.ProgrammerswouldneedtoefficientlydevelopBPFcode.
PCap (Packet Capture)
• ItisalibrarythatprovidesAPIsforpacketcapture.• Hasacompiler(pcap_compile)that
• TakesasinputfilteringrulesusinghumanreadableBooleanexpressions.• ConvertstheBooleanexpressionsintoBPFpseudo-code,whichcanbeusedbythekernel.
• WelldefinedAPIsavailableonmanyplatforms:• PortinLinuxiscalledlibpcap• PortinWindowsiscalledWinPCap.(APIsarecommonacrossports)
PCap filter expressions
Threetypesofqualifiers:type,dir,proto1.type:identifierofamachine,portnumberetc.Optionsinclude:host,net,port,portrangeExamples:hostiitm.ac.inport5000portrange5000-6000
https://linux.die.net/man/7/pcap-filter
PCap filter expressions
Threetypesofqualifiers.2.dir:transferdirectionstoorfromtheid.Optionsinclude:src,dst,srcordst,srcanddst,Examples:srchostiitm.ac.insrcordstport5000(equivalenttoport5000)portrange5000-6000
https://linux.die.net/man/7/pcap-filter
PCap filter expressions Threetypesofqualifiers.3.proto:transferdirectionstoorfromtheid.Optionsinclude:ether,fddi,tr,wlan,ip,ip6,arp,rarp,decnet,tcpandudpExamples:• ethersrcfoo:allethernetpacketswherethesourceaddressishostfoo• arpnet128.3:allarppacketstonetwork128.3• tcpport21:alltcppacketstoport21• udpportrange7000-7009
https://linux.die.net/man/7/pcap-filter
PCap Filter examples
• Examples:
https://linux.die.net/man/7/pcap-filter
hostfooandnotportftpandnotportftp-dataAnytrafficfrom/tothehostnamefooexcepttrafficonftpandftp-dataports
gatewaysnupand(portftporftp-data)AllFTPtrafficthroughthegatewapsnup
gatewaysnupandip[2:2]>576Allgatewaytrafficthroughsnupwithsizegreaterthan576bytes
ether[0]&1=0andip[16]>=224
IPbroadcastormulticasttrafficthatwerenotsentviaEthernetbroadcast/multicastByte0LSB1inEthernetframeindicatesabroadcastIPbroadcasthavedestinationaddress224.0.0.0to239.255.255.255
PCap Filter examples
• Examples:
https://linux.die.net/man/7/pcap-filter
hostheliosand\(hotorace\)
ipandnotnetlocalnet
tcp[tcpflags]&(tcp-syn|tcp-fin)!=0andnotsrcanddstnetlocalnet
PCap Filter examples
• Examples:
https://linux.die.net/man/7/pcap-filter
hostheliosand\(hotorace\)Anytrafficfromthehostnameheliosandwithdestinationhotoracewillbelogged.
ipandnotnetlocalnetTrafficthatisnotsourcedordestinedforlocalhosts
tcp[tcpflags]&(tcp-syn|tcp-fin)!=0andnotsrcanddstnetlocalnetstartandendpackets(theSYNandFINpackets)ofeachTCPconversationthatinvolvesanon-localhost.
tcpdump (uses PCap library) OutputtheBPFcodefortheinputpredicate
FilterIPandUDPpackets
LowlevelBPFoutput
Packet Sniffing using PCap API
IsfilledwiththepacketReceived.ThiscontainstherawICMPpacket
fillscompiledBPFprograminfp.Hastheformstructbpf_program*fp
Processing Ethernet Header
Processing Ethernet Header
Processing IP Packet
*packet
*(packet+sizeof(structethheader))
Processing IP Header
Further Processing of Packet • Ifwewanttofurtherprocessthepacket,suchasprintingouttheheaderoftheTCP,UDPandICMP,wecanusethesimilartechnique.
• Wemovethepointertothebeginningofthenextheaderandtype-cast• WeneedtousetheheaderlengthfieldintheIPheadertocalculatetheactualsizeoftheIPheader
• Inthefollowingexample,ifweknowthenextheaderisICMP,wecangetapointertotheICMPpartbydoingthefollowing:
Packet Spoofing
Sending Normal Packets Using Sockets
-luv:listenforincomingUDPpackets,verbose
Manipulating Transmitted Packets • Generally,transmittingpacketshasonlycontroloffewfieldsintheheader.• Example
• DestinationIPaddresscanbeset• SourceIPaddressisnotset:
• Operatingsystem,willautomaticallyfillthesefieldsbeforetranmittingthepackettothehardware
• Spoofing• Permitsmanipulationofcriticalfieldsinthepacketheaders• Cancreateunrealistic/boguspackets.Forexample:
• TransmitaTCPpacketwithSYNandFINbitsturnedon• TheresponsefromthereceiverisunpredictableanddependsontheOS
• Usedinmanynetworkattackslike• TCPSYNFlooding,TCPsessionhijacking,DNScachepoisoningattack• Suppliedinformationdependsonthetypeofattackbeingcarriedout
Spoofing Tools • Netwox• Scapy• Spoofingfromfirstprinciples
• TwoMajorSteps(1)constructingthepacketinabuffer(thisstepisgoingtodependonthetypeofpacket)(2)sendingthepacketout
Constructing an ICMP Ping Packet STEP1
Pingrequest(echorequest)
Constructing an ICMP Ping Packet STEP1
Sending Spoofed Packets Using Raw Sockets
STEP2
Spoofing UDP Packets
Spoofing UDP Packets
MAC Address Spoofing? HowtospoofMACaddresses?NeedshardwareandOSsupport
#iplinksetdeveth0down
#iplinksetdeveth0addressXX:XX:XX:XX:XX:XX
#iplinksetdeveth0up
MACisrestrictedtolocalnetworks.ThusMACspoofingisonlyaproblemwithinsiderthreats
Sniffing and Spoofing
Threat:ManinthemiddleattacksSniffapacket.Spooftheresponse
• Procedure• UsePCAPAPItocapturethepacketsofinterests• Makeacopyfromthecapturedpacket• ReplacetheUDPdatafieldwithanewmessageandswapthesourceanddestinationfields
• Sendoutthespoofedreply
Sniffing and Spoofing a UDP Example why*4?
Sniffing and Spoofing a UDP Example