GGist / bip-rs

BitTorrent Infrastructure Project In Rust
Apache License 2.0
296 stars 33 forks source link

Propagate Peer Wire Protocol Message Length Cast Overflows #93

Open GGist opened 7 years ago

GGist commented 7 years ago

Peer wire protocol headers include a 4 byte message id. For most purposes, this u32 value need to be used as a usize value. We should validate that the cast from a u32 to a usize doesn't overflow, and if it does, we should be terminating the connection and propagating an appropriate error as currently we just panic.

Kerollmops commented 7 years ago

You mean casting from u32 to usize ? or usize to u32 because in most cases usize is coded on more bytes, the conversion will not result in an overflowed u32, no ?

GGist commented 7 years ago

because in most cases usize is coded on more bytes

By this did you mean that a usize is typically larger than a u32, or perhaps the opposite?


I was primarily thinking of the case going from a u32 (which is what we will get our message length as, 4 bytes), to a usize which could be anything from 8, 16, 24, 32, or 64 bits long depending on the architecture we are running on.

So if we got a message length of 66,560 (65KB), a u32 would be able to hold that value, so it would be valid for them to send us such a value, but on an 8 or 16 bit architecture, the address space wouldn't support buffering the complete message in memory (a usize wouldnt be big enough to hold the value) and casting from the u32 message length to usize would overflow the usize.