From 5d811c9d88f1be9caa384d85d5c56c1d90021864 Mon Sep 17 00:00:00 2001 From: René Korthaus Date: Tue, 15 Nov 2016 11:12:28 +0100 Subject: Check all padding bytes in ESP_Padding::unpad() --- src/lib/modes/mode_pad/mode_pad.cpp | 13 +++++++++---- src/tests/test_pad.cpp | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/lib/modes/mode_pad/mode_pad.cpp b/src/lib/modes/mode_pad/mode_pad.cpp index d4ab914cc..eb4ae42be 100644 --- a/src/lib/modes/mode_pad/mode_pad.cpp +++ b/src/lib/modes/mode_pad/mode_pad.cpp @@ -145,22 +145,27 @@ void ESP_Padding::add_padding(secure_vector& buffer, */ size_t ESP_Padding::unpad(const byte block[], size_t size) const { - byte last_byte = block[size-1]; + const byte last_byte = block[size-1]; if(last_byte > size) { throw Decoding_Error(name()); } + // try to do this in const time by looping over the entire block + const size_t pad_pos = size - last_byte; size_t i = size - 1; - while(i > size - last_byte) + while(i) { if(block[i-1] != block[i]-1) { - throw Decoding_Error(name()); + if(i > pad_pos) + { + throw Decoding_Error(name()); + } } --i; } - return i; + return pad_pos; } diff --git a/src/tests/test_pad.cpp b/src/tests/test_pad.cpp index 6c9d1b85a..0eb14beb8 100644 --- a/src/tests/test_pad.cpp +++ b/src/tests/test_pad.cpp @@ -50,6 +50,21 @@ class Cipher_Mode_Padding_Tests : public Text_Based_Test return result; } + + std::vector run_final_tests() + { + Test::Result result("ESP negative tests"); + + std::vector invalid1 { 0xFF, 0x01, 0x02, 0x02 }; + result.test_throws("ESP invalid last pad", [&invalid1]() + { Botan::ESP_Padding().unpad(invalid1.data(), invalid1.size()); } ); + + std::vector invalid2 { 0xFF, 0x01, 0x02, 0x04 }; + result.test_throws("ESP invalid pad", [&invalid2]() + { Botan::ESP_Padding().unpad(invalid2.data(), invalid2.size()); } ); + + return {result}; + } }; BOTAN_REGISTER_TEST("bc_pad", Cipher_Mode_Padding_Tests); -- cgit v1.2.3