The routing used in the Tor network is called onion routing because the mechanism for maintaining anonymity in it is based on multiple layers of encryption which resemble layers of an onion.
Inside the Tor client it is hard-coded that the traffic will pass through three relays: entry node, middle node and exit node. There are multiple layers of encryption because the relays are allowed to know only the preceding node, and the following node so that the anonymity from end to end is maintained.
How is the communication routed?
- The Tor client selects the routing path consisting of three relays, and encrypts each packet with three nested layers of encryption (one layer for each of the three relays).
- The client sends the three times encrypted packet to the entry node which removes the first layer.
- The twice encrypted packet continues to the next node which removes the second layer.
- Then the packet with the last layer of encryption continues to the exit node which removes the last layer of encryption. Inside of the packet the exit node checks a field indicating that it was the last layer and the clear-text content should be sent to the Internet.
- If the destination conforms the exit policy of the relay the clear-text packet leaves the exit node and is normally delivered in the Internet.
Briefly said: The Tor client decides which node will be the exit relay. The exit relay recognizes its role for a packet after decrypting the last layer of encryption. It checks ID of the Tor stream and a field which indicates that the last layer of encryption was removed. The exit relay must be configured as an exit relay by its policy.