rust_memory_safety_examples/
buffer_overflow_prevention.rs

1//! Buffer overflow prevention examples
2
3/// VULNERABLE C CODE (for comparison):
4/// ```c
5/// #include <string.h>
6///
7/// void vulnerable_copy(char* dest, const char* src) {
8///     strcpy(dest, src);  // NO BOUNDS CHECKING!
9/// }
10///
11/// int main() {
12///     char buffer[10];
13///     char* long_string = "This is a very long string that will overflow";
14///     vulnerable_copy(buffer, long_string);  // BUFFER OVERFLOW!
15///     return 0;
16/// }
17/// ```
18///
19/// **Vulnerability:** strcpy doesn't check destination buffer size,
20/// causing stack corruption, potential code execution, crashes.
21///
22/// **CVE Examples:**
23/// - CVE-2021-3156 (sudo): Heap buffer overflow
24/// - CVE-2014-0160 (Heartbleed): Buffer over-read
25///
26
27/// SAFE RUST EQUIVALENT:
28/// Rust prevents buffer overflows at compile time through bounds checking
29pub fn safe_copy(dest: &mut [u8], src: &[u8]) -> Result<(), &'static str> {
30    if dest.len() < src.len() {
31        return Err("Destination buffer too small");
32    }
33
34    dest[..src.len()].copy_from_slice(src);
35    Ok(())
36}
37
38/// Example: Array access with bounds checking
39pub fn safe_array_access() {
40    let array = [1, 2, 3, 4, 5];
41
42    // Compile-time known indices are checked
43    let _first = array[0];  // OK
44
45    // Runtime bounds checking (panics on out-of-bounds)
46    // let _invalid = array[10];  // Would panic!
47
48    // Safe alternative: get() returns Option
49    match array.get(10) {
50        Some(value) => println!("Value: {}", value),
51        None => println!("Index out of bounds (safely handled)"),
52    }
53}
54
55/// Example: Vector with automatic bounds checking
56pub fn safe_vector_usage() {
57    let mut vec = Vec::new();
58    vec.push(1);
59    vec.push(2);
60    vec.push(3);
61
62    // Safe iteration (no overflow possible)
63    for item in &vec {
64        println!("{}", item);
65    }
66
67    // Safe indexed access
68    if let Some(value) = vec.get(5) {
69        println!("Value at index 5: {}", value);
70    } else {
71        println!("Index 5 doesn't exist");
72    }
73}
74
75/// Example: String handling (always safe in Rust)
76pub fn safe_string_operations() {
77    let mut dest = String::with_capacity(10);
78    let src = "This is a very long string that would overflow a fixed buffer";
79
80    // String automatically grows - no overflow possible
81    dest.push_str(src);
82
83    println!("String length: {} (automatically managed)", dest.len());
84}
85
86/// Demonstration: Why Rust prevents overflows
87pub fn demonstration_bounds_checking() {
88    let buffer: [u8; 10] = [0; 10];
89    let data: [u8; 20] = [1; 20];
90
91    // This would NOT compile:
92    // buffer.copy_from_slice(&data);  // Compile error: size mismatch!
93
94    // Safe alternative:
95    let safe_copy = &data[..buffer.len()];
96    let mut mutable_buffer = buffer;
97    mutable_buffer.copy_from_slice(safe_copy);
98
99    println!("Safe copy completed: {:?}", mutable_buffer);
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn test_safe_copy_success() {
108        let mut dest = [0u8; 10];
109        let src = [1, 2, 3, 4, 5];
110
111        assert!(safe_copy(&mut dest, &src).is_ok());
112        assert_eq!(&dest[..5], &src);
113    }
114
115    #[test]
116    fn test_safe_copy_overflow_prevented() {
117        let mut dest = [0u8; 5];
118        let src = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
119
120        // Overflow is caught and returned as error
121        assert!(safe_copy(&mut dest, &src).is_err());
122    }
123
124    #[test]
125    #[should_panic]
126    #[allow(unconditional_panic)]
127    fn test_out_of_bounds_panic() {
128        let array = [1, 2, 3];
129        let _ = array[10];  // Panics (controlled failure, not undefined behavior)
130    }
131
132    #[test]
133    fn test_safe_get() {
134        let array = [1, 2, 3];
135        assert_eq!(array.get(1), Some(&2));
136        assert_eq!(array.get(10), None);  // Safe handling
137    }
138}