Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ABI decoder crashing on certain inputs #1130

Merged
merged 21 commits into from
Oct 17, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
a261104
fix: handle division by zero
Br1ght0ne Sep 5, 2023
a113596
fix: handle multiplication with overflow
Br1ght0ne Sep 5, 2023
c25bd99
fix: handle Results throughout decoder, add regressions to tests
Br1ght0ne Sep 5, 2023
22a6818
Merge branch 'master' into oleksii/abi-decoder-crashes
Br1ght0ne Sep 11, 2023
a6d65db
Merge branch 'master' into oleksii/abi-decoder-crashes
Br1ght0ne Sep 25, 2023
8953322
fix: add DebugWithDepth to Debug-format nested types
Br1ght0ne Sep 25, 2023
bfeaf61
Merge branch 'master' into oleksii/abi-decoder-crashes
Br1ght0ne Sep 27, 2023
065a9d8
Merge branch 'master' into oleksii/abi-decoder-crashes
Br1ght0ne Sep 27, 2023
c75cb89
Merge branch 'master' into oleksii/abi-decoder-crashes
hal3e Sep 29, 2023
306b69e
Merge branch 'master' into oleksii/abi-decoder-crashes
segfault-magnet Oct 4, 2023
de2c049
Merge branch 'master' into oleksii/abi-decoder-crashes
hal3e Oct 5, 2023
7a128b2
Apply suggestions from code review
Br1ght0ne Oct 5, 2023
13381c4
Apply rest of the suggestions, renaming, cargo fmt
Br1ght0ne Oct 5, 2023
8b3dab1
Merge branch 'master' into oleksii/abi-decoder-crashes
hal3e Oct 6, 2023
a7a9acc
Merge branch 'master' into oleksii/abi-decoder-crashes
Br1ght0ne Oct 6, 2023
3da2abc
Move `DebugWithDepth` to `param_types.rs`
Br1ght0ne Oct 6, 2023
b0ba5b4
Merge branch 'master' into oleksii/abi-decoder-crashes
hal3e Oct 9, 2023
5891c94
Merge branch 'master' into oleksii/abi-decoder-crashes
Br1ght0ne Oct 16, 2023
3742a4e
Use full type names in test messages
Br1ght0ne Oct 16, 2023
66e577e
Re-wrap multiplication of `bytes_to_skip`
Br1ght0ne Oct 16, 2023
1daf0a9
Merge branch 'master' into oleksii/abi-decoder-crashes
Br1ght0ne Oct 16, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 100 additions & 42 deletions packages/fuels-core/src/codec/abi_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl Default for DecoderConfig {

#[derive(Default)]
pub struct ABIDecoder {
config: DecoderConfig,
pub config: DecoderConfig,
}

impl ABIDecoder {
Expand Down Expand Up @@ -84,6 +84,7 @@ mod tests {
use std::vec;

use super::*;
use crate::traits::Parameterize;
use crate::types::U256;
use crate::{
constants::WORD_SIZE,
Expand Down Expand Up @@ -524,95 +525,152 @@ mod tests {

#[test]
pub fn division_by_zero() {
let result = ABIDecoder::default().decode(&Vector(Box::new(Array(Box::new(U16), 0))), &[]);
let param_type = Vec::<[u16; 0]>::param_type();
let result = ABIDecoder::default().decode(&param_type, &[]);
assert!(matches!(result, Err(Error::InvalidType(_))));
}

#[test]
pub fn multiply_overflow_enum() {
let result = ABIDecoder::default().decode(
&Enum {
variants: EnumVariants {
param_types: vec![
Array(Box::new(Array(Box::new(RawSlice), 8)), 576469587185895432),
B256,
B256,
B256,
B256,
B256,
B256,
B256,
B256,
B256,
B256,
],
},
variants: EnumVariants::new(vec![
Array(Box::new(Array(Box::new(RawSlice), 8)), usize::MAX),
B256,
B256,
B256,
B256,
B256,
B256,
B256,
B256,
B256,
B256,
])
.unwrap(),
generics: vec![U16],
},
&[0, 8, 8, 8, 9, 8, 0, 8, 8, 8, 8, 8, 15, 8, 8, 8],
&[],
);
assert!(matches!(result, Err(Error::InvalidData(_))));
assert!(matches!(result, Err(Error::InvalidType(_))));
}

#[test]
pub fn multiply_overflow_vector() {
let result = ABIDecoder::default().decode(
&Vector(Box::new(Array(Box::new(Unit), 2308103648053880071))),
&[8, 8, 10, 7, 229, 8, 8, 8],
);
let param_type = Vec::<[(); usize::MAX]>::param_type();
let result = ABIDecoder::default().decode(&param_type, &[]);
assert!(matches!(result, Err(Error::InvalidData(_))));
}

#[test]
pub fn multiply_overflow_arith() {
let mut typ: ParamType = U16;
let mut param_type: ParamType = U16;
for _ in 0..50 {
typ = Array(Box::new(typ), 8);
param_type = Array(Box::new(param_type), 8);
}
Br1ght0ne marked this conversation as resolved.
Show resolved Hide resolved
let result = ABIDecoder::default().decode(
&Enum {
variants: EnumVariants {
param_types: vec![typ],
},
variants: EnumVariants::new(vec![param_type]).unwrap(),
generics: vec![U16],
},
&[0, 8, 8, 51, 51, 51, 51, 51, 51, 51, 3, 8, 15, 8, 8, 8],
&[],
);
assert!(matches!(result, Err(Error::InvalidData(_))));
}

#[test]
pub fn capacity_overflow() {
let result = ABIDecoder::default().decode(
&Array(
Box::new(Array(Box::new(Tuple(vec![])), 7638104972323651592)),
242,
),
&[13, 0, 1, 0, 0, 106, 242, 8],
&Array(Box::new(Array(Box::new(Tuple(vec![])), usize::MAX)), 1),
&[],
);
dbg!(&result);
assert!(matches!(result, Err(Error::InvalidType(_))));
}

#[test]
pub fn stack_overflow() {
let mut typ: ParamType = U16;
let mut param_type: ParamType = U16;
for _ in 0..13500 {
typ = Vector(Box::new(typ));
param_type = Vector(Box::new(param_type));
}
Br1ght0ne marked this conversation as resolved.
Show resolved Hide resolved
let result = ABIDecoder::default().decode(&typ, &[8, 9, 9, 9, 9, 9, 9, 9]);
let result = ABIDecoder::default().decode(&param_type, &[]);
assert!(matches!(result, Err(Error::InvalidType(_))));
}

#[test]
pub fn capacity_maloc() {
let result = ABIDecoder::default().decode(
&Array(Box::new(U8), 72340198607880449),
&[8, 8, 7, 252, 201, 8, 8, 8],
);
let param_type = Array(Box::new(U8), usize::MAX);
let result = ABIDecoder::default().decode(&param_type, &[]);
assert!(matches!(result, Err(Error::InvalidData(_))));
}

#[test]
fn decoding_enum_with_more_than_one_heap_type_variant_fails() -> Result<()> {
let mut param_types = vec![
ParamType::U64,
ParamType::Bool,
ParamType::Vector(Box::from(ParamType::U64)),
];
// empty data
let data = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
let variants = EnumVariants::new(param_types.clone())?;
let enum_param_type = ParamType::Enum {
variants,
generics: vec![],
};
// it works if there is only one heap type
let _ = ABIDecoder::default().decode(&enum_param_type, &data)?;

param_types.append(&mut vec![ParamType::Bytes]);
let variants = EnumVariants::new(param_types)?;
let enum_param_type = ParamType::Enum {
variants,
generics: vec![],
};
// fails if there is more than one variant using heap type in the enum
let error = ABIDecoder::default()
.decode(&enum_param_type, &data)
.expect_err("Should fail");
let expected_error =
"Invalid type: Enums currently support only one heap-type variant. Found: 2"
.to_string();
assert_eq!(error.to_string(), expected_error);

Ok(())
}

#[test]
fn enums_w_too_deeply_nested_heap_types_not_allowed() {
let param_types = vec![
ParamType::U8,
ParamType::Struct {
fields: vec![ParamType::RawSlice],
generics: vec![],
},
];
let variants = EnumVariants::new(param_types).unwrap();
let enum_param_type = ParamType::Enum {
variants,
generics: vec![],
};

let err = ABIDecoder::default()
.decode(&enum_param_type, &[])
.expect_err("should have failed");

let Error::InvalidType(msg) = err else {
panic!("Unexpected err: {err}");
};

assert_eq!(
msg,
"Enums currently support only one level deep heap types."
);
}

#[test]
fn max_depth_surpassed() {
const MAX_DEPTH: usize = 2;
Expand Down
119 changes: 15 additions & 104 deletions packages/fuels-core/src/codec/abi_decoder/bounded_decoder.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{convert::TryInto, fmt, str};
use std::{convert::TryInto, str};

use fuel_types::bytes::padded_len_usize;

Expand Down Expand Up @@ -38,7 +38,7 @@ impl BoundedDecoder {
}

pub(crate) fn decode(&mut self, param_type: &ParamType, bytes: &[u8]) -> Result<Token> {
self.is_type_decodable(param_type)?;
param_type.validate_is_decodable(self.config.max_depth)?;
Ok(self.decode_param(param_type, bytes)?.token)
}

Expand All @@ -48,25 +48,13 @@ impl BoundedDecoder {
bytes: &[u8],
) -> Result<Vec<Token>> {
for param_type in param_types {
self.is_type_decodable(param_type)?;
param_type.validate_is_decodable(self.config.max_depth)?;
}
let (tokens, _) = self.decode_params(param_types, bytes)?;

Ok(tokens)
}

fn is_type_decodable(&self, param_type: &ParamType) -> Result<()> {
if param_type.contains_nested_heap_types() {
Err(error!(
InvalidType,
"Type {:?} contains nested heap types (`Vec` or `Bytes`), this is not supported.",
DebugWithDepth::new(param_type, self.config.max_depth)
))
} else {
Ok(())
}
}

fn run_w_depth_tracking(
&mut self,
decoder: impl FnOnce(&mut Self) -> Result<Decoded>,
Expand Down Expand Up @@ -316,8 +304,18 @@ impl BoundedDecoder {
let discriminant = peek_u32(bytes)? as u8;
let selected_variant = variants.param_type_of_variant(discriminant)?;

let words_to_skip = enum_width - selected_variant.compute_encoding_width()?;
let bytes_to_skip = words_to_skip .checked_mul(WORD_SIZE).ok_or_else(|| error!(InvalidData, "attempt to multiply words_to_skip ({words_to_skip:?}) by WORD_SIZE ({WORD_SIZE:?}) with overflow"))?;
let skip_extra = variants
.heap_type_variant()
.is_some_and(|(heap_discriminant, _)| heap_discriminant == discriminant)
.then_some(3);
let words_to_skip = enum_width - selected_variant.compute_encoding_width()?
+ skip_extra.unwrap_or_default();
let bytes_to_skip = words_to_skip.checked_mul(WORD_SIZE).ok_or_else(|| {
error!(
InvalidData,
"Overflow error while decoding enum {variants:?}"
)
})?;
let enum_content_bytes = skip(bytes, bytes_to_skip)?;
let result = self.decode_token_in_enum(enum_content_bytes, variants, selected_variant)?;

Expand Down Expand Up @@ -461,90 +459,3 @@ fn skip(slice: &[u8], num_bytes: usize) -> Result<&[u8]> {
Ok(&slice[num_bytes..])
}
}

/// Allows `Debug` formatting of arbitrary-depth nested `ParamTypes` by
/// omitting the details of inner types if max depth is exceeded.
pub(crate) struct DebugWithDepth<'a> {
param_type: &'a ParamType,
depth_left: usize,
}

impl<'a> DebugWithDepth<'a> {
pub(crate) fn new(param_type: &'a ParamType, depth_left: usize) -> Self {
Self {
param_type,
depth_left,
}
}

fn descend(&'a self, param_type: &'a ParamType) -> Self {
Self {
param_type,
depth_left: self.depth_left - 1,
}
}
}

impl<'a> fmt::Debug for DebugWithDepth<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.depth_left == 0 {
return write!(f, "...");
}

match &self.param_type {
ParamType::Array(inner, size) => f
.debug_tuple("Array")
.field(&self.descend(inner))
.field(&size)
.finish(),
ParamType::Struct { fields, generics } => f
.debug_struct("Struct")
.field(
"fields",
&fields
.iter()
.map(|field| self.descend(field))
.collect::<Vec<_>>(),
)
.field(
"generics",
&generics
.iter()
.map(|generic| self.descend(generic))
.collect::<Vec<_>>(),
)
.finish(),
ParamType::Enum { variants, generics } => f
.debug_struct("Enum")
.field(
"variants",
&variants
.param_types
.iter()
.map(|variant| self.descend(variant))
.collect::<Vec<_>>(),
)
.field(
"generics",
&generics
.iter()
.map(|generic| self.descend(generic))
.collect::<Vec<_>>(),
)
.finish(),
ParamType::Tuple(inner) => f
.debug_tuple("Tuple")
.field(
&inner
.iter()
.map(|param_type| self.descend(param_type))
.collect::<Vec<_>>(),
)
.finish(),
ParamType::Vector(inner) => {
f.debug_tuple("Vector").field(&self.descend(inner)).finish()
}
_ => write!(f, "{:?}", self.param_type),
}
}
}
2 changes: 1 addition & 1 deletion packages/fuels-core/src/types/enum_variants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EnumVariants {
pub param_types: Vec<ParamType>,
param_types: Vec<ParamType>,
}

impl EnumVariants {
Expand Down
Loading
Loading