From 4a042d703f3953fa021f17770055ff566eda34b4 Mon Sep 17 00:00:00 2001 From: Heiko Schaefer Date: Thu, 13 Apr 2023 18:15:58 +0200 Subject: [PATCH] Don't panic if a long command is sent and the backend reports no support for extended length This case should not happen during normal operation with the pcsc backend. But the condition was triggered in tests with an alternate CardBackend implementation (see: https://gitlab.com/openpgp-card/openpgp-card/-/issues/69). --- openpgp-card/src/apdu/command.rs | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/openpgp-card/src/apdu/command.rs b/openpgp-card/src/apdu/command.rs index cdb6497..1a7c447 100644 --- a/openpgp-card/src/apdu/command.rs +++ b/openpgp-card/src/apdu/command.rs @@ -81,7 +81,7 @@ impl Command { let nc = self.data.len() as u16; let mut buf = vec![self.cla, self.ins, self.p1, self.p2]; - buf.extend(Self::make_lc(nc, ext_len)); + buf.extend(Self::make_lc(nc, ext_len)?); buf.extend(&self.data); buf.extend(Self::make_le(nc, ext_len, expect_response)); @@ -89,21 +89,19 @@ impl Command { } /// Encode len for Lc field - fn make_lc(len: u16, ext_len: bool) -> Vec { - if !ext_len { - assert!( - len <= 0xff, - "{}", - "unexpected: len = {len:x?}, but ext says Short" - ); + fn make_lc(len: u16, ext_len: bool) -> Result, crate::Error> { + if !ext_len && len > 0xff { + return Err(crate::Error::InternalError(format!( + "Command len = {len:x?}, but extended length is unsupported by backend" + ))); } if len == 0 { - vec![] + Ok(vec![]) } else if !ext_len { - vec![len as u8] + Ok(vec![len as u8]) } else { - vec![0, (len >> 8) as u8, (len & 255) as u8] + Ok(vec![0, (len >> 8) as u8, (len & 255) as u8]) } }