crypto.c 43 KB

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