crypto.c 75 KB

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