crypto.c 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106
  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-2013, 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 _WIN32
  13. #ifndef _WIN32_WINNT
  14. #define _WIN32_WINNT 0x0501
  15. #endif
  16. #define WIN32_LEAN_AND_MEAN
  17. #include <windows.h>
  18. #include <wincrypt.h>
  19. /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
  20. * use either definition. */
  21. #undef OCSP_RESPONSE
  22. #endif
  23. #include <openssl/err.h>
  24. #include <openssl/rsa.h>
  25. #include <openssl/pem.h>
  26. #include <openssl/evp.h>
  27. #include <openssl/engine.h>
  28. #include <openssl/rand.h>
  29. #include <openssl/opensslv.h>
  30. #include <openssl/bn.h>
  31. #include <openssl/dh.h>
  32. #include <openssl/conf.h>
  33. #include <openssl/hmac.h>
  34. #ifdef HAVE_CTYPE_H
  35. #include <ctype.h>
  36. #endif
  37. #ifdef HAVE_UNISTD_H
  38. #include <unistd.h>
  39. #endif
  40. #ifdef HAVE_FCNTL_H
  41. #include <fcntl.h>
  42. #endif
  43. #ifdef HAVE_SYS_FCNTL_H
  44. #include <sys/fcntl.h>
  45. #endif
  46. #define CRYPTO_PRIVATE
  47. #include "crypto.h"
  48. #include "../common/torlog.h"
  49. #include "aes.h"
  50. #include "../common/util.h"
  51. #include "container.h"
  52. #include "compat.h"
  53. #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
  54. #error "We require OpenSSL >= 0.9.8"
  55. #endif
  56. #ifdef ANDROID
  57. /* Android's OpenSSL seems to have removed all of its Engine support. */
  58. #define DISABLE_ENGINES
  59. #endif
  60. /** Longest recognized */
  61. #define MAX_DNS_LABEL_SIZE 63
  62. /** Macro: is k a valid RSA public or private key? */
  63. #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
  64. /** Macro: is k a valid RSA private key? */
  65. #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
  66. #ifdef TOR_IS_MULTITHREADED
  67. /** A number of preallocated mutexes for use by OpenSSL. */
  68. static tor_mutex_t **openssl_mutexes_ = NULL;
  69. /** How many mutexes have we allocated for use by OpenSSL? */
  70. static int n_openssl_mutexes_ = 0;
  71. #endif
  72. /** A public key, or a public/private key-pair. */
  73. struct crypto_pk_t
  74. {
  75. int refs; /**< reference count, so we don't have to copy keys */
  76. RSA *key; /**< The key itself */
  77. };
  78. /** Key and stream information for a stream cipher. */
  79. struct crypto_cipher_t
  80. {
  81. char key[CIPHER_KEY_LEN]; /**< The raw key. */
  82. char iv[CIPHER_IV_LEN]; /**< The initial IV. */
  83. aes_cnt_cipher_t *cipher; /**< The key in format usable for counter-mode AES
  84. * encryption */
  85. };
  86. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  87. * while we're waiting for the second.*/
  88. struct crypto_dh_t {
  89. DH *dh; /**< The openssl DH object */
  90. };
  91. static int setup_openssl_threading(void);
  92. static int tor_check_dh_key(int severity, BIGNUM *bn);
  93. /** Return the number of bytes added by padding method <b>padding</b>.
  94. */
  95. static INLINE int
  96. crypto_get_rsa_padding_overhead(int padding)
  97. {
  98. switch (padding)
  99. {
  100. case RSA_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
  101. default: tor_assert(0); return -1;
  102. }
  103. }
  104. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  105. */
  106. static INLINE int
  107. crypto_get_rsa_padding(int padding)
  108. {
  109. switch (padding)
  110. {
  111. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  112. default: tor_assert(0); return -1;
  113. }
  114. }
  115. /** Boolean: has OpenSSL's crypto been initialized? */
  116. static int crypto_global_initialized_ = 0;
  117. /** Log all pending crypto errors at level <b>severity</b>. Use
  118. * <b>doing</b> to describe our current activities.
  119. */
  120. static void
  121. crypto_log_errors(int severity, const char *doing)
  122. {
  123. unsigned long err;
  124. const char *msg, *lib, *func;
  125. while ((err = ERR_get_error()) != 0) {
  126. msg = (const char*)ERR_reason_error_string(err);
  127. lib = (const char*)ERR_lib_error_string(err);
  128. func = (const char*)ERR_func_error_string(err);
  129. if (!msg) msg = "(null)";
  130. if (!lib) lib = "(null)";
  131. if (!func) func = "(null)";
  132. if (doing) {
  133. tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  134. doing, msg, lib, func);
  135. } else {
  136. tor_log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)",
  137. msg, lib, func);
  138. }
  139. }
  140. }
  141. #ifndef DISABLE_ENGINES
  142. /** Log any OpenSSL engines we're using at NOTICE. */
  143. static void
  144. log_engine(const char *fn, ENGINE *e)
  145. {
  146. if (e) {
  147. const char *name, *id;
  148. name = ENGINE_get_name(e);
  149. id = ENGINE_get_id(e);
  150. log_notice(LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
  151. name?name:"?", id?id:"?", fn);
  152. } else {
  153. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  154. }
  155. }
  156. #endif
  157. #ifndef DISABLE_ENGINES
  158. /** Try to load an engine in a shared library via fully qualified path.
  159. */
  160. static ENGINE *
  161. try_load_engine(const char *path, const char *engine)
  162. {
  163. ENGINE *e = ENGINE_by_id("dynamic");
  164. if (e) {
  165. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  166. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  167. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  168. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  169. ENGINE_free(e);
  170. e = NULL;
  171. }
  172. }
  173. return e;
  174. }
  175. #endif
  176. static char *crypto_openssl_version_str = NULL;
  177. /* Return a human-readable version of the run-time openssl version number. */
  178. const char *
  179. crypto_openssl_get_version_str(void)
  180. {
  181. if (crypto_openssl_version_str == NULL) {
  182. const char *raw_version = SSLeay_version(SSLEAY_VERSION);
  183. const char *end_of_version = NULL;
  184. /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
  185. trim that down. */
  186. if (!strcmpstart(raw_version, "OpenSSL ")) {
  187. raw_version += strlen("OpenSSL ");
  188. end_of_version = strchr(raw_version, ' ');
  189. }
  190. if (end_of_version)
  191. crypto_openssl_version_str = tor_strndup(raw_version,
  192. end_of_version-raw_version);
  193. else
  194. crypto_openssl_version_str = tor_strdup(raw_version);
  195. }
  196. return crypto_openssl_version_str;
  197. }
  198. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  199. */
  200. int
  201. crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
  202. {
  203. if (!crypto_global_initialized_) {
  204. ERR_load_crypto_strings();
  205. OpenSSL_add_all_algorithms();
  206. crypto_global_initialized_ = 1;
  207. setup_openssl_threading();
  208. if (SSLeay() == OPENSSL_VERSION_NUMBER &&
  209. !strcmp(SSLeay_version(SSLEAY_VERSION), OPENSSL_VERSION_TEXT)) {
  210. log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
  211. "(%lx: %s).", SSLeay(), SSLeay_version(SSLEAY_VERSION));
  212. } else {
  213. log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
  214. "version we're running with. If you get weird crashes, that "
  215. "might be why. (Compiled with %lx: %s; running with %lx: %s).",
  216. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  217. SSLeay(), SSLeay_version(SSLEAY_VERSION));
  218. }
  219. if (SSLeay() < OPENSSL_V_SERIES(1,0,0)) {
  220. log_notice(LD_CRYPTO,
  221. "Your OpenSSL version seems to be %s. We recommend 1.0.0 "
  222. "or later.",
  223. crypto_openssl_get_version_str());
  224. }
  225. if (useAccel > 0) {
  226. #ifdef DISABLE_ENGINES
  227. (void)accelName;
  228. (void)accelDir;
  229. log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
  230. #else
  231. ENGINE *e = NULL;
  232. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  233. ENGINE_load_builtin_engines();
  234. ENGINE_register_all_complete();
  235. if (accelName) {
  236. if (accelDir) {
  237. log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
  238. " via path \"%s\".", accelName, accelDir);
  239. e = try_load_engine(accelName, accelDir);
  240. } else {
  241. log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
  242. " acceleration support.", accelName);
  243. e = ENGINE_by_id(accelName);
  244. }
  245. if (!e) {
  246. log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
  247. accelName);
  248. } else {
  249. log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
  250. accelName);
  251. }
  252. }
  253. if (e) {
  254. log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
  255. " setting default ciphers.");
  256. ENGINE_set_default(e, ENGINE_METHOD_ALL);
  257. }
  258. log_engine("RSA", ENGINE_get_default_RSA());
  259. log_engine("DH", ENGINE_get_default_DH());
  260. log_engine("RAND", ENGINE_get_default_RAND());
  261. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  262. log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
  263. log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  264. #endif
  265. } else {
  266. log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
  267. }
  268. evaluate_evp_for_aes(-1);
  269. evaluate_ctr_for_aes();
  270. return crypto_seed_rng(1);
  271. }
  272. return 0;
  273. }
  274. /** Free crypto resources held by this thread. */
  275. void
  276. crypto_thread_cleanup(void)
  277. {
  278. ERR_remove_state(0);
  279. }
  280. /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
  281. crypto_pk_t *
  282. crypto_new_pk_from_rsa_(RSA *rsa)
  283. {
  284. crypto_pk_t *env;
  285. tor_assert(rsa);
  286. env = tor_malloc(sizeof(crypto_pk_t));
  287. env->refs = 1;
  288. env->key = rsa;
  289. return env;
  290. }
  291. /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
  292. * crypto_pk_t. */
  293. RSA *
  294. crypto_pk_get_rsa_(crypto_pk_t *env)
  295. {
  296. return env->key;
  297. }
  298. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
  299. * private is set, include the private-key portion of the key. */
  300. EVP_PKEY *
  301. crypto_pk_get_evp_pkey_(crypto_pk_t *env, int private)
  302. {
  303. RSA *key = NULL;
  304. EVP_PKEY *pkey = NULL;
  305. tor_assert(env->key);
  306. if (private) {
  307. if (!(key = RSAPrivateKey_dup(env->key)))
  308. goto error;
  309. } else {
  310. if (!(key = RSAPublicKey_dup(env->key)))
  311. goto error;
  312. }
  313. if (!(pkey = EVP_PKEY_new()))
  314. goto error;
  315. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  316. goto error;
  317. return pkey;
  318. error:
  319. if (pkey)
  320. EVP_PKEY_free(pkey);
  321. if (key)
  322. RSA_free(key);
  323. return NULL;
  324. }
  325. /** Used by tortls.c: Get the DH* from a crypto_dh_t.
  326. */
  327. DH *
  328. crypto_dh_get_dh_(crypto_dh_t *dh)
  329. {
  330. return dh->dh;
  331. }
  332. /** Allocate and return storage for a public key. The key itself will not yet
  333. * be set.
  334. */
  335. crypto_pk_t *
  336. crypto_pk_new(void)
  337. {
  338. RSA *rsa;
  339. rsa = RSA_new();
  340. tor_assert(rsa);
  341. return crypto_new_pk_from_rsa_(rsa);
  342. }
  343. /** Release a reference to an asymmetric key; when all the references
  344. * are released, free the key.
  345. */
  346. void
  347. crypto_pk_free(crypto_pk_t *env)
  348. {
  349. if (!env)
  350. return;
  351. if (--env->refs > 0)
  352. return;
  353. tor_assert(env->refs == 0);
  354. if (env->key)
  355. RSA_free(env->key);
  356. tor_free(env);
  357. }
  358. /** Allocate and return a new symmetric cipher using the provided key and iv.
  359. * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. If you
  360. * provide NULL in place of either one, it is generated at random.
  361. */
  362. crypto_cipher_t *
  363. crypto_cipher_new_with_iv(const char *key, const char *iv)
  364. {
  365. crypto_cipher_t *env;
  366. env = tor_malloc_zero(sizeof(crypto_cipher_t));
  367. if (key == NULL)
  368. crypto_rand(env->key, CIPHER_KEY_LEN);
  369. else
  370. memcpy(env->key, key, CIPHER_KEY_LEN);
  371. if (iv == NULL)
  372. crypto_rand(env->iv, CIPHER_IV_LEN);
  373. else
  374. memcpy(env->iv, iv, CIPHER_IV_LEN);
  375. env->cipher = aes_new_cipher(env->key, env->iv);
  376. return env;
  377. }
  378. /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
  379. * zero bytes. */
  380. crypto_cipher_t *
  381. crypto_cipher_new(const char *key)
  382. {
  383. char zeroiv[CIPHER_IV_LEN];
  384. memset(zeroiv, 0, sizeof(zeroiv));
  385. return crypto_cipher_new_with_iv(key, zeroiv);
  386. }
  387. /** Free a symmetric cipher.
  388. */
  389. void
  390. crypto_cipher_free(crypto_cipher_t *env)
  391. {
  392. if (!env)
  393. return;
  394. tor_assert(env->cipher);
  395. aes_cipher_free(env->cipher);
  396. memwipe(env, 0, sizeof(crypto_cipher_t));
  397. tor_free(env);
  398. }
  399. /* public key crypto */
  400. /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
  401. * Return 0 on success, -1 on failure.
  402. */
  403. int
  404. crypto_pk_generate_key_with_bits(crypto_pk_t *env, int bits)
  405. {
  406. tor_assert(env);
  407. if (env->key)
  408. RSA_free(env->key);
  409. {
  410. BIGNUM *e = BN_new();
  411. RSA *r = NULL;
  412. if (!e)
  413. goto done;
  414. if (! BN_set_word(e, 65537))
  415. goto done;
  416. r = RSA_new();
  417. if (!r)
  418. goto done;
  419. if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
  420. goto done;
  421. env->key = r;
  422. r = NULL;
  423. done:
  424. if (e)
  425. BN_free(e);
  426. if (r)
  427. RSA_free(r);
  428. }
  429. if (!env->key) {
  430. crypto_log_errors(LOG_WARN, "generating RSA key");
  431. return -1;
  432. }
  433. return 0;
  434. }
  435. /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
  436. * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
  437. * the string is nul-terminated.
  438. */
  439. /* Used here, and used for testing. */
  440. int
  441. crypto_pk_read_private_key_from_string(crypto_pk_t *env,
  442. const char *s, ssize_t len)
  443. {
  444. BIO *b;
  445. tor_assert(env);
  446. tor_assert(s);
  447. tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
  448. /* Create a read-only memory BIO, backed by the string 's' */
  449. b = BIO_new_mem_buf((char*)s, (int)len);
  450. if (!b)
  451. return -1;
  452. if (env->key)
  453. RSA_free(env->key);
  454. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
  455. BIO_free(b);
  456. if (!env->key) {
  457. crypto_log_errors(LOG_WARN, "Error parsing private key");
  458. return -1;
  459. }
  460. return 0;
  461. }
  462. /** Read a PEM-encoded private key from the file named by
  463. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  464. */
  465. int
  466. crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
  467. const char *keyfile)
  468. {
  469. char *contents;
  470. int r;
  471. /* Read the file into a string. */
  472. contents = read_file_to_str(keyfile, 0, NULL);
  473. if (!contents) {
  474. log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
  475. return -1;
  476. }
  477. /* Try to parse it. */
  478. r = crypto_pk_read_private_key_from_string(env, contents, -1);
  479. memwipe(contents, 0, strlen(contents));
  480. tor_free(contents);
  481. if (r)
  482. return -1; /* read_private_key_from_string already warned, so we don't.*/
  483. /* Make sure it's valid. */
  484. if (crypto_pk_check_key(env) <= 0)
  485. return -1;
  486. return 0;
  487. }
  488. /** Helper function to implement crypto_pk_write_*_key_to_string. */
  489. static int
  490. crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
  491. size_t *len, int is_public)
  492. {
  493. BUF_MEM *buf;
  494. BIO *b;
  495. int r;
  496. tor_assert(env);
  497. tor_assert(env->key);
  498. tor_assert(dest);
  499. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  500. if (!b)
  501. return -1;
  502. /* Now you can treat b as if it were a file. Just use the
  503. * PEM_*_bio_* functions instead of the non-bio variants.
  504. */
  505. if (is_public)
  506. r = PEM_write_bio_RSAPublicKey(b, env->key);
  507. else
  508. r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
  509. if (!r) {
  510. crypto_log_errors(LOG_WARN, "writing RSA key to string");
  511. BIO_free(b);
  512. return -1;
  513. }
  514. BIO_get_mem_ptr(b, &buf);
  515. (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  516. BIO_free(b);
  517. *dest = tor_malloc(buf->length+1);
  518. memcpy(*dest, buf->data, buf->length);
  519. (*dest)[buf->length] = 0; /* nul terminate it */
  520. *len = buf->length;
  521. BUF_MEM_free(buf);
  522. return 0;
  523. }
  524. /** PEM-encode the public key portion of <b>env</b> and write it to a
  525. * newly allocated string. On success, set *<b>dest</b> to the new
  526. * string, *<b>len</b> to the string's length, and return 0. On
  527. * failure, return -1.
  528. */
  529. int
  530. crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
  531. size_t *len)
  532. {
  533. return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
  534. }
  535. /** PEM-encode the private key portion of <b>env</b> and write it to a
  536. * newly allocated string. On success, set *<b>dest</b> to the new
  537. * string, *<b>len</b> to the string's length, and return 0. On
  538. * failure, return -1.
  539. */
  540. int
  541. crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
  542. size_t *len)
  543. {
  544. return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
  545. }
  546. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  547. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  548. * failure.
  549. */
  550. int
  551. crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
  552. size_t len)
  553. {
  554. BIO *b;
  555. tor_assert(env);
  556. tor_assert(src);
  557. tor_assert(len<INT_MAX);
  558. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  559. if (!b)
  560. return -1;
  561. BIO_write(b, src, (int)len);
  562. if (env->key)
  563. RSA_free(env->key);
  564. env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  565. BIO_free(b);
  566. if (!env->key) {
  567. crypto_log_errors(LOG_WARN, "reading public key from string");
  568. return -1;
  569. }
  570. return 0;
  571. }
  572. /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
  573. * PEM-encoded. Return 0 on success, -1 on failure.
  574. */
  575. int
  576. crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
  577. const char *fname)
  578. {
  579. BIO *bio;
  580. char *cp;
  581. long len;
  582. char *s;
  583. int r;
  584. tor_assert(PRIVATE_KEY_OK(env));
  585. if (!(bio = BIO_new(BIO_s_mem())))
  586. return -1;
  587. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  588. == 0) {
  589. crypto_log_errors(LOG_WARN, "writing private key");
  590. BIO_free(bio);
  591. return -1;
  592. }
  593. len = BIO_get_mem_data(bio, &cp);
  594. tor_assert(len >= 0);
  595. s = tor_malloc(len+1);
  596. memcpy(s, cp, len);
  597. s[len]='\0';
  598. r = write_str_to_file(fname, s, 0);
  599. BIO_free(bio);
  600. memwipe(s, 0, strlen(s));
  601. tor_free(s);
  602. return r;
  603. }
  604. /** Return true iff <b>env</b> has a valid key.
  605. */
  606. int
  607. crypto_pk_check_key(crypto_pk_t *env)
  608. {
  609. int r;
  610. tor_assert(env);
  611. r = RSA_check_key(env->key);
  612. if (r <= 0)
  613. crypto_log_errors(LOG_WARN,"checking RSA key");
  614. return r;
  615. }
  616. /** Return true iff <b>key</b> contains the private-key portion of the RSA
  617. * key. */
  618. int
  619. crypto_pk_key_is_private(const crypto_pk_t *key)
  620. {
  621. tor_assert(key);
  622. return PRIVATE_KEY_OK(key);
  623. }
  624. /** Return true iff <b>env</b> contains a public key whose public exponent
  625. * equals 65537.
  626. */
  627. int
  628. crypto_pk_public_exponent_ok(crypto_pk_t *env)
  629. {
  630. tor_assert(env);
  631. tor_assert(env->key);
  632. return BN_is_word(env->key->e, 65537);
  633. }
  634. /** Compare the public-key components of a and b. Return less than 0
  635. * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
  636. * considered to be less than all non-NULL keys, and equal to itself.
  637. *
  638. * Note that this may leak information about the keys through timing.
  639. */
  640. int
  641. crypto_pk_cmp_keys(crypto_pk_t *a, crypto_pk_t *b)
  642. {
  643. int result;
  644. char a_is_non_null = (a != NULL) && (a->key != NULL);
  645. char b_is_non_null = (b != NULL) && (b->key != NULL);
  646. char an_argument_is_null = !a_is_non_null | !b_is_non_null;
  647. result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
  648. if (an_argument_is_null)
  649. return result;
  650. tor_assert(PUBLIC_KEY_OK(a));
  651. tor_assert(PUBLIC_KEY_OK(b));
  652. result = BN_cmp((a->key)->n, (b->key)->n);
  653. if (result)
  654. return result;
  655. return BN_cmp((a->key)->e, (b->key)->e);
  656. }
  657. /** Compare the public-key components of a and b. Return non-zero iff
  658. * a==b. A NULL key is considered to be distinct from all non-NULL
  659. * keys, and equal to itself.
  660. *
  661. * Note that this may leak information about the keys through timing.
  662. */
  663. int
  664. crypto_pk_eq_keys(crypto_pk_t *a, crypto_pk_t *b)
  665. {
  666. return (crypto_pk_cmp_keys(a, b) == 0);
  667. }
  668. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  669. size_t
  670. crypto_pk_keysize(crypto_pk_t *env)
  671. {
  672. tor_assert(env);
  673. tor_assert(env->key);
  674. return (size_t) RSA_size(env->key);
  675. }
  676. /** Return the size of the public key modulus of <b>env</b>, in bits. */
  677. int
  678. crypto_pk_num_bits(crypto_pk_t *env)
  679. {
  680. tor_assert(env);
  681. tor_assert(env->key);
  682. tor_assert(env->key->n);
  683. return BN_num_bits(env->key->n);
  684. }
  685. /** Increase the reference count of <b>env</b>, and return it.
  686. */
  687. crypto_pk_t *
  688. crypto_pk_dup_key(crypto_pk_t *env)
  689. {
  690. tor_assert(env);
  691. tor_assert(env->key);
  692. env->refs++;
  693. return env;
  694. }
  695. /** Make a real honest-to-goodness copy of <b>env</b>, and return it. */
  696. crypto_pk_t *
  697. crypto_pk_copy_full(crypto_pk_t *env)
  698. {
  699. RSA *new_key;
  700. int privatekey = 0;
  701. tor_assert(env);
  702. tor_assert(env->key);
  703. if (PRIVATE_KEY_OK(env)) {
  704. new_key = RSAPrivateKey_dup(env->key);
  705. privatekey = 1;
  706. } else {
  707. new_key = RSAPublicKey_dup(env->key);
  708. }
  709. if (!new_key) {
  710. log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
  711. privatekey?"private":"public");
  712. crypto_log_errors(LOG_ERR,
  713. privatekey ? "Duplicating a private key" :
  714. "Duplicating a public key");
  715. tor_fragile_assert();
  716. return NULL;
  717. }
  718. return crypto_new_pk_from_rsa_(new_key);
  719. }
  720. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  721. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  722. * write the result to <b>to</b>, and return the number of bytes
  723. * written. On failure, return -1.
  724. *
  725. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  726. * at least the length of the modulus of <b>env</b>.
  727. */
  728. int
  729. crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
  730. const char *from, size_t fromlen, int padding)
  731. {
  732. int r;
  733. tor_assert(env);
  734. tor_assert(from);
  735. tor_assert(to);
  736. tor_assert(fromlen<INT_MAX);
  737. tor_assert(tolen >= crypto_pk_keysize(env));
  738. r = RSA_public_encrypt((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(LOG_WARN, "performing RSA encryption");
  743. return -1;
  744. }
  745. return r;
  746. }
  747. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  748. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  749. * write the result to <b>to</b>, and return the number of bytes
  750. * written. On failure, return -1.
  751. *
  752. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  753. * at least the length of the modulus of <b>env</b>.
  754. */
  755. int
  756. crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
  757. size_t tolen,
  758. const char *from, size_t fromlen,
  759. int padding, int warnOnFailure)
  760. {
  761. int r;
  762. tor_assert(env);
  763. tor_assert(from);
  764. tor_assert(to);
  765. tor_assert(env->key);
  766. tor_assert(fromlen<INT_MAX);
  767. tor_assert(tolen >= crypto_pk_keysize(env));
  768. if (!env->key->p)
  769. /* Not a private key */
  770. return -1;
  771. r = RSA_private_decrypt((int)fromlen,
  772. (unsigned char*)from, (unsigned char*)to,
  773. env->key, crypto_get_rsa_padding(padding));
  774. if (r<0) {
  775. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  776. "performing RSA decryption");
  777. return -1;
  778. }
  779. return r;
  780. }
  781. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  782. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  783. * signed data to <b>to</b>, and return the number of bytes written.
  784. * On failure, return -1.
  785. *
  786. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  787. * at least the length of the modulus of <b>env</b>.
  788. */
  789. int
  790. crypto_pk_public_checksig(crypto_pk_t *env, char *to,
  791. size_t tolen,
  792. const char *from, size_t fromlen)
  793. {
  794. int r;
  795. tor_assert(env);
  796. tor_assert(from);
  797. tor_assert(to);
  798. tor_assert(fromlen < INT_MAX);
  799. tor_assert(tolen >= crypto_pk_keysize(env));
  800. r = RSA_public_decrypt((int)fromlen,
  801. (unsigned char*)from, (unsigned char*)to,
  802. env->key, RSA_PKCS1_PADDING);
  803. if (r<0) {
  804. crypto_log_errors(LOG_WARN, "checking RSA signature");
  805. return -1;
  806. }
  807. return r;
  808. }
  809. /** Check a siglen-byte long signature at <b>sig</b> against
  810. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  811. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  812. * SHA1(data). Else return -1.
  813. */
  814. int
  815. crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
  816. size_t datalen, const char *sig, size_t siglen)
  817. {
  818. char digest[DIGEST_LEN];
  819. char *buf;
  820. size_t buflen;
  821. int r;
  822. tor_assert(env);
  823. tor_assert(data);
  824. tor_assert(sig);
  825. tor_assert(datalen < SIZE_T_CEILING);
  826. tor_assert(siglen < SIZE_T_CEILING);
  827. if (crypto_digest(digest,data,datalen)<0) {
  828. log_warn(LD_BUG, "couldn't compute digest");
  829. return -1;
  830. }
  831. buflen = crypto_pk_keysize(env);
  832. buf = tor_malloc(buflen);
  833. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  834. if (r != DIGEST_LEN) {
  835. log_warn(LD_CRYPTO, "Invalid signature");
  836. tor_free(buf);
  837. return -1;
  838. }
  839. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  840. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  841. tor_free(buf);
  842. return -1;
  843. }
  844. tor_free(buf);
  845. return 0;
  846. }
  847. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  848. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  849. * <b>to</b>, and return the number of bytes written. On failure, return
  850. * -1.
  851. *
  852. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  853. * at least the length of the modulus of <b>env</b>.
  854. */
  855. int
  856. crypto_pk_private_sign(crypto_pk_t *env, char *to, size_t tolen,
  857. const char *from, size_t fromlen)
  858. {
  859. int r;
  860. tor_assert(env);
  861. tor_assert(from);
  862. tor_assert(to);
  863. tor_assert(fromlen < INT_MAX);
  864. tor_assert(tolen >= crypto_pk_keysize(env));
  865. if (!env->key->p)
  866. /* Not a private key */
  867. return -1;
  868. r = RSA_private_encrypt((int)fromlen,
  869. (unsigned char*)from, (unsigned char*)to,
  870. env->key, RSA_PKCS1_PADDING);
  871. if (r<0) {
  872. crypto_log_errors(LOG_WARN, "generating RSA signature");
  873. return -1;
  874. }
  875. return r;
  876. }
  877. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  878. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  879. * store it in <b>to</b>. Return the number of bytes written on
  880. * success, and -1 on failure.
  881. *
  882. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  883. * at least the length of the modulus of <b>env</b>.
  884. */
  885. int
  886. crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
  887. const char *from, size_t fromlen)
  888. {
  889. int r;
  890. char digest[DIGEST_LEN];
  891. if (crypto_digest(digest,from,fromlen)<0)
  892. return -1;
  893. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  894. memwipe(digest, 0, sizeof(digest));
  895. return r;
  896. }
  897. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  898. * bytes of data from <b>from</b>, with padding type 'padding',
  899. * storing the results on <b>to</b>.
  900. *
  901. * Returns the number of bytes written on success, -1 on failure.
  902. *
  903. * The encrypted data consists of:
  904. * - The source data, padded and encrypted with the public key, if the
  905. * padded source data is no longer than the public key, and <b>force</b>
  906. * is false, OR
  907. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  908. * padded and encrypted with the public key; followed by the rest of
  909. * the source data encrypted in AES-CTR mode with the symmetric key.
  910. */
  911. int
  912. crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
  913. char *to, size_t tolen,
  914. const char *from,
  915. size_t fromlen,
  916. int padding, int force)
  917. {
  918. int overhead, outlen, r;
  919. size_t pkeylen, symlen;
  920. crypto_cipher_t *cipher = NULL;
  921. char *buf = NULL;
  922. tor_assert(env);
  923. tor_assert(from);
  924. tor_assert(to);
  925. tor_assert(fromlen < SIZE_T_CEILING);
  926. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  927. pkeylen = crypto_pk_keysize(env);
  928. if (!force && fromlen+overhead <= pkeylen) {
  929. /* It all fits in a single encrypt. */
  930. return crypto_pk_public_encrypt(env,to,
  931. tolen,
  932. from,fromlen,padding);
  933. }
  934. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  935. tor_assert(tolen >= pkeylen);
  936. cipher = crypto_cipher_new(NULL); /* generate a new key. */
  937. buf = tor_malloc(pkeylen+1);
  938. memcpy(buf, cipher->key, CIPHER_KEY_LEN);
  939. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  940. /* Length of symmetrically encrypted data. */
  941. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  942. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  943. if (outlen!=(int)pkeylen) {
  944. goto err;
  945. }
  946. r = crypto_cipher_encrypt(cipher, to+outlen,
  947. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  948. if (r<0) goto err;
  949. memwipe(buf, 0, pkeylen);
  950. tor_free(buf);
  951. crypto_cipher_free(cipher);
  952. tor_assert(outlen+symlen < INT_MAX);
  953. return (int)(outlen + symlen);
  954. err:
  955. memwipe(buf, 0, pkeylen);
  956. tor_free(buf);
  957. crypto_cipher_free(cipher);
  958. return -1;
  959. }
  960. /** Invert crypto_pk_public_hybrid_encrypt. */
  961. int
  962. crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
  963. char *to,
  964. size_t tolen,
  965. const char *from,
  966. size_t fromlen,
  967. int padding, int warnOnFailure)
  968. {
  969. int outlen, r;
  970. size_t pkeylen;
  971. crypto_cipher_t *cipher = NULL;
  972. char *buf = NULL;
  973. tor_assert(fromlen < SIZE_T_CEILING);
  974. pkeylen = crypto_pk_keysize(env);
  975. if (fromlen <= pkeylen) {
  976. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  977. warnOnFailure);
  978. }
  979. buf = tor_malloc(pkeylen);
  980. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  981. warnOnFailure);
  982. if (outlen<0) {
  983. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  984. "Error decrypting public-key data");
  985. goto err;
  986. }
  987. if (outlen < CIPHER_KEY_LEN) {
  988. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  989. "No room for a symmetric key");
  990. goto err;
  991. }
  992. cipher = crypto_cipher_new(buf);
  993. if (!cipher) {
  994. goto err;
  995. }
  996. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  997. outlen -= CIPHER_KEY_LEN;
  998. tor_assert(tolen - outlen >= fromlen - pkeylen);
  999. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  1000. if (r<0)
  1001. goto err;
  1002. memwipe(buf,0,pkeylen);
  1003. tor_free(buf);
  1004. crypto_cipher_free(cipher);
  1005. tor_assert(outlen + fromlen < INT_MAX);
  1006. return (int)(outlen + (fromlen-pkeylen));
  1007. err:
  1008. memwipe(buf,0,pkeylen);
  1009. tor_free(buf);
  1010. crypto_cipher_free(cipher);
  1011. return -1;
  1012. }
  1013. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  1014. * Return -1 on error, or the number of characters used on success.
  1015. */
  1016. int
  1017. crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
  1018. {
  1019. int len;
  1020. unsigned char *buf = NULL;
  1021. len = i2d_RSAPublicKey(pk->key, &buf);
  1022. if (len < 0 || buf == NULL)
  1023. return -1;
  1024. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  1025. OPENSSL_free(buf);
  1026. return -1;
  1027. }
  1028. /* We don't encode directly into 'dest', because that would be illegal
  1029. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  1030. */
  1031. memcpy(dest,buf,len);
  1032. OPENSSL_free(buf);
  1033. return len;
  1034. }
  1035. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  1036. * success and NULL on failure.
  1037. */
  1038. crypto_pk_t *
  1039. crypto_pk_asn1_decode(const char *str, size_t len)
  1040. {
  1041. RSA *rsa;
  1042. unsigned char *buf;
  1043. const unsigned char *cp;
  1044. cp = buf = tor_malloc(len);
  1045. memcpy(buf,str,len);
  1046. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  1047. tor_free(buf);
  1048. if (!rsa) {
  1049. crypto_log_errors(LOG_WARN,"decoding public key");
  1050. return NULL;
  1051. }
  1052. return crypto_new_pk_from_rsa_(rsa);
  1053. }
  1054. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  1055. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  1056. * Return 0 on success, -1 on failure.
  1057. */
  1058. int
  1059. crypto_pk_get_digest(crypto_pk_t *pk, char *digest_out)
  1060. {
  1061. unsigned char *buf = NULL;
  1062. int len;
  1063. len = i2d_RSAPublicKey(pk->key, &buf);
  1064. if (len < 0 || buf == NULL)
  1065. return -1;
  1066. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  1067. OPENSSL_free(buf);
  1068. return -1;
  1069. }
  1070. OPENSSL_free(buf);
  1071. return 0;
  1072. }
  1073. /** Compute all digests of the DER encoding of <b>pk</b>, and store them
  1074. * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
  1075. int
  1076. crypto_pk_get_all_digests(crypto_pk_t *pk, digests_t *digests_out)
  1077. {
  1078. unsigned char *buf = NULL;
  1079. int len;
  1080. len = i2d_RSAPublicKey(pk->key, &buf);
  1081. if (len < 0 || buf == NULL)
  1082. return -1;
  1083. if (crypto_digest_all(digests_out, (char*)buf, len) < 0) {
  1084. OPENSSL_free(buf);
  1085. return -1;
  1086. }
  1087. OPENSSL_free(buf);
  1088. return 0;
  1089. }
  1090. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  1091. * every four spaces. */
  1092. void
  1093. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  1094. {
  1095. int n = 0;
  1096. char *end = out+outlen;
  1097. tor_assert(outlen < SIZE_T_CEILING);
  1098. while (*in && out<end) {
  1099. *out++ = *in++;
  1100. if (++n == 4 && *in && out<end) {
  1101. n = 0;
  1102. *out++ = ' ';
  1103. }
  1104. }
  1105. tor_assert(out<end);
  1106. *out = '\0';
  1107. }
  1108. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  1109. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  1110. * space). Return 0 on success, -1 on failure.
  1111. *
  1112. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  1113. * of the public key, converted to hexadecimal, in upper case, with a
  1114. * space after every four digits.
  1115. *
  1116. * If <b>add_space</b> is false, omit the spaces.
  1117. */
  1118. int
  1119. crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
  1120. {
  1121. char digest[DIGEST_LEN];
  1122. char hexdigest[HEX_DIGEST_LEN+1];
  1123. if (crypto_pk_get_digest(pk, digest)) {
  1124. return -1;
  1125. }
  1126. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  1127. if (add_space) {
  1128. crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  1129. } else {
  1130. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  1131. }
  1132. return 0;
  1133. }
  1134. /* symmetric crypto */
  1135. /** Return a pointer to the key set for the cipher in <b>env</b>.
  1136. */
  1137. const char *
  1138. crypto_cipher_get_key(crypto_cipher_t *env)
  1139. {
  1140. return env->key;
  1141. }
  1142. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1143. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1144. * On failure, return -1.
  1145. */
  1146. int
  1147. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  1148. const char *from, size_t fromlen)
  1149. {
  1150. tor_assert(env);
  1151. tor_assert(env->cipher);
  1152. tor_assert(from);
  1153. tor_assert(fromlen);
  1154. tor_assert(to);
  1155. tor_assert(fromlen < SIZE_T_CEILING);
  1156. aes_crypt(env->cipher, from, fromlen, to);
  1157. return 0;
  1158. }
  1159. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1160. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1161. * On failure, return -1.
  1162. */
  1163. int
  1164. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  1165. const char *from, size_t fromlen)
  1166. {
  1167. tor_assert(env);
  1168. tor_assert(from);
  1169. tor_assert(to);
  1170. tor_assert(fromlen < SIZE_T_CEILING);
  1171. aes_crypt(env->cipher, from, fromlen, to);
  1172. return 0;
  1173. }
  1174. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  1175. * on success, return 0. On failure, return -1.
  1176. */
  1177. int
  1178. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  1179. {
  1180. tor_assert(len < SIZE_T_CEILING);
  1181. aes_crypt_inplace(env->cipher, buf, len);
  1182. return 0;
  1183. }
  1184. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1185. * <b>key</b> to the buffer in <b>to</b> of length
  1186. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1187. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1188. * number of bytes written, on failure, return -1.
  1189. */
  1190. int
  1191. crypto_cipher_encrypt_with_iv(const char *key,
  1192. char *to, size_t tolen,
  1193. const char *from, size_t fromlen)
  1194. {
  1195. crypto_cipher_t *cipher;
  1196. tor_assert(from);
  1197. tor_assert(to);
  1198. tor_assert(fromlen < INT_MAX);
  1199. if (fromlen < 1)
  1200. return -1;
  1201. if (tolen < fromlen + CIPHER_IV_LEN)
  1202. return -1;
  1203. cipher = crypto_cipher_new_with_iv(key, NULL);
  1204. memcpy(to, cipher->iv, CIPHER_IV_LEN);
  1205. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1206. crypto_cipher_free(cipher);
  1207. return (int)(fromlen + CIPHER_IV_LEN);
  1208. }
  1209. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1210. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  1211. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1212. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1213. * number of bytes written, on failure, return -1.
  1214. */
  1215. int
  1216. crypto_cipher_decrypt_with_iv(const char *key,
  1217. char *to, size_t tolen,
  1218. const char *from, size_t fromlen)
  1219. {
  1220. crypto_cipher_t *cipher;
  1221. tor_assert(key);
  1222. tor_assert(from);
  1223. tor_assert(to);
  1224. tor_assert(fromlen < INT_MAX);
  1225. if (fromlen <= CIPHER_IV_LEN)
  1226. return -1;
  1227. if (tolen < fromlen - CIPHER_IV_LEN)
  1228. return -1;
  1229. cipher = crypto_cipher_new_with_iv(key, from);
  1230. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1231. crypto_cipher_free(cipher);
  1232. return (int)(fromlen - CIPHER_IV_LEN);
  1233. }
  1234. /* SHA-1 */
  1235. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  1236. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1237. * Return 0 on success, -1 on failure.
  1238. */
  1239. int
  1240. crypto_digest(char *digest, const char *m, size_t len)
  1241. {
  1242. tor_assert(m);
  1243. tor_assert(digest);
  1244. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1245. }
  1246. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1247. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  1248. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  1249. int
  1250. crypto_digest256(char *digest, const char *m, size_t len,
  1251. digest_algorithm_t algorithm)
  1252. {
  1253. tor_assert(m);
  1254. tor_assert(digest);
  1255. tor_assert(algorithm == DIGEST_SHA256);
  1256. return (SHA256((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1257. }
  1258. /** Set the digests_t in <b>ds_out</b> to contain every digest on the
  1259. * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
  1260. * success, -1 on failure. */
  1261. int
  1262. crypto_digest_all(digests_t *ds_out, const char *m, size_t len)
  1263. {
  1264. int i;
  1265. tor_assert(ds_out);
  1266. memset(ds_out, 0, sizeof(*ds_out));
  1267. if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
  1268. return -1;
  1269. for (i = DIGEST_SHA256; i < N_DIGEST_ALGORITHMS; ++i) {
  1270. if (crypto_digest256(ds_out->d[i], m, len, i) < 0)
  1271. return -1;
  1272. }
  1273. return 0;
  1274. }
  1275. /** Return the name of an algorithm, as used in directory documents. */
  1276. const char *
  1277. crypto_digest_algorithm_get_name(digest_algorithm_t alg)
  1278. {
  1279. switch (alg) {
  1280. case DIGEST_SHA1:
  1281. return "sha1";
  1282. case DIGEST_SHA256:
  1283. return "sha256";
  1284. default:
  1285. tor_fragile_assert();
  1286. return "??unknown_digest??";
  1287. }
  1288. }
  1289. /** Given the name of a digest algorithm, return its integer value, or -1 if
  1290. * the name is not recognized. */
  1291. int
  1292. crypto_digest_algorithm_parse_name(const char *name)
  1293. {
  1294. if (!strcmp(name, "sha1"))
  1295. return DIGEST_SHA1;
  1296. else if (!strcmp(name, "sha256"))
  1297. return DIGEST_SHA256;
  1298. else
  1299. return -1;
  1300. }
  1301. /** Intermediate information about the digest of a stream of data. */
  1302. struct crypto_digest_t {
  1303. union {
  1304. SHA_CTX sha1; /**< state for SHA1 */
  1305. SHA256_CTX sha2; /**< state for SHA256 */
  1306. } d; /**< State for the digest we're using. Only one member of the
  1307. * union is usable, depending on the value of <b>algorithm</b>. */
  1308. ENUM_BF(digest_algorithm_t) algorithm : 8; /**< Which algorithm is in use? */
  1309. };
  1310. /** Allocate and return a new digest object to compute SHA1 digests.
  1311. */
  1312. crypto_digest_t *
  1313. crypto_digest_new(void)
  1314. {
  1315. crypto_digest_t *r;
  1316. r = tor_malloc(sizeof(crypto_digest_t));
  1317. SHA1_Init(&r->d.sha1);
  1318. r->algorithm = DIGEST_SHA1;
  1319. return r;
  1320. }
  1321. /** Allocate and return a new digest object to compute 256-bit digests
  1322. * using <b>algorithm</b>. */
  1323. crypto_digest_t *
  1324. crypto_digest256_new(digest_algorithm_t algorithm)
  1325. {
  1326. crypto_digest_t *r;
  1327. tor_assert(algorithm == DIGEST_SHA256);
  1328. r = tor_malloc(sizeof(crypto_digest_t));
  1329. SHA256_Init(&r->d.sha2);
  1330. r->algorithm = algorithm;
  1331. return r;
  1332. }
  1333. /** Deallocate a digest object.
  1334. */
  1335. void
  1336. crypto_digest_free(crypto_digest_t *digest)
  1337. {
  1338. if (!digest)
  1339. return;
  1340. memwipe(digest, 0, sizeof(crypto_digest_t));
  1341. tor_free(digest);
  1342. }
  1343. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1344. */
  1345. void
  1346. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  1347. size_t len)
  1348. {
  1349. tor_assert(digest);
  1350. tor_assert(data);
  1351. /* Using the SHA*_*() calls directly means we don't support doing
  1352. * SHA in hardware. But so far the delay of getting the question
  1353. * to the hardware, and hearing the answer, is likely higher than
  1354. * just doing it ourselves. Hashes are fast.
  1355. */
  1356. switch (digest->algorithm) {
  1357. case DIGEST_SHA1:
  1358. SHA1_Update(&digest->d.sha1, (void*)data, len);
  1359. break;
  1360. case DIGEST_SHA256:
  1361. SHA256_Update(&digest->d.sha2, (void*)data, len);
  1362. break;
  1363. default:
  1364. tor_fragile_assert();
  1365. break;
  1366. }
  1367. }
  1368. /** Compute the hash of the data that has been passed to the digest
  1369. * object; write the first out_len bytes of the result to <b>out</b>.
  1370. * <b>out_len</b> must be \<= DIGEST256_LEN.
  1371. */
  1372. void
  1373. crypto_digest_get_digest(crypto_digest_t *digest,
  1374. char *out, size_t out_len)
  1375. {
  1376. unsigned char r[DIGEST256_LEN];
  1377. crypto_digest_t tmpenv;
  1378. tor_assert(digest);
  1379. tor_assert(out);
  1380. /* memcpy into a temporary ctx, since SHA*_Final clears the context */
  1381. memcpy(&tmpenv, digest, sizeof(crypto_digest_t));
  1382. switch (digest->algorithm) {
  1383. case DIGEST_SHA1:
  1384. tor_assert(out_len <= DIGEST_LEN);
  1385. SHA1_Final(r, &tmpenv.d.sha1);
  1386. break;
  1387. case DIGEST_SHA256:
  1388. tor_assert(out_len <= DIGEST256_LEN);
  1389. SHA256_Final(r, &tmpenv.d.sha2);
  1390. break;
  1391. default:
  1392. log_warn(LD_BUG, "Called with unknown algorithm %d", digest->algorithm);
  1393. /* If fragile_assert is not enabled, then we should at least not
  1394. * leak anything. */
  1395. memset(r, 0xff, sizeof(r));
  1396. tor_fragile_assert();
  1397. break;
  1398. }
  1399. memcpy(out, r, out_len);
  1400. memwipe(r, 0, sizeof(r));
  1401. }
  1402. /** Allocate and return a new digest object with the same state as
  1403. * <b>digest</b>
  1404. */
  1405. crypto_digest_t *
  1406. crypto_digest_dup(const crypto_digest_t *digest)
  1407. {
  1408. crypto_digest_t *r;
  1409. tor_assert(digest);
  1410. r = tor_malloc(sizeof(crypto_digest_t));
  1411. memcpy(r,digest,sizeof(crypto_digest_t));
  1412. return r;
  1413. }
  1414. /** Replace the state of the digest object <b>into</b> with the state
  1415. * of the digest object <b>from</b>.
  1416. */
  1417. void
  1418. crypto_digest_assign(crypto_digest_t *into,
  1419. const crypto_digest_t *from)
  1420. {
  1421. tor_assert(into);
  1422. tor_assert(from);
  1423. memcpy(into,from,sizeof(crypto_digest_t));
  1424. }
  1425. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1426. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  1427. * plus the optional string <b>append</b>, computed with the algorithm
  1428. * <b>alg</b>.
  1429. * <b>out_len</b> must be \<= DIGEST256_LEN. */
  1430. void
  1431. crypto_digest_smartlist(char *digest_out, size_t len_out,
  1432. const smartlist_t *lst, const char *append,
  1433. digest_algorithm_t alg)
  1434. {
  1435. crypto_digest_t *d;
  1436. if (alg == DIGEST_SHA1)
  1437. d = crypto_digest_new();
  1438. else
  1439. d = crypto_digest256_new(alg);
  1440. SMARTLIST_FOREACH(lst, const char *, cp,
  1441. crypto_digest_add_bytes(d, cp, strlen(cp)));
  1442. if (append)
  1443. crypto_digest_add_bytes(d, append, strlen(append));
  1444. crypto_digest_get_digest(d, digest_out, len_out);
  1445. crypto_digest_free(d);
  1446. }
  1447. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1448. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  1449. * result in <b>hmac_out</b>.
  1450. */
  1451. void
  1452. crypto_hmac_sha256(char *hmac_out,
  1453. const char *key, size_t key_len,
  1454. const char *msg, size_t msg_len)
  1455. {
  1456. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  1457. tor_assert(key_len < INT_MAX);
  1458. tor_assert(msg_len < INT_MAX);
  1459. HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  1460. (unsigned char*)hmac_out, NULL);
  1461. }
  1462. /* DH */
  1463. /** Our DH 'g' parameter */
  1464. #define DH_GENERATOR 2
  1465. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  1466. static BIGNUM *dh_param_p = NULL;
  1467. /** Shared P parameter for our TLS DH key exchanges. */
  1468. static BIGNUM *dh_param_p_tls = NULL;
  1469. /** Shared G parameter for our DH key exchanges. */
  1470. static BIGNUM *dh_param_g = NULL;
  1471. /** Generate and return a reasonable and safe DH parameter p. */
  1472. static BIGNUM *
  1473. crypto_generate_dynamic_dh_modulus(void)
  1474. {
  1475. BIGNUM *dynamic_dh_modulus;
  1476. DH *dh_parameters;
  1477. int r, dh_codes;
  1478. char *s;
  1479. dynamic_dh_modulus = BN_new();
  1480. tor_assert(dynamic_dh_modulus);
  1481. dh_parameters = DH_generate_parameters(DH_BYTES*8, DH_GENERATOR, NULL, NULL);
  1482. tor_assert(dh_parameters);
  1483. r = DH_check(dh_parameters, &dh_codes);
  1484. tor_assert(r && !dh_codes);
  1485. BN_copy(dynamic_dh_modulus, dh_parameters->p);
  1486. tor_assert(dynamic_dh_modulus);
  1487. DH_free(dh_parameters);
  1488. { /* log the dynamic DH modulus: */
  1489. s = BN_bn2hex(dynamic_dh_modulus);
  1490. tor_assert(s);
  1491. log_info(LD_OR, "Dynamic DH modulus generated: [%s]", s);
  1492. OPENSSL_free(s);
  1493. }
  1494. return dynamic_dh_modulus;
  1495. }
  1496. /** Store our dynamic DH modulus (and its group parameters) to
  1497. <b>fname</b> for future use. */
  1498. static int
  1499. crypto_store_dynamic_dh_modulus(const char *fname)
  1500. {
  1501. int len, new_len;
  1502. DH *dh = NULL;
  1503. unsigned char *dh_string_repr = NULL;
  1504. char *base64_encoded_dh = NULL;
  1505. char *file_string = NULL;
  1506. int retval = -1;
  1507. static const char file_header[] = "# This file contains stored Diffie-"
  1508. "Hellman parameters for future use.\n# You *do not* need to edit this "
  1509. "file.\n\n";
  1510. tor_assert(fname);
  1511. if (!dh_param_p_tls) {
  1512. log_info(LD_CRYPTO, "Tried to store a DH modulus that does not exist.");
  1513. goto done;
  1514. }
  1515. if (!(dh = DH_new()))
  1516. goto done;
  1517. if (!(dh->p = BN_dup(dh_param_p_tls)))
  1518. goto done;
  1519. if (!(dh->g = BN_new()))
  1520. goto done;
  1521. if (!BN_set_word(dh->g, DH_GENERATOR))
  1522. goto done;
  1523. len = i2d_DHparams(dh, &dh_string_repr);
  1524. if ((len < 0) || (dh_string_repr == NULL)) {
  1525. log_warn(LD_CRYPTO, "Error occured while DER encoding DH modulus (2).");
  1526. goto done;
  1527. }
  1528. base64_encoded_dh = tor_malloc_zero(len * 2); /* should be enough */
  1529. new_len = base64_encode(base64_encoded_dh, len * 2,
  1530. (char *)dh_string_repr, len);
  1531. if (new_len < 0) {
  1532. log_warn(LD_CRYPTO, "Error occured while base64-encoding DH modulus.");
  1533. goto done;
  1534. }
  1535. /* concatenate file header and the dh parameters blob */
  1536. new_len = tor_asprintf(&file_string, "%s%s", file_header, base64_encoded_dh);
  1537. /* write to file */
  1538. if (write_bytes_to_new_file(fname, file_string, new_len, 0) < 0) {
  1539. log_info(LD_CRYPTO, "'%s' was already occupied.", fname);
  1540. goto done;
  1541. }
  1542. retval = 0;
  1543. done:
  1544. if (dh)
  1545. DH_free(dh);
  1546. if (dh_string_repr)
  1547. OPENSSL_free(dh_string_repr);
  1548. tor_free(base64_encoded_dh);
  1549. tor_free(file_string);
  1550. return retval;
  1551. }
  1552. /** Return the dynamic DH modulus stored in <b>fname</b>. If there is no
  1553. dynamic DH modulus stored in <b>fname</b>, return NULL. */
  1554. static BIGNUM *
  1555. crypto_get_stored_dynamic_dh_modulus(const char *fname)
  1556. {
  1557. int retval;
  1558. char *contents = NULL;
  1559. const char *contents_tmp = NULL;
  1560. int dh_codes;
  1561. DH *stored_dh = NULL;
  1562. BIGNUM *dynamic_dh_modulus = NULL;
  1563. int length = 0;
  1564. unsigned char *base64_decoded_dh = NULL;
  1565. const unsigned char *cp = NULL;
  1566. tor_assert(fname);
  1567. contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
  1568. if (!contents) {
  1569. log_info(LD_CRYPTO, "Could not open file '%s'", fname);
  1570. goto done; /*usually means that ENOENT. don't try to move file to broken.*/
  1571. }
  1572. /* skip the file header */
  1573. contents_tmp = eat_whitespace(contents);
  1574. if (!*contents_tmp) {
  1575. log_warn(LD_CRYPTO, "Stored dynamic DH modulus file "
  1576. "seems corrupted (eat_whitespace).");
  1577. goto err;
  1578. }
  1579. /* 'fname' contains the DH parameters stored in base64-ed DER
  1580. * format. We are only interested in the DH modulus.
  1581. * NOTE: We allocate more storage here than we need. Since we're already
  1582. * doing that, we can also add 1 byte extra to appease Coverity's
  1583. * scanner. */
  1584. cp = base64_decoded_dh = tor_malloc_zero(strlen(contents_tmp) + 1);
  1585. length = base64_decode((char *)base64_decoded_dh, strlen(contents_tmp),
  1586. contents_tmp, strlen(contents_tmp));
  1587. if (length < 0) {
  1588. log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (base64).");
  1589. goto err;
  1590. }
  1591. stored_dh = d2i_DHparams(NULL, &cp, length);
  1592. if ((!stored_dh) || (cp - base64_decoded_dh != length)) {
  1593. log_warn(LD_CRYPTO, "Stored dynamic DH modulus seems corrupted (d2i).");
  1594. goto err;
  1595. }
  1596. { /* check the cryptographic qualities of the stored dynamic DH modulus: */
  1597. retval = DH_check(stored_dh, &dh_codes);
  1598. if (!retval || dh_codes) {
  1599. log_warn(LD_CRYPTO, "Stored dynamic DH modulus is not a safe prime.");
  1600. goto err;
  1601. }
  1602. retval = DH_size(stored_dh);
  1603. if (retval < DH_BYTES) {
  1604. log_warn(LD_CRYPTO, "Stored dynamic DH modulus is smaller "
  1605. "than '%d' bits.", DH_BYTES*8);
  1606. goto err;
  1607. }
  1608. if (!BN_is_word(stored_dh->g, 2)) {
  1609. log_warn(LD_CRYPTO, "Stored dynamic DH parameters do not use '2' "
  1610. "as the group generator.");
  1611. goto err;
  1612. }
  1613. }
  1614. { /* log the dynamic DH modulus: */
  1615. char *s = BN_bn2hex(stored_dh->p);
  1616. tor_assert(s);
  1617. log_info(LD_OR, "Found stored dynamic DH modulus: [%s]", s);
  1618. OPENSSL_free(s);
  1619. }
  1620. goto done;
  1621. err:
  1622. {
  1623. /* move broken prime to $filename.broken */
  1624. char *fname_new=NULL;
  1625. tor_asprintf(&fname_new, "%s.broken", fname);
  1626. log_warn(LD_CRYPTO, "Moving broken dynamic DH prime to '%s'.", fname_new);
  1627. if (replace_file(fname, fname_new))
  1628. log_notice(LD_CRYPTO, "Error while moving '%s' to '%s'.",
  1629. fname, fname_new);
  1630. tor_free(fname_new);
  1631. }
  1632. if (stored_dh) {
  1633. DH_free(stored_dh);
  1634. stored_dh = NULL;
  1635. }
  1636. done:
  1637. tor_free(contents);
  1638. tor_free(base64_decoded_dh);
  1639. if (stored_dh) {
  1640. dynamic_dh_modulus = BN_dup(stored_dh->p);
  1641. DH_free(stored_dh);
  1642. }
  1643. return dynamic_dh_modulus;
  1644. }
  1645. /** Set the global TLS Diffie-Hellman modulus.
  1646. * If <b>dynamic_dh_modulus_fname</b> is set, try to read a dynamic DH modulus
  1647. * off it and use it as the DH modulus. If that's not possible,
  1648. * generate a new dynamic DH modulus.
  1649. * If <b>dynamic_dh_modulus_fname</b> is NULL, use the Apache mod_ssl DH
  1650. * modulus. */
  1651. void
  1652. crypto_set_tls_dh_prime(const char *dynamic_dh_modulus_fname)
  1653. {
  1654. BIGNUM *tls_prime = NULL;
  1655. int store_dh_prime_afterwards = 0;
  1656. int r;
  1657. /* If the space is occupied, free the previous TLS DH prime */
  1658. if (dh_param_p_tls) {
  1659. BN_free(dh_param_p_tls);
  1660. dh_param_p_tls = NULL;
  1661. }
  1662. if (dynamic_dh_modulus_fname) { /* use dynamic DH modulus: */
  1663. log_info(LD_OR, "Using stored dynamic DH modulus.");
  1664. tls_prime = crypto_get_stored_dynamic_dh_modulus(dynamic_dh_modulus_fname);
  1665. if (!tls_prime) {
  1666. log_notice(LD_OR, "Generating fresh dynamic DH modulus. "
  1667. "This might take a while...");
  1668. tls_prime = crypto_generate_dynamic_dh_modulus();
  1669. store_dh_prime_afterwards++;
  1670. }
  1671. } else { /* use the static DH prime modulus used by Apache in mod_ssl: */
  1672. tls_prime = BN_new();
  1673. tor_assert(tls_prime);
  1674. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  1675. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  1676. * prime.
  1677. */
  1678. r =BN_hex2bn(&tls_prime,
  1679. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  1680. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  1681. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  1682. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  1683. "B0E7393E0F24218EB3");
  1684. tor_assert(r);
  1685. }
  1686. tor_assert(tls_prime);
  1687. dh_param_p_tls = tls_prime;
  1688. if (store_dh_prime_afterwards)
  1689. /* save the new dynamic DH modulus to disk. */
  1690. if (crypto_store_dynamic_dh_modulus(dynamic_dh_modulus_fname)) {
  1691. log_notice(LD_CRYPTO, "Failed while storing dynamic DH modulus. "
  1692. "Make sure your data directory is sane.");
  1693. }
  1694. }
  1695. /** Initialize dh_param_p and dh_param_g if they are not already
  1696. * set. */
  1697. static void
  1698. init_dh_param(void)
  1699. {
  1700. BIGNUM *circuit_dh_prime, *generator;
  1701. int r;
  1702. if (dh_param_p && dh_param_g)
  1703. return;
  1704. circuit_dh_prime = BN_new();
  1705. generator = BN_new();
  1706. tor_assert(circuit_dh_prime && generator);
  1707. /* Set our generator for all DH parameters */
  1708. r = BN_set_word(generator, DH_GENERATOR);
  1709. tor_assert(r);
  1710. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1711. supposedly it equals:
  1712. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1713. */
  1714. r = BN_hex2bn(&circuit_dh_prime,
  1715. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1716. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1717. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1718. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1719. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1720. tor_assert(r);
  1721. /* Set the new values as the global DH parameters. */
  1722. dh_param_p = circuit_dh_prime;
  1723. dh_param_g = generator;
  1724. /* Ensure that we have TLS DH parameters set up, too, even if we're
  1725. going to change them soon. */
  1726. if (!dh_param_p_tls) {
  1727. crypto_set_tls_dh_prime(NULL);
  1728. }
  1729. }
  1730. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  1731. * handshake. Since we exponentiate by this value, choosing a smaller one
  1732. * lets our handhake go faster.
  1733. */
  1734. #define DH_PRIVATE_KEY_BITS 320
  1735. /** Allocate and return a new DH object for a key exchange.
  1736. */
  1737. crypto_dh_t *
  1738. crypto_dh_new(int dh_type)
  1739. {
  1740. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  1741. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  1742. dh_type == DH_TYPE_REND);
  1743. if (!dh_param_p)
  1744. init_dh_param();
  1745. if (!(res->dh = DH_new()))
  1746. goto err;
  1747. if (dh_type == DH_TYPE_TLS) {
  1748. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  1749. goto err;
  1750. } else {
  1751. if (!(res->dh->p = BN_dup(dh_param_p)))
  1752. goto err;
  1753. }
  1754. if (!(res->dh->g = BN_dup(dh_param_g)))
  1755. goto err;
  1756. res->dh->length = DH_PRIVATE_KEY_BITS;
  1757. return res;
  1758. err:
  1759. crypto_log_errors(LOG_WARN, "creating DH object");
  1760. if (res->dh) DH_free(res->dh); /* frees p and g too */
  1761. tor_free(res);
  1762. return NULL;
  1763. }
  1764. /** Return a copy of <b>dh</b>, sharing its internal state. */
  1765. crypto_dh_t *
  1766. crypto_dh_dup(const crypto_dh_t *dh)
  1767. {
  1768. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  1769. dh_new->dh = dh->dh;
  1770. DH_up_ref(dh->dh);
  1771. return dh_new;
  1772. }
  1773. /** Return the length of the DH key in <b>dh</b>, in bytes.
  1774. */
  1775. int
  1776. crypto_dh_get_bytes(crypto_dh_t *dh)
  1777. {
  1778. tor_assert(dh);
  1779. return DH_size(dh->dh);
  1780. }
  1781. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  1782. * success, -1 on failure.
  1783. */
  1784. int
  1785. crypto_dh_generate_public(crypto_dh_t *dh)
  1786. {
  1787. again:
  1788. if (!DH_generate_key(dh->dh)) {
  1789. crypto_log_errors(LOG_WARN, "generating DH key");
  1790. return -1;
  1791. }
  1792. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  1793. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  1794. "the-universe chances really do happen. Trying again.");
  1795. /* Free and clear the keys, so OpenSSL will actually try again. */
  1796. BN_free(dh->dh->pub_key);
  1797. BN_free(dh->dh->priv_key);
  1798. dh->dh->pub_key = dh->dh->priv_key = NULL;
  1799. goto again;
  1800. }
  1801. return 0;
  1802. }
  1803. /** Generate g^x as necessary, and write the g^x for the key exchange
  1804. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  1805. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  1806. */
  1807. int
  1808. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  1809. {
  1810. int bytes;
  1811. tor_assert(dh);
  1812. if (!dh->dh->pub_key) {
  1813. if (crypto_dh_generate_public(dh)<0)
  1814. return -1;
  1815. }
  1816. tor_assert(dh->dh->pub_key);
  1817. bytes = BN_num_bytes(dh->dh->pub_key);
  1818. tor_assert(bytes >= 0);
  1819. if (pubkey_len < (size_t)bytes) {
  1820. log_warn(LD_CRYPTO,
  1821. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  1822. (int) pubkey_len, bytes);
  1823. return -1;
  1824. }
  1825. memset(pubkey, 0, pubkey_len);
  1826. BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  1827. return 0;
  1828. }
  1829. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  1830. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  1831. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  1832. */
  1833. static int
  1834. tor_check_dh_key(int severity, BIGNUM *bn)
  1835. {
  1836. BIGNUM *x;
  1837. char *s;
  1838. tor_assert(bn);
  1839. x = BN_new();
  1840. tor_assert(x);
  1841. if (!dh_param_p)
  1842. init_dh_param();
  1843. BN_set_word(x, 1);
  1844. if (BN_cmp(bn,x)<=0) {
  1845. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  1846. goto err;
  1847. }
  1848. BN_copy(x,dh_param_p);
  1849. BN_sub_word(x, 1);
  1850. if (BN_cmp(bn,x)>=0) {
  1851. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  1852. goto err;
  1853. }
  1854. BN_free(x);
  1855. return 0;
  1856. err:
  1857. BN_free(x);
  1858. s = BN_bn2hex(bn);
  1859. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  1860. OPENSSL_free(s);
  1861. return -1;
  1862. }
  1863. #undef MIN
  1864. #define MIN(a,b) ((a)<(b)?(a):(b))
  1865. /** Given a DH key exchange object, and our peer's value of g^y (as a
  1866. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  1867. * <b>secret_bytes_out</b> bytes of shared key material and write them
  1868. * to <b>secret_out</b>. Return the number of bytes generated on success,
  1869. * or -1 on failure.
  1870. *
  1871. * (We generate key material by computing
  1872. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  1873. * where || is concatenation.)
  1874. */
  1875. ssize_t
  1876. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  1877. const char *pubkey, size_t pubkey_len,
  1878. char *secret_out, size_t secret_bytes_out)
  1879. {
  1880. char *secret_tmp = NULL;
  1881. BIGNUM *pubkey_bn = NULL;
  1882. size_t secret_len=0, secret_tmp_len=0;
  1883. int result=0;
  1884. tor_assert(dh);
  1885. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  1886. tor_assert(pubkey_len < INT_MAX);
  1887. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  1888. (int)pubkey_len, NULL)))
  1889. goto error;
  1890. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  1891. /* Check for invalid public keys. */
  1892. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  1893. goto error;
  1894. }
  1895. secret_tmp_len = crypto_dh_get_bytes(dh);
  1896. secret_tmp = tor_malloc(secret_tmp_len);
  1897. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  1898. if (result < 0) {
  1899. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  1900. goto error;
  1901. }
  1902. secret_len = result;
  1903. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  1904. (uint8_t*)secret_out, secret_bytes_out)<0)
  1905. goto error;
  1906. secret_len = secret_bytes_out;
  1907. goto done;
  1908. error:
  1909. result = -1;
  1910. done:
  1911. crypto_log_errors(LOG_WARN, "completing DH handshake");
  1912. if (pubkey_bn)
  1913. BN_free(pubkey_bn);
  1914. if (secret_tmp) {
  1915. memwipe(secret_tmp, 0, secret_tmp_len);
  1916. tor_free(secret_tmp);
  1917. }
  1918. if (result < 0)
  1919. return result;
  1920. else
  1921. return secret_len;
  1922. }
  1923. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  1924. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  1925. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  1926. * H(K | [00]) | H(K | [01]) | ....
  1927. *
  1928. * This is the key expansion algorithm used in the "TAP" circuit extension
  1929. * mechanism; it shouldn't be used for new protocols.
  1930. *
  1931. * Return 0 on success, -1 on failure.
  1932. */
  1933. int
  1934. crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
  1935. uint8_t *key_out, size_t key_out_len)
  1936. {
  1937. int i;
  1938. uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
  1939. uint8_t digest[DIGEST_LEN];
  1940. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1941. tor_assert(key_out_len <= DIGEST_LEN*256);
  1942. memcpy(tmp, key_in, key_in_len);
  1943. for (cp = key_out, i=0; cp < key_out+key_out_len;
  1944. ++i, cp += DIGEST_LEN) {
  1945. tmp[key_in_len] = i;
  1946. if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1))
  1947. goto err;
  1948. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  1949. }
  1950. memwipe(tmp, 0, key_in_len+1);
  1951. tor_free(tmp);
  1952. memwipe(digest, 0, sizeof(digest));
  1953. return 0;
  1954. err:
  1955. memwipe(tmp, 0, key_in_len+1);
  1956. tor_free(tmp);
  1957. memwipe(digest, 0, sizeof(digest));
  1958. return -1;
  1959. }
  1960. /** Expand some secret key material according to RFC5869, using SHA256 as the
  1961. * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
  1962. * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
  1963. * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
  1964. * and "info" parameters respectively. On success, write <b>key_out_len</b>
  1965. * bytes to <b>key_out</b> and return 0. On failure, return -1.
  1966. */
  1967. int
  1968. crypto_expand_key_material_rfc5869_sha256(
  1969. const uint8_t *key_in, size_t key_in_len,
  1970. const uint8_t *salt_in, size_t salt_in_len,
  1971. const uint8_t *info_in, size_t info_in_len,
  1972. uint8_t *key_out, size_t key_out_len)
  1973. {
  1974. uint8_t prk[DIGEST256_LEN];
  1975. uint8_t tmp[DIGEST256_LEN + 128 + 1];
  1976. uint8_t mac[DIGEST256_LEN];
  1977. int i;
  1978. uint8_t *outp;
  1979. size_t tmp_len;
  1980. crypto_hmac_sha256((char*)prk,
  1981. (const char*)salt_in, salt_in_len,
  1982. (const char*)key_in, key_in_len);
  1983. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1984. tor_assert(key_out_len <= DIGEST256_LEN * 256);
  1985. tor_assert(info_in_len <= 128);
  1986. memset(tmp, 0, sizeof(tmp));
  1987. outp = key_out;
  1988. i = 1;
  1989. while (key_out_len) {
  1990. size_t n;
  1991. if (i > 1) {
  1992. memcpy(tmp, mac, DIGEST256_LEN);
  1993. memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
  1994. tmp[DIGEST256_LEN+info_in_len] = i;
  1995. tmp_len = DIGEST256_LEN + info_in_len + 1;
  1996. } else {
  1997. memcpy(tmp, info_in, info_in_len);
  1998. tmp[info_in_len] = i;
  1999. tmp_len = info_in_len + 1;
  2000. }
  2001. crypto_hmac_sha256((char*)mac,
  2002. (const char*)prk, DIGEST256_LEN,
  2003. (const char*)tmp, tmp_len);
  2004. n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
  2005. memcpy(outp, mac, n);
  2006. key_out_len -= n;
  2007. outp += n;
  2008. ++i;
  2009. }
  2010. memwipe(tmp, 0, sizeof(tmp));
  2011. memwipe(mac, 0, sizeof(mac));
  2012. return 0;
  2013. }
  2014. /** Free a DH key exchange object.
  2015. */
  2016. void
  2017. crypto_dh_free(crypto_dh_t *dh)
  2018. {
  2019. if (!dh)
  2020. return;
  2021. tor_assert(dh->dh);
  2022. DH_free(dh->dh);
  2023. tor_free(dh);
  2024. }
  2025. /* random numbers */
  2026. /** How many bytes of entropy we add at once.
  2027. *
  2028. * This is how much entropy OpenSSL likes to add right now, so maybe it will
  2029. * work for us too. */
  2030. #define ADD_ENTROPY 32
  2031. /** True iff it's safe to use RAND_poll after setup.
  2032. *
  2033. * Versions of OpenSSL prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
  2034. * would allocate an fd_set on the stack, open a new file, and try to FD_SET
  2035. * that fd without checking whether it fit in the fd_set. Thus, if the
  2036. * system has not just been started up, it is unsafe to call */
  2037. #define RAND_POLL_IS_SAFE \
  2038. (OPENSSL_VERSION_NUMBER >= OPENSSL_V(0,9,8,'c'))
  2039. /** Set the seed of the weak RNG to a random value. */
  2040. void
  2041. crypto_seed_weak_rng(tor_weak_rng_t *rng)
  2042. {
  2043. unsigned seed;
  2044. crypto_rand((void*)&seed, sizeof(seed));
  2045. tor_init_weak_random(rng, seed);
  2046. }
  2047. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2048. * storing it into <b>out</b>.
  2049. */
  2050. int
  2051. crypto_strongest_rand(uint8_t *out, size_t out_len)
  2052. {
  2053. #ifdef _WIN32
  2054. static int provider_set = 0;
  2055. static HCRYPTPROV provider;
  2056. #else
  2057. static const char *filenames[] = {
  2058. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  2059. };
  2060. int fd, i;
  2061. size_t n;
  2062. #endif
  2063. #ifdef _WIN32
  2064. if (!provider_set) {
  2065. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  2066. CRYPT_VERIFYCONTEXT)) {
  2067. if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
  2068. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  2069. return -1;
  2070. }
  2071. }
  2072. provider_set = 1;
  2073. }
  2074. if (!CryptGenRandom(provider, out_len, out)) {
  2075. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  2076. return -1;
  2077. }
  2078. return 0;
  2079. #else
  2080. for (i = 0; filenames[i]; ++i) {
  2081. fd = open(filenames[i], O_RDONLY, 0);
  2082. if (fd<0) continue;
  2083. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  2084. n = read_all(fd, (char*)out, out_len, 0);
  2085. close(fd);
  2086. if (n != out_len) {
  2087. log_warn(LD_CRYPTO,
  2088. "Error reading from entropy source (read only %lu bytes).",
  2089. (unsigned long)n);
  2090. return -1;
  2091. }
  2092. return 0;
  2093. }
  2094. log_warn(LD_CRYPTO, "Cannot get strong entropy: no entropy source found.");
  2095. return -1;
  2096. #endif
  2097. }
  2098. /** Seed OpenSSL's random number generator with bytes from the operating
  2099. * system. <b>startup</b> should be true iff we have just started Tor and
  2100. * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
  2101. */
  2102. int
  2103. crypto_seed_rng(int startup)
  2104. {
  2105. int rand_poll_ok = 0, load_entropy_ok = 0;
  2106. uint8_t buf[ADD_ENTROPY];
  2107. /* OpenSSL has a RAND_poll function that knows about more kinds of
  2108. * entropy than we do. We'll try calling that, *and* calling our own entropy
  2109. * functions. If one succeeds, we'll accept the RNG as seeded. */
  2110. if (startup || RAND_POLL_IS_SAFE) {
  2111. rand_poll_ok = RAND_poll();
  2112. if (rand_poll_ok == 0)
  2113. log_warn(LD_CRYPTO, "RAND_poll() failed.");
  2114. }
  2115. load_entropy_ok = !crypto_strongest_rand(buf, sizeof(buf));
  2116. if (load_entropy_ok) {
  2117. RAND_seed(buf, sizeof(buf));
  2118. }
  2119. memwipe(buf, 0, sizeof(buf));
  2120. if (rand_poll_ok || load_entropy_ok)
  2121. return 0;
  2122. else
  2123. return -1;
  2124. }
  2125. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
  2126. * success, -1 on failure.
  2127. */
  2128. MOCK_IMPL(int,
  2129. crypto_rand, (char *to, size_t n))
  2130. {
  2131. int r;
  2132. tor_assert(n < INT_MAX);
  2133. tor_assert(to);
  2134. r = RAND_bytes((unsigned char*)to, (int)n);
  2135. if (r == 0)
  2136. crypto_log_errors(LOG_WARN, "generating random data");
  2137. return (r == 1) ? 0 : -1;
  2138. }
  2139. /** Return a pseudorandom integer, chosen uniformly from the values
  2140. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  2141. * INT_MAX+1, inclusive. */
  2142. int
  2143. crypto_rand_int(unsigned int max)
  2144. {
  2145. unsigned int val;
  2146. unsigned int cutoff;
  2147. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  2148. tor_assert(max > 0); /* don't div by 0 */
  2149. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2150. * distribution with clipping at the upper end of unsigned int's
  2151. * range.
  2152. */
  2153. cutoff = UINT_MAX - (UINT_MAX%max);
  2154. while (1) {
  2155. crypto_rand((char*)&val, sizeof(val));
  2156. if (val < cutoff)
  2157. return val % max;
  2158. }
  2159. }
  2160. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  2161. * between 0 and <b>max</b>-1. */
  2162. uint64_t
  2163. crypto_rand_uint64(uint64_t max)
  2164. {
  2165. uint64_t val;
  2166. uint64_t cutoff;
  2167. tor_assert(max < UINT64_MAX);
  2168. tor_assert(max > 0); /* don't div by 0 */
  2169. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2170. * distribution with clipping at the upper end of unsigned int's
  2171. * range.
  2172. */
  2173. cutoff = UINT64_MAX - (UINT64_MAX%max);
  2174. while (1) {
  2175. crypto_rand((char*)&val, sizeof(val));
  2176. if (val < cutoff)
  2177. return val % max;
  2178. }
  2179. }
  2180. /** Return a pseudorandom double d, chosen uniformly from the range
  2181. * 0.0 <= d < 1.0.
  2182. */
  2183. double
  2184. crypto_rand_double(void)
  2185. {
  2186. /* We just use an unsigned int here; we don't really care about getting
  2187. * more than 32 bits of resolution */
  2188. unsigned int uint;
  2189. crypto_rand((char*)&uint, sizeof(uint));
  2190. #if SIZEOF_INT == 4
  2191. #define UINT_MAX_AS_DOUBLE 4294967296.0
  2192. #elif SIZEOF_INT == 8
  2193. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  2194. #else
  2195. #error SIZEOF_INT is neither 4 nor 8
  2196. #endif
  2197. return ((double)uint) / UINT_MAX_AS_DOUBLE;
  2198. }
  2199. /** Generate and return a new random hostname starting with <b>prefix</b>,
  2200. * ending with <b>suffix</b>, and containing no fewer than
  2201. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  2202. * characters between.
  2203. *
  2204. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  2205. **/
  2206. char *
  2207. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  2208. const char *suffix)
  2209. {
  2210. char *result, *rand_bytes;
  2211. int randlen, rand_bytes_len;
  2212. size_t resultlen, prefixlen;
  2213. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  2214. max_rand_len = MAX_DNS_LABEL_SIZE;
  2215. if (min_rand_len > max_rand_len)
  2216. min_rand_len = max_rand_len;
  2217. randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
  2218. prefixlen = strlen(prefix);
  2219. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  2220. rand_bytes_len = ((randlen*5)+7)/8;
  2221. if (rand_bytes_len % 5)
  2222. rand_bytes_len += 5 - (rand_bytes_len%5);
  2223. rand_bytes = tor_malloc(rand_bytes_len);
  2224. crypto_rand(rand_bytes, rand_bytes_len);
  2225. result = tor_malloc(resultlen);
  2226. memcpy(result, prefix, prefixlen);
  2227. base32_encode(result+prefixlen, resultlen-prefixlen,
  2228. rand_bytes, rand_bytes_len);
  2229. tor_free(rand_bytes);
  2230. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  2231. return result;
  2232. }
  2233. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  2234. * is empty. */
  2235. void *
  2236. smartlist_choose(const smartlist_t *sl)
  2237. {
  2238. int len = smartlist_len(sl);
  2239. if (len)
  2240. return smartlist_get(sl,crypto_rand_int(len));
  2241. return NULL; /* no elements to choose from */
  2242. }
  2243. /** Scramble the elements of <b>sl</b> into a random order. */
  2244. void
  2245. smartlist_shuffle(smartlist_t *sl)
  2246. {
  2247. int i;
  2248. /* From the end of the list to the front, choose at random from the
  2249. positions we haven't looked at yet, and swap that position into the
  2250. current position. Remember to give "no swap" the same probability as
  2251. any other swap. */
  2252. for (i = smartlist_len(sl)-1; i > 0; --i) {
  2253. int j = crypto_rand_int(i+1);
  2254. smartlist_swap(sl, i, j);
  2255. }
  2256. }
  2257. /** Base64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
  2258. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  2259. * bytes. Return the number of bytes written on success; -1 if
  2260. * destlen is too short, or other failure.
  2261. */
  2262. int
  2263. base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  2264. {
  2265. /* FFFF we might want to rewrite this along the lines of base64_decode, if
  2266. * it ever shows up in the profile. */
  2267. EVP_ENCODE_CTX ctx;
  2268. int len, ret;
  2269. tor_assert(srclen < INT_MAX);
  2270. /* 48 bytes of input -> 64 bytes of output plus newline.
  2271. Plus one more byte, in case I'm wrong.
  2272. */
  2273. if (destlen < ((srclen/48)+1)*66)
  2274. return -1;
  2275. if (destlen > SIZE_T_CEILING)
  2276. return -1;
  2277. EVP_EncodeInit(&ctx);
  2278. EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
  2279. (unsigned char*)src, (int)srclen);
  2280. EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
  2281. ret += len;
  2282. return ret;
  2283. }
  2284. /** @{ */
  2285. /** Special values used for the base64_decode_table */
  2286. #define X 255
  2287. #define SP 64
  2288. #define PAD 65
  2289. /** @} */
  2290. /** Internal table mapping byte values to what they represent in base64.
  2291. * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
  2292. * skipped. Xs are invalid and must not appear in base64. PAD indicates
  2293. * end-of-string. */
  2294. static const uint8_t base64_decode_table[256] = {
  2295. X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
  2296. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  2297. SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
  2298. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
  2299. X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  2300. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
  2301. X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  2302. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
  2303. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  2304. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  2305. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  2306. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  2307. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  2308. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  2309. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  2310. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  2311. };
  2312. /** Base64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
  2313. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  2314. * bytes. Return the number of bytes written on success; -1 if
  2315. * destlen is too short, or other failure.
  2316. *
  2317. * NOTE 1: destlen is checked conservatively, as though srclen contained no
  2318. * spaces or padding.
  2319. *
  2320. * NOTE 2: This implementation does not check for the correct number of
  2321. * padding "=" characters at the end of the string, and does not check
  2322. * for internal padding characters.
  2323. */
  2324. int
  2325. base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  2326. {
  2327. #ifdef USE_OPENSSL_BASE64
  2328. EVP_ENCODE_CTX ctx;
  2329. int len, ret;
  2330. /* 64 bytes of input -> *up to* 48 bytes of output.
  2331. Plus one more byte, in case I'm wrong.
  2332. */
  2333. if (destlen < ((srclen/64)+1)*49)
  2334. return -1;
  2335. if (destlen > SIZE_T_CEILING)
  2336. return -1;
  2337. EVP_DecodeInit(&ctx);
  2338. EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
  2339. (unsigned char*)src, srclen);
  2340. EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
  2341. ret += len;
  2342. return ret;
  2343. #else
  2344. const char *eos = src+srclen;
  2345. uint32_t n=0;
  2346. int n_idx=0;
  2347. char *dest_orig = dest;
  2348. /* Max number of bits == srclen*6.
  2349. * Number of bytes required to hold all bits == (srclen*6)/8.
  2350. * Yes, we want to round down: anything that hangs over the end of a
  2351. * byte is padding. */
  2352. if (destlen < (srclen*3)/4)
  2353. return -1;
  2354. if (destlen > SIZE_T_CEILING)
  2355. return -1;
  2356. /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
  2357. * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
  2358. * 24 bits, batch them into 3 bytes and flush those bytes to dest.
  2359. */
  2360. for ( ; src < eos; ++src) {
  2361. unsigned char c = (unsigned char) *src;
  2362. uint8_t v = base64_decode_table[c];
  2363. switch (v) {
  2364. case X:
  2365. /* This character isn't allowed in base64. */
  2366. return -1;
  2367. case SP:
  2368. /* This character is whitespace, and has no effect. */
  2369. continue;
  2370. case PAD:
  2371. /* We've hit an = character: the data is over. */
  2372. goto end_of_loop;
  2373. default:
  2374. /* We have an actual 6-bit value. Append it to the bits in n. */
  2375. n = (n<<6) | v;
  2376. if ((++n_idx) == 4) {
  2377. /* We've accumulated 24 bits in n. Flush them. */
  2378. *dest++ = (n>>16);
  2379. *dest++ = (n>>8) & 0xff;
  2380. *dest++ = (n) & 0xff;
  2381. n_idx = 0;
  2382. n = 0;
  2383. }
  2384. }
  2385. }
  2386. end_of_loop:
  2387. /* If we have leftover bits, we need to cope. */
  2388. switch (n_idx) {
  2389. case 0:
  2390. default:
  2391. /* No leftover bits. We win. */
  2392. break;
  2393. case 1:
  2394. /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
  2395. return -1;
  2396. case 2:
  2397. /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
  2398. *dest++ = n >> 4;
  2399. break;
  2400. case 3:
  2401. /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
  2402. *dest++ = n >> 10;
  2403. *dest++ = n >> 2;
  2404. }
  2405. tor_assert((dest-dest_orig) <= (ssize_t)destlen);
  2406. tor_assert((dest-dest_orig) <= INT_MAX);
  2407. return (int)(dest-dest_orig);
  2408. #endif
  2409. }
  2410. #undef X
  2411. #undef SP
  2412. #undef PAD
  2413. /** Base64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
  2414. * and newline characters, and store the nul-terminated result in the first
  2415. * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
  2416. int
  2417. digest_to_base64(char *d64, const char *digest)
  2418. {
  2419. char buf[256];
  2420. base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
  2421. buf[BASE64_DIGEST_LEN] = '\0';
  2422. memcpy(d64, buf, BASE64_DIGEST_LEN+1);
  2423. return 0;
  2424. }
  2425. /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
  2426. * trailing newline or = characters), decode it and store the result in the
  2427. * first DIGEST_LEN bytes at <b>digest</b>. */
  2428. int
  2429. digest_from_base64(char *digest, const char *d64)
  2430. {
  2431. #ifdef USE_OPENSSL_BASE64
  2432. char buf_in[BASE64_DIGEST_LEN+3];
  2433. char buf[256];
  2434. if (strlen(d64) != BASE64_DIGEST_LEN)
  2435. return -1;
  2436. memcpy(buf_in, d64, BASE64_DIGEST_LEN);
  2437. memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
  2438. if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
  2439. return -1;
  2440. memcpy(digest, buf, DIGEST_LEN);
  2441. return 0;
  2442. #else
  2443. if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
  2444. return 0;
  2445. else
  2446. return -1;
  2447. #endif
  2448. }
  2449. /** Base64 encode DIGEST256_LINE bytes from <b>digest</b>, remove the
  2450. * trailing = and newline characters, and store the nul-terminated result in
  2451. * the first BASE64_DIGEST256_LEN+1 bytes of <b>d64</b>. */
  2452. int
  2453. digest256_to_base64(char *d64, const char *digest)
  2454. {
  2455. char buf[256];
  2456. base64_encode(buf, sizeof(buf), digest, DIGEST256_LEN);
  2457. buf[BASE64_DIGEST256_LEN] = '\0';
  2458. memcpy(d64, buf, BASE64_DIGEST256_LEN+1);
  2459. return 0;
  2460. }
  2461. /** Given a base64 encoded, nul-terminated digest in <b>d64</b> (without
  2462. * trailing newline or = characters), decode it and store the result in the
  2463. * first DIGEST256_LEN bytes at <b>digest</b>. */
  2464. int
  2465. digest256_from_base64(char *digest, const char *d64)
  2466. {
  2467. #ifdef USE_OPENSSL_BASE64
  2468. char buf_in[BASE64_DIGEST256_LEN+3];
  2469. char buf[256];
  2470. if (strlen(d64) != BASE64_DIGEST256_LEN)
  2471. return -1;
  2472. memcpy(buf_in, d64, BASE64_DIGEST256_LEN);
  2473. memcpy(buf_in+BASE64_DIGEST256_LEN, "=\n\0", 3);
  2474. if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST256_LEN)
  2475. return -1;
  2476. memcpy(digest, buf, DIGEST256_LEN);
  2477. return 0;
  2478. #else
  2479. if (base64_decode(digest, DIGEST256_LEN, d64, strlen(d64)) == DIGEST256_LEN)
  2480. return 0;
  2481. else
  2482. return -1;
  2483. #endif
  2484. }
  2485. /** Implements base32 encoding as in RFC 4648. Limitation: Requires
  2486. * that srclen*8 is a multiple of 5.
  2487. */
  2488. void
  2489. base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  2490. {
  2491. unsigned int i, v, u;
  2492. size_t nbits = srclen * 8, bit;
  2493. tor_assert(srclen < SIZE_T_CEILING/8);
  2494. tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
  2495. tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
  2496. tor_assert(destlen < SIZE_T_CEILING);
  2497. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  2498. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  2499. v = ((uint8_t)src[bit/8]) << 8;
  2500. if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
  2501. /* set u to the 5-bit value at the bit'th bit of src. */
  2502. u = (v >> (11-(bit%8))) & 0x1F;
  2503. dest[i] = BASE32_CHARS[u];
  2504. }
  2505. dest[i] = '\0';
  2506. }
  2507. /** Implements base32 decoding as in RFC 4648. Limitation: Requires
  2508. * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
  2509. */
  2510. int
  2511. base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  2512. {
  2513. /* XXXX we might want to rewrite this along the lines of base64_decode, if
  2514. * it ever shows up in the profile. */
  2515. unsigned int i;
  2516. size_t nbits, j, bit;
  2517. char *tmp;
  2518. nbits = srclen * 5;
  2519. tor_assert(srclen < SIZE_T_CEILING / 5);
  2520. tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
  2521. tor_assert((nbits/8) <= destlen); /* We need enough space. */
  2522. tor_assert(destlen < SIZE_T_CEILING);
  2523. /* Convert base32 encoded chars to the 5-bit values that they represent. */
  2524. tmp = tor_malloc_zero(srclen);
  2525. for (j = 0; j < srclen; ++j) {
  2526. if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
  2527. else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
  2528. else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
  2529. else {
  2530. log_warn(LD_BUG, "illegal character in base32 encoded string");
  2531. tor_free(tmp);
  2532. return -1;
  2533. }
  2534. }
  2535. /* Assemble result byte-wise by applying five possible cases. */
  2536. for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
  2537. switch (bit % 40) {
  2538. case 0:
  2539. dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
  2540. (((uint8_t)tmp[(bit/5)+1]) >> 2);
  2541. break;
  2542. case 8:
  2543. dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
  2544. (((uint8_t)tmp[(bit/5)+1]) << 1) +
  2545. (((uint8_t)tmp[(bit/5)+2]) >> 4);
  2546. break;
  2547. case 16:
  2548. dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
  2549. (((uint8_t)tmp[(bit/5)+1]) >> 1);
  2550. break;
  2551. case 24:
  2552. dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
  2553. (((uint8_t)tmp[(bit/5)+1]) << 2) +
  2554. (((uint8_t)tmp[(bit/5)+2]) >> 3);
  2555. break;
  2556. case 32:
  2557. dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
  2558. ((uint8_t)tmp[(bit/5)+1]);
  2559. break;
  2560. }
  2561. }
  2562. memwipe(tmp, 0, srclen);
  2563. tor_free(tmp);
  2564. tmp = NULL;
  2565. return 0;
  2566. }
  2567. /** Implement RFC2440-style iterated-salted S2K conversion: convert the
  2568. * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
  2569. * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
  2570. * are a salt; the 9th byte describes how much iteration to do.
  2571. * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
  2572. */
  2573. void
  2574. secret_to_key(char *key_out, size_t key_out_len, const char *secret,
  2575. size_t secret_len, const char *s2k_specifier)
  2576. {
  2577. crypto_digest_t *d;
  2578. uint8_t c;
  2579. size_t count, tmplen;
  2580. char *tmp;
  2581. tor_assert(key_out_len < SIZE_T_CEILING);
  2582. #define EXPBIAS 6
  2583. c = s2k_specifier[8];
  2584. count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
  2585. #undef EXPBIAS
  2586. tor_assert(key_out_len <= DIGEST_LEN);
  2587. d = crypto_digest_new();
  2588. tmplen = 8+secret_len;
  2589. tmp = tor_malloc(tmplen);
  2590. memcpy(tmp,s2k_specifier,8);
  2591. memcpy(tmp+8,secret,secret_len);
  2592. secret_len += 8;
  2593. while (count) {
  2594. if (count >= secret_len) {
  2595. crypto_digest_add_bytes(d, tmp, secret_len);
  2596. count -= secret_len;
  2597. } else {
  2598. crypto_digest_add_bytes(d, tmp, count);
  2599. count = 0;
  2600. }
  2601. }
  2602. crypto_digest_get_digest(d, key_out, key_out_len);
  2603. memwipe(tmp, 0, tmplen);
  2604. tor_free(tmp);
  2605. crypto_digest_free(d);
  2606. }
  2607. /**
  2608. * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
  2609. * the value <b>byte</b>.
  2610. *
  2611. * This function is preferable to memset, since many compilers will happily
  2612. * optimize out memset() when they can convince themselves that the data being
  2613. * cleared will never be read.
  2614. *
  2615. * Right now, our convention is to use this function when we are wiping data
  2616. * that's about to become inaccessible, such as stack buffers that are about
  2617. * to go out of scope or structures that are about to get freed. (In
  2618. * practice, it appears that the compilers we're currently using will optimize
  2619. * out the memset()s for stack-allocated buffers, but not those for
  2620. * about-to-be-freed structures. That could change, though, so we're being
  2621. * wary.) If there are live reads for the data, then you can just use
  2622. * memset().
  2623. */
  2624. void
  2625. memwipe(void *mem, uint8_t byte, size_t sz)
  2626. {
  2627. /* Because whole-program-optimization exists, we may not be able to just
  2628. * have this function call "memset". A smart compiler could inline it, then
  2629. * eliminate dead memsets, and declare itself to be clever. */
  2630. /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
  2631. * based on the pointer value, then uses that junk to update a global
  2632. * variable. It's an elaborate ruse to trick the compiler into not
  2633. * optimizing out the "wipe this memory" code. Read it if you like zany
  2634. * programming tricks! In later versions of Tor, we should look for better
  2635. * not-optimized-out memory wiping stuff. */
  2636. OPENSSL_cleanse(mem, sz);
  2637. /* Just in case some caller of memwipe() is relying on getting a buffer
  2638. * filled with a particular value, fill the buffer.
  2639. *
  2640. * If this function gets inlined, this memset might get eliminated, but
  2641. * that's okay: We only care about this particular memset in the case where
  2642. * the caller should have been using memset(), and the memset() wouldn't get
  2643. * eliminated. In other words, this is here so that we won't break anything
  2644. * if somebody accidentally calls memwipe() instead of memset().
  2645. **/
  2646. memset(mem, byte, sz);
  2647. }
  2648. #ifdef TOR_IS_MULTITHREADED
  2649. #ifndef OPENSSL_THREADS
  2650. #error OpenSSL has been built without thread support. Tor requires an \
  2651. OpenSSL library with thread support enabled.
  2652. #endif
  2653. /** Helper: OpenSSL uses this callback to manipulate mutexes. */
  2654. static void
  2655. openssl_locking_cb_(int mode, int n, const char *file, int line)
  2656. {
  2657. (void)file;
  2658. (void)line;
  2659. if (!openssl_mutexes_)
  2660. /* This is not a really good fix for the
  2661. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  2662. * it can't hurt. */
  2663. return;
  2664. if (mode & CRYPTO_LOCK)
  2665. tor_mutex_acquire(openssl_mutexes_[n]);
  2666. else
  2667. tor_mutex_release(openssl_mutexes_[n]);
  2668. }
  2669. /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
  2670. * as a lock. */
  2671. struct CRYPTO_dynlock_value {
  2672. tor_mutex_t *lock;
  2673. };
  2674. /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
  2675. * documentation in OpenSSL's docs for more info. */
  2676. static struct CRYPTO_dynlock_value *
  2677. openssl_dynlock_create_cb_(const char *file, int line)
  2678. {
  2679. struct CRYPTO_dynlock_value *v;
  2680. (void)file;
  2681. (void)line;
  2682. v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
  2683. v->lock = tor_mutex_new();
  2684. return v;
  2685. }
  2686. /** OpenSSL callback function to acquire or release a lock: see
  2687. * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
  2688. static void
  2689. openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
  2690. const char *file, int line)
  2691. {
  2692. (void)file;
  2693. (void)line;
  2694. if (mode & CRYPTO_LOCK)
  2695. tor_mutex_acquire(v->lock);
  2696. else
  2697. tor_mutex_release(v->lock);
  2698. }
  2699. /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
  2700. * documentation in OpenSSL's docs for more info. */
  2701. static void
  2702. openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
  2703. const char *file, int line)
  2704. {
  2705. (void)file;
  2706. (void)line;
  2707. tor_mutex_free(v->lock);
  2708. tor_free(v);
  2709. }
  2710. /** @{ */
  2711. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  2712. * multithreaded. */
  2713. static int
  2714. setup_openssl_threading(void)
  2715. {
  2716. int i;
  2717. int n = CRYPTO_num_locks();
  2718. n_openssl_mutexes_ = n;
  2719. openssl_mutexes_ = tor_malloc(n*sizeof(tor_mutex_t *));
  2720. for (i=0; i < n; ++i)
  2721. openssl_mutexes_[i] = tor_mutex_new();
  2722. CRYPTO_set_locking_callback(openssl_locking_cb_);
  2723. CRYPTO_set_id_callback(tor_get_thread_id);
  2724. CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_);
  2725. CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_);
  2726. CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_);
  2727. return 0;
  2728. }
  2729. #else
  2730. static int
  2731. setup_openssl_threading(void)
  2732. {
  2733. return 0;
  2734. }
  2735. #endif
  2736. /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
  2737. */
  2738. int
  2739. crypto_global_cleanup(void)
  2740. {
  2741. EVP_cleanup();
  2742. ERR_remove_state(0);
  2743. ERR_free_strings();
  2744. if (dh_param_p)
  2745. BN_free(dh_param_p);
  2746. if (dh_param_p_tls)
  2747. BN_free(dh_param_p_tls);
  2748. if (dh_param_g)
  2749. BN_free(dh_param_g);
  2750. #ifndef DISABLE_ENGINES
  2751. ENGINE_cleanup();
  2752. #endif
  2753. CONF_modules_unload(1);
  2754. CRYPTO_cleanup_all_ex_data();
  2755. #ifdef TOR_IS_MULTITHREADED
  2756. if (n_openssl_mutexes_) {
  2757. int n = n_openssl_mutexes_;
  2758. tor_mutex_t **ms = openssl_mutexes_;
  2759. int i;
  2760. openssl_mutexes_ = NULL;
  2761. n_openssl_mutexes_ = 0;
  2762. for (i=0;i<n;++i) {
  2763. tor_mutex_free(ms[i]);
  2764. }
  2765. tor_free(ms);
  2766. }
  2767. #endif
  2768. tor_free(crypto_openssl_version_str);
  2769. return 0;
  2770. }
  2771. /** @} */