crypto.c 70 KB

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