Make the RSA ASYM_CIPHER implementation available inside the FIPS module
[openssl.git] / crypto / rsa / rsa_oaep.c
1 /*
2  * Copyright 1999-2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* EME-OAEP as defined in RFC 2437 (PKCS #1 v2.0) */
11
12 /*
13  * See Victor Shoup, "OAEP reconsidered," Nov. 2000, <URL:
14  * http://www.shoup.net/papers/oaep.ps.Z> for problems with the security
15  * proof for the original OAEP scheme, which EME-OAEP is based on. A new
16  * proof can be found in E. Fujisaki, T. Okamoto, D. Pointcheval, J. Stern,
17  * "RSA-OEAP is Still Alive!", Dec. 2000, <URL:
18  * http://eprint.iacr.org/2000/061/>. The new proof has stronger requirements
19  * for the underlying permutation: "partial-one-wayness" instead of
20  * one-wayness.  For the RSA function, this is an equivalent notion.
21  */
22
23 #include "internal/constant_time.h"
24
25 #include <stdio.h>
26 #include "internal/cryptlib.h"
27 #include <openssl/bn.h>
28 #include <openssl/evp.h>
29 #include <openssl/rand.h>
30 #include <openssl/sha.h>
31 #include "rsa_local.h"
32
33 int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen,
34                                const unsigned char *from, int flen,
35                                const unsigned char *param, int plen)
36 {
37     return RSA_padding_add_PKCS1_OAEP_mgf1(to, tlen, from, flen,
38                                            param, plen, NULL, NULL);
39 }
40
41 /*
42  * Perform ihe padding as per NIST 800-56B 7.2.2.3
43  *      from (K) is the key material.
44  *      param (A) is the additional input.
45  * Step numbers are included here but not in the constant time inverse below
46  * to avoid complicating an already difficult enough function.
47  */
48 int RSA_padding_add_PKCS1_OAEP_mgf1(unsigned char *to, int tlen,
49                                     const unsigned char *from, int flen,
50                                     const unsigned char *param, int plen,
51                                     const EVP_MD *md, const EVP_MD *mgf1md)
52 {
53     int rv = 0;
54     int i, emlen = tlen - 1;
55     unsigned char *db, *seed;
56     unsigned char *dbmask = NULL;
57     unsigned char seedmask[EVP_MAX_MD_SIZE];
58     int mdlen, dbmask_len = 0;
59
60 #ifndef FIPS_MODE
61     if (md == NULL)
62         md = EVP_sha1();
63 #else
64         RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1,
65                ERR_R_PASSED_NULL_PARAMETER);
66         return 0;
67 #endif
68     if (mgf1md == NULL)
69         mgf1md = md;
70
71     mdlen = EVP_MD_size(md);
72
73     /* step 2b: check KLen > nLen - 2 HLen - 2 */
74     if (flen > emlen - 2 * mdlen - 1) {
75         RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1,
76                RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
77         return 0;
78     }
79
80     if (emlen < 2 * mdlen + 1) {
81         RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1,
82                RSA_R_KEY_SIZE_TOO_SMALL);
83         return 0;
84     }
85
86     /* step 3i: EM = 00000000 || maskedMGF || maskedDB */
87     to[0] = 0;
88     seed = to + 1;
89     db = to + mdlen + 1;
90
91     /* step 3a: hash the additional input */
92     if (!EVP_Digest((void *)param, plen, db, NULL, md, NULL))
93         goto err;
94     /* step 3b: zero bytes array of length nLen - KLen - 2 HLen -2 */
95     memset(db + mdlen, 0, emlen - flen - 2 * mdlen - 1);
96     /* step 3c: DB = HA || PS || 00000001 || K */
97     db[emlen - flen - mdlen - 1] = 0x01;
98     memcpy(db + emlen - flen - mdlen, from, (unsigned int)flen);
99     /* step 3d: generate random byte string */
100     if (RAND_bytes(seed, mdlen) <= 0)
101         goto err;
102
103     dbmask_len = emlen - mdlen;
104     dbmask = OPENSSL_malloc(dbmask_len);
105     if (dbmask == NULL) {
106         RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1, ERR_R_MALLOC_FAILURE);
107         goto err;
108     }
109
110     /* step 3e: dbMask = MGF(mgfSeed, nLen - HLen - 1) */
111     if (PKCS1_MGF1(dbmask, dbmask_len, seed, mdlen, mgf1md) < 0)
112         goto err;
113     /* step 3f: maskedDB = DB XOR dbMask */
114     for (i = 0; i < dbmask_len; i++)
115         db[i] ^= dbmask[i];
116
117     /* step 3g: mgfSeed = MGF(maskedDB, HLen) */
118     if (PKCS1_MGF1(seedmask, mdlen, db, dbmask_len, mgf1md) < 0)
119         goto err;
120     /* stepo 3h: maskedMGFSeed = mgfSeed XOR mgfSeedMask */
121     for (i = 0; i < mdlen; i++)
122         seed[i] ^= seedmask[i];
123     rv = 1;
124
125  err:
126     OPENSSL_cleanse(seedmask, sizeof(seedmask));
127     OPENSSL_clear_free(dbmask, dbmask_len);
128     return rv;
129 }
130
131 int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen,
132                                  const unsigned char *from, int flen, int num,
133                                  const unsigned char *param, int plen)
134 {
135     return RSA_padding_check_PKCS1_OAEP_mgf1(to, tlen, from, flen, num,
136                                              param, plen, NULL, NULL);
137 }
138
139 int RSA_padding_check_PKCS1_OAEP_mgf1(unsigned char *to, int tlen,
140                                       const unsigned char *from, int flen,
141                                       int num, const unsigned char *param,
142                                       int plen, const EVP_MD *md,
143                                       const EVP_MD *mgf1md)
144 {
145     int i, dblen = 0, mlen = -1, one_index = 0, msg_index;
146     unsigned int good = 0, found_one_byte, mask;
147     const unsigned char *maskedseed, *maskeddb;
148     /*
149      * |em| is the encoded message, zero-padded to exactly |num| bytes: em =
150      * Y || maskedSeed || maskedDB
151      */
152     unsigned char *db = NULL, *em = NULL, seed[EVP_MAX_MD_SIZE],
153         phash[EVP_MAX_MD_SIZE];
154     int mdlen;
155
156     if (md == NULL) {
157 #ifndef FIPS_MODE
158         md = EVP_sha1();
159 #else
160         RSAerr(0, ERR_R_PASSED_NULL_PARAMETER);
161         return -1;
162 #endif
163     }
164
165     if (mgf1md == NULL)
166         mgf1md = md;
167
168     mdlen = EVP_MD_size(md);
169
170     if (tlen <= 0 || flen <= 0)
171         return -1;
172     /*
173      * |num| is the length of the modulus; |flen| is the length of the
174      * encoded message. Therefore, for any |from| that was obtained by
175      * decrypting a ciphertext, we must have |flen| <= |num|. Similarly,
176      * |num| >= 2 * |mdlen| + 2 must hold for the modulus irrespective of
177      * the ciphertext, see PKCS #1 v2.2, section 7.1.2.
178      * This does not leak any side-channel information.
179      */
180     if (num < flen || num < 2 * mdlen + 2) {
181         RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1,
182                RSA_R_OAEP_DECODING_ERROR);
183         return -1;
184     }
185
186     dblen = num - mdlen - 1;
187     db = OPENSSL_malloc(dblen);
188     if (db == NULL) {
189         RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1, ERR_R_MALLOC_FAILURE);
190         goto cleanup;
191     }
192
193     em = OPENSSL_malloc(num);
194     if (em == NULL) {
195         RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1,
196                ERR_R_MALLOC_FAILURE);
197         goto cleanup;
198     }
199
200     /*
201      * Caller is encouraged to pass zero-padded message created with
202      * BN_bn2binpad. Trouble is that since we can't read out of |from|'s
203      * bounds, it's impossible to have an invariant memory access pattern
204      * in case |from| was not zero-padded in advance.
205      */
206     for (from += flen, em += num, i = 0; i < num; i++) {
207         mask = ~constant_time_is_zero(flen);
208         flen -= 1 & mask;
209         from -= 1 & mask;
210         *--em = *from & mask;
211     }
212
213     /*
214      * The first byte must be zero, however we must not leak if this is
215      * true. See James H. Manger, "A Chosen Ciphertext  Attack on RSA
216      * Optimal Asymmetric Encryption Padding (OAEP) [...]", CRYPTO 2001).
217      */
218     good = constant_time_is_zero(em[0]);
219
220     maskedseed = em + 1;
221     maskeddb = em + 1 + mdlen;
222
223     if (PKCS1_MGF1(seed, mdlen, maskeddb, dblen, mgf1md))
224         goto cleanup;
225     for (i = 0; i < mdlen; i++)
226         seed[i] ^= maskedseed[i];
227
228     if (PKCS1_MGF1(db, dblen, seed, mdlen, mgf1md))
229         goto cleanup;
230     for (i = 0; i < dblen; i++)
231         db[i] ^= maskeddb[i];
232
233     if (!EVP_Digest((void *)param, plen, phash, NULL, md, NULL))
234         goto cleanup;
235
236     good &= constant_time_is_zero(CRYPTO_memcmp(db, phash, mdlen));
237
238     found_one_byte = 0;
239     for (i = mdlen; i < dblen; i++) {
240         /*
241          * Padding consists of a number of 0-bytes, followed by a 1.
242          */
243         unsigned int equals1 = constant_time_eq(db[i], 1);
244         unsigned int equals0 = constant_time_is_zero(db[i]);
245         one_index = constant_time_select_int(~found_one_byte & equals1,
246                                              i, one_index);
247         found_one_byte |= equals1;
248         good &= (found_one_byte | equals0);
249     }
250
251     good &= found_one_byte;
252
253     /*
254      * At this point |good| is zero unless the plaintext was valid,
255      * so plaintext-awareness ensures timing side-channels are no longer a
256      * concern.
257      */
258     msg_index = one_index + 1;
259     mlen = dblen - msg_index;
260
261     /*
262      * For good measure, do this check in constant time as well.
263      */
264     good &= constant_time_ge(tlen, mlen);
265
266     /*
267      * Move the result in-place by |dblen|-|mdlen|-1-|mlen| bytes to the left.
268      * Then if |good| move |mlen| bytes from |db|+|mdlen|+1 to |to|.
269      * Otherwise leave |to| unchanged.
270      * Copy the memory back in a way that does not reveal the size of
271      * the data being copied via a timing side channel. This requires copying
272      * parts of the buffer multiple times based on the bits set in the real
273      * length. Clear bits do a non-copy with identical access pattern.
274      * The loop below has overall complexity of O(N*log(N)).
275      */
276     tlen = constant_time_select_int(constant_time_lt(dblen - mdlen - 1, tlen),
277                                     dblen - mdlen - 1, tlen);
278     for (msg_index = 1; msg_index < dblen - mdlen - 1; msg_index <<= 1) {
279         mask = ~constant_time_eq(msg_index & (dblen - mdlen - 1 - mlen), 0);
280         for (i = mdlen + 1; i < dblen - msg_index; i++)
281             db[i] = constant_time_select_8(mask, db[i + msg_index], db[i]);
282     }
283     for (i = 0; i < tlen; i++) {
284         mask = good & constant_time_lt(i, mlen);
285         to[i] = constant_time_select_8(mask, db[i + mdlen + 1], to[i]);
286     }
287
288 #ifndef FIPS_MODE
289     /*
290      * To avoid chosen ciphertext attacks, the error message should not
291      * reveal which kind of decoding error happened.
292      *
293      * This trick doesn't work in the FIPS provider because libcrypto manages
294      * the error stack. Instead we opt not to put an error on the stack at all
295      * in case of padding failure in the FIPS provider.
296      */
297     RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1,
298            RSA_R_OAEP_DECODING_ERROR);
299     err_clear_last_constant_time(1 & good);
300 #endif
301  cleanup:
302     OPENSSL_cleanse(seed, sizeof(seed));
303     OPENSSL_clear_free(db, dblen);
304     OPENSSL_clear_free(em, num);
305
306     return constant_time_select_int(good, mlen, -1);
307 }
308
309 /*
310  * Mask Generation Function corresponding to section 7.2.2.2 of NIST SP 800-56B.
311  * The variables are named differently to NIST:
312  *      mask (T) and len (maskLen)are the returned mask.
313  *      seed (mgfSeed).
314  * The range checking steps inm the process are performed outside.
315  */
316 int PKCS1_MGF1(unsigned char *mask, long len,
317                const unsigned char *seed, long seedlen, const EVP_MD *dgst)
318 {
319     long i, outlen = 0;
320     unsigned char cnt[4];
321     EVP_MD_CTX *c = EVP_MD_CTX_new();
322     unsigned char md[EVP_MAX_MD_SIZE];
323     int mdlen;
324     int rv = -1;
325
326     if (c == NULL)
327         goto err;
328     mdlen = EVP_MD_size(dgst);
329     if (mdlen < 0)
330         goto err;
331     /* step 4 */
332     for (i = 0; outlen < len; i++) {
333         /* step 4a: D = I2BS(counter, 4) */
334         cnt[0] = (unsigned char)((i >> 24) & 255);
335         cnt[1] = (unsigned char)((i >> 16) & 255);
336         cnt[2] = (unsigned char)((i >> 8)) & 255;
337         cnt[3] = (unsigned char)(i & 255);
338         /* step 4b: T =T || hash(mgfSeed || D) */
339         if (!EVP_DigestInit_ex(c, dgst, NULL)
340             || !EVP_DigestUpdate(c, seed, seedlen)
341             || !EVP_DigestUpdate(c, cnt, 4))
342             goto err;
343         if (outlen + mdlen <= len) {
344             if (!EVP_DigestFinal_ex(c, mask + outlen, NULL))
345                 goto err;
346             outlen += mdlen;
347         } else {
348             if (!EVP_DigestFinal_ex(c, md, NULL))
349                 goto err;
350             memcpy(mask + outlen, md, len - outlen);
351             outlen = len;
352         }
353     }
354     rv = 0;
355  err:
356     OPENSSL_cleanse(md, sizeof(md));
357     EVP_MD_CTX_free(c);
358     return rv;
359 }