Brewing up an Intrusion Detection System

It is east to build your own IDS Let us examine how to write our own packet capture and injection engine from scratch. Once we know the basics of how we can "see" physical packet headers then we can apply filters, selectively modify or inject packets than we essentially have our own home brewed IDS! That is essentially the essence of an IDS-to read and examine packets arriving and departing at the network interface, apply rules/filters and allow only selected ones to pass and hold the others. We will look at two complementing network libraries libpcap and libnet that make our job all the more easier.

Packet Capture --Libpcap

The Libpcap packet capture library provides access to the OS's underlying packet capture facility in an implementation-independent way. Packet capture allows us to intercept any raw packet that is seen by the network device, and grab it in its entirety. To examine it the developer can systematically strip off the Ethernet header, the IP header, UDP header, etc until the payload itself can be viewed.

A very simple IDS sample code is provided in the downloads section. There are three key functions in the packet capture code. The following pcap_loop function:
* int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
will grab cnt packets and pass them to the callback function which is of type pcap_handler. The callback function
typedef void (*pcap_handler)(u_char *, const struct pcap_pkthdr *, const u_char *);
is called with the raw packet and is where the actual discection is performed. The netinet/if_ether.h ethernet header file and netinet/ip.h is used to strip off ethernet, IP, UDP/TCP headers etc one by one. It also provides API to convert the headers to a readable form and back. The pcap_compile(..) and pcap_setfilter(...) will allow us to accept a string from the user, (similar to tcpdump) compile it and sets it as a filter. This allows us to formulate IDS rules that allow us to check which traffic is legitimate and which is not.

Second half of story --Libnet

Simple Packet capturing is good as long as you want your tool to work as a silent network sentinel. However almost every IDS has the power to maniplulate and inject packets as well. Announcing libnet - a generic networking API that provides access to several network protocols. It provides very basic packet injection functionality and does not support complicated features such as streaming via TCP/IP. However its basic datagram/udp functions are sufficent for an IDS that typically works at a layer below the Transport layer. In short it provides a portable framework for low-level network packet writing and handling and includes packet creation at the IP layer and at the link layer as well as a host of supplementary functionalty.
libnet_init_packet_arena, libnet_build_ip, libnet_do_checksum and libnet_write_ip
are examples of the easy-to-use packet construction toold that libnet provides.