For ICMP, we differentiate between two cases: These are the ICMP request/reply connections as used by “ping”, and the ICMP error messages that can be received in response to any IP packet.
ICMP request/reply connections can be uniquely assigned to the initiator according to the identifier used, i.e. when an ICMP request is sent, an entry is created in the state database that only allows ICMP replies with the correct identifier to pass. All other ICMP replies are silently dropped.
For ICMP error messages, the IP header and the first 8 bytes of the IP packet (usually UDP or TCP header) are inside the ICMP packet. On receipt of an ICMP error message, this information is used to search for the corresponding entry in the status database. The packet is forwarded only if a suitable entry exists, otherwise it is silently dropped. Furthermore, potentially dangerous ICMP error messages (redirect route) are filtered out.