crypto.c 63 KB

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