blob: 59a22e3255e0236eb37555026eed5e4fde3fb33d [file] [log] [blame]
gabor-mezei-arm90559722021-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-arm944c1072021-09-27 11:28:54 +020021#include "constant_time.h"
gabor-mezei-armcb4317b2021-09-27 14:28:31 +020022#include "mbedtls/error.h"
gabor-mezei-arm944c1072021-09-27 11:28:54 +020023
gabor-mezei-arm097d4f52021-09-27 12:55:33 +020024#if defined(MBEDTLS_BIGNUM_C)
25#include "mbedtls/bignum.h"
26#endif
27
gabor-mezei-armcb4317b2021-09-27 14:28:31 +020028#if defined(MBEDTLS_SSL_TLS_C)
29#include "mbedtls/ssl_internal.h"
30#endif
31
gabor-mezei-armf52941e2021-09-27 16:11:12 +020032#include <string.h>
gabor-mezei-arm097d4f52021-09-27 12:55:33 +020033
gabor-mezei-arm378e7eb2021-07-19 15:19:19 +020034int mbedtls_cf_memcmp( const void *a,
35 const void *b,
36 size_t n )
gabor-mezei-arm944c1072021-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-arm944c1072021-09-27 11:28:54 +020052 return( (int)diff );
53}
54
gabor-mezei-armc11cac92021-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-armd361ccd2021-09-27 11:49:42 +020073
74/*
gabor-mezei-arm2f2c0be2021-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-armd361ccd2021-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-arm2f2c0be2021-08-10 20:56:21 +020085size_t mbedtls_cf_size_mask( size_t value )
gabor-mezei-armd361ccd2021-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-arm2f2c0be2021-08-10 20:56:21 +020093 return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
gabor-mezei-armd361ccd2021-09-27 11:49:42 +020094#if defined(_MSC_VER)
95#pragma warning( pop )
96#endif
97}
gabor-mezei-arm4d6b1462021-09-27 11:53:54 +020098
99/*
100 * Constant-flow mask generation for "less than" comparison:
101 * - if x < y, return all bits 1, that is (size_t) -1
102 * - otherwise, return all bits 0, that is 0
103 *
104 * This function can be used to write constant-time code by replacing branches
105 * with bit operations using masks.
106 *
107 * This function is implemented without using comparison operators, as those
108 * might be translated to branches by some compilers on some platforms.
109 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200110size_t mbedtls_cf_size_mask_lt( size_t x,
111 size_t y )
gabor-mezei-arm4d6b1462021-09-27 11:53:54 +0200112{
113 /* This has the most significant bit set if and only if x < y */
114 const size_t sub = x - y;
115
116 /* sub1 = (x < y) ? 1 : 0 */
117 const size_t sub1 = sub >> ( sizeof( sub ) * 8 - 1 );
118
119 /* mask = (x < y) ? 0xff... : 0x00... */
120 const size_t mask = mbedtls_cf_size_mask( sub1 );
121
122 return( mask );
123}
gabor-mezei-arma2bcabc2021-09-27 11:58:31 +0200124
125/*
126 * Constant-flow mask generation for "greater or equal" comparison:
127 * - if x >= y, return all bits 1, that is (size_t) -1
128 * - otherwise, return all bits 0, that is 0
129 *
130 * This function can be used to write constant-time code by replacing branches
131 * with bit operations using masks.
132 *
133 * This function is implemented without using comparison operators, as those
134 * might be translated to branches by some compilers on some platforms.
135 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200136size_t mbedtls_cf_size_mask_ge( size_t x,
137 size_t y )
gabor-mezei-arma2bcabc2021-09-27 11:58:31 +0200138{
139 return( ~mbedtls_cf_size_mask_lt( x, y ) );
140}
gabor-mezei-arm96584dd2021-09-27 12:15:19 +0200141
142/*
143 * Constant-flow boolean "equal" comparison:
144 * return x == y
145 *
146 * This function can be used to write constant-time code by replacing branches
147 * with bit operations - it can be used in conjunction with
148 * mbedtls_ssl_cf_mask_from_bit().
149 *
150 * This function is implemented without using comparison operators, as those
151 * might be translated to branches by some compilers on some platforms.
152 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200153size_t mbedtls_cf_size_bool_eq( size_t x,
154 size_t y )
gabor-mezei-arm96584dd2021-09-27 12:15:19 +0200155{
156 /* diff = 0 if x == y, non-zero otherwise */
157 const size_t diff = x ^ y;
158
159 /* MSVC has a warning about unary minus on unsigned integer types,
160 * but this is well-defined and precisely what we want to do here. */
161#if defined(_MSC_VER)
162#pragma warning( push )
163#pragma warning( disable : 4146 )
164#endif
165
166 /* diff_msb's most significant bit is equal to x != y */
167 const size_t diff_msb = ( diff | (size_t) -diff );
168
169#if defined(_MSC_VER)
170#pragma warning( pop )
171#endif
172
173 /* diff1 = (x != y) ? 1 : 0 */
174 const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
175
176 return( 1 ^ diff1 );
177}
gabor-mezei-arm9d7bf092021-09-27 12:25:07 +0200178
179/** Check whether a size is out of bounds, without branches.
180 *
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200181 * This is equivalent to `x > y`, but is likely to be compiled to
gabor-mezei-arm9d7bf092021-09-27 12:25:07 +0200182 * to code using bitwise operation rather than a branch.
183 *
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200184 * \param x Size to check.
185 * \param y Maximum desired value for \p size.
186 * \return \c 0 if `x <= y`.
187 * \return \c 1 if `x > y`.
gabor-mezei-arm9d7bf092021-09-27 12:25:07 +0200188 */
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200189unsigned mbedtls_cf_size_gt( size_t x,
190 size_t y )
gabor-mezei-arm9d7bf092021-09-27 12:25:07 +0200191{
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200192 /* Return the sign bit (1 for negative) of (y - x). */
193 return( ( y - x ) >> ( sizeof( size_t ) * 8 - 1 ) );
gabor-mezei-arm9d7bf092021-09-27 12:25:07 +0200194}
gabor-mezei-arm097d4f52021-09-27 12:55:33 +0200195
196#if defined(MBEDTLS_BIGNUM_C)
197
198/** Decide if an integer is less than the other, without branches.
199 *
200 * \param x First integer.
201 * \param y Second integer.
202 *
203 * \return 1 if \p x is less than \p y, 0 otherwise
204 */
205unsigned mbedtls_cf_mpi_uint_lt( const mbedtls_mpi_uint x,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200206 const mbedtls_mpi_uint y )
gabor-mezei-arm097d4f52021-09-27 12:55:33 +0200207{
208 mbedtls_mpi_uint ret;
209 mbedtls_mpi_uint cond;
210
211 /*
212 * Check if the most significant bits (MSB) of the operands are different.
213 */
214 cond = ( x ^ y );
215 /*
216 * If the MSB are the same then the difference x-y will be negative (and
217 * have its MSB set to 1 during conversion to unsigned) if and only if x<y.
218 */
219 ret = ( x - y ) & ~cond;
220 /*
221 * If the MSB are different, then the operand with the MSB of 1 is the
222 * bigger. (That is if y has MSB of 1, then x<y is true and it is false if
223 * the MSB of y is 0.)
224 */
225 ret |= y & cond;
226
227
228 ret = ret >> ( sizeof( mbedtls_mpi_uint ) * 8 - 1 );
229
230 return (unsigned) ret;
231}
232
233#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-arm75332532021-09-27 12:59:30 +0200234
235/** Choose between two integer values, without branches.
236 *
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200237 * This is equivalent to `condition ? if1 : if0`, but is likely to be compiled
gabor-mezei-arm75332532021-09-27 12:59:30 +0200238 * to code using bitwise operation rather than a branch.
239 *
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200240 * \param condition Condition to test.
241 * \param if1 Value to use if \p condition is nonzero.
242 * \param if0 Value to use if \p condition is zero.
243 * \return \c if1 if \p condition is nonzero, otherwise \c if0.
gabor-mezei-arm75332532021-09-27 12:59:30 +0200244 */
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200245
246unsigned mbedtls_cf_uint_if( unsigned condition,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200247 unsigned if1,
248 unsigned if0 )
gabor-mezei-arm75332532021-09-27 12:59:30 +0200249{
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200250 unsigned mask = mbedtls_cf_uint_mask( condition );
gabor-mezei-arm75332532021-09-27 12:59:30 +0200251 return( ( mask & if1 ) | (~mask & if0 ) );
252}
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200253
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200254size_t mbedtls_cf_size_if( unsigned condition,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200255 size_t if1,
256 size_t if0 )
gabor-mezei-armbc3a2882021-09-27 15:47:00 +0200257{
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200258 size_t mask = mbedtls_cf_size_mask( condition );
gabor-mezei-armbc3a2882021-09-27 15:47:00 +0200259 return( ( mask & if1 ) | (~mask & if0 ) );
260}
261
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200262/**
263 * Select between two sign values in constant-time.
264 *
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200265 * This is functionally equivalent to condition ? if1 : if0 but uses only bit
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200266 * operations in order to avoid branches.
267 *
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200268 * \param[in] condition Must be either 1 (return \p if1) or 0 (return \pp if0).
269 * \param[in] if1 The first sign; must be either +1 or -1.
270 * \param[in] if0 The second sign; must be either +1 or -1.
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200271 *
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200272 * \return \c if1 if \p condition is nonzero, otherwise \c if0.
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200273 */
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200274int mbedtls_cf_cond_select_sign( unsigned char condition,
275 int if1,
276 int if0 )
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200277{
278 /* In order to avoid questions about what we can reasonnably assume about
279 * the representations of signed integers, move everything to unsigned
280 * by taking advantage of the fact that a and b are either +1 or -1. */
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200281 unsigned uif1 = if1 + 1;
282 unsigned uif0 = if0 + 1;
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200283
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200284 /* condition was 0 or 1, mask is 0 or 2 as are ua and ub */
285 const unsigned mask = condition << 1;
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200286
287 /* select ua or ub */
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200288 unsigned ur = ( uif0 & ~mask ) | ( uif1 & mask );
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200289
290 /* ur is now 0 or 2, convert back to -1 or +1 */
291 return( (int) ur - 1 );
292}
gabor-mezei-arm043192d2021-09-27 13:17:15 +0200293
294#if defined(MBEDTLS_BIGNUM_C)
295
296/*
297 * Conditionally assign dest = src, without leaking information
298 * about whether the assignment was made or not.
299 * dest and src must be arrays of limbs of size n.
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200300 * condition must be 0 or 1.
gabor-mezei-arm043192d2021-09-27 13:17:15 +0200301 */
302void mbedtls_cf_mpi_uint_cond_assign( size_t n,
303 mbedtls_mpi_uint *dest,
304 const mbedtls_mpi_uint *src,
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200305 unsigned char condition )
gabor-mezei-arm043192d2021-09-27 13:17:15 +0200306{
307 size_t i;
308
309 /* MSVC has a warning about unary minus on unsigned integer types,
310 * but this is well-defined and precisely what we want to do here. */
311#if defined(_MSC_VER)
312#pragma warning( push )
313#pragma warning( disable : 4146 )
314#endif
315
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200316 /* all-bits 1 if condition is 1, all-bits 0 if condition is 0 */
317 const mbedtls_mpi_uint mask = -condition;
gabor-mezei-arm043192d2021-09-27 13:17:15 +0200318
319#if defined(_MSC_VER)
320#pragma warning( pop )
321#endif
322
323 for( i = 0; i < n; i++ )
324 dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
325}
326
327#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-arm7b23c0b2021-09-27 13:31:06 +0200328
329/** Shift some data towards the left inside a buffer without leaking
330 * the length of the data through side channels.
331 *
332 * `mbedtls_cf_mem_move_to_left(start, total, offset)` is functionally
333 * equivalent to
334 * ```
335 * memmove(start, start + offset, total - offset);
336 * memset(start + offset, 0, total - offset);
337 * ```
338 * but it strives to use a memory access pattern (and thus total timing)
339 * that does not depend on \p offset. This timing independence comes at
340 * the expense of performance.
341 *
342 * \param start Pointer to the start of the buffer.
343 * \param total Total size of the buffer.
344 * \param offset Offset from which to copy \p total - \p offset bytes.
345 */
346void mbedtls_cf_mem_move_to_left( void *start,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200347 size_t total,
348 size_t offset )
gabor-mezei-arm7b23c0b2021-09-27 13:31:06 +0200349{
350 volatile unsigned char *buf = start;
351 size_t i, n;
352 if( total == 0 )
353 return;
354 for( i = 0; i < total; i++ )
355 {
356 unsigned no_op = mbedtls_cf_size_gt( total - offset, i );
357 /* The first `total - offset` passes are a no-op. The last
358 * `offset` passes shift the data one byte to the left and
359 * zero out the last byte. */
360 for( n = 0; n < total - 1; n++ )
361 {
362 unsigned char current = buf[n];
363 unsigned char next = buf[n+1];
364 buf[n] = mbedtls_cf_uint_if( no_op, current, next );
365 }
366 buf[total-1] = mbedtls_cf_uint_if( no_op, buf[total-1], 0 );
367 }
368}
gabor-mezei-armee06feb2021-09-27 13:34:25 +0200369
370/*
371 * Constant-flow conditional memcpy:
372 * - if c1 == c2, equivalent to memcpy(dst, src, len),
373 * - otherwise, a no-op,
374 * but with execution flow independent of the values of c1 and c2.
375 *
376 * This function is implemented without using comparison operators, as those
377 * might be translated to branches by some compilers on some platforms.
378 */
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200379void mbedtls_cf_memcpy_if_eq( unsigned char *dest,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200380 const unsigned char *src,
381 size_t len,
382 size_t c1,
383 size_t c2 )
gabor-mezei-armee06feb2021-09-27 13:34:25 +0200384{
385 /* mask = c1 == c2 ? 0xff : 0x00 */
386 const size_t equal = mbedtls_cf_size_bool_eq( c1, c2 );
387 const unsigned char mask = (unsigned char) mbedtls_cf_size_mask( equal );
388
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200389 /* dest[i] = c1 == c2 ? src[i] : dest[i] */
gabor-mezei-armee06feb2021-09-27 13:34:25 +0200390 for( size_t i = 0; i < len; i++ )
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200391 dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
gabor-mezei-armee06feb2021-09-27 13:34:25 +0200392}
gabor-mezei-arm0f7b9e42021-09-27 13:57:45 +0200393
394/*
395 * Constant-flow memcpy from variable position in buffer.
396 * - functionally equivalent to memcpy(dst, src + offset_secret, len)
397 * - but with execution flow independent from the value of offset_secret.
398 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200399void mbedtls_cf_memcpy_offset( unsigned char *dst,
400 const unsigned char *src_base,
401 size_t offset_secret,
402 size_t offset_min,
403 size_t offset_max,
404 size_t len )
gabor-mezei-arm0f7b9e42021-09-27 13:57:45 +0200405{
406 size_t offset;
407
408 for( offset = offset_min; offset <= offset_max; offset++ )
409 {
410 mbedtls_cf_memcpy_if_eq( dst, src_base + offset, len,
411 offset, offset_secret );
412 }
413}
gabor-mezei-armcb4317b2021-09-27 14:28:31 +0200414
415#if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
416
417/*
418 * Compute HMAC of variable-length data with constant flow.
419 *
420 * Only works with MD-5, SHA-1, SHA-256 and SHA-384.
421 * (Otherwise, computation of block_size needs to be adapted.)
422 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200423int mbedtls_cf_hmac( mbedtls_md_context_t *ctx,
424 const unsigned char *add_data,
425 size_t add_data_len,
426 const unsigned char *data,
427 size_t data_len_secret,
428 size_t min_data_len,
429 size_t max_data_len,
430 unsigned char *output )
gabor-mezei-armcb4317b2021-09-27 14:28:31 +0200431{
432 /*
433 * This function breaks the HMAC abstraction and uses the md_clone()
434 * extension to the MD API in order to get constant-flow behaviour.
435 *
436 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
437 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
438 * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
439 *
440 * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
441 * minlen, then cloning the context, and for each byte up to maxlen
442 * finishing up the hash computation, keeping only the correct result.
443 *
444 * Then we only need to compute HASH(okey + inner_hash) and we're done.
445 */
446 const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info );
447 /* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5,
448 * all of which have the same block size except SHA-384. */
449 const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
450 const unsigned char * const ikey = ctx->hmac_ctx;
451 const unsigned char * const okey = ikey + block_size;
452 const size_t hash_size = mbedtls_md_get_size( ctx->md_info );
453
454 unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
455 mbedtls_md_context_t aux;
456 size_t offset;
457 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
458
459 mbedtls_md_init( &aux );
460
461#define MD_CHK( func_call ) \
462 do { \
463 ret = (func_call); \
464 if( ret != 0 ) \
465 goto cleanup; \
466 } while( 0 )
467
468 MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) );
469
470 /* After hmac_start() of hmac_reset(), ikey has already been hashed,
471 * so we can start directly with the message */
472 MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) );
473 MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) );
474
475 /* For each possible length, compute the hash up to that point */
476 for( offset = min_data_len; offset <= max_data_len; offset++ )
477 {
478 MD_CHK( mbedtls_md_clone( &aux, ctx ) );
479 MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
480 /* Keep only the correct inner_hash in the output buffer */
481 mbedtls_cf_memcpy_if_eq( output, aux_out, hash_size,
482 offset, data_len_secret );
483
484 if( offset < max_data_len )
485 MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
486 }
487
488 /* The context needs to finish() before it starts() again */
489 MD_CHK( mbedtls_md_finish( ctx, aux_out ) );
490
491 /* Now compute HASH(okey + inner_hash) */
492 MD_CHK( mbedtls_md_starts( ctx ) );
493 MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
494 MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
495 MD_CHK( mbedtls_md_finish( ctx, output ) );
496
497 /* Done, get ready for next time */
498 MD_CHK( mbedtls_md_hmac_reset( ctx ) );
499
500#undef MD_CHK
501
502cleanup:
503 mbedtls_md_free( &aux );
504 return( ret );
505}
506
507#endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200508
509#if defined(MBEDTLS_BIGNUM_C)
510
511#define MPI_VALIDATE_RET( cond ) \
512 MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
513
514/*
515 * Conditionally assign X = Y, without leaking information
516 * about whether the assignment was made or not.
517 * (Leaking information about the respective sizes of X and Y is ok however.)
518 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200519int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X,
520 const mbedtls_mpi *Y,
521 unsigned char assign )
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200522{
523 int ret = 0;
524 size_t i;
525 mbedtls_mpi_uint limb_mask;
526 MPI_VALIDATE_RET( X != NULL );
527 MPI_VALIDATE_RET( Y != NULL );
528
529 /* MSVC has a warning about unary minus on unsigned integer types,
530 * but this is well-defined and precisely what we want to do here. */
531#if defined(_MSC_VER)
532#pragma warning( push )
533#pragma warning( disable : 4146 )
534#endif
535
536 /* make sure assign is 0 or 1 in a time-constant manner */
537 assign = (assign | (unsigned char)-assign) >> (sizeof( assign ) * 8 - 1);
538 /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
539 limb_mask = -assign;
540
541#if defined(_MSC_VER)
542#pragma warning( pop )
543#endif
544
545 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
546
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200547 X->s = mbedtls_cf_cond_select_sign( assign, Y->s, X->s );
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200548
549 mbedtls_cf_mpi_uint_cond_assign( Y->n, X->p, Y->p, assign );
550
551 for( i = Y->n; i < X->n; i++ )
552 X->p[i] &= ~limb_mask;
553
554cleanup:
555 return( ret );
556}
557
gabor-mezei-arm58fc8a62021-09-27 15:37:50 +0200558/*
559 * Conditionally swap X and Y, without leaking information
560 * about whether the swap was made or not.
561 * Here it is not ok to simply swap the pointers, which whould lead to
562 * different memory access patterns when X and Y are used afterwards.
563 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200564int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X,
565 mbedtls_mpi *Y,
566 unsigned char swap )
gabor-mezei-arm58fc8a62021-09-27 15:37:50 +0200567{
568 int ret, s;
569 size_t i;
570 mbedtls_mpi_uint limb_mask;
571 mbedtls_mpi_uint tmp;
572 MPI_VALIDATE_RET( X != NULL );
573 MPI_VALIDATE_RET( Y != NULL );
574
575 if( X == Y )
576 return( 0 );
577
578 /* MSVC has a warning about unary minus on unsigned integer types,
579 * but this is well-defined and precisely what we want to do here. */
580#if defined(_MSC_VER)
581#pragma warning( push )
582#pragma warning( disable : 4146 )
583#endif
584
585 /* make sure swap is 0 or 1 in a time-constant manner */
586 swap = (swap | (unsigned char)-swap) >> (sizeof( swap ) * 8 - 1);
587 /* all-bits 1 if swap is 1, all-bits 0 if swap is 0 */
588 limb_mask = -swap;
589
590#if defined(_MSC_VER)
591#pragma warning( pop )
592#endif
593
594 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
595 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );
596
597 s = X->s;
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200598 X->s = mbedtls_cf_cond_select_sign( swap, Y->s, X->s );
599 Y->s = mbedtls_cf_cond_select_sign( swap, s, Y->s );
gabor-mezei-arm58fc8a62021-09-27 15:37:50 +0200600
601
602 for( i = 0; i < X->n; i++ )
603 {
604 tmp = X->p[i];
605 X->p[i] = ( X->p[i] & ~limb_mask ) | ( Y->p[i] & limb_mask );
606 Y->p[i] = ( Y->p[i] & ~limb_mask ) | ( tmp & limb_mask );
607 }
608
609cleanup:
610 return( ret );
611}
612
gabor-mezei-armb10301d2021-09-27 15:41:30 +0200613/*
614 * Compare signed values in constant time
615 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200616int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X,
617 const mbedtls_mpi *Y,
618 unsigned *ret )
gabor-mezei-armb10301d2021-09-27 15:41:30 +0200619{
620 size_t i;
621 /* The value of any of these variables is either 0 or 1 at all times. */
622 unsigned cond, done, X_is_negative, Y_is_negative;
623
624 MPI_VALIDATE_RET( X != NULL );
625 MPI_VALIDATE_RET( Y != NULL );
626 MPI_VALIDATE_RET( ret != NULL );
627
628 if( X->n != Y->n )
629 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
630
631 /*
632 * Set sign_N to 1 if N >= 0, 0 if N < 0.
633 * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
634 */
635 X_is_negative = ( X->s & 2 ) >> 1;
636 Y_is_negative = ( Y->s & 2 ) >> 1;
637
638 /*
639 * If the signs are different, then the positive operand is the bigger.
640 * That is if X is negative (X_is_negative == 1), then X < Y is true and it
641 * is false if X is positive (X_is_negative == 0).
642 */
643 cond = ( X_is_negative ^ Y_is_negative );
644 *ret = cond & X_is_negative;
645
646 /*
647 * This is a constant-time function. We might have the result, but we still
648 * need to go through the loop. Record if we have the result already.
649 */
650 done = cond;
651
652 for( i = X->n; i > 0; i-- )
653 {
654 /*
655 * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
656 * X and Y are negative.
657 *
658 * Again even if we can make a decision, we just mark the result and
659 * the fact that we are done and continue looping.
660 */
661 cond = mbedtls_cf_mpi_uint_lt( Y->p[i - 1], X->p[i - 1] );
662 *ret |= cond & ( 1 - done ) & X_is_negative;
663 done |= cond;
664
665 /*
666 * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
667 * X and Y are positive.
668 *
669 * Again even if we can make a decision, we just mark the result and
670 * the fact that we are done and continue looping.
671 */
672 cond = mbedtls_cf_mpi_uint_lt( X->p[i - 1], Y->p[i - 1] );
673 *ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
674 done |= cond;
675 }
676
677 return( 0 );
678}
679
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200680#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-armf52941e2021-09-27 16:11:12 +0200681
682#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
683
684int mbedtls_cf_rsaes_pkcs1_v15_unpadding( int mode,
685 size_t ilen,
686 size_t *olen,
687 unsigned char *output,
688 size_t output_max_len,
689 unsigned char *buf )
690{
691 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
692 size_t i, plaintext_max_size;
693
694 /* The following variables take sensitive values: their value must
695 * not leak into the observable behavior of the function other than
696 * the designated outputs (output, olen, return value). Otherwise
697 * this would open the execution of the function to
698 * side-channel-based variants of the Bleichenbacher padding oracle
699 * attack. Potential side channels include overall timing, memory
700 * access patterns (especially visible to an adversary who has access
701 * to a shared memory cache), and branches (especially visible to
702 * an adversary who has access to a shared code cache or to a shared
703 * branch predictor). */
704 size_t pad_count = 0;
705 unsigned bad = 0;
706 unsigned char pad_done = 0;
707 size_t plaintext_size = 0;
708 unsigned output_too_large;
709
710 plaintext_max_size = mbedtls_cf_size_if( output_max_len > ilen - 11,
711 ilen - 11,
712 output_max_len );
713
714 /* Check and get padding length in constant time and constant
715 * memory trace. The first byte must be 0. */
716 bad |= buf[0];
717
718 if( mode == MBEDTLS_RSA_PRIVATE )
719 {
720 /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
721 * where PS must be at least 8 nonzero bytes. */
722 bad |= buf[1] ^ MBEDTLS_RSA_CRYPT;
723
724 /* Read the whole buffer. Set pad_done to nonzero if we find
725 * the 0x00 byte and remember the padding length in pad_count. */
726 for( i = 2; i < ilen; i++ )
727 {
728 pad_done |= ((buf[i] | (unsigned char)-buf[i]) >> 7) ^ 1;
729 pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
730 }
731 }
732 else
733 {
734 /* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00
735 * where PS must be at least 8 bytes with the value 0xFF. */
736 bad |= buf[1] ^ MBEDTLS_RSA_SIGN;
737
738 /* Read the whole buffer. Set pad_done to nonzero if we find
739 * the 0x00 byte and remember the padding length in pad_count.
740 * If there's a non-0xff byte in the padding, the padding is bad. */
741 for( i = 2; i < ilen; i++ )
742 {
743 pad_done |= mbedtls_cf_uint_if( buf[i], 0, 1 );
744 pad_count += mbedtls_cf_uint_if( pad_done, 0, 1 );
745 bad |= mbedtls_cf_uint_if( pad_done, 0, buf[i] ^ 0xFF );
746 }
747 }
748
749 /* If pad_done is still zero, there's no data, only unfinished padding. */
750 bad |= mbedtls_cf_uint_if( pad_done, 0, 1 );
751
752 /* There must be at least 8 bytes of padding. */
753 bad |= mbedtls_cf_size_gt( 8, pad_count );
754
755 /* If the padding is valid, set plaintext_size to the number of
756 * remaining bytes after stripping the padding. If the padding
757 * is invalid, avoid leaking this fact through the size of the
758 * output: use the maximum message size that fits in the output
759 * buffer. Do it without branches to avoid leaking the padding
760 * validity through timing. RSA keys are small enough that all the
761 * size_t values involved fit in unsigned int. */
762 plaintext_size = mbedtls_cf_uint_if(
763 bad, (unsigned) plaintext_max_size,
764 (unsigned) ( ilen - pad_count - 3 ) );
765
766 /* Set output_too_large to 0 if the plaintext fits in the output
767 * buffer and to 1 otherwise. */
768 output_too_large = mbedtls_cf_size_gt( plaintext_size,
769 plaintext_max_size );
770
771 /* Set ret without branches to avoid timing attacks. Return:
772 * - INVALID_PADDING if the padding is bad (bad != 0).
773 * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
774 * plaintext does not fit in the output buffer.
775 * - 0 if the padding is correct. */
776 ret = - (int) mbedtls_cf_uint_if(
777 bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
778 mbedtls_cf_uint_if( output_too_large,
779 - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
780 0 ) );
781
782 /* If the padding is bad or the plaintext is too large, zero the
783 * data that we're about to copy to the output buffer.
784 * We need to copy the same amount of data
785 * from the same buffer whether the padding is good or not to
786 * avoid leaking the padding validity through overall timing or
787 * through memory or cache access patterns. */
788 bad = mbedtls_cf_uint_mask( bad | output_too_large );
789 for( i = 11; i < ilen; i++ )
790 buf[i] &= ~bad;
791
792 /* If the plaintext is too large, truncate it to the buffer size.
793 * Copy anyway to avoid revealing the length through timing, because
794 * revealing the length is as bad as revealing the padding validity
795 * for a Bleichenbacher attack. */
796 plaintext_size = mbedtls_cf_uint_if( output_too_large,
797 (unsigned) plaintext_max_size,
798 (unsigned) plaintext_size );
799
800 /* Move the plaintext to the leftmost position where it can start in
801 * the working buffer, i.e. make it start plaintext_max_size from
802 * the end of the buffer. Do this with a memory access trace that
803 * does not depend on the plaintext size. After this move, the
804 * starting location of the plaintext is no longer sensitive
805 * information. */
806 mbedtls_cf_mem_move_to_left( buf + ilen - plaintext_max_size,
807 plaintext_max_size,
808 plaintext_max_size - plaintext_size );
809
810 /* Finally copy the decrypted plaintext plus trailing zeros into the output
811 * buffer. If output_max_len is 0, then output may be an invalid pointer
812 * and the result of memcpy() would be undefined; prevent undefined
813 * behavior making sure to depend only on output_max_len (the size of the
814 * user-provided output buffer), which is independent from plaintext
815 * length, validity of padding, success of the decryption, and other
816 * secrets. */
817 if( output_max_len != 0 )
818 memcpy( output, buf + ilen - plaintext_max_size, plaintext_max_size );
819
820 /* Report the amount of data we copied to the output buffer. In case
821 * of errors (bad padding or output too large), the value of *olen
822 * when this function returns is not specified. Making it equivalent
823 * to the good case limits the risks of leaking the padding validity. */
824 *olen = plaintext_size;
825
826 return( ret );
827}
828
829#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */