crypto.c 36 KB

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