commit 54938332a8733e0f00110c4fcaccaa1973c905cc
parent 6faa0350f2dfb446caa59261c5f337c33501ac2b
Author: Nick Mathewson <nickm@torproject.org>
Date: Mon, 5 May 2025 20:38:55 -0400
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.
Diffstat:
2 files changed, 15 insertions(+), 1 deletion(-)
diff --git 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
@@ -21,7 +21,15 @@
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;
@@ -29,6 +37,8 @@ typedef struct relay_msg_t {
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. */
const uint8_t *body;