crypto.c 75 KB

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