Libpcap使用简介.pdf
Libpcap使用简介,无线驱动开发技术相关资料,用兴趣可以自行下载。Libpcap使用简介,无线驱动开发技术相关资料,用兴趣可以自行下载。Programming with Libpcapies it from the card buffer to a block through but, as we will see later, Python, Java, C# or Ruby. Libpcapof memory in kernel space. Then, it they usually offer advanced filtering runs on most UNIX-like operatingdetermines which type of packet has capabilities. As packet capture may systems (Linux, Solaris, BSD, HPbeen received looking at the ether- involve security risks, most systems UX.. there is also a Windows ver-type field of the Ethernet header and require administrator privileges in sion named Winpcap. Today, libpcappasses it to the appropriate protocol order to use this feature. Figure 1 is maintained by the Tcpdump grouphandler in the protocol stack. In most illustrates the capture processFull documentation and source codecases the frame will contain an iPv4is available from the tcpdump' s officialdatagram so the IPv4 packet handler Libpcapsiteathttp://www.tcpdump.org.(httpwillbecalledThishandlerperformsLibpcapisanopensourcelibrarythat//www.winpcap.org/forWinpcap)a number of check to ensure, for provides a high level interface to net-example, that the packet is not cor- work packet capture systems. It was Our First Stepsrupt and that is actually destined created in 1994 by McCanne, Leres With Libpcapfor this host. If all tests are passed, and Jacobson researchers at thethat we know the basics ofthe IP headers are removed and Lawrence Berkeley National Labora- packet capture let us write our ownthe remainder is passed to the next tory from the University of California at sniffing applicationprotocol handler(probably TCP or Berkeley as part of a research projectThe first thing we need is a net-UDP). This process is repeated until to investigate and improve TCP and work interface to listen on. We canthe data gets to the application layer Internet gateway performanceeither specify one explicitly or letwhere it is processed by the userLibpcap authors main objective libpcap get one for us. The functionlevel applicationwas to create a platform-independ char *pcap lookurdev(char *erroufyWhen we use a sniffer, packets ent API to eliminate the need for returns a pointer to a string containgo through the same process de- system-dependent packet capture ing the name of the first networkscribed above but with one differ- modules in each application, as vir- device that is suitable for packet capence: the network driver also sends tually every OS vendor implements ture. Usually this function is calleda copy of any received or transmitted its own capture mechanismswhen end-users do not specify anypacket to a part of the kernel calledThe libpcap API is designed to network interface. It is generallythe packet filter. Packet filters are be used from c and C++. However, a bad idea to use hard coded inter-what makes packet capture pos- there are many wrappers that allow face names as they are usually notsible. By default they let any packet its use from languages like Perl, portable across platformsSnifferTransmittedPacketPacket filteReceivedMonitorNETWORKCARDPacketARDDRIVERWeb browserProtocol StackFTP ServeHardwareKernel SpaceUser SpaceFigure 1 Elements involved in the capture processwww.haking.org/enhakin9 2/200839AttackThe errbuf argument of psap mented by libpcap take this paramOnce we have the name of thelookupdev() is a user supplied buffer eter. When allocating the buffer we network device we have to openthat the library uses to store an error have to be careful because it must be it. The functiap t "pcapmessage in case something goes able to hold at least PCAP ERRBUF open live(cons: char device,intwrong. Many of the functions imple- SIZE bytes(currently defined as 256). snaplen, -nt promisc, int to ns,char *errkuf) does that. It returns anListing 1. Structure pcap pkthdrinterface handler of type rcap t thatwill be used later when calling the reststruct pcap pktharof the functions provided by libpcapstruct timeval ts; / Timestamp ot captureThe first argument of pcapbof u int 32 caplen; / Nunber cf bytes thdt were stored *bof u int 32 len; / TctaI length of the packet *oFen live() is a string containingthe name of the network interfacewe want to open. The second oneListing 2. Simple snifferis the maximum number of bytes tocapture. setting a low value for this★o compile: gcc simplesniffer. c -o simplesniffer -Pcap */parameter might be useful in casewe are only interested in grabbing#include embedded systems with important#include len);many milliseconds should the kernelprintf(" Payload: \n")vait betore copying the capturedor (1=0; i-en: i++)iinformation from kernel space toif( isprint(packet[i]))user space. Changes of context areprintf(" c", packet[il)icomputationally expensive. If weelsecapturing a high volume of networktraffic it is better to let the kernelgroup some packets before crossif(i816==05i1=0)1i==pe1-1)printf(n")ing the kernel-userspace bound-ary. A value of zero will cause thereturnread operations to wait forever untilgh packets arrived to the net-work interfation does not provide any suggestionpcap t descr- NULLor this value to have an idea wechar errbulf I PCAP FRRRUF STZF], *devi ceNUl.;can examine what other sniffers domemset(errbuf,0, PCAP ERRBUF SIZEiTcpdump uses a value of 1000, dsniffuses 512 and ettercap distinguishes/ Get the name of the iirs: device suitable for capture*between different operating systemsdevice pcap lookupdev(errbu-)iusing 0 for Linux or Open BSD and 10print ("Opening device s\n", device)ifor the restThe prom - sc flag decides wheth/* Open device in promiscuous mode *er the network interface should ber= pcap open live(device, MAXBYIES2CAPTJEE, 1, 512, errbuf)put into promiscuous mode or not/ Loop forever caII processPacket() for every received packer%,That is, whether the network cardpcap loop(descr, -l, processPacket, (u char *should accept packets that are notdestined to it or not. Specify 0 forreturn onon-promiscuous and any othervalue for promiscuous mode. Notethat even if we tell libpcap to listen40hakin 9 2/2008www.haking.org/enAttackin non-promiscuous mode, if the You are probably wondering if the struct pcap pkthdrr pkthdr, conet uinterface was already in promiscu- function only returns an integer,wherepacket)ous mode it may stay that way. We are the packets that were captured?should not take for granted that we The answer is a bit tricky. pcap lcop( The first argument is the user pointerwill not receive traffic destined for does not return those packets, instead, that we passed to pcap loop(), theother hosts, instead, it is better to it calls a user-defined function every second one is a pointer to a structureuse the filtering capabilities that lib- time there is a packet ready to be read. that contains information about thepcap provides, as we will see later. This way we can do our own process- captured packet Listing 1 shows theOnce we have a network inter- ing in a separate function instead of definition of this structureface open for packet capture, we calling pcap next() in a loop andThe caplen member has usuallyhave to actually tell pcap that we process everything inside. However the same value as len except thewant to start getting packets For this there is a problem. If pcap lcop0) situation when the size of the capwe have some options:calls our function, how can we pass ar- tured packet exceeds the snaplenguments to it? Do we have to use ugly specified in open pcap live(The function const u char globals? The answer is no, the libpcapThe third alternative is to use int*pcap next(pcap t *p, struct guys thought about this problem and pcap dispatch(pcap t *p, int cnt,pcap pktrdr *h) takes the included a way to pass information to pcap handler callback.harpcap t handler returned by the callback function. This is the user user), which is similar to pcappcap oper. live, a pointer to argument. This pointer is passed in 100p) but it also returns when thea structure of type pcap pkthdr every call. The pointer is of type u to ns timeout specified in pcapand returns the first packet that char so we will have to cast it for our oren live( elapsesarrives to the network interfaceown needs when calling pcap 1co?()Listing 1 provides an exampleThe function intand when using it inside the callback of a simple sniffer that prints thecn-rfunction. Our packet processing func- raw data that it captures. Note thatpcap landler callback, u char tion must have a specific prototype, header file pcap. h must be included*user)is used to collect packets otherwise pcap 100p() wouldn't Error checks have been omitted forand process them. It will notknow how to use it. This is the way it clarityturn until cnt packets have been should be declared:captured. Aative cnt valueOncewill cause pcap locp() to return void furction name (u char *userargWe Capture a packetonly in case of error.constWhen a packet is captured, the onlything that our application has gota bunch of bytes. Usually, the net-work card driver and the protocolI Capture Loopstack process that data for us butwhen we are capturing packets fronInitializeCaptureour own application we do it at theNetworkSet FilterInterfacewest level so we are the ones incharge of making the data rationalTo do that there are some things thatshould be taken into accountExitCloseProcessData Link Type一-1-PacketAlthough Etheseems to bepresent everywhere, there are a lot ofdifferent technologies and standardsthat operate at the data link layer. Inorder to be able to decode packetsFigure 2. Normal program flow of a pcap applicationcaptured from a network interfacewe must know the underlying datalink type so we are able to interpretthe headers used in that layerETHERNETEADERIP HEADER TCP HEADERPAYLOADETHERNETCHECKSUMefunctiontype of the device opened byFigure 3. Data encapsulation in Ethernet networks using the TCP/Ppcap open live(). Libpcap is ableprotocolto distinguish over 180 different link42hakin 9 2/2008www.haking.org/enProgramming with Libpcaptypes. However, it is the responsibil- defined. A complete list can be found for example, we capture a packet thatityoftheusertoknowthespecificathttp://www.iana.org/assignments/istargetedtoorcomesfromport80details of any particular technology. protocol-numbersand it is payload is plain ascll text, itThis means that we, as programwill probably be some kind of Httpmers, must know the exact format Application Layer Protocoltraffic between a web browser and aof the data link headers that the cap- Ok, so we have got the Ethernet web server. However, this is not exacttured packets will have. In most ap- header, the IP header, the TCP science so we have to be very careplications we would just want to know header and now what?. Application ful when handling the TCP payload, itthe length of the header so we know layer protocols are a bit harder to may contain unexpected datawhere the iP datagram startsdistinguish. The TCP header doesTable 1 summarizes the most not provide any information about Malformed Packetscommon data link types, their the payload it transports but TCP In Louis Amstrong's wonderful worldnames in libpcap and the offsets port numbers can give as a clue. If, everything is beautiful and perfectthat should be applied to the startTable 1. Common data link typesof the captured data to get the nextprotocol header.Data Link TypePcap AliasOffset (in bytes)Probably the best way to handle Ethernet 10/100/1000 Mbsthe different link layer header sizesDLT EN10MBis to implement a function that takeWi-Fi802.11a pcap t structure and returns theDLT IEEE802 11offset that should be used to get the FDDI( Fiber Distributed Data21network layer headers. Dsniff takes InterfaceDLT FFDIthis approach. Have a look at func- PPPoE (PPP over Ethernet)14(Ethernet)+6tion pcap dloff( in file pcap util.cDLE PPE ETHER(PPP)=20from the dsniff source codeSD LoopbackDLT NULLNetwork Layer ProtocolPoint to Point(Dial-up)The next step is to determine whatDLT PPEfollows the data link layer headerFrom now on we will assume that weTable 2. Network layer protocols and ethertype valuesare working with Ethernet networks. Network Layer ProtocolEthertype ValueThe Ethernet header has a 16-bit Internet Protocol Version 4(IPv4)0x0800field named ethertype which specinternet Protocol Version 6(IPv6)0x86DDfies the protocol that comes next. Ta0x0806ble 2 lists the most popular networkAddress Resolution Protocol (ARP)layer protocols and their ethertypeReverse Address Resolution Protocol (RARP)0x8035valueAppleTalk over Ethernet(EtherTalk)0x809BWhen testing this value we Point-to-Point Protocol (PPP))0x880Bmust remember that it is received inPPPOE Discovery Stage0X8863network byte order so we will have0x8864to convert it to our host's orderingPPPOE Session Stagescheme using the function ntohs(Simple Network Management Protocol(SNMP) 0x814CTransport Layer ProtocolTable 3. Transport layer protocolsOnce we know which network layer ProtocolRFCprotocol was used to route our cap- Internet Control Message Protocol0x01RFC 792tured packet we have to find out (ICMPwhich protocol comes next. AssumInternet Group Management Protocol0x02RFC 3376ng that the captured packet hasan iP datagram knowing the next(IGMPprotocol is easy, a quick look at theTransmission Control Protocol(TCP) 0X06 RFC: 793protocol field of the IPv4 header(inExterior Gateway Protocol0×08RFC888IPv6 is called next header) will tell User Datagram Protocol(UDP)RFC 768s. Table 3 summarizes the mostIPv6 Routing Header0x2BRFC 1883common transport layer protocolsIPv6 Fragment Header0x2CRFC 1883their hexadecimal value and theRFC document in which they areICMP for IPv60×3ARFC 1883www.haking.org/enhakin9 2/20083Attackbut sniffers usually live in hell. Net- we cannot blindly trust the protocolwe are expecting an arP packetworks do not always carry valid pack- field of an ip datagram to contain theon an Ethernet network, packetsets. Sometimes packets may not be correct value for the following header.with a length different than=4+crafted according to the standards Not even the fields that specify lengths28= 42 bytes should be discard-or may get corrupted in their way. can be trusted. If we want to designed. Failing to check the length ofThese situations must be taken into a powerful packet analyzer, avoidinga packet may result in a noisyaccount when designing an applica- segmentation faults and headaches.segmentation fault when trying totion that handles sniffed trafficevery detail must be checkedaccess the received dataThe fact that an echertype value Here are a few tipsCheck iP and tcp checksumssays that the next header is of typeIf checksums are not valid thenARP does not mean we will actuallyCheck the whole size of the re-the data contained in the headfind an ARP header In the same wayceived packet. If, for example,ers may be garbage. However,Listing 3 Simple ARP sniffer/*Simple ARP Sniffedescr- pcap open -ive(argv [1], MAXBYTES2CAPTURE, 0,/ To compile: gcc arpsniffer. c -o arpsniff -Pcap *,512, errbuf)iLook up info from the capture device.*.#inclIne /* Compiles the filter expression irt a BPE filter/x ARE Header, ( assuming Ethernet+IP74pcap compile( descr, &filter,"armask)#fdef ne ARP REQJEST 1 / ARP Requesdefne ARP REPLY 2/ ARP ReplyLoad the ilter program into the packet capturetypedef struct arphdr Idevice. *u int16 t htypeHardware Typepcap netfilter(descr, &filteru int16 t ptypei4 ProtocoL Typeu char leniHardware Address Lergthwhile(1)(u char plen,x protocol Address Length x,u int16 t oper:x Operation Codepacket= pcap next (descr, &pkthcri/* Get one packetu char sha6」/* Sender hardware addressu char spa[4]Sender Ip addresarpheader-(struct arphdr *)(packet+14)i/* Point tou char tha[6li/ Target hardware addressth∈AFP上 eaderyarphdr tiprintf(\n\rEceived Packet Size: d bytes \n"pkthar. len)if defne MAXBYTES2CAPTURE 2048printf ("hardware type: s\n", (ntchs(arpheaderchtype)== 1)?Ethernetint main (int argc, char argv[:)il Unknown"printf("Protocol type: ss\n",(ntchs(arppe)=- Cx0E00)?"IPv4bpf a int32 netaddr-0, nask=0; /* To Store networkUnknown")iaddress ann netmask */print f("Operation: s\n",(ntors(arpheader->per)=-struct opf program filter/ place to store theARE REQUEST)? ARE RequestBFF filter program"ARE Replychar errbuf I PCAP ERRDUF SIZError bufferIf is Ethernet and Ip1, print packet contents *pcap t *descr= NULL/ Network interfaceif (ntohs (arpheader->htype,==1 & rohs(arpheader>ptype)== CX0E0)[struct ucap pkthdr pkthdr/ Packet informationprintf("Sender MAC:")timestamp;③i2e,,,)*for(1-0, 1<611++)printf("s02K: " arpheader->sha [i])const unsigned char *packet=NULL; / Received rawprintf("\sEnder IP: mfor(=0; 1<4; 1++)printf( sd., arpneader->spa[i1)iarphdr t *arpheader= NULL, / Pointer to the ARPprintf("\target MAC:headerfor(1-0, 1<611++)printf("902K: " arpheader->tha [i])memset(errbuf,0, PCAP ERRBUF S-ZE,;printf("\mArget Ipfor(i=0; i<4: i+-)printf("d " arpreader->tpa[i])if (arccprintf("\n")iprintf ("USAGE: arps- ffer \n")exit(1)i/ Open network device for packe capture *44hakin 9 2/2008www.haking.org/enProgramming with Libpcapthe fact that checksums are coran iP address, checks should CPu time. Capturing everything thatrect does not guarantee that thebe made to ensure that the data flows past the network card couldpacket contains valid headeractually represents a valid IPv4 easily degrade the overall perform-valuesaddressance of our host and cause the kelCheck encoding Http Or Smtpnel to drop packetsare text oriented protocols while Filtering PacketsIf we really need to capture allEthernet or TCP/IP use binary fo As we saw before, the capture proc- traffic, then there is little we can dormat. Check whether you have ess takes place in the kernel while to optimize the capture process, butwhat you expectour application runs at user levif we are only interested in a specificAny data extracted from a packet When the kernel gets a packet fromtype of packets we can tell the kernelfor later use should be validated. the network interface it has to copy to filter the incoming traffic so we justFor example, If the payload of it from kernel space to user space, get a copy of the packets that matcha packet is supposed to contain consuming a significant amount of a filter expression. The part of theListing 4. TCP RST Attack too//A simple TCP RST Attack toolchar errbuf[ PCAP ERRBUF SIZE]memset'errbuf, 0, PCAF ERRDUF SIZE)icp reseprint ("USAGE: tcpsyndcs \n")iI def ne USE BSDUsing ESp Ip headerex⊥t(1)#include / Internet Protocolx Open network device for packet capture *define FAVOR BSD/4 Using EsD ICP headerdescr- pcap open live(argv[ll, MAXBYTES2CAPTURE, 1,512#inclde <,netinet/tcp. h> Transmission. ControlProtocol */* Look up info from the capture device#inc⊥ce/ Lirpcappcap lookupnet( argyll &netaddr, &mask, errbufHfinclace /* String operations/* Compiles the filter expression: Packets with ACK oraCK flags set 7/# incline / Standard librarypcap comp- le(descr, &filter, "(tcp[13]==0x10)ordefinitions ./(tcp[l0x18)",1,mask)define MAXBYTES 2CAPTURE 204 8x Load the lilter program into the packet captureint TCP RST send(tcp seg seg, tcp seg ack, unsignedpcap setiiter (descr, filter)long src ip,unsigned long dst ip, u short src prt u chortwhile(1)[dst prt, u short win)iext( descr, &pth ack))ireturn 0printf: "Seo: u'in", nohl(tcphdr->th seq))iprint:DST IP: s\n", inet r toa(iphdr->ip dst))iprintf: SRC IP: s\1", inet I: tuc(iphir->ip src))iint main(int argc, char xargv[: )Iprintf: "SRC PORT: 9d\n", ntors(tcprdr->th sport))iprintf! "DST PORT %d\n", ntors(tcnrdr->th dport)int count=0printf: n")ibpf 1 int32 netaddr=0, nask=0pcap t *descr- NULLTCP RST send( tcphdr->th ack, 0, iphdr->ip dst. s addrstruct opf program filterstruct ip *iphdstruct tcphar * tcphdrstruct pcap pkthdr pkthdrireturn 0const unsigned char * packet-NULLwww.haking.org/enhakin9 2/200845Attackkernel that provides this functionalitis the system's packet filterAbout the authorA packet filter is basically a userLuis Martin Garcia is a graduate in Computer Science from the University of Salamandefined routine that is called by theca, Spain, and is currently pursuing his Master's degree in Information Security. He isnetwork card driver for every packet also the creator of Aldaba, an open source Port Knocking and Single Packet Authorizathat it gets. If the routine validatestionsystemforGnu/lInux,availableathttp://www.aldabaknocking.comthe packet, it is delivered to our application, otherwise it is only passedto the protocol stack for the usualprocessingOn the netEvery operating system implehttp://www.tcpdumporg/-tcpdumpandlibpcapofficialsitements its own packet filtering mechahttp.://www.stearns.org/doc/pcap-apps.htm/-listoftoolsbasedonlibpcap,nisms. However, many of them arehttp://ftp.gnumonks.org/pub/doc/packet-journey-2.4.htm/-thejourneyofapacketbased on the same architecture thethrough the Linux network stackBSD Packet Filter or BPF. Libpcaphttp://www.tcpdump.org/papers/bpf-usenix93.pdf-paperabouttheBpffilterprovides complete support for BPFwritten by the original authors of libpcap,based packet filters. This includeshttp://www.cs.ucr.edu/-marios/ethereal-tcpdump.pdf-atutorialonlibpcapfilterplatforms like *BSD, AIX, Tru64expressions.Mac Os or Linux On systems thatdo not accept BPF filters, libpcap isnot able to provide kernel level filterpackets with the sYN flag set and char *dev ce, bpf u int32 *netping but it is still capable of selectingwhose destination port is either bpf u int 32 *maskp, char terrbuf)traffic by reading all the packetswill do it for usand evaluating the BPF filters inicmp [icmptypel--icmp-ecorep-yOnce we have a compiled BPFuser-space, inside the library. Thisor icmp[icmmptype]== icmp-echo program we have to insert it intoinvolves considerable computationalreturns ICMP ping requests and the kernel calling the function intoverhead but it provides unmatchedrepliespcap se-filter(pcap t *p,stportabilityether dst 00: 00: 09: c1: 0e: 82 brf program *fp). If everythingeturns Ethernet frames whose goes well we can call pcap loop(Setting a Filterdestination MAC address match- or pcap next( and start grabSetting a filter involves three stepses00:eC:09:c1:0e:82bing packets. Listing 3 shows anconstructing the filter expressionip[81--5 returns packets whose example of a simple applicationcompiling the expression into aP TTL value equals 5hat captures ARP traffic. ListingBPF program and finally applying4 shows a bit more advanced toolthe filterOnce we have the filter expression that listens for TCP packets withBPF programs are written in a we have to translate it into some- the ACK or PSH-ACK flags set andspecial language similar to assem- thing the kernel can understand, resets the connection, resulting in ably. However, libpcap and tcpdump a BPF program. The function int denial of service for everyone in theimplement a high level language pcap compile(pcap t " struct network. Error checks and somethat lets us define filters in a much bpf program Afp, char *str, int portions of code have been omiteasier way. The specific syntax of optimize, bpt u int 32 netmask) ted for clarity. Full examples canthislanguageisoutofthescopecompilesthefilterexpressionbefoundinhttpprogrammingofthisarticleThefullspecificationpointedbystrintoBpfcodeThepcapaldabaknocking.comcan be found in the manual page argument fp is a pointer to a strucfor tcpdump. Here are some ex- ture of type struct hpf program that Conclusionampleswe should declare before the call to In this article we have explored thepcap compile(). The optimize flag basics of packet capture and learnedsrc nost 192.. 1.77 returns controls whether the filter program how to implement simple sniffingpackets whose source IP ad- should be optimized for efficiency applications using the pcap librarydress is192.168.1.77,or not. The last argument is the net- However, libpcap offers additionalcst port 30 returns packets mask of the network on which pack- functionality that has not been covhose TCP/UDP destination port ets will be captured Unless we want ered here(dumping packets to cap-is 80to test for broadcast addresses the ture files, injecting packets, gettingnot tcp Returns any packet that netmask parameter can be safely statistics, etc). Full documentationdoes not use the tCP protocol, set to zero. However, if we need to and some tutorials can be found intcp[13]=- 0x02 and (dst port determine the network mask, thethe pcap man page or at tcpdump's2 or dst port 23) returns TCP function int pcap loocupnet(const official site. o46hakin 9 2/2008www.haking.org/en
用户评论