Coverage Report

Created: 2020-11-21 08:34

/src/botan/src/lib/utils/ct_utils.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* (C) 2018 Jack Lloyd
3
*
4
* Botan is released under the Simplified BSD License (see license.txt)
5
*/
6
7
#include <botan/internal/ct_utils.h>
8
9
namespace Botan {
10
11
namespace CT {
12
13
secure_vector<uint8_t> copy_output(CT::Mask<uint8_t> bad_input,
14
                                   const uint8_t input[],
15
                                   size_t input_length,
16
                                   size_t offset)
17
2.84k
   {
18
2.84k
   if(input_length == 0)
19
0
      return secure_vector<uint8_t>();
20
21
   /*
22
   * Ensure at runtime that offset <= input_length. This is an invalid input,
23
   * but we can't throw without using the poisoned value. Instead, if it happens,
24
   * set offset to be equal to the input length (so output_bytes becomes 0 and
25
   * the returned vector is empty)
26
   */
27
2.84k
   const auto valid_offset = CT::Mask<size_t>::is_lte(offset, input_length);
28
2.84k
   offset = valid_offset.select(offset, input_length);
29
30
2.84k
   const size_t output_bytes = input_length - offset;
31
32
2.84k
   secure_vector<uint8_t> output(input_length);
33
34
   /*
35
   Move the desired output bytes to the front using a slow (O^n)
36
   but constant time loop that does not leak the value of the offset
37
   */
38
1.06M
   for(size_t i = 0; i != input_length; ++i)
39
1.06M
      {
40
      /*
41
      start index from i rather than 0 since we know j must be >= i + offset
42
      to have any effect, and starting from i does not reveal information
43
      */
44
1.32G
      for(size_t j = i; j != input_length; ++j)
45
1.31G
         {
46
1.31G
         const uint8_t b = input[j];
47
1.31G
         const auto is_eq = CT::Mask<size_t>::is_equal(j, offset + i);
48
1.31G
         output[i] |= is_eq.if_set_return(b);
49
1.31G
         }
50
1.06M
      }
51
52
2.84k
   bad_input.if_set_zero_out(output.data(), output.size());
53
54
2.84k
   CT::unpoison(output.data(), output.size());
55
2.84k
   CT::unpoison(output_bytes);
56
57
   /*
58
   This is potentially not const time, depending on how std::vector is
59
   implemented. But since we are always reducing length, it should
60
   just amount to setting the member var holding the length.
61
   */
62
2.84k
   output.resize(output_bytes);
63
2.84k
   return output;
64
2.84k
   }
65
66
secure_vector<uint8_t> strip_leading_zeros(const uint8_t in[], size_t length)
67
2.44k
   {
68
2.44k
   size_t leading_zeros = 0;
69
70
2.44k
   auto only_zeros = Mask<uint8_t>::set();
71
72
636k
   for(size_t i = 0; i != length; ++i)
73
634k
      {
74
634k
      only_zeros &= CT::Mask<uint8_t>::is_zero(in[i]);
75
634k
      leading_zeros += only_zeros.if_set_return(1);
76
634k
      }
77
78
2.44k
   return copy_output(CT::Mask<uint8_t>::cleared(), in, length, leading_zeros);
79
2.44k
   }
80
81
}
82
83
}