From: Nick Mathewson Date: Tue, 6 May 2025 00:38:55 +0000 (-0400) Subject: relay_msg: Document and enforce length invariants. X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=54938332a8733e0f00110c4fcaccaa1973c905cc;p=thirdparty%2Ftor.git relay_msg: Document and enforce length invariants. This takes a slightly different approach from suggested in the MR: we document that a relay_msg_t must _always_ have a valid length, and note that this warning still applies for relay_msg_copy. --- diff --git a/src/core/or/relay_msg.c b/src/core/or/relay_msg.c index 8d270058e4..ae4d98db91 100644 --- a/src/core/or/relay_msg.c +++ b/src/core/or/relay_msg.c @@ -60,10 +60,14 @@ relay_msg_clear(relay_msg_t *msg) /** Allocate a new relay message and copy the content of the given message. * * This message allocation _will_ own its body, even if the original did not. + * + * Requires that msg is well-formed, and that its length is within + * allowable bounds. **/ relay_msg_t * relay_msg_copy(const relay_msg_t *msg) { + tor_assert(msg->length <= RELAY_PAYLOAD_SIZE_MAX); void *alloc = tor_malloc_zero(sizeof(relay_msg_t) + msg->length); relay_msg_t *new_msg = alloc; uint8_t *body = ((uint8_t*)alloc) + sizeof(relay_msg_t); diff --git a/src/core/or/relay_msg_st.h b/src/core/or/relay_msg_st.h index 9cf27305e9..81e84135d0 100644 --- a/src/core/or/relay_msg_st.h +++ b/src/core/or/relay_msg_st.h @@ -21,13 +21,23 @@ typedef struct relay_msg_t { /* Relay command of a message. */ uint8_t command; - /* Length of the message body. */ + /* Length of the message body. + * + * This value MUST always be less than or equal to the lower of: + * - the number of bytes available in `body`. + * - relay_cell_max_format(_, command). + * + * (These bounds on the length field are guaranteed by all message decoding + * functions, and enforced by all message encoding functions.) + */ uint16_t length; /* Optional routing header: stream ID of a message or 0. */ streamid_t stream_id; /* Indicate if this is a message from a relay early cell. */ bool is_relay_early; /* Message body of a relay message. + * + * Code MUST NOT access any part of `body` beyond the first `length` bytes. * * NOTE that this struct does not own the body; instead, this is a pointer * into a different object. */