crypto.c 45 KB

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