TExcelTAD

ICMP, Ping and Traceroute

ICMP is the network's error and diagnostics channel: "destination unreachable", "time exceeded", "echo request". Administrators love it because ping and traceroute are the first tools in every troubleshooting session. Security teams have a more mixed view: ICMP reveals which hosts are alive and how the network is laid out, its echo messages can carry arbitrary data, and yet blocking it outright breaks things that matter. This lesson reads ICMP from bytes, rebuilds traceroute on a simulated path, and shows where ICMP shows up in detections. The basics are in ICMP & Ping.

The message

An ICMP message sits directly in an IP packet (protocol 1). Its header is 4 bytes, type, code, checksum, followed by type-specific fields; echo messages add an identifier and sequence number and then any payload.

Type Code Meaning Security note
0 / 8 0 echo reply / request host discovery; payload can hide data
3 0–15 destination unreachable (3 = port unreachable, 4 = fragmentation needed) reveals closed UDP ports and filtering; code 4 is needed for path-MTU discovery
5 0–3 redirect can reroute a host; ignore on hosts
11 0 time exceeded in transit makes traceroute work; reveals router addresses

Building and checking an echo request

The checksum is the same Internet checksum as in the IPv4 header, but over the whole ICMP message. The program builds a request shaped like the one Linux ping sends (identifier, sequence number, and the counting pattern that follows ping's 16-byte timestamp), then verifies it.

python · try it yourself
import struct

def checksum(data):
    if len(data) % 2:
        data += b"\0"
    s = sum(w for (w,) in struct.iter_unpack("!H", data))
    while s >> 16:
        s = (s & 0xFFFF) + (s >> 16)
    return ~s & 0xFFFF

def echo_request(ident, seq, payload):
    head = struct.pack("!BBHHH", 8, 0, 0, ident, seq)
    c = checksum(head + payload)
    return struct.pack("!BBHHH", 8, 0, c, ident, seq) + payload

payload = bytes(range(0x10, 0x38))          # 40 bytes of the counting pattern ping uses
msg = echo_request(0x4c41, 1, payload)
t, code, c, ident, seq = struct.unpack("!BBHHH", msg[:8])
print("type", t, "code", code, "checksum", hex(c), "id", hex(ident), "seq", seq, "payload", len(msg) - 8, "bytes")
print("first 16 bytes:", msg[:16].hex(" "))
print("verifies:", checksum(msg) == 0)
type 8 code 0 checksum 0xecea id 0x4c41 seq 1 payload 40 bytes
first 16 bytes: 08 00 ec ea 4c 41 00 01 10 11 12 13 14 15 16 17
verifies: True

Traceroute, rebuilt

Traceroute sends probes with TTL 1, 2, 3, … Each router decrements the TTL; the one that brings it to 0 drops the packet and returns ICMP time exceeded from its own address. So the sender learns one router per TTL, until the destination answers (with an echo reply for ICMP probes, or port unreachable for the classic UDP probes to high ports). The program simulates that on a lab path; one router is configured not to send time-exceeded messages, which shows up as *.

python · try it yourself
path = [("10.10.0.1", True), ("192.0.2.1", True), ("198.51.100.17", False), ("203.0.113.5", True)]
target = "203.0.113.80"
rtt_base = [0.4, 3.1, 7.8, 11.2, 11.9]              # fixed, illustrative milliseconds

def probe(ttl):
    for hop, (router, answers) in enumerate(path, start=1):
        if ttl == hop:                              # TTL reaches 0 at this router
            return (router, "time exceeded") if answers else (None, None)
    return (target, "echo reply")

print(f"traceroute to {target}, 30 hops max")
for ttl in range(1, 31):
    who, what = probe(ttl)
    if who is None:
        print(f"{ttl:>2}  * * *")
        continue
    print(f"{ttl:>2}  {who:<15} {rtt_base[ttl - 1]:.1f} ms  ({what})")
    if who == target:
        break
traceroute to 203.0.113.80, 30 hops max
 1  10.10.0.1       0.4 ms  (time exceeded)
 2  192.0.2.1       3.1 ms  (time exceeded)
 3  * * *
 4  203.0.113.5     11.2 ms  (time exceeded)
 5  203.0.113.80    11.9 ms  (echo reply)

On a real network you would see the same pattern. A recorded lab session (scope: the lab network and documentation ranges only):

console
lab-session$ traceroute -n -I 203.0.113.80
traceroute to 203.0.113.80 (203.0.113.80), 30 hops max, 60 byte packets
 1  10.10.0.1  0.412 ms  0.388 ms  0.371 ms
 2  192.0.2.1  3.105 ms  3.090 ms  3.122 ms
 3  * * *
 4  203.0.113.5  11.230 ms  11.198 ms  11.244 ms
 5  203.0.113.80  11.901 ms  11.887 ms  11.910 ms

(-I uses ICMP echo probes and needs root, like most raw-socket tools, which is why the sandbox can't run it.)

How ICMP is abused, and how it is detected

  • Host discovery. Echo sweeps across a subnet ("ping sweeps") are the oldest reconnaissance step. Detection: one source sending echo requests to many addresses in a short window; IDS rules count them.
  • Topology mapping. Time-exceeded replies reveal internal router addresses to anyone tracing from outside.
  • Covert channels ("ICMP tunnelling"). The echo payload is free-form, so data can be smuggled inside pings. Normal pings have small payloads of a fixed shape (on Linux 56 bytes: a 16-byte timestamp followed by a counting pattern; on Windows 32 bytes of the alphabet) and the reply echoes the request. Detection: unusual payload sizes, payloads that change from packet to packet, high volumes of echo to one external host, replies that don't match requests.
  • Reflection. Historic "smurf" attacks sent echo requests to broadcast addresses with the victim's source; routers no longer forward directed broadcasts by default (RFC 2644).

The session writes a synthetic capture with standard pings and a few echo requests whose payloads vary in size and content, then uses tshark to profile payload sizes per destination, the first step of a tunnelling hunt:

bash · try it yourself
python3 - <<'PY'
from scapy.all import Ether, IP, ICMP, Raw, wrpcap
t0, pkts = 1768471200.0, []
pattern = bytes(range(0x10, 0x38)) + bytes(16)          # 56 bytes, like Linux ping
for i in range(3):
    pkts.append(Ether(src="02:00:00:0a:0a:05", dst="02:00:00:0a:0a:01")/IP(src="10.10.0.5", dst="10.10.0.1")/ICMP(id=0x4c41, seq=i + 1)/Raw(pattern))
for i, chunk in enumerate([b"lab-synthetic-" * 30, b"x" * 900, b"lab-" * 120]):
    pkts.append(Ether(src="02:00:00:0a:0a:07", dst="02:00:00:0a:0a:01")/IP(src="10.10.0.7", dst="203.0.113.99")/ICMP(id=0x0101, seq=i + 1)/Raw(chunk))
for i, p in enumerate(pkts):
    p.time = t0 + i
wrpcap("icmp.pcap", pkts)
PY
echo "dst            requests  payload sizes"
tshark -r icmp.pcap -Y 'icmp.type == 8' -T fields -e ip.dst -e data.len |
awk -F'\t' '{n[$1]++; s[$1] = s[$1] " " $2} END {for (d in n) printf "%-14s %8d  %s\n", d, n[d], s[d]}' | sort
dst            requests  payload sizes
10.10.0.1             3   56 56 56
203.0.113.99          3   420 900 480

The pings to the gateway have one constant size; the requests to 203.0.113.99 vary and are an order of magnitude larger. That alone is not proof, but it is exactly what a tunnelling detection looks for.

How it is fixed (without breaking the network)

  • Don't block all ICMP. "Fragmentation needed" (type 3 code 4) is required for path-MTU discovery; blocking it causes connections that hang on large packets. For ICMPv6, RFC 4890 lists the messages that must pass (Neighbor Discovery, packet too big, and more).
  • Filter selectively at the edge: allow echo to the hosts that need it, rate-limit ICMP, and drop inbound echo to internal ranges. Consider dropping outbound time-exceeded from internal routers to hide topology.
  • Limit payload sizes of echo leaving the network, or allow external echo only from monitoring systems; alert on the profile above.
  • Ignore redirects on hosts (accept_redirects = 0) and disable directed broadcast on routers.

Pitfalls

  • Concluding a host is down because it doesn't answer ping. Many hosts and firewalls drop echo; use TCP to the service port instead (see Nmap Connect Scans).
  • Reading * * * in traceroute as packet loss. It often just means a router that doesn't send time-exceeded messages, while forwarding normally.
  • Blocking ICMP to "be secure" and then debugging mysterious TLS stalls for a week.

Practice

1. Which ICMP message reveals that a UDP port is closed?

Destination unreachable, type 3 code 3 (port unreachable). No reply at all can mean open or filtered, which is why UDP scanning is slow and ambiguous.

2. In the traceroute simulation, change the second router to False too. What does the output look like and what does it hide?

Hops 2 and 3 both show * * *. The path still works (hop 4 and the target answer), but the addresses of those routers stay hidden from the tracer.

3. Why is "payload differs from the standard pattern" a better tunnelling signal than "payload larger than 56 bytes"?

Administrators legitimately send large pings (ping -s 1400) to test MTUs, but those carry the tool's fixed pattern (apart from Linux ping's timestamp in the first bytes). Data smuggled in echo changes throughout the payload from packet to packet and doesn't match any tool's pattern, and the replies usually don't mirror the requests.

Test yourself

What does a router send when it decrements a packet's TTL to 0?

  1. Echo reply
  2. ICMP time exceeded (type 11)
  3. Destination unreachable (type 3)
  4. Nothing

Why shouldn't a firewall drop all ICMP?

  1. ICMP carries DNS
  2. Fragmentation-needed messages are required for path-MTU discovery
  3. TCP uses ICMP for its handshake
  4. It would disable ARP

In the tshark profile, which pattern points to possible ICMP tunnelling?

  1. Three 56-byte pings to the gateway
  2. Echo requests to an external host with large payloads that vary in size
  3. An echo reply for every request
  4. Pings with sequence numbers 1, 2, 3