cairo_vm/vm/
security.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
use crate::stdlib::prelude::*;

use num_traits::ToPrimitive;

use super::{
    errors::{runner_errors::RunnerError, vm_errors::VirtualMachineError},
    runners::cairo_runner::CairoRunner,
};
use crate::types::relocatable::MaybeRelocatable;

/// Verify that the completed run in a runner is safe to be relocated and be
/// used by other Cairo programs.
///
/// Checks include:
///   - (Only if `verify_builtins` is set to true) All accesses to the builtin segments must be within the range defined by
///     the builtins themselves.
///   - There must not be accesses to the program segment outside the program
///     data range. This check will use the `program_segment_size` instead of the program data length if available.
///   - All addresses in memory must be real (not temporary)
///
/// Note: Each builtin is responsible for checking its own segments' data.
pub fn verify_secure_runner(
    runner: &CairoRunner,
    verify_builtins: bool,
    program_segment_size: Option<usize>,
) -> Result<(), VirtualMachineError> {
    let builtins_segment_info = match verify_builtins {
        true => runner.get_builtin_segments_info()?,
        false => Vec::new(),
    };
    // Check builtin segment out of bounds.
    for (index, stop_ptr) in builtins_segment_info {
        let current_size = runner
            .vm
            .segments
            .memory
            .data
            .get(index)
            .map(|segment| segment.len());
        // + 1 here accounts for maximum segment offset being segment.len() -1
        if current_size >= Some(stop_ptr + 1) {
            return Err(VirtualMachineError::OutOfBoundsBuiltinSegmentAccess);
        }
    }
    // Check out of bounds for program segment.
    let program_segment_index = runner
        .program_base
        .and_then(|rel| rel.segment_index.to_usize())
        .ok_or(RunnerError::NoProgBase)?;
    let program_segment_size =
        program_segment_size.unwrap_or(runner.program.shared_program_data.data.len());
    let program_length = runner
        .vm
        .segments
        .memory
        .data
        .get(program_segment_index)
        .map(|segment| segment.len());
    // + 1 here accounts for maximum segment offset being segment.len() -1
    if program_length >= Some(program_segment_size + 1) {
        return Err(VirtualMachineError::OutOfBoundsProgramSegmentAccess);
    }
    // Check that the addresses in memory are valid
    // This means that every temporary address has been properly relocated to a real address
    // Asumption: If temporary memory is empty, this means no temporary memory addresses were generated and all addresses in memory are real
    if !runner.vm.segments.memory.temp_data.is_empty() {
        for value in runner.vm.segments.memory.data.iter().flatten() {
            match value.get_value() {
                Some(MaybeRelocatable::RelocatableValue(addr)) if addr.segment_index < 0 => {
                    return Err(VirtualMachineError::InvalidMemoryValueTemporaryAddress(
                        Box::new(addr),
                    ))
                }
                _ => {}
            }
        }
    }
    for builtin in runner.vm.builtin_runners.iter() {
        builtin.run_security_checks(&runner.vm)?;
    }

    Ok(())
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::BuiltinHintProcessor;

    use crate::types::builtin_name::BuiltinName;
    use crate::types::relocatable::Relocatable;

    use crate::Felt252;
    use crate::{relocatable, types::program::Program, utils::test_utils::*};
    use assert_matches::assert_matches;

    #[cfg(target_arch = "wasm32")]
    use wasm_bindgen_test::*;

    #[test]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn verify_secure_runner_without_program_base() {
        let program = program!();

        let runner = cairo_runner!(program);

        assert_matches!(
            verify_secure_runner(&runner, true, None),
            Err(VirtualMachineError::RunnerError(RunnerError::NoProgBase))
        );
    }

    #[test]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn verify_secure_runner_empty_memory() {
        let program = program!(main = Some(0),);
        let mut runner = cairo_runner!(program);

        runner.initialize(false).unwrap();
        runner.vm.segments.compute_effective_sizes();
        assert_matches!(verify_secure_runner(&runner, true, None), Ok(()));
    }

    #[test]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn verify_secure_runner_program_access_out_of_bounds() {
        let program = program!(main = Some(0),);
        let mut runner = cairo_runner!(program);

        runner.initialize(false).unwrap();

        runner.vm.segments = segments![((0, 0), 100)];
        runner.vm.segments.segment_used_sizes = Some(vec![1]);

        assert_matches!(
            verify_secure_runner(&runner, true, None),
            Err(VirtualMachineError::OutOfBoundsProgramSegmentAccess)
        );
    }

    #[test]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn verify_secure_runner_program_with_program_size() {
        let program = program!(main = Some(0),);
        let mut runner = cairo_runner!(program);

        runner.initialize(false).unwrap();

        runner.vm.segments = segments![((0, 0), 100)];
        runner.vm.segments.segment_used_sizes = Some(vec![1]);

        assert_matches!(verify_secure_runner(&runner, true, Some(1)), Ok(()));
    }

    #[test]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn verify_secure_runner_builtin_access_out_of_bounds() {
        let program = program!(main = Some(0), builtins = vec![BuiltinName::range_check],);
        let mut runner = cairo_runner!(program);

        runner.initialize(false).unwrap();
        runner.vm.builtin_runners[0].set_stop_ptr(0);
        runner.vm.segments.memory = memory![((2, 0), 1)];
        runner.vm.segments.segment_used_sizes = Some(vec![0, 0, 0, 0]);

        assert_matches!(
            verify_secure_runner(&runner, true, None),
            Err(VirtualMachineError::OutOfBoundsBuiltinSegmentAccess)
        );
    }

    #[test]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn verify_secure_runner_builtin_access_correct() {
        let program = program!(main = Some(0), builtins = vec![BuiltinName::range_check],);
        let mut runner = cairo_runner!(program);

        runner.initialize(false).unwrap();
        let mut hint_processor = BuiltinHintProcessor::new_empty();
        runner.end_run(false, false, &mut hint_processor).unwrap();
        runner.vm.builtin_runners[0].set_stop_ptr(1);

        runner.vm.segments.memory = memory![((2, 0), 1)];
        runner.vm.segments.segment_used_sizes = Some(vec![0, 0, 1, 0]);

        assert_matches!(verify_secure_runner(&runner, true, None), Ok(()));
    }

    #[test]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn verify_secure_runner_success() {
        let program = program!(
            data = vec![
                Felt252::ZERO.into(),
                Felt252::ZERO.into(),
                Felt252::ZERO.into(),
                Felt252::ZERO.into(),
            ],
            main = Some(0),
        );

        let mut runner = cairo_runner!(program);

        runner.initialize(false).unwrap();
        runner.vm.segments.memory = memory![
            ((0, 0), (1, 0)),
            ((0, 1), (2, 1)),
            ((0, 2), (3, 2)),
            ((0, 3), (4, 3))
        ];
        runner.vm.segments.segment_used_sizes = Some(vec![5, 1, 2, 3, 4]);

        assert_matches!(verify_secure_runner(&runner, true, None), Ok(()));
    }

    #[test]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn verify_secure_runner_temporary_memory_properly_relocated() {
        let program = program!(
            data = vec![
                Felt252::ZERO.into(),
                Felt252::ZERO.into(),
                Felt252::ZERO.into(),
                Felt252::ZERO.into(),
            ],
            main = Some(0),
        );

        let mut runner = cairo_runner!(program);

        runner.initialize(false).unwrap();
        runner.vm.segments.memory = memory![
            ((0, 1), (1, 0)),
            ((0, 2), (2, 1)),
            ((0, 3), (3, 2)),
            ((-1, 0), (1, 2))
        ];
        runner.vm.segments.segment_used_sizes = Some(vec![5, 1, 2, 3, 4]);

        assert_matches!(verify_secure_runner(&runner, true, None), Ok(()));
    }

    #[test]
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    fn verify_secure_runner_temporary_memory_not_fully_relocated() {
        let program = program!(
            data = vec![
                Felt252::ZERO.into(),
                Felt252::ZERO.into(),
                Felt252::ZERO.into(),
                Felt252::ZERO.into(),
            ],
            main = Some(0),
        );

        let mut runner = cairo_runner!(program);

        runner.initialize(false).unwrap();
        runner.vm.segments.memory = memory![
            ((0, 0), (1, 0)),
            ((0, 1), (2, 1)),
            ((0, 2), (-3, 2)),
            ((0, 3), (4, 3)),
            ((-1, 0), (1, 2))
        ];
        runner.vm.segments.segment_used_sizes = Some(vec![5, 1, 2, 3, 4]);

        assert_matches!(
            verify_secure_runner(&runner, true, None),
            Err(VirtualMachineError::InvalidMemoryValueTemporaryAddress(
                bx
            )) if *bx == relocatable!(-3, 2)
        );
    }
}