Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check RequestPair payload length during decoding #7292

Merged
merged 5 commits into from Mar 25, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 37 additions & 3 deletions crates/net/eth-wire/src/types/message.rs
Expand Up @@ -468,8 +468,22 @@ where
T: Decodable,
{
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let _header = Header::decode(buf)?;
Ok(Self { request_id: u64::decode(buf)?, message: T::decode(buf)? })
let header = Header::decode(buf)?;

let initial_length = buf.len();
let request_id = u64::decode(buf)?;
let message = T::decode(buf)?;

// Check that the buffer consumed exactly payload_length bytes after decoding the
// RequestPair
let consumed_len = initial_length - buf.len();
if consumed_len != header.payload_length {
return Err(alloy_rlp::Error::Custom(
"Buffer did not consume exactly payload_length bytes",
));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use RlpError::UnexpectedLength, we've used it in other places where we check the consumed bytes vs the payload length

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

}

Ok(Self { request_id, message })
}
}

Expand All @@ -479,7 +493,7 @@ mod tests {
errors::EthStreamError, types::message::RequestPair, EthMessage, EthMessageID, GetNodeData,
NodeData, ProtocolMessage,
};
use alloy_rlp::{Decodable, Encodable};
use alloy_rlp::{Decodable, Encodable, Error};
use reth_primitives::hex;

fn encode<T: Encodable>(value: T) -> Vec<u8> {
Expand Down Expand Up @@ -532,4 +546,24 @@ mod tests {
assert_eq!(expected.length(), raw_pair.len());
assert_eq!(expected, got);
}

#[test]
fn malicious_request_pair_decode() {
// A maliciously encoded request pair, where the len(full_list) is 5, but it
// actually consumes 6 bytes when decoding
//
// c5: start of list (c0) + len(full_list) (length is <55 bytes)
// 82: 0x80 + len(1337)
// 05 39: 1337 (request_id)
// === full_list ===
// c2: start of list (c0) + len(list) (length is <55 bytes)
// 05 05: 5 5(message)
let raw_pair = &hex!("c5820539c20505")[..];

let result = RequestPair::<Vec<u8>>::decode(&mut &*raw_pair);
assert!(matches!(
result,
Err(Error::Custom("Buffer did not consume exactly payload_length bytes",))
));
}
}