Ver Fonte

zkas: fix index out of bounds panic

The decode() function panics when the input length is less than 10 bytes
in size due to direct magic-number indexing on the vector elements. This
check returns an error when the input is too small.
y há 3 anos atrás
pai
commit
f6d1915556
2 ficheiros alterados com 12 adições e 1 exclusões
  1. 6 0
      src/zkas/constants.rs
  2. 6 1
      src/zkas/decoder.rs

+ 6 - 0
src/zkas/constants.rs

@@ -22,5 +22,11 @@ pub const MAX_K: u32 = 16;
 /// Maximum allowed namespace length in bytes
 pub const MAX_NS_LEN: usize = 32;
 
+/// Minimum size allowed for a syntactically valid ZkBinary
+/// MAGIC_BYTES.length = 4;
+/// `k = ##;` = 6 (because the current upper-limit for k is a two-digit number
+/// Therefore 4 + 6 = 10 is the minimum size
+pub const MIN_BIN_SIZE: usize = 10;
+
 /// Allowed fields for proofs
 pub const ALLOWED_FIELDS: [&str; 1] = ["pallas"];

+ 6 - 1
src/zkas/decoder.rs

@@ -20,7 +20,7 @@ use darkfi_serial::{deserialize_partial, VarInt};
 
 use super::{
     compiler::MAGIC_BYTES,
-    constants::{MAX_K, MAX_NS_LEN},
+    constants::{MAX_K, MAX_NS_LEN, MIN_BIN_SIZE},
     types::HeapType,
     LitType, Opcode, VarType,
 };
@@ -45,6 +45,11 @@ fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
 
 impl ZkBinary {
     pub fn decode(bytes: &[u8]) -> Result<Self> {
+        // Ensure that bytes is a certain minimum length. Otherwise the code
+        // below will panic due to an index out of bounds error.
+        if bytes.len() < MIN_BIN_SIZE {
+            return Err(ZkasErr("Not enough bytes".to_string()))
+        }
         let magic_bytes = &bytes[0..4];
         if magic_bytes != MAGIC_BYTES {
             return Err(ZkasErr("Magic bytes are incorrect".to_string()))