Tor 0.4.9.2-alpha-dev
All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
crypto_rsa_openssl.c
1/* Copyright (c) 2001, Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7/**
8 * \file crypto_rsa.c
9 * \brief OpenSSL implementations of our RSA code.
10 **/
11
12#include "lib/crypt_ops/compat_openssl.h"
15#include "lib/ctime/di_ops.h"
16#include "lib/log/util_bug.h"
17#include "lib/fs/files.h"
18
19DISABLE_GCC_WARNING("-Wredundant-decls")
20
21#include <openssl/err.h>
22#include <openssl/rsa.h>
23#include <openssl/pem.h>
24#include <openssl/evp.h>
25#include <openssl/engine.h>
26#include <openssl/rand.h>
27#include <openssl/bn.h>
28#include <openssl/conf.h>
29
30ENABLE_GCC_WARNING("-Wredundant-decls")
31
32#include "lib/log/log.h"
34
35#include <string.h>
36#include <stdbool.h>
37
38/** Declaration for crypto_pk_t structure. */
39struct crypto_pk_t
40{
41 int refs; /**< reference count, so we don't have to copy keys */
42 RSA *key; /**< The key itself */
43};
44
45/** Return true iff <b>key</b> contains the private-key portion of the RSA
46 * key. */
47int
49{
50 if (!k || !k->key)
51 return 0;
52
53 const BIGNUM *p, *q;
54 RSA_get0_factors(k->key, &p, &q);
55 return p != NULL; /* XXX/yawning: Should we check q? */
56}
57
58/** used by tortls.c: wrap an RSA* in a crypto_pk_t. Takes ownership of
59 * its argument. */
61crypto_new_pk_from_openssl_rsa_(RSA *rsa)
62{
63 crypto_pk_t *env;
64 tor_assert(rsa);
65 env = tor_malloc(sizeof(crypto_pk_t));
66 env->refs = 1;
67 env->key = rsa;
68 return env;
69}
70
71/** Helper, used by tor-gencert.c. Return a copy of the private RSA from a
72 * crypto_pk_t. */
73RSA *
74crypto_pk_get_openssl_rsa_(crypto_pk_t *env)
75{
76 return RSAPrivateKey_dup(env->key);
77}
78
79/** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
80 * private is set, include the private-key portion of the key. Return a valid
81 * pointer on success, and NULL on failure. */
82MOCK_IMPL(EVP_PKEY *,
83crypto_pk_get_openssl_evp_pkey_,(crypto_pk_t *env, int private))
84{
85 RSA *key = NULL;
86 EVP_PKEY *pkey = NULL;
87 tor_assert(env->key);
88 if (private) {
89 if (!(key = RSAPrivateKey_dup(env->key)))
90 goto error;
91 } else {
92 if (!(key = RSAPublicKey_dup(env->key)))
93 goto error;
94 }
95 if (!(pkey = EVP_PKEY_new()))
96 goto error;
97 if (!(EVP_PKEY_assign_RSA(pkey, key)))
98 goto error;
99 return pkey;
100 error:
101 if (pkey)
102 EVP_PKEY_free(pkey);
103 if (key)
104 RSA_free(key);
105 return NULL;
106}
107
108/** Allocate and return storage for a public key. The key itself will not yet
109 * be set.
110 */
112crypto_pk_new,(void))
113{
114 RSA *rsa;
115
116 rsa = RSA_new();
117 tor_assert(rsa);
118 return crypto_new_pk_from_openssl_rsa_(rsa);
119}
120
121/** Release a reference to an asymmetric key; when all the references
122 * are released, free the key.
123 */
124void
126{
127 if (!env)
128 return;
129
130 if (--env->refs > 0)
131 return;
132 tor_assert(env->refs == 0);
133
134 if (env->key)
135 RSA_free(env->key);
136
137 tor_free(env);
138}
139
140/** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
141 * Return 0 on success, -1 on failure.
142 */
143MOCK_IMPL(int,
145{
146 tor_assert(env);
147
148 if (env->key) {
149 RSA_free(env->key);
150 env->key = NULL;
151 }
152
153 {
154 BIGNUM *e = BN_new();
155 RSA *r = NULL;
156 if (!e)
157 goto done;
158 if (! BN_set_word(e, TOR_RSA_EXPONENT))
159 goto done;
160 r = RSA_new();
161 if (!r)
162 goto done;
163 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
164 goto done;
165
166 env->key = r;
167 r = NULL;
168 done:
169 if (e)
170 BN_clear_free(e);
171 if (r)
172 RSA_free(r);
173 }
174
175 if (!env->key) {
176 crypto_openssl_log_errors(LOG_WARN, "generating RSA key");
177 return -1;
178 }
179
180 return 0;
181}
182
183/** Return true if <b>env</b> has a valid key; false otherwise.
184 */
185int
187{
188 int r;
189 tor_assert(env);
190
191 r = RSA_check_key(env->key);
192 if (r <= 0) {
193 crypto_openssl_log_errors(LOG_WARN,"checking RSA key");
194 return 0;
195 } else {
196 return 1;
197 }
198}
199
200/** Return true iff <b>env</b> contains a public key whose public exponent
201 * equals TOR_RSA_EXPONENT.
202 */
203int
205{
206 tor_assert(env);
207 tor_assert(env->key);
208
209 const BIGNUM *e;
210
211 const BIGNUM *n, *d;
212 RSA_get0_key(env->key, &n, &e, &d);
213 return BN_is_word(e, TOR_RSA_EXPONENT);
214}
215
216/** Compare the public-key components of a and b. Return less than 0
217 * if a<b, 0 if a==b, and greater than 0 if a>b. A NULL key is
218 * considered to be less than all non-NULL keys, and equal to itself.
219 *
220 * Note that this may leak information about the keys through timing.
221 */
222int
224{
225 int result;
226 char a_is_non_null = (a != NULL) && (a->key != NULL);
227 char b_is_non_null = (b != NULL) && (b->key != NULL);
228 char an_argument_is_null = !a_is_non_null | !b_is_non_null;
229
230 result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
231 if (an_argument_is_null)
232 return result;
233
234 const BIGNUM *a_n, *a_e;
235 const BIGNUM *b_n, *b_e;
236
237 const BIGNUM *a_d, *b_d;
238 RSA_get0_key(a->key, &a_n, &a_e, &a_d);
239 RSA_get0_key(b->key, &b_n, &b_e, &b_d);
240
241 tor_assert(a_n != NULL && a_e != NULL);
242 tor_assert(b_n != NULL && b_e != NULL);
243
244 result = BN_cmp(a_n, b_n);
245 if (result)
246 return result;
247 return BN_cmp(a_e, b_e);
248}
249
250/** Return the size of the public key modulus in <b>env</b>, in bytes. */
251size_t
253{
254 tor_assert(env);
255 tor_assert(env->key);
256
257 return (size_t) RSA_size((RSA*)env->key);
258}
259
260/** Return the size of the public key modulus of <b>env</b>, in bits. */
261int
263{
264 tor_assert(env);
265 tor_assert(env->key);
266
267 /* It's so stupid that there's no other way to check that n is valid
268 * before calling RSA_bits().
269 */
270 const BIGNUM *n, *e, *d;
271 RSA_get0_key(env->key, &n, &e, &d);
272 tor_assert(n != NULL);
273
274 return RSA_bits(env->key);
275}
276
277/** Increase the reference count of <b>env</b>, and return it.
278 */
281{
282 tor_assert(env);
283 tor_assert(env->key);
284
285 env->refs++;
286 return env;
287}
288
289/** Replace dest with src (private key only). (Dest must have a refcount
290 * of 1)
291 */
292void
294{
295 tor_assert(dest);
296 tor_assert(dest->refs == 1);
297 tor_assert(src);
298 RSA_free(dest->key);
299 dest->key = RSAPrivateKey_dup(src->key);
300}
301
302/** Replace dest with src (public key only). (Dest must have a refcount
303 * of 1)
304 */
305void
307{
308 tor_assert(dest);
309 tor_assert(dest->refs == 1);
310 tor_assert(src);
311 RSA_free(dest->key);
312 dest->key = RSAPublicKey_dup(src->key);
313}
314
315/** Make a real honest-to-goodness copy of <b>env</b>, and return it.
316 * Returns NULL on failure. */
319{
320 RSA *new_key;
321 int privatekey = 0;
322 tor_assert(env);
323 tor_assert(env->key);
324
325 if (crypto_pk_key_is_private(env)) {
326 new_key = RSAPrivateKey_dup(env->key);
327 privatekey = 1;
328 } else {
329 new_key = RSAPublicKey_dup(env->key);
330 }
331 if (!new_key) {
332 /* LCOV_EXCL_START
333 *
334 * We can't cause RSA*Key_dup() to fail, so we can't really test this.
335 */
336 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
337 privatekey?"private":"public");
339 privatekey ? "Duplicating a private key" :
340 "Duplicating a public key");
342 return NULL;
343 /* LCOV_EXCL_STOP */
344 }
345
346 return crypto_new_pk_from_openssl_rsa_(new_key);
347}
348
349/** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
350 * in <b>env</b>, using the padding method <b>padding</b>. On success,
351 * write the result to <b>to</b>, and return the number of bytes
352 * written. On failure, return -1.
353 *
354 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
355 * at least the length of the modulus of <b>env</b>.
356 */
357int
358crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
359 const char *from, size_t fromlen, int padding)
360{
361 int r;
362 tor_assert(env);
363 tor_assert(from);
364 tor_assert(to);
365 tor_assert(fromlen<INT_MAX);
366 tor_assert(tolen >= crypto_pk_keysize(env));
367
368 r = RSA_public_encrypt((int)fromlen,
369 (unsigned char*)from, (unsigned char*)to,
370 env->key, crypto_get_rsa_padding(padding));
371 if (r<0) {
372 crypto_openssl_log_errors(LOG_WARN, "performing RSA encryption");
373 return -1;
374 }
375 return r;
376}
377
378/** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
379 * in <b>env</b>, using the padding method <b>padding</b>. On success,
380 * write the result to <b>to</b>, and return the number of bytes
381 * written. On failure, return -1.
382 *
383 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
384 * at least the length of the modulus of <b>env</b>.
385 */
386int
388 size_t tolen,
389 const char *from, size_t fromlen,
390 int padding, int warnOnFailure)
391{
392 int r;
393 tor_assert(env);
394 tor_assert(from);
395 tor_assert(to);
396 tor_assert(env->key);
397 tor_assert(fromlen<INT_MAX);
398 tor_assert(tolen >= crypto_pk_keysize(env));
399 if (!crypto_pk_key_is_private(env))
400 /* Not a private key */
401 return -1;
402
403 r = RSA_private_decrypt((int)fromlen,
404 (unsigned char*)from, (unsigned char*)to,
405 env->key, crypto_get_rsa_padding(padding));
406
407 if (r<0) {
409 "performing RSA decryption");
410 return -1;
411 }
412 return r;
413}
414
415/** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
416 * public key in <b>env</b>, using PKCS1 padding. On success, write the
417 * signed data to <b>to</b>, and return the number of bytes written.
418 * On failure, return -1.
419 *
420 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
421 * at least the length of the modulus of <b>env</b>.
422 */
423MOCK_IMPL(int,
424crypto_pk_public_checksig,(const crypto_pk_t *env, char *to,
425 size_t tolen,
426 const char *from, size_t fromlen))
427{
428 int r;
429 tor_assert(env);
430 tor_assert(from);
431 tor_assert(to);
432 tor_assert(fromlen < INT_MAX);
433 tor_assert(tolen >= crypto_pk_keysize(env));
434 r = RSA_public_decrypt((int)fromlen,
435 (unsigned char*)from, (unsigned char*)to,
436 env->key, RSA_PKCS1_PADDING);
437
438 if (r<0) {
439 crypto_openssl_log_errors(LOG_INFO, "checking RSA signature");
440 return -1;
441 }
442 return r;
443}
444
445/** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
446 * <b>env</b>, using PKCS1 padding. On success, write the signature to
447 * <b>to</b>, and return the number of bytes written. On failure, return
448 * -1.
449 *
450 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
451 * at least the length of the modulus of <b>env</b>.
452 */
453int
454crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
455 const char *from, size_t fromlen)
456{
457 int r;
458 tor_assert(env);
459 tor_assert(from);
460 tor_assert(to);
461 tor_assert(fromlen < INT_MAX);
462 tor_assert(tolen >= crypto_pk_keysize(env));
463 if (!crypto_pk_key_is_private(env))
464 /* Not a private key */
465 return -1;
466
467 r = RSA_private_encrypt((int)fromlen,
468 (unsigned char*)from, (unsigned char*)to,
469 (RSA*)env->key, RSA_PKCS1_PADDING);
470 if (r<0) {
471 crypto_openssl_log_errors(LOG_WARN, "generating RSA signature");
472 return -1;
473 }
474 return r;
475}
476
477/** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
478 * Return -1 on error, or the number of characters used on success.
479 */
480int
481crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
482{
483 int len;
484 unsigned char *buf = NULL;
485
486 len = i2d_RSAPublicKey(pk->key, &buf);
487 if (len < 0 || buf == NULL)
488 return -1;
489
490 if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
491 OPENSSL_free(buf);
492 return -1;
493 }
494 /* We don't encode directly into 'dest', because that would be illegal
495 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
496 */
497 memcpy(dest,buf,len);
498 OPENSSL_free(buf);
499 return len;
500}
501
502/** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
503 * success and NULL on failure.
504 */
506crypto_pk_asn1_decode(const char *str, size_t len)
507{
508 RSA *rsa;
509 unsigned char *buf;
510 const unsigned char *cp;
511 cp = buf = tor_malloc(len);
512 memcpy(buf,str,len);
513 rsa = d2i_RSAPublicKey(NULL, &cp, len);
514 tor_free(buf);
515 if (!rsa) {
516 crypto_openssl_log_errors(LOG_WARN,"decoding public key");
517 return NULL;
518 }
519 return crypto_new_pk_from_openssl_rsa_(rsa);
520}
521
522/** ASN.1-encode the private portion of <b>pk</b> into <b>dest</b>.
523 * Return -1 on error, or the number of characters used on success.
524 */
525int
526crypto_pk_asn1_encode_private(const crypto_pk_t *pk, char *dest,
527 size_t dest_len)
528{
529 int len;
530 unsigned char *buf = NULL;
531
532 len = i2d_RSAPrivateKey(pk->key, &buf);
533 if (len < 0 || buf == NULL)
534 return -1;
535
536 if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
537 OPENSSL_free(buf);
538 return -1;
539 }
540 /* We don't encode directly into 'dest', because that would be illegal
541 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
542 */
543 memcpy(dest,buf,len);
544 OPENSSL_free(buf);
545 return len;
546}
547
548/** Check whether any component of a private key is too large in a way that
549 * seems likely to make verification too expensive. Return true if it's too
550 * long, and false otherwise. */
551static bool
552rsa_private_key_too_long(RSA *rsa, int max_bits)
553{
554 const BIGNUM *n, *e, *p, *q, *d, *dmp1, *dmq1, *iqmp;
555
556 n = RSA_get0_n(rsa);
557 e = RSA_get0_e(rsa);
558 p = RSA_get0_p(rsa);
559 q = RSA_get0_q(rsa);
560 d = RSA_get0_d(rsa);
561 dmp1 = RSA_get0_dmp1(rsa);
562 dmq1 = RSA_get0_dmq1(rsa);
563 iqmp = RSA_get0_iqmp(rsa);
564
565 if (RSA_bits(rsa) > max_bits)
566 return true;
567
568 if (n && BN_num_bits(n) > max_bits)
569 return true;
570 if (e && BN_num_bits(e) > max_bits)
571 return true;
572 if (p && BN_num_bits(p) > max_bits)
573 return true;
574 if (q && BN_num_bits(q) > max_bits)
575 return true;
576 if (d && BN_num_bits(d) > max_bits)
577 return true;
578 if (dmp1 && BN_num_bits(dmp1) > max_bits)
579 return true;
580 if (dmq1 && BN_num_bits(dmq1) > max_bits)
581 return true;
582 if (iqmp && BN_num_bits(iqmp) > max_bits)
583 return true;
584
585 return false;
586}
587
588/** Decode an ASN.1-encoded private key from <b>str</b>; return the result on
589 * success and NULL on failure.
590 *
591 * If <b>max_bits</b> is nonnegative, reject any key longer than max_bits
592 * without performing any expensive validation on it.
593 */
595crypto_pk_asn1_decode_private(const char *str, size_t len, int max_bits)
596{
597 RSA *rsa;
598 unsigned char *buf;
599 const unsigned char *cp;
600 cp = buf = tor_malloc(len);
601 memcpy(buf,str,len);
602 rsa = d2i_RSAPrivateKey(NULL, &cp, len);
603 tor_free(buf);
604 if (!rsa) {
605 crypto_openssl_log_errors(LOG_WARN,"decoding private key");
606 return NULL;
607 }
608 if (max_bits >= 0 && rsa_private_key_too_long(rsa, max_bits)) {
609 log_info(LD_CRYPTO, "Private key longer than expected.");
610 RSA_free(rsa);
611 return NULL;
612 }
613 crypto_pk_t *result = crypto_new_pk_from_openssl_rsa_(rsa);
614 if (! crypto_pk_is_valid_private_key(result)) {
615 crypto_pk_free(result);
616 return NULL;
617 }
618 return result;
619}
Header for binascii.c.
void crypto_openssl_log_errors(int severity, const char *doing)
Headers for crypto_rsa.c.
#define TOR_RSA_EXPONENT
Definition: crypto_rsa.h:37
void crypto_pk_assign_private(crypto_pk_t *dest, const crypto_pk_t *src)
crypto_pk_t * crypto_pk_new(void)
int crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
int crypto_pk_generate_key_with_bits(crypto_pk_t *env, int bits)
size_t crypto_pk_keysize(const crypto_pk_t *env)
int crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen)
int crypto_pk_is_valid_private_key(const crypto_pk_t *env)
int crypto_pk_private_decrypt(crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen, int padding, int warnOnFailure)
int crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
crypto_pk_t * crypto_pk_asn1_decode(const char *str, size_t len)
crypto_pk_t * crypto_pk_copy_full(crypto_pk_t *orig)
int crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen, int padding)
void crypto_pk_assign_public(crypto_pk_t *dest, const crypto_pk_t *src)
crypto_pk_t * crypto_pk_asn1_decode_private(const char *str, size_t len, int max_bits)
int crypto_pk_num_bits(crypto_pk_t *env)
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
int crypto_pk_key_is_private(const crypto_pk_t *key)
int crypto_pk_asn1_encode_private(const crypto_pk_t *pk, char *dest, size_t dest_len)
int crypto_pk_public_checksig(const crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen)
int crypto_pk_public_exponent_ok(const crypto_pk_t *env)
void crypto_pk_free_(crypto_pk_t *env)
Common functions for cryptographic routines.
int tor_memcmp(const void *a, const void *b, size_t len)
Definition: di_ops.c:31
Headers for di_ops.c.
Wrappers for reading and writing data to files on disk.
#define LD_CRYPTO
Definition: log.h:64
#define LOG_DEBUG
Definition: log.h:42
#define LOG_ERR
Definition: log.h:56
#define LOG_WARN
Definition: log.h:53
#define LOG_INFO
Definition: log.h:45
#define tor_free(p)
Definition: malloc.h:56
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
#define SIZE_T_CEILING
Definition: torint.h:126
Macros to manage assertions, fatal and non-fatal.
#define tor_assert(expr)
Definition: util_bug.h:103
#define tor_fragile_assert()
Definition: util_bug.h:278