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

de::Builder and sequence length limit #12

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
225 changes: 172 additions & 53 deletions src/de.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,138 @@
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

//! BCS deserialization

use crate::error::{Error, Result};
use serde::de::{self, Deserialize, DeserializeOwned, DeserializeSeed, IntoDeserializer, Visitor};
use std::{convert::TryFrom, io::Read};
use std::{convert::TryFrom, io::Read, marker::PhantomData};

/// Builder API to configure deserialization.
///
/// # Examples
///
/// ```
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Ip([u8; 4]);
///
/// #[derive(Deserialize)]
/// struct Port(u16);
///
/// #[derive(Deserialize)]
/// struct SocketAddr {
/// ip: Ip,
/// port: Port,
/// }
///
/// let bytes = vec![0x7f, 0x00, 0x00, 0x01, 0x41, 0x1f];
/// let socket_addr: SocketAddr =
/// bcs::de::Builder::new()
/// .max_sequence_length(1_024 * 1_024)
/// .max_container_depth(64)
/// .deserialize_bytes(&bytes)
/// .unwrap();
///
/// assert_eq!(socket_addr.ip.0, [127, 0, 0, 1]);
/// assert_eq!(socket_addr.port.0, 8001);
/// ```
pub struct Builder<T> {
max_container_depth: usize,
max_sequence_length: usize,
seed: T,
}

impl<T> Builder<PhantomData<T>> {
/// Creates a `Builder` instance with default parameter values.
pub fn new() -> Self {
Self::with_seed(PhantomData)
}
}

impl<S> Builder<S> {
/// Creates a `Builder` with the given seed value for stateful deserialization.
/// The other parameters are initialized with default values.
pub fn with_seed(seed: S) -> Builder<S> {
Self {
max_container_depth: crate::MAX_CONTAINER_DEPTH,
max_sequence_length: crate::MAX_SEQUENCE_LENGTH,
seed,
}
}
}

impl<T: Default> Default for Builder<T> {
fn default() -> Self {
Builder::with_seed(Default::default())
}
}

impl<T> Builder<T> {
/// Sets the limit on depth of nested BCS data.
///
/// The default is the [well-known limit][crate::MAX_CONTAINER_DEPTH]
/// defined for BCS.
/// If the value passed is larger than that, deserialization with this
/// `Builder` will fail with an error.
pub fn max_container_depth(mut self, limit: usize) -> Self {
self.max_container_depth = limit;
self
}

/// Set the length limit on variable-length sequences: byte arrays,
/// strings, sequences and maps. Encountering an encoded sequence
/// with a greater length will cause deserialization to fail with an
/// `ExceededMaxLen` error.
///
/// The default is the [well-known limit][crate::MAX_SEQUENCE_LENGTH]
/// defined for BCS.
/// If the value passed is larger than that, deserialization with this
/// `Builder` will fail with an error.
pub fn max_sequence_length(mut self, limit: usize) -> Self {
self.max_sequence_length = limit;
self
}

fn check_sanity(&self) -> Result<(), Error> {
if self.max_container_depth > crate::MAX_CONTAINER_DEPTH {
return Err(Error::NotSupported(
"container depth limit exceeds the max allowed depth",
));
}
if self.max_sequence_length > crate::MAX_SEQUENCE_LENGTH {
return Err(Error::NotSupported(
"sequence length limit exceeds the max sequence length",
));
}
Ok(())
}
}

impl<'a, T> Builder<T>
where
T: DeserializeSeed<'a>,
{
/// Deserializes a value from an `&[u8]` using the configured parameters.
pub fn deserialize_bytes(self, bytes: &'a [u8]) -> Result<T::Value> {
self.check_sanity()?;
let mut deserializer =
Deserializer::new(bytes, self.max_container_depth, self.max_sequence_length);
let t = self.seed.deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
}

/// Deserializes a value from an implementation of [`Read`] using the configured parameters.
pub fn deserialize_reader(self, reader: &'a mut impl Read) -> Result<T::Value> {
self.check_sanity()?;
let mut deserializer =
Deserializer::from_reader(reader, self.max_container_depth, self.max_sequence_length);
let t = self.seed.deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
}
}

/// Deserializes a `&[u8]` into a type.
///
Expand Down Expand Up @@ -38,10 +167,7 @@ pub fn from_bytes<'a, T>(bytes: &'a [u8]) -> Result<T>
where
T: Deserialize<'a>,
{
let mut deserializer = Deserializer::new(bytes, crate::MAX_CONTAINER_DEPTH);
let t = T::deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
Builder::new().deserialize_bytes(bytes)
}

/// Same as `from_bytes` but use `limit` as max container depth instead of MAX_CONTAINER_DEPTH`
Expand All @@ -50,24 +176,17 @@ pub fn from_bytes_with_limit<'a, T>(bytes: &'a [u8], limit: usize) -> Result<T>
where
T: Deserialize<'a>,
{
if limit > crate::MAX_CONTAINER_DEPTH {
return Err(Error::NotSupported("limit exceeds the max allowed depth"));
}
let mut deserializer = Deserializer::new(bytes, limit);
let t = T::deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
Builder::new()
.max_container_depth(limit)
.deserialize_bytes(bytes)
}

/// Perform a stateful deserialization from a `&[u8]` using the provided `seed`.
pub fn from_bytes_seed<'a, T>(seed: T, bytes: &'a [u8]) -> Result<T::Value>
where
T: DeserializeSeed<'a>,
{
let mut deserializer = Deserializer::new(bytes, crate::MAX_CONTAINER_DEPTH);
let t = seed.deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
Builder::with_seed(seed).deserialize_bytes(bytes)
}

/// Same as `from_bytes_seed` but use `limit` as max container depth instead of MAX_CONTAINER_DEPTH`
Expand All @@ -76,24 +195,17 @@ pub fn from_bytes_seed_with_limit<'a, T>(seed: T, bytes: &'a [u8], limit: usize)
where
T: DeserializeSeed<'a>,
{
if limit > crate::MAX_CONTAINER_DEPTH {
return Err(Error::NotSupported("limit exceeds the max allowed depth"));
}
let mut deserializer = Deserializer::new(bytes, limit);
let t = seed.deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
Builder::with_seed(seed)
.max_container_depth(limit)
.deserialize_bytes(bytes)
}

/// Deserialize a type from an implementation of [`Read`].
pub fn from_reader<T>(mut reader: impl Read) -> Result<T>
where
T: DeserializeOwned,
{
let mut deserializer = Deserializer::from_reader(&mut reader, crate::MAX_CONTAINER_DEPTH);
let t = T::deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
Builder::new().deserialize_reader(&mut reader)
}

/// Same as `from_reader_seed` but use `limit` as max container depth instead of MAX_CONTAINER_DEPTH`
Expand All @@ -102,24 +214,17 @@ pub fn from_reader_with_limit<T>(mut reader: impl Read, limit: usize) -> Result<
where
T: DeserializeOwned,
{
if limit > crate::MAX_CONTAINER_DEPTH {
return Err(Error::NotSupported("limit exceeds the max allowed depth"));
}
let mut deserializer = Deserializer::from_reader(&mut reader, limit);
let t = T::deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
Builder::new()
.max_container_depth(limit)
.deserialize_reader(&mut reader)
}

/// Deserialize a type from an implementation of [`Read`] using the provided seed
pub fn from_reader_seed<T, V>(seed: T, mut reader: impl Read) -> Result<V>
where
for<'a> T: DeserializeSeed<'a, Value = V>,
{
let mut deserializer = Deserializer::from_reader(&mut reader, crate::MAX_CONTAINER_DEPTH);
let t = seed.deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
Builder::with_seed(seed).deserialize_reader(&mut reader)
}

/// Same as `from_reader_seed` but use `limit` as max container depth instead of MAX_CONTAINER_DEPTH`
Expand All @@ -128,37 +233,40 @@ pub fn from_reader_seed_with_limit<T, V>(seed: T, mut reader: impl Read, limit:
where
for<'a> T: DeserializeSeed<'a, Value = V>,
{
if limit > crate::MAX_CONTAINER_DEPTH {
return Err(Error::NotSupported("limit exceeds the max allowed depth"));
}
let mut deserializer = Deserializer::from_reader(&mut reader, limit);
let t = seed.deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(t)
Builder::with_seed(seed)
.max_container_depth(limit)
.deserialize_reader(&mut reader)
}

/// Deserialization implementation for BCS
struct Deserializer<R> {
input: R,
max_remaining_depth: usize,
max_sequence_length: usize,
}

impl<'de, R: Read> Deserializer<TeeReader<'de, R>> {
fn from_reader(input: &'de mut R, max_remaining_depth: usize) -> Self {
fn from_reader(
input: &'de mut R,
max_remaining_depth: usize,
max_sequence_length: usize,
) -> Self {
Deserializer {
input: TeeReader::new(input),
max_remaining_depth,
max_sequence_length,
}
}
}

impl<'de> Deserializer<&'de [u8]> {
/// Creates a new `Deserializer` which will be deserializing the provided
/// input.
fn new(input: &'de [u8], max_remaining_depth: usize) -> Self {
fn new(input: &'de [u8], max_remaining_depth: usize, max_sequence_length: usize) -> Self {
Deserializer {
input,
max_remaining_depth,
max_sequence_length,
}
}
}
Expand Down Expand Up @@ -191,7 +299,11 @@ impl<'de, R: Read> Read for TeeReader<'de, R> {
}
}

trait BcsDeserializer<'de> {
trait ValidateLength {
fn validate_length(&self, parsed_value: u32) -> Result<usize, Error>;
}

trait BcsDeserializer<'de>: ValidateLength {
type MaybeBorrowedBytes: AsRef<[u8]>;

fn fill_slice(&mut self, slice: &mut [u8]) -> Result<()>;
Expand Down Expand Up @@ -281,11 +393,8 @@ trait BcsDeserializer<'de> {
}

fn parse_length(&mut self) -> Result<usize> {
let len = self.parse_u32_from_uleb128()? as usize;
if len > crate::MAX_SEQUENCE_LENGTH {
return Err(Error::ExceededMaxLen(len));
}
Ok(len)
let parsed_value = self.parse_u32_from_uleb128()?;
self.validate_length(parsed_value)
}
}

Expand All @@ -303,6 +412,16 @@ impl<'de, R: Read> Deserializer<TeeReader<'de, R>> {
}
}

impl<R> ValidateLength for Deserializer<R> {
fn validate_length(&self, parsed_value: u32) -> Result<usize, Error> {
let len = parsed_value as usize;
if len > self.max_sequence_length {
return Err(Error::ExceededMaxLen(len));
}
Ok(len)
}
}

impl<'de, R: Read> BcsDeserializer<'de> for Deserializer<TeeReader<'de, R>> {
type MaybeBorrowedBytes = Vec<u8>;

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@
//! # Ok(())}
//! ```

mod de;
pub mod de;
mod error;
mod ser;
pub mod test_helpers;
Expand Down
12 changes: 9 additions & 3 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ where
T: ?Sized + Serialize,
{
if limit > crate::MAX_CONTAINER_DEPTH {
return Err(Error::NotSupported("limit exceeds the max allowed depth"));
return Err(Error::NotSupported(
"container depth limit exceeds the max allowed depth",
));
}
let mut output = Vec::new();
serialize_into_with_limit(&mut output, value, limit)?;
Expand All @@ -87,7 +89,9 @@ where
T: ?Sized + Serialize,
{
if limit > crate::MAX_CONTAINER_DEPTH {
return Err(Error::NotSupported("limit exceeds the max allowed depth"));
return Err(Error::NotSupported(
"container depth limit exceeds the max allowed depth",
));
}
let serializer = Serializer::new(write, limit);
value.serialize(serializer)
Expand Down Expand Up @@ -126,7 +130,9 @@ where
T: ?Sized + Serialize,
{
if limit > crate::MAX_CONTAINER_DEPTH {
return Err(Error::NotSupported("limit exceeds the max allowed depth"));
return Err(Error::NotSupported(
"container depth limit exceeds the max allowed depth",
));
}
let mut counter = WriteCounter(0);
serialize_into_with_limit(&mut counter, value, limit)?;
Expand Down
Loading