crypto.c 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452
  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. /** Return true iff <b>env</b> contains a public key whose public exponent
  576. * equals 65537.
  577. */
  578. int
  579. crypto_pk_check_key_public_exponent(crypto_pk_env_t *env)
  580. {
  581. tor_assert(env);
  582. tor_assert(env->key);
  583. return BN_is_word(env->key->e, 65537);
  584. }
  585. /** Compare the public-key components of a and b. Return -1 if a\<b, 0
  586. * if a==b, and 1 if a\>b.
  587. */
  588. int
  589. crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
  590. {
  591. int result;
  592. if (!a || !b)
  593. return -1;
  594. if (!a->key || !b->key)
  595. return -1;
  596. tor_assert(PUBLIC_KEY_OK(a));
  597. tor_assert(PUBLIC_KEY_OK(b));
  598. result = BN_cmp((a->key)->n, (b->key)->n);
  599. if (result)
  600. return result;
  601. return BN_cmp((a->key)->e, (b->key)->e);
  602. }
  603. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  604. size_t
  605. crypto_pk_keysize(crypto_pk_env_t *env)
  606. {
  607. tor_assert(env);
  608. tor_assert(env->key);
  609. return (size_t) RSA_size(env->key);
  610. }
  611. /** Increase the reference count of <b>env</b>, and return it.
  612. */
  613. crypto_pk_env_t *
  614. crypto_pk_dup_key(crypto_pk_env_t *env)
  615. {
  616. tor_assert(env);
  617. tor_assert(env->key);
  618. env->refs++;
  619. return env;
  620. }
  621. /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
  622. crypto_pk_env_t *
  623. crypto_pk_copy_full(crypto_pk_env_t *env)
  624. {
  625. RSA *new_key;
  626. tor_assert(env);
  627. tor_assert(env->key);
  628. if (PRIVATE_KEY_OK(env)) {
  629. new_key = RSAPrivateKey_dup(env->key);
  630. } else {
  631. new_key = RSAPublicKey_dup(env->key);
  632. }
  633. return _crypto_new_pk_env_rsa(new_key);
  634. }
  635. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  636. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  637. * write the result to <b>to</b>, and return the number of bytes
  638. * written. On failure, return -1.
  639. *
  640. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  641. * at least the length of the modulus of <b>env</b>.
  642. */
  643. int
  644. crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to, size_t tolen,
  645. const char *from, size_t fromlen, int padding)
  646. {
  647. int r;
  648. tor_assert(env);
  649. tor_assert(from);
  650. tor_assert(to);
  651. tor_assert(fromlen<INT_MAX);
  652. tor_assert(tolen >= crypto_pk_keysize(env));
  653. r = RSA_public_encrypt((int)fromlen,
  654. (unsigned char*)from, (unsigned char*)to,
  655. env->key, crypto_get_rsa_padding(padding));
  656. if (r<0) {
  657. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  658. return -1;
  659. }
  660. return r;
  661. }
  662. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  663. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  664. * write the result to <b>to</b>, and return the number of bytes
  665. * written. On failure, return -1.
  666. *
  667. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  668. * at least the length of the modulus of <b>env</b>.
  669. */
  670. int
  671. crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
  672. size_t tolen,
  673. const char *from, size_t fromlen,
  674. int padding, int warnOnFailure)
  675. {
  676. int r;
  677. tor_assert(env);
  678. tor_assert(from);
  679. tor_assert(to);
  680. tor_assert(env->key);
  681. tor_assert(fromlen<INT_MAX);
  682. tor_assert(tolen >= crypto_pk_keysize(env));
  683. if (!env->key->p)
  684. /* Not a private key */
  685. return -1;
  686. r = RSA_private_decrypt((int)fromlen,
  687. (unsigned char*)from, (unsigned char*)to,
  688. env->key, crypto_get_rsa_padding(padding));
  689. if (r<0) {
  690. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  691. "performing RSA decryption");
  692. return -1;
  693. }
  694. return r;
  695. }
  696. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  697. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  698. * signed data to <b>to</b>, and return the number of bytes written.
  699. * On failure, return -1.
  700. *
  701. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  702. * at least the length of the modulus of <b>env</b>.
  703. */
  704. int
  705. crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
  706. size_t tolen,
  707. const char *from, size_t fromlen)
  708. {
  709. int r;
  710. tor_assert(env);
  711. tor_assert(from);
  712. tor_assert(to);
  713. tor_assert(fromlen < INT_MAX);
  714. tor_assert(tolen >= crypto_pk_keysize(env));
  715. r = RSA_public_decrypt((int)fromlen,
  716. (unsigned char*)from, (unsigned char*)to,
  717. env->key, RSA_PKCS1_PADDING);
  718. if (r<0) {
  719. crypto_log_errors(LOG_WARN, "checking RSA signature");
  720. return -1;
  721. }
  722. return r;
  723. }
  724. /** Check a siglen-byte long signature at <b>sig</b> against
  725. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  726. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  727. * SHA1(data). Else return -1.
  728. */
  729. int
  730. crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
  731. size_t datalen, const char *sig, size_t siglen)
  732. {
  733. char digest[DIGEST_LEN];
  734. char *buf;
  735. size_t buflen;
  736. int r;
  737. tor_assert(env);
  738. tor_assert(data);
  739. tor_assert(sig);
  740. tor_assert(datalen < SIZE_T_CEILING);
  741. tor_assert(siglen < SIZE_T_CEILING);
  742. if (crypto_digest(digest,data,datalen)<0) {
  743. log_warn(LD_BUG, "couldn't compute digest");
  744. return -1;
  745. }
  746. buflen = crypto_pk_keysize(env)+1;
  747. buf = tor_malloc(buflen);
  748. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  749. if (r != DIGEST_LEN) {
  750. log_warn(LD_CRYPTO, "Invalid signature");
  751. tor_free(buf);
  752. return -1;
  753. }
  754. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  755. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  756. tor_free(buf);
  757. return -1;
  758. }
  759. tor_free(buf);
  760. return 0;
  761. }
  762. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  763. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  764. * <b>to</b>, and return the number of bytes written. On failure, return
  765. * -1.
  766. *
  767. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  768. * at least the length of the modulus of <b>env</b>.
  769. */
  770. int
  771. crypto_pk_private_sign(crypto_pk_env_t *env, char *to, size_t tolen,
  772. const char *from, size_t fromlen)
  773. {
  774. int r;
  775. tor_assert(env);
  776. tor_assert(from);
  777. tor_assert(to);
  778. tor_assert(fromlen < INT_MAX);
  779. tor_assert(tolen >= crypto_pk_keysize(env));
  780. if (!env->key->p)
  781. /* Not a private key */
  782. return -1;
  783. r = RSA_private_encrypt((int)fromlen,
  784. (unsigned char*)from, (unsigned char*)to,
  785. env->key, RSA_PKCS1_PADDING);
  786. if (r<0) {
  787. crypto_log_errors(LOG_WARN, "generating RSA signature");
  788. return -1;
  789. }
  790. return r;
  791. }
  792. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  793. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  794. * store it in <b>to</b>. Return the number of bytes written on
  795. * success, and -1 on failure.
  796. *
  797. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  798. * at least the length of the modulus of <b>env</b>.
  799. */
  800. int
  801. crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to, size_t tolen,
  802. const char *from, size_t fromlen)
  803. {
  804. int r;
  805. char digest[DIGEST_LEN];
  806. if (crypto_digest(digest,from,fromlen)<0)
  807. return -1;
  808. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  809. memset(digest, 0, sizeof(digest));
  810. return r;
  811. }
  812. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  813. * bytes of data from <b>from</b>, with padding type 'padding',
  814. * storing the results on <b>to</b>.
  815. *
  816. * If no padding is used, the public key must be at least as large as
  817. * <b>from</b>.
  818. *
  819. * Returns the number of bytes written on success, -1 on failure.
  820. *
  821. * The encrypted data consists of:
  822. * - The source data, padded and encrypted with the public key, if the
  823. * padded source data is no longer than the public key, and <b>force</b>
  824. * is false, OR
  825. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  826. * padded and encrypted with the public key; followed by the rest of
  827. * the source data encrypted in AES-CTR mode with the symmetric key.
  828. */
  829. int
  830. crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
  831. char *to, size_t tolen,
  832. const char *from,
  833. size_t fromlen,
  834. int padding, int force)
  835. {
  836. int overhead, outlen, r;
  837. size_t pkeylen, symlen;
  838. crypto_cipher_env_t *cipher = NULL;
  839. char *buf = NULL;
  840. tor_assert(env);
  841. tor_assert(from);
  842. tor_assert(to);
  843. tor_assert(fromlen < SIZE_T_CEILING);
  844. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  845. pkeylen = crypto_pk_keysize(env);
  846. if (padding == PK_NO_PADDING && fromlen < pkeylen)
  847. return -1;
  848. if (!force && fromlen+overhead <= pkeylen) {
  849. /* It all fits in a single encrypt. */
  850. return crypto_pk_public_encrypt(env,to,
  851. tolen,
  852. from,fromlen,padding);
  853. }
  854. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  855. tor_assert(tolen >= pkeylen);
  856. cipher = crypto_new_cipher_env();
  857. if (!cipher) return -1;
  858. if (crypto_cipher_generate_key(cipher)<0)
  859. goto err;
  860. /* You can't just run around RSA-encrypting any bitstream: if it's
  861. * greater than the RSA key, then OpenSSL will happily encrypt, and
  862. * later decrypt to the wrong value. So we set the first bit of
  863. * 'cipher->key' to 0 if we aren't padding. This means that our
  864. * symmetric key is really only 127 bits.
  865. */
  866. if (padding == PK_NO_PADDING)
  867. cipher->key[0] &= 0x7f;
  868. if (crypto_cipher_encrypt_init_cipher(cipher)<0)
  869. goto err;
  870. buf = tor_malloc(pkeylen+1);
  871. memcpy(buf, cipher->key, CIPHER_KEY_LEN);
  872. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  873. /* Length of symmetrically encrypted data. */
  874. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  875. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  876. if (outlen!=(int)pkeylen) {
  877. goto err;
  878. }
  879. r = crypto_cipher_encrypt(cipher, to+outlen,
  880. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  881. if (r<0) goto err;
  882. memset(buf, 0, pkeylen);
  883. tor_free(buf);
  884. crypto_free_cipher_env(cipher);
  885. tor_assert(outlen+symlen < INT_MAX);
  886. return (int)(outlen + symlen);
  887. err:
  888. if (buf) {
  889. memset(buf, 0, pkeylen);
  890. tor_free(buf);
  891. }
  892. if (cipher) crypto_free_cipher_env(cipher);
  893. return -1;
  894. }
  895. /** Invert crypto_pk_public_hybrid_encrypt. */
  896. int
  897. crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
  898. char *to,
  899. size_t tolen,
  900. const char *from,
  901. size_t fromlen,
  902. int padding, int warnOnFailure)
  903. {
  904. int outlen, r;
  905. size_t pkeylen;
  906. crypto_cipher_env_t *cipher = NULL;
  907. char *buf = NULL;
  908. tor_assert(fromlen < SIZE_T_CEILING);
  909. pkeylen = crypto_pk_keysize(env);
  910. if (fromlen <= pkeylen) {
  911. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  912. warnOnFailure);
  913. }
  914. buf = tor_malloc(pkeylen+1);
  915. outlen = crypto_pk_private_decrypt(env,buf,pkeylen+1,from,pkeylen,padding,
  916. warnOnFailure);
  917. if (outlen<0) {
  918. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  919. "Error decrypting public-key data");
  920. goto err;
  921. }
  922. if (outlen < CIPHER_KEY_LEN) {
  923. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  924. "No room for a symmetric key");
  925. goto err;
  926. }
  927. cipher = crypto_create_init_cipher(buf, 0);
  928. if (!cipher) {
  929. goto err;
  930. }
  931. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  932. outlen -= CIPHER_KEY_LEN;
  933. tor_assert(tolen - outlen >= fromlen - pkeylen);
  934. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  935. if (r<0)
  936. goto err;
  937. memset(buf,0,pkeylen);
  938. tor_free(buf);
  939. crypto_free_cipher_env(cipher);
  940. tor_assert(outlen + fromlen < INT_MAX);
  941. return (int)(outlen + (fromlen-pkeylen));
  942. err:
  943. memset(buf,0,pkeylen);
  944. tor_free(buf);
  945. if (cipher) crypto_free_cipher_env(cipher);
  946. return -1;
  947. }
  948. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  949. * Return -1 on error, or the number of characters used on success.
  950. */
  951. int
  952. crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
  953. {
  954. int len;
  955. unsigned char *buf, *cp;
  956. len = i2d_RSAPublicKey(pk->key, NULL);
  957. if (len < 0 || (size_t)len > dest_len || dest_len > SIZE_T_CEILING)
  958. return -1;
  959. cp = buf = tor_malloc(len+1);
  960. len = i2d_RSAPublicKey(pk->key, &cp);
  961. if (len < 0) {
  962. crypto_log_errors(LOG_WARN,"encoding public key");
  963. tor_free(buf);
  964. return -1;
  965. }
  966. /* We don't encode directly into 'dest', because that would be illegal
  967. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  968. */
  969. memcpy(dest,buf,len);
  970. tor_free(buf);
  971. return len;
  972. }
  973. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  974. * success and NULL on failure.
  975. */
  976. crypto_pk_env_t *
  977. crypto_pk_asn1_decode(const char *str, size_t len)
  978. {
  979. RSA *rsa;
  980. unsigned char *buf;
  981. /* This ifdef suppresses a type warning. Take out the first case once
  982. * everybody is using OpenSSL 0.9.7 or later.
  983. */
  984. const unsigned char *cp;
  985. cp = buf = tor_malloc(len);
  986. memcpy(buf,str,len);
  987. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  988. tor_free(buf);
  989. if (!rsa) {
  990. crypto_log_errors(LOG_WARN,"decoding public key");
  991. return NULL;
  992. }
  993. return _crypto_new_pk_env_rsa(rsa);
  994. }
  995. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  996. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  997. * Return 0 on success, -1 on failure.
  998. */
  999. int
  1000. crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
  1001. {
  1002. unsigned char *buf, *bufp;
  1003. int len;
  1004. len = i2d_RSAPublicKey(pk->key, NULL);
  1005. if (len < 0)
  1006. return -1;
  1007. buf = bufp = tor_malloc(len+1);
  1008. len = i2d_RSAPublicKey(pk->key, &bufp);
  1009. if (len < 0) {
  1010. crypto_log_errors(LOG_WARN,"encoding public key");
  1011. tor_free(buf);
  1012. return -1;
  1013. }
  1014. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  1015. tor_free(buf);
  1016. return -1;
  1017. }
  1018. tor_free(buf);
  1019. return 0;
  1020. }
  1021. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  1022. * every four spaces. */
  1023. /* static */ void
  1024. add_spaces_to_fp(char *out, size_t outlen, const char *in)
  1025. {
  1026. int n = 0;
  1027. char *end = out+outlen;
  1028. tor_assert(outlen < SIZE_T_CEILING);
  1029. while (*in && out<end) {
  1030. *out++ = *in++;
  1031. if (++n == 4 && *in && out<end) {
  1032. n = 0;
  1033. *out++ = ' ';
  1034. }
  1035. }
  1036. tor_assert(out<end);
  1037. *out = '\0';
  1038. }
  1039. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  1040. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  1041. * space). Return 0 on success, -1 on failure.
  1042. *
  1043. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  1044. * of the public key, converted to hexadecimal, in upper case, with a
  1045. * space after every four digits.
  1046. *
  1047. * If <b>add_space</b> is false, omit the spaces.
  1048. */
  1049. int
  1050. crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
  1051. {
  1052. char digest[DIGEST_LEN];
  1053. char hexdigest[HEX_DIGEST_LEN+1];
  1054. if (crypto_pk_get_digest(pk, digest)) {
  1055. return -1;
  1056. }
  1057. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  1058. if (add_space) {
  1059. add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  1060. } else {
  1061. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  1062. }
  1063. return 0;
  1064. }
  1065. /** Return true iff <b>s</b> is in the correct format for a fingerprint.
  1066. */
  1067. int
  1068. crypto_pk_check_fingerprint_syntax(const char *s)
  1069. {
  1070. int i;
  1071. for (i = 0; i < FINGERPRINT_LEN; ++i) {
  1072. if ((i%5) == 4) {
  1073. if (!TOR_ISSPACE(s[i])) return 0;
  1074. } else {
  1075. if (!TOR_ISXDIGIT(s[i])) return 0;
  1076. }
  1077. }
  1078. if (s[FINGERPRINT_LEN]) return 0;
  1079. return 1;
  1080. }
  1081. /* symmetric crypto */
  1082. /** Generate a new random key for the symmetric cipher in <b>env</b>.
  1083. * Return 0 on success, -1 on failure. Does not initialize the cipher.
  1084. */
  1085. int
  1086. crypto_cipher_generate_key(crypto_cipher_env_t *env)
  1087. {
  1088. tor_assert(env);
  1089. return crypto_rand(env->key, CIPHER_KEY_LEN);
  1090. }
  1091. /** Set the symmetric key for the cipher in <b>env</b> to the first
  1092. * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
  1093. * Return 0 on success, -1 on failure.
  1094. */
  1095. int
  1096. crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
  1097. {
  1098. tor_assert(env);
  1099. tor_assert(key);
  1100. if (!env->key)
  1101. return -1;
  1102. memcpy(env->key, key, CIPHER_KEY_LEN);
  1103. return 0;
  1104. }
  1105. /** Generate an initialization vector for our AES-CTR cipher; store it
  1106. * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
  1107. void
  1108. crypto_cipher_generate_iv(char *iv_out)
  1109. {
  1110. crypto_rand(iv_out, CIPHER_IV_LEN);
  1111. }
  1112. /** Adjust the counter of <b>env</b> to point to the first byte of the block
  1113. * corresponding to the encryption of the CIPHER_IV_LEN bytes at
  1114. * <b>iv</b>. */
  1115. int
  1116. crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
  1117. {
  1118. tor_assert(env);
  1119. tor_assert(iv);
  1120. aes_set_iv(env->cipher, iv);
  1121. return 0;
  1122. }
  1123. /** Return a pointer to the key set for the cipher in <b>env</b>.
  1124. */
  1125. const char *
  1126. crypto_cipher_get_key(crypto_cipher_env_t *env)
  1127. {
  1128. return env->key;
  1129. }
  1130. /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
  1131. * success, -1 on failure.
  1132. */
  1133. int
  1134. crypto_cipher_encrypt_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. /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
  1141. * success, -1 on failure.
  1142. */
  1143. int
  1144. crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
  1145. {
  1146. tor_assert(env);
  1147. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  1148. return 0;
  1149. }
  1150. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1151. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1152. * On failure, return -1.
  1153. */
  1154. int
  1155. crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
  1156. const char *from, size_t fromlen)
  1157. {
  1158. tor_assert(env);
  1159. tor_assert(env->cipher);
  1160. tor_assert(from);
  1161. tor_assert(fromlen);
  1162. tor_assert(to);
  1163. tor_assert(fromlen < SIZE_T_CEILING);
  1164. aes_crypt(env->cipher, from, fromlen, to);
  1165. return 0;
  1166. }
  1167. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1168. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1169. * On failure, return -1.
  1170. */
  1171. int
  1172. crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
  1173. const char *from, size_t fromlen)
  1174. {
  1175. tor_assert(env);
  1176. tor_assert(from);
  1177. tor_assert(to);
  1178. tor_assert(fromlen < SIZE_T_CEILING);
  1179. aes_crypt(env->cipher, from, fromlen, to);
  1180. return 0;
  1181. }
  1182. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  1183. * on success, return 0. On failure, return -1.
  1184. */
  1185. int
  1186. crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
  1187. {
  1188. tor_assert(len < SIZE_T_CEILING);
  1189. aes_crypt_inplace(env->cipher, buf, len);
  1190. return 0;
  1191. }
  1192. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1193. * <b>cipher</b> to the buffer in <b>to</b> of length
  1194. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1195. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1196. * number of bytes written, on failure, return -1.
  1197. *
  1198. * This function adjusts the current position of the counter in <b>cipher</b>
  1199. * to immediately after the encrypted data.
  1200. */
  1201. int
  1202. crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
  1203. char *to, size_t tolen,
  1204. const char *from, size_t fromlen)
  1205. {
  1206. tor_assert(cipher);
  1207. tor_assert(from);
  1208. tor_assert(to);
  1209. tor_assert(fromlen < INT_MAX);
  1210. if (fromlen < 1)
  1211. return -1;
  1212. if (tolen < fromlen + CIPHER_IV_LEN)
  1213. return -1;
  1214. crypto_cipher_generate_iv(to);
  1215. if (crypto_cipher_set_iv(cipher, to)<0)
  1216. return -1;
  1217. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1218. return (int)(fromlen + CIPHER_IV_LEN);
  1219. }
  1220. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1221. * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
  1222. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1223. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1224. * number of bytes written, on failure, return -1.
  1225. *
  1226. * This function adjusts the current position of the counter in <b>cipher</b>
  1227. * to immediately after the decrypted data.
  1228. */
  1229. int
  1230. crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
  1231. char *to, size_t tolen,
  1232. const char *from, size_t fromlen)
  1233. {
  1234. tor_assert(cipher);
  1235. tor_assert(from);
  1236. tor_assert(to);
  1237. tor_assert(fromlen < INT_MAX);
  1238. if (fromlen <= CIPHER_IV_LEN)
  1239. return -1;
  1240. if (tolen < fromlen - CIPHER_IV_LEN)
  1241. return -1;
  1242. if (crypto_cipher_set_iv(cipher, from)<0)
  1243. return -1;
  1244. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1245. return (int)(fromlen - CIPHER_IV_LEN);
  1246. }
  1247. /* SHA-1 */
  1248. /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
  1249. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1250. * Return 0 on success, -1 on failure.
  1251. */
  1252. int
  1253. crypto_digest(char *digest, const char *m, size_t len)
  1254. {
  1255. tor_assert(m);
  1256. tor_assert(digest);
  1257. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1258. }
  1259. /** Intermediate information about the digest of a stream of data. */
  1260. struct crypto_digest_env_t {
  1261. SHA_CTX d;
  1262. };
  1263. /** Allocate and return a new digest object.
  1264. */
  1265. crypto_digest_env_t *
  1266. crypto_new_digest_env(void)
  1267. {
  1268. crypto_digest_env_t *r;
  1269. r = tor_malloc(sizeof(crypto_digest_env_t));
  1270. SHA1_Init(&r->d);
  1271. return r;
  1272. }
  1273. /** Deallocate a digest object.
  1274. */
  1275. void
  1276. crypto_free_digest_env(crypto_digest_env_t *digest)
  1277. {
  1278. memset(digest, 0, sizeof(crypto_digest_env_t));
  1279. tor_free(digest);
  1280. }
  1281. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1282. */
  1283. void
  1284. crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
  1285. size_t len)
  1286. {
  1287. tor_assert(digest);
  1288. tor_assert(data);
  1289. /* Using the SHA1_*() calls directly means we don't support doing
  1290. * SHA1 in hardware. But so far the delay of getting the question
  1291. * to the hardware, and hearing the answer, is likely higher than
  1292. * just doing it ourselves. Hashes are fast.
  1293. */
  1294. SHA1_Update(&digest->d, (void*)data, len);
  1295. }
  1296. /** Compute the hash of the data that has been passed to the digest
  1297. * object; write the first out_len bytes of the result to <b>out</b>.
  1298. * <b>out_len</b> must be \<= DIGEST_LEN.
  1299. */
  1300. void
  1301. crypto_digest_get_digest(crypto_digest_env_t *digest,
  1302. char *out, size_t out_len)
  1303. {
  1304. unsigned char r[DIGEST_LEN];
  1305. SHA_CTX tmpctx;
  1306. tor_assert(digest);
  1307. tor_assert(out);
  1308. tor_assert(out_len <= DIGEST_LEN);
  1309. /* memcpy into a temporary ctx, since SHA1_Final clears the context */
  1310. memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
  1311. SHA1_Final(r, &tmpctx);
  1312. memcpy(out, r, out_len);
  1313. memset(r, 0, sizeof(r));
  1314. }
  1315. /** Allocate and return a new digest object with the same state as
  1316. * <b>digest</b>
  1317. */
  1318. crypto_digest_env_t *
  1319. crypto_digest_dup(const crypto_digest_env_t *digest)
  1320. {
  1321. crypto_digest_env_t *r;
  1322. tor_assert(digest);
  1323. r = tor_malloc(sizeof(crypto_digest_env_t));
  1324. memcpy(r,digest,sizeof(crypto_digest_env_t));
  1325. return r;
  1326. }
  1327. /** Replace the state of the digest object <b>into</b> with the state
  1328. * of the digest object <b>from</b>.
  1329. */
  1330. void
  1331. crypto_digest_assign(crypto_digest_env_t *into,
  1332. const crypto_digest_env_t *from)
  1333. {
  1334. tor_assert(into);
  1335. tor_assert(from);
  1336. memcpy(into,from,sizeof(crypto_digest_env_t));
  1337. }
  1338. /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1339. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
  1340. * in <b>hmac_out</b>.
  1341. */
  1342. void
  1343. crypto_hmac_sha1(char *hmac_out,
  1344. const char *key, size_t key_len,
  1345. const char *msg, size_t msg_len)
  1346. {
  1347. tor_assert(key_len < INT_MAX);
  1348. tor_assert(msg_len < INT_MAX);
  1349. HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  1350. (unsigned char*)hmac_out, NULL);
  1351. }
  1352. /* DH */
  1353. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  1354. static BIGNUM *dh_param_p = NULL;
  1355. /** Shared P parameter for our TLS DH key exchanges. */
  1356. static BIGNUM *dh_param_p_tls = NULL;
  1357. /** Shared G parameter for our DH key exchanges. */
  1358. static BIGNUM *dh_param_g = NULL;
  1359. /** Initialize dh_param_p and dh_param_g if they are not already
  1360. * set. */
  1361. static void
  1362. init_dh_param(void)
  1363. {
  1364. BIGNUM *p, *p2, *g;
  1365. int r;
  1366. if (dh_param_p && dh_param_g && dh_param_p_tls)
  1367. return;
  1368. p = BN_new();
  1369. p2 = BN_new();
  1370. g = BN_new();
  1371. tor_assert(p);
  1372. tor_assert(p2);
  1373. tor_assert(g);
  1374. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1375. supposedly it equals:
  1376. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1377. */
  1378. r = BN_hex2bn(&p,
  1379. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1380. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1381. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1382. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1383. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1384. tor_assert(r);
  1385. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  1386. * modules/ssl/ssl_engine_dh.c */
  1387. r = BN_hex2bn(&p2,
  1388. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  1389. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  1390. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  1391. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  1392. "B0E7393E0F24218EB3");
  1393. tor_assert(r);
  1394. r = BN_set_word(g, 2);
  1395. tor_assert(r);
  1396. dh_param_p = p;
  1397. dh_param_p_tls = p2;
  1398. dh_param_g = g;
  1399. }
  1400. #define DH_PRIVATE_KEY_BITS 320
  1401. /** Allocate and return a new DH object for a key exchange.
  1402. */
  1403. crypto_dh_env_t *
  1404. crypto_dh_new(int dh_type)
  1405. {
  1406. crypto_dh_env_t *res = tor_malloc_zero(sizeof(crypto_dh_env_t));
  1407. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  1408. dh_type == DH_TYPE_REND);
  1409. if (!dh_param_p)
  1410. init_dh_param();
  1411. if (!(res->dh = DH_new()))
  1412. goto err;
  1413. if (dh_type == DH_TYPE_TLS) {
  1414. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  1415. goto err;
  1416. } else {
  1417. if (!(res->dh->p = BN_dup(dh_param_p)))
  1418. goto err;
  1419. }
  1420. if (!(res->dh->g = BN_dup(dh_param_g)))
  1421. goto err;
  1422. res->dh->length = DH_PRIVATE_KEY_BITS;
  1423. return res;
  1424. err:
  1425. crypto_log_errors(LOG_WARN, "creating DH object");
  1426. if (res->dh) DH_free(res->dh); /* frees p and g too */
  1427. tor_free(res);
  1428. return NULL;
  1429. }
  1430. /** Return the length of the DH key in <b>dh</b>, in bytes.
  1431. */
  1432. int
  1433. crypto_dh_get_bytes(crypto_dh_env_t *dh)
  1434. {
  1435. tor_assert(dh);
  1436. return DH_size(dh->dh);
  1437. }
  1438. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  1439. * success, -1 on failure.
  1440. */
  1441. int
  1442. crypto_dh_generate_public(crypto_dh_env_t *dh)
  1443. {
  1444. again:
  1445. if (!DH_generate_key(dh->dh)) {
  1446. crypto_log_errors(LOG_WARN, "generating DH key");
  1447. return -1;
  1448. }
  1449. if (tor_check_dh_key(dh->dh->pub_key)<0) {
  1450. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  1451. "the-universe chances really do happen. Trying again.");
  1452. /* Free and clear the keys, so OpenSSL will actually try again. */
  1453. BN_free(dh->dh->pub_key);
  1454. BN_free(dh->dh->priv_key);
  1455. dh->dh->pub_key = dh->dh->priv_key = NULL;
  1456. goto again;
  1457. }
  1458. return 0;
  1459. }
  1460. /** Generate g^x as necessary, and write the g^x for the key exchange
  1461. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  1462. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  1463. */
  1464. int
  1465. crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
  1466. {
  1467. int bytes;
  1468. tor_assert(dh);
  1469. if (!dh->dh->pub_key) {
  1470. if (crypto_dh_generate_public(dh)<0)
  1471. return -1;
  1472. }
  1473. tor_assert(dh->dh->pub_key);
  1474. bytes = BN_num_bytes(dh->dh->pub_key);
  1475. tor_assert(bytes >= 0);
  1476. if (pubkey_len < (size_t)bytes) {
  1477. log_warn(LD_CRYPTO,
  1478. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  1479. (int) pubkey_len, bytes);
  1480. return -1;
  1481. }
  1482. memset(pubkey, 0, pubkey_len);
  1483. BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  1484. return 0;
  1485. }
  1486. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  1487. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  1488. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  1489. */
  1490. static int
  1491. tor_check_dh_key(BIGNUM *bn)
  1492. {
  1493. BIGNUM *x;
  1494. char *s;
  1495. tor_assert(bn);
  1496. x = BN_new();
  1497. tor_assert(x);
  1498. if (!dh_param_p)
  1499. init_dh_param();
  1500. BN_set_word(x, 1);
  1501. if (BN_cmp(bn,x)<=0) {
  1502. log_warn(LD_CRYPTO, "DH key must be at least 2.");
  1503. goto err;
  1504. }
  1505. BN_copy(x,dh_param_p);
  1506. BN_sub_word(x, 1);
  1507. if (BN_cmp(bn,x)>=0) {
  1508. log_warn(LD_CRYPTO, "DH key must be at most p-2.");
  1509. goto err;
  1510. }
  1511. BN_free(x);
  1512. return 0;
  1513. err:
  1514. BN_free(x);
  1515. s = BN_bn2hex(bn);
  1516. log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  1517. OPENSSL_free(s);
  1518. return -1;
  1519. }
  1520. #undef MIN
  1521. #define MIN(a,b) ((a)<(b)?(a):(b))
  1522. /** Given a DH key exchange object, and our peer's value of g^y (as a
  1523. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  1524. * <b>secret_bytes_out</b> bytes of shared key material and write them
  1525. * to <b>secret_out</b>. Return the number of bytes generated on success,
  1526. * or -1 on failure.
  1527. *
  1528. * (We generate key material by computing
  1529. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  1530. * where || is concatenation.)
  1531. */
  1532. ssize_t
  1533. crypto_dh_compute_secret(crypto_dh_env_t *dh,
  1534. const char *pubkey, size_t pubkey_len,
  1535. char *secret_out, size_t secret_bytes_out)
  1536. {
  1537. char *secret_tmp = NULL;
  1538. BIGNUM *pubkey_bn = NULL;
  1539. size_t secret_len=0, secret_tmp_len=0;
  1540. int result=0;
  1541. tor_assert(dh);
  1542. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  1543. tor_assert(pubkey_len < INT_MAX);
  1544. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  1545. (int)pubkey_len, NULL)))
  1546. goto error;
  1547. if (tor_check_dh_key(pubkey_bn)<0) {
  1548. /* Check for invalid public keys. */
  1549. log_warn(LD_CRYPTO,"Rejected invalid g^x");
  1550. goto error;
  1551. }
  1552. secret_tmp_len = crypto_dh_get_bytes(dh);
  1553. secret_tmp = tor_malloc(secret_tmp_len);
  1554. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  1555. if (result < 0) {
  1556. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  1557. goto error;
  1558. }
  1559. secret_len = result;
  1560. if (crypto_expand_key_material(secret_tmp, secret_len,
  1561. secret_out, secret_bytes_out)<0)
  1562. goto error;
  1563. secret_len = secret_bytes_out;
  1564. goto done;
  1565. error:
  1566. result = -1;
  1567. done:
  1568. crypto_log_errors(LOG_WARN, "completing DH handshake");
  1569. if (pubkey_bn)
  1570. BN_free(pubkey_bn);
  1571. if (secret_tmp) {
  1572. memset(secret_tmp, 0, secret_tmp_len);
  1573. tor_free(secret_tmp);
  1574. }
  1575. if (result < 0)
  1576. return result;
  1577. else
  1578. return secret_len;
  1579. }
  1580. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  1581. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  1582. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  1583. * H(K | [00]) | H(K | [01]) | ....
  1584. *
  1585. * Return 0 on success, -1 on failure.
  1586. */
  1587. int
  1588. crypto_expand_key_material(const char *key_in, size_t key_in_len,
  1589. char *key_out, size_t key_out_len)
  1590. {
  1591. int i;
  1592. char *cp, *tmp = tor_malloc(key_in_len+1);
  1593. char digest[DIGEST_LEN];
  1594. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1595. tor_assert(key_out_len <= DIGEST_LEN*256);
  1596. memcpy(tmp, key_in, key_in_len);
  1597. for (cp = key_out, i=0; cp < key_out+key_out_len;
  1598. ++i, cp += DIGEST_LEN) {
  1599. tmp[key_in_len] = i;
  1600. if (crypto_digest(digest, tmp, key_in_len+1))
  1601. goto err;
  1602. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  1603. }
  1604. memset(tmp, 0, key_in_len+1);
  1605. tor_free(tmp);
  1606. memset(digest, 0, sizeof(digest));
  1607. return 0;
  1608. err:
  1609. memset(tmp, 0, key_in_len+1);
  1610. tor_free(tmp);
  1611. memset(digest, 0, sizeof(digest));
  1612. return -1;
  1613. }
  1614. /** Free a DH key exchange object.
  1615. */
  1616. void
  1617. crypto_dh_free(crypto_dh_env_t *dh)
  1618. {
  1619. tor_assert(dh);
  1620. tor_assert(dh->dh);
  1621. DH_free(dh->dh);
  1622. tor_free(dh);
  1623. }
  1624. /* random numbers */
  1625. /* This is how much entropy OpenSSL likes to add right now, so maybe it will
  1626. * work for us too. */
  1627. #define ADD_ENTROPY 32
  1628. /* Use RAND_poll if OpenSSL is 0.9.6 release or later. (The "f" means
  1629. "release".) */
  1630. #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
  1631. /* Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
  1632. * would allocate an fd_set on the stack, open a new file, and try to FD_SET
  1633. * that fd without checking whether it fit in the fd_set. Thus, if the
  1634. * system has not just been started up, it is unsafe to call */
  1635. #define RAND_POLL_IS_SAFE \
  1636. ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
  1637. OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
  1638. (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
  1639. /** Seed OpenSSL's random number generator with bytes from the operating
  1640. * system. <b>startup</b> should be true iff we have just started Tor and
  1641. * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
  1642. */
  1643. int
  1644. crypto_seed_rng(int startup)
  1645. {
  1646. char buf[ADD_ENTROPY];
  1647. int rand_poll_status = 0;
  1648. /* local variables */
  1649. #ifdef MS_WINDOWS
  1650. static int provider_set = 0;
  1651. static HCRYPTPROV provider;
  1652. #else
  1653. static const char *filenames[] = {
  1654. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1655. };
  1656. int fd, i;
  1657. size_t n;
  1658. #endif
  1659. #if HAVE_RAND_POLL
  1660. /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
  1661. * entropy than we do. We'll try calling that, *and* calling our own entropy
  1662. * functions. If one succeeds, we'll accept the RNG as seeded. */
  1663. if (startup || RAND_POLL_IS_SAFE) {
  1664. rand_poll_status = RAND_poll();
  1665. if (rand_poll_status == 0)
  1666. log_warn(LD_CRYPTO, "RAND_poll() failed.");
  1667. }
  1668. #endif
  1669. #ifdef MS_WINDOWS
  1670. if (!provider_set) {
  1671. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  1672. CRYPT_VERIFYCONTEXT)) {
  1673. if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
  1674. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  1675. return rand_poll_status ? 0 : -1;
  1676. }
  1677. }
  1678. provider_set = 1;
  1679. }
  1680. if (!CryptGenRandom(provider, sizeof(buf), buf)) {
  1681. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  1682. return rand_poll_status ? 0 : -1;
  1683. }
  1684. RAND_seed(buf, sizeof(buf));
  1685. memset(buf, 0, sizeof(buf));
  1686. return 0;
  1687. #else
  1688. for (i = 0; filenames[i]; ++i) {
  1689. fd = open(filenames[i], O_RDONLY, 0);
  1690. if (fd<0) continue;
  1691. log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
  1692. n = read_all(fd, buf, sizeof(buf), 0);
  1693. close(fd);
  1694. if (n != sizeof(buf)) {
  1695. log_warn(LD_CRYPTO,
  1696. "Error reading from entropy source (read only %lu bytes).",
  1697. (unsigned long)n);
  1698. return -1;
  1699. }
  1700. RAND_seed(buf, (int)sizeof(buf));
  1701. memset(buf, 0, sizeof(buf));
  1702. return 0;
  1703. }
  1704. log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
  1705. return rand_poll_status ? 0 : -1;
  1706. #endif
  1707. }
  1708. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
  1709. * success, -1 on failure.
  1710. */
  1711. int
  1712. crypto_rand(char *to, size_t n)
  1713. {
  1714. int r;
  1715. tor_assert(n < INT_MAX);
  1716. tor_assert(to);
  1717. r = RAND_bytes((unsigned char*)to, (int)n);
  1718. if (r == 0)
  1719. crypto_log_errors(LOG_WARN, "generating random data");
  1720. return (r == 1) ? 0 : -1;
  1721. }
  1722. /** Return a pseudorandom integer, chosen uniformly from the values
  1723. * between 0 and <b>max</b>-1. */
  1724. int
  1725. crypto_rand_int(unsigned int max)
  1726. {
  1727. unsigned int val;
  1728. unsigned int cutoff;
  1729. tor_assert(max < UINT_MAX);
  1730. tor_assert(max > 0); /* don't div by 0 */
  1731. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1732. * distribution with clipping at the upper end of unsigned int's
  1733. * range.
  1734. */
  1735. cutoff = UINT_MAX - (UINT_MAX%max);
  1736. while (1) {
  1737. crypto_rand((char*)&val, sizeof(val));
  1738. if (val < cutoff)
  1739. return val % max;
  1740. }
  1741. }
  1742. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  1743. * between 0 and <b>max</b>-1. */
  1744. uint64_t
  1745. crypto_rand_uint64(uint64_t max)
  1746. {
  1747. uint64_t val;
  1748. uint64_t cutoff;
  1749. tor_assert(max < UINT64_MAX);
  1750. tor_assert(max > 0); /* don't div by 0 */
  1751. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1752. * distribution with clipping at the upper end of unsigned int's
  1753. * range.
  1754. */
  1755. cutoff = UINT64_MAX - (UINT64_MAX%max);
  1756. while (1) {
  1757. crypto_rand((char*)&val, sizeof(val));
  1758. if (val < cutoff)
  1759. return val % max;
  1760. }
  1761. }
  1762. /** Generate and return a new random hostname starting with <b>prefix</b>,
  1763. * ending with <b>suffix</b>, and containing no less than
  1764. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  1765. * characters between. */
  1766. char *
  1767. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  1768. const char *suffix)
  1769. {
  1770. char *result, *rand_bytes;
  1771. int randlen, rand_bytes_len;
  1772. size_t resultlen, prefixlen;
  1773. tor_assert(max_rand_len >= min_rand_len);
  1774. randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
  1775. prefixlen = strlen(prefix);
  1776. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  1777. rand_bytes_len = ((randlen*5)+7)/8;
  1778. if (rand_bytes_len % 5)
  1779. rand_bytes_len += 5 - (rand_bytes_len%5);
  1780. rand_bytes = tor_malloc(rand_bytes_len);
  1781. crypto_rand(rand_bytes, rand_bytes_len);
  1782. result = tor_malloc(resultlen);
  1783. memcpy(result, prefix, prefixlen);
  1784. base32_encode(result+prefixlen, resultlen-prefixlen,
  1785. rand_bytes, rand_bytes_len);
  1786. tor_free(rand_bytes);
  1787. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  1788. return result;
  1789. }
  1790. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  1791. * is empty. */
  1792. void *
  1793. smartlist_choose(const smartlist_t *sl)
  1794. {
  1795. int len = smartlist_len(sl);
  1796. if (len)
  1797. return smartlist_get(sl,crypto_rand_int(len));
  1798. return NULL; /* no elements to choose from */
  1799. }
  1800. /** Scramble the elements of <b>sl</b> into a random order. */
  1801. void
  1802. smartlist_shuffle(smartlist_t *sl)
  1803. {
  1804. int i;
  1805. /* From the end of the list to the front, choose at random from the
  1806. positions we haven't looked at yet, and swap that position into the
  1807. current position. Remember to give "no swap" the same probability as
  1808. any other swap. */
  1809. for (i = smartlist_len(sl)-1; i > 0; --i) {
  1810. int j = crypto_rand_int(i+1);
  1811. smartlist_swap(sl, i, j);
  1812. }
  1813. }
  1814. /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
  1815. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1816. * bytes. Return the number of bytes written on success; -1 if
  1817. * destlen is too short, or other failure.
  1818. */
  1819. int
  1820. base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1821. {
  1822. /* FFFF we might want to rewrite this along the lines of base64_decode, if
  1823. * it ever shows up in the profile. */
  1824. EVP_ENCODE_CTX ctx;
  1825. int len, ret;
  1826. tor_assert(srclen < INT_MAX);
  1827. /* 48 bytes of input -> 64 bytes of output plus newline.
  1828. Plus one more byte, in case I'm wrong.
  1829. */
  1830. if (destlen < ((srclen/48)+1)*66)
  1831. return -1;
  1832. if (destlen > SIZE_T_CEILING)
  1833. return -1;
  1834. EVP_EncodeInit(&ctx);
  1835. EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
  1836. (unsigned char*)src, (int)srclen);
  1837. EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
  1838. ret += len;
  1839. return ret;
  1840. }
  1841. #define X 255
  1842. #define SP 64
  1843. #define PAD 65
  1844. /** Internal table mapping byte values to what they represent in base64.
  1845. * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
  1846. * skipped. Xs are invalid and must not appear in base64. PAD indicates
  1847. * end-of-string. */
  1848. static const uint8_t base64_decode_table[256] = {
  1849. X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
  1850. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1851. SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
  1852. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
  1853. X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  1854. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
  1855. X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  1856. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
  1857. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1858. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1859. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1860. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1861. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1862. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1863. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1864. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1865. };
  1866. /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
  1867. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1868. * bytes. Return the number of bytes written on success; -1 if
  1869. * destlen is too short, or other failure.
  1870. *
  1871. * NOTE 1: destlen is checked conservatively, as though srclen contained no
  1872. * spaces or padding.
  1873. *
  1874. * NOTE 2: This implementation does not check for the correct number of
  1875. * padding "=" characters at the end of the string, and does not check
  1876. * for internal padding characters.
  1877. */
  1878. int
  1879. base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  1880. {
  1881. #ifdef USE_OPENSSL_BASE64
  1882. EVP_ENCODE_CTX ctx;
  1883. int len, ret;
  1884. /* 64 bytes of input -> *up to* 48 bytes of output.
  1885. Plus one more byte, in case I'm wrong.
  1886. */
  1887. if (destlen < ((srclen/64)+1)*49)
  1888. return -1;
  1889. if (destlen > SIZE_T_CEILING)
  1890. return -1;
  1891. EVP_DecodeInit(&ctx);
  1892. EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
  1893. (unsigned char*)src, srclen);
  1894. EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
  1895. ret += len;
  1896. return ret;
  1897. #else
  1898. const char *eos = src+srclen;
  1899. uint32_t n=0;
  1900. int n_idx=0;
  1901. char *dest_orig = dest;
  1902. /* Max number of bits == srclen*6.
  1903. * Number of bytes required to hold all bits == (srclen*6)/8.
  1904. * Yes, we want to round down: anything that hangs over the end of a
  1905. * byte is padding. */
  1906. if (destlen < (srclen*3)/4)
  1907. return -1;
  1908. if (destlen > SIZE_T_CEILING)
  1909. return -1;
  1910. /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
  1911. * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
  1912. * 24 bits, batch them into 3 bytes and flush those bytes to dest.
  1913. */
  1914. for ( ; src < eos; ++src) {
  1915. unsigned char c = (unsigned char) *src;
  1916. uint8_t v = base64_decode_table[c];
  1917. switch (v) {
  1918. case X:
  1919. /* This character isn't allowed in base64. */
  1920. return -1;
  1921. case SP:
  1922. /* This character is whitespace, and has no effect. */
  1923. continue;
  1924. case PAD:
  1925. /* We've hit an = character: the data is over. */
  1926. goto end_of_loop;
  1927. default:
  1928. /* We have an actual 6-bit value. Append it to the bits in n. */
  1929. n = (n<<6) | v;
  1930. if ((++n_idx) == 4) {
  1931. /* We've accumulated 24 bits in n. Flush them. */
  1932. *dest++ = (n>>16);
  1933. *dest++ = (n>>8) & 0xff;
  1934. *dest++ = (n) & 0xff;
  1935. n_idx = 0;
  1936. n = 0;
  1937. }
  1938. }
  1939. }
  1940. end_of_loop:
  1941. /* If we have leftover bits, we need to cope. */
  1942. switch (n_idx) {
  1943. case 0:
  1944. default:
  1945. /* No leftover bits. We win. */
  1946. break;
  1947. case 1:
  1948. /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
  1949. return -1;
  1950. case 2:
  1951. /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
  1952. *dest++ = n >> 4;
  1953. break;
  1954. case 3:
  1955. /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
  1956. *dest++ = n >> 10;
  1957. *dest++ = n >> 2;
  1958. }
  1959. tor_assert((dest-dest_orig) <= (ssize_t)destlen);
  1960. tor_assert((dest-dest_orig) <= INT_MAX);
  1961. return (int)(dest-dest_orig);
  1962. #endif
  1963. }
  1964. #undef X
  1965. #undef SP
  1966. #undef PAD
  1967. /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
  1968. * and newline characters, and store the nul-terminated result in the first
  1969. * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
  1970. int
  1971. digest_to_base64(char *d64, const char *digest)
  1972. {
  1973. char buf[256];
  1974. base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
  1975. buf[BASE64_DIGEST_LEN] = '\0';
  1976. memcpy(d64, buf, BASE64_DIGEST_LEN+1);
  1977. return 0;
  1978. }
  1979. /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
  1980. * trailing newline or = characters), decode it and store the result in the
  1981. * first DIGEST_LEN bytes at <b>digest</b>. */
  1982. int
  1983. digest_from_base64(char *digest, const char *d64)
  1984. {
  1985. #ifdef USE_OPENSSL_BASE64
  1986. char buf_in[BASE64_DIGEST_LEN+3];
  1987. char buf[256];
  1988. if (strlen(d64) != BASE64_DIGEST_LEN)
  1989. return -1;
  1990. memcpy(buf_in, d64, BASE64_DIGEST_LEN);
  1991. memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
  1992. if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
  1993. return -1;
  1994. memcpy(digest, buf, DIGEST_LEN);
  1995. return 0;
  1996. #else
  1997. if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
  1998. return 0;
  1999. else
  2000. return -1;
  2001. #endif
  2002. }
  2003. /** Implements base32 encoding as in rfc3548. Limitation: Requires
  2004. * that srclen*8 is a multiple of 5.
  2005. */
  2006. void
  2007. base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  2008. {
  2009. unsigned int i, bit, v, u;
  2010. size_t nbits = srclen * 8;
  2011. tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
  2012. tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
  2013. tor_assert(destlen < SIZE_T_CEILING);
  2014. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  2015. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  2016. v = ((uint8_t)src[bit/8]) << 8;
  2017. if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
  2018. /* set u to the 5-bit value at the bit'th bit of src. */
  2019. u = (v >> (11-(bit%8))) & 0x1F;
  2020. dest[i] = BASE32_CHARS[u];
  2021. }
  2022. dest[i] = '\0';
  2023. }
  2024. /** Implements base32 decoding as in rfc3548. Limitation: Requires
  2025. * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
  2026. */
  2027. int
  2028. base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  2029. {
  2030. /* XXXX we might want to rewrite this along the lines of base64_decode, if
  2031. * it ever shows up in the profile. */
  2032. unsigned int i, j, bit;
  2033. size_t nbits;
  2034. char *tmp;
  2035. nbits = srclen * 5;
  2036. tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
  2037. tor_assert((nbits/8) <= destlen); /* We need enough space. */
  2038. tor_assert(destlen < SIZE_T_CEILING);
  2039. /* Convert base32 encoded chars to the 5-bit values that they represent. */
  2040. tmp = tor_malloc_zero(srclen);
  2041. for (j = 0; j < srclen; ++j) {
  2042. if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
  2043. else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
  2044. else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
  2045. else {
  2046. log_warn(LD_BUG, "illegal character in base32 encoded string");
  2047. tor_free(tmp);
  2048. return -1;
  2049. }
  2050. }
  2051. /* Assemble result byte-wise by applying five possible cases. */
  2052. for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
  2053. switch (bit % 40) {
  2054. case 0:
  2055. dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
  2056. (((uint8_t)tmp[(bit/5)+1]) >> 2);
  2057. break;
  2058. case 8:
  2059. dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
  2060. (((uint8_t)tmp[(bit/5)+1]) << 1) +
  2061. (((uint8_t)tmp[(bit/5)+2]) >> 4);
  2062. break;
  2063. case 16:
  2064. dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
  2065. (((uint8_t)tmp[(bit/5)+1]) >> 1);
  2066. break;
  2067. case 24:
  2068. dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
  2069. (((uint8_t)tmp[(bit/5)+1]) << 2) +
  2070. (((uint8_t)tmp[(bit/5)+2]) >> 3);
  2071. break;
  2072. case 32:
  2073. dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
  2074. ((uint8_t)tmp[(bit/5)+1]);
  2075. break;
  2076. }
  2077. }
  2078. memset(tmp, 0, srclen);
  2079. tor_free(tmp);
  2080. tmp = NULL;
  2081. return 0;
  2082. }
  2083. /** Implement RFC2440-style iterated-salted S2K conversion: convert the
  2084. * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
  2085. * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
  2086. * are a salt; the 9th byte describes how much iteration to do.
  2087. * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
  2088. */
  2089. void
  2090. secret_to_key(char *key_out, size_t key_out_len, const char *secret,
  2091. size_t secret_len, const char *s2k_specifier)
  2092. {
  2093. crypto_digest_env_t *d;
  2094. uint8_t c;
  2095. size_t count, tmplen;
  2096. char *tmp;
  2097. tor_assert(key_out_len < SIZE_T_CEILING);
  2098. #define EXPBIAS 6
  2099. c = s2k_specifier[8];
  2100. count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
  2101. #undef EXPBIAS
  2102. tor_assert(key_out_len <= DIGEST_LEN);
  2103. d = crypto_new_digest_env();
  2104. tmplen = 8+secret_len;
  2105. tmp = tor_malloc(tmplen);
  2106. memcpy(tmp,s2k_specifier,8);
  2107. memcpy(tmp+8,secret,secret_len);
  2108. secret_len += 8;
  2109. while (count) {
  2110. if (count >= secret_len) {
  2111. crypto_digest_add_bytes(d, tmp, secret_len);
  2112. count -= secret_len;
  2113. } else {
  2114. crypto_digest_add_bytes(d, tmp, count);
  2115. count = 0;
  2116. }
  2117. }
  2118. crypto_digest_get_digest(d, key_out, key_out_len);
  2119. memset(tmp, 0, tmplen);
  2120. tor_free(tmp);
  2121. crypto_free_digest_env(d);
  2122. }
  2123. #ifdef TOR_IS_MULTITHREADED
  2124. /** Helper: OpenSSL uses this callback to manipulate mutexes. */
  2125. static void
  2126. _openssl_locking_cb(int mode, int n, const char *file, int line)
  2127. {
  2128. (void)file;
  2129. (void)line;
  2130. if (!_openssl_mutexes)
  2131. /* This is not a really good fix for the
  2132. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  2133. * it can't hurt. */
  2134. return;
  2135. if (mode & CRYPTO_LOCK)
  2136. tor_mutex_acquire(_openssl_mutexes[n]);
  2137. else
  2138. tor_mutex_release(_openssl_mutexes[n]);
  2139. }
  2140. /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
  2141. * as a lock. */
  2142. struct CRYPTO_dynlock_value {
  2143. tor_mutex_t *lock;
  2144. };
  2145. /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
  2146. * documentation in OpenSSL's docs for more info. */
  2147. static struct CRYPTO_dynlock_value *
  2148. _openssl_dynlock_create_cb(const char *file, int line)
  2149. {
  2150. struct CRYPTO_dynlock_value *v;
  2151. (void)file;
  2152. (void)line;
  2153. v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
  2154. v->lock = tor_mutex_new();
  2155. return v;
  2156. }
  2157. /** OpenSSL callback function to acquire or release a lock: see
  2158. * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
  2159. static void
  2160. _openssl_dynlock_lock_cb(int mode, struct CRYPTO_dynlock_value *v,
  2161. const char *file, int line)
  2162. {
  2163. (void)file;
  2164. (void)line;
  2165. if (mode & CRYPTO_LOCK)
  2166. tor_mutex_acquire(v->lock);
  2167. else
  2168. tor_mutex_release(v->lock);
  2169. }
  2170. /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
  2171. * documentation in OpenSSL's docs for more info. */
  2172. static void
  2173. _openssl_dynlock_destroy_cb(struct CRYPTO_dynlock_value *v,
  2174. const char *file, int line)
  2175. {
  2176. (void)file;
  2177. (void)line;
  2178. tor_mutex_free(v->lock);
  2179. tor_free(v);
  2180. }
  2181. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  2182. * multithreaded. */
  2183. static int
  2184. setup_openssl_threading(void)
  2185. {
  2186. int i;
  2187. int n = CRYPTO_num_locks();
  2188. _n_openssl_mutexes = n;
  2189. _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
  2190. for (i=0; i < n; ++i)
  2191. _openssl_mutexes[i] = tor_mutex_new();
  2192. CRYPTO_set_locking_callback(_openssl_locking_cb);
  2193. CRYPTO_set_id_callback(tor_get_thread_id);
  2194. CRYPTO_set_dynlock_create_callback(_openssl_dynlock_create_cb);
  2195. CRYPTO_set_dynlock_lock_callback(_openssl_dynlock_lock_cb);
  2196. CRYPTO_set_dynlock_destroy_callback(_openssl_dynlock_destroy_cb);
  2197. return 0;
  2198. }
  2199. #else
  2200. static int
  2201. setup_openssl_threading(void)
  2202. {
  2203. return 0;
  2204. }
  2205. #endif