crypto.c 69 KB

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