1 /**
2  *  Constant-time functions
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 #ifndef MBEDTLS_CONSTANT_TIME_INTERNAL_H
21 #define MBEDTLS_CONSTANT_TIME_INTERNAL_H
22 
23 #include "common.h"
24 
25 #if defined(MBEDTLS_BIGNUM_C)
26 #include "mbedtls/bignum.h"
27 #endif
28 
29 #if defined(MBEDTLS_SSL_TLS_C)
30 #include "mbedtls/ssl_internal.h"
31 #endif
32 
33 #include <stddef.h>
34 
35 
36 /** Turn a value into a mask:
37  * - if \p value == 0, return the all-bits 0 mask, aka 0
38  * - otherwise, return the all-bits 1 mask, aka (unsigned) -1
39  *
40  * This function can be used to write constant-time code by replacing branches
41  * with bit operations using masks.
42  *
43  * \param value     The value to analyze.
44  *
45  * \return          Zero if \p value is zero, otherwise all-bits-one.
46  */
47 unsigned mbedtls_ct_uint_mask( unsigned value );
48 
49 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
50 
51 /** Turn a value into a mask:
52  * - if \p value == 0, return the all-bits 0 mask, aka 0
53  * - otherwise, return the all-bits 1 mask, aka (size_t) -1
54  *
55  * This function can be used to write constant-time code by replacing branches
56  * with bit operations using masks.
57  *
58  * \param value     The value to analyze.
59  *
60  * \return          Zero if \p value is zero, otherwise all-bits-one.
61  */
62 size_t mbedtls_ct_size_mask( size_t value );
63 
64 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
65 
66 #if defined(MBEDTLS_BIGNUM_C)
67 
68 /** Turn a value into a mask:
69  * - if \p value == 0, return the all-bits 0 mask, aka 0
70  * - otherwise, return the all-bits 1 mask, aka (mbedtls_mpi_uint) -1
71  *
72  * This function can be used to write constant-time code by replacing branches
73  * with bit operations using masks.
74  *
75  * \param value     The value to analyze.
76  *
77  * \return          Zero if \p value is zero, otherwise all-bits-one.
78  */
79 mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask( mbedtls_mpi_uint value );
80 
81 #endif /* MBEDTLS_BIGNUM_C */
82 
83 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
84 
85 /** Constant-flow mask generation for "greater or equal" comparison:
86  * - if \p x >= \p y, return all-bits 1, that is (size_t) -1
87  * - otherwise, return all bits 0, that is 0
88  *
89  * This function can be used to write constant-time code by replacing branches
90  * with bit operations using masks.
91  *
92  * \param x     The first value to analyze.
93  * \param y     The second value to analyze.
94  *
95  * \return      All-bits-one if \p x is greater or equal than \p y,
96  *              otherwise zero.
97  */
98 size_t mbedtls_ct_size_mask_ge( size_t x,
99                                 size_t y );
100 
101 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
102 
103 /** Constant-flow boolean "equal" comparison:
104  * return x == y
105  *
106  * This is equivalent to \p x == \p y, but is likely to be compiled
107  * to code using bitwise operation rather than a branch.
108  *
109  * \param x     The first value to analyze.
110  * \param y     The second value to analyze.
111  *
112  * \return      1 if \p x equals to \p y, otherwise 0.
113  */
114 unsigned mbedtls_ct_size_bool_eq( size_t x,
115                                   size_t y );
116 
117 #if defined(MBEDTLS_BIGNUM_C)
118 
119 /** Decide if an integer is less than the other, without branches.
120  *
121  * This is equivalent to \p x < \p y, but is likely to be compiled
122  * to code using bitwise operation rather than a branch.
123  *
124  * \param x     The first value to analyze.
125  * \param y     The second value to analyze.
126  *
127  * \return      1 if \p x is less than \p y, otherwise 0.
128  */
129 unsigned mbedtls_ct_mpi_uint_lt( const mbedtls_mpi_uint x,
130                                  const mbedtls_mpi_uint y );
131 
132 #endif /* MBEDTLS_BIGNUM_C */
133 
134 /** Choose between two integer values without branches.
135  *
136  * This is equivalent to `condition ? if1 : if0`, but is likely to be compiled
137  * to code using bitwise operation rather than a branch.
138  *
139  * \param condition     Condition to test.
140  * \param if1           Value to use if \p condition is nonzero.
141  * \param if0           Value to use if \p condition is zero.
142  *
143  * \return  \c if1 if \p condition is nonzero, otherwise \c if0.
144  */
145 unsigned mbedtls_ct_uint_if( unsigned condition,
146                              unsigned if1,
147                              unsigned if0 );
148 
149 #if defined(MBEDTLS_BIGNUM_C)
150 
151 /** Conditionally assign a value without branches.
152  *
153  * This is equivalent to `if ( condition ) dest = src`, but is likely
154  * to be compiled to code using bitwise operation rather than a branch.
155  *
156  * \param n             \p dest and \p src must be arrays of limbs of size n.
157  * \param dest          The MPI to conditionally assign to. This must point
158  *                      to an initialized MPI.
159  * \param src           The MPI to be assigned from. This must point to an
160  *                      initialized MPI.
161  * \param condition     Condition to test, must be 0 or 1.
162  */
163 void mbedtls_ct_mpi_uint_cond_assign( size_t n,
164                                       mbedtls_mpi_uint *dest,
165                                       const mbedtls_mpi_uint *src,
166                                       unsigned char condition );
167 
168 #endif /* MBEDTLS_BIGNUM_C */
169 
170 #if defined(MBEDTLS_BASE64_C)
171 
172 /** Given a value in the range 0..63, return the corresponding Base64 digit.
173  *
174  * The implementation assumes that letters are consecutive (e.g. ASCII
175  * but not EBCDIC).
176  *
177  * \param value     A value in the range 0..63.
178  *
179  * \return          A base64 digit converted from \p value.
180  */
181 unsigned char mbedtls_ct_base64_enc_char( unsigned char value );
182 
183 /** Given a Base64 digit, return its value.
184  *
185  * If c is not a Base64 digit ('A'..'Z', 'a'..'z', '0'..'9', '+' or '/'),
186  * return -1.
187  *
188  * The implementation assumes that letters are consecutive (e.g. ASCII
189  * but not EBCDIC).
190  *
191  * \param c     A base64 digit.
192  *
193  * \return      The value of the base64 digit \p c.
194  */
195 signed char mbedtls_ct_base64_dec_value( unsigned char c );
196 
197 #endif /* MBEDTLS_BASE64_C */
198 
199 #if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
200 
201 /** Conditional memcpy without branches.
202  *
203  * This is equivalent to `if ( c1 == c2 ) memcpy(dest, src, len)`, but is likely
204  * to be compiled to code using bitwise operation rather than a branch.
205  *
206  * \param dest      The pointer to conditionally copy to.
207  * \param src       The pointer to copy from. Shouldn't overlap with \p dest.
208  * \param len       The number of bytes to copy.
209  * \param c1        The first value to analyze in the condition.
210  * \param c2        The second value to analyze in the condition.
211  */
212 void mbedtls_ct_memcpy_if_eq( unsigned char *dest,
213                               const unsigned char *src,
214                               size_t len,
215                               size_t c1, size_t c2 );
216 
217 /** Copy data from a secret position with constant flow.
218  *
219  * This function copies \p len bytes from \p src_base + \p offset_secret to \p
220  * dst, with a code flow and memory access pattern that does not depend on \p
221  * offset_secret, but only on \p offset_min, \p offset_max and \p len.
222  * Functionally equivalent to `memcpy(dst, src + offset_secret, len)`.
223  *
224  * \note                This function reads from \p dest, but the value that
225  *                      is read does not influence the result and this
226  *                      function's behavior is well-defined regardless of the
227  *                      contents of the buffers. This may result in false
228  *                      positives from static or dynamic analyzers, especially
229  *                      if \p dest is not initialized.
230  *
231  * \param dest          The destination buffer. This must point to a writable
232  *                      buffer of at least \p len bytes.
233  * \param src           The base of the source buffer. This must point to a
234  *                      readable buffer of at least \p offset_max + \p len
235  *                      bytes. Shouldn't overlap with \p dest.
236  * \param offset        The offset in the source buffer from which to copy.
237  *                      This must be no less than \p offset_min and no greater
238  *                      than \p offset_max.
239  * \param offset_min    The minimal value of \p offset.
240  * \param offset_max    The maximal value of \p offset.
241  * \param len           The number of bytes to copy.
242  */
243 void mbedtls_ct_memcpy_offset( unsigned char *dest,
244                                const unsigned char *src,
245                                size_t offset,
246                                size_t offset_min,
247                                size_t offset_max,
248                                size_t len );
249 
250 /** Compute the HMAC of variable-length data with constant flow.
251  *
252  * This function computes the HMAC of the concatenation of \p add_data and \p
253  * data, and does with a code flow and memory access pattern that does not
254  * depend on \p data_len_secret, but only on \p min_data_len and \p
255  * max_data_len. In particular, this function always reads exactly \p
256  * max_data_len bytes from \p data.
257  *
258  * \param ctx               The HMAC context. It must have keys configured
259  *                          with mbedtls_md_hmac_starts() and use one of the
260  *                          following hashes: SHA-384, SHA-256, SHA-1 or MD-5.
261  *                          It is reset using mbedtls_md_hmac_reset() after
262  *                          the computation is complete to prepare for the
263  *                          next computation.
264  * \param add_data          The first part of the message whose HMAC is being
265  *                          calculated. This must point to a readable buffer
266  *                          of \p add_data_len bytes.
267  * \param add_data_len      The length of \p add_data in bytes.
268  * \param data              The buffer containing the second part of the
269  *                          message. This must point to a readable buffer
270  *                          of \p max_data_len bytes.
271  * \param data_len_secret   The length of the data to process in \p data.
272  *                          This must be no less than \p min_data_len and no
273  *                          greater than \p max_data_len.
274  * \param min_data_len      The minimal length of the second part of the
275  *                          message, read from \p data.
276  * \param max_data_len      The maximal length of the second part of the
277  *                          message, read from \p data.
278  * \param output            The HMAC will be written here. This must point to
279  *                          a writable buffer of sufficient size to hold the
280  *                          HMAC value.
281  *
282  * \retval 0 on success.
283  * \retval #MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED
284  *         The hardware accelerator failed.
285  */
286 int mbedtls_ct_hmac( mbedtls_md_context_t *ctx,
287                      const unsigned char *add_data,
288                      size_t add_data_len,
289                      const unsigned char *data,
290                      size_t data_len_secret,
291                      size_t min_data_len,
292                      size_t max_data_len,
293                      unsigned char *output );
294 
295 #endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
296 
297 #if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
298 
299 /** This function performs the unpadding part of a PKCS#1 v1.5 decryption
300  *  operation (EME-PKCS1-v1_5 decoding).
301  *
302  * \note The return value from this function is a sensitive value
303  *       (this is unusual). #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE shouldn't happen
304  *       in a well-written application, but 0 vs #MBEDTLS_ERR_RSA_INVALID_PADDING
305  *       is often a situation that an attacker can provoke and leaking which
306  *       one is the result is precisely the information the attacker wants.
307  *
308  * \param mode           The mode of operation. This must be either
309  *                       #MBEDTLS_RSA_PRIVATE or #MBEDTLS_RSA_PUBLIC (deprecated).
310  * \param input          The input buffer which is the payload inside PKCS#1v1.5
311  *                       encryption padding, called the "encoded message EM"
312  *                       by the terminology.
313  * \param ilen           The length of the payload in the \p input buffer.
314  * \param output         The buffer for the payload, called "message M" by the
315  *                       PKCS#1 terminology. This must be a writable buffer of
316  *                       length \p output_max_len bytes.
317  * \param olen           The address at which to store the length of
318  *                       the payload. This must not be \c NULL.
319  * \param output_max_len The length in bytes of the output buffer \p output.
320  *
321  * \return      \c 0 on success.
322  * \return      #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE
323  *              The output buffer is too small for the unpadded payload.
324  * \return      #MBEDTLS_ERR_RSA_INVALID_PADDING
325  *              The input doesn't contain properly formatted padding.
326  */
327 int mbedtls_ct_rsaes_pkcs1_v15_unpadding( int mode,
328                                           unsigned char *input,
329                                           size_t ilen,
330                                           unsigned char *output,
331                                           size_t output_max_len,
332                                           size_t *olen );
333 
334 #endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
335 
336 #endif /* MBEDTLS_CONSTANT_TIME_INTERNAL_H */
337