crypto.c 66 KB

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