blob: 712008a92836d46a641818017fa55bf55c85672f [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-arm944c1072021-09-27 11:28:54 +020034/* constant-time buffer comparison */
35int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t n )
36{
37 size_t i;
38 volatile const unsigned char *A = (volatile const unsigned char *) a;
39 volatile const unsigned char *B = (volatile const unsigned char *) b;
40 volatile unsigned char diff = 0;
41
42 for( i = 0; i < n; i++ )
43 {
44 /* Read volatile data in order before computing diff.
45 * This avoids IAR compiler warning:
46 * 'the order of volatile accesses is undefined ..' */
47 unsigned char x = A[i], y = B[i];
48 diff |= x ^ y;
49 }
50
51 return( diff );
52}
53
54/* Compare the contents of two buffers in constant time.
55 * Returns 0 if the contents are bitwise identical, otherwise returns
56 * a non-zero value.
57 * This is currently only used by GCM and ChaCha20+Poly1305.
58 */
59int mbedtls_constant_time_memcmp( const void *v1, const void *v2,
60 size_t len )
61{
62 const unsigned char *p1 = (const unsigned char*) v1;
63 const unsigned char *p2 = (const unsigned char*) v2;
64 size_t i;
65 unsigned char diff;
66
67 for( diff = 0, i = 0; i < len; i++ )
68 diff |= p1[i] ^ p2[i];
69
70 return( (int)diff );
71}
72
73/* constant-time buffer comparison */
74unsigned char mbedtls_nist_kw_safer_memcmp( const void *a, const void *b, size_t n )
75{
76 size_t i;
77 volatile const unsigned char *A = (volatile const unsigned char *) a;
78 volatile const unsigned char *B = (volatile const unsigned char *) b;
79 volatile unsigned char diff = 0;
80
81 for( i = 0; i < n; i++ )
82 {
83 /* Read volatile data in order before computing diff.
84 * This avoids IAR compiler warning:
85 * 'the order of volatile accesses is undefined ..' */
86 unsigned char x = A[i], y = B[i];
87 diff |= x ^ y;
88 }
89
90 return( diff );
91}
92
93/* constant-time buffer comparison */
94int mbedtls_safer_memcmp( const void *a, const void *b, size_t n )
95{
96 size_t i;
97 const unsigned char *A = (const unsigned char *) a;
98 const unsigned char *B = (const unsigned char *) b;
99 unsigned char diff = 0;
100
101 for( i = 0; i < n; i++ )
102 diff |= A[i] ^ B[i];
103
104 return( diff );
105}
gabor-mezei-armc11cac92021-09-27 11:40:03 +0200106
107/** Turn zero-or-nonzero into zero-or-all-bits-one, without branches.
108 *
109 * \param value The value to analyze.
110 * \return Zero if \p value is zero, otherwise all-bits-one.
111 */
112unsigned mbedtls_cf_uint_mask( unsigned value )
113{
114 /* MSVC has a warning about unary minus on unsigned, but this is
115 * well-defined and precisely what we want to do here */
116#if defined(_MSC_VER)
117#pragma warning( push )
118#pragma warning( disable : 4146 )
119#endif
120 return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
121#if defined(_MSC_VER)
122#pragma warning( pop )
123#endif
124}
gabor-mezei-armd361ccd2021-09-27 11:49:42 +0200125
126/*
127 * Turn a bit into a mask:
128 * - if bit == 1, return the all-bits 1 mask, aka (size_t) -1
129 * - if bit == 0, return the all-bits 0 mask, aka 0
130 *
131 * This function can be used to write constant-time code by replacing branches
132 * with bit operations using masks.
133 *
134 * This function is implemented without using comparison operators, as those
135 * might be translated to branches by some compilers on some platforms.
136 */
137size_t mbedtls_cf_size_mask( size_t bit )
138{
139 /* MSVC has a warning about unary minus on unsigned integer types,
140 * but this is well-defined and precisely what we want to do here. */
141#if defined(_MSC_VER)
142#pragma warning( push )
143#pragma warning( disable : 4146 )
144#endif
145 return -bit;
146#if defined(_MSC_VER)
147#pragma warning( pop )
148#endif
149}
gabor-mezei-arm4d6b1462021-09-27 11:53:54 +0200150
151/*
152 * Constant-flow mask generation for "less than" comparison:
153 * - if x < y, return all bits 1, that is (size_t) -1
154 * - otherwise, return all bits 0, that is 0
155 *
156 * This function can be used to write constant-time code by replacing branches
157 * with bit operations using masks.
158 *
159 * This function is implemented without using comparison operators, as those
160 * might be translated to branches by some compilers on some platforms.
161 */
162size_t mbedtls_cf_size_mask_lt( size_t x, size_t y )
163{
164 /* This has the most significant bit set if and only if x < y */
165 const size_t sub = x - y;
166
167 /* sub1 = (x < y) ? 1 : 0 */
168 const size_t sub1 = sub >> ( sizeof( sub ) * 8 - 1 );
169
170 /* mask = (x < y) ? 0xff... : 0x00... */
171 const size_t mask = mbedtls_cf_size_mask( sub1 );
172
173 return( mask );
174}
gabor-mezei-arma2bcabc2021-09-27 11:58:31 +0200175
176/*
177 * Constant-flow mask generation for "greater or equal" comparison:
178 * - if x >= y, return all bits 1, that is (size_t) -1
179 * - otherwise, return all bits 0, that is 0
180 *
181 * This function can be used to write constant-time code by replacing branches
182 * with bit operations using masks.
183 *
184 * This function is implemented without using comparison operators, as those
185 * might be translated to branches by some compilers on some platforms.
186 */
187size_t mbedtls_cf_size_mask_ge( size_t x, size_t y )
188{
189 return( ~mbedtls_cf_size_mask_lt( x, y ) );
190}
gabor-mezei-arm96584dd2021-09-27 12:15:19 +0200191
192/*
193 * Constant-flow boolean "equal" comparison:
194 * return x == y
195 *
196 * This function can be used to write constant-time code by replacing branches
197 * with bit operations - it can be used in conjunction with
198 * mbedtls_ssl_cf_mask_from_bit().
199 *
200 * This function is implemented without using comparison operators, as those
201 * might be translated to branches by some compilers on some platforms.
202 */
203size_t mbedtls_cf_size_bool_eq( size_t x, size_t y )
204{
205 /* diff = 0 if x == y, non-zero otherwise */
206 const size_t diff = x ^ y;
207
208 /* MSVC has a warning about unary minus on unsigned integer types,
209 * but this is well-defined and precisely what we want to do here. */
210#if defined(_MSC_VER)
211#pragma warning( push )
212#pragma warning( disable : 4146 )
213#endif
214
215 /* diff_msb's most significant bit is equal to x != y */
216 const size_t diff_msb = ( diff | (size_t) -diff );
217
218#if defined(_MSC_VER)
219#pragma warning( pop )
220#endif
221
222 /* diff1 = (x != y) ? 1 : 0 */
223 const size_t diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
224
225 return( 1 ^ diff1 );
226}
gabor-mezei-arm9d7bf092021-09-27 12:25:07 +0200227
228/** Check whether a size is out of bounds, without branches.
229 *
230 * This is equivalent to `size > max`, but is likely to be compiled to
231 * to code using bitwise operation rather than a branch.
232 *
233 * \param size Size to check.
234 * \param max Maximum desired value for \p size.
235 * \return \c 0 if `size <= max`.
236 * \return \c 1 if `size > max`.
237 */
238unsigned mbedtls_cf_size_gt( size_t size, size_t max )
239{
240 /* Return the sign bit (1 for negative) of (max - size). */
241 return( ( max - size ) >> ( sizeof( size_t ) * 8 - 1 ) );
242}
gabor-mezei-arm097d4f52021-09-27 12:55:33 +0200243
244#if defined(MBEDTLS_BIGNUM_C)
245
246/** Decide if an integer is less than the other, without branches.
247 *
248 * \param x First integer.
249 * \param y Second integer.
250 *
251 * \return 1 if \p x is less than \p y, 0 otherwise
252 */
253unsigned mbedtls_cf_mpi_uint_lt( const mbedtls_mpi_uint x,
254 const mbedtls_mpi_uint y )
255{
256 mbedtls_mpi_uint ret;
257 mbedtls_mpi_uint cond;
258
259 /*
260 * Check if the most significant bits (MSB) of the operands are different.
261 */
262 cond = ( x ^ y );
263 /*
264 * If the MSB are the same then the difference x-y will be negative (and
265 * have its MSB set to 1 during conversion to unsigned) if and only if x<y.
266 */
267 ret = ( x - y ) & ~cond;
268 /*
269 * If the MSB are different, then the operand with the MSB of 1 is the
270 * bigger. (That is if y has MSB of 1, then x<y is true and it is false if
271 * the MSB of y is 0.)
272 */
273 ret |= y & cond;
274
275
276 ret = ret >> ( sizeof( mbedtls_mpi_uint ) * 8 - 1 );
277
278 return (unsigned) ret;
279}
280
281#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-arm75332532021-09-27 12:59:30 +0200282
283/** Choose between two integer values, without branches.
284 *
285 * This is equivalent to `cond ? if1 : if0`, but is likely to be compiled
286 * to code using bitwise operation rather than a branch.
287 *
288 * \param cond Condition to test.
289 * \param if1 Value to use if \p cond is nonzero.
290 * \param if0 Value to use if \p cond is zero.
291 * \return \c if1 if \p cond is nonzero, otherwise \c if0.
292 */
293unsigned mbedtls_cf_uint_if( unsigned cond, unsigned if1, unsigned if0 )
294{
295 unsigned mask = mbedtls_cf_uint_mask( cond );
296 return( ( mask & if1 ) | (~mask & if0 ) );
297}
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200298
gabor-mezei-armbc3a2882021-09-27 15:47:00 +0200299size_t mbedtls_cf_size_if( unsigned cond, size_t if1, size_t if0 )
300{
301 size_t mask = mbedtls_cf_size_mask( cond );
302 return( ( mask & if1 ) | (~mask & if0 ) );
303}
304
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200305/**
306 * Select between two sign values in constant-time.
307 *
308 * This is functionally equivalent to second ? a : b but uses only bit
309 * operations in order to avoid branches.
310 *
311 * \param[in] a The first sign; must be either +1 or -1.
312 * \param[in] b The second sign; must be either +1 or -1.
313 * \param[in] second Must be either 1 (return b) or 0 (return a).
314 *
315 * \return The selected sign value.
316 */
317int mbedtls_cf_cond_select_sign( int a, int b, unsigned char second )
318{
319 /* In order to avoid questions about what we can reasonnably assume about
320 * the representations of signed integers, move everything to unsigned
321 * by taking advantage of the fact that a and b are either +1 or -1. */
322 unsigned ua = a + 1;
323 unsigned ub = b + 1;
324
325 /* second was 0 or 1, mask is 0 or 2 as are ua and ub */
326 const unsigned mask = second << 1;
327
328 /* select ua or ub */
329 unsigned ur = ( ua & ~mask ) | ( ub & mask );
330
331 /* ur is now 0 or 2, convert back to -1 or +1 */
332 return( (int) ur - 1 );
333}
gabor-mezei-arm043192d2021-09-27 13:17:15 +0200334
335#if defined(MBEDTLS_BIGNUM_C)
336
337/*
338 * Conditionally assign dest = src, without leaking information
339 * about whether the assignment was made or not.
340 * dest and src must be arrays of limbs of size n.
341 * assign must be 0 or 1.
342 */
343void mbedtls_cf_mpi_uint_cond_assign( size_t n,
344 mbedtls_mpi_uint *dest,
345 const mbedtls_mpi_uint *src,
346 unsigned char assign )
347{
348 size_t i;
349
350 /* MSVC has a warning about unary minus on unsigned integer types,
351 * but this is well-defined and precisely what we want to do here. */
352#if defined(_MSC_VER)
353#pragma warning( push )
354#pragma warning( disable : 4146 )
355#endif
356
357 /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
358 const mbedtls_mpi_uint mask = -assign;
359
360#if defined(_MSC_VER)
361#pragma warning( pop )
362#endif
363
364 for( i = 0; i < n; i++ )
365 dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
366}
367
368#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-arm7b23c0b2021-09-27 13:31:06 +0200369
370/** Shift some data towards the left inside a buffer without leaking
371 * the length of the data through side channels.
372 *
373 * `mbedtls_cf_mem_move_to_left(start, total, offset)` is functionally
374 * equivalent to
375 * ```
376 * memmove(start, start + offset, total - offset);
377 * memset(start + offset, 0, total - offset);
378 * ```
379 * but it strives to use a memory access pattern (and thus total timing)
380 * that does not depend on \p offset. This timing independence comes at
381 * the expense of performance.
382 *
383 * \param start Pointer to the start of the buffer.
384 * \param total Total size of the buffer.
385 * \param offset Offset from which to copy \p total - \p offset bytes.
386 */
387void mbedtls_cf_mem_move_to_left( void *start,
388 size_t total,
389 size_t offset )
390{
391 volatile unsigned char *buf = start;
392 size_t i, n;
393 if( total == 0 )
394 return;
395 for( i = 0; i < total; i++ )
396 {
397 unsigned no_op = mbedtls_cf_size_gt( total - offset, i );
398 /* The first `total - offset` passes are a no-op. The last
399 * `offset` passes shift the data one byte to the left and
400 * zero out the last byte. */
401 for( n = 0; n < total - 1; n++ )
402 {
403 unsigned char current = buf[n];
404 unsigned char next = buf[n+1];
405 buf[n] = mbedtls_cf_uint_if( no_op, current, next );
406 }
407 buf[total-1] = mbedtls_cf_uint_if( no_op, buf[total-1], 0 );
408 }
409}
gabor-mezei-armee06feb2021-09-27 13:34:25 +0200410
411/*
412 * Constant-flow conditional memcpy:
413 * - if c1 == c2, equivalent to memcpy(dst, src, len),
414 * - otherwise, a no-op,
415 * but with execution flow independent of the values of c1 and c2.
416 *
417 * This function is implemented without using comparison operators, as those
418 * might be translated to branches by some compilers on some platforms.
419 */
420void mbedtls_cf_memcpy_if_eq( unsigned char *dst,
421 const unsigned char *src,
422 size_t len,
423 size_t c1, size_t c2 )
424{
425 /* mask = c1 == c2 ? 0xff : 0x00 */
426 const size_t equal = mbedtls_cf_size_bool_eq( c1, c2 );
427 const unsigned char mask = (unsigned char) mbedtls_cf_size_mask( equal );
428
429 /* dst[i] = c1 == c2 ? src[i] : dst[i] */
430 for( size_t i = 0; i < len; i++ )
431 dst[i] = ( src[i] & mask ) | ( dst[i] & ~mask );
432}
gabor-mezei-arm0f7b9e42021-09-27 13:57:45 +0200433
434/*
435 * Constant-flow memcpy from variable position in buffer.
436 * - functionally equivalent to memcpy(dst, src + offset_secret, len)
437 * - but with execution flow independent from the value of offset_secret.
438 */
439void mbedtls_cf_memcpy_offset(
440 unsigned char *dst,
441 const unsigned char *src_base,
442 size_t offset_secret,
443 size_t offset_min, size_t offset_max,
444 size_t len )
445{
446 size_t offset;
447
448 for( offset = offset_min; offset <= offset_max; offset++ )
449 {
450 mbedtls_cf_memcpy_if_eq( dst, src_base + offset, len,
451 offset, offset_secret );
452 }
453}
gabor-mezei-armcb4317b2021-09-27 14:28:31 +0200454
455#if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
456
457/*
458 * Compute HMAC of variable-length data with constant flow.
459 *
460 * Only works with MD-5, SHA-1, SHA-256 and SHA-384.
461 * (Otherwise, computation of block_size needs to be adapted.)
462 */
463int mbedtls_cf_hmac(
464 mbedtls_md_context_t *ctx,
465 const unsigned char *add_data, size_t add_data_len,
466 const unsigned char *data, size_t data_len_secret,
467 size_t min_data_len, size_t max_data_len,
468 unsigned char *output )
469{
470 /*
471 * This function breaks the HMAC abstraction and uses the md_clone()
472 * extension to the MD API in order to get constant-flow behaviour.
473 *
474 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
475 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
476 * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
477 *
478 * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
479 * minlen, then cloning the context, and for each byte up to maxlen
480 * finishing up the hash computation, keeping only the correct result.
481 *
482 * Then we only need to compute HASH(okey + inner_hash) and we're done.
483 */
484 const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info );
485 /* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5,
486 * all of which have the same block size except SHA-384. */
487 const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
488 const unsigned char * const ikey = ctx->hmac_ctx;
489 const unsigned char * const okey = ikey + block_size;
490 const size_t hash_size = mbedtls_md_get_size( ctx->md_info );
491
492 unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
493 mbedtls_md_context_t aux;
494 size_t offset;
495 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
496
497 mbedtls_md_init( &aux );
498
499#define MD_CHK( func_call ) \
500 do { \
501 ret = (func_call); \
502 if( ret != 0 ) \
503 goto cleanup; \
504 } while( 0 )
505
506 MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) );
507
508 /* After hmac_start() of hmac_reset(), ikey has already been hashed,
509 * so we can start directly with the message */
510 MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) );
511 MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) );
512
513 /* For each possible length, compute the hash up to that point */
514 for( offset = min_data_len; offset <= max_data_len; offset++ )
515 {
516 MD_CHK( mbedtls_md_clone( &aux, ctx ) );
517 MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
518 /* Keep only the correct inner_hash in the output buffer */
519 mbedtls_cf_memcpy_if_eq( output, aux_out, hash_size,
520 offset, data_len_secret );
521
522 if( offset < max_data_len )
523 MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
524 }
525
526 /* The context needs to finish() before it starts() again */
527 MD_CHK( mbedtls_md_finish( ctx, aux_out ) );
528
529 /* Now compute HASH(okey + inner_hash) */
530 MD_CHK( mbedtls_md_starts( ctx ) );
531 MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
532 MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
533 MD_CHK( mbedtls_md_finish( ctx, output ) );
534
535 /* Done, get ready for next time */
536 MD_CHK( mbedtls_md_hmac_reset( ctx ) );
537
538#undef MD_CHK
539
540cleanup:
541 mbedtls_md_free( &aux );
542 return( ret );
543}
544
545#endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200546
547#if defined(MBEDTLS_BIGNUM_C)
548
549#define MPI_VALIDATE_RET( cond ) \
550 MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
551
552/*
553 * Conditionally assign X = Y, without leaking information
554 * about whether the assignment was made or not.
555 * (Leaking information about the respective sizes of X and Y is ok however.)
556 */
557int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign )
558{
559 int ret = 0;
560 size_t i;
561 mbedtls_mpi_uint limb_mask;
562 MPI_VALIDATE_RET( X != NULL );
563 MPI_VALIDATE_RET( Y != NULL );
564
565 /* MSVC has a warning about unary minus on unsigned integer types,
566 * but this is well-defined and precisely what we want to do here. */
567#if defined(_MSC_VER)
568#pragma warning( push )
569#pragma warning( disable : 4146 )
570#endif
571
572 /* make sure assign is 0 or 1 in a time-constant manner */
573 assign = (assign | (unsigned char)-assign) >> (sizeof( assign ) * 8 - 1);
574 /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
575 limb_mask = -assign;
576
577#if defined(_MSC_VER)
578#pragma warning( pop )
579#endif
580
581 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
582
583 X->s = mbedtls_cf_cond_select_sign( X->s, Y->s, assign );
584
585 mbedtls_cf_mpi_uint_cond_assign( Y->n, X->p, Y->p, assign );
586
587 for( i = Y->n; i < X->n; i++ )
588 X->p[i] &= ~limb_mask;
589
590cleanup:
591 return( ret );
592}
593
gabor-mezei-arm58fc8a62021-09-27 15:37:50 +0200594/*
595 * Conditionally swap X and Y, without leaking information
596 * about whether the swap was made or not.
597 * Here it is not ok to simply swap the pointers, which whould lead to
598 * different memory access patterns when X and Y are used afterwards.
599 */
600int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char swap )
601{
602 int ret, s;
603 size_t i;
604 mbedtls_mpi_uint limb_mask;
605 mbedtls_mpi_uint tmp;
606 MPI_VALIDATE_RET( X != NULL );
607 MPI_VALIDATE_RET( Y != NULL );
608
609 if( X == Y )
610 return( 0 );
611
612 /* MSVC has a warning about unary minus on unsigned integer types,
613 * but this is well-defined and precisely what we want to do here. */
614#if defined(_MSC_VER)
615#pragma warning( push )
616#pragma warning( disable : 4146 )
617#endif
618
619 /* make sure swap is 0 or 1 in a time-constant manner */
620 swap = (swap | (unsigned char)-swap) >> (sizeof( swap ) * 8 - 1);
621 /* all-bits 1 if swap is 1, all-bits 0 if swap is 0 */
622 limb_mask = -swap;
623
624#if defined(_MSC_VER)
625#pragma warning( pop )
626#endif
627
628 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
629 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );
630
631 s = X->s;
632 X->s = mbedtls_cf_cond_select_sign( X->s, Y->s, swap );
633 Y->s = mbedtls_cf_cond_select_sign( Y->s, s, swap );
634
635
636 for( i = 0; i < X->n; i++ )
637 {
638 tmp = X->p[i];
639 X->p[i] = ( X->p[i] & ~limb_mask ) | ( Y->p[i] & limb_mask );
640 Y->p[i] = ( Y->p[i] & ~limb_mask ) | ( tmp & limb_mask );
641 }
642
643cleanup:
644 return( ret );
645}
646
gabor-mezei-armb10301d2021-09-27 15:41:30 +0200647/*
648 * Compare signed values in constant time
649 */
650int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X, const mbedtls_mpi *Y,
651 unsigned *ret )
652{
653 size_t i;
654 /* The value of any of these variables is either 0 or 1 at all times. */
655 unsigned cond, done, X_is_negative, Y_is_negative;
656
657 MPI_VALIDATE_RET( X != NULL );
658 MPI_VALIDATE_RET( Y != NULL );
659 MPI_VALIDATE_RET( ret != NULL );
660
661 if( X->n != Y->n )
662 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
663
664 /*
665 * Set sign_N to 1 if N >= 0, 0 if N < 0.
666 * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
667 */
668 X_is_negative = ( X->s & 2 ) >> 1;
669 Y_is_negative = ( Y->s & 2 ) >> 1;
670
671 /*
672 * If the signs are different, then the positive operand is the bigger.
673 * That is if X is negative (X_is_negative == 1), then X < Y is true and it
674 * is false if X is positive (X_is_negative == 0).
675 */
676 cond = ( X_is_negative ^ Y_is_negative );
677 *ret = cond & X_is_negative;
678
679 /*
680 * This is a constant-time function. We might have the result, but we still
681 * need to go through the loop. Record if we have the result already.
682 */
683 done = cond;
684
685 for( i = X->n; i > 0; i-- )
686 {
687 /*
688 * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
689 * X and Y are negative.
690 *
691 * Again even if we can make a decision, we just mark the result and
692 * the fact that we are done and continue looping.
693 */
694 cond = mbedtls_cf_mpi_uint_lt( Y->p[i - 1], X->p[i - 1] );
695 *ret |= cond & ( 1 - done ) & X_is_negative;
696 done |= cond;
697
698 /*
699 * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
700 * X and Y are positive.
701 *
702 * Again even if we can make a decision, we just mark the result and
703 * the fact that we are done and continue looping.
704 */
705 cond = mbedtls_cf_mpi_uint_lt( X->p[i - 1], Y->p[i - 1] );
706 *ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
707 done |= cond;
708 }
709
710 return( 0 );
711}
712
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200713#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-armf52941e2021-09-27 16:11:12 +0200714
715#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
716
717int mbedtls_cf_rsaes_pkcs1_v15_unpadding( int mode,
718 size_t ilen,
719 size_t *olen,
720 unsigned char *output,
721 size_t output_max_len,
722 unsigned char *buf )
723{
724 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
725 size_t i, plaintext_max_size;
726
727 /* The following variables take sensitive values: their value must
728 * not leak into the observable behavior of the function other than
729 * the designated outputs (output, olen, return value). Otherwise
730 * this would open the execution of the function to
731 * side-channel-based variants of the Bleichenbacher padding oracle
732 * attack. Potential side channels include overall timing, memory
733 * access patterns (especially visible to an adversary who has access
734 * to a shared memory cache), and branches (especially visible to
735 * an adversary who has access to a shared code cache or to a shared
736 * branch predictor). */
737 size_t pad_count = 0;
738 unsigned bad = 0;
739 unsigned char pad_done = 0;
740 size_t plaintext_size = 0;
741 unsigned output_too_large;
742
743 plaintext_max_size = mbedtls_cf_size_if( output_max_len > ilen - 11,
744 ilen - 11,
745 output_max_len );
746
747 /* Check and get padding length in constant time and constant
748 * memory trace. The first byte must be 0. */
749 bad |= buf[0];
750
751 if( mode == MBEDTLS_RSA_PRIVATE )
752 {
753 /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
754 * where PS must be at least 8 nonzero bytes. */
755 bad |= buf[1] ^ MBEDTLS_RSA_CRYPT;
756
757 /* Read the whole buffer. Set pad_done to nonzero if we find
758 * the 0x00 byte and remember the padding length in pad_count. */
759 for( i = 2; i < ilen; i++ )
760 {
761 pad_done |= ((buf[i] | (unsigned char)-buf[i]) >> 7) ^ 1;
762 pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
763 }
764 }
765 else
766 {
767 /* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00
768 * where PS must be at least 8 bytes with the value 0xFF. */
769 bad |= buf[1] ^ MBEDTLS_RSA_SIGN;
770
771 /* Read the whole buffer. Set pad_done to nonzero if we find
772 * the 0x00 byte and remember the padding length in pad_count.
773 * If there's a non-0xff byte in the padding, the padding is bad. */
774 for( i = 2; i < ilen; i++ )
775 {
776 pad_done |= mbedtls_cf_uint_if( buf[i], 0, 1 );
777 pad_count += mbedtls_cf_uint_if( pad_done, 0, 1 );
778 bad |= mbedtls_cf_uint_if( pad_done, 0, buf[i] ^ 0xFF );
779 }
780 }
781
782 /* If pad_done is still zero, there's no data, only unfinished padding. */
783 bad |= mbedtls_cf_uint_if( pad_done, 0, 1 );
784
785 /* There must be at least 8 bytes of padding. */
786 bad |= mbedtls_cf_size_gt( 8, pad_count );
787
788 /* If the padding is valid, set plaintext_size to the number of
789 * remaining bytes after stripping the padding. If the padding
790 * is invalid, avoid leaking this fact through the size of the
791 * output: use the maximum message size that fits in the output
792 * buffer. Do it without branches to avoid leaking the padding
793 * validity through timing. RSA keys are small enough that all the
794 * size_t values involved fit in unsigned int. */
795 plaintext_size = mbedtls_cf_uint_if(
796 bad, (unsigned) plaintext_max_size,
797 (unsigned) ( ilen - pad_count - 3 ) );
798
799 /* Set output_too_large to 0 if the plaintext fits in the output
800 * buffer and to 1 otherwise. */
801 output_too_large = mbedtls_cf_size_gt( plaintext_size,
802 plaintext_max_size );
803
804 /* Set ret without branches to avoid timing attacks. Return:
805 * - INVALID_PADDING if the padding is bad (bad != 0).
806 * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
807 * plaintext does not fit in the output buffer.
808 * - 0 if the padding is correct. */
809 ret = - (int) mbedtls_cf_uint_if(
810 bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
811 mbedtls_cf_uint_if( output_too_large,
812 - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
813 0 ) );
814
815 /* If the padding is bad or the plaintext is too large, zero the
816 * data that we're about to copy to the output buffer.
817 * We need to copy the same amount of data
818 * from the same buffer whether the padding is good or not to
819 * avoid leaking the padding validity through overall timing or
820 * through memory or cache access patterns. */
821 bad = mbedtls_cf_uint_mask( bad | output_too_large );
822 for( i = 11; i < ilen; i++ )
823 buf[i] &= ~bad;
824
825 /* If the plaintext is too large, truncate it to the buffer size.
826 * Copy anyway to avoid revealing the length through timing, because
827 * revealing the length is as bad as revealing the padding validity
828 * for a Bleichenbacher attack. */
829 plaintext_size = mbedtls_cf_uint_if( output_too_large,
830 (unsigned) plaintext_max_size,
831 (unsigned) plaintext_size );
832
833 /* Move the plaintext to the leftmost position where it can start in
834 * the working buffer, i.e. make it start plaintext_max_size from
835 * the end of the buffer. Do this with a memory access trace that
836 * does not depend on the plaintext size. After this move, the
837 * starting location of the plaintext is no longer sensitive
838 * information. */
839 mbedtls_cf_mem_move_to_left( buf + ilen - plaintext_max_size,
840 plaintext_max_size,
841 plaintext_max_size - plaintext_size );
842
843 /* Finally copy the decrypted plaintext plus trailing zeros into the output
844 * buffer. If output_max_len is 0, then output may be an invalid pointer
845 * and the result of memcpy() would be undefined; prevent undefined
846 * behavior making sure to depend only on output_max_len (the size of the
847 * user-provided output buffer), which is independent from plaintext
848 * length, validity of padding, success of the decryption, and other
849 * secrets. */
850 if( output_max_len != 0 )
851 memcpy( output, buf + ilen - plaintext_max_size, plaintext_max_size );
852
853 /* Report the amount of data we copied to the output buffer. In case
854 * of errors (bad padding or output too large), the value of *olen
855 * when this function returns is not specified. Making it equivalent
856 * to the good case limits the risks of leaking the padding validity. */
857 *olen = plaintext_size;
858
859 return( ret );
860}
861
862#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */