blob: f96bd1ae714f7552e00b2df4e101d03ed1542e10 [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 +020055unsigned mbedtls_cf_uint_mask( unsigned value )
56{
57 /* MSVC has a warning about unary minus on unsigned, but this is
58 * well-defined and precisely what we want to do here */
59#if defined(_MSC_VER)
60#pragma warning( push )
61#pragma warning( disable : 4146 )
62#endif
63 return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
64#if defined(_MSC_VER)
65#pragma warning( pop )
66#endif
67}
gabor-mezei-armd361ccd2021-09-27 11:49:42 +020068
gabor-mezei-arm2f2c0be2021-08-10 20:56:21 +020069size_t mbedtls_cf_size_mask( size_t value )
gabor-mezei-armd361ccd2021-09-27 11:49:42 +020070{
71 /* MSVC has a warning about unary minus on unsigned integer types,
72 * but this is well-defined and precisely what we want to do here. */
73#if defined(_MSC_VER)
74#pragma warning( push )
75#pragma warning( disable : 4146 )
76#endif
gabor-mezei-arm2f2c0be2021-08-10 20:56:21 +020077 return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
gabor-mezei-armd361ccd2021-09-27 11:49:42 +020078#if defined(_MSC_VER)
79#pragma warning( pop )
80#endif
81}
gabor-mezei-arm4d6b1462021-09-27 11:53:54 +020082
gabor-mezei-arm60febd52021-08-11 15:07:02 +020083#if defined(MBEDTLS_BIGNUM_C)
84
85mbedtls_mpi_uint mbedtls_cf_mpi_uint_mask( mbedtls_mpi_uint value )
86{
87 /* MSVC has a warning about unary minus on unsigned, but this is
88 * 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
93 return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
94#if defined(_MSC_VER)
95#pragma warning( pop )
96#endif
97}
98
99#endif /* MBEDTLS_BIGNUM_C */
100
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200101size_t mbedtls_cf_size_mask_lt( size_t x,
102 size_t y )
gabor-mezei-arm4d6b1462021-09-27 11:53:54 +0200103{
104 /* This has the most significant bit set if and only if x < y */
105 const size_t sub = x - y;
106
107 /* sub1 = (x < y) ? 1 : 0 */
108 const size_t sub1 = sub >> ( sizeof( sub ) * 8 - 1 );
109
110 /* mask = (x < y) ? 0xff... : 0x00... */
111 const size_t mask = mbedtls_cf_size_mask( sub1 );
112
113 return( mask );
114}
gabor-mezei-arma2bcabc2021-09-27 11:58:31 +0200115
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200116size_t mbedtls_cf_size_mask_ge( size_t x,
117 size_t y )
gabor-mezei-arma2bcabc2021-09-27 11:58:31 +0200118{
119 return( ~mbedtls_cf_size_mask_lt( x, y ) );
120}
gabor-mezei-arm96584dd2021-09-27 12:15:19 +0200121
gabor-mezei-arm1ffd0cc2021-08-11 17:28:49 +0200122unsigned mbedtls_cf_size_bool_eq( size_t x,
123 size_t y )
gabor-mezei-arm96584dd2021-09-27 12:15:19 +0200124{
125 /* diff = 0 if x == y, non-zero otherwise */
126 const size_t diff = x ^ y;
127
128 /* MSVC has a warning about unary minus on unsigned integer types,
129 * but this is well-defined and precisely what we want to do here. */
130#if defined(_MSC_VER)
131#pragma warning( push )
132#pragma warning( disable : 4146 )
133#endif
134
135 /* diff_msb's most significant bit is equal to x != y */
136 const size_t diff_msb = ( diff | (size_t) -diff );
137
138#if defined(_MSC_VER)
139#pragma warning( pop )
140#endif
141
142 /* diff1 = (x != y) ? 1 : 0 */
gabor-mezei-arm1ffd0cc2021-08-11 17:28:49 +0200143 const unsigned diff1 = diff_msb >> ( sizeof( diff_msb ) * 8 - 1 );
gabor-mezei-arm96584dd2021-09-27 12:15:19 +0200144
145 return( 1 ^ diff1 );
146}
gabor-mezei-arm9d7bf092021-09-27 12:25:07 +0200147
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200148unsigned mbedtls_cf_size_gt( size_t x,
149 size_t y )
gabor-mezei-arm9d7bf092021-09-27 12:25:07 +0200150{
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200151 /* Return the sign bit (1 for negative) of (y - x). */
152 return( ( y - x ) >> ( sizeof( size_t ) * 8 - 1 ) );
gabor-mezei-arm9d7bf092021-09-27 12:25:07 +0200153}
gabor-mezei-arm097d4f52021-09-27 12:55:33 +0200154
155#if defined(MBEDTLS_BIGNUM_C)
156
gabor-mezei-arm097d4f52021-09-27 12:55:33 +0200157unsigned mbedtls_cf_mpi_uint_lt( const mbedtls_mpi_uint x,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200158 const mbedtls_mpi_uint y )
gabor-mezei-arm097d4f52021-09-27 12:55:33 +0200159{
160 mbedtls_mpi_uint ret;
161 mbedtls_mpi_uint cond;
162
163 /*
164 * Check if the most significant bits (MSB) of the operands are different.
165 */
166 cond = ( x ^ y );
167 /*
168 * If the MSB are the same then the difference x-y will be negative (and
169 * have its MSB set to 1 during conversion to unsigned) if and only if x<y.
170 */
171 ret = ( x - y ) & ~cond;
172 /*
173 * If the MSB are different, then the operand with the MSB of 1 is the
174 * bigger. (That is if y has MSB of 1, then x<y is true and it is false if
175 * the MSB of y is 0.)
176 */
177 ret |= y & cond;
178
179
180 ret = ret >> ( sizeof( mbedtls_mpi_uint ) * 8 - 1 );
181
182 return (unsigned) ret;
183}
184
185#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-arm75332532021-09-27 12:59:30 +0200186
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200187unsigned mbedtls_cf_uint_if( unsigned condition,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200188 unsigned if1,
189 unsigned if0 )
gabor-mezei-arm75332532021-09-27 12:59:30 +0200190{
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200191 unsigned mask = mbedtls_cf_uint_mask( condition );
gabor-mezei-arm75332532021-09-27 12:59:30 +0200192 return( ( mask & if1 ) | (~mask & if0 ) );
193}
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200194
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200195size_t mbedtls_cf_size_if( unsigned condition,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200196 size_t if1,
197 size_t if0 )
gabor-mezei-armbc3a2882021-09-27 15:47:00 +0200198{
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200199 size_t mask = mbedtls_cf_size_mask( condition );
gabor-mezei-armbc3a2882021-09-27 15:47:00 +0200200 return( ( mask & if1 ) | (~mask & if0 ) );
201}
202
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200203int mbedtls_cf_cond_select_sign( unsigned char condition,
204 int if1,
205 int if0 )
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200206{
207 /* In order to avoid questions about what we can reasonnably assume about
208 * the representations of signed integers, move everything to unsigned
209 * by taking advantage of the fact that a and b are either +1 or -1. */
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200210 unsigned uif1 = if1 + 1;
211 unsigned uif0 = if0 + 1;
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200212
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200213 /* condition was 0 or 1, mask is 0 or 2 as are ua and ub */
214 const unsigned mask = condition << 1;
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200215
216 /* select ua or ub */
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200217 unsigned ur = ( uif0 & ~mask ) | ( uif1 & mask );
gabor-mezei-arm5cec8b42021-09-27 13:03:57 +0200218
219 /* ur is now 0 or 2, convert back to -1 or +1 */
220 return( (int) ur - 1 );
221}
gabor-mezei-arm043192d2021-09-27 13:17:15 +0200222
223#if defined(MBEDTLS_BIGNUM_C)
224
gabor-mezei-arm043192d2021-09-27 13:17:15 +0200225void mbedtls_cf_mpi_uint_cond_assign( size_t n,
226 mbedtls_mpi_uint *dest,
227 const mbedtls_mpi_uint *src,
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200228 unsigned char condition )
gabor-mezei-arm043192d2021-09-27 13:17:15 +0200229{
230 size_t i;
231
232 /* MSVC has a warning about unary minus on unsigned integer types,
233 * but this is well-defined and precisely what we want to do here. */
234#if defined(_MSC_VER)
235#pragma warning( push )
236#pragma warning( disable : 4146 )
237#endif
238
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200239 /* all-bits 1 if condition is 1, all-bits 0 if condition is 0 */
240 const mbedtls_mpi_uint mask = -condition;
gabor-mezei-arm043192d2021-09-27 13:17:15 +0200241
242#if defined(_MSC_VER)
243#pragma warning( pop )
244#endif
245
246 for( i = 0; i < n; i++ )
247 dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
248}
249
250#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-arm7b23c0b2021-09-27 13:31:06 +0200251
gabor-mezei-arm7b23c0b2021-09-27 13:31:06 +0200252void mbedtls_cf_mem_move_to_left( void *start,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200253 size_t total,
254 size_t offset )
gabor-mezei-arm7b23c0b2021-09-27 13:31:06 +0200255{
256 volatile unsigned char *buf = start;
257 size_t i, n;
258 if( total == 0 )
259 return;
260 for( i = 0; i < total; i++ )
261 {
262 unsigned no_op = mbedtls_cf_size_gt( total - offset, i );
263 /* The first `total - offset` passes are a no-op. The last
264 * `offset` passes shift the data one byte to the left and
265 * zero out the last byte. */
266 for( n = 0; n < total - 1; n++ )
267 {
268 unsigned char current = buf[n];
269 unsigned char next = buf[n+1];
270 buf[n] = mbedtls_cf_uint_if( no_op, current, next );
271 }
272 buf[total-1] = mbedtls_cf_uint_if( no_op, buf[total-1], 0 );
273 }
274}
gabor-mezei-armee06feb2021-09-27 13:34:25 +0200275
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200276void mbedtls_cf_memcpy_if_eq( unsigned char *dest,
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200277 const unsigned char *src,
278 size_t len,
279 size_t c1,
280 size_t c2 )
gabor-mezei-armee06feb2021-09-27 13:34:25 +0200281{
282 /* mask = c1 == c2 ? 0xff : 0x00 */
283 const size_t equal = mbedtls_cf_size_bool_eq( c1, c2 );
284 const unsigned char mask = (unsigned char) mbedtls_cf_size_mask( equal );
285
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200286 /* dest[i] = c1 == c2 ? src[i] : dest[i] */
gabor-mezei-armee06feb2021-09-27 13:34:25 +0200287 for( size_t i = 0; i < len; i++ )
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200288 dest[i] = ( src[i] & mask ) | ( dest[i] & ~mask );
gabor-mezei-armee06feb2021-09-27 13:34:25 +0200289}
gabor-mezei-arm0f7b9e42021-09-27 13:57:45 +0200290
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200291void mbedtls_cf_memcpy_offset( unsigned char *dst,
292 const unsigned char *src_base,
293 size_t offset_secret,
294 size_t offset_min,
295 size_t offset_max,
296 size_t len )
gabor-mezei-arm0f7b9e42021-09-27 13:57:45 +0200297{
298 size_t offset;
299
300 for( offset = offset_min; offset <= offset_max; offset++ )
301 {
302 mbedtls_cf_memcpy_if_eq( dst, src_base + offset, len,
303 offset, offset_secret );
304 }
305}
gabor-mezei-armcb4317b2021-09-27 14:28:31 +0200306
307#if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
308
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200309int mbedtls_cf_hmac( mbedtls_md_context_t *ctx,
310 const unsigned char *add_data,
311 size_t add_data_len,
312 const unsigned char *data,
313 size_t data_len_secret,
314 size_t min_data_len,
315 size_t max_data_len,
316 unsigned char *output )
gabor-mezei-armcb4317b2021-09-27 14:28:31 +0200317{
318 /*
319 * This function breaks the HMAC abstraction and uses the md_clone()
320 * extension to the MD API in order to get constant-flow behaviour.
321 *
322 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
323 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
324 * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
325 *
326 * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
327 * minlen, then cloning the context, and for each byte up to maxlen
328 * finishing up the hash computation, keeping only the correct result.
329 *
330 * Then we only need to compute HASH(okey + inner_hash) and we're done.
331 */
332 const mbedtls_md_type_t md_alg = mbedtls_md_get_type( ctx->md_info );
333 /* TLS 1.0-1.2 only support SHA-384, SHA-256, SHA-1, MD-5,
334 * all of which have the same block size except SHA-384. */
335 const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
336 const unsigned char * const ikey = ctx->hmac_ctx;
337 const unsigned char * const okey = ikey + block_size;
338 const size_t hash_size = mbedtls_md_get_size( ctx->md_info );
339
340 unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
341 mbedtls_md_context_t aux;
342 size_t offset;
343 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
344
345 mbedtls_md_init( &aux );
346
347#define MD_CHK( func_call ) \
348 do { \
349 ret = (func_call); \
350 if( ret != 0 ) \
351 goto cleanup; \
352 } while( 0 )
353
354 MD_CHK( mbedtls_md_setup( &aux, ctx->md_info, 0 ) );
355
356 /* After hmac_start() of hmac_reset(), ikey has already been hashed,
357 * so we can start directly with the message */
358 MD_CHK( mbedtls_md_update( ctx, add_data, add_data_len ) );
359 MD_CHK( mbedtls_md_update( ctx, data, min_data_len ) );
360
361 /* For each possible length, compute the hash up to that point */
362 for( offset = min_data_len; offset <= max_data_len; offset++ )
363 {
364 MD_CHK( mbedtls_md_clone( &aux, ctx ) );
365 MD_CHK( mbedtls_md_finish( &aux, aux_out ) );
366 /* Keep only the correct inner_hash in the output buffer */
367 mbedtls_cf_memcpy_if_eq( output, aux_out, hash_size,
368 offset, data_len_secret );
369
370 if( offset < max_data_len )
371 MD_CHK( mbedtls_md_update( ctx, data + offset, 1 ) );
372 }
373
374 /* The context needs to finish() before it starts() again */
375 MD_CHK( mbedtls_md_finish( ctx, aux_out ) );
376
377 /* Now compute HASH(okey + inner_hash) */
378 MD_CHK( mbedtls_md_starts( ctx ) );
379 MD_CHK( mbedtls_md_update( ctx, okey, block_size ) );
380 MD_CHK( mbedtls_md_update( ctx, output, hash_size ) );
381 MD_CHK( mbedtls_md_finish( ctx, output ) );
382
383 /* Done, get ready for next time */
384 MD_CHK( mbedtls_md_hmac_reset( ctx ) );
385
386#undef MD_CHK
387
388cleanup:
389 mbedtls_md_free( &aux );
390 return( ret );
391}
392
393#endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200394
395#if defined(MBEDTLS_BIGNUM_C)
396
397#define MPI_VALIDATE_RET( cond ) \
398 MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
399
400/*
401 * Conditionally assign X = Y, without leaking information
402 * about whether the assignment was made or not.
403 * (Leaking information about the respective sizes of X and Y is ok however.)
404 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200405int mbedtls_mpi_safe_cond_assign( mbedtls_mpi *X,
406 const mbedtls_mpi *Y,
407 unsigned char assign )
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200408{
409 int ret = 0;
410 size_t i;
411 mbedtls_mpi_uint limb_mask;
412 MPI_VALIDATE_RET( X != NULL );
413 MPI_VALIDATE_RET( Y != NULL );
414
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200415 /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
gabor-mezei-arm60febd52021-08-11 15:07:02 +0200416 limb_mask = mbedtls_cf_mpi_uint_mask( assign );;
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200417
418 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
419
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200420 X->s = mbedtls_cf_cond_select_sign( assign, Y->s, X->s );
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200421
422 mbedtls_cf_mpi_uint_cond_assign( Y->n, X->p, Y->p, assign );
423
424 for( i = Y->n; i < X->n; i++ )
425 X->p[i] &= ~limb_mask;
426
427cleanup:
428 return( ret );
429}
430
gabor-mezei-arm58fc8a62021-09-27 15:37:50 +0200431/*
432 * Conditionally swap X and Y, without leaking information
433 * about whether the swap was made or not.
434 * Here it is not ok to simply swap the pointers, which whould lead to
435 * different memory access patterns when X and Y are used afterwards.
436 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200437int mbedtls_mpi_safe_cond_swap( mbedtls_mpi *X,
438 mbedtls_mpi *Y,
439 unsigned char swap )
gabor-mezei-arm58fc8a62021-09-27 15:37:50 +0200440{
441 int ret, s;
442 size_t i;
443 mbedtls_mpi_uint limb_mask;
444 mbedtls_mpi_uint tmp;
445 MPI_VALIDATE_RET( X != NULL );
446 MPI_VALIDATE_RET( Y != NULL );
447
448 if( X == Y )
449 return( 0 );
450
gabor-mezei-arm58fc8a62021-09-27 15:37:50 +0200451 /* all-bits 1 if swap is 1, all-bits 0 if swap is 0 */
gabor-mezei-arm60febd52021-08-11 15:07:02 +0200452 limb_mask = mbedtls_cf_mpi_uint_mask( swap );
gabor-mezei-arm58fc8a62021-09-27 15:37:50 +0200453
454 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, Y->n ) );
455 MBEDTLS_MPI_CHK( mbedtls_mpi_grow( Y, X->n ) );
456
457 s = X->s;
gabor-mezei-arm5e488242021-08-10 20:36:09 +0200458 X->s = mbedtls_cf_cond_select_sign( swap, Y->s, X->s );
459 Y->s = mbedtls_cf_cond_select_sign( swap, s, Y->s );
gabor-mezei-arm58fc8a62021-09-27 15:37:50 +0200460
461
462 for( i = 0; i < X->n; i++ )
463 {
464 tmp = X->p[i];
465 X->p[i] = ( X->p[i] & ~limb_mask ) | ( Y->p[i] & limb_mask );
466 Y->p[i] = ( Y->p[i] & ~limb_mask ) | ( tmp & limb_mask );
467 }
468
469cleanup:
470 return( ret );
471}
472
gabor-mezei-armb10301d2021-09-27 15:41:30 +0200473/*
474 * Compare signed values in constant time
475 */
gabor-mezei-arm04087df2021-09-27 16:29:52 +0200476int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X,
477 const mbedtls_mpi *Y,
478 unsigned *ret )
gabor-mezei-armb10301d2021-09-27 15:41:30 +0200479{
480 size_t i;
481 /* The value of any of these variables is either 0 or 1 at all times. */
482 unsigned cond, done, X_is_negative, Y_is_negative;
483
484 MPI_VALIDATE_RET( X != NULL );
485 MPI_VALIDATE_RET( Y != NULL );
486 MPI_VALIDATE_RET( ret != NULL );
487
488 if( X->n != Y->n )
489 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
490
491 /*
492 * Set sign_N to 1 if N >= 0, 0 if N < 0.
493 * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
494 */
495 X_is_negative = ( X->s & 2 ) >> 1;
496 Y_is_negative = ( Y->s & 2 ) >> 1;
497
498 /*
499 * If the signs are different, then the positive operand is the bigger.
500 * That is if X is negative (X_is_negative == 1), then X < Y is true and it
501 * is false if X is positive (X_is_negative == 0).
502 */
503 cond = ( X_is_negative ^ Y_is_negative );
504 *ret = cond & X_is_negative;
505
506 /*
507 * This is a constant-time function. We might have the result, but we still
508 * need to go through the loop. Record if we have the result already.
509 */
510 done = cond;
511
512 for( i = X->n; i > 0; i-- )
513 {
514 /*
515 * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
516 * X and Y are negative.
517 *
518 * Again even if we can make a decision, we just mark the result and
519 * the fact that we are done and continue looping.
520 */
521 cond = mbedtls_cf_mpi_uint_lt( Y->p[i - 1], X->p[i - 1] );
522 *ret |= cond & ( 1 - done ) & X_is_negative;
523 done |= cond;
524
525 /*
526 * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
527 * X and Y are positive.
528 *
529 * Again even if we can make a decision, we just mark the result and
530 * the fact that we are done and continue looping.
531 */
532 cond = mbedtls_cf_mpi_uint_lt( X->p[i - 1], Y->p[i - 1] );
533 *ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
534 done |= cond;
535 }
536
537 return( 0 );
538}
539
gabor-mezei-armb8caeee2021-09-27 15:33:35 +0200540#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-armf52941e2021-09-27 16:11:12 +0200541
542#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
543
544int mbedtls_cf_rsaes_pkcs1_v15_unpadding( int mode,
545 size_t ilen,
546 size_t *olen,
547 unsigned char *output,
548 size_t output_max_len,
549 unsigned char *buf )
550{
551 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
552 size_t i, plaintext_max_size;
553
554 /* The following variables take sensitive values: their value must
555 * not leak into the observable behavior of the function other than
556 * the designated outputs (output, olen, return value). Otherwise
557 * this would open the execution of the function to
558 * side-channel-based variants of the Bleichenbacher padding oracle
559 * attack. Potential side channels include overall timing, memory
560 * access patterns (especially visible to an adversary who has access
561 * to a shared memory cache), and branches (especially visible to
562 * an adversary who has access to a shared code cache or to a shared
563 * branch predictor). */
564 size_t pad_count = 0;
565 unsigned bad = 0;
566 unsigned char pad_done = 0;
567 size_t plaintext_size = 0;
568 unsigned output_too_large;
569
570 plaintext_max_size = mbedtls_cf_size_if( output_max_len > ilen - 11,
571 ilen - 11,
572 output_max_len );
573
574 /* Check and get padding length in constant time and constant
575 * memory trace. The first byte must be 0. */
576 bad |= buf[0];
577
578 if( mode == MBEDTLS_RSA_PRIVATE )
579 {
580 /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
581 * where PS must be at least 8 nonzero bytes. */
582 bad |= buf[1] ^ MBEDTLS_RSA_CRYPT;
583
584 /* Read the whole buffer. Set pad_done to nonzero if we find
585 * the 0x00 byte and remember the padding length in pad_count. */
586 for( i = 2; i < ilen; i++ )
587 {
588 pad_done |= ((buf[i] | (unsigned char)-buf[i]) >> 7) ^ 1;
589 pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
590 }
591 }
592 else
593 {
594 /* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00
595 * where PS must be at least 8 bytes with the value 0xFF. */
596 bad |= buf[1] ^ MBEDTLS_RSA_SIGN;
597
598 /* Read the whole buffer. Set pad_done to nonzero if we find
599 * the 0x00 byte and remember the padding length in pad_count.
600 * If there's a non-0xff byte in the padding, the padding is bad. */
601 for( i = 2; i < ilen; i++ )
602 {
603 pad_done |= mbedtls_cf_uint_if( buf[i], 0, 1 );
604 pad_count += mbedtls_cf_uint_if( pad_done, 0, 1 );
605 bad |= mbedtls_cf_uint_if( pad_done, 0, buf[i] ^ 0xFF );
606 }
607 }
608
609 /* If pad_done is still zero, there's no data, only unfinished padding. */
610 bad |= mbedtls_cf_uint_if( pad_done, 0, 1 );
611
612 /* There must be at least 8 bytes of padding. */
613 bad |= mbedtls_cf_size_gt( 8, pad_count );
614
615 /* If the padding is valid, set plaintext_size to the number of
616 * remaining bytes after stripping the padding. If the padding
617 * is invalid, avoid leaking this fact through the size of the
618 * output: use the maximum message size that fits in the output
619 * buffer. Do it without branches to avoid leaking the padding
620 * validity through timing. RSA keys are small enough that all the
621 * size_t values involved fit in unsigned int. */
622 plaintext_size = mbedtls_cf_uint_if(
623 bad, (unsigned) plaintext_max_size,
624 (unsigned) ( ilen - pad_count - 3 ) );
625
626 /* Set output_too_large to 0 if the plaintext fits in the output
627 * buffer and to 1 otherwise. */
628 output_too_large = mbedtls_cf_size_gt( plaintext_size,
629 plaintext_max_size );
630
631 /* Set ret without branches to avoid timing attacks. Return:
632 * - INVALID_PADDING if the padding is bad (bad != 0).
633 * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
634 * plaintext does not fit in the output buffer.
635 * - 0 if the padding is correct. */
636 ret = - (int) mbedtls_cf_uint_if(
637 bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
638 mbedtls_cf_uint_if( output_too_large,
639 - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
640 0 ) );
641
642 /* If the padding is bad or the plaintext is too large, zero the
643 * data that we're about to copy to the output buffer.
644 * We need to copy the same amount of data
645 * from the same buffer whether the padding is good or not to
646 * avoid leaking the padding validity through overall timing or
647 * through memory or cache access patterns. */
648 bad = mbedtls_cf_uint_mask( bad | output_too_large );
649 for( i = 11; i < ilen; i++ )
650 buf[i] &= ~bad;
651
652 /* If the plaintext is too large, truncate it to the buffer size.
653 * Copy anyway to avoid revealing the length through timing, because
654 * revealing the length is as bad as revealing the padding validity
655 * for a Bleichenbacher attack. */
656 plaintext_size = mbedtls_cf_uint_if( output_too_large,
657 (unsigned) plaintext_max_size,
658 (unsigned) plaintext_size );
659
660 /* Move the plaintext to the leftmost position where it can start in
661 * the working buffer, i.e. make it start plaintext_max_size from
662 * the end of the buffer. Do this with a memory access trace that
663 * does not depend on the plaintext size. After this move, the
664 * starting location of the plaintext is no longer sensitive
665 * information. */
666 mbedtls_cf_mem_move_to_left( buf + ilen - plaintext_max_size,
667 plaintext_max_size,
668 plaintext_max_size - plaintext_size );
669
670 /* Finally copy the decrypted plaintext plus trailing zeros into the output
671 * buffer. If output_max_len is 0, then output may be an invalid pointer
672 * and the result of memcpy() would be undefined; prevent undefined
673 * behavior making sure to depend only on output_max_len (the size of the
674 * user-provided output buffer), which is independent from plaintext
675 * length, validity of padding, success of the decryption, and other
676 * secrets. */
677 if( output_max_len != 0 )
678 memcpy( output, buf + ilen - plaintext_max_size, plaintext_max_size );
679
680 /* Report the amount of data we copied to the output buffer. In case
681 * of errors (bad padding or output too large), the value of *olen
682 * when this function returns is not specified. Making it equivalent
683 * to the good case limits the risks of leaking the padding validity. */
684 *olen = plaintext_size;
685
686 return( ret );
687}
688
689#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */