blob: 76cab097ae879e1d389a5f71802cd5724e34fbd8 [file] [log] [blame]
gabor-mezei-armd1125342021-07-12 16:31:22 +02001/**
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#include "common.h"
gabor-mezei-armdb9a38c2021-09-27 11:28:54 +020021#include "constant_time.h"
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +020022#include "mbedtls/error.h"
gabor-mezei-armdb9a38c2021-09-27 11:28:54 +020023
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +020024#if defined(MBEDTLS_BIGNUM_C)
25#include "mbedtls/bignum.h"
26#endif
27
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +020028#if defined(MBEDTLS_SSL_TLS_C)
29#include "ssl_misc.h"
30#endif
31
gabor-mezei-armfdb71182021-09-27 16:11:12 +020032#include <string.h>
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +020033
gabor-mezei-arm46025642021-07-19 15:19:19 +020034int mbedtls_cf_memcmp( const void *a,
35 const void *b,
36 size_t n )
gabor-mezei-armdb9a38c2021-09-27 11:28:54 +020037{
38 size_t i;
39 volatile const unsigned char *A = (volatile const unsigned char *) a;
40 volatile const unsigned char *B = (volatile const unsigned char *) b;
41 volatile unsigned char diff = 0;
42
43 for( i = 0; i < n; i++ )
44 {
45 /* Read volatile data in order before computing diff.
46 * This avoids IAR compiler warning:
47 * 'the order of volatile accesses is undefined ..' */
48 unsigned char x = A[i], y = B[i];
49 diff |= x ^ y;
50 }
51
gabor-mezei-armdb9a38c2021-09-27 11:28:54 +020052 return( (int)diff );
53}
54
gabor-mezei-arm340948e2021-09-27 11:40:03 +020055/** Turn zero-or-nonzero into zero-or-all-bits-one, without branches.
56 *
57 * \param value The value to analyze.
58 * \return Zero if \p value is zero, otherwise all-bits-one.
59 */
60unsigned mbedtls_cf_uint_mask( unsigned value )
61{
62 /* MSVC has a warning about unary minus on unsigned, but this is
63 * well-defined and precisely what we want to do here */
64#if defined(_MSC_VER)
65#pragma warning( push )
66#pragma warning( disable : 4146 )
67#endif
68 return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
69#if defined(_MSC_VER)
70#pragma warning( pop )
71#endif
72}
gabor-mezei-arm3733bf82021-09-27 11:49:42 +020073
74/*
gabor-mezei-arm396438c2021-08-10 20:56:21 +020075 * Turn a value into a mask:
76 * - if value != 0, return the all-bits 1 mask, aka (size_t) -1
77 * - if value == 0, return the all-bits 0 mask, aka 0
gabor-mezei-arm3733bf82021-09-27 11:49:42 +020078 *
79 * This function can be used to write constant-time code by replacing branches
80 * with bit operations using masks.
81 *
82 * This function is implemented without using comparison operators, as those
83 * might be translated to branches by some compilers on some platforms.
84 */
gabor-mezei-arm396438c2021-08-10 20:56:21 +020085size_t mbedtls_cf_size_mask( size_t value )
gabor-mezei-arm3733bf82021-09-27 11:49:42 +020086{
87 /* MSVC has a warning about unary minus on unsigned integer types,
88 * but this is well-defined and precisely what we want to do here. */
89#if defined(_MSC_VER)
90#pragma warning( push )
91#pragma warning( disable : 4146 )
92#endif
gabor-mezei-arm396438c2021-08-10 20:56:21 +020093 return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
gabor-mezei-arm3733bf82021-09-27 11:49:42 +020094#if defined(_MSC_VER)
95#pragma warning( pop )
96#endif
97}
gabor-mezei-armc76227d2021-09-27 11:53:54 +020098
gabor-mezei-arm9cb55692021-08-11 15:07:02 +020099#if defined(MBEDTLS_BIGNUM_C)
100
101mbedtls_mpi_uint mbedtls_cf_mpi_uint_mask( mbedtls_mpi_uint value )
102{
103 /* MSVC has a warning about unary minus on unsigned, but this is
104 * well-defined and precisely what we want to do here */
105#if defined(_MSC_VER)
106#pragma warning( push )
107#pragma warning( disable : 4146 )
108#endif
109 return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
110#if defined(_MSC_VER)
111#pragma warning( pop )
112#endif
113}
114
115#endif /* MBEDTLS_BIGNUM_C */
116
gabor-mezei-armc76227d2021-09-27 11:53:54 +0200117/*
118 * Constant-flow mask generation for "less than" comparison:
119 * - if x < y, return all bits 1, that is (size_t) -1
120 * - otherwise, return all bits 0, that is 0
121 *
122 * This function can be used to write constant-time code by replacing branches
123 * with bit operations using masks.
124 *
125 * This function is implemented without using comparison operators, as those
126 * might be translated to branches by some compilers on some platforms.
127 */
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200128size_t mbedtls_cf_size_mask_lt( size_t x,
129 size_t y )
gabor-mezei-armc76227d2021-09-27 11:53:54 +0200130{
131 /* This has the most significant bit set if and only if x < y */
132 const size_t sub = x - y;
133
134 /* sub1 = (x < y) ? 1 : 0 */
135 const size_t sub1 = sub >> ( sizeof( sub ) * 8 - 1 );
136
137 /* mask = (x < y) ? 0xff... : 0x00... */
138 const size_t mask = mbedtls_cf_size_mask( sub1 );
139
140 return( mask );
141}
gabor-mezei-arm16fc57b2021-09-27 11:58:31 +0200142
143/*
144 * Constant-flow mask generation for "greater or equal" comparison:
145 * - if x >= y, return all bits 1, that is (size_t) -1
146 * - otherwise, return all bits 0, that is 0
147 *
148 * This function can be used to write constant-time code by replacing branches
149 * with bit operations using masks.
150 *
151 * This function is implemented without using comparison operators, as those
152 * might be translated to branches by some compilers on some platforms.
153 */
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200154size_t mbedtls_cf_size_mask_ge( size_t x,
155 size_t y )
gabor-mezei-arm16fc57b2021-09-27 11:58:31 +0200156{
157 return( ~mbedtls_cf_size_mask_lt( x, y ) );
158}
gabor-mezei-arm8d1d5fd2021-09-27 12:15:19 +0200159
160/*
161 * Constant-flow boolean "equal" comparison:
162 * return x == y
163 *
164 * This function can be used to write constant-time code by replacing branches
165 * with bit operations - it can be used in conjunction with
166 * mbedtls_ssl_cf_mask_from_bit().
167 *
168 * This function is implemented without using comparison operators, as those
169 * might be translated to branches by some compilers on some platforms.
170 */
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200171size_t mbedtls_cf_size_bool_eq( size_t x,
172 size_t y )
gabor-mezei-arm8d1d5fd2021-09-27 12:15:19 +0200173{
174 /* diff = 0 if x == y, non-zero otherwise */
175 const size_t diff = x ^ y;
176
177 /* MSVC has a warning about unary minus on unsigned integer types,
178 * but this is well-defined and precisely what we want to do here. */
179#if defined(_MSC_VER)
180#pragma warning( push )
181#pragma warning( disable : 4146 )
182#endif
183
184 /* diff_msb's most significant bit is equal to x != y */
185 const size_t diff_msb = ( diff | (size_t) -diff );
186
187#if defined(_MSC_VER)
188#pragma warning( pop )
189#endif
190
191 /* diff1 = (x != y) ? 1 : 0 */
192 const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
193
194 return( 1 ^ diff1 );
195}
gabor-mezei-arm5a854422021-09-27 12:25:07 +0200196
197/** Check whether a size is out of bounds, without branches.
198 *
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200199 * This is equivalent to `x > y`, but is likely to be compiled to
gabor-mezei-arm5a854422021-09-27 12:25:07 +0200200 * to code using bitwise operation rather than a branch.
201 *
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200202 * \param x Size to check.
203 * \param y Maximum desired value for \p size.
204 * \return \c 0 if `x <= y`.
205 * \return \c 1 if `x > y`.
gabor-mezei-arm5a854422021-09-27 12:25:07 +0200206 */
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200207unsigned mbedtls_cf_size_gt( size_t x,
208 size_t y )
gabor-mezei-arm5a854422021-09-27 12:25:07 +0200209{
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200210 /* Return the sign bit (1 for negative) of (y - x). */
211 return( ( y - x ) >> ( sizeof( size_t ) * 8 - 1 ) );
gabor-mezei-arm5a854422021-09-27 12:25:07 +0200212}
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +0200213
214#if defined(MBEDTLS_BIGNUM_C)
215
216/** Decide if an integer is less than the other, without branches.
217 *
218 * \param x First integer.
219 * \param y Second integer.
220 *
221 * \return 1 if \p x is less than \p y, 0 otherwise
222 */
223unsigned mbedtls_cf_mpi_uint_lt( const mbedtls_mpi_uint x,
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200224 const mbedtls_mpi_uint y )
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +0200225{
226 mbedtls_mpi_uint ret;
227 mbedtls_mpi_uint cond;
228
229 /*
230 * Check if the most significant bits (MSB) of the operands are different.
231 */
232 cond = ( x ^ y );
233 /*
234 * If the MSB are the same then the difference x-y will be negative (and
235 * have its MSB set to 1 during conversion to unsigned) if and only if x<y.
236 */
237 ret = ( x - y ) & ~cond;
238 /*
239 * If the MSB are different, then the operand with the MSB of 1 is the
240 * bigger. (That is if y has MSB of 1, then x<y is true and it is false if
241 * the MSB of y is 0.)
242 */
243 ret |= y & cond;
244
245
246 ret = ret >> ( sizeof( mbedtls_mpi_uint ) * 8 - 1 );
247
248 return (unsigned) ret;
249}
250
251#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-armb2dbf2c2021-09-27 12:59:30 +0200252
253/** Choose between two integer values, without branches.
254 *
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200255 * This is equivalent to `condition ? if1 : if0`, but is likely to be compiled
gabor-mezei-armb2dbf2c2021-09-27 12:59:30 +0200256 * to code using bitwise operation rather than a branch.
257 *
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200258 * \param condition Condition to test.
259 * \param if1 Value to use if \p condition is nonzero.
260 * \param if0 Value to use if \p condition is zero.
261 * \return \c if1 if \p condition is nonzero, otherwise \c if0.
gabor-mezei-armb2dbf2c2021-09-27 12:59:30 +0200262 */
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200263
264unsigned mbedtls_cf_uint_if( unsigned condition,
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200265 unsigned if1,
266 unsigned if0 )
gabor-mezei-armb2dbf2c2021-09-27 12:59:30 +0200267{
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200268 unsigned mask = mbedtls_cf_uint_mask( condition );
gabor-mezei-armb2dbf2c2021-09-27 12:59:30 +0200269 return( ( mask & if1 ) | (~mask & if0 ) );
270}
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200271
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200272size_t mbedtls_cf_size_if( unsigned condition,
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200273 size_t if1,
274 size_t if0 )
gabor-mezei-arm65cefdb2021-09-27 15:47:00 +0200275{
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200276 size_t mask = mbedtls_cf_size_mask( condition );
gabor-mezei-arm65cefdb2021-09-27 15:47:00 +0200277 return( ( mask & if1 ) | (~mask & if0 ) );
278}
279
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200280/**
281 * Select between two sign values in constant-time.
282 *
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200283 * This is functionally equivalent to condition ? if1 : if0 but uses only bit
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200284 * operations in order to avoid branches.
285 *
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200286 * \param[in] condition Must be either 1 (return \p if1) or 0 (return \pp if0).
287 * \param[in] if1 The first sign; must be either +1 or -1.
288 * \param[in] if0 The second sign; must be either +1 or -1.
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200289 *
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200290 * \return \c if1 if \p condition is nonzero, otherwise \c if0.
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200291 */
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200292int mbedtls_cf_cond_select_sign( unsigned char condition,
293 int if1,
294 int if0 )
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200295{
296 /* In order to avoid questions about what we can reasonnably assume about
297 * the representations of signed integers, move everything to unsigned
298 * by taking advantage of the fact that a and b are either +1 or -1. */
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200299 unsigned uif1 = if1 + 1;
300 unsigned uif0 = if0 + 1;
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200301
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200302 /* condition was 0 or 1, mask is 0 or 2 as are ua and ub */
303 const unsigned mask = condition << 1;
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200304
305 /* select ua or ub */
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200306 unsigned ur = ( uif0 & ~mask ) | ( uif1 & mask );
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200307
308 /* ur is now 0 or 2, convert back to -1 or +1 */
309 return( (int) ur - 1 );
310}
gabor-mezei-armbe8d98b2021-09-27 13:17:15 +0200311
312#if defined(MBEDTLS_BIGNUM_C)
313
314/*
315 * Conditionally assign dest = src, without leaking information
316 * about whether the assignment was made or not.
317 * dest and src must be arrays of limbs of size n.
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200318 * condition must be 0 or 1.
gabor-mezei-armbe8d98b2021-09-27 13:17:15 +0200319 */
320void mbedtls_cf_mpi_uint_cond_assign( size_t n,
321 mbedtls_mpi_uint *dest,
322 const mbedtls_mpi_uint *src,
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200323 unsigned char condition )
gabor-mezei-armbe8d98b2021-09-27 13:17:15 +0200324{
325 size_t i;
326
327 /* MSVC has a warning about unary minus on unsigned integer types,
328 * but this is well-defined and precisely what we want to do here. */
329#if defined(_MSC_VER)
330#pragma warning( push )
331#pragma warning( disable : 4146 )
332#endif
333
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200334 /* all-bits 1 if condition is 1, all-bits 0 if condition is 0 */
335 const mbedtls_mpi_uint mask = -condition;
gabor-mezei-armbe8d98b2021-09-27 13:17:15 +0200336
337#if defined(_MSC_VER)
338#pragma warning( pop )
339#endif
340
341 for( i = 0; i < n; i++ )
342 dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
343}
344
345#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-arm394aeaa2021-09-27 13:31:06 +0200346
347/** Shift some data towards the left inside a buffer without leaking
348 * the length of the data through side channels.
349 *
350 * `mbedtls_cf_mem_move_to_left(start, total, offset)` is functionally
351 * equivalent to
352 * ```
353 * memmove(start, start + offset, total - offset);
354 * memset(start + offset, 0, total - offset);
355 * ```
356 * but it strives to use a memory access pattern (and thus total timing)
357 * that does not depend on \p offset. This timing independence comes at
358 * the expense of performance.
359 *
360 * \param start Pointer to the start of the buffer.
361 * \param total Total size of the buffer.
362 * \param offset Offset from which to copy \p total - \p offset bytes.
363 */
364void mbedtls_cf_mem_move_to_left( void *start,
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200365 size_t total,
366 size_t offset )
gabor-mezei-arm394aeaa2021-09-27 13:31:06 +0200367{
368 volatile unsigned char *buf = start;
369 size_t i, n;
370 if( total == 0 )
371 return;
372 for( i = 0; i < total; i++ )
373 {
374 unsigned no_op = mbedtls_cf_size_gt( total - offset, i );
375 /* The first `total - offset` passes are a no-op. The last
376 * `offset` passes shift the data one byte to the left and
377 * zero out the last byte. */
378 for( n = 0; n < total - 1; n++ )
379 {
380 unsigned char current = buf[n];
381 unsigned char next = buf[n+1];
382 buf[n] = mbedtls_cf_uint_if( no_op, current, next );
383 }
384 buf[total-1] = mbedtls_cf_uint_if( no_op, buf[total-1], 0 );
385 }
386}
gabor-mezei-armdee0fd32021-09-27 13:34:25 +0200387
388/*
389 * Constant-flow conditional memcpy:
390 * - if c1 == c2, equivalent to memcpy(dst, src, len),
391 * - otherwise, a no-op,
392 * but with execution flow independent of the values of c1 and c2.
393 *
394 * This function is implemented without using comparison operators, as those
395 * might be translated to branches by some compilers on some platforms.
396 */
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200397void mbedtls_cf_memcpy_if_eq( unsigned char *dest,
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200398 const unsigned char *src,
399 size_t len,
400 size_t c1,
401 size_t c2 )
gabor-mezei-armdee0fd32021-09-27 13:34:25 +0200402{
403 /* mask = c1 == c2 ? 0xff : 0x00 */
404 const size_t equal = mbedtls_cf_size_bool_eq( c1, c2 );
405 const unsigned char mask = (unsigned char) mbedtls_cf_size_mask( equal );
406
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200407 /* dest[i] = c1 == c2 ? src[i] : dest[i] */
gabor-mezei-armdee0fd32021-09-27 13:34:25 +0200408 for( size_t i = 0; i < len; i++ )
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200409 dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
gabor-mezei-armdee0fd32021-09-27 13:34:25 +0200410}
gabor-mezei-arm0e7f71e2021-09-27 13:57:45 +0200411
412/*
413 * Constant-flow memcpy from variable position in buffer.
414 * - functionally equivalent to memcpy(dst, src + offset_secret, len)
415 * - but with execution flow independent from the value of offset_secret.
416 */
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200417void mbedtls_cf_memcpy_offset( unsigned char *dst,
418 const unsigned char *src_base,
419 size_t offset_secret,
420 size_t offset_min,
421 size_t offset_max,
422 size_t len )
gabor-mezei-arm0e7f71e2021-09-27 13:57:45 +0200423{
424 size_t offset;
425
426 for( offset = offset_min; offset <= offset_max; offset++ )
427 {
428 mbedtls_cf_memcpy_if_eq( dst, src_base + offset, len,
429 offset, offset_secret );
430 }
431}
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200432
433#if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
434
435/*
436 * Compute HMAC of variable-length data with constant flow.
437 *
438 * Only works with MD-5, SHA-1, SHA-256 and SHA-384.
439 * (Otherwise, computation of block_size needs to be adapted.)
440 */
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200441int mbedtls_cf_hmac( mbedtls_md_context_t *ctx,
442 const unsigned char *add_data,
443 size_t add_data_len,
444 const unsigned char *data,
445 size_t data_len_secret,
446 size_t min_data_len,
447 size_t max_data_len,
448 unsigned char *output )
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200449{
450 /*
451 * This function breaks the HMAC abstraction and uses the md_clone()
452 * extension to the MD API in order to get constant-flow behaviour.
453 *
454 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
455 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
456 * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
457 *
458 * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
459 * minlen, then cloning the context, and for each byte up to maxlen
460 * finishing up the hash computation, keeping only the correct result.
461 *
462 * Then we only need to compute HASH(okey + inner_hash) and we're done.
463 */
464 const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info );
465 /* TLS 1.2 only supports SHA-384, SHA-256, SHA-1, MD-5,
466 * all of which have the same block size except SHA-384. */
467 const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
468 const unsigned char * const ikey = ctx->hmac_ctx;
469 const unsigned char * const okey = ikey + block_size;
470 const size_t hash_size = mbedtls_md_get_size( ctx->md_info );
471
472 unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
473 mbedtls_md_context_t aux;
474 size_t offset;
475 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
476
477 mbedtls_md_init( &aux );
478
479#define MD_CHK( func_call ) \
480 do { \
481 ret = (func_call); \
482 if( ret != 0 ) \
483 goto cleanup; \
484 } while( 0 )
485
486 MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) );
487
488 /* After hmac_start() of hmac_reset(), ikey has already been hashed,
489 * so we can start directly with the message */
490 MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) );
491 MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) );
492
493 /* For each possible length, compute the hash up to that point */
494 for( offset = min_data_len; offset <= max_data_len; offset++ )
495 {
496 MD_CHK( mbedtls_md_clone( &aux, ctx ) );
497 MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
498 /* Keep only the correct inner_hash in the output buffer */
499 mbedtls_cf_memcpy_if_eq( output, aux_out, hash_size,
500 offset, data_len_secret );
501
502 if( offset < max_data_len )
503 MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
504 }
505
506 /* The context needs to finish() before it starts() again */
507 MD_CHK( mbedtls_md_finish( ctx, aux_out ) );
508
509 /* Now compute HASH(okey + inner_hash) */
510 MD_CHK( mbedtls_md_starts( ctx ) );
511 MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
512 MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
513 MD_CHK( mbedtls_md_finish( ctx, output ) );
514
515 /* Done, get ready for next time */
516 MD_CHK( mbedtls_md_hmac_reset( ctx ) );
517
518#undef MD_CHK
519
520cleanup:
521 mbedtls_md_free( &aux );
522 return( ret );
523}
524
525#endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200526
527#if defined(MBEDTLS_BIGNUM_C)
528
529#define MPI_VALIDATE_RET( cond ) \
530 MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
531
532/*
533 * Conditionally assign X = Y, without leaking information
534 * about whether the assignment was made or not.
535 * (Leaking information about the respective sizes of X and Y is ok however.)
536 */
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200537int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X,
538 const mbedtls_mpi *Y,
539 unsigned char assign )
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200540{
541 int ret = 0;
542 size_t i;
543 mbedtls_mpi_uint limb_mask;
544 MPI_VALIDATE_RET( X != NULL );
545 MPI_VALIDATE_RET( Y != NULL );
546
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200547 /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
gabor-mezei-arm9cb55692021-08-11 15:07:02 +0200548 limb_mask = mbedtls_cf_mpi_uint_mask( assign );;
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200549
550 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
551
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200552 X->s = mbedtls_cf_cond_select_sign( assign, Y->s, X->s );
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200553
554 mbedtls_cf_mpi_uint_cond_assign( Y->n, X->p, Y->p, assign );
555
556 for( i = Y->n; i < X->n; i++ )
557 X->p[i] &= ~limb_mask;
558
559cleanup:
560 return( ret );
561}
562
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200563/*
564 * Conditionally swap X and Y, without leaking information
565 * about whether the swap was made or not.
566 * Here it is not ok to simply swap the pointers, which whould lead to
567 * different memory access patterns when X and Y are used afterwards.
568 */
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200569int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X,
570 mbedtls_mpi *Y,
571 unsigned char swap )
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200572{
573 int ret, s;
574 size_t i;
575 mbedtls_mpi_uint limb_mask;
576 mbedtls_mpi_uint tmp;
577 MPI_VALIDATE_RET( X != NULL );
578 MPI_VALIDATE_RET( Y != NULL );
579
580 if( X == Y )
581 return( 0 );
582
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200583 /* all-bits 1 if swap is 1, all-bits 0 if swap is 0 */
gabor-mezei-arm9cb55692021-08-11 15:07:02 +0200584 limb_mask = mbedtls_cf_mpi_uint_mask( swap );
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200585
586 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
587 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );
588
589 s = X->s;
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200590 X->s = mbedtls_cf_cond_select_sign( swap, Y->s, X->s );
591 Y->s = mbedtls_cf_cond_select_sign( swap, s, Y->s );
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200592
593
594 for( i = 0; i < X->n; i++ )
595 {
596 tmp = X->p[i];
597 X->p[i] = ( X->p[i] & ~limb_mask ) | ( Y->p[i] & limb_mask );
598 Y->p[i] = ( Y->p[i] & ~limb_mask ) | ( tmp & limb_mask );
599 }
600
601cleanup:
602 return( ret );
603}
604
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200605/*
606 * Compare signed values in constant time
607 */
gabor-mezei-arm2dcd7682021-09-27 16:29:52 +0200608int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X,
609 const mbedtls_mpi *Y,
610 unsigned *ret )
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200611{
612 size_t i;
613 /* The value of any of these variables is either 0 or 1 at all times. */
614 unsigned cond, done, X_is_negative, Y_is_negative;
615
616 MPI_VALIDATE_RET( X != NULL );
617 MPI_VALIDATE_RET( Y != NULL );
618 MPI_VALIDATE_RET( ret != NULL );
619
620 if( X->n != Y->n )
621 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
622
623 /*
624 * Set sign_N to 1 if N >= 0, 0 if N < 0.
625 * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
626 */
627 X_is_negative = ( X->s & 2 ) >> 1;
628 Y_is_negative = ( Y->s & 2 ) >> 1;
629
630 /*
631 * If the signs are different, then the positive operand is the bigger.
632 * That is if X is negative (X_is_negative == 1), then X < Y is true and it
633 * is false if X is positive (X_is_negative == 0).
634 */
635 cond = ( X_is_negative ^ Y_is_negative );
636 *ret = cond & X_is_negative;
637
638 /*
639 * This is a constant-time function. We might have the result, but we still
640 * need to go through the loop. Record if we have the result already.
641 */
642 done = cond;
643
644 for( i = X->n; i > 0; i-- )
645 {
646 /*
647 * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
648 * X and Y are negative.
649 *
650 * Again even if we can make a decision, we just mark the result and
651 * the fact that we are done and continue looping.
652 */
653 cond = mbedtls_cf_mpi_uint_lt( Y->p[i - 1], X->p[i - 1] );
654 *ret |= cond & ( 1 - done ) & X_is_negative;
655 done |= cond;
656
657 /*
658 * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
659 * X and Y are positive.
660 *
661 * Again even if we can make a decision, we just mark the result and
662 * the fact that we are done and continue looping.
663 */
664 cond = mbedtls_cf_mpi_uint_lt( X->p[i - 1], Y->p[i - 1] );
665 *ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
666 done |= cond;
667 }
668
669 return( 0 );
670}
671
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200672#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200673
674#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
675
676int mbedtls_cf_rsaes_pkcs1_v15_unpadding( size_t ilen,
677 size_t *olen,
678 unsigned char *output,
679 size_t output_max_len,
680 unsigned char *buf )
681{
682 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
683 size_t i, plaintext_max_size;
684
685 /* The following variables take sensitive values: their value must
686 * not leak into the observable behavior of the function other than
687 * the designated outputs (output, olen, return value). Otherwise
688 * this would open the execution of the function to
689 * side-channel-based variants of the Bleichenbacher padding oracle
690 * attack. Potential side channels include overall timing, memory
691 * access patterns (especially visible to an adversary who has access
692 * to a shared memory cache), and branches (especially visible to
693 * an adversary who has access to a shared code cache or to a shared
694 * branch predictor). */
695 size_t pad_count = 0;
696 unsigned bad = 0;
697 unsigned char pad_done = 0;
698 size_t plaintext_size = 0;
699 unsigned output_too_large;
700
701 plaintext_max_size = mbedtls_cf_size_if( output_max_len > ilen - 11,
702 ilen - 11,
703 output_max_len );
704
705 /* Check and get padding length in constant time and constant
706 * memory trace. The first byte must be 0. */
707 bad |= buf[0];
708
709
710 /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
711 * where PS must be at least 8 nonzero bytes. */
712 bad |= buf[1] ^ MBEDTLS_RSA_CRYPT;
713
714 /* Read the whole buffer. Set pad_done to nonzero if we find
715 * the 0x00 byte and remember the padding length in pad_count. */
716 for( i = 2; i < ilen; i++ )
717 {
718 pad_done |= ((buf[i] | (unsigned char)-buf[i]) >> 7) ^ 1;
719 pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
720 }
721
722
723 /* If pad_done is still zero, there's no data, only unfinished padding. */
724 bad |= mbedtls_cf_uint_if( pad_done, 0, 1 );
725
726 /* There must be at least 8 bytes of padding. */
727 bad |= mbedtls_cf_size_gt( 8, pad_count );
728
729 /* If the padding is valid, set plaintext_size to the number of
730 * remaining bytes after stripping the padding. If the padding
731 * is invalid, avoid leaking this fact through the size of the
732 * output: use the maximum message size that fits in the output
733 * buffer. Do it without branches to avoid leaking the padding
734 * validity through timing. RSA keys are small enough that all the
735 * size_t values involved fit in unsigned int. */
736 plaintext_size = mbedtls_cf_uint_if(
737 bad, (unsigned) plaintext_max_size,
738 (unsigned) ( ilen - pad_count - 3 ) );
739
740 /* Set output_too_large to 0 if the plaintext fits in the output
741 * buffer and to 1 otherwise. */
742 output_too_large = mbedtls_cf_size_gt( plaintext_size,
743 plaintext_max_size );
744
745 /* Set ret without branches to avoid timing attacks. Return:
746 * - INVALID_PADDING if the padding is bad (bad != 0).
747 * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
748 * plaintext does not fit in the output buffer.
749 * - 0 if the padding is correct. */
750 ret = - (int) mbedtls_cf_uint_if(
751 bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
752 mbedtls_cf_uint_if( output_too_large,
753 - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
754 0 ) );
755
756 /* If the padding is bad or the plaintext is too large, zero the
757 * data that we're about to copy to the output buffer.
758 * We need to copy the same amount of data
759 * from the same buffer whether the padding is good or not to
760 * avoid leaking the padding validity through overall timing or
761 * through memory or cache access patterns. */
762 bad = mbedtls_cf_uint_mask( bad | output_too_large );
763 for( i = 11; i < ilen; i++ )
764 buf[i] &= ~bad;
765
766 /* If the plaintext is too large, truncate it to the buffer size.
767 * Copy anyway to avoid revealing the length through timing, because
768 * revealing the length is as bad as revealing the padding validity
769 * for a Bleichenbacher attack. */
770 plaintext_size = mbedtls_cf_uint_if( output_too_large,
771 (unsigned) plaintext_max_size,
772 (unsigned) plaintext_size );
773
774 /* Move the plaintext to the leftmost position where it can start in
775 * the working buffer, i.e. make it start plaintext_max_size from
776 * the end of the buffer. Do this with a memory access trace that
777 * does not depend on the plaintext size. After this move, the
778 * starting location of the plaintext is no longer sensitive
779 * information. */
780 mbedtls_cf_mem_move_to_left( buf + ilen - plaintext_max_size,
781 plaintext_max_size,
782 plaintext_max_size - plaintext_size );
783
784 /* Finally copy the decrypted plaintext plus trailing zeros into the output
785 * buffer. If output_max_len is 0, then output may be an invalid pointer
786 * and the result of memcpy() would be undefined; prevent undefined
787 * behavior making sure to depend only on output_max_len (the size of the
788 * user-provided output buffer), which is independent from plaintext
789 * length, validity of padding, success of the decryption, and other
790 * secrets. */
791 if( output_max_len != 0 )
792 memcpy( output, buf + ilen - plaintext_max_size, plaintext_max_size );
793
794 /* Report the amount of data we copied to the output buffer. In case
795 * of errors (bad padding or output too large), the value of *olen
796 * when this function returns is not specified. Making it equivalent
797 * to the good case limits the risks of leaking the padding validity. */
798 *olen = plaintext_size;
799
800 return( ret );
801}
802
803#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */