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