From e2daf4f5970b3e329c3279499db1ab1fa3909d15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20Sch=C3=BCtt?= Date: Tue, 23 Aug 2022 14:39:28 +0200 Subject: [PATCH] Test metadata slice len before accessing to prevent panic --- lib/compiler/src/engine/artifact.rs | 25 ++++++++++++++++++++++++- lib/types/src/error.rs | 8 ++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/compiler/src/engine/artifact.rs b/lib/compiler/src/engine/artifact.rs index 2608723a037..f362ed4de83 100644 --- a/lib/compiler/src/engine/artifact.rs +++ b/lib/compiler/src/engine/artifact.rs @@ -116,9 +116,32 @@ impl Artifact { "The provided bytes are not wasmer-universal".to_string(), )); } + + if bytes.len() < ArtifactBuild::MAGIC_HEADER.len() { + return Err(DeserializeError::InvalidByteLength { + expected: ArtifactBuild::MAGIC_HEADER.len(), + got: bytes.len(), + }); + } + let bytes = &bytes[ArtifactBuild::MAGIC_HEADER.len()..]; let metadata_len = MetadataHeader::parse(bytes)?; - let metadata_slice: &[u8] = &bytes[MetadataHeader::LEN..][..metadata_len]; + if bytes.len() < MetadataHeader::LEN { + return Err(DeserializeError::InvalidByteLength { + expected: MetadataHeader::LEN, + got: bytes.len(), + }); + } + + let metadata_slice: &[u8] = &bytes[MetadataHeader::LEN..]; + if metadata_slice.len() < metadata_len { + return Err(DeserializeError::InvalidByteLength { + expected: metadata_len + MetadataHeader::LEN, + got: bytes.len(), + }); + } + + let metadata_slice: &[u8] = &metadata_slice[..metadata_len]; let serializable = SerializableModule::deserialize(metadata_slice)?; let artifact = ArtifactBuild::from_serializable(serializable); let mut inner_engine = engine.inner_mut(); diff --git a/lib/types/src/error.rs b/lib/types/src/error.rs index 0e0a1eb12fd..8f99f9419aa 100644 --- a/lib/types/src/error.rs +++ b/lib/types/src/error.rs @@ -35,6 +35,14 @@ pub enum DeserializeError { /// trying to allocate the required resources. #[error(transparent)] Compiler(#[from] CompileError), + /// Input artifact bytes have an invalid length + #[error("invalid input bytes: expected {expected} bytes, got {got}")] + InvalidByteLength { + /// How many bytes were expected + expected: usize, + /// How many bytes the artifact contained + got: usize, + } } /// Error type describing things that can go wrong when operating on Wasm Memories.