crypto.c 69 KB

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