Category: Network

Network Grep for the Folks Who Love to Grep!

Network grep (ngrep) is a great program that allows you to search and filter network packets rather quickly. There is some resemblance to the well-known Linux grep program. Ngrep can analyze live traffic or saved pcaps. The man pages for ngrep are rather straightforward. Ngrep currently recognizes IPv4/ 6, TCP, UDP, ICMPv4/6 and IGMP. The program also understands regular and hex expressions, which is a huge benefit. In the simplest terms, ngrep applies the most common features of grep at the network layer. A few key switches that I will typically use are below but a full list can be found on the man pages.

-q | Will ‘quiet’ the output by printing only packet headers and relevant payloads
-t | Print the timestamp every time there is a match
-i | Ignore case
-I | Read in saved pcap
-w | Expression must match word – regex
-W byline | Linefeeds are printed as linefeeds, making the output pretty and more legible
-s | Set BPF capture length

Below are a few examples of common usages of ngrep.

This command will query all interfaces and protocols for a string match of ‘HTTP’.

If you have a network capture file in .pcap format, use -I $FILE to filter the capture instead of a network interface. This can be handy, for example, if you have a record of a networking event and you need to do a quick analysis.

Reverse of the above command, using only the -O flag will filter against a network interface and copy the matched packets into a capture file in .pcap format.

Search for .exe

Monitor for current email transactions and print the addresses.

This will grab the password and username of all ftp sessions.

Capture network traffic incoming to eth0 interface and show parameters following HTTP GET or POST methods

Monitor all traffic on your network using port 80 with a source IP of 12.34.56.78

Monitor all traffic on your network using port 80 with a source IP of 12.34.56.78 and destination of 98.76.54.32

Search the word “login” tranversing port 23 using regex

The match expression can be combined with a pcap filter. For example, suppose we wanted to look for DNS traffic mentioning cyberfibers.com

Berkley packet filter (bpf) adds to the flexibility of ngrep. Bpf specifies a rich syntax for filtering network packets based on information such as IP address, IP protocol, and port number.

IP address

IP protocol

Port number

For even more granularity, you can combine primitives using boolean connectives and, or and not to really specify what your looking for.