crypto.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char crypto_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file crypto.c
  10. * \brief Wrapper functions to present a consistent interface to
  11. * public-key and symmetric cryptography operations from OpenSSL.
  12. **/
  13. #include "orconfig.h"
  14. #ifdef MS_WINDOWS
  15. #define WIN32_WINNT 0x400
  16. #define _WIN32_WINNT 0x400
  17. #define WIN32_LEAN_AND_MEAN
  18. #include <windows.h>
  19. #include <wincrypt.h>
  20. #endif
  21. #include <openssl/err.h>
  22. #include <openssl/rsa.h>
  23. #include <openssl/pem.h>
  24. #include <openssl/evp.h>
  25. #include <openssl/rand.h>
  26. #include <openssl/opensslv.h>
  27. #include <openssl/bn.h>
  28. #include <openssl/dh.h>
  29. #include <openssl/conf.h>
  30. #ifdef HAVE_CTYPE_H
  31. #include <ctype.h>
  32. #endif
  33. #ifdef HAVE_UNISTD_H
  34. #include <unistd.h>
  35. #endif
  36. #ifdef HAVE_FCNTL_H
  37. #include <fcntl.h>
  38. #endif
  39. #ifdef HAVE_SYS_FCNTL_H
  40. #include <sys/fcntl.h>
  41. #endif
  42. #define CRYPTO_PRIVATE
  43. #include "crypto.h"
  44. #include "log.h"
  45. #include "aes.h"
  46. #include "util.h"
  47. #include "container.h"
  48. #include "compat.h"
  49. #if OPENSSL_VERSION_NUMBER < 0x00905000l
  50. #error "We require openssl >= 0.9.5"
  51. #endif
  52. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  53. #define NO_ENGINES
  54. #else
  55. #include <openssl/engine.h>
  56. #endif
  57. /** Macro: is k a valid RSA public or private key? */
  58. #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
  59. /** Macro: is k a valid RSA private key? */
  60. #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
  61. #ifdef TOR_IS_MULTITHREADED
  62. /** A number of prealloced mutexes for use by openssl. */
  63. static tor_mutex_t **_openssl_mutexes = NULL;
  64. /** How many mutexes have we allocated for use by openssl? */
  65. static int _n_openssl_mutexes = 0;
  66. #endif
  67. /** A public key, or a public/private keypair. */
  68. struct crypto_pk_env_t
  69. {
  70. int refs; /* reference counting so we don't have to copy keys */
  71. RSA *key;
  72. };
  73. /** Key and stream information for a stream cipher. */
  74. struct crypto_cipher_env_t
  75. {
  76. char key[CIPHER_KEY_LEN];
  77. aes_cnt_cipher_t *cipher;
  78. };
  79. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  80. * while we're waiting for the second.*/
  81. struct crypto_dh_env_t {
  82. DH *dh;
  83. };
  84. static int setup_openssl_threading(void);
  85. static int tor_check_dh_key(BIGNUM *bn);
  86. /** Return the number of bytes added by padding method <b>padding</b>.
  87. */
  88. static INLINE int
  89. crypto_get_rsa_padding_overhead(int padding)
  90. {
  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. {
  104. switch (padding)
  105. {
  106. case PK_NO_PADDING: return RSA_NO_PADDING;
  107. case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
  108. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  109. default: tor_assert(0); return -1;
  110. }
  111. }
  112. /** Boolean: has OpenSSL's crypto been initialized? */
  113. static int _crypto_global_initialized = 0;
  114. /** Log all pending crypto errors at level <b>severity</b>. Use
  115. * <b>doing</b> to describe our current activities.
  116. */
  117. static void
  118. crypto_log_errors(int severity, const char *doing)
  119. {
  120. unsigned int err;
  121. const char *msg, *lib, *func;
  122. while ((err = ERR_get_error()) != 0) {
  123. msg = (const char*)ERR_reason_error_string(err);
  124. lib = (const char*)ERR_lib_error_string(err);
  125. func = (const char*)ERR_func_error_string(err);
  126. if (!msg) msg = "(null)";
  127. if (!lib) lib = "(null)";
  128. if (!func) func = "(null)";
  129. if (doing) {
  130. log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  131. doing, msg, lib, func);
  132. } else {
  133. log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
  134. }
  135. }
  136. }
  137. #ifndef NO_ENGINES
  138. /** Log any OpenSSL engines we're using at NOTICE. */
  139. static void
  140. log_engine(const char *fn, ENGINE *e)
  141. {
  142. if (e) {
  143. const char *name, *id;
  144. name = ENGINE_get_name(e);
  145. id = ENGINE_get_id(e);
  146. log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
  147. name?name:"?", id?id:"?", fn);
  148. } else {
  149. log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
  150. }
  151. }
  152. #endif
  153. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  154. */
  155. int
  156. crypto_global_init(int useAccel)
  157. {
  158. if (!_crypto_global_initialized) {
  159. ERR_load_crypto_strings();
  160. OpenSSL_add_all_algorithms();
  161. _crypto_global_initialized = 1;
  162. setup_openssl_threading();
  163. /* XXX the below is a bug, since we can't know if we're supposed
  164. * to be using hardware acceleration or not. we should arrange
  165. * for this function to be called before init_keys. But make it
  166. * not complain loudly, at least until we make acceleration work. */
  167. if (useAccel < 0) {
  168. log_info(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
  169. }
  170. #ifndef NO_ENGINES
  171. if (useAccel > 0) {
  172. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  173. ENGINE_load_builtin_engines();
  174. if (!ENGINE_register_all_complete())
  175. return -1;
  176. /* XXXX make sure this isn't leaking. */
  177. log_engine("RSA", ENGINE_get_default_RSA());
  178. log_engine("DH", ENGINE_get_default_DH());
  179. log_engine("RAND", ENGINE_get_default_RAND());
  180. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  181. log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
  182. log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  183. }
  184. #endif
  185. }
  186. return 0;
  187. }
  188. /** Free crypto resources held by this thread. */
  189. void
  190. crypto_thread_cleanup(void)
  191. {
  192. ERR_remove_state(0);
  193. }
  194. /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
  195. */
  196. int
  197. crypto_global_cleanup(void)
  198. {
  199. EVP_cleanup();
  200. ERR_remove_state(0);
  201. ERR_free_strings();
  202. #ifndef NO_ENGINES
  203. ENGINE_cleanup();
  204. CONF_modules_unload(1);
  205. CRYPTO_cleanup_all_ex_data();
  206. #endif
  207. #ifdef TOR_IS_MULTITHREADED
  208. if (_n_openssl_mutexes) {
  209. int n = _n_openssl_mutexes;
  210. tor_mutex_t **ms = _openssl_mutexes;
  211. int i;
  212. _openssl_mutexes = NULL;
  213. _n_openssl_mutexes = 0;
  214. for (i=0;i<n;++i) {
  215. tor_mutex_free(ms[i]);
  216. }
  217. tor_free(ms);
  218. }
  219. #endif
  220. return 0;
  221. }
  222. /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
  223. crypto_pk_env_t *
  224. _crypto_new_pk_env_rsa(RSA *rsa)
  225. {
  226. crypto_pk_env_t *env;
  227. tor_assert(rsa);
  228. env = tor_malloc(sizeof(crypto_pk_env_t));
  229. env->refs = 1;
  230. env->key = rsa;
  231. return env;
  232. }
  233. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
  234. * private is set, include the private-key portion of the key. */
  235. EVP_PKEY *
  236. _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
  237. {
  238. RSA *key = NULL;
  239. EVP_PKEY *pkey = NULL;
  240. tor_assert(env->key);
  241. if (private) {
  242. if (!(key = RSAPrivateKey_dup(env->key)))
  243. goto error;
  244. } else {
  245. if (!(key = RSAPublicKey_dup(env->key)))
  246. goto error;
  247. }
  248. if (!(pkey = EVP_PKEY_new()))
  249. goto error;
  250. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  251. goto error;
  252. return pkey;
  253. error:
  254. if (pkey)
  255. EVP_PKEY_free(pkey);
  256. if (key)
  257. RSA_free(key);
  258. return NULL;
  259. }
  260. /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
  261. */
  262. DH *
  263. _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
  264. {
  265. return dh->dh;
  266. }
  267. /** Allocate and return storage for a public key. The key itself will not yet
  268. * be set.
  269. */
  270. crypto_pk_env_t *
  271. crypto_new_pk_env(void)
  272. {
  273. RSA *rsa;
  274. rsa = RSA_new();
  275. if (!rsa) return NULL;
  276. return _crypto_new_pk_env_rsa(rsa);
  277. }
  278. /** Release a reference to an asymmetric key; when all the references
  279. * are released, free the key.
  280. */
  281. void
  282. crypto_free_pk_env(crypto_pk_env_t *env)
  283. {
  284. tor_assert(env);
  285. if (--env->refs > 0)
  286. return;
  287. if (env->key)
  288. RSA_free(env->key);
  289. tor_free(env);
  290. }
  291. /** Create a new symmetric cipher for a given key and encryption flag
  292. * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
  293. * on failure.
  294. */
  295. crypto_cipher_env_t *
  296. crypto_create_init_cipher(const char *key, int encrypt_mode)
  297. {
  298. int r;
  299. crypto_cipher_env_t *crypto = NULL;
  300. if (! (crypto = crypto_new_cipher_env())) {
  301. log_warn(LD_CRYPTO, "Unable to allocate crypto object");
  302. return NULL;
  303. }
  304. if (crypto_cipher_set_key(crypto, key)) {
  305. crypto_log_errors(LOG_WARN, "setting symmetric key");
  306. goto error;
  307. }
  308. if (encrypt_mode)
  309. r = crypto_cipher_encrypt_init_cipher(crypto);
  310. else
  311. r = crypto_cipher_decrypt_init_cipher(crypto);
  312. if (r)
  313. goto error;
  314. return crypto;
  315. error:
  316. if (crypto)
  317. crypto_free_cipher_env(crypto);
  318. return NULL;
  319. }
  320. /** Allocate and return a new symmetric cipher.
  321. */
  322. crypto_cipher_env_t *
  323. crypto_new_cipher_env(void)
  324. {
  325. crypto_cipher_env_t *env;
  326. env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
  327. env->cipher = aes_new_cipher();
  328. return env;
  329. }
  330. /** Free a symmetric cipher.
  331. */
  332. void
  333. crypto_free_cipher_env(crypto_cipher_env_t *env)
  334. {
  335. tor_assert(env);
  336. tor_assert(env->cipher);
  337. aes_free_cipher(env->cipher);
  338. tor_free(env);
  339. }
  340. /* public key crypto */
  341. /** Generate a new public/private keypair in <b>env</b>. Return 0 on
  342. * success, -1 on failure.
  343. */
  344. int
  345. crypto_pk_generate_key(crypto_pk_env_t *env)
  346. {
  347. tor_assert(env);
  348. if (env->key)
  349. RSA_free(env->key);
  350. env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
  351. if (!env->key) {
  352. crypto_log_errors(LOG_WARN, "generating RSA key");
  353. return -1;
  354. }
  355. return 0;
  356. }
  357. /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
  358. * Return 0 on success, -1 on failure.
  359. */
  360. /* Used here, and used for testing. */
  361. int
  362. crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
  363. const char *s)
  364. {
  365. BIO *b;
  366. tor_assert(env);
  367. tor_assert(s);
  368. /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
  369. b = BIO_new_mem_buf((char*)s, -1);
  370. if (env->key)
  371. RSA_free(env->key);
  372. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
  373. BIO_free(b);
  374. if (!env->key) {
  375. crypto_log_errors(LOG_WARN, "Error parsing private key");
  376. return -1;
  377. }
  378. return 0;
  379. }
  380. /** Read a PEM-encoded private key from the file named by
  381. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  382. */
  383. int
  384. crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
  385. const char *keyfile)
  386. {
  387. char *contents;
  388. int r;
  389. /* Read the file into a string. */
  390. contents = read_file_to_str(keyfile, 0, NULL);
  391. if (!contents) {
  392. log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
  393. return -1;
  394. }
  395. /* Try to parse it. */
  396. r = crypto_pk_read_private_key_from_string(env, contents);
  397. tor_free(contents);
  398. if (r)
  399. return -1; /* read_private_key_from_string already warned, so we don't.*/
  400. /* Make sure it's valid. */
  401. if (crypto_pk_check_key(env) <= 0)
  402. return -1;
  403. return 0;
  404. }
  405. /** PEM-encode the public key portion of <b>env</b> and write it to a
  406. * newly allocated string. On success, set *<b>dest</b> to the new
  407. * string, *<b>len</b> to the string's length, and return 0. On
  408. * failure, return -1.
  409. */
  410. int
  411. crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
  412. size_t *len)
  413. {
  414. BUF_MEM *buf;
  415. BIO *b;
  416. tor_assert(env);
  417. tor_assert(env->key);
  418. tor_assert(dest);
  419. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  420. /* Now you can treat b as if it were a file. Just use the
  421. * PEM_*_bio_* functions instead of the non-bio variants.
  422. */
  423. if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
  424. crypto_log_errors(LOG_WARN, "writing public key to string");
  425. return -1;
  426. }
  427. BIO_get_mem_ptr(b, &buf);
  428. (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  429. BIO_free(b);
  430. tor_assert(buf->length >= 0);
  431. *dest = tor_malloc(buf->length+1);
  432. memcpy(*dest, buf->data, buf->length);
  433. (*dest)[buf->length] = 0; /* nul terminate it */
  434. *len = buf->length;
  435. BUF_MEM_free(buf);
  436. return 0;
  437. }
  438. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  439. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  440. * failure.
  441. */
  442. int
  443. crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
  444. size_t len)
  445. {
  446. BIO *b;
  447. tor_assert(env);
  448. tor_assert(src);
  449. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  450. BIO_write(b, src, len);
  451. if (env->key)
  452. RSA_free(env->key);
  453. env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  454. BIO_free(b);
  455. if (!env->key) {
  456. crypto_log_errors(LOG_WARN, "reading public key from string");
  457. return -1;
  458. }
  459. return 0;
  460. }
  461. /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
  462. * PEM-encoded. Return 0 on success, -1 on failure.
  463. */
  464. int
  465. crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
  466. const char *fname)
  467. {
  468. BIO *bio;
  469. char *cp;
  470. long len;
  471. char *s;
  472. int r;
  473. tor_assert(PRIVATE_KEY_OK(env));
  474. if (!(bio = BIO_new(BIO_s_mem())))
  475. return -1;
  476. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  477. == 0) {
  478. crypto_log_errors(LOG_WARN, "writing private key");
  479. BIO_free(bio);
  480. return -1;
  481. }
  482. len = BIO_get_mem_data(bio, &cp);
  483. tor_assert(len >= 0);
  484. s = tor_malloc(len+1);
  485. memcpy(s, cp, len);
  486. s[len]='\0';
  487. r = write_str_to_file(fname, s, 0);
  488. BIO_free(bio);
  489. tor_free(s);
  490. return r;
  491. }
  492. /** Return true iff <b>env</b> has a valid key.
  493. */
  494. int
  495. crypto_pk_check_key(crypto_pk_env_t *env)
  496. {
  497. int r;
  498. tor_assert(env);
  499. r = RSA_check_key(env->key);
  500. if (r <= 0)
  501. crypto_log_errors(LOG_WARN,"checking RSA key");
  502. return r;
  503. }
  504. /** Compare the public-key components of a and b. Return -1 if a\<b, 0
  505. * if a==b, and 1 if a\>b.
  506. */
  507. int
  508. crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
  509. {
  510. int result;
  511. if (!a || !b)
  512. return -1;
  513. if (!a->key || !b->key)
  514. return -1;
  515. tor_assert(PUBLIC_KEY_OK(a));
  516. tor_assert(PUBLIC_KEY_OK(b));
  517. result = BN_cmp((a->key)->n, (b->key)->n);
  518. if (result)
  519. return result;
  520. return BN_cmp((a->key)->e, (b->key)->e);
  521. }
  522. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  523. size_t
  524. crypto_pk_keysize(crypto_pk_env_t *env)
  525. {
  526. tor_assert(env);
  527. tor_assert(env->key);
  528. return (size_t) RSA_size(env->key);
  529. }
  530. /** Increase the reference count of <b>env</b>, and return it.
  531. */
  532. crypto_pk_env_t *
  533. crypto_pk_dup_key(crypto_pk_env_t *env)
  534. {
  535. tor_assert(env);
  536. tor_assert(env->key);
  537. env->refs++;
  538. return env;
  539. }
  540. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  541. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  542. * write the result to <b>to</b>, and return the number of bytes
  543. * written. On failure, return -1.
  544. */
  545. int
  546. crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
  547. const char *from, size_t fromlen, int padding)
  548. {
  549. int r;
  550. tor_assert(env);
  551. tor_assert(from);
  552. tor_assert(to);
  553. r = RSA_public_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
  554. env->key, crypto_get_rsa_padding(padding));
  555. if (r<0) {
  556. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  557. return -1;
  558. }
  559. return r;
  560. }
  561. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  562. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  563. * write the result to <b>to</b>, and return the number of bytes
  564. * written. On failure, return -1.
  565. */
  566. int
  567. crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
  568. const char *from, size_t fromlen,
  569. int padding, int warnOnFailure)
  570. {
  571. int r;
  572. tor_assert(env);
  573. tor_assert(from);
  574. tor_assert(to);
  575. tor_assert(env->key);
  576. if (!env->key->p)
  577. /* Not a private key */
  578. return -1;
  579. r = RSA_private_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
  580. env->key, crypto_get_rsa_padding(padding));
  581. if (r<0) {
  582. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  583. "performing RSA decryption");
  584. return -1;
  585. }
  586. return r;
  587. }
  588. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  589. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  590. * signed data to <b>to</b>, and return the number of bytes written.
  591. * On failure, return -1.
  592. */
  593. int
  594. crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
  595. const char *from, size_t fromlen)
  596. {
  597. int r;
  598. tor_assert(env);
  599. tor_assert(from);
  600. tor_assert(to);
  601. r = RSA_public_decrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
  602. env->key, RSA_PKCS1_PADDING);
  603. if (r<0) {
  604. crypto_log_errors(LOG_WARN, "checking RSA signature");
  605. return -1;
  606. }
  607. return r;
  608. }
  609. /** Check a siglen-byte long signature at <b>sig</b> against
  610. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  611. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  612. * SHA1(data). Else return -1.
  613. */
  614. int
  615. crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
  616. int datalen, const char *sig, int siglen)
  617. {
  618. char digest[DIGEST_LEN];
  619. char *buf;
  620. int r;
  621. tor_assert(env);
  622. tor_assert(data);
  623. tor_assert(sig);
  624. if (crypto_digest(digest,data,datalen)<0) {
  625. log_warn(LD_BUG, "couldn't compute digest");
  626. return -1;
  627. }
  628. buf = tor_malloc(crypto_pk_keysize(env)+1);
  629. r = crypto_pk_public_checksig(env,buf,sig,siglen);
  630. if (r != DIGEST_LEN) {
  631. log_warn(LD_CRYPTO, "Invalid signature");
  632. tor_free(buf);
  633. return -1;
  634. }
  635. if (memcmp(buf, digest, DIGEST_LEN)) {
  636. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  637. tor_free(buf);
  638. return -1;
  639. }
  640. tor_free(buf);
  641. return 0;
  642. }
  643. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  644. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  645. * <b>to</b>, and return the number of bytes written. On failure, return
  646. * -1.
  647. */
  648. int
  649. crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
  650. const char *from, size_t fromlen)
  651. {
  652. int r;
  653. tor_assert(env);
  654. tor_assert(from);
  655. tor_assert(to);
  656. if (!env->key->p)
  657. /* Not a private key */
  658. return -1;
  659. r = RSA_private_encrypt(fromlen, (unsigned char*)from, (unsigned char*)to,
  660. env->key, RSA_PKCS1_PADDING);
  661. if (r<0) {
  662. crypto_log_errors(LOG_WARN, "generating RSA signature");
  663. return -1;
  664. }
  665. return r;
  666. }
  667. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  668. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  669. * store it in <b>to</b>. Return the number of bytes written on
  670. * success, and -1 on failure.
  671. */
  672. int
  673. crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
  674. const char *from, size_t fromlen)
  675. {
  676. char digest[DIGEST_LEN];
  677. if (crypto_digest(digest,from,fromlen)<0)
  678. return -1;
  679. return crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
  680. }
  681. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  682. * bytes of data from <b>from</b>, with padding type 'padding',
  683. * storing the results on <b>to</b>.
  684. *
  685. * If no padding is used, the public key must be at least as large as
  686. * <b>from</b>.
  687. *
  688. * Returns the number of bytes written on success, -1 on failure.
  689. *
  690. * The encrypted data consists of:
  691. * - The source data, padded and encrypted with the public key, if the
  692. * padded source data is no longer than the public key, and <b>force</b>
  693. * is false, OR
  694. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  695. * padded and encrypted with the public key; followed by the rest of
  696. * the source data encrypted in AES-CTR mode with the symmetric key.
  697. */
  698. int
  699. crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
  700. char *to,
  701. const char *from,
  702. size_t fromlen,
  703. int padding, int force)
  704. {
  705. int overhead, outlen, r, symlen;
  706. size_t pkeylen;
  707. crypto_cipher_env_t *cipher = NULL;
  708. char *buf = NULL;
  709. tor_assert(env);
  710. tor_assert(from);
  711. tor_assert(to);
  712. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  713. pkeylen = crypto_pk_keysize(env);
  714. if (padding == PK_NO_PADDING && fromlen < pkeylen)
  715. return -1;
  716. if (!force && fromlen+overhead <= pkeylen) {
  717. /* It all fits in a single encrypt. */
  718. return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
  719. }
  720. cipher = crypto_new_cipher_env();
  721. if (!cipher) return -1;
  722. if (crypto_cipher_generate_key(cipher)<0)
  723. goto err;
  724. /* You can't just run around RSA-encrypting any bitstream: if it's
  725. * greater than the RSA key, then OpenSSL will happily encrypt, and
  726. * later decrypt to the wrong value. So we set the first bit of
  727. * 'cipher->key' to 0 if we aren't padding. This means that our
  728. * symmetric key is really only 127 bits.
  729. */
  730. if (padding == PK_NO_PADDING)
  731. cipher->key[0] &= 0x7f;
  732. if (crypto_cipher_encrypt_init_cipher(cipher)<0)
  733. goto err;
  734. buf = tor_malloc(pkeylen+1);
  735. memcpy(buf, cipher->key, CIPHER_KEY_LEN);
  736. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  737. /* Length of symmetrically encrypted data. */
  738. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  739. outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
  740. if (outlen!=(int)pkeylen) {
  741. goto err;
  742. }
  743. r = crypto_cipher_encrypt(cipher, to+outlen,
  744. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  745. if (r<0) goto err;
  746. memset(buf, 0, pkeylen);
  747. tor_free(buf);
  748. crypto_free_cipher_env(cipher);
  749. return outlen + symlen;
  750. err:
  751. memset(buf, 0, pkeylen);
  752. tor_free(buf);
  753. if (cipher) crypto_free_cipher_env(cipher);
  754. return -1;
  755. }
  756. /** Invert crypto_pk_public_hybrid_encrypt. */
  757. int
  758. crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
  759. char *to,
  760. const char *from,
  761. size_t fromlen,
  762. int padding, int warnOnFailure)
  763. {
  764. int outlen, r;
  765. size_t pkeylen;
  766. crypto_cipher_env_t *cipher = NULL;
  767. char *buf = NULL;
  768. pkeylen = crypto_pk_keysize(env);
  769. if (fromlen <= pkeylen) {
  770. return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
  771. warnOnFailure);
  772. }
  773. buf = tor_malloc(pkeylen+1);
  774. outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
  775. warnOnFailure);
  776. if (outlen<0) {
  777. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  778. "Error decrypting public-key data");
  779. goto err;
  780. }
  781. if (outlen < CIPHER_KEY_LEN) {
  782. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  783. "No room for a symmetric key");
  784. goto err;
  785. }
  786. cipher = crypto_create_init_cipher(buf, 0);
  787. if (!cipher) {
  788. goto err;
  789. }
  790. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  791. outlen -= CIPHER_KEY_LEN;
  792. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  793. if (r<0)
  794. goto err;
  795. memset(buf,0,pkeylen);
  796. tor_free(buf);
  797. crypto_free_cipher_env(cipher);
  798. return outlen + (fromlen-pkeylen);
  799. err:
  800. memset(buf,0,pkeylen);
  801. tor_free(buf);
  802. if (cipher) crypto_free_cipher_env(cipher);
  803. return -1;
  804. }
  805. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  806. * Return -1 on error, or the number of characters used on success.
  807. */
  808. int
  809. crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
  810. {
  811. int len;
  812. unsigned char *buf, *cp;
  813. len = i2d_RSAPublicKey(pk->key, NULL);
  814. if (len < 0 || len > dest_len)
  815. return -1;
  816. cp = buf = tor_malloc(len+1);
  817. len = i2d_RSAPublicKey(pk->key, &cp);
  818. if (len < 0) {
  819. crypto_log_errors(LOG_WARN,"encoding public key");
  820. tor_free(buf);
  821. return -1;
  822. }
  823. /* We don't encode directly into 'dest', because that would be illegal
  824. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  825. */
  826. memcpy(dest,buf,len);
  827. tor_free(buf);
  828. return len;
  829. }
  830. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  831. * success and NULL on failure.
  832. */
  833. crypto_pk_env_t *
  834. crypto_pk_asn1_decode(const char *str, size_t len)
  835. {
  836. RSA *rsa;
  837. unsigned char *buf;
  838. /* This ifdef suppresses a type warning. Take out the first case once
  839. * everybody is using openssl 0.9.7 or later.
  840. */
  841. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  842. unsigned char *cp;
  843. #else
  844. const unsigned char *cp;
  845. #endif
  846. cp = buf = tor_malloc(len);
  847. memcpy(buf,str,len);
  848. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  849. tor_free(buf);
  850. if (!rsa) {
  851. crypto_log_errors(LOG_WARN,"decoding public key");
  852. return NULL;
  853. }
  854. return _crypto_new_pk_env_rsa(rsa);
  855. }
  856. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  857. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  858. * Return 0 on success, -1 on failure.
  859. */
  860. int
  861. crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
  862. {
  863. unsigned char *buf, *bufp;
  864. int len;
  865. len = i2d_RSAPublicKey(pk->key, NULL);
  866. if (len < 0)
  867. return -1;
  868. buf = bufp = tor_malloc(len+1);
  869. len = i2d_RSAPublicKey(pk->key, &bufp);
  870. if (len < 0) {
  871. crypto_log_errors(LOG_WARN,"encoding public key");
  872. tor_free(buf);
  873. return -1;
  874. }
  875. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  876. tor_free(buf);
  877. return -1;
  878. }
  879. tor_free(buf);
  880. return 0;
  881. }
  882. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  883. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  884. * space). Return 0 on success, -1 on failure.
  885. *
  886. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  887. * of the public key, converted to hexadecimal, in upper case, with a
  888. * space after every four digits.
  889. *
  890. * If <b>add_space</b> is false, omit the spaces.
  891. */
  892. int
  893. crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
  894. {
  895. char digest[DIGEST_LEN];
  896. char hexdigest[HEX_DIGEST_LEN+1];
  897. if (crypto_pk_get_digest(pk, digest)) {
  898. return -1;
  899. }
  900. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  901. if (add_space) {
  902. if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4)<0)
  903. return -1;
  904. } else {
  905. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  906. }
  907. return 0;
  908. }
  909. /** Return true iff <b>s</b> is in the correct format for a fingerprint.
  910. */
  911. int
  912. crypto_pk_check_fingerprint_syntax(const char *s)
  913. {
  914. int i;
  915. for (i = 0; i < FINGERPRINT_LEN; ++i) {
  916. if ((i%5) == 4) {
  917. if (!TOR_ISSPACE(s[i])) return 0;
  918. } else {
  919. if (!TOR_ISXDIGIT(s[i])) return 0;
  920. }
  921. }
  922. if (s[FINGERPRINT_LEN]) return 0;
  923. return 1;
  924. }
  925. /* symmetric crypto */
  926. /** Generate a new random key for the symmetric cipher in <b>env</b>.
  927. * Return 0 on success, -1 on failure. Does not initialize the cipher.
  928. */
  929. int
  930. crypto_cipher_generate_key(crypto_cipher_env_t *env)
  931. {
  932. tor_assert(env);
  933. return crypto_rand(env->key, CIPHER_KEY_LEN);
  934. }
  935. /** Set the symmetric key for the cipher in <b>env</b> to the first
  936. * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
  937. * Return 0 on success, -1 on failure.
  938. */
  939. int
  940. crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
  941. {
  942. tor_assert(env);
  943. tor_assert(key);
  944. if (!env->key)
  945. return -1;
  946. memcpy(env->key, key, CIPHER_KEY_LEN);
  947. return 0;
  948. }
  949. /** Generate an initialization vector for our AES-CTR cipher; store it
  950. * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
  951. void
  952. crypto_cipher_generate_iv(char *iv_out)
  953. {
  954. crypto_rand(iv_out, CIPHER_IV_LEN);
  955. }
  956. /** Adjust the counter of <b>env</b> to point to the first byte of the block
  957. * corresponding to the encryption of the CIPHER_IV_LEN bytes at
  958. * <b>iv</b>. */
  959. int
  960. crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
  961. {
  962. tor_assert(env);
  963. tor_assert(iv);
  964. aes_set_iv(env->cipher, iv);
  965. return 0;
  966. }
  967. /** Return a pointer to the key set for the cipher in <b>env</b>.
  968. */
  969. const char *
  970. crypto_cipher_get_key(crypto_cipher_env_t *env)
  971. {
  972. return env->key;
  973. }
  974. /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
  975. * success, -1 on failure.
  976. */
  977. int
  978. crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
  979. {
  980. tor_assert(env);
  981. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  982. return 0;
  983. }
  984. /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
  985. * success, -1 on failure.
  986. */
  987. int
  988. crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
  989. {
  990. tor_assert(env);
  991. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  992. return 0;
  993. }
  994. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  995. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  996. * On failure, return -1.
  997. */
  998. int
  999. crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
  1000. const char *from, size_t fromlen)
  1001. {
  1002. tor_assert(env);
  1003. tor_assert(env->cipher);
  1004. tor_assert(from);
  1005. tor_assert(fromlen);
  1006. tor_assert(to);
  1007. aes_crypt(env->cipher, from, fromlen, to);
  1008. return 0;
  1009. }
  1010. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1011. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1012. * On failure, return -1.
  1013. */
  1014. int
  1015. crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
  1016. const char *from, size_t fromlen)
  1017. {
  1018. tor_assert(env);
  1019. tor_assert(from);
  1020. tor_assert(to);
  1021. aes_crypt(env->cipher, from, fromlen, to);
  1022. return 0;
  1023. }
  1024. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1025. * <b>cipher</b> to the buffer in <b>to</b> of length
  1026. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1027. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1028. * number of bytes written, on failure, return -1.
  1029. *
  1030. * This function adjusts the current position of the counter in <b>cipher</b>
  1031. * to immediately after the encrypted data.
  1032. */
  1033. int
  1034. crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
  1035. char *to, size_t tolen,
  1036. const char *from, size_t fromlen)
  1037. {
  1038. tor_assert(cipher);
  1039. tor_assert(from);
  1040. tor_assert(to);
  1041. if (fromlen < 1)
  1042. return -1;
  1043. if (tolen < fromlen + CIPHER_IV_LEN)
  1044. return -1;
  1045. crypto_cipher_generate_iv(to);
  1046. if (crypto_cipher_set_iv(cipher, to)<0)
  1047. return -1;
  1048. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1049. return fromlen + CIPHER_IV_LEN;
  1050. }
  1051. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1052. * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
  1053. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1054. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1055. * number of bytes written, on failure, return -1.
  1056. *
  1057. * This function adjusts the current position of the counter in <b>cipher</b>
  1058. * to immediately after the decrypted data.
  1059. */
  1060. int
  1061. crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
  1062. char *to, size_t tolen,
  1063. const char *from, size_t fromlen)
  1064. {
  1065. tor_assert(cipher);
  1066. tor_assert(from);
  1067. tor_assert(to);
  1068. if (fromlen <= CIPHER_IV_LEN)
  1069. return -1;
  1070. if (tolen < fromlen - CIPHER_IV_LEN)
  1071. return -1;
  1072. if (crypto_cipher_set_iv(cipher, from)<0)
  1073. return -1;
  1074. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1075. return fromlen - CIPHER_IV_LEN;
  1076. }
  1077. /* SHA-1 */
  1078. /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
  1079. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1080. * Return 0 on success, -1 on failure.
  1081. */
  1082. int
  1083. crypto_digest(char *digest, const char *m, size_t len)
  1084. {
  1085. tor_assert(m);
  1086. tor_assert(digest);
  1087. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1088. }
  1089. /** Intermediate information about the digest of a stream of data. */
  1090. struct crypto_digest_env_t {
  1091. SHA_CTX d;
  1092. };
  1093. /** Allocate and return a new digest object.
  1094. */
  1095. crypto_digest_env_t *
  1096. crypto_new_digest_env(void)
  1097. {
  1098. crypto_digest_env_t *r;
  1099. r = tor_malloc(sizeof(crypto_digest_env_t));
  1100. SHA1_Init(&r->d);
  1101. return r;
  1102. }
  1103. /** Deallocate a digest object.
  1104. */
  1105. void
  1106. crypto_free_digest_env(crypto_digest_env_t *digest)
  1107. {
  1108. tor_free(digest);
  1109. }
  1110. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1111. */
  1112. void
  1113. crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
  1114. size_t len)
  1115. {
  1116. tor_assert(digest);
  1117. tor_assert(data);
  1118. /* Using the SHA1_*() calls directly means we don't support doing
  1119. * sha1 in hardware. But so far the delay of getting the question
  1120. * to the hardware, and hearing the answer, is likely higher than
  1121. * just doing it ourselves. Hashes are fast.
  1122. */
  1123. SHA1_Update(&digest->d, (void*)data, len);
  1124. }
  1125. /** Compute the hash of the data that has been passed to the digest
  1126. * object; write the first out_len bytes of the result to <b>out</b>.
  1127. * <b>out_len</b> must be \<= DIGEST_LEN.
  1128. */
  1129. void
  1130. crypto_digest_get_digest(crypto_digest_env_t *digest,
  1131. char *out, size_t out_len)
  1132. {
  1133. static unsigned char r[DIGEST_LEN];
  1134. SHA_CTX tmpctx;
  1135. tor_assert(digest);
  1136. tor_assert(out);
  1137. tor_assert(out_len <= DIGEST_LEN);
  1138. /* memcpy into a temporary ctx, since SHA1_Final clears the context */
  1139. memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
  1140. SHA1_Final(r, &tmpctx);
  1141. memcpy(out, r, out_len);
  1142. }
  1143. /** Allocate and return a new digest object with the same state as
  1144. * <b>digest</b>
  1145. */
  1146. crypto_digest_env_t *
  1147. crypto_digest_dup(const crypto_digest_env_t *digest)
  1148. {
  1149. crypto_digest_env_t *r;
  1150. tor_assert(digest);
  1151. r = tor_malloc(sizeof(crypto_digest_env_t));
  1152. memcpy(r,digest,sizeof(crypto_digest_env_t));
  1153. return r;
  1154. }
  1155. /** Replace the state of the digest object <b>into</b> with the state
  1156. * of the digest object <b>from</b>.
  1157. */
  1158. void
  1159. crypto_digest_assign(crypto_digest_env_t *into,
  1160. const crypto_digest_env_t *from)
  1161. {
  1162. tor_assert(into);
  1163. tor_assert(from);
  1164. memcpy(into,from,sizeof(crypto_digest_env_t));
  1165. }
  1166. /* DH */
  1167. /** Shared P parameter for our DH key exchanged. */
  1168. static BIGNUM *dh_param_p = NULL;
  1169. /** Shared G parameter for our DH key exchanges. */
  1170. static BIGNUM *dh_param_g = NULL;
  1171. /** Initialize dh_param_p and dh_param_g if they are not already
  1172. * set. */
  1173. static void
  1174. init_dh_param(void)
  1175. {
  1176. BIGNUM *p, *g;
  1177. int r;
  1178. if (dh_param_p && dh_param_g)
  1179. return;
  1180. p = BN_new();
  1181. g = BN_new();
  1182. tor_assert(p);
  1183. tor_assert(g);
  1184. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1185. supposedly it equals:
  1186. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1187. */
  1188. r = BN_hex2bn(&p,
  1189. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1190. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1191. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1192. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1193. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1194. tor_assert(r);
  1195. r = BN_set_word(g, 2);
  1196. tor_assert(r);
  1197. dh_param_p = p;
  1198. dh_param_g = g;
  1199. }
  1200. #define DH_PRIVATE_KEY_BITS 320
  1201. /** Allocate and return a new DH object for a key exchange.
  1202. */
  1203. crypto_dh_env_t *
  1204. crypto_dh_new(void)
  1205. {
  1206. crypto_dh_env_t *res = NULL;
  1207. if (!dh_param_p)
  1208. init_dh_param();
  1209. res = tor_malloc_zero(sizeof(crypto_dh_env_t));
  1210. if (!(res->dh = DH_new()))
  1211. goto err;
  1212. if (!(res->dh->p = BN_dup(dh_param_p)))
  1213. goto err;
  1214. if (!(res->dh->g = BN_dup(dh_param_g)))
  1215. goto err;
  1216. res->dh->length = DH_PRIVATE_KEY_BITS;
  1217. return res;
  1218. err:
  1219. crypto_log_errors(LOG_WARN, "creating DH object");
  1220. if (res && res->dh) DH_free(res->dh); /* frees p and g too */
  1221. if (res) tor_free(res);
  1222. return NULL;
  1223. }
  1224. /** Return the length of the DH key in <b>dh</b>, in bytes.
  1225. */
  1226. int
  1227. crypto_dh_get_bytes(crypto_dh_env_t *dh)
  1228. {
  1229. tor_assert(dh);
  1230. return DH_size(dh->dh);
  1231. }
  1232. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  1233. * success, -1 on failure.
  1234. */
  1235. int
  1236. crypto_dh_generate_public(crypto_dh_env_t *dh)
  1237. {
  1238. again:
  1239. if (!DH_generate_key(dh->dh)) {
  1240. crypto_log_errors(LOG_WARN, "generating DH key");
  1241. return -1;
  1242. }
  1243. if (tor_check_dh_key(dh->dh->pub_key)<0) {
  1244. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  1245. "the-universe chances really do happen. Trying again.");
  1246. /* Free and clear the keys, so openssl will actually try again. */
  1247. BN_free(dh->dh->pub_key);
  1248. BN_free(dh->dh->priv_key);
  1249. dh->dh->pub_key = dh->dh->priv_key = NULL;
  1250. goto again;
  1251. }
  1252. return 0;
  1253. }
  1254. /** Generate g^x as necessary, and write the g^x for the key exchange
  1255. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  1256. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  1257. */
  1258. int
  1259. crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
  1260. {
  1261. int bytes;
  1262. tor_assert(dh);
  1263. if (!dh->dh->pub_key) {
  1264. if (crypto_dh_generate_public(dh)<0)
  1265. return -1;
  1266. }
  1267. tor_assert(dh->dh->pub_key);
  1268. bytes = BN_num_bytes(dh->dh->pub_key);
  1269. tor_assert(bytes >= 0);
  1270. if (pubkey_len < (size_t)bytes) {
  1271. log_warn(LD_CRYPTO,
  1272. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  1273. (int) pubkey_len, bytes);
  1274. return -1;
  1275. }
  1276. memset(pubkey, 0, pubkey_len);
  1277. BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  1278. return 0;
  1279. }
  1280. /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
  1281. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  1282. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  1283. */
  1284. static int
  1285. tor_check_dh_key(BIGNUM *bn)
  1286. {
  1287. BIGNUM *x;
  1288. char *s;
  1289. tor_assert(bn);
  1290. x = BN_new();
  1291. tor_assert(x);
  1292. if (!dh_param_p)
  1293. init_dh_param();
  1294. BN_set_word(x, 1);
  1295. if (BN_cmp(bn,x)<=0) {
  1296. log_warn(LD_CRYPTO, "DH key must be at least 2.");
  1297. goto err;
  1298. }
  1299. BN_copy(x,dh_param_p);
  1300. BN_sub_word(x, 1);
  1301. if (BN_cmp(bn,x)>=0) {
  1302. log_warn(LD_CRYPTO, "DH key must be at most p-2.");
  1303. goto err;
  1304. }
  1305. BN_free(x);
  1306. return 0;
  1307. err:
  1308. BN_free(x);
  1309. s = BN_bn2hex(bn);
  1310. log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  1311. OPENSSL_free(s);
  1312. return -1;
  1313. }
  1314. #undef MIN
  1315. #define MIN(a,b) ((a)<(b)?(a):(b))
  1316. /** Given a DH key exchange object, and our peer's value of g^y (as a
  1317. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  1318. * <b>secret_bytes_out</b> bytes of shared key material and write them
  1319. * to <b>secret_out</b>. Return the number of bytes generated on success,
  1320. * or -1 on failure.
  1321. *
  1322. * (We generate key material by computing
  1323. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  1324. * where || is concatenation.)
  1325. */
  1326. int
  1327. crypto_dh_compute_secret(crypto_dh_env_t *dh,
  1328. const char *pubkey, size_t pubkey_len,
  1329. char *secret_out, size_t secret_bytes_out)
  1330. {
  1331. char *secret_tmp = NULL;
  1332. BIGNUM *pubkey_bn = NULL;
  1333. size_t secret_len=0;
  1334. int result=0;
  1335. tor_assert(dh);
  1336. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  1337. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey, pubkey_len, NULL)))
  1338. goto error;
  1339. if (tor_check_dh_key(pubkey_bn)<0) {
  1340. /* Check for invalid public keys. */
  1341. log_warn(LD_CRYPTO,"Rejected invalid g^x");
  1342. goto error;
  1343. }
  1344. secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
  1345. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  1346. if (result < 0) {
  1347. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  1348. goto error;
  1349. }
  1350. secret_len = result;
  1351. /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
  1352. /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
  1353. * Leading zeros MUST be preserved, so that ZZ occupies as many
  1354. * octets as p. For instance, if p is 1024 bits, ZZ should be 128
  1355. * bytes long.
  1356. * What are the security implications here?
  1357. */
  1358. if (crypto_expand_key_material(secret_tmp, secret_len,
  1359. secret_out, secret_bytes_out)<0)
  1360. goto error;
  1361. secret_len = secret_bytes_out;
  1362. goto done;
  1363. error:
  1364. result = -1;
  1365. done:
  1366. crypto_log_errors(LOG_WARN, "completing DH handshake");
  1367. if (pubkey_bn)
  1368. BN_free(pubkey_bn);
  1369. tor_free(secret_tmp);
  1370. if (result < 0)
  1371. return result;
  1372. else
  1373. return secret_len;
  1374. }
  1375. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  1376. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  1377. * <b>key_out</b> by taking the first key_out_len bytes of
  1378. * H(K | [00]) | H(K | [01]) | ....
  1379. *
  1380. * Return 0 on success, -1 on failure.
  1381. */
  1382. int
  1383. crypto_expand_key_material(const char *key_in, size_t key_in_len,
  1384. char *key_out, size_t key_out_len)
  1385. {
  1386. int i;
  1387. char *cp, *tmp = tor_malloc(key_in_len+1);
  1388. char digest[DIGEST_LEN];
  1389. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1390. tor_assert(key_out_len <= DIGEST_LEN*256);
  1391. memcpy(tmp, key_in, key_in_len);
  1392. for (cp = key_out, i=0; cp < key_out+key_out_len;
  1393. ++i, cp += DIGEST_LEN) {
  1394. tmp[key_in_len] = i;
  1395. if (crypto_digest(digest, tmp, key_in_len+1))
  1396. goto err;
  1397. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  1398. }
  1399. memset(tmp, 0, key_in_len+1);
  1400. tor_free(tmp);
  1401. return 0;
  1402. err:
  1403. memset(tmp, 0, key_in_len+1);
  1404. tor_free(tmp);
  1405. return -1;
  1406. }
  1407. /** Free a DH key exchange object.
  1408. */
  1409. void
  1410. crypto_dh_free(crypto_dh_env_t *dh)
  1411. {
  1412. tor_assert(dh);
  1413. tor_assert(dh->dh);
  1414. DH_free(dh->dh);
  1415. tor_free(dh);
  1416. }
  1417. /* random numbers */
  1418. /* This is how much entropy OpenSSL likes to add right now, so maybe it will
  1419. * work for us too. */
  1420. #define ADD_ENTROPY 32
  1421. /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
  1422. "release".) */
  1423. //#define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
  1424. #define USE_RAND_POLL 0
  1425. /* XXX Somehow setting USE_RAND_POLL on causes stack smashes. We're
  1426. * not sure where. This was the big bug with Tor 0.1.1.9-alpha. */
  1427. /** Seed OpenSSL's random number generator with bytes from the
  1428. * operating system. Return 0 on success, -1 on failure.
  1429. */
  1430. int
  1431. crypto_seed_rng(void)
  1432. {
  1433. char buf[ADD_ENTROPY];
  1434. int rand_poll_status;
  1435. /* local variables */
  1436. #ifdef MS_WINDOWS
  1437. static int provider_set = 0;
  1438. static HCRYPTPROV provider;
  1439. #else
  1440. static const char *filenames[] = {
  1441. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1442. };
  1443. int fd;
  1444. int i, n;
  1445. #endif
  1446. #if USE_RAND_POLL
  1447. /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
  1448. * entropy than we do. We'll try calling that, *and* calling our own entropy
  1449. * functions. If one succeeds, we'll accept the RNG as seeded. */
  1450. rand_poll_status = RAND_poll();
  1451. if (rand_poll_status == 0)
  1452. log_warn(LD_CRYPTO, "RAND_poll() failed.");
  1453. #else
  1454. rand_poll_status = 0;
  1455. #endif
  1456. #ifdef MS_WINDOWS
  1457. if (!provider_set) {
  1458. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  1459. CRYPT_VERIFYCONTEXT)) {
  1460. if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
  1461. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  1462. return rand_poll_status ? 0 : -1;
  1463. }
  1464. }
  1465. provider_set = 1;
  1466. }
  1467. if (!CryptGenRandom(provider, sizeof(buf), buf)) {
  1468. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  1469. return rand_poll_status ? 0 : -1;
  1470. }
  1471. RAND_seed(buf, sizeof(buf));
  1472. return 0;
  1473. #else
  1474. for (i = 0; filenames[i]; ++i) {
  1475. fd = open(filenames[i], O_RDONLY, 0);
  1476. if (fd<0) continue;
  1477. log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
  1478. n = read_all(fd, buf, sizeof(buf), 0);
  1479. close(fd);
  1480. if (n != sizeof(buf)) {
  1481. log_warn(LD_CRYPTO,
  1482. "Error reading from entropy source (read only %d bytes).", n);
  1483. return -1;
  1484. }
  1485. RAND_seed(buf, sizeof(buf));
  1486. return 0;
  1487. }
  1488. log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
  1489. return rand_poll_status ? 0 : -1;
  1490. #endif
  1491. }
  1492. /** Write n bytes of strong random data to <b>to</b>. Return 0 on
  1493. * success, -1 on failure.
  1494. */
  1495. int
  1496. crypto_rand(char *to, size_t n)
  1497. {
  1498. int r;
  1499. tor_assert(to);
  1500. r = RAND_bytes((unsigned char*)to, n);
  1501. if (r == 0)
  1502. crypto_log_errors(LOG_WARN, "generating random data");
  1503. return (r == 1) ? 0 : -1;
  1504. }
  1505. /** Return a pseudorandom integer, chosen uniformly from the values
  1506. * between 0 and max-1. */
  1507. int
  1508. crypto_rand_int(unsigned int max)
  1509. {
  1510. unsigned int val;
  1511. unsigned int cutoff;
  1512. tor_assert(max < UINT_MAX);
  1513. tor_assert(max > 0); /* don't div by 0 */
  1514. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1515. * distribution with clipping at the upper end of unsigned int's
  1516. * range.
  1517. */
  1518. cutoff = UINT_MAX - (UINT_MAX%max);
  1519. while (1) {
  1520. crypto_rand((char*)&val, sizeof(val));
  1521. if (val < cutoff)
  1522. return val % max;
  1523. }
  1524. }
  1525. /** Return a pseudorandom integer, chosen uniformly from the values
  1526. * between 0 and max-1. */
  1527. uint64_t
  1528. crypto_rand_uint64(uint64_t max)
  1529. {
  1530. uint64_t val;
  1531. uint64_t cutoff;
  1532. tor_assert(max < UINT64_MAX);
  1533. tor_assert(max > 0); /* don't div by 0 */
  1534. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1535. * distribution with clipping at the upper end of unsigned int's
  1536. * range.
  1537. */
  1538. cutoff = UINT64_MAX - (UINT64_MAX%max);
  1539. while (1) {
  1540. crypto_rand((char*)&val, sizeof(val));
  1541. if (val < cutoff)
  1542. return val % max;
  1543. }
  1544. }
  1545. /** Return a randomly chosen element of sl; or NULL if sl is empty.
  1546. */
  1547. void *
  1548. smartlist_choose(const smartlist_t *sl)
  1549. {
  1550. size_t len;
  1551. len = smartlist_len(sl);
  1552. if (len)
  1553. return smartlist_get(sl,crypto_rand_int(len));
  1554. return NULL; /* no elements to choose from */
  1555. }
  1556. /** Scramble the elements of sl into a random order. */
  1557. void
  1558. smartlist_shuffle(smartlist_t *sl)
  1559. {
  1560. int i;
  1561. /* From the end of the list to the front, choose at random from the
  1562. positions we haven't looked at yet, and swap that position into the
  1563. current position. Remember to give "no swap" the same probability as
  1564. any other swap. */
  1565. for (i = smartlist_len(sl)-1; i > 0; --i) {
  1566. int j = crypto_rand_int(i+1);
  1567. smartlist_swap(sl, i, j);
  1568. }
  1569. }
  1570. /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
  1571. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1572. * bytes. Return the number of bytes written on success; -1 if
  1573. * destlen is too short, or other failure.
  1574. */
  1575. int
  1576. base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1577. {
  1578. EVP_ENCODE_CTX ctx;
  1579. int len, ret;
  1580. /* 48 bytes of input -> 64 bytes of output plus newline.
  1581. Plus one more byte, in case I'm wrong.
  1582. */
  1583. if (destlen < ((srclen/48)+1)*66)
  1584. return -1;
  1585. if (destlen > SIZE_T_CEILING)
  1586. return -1;
  1587. EVP_EncodeInit(&ctx);
  1588. EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
  1589. (unsigned char*)src, srclen);
  1590. EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
  1591. ret += len;
  1592. return ret;
  1593. }
  1594. /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
  1595. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1596. * bytes. Return the number of bytes written on success; -1 if
  1597. * destlen is too short, or other failure.
  1598. *
  1599. * NOTE: destlen should be a little longer than the amount of data it
  1600. * will contain, since we check for sufficient space conservatively.
  1601. * Here, "a little" is around 64-ish bytes.
  1602. */
  1603. int
  1604. base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  1605. {
  1606. EVP_ENCODE_CTX ctx;
  1607. int len, ret;
  1608. /* 64 bytes of input -> *up to* 48 bytes of output.
  1609. Plus one more byte, in case I'm wrong.
  1610. */
  1611. if (destlen < ((srclen/64)+1)*49)
  1612. return -1;
  1613. if (destlen > SIZE_T_CEILING)
  1614. return -1;
  1615. EVP_DecodeInit(&ctx);
  1616. EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
  1617. (unsigned char*)src, srclen);
  1618. EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
  1619. ret += len;
  1620. return ret;
  1621. }
  1622. /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
  1623. * and newline characters, and store the nul-terminated result in the first
  1624. * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
  1625. int
  1626. digest_to_base64(char *d64, const char *digest)
  1627. {
  1628. char buf[256];
  1629. base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
  1630. buf[BASE64_DIGEST_LEN] = '\0';
  1631. memcpy(d64, buf, BASE64_DIGEST_LEN+1);
  1632. return 0;
  1633. }
  1634. /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
  1635. * trailing newline or = characters), decode it and store the result in the
  1636. * first DIGEST_LEN bytes at <b>digest</b>. */
  1637. int
  1638. digest_from_base64(char *digest, const char *d64)
  1639. {
  1640. char buf_in[BASE64_DIGEST_LEN+3];
  1641. char buf[256];
  1642. if (strlen(d64) != BASE64_DIGEST_LEN)
  1643. return -1;
  1644. memcpy(buf_in, d64, BASE64_DIGEST_LEN);
  1645. memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
  1646. if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
  1647. return -1;
  1648. memcpy(digest, buf, DIGEST_LEN);
  1649. return 0;
  1650. }
  1651. /** Implements base32 encoding as in rfc3548. Limitation: Requires
  1652. * that srclen*8 is a multiple of 5.
  1653. */
  1654. void
  1655. base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1656. {
  1657. unsigned int nbits, i, bit, v, u;
  1658. nbits = srclen * 8;
  1659. tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
  1660. tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
  1661. tor_assert(destlen < SIZE_T_CEILING);
  1662. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  1663. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  1664. v = ((uint8_t)src[bit/8]) << 8;
  1665. if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
  1666. /* set u to the 5-bit value at the bit'th bit of src. */
  1667. u = (v >> (11-(bit%8))) & 0x1F;
  1668. dest[i] = BASE32_CHARS[u];
  1669. }
  1670. dest[i] = '\0';
  1671. }
  1672. /** Implements base32 decoding as in rfc3548. Limitation: Requires
  1673. * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
  1674. */
  1675. int
  1676. base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  1677. {
  1678. unsigned int nbits, i, j, bit;
  1679. char *tmp;
  1680. nbits = srclen * 5;
  1681. tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
  1682. tor_assert((nbits/8) <= destlen); /* We need enough space. */
  1683. tor_assert(destlen < SIZE_T_CEILING);
  1684. /* Convert base32 encoded chars to the 5-bit values that they represent. */
  1685. tmp = tor_malloc_zero(srclen);
  1686. for (j = 0; j < srclen; ++j) {
  1687. if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
  1688. else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
  1689. else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
  1690. else {
  1691. log_warn(LD_BUG, "illegal character in base32 encoded string");
  1692. tor_free(tmp);
  1693. return -1;
  1694. }
  1695. }
  1696. /* Assemble result byte-wise by applying five possible cases. */
  1697. for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
  1698. switch (bit % 40) {
  1699. case 0:
  1700. dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
  1701. (((uint8_t)tmp[(bit/5)+1]) >> 2);
  1702. break;
  1703. case 8:
  1704. dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
  1705. (((uint8_t)tmp[(bit/5)+1]) << 1) +
  1706. (((uint8_t)tmp[(bit/5)+2]) >> 4);
  1707. break;
  1708. case 16:
  1709. dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
  1710. (((uint8_t)tmp[(bit/5)+1]) >> 1);
  1711. break;
  1712. case 24:
  1713. dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
  1714. (((uint8_t)tmp[(bit/5)+1]) << 2) +
  1715. (((uint8_t)tmp[(bit/5)+2]) >> 3);
  1716. break;
  1717. case 32:
  1718. dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
  1719. ((uint8_t)tmp[(bit/5)+1]);
  1720. break;
  1721. }
  1722. }
  1723. tor_free(tmp);
  1724. tmp = NULL;
  1725. return 0;
  1726. }
  1727. /** Implement RFC2440-style iterated-salted S2K conversion: convert the
  1728. * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
  1729. * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
  1730. * are a salt; the 9th byte describes how much iteration to do.
  1731. * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
  1732. */
  1733. void
  1734. secret_to_key(char *key_out, size_t key_out_len, const char *secret,
  1735. size_t secret_len, const char *s2k_specifier)
  1736. {
  1737. crypto_digest_env_t *d;
  1738. uint8_t c;
  1739. size_t count;
  1740. char *tmp;
  1741. tor_assert(key_out_len < SIZE_T_CEILING);
  1742. #define EXPBIAS 6
  1743. c = s2k_specifier[8];
  1744. count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
  1745. #undef EXPBIAS
  1746. tor_assert(key_out_len <= DIGEST_LEN);
  1747. d = crypto_new_digest_env();
  1748. tmp = tor_malloc(8+secret_len);
  1749. memcpy(tmp,s2k_specifier,8);
  1750. memcpy(tmp+8,secret,secret_len);
  1751. secret_len += 8;
  1752. while (count) {
  1753. if (count >= secret_len) {
  1754. crypto_digest_add_bytes(d, tmp, secret_len);
  1755. count -= secret_len;
  1756. } else {
  1757. crypto_digest_add_bytes(d, tmp, count);
  1758. count = 0;
  1759. }
  1760. }
  1761. crypto_digest_get_digest(d, key_out, key_out_len);
  1762. tor_free(tmp);
  1763. crypto_free_digest_env(d);
  1764. }
  1765. #ifdef TOR_IS_MULTITHREADED
  1766. /** Helper: openssl uses this callback to manipulate mutexes. */
  1767. static void
  1768. _openssl_locking_cb(int mode, int n, const char *file, int line)
  1769. {
  1770. (void)file;
  1771. (void)line;
  1772. if (!_openssl_mutexes)
  1773. /* This is not a really good fix for the
  1774. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  1775. * it can't hurt. */
  1776. return;
  1777. if (mode & CRYPTO_LOCK)
  1778. tor_mutex_acquire(_openssl_mutexes[n]);
  1779. else
  1780. tor_mutex_release(_openssl_mutexes[n]);
  1781. }
  1782. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  1783. * multithreaded. */
  1784. static int
  1785. setup_openssl_threading(void)
  1786. {
  1787. int i;
  1788. int n = CRYPTO_num_locks();
  1789. _n_openssl_mutexes = n;
  1790. _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
  1791. for (i=0; i < n; ++i)
  1792. _openssl_mutexes[i] = tor_mutex_new();
  1793. CRYPTO_set_locking_callback(_openssl_locking_cb);
  1794. CRYPTO_set_id_callback(tor_get_thread_id);
  1795. return 0;
  1796. }
  1797. #else
  1798. static int
  1799. setup_openssl_threading(void)
  1800. {
  1801. return 0;
  1802. }
  1803. #endif