crypto.c 46 KB

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