crypto.c 66 KB

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