-
Notifications
You must be signed in to change notification settings - Fork 273
Expand file tree
/
Copy pathbuffer_validator.rs
More file actions
250 lines (224 loc) · 8.12 KB
/
Copy pathbuffer_validator.rs
File metadata and controls
250 lines (224 loc) · 8.12 KB
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
// SPDX-License-Identifier: Apache-2.0
use crate::codegen::cfg::{ControlFlowGraph, Instr};
use crate::codegen::revert::{assert_failure, PanicCode, SolidityError};
use crate::codegen::vartable::Vartable;
use crate::codegen::Expression;
use crate::sema::ast::{Namespace, Type};
use num_bigint::BigInt;
use num_traits::Zero;
use solang_parser::pt::Loc;
use std::ops::AddAssign;
/// When we are decoding serialized data from a bytes array, we must constantly verify if
/// we are not reading past its ending. This struct helps us decrease the number of checks we do,
/// by merging checks when we can determine the size of what to read beforehand.
pub(crate) struct BufferValidator<'a> {
/// Saves the codegen::Expression that contains the buffer length.
buffer_length: Expression,
/// The types we are supposed to decode
types: &'a [Type],
/// The argument whose size has already been accounted for when verifying the buffer
verified_until: Option<usize>,
/// The argument we are analysing presently
current_arg: usize,
}
impl BufferValidator<'_> {
pub fn new(buffer_size_var: usize, types: &[Type]) -> BufferValidator<'_> {
BufferValidator {
buffer_length: Expression::Variable {
loc: Loc::Codegen,
ty: Type::Uint(32),
var_no: buffer_size_var,
},
types,
verified_until: None,
current_arg: 0,
}
}
/// Set which item we are currently reading from the buffer
pub(super) fn set_argument_number(&mut self, arg_no: usize) {
self.current_arg = arg_no;
}
/// Initialize the validator, by verifying every type that has a fixed size
pub(super) fn initialize_validation(
&mut self,
offset: &Expression,
ns: &Namespace,
vartab: &mut Vartable,
cfg: &mut ControlFlowGraph,
) {
// -1 means nothing has been verified yet
self.verified_until = None;
self._verify_buffer(offset, ns, vartab, cfg);
}
/// Validate the buffer for the current argument, if necessary.
pub(super) fn validate_buffer(
&mut self,
offset: &Expression,
ns: &Namespace,
vartab: &mut Vartable,
cfg: &mut ControlFlowGraph,
) {
// We may have already verified this
if self.verified_until.is_some() && self.current_arg <= self.verified_until.unwrap() {
return;
}
self._verify_buffer(offset, ns, vartab, cfg);
}
/// Validate if a given offset is within the buffer's bound.
pub(super) fn validate_offset(
&self,
offset: Expression,
ns: &Namespace,
vartab: &mut Vartable,
cfg: &mut ControlFlowGraph,
) {
self.build_out_of_bounds_fail_branch(offset, ns, vartab, cfg);
}
/// Checks if a buffer validation is necessary
pub(super) fn validation_necessary(&self) -> bool {
self.verified_until.is_none() || self.current_arg > self.verified_until.unwrap()
}
/// After an array validation, we do not need to re-check its elements.
pub(super) fn validate_array(&mut self) {
self.verified_until = Some(self.current_arg);
}
/// Validate if offset + size is within the buffer's boundaries
pub(super) fn validate_offset_plus_size(
&mut self,
offset: &Expression,
size: &Expression,
ns: &Namespace,
vartab: &mut Vartable,
cfg: &mut ControlFlowGraph,
) {
if self.validation_necessary() {
let offset_to_validate = Expression::Add {
loc: Loc::Codegen,
ty: Type::Uint(32),
overflowing: false,
left: Box::new(offset.clone()),
right: Box::new(size.clone()),
};
self.validate_offset(offset_to_validate, ns, vartab, cfg);
}
}
/// Validates if we have read all the bytes in a buffer
pub(super) fn validate_all_bytes_read(
&self,
end_offset: Expression,
ns: &Namespace,
vartab: &mut Vartable,
cfg: &mut ControlFlowGraph,
) {
let cond = Expression::Less {
loc: Loc::Codegen,
signed: false,
left: Box::new(end_offset),
right: Box::new(self.buffer_length.clone()),
};
let invalid = cfg.new_basic_block("not_all_bytes_read".to_string());
let valid = cfg.new_basic_block("buffer_read".to_string());
cfg.add(
vartab,
Instr::BranchCond {
cond,
true_block: invalid,
false_block: valid,
},
);
cfg.set_basic_block(invalid);
// Use ArrayIndexOob panic code for proper Solidity-compliant error reporting
let error = SolidityError::Panic(PanicCode::ArrayIndexOob);
assert_failure(&Loc::Codegen, error, ns, cfg, vartab);
cfg.set_basic_block(valid);
}
/// Auxiliary function to verify if the offset is valid.
fn _verify_buffer(
&mut self,
offset: &Expression,
ns: &Namespace,
vartab: &mut Vartable,
cfg: &mut ControlFlowGraph,
) {
// Calculate the what arguments we can validate
let mut maximum_verifiable = self.current_arg;
for i in self.current_arg..self.types.len() {
if !self.types[i].is_dynamic(ns) {
maximum_verifiable = i;
} else {
break;
}
}
// It is not possible to validate anything
if maximum_verifiable == self.current_arg {
return;
}
// Create validation check
let mut advance = BigInt::zero();
for i in self.current_arg..=maximum_verifiable {
advance.add_assign(self.types[i].memory_size_of(ns));
}
let reach = Expression::Add {
loc: Loc::Codegen,
ty: Type::Uint(32),
overflowing: false,
left: Box::new(offset.clone()),
right: Box::new(Expression::NumberLiteral {
loc: Loc::Codegen,
ty: Type::Uint(32),
value: advance,
}),
};
self.verified_until = Some(maximum_verifiable);
self.build_out_of_bounds_fail_branch(reach, ns, vartab, cfg);
}
/// Builds a branch for failing if we are out of bounds
fn build_out_of_bounds_fail_branch(
&self,
offset: Expression,
ns: &Namespace,
vartab: &mut Vartable,
cfg: &mut ControlFlowGraph,
) {
let cond = Expression::LessEqual {
loc: Loc::Codegen,
signed: false,
left: Box::new(offset),
right: Box::new(self.buffer_length.clone()),
};
let inbounds_block = cfg.new_basic_block("inbounds".to_string());
let out_of_bounds_block = cfg.new_basic_block("out_of_bounds".to_string());
cfg.add(
vartab,
Instr::BranchCond {
cond,
true_block: inbounds_block,
false_block: out_of_bounds_block,
},
);
cfg.set_basic_block(out_of_bounds_block);
// Use ArrayIndexOob panic code for proper Solidity-compliant error reporting
let error = SolidityError::Panic(PanicCode::ArrayIndexOob);
assert_failure(&Loc::Codegen, error, ns, cfg, vartab);
cfg.set_basic_block(inbounds_block);
}
/// Create a new buffer validator to validate struct fields.
pub(super) fn create_sub_validator<'a>(&self, types: &'a [Type]) -> BufferValidator<'a> {
// If the struct has been previously validated, there is no need to validate it again,
// so verified_until and current_arg are set to type.len() to avoid any further validation.
BufferValidator {
buffer_length: self.buffer_length.clone(),
types,
verified_until: if self.validation_necessary() {
None
} else {
Some(types.len())
},
current_arg: if self.validation_necessary() {
0
} else {
types.len()
},
}
}
}