crypto.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar.
  2. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char crypto_c_id[] = "$Id$";
  6. /**
  7. * \file crypto.c
  8. *
  9. * \brief Low-level cryptographic functions.
  10. **/
  11. #include "orconfig.h"
  12. #ifdef MS_WINDOWS
  13. #define WIN32_WINNT 0x400
  14. #define _WIN32_WINNT 0x400
  15. #define WIN32_LEAN_AND_MEAN
  16. #include <windows.h>
  17. #include <wincrypt.h>
  18. #endif
  19. #include <string.h>
  20. #include <openssl/err.h>
  21. #include <openssl/rsa.h>
  22. #include <openssl/pem.h>
  23. #include <openssl/evp.h>
  24. #include <openssl/rand.h>
  25. #include <openssl/opensslv.h>
  26. #include <openssl/bn.h>
  27. #include <openssl/dh.h>
  28. #include <openssl/rsa.h>
  29. #include <openssl/dh.h>
  30. #include <stdlib.h>
  31. #include <assert.h>
  32. #include <stdio.h>
  33. #include <limits.h>
  34. #ifdef HAVE_CTYPE_H
  35. #include <ctype.h>
  36. #endif
  37. #ifdef HAVE_UNISTD_H
  38. #include <unistd.h>
  39. #endif
  40. #ifdef HAVE_FCNTL_H
  41. #include <fcntl.h>
  42. #endif
  43. #ifdef HAVE_SYS_FCNTL_H
  44. #include <sys/fcntl.h>
  45. #endif
  46. #include "crypto.h"
  47. #include "log.h"
  48. #include "aes.h"
  49. #include "util.h"
  50. #include "container.h"
  51. #include "compat.h"
  52. #if OPENSSL_VERSION_NUMBER < 0x00905000l
  53. #error "We require openssl >= 0.9.5"
  54. #elif OPENSSL_VERSION_NUMBER < 0x00906000l
  55. #define OPENSSL_095
  56. #endif
  57. /* Certain functions that return a success code in OpenSSL 0.9.6 return void
  58. * (and don't indicate errors) in OpenSSL version 0.9.5.
  59. *
  60. * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
  61. */
  62. #ifdef OPENSSL_095
  63. #define RETURN_SSL_OUTCOME(exp) (exp); return 0
  64. #else
  65. #define RETURN_SSL_OUTCOME(exp) return !(exp)
  66. #endif
  67. /** Macro: is k a valid RSA public or private key? */
  68. #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
  69. /** Macro: is k a valid RSA private key? */
  70. #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
  71. #ifdef TOR_IS_MULTITHREADED
  72. static tor_mutex_t **_openssl_mutexes = NULL;
  73. static int _n_openssl_mutexes = -1;
  74. #endif
  75. struct crypto_pk_env_t
  76. {
  77. int refs; /* reference counting so we don't have to copy keys */
  78. RSA *key;
  79. };
  80. struct crypto_cipher_env_t
  81. {
  82. unsigned char key[CIPHER_KEY_LEN];
  83. aes_cnt_cipher_t *cipher;
  84. };
  85. struct crypto_dh_env_t {
  86. DH *dh;
  87. };
  88. /* Prototypes for functions only used by tortls.c */
  89. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
  90. RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env);
  91. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
  92. DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
  93. static int setup_openssl_threading(void);
  94. /** Return the number of bytes added by padding method <b>padding</b>.
  95. */
  96. static INLINE int
  97. crypto_get_rsa_padding_overhead(int padding) {
  98. switch (padding)
  99. {
  100. case RSA_NO_PADDING: return 0;
  101. case RSA_PKCS1_OAEP_PADDING: return 42;
  102. case RSA_PKCS1_PADDING: return 11;
  103. default: tor_assert(0); return -1;
  104. }
  105. }
  106. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  107. */
  108. static INLINE int
  109. crypto_get_rsa_padding(int padding) {
  110. switch (padding)
  111. {
  112. case PK_NO_PADDING: return RSA_NO_PADDING;
  113. case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
  114. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  115. default: tor_assert(0); return -1;
  116. }
  117. }
  118. /** Boolean: has OpenSSL's crypto been initialized? */
  119. static int _crypto_global_initialized = 0;
  120. /** Log all pending crypto errors at level <b>severity</b>. Use
  121. * <b>doing</b> to describe our current activities.
  122. */
  123. static void
  124. crypto_log_errors(int severity, const char *doing)
  125. {
  126. unsigned int err;
  127. const char *msg, *lib, *func;
  128. while ((err = ERR_get_error()) != 0) {
  129. msg = (const char*)ERR_reason_error_string(err);
  130. lib = (const char*)ERR_lib_error_string(err);
  131. func = (const char*)ERR_func_error_string(err);
  132. if (!msg) msg = "(null)";
  133. if (doing) {
  134. log(severity, "crypto error while %s: %s (in %s:%s)", doing, msg, lib, func);
  135. } else {
  136. log(severity, "crypto error: %s (in %s:%s)", msg, lib, func);
  137. }
  138. }
  139. }
  140. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  141. */
  142. int crypto_global_init()
  143. {
  144. if (!_crypto_global_initialized) {
  145. ERR_load_crypto_strings();
  146. _crypto_global_initialized = 1;
  147. setup_openssl_threading();
  148. }
  149. return 0;
  150. }
  151. /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
  152. */
  153. int crypto_global_cleanup()
  154. {
  155. ERR_free_strings();
  156. #ifdef TOR_IS_MULTITHREADED
  157. if (_n_openssl_mutexes) {
  158. int n = _n_openssl_mutexes;
  159. tor_mutex_t **ms = _openssl_mutexes;
  160. int i;
  161. _openssl_mutexes = NULL;
  162. _n_openssl_mutexes = 0;
  163. for (i=0;i<n;++i) {
  164. tor_mutex_free(ms[i]);
  165. }
  166. tor_free(ms);
  167. }
  168. #endif
  169. return 0;
  170. }
  171. /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
  172. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
  173. {
  174. crypto_pk_env_t *env;
  175. tor_assert(rsa);
  176. env = tor_malloc(sizeof(crypto_pk_env_t));
  177. env->refs = 1;
  178. env->key = rsa;
  179. return env;
  180. }
  181. /** used by tortls.c: return the RSA* from a crypto_pk_env_t. */
  182. RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env)
  183. {
  184. return env->key;
  185. }
  186. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
  187. * private is set, include the private-key portion of the key. */
  188. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
  189. {
  190. RSA *key = NULL;
  191. EVP_PKEY *pkey = NULL;
  192. tor_assert(env->key);
  193. if (private) {
  194. if (!(key = RSAPrivateKey_dup(env->key)))
  195. goto error;
  196. } else {
  197. if (!(key = RSAPublicKey_dup(env->key)))
  198. goto error;
  199. }
  200. if (!(pkey = EVP_PKEY_new()))
  201. goto error;
  202. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  203. goto error;
  204. return pkey;
  205. error:
  206. if (pkey)
  207. EVP_PKEY_free(pkey);
  208. if (key)
  209. RSA_free(key);
  210. return NULL;
  211. }
  212. /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
  213. */
  214. DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh)
  215. {
  216. return dh->dh;
  217. }
  218. /** Allocate and return storage for a public key. The key itself will not yet
  219. * be set.
  220. */
  221. crypto_pk_env_t *crypto_new_pk_env(void)
  222. {
  223. RSA *rsa;
  224. rsa = RSA_new();
  225. if (!rsa) return NULL;
  226. return _crypto_new_pk_env_rsa(rsa);
  227. }
  228. /** Release a reference to an asymmetric key; when all the references
  229. * are released, free the key.
  230. */
  231. void crypto_free_pk_env(crypto_pk_env_t *env)
  232. {
  233. tor_assert(env);
  234. if (--env->refs > 0)
  235. return;
  236. if (env->key)
  237. RSA_free(env->key);
  238. free(env);
  239. }
  240. /** Create a new symmetric cipher for a given key and encryption flag
  241. * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
  242. * on failure.
  243. */
  244. crypto_cipher_env_t *
  245. crypto_create_init_cipher(const char *key, int encrypt_mode)
  246. {
  247. int r;
  248. crypto_cipher_env_t *crypto = NULL;
  249. if (! (crypto = crypto_new_cipher_env())) {
  250. log_fn(LOG_WARN, "Unable to allocate crypto object");
  251. return NULL;
  252. }
  253. if (crypto_cipher_set_key(crypto, key)) {
  254. crypto_log_errors(LOG_WARN, "setting symmetric key");
  255. goto error;
  256. }
  257. if (encrypt_mode)
  258. r = crypto_cipher_encrypt_init_cipher(crypto);
  259. else
  260. r = crypto_cipher_decrypt_init_cipher(crypto);
  261. if (r)
  262. goto error;
  263. return crypto;
  264. error:
  265. if (crypto)
  266. crypto_free_cipher_env(crypto);
  267. return NULL;
  268. }
  269. /** Allocate and return a new symmetric cipher.
  270. */
  271. crypto_cipher_env_t *crypto_new_cipher_env()
  272. {
  273. crypto_cipher_env_t *env;
  274. env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
  275. env->cipher = aes_new_cipher();
  276. return env;
  277. }
  278. /** Free a symmetric cipher.
  279. */
  280. void crypto_free_cipher_env(crypto_cipher_env_t *env)
  281. {
  282. tor_assert(env);
  283. tor_assert(env->cipher);
  284. aes_free_cipher(env->cipher);
  285. tor_free(env);
  286. }
  287. /* public key crypto */
  288. /** Generate a new public/private keypair in <b>env</b>. Return 0 on
  289. * success, -1 on failure.
  290. */
  291. int crypto_pk_generate_key(crypto_pk_env_t *env)
  292. {
  293. tor_assert(env);
  294. if (env->key)
  295. RSA_free(env->key);
  296. env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
  297. if (!env->key) {
  298. crypto_log_errors(LOG_WARN, "generating RSA key");
  299. return -1;
  300. }
  301. return 0;
  302. }
  303. /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
  304. * Return 0 on success, -1 on failure.
  305. */
  306. static int crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
  307. const char *s)
  308. {
  309. BIO *b;
  310. tor_assert(env);
  311. tor_assert(s);
  312. /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
  313. b = BIO_new_mem_buf((char*)s, -1);
  314. if (env->key)
  315. RSA_free(env->key);
  316. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
  317. BIO_free(b);
  318. if (!env->key) {
  319. crypto_log_errors(LOG_WARN, "Error parsing private key");
  320. return -1;
  321. }
  322. return 0;
  323. }
  324. /** Read a PEM-encoded private key from the file named by
  325. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  326. */
  327. int crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
  328. {
  329. char *contents;
  330. int r;
  331. /* Read the file into a string. */
  332. contents = read_file_to_str(keyfile, 0);
  333. if (!contents) {
  334. log_fn(LOG_WARN, "Error reading private key from %s", keyfile);
  335. return -1;
  336. }
  337. /* Try to parse it. */
  338. r = crypto_pk_read_private_key_from_string(env, contents);
  339. tor_free(contents);
  340. if (r)
  341. return -1; /* read_private_key_from_string already warned, so we don't.*/
  342. /* Make sure it's valid. */
  343. if (crypto_pk_check_key(env) <= 0)
  344. return -1;
  345. return 0;
  346. }
  347. /** PEM-encode the public key portion of <b>env</b> and write it to a
  348. * newly allocated string. On success, set *<b>dest</b> to the new
  349. * string, *<b>len</b> to the string's length, and return 0. On
  350. * failure, return -1.
  351. */
  352. int crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, size_t *len) {
  353. BUF_MEM *buf;
  354. BIO *b;
  355. tor_assert(env);
  356. tor_assert(env->key);
  357. tor_assert(dest);
  358. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  359. /* Now you can treat b as if it were a file. Just use the
  360. * PEM_*_bio_* functions instead of the non-bio variants.
  361. */
  362. if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
  363. crypto_log_errors(LOG_WARN, "writing public key to string");
  364. return -1;
  365. }
  366. BIO_get_mem_ptr(b, &buf);
  367. BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  368. BIO_free(b);
  369. tor_assert(buf->length >= 0);
  370. *dest = tor_malloc(buf->length+1);
  371. memcpy(*dest, buf->data, buf->length);
  372. (*dest)[buf->length] = 0; /* null terminate it */
  373. *len = buf->length;
  374. BUF_MEM_free(buf);
  375. return 0;
  376. }
  377. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  378. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  379. * failure.
  380. */
  381. int crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src, size_t len) {
  382. BIO *b;
  383. tor_assert(env);
  384. tor_assert(src);
  385. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  386. BIO_write(b, src, len);
  387. if (env->key)
  388. RSA_free(env->key);
  389. env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  390. BIO_free(b);
  391. if (!env->key) {
  392. crypto_log_errors(LOG_WARN, "reading public key from string");
  393. return -1;
  394. }
  395. return 0;
  396. }
  397. /* Write the private key from 'env' into the file named by 'fname',
  398. * PEM-encoded. Return 0 on success, -1 on failure.
  399. */
  400. int
  401. crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
  402. const char *fname)
  403. {
  404. BIO *bio;
  405. char *cp;
  406. long len;
  407. char *s;
  408. int r;
  409. tor_assert(PRIVATE_KEY_OK(env));
  410. if (!(bio = BIO_new(BIO_s_mem())))
  411. return -1;
  412. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  413. == 0) {
  414. crypto_log_errors(LOG_WARN, "writing private key");
  415. BIO_free(bio);
  416. return -1;
  417. }
  418. len = BIO_get_mem_data(bio, &cp);
  419. tor_assert(len >= 0);
  420. s = tor_malloc(len+1);
  421. memcpy(s, cp, len);
  422. s[len]='\0';
  423. r = write_str_to_file(fname, s, 0);
  424. BIO_free(bio);
  425. free(s);
  426. return r;
  427. }
  428. /** Allocate a new string in *<b>out</b>, containing the public portion of the
  429. * RSA key in <b>env</b>, encoded first with DER, then in base-64. Return the
  430. * length of the encoded representation on success, and -1 on failure.
  431. *
  432. * <i>This function is for temporary use only. We need a simple
  433. * one-line representation for keys to work around a bug in parsing
  434. * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
  435. * in versions of Tor up to 0.0.9pre2.</i>
  436. */
  437. int crypto_pk_DER64_encode_public_key(crypto_pk_env_t *env, char **out)
  438. {
  439. int len;
  440. char buf[PK_BYTES*2]; /* Too long, but hey, stacks are big. */
  441. tor_assert(env);
  442. tor_assert(out);
  443. len = crypto_pk_asn1_encode(env, buf, sizeof(buf));
  444. if (len < 0) {
  445. return -1;
  446. }
  447. *out = tor_malloc(len * 2); /* too long, but safe. */
  448. if (base64_encode(*out, len*2, buf, len) < 0) {
  449. log_fn(LOG_WARN, "Error base64-encoding DER-encoded key");
  450. tor_free(*out);
  451. return -1;
  452. }
  453. /* Remove spaces */
  454. tor_strstrip(*out, " \r\n\t");
  455. return strlen(*out);
  456. }
  457. /** Decode a base-64 encoded DER representation of an RSA key from <b>in</b>,
  458. * and store the result in <b>env</b>. Return 0 on success, -1 on failure.
  459. *
  460. * <i>This function is for temporary use only. We need a simple
  461. * one-line representation for keys to work around a bug in parsing
  462. * directories containing "opt keyword\n-----BEGIN OBJECT----" entries
  463. * in versions of Tor up to 0.0.9pre2.</i>
  464. */
  465. crypto_pk_env_t *crypto_pk_DER64_decode_public_key(const char *in)
  466. {
  467. char partitioned[PK_BYTES*2 + 16];
  468. char buf[PK_BYTES*2];
  469. int len;
  470. tor_assert(in);
  471. len = strlen(in);
  472. if (strlen(in) > PK_BYTES*2) {
  473. return NULL;
  474. }
  475. /* base64_decode doesn't work unless we insert linebreaks every 64
  476. * characters. how dumb. */
  477. if (tor_strpartition(partitioned, sizeof(partitioned), in, "\n", 64,
  478. ALWAYS_TERMINATE))
  479. return NULL;
  480. len = base64_decode(buf, sizeof(buf), partitioned, strlen(partitioned));
  481. if (len<0) {
  482. log_fn(LOG_WARN,"Error base-64 decoding key");
  483. return NULL;
  484. }
  485. return crypto_pk_asn1_decode(buf, len);
  486. }
  487. /** Return true iff <b>env</b> has a valid key.
  488. */
  489. int crypto_pk_check_key(crypto_pk_env_t *env)
  490. {
  491. int r;
  492. tor_assert(env);
  493. r = RSA_check_key(env->key);
  494. if (r <= 0)
  495. crypto_log_errors(LOG_WARN,"checking RSA key");
  496. return r;
  497. }
  498. /** Compare the public-key components of a and b. Return -1 if a\<b, 0
  499. * if a==b, and 1 if a\>b.
  500. */
  501. int crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b) {
  502. int result;
  503. if (!a || !b)
  504. return -1;
  505. if (!a->key || !b->key)
  506. return -1;
  507. tor_assert(PUBLIC_KEY_OK(a));
  508. tor_assert(PUBLIC_KEY_OK(b));
  509. result = BN_cmp((a->key)->n, (b->key)->n);
  510. if (result)
  511. return result;
  512. return BN_cmp((a->key)->e, (b->key)->e);
  513. }
  514. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  515. int crypto_pk_keysize(crypto_pk_env_t *env)
  516. {
  517. tor_assert(env);
  518. tor_assert(env->key);
  519. return RSA_size(env->key);
  520. }
  521. /** Increase the reference count of <b>env</b>, and return it.
  522. */
  523. crypto_pk_env_t *crypto_pk_dup_key(crypto_pk_env_t *env) {
  524. tor_assert(env);
  525. tor_assert(env->key);
  526. env->refs++;
  527. return env;
  528. }
  529. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  530. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  531. * write the result to <b>to</b>, and return the number of bytes
  532. * written. On failure, return -1.
  533. */
  534. int
  535. crypto_pk_public_encrypt(crypto_pk_env_t *env, unsigned char *to,
  536. const unsigned char *from, int fromlen, int padding)
  537. {
  538. int r;
  539. tor_assert(env);
  540. tor_assert(from);
  541. tor_assert(to);
  542. r = RSA_public_encrypt(fromlen, (unsigned char*)from, to, env->key,
  543. crypto_get_rsa_padding(padding));
  544. if (r<0) {
  545. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  546. return -1;
  547. }
  548. return r;
  549. }
  550. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  551. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  552. * write the result to <b>to</b>, and return the number of bytes
  553. * written. On failure, return -1.
  554. */
  555. int
  556. crypto_pk_private_decrypt(crypto_pk_env_t *env, unsigned char *to,
  557. const unsigned char *from, int fromlen,
  558. int padding, int warnOnFailure)
  559. {
  560. int r;
  561. tor_assert(env);
  562. tor_assert(from);
  563. tor_assert(to);
  564. tor_assert(env->key);
  565. if (!env->key->p)
  566. /* Not a private key */
  567. return -1;
  568. r = RSA_private_decrypt(fromlen, (unsigned char*)from, to, env->key,
  569. crypto_get_rsa_padding(padding));
  570. if (r<0) {
  571. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_INFO,
  572. "performing RSA decryption");
  573. return -1;
  574. }
  575. return r;
  576. }
  577. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  578. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  579. * signed data to <b>to</b>, and return the number of bytes written.
  580. * On failure, return -1.
  581. */
  582. int
  583. crypto_pk_public_checksig(crypto_pk_env_t *env, unsigned char *to,
  584. const unsigned char *from, int fromlen)
  585. {
  586. int r;
  587. tor_assert(env);
  588. tor_assert(from);
  589. tor_assert(to);
  590. r = RSA_public_decrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
  591. if (r<0) {
  592. crypto_log_errors(LOG_WARN, "checking RSA signature");
  593. return -1;
  594. }
  595. return r;
  596. }
  597. /** Check a siglen-byte long signature at <b>sig</b> against
  598. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  599. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  600. * SHA1(data). Else return -1.
  601. */
  602. int
  603. crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const unsigned char *data,
  604. int datalen, const unsigned char *sig, int siglen)
  605. {
  606. char digest[DIGEST_LEN];
  607. char buf[PK_BYTES+1];
  608. int r;
  609. tor_assert(env);
  610. tor_assert(data);
  611. tor_assert(sig);
  612. if (crypto_digest(digest,data,datalen)<0) {
  613. log_fn(LOG_WARN, "couldn't compute digest");
  614. return -1;
  615. }
  616. r = crypto_pk_public_checksig(env,buf,sig,siglen);
  617. if (r != DIGEST_LEN) {
  618. log_fn(LOG_WARN, "Invalid signature");
  619. return -1;
  620. }
  621. if (memcmp(buf, digest, DIGEST_LEN)) {
  622. log_fn(LOG_WARN, "Signature mismatched with digest.");
  623. return -1;
  624. }
  625. return 0;
  626. }
  627. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  628. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  629. * <b>to</b>, and return the number of bytes written. On failure, return
  630. * -1.
  631. */
  632. int
  633. crypto_pk_private_sign(crypto_pk_env_t *env, unsigned char *to,
  634. const unsigned char *from, int fromlen)
  635. {
  636. int r;
  637. tor_assert(env);
  638. tor_assert(from);
  639. tor_assert(to);
  640. if (!env->key->p)
  641. /* Not a private key */
  642. return -1;
  643. r = RSA_private_encrypt(fromlen, (unsigned char*)from, to, env->key, RSA_PKCS1_PADDING);
  644. if (r<0) {
  645. crypto_log_errors(LOG_WARN, "generating RSA signature");
  646. return -1;
  647. }
  648. return r;
  649. }
  650. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  651. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  652. * store it in <b>to</b>. Return the number of bytes written on
  653. * success, and -1 on failure.
  654. */
  655. int
  656. crypto_pk_private_sign_digest(crypto_pk_env_t *env, unsigned char *to,
  657. const unsigned char *from, int fromlen)
  658. {
  659. char digest[DIGEST_LEN];
  660. if (crypto_digest(digest,from,fromlen)<0)
  661. return -1;
  662. return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
  663. }
  664. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  665. * bytes of data from <b>from</b>, with padding type 'padding',
  666. * storing the results on <b>to</b>.
  667. *
  668. * If no padding is used, the public key must be at least as large as
  669. * <b>from</b>.
  670. *
  671. * Returns the number of bytes written on success, -1 on failure.
  672. *
  673. * The encrypted data consists of:
  674. * - The source data, padded and encrypted with the public key, if the
  675. * padded source data is no longer than the public key, and <b>force</b>
  676. * is false, OR
  677. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  678. * padded and encrypted with the public key; followed by the rest of
  679. * the source data encrypted in AES-CTR mode with the symmetric key.
  680. */
  681. int crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
  682. unsigned char *to,
  683. const unsigned char *from,
  684. int fromlen,
  685. int padding, int force)
  686. {
  687. int overhead, pkeylen, outlen, r, symlen;
  688. crypto_cipher_env_t *cipher = NULL;
  689. char buf[PK_BYTES+1];
  690. tor_assert(env);
  691. tor_assert(from);
  692. tor_assert(to);
  693. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  694. pkeylen = crypto_pk_keysize(env);
  695. if (padding == PK_NO_PADDING && fromlen < pkeylen)
  696. return -1;
  697. if (!force && fromlen+overhead <= pkeylen) {
  698. /* It all fits in a single encrypt. */
  699. return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
  700. }
  701. cipher = crypto_new_cipher_env();
  702. if (!cipher) return -1;
  703. if (crypto_cipher_generate_key(cipher)<0)
  704. goto err;
  705. /* You can't just run around RSA-encrypting any bitstream: if it's
  706. * greater than the RSA key, then OpenSSL will happily encrypt, and
  707. * later decrypt to the wrong value. So we set the first bit of
  708. * 'cipher->key' to 0 if we aren't padding. This means that our
  709. * symmetric key is really only 127 bits.
  710. */
  711. if (padding == PK_NO_PADDING)
  712. cipher->key[0] &= 0x7f;
  713. if (crypto_cipher_encrypt_init_cipher(cipher)<0)
  714. goto err;
  715. memcpy(buf, cipher->key, CIPHER_KEY_LEN);
  716. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  717. /* Length of symmetrically encrypted data. */
  718. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  719. outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
  720. if (outlen!=pkeylen) {
  721. goto err;
  722. }
  723. r = crypto_cipher_encrypt(cipher, to+outlen,
  724. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  725. if (r<0) goto err;
  726. memset(buf, 0, sizeof(buf));
  727. crypto_free_cipher_env(cipher);
  728. return outlen + symlen;
  729. err:
  730. memset(buf, 0, sizeof(buf));
  731. if (cipher) crypto_free_cipher_env(cipher);
  732. return -1;
  733. }
  734. /** Invert crypto_pk_public_hybrid_encrypt. */
  735. int crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
  736. unsigned char *to,
  737. const unsigned char *from,
  738. int fromlen,
  739. int padding, int warnOnFailure)
  740. {
  741. int overhead, pkeylen, outlen, r;
  742. crypto_cipher_env_t *cipher = NULL;
  743. char buf[PK_BYTES+1];
  744. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  745. pkeylen = crypto_pk_keysize(env);
  746. if (fromlen <= pkeylen) {
  747. return crypto_pk_private_decrypt(env,to,from,fromlen,padding,warnOnFailure);
  748. }
  749. outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,warnOnFailure);
  750. if (outlen<0) {
  751. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, "Error decrypting public-key data");
  752. return -1;
  753. }
  754. if (outlen < CIPHER_KEY_LEN) {
  755. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, "No room for a symmetric key");
  756. return -1;
  757. }
  758. cipher = crypto_create_init_cipher(buf, 0);
  759. if (!cipher) {
  760. return -1;
  761. }
  762. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  763. outlen -= CIPHER_KEY_LEN;
  764. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  765. if (r<0)
  766. goto err;
  767. memset(buf,0,sizeof(buf));
  768. crypto_free_cipher_env(cipher);
  769. return outlen + (fromlen-pkeylen);
  770. err:
  771. memset(buf,0,sizeof(buf));
  772. if (cipher) crypto_free_cipher_env(cipher);
  773. return -1;
  774. }
  775. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  776. * Return -1 on error, or the number of characters used on success.
  777. */
  778. int crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
  779. {
  780. int len;
  781. unsigned char *buf, *cp;
  782. len = i2d_RSAPublicKey(pk->key, NULL);
  783. if (len < 0 || len > dest_len)
  784. return -1;
  785. cp = buf = tor_malloc(len+1);
  786. len = i2d_RSAPublicKey(pk->key, &cp);
  787. if (len < 0) {
  788. crypto_log_errors(LOG_WARN,"encoding public key");
  789. tor_free(buf);
  790. return -1;
  791. }
  792. /* We don't encode directly into 'dest', because that would be illegal
  793. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  794. */
  795. memcpy(dest,buf,len);
  796. tor_free(buf);
  797. return len;
  798. }
  799. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  800. * success and NULL on failure.
  801. */
  802. crypto_pk_env_t *crypto_pk_asn1_decode(const char *str, int len)
  803. {
  804. RSA *rsa;
  805. unsigned char *buf;
  806. /* This ifdef suppresses a type warning. Take out the first case once
  807. * everybody is using openssl 0.9.7 or later.
  808. */
  809. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  810. unsigned char *cp;
  811. #else
  812. const unsigned char *cp;
  813. #endif
  814. cp = buf = tor_malloc(len);
  815. memcpy(buf,str,len);
  816. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  817. tor_free(buf);
  818. if (!rsa) {
  819. crypto_log_errors(LOG_WARN,"decoding public key");
  820. return NULL;
  821. }
  822. return _crypto_new_pk_env_rsa(rsa);
  823. }
  824. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  825. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  826. * Return 0 on success, -1 on failure.
  827. */
  828. int crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
  829. {
  830. unsigned char *buf, *bufp;
  831. int len;
  832. len = i2d_RSAPublicKey(pk->key, NULL);
  833. if (len < 0)
  834. return -1;
  835. buf = bufp = tor_malloc(len+1);
  836. len = i2d_RSAPublicKey(pk->key, &bufp);
  837. if (len < 0) {
  838. crypto_log_errors(LOG_WARN,"encoding public key");
  839. free(buf);
  840. return -1;
  841. }
  842. if (crypto_digest(digest_out, buf, len) < 0) {
  843. free(buf);
  844. return -1;
  845. }
  846. free(buf);
  847. return 0;
  848. }
  849. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  850. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  851. * space). Return 0 on success, -1 on failure.
  852. *
  853. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  854. * of the public key, converted to hexadecimal, in upper case, with a
  855. * space after every four digits.
  856. *
  857. * If <b>add_space</b> is false, omit the spaces.
  858. */
  859. int
  860. crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
  861. {
  862. unsigned char digest[DIGEST_LEN];
  863. unsigned char hexdigest[HEX_DIGEST_LEN+1];
  864. if (crypto_pk_get_digest(pk, digest)) {
  865. return -1;
  866. }
  867. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  868. if (add_space) {
  869. if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4,
  870. NEVER_TERMINATE)<0)
  871. return -1;
  872. } else {
  873. strcpy(fp_out, hexdigest);
  874. }
  875. return 0;
  876. }
  877. /** Return true iff <b>s</b> is in the correct format for a fingerprint.
  878. */
  879. int
  880. crypto_pk_check_fingerprint_syntax(const char *s)
  881. {
  882. int i;
  883. for (i = 0; i < FINGERPRINT_LEN; ++i) {
  884. if ((i%5) == 4) {
  885. if (!TOR_ISSPACE(s[i])) return 0;
  886. } else {
  887. if (!TOR_ISXDIGIT(s[i])) return 0;
  888. }
  889. }
  890. if (s[FINGERPRINT_LEN]) return 0;
  891. return 1;
  892. }
  893. /* symmetric crypto */
  894. /** Generate a new random key for the symmetric cipher in <b>env</b>.
  895. * Return 0 on success, -1 on failure. Does not initialize the cipher.
  896. */
  897. int crypto_cipher_generate_key(crypto_cipher_env_t *env)
  898. {
  899. tor_assert(env);
  900. return crypto_rand(env->key, CIPHER_KEY_LEN);
  901. }
  902. /** Set the symmetric key for the cipher in <b>env</b> to the first
  903. * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
  904. * Return 0 on success, -1 on failure.
  905. */
  906. int crypto_cipher_set_key(crypto_cipher_env_t *env, const unsigned char *key)
  907. {
  908. tor_assert(env);
  909. tor_assert(key);
  910. if (!env->key)
  911. return -1;
  912. memcpy(env->key, key, CIPHER_KEY_LEN);
  913. return 0;
  914. }
  915. /** Return a pointer to the key set for the cipher in <b>env</b>.
  916. */
  917. const unsigned char *crypto_cipher_get_key(crypto_cipher_env_t *env)
  918. {
  919. return env->key;
  920. }
  921. /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
  922. * success, -1 on failure.
  923. */
  924. int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
  925. {
  926. tor_assert(env);
  927. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  928. return 0;
  929. }
  930. /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
  931. * success, -1 on failure.
  932. */
  933. int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
  934. {
  935. tor_assert(env);
  936. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  937. return 0;
  938. }
  939. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  940. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  941. * On failure, return -1.
  942. */
  943. int
  944. crypto_cipher_encrypt(crypto_cipher_env_t *env, unsigned char *to,
  945. const unsigned char *from, unsigned int fromlen)
  946. {
  947. tor_assert(env);
  948. tor_assert(env->cipher);
  949. tor_assert(from);
  950. tor_assert(fromlen);
  951. tor_assert(to);
  952. aes_crypt(env->cipher, from, fromlen, to);
  953. return 0;
  954. }
  955. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  956. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  957. * On failure, return -1.
  958. */
  959. int
  960. crypto_cipher_decrypt(crypto_cipher_env_t *env, unsigned char *to,
  961. const unsigned char *from, unsigned int fromlen)
  962. {
  963. tor_assert(env);
  964. tor_assert(from);
  965. tor_assert(to);
  966. aes_crypt(env->cipher, from, fromlen, to);
  967. return 0;
  968. }
  969. /** Move the position of the cipher stream backwards by <b>delta</b> bytes.
  970. * Return 0 on success, -1 on failure.
  971. */
  972. int
  973. crypto_cipher_rewind(crypto_cipher_env_t *env, long delta)
  974. {
  975. return crypto_cipher_advance(env, -delta);
  976. }
  977. /** Move the position of the cipher stream forwards by <b>delta</b> bytes.
  978. * Return 0 on success, -1 on failure.
  979. */
  980. int
  981. crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
  982. {
  983. aes_adjust_counter(env->cipher, delta);
  984. return 0;
  985. }
  986. /* SHA-1 */
  987. /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
  988. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  989. * Return 0 on success, -1 on failure.
  990. */
  991. int crypto_digest(unsigned char *digest, const unsigned char *m, int len)
  992. {
  993. tor_assert(m);
  994. tor_assert(digest);
  995. return (SHA1(m,len,digest) == NULL);
  996. }
  997. struct crypto_digest_env_t {
  998. SHA_CTX d;
  999. };
  1000. /** Allocate and return a new digest object.
  1001. */
  1002. crypto_digest_env_t *
  1003. crypto_new_digest_env(void)
  1004. {
  1005. crypto_digest_env_t *r;
  1006. r = tor_malloc(sizeof(crypto_digest_env_t));
  1007. SHA1_Init(&r->d);
  1008. return r;
  1009. }
  1010. /** Deallocate a digest object.
  1011. */
  1012. void
  1013. crypto_free_digest_env(crypto_digest_env_t *digest) {
  1014. tor_free(digest);
  1015. }
  1016. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1017. */
  1018. void
  1019. crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
  1020. size_t len)
  1021. {
  1022. tor_assert(digest);
  1023. tor_assert(data);
  1024. /* Using the SHA1_*() calls directly means we don't support doing
  1025. * sha1 in hardware. But so far the delay of getting the question
  1026. * to the hardware, and hearing the answer, is likely higher than
  1027. * just doing it ourselves. Hashes are fast.
  1028. */
  1029. SHA1_Update(&digest->d, (void*)data, len);
  1030. }
  1031. /** Compute the hash of the data that has been passed to the digest
  1032. * object; write the first out_len bytes of the result to <b>out</b>.
  1033. * <b>out_len</b> must be \<= DIGEST_LEN.
  1034. */
  1035. void crypto_digest_get_digest(crypto_digest_env_t *digest,
  1036. char *out, size_t out_len)
  1037. {
  1038. static char r[DIGEST_LEN];
  1039. SHA_CTX tmpctx;
  1040. tor_assert(digest);
  1041. tor_assert(out);
  1042. tor_assert(out_len <= DIGEST_LEN);
  1043. /* memcpy into a temporary ctx, since SHA1_Final clears the context */
  1044. memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
  1045. SHA1_Final(r, &tmpctx);
  1046. memcpy(out, r, out_len);
  1047. }
  1048. /** Allocate and return a new digest object with the same state as
  1049. * <b>digest</b>
  1050. */
  1051. crypto_digest_env_t *
  1052. crypto_digest_dup(const crypto_digest_env_t *digest)
  1053. {
  1054. crypto_digest_env_t *r;
  1055. tor_assert(digest);
  1056. r = tor_malloc(sizeof(crypto_digest_env_t));
  1057. memcpy(r,digest,sizeof(crypto_digest_env_t));
  1058. return r;
  1059. }
  1060. /** Replace the state of the digest object <b>into</b> with the state
  1061. * of the digest object <b>from</b>.
  1062. */
  1063. void
  1064. crypto_digest_assign(crypto_digest_env_t *into,
  1065. const crypto_digest_env_t *from)
  1066. {
  1067. tor_assert(into);
  1068. tor_assert(from);
  1069. memcpy(into,from,sizeof(crypto_digest_env_t));
  1070. }
  1071. /* DH */
  1072. /** Shared P parameter for our DH key exchanged. */
  1073. static BIGNUM *dh_param_p = NULL;
  1074. /** Shared G parameter for our DH key exchanges. */
  1075. static BIGNUM *dh_param_g = NULL;
  1076. /** Initialize dh_param_p and dh_param_g if they are not already
  1077. * set. */
  1078. static void init_dh_param(void) {
  1079. BIGNUM *p, *g;
  1080. int r;
  1081. if (dh_param_p && dh_param_g)
  1082. return;
  1083. p = BN_new();
  1084. g = BN_new();
  1085. tor_assert(p);
  1086. tor_assert(g);
  1087. #if 0
  1088. /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
  1089. prime, and supposedly it equals:
  1090. 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
  1091. */
  1092. r = BN_hex2bn(&p,
  1093. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
  1094. "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
  1095. "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
  1096. "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
  1097. "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
  1098. "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
  1099. "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
  1100. "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
  1101. #endif
  1102. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1103. supposedly it equals:
  1104. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1105. */
  1106. /* See also rfc 3536 */
  1107. r = BN_hex2bn(&p,
  1108. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1109. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1110. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1111. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1112. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1113. tor_assert(r);
  1114. r = BN_set_word(g, 2);
  1115. tor_assert(r);
  1116. dh_param_p = p;
  1117. dh_param_g = g;
  1118. }
  1119. /** Allocate and return a new DH object for a key exchange.
  1120. */
  1121. crypto_dh_env_t *crypto_dh_new()
  1122. {
  1123. crypto_dh_env_t *res = NULL;
  1124. if (!dh_param_p)
  1125. init_dh_param();
  1126. res = tor_malloc_zero(sizeof(crypto_dh_env_t));
  1127. if (!(res->dh = DH_new()))
  1128. goto err;
  1129. if (!(res->dh->p = BN_dup(dh_param_p)))
  1130. goto err;
  1131. if (!(res->dh->g = BN_dup(dh_param_g)))
  1132. goto err;
  1133. return res;
  1134. err:
  1135. crypto_log_errors(LOG_WARN, "creating DH object");
  1136. if (res && res->dh) DH_free(res->dh); /* frees p and g too */
  1137. if (res) free(res);
  1138. return NULL;
  1139. }
  1140. /** Return the length of the DH key in <b>dh</b>, in bytes.
  1141. */
  1142. int crypto_dh_get_bytes(crypto_dh_env_t *dh)
  1143. {
  1144. tor_assert(dh);
  1145. return DH_size(dh->dh);
  1146. }
  1147. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  1148. * success, -1 on failure.
  1149. */
  1150. int crypto_dh_generate_public(crypto_dh_env_t *dh)
  1151. {
  1152. if (!DH_generate_key(dh->dh)) {
  1153. crypto_log_errors(LOG_WARN, "generating DH key");
  1154. return -1;
  1155. }
  1156. return 0;
  1157. }
  1158. /** Generate g^x as necessary, and write the g^x for the key exchange
  1159. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  1160. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  1161. */
  1162. int crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
  1163. {
  1164. int bytes;
  1165. tor_assert(dh);
  1166. if (!dh->dh->pub_key) {
  1167. if (crypto_dh_generate_public(dh)<0)
  1168. return -1;
  1169. }
  1170. tor_assert(dh->dh->pub_key);
  1171. bytes = BN_num_bytes(dh->dh->pub_key);
  1172. tor_assert(bytes >= 0);
  1173. if (pubkey_len < (size_t)bytes)
  1174. return -1;
  1175. memset(pubkey, 0, pubkey_len);
  1176. BN_bn2bin(dh->dh->pub_key, pubkey+(pubkey_len-bytes));
  1177. return 0;
  1178. }
  1179. #undef MIN
  1180. #define MIN(a,b) ((a)<(b)?(a):(b))
  1181. /** Given a DH key exchange object, and our peer's value of g^y (as a
  1182. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  1183. * <b>secret_bytes_out</b> bytes of shared key material and write them
  1184. * to <b>secret_out</b>. Return the number of bytes generated on success,
  1185. * or -1 on failure.
  1186. *
  1187. * (We generate key material by computing
  1188. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  1189. * where || is concatenation.)
  1190. */
  1191. int crypto_dh_compute_secret(crypto_dh_env_t *dh,
  1192. const char *pubkey, size_t pubkey_len,
  1193. char *secret_out, size_t secret_bytes_out)
  1194. {
  1195. unsigned char hash[DIGEST_LEN];
  1196. unsigned char *secret_tmp = NULL;
  1197. BIGNUM *pubkey_bn = NULL;
  1198. size_t secret_len=0;
  1199. unsigned int i;
  1200. int result=0;
  1201. tor_assert(dh);
  1202. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  1203. if (!(pubkey_bn = BN_bin2bn(pubkey, pubkey_len, NULL)))
  1204. goto error;
  1205. secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
  1206. result = DH_compute_key(secret_tmp, pubkey_bn, dh->dh);
  1207. if (result < 0) {
  1208. log_fn(LOG_WARN,"DH_compute_key() failed.");
  1209. goto error;
  1210. }
  1211. secret_len = result;
  1212. /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
  1213. for (i = 0; i < secret_bytes_out; i += DIGEST_LEN) {
  1214. secret_tmp[secret_len] = (unsigned char) i/DIGEST_LEN;
  1215. if (crypto_digest(hash, secret_tmp, secret_len+1))
  1216. goto error;
  1217. memcpy(secret_out+i, hash, MIN(DIGEST_LEN, secret_bytes_out-i));
  1218. }
  1219. secret_len = secret_bytes_out;
  1220. goto done;
  1221. error:
  1222. result = -1;
  1223. done:
  1224. crypto_log_errors(LOG_WARN, "completing DH handshake");
  1225. if (pubkey_bn)
  1226. BN_free(pubkey_bn);
  1227. tor_free(secret_tmp);
  1228. if (result < 0)
  1229. return result;
  1230. else
  1231. return secret_len;
  1232. }
  1233. /** Free a DH key exchange object.
  1234. */
  1235. void crypto_dh_free(crypto_dh_env_t *dh)
  1236. {
  1237. tor_assert(dh);
  1238. tor_assert(dh->dh);
  1239. DH_free(dh->dh);
  1240. free(dh);
  1241. }
  1242. /* random numbers */
  1243. /** Seed OpenSSL's random number generator with DIGEST_LEN bytes from the
  1244. * operating system. Return 0 on success, -1 on failure.
  1245. */
  1246. int crypto_seed_rng(void)
  1247. {
  1248. #ifdef MS_WINDOWS
  1249. static int provider_set = 0;
  1250. static HCRYPTPROV provider;
  1251. char buf[DIGEST_LEN+1];
  1252. if (!provider_set) {
  1253. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET)) {
  1254. if (GetLastError() != NTE_BAD_KEYSET) {
  1255. log_fn(LOG_ERR,"Can't get CryptoAPI provider [1]");
  1256. return -1;
  1257. }
  1258. /* Yes, we need to try it twice. */
  1259. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  1260. CRYPT_MACHINE_KEYSET | CRYPT_NEWKEYSET)) {
  1261. log_fn(LOG_ERR,"Can't get CryptoAPI provider [2], error code: %x", GetLastError());
  1262. return -1;
  1263. }
  1264. }
  1265. provider_set = 1;
  1266. }
  1267. if (!CryptGenRandom(provider, DIGEST_LEN, buf)) {
  1268. log_fn(LOG_ERR,"Can't get entropy from CryptoAPI.");
  1269. return -1;
  1270. }
  1271. RAND_seed(buf, DIGEST_LEN);
  1272. /* And add the current screen state to the entropy pool for
  1273. * good measure. */
  1274. RAND_screen();
  1275. return 0;
  1276. #else
  1277. static const char *filenames[] = {
  1278. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1279. };
  1280. int fd;
  1281. int i, n;
  1282. char buf[DIGEST_LEN+1];
  1283. for (i = 0; filenames[i]; ++i) {
  1284. fd = open(filenames[i], O_RDONLY, 0);
  1285. if (fd<0) continue;
  1286. log_fn(LOG_INFO, "Seeding RNG from %s", filenames[i]);
  1287. n = read(fd, buf, DIGEST_LEN);
  1288. close(fd);
  1289. if (n != DIGEST_LEN) {
  1290. log_fn(LOG_WARN, "Error reading from entropy source");
  1291. return -1;
  1292. }
  1293. RAND_seed(buf, DIGEST_LEN);
  1294. return 0;
  1295. }
  1296. log_fn(LOG_WARN, "Cannot seed RNG -- no entropy source found.");
  1297. return -1;
  1298. #endif
  1299. }
  1300. /** Write n bytes of strong random data to <b>to</b>. Return 0 on
  1301. * success, -1 on failure.
  1302. */
  1303. int crypto_rand(unsigned char *to, unsigned int n)
  1304. {
  1305. int r;
  1306. tor_assert(to);
  1307. r = RAND_bytes(to, n);
  1308. if (r == 0)
  1309. crypto_log_errors(LOG_WARN, "generating random data");
  1310. return (r == 1) ? 0 : -1;
  1311. }
  1312. /** Write n bytes of pseudorandom data to <b>to</b>. Return 0 on
  1313. * success, -1 on failure.
  1314. */
  1315. void crypto_pseudo_rand(unsigned char *to, unsigned int n)
  1316. {
  1317. tor_assert(to);
  1318. if (RAND_pseudo_bytes(to, n) == -1) {
  1319. log_fn(LOG_ERR, "RAND_pseudo_bytes failed unexpectedly.");
  1320. crypto_log_errors(LOG_WARN, "generating random data");
  1321. exit(1);
  1322. }
  1323. }
  1324. /** Return a pseudorandom integer, chosen uniformly from the values
  1325. * between 0 and max-1. */
  1326. int crypto_pseudo_rand_int(unsigned int max) {
  1327. unsigned int val;
  1328. unsigned int cutoff;
  1329. tor_assert(max < UINT_MAX);
  1330. tor_assert(max > 0); /* don't div by 0 */
  1331. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1332. * distribution with clipping at the upper end of unsigned int's
  1333. * range.
  1334. */
  1335. cutoff = UINT_MAX - (UINT_MAX%max);
  1336. while (1) {
  1337. crypto_pseudo_rand((unsigned char*) &val, sizeof(val));
  1338. if (val < cutoff)
  1339. return val % max;
  1340. }
  1341. }
  1342. /** Return a randomly chosen element of sl; or NULL if sl is empty.
  1343. */
  1344. void *smartlist_choose(const smartlist_t *sl) {
  1345. size_t len;
  1346. len = smartlist_len(sl);
  1347. if (len)
  1348. return smartlist_get(sl,crypto_pseudo_rand_int(len));
  1349. return NULL; /* no elements to choose from */
  1350. }
  1351. /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
  1352. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1353. * bytes. Return the number of bytes written on success; -1 if
  1354. * destlen is too short, or other failure.
  1355. */
  1356. int
  1357. base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1358. {
  1359. EVP_ENCODE_CTX ctx;
  1360. int len, ret;
  1361. /* 48 bytes of input -> 64 bytes of output plus newline.
  1362. Plus one more byte, in case I'm wrong.
  1363. */
  1364. if (destlen < ((srclen/48)+1)*66)
  1365. return -1;
  1366. if (destlen > SIZE_T_CEILING)
  1367. return -1;
  1368. EVP_EncodeInit(&ctx);
  1369. EVP_EncodeUpdate(&ctx, dest, &len, (char*) src, srclen);
  1370. EVP_EncodeFinal(&ctx, dest+len, &ret);
  1371. ret += len;
  1372. return ret;
  1373. }
  1374. /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
  1375. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1376. * bytes. Return the number of bytes written on success; -1 if
  1377. * destlen is too short, or other failure.
  1378. *
  1379. * NOTE: destlen should be a little longer than the amount of data it
  1380. * will contain, since we check for sufficient space conservatively.
  1381. * Here, "a little" is around 64-ish bytes.
  1382. */
  1383. int
  1384. base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  1385. {
  1386. EVP_ENCODE_CTX ctx;
  1387. int len, ret;
  1388. /* 64 bytes of input -> *up to* 48 bytes of output.
  1389. Plus one more byte, in case I'm wrong.
  1390. */
  1391. if (destlen < ((srclen/64)+1)*49)
  1392. return -1;
  1393. if (destlen > SIZE_T_CEILING)
  1394. return -1;
  1395. EVP_DecodeInit(&ctx);
  1396. EVP_DecodeUpdate(&ctx, dest, &len, (char*) src, srclen);
  1397. EVP_DecodeFinal(&ctx, dest, &ret);
  1398. ret += len;
  1399. return ret;
  1400. }
  1401. /** Implements base32 encoding as in rfc3548. Limitation: Requires
  1402. * that srclen*8 is a multiple of 5.
  1403. */
  1404. void
  1405. base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1406. {
  1407. unsigned int nbits, i, bit, v, u;
  1408. nbits = srclen * 8;
  1409. tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
  1410. tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
  1411. tor_assert(destlen < SIZE_T_CEILING);
  1412. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  1413. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  1414. v = ((uint8_t)src[bit/8]) << 8;
  1415. if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
  1416. /* set u to the 5-bit value at the bit'th bit of src. */
  1417. u = (v >> (11-(bit%8))) & 0x1F;
  1418. dest[i] = BASE32_CHARS[u];
  1419. }
  1420. dest[i] = '\0';
  1421. }
  1422. /** Implement RFC2440-style iterated-salted S2K conversion: convert the
  1423. * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
  1424. * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
  1425. * are a salt; the 9th byte describes how much iteration to do.
  1426. * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
  1427. */
  1428. void
  1429. secret_to_key(char *key_out, size_t key_out_len, const char *secret,
  1430. size_t secret_len, const char *s2k_specifier)
  1431. {
  1432. crypto_digest_env_t *d;
  1433. uint8_t c;
  1434. size_t count;
  1435. char *tmp;
  1436. tor_assert(key_out_len < SIZE_T_CEILING);
  1437. #define EXPBIAS 6
  1438. c = s2k_specifier[8];
  1439. count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
  1440. #undef EXPBIAS
  1441. tor_assert(key_out_len <= DIGEST_LEN);
  1442. d = crypto_new_digest_env();
  1443. tmp = tor_malloc(8+secret_len);
  1444. memcpy(tmp,s2k_specifier,8);
  1445. memcpy(tmp+8,secret,secret_len);
  1446. secret_len += 8;
  1447. while (count) {
  1448. if (count >= secret_len) {
  1449. crypto_digest_add_bytes(d, tmp, secret_len);
  1450. count -= secret_len;
  1451. } else {
  1452. crypto_digest_add_bytes(d, tmp, count);
  1453. count = 0;
  1454. }
  1455. }
  1456. crypto_digest_get_digest(d, key_out, key_out_len);
  1457. tor_free(tmp);
  1458. crypto_free_digest_env(d);
  1459. }
  1460. #ifdef TOR_IS_MULTITHREADED
  1461. static void
  1462. _openssl_locking_cb(int mode, int n, const char *file, int line)
  1463. {
  1464. if (!_openssl_mutexes)
  1465. /* This is not a really good fix for the
  1466. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  1467. * it can't hurt. */
  1468. return;
  1469. if (mode & CRYPTO_LOCK)
  1470. tor_mutex_acquire(_openssl_mutexes[n]);
  1471. else
  1472. tor_mutex_release(_openssl_mutexes[n]);
  1473. }
  1474. static int
  1475. setup_openssl_threading(void) {
  1476. int i;
  1477. int n = CRYPTO_num_locks();
  1478. _n_openssl_mutexes = n;
  1479. _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
  1480. for (i=0; i < n; ++i)
  1481. _openssl_mutexes[i] = tor_mutex_new();
  1482. CRYPTO_set_locking_callback(_openssl_locking_cb);
  1483. CRYPTO_set_id_callback(tor_get_thread_id);
  1484. return 0;
  1485. }
  1486. #else
  1487. static int setup_openssl_threading(void) { return 0; }
  1488. #endif