Sniffer technology principle and application, including programming methods and tools (1) Warton (original) Keyword Sniffer programming tool Ethereal, Sniffer Pro First, I am coming to advertise today :) I haven't updated column for a long time, the key is written What good things, I am afraid that everyone will laugh! Although I haven't been to be over, I have seen others being smashed, hehe. Not to say, this seems to be normal in 9cbs! Today, I put this post, this is a special discussion of the topic development version: http://expert.9cbs.net/EXPERT/topic/2333/2333459.xml? Temp = .3382532, in fact, this post also There is no more in-depth thing, the key is that the topic is very popular. I sent this post to I hope more people can go to the special edition, participate in and organize discussions, but the result is not ideal. Kingzai: Sniffer Chinese translation is an olfactory detector, which is very wide in current network technology. Sniffer can be used as a diagnostic tool for network faults, or as a tool for hacker sniffing and listening. In the last two years, the Sniffer technology has new features. Traditional SNIFFER technology is passively listening to network communication, username, and passwords. The new SNIFFER technology has actively controlled the characteristics of communication data, and the SNIFFER technology is extended to a new field. In addition to the current network detection management, Sniffer technology has also begun to be applied in the field of information preservation. It can be said that Sniffer technology is a double-edged sword, how to better use it, understand some of its characteristics, will make this technology better for us. Sniffer's programming method is relatively universal, 1.WinPCap This is a relatively universal library. I believe that most people don't have to be too unfamiliar. 2.Raw Socket has supported this after 2000. Item features, 2000 Server has a network monitor based on Raw Socket 3.TDI, NDIS, SPI, Hook Socket technology. This technique is relatively large, which can be intercepted instead of just get a copy of the package. In general, it will generally be more than two. I have mentioned one here, but more needs everyone to add. The purpose of this topic is to see everyone to learn together, discuss Sniffer technology, let more people participate, let everyone know that this sector can bring you really want. Warton: libpcap is a good thing, Linux, Windows can be used under Windows, and the security systems such as many intrusion detection are used as the core. But I have never used it, I don't know how it is cross-platform. To use the SPI, look at the XFilter's code and book, especially the book is good, but unfortunately, it has not used it.
Raw Socket writes more than Sniffer, there are also a lot online code! Yesterday I saw 9CBS Home, there were a few articles about Sniffer, preserved, haven't come to see ... I will talk about the current common SNIFFER tools and their technical implementation! Two articles of the 9CBS homepage, everyone can look at it, there is still a few articles, temporarily can't find http://www.9cbs.net/develop/Article/21/21363.shtmhttp://www.9cbs.net /Develop/Article/21/21352.shtmhtp://www.9cbs.net/develop/Article/15/15919.shtmnetsys2: 1) WinPCAP Drive Introduction WinPCAP (Windows Packet Capture) is a Windows Platform next to a free, public network Access system. Developing WinPCap This project is to provide Win32 applications to provide access to the network underlying. It provides the following functions: 1> Capture the original datagram, including the data reported on the shared network and exchange / acceptance between each other; 2> Before the data is reported to the application, according to the custom The rule filters some special datagrams; 3> Send raw datagram on the network; 4> Collect statistics during network communication. The main function of WinPCAP is to send and receive raw datagrams independently of host protocols such as TCP-IP. That is, WinPCAP cannot block, filter or control the sending of other application datagrams, which is just the data report transmitted on the shared network. Therefore, it cannot be used for QoS schedule or personal firewall. At present, the main object developed by WinPCAP is Windows NT / 2000 / XP, which is mainly because only a small portion of the user who uses WinPCap is only using Windows 95/98 / Me, and M $ has also given up the development of Win9x. . Therefore, the programs T-ARP related to this article are also NT / 2000 / XP users. In fact, the concept of 9X system in WinPCap is very similar to the NT system, just a bit difference in some implementation, such as 9X only supports ANSI encoding, and the NT system advises using Unicode encoding. ZZHONG2: There is a software called Sniffer Pro. It can be used for network management software. There are many functions to monitor network operation, data traffic for each network machine, real-time reflecting IP accesses IP and data between each machine. You can capture the filter, you can only grab the filter, such as the POP3 package, SMTP package, FTP package, etc., and can find the mailbox username and password, and FTP username and password. It also You can listen on the network using the switch, but you have to load it on the switch. There is also a simple listener called Passwordsniffer, you can take the mailbox username and password, and the ftp username and password, it can only use Hub The above two software can be uploaded uploaded in Xiaofeng to: http://www.chinesehack.org/warton: Libpcap's latest version is 0.7.2, download a lot (Linux / UNIX) WinPCAP's latest version is 3.0 Sourcecodes with WinPCAP: http: //download.pchome.net/php/dl.php? SID = 11474 Famous Software TCPDUMP and IDS Snort are based on libpcap, and the NMAP scanner is also libppcap to capture the target. The packet returned by the host. WinPCap provides two different levels of programming interfaces: a libpcap-based WPCAP.DL and the other is a lower packet.dll. For the general development of libpcap-compatible development with UNIX platforms, it is of course selection.
The following libraries are related to LIPCAP: libnet1.0.2: Send a construction process of packets Libnids: Some frameworks for IDS LIBICMP: ICMP packets handle some famous snifper: TCPDump / Windump: Support multiple UNIX The latter supports Windows. Based on libpCapsniffit: UNIX, Windows, Libpcapngrep: Libpcap, UnixWindows. You can use rule expressions, identify PPP, SLIP, and FDDI packets Snifer Pro / NetXray: Professional protocol analysis tools, is part of the network analysis scheme provided by NAI: IrislanexplorerNetmonitorCommview single-purpose 噢 口 口 口: Winsnifer, typical hacker tool, sniffing and analyzing FTP, POP3, HTTP, ICQ, SMTP, Telnet, IMAP, NNTP, etc. Password Sniffer for NethacKeriii dedicated sniffer: SMB sniffing L0PHTCRACK, SMPRELAYTCP Connection Session Snark: CommView, Iris, JuggerNautssl Snifting: SSLDUMP - SSLV3 / TLS Network Protocol Analysis Tool Ridius 控: A UDP-based argument accounting protocol, RADIUSNIFF is its representative PPTP sniff Controller: Anger, PPTP-SNIFF (Solaris) SNMP: SNMPSNIFF Switching Network Smeraper: etccon synthesis: DSNIFF Other exchange network sniffer: SNARP, Parasite sniffing countermeasures ......... Netsys2 : Guniffer, circulated on the network is a basic prototype: http://asp.6to23.com/nowcan/code/guniffer.zipvoid main (int Argc, char ** argv) {int ererrorcode; char recvbuf [MAX_PACK_LEN] = {0 }; usage (); if (getCmdLine (argc, argv) == CMD_PARAM_HELP) exit (0); // initialize SOCKETWSADATA wsaData; iErrorCode = WSAStartup (MAKEWORD (2,1), & wsaData); CheckSockError (iErrorCode, "WSAStartup" ); Sockraw = socket (AF_INET, SOCK_RAW, IPPROTO_IP); Checksockerror (SockRaw, "Socket"); // Get Native IP Address Char Far Name [MAX_HOSTNAME_LAN]; Ier rorCode = gethostname (name, MAX_HOSTNAME_LAN); CheckSockError (iErrorCode, "gethostname"); struct hostent FAR * pHostent; // Note that the following three, where the first of pHostent assigned a pHostent = (struct hostent *) malloc (sizeof ( Struct hostent); // memory, then let it wait for the return phostent = gethostByname (Name); // value of the gethostByname function, but the gethostbyname function is self-assigned in the function, so the previous sentence is more than, Everything is normal after delete.
But this procedure has no problem with VC6 compile, I don't know why? Perhaps the compiler optimization of VC6 is played. SockAddr_in sa; sa.sin_family = AF_INET; sa.sin_port = HTONS (6000); Memcpy (& sa.sin_addr.s_un.s_addr, phostent-> h_addr_list [0], phostent-> h_length); free (phostent); // due to The statement that allocates the memory has been deleted, so this sentence is also removed, otherwise an error. Thanks to the netizen heyuming to discover this problem. Irrorcode = Bind (SockRaw, (PsockAddr) & sa, sizeof (sa)); checksockerror (iERRORCODE, "Bind"); // Sets Sock_RAW to SiO_RCVALL to receive all IP packets DWORD DWBufferlen [10]; dword dwbufferinlen = 1; DWORD dwBytesReturned = 0; iErrorCode = WSAIoctl (SockRaw, SIO_RCVALL, & dwBufferInLen, sizeof (dwBufferInLen), & dwBufferLen, sizeof (dwBufferLen), & dwBytesReturned, NULL, NULL); CheckSockError (iErrorCode, "Ioctl"); // listening IP packets while (1) {memset (recvBuf, 0, sizeof (recvBuf)); iErrorCode = recv (SockRaw, recvBuf, sizeof (recvBuf), 0); CheckSockError (iErrorCode, "recv"); iErrorCode = DecodeIpPack (recvBuf, iErrorCode) Checksockerror (IrrorCode, "decode");}} It has 2 inconvenienties: 1) Cannot Select NIC 2) Read the data with dead loop mode, adapted to Windows window mode, there is a standing feel. Sevencat (): The last time I found some information, but the popularity is not prosperous, and I have been busy recently. I haven't going it yet. Http://expert.9cbs.net/expert/topic/2299/2299615.xml?temp =.2761499windows network package filtering technology (original: http://www.ndis.com/papers/winpktfilter.htm) 1, User -Mode network package filter 1, Winsock layered Service Provider refers to the documentation and examples on Microsoft Platform SDK (http://www.microsoft.com/msdownload/platformsdk/sdkupdate/) There are several Microsoft LSP examples, the latest (possibly The most bug-free is often found here. It is necessary to call the core TCPIP driver via TDI, and you can freely bypass Winsock, which is not a problem in most cases. For example: QoS implementation can be on the Winsock LSP. However, if this is done, the program must check and operate each package, and cannot rely on Winsock LSP, they have to be implemented in a way to the core state.
2, WIN2000 package filter interface WIN2000 packet filter interface provides a mechanism, which allows user programs or services to specify a series of "filtration principles", which will be implemented by low-level TCPIP. This filter is mainly Pass or DROP operations for the IP origin address, target address, port number (or port number range). Windows Developer's Journal "packet filtering with iphlpapi.dll" Author: Ton plooy, October, 2000, Volume 11, Number 10. Win2000 provides a better programmable control for TCPIP, including packet filtering. Unfortunately, the documentation about this new API is not easy to find. This article demonstrates how to block the package for a particular IP address or a specific TCP port. Link: www.wdj.com The top of this example download: ftp://ftp.wdj.com/pub/webzip/1110/plooy.ziphollis solution: HTS W2K iPhook example demonstrates IP filtering and its hook API, Contains original files, and free, you need HTSCPP runtime libraries (free), download address: http://www.hollistech.com/3 ,winsock replacing DLL before using Winsock LSP, the only way is to use your own DLL Replacing Microsoft's Winsock DLL, if you have achieved smooth, your own DLL will receive the user's Winsock call request, and then call the original Winsock DLL to process. However, this is relatively laborious, with some difficulty is that Microsoft's Winsock DLL often has some unapproved internal functions, and a Winsock instead of at least some of the unusfined functions of at least the DLL. With the changes in the Windows system structure, some aspects have been strengthened, such as system file protection, which makes this technique becomes less feasible. In general, the use of Winsock DLL is not a bad idea. (Xfilter is using this technology, the original code may be circulated online, I have seen it before, Kernel-Mode network package filter 1, Transport Data Interface (TDI) This is mainly a direct TCPIP drive drive One layer of filtering is driven. The TDI drive on WinXP is a traditional NT-style driver that uses IRP-based APIs, there are two methods here. A, IoattachDevicexyz function family using core mode services implements one filtering on TDI. B. Filter the TDI drive IRP DISPATCH table. The IoattachDevicexyz function mentioned in many WinNT driver development. Both techniques need to know the WinNT driver development programming technology, and the TDI function is also quite understanding. 2, NDIS Intermediate Layer (IM) Specifically, see NDIS IM FAQ: http://www.pcausa.com/resources/ndisimfaq.htm3 ,win2000 Filter-Hook Please refer to DDK documentation, there can be only one event in the system. -HOOK exists, which makes this technology have serious restrictions. (Usually seen this is this) 4, Win2000 FireWall-Hook FireWall-Hook Driver function is a little in the document and is not available in some Win2000 versions.
Please refer to Microsoft's related documentation: http://msdn.microsoft.com/library/default.asp? Url = / library / en-us / network / hh / network / firewall_3wfb.asp5, ndis-hooking (Fair firewall is used This technology, according to what I know, although I haven't seen the original code.) NDIS-hooking driver intercepts or calls "hook" some functions exported by NDIS packages. Although it is a little informal from achieving a means, a systematic NDIS-Hooking filter will be very effective. In addition: Ndis-hooking filter drivers have the following benefits: A, easy to install (can be dynamically handled, but sometimes there is a problem, there are some cases now unknown.) B, support dial -ppp adapter. Ndis-hooking technology is very effective and practical under the 98 and ME systems. On these platforms, DDK documents and Provided Services can help you Hook your hook by Ndis Wrapper exported functions. Ndis-hooking technology is equally effective and practical on NT, 2000, and XP. This technique is very similar to the debugger of the core mode. The document supports less, and basically will not be certified by WHQL. PCAUSA provides an example of NDIS PIM driver that can run on an existing WIN platform (from 95 to XP). Address: http://www.pcausa.com/ndispim/default.htm Other: NetWork Actions and Process Information: How many people want to know how to connect between the operation and WIN process (that is, the application) For it, you may want to know which process sends or receives data on a specific IP port. Don't consider whether this technology is useful, or whether it is reliable, we believe that the core mode TCPIP drives the upper filter to handle this problem. The filter drove the lower layer of the TCPIP does not see process information at all. It is important to note that some network service operations generate a new process attach to the system process. In this case process information does not tell us which process is originally generated. Especially in the core mode WIN service (TDI customer), it is necessary to see the following information united State Patent 5,987,611; "System and methodology for managing Internet access on a per application basis for client computers connect to the internet" We I don't know the value of this patent, I don't know if he can use it on the package. For details, please refer to: http://www.uspto.gov/patft/index.htmlwww.pcausa.com=========================== ================= DRVIPFLT specific parses, it is mentioned above (2-3 means this East). Assume that everyone has a certain understanding of the driver framework.
IRP assignment procedure is as follows: NTSTATUS DrvDispatch (IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) {... switch (irpStack-> MajorFunction) {... case IRP_MJ_DEVICE_CONTROL: ioControlCode = irpStack-> Parameters.DeviceIoControl.IoControlCode; switch (ioControlCode) { // ioctl code to start filtering / / This can be sent from the user mode program. / / Directly use Deviceiocontrol this function, just like this, you can call, I think. // deviceioControl (DriveHandle, Start_ip_hook, null, 0, null, 0, & Bytereturned, NULL) case start_ip_hook: {// This should be the most important function. SetFilterFunction (cbFilterFunction); break;} // ioctl to stop filtering case STOP_IP_HOOK: {SetFilterFunction (NULL); break;} // ioctl to add a filter rule case ADD_FILTER: {if (inputBufferLength == sizeof (IPFilter)) {IPFilter * nf; nf = (IPFilter *) ioBuffer; AddFilterToList (nf);} break;} // ioctl to free filter rule list case CLEAR_FILTER: {ClearFilterList (); break;} default: Irp-> IoStatus.Status = STATUS_INVALID_PARAMETER; Break;} Break; ...} setfilterFunction (cbfilterfunction) may be the most important program. The specific is as follows: In fact, this approach is quite registered a callback function in the system. NTSTATUS SetFilterFunction (PacketFilterExtensionPtr filterFunction) {NTSTATUS status = STATUS_SUCCESS, waitStatus = STATUS_SUCCESS; UNICODE_STRING filterName; PDEVICE_OBJECT ipDeviceObject = NULL; PFILE_OBJECT ipFileObject = NULL; PF_SET_EXTENSION_HOOK_INFO filterData; KEVENT event; IO_STATUS_BLOCK ioStatus; PIRP irp; // first obtains a pointer device.
// first of all, we have to get a pointer to IpFilterDriver Device RtlInitUnicodeString (& filterName, DD_IPFLTRDRVR_DEVICE_NAME); status = IoGetDeviceObjectPointer (& filterName, STANDARD_RIGHTS_ALL, & ipFileObject, & ipDeviceObject); if (NT_SUCCESS (status)) {// some initialization, filled Filterdata. // the struct with functions parameters filterData.ExtensionPointer = filterFunction initialize; // we need initialize the event used later by the IpFilterDriver to signal us // when it finished its work KeInitializeEvent (& event, NotificationEvent, FALSE); // this is the most Important registration callback function process. DDK specifically about this is // IOCTL_PF_SET_EXTENSION_POINTER registers filter-hook callback functions to the IP filter driver // to inform the IP filter driver to call those filter hook callbacks for every IP packet // that is received or transmitted. Also, IOCTL_PF_SET_EXTENSION_POINTER Clears Filter-Hook // Callback Functions from The IP Filter Driver. (See it, the last sentence, registering new callback functions, just clearing the original clear, // So there is only one such driver in the system .) // we build the irp needed to establish fitler function of this place is just generating such IRP, not registered irp = IoBuildDeviceIoControlRequest (IOCTL_PF_SET_EXTENSION_POINTER, ipDeviceObject, (PVOID) & filterData, sizeof (PF_SET_EXTENSION_HOOK_INFO), NULL, 0, FALSE, & event , & Iostatus); if (IRP! = Null) {// We send the IRP // This place is true registration.
status = IoCallDriver (ipDeviceObject, irp); // and finally, we wait for "acknowledge" of IpDriverFilter if (status == STATUS_PENDING) {waitStatus = KeWaitForSingleObject (& event, Executive, KernelMode, FALSE, NULL); if (waitStatus =! STATUS_SUCCESS) {}} status = ioStatus.Status; (! NT_SUCCESS (status) if) {}} else {// if we cant allocate the space, we return the corresponding code error status = STATUS_INSUFFICIENT_RESOURCES;!} if (ipFileObject = NULL ) ObdereferenceObject; ipfileObject = null; ipDeviceObject = null;} Else Return status;} // The true filter function is this, which is passed in the earliest IrpDisPatch. // This function is something that the system passes a cladding and package content and packet length. You can do some processing, // If you want this package, return pf_forward, or you don't want to make the package If you return PF_DROP, you will stop it.
// Is not It sounds simple, PF_FORWARD_ACTION cbFilterFunction (IN unsigned char * PacketHeader, IN unsigned char * Packet, IN unsigned int PacketLength, IN unsigned int RecvInterfaceIndex, IN unsigned int SendInterfaceIndex, IN unsigned long RecvLinkNextHop, IN unsigned long SendLinkNextHop) { Ippacket * ipp; TCPHEADER * TCPH; udpheader * udph; int countRule = 0; struct filterlist * aux = first; // We "extract" The ip header ipp = (ippacket *) PacketHeader; // Dprintf ("Source:% x / ndestination:% x / nprotocol:% d ", IPP-> ipSource, IPP-> ipdestination, ipp-> ipprotocol); // TCP -> protocol = 6 // We accept all packets of established connections if (ipp-> ipprotocol == 6) {TCPH = (TCPHEADER *) Packet; // Dprintf ("Flags:% x / n", tcph-> flags); // if we havent the bit syn activate, we pass the packets if (! (TCPH-> FLAGS & 0X02)) Return Pf_forward;} // OtherWise, We Compare the Packet with our rules while (aux! = null) {// Dprintf ("Comparing with rule% d", countrule; // if Protocol is the same .... if (aux-> ipf.protocol == 0 | | Ipp-> ipprotocol == aux-> ipf.protocol) {// we look in source address if (aux-> ipf.sourceIP! = 0 && (ipp-> ipSource & aux-> ipf.sourcemask)! = AUX -> ipf.sourceip) {aux = aux-> next; countrule ; continue;} // WE LOOK IN DESTINATIONIP! = 0 && (ipp-> ipdestination & aux-> ipf.destinationmask )! = Aux-> ipf.destinationip {aux = aux-> next; countrule ; contract,} // if we have a tcp packet, we look in ports // tcp, protocol = 6 if (ipp->
ipprotocol == 6) {if (aux-> ipf.sourcePort == 0 || TCPH-> Sourceport == aux-> ipf.sourceport) {if (aux-> ipf.destinationport == 0 || TCPH-> DestinationPort == aux-> ipf.destinationport) // puerto tcp de do do with the packet if (aux-> ipf.drop) Return PF_DROP; Else Return Pf_forward;}}} // UDP, Protocol = 17 else if (ipp-> ipprotocol == 17) {udph = (udpheader *) packet; if (aux-> ipf.sourcePort == 0 || UDPH-> Sourceport == aux-> ipf.sourceport) {if (AUX-> ipf.destinationport == 0 || UDPH-> DestinationPort == AUX-> ipf.destinationport) {// now we decided what to do with the packet if (aux-> ipf.drop) Return PF_DROP; ELSE Return Pf_forward;}}} else {// for Other Packet We DONT LOOK More and .... // Now We Decided What to do with the packet if (aux-> ipf.drop) Return PF_DROP; Else Return PF_FORWARD;} } // compare With the next rule countrule ; aux = aux-> next;} // we accept all NOT Registered Return PF_FORWARD;} WinPCAP is also used for NDIS, registering yourself as an protocol processed drive. (Can be seen in the driverentry of the original code): The filter section of this drvipflt this code doesn't know if everyone looks familiar, yes, it is the name of the name of the Numege driver development package in a package filter. It seems that foreigners also like to copy everywhere. Ruike: It is special to have a unique closure for WinPCAP, which is really easy to use, but it is really annoying, it is also a deadly defect that is only available for shared Ethernet, For data under exchanging networks, I don't have testing. I have been testing. Under the LAN for use, I can only listen to the data within this network segment, and I can't listen for data from other network segments, unless you put PROBE is connected to the switch before the switch is connected to the switch's console, but that's it is obvious.
Therefore, WinPCAP's application is still very limited! Kingzai: There are also many ways to implement the switching network 1. Place your captains on the gateway or proxy server, which caught the entire LAN. 2. For the switch to implement port mapping, map all the packets of the port to a monitoring machine. 3. Connect a HUB between the switch and the router, so that the data will be sent in a broadcast manner. 4. Implement ARP spoof, that is, the forwarding of the entire package is achieved on your machine, but it will reduce the efficiency of the entire local area network. Warton: Sniffing Countermeasures: Light Sniffing, I talk about the anti-sniffing :) 1. Check if the network card is set to a mixed mode (there are many tools to do, Antisniff, Promiscan, Sentinel, etc. 2. For ETTERCAP switched network sniffer (ARP spoof), it can be used to prevent ARP spoofing from the 3.SSH encryption channel 4.ssl5.vpn6.pgp, etc., this is used to use NIC mixed mode to perform SNIFFER. The software seems to be not too big, so we should consider the feasibility of switched networks: Mac flooding, mac duplicating, arp spoof, etc. It is not easy, welcome to provide interest in providing relevant information, Ha ha! Netsys: Does anyone have used Raw Socket? Although the WinPCP is very large, Raw Socket allows you to directly Socket's native mechanism. In fact, the two issues I mention are very easy to solve. . Netsys2: For some of the mixed mode Sniffer, most of which use the way a special ARP package, the correct NIC does not respond, and the NIC in the mixed mode will respond. Of course, the ARP and IP are in the same level, so you can't complete it with Raw Socket, you need WinPCAP support work.
The following is a part of the code AnsiString msgStatus; extern TArpFuncParam wParams; int BuildARPPacket (PArpPacket ArpPacket, unsigned char * dst_etheraddr, unsigned char * src_etheraddr, int ar_op, unsigned char * ar_sha, unsigned char * ar_sip, unsigned char * ar_tha, unsigned char * ar_tip, unsigned short int ar_hw) {memcpy (& (ArpPacket-> eth_dst_addr), dst_etheraddr, ETH_ADD_LEN); memcpy (& (ArpPacket-> eth_src_addr), src_etheraddr, ETH_ADD_LEN); ArpPacket-> eth_type = htons (ETH_TYPE_ARP); ArpPacket-> ar_hrd = htons (ar_hw); ArpPacket-> ar_pro = htons (ARP_PRO_IP); ArpPacket-> ar_hln = ARP_ETH_ADD_SPACE; ArpPacket-> ar_pln = ARP_IP_ADD_SPACE; ArpPacket-> ar_op = htons (ar_op); memcpy (& (ArpPacket-> ar_sha), ar_sha, ARP_ETH_ADD_SPACE); memcpy (& (ArpPacket-> ar_spa), ar_sip, ARP_IP_ADD_SPACE); memcpy (& (ArpPacket-> ar_tha), ar_tha, ARP_ETH_ADD_SPACE); memcpy (& (ArpPacket-> ar_tpa), ar_tip, ARP_IP_ADD_SPACE); MEMSET (Arppacket-> Eth_Pad, 32, Eth_padding_arp); Return (exit_success);} int OpenAdapt er (LPADAPTER * lpAdapter) {* lpAdapter = PacketOpenAdapter (wParams.AdapterList [wParams.SelectedAdapter]); if ((* lpAdapter) || ((* lpAdapter) -> hFile == INVALID_HANDLE_VALUE)!) {msgStatus = "Error: unable to open the driver ";. SHOWSTAT (msgStatus); return (EXIT_FAILURE);} return (EXIT_SUCCESS);} void CloseAdapter (lPADAPTER lpAdapter) {PacketCloseAdapter (lpAdapter);} void GetLocalMAC (lPADAPTER lpAdapter, unsigned char * ether_addr) { Ulong ioctlbufferLength = (Sizeof) Sizeof (Ulong) - 1); PPACKET_OID_DATA OIDDATA; OIDDATA = (struct _packet_oid_data *) malloc (ioctlbufferlength); Oiddata->
Oid = OID_802_3_CURRENT_ADDRESS; OidData-> Length = 6; if (PacketRequest (lpAdapter, FALSE, OidData) == FALSE) memcpy (ether_addr, 0, 6); else memcpy (ether_addr, OidData-> Data, 6); free (OidData );} int GetARPReply (lPPACKET lpPacket, unsigned char * iptarget, unsigned char * result) {unsigned short int ether_type; unsigned char ipsender [4]; unsigned int off = 0; unsigned int tlen; struct bpf_hdr * hdr; char * pChar Char * BUF; buf = (char *) LPPACKET-> BUFFER; HDR = (struct bpf_hdr *) (BUF OFF); TLEN = HDR-> BH_CAPLEN; OFF = HDR-> BH_HDRLEN; PCHAR = (char *) (BUF OFF); OFF = packet_wordalign (off tlen); Memcpy (Eer_Type, PCHAR 12, 2); Ether_TYPE = NTOHS (Ether_TYPE); if (Ether_TYPE == Eth_Type_arp) {Memcpy (Ipsender, Pchar 28, 4 ); If (iptarget [0] == ipsender [0]) && (iptarget [1] == ipsender [1]) && (iptarget [2] == ipsender [2]) && (iptarget [3] == IpSender [3])) Memcpy (Result, PCHAR 22, 6); ELSE return (EXIT_FAILURE);} else return (EXIT_FAILURE); return (EXIT_SUCCESS);} int CheckPROMode (LPADAPTER lpAdapter, unsigned char * iptarget, unsigned char * remotemac) {LPPACKET lpPacketRequest; LPPACKET lpPacketReply; char buffer [256000]; TArpPacket ArpPacket; unsigned char magicpack [ETH_ADD_LEN] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE}; unsigned char mactarget [ARP_ETH_ADD_SPACE]; DWORD timestamp = 0; int numPacks = 0; / * Init fields * / memset (mactarget, 0, 6); / * Allocate Packet Structure for ARP Request Packet * / IF ((LPPACKETREQUEST =
PacketAllocatePacket ()) == NULL) {msgStatus = "Error: failed to allocate the LPPACKET structure .."; SHOWSTAT (msgStatus); return (EXIT_FAILURE);} / * Init packet structure * / memset (& ArpPacket, 0, sizeof ( TArpPacket)); / * Build ARP Request packet * / BuildARPPacket (& ArpPacket, magicpack, wParams.srcMAC, ARP_OP_REQUEST, wParams.srcMAC, wParams.srcIPAdd, mactarget, iptarget, wParams.ar_hw); / * Init ARP Request packet * / PacketInitPacket (lpPacketRequest, & ArpPacket, sizeof (ArpPacket)); / * Set number of ARP Request packets to send * / if (PacketSetNumWrites (lpAdapter, 1) == FALSE) {msgStatus = "Warning: unable to send more than one packet in a single write .. "; SHOWSTAT (msgStatus);} / * Set hardware filter to directed mode * / if (PacketSetHwFilter (lpAdapter, NDIS_PACKET_TYPE_DIRECTED) == FALSE) {msgStatus =" Warning: unable to set directed mode .. "; SHOWSTAT (msgstatus);} / * set a 512k buffer in the driver * / if (PacketSetBuff (lPadapter, 512000) == false {MsgStatus = "Error: unable to set the kernel buffer .."; SHOWSTAT (msgStatus); PacketFreePacket (lpPacketRequest); return (EXIT_FAILURE);} / * Set a 1 second read timeout * / if (PacketSetReadTimeout (lpAdapter, -1 ) == FALSE) {msgStatus = "Warning: unable to set the read tiemout .."; SHOWSTAT (msgStatus);} / * Allocate PACKET structure for ARP Reply packet * / if ((lpPacketReply = PacketAllocatePacket ()) == NULL ) {Msgstatus = "error: failed to allocate the lppacket structure .."; showst (msgstatus); packetfreepacket; return (exit_failure);
} / * Init ARP reply packet * / packetinitpacket (lppacketreply, (char *) Buffer, 256000); / * allocate memory for remote mac address * / timestamp = gettickcount (); / * main capture loop * / for (;;) {if (numPacks