crypto.c 47 KB

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