Merge branch 'bug19152_024_v2' into maint-0.2.8
[tor.git] / src / common / crypto.c
blob933f1033f79d7195f4ac430703baefe2a5418fc0
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-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file crypto.c
9 * \brief Wrapper functions to present a consistent interface to
10 * public-key and symmetric cryptography operations from OpenSSL and
11 * other places.
12 **/
14 #include "orconfig.h"
16 #ifdef _WIN32
17 #include <winsock2.h>
18 #include <windows.h>
19 #include <wincrypt.h>
20 /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
21 * use either definition. */
22 #undef OCSP_RESPONSE
23 #endif
25 #define CRYPTO_PRIVATE
26 #include "crypto.h"
27 #include "compat_openssl.h"
28 #include "crypto_curve25519.h"
29 #include "crypto_ed25519.h"
30 #include "crypto_format.h"
32 #include <openssl/err.h>
33 #include <openssl/rsa.h>
34 #include <openssl/pem.h>
35 #include <openssl/evp.h>
36 #include <openssl/engine.h>
37 #include <openssl/rand.h>
38 #include <openssl/bn.h>
39 #include <openssl/dh.h>
40 #include <openssl/conf.h>
41 #include <openssl/hmac.h>
43 #ifdef HAVE_CTYPE_H
44 #include <ctype.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 #define _GNU_SOURCE
48 #include <unistd.h>
49 #endif
50 #ifdef HAVE_FCNTL_H
51 #include <fcntl.h>
52 #endif
53 #ifdef HAVE_SYS_FCNTL_H
54 #include <sys/fcntl.h>
55 #endif
56 #ifdef HAVE_SYS_SYSCALL_H
57 #include <sys/syscall.h>
58 #endif
60 #include "torlog.h"
61 #include "aes.h"
62 #include "util.h"
63 #include "container.h"
64 #include "compat.h"
65 #include "sandbox.h"
66 #include "util_format.h"
68 #include "keccak-tiny/keccak-tiny.h"
70 #ifdef ANDROID
71 /* Android's OpenSSL seems to have removed all of its Engine support. */
72 #define DISABLE_ENGINES
73 #endif
75 #if OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,4) && \
76 !defined(LIBRESSL_VERSION_NUMBER)
77 /* OpenSSL as of 1.1.0-pre4 has an "new" thread API, which doesn't require
78 * seting up various callbacks.
80 * Note: Yes, using OPENSSL_VER is naughty, but this was introduced in the
81 * pre-release series.
83 #define NEW_THREAD_API
84 #endif
86 /** Longest recognized */
87 #define MAX_DNS_LABEL_SIZE 63
89 /** Largest strong entropy request */
90 #define MAX_STRONGEST_RAND_SIZE 256
92 /** Macro: is k a valid RSA public or private key? */
93 #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
94 /** Macro: is k a valid RSA private key? */
95 #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
97 #ifndef NEW_THREAD_API
98 /** A number of preallocated mutexes for use by OpenSSL. */
99 static tor_mutex_t **openssl_mutexes_ = NULL;
100 /** How many mutexes have we allocated for use by OpenSSL? */
101 static int n_openssl_mutexes_ = 0;
102 #endif
104 /** A public key, or a public/private key-pair. */
105 struct crypto_pk_t
107 int refs; /**< reference count, so we don't have to copy keys */
108 RSA *key; /**< The key itself */
111 /** Key and stream information for a stream cipher. */
112 struct crypto_cipher_t
114 char key[CIPHER_KEY_LEN]; /**< The raw key. */
115 char iv[CIPHER_IV_LEN]; /**< The initial IV. */
116 aes_cnt_cipher_t *cipher; /**< The key in format usable for counter-mode AES
117 * encryption */
120 /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
121 * while we're waiting for the second.*/
122 struct crypto_dh_t {
123 DH *dh; /**< The openssl DH object */
126 static int setup_openssl_threading(void);
127 static int tor_check_dh_key(int severity, BIGNUM *bn);
129 /** Return the number of bytes added by padding method <b>padding</b>.
131 static inline int
132 crypto_get_rsa_padding_overhead(int padding)
134 switch (padding)
136 case RSA_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
137 default: tor_assert(0); return -1;
141 /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
143 static inline int
144 crypto_get_rsa_padding(int padding)
146 switch (padding)
148 case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
149 default: tor_assert(0); return -1;
153 /** Boolean: has OpenSSL's crypto been initialized? */
154 static int crypto_early_initialized_ = 0;
156 /** Boolean: has OpenSSL's crypto been initialized? */
157 static int crypto_global_initialized_ = 0;
159 /** Log all pending crypto errors at level <b>severity</b>. Use
160 * <b>doing</b> to describe our current activities.
162 static void
163 crypto_log_errors(int severity, const char *doing)
165 unsigned long err;
166 const char *msg, *lib, *func;
167 while ((err = ERR_get_error()) != 0) {
168 msg = (const char*)ERR_reason_error_string(err);
169 lib = (const char*)ERR_lib_error_string(err);
170 func = (const char*)ERR_func_error_string(err);
171 if (!msg) msg = "(null)";
172 if (!lib) lib = "(null)";
173 if (!func) func = "(null)";
174 if (doing) {
175 tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
176 doing, msg, lib, func);
177 } else {
178 tor_log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)",
179 msg, lib, func);
184 #ifndef DISABLE_ENGINES
185 /** Log any OpenSSL engines we're using at NOTICE. */
186 static void
187 log_engine(const char *fn, ENGINE *e)
189 if (e) {
190 const char *name, *id;
191 name = ENGINE_get_name(e);
192 id = ENGINE_get_id(e);
193 log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
194 fn, name?name:"?", id?id:"?");
195 } else {
196 log_info(LD_CRYPTO, "Using default implementation for %s", fn);
199 #endif
201 #ifndef DISABLE_ENGINES
202 /** Try to load an engine in a shared library via fully qualified path.
204 static ENGINE *
205 try_load_engine(const char *path, const char *engine)
207 ENGINE *e = ENGINE_by_id("dynamic");
208 if (e) {
209 if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
210 !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
211 !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
212 !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
213 ENGINE_free(e);
214 e = NULL;
217 return e;
219 #endif
221 /* Returns a trimmed and human-readable version of an openssl version string
222 * <b>raw_version</b>. They are usually in the form of 'OpenSSL 1.0.0b 10
223 * May 2012' and this will parse them into a form similar to '1.0.0b' */
224 static char *
225 parse_openssl_version_str(const char *raw_version)
227 const char *end_of_version = NULL;
228 /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
229 trim that down. */
230 if (!strcmpstart(raw_version, "OpenSSL ")) {
231 raw_version += strlen("OpenSSL ");
232 end_of_version = strchr(raw_version, ' ');
235 if (end_of_version)
236 return tor_strndup(raw_version,
237 end_of_version-raw_version);
238 else
239 return tor_strdup(raw_version);
242 static char *crypto_openssl_version_str = NULL;
243 /* Return a human-readable version of the run-time openssl version number. */
244 const char *
245 crypto_openssl_get_version_str(void)
247 if (crypto_openssl_version_str == NULL) {
248 const char *raw_version = OpenSSL_version(OPENSSL_VERSION);
249 crypto_openssl_version_str = parse_openssl_version_str(raw_version);
251 return crypto_openssl_version_str;
254 static char *crypto_openssl_header_version_str = NULL;
255 /* Return a human-readable version of the compile-time openssl version
256 * number. */
257 const char *
258 crypto_openssl_get_header_version_str(void)
260 if (crypto_openssl_header_version_str == NULL) {
261 crypto_openssl_header_version_str =
262 parse_openssl_version_str(OPENSSL_VERSION_TEXT);
264 return crypto_openssl_header_version_str;
267 /** Make sure that openssl is using its default PRNG. Return 1 if we had to
268 * adjust it; 0 otherwise. */
269 STATIC int
270 crypto_force_rand_ssleay(void)
272 RAND_METHOD *default_method;
273 default_method = RAND_OpenSSL();
274 if (RAND_get_rand_method() != default_method) {
275 log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
276 "a replacement the OpenSSL RNG. Resetting it to the default "
277 "implementation.");
278 RAND_set_rand_method(default_method);
279 return 1;
281 return 0;
284 /** Set up the siphash key if we haven't already done so. */
286 crypto_init_siphash_key(void)
288 static int have_seeded_siphash = 0;
289 struct sipkey key;
290 if (have_seeded_siphash)
291 return 0;
293 crypto_rand((char*) &key, sizeof(key));
294 siphash_set_global_key(&key);
295 have_seeded_siphash = 1;
296 return 0;
299 /** Initialize the crypto library. Return 0 on success, -1 on failure.
302 crypto_early_init(void)
304 if (!crypto_early_initialized_) {
306 crypto_early_initialized_ = 1;
308 ERR_load_crypto_strings();
309 OpenSSL_add_all_algorithms();
311 setup_openssl_threading();
313 unsigned long version_num = OpenSSL_version_num();
314 const char *version_str = OpenSSL_version(OPENSSL_VERSION);
315 if (version_num == OPENSSL_VERSION_NUMBER &&
316 !strcmp(version_str, OPENSSL_VERSION_TEXT)) {
317 log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
318 "(%lx: %s).", version_num, version_str);
319 } else {
320 log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
321 "version we're running with. If you get weird crashes, that "
322 "might be why. (Compiled with %lx: %s; running with %lx: %s).",
323 (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
324 version_num, version_str);
327 crypto_force_rand_ssleay();
329 if (crypto_seed_rng() < 0)
330 return -1;
331 if (crypto_init_siphash_key() < 0)
332 return -1;
334 curve25519_init();
335 ed25519_init();
337 return 0;
340 /** Initialize the crypto library. Return 0 on success, -1 on failure.
343 crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
345 if (!crypto_global_initialized_) {
346 if (crypto_early_init() < 0)
347 return -1;
349 crypto_global_initialized_ = 1;
351 if (useAccel > 0) {
352 #ifdef DISABLE_ENGINES
353 (void)accelName;
354 (void)accelDir;
355 log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
356 #else
357 ENGINE *e = NULL;
359 log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
360 ENGINE_load_builtin_engines();
361 ENGINE_register_all_complete();
363 if (accelName) {
364 if (accelDir) {
365 log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
366 " via path \"%s\".", accelName, accelDir);
367 e = try_load_engine(accelName, accelDir);
368 } else {
369 log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
370 " acceleration support.", accelName);
371 e = ENGINE_by_id(accelName);
373 if (!e) {
374 log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
375 accelName);
376 } else {
377 log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
378 accelName);
381 if (e) {
382 log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
383 " setting default ciphers.");
384 ENGINE_set_default(e, ENGINE_METHOD_ALL);
386 /* Log, if available, the intersection of the set of algorithms
387 used by Tor and the set of algorithms available in the engine */
388 log_engine("RSA", ENGINE_get_default_RSA());
389 log_engine("DH", ENGINE_get_default_DH());
390 #ifdef OPENSSL_1_1_API
391 log_engine("EC", ENGINE_get_default_EC());
392 #else
393 log_engine("ECDH", ENGINE_get_default_ECDH());
394 log_engine("ECDSA", ENGINE_get_default_ECDSA());
395 #endif
396 log_engine("RAND", ENGINE_get_default_RAND());
397 log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
398 log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
399 log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
400 log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
401 log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
402 #ifdef NID_aes_128_ctr
403 log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
404 #endif
405 #ifdef NID_aes_128_gcm
406 log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
407 #endif
408 log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
409 #ifdef NID_aes_256_gcm
410 log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
411 #endif
413 #endif
414 } else {
415 log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
418 if (crypto_force_rand_ssleay()) {
419 if (crypto_seed_rng() < 0)
420 return -1;
423 evaluate_evp_for_aes(-1);
424 evaluate_ctr_for_aes();
426 return 0;
429 /** Free crypto resources held by this thread. */
430 void
431 crypto_thread_cleanup(void)
433 #ifdef NEW_THREAD_API
434 ERR_remove_thread_state();
435 #else
436 ERR_remove_thread_state(NULL);
437 #endif
440 /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
441 crypto_pk_t *
442 crypto_new_pk_from_rsa_(RSA *rsa)
444 crypto_pk_t *env;
445 tor_assert(rsa);
446 env = tor_malloc(sizeof(crypto_pk_t));
447 env->refs = 1;
448 env->key = rsa;
449 return env;
452 /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
453 * crypto_pk_t. */
454 RSA *
455 crypto_pk_get_rsa_(crypto_pk_t *env)
457 return env->key;
460 /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
461 * private is set, include the private-key portion of the key. Return a valid
462 * pointer on success, and NULL on failure. */
463 MOCK_IMPL(EVP_PKEY *,
464 crypto_pk_get_evp_pkey_,(crypto_pk_t *env, int private))
466 RSA *key = NULL;
467 EVP_PKEY *pkey = NULL;
468 tor_assert(env->key);
469 if (private) {
470 if (!(key = RSAPrivateKey_dup(env->key)))
471 goto error;
472 } else {
473 if (!(key = RSAPublicKey_dup(env->key)))
474 goto error;
476 if (!(pkey = EVP_PKEY_new()))
477 goto error;
478 if (!(EVP_PKEY_assign_RSA(pkey, key)))
479 goto error;
480 return pkey;
481 error:
482 if (pkey)
483 EVP_PKEY_free(pkey);
484 if (key)
485 RSA_free(key);
486 return NULL;
489 /** Used by tortls.c: Get the DH* from a crypto_dh_t.
491 DH *
492 crypto_dh_get_dh_(crypto_dh_t *dh)
494 return dh->dh;
497 /** Allocate and return storage for a public key. The key itself will not yet
498 * be set.
500 MOCK_IMPL(crypto_pk_t *,
501 crypto_pk_new,(void))
503 RSA *rsa;
505 rsa = RSA_new();
506 tor_assert(rsa);
507 return crypto_new_pk_from_rsa_(rsa);
510 /** Release a reference to an asymmetric key; when all the references
511 * are released, free the key.
513 void
514 crypto_pk_free(crypto_pk_t *env)
516 if (!env)
517 return;
519 if (--env->refs > 0)
520 return;
521 tor_assert(env->refs == 0);
523 if (env->key)
524 RSA_free(env->key);
526 tor_free(env);
529 /** Allocate and return a new symmetric cipher using the provided key and iv.
530 * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. If you
531 * provide NULL in place of either one, it is generated at random.
533 crypto_cipher_t *
534 crypto_cipher_new_with_iv(const char *key, const char *iv)
536 crypto_cipher_t *env;
538 env = tor_malloc_zero(sizeof(crypto_cipher_t));
540 if (key == NULL)
541 crypto_rand(env->key, CIPHER_KEY_LEN);
542 else
543 memcpy(env->key, key, CIPHER_KEY_LEN);
544 if (iv == NULL)
545 crypto_rand(env->iv, CIPHER_IV_LEN);
546 else
547 memcpy(env->iv, iv, CIPHER_IV_LEN);
549 env->cipher = aes_new_cipher(env->key, env->iv);
551 return env;
554 /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
555 * zero bytes. */
556 crypto_cipher_t *
557 crypto_cipher_new(const char *key)
559 char zeroiv[CIPHER_IV_LEN];
560 memset(zeroiv, 0, sizeof(zeroiv));
561 return crypto_cipher_new_with_iv(key, zeroiv);
564 /** Free a symmetric cipher.
566 void
567 crypto_cipher_free(crypto_cipher_t *env)
569 if (!env)
570 return;
572 tor_assert(env->cipher);
573 aes_cipher_free(env->cipher);
574 memwipe(env, 0, sizeof(crypto_cipher_t));
575 tor_free(env);
578 /* public key crypto */
580 /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
581 * Return 0 on success, -1 on failure.
583 MOCK_IMPL(int,
584 crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
586 tor_assert(env);
588 if (env->key) {
589 RSA_free(env->key);
590 env->key = NULL;
594 BIGNUM *e = BN_new();
595 RSA *r = NULL;
596 if (!e)
597 goto done;
598 if (! BN_set_word(e, 65537))
599 goto done;
600 r = RSA_new();
601 if (!r)
602 goto done;
603 if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
604 goto done;
606 env->key = r;
607 r = NULL;
608 done:
609 if (e)
610 BN_clear_free(e);
611 if (r)
612 RSA_free(r);
615 if (!env->key) {
616 crypto_log_errors(LOG_WARN, "generating RSA key");
617 return -1;
620 return 0;
623 /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
624 * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
625 * the string is nul-terminated.
627 /* Used here, and used for testing. */
629 crypto_pk_read_private_key_from_string(crypto_pk_t *env,
630 const char *s, ssize_t len)
632 BIO *b;
634 tor_assert(env);
635 tor_assert(s);
636 tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
638 /* Create a read-only memory BIO, backed by the string 's' */
639 b = BIO_new_mem_buf((char*)s, (int)len);
640 if (!b)
641 return -1;
643 if (env->key)
644 RSA_free(env->key);
646 env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
648 BIO_free(b);
650 if (!env->key) {
651 crypto_log_errors(LOG_WARN, "Error parsing private key");
652 return -1;
654 return 0;
657 /** Read a PEM-encoded private key from the file named by
658 * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
661 crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
662 const char *keyfile)
664 char *contents;
665 int r;
667 /* Read the file into a string. */
668 contents = read_file_to_str(keyfile, 0, NULL);
669 if (!contents) {
670 log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
671 return -1;
674 /* Try to parse it. */
675 r = crypto_pk_read_private_key_from_string(env, contents, -1);
676 memwipe(contents, 0, strlen(contents));
677 tor_free(contents);
678 if (r)
679 return -1; /* read_private_key_from_string already warned, so we don't.*/
681 /* Make sure it's valid. */
682 if (crypto_pk_check_key(env) <= 0)
683 return -1;
685 return 0;
688 /** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
689 * success, -1 on failure. */
690 static int
691 crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
692 size_t *len, int is_public)
694 BUF_MEM *buf;
695 BIO *b;
696 int r;
698 tor_assert(env);
699 tor_assert(env->key);
700 tor_assert(dest);
702 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
703 if (!b)
704 return -1;
706 /* Now you can treat b as if it were a file. Just use the
707 * PEM_*_bio_* functions instead of the non-bio variants.
709 if (is_public)
710 r = PEM_write_bio_RSAPublicKey(b, env->key);
711 else
712 r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
714 if (!r) {
715 crypto_log_errors(LOG_WARN, "writing RSA key to string");
716 BIO_free(b);
717 return -1;
720 BIO_get_mem_ptr(b, &buf);
721 (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
722 BIO_free(b);
724 *dest = tor_malloc(buf->length+1);
725 memcpy(*dest, buf->data, buf->length);
726 (*dest)[buf->length] = 0; /* nul terminate it */
727 *len = buf->length;
728 BUF_MEM_free(buf);
730 return 0;
733 /** PEM-encode the public key portion of <b>env</b> and write it to a
734 * newly allocated string. On success, set *<b>dest</b> to the new
735 * string, *<b>len</b> to the string's length, and return 0. On
736 * failure, return -1.
739 crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
740 size_t *len)
742 return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
745 /** PEM-encode the private key portion of <b>env</b> and write it to a
746 * newly allocated string. On success, set *<b>dest</b> to the new
747 * string, *<b>len</b> to the string's length, and return 0. On
748 * failure, return -1.
751 crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
752 size_t *len)
754 return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
757 /** Read a PEM-encoded public key from the first <b>len</b> characters of
758 * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
759 * failure.
762 crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
763 size_t len)
765 BIO *b;
767 tor_assert(env);
768 tor_assert(src);
769 tor_assert(len<INT_MAX);
771 b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
772 if (!b)
773 return -1;
775 BIO_write(b, src, (int)len);
777 if (env->key)
778 RSA_free(env->key);
779 env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
780 BIO_free(b);
781 if (!env->key) {
782 crypto_log_errors(LOG_WARN, "reading public key from string");
783 return -1;
786 return 0;
789 /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
790 * PEM-encoded. Return 0 on success, -1 on failure.
793 crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
794 const char *fname)
796 BIO *bio;
797 char *cp;
798 long len;
799 char *s;
800 int r;
802 tor_assert(PRIVATE_KEY_OK(env));
804 if (!(bio = BIO_new(BIO_s_mem())))
805 return -1;
806 if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
807 == 0) {
808 crypto_log_errors(LOG_WARN, "writing private key");
809 BIO_free(bio);
810 return -1;
812 len = BIO_get_mem_data(bio, &cp);
813 tor_assert(len >= 0);
814 s = tor_malloc(len+1);
815 memcpy(s, cp, len);
816 s[len]='\0';
817 r = write_str_to_file(fname, s, 0);
818 BIO_free(bio);
819 memwipe(s, 0, strlen(s));
820 tor_free(s);
821 return r;
824 /** Return true iff <b>env</b> has a valid key.
827 crypto_pk_check_key(crypto_pk_t *env)
829 int r;
830 tor_assert(env);
832 r = RSA_check_key(env->key);
833 if (r <= 0)
834 crypto_log_errors(LOG_WARN,"checking RSA key");
835 return r;
838 /** Return true iff <b>key</b> contains the private-key portion of the RSA
839 * key. */
841 crypto_pk_key_is_private(const crypto_pk_t *key)
843 tor_assert(key);
844 return PRIVATE_KEY_OK(key);
847 /** Return true iff <b>env</b> contains a public key whose public exponent
848 * equals 65537.
851 crypto_pk_public_exponent_ok(crypto_pk_t *env)
853 tor_assert(env);
854 tor_assert(env->key);
856 return BN_is_word(env->key->e, 65537);
859 /** Compare the public-key components of a and b. Return less than 0
860 * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
861 * considered to be less than all non-NULL keys, and equal to itself.
863 * Note that this may leak information about the keys through timing.
866 crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
868 int result;
869 char a_is_non_null = (a != NULL) && (a->key != NULL);
870 char b_is_non_null = (b != NULL) && (b->key != NULL);
871 char an_argument_is_null = !a_is_non_null | !b_is_non_null;
873 result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
874 if (an_argument_is_null)
875 return result;
877 tor_assert(PUBLIC_KEY_OK(a));
878 tor_assert(PUBLIC_KEY_OK(b));
879 result = BN_cmp((a->key)->n, (b->key)->n);
880 if (result)
881 return result;
882 return BN_cmp((a->key)->e, (b->key)->e);
885 /** Compare the public-key components of a and b. Return non-zero iff
886 * a==b. A NULL key is considered to be distinct from all non-NULL
887 * keys, and equal to itself.
889 * Note that this may leak information about the keys through timing.
892 crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
894 return (crypto_pk_cmp_keys(a, b) == 0);
897 /** Return the size of the public key modulus in <b>env</b>, in bytes. */
898 size_t
899 crypto_pk_keysize(const crypto_pk_t *env)
901 tor_assert(env);
902 tor_assert(env->key);
904 return (size_t) RSA_size((RSA*)env->key);
907 /** Return the size of the public key modulus of <b>env</b>, in bits. */
909 crypto_pk_num_bits(crypto_pk_t *env)
911 tor_assert(env);
912 tor_assert(env->key);
913 tor_assert(env->key->n);
915 return BN_num_bits(env->key->n);
918 /** Increase the reference count of <b>env</b>, and return it.
920 crypto_pk_t *
921 crypto_pk_dup_key(crypto_pk_t *env)
923 tor_assert(env);
924 tor_assert(env->key);
926 env->refs++;
927 return env;
930 /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
931 * Returns NULL on failure. */
932 crypto_pk_t *
933 crypto_pk_copy_full(crypto_pk_t *env)
935 RSA *new_key;
936 int privatekey = 0;
937 tor_assert(env);
938 tor_assert(env->key);
940 if (PRIVATE_KEY_OK(env)) {
941 new_key = RSAPrivateKey_dup(env->key);
942 privatekey = 1;
943 } else {
944 new_key = RSAPublicKey_dup(env->key);
946 if (!new_key) {
947 log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
948 privatekey?"private":"public");
949 crypto_log_errors(LOG_ERR,
950 privatekey ? "Duplicating a private key" :
951 "Duplicating a public key");
952 tor_fragile_assert();
953 return NULL;
956 return crypto_new_pk_from_rsa_(new_key);
959 /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
960 * in <b>env</b>, using the padding method <b>padding</b>. On success,
961 * write the result to <b>to</b>, and return the number of bytes
962 * written. On failure, return -1.
964 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
965 * at least the length of the modulus of <b>env</b>.
968 crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
969 const char *from, size_t fromlen, int padding)
971 int r;
972 tor_assert(env);
973 tor_assert(from);
974 tor_assert(to);
975 tor_assert(fromlen<INT_MAX);
976 tor_assert(tolen >= crypto_pk_keysize(env));
978 r = RSA_public_encrypt((int)fromlen,
979 (unsigned char*)from, (unsigned char*)to,
980 env->key, crypto_get_rsa_padding(padding));
981 if (r<0) {
982 crypto_log_errors(LOG_WARN, "performing RSA encryption");
983 return -1;
985 return r;
988 /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
989 * in <b>env</b>, using the padding method <b>padding</b>. On success,
990 * write the result to <b>to</b>, and return the number of bytes
991 * written. On failure, return -1.
993 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
994 * at least the length of the modulus of <b>env</b>.
997 crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
998 size_t tolen,
999 const char *from, size_t fromlen,
1000 int padding, int warnOnFailure)
1002 int r;
1003 tor_assert(env);
1004 tor_assert(from);
1005 tor_assert(to);
1006 tor_assert(env->key);
1007 tor_assert(fromlen<INT_MAX);
1008 tor_assert(tolen >= crypto_pk_keysize(env));
1009 if (!env->key->p)
1010 /* Not a private key */
1011 return -1;
1013 r = RSA_private_decrypt((int)fromlen,
1014 (unsigned char*)from, (unsigned char*)to,
1015 env->key, crypto_get_rsa_padding(padding));
1017 if (r<0) {
1018 crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
1019 "performing RSA decryption");
1020 return -1;
1022 return r;
1025 /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
1026 * public key in <b>env</b>, using PKCS1 padding. On success, write the
1027 * signed data to <b>to</b>, and return the number of bytes written.
1028 * On failure, return -1.
1030 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1031 * at least the length of the modulus of <b>env</b>.
1034 crypto_pk_public_checksig(const crypto_pk_t *env, char *to,
1035 size_t tolen,
1036 const char *from, size_t fromlen)
1038 int r;
1039 tor_assert(env);
1040 tor_assert(from);
1041 tor_assert(to);
1042 tor_assert(fromlen < INT_MAX);
1043 tor_assert(tolen >= crypto_pk_keysize(env));
1044 r = RSA_public_decrypt((int)fromlen,
1045 (unsigned char*)from, (unsigned char*)to,
1046 env->key, RSA_PKCS1_PADDING);
1048 if (r<0) {
1049 crypto_log_errors(LOG_INFO, "checking RSA signature");
1050 return -1;
1052 return r;
1055 /** Check a siglen-byte long signature at <b>sig</b> against
1056 * <b>datalen</b> bytes of data at <b>data</b>, using the public key
1057 * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
1058 * SHA1(data). Else return -1.
1061 crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
1062 size_t datalen, const char *sig, size_t siglen)
1064 char digest[DIGEST_LEN];
1065 char *buf;
1066 size_t buflen;
1067 int r;
1069 tor_assert(env);
1070 tor_assert(data);
1071 tor_assert(sig);
1072 tor_assert(datalen < SIZE_T_CEILING);
1073 tor_assert(siglen < SIZE_T_CEILING);
1075 if (crypto_digest(digest,data,datalen)<0) {
1076 log_warn(LD_BUG, "couldn't compute digest");
1077 return -1;
1079 buflen = crypto_pk_keysize(env);
1080 buf = tor_malloc(buflen);
1081 r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
1082 if (r != DIGEST_LEN) {
1083 log_warn(LD_CRYPTO, "Invalid signature");
1084 tor_free(buf);
1085 return -1;
1087 if (tor_memneq(buf, digest, DIGEST_LEN)) {
1088 log_warn(LD_CRYPTO, "Signature mismatched with digest.");
1089 tor_free(buf);
1090 return -1;
1092 tor_free(buf);
1094 return 0;
1097 /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
1098 * <b>env</b>, using PKCS1 padding. On success, write the signature to
1099 * <b>to</b>, and return the number of bytes written. On failure, return
1100 * -1.
1102 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1103 * at least the length of the modulus of <b>env</b>.
1106 crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
1107 const char *from, size_t fromlen)
1109 int r;
1110 tor_assert(env);
1111 tor_assert(from);
1112 tor_assert(to);
1113 tor_assert(fromlen < INT_MAX);
1114 tor_assert(tolen >= crypto_pk_keysize(env));
1115 if (!env->key->p)
1116 /* Not a private key */
1117 return -1;
1119 r = RSA_private_encrypt((int)fromlen,
1120 (unsigned char*)from, (unsigned char*)to,
1121 (RSA*)env->key, RSA_PKCS1_PADDING);
1122 if (r<0) {
1123 crypto_log_errors(LOG_WARN, "generating RSA signature");
1124 return -1;
1126 return r;
1129 /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
1130 * <b>from</b>; sign the data with the private key in <b>env</b>, and
1131 * store it in <b>to</b>. Return the number of bytes written on
1132 * success, and -1 on failure.
1134 * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
1135 * at least the length of the modulus of <b>env</b>.
1138 crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
1139 const char *from, size_t fromlen)
1141 int r;
1142 char digest[DIGEST_LEN];
1143 if (crypto_digest(digest,from,fromlen)<0)
1144 return -1;
1145 r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
1146 memwipe(digest, 0, sizeof(digest));
1147 return r;
1150 /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
1151 * bytes of data from <b>from</b>, with padding type 'padding',
1152 * storing the results on <b>to</b>.
1154 * Returns the number of bytes written on success, -1 on failure.
1156 * The encrypted data consists of:
1157 * - The source data, padded and encrypted with the public key, if the
1158 * padded source data is no longer than the public key, and <b>force</b>
1159 * is false, OR
1160 * - The beginning of the source data prefixed with a 16-byte symmetric key,
1161 * padded and encrypted with the public key; followed by the rest of
1162 * the source data encrypted in AES-CTR mode with the symmetric key.
1165 crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
1166 char *to, size_t tolen,
1167 const char *from,
1168 size_t fromlen,
1169 int padding, int force)
1171 int overhead, outlen, r;
1172 size_t pkeylen, symlen;
1173 crypto_cipher_t *cipher = NULL;
1174 char *buf = NULL;
1176 tor_assert(env);
1177 tor_assert(from);
1178 tor_assert(to);
1179 tor_assert(fromlen < SIZE_T_CEILING);
1181 overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
1182 pkeylen = crypto_pk_keysize(env);
1184 if (!force && fromlen+overhead <= pkeylen) {
1185 /* It all fits in a single encrypt. */
1186 return crypto_pk_public_encrypt(env,to,
1187 tolen,
1188 from,fromlen,padding);
1190 tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
1191 tor_assert(tolen >= pkeylen);
1193 cipher = crypto_cipher_new(NULL); /* generate a new key. */
1195 buf = tor_malloc(pkeylen+1);
1196 memcpy(buf, cipher->key, CIPHER_KEY_LEN);
1197 memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
1199 /* Length of symmetrically encrypted data. */
1200 symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
1202 outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
1203 if (outlen!=(int)pkeylen) {
1204 goto err;
1206 r = crypto_cipher_encrypt(cipher, to+outlen,
1207 from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
1209 if (r<0) goto err;
1210 memwipe(buf, 0, pkeylen);
1211 tor_free(buf);
1212 crypto_cipher_free(cipher);
1213 tor_assert(outlen+symlen < INT_MAX);
1214 return (int)(outlen + symlen);
1215 err:
1217 memwipe(buf, 0, pkeylen);
1218 tor_free(buf);
1219 crypto_cipher_free(cipher);
1220 return -1;
1223 /** Invert crypto_pk_public_hybrid_encrypt. Returns the number of bytes
1224 * written on success, -1 on failure. */
1226 crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
1227 char *to,
1228 size_t tolen,
1229 const char *from,
1230 size_t fromlen,
1231 int padding, int warnOnFailure)
1233 int outlen, r;
1234 size_t pkeylen;
1235 crypto_cipher_t *cipher = NULL;
1236 char *buf = NULL;
1238 tor_assert(fromlen < SIZE_T_CEILING);
1239 pkeylen = crypto_pk_keysize(env);
1241 if (fromlen <= pkeylen) {
1242 return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
1243 warnOnFailure);
1246 buf = tor_malloc(pkeylen);
1247 outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
1248 warnOnFailure);
1249 if (outlen<0) {
1250 log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
1251 "Error decrypting public-key data");
1252 goto err;
1254 if (outlen < CIPHER_KEY_LEN) {
1255 log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
1256 "No room for a symmetric key");
1257 goto err;
1259 cipher = crypto_cipher_new(buf);
1260 if (!cipher) {
1261 goto err;
1263 memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
1264 outlen -= CIPHER_KEY_LEN;
1265 tor_assert(tolen - outlen >= fromlen - pkeylen);
1266 r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
1267 if (r<0)
1268 goto err;
1269 memwipe(buf,0,pkeylen);
1270 tor_free(buf);
1271 crypto_cipher_free(cipher);
1272 tor_assert(outlen + fromlen < INT_MAX);
1273 return (int)(outlen + (fromlen-pkeylen));
1274 err:
1275 memwipe(buf,0,pkeylen);
1276 tor_free(buf);
1277 crypto_cipher_free(cipher);
1278 return -1;
1281 /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
1282 * Return -1 on error, or the number of characters used on success.
1285 crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
1287 int len;
1288 unsigned char *buf = NULL;
1290 len = i2d_RSAPublicKey(pk->key, &buf);
1291 if (len < 0 || buf == NULL)
1292 return -1;
1294 if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
1295 OPENSSL_free(buf);
1296 return -1;
1298 /* We don't encode directly into 'dest', because that would be illegal
1299 * type-punning. (C99 is smarter than me, C99 is smarter than me...)
1301 memcpy(dest,buf,len);
1302 OPENSSL_free(buf);
1303 return len;
1306 /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
1307 * success and NULL on failure.
1309 crypto_pk_t *
1310 crypto_pk_asn1_decode(const char *str, size_t len)
1312 RSA *rsa;
1313 unsigned char *buf;
1314 const unsigned char *cp;
1315 cp = buf = tor_malloc(len);
1316 memcpy(buf,str,len);
1317 rsa = d2i_RSAPublicKey(NULL, &cp, len);
1318 tor_free(buf);
1319 if (!rsa) {
1320 crypto_log_errors(LOG_WARN,"decoding public key");
1321 return NULL;
1323 return crypto_new_pk_from_rsa_(rsa);
1326 /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
1327 * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
1328 * Return 0 on success, -1 on failure.
1331 crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
1333 unsigned char *buf = NULL;
1334 int len;
1336 len = i2d_RSAPublicKey((RSA*)pk->key, &buf);
1337 if (len < 0 || buf == NULL)
1338 return -1;
1339 if (crypto_digest(digest_out, (char*)buf, len) < 0) {
1340 OPENSSL_free(buf);
1341 return -1;
1343 OPENSSL_free(buf);
1344 return 0;
1347 /** Compute all digests of the DER encoding of <b>pk</b>, and store them
1348 * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
1350 crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
1352 unsigned char *buf = NULL;
1353 int len;
1355 len = i2d_RSAPublicKey(pk->key, &buf);
1356 if (len < 0 || buf == NULL)
1357 return -1;
1358 if (crypto_common_digests(digests_out, (char*)buf, len) < 0) {
1359 OPENSSL_free(buf);
1360 return -1;
1362 OPENSSL_free(buf);
1363 return 0;
1366 /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
1367 * every four characters. */
1368 void
1369 crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
1371 int n = 0;
1372 char *end = out+outlen;
1373 tor_assert(outlen < SIZE_T_CEILING);
1375 while (*in && out<end) {
1376 *out++ = *in++;
1377 if (++n == 4 && *in && out<end) {
1378 n = 0;
1379 *out++ = ' ';
1382 tor_assert(out<end);
1383 *out = '\0';
1386 /** Given a private or public key <b>pk</b>, put a fingerprint of the
1387 * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
1388 * space). Return 0 on success, -1 on failure.
1390 * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
1391 * of the public key, converted to hexadecimal, in upper case, with a
1392 * space after every four digits.
1394 * If <b>add_space</b> is false, omit the spaces.
1397 crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
1399 char digest[DIGEST_LEN];
1400 char hexdigest[HEX_DIGEST_LEN+1];
1401 if (crypto_pk_get_digest(pk, digest)) {
1402 return -1;
1404 base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
1405 if (add_space) {
1406 crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
1407 } else {
1408 strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
1410 return 0;
1413 /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
1414 * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
1415 * bytes of space). Return 0 on success, -1 on failure.
1417 * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
1418 * of the ASN.1 encoding of the public key, converted to hexadecimal, in
1419 * upper case.
1422 crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
1424 char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
1425 if (crypto_pk_get_digest(pk, digest)) {
1426 return -1;
1428 if (crypto_digest(hashed_digest, digest, DIGEST_LEN)) {
1429 return -1;
1431 base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
1432 return 0;
1435 /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
1436 * Base64 encoding of the DER representation of the private key as a NUL
1437 * terminated string, and return it via <b>priv_out</b>. Return 0 on
1438 * sucess, -1 on failure.
1440 * It is the caller's responsibility to sanitize and free the resulting buffer.
1443 crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
1445 unsigned char *der = NULL;
1446 int der_len;
1447 int ret = -1;
1449 *priv_out = NULL;
1451 der_len = i2d_RSAPrivateKey(pk->key, &der);
1452 if (der_len < 0 || der == NULL)
1453 return ret;
1455 size_t priv_len = base64_encode_size(der_len, 0) + 1;
1456 char *priv = tor_malloc_zero(priv_len);
1457 if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
1458 *priv_out = priv;
1459 ret = 0;
1460 } else {
1461 tor_free(priv);
1464 memwipe(der, 0, der_len);
1465 OPENSSL_free(der);
1466 return ret;
1469 /** Given a string containing the Base64 encoded DER representation of the
1470 * private key <b>str</b>, decode and return the result on success, or NULL
1471 * on failure.
1473 crypto_pk_t *
1474 crypto_pk_base64_decode(const char *str, size_t len)
1476 crypto_pk_t *pk = NULL;
1478 char *der = tor_malloc_zero(len + 1);
1479 int der_len = base64_decode(der, len, str, len);
1480 if (der_len <= 0) {
1481 log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
1482 goto out;
1485 const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
1486 RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
1487 if (!rsa) {
1488 crypto_log_errors(LOG_WARN, "decoding private key");
1489 goto out;
1492 pk = crypto_new_pk_from_rsa_(rsa);
1494 /* Make sure it's valid. */
1495 if (crypto_pk_check_key(pk) <= 0) {
1496 crypto_pk_free(pk);
1497 pk = NULL;
1498 goto out;
1501 out:
1502 memwipe(der, 0, len + 1);
1503 tor_free(der);
1504 return pk;
1507 /* symmetric crypto */
1509 /** Return a pointer to the key set for the cipher in <b>env</b>.
1511 const char *
1512 crypto_cipher_get_key(crypto_cipher_t *env)
1514 return env->key;
1517 /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1518 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1519 * Does not check for failure.
1522 crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
1523 const char *from, size_t fromlen)
1525 tor_assert(env);
1526 tor_assert(env->cipher);
1527 tor_assert(from);
1528 tor_assert(fromlen);
1529 tor_assert(to);
1530 tor_assert(fromlen < SIZE_T_CEILING);
1532 memcpy(to, from, fromlen);
1533 aes_crypt_inplace(env->cipher, to, fromlen);
1534 return 0;
1537 /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
1538 * <b>env</b>; on success, store the result to <b>to</b> and return 0.
1539 * Does not check for failure.
1542 crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
1543 const char *from, size_t fromlen)
1545 tor_assert(env);
1546 tor_assert(from);
1547 tor_assert(to);
1548 tor_assert(fromlen < SIZE_T_CEILING);
1550 memcpy(to, from, fromlen);
1551 aes_crypt_inplace(env->cipher, to, fromlen);
1552 return 0;
1555 /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
1556 * on success. Does not check for failure.
1558 void
1559 crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
1561 tor_assert(len < SIZE_T_CEILING);
1562 aes_crypt_inplace(env->cipher, buf, len);
1565 /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
1566 * <b>key</b> to the buffer in <b>to</b> of length
1567 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
1568 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1569 * number of bytes written, on failure, return -1.
1572 crypto_cipher_encrypt_with_iv(const char *key,
1573 char *to, size_t tolen,
1574 const char *from, size_t fromlen)
1576 crypto_cipher_t *cipher;
1577 tor_assert(from);
1578 tor_assert(to);
1579 tor_assert(fromlen < INT_MAX);
1581 if (fromlen < 1)
1582 return -1;
1583 if (tolen < fromlen + CIPHER_IV_LEN)
1584 return -1;
1586 cipher = crypto_cipher_new_with_iv(key, NULL);
1588 memcpy(to, cipher->iv, CIPHER_IV_LEN);
1589 crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
1590 crypto_cipher_free(cipher);
1591 return (int)(fromlen + CIPHER_IV_LEN);
1594 /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
1595 * with the key in <b>key</b> to the buffer in <b>to</b> of length
1596 * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
1597 * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
1598 * number of bytes written, on failure, return -1.
1601 crypto_cipher_decrypt_with_iv(const char *key,
1602 char *to, size_t tolen,
1603 const char *from, size_t fromlen)
1605 crypto_cipher_t *cipher;
1606 tor_assert(key);
1607 tor_assert(from);
1608 tor_assert(to);
1609 tor_assert(fromlen < INT_MAX);
1611 if (fromlen <= CIPHER_IV_LEN)
1612 return -1;
1613 if (tolen < fromlen - CIPHER_IV_LEN)
1614 return -1;
1616 cipher = crypto_cipher_new_with_iv(key, from);
1618 crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
1619 crypto_cipher_free(cipher);
1620 return (int)(fromlen - CIPHER_IV_LEN);
1623 /* SHA-1 */
1625 /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
1626 * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
1627 * Return 0 on success, 1 on failure.
1630 crypto_digest(char *digest, const char *m, size_t len)
1632 tor_assert(m);
1633 tor_assert(digest);
1634 return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
1637 /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1638 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
1639 * into <b>digest</b>. Return 0 on success, 1 on failure. */
1641 crypto_digest256(char *digest, const char *m, size_t len,
1642 digest_algorithm_t algorithm)
1644 tor_assert(m);
1645 tor_assert(digest);
1646 tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
1647 if (algorithm == DIGEST_SHA256)
1648 return (SHA256((const uint8_t*)m,len,(uint8_t*)digest) == NULL);
1649 else
1650 return (sha3_256((uint8_t *)digest, DIGEST256_LEN,(const uint8_t *)m, len)
1651 == -1);
1654 /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
1655 * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
1656 * into <b>digest</b>. Return 0 on success, 1 on failure. */
1658 crypto_digest512(char *digest, const char *m, size_t len,
1659 digest_algorithm_t algorithm)
1661 tor_assert(m);
1662 tor_assert(digest);
1663 tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
1664 if (algorithm == DIGEST_SHA512)
1665 return (SHA512((const unsigned char*)m,len,(unsigned char*)digest)
1666 == NULL);
1667 else
1668 return (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len)
1669 == -1);
1672 /** Set the common_digests_t in <b>ds_out</b> to contain every digest on the
1673 * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
1674 * success, -1 on failure. */
1676 crypto_common_digests(common_digests_t *ds_out, const char *m, size_t len)
1678 tor_assert(ds_out);
1679 memset(ds_out, 0, sizeof(*ds_out));
1680 if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
1681 return -1;
1682 if (crypto_digest256(ds_out->d[DIGEST_SHA256], m, len, DIGEST_SHA256) < 0)
1683 return -1;
1685 return 0;
1688 /** Return the name of an algorithm, as used in directory documents. */
1689 const char *
1690 crypto_digest_algorithm_get_name(digest_algorithm_t alg)
1692 switch (alg) {
1693 case DIGEST_SHA1:
1694 return "sha1";
1695 case DIGEST_SHA256:
1696 return "sha256";
1697 case DIGEST_SHA512:
1698 return "sha512";
1699 case DIGEST_SHA3_256:
1700 return "sha3-256";
1701 case DIGEST_SHA3_512:
1702 return "sha3-512";
1703 default:
1704 tor_fragile_assert();
1705 return "??unknown_digest??";
1709 /** Given the name of a digest algorithm, return its integer value, or -1 if
1710 * the name is not recognized. */
1712 crypto_digest_algorithm_parse_name(const char *name)
1714 if (!strcmp(name, "sha1"))
1715 return DIGEST_SHA1;
1716 else if (!strcmp(name, "sha256"))
1717 return DIGEST_SHA256;
1718 else if (!strcmp(name, "sha512"))
1719 return DIGEST_SHA512;
1720 else if (!strcmp(name, "sha3-256"))
1721 return DIGEST_SHA3_256;
1722 else if (!strcmp(name, "sha3-512"))
1723 return DIGEST_SHA3_512;
1724 else
1725 return -1;
1728 /** Given an algorithm, return the digest length in bytes. */
1729 static inline size_t
1730 crypto_digest_algorithm_get_length(digest_algorithm_t alg)
1732 switch (alg) {
1733 case DIGEST_SHA1:
1734 return DIGEST_LEN;
1735 case DIGEST_SHA256:
1736 return DIGEST256_LEN;
1737 case DIGEST_SHA512:
1738 return DIGEST512_LEN;
1739 case DIGEST_SHA3_256:
1740 return DIGEST256_LEN;
1741 case DIGEST_SHA3_512:
1742 return DIGEST512_LEN;
1743 default:
1744 tor_assert(0);
1745 return 0; /* Unreachable */
1749 /** Intermediate information about the digest of a stream of data. */
1750 struct crypto_digest_t {
1751 digest_algorithm_t algorithm; /**< Which algorithm is in use? */
1752 /** State for the digest we're using. Only one member of the
1753 * union is usable, depending on the value of <b>algorithm</b>. Note also
1754 * that space for other members might not even be allocated!
1756 union {
1757 SHA_CTX sha1; /**< state for SHA1 */
1758 SHA256_CTX sha2; /**< state for SHA256 */
1759 SHA512_CTX sha512; /**< state for SHA512 */
1760 keccak_state sha3; /**< state for SHA3-[256,512] */
1761 } d;
1765 * Return the number of bytes we need to malloc in order to get a
1766 * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
1767 * when we free one.
1769 static size_t
1770 crypto_digest_alloc_bytes(digest_algorithm_t alg)
1772 /* Helper: returns the number of bytes in the 'f' field of 'st' */
1773 #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
1774 /* Gives the length of crypto_digest_t through the end of the field 'd' */
1775 #define END_OF_FIELD(f) (STRUCT_OFFSET(crypto_digest_t, f) + \
1776 STRUCT_FIELD_SIZE(crypto_digest_t, f))
1777 switch (alg) {
1778 case DIGEST_SHA1:
1779 return END_OF_FIELD(d.sha1);
1780 case DIGEST_SHA256:
1781 return END_OF_FIELD(d.sha2);
1782 case DIGEST_SHA512:
1783 return END_OF_FIELD(d.sha512);
1784 case DIGEST_SHA3_256:
1785 case DIGEST_SHA3_512:
1786 return END_OF_FIELD(d.sha3);
1787 default:
1788 tor_assert(0);
1789 return 0;
1791 #undef END_OF_FIELD
1792 #undef STRUCT_FIELD_SIZE
1795 /** Allocate and return a new digest object to compute SHA1 digests.
1797 crypto_digest_t *
1798 crypto_digest_new(void)
1800 crypto_digest_t *r;
1801 r = tor_malloc(crypto_digest_alloc_bytes(DIGEST_SHA1));
1802 SHA1_Init(&r->d.sha1);
1803 r->algorithm = DIGEST_SHA1;
1804 return r;
1807 /** Allocate and return a new digest object to compute 256-bit digests
1808 * using <b>algorithm</b>. */
1809 crypto_digest_t *
1810 crypto_digest256_new(digest_algorithm_t algorithm)
1812 crypto_digest_t *r;
1813 tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
1814 r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
1815 if (algorithm == DIGEST_SHA256)
1816 SHA256_Init(&r->d.sha2);
1817 else
1818 keccak_digest_init(&r->d.sha3, 256);
1819 r->algorithm = algorithm;
1820 return r;
1823 /** Allocate and return a new digest object to compute 512-bit digests
1824 * using <b>algorithm</b>. */
1825 crypto_digest_t *
1826 crypto_digest512_new(digest_algorithm_t algorithm)
1828 crypto_digest_t *r;
1829 tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
1830 r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
1831 if (algorithm == DIGEST_SHA512)
1832 SHA512_Init(&r->d.sha512);
1833 else
1834 keccak_digest_init(&r->d.sha3, 512);
1835 r->algorithm = algorithm;
1836 return r;
1839 /** Deallocate a digest object.
1841 void
1842 crypto_digest_free(crypto_digest_t *digest)
1844 if (!digest)
1845 return;
1846 size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
1847 memwipe(digest, 0, bytes);
1848 tor_free(digest);
1851 /** Add <b>len</b> bytes from <b>data</b> to the digest object.
1853 void
1854 crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
1855 size_t len)
1857 tor_assert(digest);
1858 tor_assert(data);
1859 /* Using the SHA*_*() calls directly means we don't support doing
1860 * SHA in hardware. But so far the delay of getting the question
1861 * to the hardware, and hearing the answer, is likely higher than
1862 * just doing it ourselves. Hashes are fast.
1864 switch (digest->algorithm) {
1865 case DIGEST_SHA1:
1866 SHA1_Update(&digest->d.sha1, (void*)data, len);
1867 break;
1868 case DIGEST_SHA256:
1869 SHA256_Update(&digest->d.sha2, (void*)data, len);
1870 break;
1871 case DIGEST_SHA512:
1872 SHA512_Update(&digest->d.sha512, (void*)data, len);
1873 break;
1874 case DIGEST_SHA3_256: /* FALLSTHROUGH */
1875 case DIGEST_SHA3_512:
1876 keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
1877 break;
1878 default:
1879 tor_fragile_assert();
1880 break;
1884 /** Compute the hash of the data that has been passed to the digest
1885 * object; write the first out_len bytes of the result to <b>out</b>.
1886 * <b>out_len</b> must be \<= DIGEST512_LEN.
1888 void
1889 crypto_digest_get_digest(crypto_digest_t *digest,
1890 char *out, size_t out_len)
1892 unsigned char r[DIGEST512_LEN];
1893 crypto_digest_t tmpenv;
1894 tor_assert(digest);
1895 tor_assert(out);
1896 tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
1898 /* The SHA-3 code handles copying into a temporary ctx, and also can handle
1899 * short output buffers by truncating appropriately. */
1900 if (digest->algorithm == DIGEST_SHA3_256 ||
1901 digest->algorithm == DIGEST_SHA3_512) {
1902 keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
1903 return;
1906 const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
1907 /* memcpy into a temporary ctx, since SHA*_Final clears the context */
1908 memcpy(&tmpenv, digest, alloc_bytes);
1909 switch (digest->algorithm) {
1910 case DIGEST_SHA1:
1911 SHA1_Final(r, &tmpenv.d.sha1);
1912 break;
1913 case DIGEST_SHA256:
1914 SHA256_Final(r, &tmpenv.d.sha2);
1915 break;
1916 case DIGEST_SHA512:
1917 SHA512_Final(r, &tmpenv.d.sha512);
1918 break;
1919 case DIGEST_SHA3_256: /* FALLSTHROUGH */
1920 case DIGEST_SHA3_512:
1921 log_warn(LD_BUG, "Handling unexpected algorithm %d", digest->algorithm);
1922 tor_assert(0); /* This is fatal, because it should never happen. */
1923 default:
1924 tor_assert(0); /* Unreachable. */
1925 break;
1927 memcpy(out, r, out_len);
1928 memwipe(r, 0, sizeof(r));
1931 /** Allocate and return a new digest object with the same state as
1932 * <b>digest</b>
1934 crypto_digest_t *
1935 crypto_digest_dup(const crypto_digest_t *digest)
1937 tor_assert(digest);
1938 const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
1939 return tor_memdup(digest, alloc_bytes);
1942 /** Replace the state of the digest object <b>into</b> with the state
1943 * of the digest object <b>from</b>. Requires that 'into' and 'from'
1944 * have the same digest type.
1946 void
1947 crypto_digest_assign(crypto_digest_t *into,
1948 const crypto_digest_t *from)
1950 tor_assert(into);
1951 tor_assert(from);
1952 tor_assert(into->algorithm == from->algorithm);
1953 const size_t alloc_bytes = crypto_digest_alloc_bytes(from->algorithm);
1954 memcpy(into,from,alloc_bytes);
1957 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
1958 * at <b>digest_out</b> to the hash of the concatenation of those strings,
1959 * plus the optional string <b>append</b>, computed with the algorithm
1960 * <b>alg</b>.
1961 * <b>out_len</b> must be \<= DIGEST512_LEN. */
1962 void
1963 crypto_digest_smartlist(char *digest_out, size_t len_out,
1964 const smartlist_t *lst,
1965 const char *append,
1966 digest_algorithm_t alg)
1968 crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
1971 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
1972 * at <b>digest_out</b> to the hash of the concatenation of: the
1973 * optional string <b>prepend</b>, those strings,
1974 * and the optional string <b>append</b>, computed with the algorithm
1975 * <b>alg</b>.
1976 * <b>len_out</b> must be \<= DIGEST512_LEN. */
1977 void
1978 crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
1979 const char *prepend,
1980 const smartlist_t *lst,
1981 const char *append,
1982 digest_algorithm_t alg)
1984 crypto_digest_t *d = NULL;
1985 switch (alg) {
1986 case DIGEST_SHA1:
1987 d = crypto_digest_new();
1988 break;
1989 case DIGEST_SHA256: /* FALLSTHROUGH */
1990 case DIGEST_SHA3_256:
1991 d = crypto_digest256_new(alg);
1992 break;
1993 case DIGEST_SHA512: /* FALLSTHROUGH */
1994 case DIGEST_SHA3_512:
1995 d = crypto_digest512_new(alg);
1996 break;
1997 default:
1998 log_warn(LD_BUG, "Called with unknown algorithm %d", alg);
1999 /* If fragile_assert is not enabled, wipe output and return
2000 * without running any calculations */
2001 memwipe(digest_out, 0xff, len_out);
2002 tor_fragile_assert();
2003 goto free;
2005 if (prepend)
2006 crypto_digest_add_bytes(d, prepend, strlen(prepend));
2007 SMARTLIST_FOREACH(lst, const char *, cp,
2008 crypto_digest_add_bytes(d, cp, strlen(cp)));
2009 if (append)
2010 crypto_digest_add_bytes(d, append, strlen(append));
2011 crypto_digest_get_digest(d, digest_out, len_out);
2013 free:
2014 crypto_digest_free(d);
2017 /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
2018 * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
2019 * result in <b>hmac_out</b>. Asserts on failure.
2021 void
2022 crypto_hmac_sha256(char *hmac_out,
2023 const char *key, size_t key_len,
2024 const char *msg, size_t msg_len)
2026 unsigned char *rv = NULL;
2027 /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
2028 tor_assert(key_len < INT_MAX);
2029 tor_assert(msg_len < INT_MAX);
2030 tor_assert(hmac_out);
2031 rv = HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
2032 (unsigned char*)hmac_out, NULL);
2033 tor_assert(rv);
2036 /** Internal state for a eXtendable-Output Function (XOF). */
2037 struct crypto_xof_t {
2038 keccak_state s;
2041 /** Allocate a new XOF object backed by SHAKE-256. The security level
2042 * provided is a function of the length of the output used. Read and
2043 * understand FIPS-202 A.2 "Additional Consideration for Extendable-Output
2044 * Functions" before using this construct.
2046 crypto_xof_t *
2047 crypto_xof_new(void)
2049 crypto_xof_t *xof;
2050 xof = tor_malloc(sizeof(crypto_xof_t));
2051 keccak_xof_init(&xof->s, 256);
2052 return xof;
2055 /** Absorb bytes into a XOF object. Must not be called after a call to
2056 * crypto_xof_squeeze_bytes() for the same instance, and will assert
2057 * if attempted.
2059 void
2060 crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
2062 int i = keccak_xof_absorb(&xof->s, data, len);
2063 tor_assert(i == 0);
2066 /** Squeeze bytes out of a XOF object. Calling this routine will render
2067 * the XOF instance ineligible to absorb further data.
2069 void
2070 crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
2072 int i = keccak_xof_squeeze(&xof->s, out, len);
2073 tor_assert(i == 0);
2076 /** Cleanse and deallocate a XOF object. */
2077 void
2078 crypto_xof_free(crypto_xof_t *xof)
2080 if (!xof)
2081 return;
2082 memwipe(xof, 0, sizeof(crypto_xof_t));
2083 tor_free(xof);
2086 /* DH */
2088 /** Our DH 'g' parameter */
2089 #define DH_GENERATOR 2
2091 /** Shared P parameter for our circuit-crypto DH key exchanges. */
2092 static BIGNUM *dh_param_p = NULL;
2093 /** Shared P parameter for our TLS DH key exchanges. */
2094 static BIGNUM *dh_param_p_tls = NULL;
2095 /** Shared G parameter for our DH key exchanges. */
2096 static BIGNUM *dh_param_g = NULL;
2098 /** Validate a given set of Diffie-Hellman parameters. This is moderately
2099 * computationally expensive (milliseconds), so should only be called when
2100 * the DH parameters change. Returns 0 on success, * -1 on failure.
2102 static int
2103 crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
2105 DH *dh = NULL;
2106 int ret = -1;
2108 /* Copy into a temporary DH object. */
2109 if (!(dh = DH_new()))
2110 goto out;
2111 if (!(dh->p = BN_dup(p)))
2112 goto out;
2113 if (!(dh->g = BN_dup(g)))
2114 goto out;
2116 /* Perform the validation. */
2117 int codes = 0;
2118 if (!DH_check(dh, &codes))
2119 goto out;
2120 if (BN_is_word(dh->g, DH_GENERATOR_2)) {
2121 /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
2123 * OpenSSL checks the prime is congruent to 11 when g = 2; while the
2124 * IETF's primes are congruent to 23 when g = 2.
2126 BN_ULONG residue = BN_mod_word(dh->p, 24);
2127 if (residue == 11 || residue == 23)
2128 codes &= ~DH_NOT_SUITABLE_GENERATOR;
2130 if (codes != 0) /* Specifics on why the params suck is irrelevant. */
2131 goto out;
2133 /* Things are probably not evil. */
2134 ret = 0;
2136 out:
2137 if (dh)
2138 DH_free(dh);
2139 return ret;
2142 /** Set the global Diffie-Hellman generator, used for both TLS and internal
2143 * DH stuff.
2145 static void
2146 crypto_set_dh_generator(void)
2148 BIGNUM *generator;
2149 int r;
2151 if (dh_param_g)
2152 return;
2154 generator = BN_new();
2155 tor_assert(generator);
2157 r = BN_set_word(generator, DH_GENERATOR);
2158 tor_assert(r);
2160 dh_param_g = generator;
2163 /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
2164 * modulus. */
2165 void
2166 crypto_set_tls_dh_prime(void)
2168 BIGNUM *tls_prime = NULL;
2169 int r;
2171 /* If the space is occupied, free the previous TLS DH prime */
2172 if (dh_param_p_tls) {
2173 BN_clear_free(dh_param_p_tls);
2174 dh_param_p_tls = NULL;
2177 tls_prime = BN_new();
2178 tor_assert(tls_prime);
2180 /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
2181 * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
2182 * prime.
2184 r = BN_hex2bn(&tls_prime,
2185 "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
2186 "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
2187 "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
2188 "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
2189 "B0E7393E0F24218EB3");
2190 tor_assert(r);
2192 tor_assert(tls_prime);
2194 dh_param_p_tls = tls_prime;
2195 crypto_set_dh_generator();
2196 tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
2199 /** Initialize dh_param_p and dh_param_g if they are not already
2200 * set. */
2201 static void
2202 init_dh_param(void)
2204 BIGNUM *circuit_dh_prime;
2205 int r;
2206 if (dh_param_p && dh_param_g)
2207 return;
2209 circuit_dh_prime = BN_new();
2210 tor_assert(circuit_dh_prime);
2212 /* This is from rfc2409, section 6.2. It's a safe prime, and
2213 supposedly it equals:
2214 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
2216 r = BN_hex2bn(&circuit_dh_prime,
2217 "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
2218 "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
2219 "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
2220 "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
2221 "49286651ECE65381FFFFFFFFFFFFFFFF");
2222 tor_assert(r);
2224 /* Set the new values as the global DH parameters. */
2225 dh_param_p = circuit_dh_prime;
2226 crypto_set_dh_generator();
2227 tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
2229 if (!dh_param_p_tls) {
2230 crypto_set_tls_dh_prime();
2234 /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
2235 * handshake. Since we exponentiate by this value, choosing a smaller one
2236 * lets our handhake go faster.
2238 #define DH_PRIVATE_KEY_BITS 320
2240 /** Allocate and return a new DH object for a key exchange. Returns NULL on
2241 * failure.
2243 crypto_dh_t *
2244 crypto_dh_new(int dh_type)
2246 crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
2248 tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
2249 dh_type == DH_TYPE_REND);
2251 if (!dh_param_p)
2252 init_dh_param();
2254 if (!(res->dh = DH_new()))
2255 goto err;
2257 if (dh_type == DH_TYPE_TLS) {
2258 if (!(res->dh->p = BN_dup(dh_param_p_tls)))
2259 goto err;
2260 } else {
2261 if (!(res->dh->p = BN_dup(dh_param_p)))
2262 goto err;
2265 if (!(res->dh->g = BN_dup(dh_param_g)))
2266 goto err;
2268 res->dh->length = DH_PRIVATE_KEY_BITS;
2270 return res;
2271 err:
2272 crypto_log_errors(LOG_WARN, "creating DH object");
2273 if (res->dh) DH_free(res->dh); /* frees p and g too */
2274 tor_free(res);
2275 return NULL;
2278 /** Return a copy of <b>dh</b>, sharing its internal state. */
2279 crypto_dh_t *
2280 crypto_dh_dup(const crypto_dh_t *dh)
2282 crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
2283 tor_assert(dh);
2284 tor_assert(dh->dh);
2285 dh_new->dh = dh->dh;
2286 DH_up_ref(dh->dh);
2287 return dh_new;
2290 /** Return the length of the DH key in <b>dh</b>, in bytes.
2293 crypto_dh_get_bytes(crypto_dh_t *dh)
2295 tor_assert(dh);
2296 return DH_size(dh->dh);
2299 /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
2300 * success, -1 on failure.
2303 crypto_dh_generate_public(crypto_dh_t *dh)
2305 again:
2306 if (!DH_generate_key(dh->dh)) {
2307 crypto_log_errors(LOG_WARN, "generating DH key");
2308 return -1;
2310 if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
2311 log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
2312 "the-universe chances really do happen. Trying again.");
2313 /* Free and clear the keys, so OpenSSL will actually try again. */
2314 BN_clear_free(dh->dh->pub_key);
2315 BN_clear_free(dh->dh->priv_key);
2316 dh->dh->pub_key = dh->dh->priv_key = NULL;
2317 goto again;
2319 return 0;
2322 /** Generate g^x as necessary, and write the g^x for the key exchange
2323 * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
2324 * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
2327 crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
2329 int bytes;
2330 tor_assert(dh);
2331 if (!dh->dh->pub_key) {
2332 if (crypto_dh_generate_public(dh)<0)
2333 return -1;
2336 tor_assert(dh->dh->pub_key);
2337 bytes = BN_num_bytes(dh->dh->pub_key);
2338 tor_assert(bytes >= 0);
2339 if (pubkey_len < (size_t)bytes) {
2340 log_warn(LD_CRYPTO,
2341 "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
2342 (int) pubkey_len, bytes);
2343 return -1;
2346 memset(pubkey, 0, pubkey_len);
2347 BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
2349 return 0;
2352 /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
2353 * okay (in the subgroup [2,p-2]), or -1 if it's bad.
2354 * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
2356 static int
2357 tor_check_dh_key(int severity, BIGNUM *bn)
2359 BIGNUM *x;
2360 char *s;
2361 tor_assert(bn);
2362 x = BN_new();
2363 tor_assert(x);
2364 if (!dh_param_p)
2365 init_dh_param();
2366 BN_set_word(x, 1);
2367 if (BN_cmp(bn,x)<=0) {
2368 log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
2369 goto err;
2371 BN_copy(x,dh_param_p);
2372 BN_sub_word(x, 1);
2373 if (BN_cmp(bn,x)>=0) {
2374 log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
2375 goto err;
2377 BN_clear_free(x);
2378 return 0;
2379 err:
2380 BN_clear_free(x);
2381 s = BN_bn2hex(bn);
2382 log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
2383 OPENSSL_free(s);
2384 return -1;
2387 #undef MIN
2388 #define MIN(a,b) ((a)<(b)?(a):(b))
2389 /** Given a DH key exchange object, and our peer's value of g^y (as a
2390 * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
2391 * <b>secret_bytes_out</b> bytes of shared key material and write them
2392 * to <b>secret_out</b>. Return the number of bytes generated on success,
2393 * or -1 on failure.
2395 * (We generate key material by computing
2396 * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
2397 * where || is concatenation.)
2399 ssize_t
2400 crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
2401 const char *pubkey, size_t pubkey_len,
2402 char *secret_out, size_t secret_bytes_out)
2404 char *secret_tmp = NULL;
2405 BIGNUM *pubkey_bn = NULL;
2406 size_t secret_len=0, secret_tmp_len=0;
2407 int result=0;
2408 tor_assert(dh);
2409 tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
2410 tor_assert(pubkey_len < INT_MAX);
2412 if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
2413 (int)pubkey_len, NULL)))
2414 goto error;
2415 if (tor_check_dh_key(severity, pubkey_bn)<0) {
2416 /* Check for invalid public keys. */
2417 log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
2418 goto error;
2420 secret_tmp_len = crypto_dh_get_bytes(dh);
2421 secret_tmp = tor_malloc(secret_tmp_len);
2422 result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
2423 if (result < 0) {
2424 log_warn(LD_CRYPTO,"DH_compute_key() failed.");
2425 goto error;
2427 secret_len = result;
2428 if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
2429 (uint8_t*)secret_out, secret_bytes_out)<0)
2430 goto error;
2431 secret_len = secret_bytes_out;
2433 goto done;
2434 error:
2435 result = -1;
2436 done:
2437 crypto_log_errors(LOG_WARN, "completing DH handshake");
2438 if (pubkey_bn)
2439 BN_clear_free(pubkey_bn);
2440 if (secret_tmp) {
2441 memwipe(secret_tmp, 0, secret_tmp_len);
2442 tor_free(secret_tmp);
2444 if (result < 0)
2445 return result;
2446 else
2447 return secret_len;
2450 /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
2451 * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
2452 * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
2453 * H(K | [00]) | H(K | [01]) | ....
2455 * This is the key expansion algorithm used in the "TAP" circuit extension
2456 * mechanism; it shouldn't be used for new protocols.
2458 * Return 0 on success, -1 on failure.
2461 crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
2462 uint8_t *key_out, size_t key_out_len)
2464 int i, r = -1;
2465 uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
2466 uint8_t digest[DIGEST_LEN];
2468 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2469 tor_assert(key_out_len <= DIGEST_LEN*256);
2471 memcpy(tmp, key_in, key_in_len);
2472 for (cp = key_out, i=0; cp < key_out+key_out_len;
2473 ++i, cp += DIGEST_LEN) {
2474 tmp[key_in_len] = i;
2475 if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1))
2476 goto exit;
2477 memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
2480 r = 0;
2481 exit:
2482 memwipe(tmp, 0, key_in_len+1);
2483 tor_free(tmp);
2484 memwipe(digest, 0, sizeof(digest));
2485 return r;
2488 /** Expand some secret key material according to RFC5869, using SHA256 as the
2489 * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
2490 * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
2491 * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
2492 * and "info" parameters respectively. On success, write <b>key_out_len</b>
2493 * bytes to <b>key_out</b> and return 0. Assert on failure.
2496 crypto_expand_key_material_rfc5869_sha256(
2497 const uint8_t *key_in, size_t key_in_len,
2498 const uint8_t *salt_in, size_t salt_in_len,
2499 const uint8_t *info_in, size_t info_in_len,
2500 uint8_t *key_out, size_t key_out_len)
2502 uint8_t prk[DIGEST256_LEN];
2503 uint8_t tmp[DIGEST256_LEN + 128 + 1];
2504 uint8_t mac[DIGEST256_LEN];
2505 int i;
2506 uint8_t *outp;
2507 size_t tmp_len;
2509 crypto_hmac_sha256((char*)prk,
2510 (const char*)salt_in, salt_in_len,
2511 (const char*)key_in, key_in_len);
2513 /* If we try to get more than this amount of key data, we'll repeat blocks.*/
2514 tor_assert(key_out_len <= DIGEST256_LEN * 256);
2515 tor_assert(info_in_len <= 128);
2516 memset(tmp, 0, sizeof(tmp));
2517 outp = key_out;
2518 i = 1;
2520 while (key_out_len) {
2521 size_t n;
2522 if (i > 1) {
2523 memcpy(tmp, mac, DIGEST256_LEN);
2524 memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
2525 tmp[DIGEST256_LEN+info_in_len] = i;
2526 tmp_len = DIGEST256_LEN + info_in_len + 1;
2527 } else {
2528 memcpy(tmp, info_in, info_in_len);
2529 tmp[info_in_len] = i;
2530 tmp_len = info_in_len + 1;
2532 crypto_hmac_sha256((char*)mac,
2533 (const char*)prk, DIGEST256_LEN,
2534 (const char*)tmp, tmp_len);
2535 n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
2536 memcpy(outp, mac, n);
2537 key_out_len -= n;
2538 outp += n;
2539 ++i;
2542 memwipe(tmp, 0, sizeof(tmp));
2543 memwipe(mac, 0, sizeof(mac));
2544 return 0;
2547 /** Free a DH key exchange object.
2549 void
2550 crypto_dh_free(crypto_dh_t *dh)
2552 if (!dh)
2553 return;
2554 tor_assert(dh->dh);
2555 DH_free(dh->dh);
2556 tor_free(dh);
2559 /* random numbers */
2561 /** How many bytes of entropy we add at once.
2563 * This is how much entropy OpenSSL likes to add right now, so maybe it will
2564 * work for us too. */
2565 #define ADD_ENTROPY 32
2567 /** Set the seed of the weak RNG to a random value. */
2568 void
2569 crypto_seed_weak_rng(tor_weak_rng_t *rng)
2571 unsigned seed;
2572 crypto_rand((void*)&seed, sizeof(seed));
2573 tor_init_weak_random(rng, seed);
2576 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2577 * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
2578 * failure. A maximum request size of 256 bytes is imposed.
2580 static int
2581 crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
2583 tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
2585 #if defined(_WIN32)
2586 static int provider_set = 0;
2587 static HCRYPTPROV provider;
2589 if (!provider_set) {
2590 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
2591 CRYPT_VERIFYCONTEXT)) {
2592 log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
2593 return -1;
2595 provider_set = 1;
2597 if (!CryptGenRandom(provider, out_len, out)) {
2598 log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
2599 return -1;
2602 return 0;
2603 #elif defined(__linux__) && defined(SYS_getrandom)
2604 static int getrandom_works = 1; /* Be optimitic about our chances... */
2606 /* getrandom() isn't as straight foward as getentropy(), and has
2607 * no glibc wrapper.
2609 * As far as I can tell from getrandom(2) and the source code, the
2610 * requests we issue will always succeed (though it will block on the
2611 * call if /dev/urandom isn't seeded yet), since we are NOT specifying
2612 * GRND_NONBLOCK and the request is <= 256 bytes.
2614 * The manpage is unclear on what happens if a signal interrupts the call
2615 * while the request is blocked due to lack of entropy....
2617 * We optimistically assume that getrandom() is available and functional
2618 * because it is the way of the future, and 2 branch mispredicts pale in
2619 * comparision to the overheads involved with failing to open
2620 * /dev/srandom followed by opening and reading from /dev/urandom.
2622 if (PREDICT_LIKELY(getrandom_works)) {
2623 long ret;
2624 /* A flag of '0' here means to read from '/dev/urandom', and to
2625 * block if insufficient entropy is available to service the
2626 * request.
2628 const unsigned int flags = 0;
2629 do {
2630 ret = syscall(SYS_getrandom, out, out_len, flags);
2631 } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
2633 if (PREDICT_UNLIKELY(ret == -1)) {
2634 tor_assert(errno != EAGAIN);
2635 tor_assert(errno != EINTR);
2637 /* Probably ENOSYS. */
2638 log_warn(LD_CRYPTO, "Can't get entropy from getrandom().");
2639 getrandom_works = 0; /* Don't bother trying again. */
2640 return -1;
2643 tor_assert(ret == (long)out_len);
2644 return 0;
2647 return -1; /* getrandom() previously failed unexpectedly. */
2648 #elif defined(HAVE_GETENTROPY)
2649 /* getentropy() is what Linux's getrandom() wants to be when it grows up.
2650 * the only gotcha is that requests are limited to 256 bytes.
2652 return getentropy(out, out_len);
2653 #else
2654 (void) out;
2655 #endif
2657 /* This platform doesn't have a supported syscall based random. */
2658 return -1;
2661 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2662 * via the per-platform fallback mechanism, storing it into <b>out</b>.
2663 * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
2664 * is imposed.
2666 static int
2667 crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
2669 #ifdef _WIN32
2670 /* Windows exclusively uses crypto_strongest_rand_syscall(). */
2671 (void)out;
2672 (void)out_len;
2673 return -1;
2674 #else
2675 static const char *filenames[] = {
2676 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
2678 int fd, i;
2679 size_t n;
2681 for (i = 0; filenames[i]; ++i) {
2682 log_debug(LD_FS, "Opening %s for entropy", filenames[i]);
2683 fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
2684 if (fd<0) continue;
2685 log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
2686 n = read_all(fd, (char*)out, out_len, 0);
2687 close(fd);
2688 if (n != out_len) {
2689 log_warn(LD_CRYPTO,
2690 "Error reading from entropy source (read only %lu bytes).",
2691 (unsigned long)n);
2692 return -1;
2695 return 0;
2698 return -1;
2699 #endif
2702 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2703 * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
2704 * request size of 256 bytes is imposed.
2706 static int
2707 crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
2709 static const size_t sanity_min_size = 16;
2710 static const int max_attempts = 3;
2711 tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
2713 /* For buffers >= 16 bytes (128 bits), we sanity check the output by
2714 * zero filling the buffer and ensuring that it actually was at least
2715 * partially modified.
2717 * Checking that any individual byte is non-zero seems like it would
2718 * fail too often (p = out_len * 1/256) for comfort, but this is an
2719 * "adjust according to taste" sort of check.
2721 memwipe(out, 0, out_len);
2722 for (int i = 0; i < max_attempts; i++) {
2723 /* Try to use the syscall/OS favored mechanism to get strong entropy. */
2724 if (crypto_strongest_rand_syscall(out, out_len) != 0) {
2725 /* Try to use the less-favored mechanism to get strong entropy. */
2726 if (crypto_strongest_rand_fallback(out, out_len) != 0) {
2727 /* Welp, we tried. Hopefully the calling code terminates the process
2728 * since we're basically boned without good entropy.
2730 log_warn(LD_CRYPTO,
2731 "Cannot get strong entropy: no entropy source found.");
2732 return -1;
2736 if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
2737 return 0;
2740 /* We tried max_attempts times to fill a buffer >= 128 bits long,
2741 * and each time it returned all '0's. Either the system entropy
2742 * source is busted, or the user should go out and buy a ticket to
2743 * every lottery on the planet.
2745 log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
2746 return -1;
2749 /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
2750 * storing it into <b>out</b>.
2752 void
2753 crypto_strongest_rand(uint8_t *out, size_t out_len)
2755 #define DLEN SHA512_DIGEST_LENGTH
2756 /* We're going to hash DLEN bytes from the system RNG together with some
2757 * bytes from the openssl PRNG, in order to yield DLEN bytes.
2759 uint8_t inp[DLEN*2];
2760 uint8_t tmp[DLEN];
2761 tor_assert(out);
2762 while (out_len) {
2763 crypto_rand((char*) inp, DLEN);
2764 if (crypto_strongest_rand_raw(inp+DLEN, DLEN) < 0) {
2765 log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
2766 "important key. Exiting.");
2767 /* Die with an assertion so we get a stack trace. */
2768 tor_assert(0);
2770 if (out_len >= DLEN) {
2771 SHA512(inp, sizeof(inp), out);
2772 out += DLEN;
2773 out_len -= DLEN;
2774 } else {
2775 SHA512(inp, sizeof(inp), tmp);
2776 memcpy(out, tmp, out_len);
2777 break;
2780 memwipe(tmp, 0, sizeof(tmp));
2781 memwipe(inp, 0, sizeof(inp));
2782 #undef DLEN
2785 /** Seed OpenSSL's random number generator with bytes from the operating
2786 * system. Return 0 on success, -1 on failure.
2789 crypto_seed_rng(void)
2791 int rand_poll_ok = 0, load_entropy_ok = 0;
2792 uint8_t buf[ADD_ENTROPY];
2794 /* OpenSSL has a RAND_poll function that knows about more kinds of
2795 * entropy than we do. We'll try calling that, *and* calling our own entropy
2796 * functions. If one succeeds, we'll accept the RNG as seeded. */
2797 rand_poll_ok = RAND_poll();
2798 if (rand_poll_ok == 0)
2799 log_warn(LD_CRYPTO, "RAND_poll() failed.");
2801 load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
2802 if (load_entropy_ok) {
2803 RAND_seed(buf, sizeof(buf));
2806 memwipe(buf, 0, sizeof(buf));
2808 if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
2809 return 0;
2810 else
2811 return -1;
2814 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
2815 * for unit tests.
2817 * This function is not allowed to fail; if it would fail to generate strong
2818 * entropy, it must terminate the process instead.
2820 MOCK_IMPL(void,
2821 crypto_rand, (char *to, size_t n))
2823 crypto_rand_unmocked(to, n);
2826 /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
2827 * will want crypto_rand instead.
2829 * This function is not allowed to fail; if it would fail to generate strong
2830 * entropy, it must terminate the process instead.
2832 void
2833 crypto_rand_unmocked(char *to, size_t n)
2835 int r;
2836 if (n == 0)
2837 return;
2839 tor_assert(n < INT_MAX);
2840 tor_assert(to);
2841 r = RAND_bytes((unsigned char*)to, (int)n);
2842 /* We consider a PRNG failure non-survivable. Let's assert so that we get a
2843 * stack trace about where it happened.
2845 tor_assert(r >= 0);
2848 /** Return a pseudorandom integer, chosen uniformly from the values
2849 * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
2850 * INT_MAX+1, inclusive. */
2852 crypto_rand_int(unsigned int max)
2854 unsigned int val;
2855 unsigned int cutoff;
2856 tor_assert(max <= ((unsigned int)INT_MAX)+1);
2857 tor_assert(max > 0); /* don't div by 0 */
2859 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2860 * distribution with clipping at the upper end of unsigned int's
2861 * range.
2863 cutoff = UINT_MAX - (UINT_MAX%max);
2864 while (1) {
2865 crypto_rand((char*)&val, sizeof(val));
2866 if (val < cutoff)
2867 return val % max;
2871 /** Return a pseudorandom integer, chosen uniformly from the values i such
2872 * that min <= i < max.
2874 * <b>min</b> MUST be in range [0, <b>max</b>).
2875 * <b>max</b> MUST be in range (min, INT_MAX].
2878 crypto_rand_int_range(unsigned int min, unsigned int max)
2880 tor_assert(min < max);
2881 tor_assert(max <= INT_MAX);
2883 /* The overflow is avoided here because crypto_rand_int() returns a value
2884 * between 0 and (max - min) inclusive. */
2885 return min + crypto_rand_int(max - min);
2888 /** As crypto_rand_int_range, but supports uint64_t. */
2889 uint64_t
2890 crypto_rand_uint64_range(uint64_t min, uint64_t max)
2892 tor_assert(min < max);
2893 return min + crypto_rand_uint64(max - min);
2896 /** As crypto_rand_int_range, but supports time_t. */
2897 time_t
2898 crypto_rand_time_range(time_t min, time_t max)
2900 tor_assert(min < max);
2901 return min + (time_t)crypto_rand_uint64(max - min);
2904 /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
2905 * between 0 and <b>max</b>-1 inclusive. */
2906 uint64_t
2907 crypto_rand_uint64(uint64_t max)
2909 uint64_t val;
2910 uint64_t cutoff;
2911 tor_assert(max < UINT64_MAX);
2912 tor_assert(max > 0); /* don't div by 0 */
2914 /* We ignore any values that are >= 'cutoff,' to avoid biasing the
2915 * distribution with clipping at the upper end of unsigned int's
2916 * range.
2918 cutoff = UINT64_MAX - (UINT64_MAX%max);
2919 while (1) {
2920 crypto_rand((char*)&val, sizeof(val));
2921 if (val < cutoff)
2922 return val % max;
2926 /** Return a pseudorandom double d, chosen uniformly from the range
2927 * 0.0 <= d < 1.0.
2929 double
2930 crypto_rand_double(void)
2932 /* We just use an unsigned int here; we don't really care about getting
2933 * more than 32 bits of resolution */
2934 unsigned int uint;
2935 crypto_rand((char*)&uint, sizeof(uint));
2936 #if SIZEOF_INT == 4
2937 #define UINT_MAX_AS_DOUBLE 4294967296.0
2938 #elif SIZEOF_INT == 8
2939 #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
2940 #else
2941 #error SIZEOF_INT is neither 4 nor 8
2942 #endif
2943 return ((double)uint) / UINT_MAX_AS_DOUBLE;
2946 /** Generate and return a new random hostname starting with <b>prefix</b>,
2947 * ending with <b>suffix</b>, and containing no fewer than
2948 * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
2949 * characters. Does not check for failure.
2951 * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
2953 char *
2954 crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
2955 const char *suffix)
2957 char *result, *rand_bytes;
2958 int randlen, rand_bytes_len;
2959 size_t resultlen, prefixlen;
2961 if (max_rand_len > MAX_DNS_LABEL_SIZE)
2962 max_rand_len = MAX_DNS_LABEL_SIZE;
2963 if (min_rand_len > max_rand_len)
2964 min_rand_len = max_rand_len;
2966 randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
2968 prefixlen = strlen(prefix);
2969 resultlen = prefixlen + strlen(suffix) + randlen + 16;
2971 rand_bytes_len = ((randlen*5)+7)/8;
2972 if (rand_bytes_len % 5)
2973 rand_bytes_len += 5 - (rand_bytes_len%5);
2974 rand_bytes = tor_malloc(rand_bytes_len);
2975 crypto_rand(rand_bytes, rand_bytes_len);
2977 result = tor_malloc(resultlen);
2978 memcpy(result, prefix, prefixlen);
2979 base32_encode(result+prefixlen, resultlen-prefixlen,
2980 rand_bytes, rand_bytes_len);
2981 tor_free(rand_bytes);
2982 strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
2984 return result;
2987 /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
2988 * is empty. */
2989 void *
2990 smartlist_choose(const smartlist_t *sl)
2992 int len = smartlist_len(sl);
2993 if (len)
2994 return smartlist_get(sl,crypto_rand_int(len));
2995 return NULL; /* no elements to choose from */
2998 /** Scramble the elements of <b>sl</b> into a random order. */
2999 void
3000 smartlist_shuffle(smartlist_t *sl)
3002 int i;
3003 /* From the end of the list to the front, choose at random from the
3004 positions we haven't looked at yet, and swap that position into the
3005 current position. Remember to give "no swap" the same probability as
3006 any other swap. */
3007 for (i = smartlist_len(sl)-1; i > 0; --i) {
3008 int j = crypto_rand_int(i+1);
3009 smartlist_swap(sl, i, j);
3014 * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
3015 * the value <b>byte</b>.
3016 * If <b>mem</b> is NULL or <b>sz</b> is zero, nothing happens.
3018 * This function is preferable to memset, since many compilers will happily
3019 * optimize out memset() when they can convince themselves that the data being
3020 * cleared will never be read.
3022 * Right now, our convention is to use this function when we are wiping data
3023 * that's about to become inaccessible, such as stack buffers that are about
3024 * to go out of scope or structures that are about to get freed. (In
3025 * practice, it appears that the compilers we're currently using will optimize
3026 * out the memset()s for stack-allocated buffers, but not those for
3027 * about-to-be-freed structures. That could change, though, so we're being
3028 * wary.) If there are live reads for the data, then you can just use
3029 * memset().
3031 void
3032 memwipe(void *mem, uint8_t byte, size_t sz)
3034 if (sz == 0) {
3035 return;
3037 /* If sz is nonzero, then mem must not be NULL. */
3038 tor_assert(mem != NULL);
3040 /* Data this large is likely to be an underflow. */
3041 tor_assert(sz < SIZE_T_CEILING);
3043 /* Because whole-program-optimization exists, we may not be able to just
3044 * have this function call "memset". A smart compiler could inline it, then
3045 * eliminate dead memsets, and declare itself to be clever. */
3047 #if defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY)
3048 /* Here's what you do on windows. */
3049 SecureZeroMemory(mem,sz);
3050 #elif defined(HAVE_RTLSECUREZEROMEMORY)
3051 RtlSecureZeroMemory(mem,sz);
3052 #elif defined(HAVE_EXPLICIT_BZERO)
3053 /* The BSDs provide this. */
3054 explicit_bzero(mem, sz);
3055 #elif defined(HAVE_MEMSET_S)
3056 /* This is in the C99 standard. */
3057 memset_s(mem, sz, 0, sz);
3058 #else
3059 /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
3060 * based on the pointer value, then uses that junk to update a global
3061 * variable. It's an elaborate ruse to trick the compiler into not
3062 * optimizing out the "wipe this memory" code. Read it if you like zany
3063 * programming tricks! In later versions of Tor, we should look for better
3064 * not-optimized-out memory wiping stuff...
3066 * ...or maybe not. In practice, there are pure-asm implementations of
3067 * OPENSSL_cleanse() on most platforms, which ought to do the job.
3070 OPENSSL_cleanse(mem, sz);
3071 #endif
3073 /* Just in case some caller of memwipe() is relying on getting a buffer
3074 * filled with a particular value, fill the buffer.
3076 * If this function gets inlined, this memset might get eliminated, but
3077 * that's okay: We only care about this particular memset in the case where
3078 * the caller should have been using memset(), and the memset() wouldn't get
3079 * eliminated. In other words, this is here so that we won't break anything
3080 * if somebody accidentally calls memwipe() instead of memset().
3082 memset(mem, byte, sz);
3085 #ifndef OPENSSL_THREADS
3086 #error OpenSSL has been built without thread support. Tor requires an \
3087 OpenSSL library with thread support enabled.
3088 #endif
3090 #ifndef NEW_THREAD_API
3091 /** Helper: OpenSSL uses this callback to manipulate mutexes. */
3092 static void
3093 openssl_locking_cb_(int mode, int n, const char *file, int line)
3095 (void)file;
3096 (void)line;
3097 if (!openssl_mutexes_)
3098 /* This is not a really good fix for the
3099 * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
3100 * it can't hurt. */
3101 return;
3102 if (mode & CRYPTO_LOCK)
3103 tor_mutex_acquire(openssl_mutexes_[n]);
3104 else
3105 tor_mutex_release(openssl_mutexes_[n]);
3108 static void
3109 tor_set_openssl_thread_id(CRYPTO_THREADID *threadid)
3111 CRYPTO_THREADID_set_numeric(threadid, tor_get_thread_id());
3113 #endif
3115 #if 0
3116 /* This code is disabled, because OpenSSL never actually uses these callbacks.
3119 /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
3120 * as a lock. */
3121 struct CRYPTO_dynlock_value {
3122 tor_mutex_t *lock;
3125 /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
3126 * documentation in OpenSSL's docs for more info. */
3127 static struct CRYPTO_dynlock_value *
3128 openssl_dynlock_create_cb_(const char *file, int line)
3130 struct CRYPTO_dynlock_value *v;
3131 (void)file;
3132 (void)line;
3133 v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
3134 v->lock = tor_mutex_new();
3135 return v;
3138 /** OpenSSL callback function to acquire or release a lock: see
3139 * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
3140 static void
3141 openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
3142 const char *file, int line)
3144 (void)file;
3145 (void)line;
3146 if (mode & CRYPTO_LOCK)
3147 tor_mutex_acquire(v->lock);
3148 else
3149 tor_mutex_release(v->lock);
3152 /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
3153 * documentation in OpenSSL's docs for more info. */
3154 static void
3155 openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
3156 const char *file, int line)
3158 (void)file;
3159 (void)line;
3160 tor_mutex_free(v->lock);
3161 tor_free(v);
3163 #endif
3165 /** @{ */
3166 /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
3167 * multithreaded. Returns 0. */
3168 static int
3169 setup_openssl_threading(void)
3171 #ifndef NEW_THREAD_API
3172 int i;
3173 int n = CRYPTO_num_locks();
3174 n_openssl_mutexes_ = n;
3175 openssl_mutexes_ = tor_calloc(n, sizeof(tor_mutex_t *));
3176 for (i=0; i < n; ++i)
3177 openssl_mutexes_[i] = tor_mutex_new();
3178 CRYPTO_set_locking_callback(openssl_locking_cb_);
3179 CRYPTO_THREADID_set_callback(tor_set_openssl_thread_id);
3180 #endif
3181 #if 0
3182 CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_);
3183 CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_);
3184 CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_);
3185 #endif
3186 return 0;
3189 /** Uninitialize the crypto library. Return 0 on success. Does not detect
3190 * failure.
3193 crypto_global_cleanup(void)
3195 EVP_cleanup();
3196 #ifdef NEW_THREAD_API
3197 ERR_remove_thread_state();
3198 #else
3199 ERR_remove_thread_state(NULL);
3200 #endif
3201 ERR_free_strings();
3203 if (dh_param_p)
3204 BN_clear_free(dh_param_p);
3205 if (dh_param_p_tls)
3206 BN_clear_free(dh_param_p_tls);
3207 if (dh_param_g)
3208 BN_clear_free(dh_param_g);
3210 #ifndef DISABLE_ENGINES
3211 ENGINE_cleanup();
3212 #endif
3214 CONF_modules_unload(1);
3215 CRYPTO_cleanup_all_ex_data();
3217 #ifndef NEW_THREAD_API
3218 if (n_openssl_mutexes_) {
3219 int n = n_openssl_mutexes_;
3220 tor_mutex_t **ms = openssl_mutexes_;
3221 int i;
3222 openssl_mutexes_ = NULL;
3223 n_openssl_mutexes_ = 0;
3224 for (i=0;i<n;++i) {
3225 tor_mutex_free(ms[i]);
3227 tor_free(ms);
3229 #endif
3231 tor_free(crypto_openssl_version_str);
3232 tor_free(crypto_openssl_header_version_str);
3233 return 0;
3236 /** @} */