没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
==PhrackInc.==
Volume0x0b,Issue0x3d,Phile#0x0dof0x0f
|=‐‐‐‐‐‐‐‐‐‐‐‐=[HackingtheLinuxKernelNetworkStack]=‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐=|
|=‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐=|
|=‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐=[bioforge<alkerr@yifan.net>]=‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐=|
TableofContents
1‐Introduction
1.1‐Whatthisdocumentis
1.2‐Whatthisdocumentisnot
2‐ThevariousNetfilterhooksandtheiruses
2.1‐TheLinuxkernel'shandlingofpackets
2.2‐TheNetfilterhooksforIPv4
3‐RegisteringandunregisteringNetfilterhooks
4‐PacketfilteringoperationswithNetfilter
4.1‐Acloserlookathookfunctions
4.2‐Filteringbyinterface
4.3‐Filteringbyaddress
4.4‐FilteringbyTCPport
5‐OtherpossibilitiesforNetfilterhooks
5.1‐Hiddenbackdoordaemons
5.2‐KernelbasedFTPpasswordsniffer
5.2.1‐Thecode...nfsniff.c
5.2.2‐getpass.c
6‐HidingnetworktrafficfromLibpcap
6.1‐SOCK_PACKET,SOCK_RAWandLibpcap
6.2‐Wrappingthecloakaroundthedagger
7‐Conclusion
A‐Light‐WeightFireWall
A.1‐Overview
A.2‐Thesource...lwfw.c
A.3‐lwfw.h
B‐Codeforsection6
‐‐[1‐Introduction
Thisarticledescribeshowquirks(notnecessarilyweaknesses)inthe
Linuxnetworkstackcanbeusedforvariouspurposes,nefariousorotherw‐
ise.Presentedherewillbeadiscussiononusingseeminglylegitimate
Netfilterhooksforbackdoorcommunicationsandalsoatechniquetohide
suchtrafficfromaLibpcapbasedsnifferrunningonthelocalmachine.
NetfilterisasubsystemintheLinux2.4kernel.Netfiltermakes
suchnetworktricksaspacketfiltering,networkaddresstranslation
(NAT)andconnectiontrackingpossiblethroughtheuseofvarioushooksin
thekernel'snetworkcode.Thesehooksareplacesthatkernelcode,either
staticallybuiltorintheformofaloadablemodule,canregister
functionstobecalledforspecificnetworkevents.Anexampleofsuchan
eventisthereceptionofapacket.
‐‐‐‐[1.1‐Whatthisdocumentis
ThisdocumentdiscusseshowamodulewritercanmakeuseoftheNetfilter
hooksforwhateverpurposesandalsohownetworktrafficcanbehidden
fromaLibpcapapplication.AlthoughLinux2.4supportshooksforIPv4,
IPv6andDECnet,onlyIPv4willbediscussedinthisdocument.However,
mostoftheIPv4contentcanbeappliedtotheotherprotocols.Asanaide
toteaching,aworkingkernelmodulethatprovidesbasicpacketfiltering
isprovidedinAppendixA.Anydevelopment/experimentationdoneforthis
documentwasdoneonanIntelmachinerunningLinux2.4.5.Testingthe
behaviourofNetfilterhookswasdoneusingtheloopbackdevice,an
EthernetdeviceandamodemPoint‐to‐Pointinterface.
Thisdocumentisalsowrittenformybenefitinanattempttofully
understandNetfilter.Idonotguaranteethatanycodeaccompanyingthis
documentis100%errorfreebutIhavetestedallcodeprovidedhere.I
havesufferedthekernelfaultssohopefullyyouwon'thaveto.Also,I
donotacceptanyresponsibilityfordamagesthatmayoccurthrough
followingthisdocument.Itisexpectedthatthereaderbecomfortablewith
theCprogramminglanguageandhavesomeexperiencewithLoadableKernel
Modules.
IfIhavemadeamistakeinsomethingpresentedherethenpleaseletme
know.Iamalsoopentosuggestionsoneitherimprovingthisdocumentor
otherniftyNetfiltertricksingeneral.
‐‐‐‐[1.2‐Whatthisdocumentisnot
Thisdocumentisnotacompleteins‐and‐outsreferenceforNetfilter.It
isalso*not*areferencefortheiptablescommand.Ifyouwanttolearn
moreabouttheiptablescommand,consultthemanpages.
Solet'sgetstartedwithanintroductiontousingNetfilter...
‐‐[2‐ThevariousNetfilterhooksandtheiruses
‐‐‐‐[2.1‐TheLinuxkernel'shandlingofpackets
AsmuchasIwouldlovetogointothegorydetailsofLinux'shandlingof
packetsandtheeventspreceedingandfollowingeachNetfilterhook,I
won't.ThesimplereasonisthatHaraldWeltehasalreadywrittenanice
documentonthesubject,hisJourneyofaPacketThroughtheLinux2.4
NetworkStackdocument.TolearnmoreonLinux'shandlingofpackets,I
stronglysuggestthatyoureadthisdocumentaswell.Fornow,just
understandthatasapacketmovesthroughtheLinuxkernel'snetworkstack
itcrossesseveralhooklocationswherepacketscanbeanalysedandkept
ordiscarded.ThesearetheNetfilterhooks.
‐‐‐‐‐‐[2.2TheNetfilterhooksforIPv4
NetfilterdefinesfivehooksforIPv4.Thedeclarationofthesymbolsfor
thesecanbefoundinlinux/netfilter_ipv4.h.Thesehooksaredisplayed
inthetablebelow:
Table1:AvailableIPv4hooks
HookCalled
NF_IP_PRE_ROUTINGAftersanitychecks,beforeroutingdecisions.
NF_IP_LOCAL_INAfterroutingdecisionsifpacketisforthishost.
NF_IP_FORWARDIfthepacketisdestinedforanotherinterface.
NF_IP_LOCAL_OUTForpacketscomingfromlocalprocesseson
theirwayout.
NF_IP_POST_ROUTINGJustbeforeoutboundpackets"hitthewire".
TheNF_IP_PRE_ROUTINGhookiscalledasthefirsthookafterapacket
hasbeenreceived.Thisisthehookthatthemodulepresentedlaterwill
utilise.Yestheotherhooksareveryusefulaswell,butfornowwe
willfocusonlyonNF_IP_PRE_ROUTING.
Afterhookfunctionshavedonewhateverprocessingtheyneedtodowith
apackettheymustreturnoneofthepredefinedNetfilterreturncodes.
Thesecodesare:
Table2:Netfilterreturncodes
ReturnCodeMeaning
NF_DROPDiscardthepacket.
NF_ACCEPTKeepthepacket.
NF_STOLENForgetaboutthepacket.
NF_QUEUEQueuepacketforuserspace.
NF_REPEATCallthishookfunctionagain.
TheNF_DROPreturncodemeansthatthispacketshouldbedropped
completelyandanyresourcesallocatedforitshouldbereleased.
NF_ACCEPTtellsNetfilterthatsofarthepacketisstillacceptableand
thatitshouldmovetothenextstageofthenetworkstack.NF_STOLENis
aninterestingonebecauseittellsNetfilterto"forget"aboutthepacket.
WhatthistellsNetfilteristhatthehookfunctionwilltakeprocessing
ofthispacketfromhereandthatNetfiltershoulddropallprocessingof
it.Thisdoesnotmean,however,thatresourcesforthepacketare
released.Thepacketandit'srespectivesk_buffstructurearestillvalid,
it'sjustthatthehookfunctionhastakenownershipofthepacketaway
fromNetfilter.UnfortunatelyI'mnotexactlyclearonwhatNF_QUEUE
reallydoessofornowIwon'tdiscussit.Thelastreturnvalue,
NF_REPEATrequeststhatNetfiltercallsthehookfunctionagain.Obviously
onemustbecarefulusingNF_REPEATsoastoavoidanendlessloop.
‐‐[3‐RegisteringandunregisteringNetfilterhooks
Registrationofahookfunctionisaverysimpleprocessthatrevolves
aroundthenf_hook_opsstructure,definedinlinux/netfilter.h.The
definitionofthisstructureisasfollows:
structnf_hook_ops{
structlist_headlist;
/*Userfillsinfromheredown.*/
nf_hookfn*hook;
intpf;
inthooknum;
/*Hooksareorderedinascendingpriority.*/
intpriority;
};
Thelistmemberofthisstructureisusedtomaintainthelistsof
Netfilterhooksandhasnoimportanceforhookregistrationasfarasusers
areconcerned.hookisapointertoanf_hookfnfunction.Thisisthe
functionthatwillbecalledforthehook.nf_hookfnisdefinedin
linux/netfilter.haswell.Thepffieldspecifiesaprotocolfamily.Valid
protocolfamiliesareavailablefromlinux/socket.hbutforIPv4wewantto
usePF_INET.Thehooknumfieldspecifiestheparticularhooktoinstall
thisfunctionforandisoneofthevalueslistedintable1.Finally,the
priorityfieldspecifieswhereintheorderofexecutionthishookfunction
shouldbeplaced.ForIPv4,acceptablevaluesaredefinedin
linux/netfilter_ipv4.hinthenf_ip_hook_prioritiesenumeration.Forthe
purposesofdemonstrationmoduleswewillbeusingNF_IP_PRI_FIRST.
RegistrationofaNetfilterhookrequiresusinganf_hook_opsstructure
withthenf_register_hook()function.nf_register_hook()takestheaddress
ofannf_hook_opsstructureandreturnsanintegervalue.However,ifyou
actuallylookatthecodeforthenf_register_hook()functionin
net/core/netfilter.c,youwillnoticethatitonlyeverreturnsavalueof
zero.Providedbelowisexamplecodethatsimplyregistersafunctionthat
willdropallpacketsthatcomein.Thiscodewillalsoshowhowthe
Netfilterreturnvaluesareinterpreted.
Listing1.RegistrationofaNetfilterhook
/*SamplecodetoinstallaNetfilterhookfunctionthatwill
*dropallincomingpackets.*/
#define__KERNEL__
#defineMODULE
#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/netfilter.h>
#include<linux/netfilter_ipv4.h>
/*Thisisthestructureweshallusetoregisterourfunction*/
staticstructnf_hook_opsnfho;
/*Thisisthehookfunctionitself*/
unsignedinthook_func(unsignedinthooknum,
structsk_buff**skb,
conststructnet_device*in,
conststructnet_device*out,
int(*okfn)(structsk_buff*))
{
returnNF_DROP;/*DropALLpackets*/
}
/*Initialisationroutine*/
intinit_module()
{
/*Fillinourhookstructure*/
nfho.hook=hook_func;/*Handlerfunction*/
nfho.hooknum=NF_IP_PRE_ROUTING;/*FirsthookforIPv4*/
nfho.pf=PF_INET;
nfho.priority=NF_IP_PRI_FIRST;/*Makeourfunctionfirst*/
nf_register_hook(&nfho);
return0;
}
/*Cleanuproutine*/
voidcleanup_module()
{
nf_unregister_hook(&nfho);
}
That'sallthereistoit.Fromthecodegiveninlisting1youcansee
thatunregisteringaNetfilterhookisasimplematterofcalling
nf_unregister_hook()withtheaddressofthesamestructureyouusedto
registerthehook.
‐‐[4‐BasicpacketfilteringtechniqueswithNetfilter
‐‐‐‐[4.1‐Acloserlookathookfunctions
Nowitstimetostartlookingatwhatdatagetspassedintohook
functionsandhowthatdataanbeusedtomakefilteringdecisions.So
let'slookmorecloselyattheprototypefornf_hookfnfunctions.The
prototypeisgiveninlinux/netfilter.hasfollows:
typedefunsignedintnf_hookfn(unsignedinthooknum,
structsk_buff**skb,
conststructnet_device*in,
conststructnet_device*out,
int(*okfn)(structsk_buff*));
Thefirstargumenttonf_hookfnfunctionsisavaluespecifyingoneof
thehooktypesgivenintable1.Thesecondargumentismoreinteresting.
Itisapointertoapointertoask_buffstructure,thestructureused
bythenetworkstacktodescribepackets.Thisstructureisdefinedin
linux/skbuff.handduetoitssize,Ishallonlyhighlightsomeofit's
moreinterestingfieldshere.
Possiblythemostusefulfieldsoutofsk_buffstructuresarethethree
unionsthatdescribethetransportheader(ie.UDP,TCP,ICMP,SPX),the
networkheader(ie.IPv4/6,IPX,RAW)andthelinklayerheader(Ethernet
orRAW).Thenamesoftheseunionsareh,nhandmacrespectively.These
unionscontainseveralstructures,dependingonwhatprotocolsareinuse
inaparticularpacket.Oneshouldnotethatthetransportheaderand
networkheadermayverywellpointtothesamelocationinmemory.This
isthecaseforTCPpacketswherehandnharebothconsideredas
pointerstoIPheaderstructures.Thismeansthatattemptingtogeta
valuefromh‐>ththinkingit'spointingtotheTCPheaderwillresultin
falseresultsbecauseh‐>thwillactuallybepointingtotheIPheader,
justlikenh‐>iph.
Otherfieldsofimmediateinterestarethelenanddatafields.len
specifiesthetotallengthofthepacketdatabeginningatdata.Sonow
weknowhowtoaccessindividualprotocolheadersandthepacketdata
itselffromask_buffstructure.Whatotherinterestingbitsof
informationareavailabletoNetfilterhookfunctions?
Thetwoargumentsthatcomeafterskbarepointerstonet_device
structures.net_devicestructuresarewhattheLinuxkernelusesto
describenetworkinterfacesofallsorts.Thefirstofthesestructures,
in,isusedtodescribetheinterfacethepacketarrivedon.Not
surprisingly,theoutstructuredescribestheinterfacethepacketis
leavingon.Itisimportanttorealisethatusuallyonlyoneofthese
structureswillbeprovided.Forinstance,inwillonlybeprovidedfor
theNF_IP_PRE_ROUTINGandNF_IP_LOCAL_INhooks.outwillonlybeprovided
fortheNF_IP_LOCAL_OUTandNF_IP_POST_ROUTINGhooks.AtthisstageI
haven'ttestedwhichofthesestructuresareavailableforthe
NF_IP_FORWARDhookbutifyoumakesurethepointersarenon‐NULLbefore
attemptingtodereferencethemyoushouldbefine.
Finally,thelastitempassedintoahookfunctionisafunctionpointer
calledokfnthattakesask_buffstructureasitsonlyargumentand
returnsaninteger.I'mnottoosureonwhatthisfunctiondoes.Looking
innet/core/netfilter.ctherearetwoplaceswherethisokfniscalled.
Thesetwoplacesareinthefunctionsnf_hook_slow()andnf_reinject()
whereatacertainplacethisfunctioniscalledonareturnvalueof
NF_ACCEPTfromaNetfilterhook.Ifanybodyhasmoreinformationonokfn
pleaseletmeknow.
Nowthatwe'velookedatthemostinterestingandusefulbitsofinforma‐
tionthatourhookfunctionsreceive,it'stimetolookathowwecanuse
thatinformationtofilterpacketsinavarietyofways.
‐‐‐‐[4.2‐Filteringbyinterface
Thiswouldhavetobethesimplestfilteringtechniquewecando.
Rememberthosenet_devicestructuresourhookfunctionreceived?Using
thenamefieldfromtherelevantnet_devicestructureallowsustodrop
packetsdependingontheirsourceinterfaceordestinationinterface.To
dropallpacketsthatarriveoninterfaceeth0allonehastodois
comparethevalueofin‐>namewith"eth0".Ifthenamesmatchthenthe
hookfunctionsimplyreturnsNF_DROPandthepacketisdestroyed.It'sas
easyasthat.Samplecodetodothisisprovidedinlisting2below.Note
thattheLight‐WeightFireWallmodulewillprovidesimpleexamplesof
allthefilteringmethodspresentedhere.ItalsoincludesanIOCTL
interfaceandapplicationtochangeitsbehaviourdynamically.
Listing2.Filteringpacketsbasedontheirsourceinterface
/*SamplecodetoinstallaNetfilterhookfunctionthatwill
*dropallincomingpacketsonaninterfacewespecify*/
#define__KERNEL__
#defineMODULE
#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/netdevice.h>
#include<linux/netfilter.h>
#include<linux/netfilter_ipv4.h>
/*Thisisthestructureweshallusetoregisterourfunction*/
staticstructnf_hook_opsnfho;
/*Nameoftheinterfacewewanttodroppacketsfrom*/
staticchar*drop_if="lo";
/*Thisisthehookfunctionitself*/
unsignedinthook_func(unsignedinthooknum,
structsk_buff**skb,
conststructnet_device*in,
conststructnet_device*out,
int(*okfn)(structsk_buff*))
剩余29页未读,继续阅读
资源评论
dan_chow
- 粉丝: 0
- 资源: 2
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功