blob: 442eb0e7a2f866328ac0154ba8a8573e26368ab9 [file] [log] [blame]
gabor-mezei-armd1125342021-07-12 16:31:22 +02001/**
2 * Constant-time functions
3 *
4 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may
8 * not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
Gilles Peskine449bd832023-01-11 14:50:10 +010020/*
Gabor Mezei642eeb22021-11-03 16:13:32 +010021 * The following functions are implemented without using comparison operators, as those
Gabor Mezeieab90bc2021-10-18 16:09:41 +020022 * might be translated to branches by some compilers on some platforms.
23 */
24
gabor-mezei-armd1125342021-07-12 16:31:22 +020025#include "common.h"
Gabor Mezei22c9a6f2021-10-20 12:09:35 +020026#include "constant_time_internal.h"
Gabor Mezei765862c2021-10-19 12:22:25 +020027#include "mbedtls/constant_time.h"
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +020028#include "mbedtls/error.h"
gabor-mezei-arm5b3a32d2021-09-29 10:50:31 +020029#include "mbedtls/platform_util.h"
gabor-mezei-armdb9a38c2021-09-27 11:28:54 +020030
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +020031#if defined(MBEDTLS_BIGNUM_C)
32#include "mbedtls/bignum.h"
Gabor Mezei87638a92022-09-15 20:02:36 +020033#include "bignum_core.h"
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +020034#endif
35
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +020036#if defined(MBEDTLS_SSL_TLS_C)
37#include "ssl_misc.h"
38#endif
39
gabor-mezei-arm5b3a32d2021-09-29 10:50:31 +020040#if defined(MBEDTLS_RSA_C)
41#include "mbedtls/rsa.h"
42#endif
43
Gabor Mezei28d61152021-11-15 16:13:01 +010044#if defined(MBEDTLS_BASE64_C)
45#include "constant_time_invasive.h"
46#endif
47
gabor-mezei-armfdb71182021-09-27 16:11:12 +020048#include <string.h>
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +020049
Gilles Peskine449bd832023-01-11 14:50:10 +010050int mbedtls_ct_memcmp(const void *a,
51 const void *b,
52 size_t n)
gabor-mezei-armdb9a38c2021-09-27 11:28:54 +020053{
54 size_t i;
55 volatile const unsigned char *A = (volatile const unsigned char *) a;
56 volatile const unsigned char *B = (volatile const unsigned char *) b;
57 volatile unsigned char diff = 0;
58
Gilles Peskine449bd832023-01-11 14:50:10 +010059 for (i = 0; i < n; i++) {
gabor-mezei-armdb9a38c2021-09-27 11:28:54 +020060 /* Read volatile data in order before computing diff.
61 * This avoids IAR compiler warning:
62 * 'the order of volatile accesses is undefined ..' */
63 unsigned char x = A[i], y = B[i];
64 diff |= x ^ y;
65 }
66
Gilles Peskine449bd832023-01-11 14:50:10 +010067 return (int) diff;
gabor-mezei-armdb9a38c2021-09-27 11:28:54 +020068}
69
Gilles Peskine449bd832023-01-11 14:50:10 +010070unsigned mbedtls_ct_uint_mask(unsigned value)
gabor-mezei-arm340948e2021-09-27 11:40:03 +020071{
72 /* MSVC has a warning about unary minus on unsigned, but this is
73 * well-defined and precisely what we want to do here */
74#if defined(_MSC_VER)
75#pragma warning( push )
76#pragma warning( disable : 4146 )
77#endif
Gilles Peskine449bd832023-01-11 14:50:10 +010078 return -((value | -value) >> (sizeof(value) * 8 - 1));
gabor-mezei-arm340948e2021-09-27 11:40:03 +020079#if defined(_MSC_VER)
80#pragma warning( pop )
81#endif
82}
gabor-mezei-arm3733bf82021-09-27 11:49:42 +020083
Przemek Stekiel89ad6232022-09-27 13:36:12 +020084#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
Gabor Mezei6a426c92021-10-20 11:17:43 +020085
Gilles Peskine449bd832023-01-11 14:50:10 +010086size_t mbedtls_ct_size_mask(size_t value)
gabor-mezei-arm3733bf82021-09-27 11:49:42 +020087{
88 /* MSVC has a warning about unary minus on unsigned integer types,
89 * but this is well-defined and precisely what we want to do here. */
90#if defined(_MSC_VER)
91#pragma warning( push )
92#pragma warning( disable : 4146 )
93#endif
Gilles Peskine449bd832023-01-11 14:50:10 +010094 return -((value | -value) >> (sizeof(value) * 8 - 1));
gabor-mezei-arm3733bf82021-09-27 11:49:42 +020095#if defined(_MSC_VER)
96#pragma warning( pop )
97#endif
98}
gabor-mezei-armc76227d2021-09-27 11:53:54 +020099
Przemek Stekiel89ad6232022-09-27 13:36:12 +0200100#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
Gabor Mezei6a426c92021-10-20 11:17:43 +0200101
gabor-mezei-arm9cb55692021-08-11 15:07:02 +0200102#if defined(MBEDTLS_BIGNUM_C)
103
Gilles Peskine449bd832023-01-11 14:50:10 +0100104mbedtls_mpi_uint mbedtls_ct_mpi_uint_mask(mbedtls_mpi_uint value)
gabor-mezei-arm9cb55692021-08-11 15:07:02 +0200105{
106 /* MSVC has a warning about unary minus on unsigned, but this is
107 * well-defined and precisely what we want to do here */
108#if defined(_MSC_VER)
109#pragma warning( push )
110#pragma warning( disable : 4146 )
111#endif
Gilles Peskine449bd832023-01-11 14:50:10 +0100112 return -((value | -value) >> (sizeof(value) * 8 - 1));
gabor-mezei-arm9cb55692021-08-11 15:07:02 +0200113#if defined(_MSC_VER)
114#pragma warning( pop )
115#endif
116}
117
118#endif /* MBEDTLS_BIGNUM_C */
119
Gabor Mezeie2123792021-10-18 17:05:06 +0200120#if defined(MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC)
121
Gabor Mezei1e642612021-10-18 16:05:50 +0200122/** Constant-flow mask generation for "less than" comparison:
123 * - if \p x < \p y, return all-bits 1, that is (size_t) -1
124 * - otherwise, return all bits 0, that is 0
125 *
126 * This function can be used to write constant-time code by replacing branches
127 * with bit operations using masks.
128 *
129 * \param x The first value to analyze.
130 * \param y The second value to analyze.
131 *
132 * \return All-bits-one if \p x is less than \p y, otherwise zero.
133 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100134static size_t mbedtls_ct_size_mask_lt(size_t x,
135 size_t y)
gabor-mezei-armc76227d2021-09-27 11:53:54 +0200136{
137 /* This has the most significant bit set if and only if x < y */
138 const size_t sub = x - y;
139
140 /* sub1 = (x < y) ? 1 : 0 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100141 const size_t sub1 = sub >> (sizeof(sub) * 8 - 1);
gabor-mezei-armc76227d2021-09-27 11:53:54 +0200142
143 /* mask = (x < y) ? 0xff... : 0x00... */
Gilles Peskine449bd832023-01-11 14:50:10 +0100144 const size_t mask = mbedtls_ct_size_mask(sub1);
gabor-mezei-armc76227d2021-09-27 11:53:54 +0200145
Gilles Peskine449bd832023-01-11 14:50:10 +0100146 return mask;
gabor-mezei-armc76227d2021-09-27 11:53:54 +0200147}
gabor-mezei-arm16fc57b2021-09-27 11:58:31 +0200148
Gilles Peskine449bd832023-01-11 14:50:10 +0100149size_t mbedtls_ct_size_mask_ge(size_t x,
150 size_t y)
gabor-mezei-arm16fc57b2021-09-27 11:58:31 +0200151{
Gilles Peskine449bd832023-01-11 14:50:10 +0100152 return ~mbedtls_ct_size_mask_lt(x, y);
gabor-mezei-arm16fc57b2021-09-27 11:58:31 +0200153}
gabor-mezei-arm8d1d5fd2021-09-27 12:15:19 +0200154
Gabor Mezeie2123792021-10-18 17:05:06 +0200155#endif /* MBEDTLS_SSL_SOME_SUITES_USE_TLS_CBC */
156
Gabor Mezei28d61152021-11-15 16:13:01 +0100157#if defined(MBEDTLS_BASE64_C)
158
159/* Return 0xff if low <= c <= high, 0 otherwise.
160 *
161 * Constant flow with respect to c.
162 */
Gabor Mezeic0d8dda2021-11-26 17:20:36 +0100163MBEDTLS_STATIC_TESTABLE
Gilles Peskine449bd832023-01-11 14:50:10 +0100164unsigned char mbedtls_ct_uchar_mask_of_range(unsigned char low,
165 unsigned char high,
166 unsigned char c)
Gabor Mezei28d61152021-11-15 16:13:01 +0100167{
168 /* low_mask is: 0 if low <= c, 0x...ff if low > c */
Gilles Peskine449bd832023-01-11 14:50:10 +0100169 unsigned low_mask = ((unsigned) c - low) >> 8;
Gabor Mezei28d61152021-11-15 16:13:01 +0100170 /* high_mask is: 0 if c <= high, 0x...ff if c > high */
Gilles Peskine449bd832023-01-11 14:50:10 +0100171 unsigned high_mask = ((unsigned) high - c) >> 8;
172 return ~(low_mask | high_mask) & 0xff;
Gabor Mezei28d61152021-11-15 16:13:01 +0100173}
174
175#endif /* MBEDTLS_BASE64_C */
176
Gilles Peskine449bd832023-01-11 14:50:10 +0100177unsigned mbedtls_ct_size_bool_eq(size_t x,
178 size_t y)
gabor-mezei-arm8d1d5fd2021-09-27 12:15:19 +0200179{
180 /* diff = 0 if x == y, non-zero otherwise */
181 const size_t diff = x ^ y;
182
183 /* MSVC has a warning about unary minus on unsigned integer types,
184 * but this is well-defined and precisely what we want to do here. */
185#if defined(_MSC_VER)
186#pragma warning( push )
187#pragma warning( disable : 4146 )
188#endif
189
190 /* diff_msb's most significant bit is equal to x != y */
Gilles Peskine449bd832023-01-11 14:50:10 +0100191 const size_t diff_msb = (diff | (size_t) -diff);
gabor-mezei-arm8d1d5fd2021-09-27 12:15:19 +0200192
193#if defined(_MSC_VER)
194#pragma warning( pop )
195#endif
196
197 /* diff1 = (x != y) ? 1 : 0 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100198 const unsigned diff1 = diff_msb >> (sizeof(diff_msb) * 8 - 1);
gabor-mezei-arm8d1d5fd2021-09-27 12:15:19 +0200199
Gilles Peskine449bd832023-01-11 14:50:10 +0100200 return 1 ^ diff1;
gabor-mezei-arm8d1d5fd2021-09-27 12:15:19 +0200201}
gabor-mezei-arm5a854422021-09-27 12:25:07 +0200202
Gabor Mezeie2123792021-10-18 17:05:06 +0200203#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
204
Gabor Mezeia2d0f902021-10-18 16:35:23 +0200205/** Constant-flow "greater than" comparison:
206 * return x > y
207 *
208 * This is equivalent to \p x > \p y, but is likely to be compiled
209 * to code using bitwise operation rather than a branch.
210 *
211 * \param x The first value to analyze.
212 * \param y The second value to analyze.
213 *
214 * \return 1 if \p x greater than \p y, otherwise 0.
215 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100216static unsigned mbedtls_ct_size_gt(size_t x,
217 size_t y)
gabor-mezei-arm5a854422021-09-27 12:25:07 +0200218{
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200219 /* Return the sign bit (1 for negative) of (y - x). */
Gilles Peskine449bd832023-01-11 14:50:10 +0100220 return (y - x) >> (sizeof(size_t) * 8 - 1);
gabor-mezei-arm5a854422021-09-27 12:25:07 +0200221}
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +0200222
Gabor Mezeie2123792021-10-18 17:05:06 +0200223#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
224
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +0200225#if defined(MBEDTLS_BIGNUM_C)
226
Gilles Peskine449bd832023-01-11 14:50:10 +0100227unsigned mbedtls_ct_mpi_uint_lt(const mbedtls_mpi_uint x,
228 const mbedtls_mpi_uint y)
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +0200229{
230 mbedtls_mpi_uint ret;
231 mbedtls_mpi_uint cond;
232
233 /*
234 * Check if the most significant bits (MSB) of the operands are different.
235 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100236 cond = (x ^ y);
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +0200237 /*
238 * If the MSB are the same then the difference x-y will be negative (and
239 * have its MSB set to 1 during conversion to unsigned) if and only if x<y.
240 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100241 ret = (x - y) & ~cond;
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +0200242 /*
243 * If the MSB are different, then the operand with the MSB of 1 is the
244 * bigger. (That is if y has MSB of 1, then x<y is true and it is false if
245 * the MSB of y is 0.)
246 */
247 ret |= y & cond;
248
249
Gilles Peskine449bd832023-01-11 14:50:10 +0100250 ret = ret >> (sizeof(mbedtls_mpi_uint) * 8 - 1);
gabor-mezei-arm3f90fd52021-09-27 12:55:33 +0200251
252 return (unsigned) ret;
253}
254
255#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-armb2dbf2c2021-09-27 12:59:30 +0200256
Gilles Peskine449bd832023-01-11 14:50:10 +0100257unsigned mbedtls_ct_uint_if(unsigned condition,
258 unsigned if1,
259 unsigned if0)
gabor-mezei-armb2dbf2c2021-09-27 12:59:30 +0200260{
Gilles Peskine449bd832023-01-11 14:50:10 +0100261 unsigned mask = mbedtls_ct_uint_mask(condition);
262 return (mask & if1) | (~mask & if0);
gabor-mezei-armb2dbf2c2021-09-27 12:59:30 +0200263}
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200264
Gabor Mezeie2123792021-10-18 17:05:06 +0200265#if defined(MBEDTLS_BIGNUM_C)
gabor-mezei-arm65cefdb2021-09-27 15:47:00 +0200266
Gabor Mezei642eeb22021-11-03 16:13:32 +0100267/** Select between two sign values without branches.
Gabor Mezeia2d0f902021-10-18 16:35:23 +0200268 *
269 * This is functionally equivalent to `condition ? if1 : if0` but uses only bit
270 * operations in order to avoid branches.
271 *
272 * \note if1 and if0 must be either 1 or -1, otherwise the result
273 * is undefined.
274 *
Tom Cosgrove583816c2022-08-18 14:09:18 +0100275 * \param condition Condition to test; must be either 0 or 1.
Gabor Mezeia2d0f902021-10-18 16:35:23 +0200276 * \param if1 The first sign; must be either +1 or -1.
277 * \param if0 The second sign; must be either +1 or -1.
278 *
279 * \return \c if1 if \p condition is nonzero, otherwise \c if0.
280 * */
Gilles Peskine449bd832023-01-11 14:50:10 +0100281static int mbedtls_ct_cond_select_sign(unsigned char condition,
282 int if1,
283 int if0)
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200284{
Gabor Mezei642eeb22021-11-03 16:13:32 +0100285 /* In order to avoid questions about what we can reasonably assume about
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200286 * the representations of signed integers, move everything to unsigned
Gabor Mezeia316fc82021-10-18 16:28:27 +0200287 * by taking advantage of the fact that if1 and if0 are either +1 or -1. */
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200288 unsigned uif1 = if1 + 1;
289 unsigned uif0 = if0 + 1;
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200290
Gabor Mezeia316fc82021-10-18 16:28:27 +0200291 /* condition was 0 or 1, mask is 0 or 2 as are uif1 and uif0 */
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200292 const unsigned mask = condition << 1;
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200293
Gabor Mezeia316fc82021-10-18 16:28:27 +0200294 /* select uif1 or uif0 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100295 unsigned ur = (uif0 & ~mask) | (uif1 & mask);
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200296
297 /* ur is now 0 or 2, convert back to -1 or +1 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100298 return (int) ur - 1;
gabor-mezei-armd3230d52021-09-27 13:03:57 +0200299}
gabor-mezei-armbe8d98b2021-09-27 13:17:15 +0200300
Gilles Peskine449bd832023-01-11 14:50:10 +0100301void mbedtls_ct_mpi_uint_cond_assign(size_t n,
302 mbedtls_mpi_uint *dest,
303 const mbedtls_mpi_uint *src,
304 unsigned char condition)
gabor-mezei-armbe8d98b2021-09-27 13:17:15 +0200305{
306 size_t i;
307
308 /* MSVC has a warning about unary minus on unsigned integer types,
309 * but this is well-defined and precisely what we want to do here. */
310#if defined(_MSC_VER)
311#pragma warning( push )
312#pragma warning( disable : 4146 )
313#endif
314
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200315 /* all-bits 1 if condition is 1, all-bits 0 if condition is 0 */
316 const mbedtls_mpi_uint mask = -condition;
gabor-mezei-armbe8d98b2021-09-27 13:17:15 +0200317
318#if defined(_MSC_VER)
319#pragma warning( pop )
320#endif
321
Gilles Peskine449bd832023-01-11 14:50:10 +0100322 for (i = 0; i < n; i++) {
323 dest[i] = (src[i] & mask) | (dest[i] & ~mask);
324 }
gabor-mezei-armbe8d98b2021-09-27 13:17:15 +0200325}
326
327#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-arm394aeaa2021-09-27 13:31:06 +0200328
Gabor Mezei9a4074a2021-11-15 16:18:54 +0100329#if defined(MBEDTLS_BASE64_C)
330
Gilles Peskine449bd832023-01-11 14:50:10 +0100331unsigned char mbedtls_ct_base64_enc_char(unsigned char value)
Gabor Mezei9a4074a2021-11-15 16:18:54 +0100332{
333 unsigned char digit = 0;
Gabor Mezei14d5fac2021-11-24 15:51:39 +0100334 /* For each range of values, if value is in that range, mask digit with
335 * the corresponding value. Since value can only be in a single range,
Gabor Mezei9a4074a2021-11-15 16:18:54 +0100336 * only at most one masking will change digit. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100337 digit |= mbedtls_ct_uchar_mask_of_range(0, 25, value) & ('A' + value);
338 digit |= mbedtls_ct_uchar_mask_of_range(26, 51, value) & ('a' + value - 26);
339 digit |= mbedtls_ct_uchar_mask_of_range(52, 61, value) & ('0' + value - 52);
340 digit |= mbedtls_ct_uchar_mask_of_range(62, 62, value) & '+';
341 digit |= mbedtls_ct_uchar_mask_of_range(63, 63, value) & '/';
342 return digit;
Gabor Mezei9a4074a2021-11-15 16:18:54 +0100343}
344
Gilles Peskine449bd832023-01-11 14:50:10 +0100345signed char mbedtls_ct_base64_dec_value(unsigned char c)
Gabor Mezei358829a2021-11-15 16:22:37 +0100346{
347 unsigned char val = 0;
348 /* For each range of digits, if c is in that range, mask val with
349 * the corresponding value. Since c can only be in a single range,
350 * only at most one masking will change val. Set val to one plus
351 * the desired value so that it stays 0 if c is in none of the ranges. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100352 val |= mbedtls_ct_uchar_mask_of_range('A', 'Z', c) & (c - 'A' + 0 + 1);
353 val |= mbedtls_ct_uchar_mask_of_range('a', 'z', c) & (c - 'a' + 26 + 1);
354 val |= mbedtls_ct_uchar_mask_of_range('0', '9', c) & (c - '0' + 52 + 1);
355 val |= mbedtls_ct_uchar_mask_of_range('+', '+', c) & (c - '+' + 62 + 1);
356 val |= mbedtls_ct_uchar_mask_of_range('/', '/', c) & (c - '/' + 63 + 1);
Gabor Mezei358829a2021-11-15 16:22:37 +0100357 /* At this point, val is 0 if c is an invalid digit and v+1 if c is
358 * a digit with the value v. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100359 return val - 1;
Gabor Mezei358829a2021-11-15 16:22:37 +0100360}
361
Gabor Mezei9a4074a2021-11-15 16:18:54 +0100362#endif /* MBEDTLS_BASE64_C */
363
Gabor Mezeie2123792021-10-18 17:05:06 +0200364#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
365
Gabor Mezeia2d0f902021-10-18 16:35:23 +0200366/** Shift some data towards the left inside a buffer.
367 *
Gabor Mezei90437e32021-10-20 11:59:27 +0200368 * `mbedtls_ct_mem_move_to_left(start, total, offset)` is functionally
Gabor Mezeia2d0f902021-10-18 16:35:23 +0200369 * equivalent to
370 * ```
371 * memmove(start, start + offset, total - offset);
372 * memset(start + offset, 0, total - offset);
373 * ```
374 * but it strives to use a memory access pattern (and thus total timing)
375 * that does not depend on \p offset. This timing independence comes at
376 * the expense of performance.
377 *
378 * \param start Pointer to the start of the buffer.
379 * \param total Total size of the buffer.
380 * \param offset Offset from which to copy \p total - \p offset bytes.
381 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100382static void mbedtls_ct_mem_move_to_left(void *start,
383 size_t total,
384 size_t offset)
gabor-mezei-arm394aeaa2021-09-27 13:31:06 +0200385{
386 volatile unsigned char *buf = start;
387 size_t i, n;
Gilles Peskine449bd832023-01-11 14:50:10 +0100388 if (total == 0) {
gabor-mezei-arm394aeaa2021-09-27 13:31:06 +0200389 return;
Gilles Peskine449bd832023-01-11 14:50:10 +0100390 }
391 for (i = 0; i < total; i++) {
392 unsigned no_op = mbedtls_ct_size_gt(total - offset, i);
gabor-mezei-arm394aeaa2021-09-27 13:31:06 +0200393 /* The first `total - offset` passes are a no-op. The last
394 * `offset` passes shift the data one byte to the left and
395 * zero out the last byte. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100396 for (n = 0; n < total - 1; n++) {
gabor-mezei-arm394aeaa2021-09-27 13:31:06 +0200397 unsigned char current = buf[n];
398 unsigned char next = buf[n+1];
Gilles Peskine449bd832023-01-11 14:50:10 +0100399 buf[n] = mbedtls_ct_uint_if(no_op, current, next);
gabor-mezei-arm394aeaa2021-09-27 13:31:06 +0200400 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100401 buf[total-1] = mbedtls_ct_uint_if(no_op, buf[total-1], 0);
gabor-mezei-arm394aeaa2021-09-27 13:31:06 +0200402 }
403}
gabor-mezei-armdee0fd32021-09-27 13:34:25 +0200404
Gabor Mezeie2123792021-10-18 17:05:06 +0200405#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
406
Przemek Stekiel89ad6232022-09-27 13:36:12 +0200407#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
Gabor Mezeie2123792021-10-18 17:05:06 +0200408
Gilles Peskine449bd832023-01-11 14:50:10 +0100409void mbedtls_ct_memcpy_if_eq(unsigned char *dest,
410 const unsigned char *src,
411 size_t len,
412 size_t c1,
413 size_t c2)
gabor-mezei-armdee0fd32021-09-27 13:34:25 +0200414{
415 /* mask = c1 == c2 ? 0xff : 0x00 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100416 const size_t equal = mbedtls_ct_size_bool_eq(c1, c2);
417 const unsigned char mask = (unsigned char) mbedtls_ct_size_mask(equal);
gabor-mezei-armdee0fd32021-09-27 13:34:25 +0200418
gabor-mezei-arm87ac5be2021-08-10 20:36:09 +0200419 /* dest[i] = c1 == c2 ? src[i] : dest[i] */
Gilles Peskine449bd832023-01-11 14:50:10 +0100420 for (size_t i = 0; i < len; i++) {
421 dest[i] = (src[i] & mask) | (dest[i] & ~mask);
422 }
gabor-mezei-armdee0fd32021-09-27 13:34:25 +0200423}
gabor-mezei-arm0e7f71e2021-09-27 13:57:45 +0200424
Gilles Peskine449bd832023-01-11 14:50:10 +0100425void mbedtls_ct_memcpy_offset(unsigned char *dest,
426 const unsigned char *src,
427 size_t offset,
428 size_t offset_min,
429 size_t offset_max,
430 size_t len)
gabor-mezei-arm0e7f71e2021-09-27 13:57:45 +0200431{
Gabor Mezei63bbba52021-10-18 16:17:57 +0200432 size_t offsetval;
gabor-mezei-arm0e7f71e2021-09-27 13:57:45 +0200433
Gilles Peskine449bd832023-01-11 14:50:10 +0100434 for (offsetval = offset_min; offsetval <= offset_max; offsetval++) {
435 mbedtls_ct_memcpy_if_eq(dest, src + offsetval, len,
436 offsetval, offset);
gabor-mezei-arm0e7f71e2021-09-27 13:57:45 +0200437 }
438}
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200439
Neil Armstrong2968d302022-02-25 15:09:36 +0100440#if defined(MBEDTLS_USE_PSA_CRYPTO)
Neil Armstrong36cc13b2022-03-17 16:36:52 +0100441
442#if defined(PSA_WANT_ALG_SHA_384)
Gilles Peskine449bd832023-01-11 14:50:10 +0100443#define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_384)
Neil Armstrong36cc13b2022-03-17 16:36:52 +0100444#elif defined(PSA_WANT_ALG_SHA_256)
Gilles Peskine449bd832023-01-11 14:50:10 +0100445#define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_256)
Neil Armstrong36cc13b2022-03-17 16:36:52 +0100446#else /* See check_config.h */
Gilles Peskine449bd832023-01-11 14:50:10 +0100447#define MAX_HASH_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_1)
Neil Armstrong36cc13b2022-03-17 16:36:52 +0100448#endif
449
Gilles Peskine449bd832023-01-11 14:50:10 +0100450int mbedtls_ct_hmac(mbedtls_svc_key_id_t key,
451 psa_algorithm_t mac_alg,
452 const unsigned char *add_data,
453 size_t add_data_len,
454 const unsigned char *data,
455 size_t data_len_secret,
456 size_t min_data_len,
457 size_t max_data_len,
458 unsigned char *output)
Neil Armstrong2968d302022-02-25 15:09:36 +0100459{
460 /*
Neil Armstrong28d9c632022-03-17 16:33:27 +0100461 * This function breaks the HMAC abstraction and uses psa_hash_clone()
462 * extension in order to get constant-flow behaviour.
Neil Armstrong2968d302022-02-25 15:09:36 +0100463 *
464 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
465 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
466 * patterns (see RFC 2104, sec. 2).
467 *
468 * We'll first compute ikey/okey, then inner_hash = HASH(ikey + msg) by
469 * hashing up to minlen, then cloning the context, and for each byte up
470 * to maxlen finishing up the hash computation, keeping only the
471 * correct result.
472 *
473 * Then we only need to compute HASH(okey + inner_hash) and we're done.
474 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100475 psa_algorithm_t hash_alg = PSA_ALG_HMAC_GET_HASH(mac_alg);
476 const size_t block_size = PSA_HASH_BLOCK_LENGTH(hash_alg);
Neil Armstrong9ebb9ff2022-03-17 17:04:37 +0100477 unsigned char key_buf[MAX_HASH_BLOCK_LENGTH];
Gilles Peskine449bd832023-01-11 14:50:10 +0100478 const size_t hash_size = PSA_HASH_LENGTH(hash_alg);
Neil Armstrong2968d302022-02-25 15:09:36 +0100479 psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
480 size_t hash_length;
481
Neil Armstrong36cc13b2022-03-17 16:36:52 +0100482 unsigned char aux_out[PSA_HASH_MAX_SIZE];
Neil Armstrong2968d302022-02-25 15:09:36 +0100483 psa_hash_operation_t aux_operation = PSA_HASH_OPERATION_INIT;
484 size_t offset;
485 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
486
Neil Armstrong2968d302022-02-25 15:09:36 +0100487 size_t mac_key_length;
488 size_t i;
489
Gilles Peskine449bd832023-01-11 14:50:10 +0100490#define PSA_CHK(func_call) \
Neil Armstrong2968d302022-02-25 15:09:36 +0100491 do { \
492 status = (func_call); \
Gilles Peskine449bd832023-01-11 14:50:10 +0100493 if (status != PSA_SUCCESS) \
494 goto cleanup; \
495 } while (0)
Neil Armstrong2968d302022-02-25 15:09:36 +0100496
Neil Armstrong72c2f762022-03-17 16:39:10 +0100497 /* Export MAC key
498 * We assume key length is always exactly the output size
499 * which is never more than the block size, thus we use block_size
500 * as the key buffer size.
501 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100502 PSA_CHK(psa_export_key(key, key_buf, block_size, &mac_key_length));
Neil Armstrong2968d302022-02-25 15:09:36 +0100503
Neil Armstrong9ebb9ff2022-03-17 17:04:37 +0100504 /* Calculate ikey */
Gilles Peskine449bd832023-01-11 14:50:10 +0100505 for (i = 0; i < mac_key_length; i++) {
506 key_buf[i] = (unsigned char) (key_buf[i] ^ 0x36);
507 }
508 for (; i < block_size; ++i) {
Neil Armstrong9ebb9ff2022-03-17 17:04:37 +0100509 key_buf[i] = 0x36;
Gilles Peskine449bd832023-01-11 14:50:10 +0100510 }
Neil Armstrong2968d302022-02-25 15:09:36 +0100511
Gilles Peskine449bd832023-01-11 14:50:10 +0100512 PSA_CHK(psa_hash_setup(&operation, hash_alg));
Neil Armstrong2968d302022-02-25 15:09:36 +0100513
514 /* Now compute inner_hash = HASH(ikey + msg) */
Gilles Peskine449bd832023-01-11 14:50:10 +0100515 PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
516 PSA_CHK(psa_hash_update(&operation, add_data, add_data_len));
517 PSA_CHK(psa_hash_update(&operation, data, min_data_len));
Neil Armstrong2968d302022-02-25 15:09:36 +0100518
Paul Elliott5260ce22022-05-09 18:15:54 +0100519 /* Fill the hash buffer in advance with something that is
520 * not a valid hash (barring an attack on the hash and
521 * deliberately-crafted input), in case the caller doesn't
522 * check the return status properly. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100523 memset(output, '!', hash_size);
Paul Elliott5260ce22022-05-09 18:15:54 +0100524
Neil Armstrong2968d302022-02-25 15:09:36 +0100525 /* For each possible length, compute the hash up to that point */
Gilles Peskine449bd832023-01-11 14:50:10 +0100526 for (offset = min_data_len; offset <= max_data_len; offset++) {
527 PSA_CHK(psa_hash_clone(&operation, &aux_operation));
528 PSA_CHK(psa_hash_finish(&aux_operation, aux_out,
529 PSA_HASH_MAX_SIZE, &hash_length));
Neil Armstrong2968d302022-02-25 15:09:36 +0100530 /* Keep only the correct inner_hash in the output buffer */
Gilles Peskine449bd832023-01-11 14:50:10 +0100531 mbedtls_ct_memcpy_if_eq(output, aux_out, hash_size,
532 offset, data_len_secret);
Neil Armstrong2968d302022-02-25 15:09:36 +0100533
Gilles Peskine449bd832023-01-11 14:50:10 +0100534 if (offset < max_data_len) {
535 PSA_CHK(psa_hash_update(&operation, data + offset, 1));
536 }
Neil Armstrong2968d302022-02-25 15:09:36 +0100537 }
538
Neil Armstrong28d9c632022-03-17 16:33:27 +0100539 /* Abort current operation to prepare for final operation */
Gilles Peskine449bd832023-01-11 14:50:10 +0100540 PSA_CHK(psa_hash_abort(&operation));
Neil Armstrong2968d302022-02-25 15:09:36 +0100541
Neil Armstrong9ebb9ff2022-03-17 17:04:37 +0100542 /* Calculate okey */
Gilles Peskine449bd832023-01-11 14:50:10 +0100543 for (i = 0; i < mac_key_length; i++) {
544 key_buf[i] = (unsigned char) ((key_buf[i] ^ 0x36) ^ 0x5C);
545 }
546 for (; i < block_size; ++i) {
Neil Armstrong9ebb9ff2022-03-17 17:04:37 +0100547 key_buf[i] = 0x5C;
Gilles Peskine449bd832023-01-11 14:50:10 +0100548 }
Neil Armstrong9ebb9ff2022-03-17 17:04:37 +0100549
Neil Armstrong2968d302022-02-25 15:09:36 +0100550 /* Now compute HASH(okey + inner_hash) */
Gilles Peskine449bd832023-01-11 14:50:10 +0100551 PSA_CHK(psa_hash_setup(&operation, hash_alg));
552 PSA_CHK(psa_hash_update(&operation, key_buf, block_size));
553 PSA_CHK(psa_hash_update(&operation, output, hash_size));
554 PSA_CHK(psa_hash_finish(&operation, output, hash_size, &hash_length));
Neil Armstrong2968d302022-02-25 15:09:36 +0100555
556#undef PSA_CHK
557
558cleanup:
Gilles Peskine449bd832023-01-11 14:50:10 +0100559 mbedtls_platform_zeroize(key_buf, MAX_HASH_BLOCK_LENGTH);
560 mbedtls_platform_zeroize(aux_out, PSA_HASH_MAX_SIZE);
Neil Armstrong36cc13b2022-03-17 16:36:52 +0100561
Gilles Peskine449bd832023-01-11 14:50:10 +0100562 psa_hash_abort(&operation);
563 psa_hash_abort(&aux_operation);
564 return psa_ssl_status_to_mbedtls(status);
Neil Armstrong2968d302022-02-25 15:09:36 +0100565}
Neil Armstrong36cc13b2022-03-17 16:36:52 +0100566
567#undef MAX_HASH_BLOCK_LENGTH
568
Neil Armstrong2968d302022-02-25 15:09:36 +0100569#else
Gilles Peskine449bd832023-01-11 14:50:10 +0100570int mbedtls_ct_hmac(mbedtls_md_context_t *ctx,
571 const unsigned char *add_data,
572 size_t add_data_len,
573 const unsigned char *data,
574 size_t data_len_secret,
575 size_t min_data_len,
576 size_t max_data_len,
577 unsigned char *output)
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200578{
579 /*
580 * This function breaks the HMAC abstraction and uses the md_clone()
581 * extension to the MD API in order to get constant-flow behaviour.
582 *
583 * HMAC(msg) is defined as HASH(okey + HASH(ikey + msg)) where + means
584 * concatenation, and okey/ikey are the XOR of the key with some fixed bit
585 * patterns (see RFC 2104, sec. 2), which are stored in ctx->hmac_ctx.
586 *
587 * We'll first compute inner_hash = HASH(ikey + msg) by hashing up to
588 * minlen, then cloning the context, and for each byte up to maxlen
589 * finishing up the hash computation, keeping only the correct result.
590 *
591 * Then we only need to compute HASH(okey + inner_hash) and we're done.
592 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100593 const mbedtls_md_type_t md_alg = mbedtls_md_get_type(ctx->md_info);
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200594 /* TLS 1.2 only supports SHA-384, SHA-256, SHA-1, MD-5,
595 * all of which have the same block size except SHA-384. */
596 const size_t block_size = md_alg == MBEDTLS_MD_SHA384 ? 128 : 64;
597 const unsigned char * const ikey = ctx->hmac_ctx;
598 const unsigned char * const okey = ikey + block_size;
Gilles Peskine449bd832023-01-11 14:50:10 +0100599 const size_t hash_size = mbedtls_md_get_size(ctx->md_info);
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200600
601 unsigned char aux_out[MBEDTLS_MD_MAX_SIZE];
602 mbedtls_md_context_t aux;
603 size_t offset;
604 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
605
Gilles Peskine449bd832023-01-11 14:50:10 +0100606 mbedtls_md_init(&aux);
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200607
Gilles Peskine449bd832023-01-11 14:50:10 +0100608#define MD_CHK(func_call) \
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200609 do { \
610 ret = (func_call); \
Gilles Peskine449bd832023-01-11 14:50:10 +0100611 if (ret != 0) \
612 goto cleanup; \
613 } while (0)
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200614
Gilles Peskine449bd832023-01-11 14:50:10 +0100615 MD_CHK(mbedtls_md_setup(&aux, ctx->md_info, 0));
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200616
617 /* After hmac_start() of hmac_reset(), ikey has already been hashed,
618 * so we can start directly with the message */
Gilles Peskine449bd832023-01-11 14:50:10 +0100619 MD_CHK(mbedtls_md_update(ctx, add_data, add_data_len));
620 MD_CHK(mbedtls_md_update(ctx, data, min_data_len));
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200621
Paul Elliott5260ce22022-05-09 18:15:54 +0100622 /* Fill the hash buffer in advance with something that is
623 * not a valid hash (barring an attack on the hash and
624 * deliberately-crafted input), in case the caller doesn't
625 * check the return status properly. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100626 memset(output, '!', hash_size);
Paul Elliott5260ce22022-05-09 18:15:54 +0100627
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200628 /* For each possible length, compute the hash up to that point */
Gilles Peskine449bd832023-01-11 14:50:10 +0100629 for (offset = min_data_len; offset <= max_data_len; offset++) {
630 MD_CHK(mbedtls_md_clone(&aux, ctx));
631 MD_CHK(mbedtls_md_finish(&aux, aux_out));
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200632 /* Keep only the correct inner_hash in the output buffer */
Gilles Peskine449bd832023-01-11 14:50:10 +0100633 mbedtls_ct_memcpy_if_eq(output, aux_out, hash_size,
634 offset, data_len_secret);
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200635
Gilles Peskine449bd832023-01-11 14:50:10 +0100636 if (offset < max_data_len) {
637 MD_CHK(mbedtls_md_update(ctx, data + offset, 1));
638 }
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200639 }
640
641 /* The context needs to finish() before it starts() again */
Gilles Peskine449bd832023-01-11 14:50:10 +0100642 MD_CHK(mbedtls_md_finish(ctx, aux_out));
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200643
644 /* Now compute HASH(okey + inner_hash) */
Gilles Peskine449bd832023-01-11 14:50:10 +0100645 MD_CHK(mbedtls_md_starts(ctx));
646 MD_CHK(mbedtls_md_update(ctx, okey, block_size));
647 MD_CHK(mbedtls_md_update(ctx, output, hash_size));
648 MD_CHK(mbedtls_md_finish(ctx, output));
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200649
650 /* Done, get ready for next time */
Gilles Peskine449bd832023-01-11 14:50:10 +0100651 MD_CHK(mbedtls_md_hmac_reset(ctx));
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200652
653#undef MD_CHK
654
655cleanup:
Gilles Peskine449bd832023-01-11 14:50:10 +0100656 mbedtls_md_free(&aux);
657 return ret;
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200658}
Neil Armstrong2968d302022-02-25 15:09:36 +0100659#endif /* MBEDTLS_USE_PSA_CRYPTO */
gabor-mezei-arm1349ffd2021-09-27 14:28:31 +0200660
Przemek Stekiel89ad6232022-09-27 13:36:12 +0200661#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200662
663#if defined(MBEDTLS_BIGNUM_C)
664
Gilles Peskine449bd832023-01-11 14:50:10 +0100665#define MPI_VALIDATE_RET(cond) \
666 MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA)
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200667
668/*
669 * Conditionally assign X = Y, without leaking information
670 * about whether the assignment was made or not.
671 * (Leaking information about the respective sizes of X and Y is ok however.)
672 */
Tautvydas Žilys40fc7da2022-01-31 13:34:01 -0800673#if defined(_MSC_VER) && defined(_M_ARM64) && (_MSC_FULL_VER < 193131103)
Tautvydas Žilys60165d72022-01-26 15:33:27 -0800674/*
Tautvydas Žilys40fc7da2022-01-31 13:34:01 -0800675 * MSVC miscompiles this function if it's inlined prior to Visual Studio 2022 version 17.1. See:
Tautvydas Žilys60165d72022-01-26 15:33:27 -0800676 * https://developercommunity.visualstudio.com/t/c-compiler-miscompiles-part-of-mbedtls-library-on/1646989
677 */
678__declspec(noinline)
679#endif
Gilles Peskine449bd832023-01-11 14:50:10 +0100680int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X,
681 const mbedtls_mpi *Y,
682 unsigned char assign)
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200683{
684 int ret = 0;
Gilles Peskine449bd832023-01-11 14:50:10 +0100685 MPI_VALIDATE_RET(X != NULL);
686 MPI_VALIDATE_RET(Y != NULL);
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200687
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200688 /* all-bits 1 if assign is 1, all-bits 0 if assign is 0 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100689 mbedtls_mpi_uint limb_mask = mbedtls_ct_mpi_uint_mask(assign);
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200690
Gilles Peskine449bd832023-01-11 14:50:10 +0100691 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200692
Gilles Peskine449bd832023-01-11 14:50:10 +0100693 X->s = mbedtls_ct_cond_select_sign(assign, Y->s, X->s);
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200694
Gilles Peskine449bd832023-01-11 14:50:10 +0100695 mbedtls_mpi_core_cond_assign(X->p, Y->p, Y->n, assign);
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200696
Gilles Peskine449bd832023-01-11 14:50:10 +0100697 for (size_t i = Y->n; i < X->n; i++) {
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200698 X->p[i] &= ~limb_mask;
Gilles Peskine449bd832023-01-11 14:50:10 +0100699 }
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200700
701cleanup:
Gilles Peskine449bd832023-01-11 14:50:10 +0100702 return ret;
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200703}
704
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200705/*
706 * Conditionally swap X and Y, without leaking information
707 * about whether the swap was made or not.
Shaun Case8b0ecbc2021-12-20 21:14:10 -0800708 * Here it is not ok to simply swap the pointers, which would lead to
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200709 * different memory access patterns when X and Y are used afterwards.
710 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100711int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X,
712 mbedtls_mpi *Y,
713 unsigned char swap)
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200714{
Gabor Mezeid7edb1d2022-10-10 14:32:09 +0200715 int ret = 0;
716 int s;
Gilles Peskine449bd832023-01-11 14:50:10 +0100717 MPI_VALIDATE_RET(X != NULL);
718 MPI_VALIDATE_RET(Y != NULL);
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200719
Gilles Peskine449bd832023-01-11 14:50:10 +0100720 if (X == Y) {
721 return 0;
722 }
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200723
Gilles Peskine449bd832023-01-11 14:50:10 +0100724 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
725 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Y, X->n));
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200726
727 s = X->s;
Gilles Peskine449bd832023-01-11 14:50:10 +0100728 X->s = mbedtls_ct_cond_select_sign(swap, Y->s, X->s);
729 Y->s = mbedtls_ct_cond_select_sign(swap, s, Y->s);
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200730
Gilles Peskine449bd832023-01-11 14:50:10 +0100731 mbedtls_mpi_core_cond_swap(X->p, Y->p, X->n, swap);
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200732
733cleanup:
Gilles Peskine449bd832023-01-11 14:50:10 +0100734 return ret;
gabor-mezei-arm5c976212021-09-27 15:37:50 +0200735}
736
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200737/*
Janos Follath23bdeca2022-07-22 18:24:06 +0100738 * Compare unsigned values in constant time
739 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100740unsigned mbedtls_mpi_core_lt_ct(const mbedtls_mpi_uint *A,
741 const mbedtls_mpi_uint *B,
742 size_t limbs)
Janos Follath23bdeca2022-07-22 18:24:06 +0100743{
Janos Follath23bdeca2022-07-22 18:24:06 +0100744 unsigned ret, cond, done;
745
Janos Follath63184682022-08-11 17:42:59 +0100746 /* The value of any of these variables is either 0 or 1 for the rest of
747 * their scope. */
Janos Follath23bdeca2022-07-22 18:24:06 +0100748 ret = cond = done = 0;
749
Gilles Peskine449bd832023-01-11 14:50:10 +0100750 for (size_t i = limbs; i > 0; i--) {
Janos Follath23bdeca2022-07-22 18:24:06 +0100751 /*
Janos Follathb7a88ec2022-08-19 12:24:40 +0100752 * If B[i - 1] < A[i - 1] then A < B is false and the result must
Janos Follath23bdeca2022-07-22 18:24:06 +0100753 * remain 0.
754 *
755 * Again even if we can make a decision, we just mark the result and
756 * the fact that we are done and continue looping.
757 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100758 cond = mbedtls_ct_mpi_uint_lt(B[i - 1], A[i - 1]);
Janos Follath23bdeca2022-07-22 18:24:06 +0100759 done |= cond;
760
761 /*
Janos Follathb7a88ec2022-08-19 12:24:40 +0100762 * If A[i - 1] < B[i - 1] then A < B is true.
Janos Follath23bdeca2022-07-22 18:24:06 +0100763 *
764 * Again even if we can make a decision, we just mark the result and
765 * the fact that we are done and continue looping.
766 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100767 cond = mbedtls_ct_mpi_uint_lt(A[i - 1], B[i - 1]);
768 ret |= cond & (1 - done);
Janos Follath23bdeca2022-07-22 18:24:06 +0100769 done |= cond;
770 }
771
772 /*
Janos Follathb7a88ec2022-08-19 12:24:40 +0100773 * If all the limbs were equal, then the numbers are equal, A < B is false
Janos Follath23bdeca2022-07-22 18:24:06 +0100774 * and leaving the result 0 is correct.
775 */
776
Gilles Peskine449bd832023-01-11 14:50:10 +0100777 return ret;
Janos Follath23bdeca2022-07-22 18:24:06 +0100778}
779
780/*
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200781 * Compare signed values in constant time
782 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100783int mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi *X,
784 const mbedtls_mpi *Y,
785 unsigned *ret)
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200786{
787 size_t i;
788 /* The value of any of these variables is either 0 or 1 at all times. */
789 unsigned cond, done, X_is_negative, Y_is_negative;
790
Gilles Peskine449bd832023-01-11 14:50:10 +0100791 MPI_VALIDATE_RET(X != NULL);
792 MPI_VALIDATE_RET(Y != NULL);
793 MPI_VALIDATE_RET(ret != NULL);
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200794
Gilles Peskine449bd832023-01-11 14:50:10 +0100795 if (X->n != Y->n) {
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200796 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
Gilles Peskine449bd832023-01-11 14:50:10 +0100797 }
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200798
799 /*
800 * Set sign_N to 1 if N >= 0, 0 if N < 0.
801 * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
802 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100803 X_is_negative = (X->s & 2) >> 1;
804 Y_is_negative = (Y->s & 2) >> 1;
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200805
806 /*
807 * If the signs are different, then the positive operand is the bigger.
808 * That is if X is negative (X_is_negative == 1), then X < Y is true and it
809 * is false if X is positive (X_is_negative == 0).
810 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100811 cond = (X_is_negative ^ Y_is_negative);
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200812 *ret = cond & X_is_negative;
813
814 /*
815 * This is a constant-time function. We might have the result, but we still
816 * need to go through the loop. Record if we have the result already.
817 */
818 done = cond;
819
Gilles Peskine449bd832023-01-11 14:50:10 +0100820 for (i = X->n; i > 0; i--) {
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200821 /*
822 * If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
823 * X and Y are negative.
824 *
825 * Again even if we can make a decision, we just mark the result and
826 * the fact that we are done and continue looping.
827 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100828 cond = mbedtls_ct_mpi_uint_lt(Y->p[i - 1], X->p[i - 1]);
829 *ret |= cond & (1 - done) & X_is_negative;
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200830 done |= cond;
831
832 /*
833 * If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
834 * X and Y are positive.
835 *
836 * Again even if we can make a decision, we just mark the result and
837 * the fact that we are done and continue looping.
838 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100839 cond = mbedtls_ct_mpi_uint_lt(X->p[i - 1], Y->p[i - 1]);
840 *ret |= cond & (1 - done) & (1 - X_is_negative);
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200841 done |= cond;
842 }
843
Gilles Peskine449bd832023-01-11 14:50:10 +0100844 return 0;
gabor-mezei-armc29a3da2021-09-27 15:41:30 +0200845}
846
gabor-mezei-arm40a49252021-09-27 15:33:35 +0200847#endif /* MBEDTLS_BIGNUM_C */
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200848
849#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
850
Gilles Peskine449bd832023-01-11 14:50:10 +0100851int mbedtls_ct_rsaes_pkcs1_v15_unpadding(unsigned char *input,
852 size_t ilen,
853 unsigned char *output,
854 size_t output_max_len,
855 size_t *olen)
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200856{
857 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
858 size_t i, plaintext_max_size;
859
860 /* The following variables take sensitive values: their value must
861 * not leak into the observable behavior of the function other than
862 * the designated outputs (output, olen, return value). Otherwise
863 * this would open the execution of the function to
864 * side-channel-based variants of the Bleichenbacher padding oracle
865 * attack. Potential side channels include overall timing, memory
866 * access patterns (especially visible to an adversary who has access
867 * to a shared memory cache), and branches (especially visible to
868 * an adversary who has access to a shared code cache or to a shared
869 * branch predictor). */
870 size_t pad_count = 0;
871 unsigned bad = 0;
872 unsigned char pad_done = 0;
873 size_t plaintext_size = 0;
874 unsigned output_too_large;
875
Gilles Peskine449bd832023-01-11 14:50:10 +0100876 plaintext_max_size = (output_max_len > ilen - 11) ? ilen - 11
Gabor Mezei7013f622021-10-18 16:12:45 +0200877 : output_max_len;
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200878
879 /* Check and get padding length in constant time and constant
880 * memory trace. The first byte must be 0. */
Gabor Mezei63bbba52021-10-18 16:17:57 +0200881 bad |= input[0];
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200882
883
884 /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
Gabor Mezei63bbba52021-10-18 16:17:57 +0200885 * where PS must be at least 8 nonzero bytes. */
886 bad |= input[1] ^ MBEDTLS_RSA_CRYPT;
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200887
888 /* Read the whole buffer. Set pad_done to nonzero if we find
Gabor Mezei63bbba52021-10-18 16:17:57 +0200889 * the 0x00 byte and remember the padding length in pad_count. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100890 for (i = 2; i < ilen; i++) {
891 pad_done |= ((input[i] | (unsigned char) -input[i]) >> 7) ^ 1;
892 pad_count += ((pad_done | (unsigned char) -pad_done) >> 7) ^ 1;
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200893 }
894
895
896 /* If pad_done is still zero, there's no data, only unfinished padding. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100897 bad |= mbedtls_ct_uint_if(pad_done, 0, 1);
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200898
899 /* There must be at least 8 bytes of padding. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100900 bad |= mbedtls_ct_size_gt(8, pad_count);
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200901
902 /* If the padding is valid, set plaintext_size to the number of
903 * remaining bytes after stripping the padding. If the padding
904 * is invalid, avoid leaking this fact through the size of the
905 * output: use the maximum message size that fits in the output
906 * buffer. Do it without branches to avoid leaking the padding
907 * validity through timing. RSA keys are small enough that all the
908 * size_t values involved fit in unsigned int. */
Gabor Mezei90437e32021-10-20 11:59:27 +0200909 plaintext_size = mbedtls_ct_uint_if(
Gilles Peskine449bd832023-01-11 14:50:10 +0100910 bad, (unsigned) plaintext_max_size,
911 (unsigned) (ilen - pad_count - 3));
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200912
913 /* Set output_too_large to 0 if the plaintext fits in the output
914 * buffer and to 1 otherwise. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100915 output_too_large = mbedtls_ct_size_gt(plaintext_size,
916 plaintext_max_size);
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200917
918 /* Set ret without branches to avoid timing attacks. Return:
919 * - INVALID_PADDING if the padding is bad (bad != 0).
920 * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
921 * plaintext does not fit in the output buffer.
922 * - 0 if the padding is correct. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100923 ret = -(int) mbedtls_ct_uint_if(
924 bad, -MBEDTLS_ERR_RSA_INVALID_PADDING,
925 mbedtls_ct_uint_if(output_too_large,
926 -MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
927 0));
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200928
929 /* If the padding is bad or the plaintext is too large, zero the
930 * data that we're about to copy to the output buffer.
931 * We need to copy the same amount of data
932 * from the same buffer whether the padding is good or not to
933 * avoid leaking the padding validity through overall timing or
934 * through memory or cache access patterns. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100935 bad = mbedtls_ct_uint_mask(bad | output_too_large);
936 for (i = 11; i < ilen; i++) {
Gabor Mezei63bbba52021-10-18 16:17:57 +0200937 input[i] &= ~bad;
Gilles Peskine449bd832023-01-11 14:50:10 +0100938 }
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200939
940 /* If the plaintext is too large, truncate it to the buffer size.
941 * Copy anyway to avoid revealing the length through timing, because
942 * revealing the length is as bad as revealing the padding validity
943 * for a Bleichenbacher attack. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100944 plaintext_size = mbedtls_ct_uint_if(output_too_large,
945 (unsigned) plaintext_max_size,
946 (unsigned) plaintext_size);
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200947
948 /* Move the plaintext to the leftmost position where it can start in
949 * the working buffer, i.e. make it start plaintext_max_size from
950 * the end of the buffer. Do this with a memory access trace that
951 * does not depend on the plaintext size. After this move, the
952 * starting location of the plaintext is no longer sensitive
953 * information. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100954 mbedtls_ct_mem_move_to_left(input + ilen - plaintext_max_size,
955 plaintext_max_size,
956 plaintext_max_size - plaintext_size);
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200957
958 /* Finally copy the decrypted plaintext plus trailing zeros into the output
959 * buffer. If output_max_len is 0, then output may be an invalid pointer
960 * and the result of memcpy() would be undefined; prevent undefined
961 * behavior making sure to depend only on output_max_len (the size of the
962 * user-provided output buffer), which is independent from plaintext
963 * length, validity of padding, success of the decryption, and other
964 * secrets. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100965 if (output_max_len != 0) {
966 memcpy(output, input + ilen - plaintext_max_size, plaintext_max_size);
967 }
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200968
969 /* Report the amount of data we copied to the output buffer. In case
970 * of errors (bad padding or output too large), the value of *olen
971 * when this function returns is not specified. Making it equivalent
972 * to the good case limits the risks of leaking the padding validity. */
973 *olen = plaintext_size;
974
Gilles Peskine449bd832023-01-11 14:50:10 +0100975 return ret;
gabor-mezei-armfdb71182021-09-27 16:11:12 +0200976}
977
978#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */