crypto.c 64 KB

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