
Preventing Unsafe Integer Conversions in Rust: Avoiding Truncation, Overflow, and Signedness Bugs
Why integer conversions matter in security code
Numeric bugs are often dismissed as “just correctness issues,” but they frequently become security issues when attacker-controlled input is involved. Common examples include:
- Parsing a user-supplied length into a smaller integer type
- Casting a signed value to an unsigned type
- Converting a large
usizeintou32for storage or protocol encoding - Using
ascasts in arithmetic that can overflow or wrap
Rust’s as operator is intentionally permissive. It performs conversions even when information is lost. That makes it convenient, but also dangerous in security-sensitive paths.
Typical failure modes
| Bug type | Example | Security impact |
|---|---|---|
| Truncation | u64 to u16 | Limits bypass, incorrect allocation, protocol corruption |
| Signedness change | i32 to usize | Negative values become huge positive values |
| Overflow | u32 + 1 | Counter wraparound, quota bypass |
| Underflow | 0 - 1 | Unexpected large values, logic inversion |
| Platform dependence | usize assumptions | Different behavior on 32-bit vs 64-bit targets |
The goal is not to avoid all conversions. The goal is to make every conversion explicit, checked, and intentional.
Prefer checked conversions over as
The simplest rule is: avoid as for security-relevant integer conversions unless you have proven the conversion is safe and lossless.
Rust provides checked alternatives through the standard library:
TryFrom/TryIntofor fallible conversionschecked_add,checked_sub,checked_mulfor arithmeticsaturating_*for bounded behavior when that is explicitly desiredwrapping_*only when wraparound is part of the protocol or algorithm
Example: converting a request length safely
use std::convert::TryFrom;
fn parse_payload_len(len: u64) -> Result<usize, &'static str> {
usize::try_from(len).map_err(|_| "payload too large")
}
fn allocate_buffer(len: u64) -> Result<Vec<u8>, &'static str> {
let size = parse_payload_len(len)?;
Ok(vec![0u8; size])
}
This code fails cleanly if len does not fit in usize. A naive cast like len as usize could truncate on some platforms or allow a maliciously large value to become smaller than intended.
Why TryFrom is better than as
- It makes failure visible in the type system
- It forces the caller to handle invalid input
- It documents the conversion boundary clearly
- It prevents silent truncation and sign changes
Treat signed-to-unsigned conversions as hostile
Signed-to-unsigned casts are especially risky because negative values become large positive numbers. For example:
let x: i32 = -1;
let y: usize = x as usize;
On a 64-bit platform, y becomes a very large number. If that value is used for indexing, allocation, or limits, the result can be catastrophic.
Safer pattern: validate before conversion
fn to_nonnegative_usize(value: i32) -> Result<usize, &'static str> {
if value < 0 {
return Err("negative value not allowed");
}
usize::try_from(value).map_err(|_| "value out of range")
}
This pattern is especially useful when parsing values from:
- JSON or form input
- database fields
- network protocols
- environment variables
If a field is conceptually nonnegative, represent it that way as early as possible. Do not carry signed values deeper into the system unless negative values are semantically meaningful.
Use arithmetic checks, not assumptions
Even if a value starts in range, later arithmetic can overflow. Security bugs often appear when code assumes “this counter can’t get that big” or “the sum will always fit.”
Unsafe arithmetic example
fn total_size(header: usize, body: usize) -> usize {
header + body
}
If header + body overflows, Rust will panic in debug builds and wrap in release builds for primitive integers. Neither outcome is acceptable in security-critical code unless explicitly intended.
Safer alternative
fn total_size(header: usize, body: usize) -> Result<usize, &'static str> {
header.checked_add(body).ok_or("size overflow")
}
Use the same approach for subtraction and multiplication:
checked_subfor bounds calculationschecked_mulfor buffer sizes and repeated countschecked_addfor offsets and totals
Example: safe buffer sizing
fn compute_capacity(count: usize, item_size: usize) -> Result<usize, &'static str> {
count.checked_mul(item_size).ok_or("capacity overflow")
}
This is particularly important when handling attacker-controlled counts, such as the number of records in an upload, message, or archive.
Choose the right numeric type at the boundary
A common mistake is converting too early into a narrower type. Instead, keep values in a wide type until you have validated the range.
Practical guideline
| Situation | Prefer |
|---|---|
| Parsing external input | u64 or i64 first |
| In-memory indexing | usize |
| Protocol field with fixed width | Exact type from the spec, with checked conversion |
| Small bounded domain | Newtype with validation |
For example, if a protocol field is a 16-bit length, parse into a wider type first, validate the range, then convert:
use std::convert::TryFrom;
fn parse_u16_length(raw: u64) -> Result<u16, &'static str> {
u16::try_from(raw).map_err(|_| "length out of range")
}
This avoids accidental truncation if the input is larger than expected.
Use newtypes to encode invariants
If a value must always satisfy a constraint, encode that constraint in a dedicated type. This reduces the chance of repeated ad hoc checks and makes invalid states harder to represent.
Example: bounded count type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct RecordCount(u32);
impl RecordCount {
fn new(value: u64) -> Result<Self, &'static str> {
let v = u32::try_from(value).map_err(|_| "count too large")?;
if v == 0 {
return Err("count must be positive");
}
Ok(Self(v))
}
fn get(self) -> u32 {
self.0
}
}
Now any function that accepts RecordCount can assume the value is positive and within range. This is much safer than passing raw integers around and revalidating them inconsistently.
Benefits of newtypes
- Centralized validation
- Better API documentation
- Fewer accidental misuse paths
- Easier auditing of security-sensitive invariants
Be careful with platform-dependent types
usize and isize depend on the target architecture. That is usually correct for indexing and pointer arithmetic, but it can be dangerous for serialized data, file formats, and network protocols.
When usize is appropriate
- Vector indexing
- Slice lengths
- Memory allocation sizes
- Pointer offsets within a process
When usize is risky
- On-the-wire message formats
- Persistent storage formats
- Cross-platform APIs
- Security checks that must behave identically on 32-bit and 64-bit systems
If a field is part of an external contract, use a fixed-width type such as u32 or u64, then convert to usize only after validation.
Avoid lossy casts in protocol handling
Protocols often define exact field widths. A common anti-pattern is to parse into a large type, do some math, and then cast down at the end.
Bad pattern
fn encode_length(len: u64) -> u16 {
len as u16
}
This silently truncates values above u16::MAX, which can corrupt the protocol or create ambiguity between large and small inputs.
Better pattern
fn encode_length(len: u64) -> Result<u16, &'static str> {
u16::try_from(len).map_err(|_| "length exceeds protocol limit")
}
If the protocol has a maximum allowed length, enforce it explicitly. Do not rely on truncation to “make it fit.”
Use saturating and wrapping arithmetic only by design
Sometimes you do want saturation or wraparound. The key is to make that choice explicit and local.
Saturating arithmetic
Use saturating_add when a value should clamp at a maximum rather than overflow.
fn increment_rate_limit(current: u32) -> u32 {
current.saturating_add(1)
}
This is useful for counters where exceeding the maximum should not panic or wrap.
Wrapping arithmetic
Use wrapping_add only when the algorithm requires modular arithmetic, such as checksums or cryptographic primitives that define wraparound behavior.
fn next_state(state: u32, delta: u32) -> u32 {
state.wrapping_add(delta)
}
Do not use wrapping arithmetic for sizes, counts, or security decisions unless the specification explicitly requires it.
Audit conversion hot spots
When reviewing Rust code for security issues, focus on places where untrusted data meets numeric operations.
High-risk locations
- Request parsing
- Deserialization code
- Length-prefixed buffers
- Pagination and offset handling
- Rate limiting and quota checks
- File and memory allocation
- Index calculations
- Timeouts and retry counters
Review questions
- Is the source value attacker-controlled?
- Could the value be negative, too large, or malformed?
- Does the conversion lose information?
- What happens if arithmetic overflows?
- Is the chosen type platform-dependent?
- Is failure handled explicitly?
If any answer is uncertain, replace the cast with a checked conversion and a clear error path.
A secure conversion workflow
A practical pattern for security-sensitive code is:
- Parse into a wide type
- Validate semantic constraints
- Convert with
TryFrom - Use checked arithmetic
- Store in a type that encodes the invariant
Example workflow
use std::convert::TryFrom;
#[derive(Debug)]
struct PageSize(usize);
impl PageSize {
fn new(raw: u64) -> Result<Self, &'static str> {
let size = usize::try_from(raw).map_err(|_| "page size too large")?;
if size == 0 || size > 1_048_576 {
return Err("invalid page size");
}
Ok(Self(size))
}
fn get(&self) -> usize {
self.0
}
}
fn allocate_page_buffer(page_size: PageSize) -> Vec<u8> {
vec![0u8; page_size.get()]
}
This design prevents invalid values from reaching the allocation site. The constructor becomes the single enforcement point.
Checklist for safe integer handling
- Prefer
TryFromandTryIntooveras - Validate sign before converting signed values to unsigned types
- Use
checked_*arithmetic for security-sensitive calculations - Keep external values in wide types until validation is complete
- Avoid
usizein serialized or cross-platform data formats - Encode invariants with newtypes
- Use
saturating_andwrapping_only when the behavior is intentional - Review all length, offset, count, and quota calculations carefully
Conclusion
Unsafe integer conversions are a subtle but serious source of security bugs in Rust. They rarely cause memory unsafety directly, but they can undermine validation, corrupt protocol logic, and create exploitable edge cases. The safest approach is to make conversions explicit, checked, and local to the boundary where data enters the system.
If you treat every narrowing cast as a potential security decision, your Rust code will be more robust, easier to audit, and far less likely to fail in surprising ways.