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