The tcpdump command is also called a packet sniffer.

The tcpdump command will work on most flavors of the UNIX operating system. tcpdump allows you to save captured packets so that we can use the captured packet for further analysis. The saved file can be viewed with the same tcpdump command. We can also use software open source code like Wireshark to read tcpdump PCAP files.

In this lesson, we will look at some practical examples of how to use the tcpdump command.

1. Capture packets from a specific ethernet interface using tcpdump -i

When executing the tcpdump command without any option, it will capture all packets passing through all interfaces. Option -i tcpdump command allows you to filter on a specific ethernet interface.

$ tcpdump -i eth1 12:59:41.967250 ARP, Request who-has free.msk.ispsystem.net tell gw.msk.ispsystem.net, length 46 12:59:41.967257 ARP, Request who-has reserve.scoffserver.ru tell gw.msk.ispsystem.net, length 46 12:59:41..44141 > wdc-ns1.ispsystem.net.domain: 14799+ PTR? 184.48.146.82.in-addr.arpa. (44) ...

In this example, tcpdump captures all stream packets on interface eth1 and displays them on standard output.

Note:

The Editcap utility is used to select or remove specific packages from a dump file and translate them into a given format.

2. Capture only N number of packets with tcpdump -c

Running the tcpdump command gives packets until you cancel the tcpdump command. Using the option -c you can specify the number of packets to capture.

$ tcpdump -c 2 -i eth0 listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes 13:01:35.165898 ARP, Request who-has 213.159.211.80 tell gw.msk.ispsystem.net, length 46 13 :01:35..35123 > wdc-ns1.ispsystem.net.domain: 7254+ PTR? 80.211.159.213.in-addr.arpa. (45) 2 packets captured 7 packets received by filter 0 packets dropped by kernel

tcpdump command captured only 2 packets from interface eth0.

Note:

Mergecap and TShark: Mergecap is a package dump merge tool that will merge multiple packages into a single dump file. Tshark is a powerful network packet capture tool that can be used to analyze network traffic. It comes with a Wireshark network distribution analyzer.

3. Display captured packets in ASCII using tcpdump -a

The following tcpdump syntax prints a packet in ASCII.

$ tcpdump -A -i eth0 13:03:06.516709 IP 213.132.93.178..vlsi-lm: Flags [.], ack 3120779210, win 254, length 0 E..( [email protected]]......b...%.=...O.P....... 13:03:06..35313 > wdc-ns1.ispsystem.net.domain: 13562+ PTR? 178.93.132.213.in-addr.arpa. (45) [email protected]@........x.....5.5, seq 3666073194:3666074622, ack 3281095139, win 2000, options , length 1428

This is a TCP packet, the format of information about which is presented in tcpdump is as follows (fields are separated by commas):

  • flags - set flags. Denoted by the symbols S (SYN), F (FIN), P (PUSH) and R (RST), a dot means no flags set;
  • data-seqno - describes the data contained in the packet in the following format: first:last, where first and last are the sequence number of the first and last byte of the transmitted data, nbytes;
  • ack - next sequence number (ISN + 1);
  • window - window size;
  • options - additional information can be specified here, for example ( maximum size segment);
  • length - the length of the packet.

All this data can be very useful while studying or debugging protocols and network applications, but they do not tell us anything about its contents. To see the contents of the package in hexadecimal format, use the -X flag:

# tcpdump -i wlan0 -c 10 -n -X host 192.168.0.1 and port 80

This function is very useful for parsing protocols in which data is transmitted in clear text, such as HTTP. For binary protocols and protocols with encryption, it will, of course, be useless.
You can also use the -v flag to get more information about a package. Then after the IP in brackets will appear detailed information about IP packet:

(tos 0x0, ttl 64, id 8339, offset 0, flags , proto UDP(17), length 51)

In general, everything here is quite prosaic. First comes the type of service (TOS), followed by packet time to live (TTL), packet identifier, offset from the start of the first packet in the chain, flags, transport layer protocol used (TCP, UDP, ICMP), and length.


Advanced Features

We have already covered most of the most important features of tcpdump, but its functionality is much wider. For example, we used the host and port statements to specify the address and port we want to filter the output, but what if we only want to see packets going to the specified address, but not outgoing from it? You can use the src operator for this:

# tcpdump -i wlan0 -c 10 -n src 192.168.0.1

There is also its reverse version dst, designed to indicate the destination address. As shown above, all operators can be combined using the and operator (monitoring network traffic, excluding SSH sessions and DNS requests):

# tcpdump -i wlan0 port not 22 and port not 53

You can also use or (or) and except (not). Also, tcpdump understands port ranges:

# tcpdump -i wlan0 -c 10 -n portrange 21-23

Able to filter packets by their size:

# tcpdump -i wlan0 -c 10 -n > 32 and<= 128

And understands subnet masks:

# tcpdump -i wlan0 c 10 -n src net 192.168.0.0/16 and dst net 10.0.0.0/8 or 172.16.0.0/16

One of the most interesting features of tcpdump is the ability to filter packets based on the content of specific bits or bytes in the protocol headers. For this, the following format is used: proto, where proto is the protocol, expr is the offset in bytes from the beginning of the packet header, and size is an optional field indicating the length of the data in question (default is 1 byte). For example, to filter only packets with the SYN flag (TCP handshake initiation) set, you would use the following entry:

# tcpdump "tcp==2"

How it works? Very simple. The 13 bytes of the TCP header contain exactly eight flags, one bit each. The second bit is reserved for the SYN flag. The above entry simply checks to see if this bit is set. By the way, a more readable form of this entry would look like this:

# tcpdump "tcp & tcp-syn != 0"

Practical use

The tcpdump utility is commonly used for two purposes: to debug the network, network applications, and new protocols, and to teach you the basics of TCP/IP. We will go the other way and use the power of tcpdump to detect host scans and network attacks.

On fig. Figure 1 shows what a classic TCP port scan done by Nmap looks like in tcpdump logs. You can clearly see how Nmap from the address 192.168.0.100 tries to establish a TCP connection with different ports by sending a SYN packet (S in the flags field). First, port 8888 is probed, an RST packet comes in response, which means that no service is listening on the port, then port 587 is probed with the same result. Finally, Nmap sends a SYN packet to port 22 (SSH) and receives a response in the form of a SYN-ACK packet:

192.168.0.100.43337 > 192.168.0.111.22: Flags[S], seq 2610024277, ... 43337 > 192.168.0.111.22: Flags [.], ack 1, ...

The port is open and now Nmap can successfully close the connection by sending an RST packet and move on to the next ports. However, it does something smarter: it sends an acknowledgment of receipt of the ACK packet and immediately moves on to the next ports. This behavior allows you to bypass some intrusion detection systems, but you can’t easily fool a person armed with a sniffer.

Pay attention also to the numbers of ports to be sorted out, they are not generated randomly, but are selected taking into account the greatest prevalence. This means that a fast scan is being performed, or more specifically, Nmap is most likely running without any flags at all.



Now let's look at another method for detecting open ports - SYN scanning (nmap -sS). This type of scan is usually called hidden, because during it a full TCP connection is never established, which means that information about the fact of the connection is not included in the logs. The tcpdump output for this kind of scan is shown in Figure 1. 2. It is very similar to the log of a regular TCP scan, however, the scanner's reaction to open ports now another one:

192.168.0.100.48585 > 192.168.0.111.22: Flags[S], seq 1679394613, ... 48585 > 192.168.0.111.22: Flags[R], seq 1679394614, ...

It can be seen that after receiving the SYN-ACK approval packet, the scanner does not complete the connection, but immediately terminates it, avoiding getting into the logs. On fig. 3 you can see the result of the UDP scan. Everything is very simple here, Nmap enumerates ports with possible UDP services, sending a packet of zero length to each of them. If the port is closed, the OS sends back an ICMP unreachable message:

16:41:48.798310 IP 192.168.0.100.61020 > 192.168.0.111.18869: UDP, length 0

Otherwise, the port is considered open. Another scanning method is null scanning by sending packets with no flags set (nmap -sN). The reaction to such packets may vary depending on the operating system, but as you can see from the following listing, Linux responds to them by sending RST packets:

192.168.0.100.39132 > 192.168.0.111.256: Flags , win 3072, length 0 192.168.0.111.256 > 192.168.0.100.39132: Flags , ...

An attacker can also use Xmas scanning, in which packets have the FIN, URG and PUSH flags set (the packet seems to glow with flags like a Christmas tree):

192.168.0.100.35331 > 192.168.0.111.5544: Flags , seq 3998959601, win 4096, urg 0, length 0

As you can see, the reaction to such packages is identical. An ACK scan (-sA) will appear in the tcpdump logs as sending multiple packets with the ACK flag set and responding to them by sending RST packets. However, if a firewall is installed on the system, there will be no response messages, and Nmap will be able to understand if the port is being filtered.

With tcpdump, you can also trace and different kinds flood. For example, a classic ICMP flood in the logs will look like this:

16:43:06.008305 IP 192.168.0.100 > 192.168.0.111: ICMP type-#68, length 1032 192.168.0.100 > 192.168.0.111: ICMP type-#183, length 1032 16:43:06.008831

Of particular importance here is the field containing the time the packet was received. No normal application will send many ICMP messages in a period of time equal to one thousandth of a second. Other types of flood (eg SYN) are defined in exactly the same way.

Interaction with other programs

One of the most important advantages of tcpdump is that the format of its reports during the existence of the program has actually become the standard for all sniffers and today it is understood by all more or less serious traffic analysis tools. For example, tcpdump can be used to generate a dump on a remote machine, then send it to the local machine and parse it with wireshark:

$ ssh [email protected] tcpdump -w - "port !22" | wireshark -k -i -

Here we used the -w - option to write the dump to stdout and redirected it to wireshark running on the local machine. In the same way, you can analyze traffic using snort:

$ ssh [email protected]"tcpdump -nn -i eth1 -w -" | snort -c /etc/snort/snort.conf -r -

By redirecting the program's output to grep's input, one can find various problems in network operation, for example, to detect packets with an incorrect checksum, information about which can be displayed using the -vv flag:

# tcpdump -nnvv -r dump.cap tcp | grep -v "tcp sum ok" | wc-l

Admin stuff

The ability to filter packets based on header data, which we discussed at the beginning of the first section, is very useful for debugging various protocols and finding network problems. For example, we can use it to catch network packets transmitted over the Cisco Discovery Protocol, through which Cisco routers exchange information about the topology and network status:

# tcpdump -nn -v -i eth0 -s 1500 -c 1 "ether == 0?2000"

In the same way, you can catch all packets transmitted via the DHCP protocol (DISCOVER, REQUEST, INFORM) in order to identify client connection problems:

# tcpdump -i eth0 -vvv -s 1500 "((port 67 or port 68) and (udp = 0x1))"

Or catch packets sent as part of POP3 authentication:

# tcpdump -i eth0 "tcp port pop3 and ip = 85 and ip = 83" -s 1500 -n

network grep

The tcpdump sniffer is good for its versatility and variety of capabilities, but it is not so easy and convenient to use it to search for specific data inside transmitted packets. This task is much better handled by ngrep, which is designed to display passing network packets that match a given mask.

For example, to find the parameters passed GET methods and POST within an HTTP session, you can use the following command:

# ngrep -l -q -d eth0 "^GET |^POST " tcp and port 80

Finding the slackers:

# ngrep -i "game*|p0rn|adult" -W byline -d eth0 > slackers.txt

We analyze SMTP traffic on all network interfaces:

# ngrep -i "rcpt to|mail from" tcp port smtp

tcpdump options

A table of the most interesting and useful tcpdump flags.

  • -i [interface] - the network interface to listen on, specify any for all.
  • -n Do not resolve IP addresses to DNS names.
  • -nn Do not translate IP addresses and port numbers.
  • -X - show package contents in text and hexadecimal formats.
  • -XX - the same plus the contents of the Ethernet frame.
  • -v, -vv, -vvv - increase the amount of information and packages shown (more, more, everything).
  • -c [n] Show only the first n packets.
  • -s [n] - number of bytes displayed for each packet (can be reduced for readability or increased for more information).
  • -S - show absolute TCP sequence numbers.
  • -e - show ethernet frame headers.
  • -q - show less information (for readability).
  • -E - decrypt IPsec traffic using the specified key.
  • -w - save program dump to file, argument - used to specify stdout.

conclusions

In the hands of a knowledgeable user, tcpdump turns into a powerful tool not only for debugging, but also for anomaly research. Thanks to a rich set of operators and flags, you can use it to get out of the network air and explore what you really need.

tcpdump instruction in Russian and examples.

-A specifies the output of each packet (without link-layer headers) in ASCII format. This mode is useful for capturing HTTP traffic.

-c <число пакетов>specifies that the program terminates after capturing the specified number of packets.

-C<размер файла>specifies whether to check the size of the capture file before each new package is written to it. If the file size exceeds the value of the file_size parameter, the file is closed
and a new file is created to write packages to it. Capture files use the name set by parameter-w and, starting from the second file, it is added to the name as
suffix file number. The variable file_size specifies the size of the file in millions of bytes (not in megabytes = 1,048,576 bytes).

-d specifies outputting a dump of the compiled packet-matching code in a human-readable format and exiting the program.

-dd outputs a dump of the matching code as a fragment of a C program.

-ddd Dumps the match code as a string of decimal values ​​preceded by a string containing the counter value.

-D lists the network interfaces on the system from which tcpdump can collect packets. Each network interface is given a name and number, which may be followed by
text description of the interface. The interface name and number can be used with the -i flag to specify that packets be collected from a single interface.

This option can be very useful for systems that do not provide information about available network interfaces3.

The -D flag is not supported if tcpdump was compiled with old version libpcap which does not support the pcap_findalldevs() function.

-e prints the link-layer header on each line of the dump.

-E specifies the use of the algorithm and secret [email protected] to decrypt IPsec ESP packets directed to ipaddr and containing and in the Security Parameter Index field value
spi. The combination of spi and address can be repeated using either a comma or a newline as the separator. Note that setting the secret for IPv4 ESP packets in
currently supported.

Algorithms can be des-cbc, 3des-cbc, blowfish-cbc, rc3-cbc, cast128-cbc or none. The default algorithm is des-cbc. Possibility of decryption
packages are only provided if cryptographic support options were enabled when tcpdump was compiled.

The secret parameter contains the ASCII text of the ESP secret key. If the secret starts with characters 0x, will be read hex value. The option involves the use
ESP is in accordance with RFC 2406, not RFC 1827. This option is only supported for debugging purposes and should not be used with real secret keys, as introduced in
command line the IPsec key is available to other system users4.

In addition to explicitly specifying options on the command line, they can be specified in an options file that tcpdump will read when it receives the first ESP packet.

-f specifies the display of foreign IPv4 addresses in numeric format. Using this option eliminates problems that Sun NIS servers encounter when trying to translate
non-local addresses. The foreignness of an IPv4 address is checked using the address and mask of the interface that received the packet. If the address and interface mask are not available
(e.g. when using unnumbered interfaces, or when capturing packets from all addresses on Linux using the dummy any interface), this option will work
incorrectly.

-F<файл> specifies the use of filters contained in the specified file. In this case, the filters specified on the command line are ignored.

-i<интерфейс> specifies collection of packets from the specified interface. If no interface is specified, tcpdump searches the system for a list of available interfaces and selects the active device with the minimum
number (excluding loopback).

Linux systems since the 2.2 kernel support a dummy interface called any, which collects packets from all active system interfaces. Note that the collection
packets from the device any is carried out in the normal (non-promiscuous) mode.

If the -D flag is supported on the system, the interface number displayed when using this flag can be given as an argument.

-l specifies buffering of stdout lines. This option is useful when you want to view data while collecting packets. For example, commands

tcpdump -l | tee date

tcpdump -l > dat & tail -f dat

provide a way to write packets to a dat file and output to the console at the same time.

-L specifies to display a list of known link layer types and exit the program.

-m<файл> loads the SMI MIB definition module from the specified file. This option can be used repeatedly to load multiple MIB modules.

-n disables translation of addresses and port numbers into symbolic names.

-N specifies to use only hostnames, not FQDNs. For example, instead of lhotze.bilim-systems.net when using this option, my work station will be
referred to as lhotze.

-O disables the code optimizer for checking whether packets match filtering conditions. Use this option if the optimizer appears to be buggy.

-p tells the program not to put the interface into capture mode5. The -p option cannot be used with the ether host (local-hw-addr) or ether broadcast filter.

-q specifies the output of the minimum amount of information.

-R setting this flag assumes that ESP/AH packets use the old specification6 and tcpdump will not output replay prevention fields.
playback). Because the ESP/AH specification does not include a version number field, tcpdump cannot determine the ESP/AH protocol version from the packet headers.

-r<файл> specifies to read data from a file previously created using the tcpdump -w command or another program that supports the tcpdump format (such as Ethereal). If in
the character - is specified as the file name, the data stream from the standard input device (stdin) is used.

-S specifies the output of absolute serial numbers TCP instead of relative.

-s specifies to capture bytes from each snaplen packet instead of the default 68 bytes7. The value 68 is suitable for IP, ICMP, TCP, and UDP protocols, but may result in loss of
protocol information for some DNS and NFS packets. The loss of some packets due to the small size of the capture frame (snapshot) is indicated in the output by fields of the form
[|proto]', where proto is the name of the protocol layer at which a part of the packet was truncated8. Note that an increase in the capture frame will lead to additional time
packet processing costs and a reduction in the number of buffered packets, which can lead to the loss of some packets. Use the minimum snaplen value that will allow
do without losing information about the protocol you are interested in. Setting snaplen=0 will capture full packets.

-T<тип> specifies the interpretation of packages selected using the filter as packages of the type specified by the parameter. Currently supported types are aodv9, cnfp10, rpc11, rtp12, rtcp13,
snmp14, tftp15, vat16 and wb17.

-t disables the output of timestamps on each line of the dump.

-tt specifies output on each line of an unformatted timestamp dump.

-ttt specifies the output of the time intervals (in microseconds) between the capture of the previous and this packet in each line of the dump.

-tttt specifies the output of timestamps in the default format for each dump line.

-u specifies the output of NFS handles without decoding.

-U sets the “batch-level buffering” mode for files saved with the -w option. In this mode, each packet is written to the output file as soon as it is captured.
(without waiting for the output buffer to fill). The -U flag will not be supported if the tcpdump program was compiled with the old libpcap option not supporting the function
pcap_dump_flush().

-v specifies the display of additional information when capturing files. Such information may include TTL value (time to live), identification, total size, IP options, etc. When
using this flag also performs additional packet integrity checks using checksums (for example, for IP and ICMP protocols).

-vv specifies an additional increase in the amount of output information (for example, full decoding of SMB packets, output of additional fields in NFS responses, etc.).

-vvv sets the maximum amount of output information (for example, telnet options SB ... SE are displayed in full). When used with the -X switch, Telnet options are also displayed in
hexadecimal representation.

-w<файл> specifies recording of raw packets. Packages compiled into a file can be subsequently viewed using the -r flag or passed to other programs for analysis.
(e.g. Ethereal). If the - character is specified as the filename, the file is written to standard output (stdout).

-x specifies to output a hexadecimal dump (without the link-layer header) for each captured packet. The amount of output information is determined by the smaller of the two values ​​−
the size of the packet and the value of the snaplen parameter. Note that when capturing full link-layer frames, the dump may also include padding bytes if the packet network layer
has a small size.

-xx specifies output of a hexadecimal dump for each packet, including link-layer headers.

-X specifies dump output in hexadecimal and ASCII format without link layer headers. This option can be very handy when analyzing new protocols.

-XX specifies dump output in hexadecimal and ASCII format including link layer headers.

-y<тип> specifies the type of link layer used when capturing packets. Supported values ​​can be viewed using the -L flag.

Examples.

  • We catch all outgoing traffic

tcpdump -i re0 -n -nn -ttt dst host 192.168.1.2

  • We catch all outgoing traffic except for our ssh session, because a very large data flow is obtained.

tcpdump -i re0 -n -nn -ttt ‘dst host 192.168.1.110 and not(src host 192.168.1.2 and dst port 22)’

  • View dns communication

tcpdump -i re0 -n -nn -ttt ‘host 192.168.1.110 and port 53’

  • Viewing icmp packets

tcpdump -i re0 -n -nn -ttt ‘ip proto \icmp’

  • Traffic coming from network 10.7.20 with destination on network 10.7.0. or 10.7.24.:

tcpdump -nvX src net 10.7.20.0.0/16 and dst net 10.7.0.0/8 or 10.7.24.0/16

  • Traffic coming from network 10.7.0.0 to destination ports 22 or 4589:

tcpdump 'src 10.7.0.0 and (dst port 22 or 4589)'

  • View traffic on the interface:
  • see the traffic of one host:

tcpdump host 192.168.1.1

  • View traffic on a port:

tcpdump src port 80

  • View IP traffic per host:

tcpdump ip host 192.168.1.2

  • View ARP traffic to the host:

tcpdump arp host 192.168.1.2

  • We look at RARP traffic to the host:

tcpdump rarp host 192.168.1.2

  • We look at traffic, except for the host pav253

tcpdump not host pav253

  • Watch traffic on pav253 and pav210

tcpdump host pav253 or host pav210

  • We look at the contents of the packages on the interface re0 on the host site

tcpdump -X -i re0 host site

  • icq traffic

tcpdump -X -i re0 port aol

  • We look at the contents of the packets on the tun0 interface to the ya.ru host, while reading 1500 bytes from each packet and not converting the IP into a host name

tcpdump -X -s 1500 -n -i re0 host site

  • Top active interactions

tcpdump -tn -c 10000 -i re0 tcp or udp | awk -F "." ‘(print $1″.”$2″.”$3″.”$4)’ | \ sort | uniq -c | sort-nr | awk ‘$1 > 100’

  • We look at all TCP packets with the SYN flag (session start).

tcpdump -i eth0 -nn tcp == 2 and src net 192.168.1.0/24

  • Viewing syn and fin packets from outside

tcpdump ‘tcp & (tcp-syn|tcp-fin) != 0 and not src and dst net 192.168.1.0’

  • View all ipv4 http packets from port 80 except syn/fin/ack data

tcpdump 'tcp port 80 and (((ip - ((ip&0xf)<>2)) != 0)’

  • View only syn packages