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