分类:
2007-08-20 21:51:27
if you deal with network administration or security management, or if you are merely curious about what is passing by over your local network, grabbing some packets off the network card can be a useful exercise. with a little bit of c coding and a basic knowledge of networking, you will be able to capture data even if it is not addressed to your machine. in this article, we will refer to ethernet networks, by far the most widespread lan technology. also, for reasons that will be explained later, we will assume that source and destination hosts belong to the same lan.
first off, we will briefly recall how a common ethernet network card works. those of you who are already skilled in this field may safely skip to the next paragraph. ip packets sourced from users' applications are encapsulated into ethernet frames (this is the name given to packets when sent over an ethernet segment), which are just bigger lower-level packets containing the original ip packet and some information needed to carry it to its destination (see figure 1). in particular, the destination ip address is mapped to a 6-byte destination ethernet address (often called mac address) through a mechanism called arp. thus, the frame containing the packet travels from the source host to the destination host over the cable that connects them. it is likely that the frame will go through network devices such as hubs and switches, but since we assumed no lan borders are crossed, no routers or gateways will be involved.
no routing process happens at the ethernet level. in other words, the frame sent by the source host will not be headed directly toward the destination host; instead, the frame will be copied over all the cables that make up the lan, and all the network cards will see it passing (see figure 2). each network card will start reading the first six bytes of the frame (which happen to contain the above-mentioned destination mac addresses), but only one card will recognize its own address in the destination field and will pick up the frame. at this point, the frame will be taken apart by the network driver and the original ip packet will be recovered and passed up to the receiving application through the network protocol stack.
more precisely, the network driver will have a look at the protocol type field inside the ethernet frame header (see figure 1) and, based on that value, forward the packet to the appropriate protocol receiving function. most of the time the protocol will be ip, and the receiving function will take off the ip header and pass the payload up to the udp- or tcp-receiving functions. these protocols, in turn, will pass it to the socket-handling functions, which will eventually deliver packet data to the receiving application in userland. during this trip, the packet loses all network information related to it, such as the source addresses (ip and mac) and port, ip options, tcp parameters and so on. furthermore, if the destination host does not have an open socket with the correct parameters, the packet will be discarded and never make it to the application level.
as a consequence, we have two distinct issues in sniffing packets over the network. one is related to ethernet addressing--we cannot read packets that are not destined to our host; the other is related to protocol stack processing--in order for the packet not to be discarded, we should have a listening socket for each and every port. furthermore, part of the packet information is lost during protocol stack processing.
the first issue is not fundamental, since we may not be interested in other hosts' packets and may tend to sniff all the packets directed to our machine. the second one, however, must be solved. we will see how to address these issues separately, starting with the latter.
when you open a socket with the standard call sock = socket(domain, type, protocol) you have to specify which domain (or protocol family) you are going to use with that socket. commonly used families are pf_unix, for communications bounded on the local machine, and pf_inet, for communications based on ipv4 protocols. furthermore, you have to specify a type for your socket and possible values depend on the family you specified. common values for type, when dealing with the pf_inet family, include sock_stream (typically associated with tcp) and sock_dgram (associated with udp). socket types influence how packets are handled by the kernel before being passed up to the application. finally, you specify the protocol that will handle the packets flowing through the socket (more details on this can be found on the socket(3) man page).
in recent versions of the linux kernel (post-2.0 releases) a new protocol family has been introduced, named pf_packet. this family allows an application to send and receive packets dealing directly with the network card driver, thus avoiding the usual protocol stack-handling (e.g., ip/tcp or ip/udp processing). that is, any packet sent through the socket will be directly passed to the ethernet interface, and any packet received through the interface will be directly passed to the application.
the pf_packet family supports two slightly different socket types, sock_dgram and sock_raw. the former leaves to the kernel the burden of adding and removing ethernet level headers. the latter gives the application complete control over the ethernet header. the protocol field in the socket() call must match one of the ethernet ids defined in /usr/include/linux/if_ether.h, which represents the registered protocols that can be shipped in an ethernet frame. unless dealing with very specific protocols, you typically use eth_p_ip, which encompasses all of the ip-suite protocols (e.g., tcp, udp, icmp, raw ip and so on).
since they have pretty serious security implications (for example, you may forge a frame with a spoofed mac address), pf_packet-family sockets may only be used by root.
the pf_packet family easily solves the problem associated with protocol stack-handling of our sniffed packets. let's see it do so with the example in listing 1. we open a socket belonging to the pf_packet family, specifying a sock_raw socket type and ip-related protocol type. then we start reading from the socket and, after a few sanity checks, we print out some information extracted from the ethernet level and ip level headers. by cross-checking the printed addresses with the offsets in figure 1, you will see how easy it is for the application to get access to network level data.
assuming that your machine is connected to an ethernet lan, you can experiment with our short example by running it while generating packets directed to your host from another machine (you can ping or telnet to your host). you will be able to see all the packets directed to you, but you will not see any packet headed toward other hosts.
the pf_packet family allows an application to retrieve data packets as they are received at the network card level, but still does not allow it to read packets that are not addressed to its host. as we have seen before, this is due to the network card discarding all the packets that do not contain its own mac address--an operation mode called nonpromiscuous, which basically means that each network card is minding its own business and reading only the frames directed to it. there are three exceptions to this rule: a frame whose destination mac address is the special broadcast address (ff:ff:ff:ff:ff:ff) will be picked up by any card; a frame whose destination mac address is a multicast address will be picked up by cards that have multicast reception enabled and a card that has been set in promiscuous mode will pick up all the packets it sees.
the last case is, of course, the most interesting one for our purposes. to set a network card to promiscuous mode, all we have to do is issue a particular ioctl() call to an open socket on that card. since this is a potentially security-threatening operation, the call is only allowed for the root user. supposing that ``sock'' contains an already open socket, the following instructions will do the trick:
strncpy(ethreq.ifr_name,"eth0",ifnamsiz);
ioctl(sock, siocgifflags, ðreq);
ethreq.ifr_flags |= iff_promisc;
ioctl(sock, siocsifflags, ðreq);
(where ethreq is an ifreq structure, defined in /usr/include/net/if.h). the first ioctl reads the current value of the ethernet card flags; the flags are then ored with iff_promisc, which enables promiscuous mode and are written back to the card with the second ioctl.
let's see it in a more complete example (see listing 2 at ). if you compile and run it as root on a machine connected to a lan, you will be able to see all the packets flowing on the cable, even if they are not for your host. this is because your network card is now working in promiscuous mode. you can easily check it out by giving the ifconfig command and observing the third line in the output.
note that if your lan uses ethernet switches instead of hubs, you will see only packets flowing in the switch's branch you belong to. this is due to the way switches work, and there is very little you can do about it (except for deceiving the switch with mac address-spoofing, which is outside the scope of this article). for more information on hubs and switches, please have a look at the articles cited in the resources section.
all our sniffing problems seem to be solved right now, but there is still one important thing to consider: if you actually tried the example in listing 2, and if your lan serves even a modest amount of traffic (a couple of windows hosts will be enough to waste some bandwidth with a good number of netbios packets), you will have noticed our sniffer prints out too much data. as network traffic increases, the sniffer will start losing packets since the pc will not be able to process them quickly enough.
the solution to this problem is to filter the packets you receive, and print out information only on those you are interested in. one idea would be to insert an ``if statement'' in the sniffer's source; this would help polish the output of the sniffer, but it would not be very efficient in terms of performance. the kernel would still pull up all the packets flowing on the network, thus wasting processing time, and the sniffer would still examine each packet header to decide whether to print out the related data or not.
the optimal solution to this problem is to put the filter as early as possible in the packet-processing chain (it starts at the network driver level and ends at the application level, see figure 3). the linux kernel allows us to put a filter, called an lpf, directly inside the pf_packet protocol-processing routines, which are run shortly after the network card reception interrupt has been served. the filter decides which packets shall be relayed to the application and which ones should be discarded.
in order to be as flexible as possible, and not to limit the programmer to a set of predefined conditions, the packet-filtering engine is actually implemented as a state machine running a user-defined program. the program is written in a specific pseudo-machine code language called bpf (for berkeley packet filter), inspired by an old paper written by steve mccanne and van jacobson (see resources). bpf actually looks like a real assembly language with a couple of registers and a few instructions to load and store values, perform arithmetic operations and conditionally branch.
the filter code is run on each packet to be examined, and the memory space into which the bpf processor operates are the bytes containing the packet data. the result of the filter is an integer number that specifies how many bytes of the packet (if any) the socket should pass to the application level. this is a further advantage, since often you are interested in just the first few bytes of a packet, and you can spare processing time by avoiding copying the excess ones.
even if the bpf language is pretty simple and easy to learn, most of us would probably be more comfortable with filters written in human-readable expressions. so, instead of presenting the details and instructions of the bpf language (which you can find in the above-mentioned paper), we will discuss how to obtain the code for a working filter starting from a logic expression.
first, you will need to install the tcpdump program from lbl (see resources). but, if you are reading this article, it is likely that you already know and use tcpdump. the first versions were written by the same people who wrote the bpf paper and its first implementation. in fact, tcpdump uses bpf, in the form of a library called libpcap, to capture and filter packets. the library is an os-independent wrapper for the bpf engine. when used on linux machines, bpf functions are carried out by the linux packet filter.
one of the most useful functions provided by the libpcap is pcap_compile(), which takes a string containing a logic expression as input and outputs the bpf filter code. tcpdump uses this function to translate the command-line expression passed by the user into a working bpf filter. what is interesting for our purposes is that tcpdump has a seldomly used switch, -d, which prints the code of the filter.
for example, typing tcpdump host 192.168.9.10 will start sniffing and grab only those packets whose source or destination ip address matches 192.168.9.10. typing tcpdump -d host 192.168.9.10 will print the bpf code that recognizes the filter, as shown in listing 3.
let's briefly comment on this code; lines 0-1 and 6-7 verify that the captured frame is actually transporting ip, arp or rarp protocols by comparing their protocol ids (see /usr/include/linux/if_ether.h) with the value found at offset 12 in the frame (see figure 1). if the test fails, the packet is discarded (line 13).
lines 2-5 and 8-11 compare the source and destination ip addresses with 192.168.9.10. note that, depending on the protocol, the offsets of these addresses are different; if the protocol is ip, they are 26 and 30, otherwise they are 28 and 38. if one of the addresses matches, the packet is accepted by the filter, and the first 68 bytes are passed to the application (line 12).
the filter code is not always optimized, since it is generated for a generic bpf machine and not tailored to the specific architecture that runs the filter engine. in the particular case of the lpf, the filter is run by the pf_packet processing routines, which may have already checked the ethernet protocol. this depends on the protocol field you specified in the initial socket() call: if it is not eth_p_all (which means that every ethernet frame shall be captured), then only frames having the specified ethernet protocol will arrive at the filter. for example, in the case of an eth_p_ip socket, we could rewrite a faster and more compact filter as follows:
(000) ld [26]
(001) jeq #0xc0a8090a jt 4 jf 2
(002) ld [30]
(003) jeq #0xc0a8090a jt 4 jf 5
(004) ret #68
(005) ret #0
installing an lpf is a straightforward operation: all you have to do is create a sock_filter structure containing the filter and attach it to an open socket.
the filter structure is easily obtained by substituting the -d switch to tcpdump with -dd. the filter will be printed as a c array that you can copy and paste into your code, as shown in listing 4. afterward, you attach the filter to the socket by simply issuing a setsockopt() call.
we will conclude this article with a complete example (see listing 5 at ). it is exactly like the first two examples, with the addition of the lsf code and the setsockopt() call. the filter has been configured to select only udp packets, having either source or destination ip address 192.168.9.10 and source udp port equal to 5000.
in order to test this listing, you will need a simple way to generate arbitrary udp packets (such as sendip or apsend, found on ). also, you may want to adapt the ip address to match the ones used in your own lan. to accomplish this, just substitute 0xc0a8090a in the filter code with the ip address of your choice in hex notation.
a final remark concerns the status of the ethernet card when you exit the program. since we did not reset the ethernet flags, the card will remain in promiscuous mode. to solve this problem, all you need to do is install a control-c (sigint) signal handler that resets the ethernet flags to their previous value (which you will have saved just before oring with iff_promisc) before exiting the program.
sniffing packets over your lan is an invaluable tool for debugging network problems or collecting measurements. sometimes the commonly available tools, such as tcpdump or ethereal, will not exactly fit your needs and writing your own sniffer can be of great help. thanks to the lpf, you can do this in a simple and efficient way.
from: