crypto.c 43 KB

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