crypto.c 41 KB

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