From the tor protocol whitepaper: https://svn.torproject.org/svn/projects/design-paper/tor-design.pdf
Relay cells. Once Alice has established the circuit (so she shares keys with
each OR on the circuit), she can send relay cells. Upon re-
ceiving a relay cell, an OR looks up the corresponding circuit,
and decrypts the relay header and payload with the session
key for that circuit. If the cell is headed away from Alice the
OR then checks whether the decrypted cell has a valid digest
(as an optimization, the first two bytes of the integrity check
are zero, so in most cases we can avoid computing the hash).
If valid, it accepts the relay cell and processes it as described
below. Otherwise, the OR looks up the circID and OR for the
next step in the circuit, replaces the circID as appropriate, and
sends the decrypted relay cell to the next OR. (If the OR at
the end of the circuit receives an unrecognized relay cell, an
error has occurred, and the circuit is torn down.
(Bold emphasis mine.)
I recommend reading the whole section of Relay cells in the linked paper. The idea is that tor packets ("cells") are designed with a hash/signature ("digest") that will only be valid for the data after the last node in your circuit decrypts it. Middle nodes will find that the signature is invalid and know to send it further down the line.