crypto.c 38 KB

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