From a0e1d2e7061e5e3fec1ea07071bb1be34f58a4a0 Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Sun, 19 Sep 2021 13:17:53 +0200 Subject: [PATCH] Check for overflow in Script::bytes_to_asm_fmt() This adds an overflow check in `Script::bytes_to_asm_fmt()` motivated by `electrs` issue. While it was not tested yet, I'm very confident that overflow is the cause of panic there and even if not it can cause panic becuase the public function takes unvalidated byte array and reads `data_len` from it. The `electrs` issue: https://github.com/romanz/electrs/issues/490 --- src/blockdata/script.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/blockdata/script.rs b/src/blockdata/script.rs index 2651325d..888119d0 100644 --- a/src/blockdata/script.rs +++ b/src/blockdata/script.rs @@ -529,14 +529,17 @@ impl Script { // Write any pushdata if data_len > 0 { f.write_str(" ")?; - if index + data_len <= script.len() { - for ch in &script[index..index + data_len] { + match index.checked_add(data_len) { + Some(end) if end <= script.len() => { + for ch in &script[index..end] { write!(f, "{:02x}", ch)?; - } - index += data_len; - } else { - f.write_str("")?; - break; + } + index = end; + }, + _ => { + f.write_str("")?; + break; + }, } } }