crypto.c 38 KB

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