crypto.c 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368
  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-2017, 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 and
  10. * other places.
  11. **/
  12. #include "orconfig.h"
  13. #ifdef _WIN32
  14. #include <winsock2.h>
  15. #include <windows.h>
  16. #include <wincrypt.h>
  17. /* Windows defines this; so does OpenSSL 0.9.8h and later. We don't actually
  18. * use either definition. */
  19. #undef OCSP_RESPONSE
  20. #endif /* defined(_WIN32) */
  21. #define CRYPTO_PRIVATE
  22. #include "crypto.h"
  23. #include "compat_openssl.h"
  24. #include "crypto_curve25519.h"
  25. #include "crypto_ed25519.h"
  26. #include "crypto_format.h"
  27. #if __GNUC__ && GCC_VERSION >= 402
  28. #if GCC_VERSION >= 406
  29. #pragma GCC diagnostic pop
  30. #else
  31. #pragma GCC diagnostic warning "-Wredundant-decls"
  32. #endif
  33. #endif /* __GNUC__ && GCC_VERSION >= 402 */
  34. #ifdef HAVE_CTYPE_H
  35. #include <ctype.h>
  36. #endif
  37. #ifdef HAVE_UNISTD_H
  38. #include <unistd.h>
  39. #endif
  40. #ifdef HAVE_FCNTL_H
  41. #include <fcntl.h>
  42. #endif
  43. #ifdef HAVE_SYS_FCNTL_H
  44. #include <sys/fcntl.h>
  45. #endif
  46. #ifdef HAVE_SYS_SYSCALL_H
  47. #include <sys/syscall.h>
  48. #endif
  49. #ifdef HAVE_SYS_RANDOM_H
  50. #include <sys/random.h>
  51. #endif
  52. #include "torlog.h"
  53. #include "torint.h"
  54. #include "aes.h"
  55. #include "util.h"
  56. #include "container.h"
  57. #include "compat.h"
  58. #include "sandbox.h"
  59. #include "util_format.h"
  60. #include "keccak-tiny/keccak-tiny.h"
  61. /** Longest recognized */
  62. #define MAX_DNS_LABEL_SIZE 63
  63. /** Largest strong entropy request */
  64. #define MAX_STRONGEST_RAND_SIZE 256
  65. /** A public key, or a public/private key-pair. */
  66. struct crypto_pk_t
  67. {
  68. int refs; /**< reference count, so we don't have to copy keys */
  69. RSA *key; /**< The key itself */
  70. };
  71. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  72. * while we're waiting for the second.*/
  73. struct crypto_dh_t {
  74. DH *dh; /**< The openssl DH object */
  75. };
  76. static int tor_check_dh_key(int severity, const BIGNUM *bn);
  77. /** Return the number of bytes added by padding method <b>padding</b>.
  78. */
  79. static inline int
  80. crypto_get_rsa_padding_overhead(int padding)
  81. {
  82. switch (padding)
  83. {
  84. case RSA_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
  85. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  86. }
  87. }
  88. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  89. */
  90. static inline int
  91. crypto_get_rsa_padding(int padding)
  92. {
  93. switch (padding)
  94. {
  95. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  96. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  97. }
  98. }
  99. /** Boolean: has OpenSSL's crypto been initialized? */
  100. static int crypto_early_initialized_ = 0;
  101. /** Boolean: has OpenSSL's crypto been initialized? */
  102. static int crypto_global_initialized_ = 0;
  103. /** Log all pending crypto errors at level <b>severity</b>. Use
  104. * <b>doing</b> to describe our current activities.
  105. */
  106. static void
  107. crypto_log_errors(int severity, const char *doing)
  108. {
  109. unsigned long err;
  110. const char *msg, *lib, *func;
  111. while ((err = ERR_get_error()) != 0) {
  112. msg = (const char*)ERR_reason_error_string(err);
  113. lib = (const char*)ERR_lib_error_string(err);
  114. func = (const char*)ERR_func_error_string(err);
  115. if (!msg) msg = "(null)";
  116. if (!lib) lib = "(null)";
  117. if (!func) func = "(null)";
  118. if (BUG(!doing)) doing = "(null)";
  119. tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  120. doing, msg, lib, func);
  121. }
  122. }
  123. #ifndef DISABLE_ENGINES
  124. /** Log any OpenSSL engines we're using at NOTICE. */
  125. static void
  126. log_engine(const char *fn, ENGINE *e)
  127. {
  128. if (e) {
  129. const char *name, *id;
  130. name = ENGINE_get_name(e);
  131. id = ENGINE_get_id(e);
  132. log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
  133. fn, name?name:"?", id?id:"?");
  134. } else {
  135. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  136. }
  137. }
  138. #endif /* !defined(DISABLE_ENGINES) */
  139. #ifndef DISABLE_ENGINES
  140. /** Try to load an engine in a shared library via fully qualified path.
  141. */
  142. static ENGINE *
  143. try_load_engine(const char *path, const char *engine)
  144. {
  145. ENGINE *e = ENGINE_by_id("dynamic");
  146. if (e) {
  147. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  148. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  149. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  150. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  151. ENGINE_free(e);
  152. e = NULL;
  153. }
  154. }
  155. return e;
  156. }
  157. #endif /* !defined(DISABLE_ENGINES) */
  158. /** Make sure that openssl is using its default PRNG. Return 1 if we had to
  159. * adjust it; 0 otherwise. */
  160. STATIC int
  161. crypto_force_rand_ssleay(void)
  162. {
  163. RAND_METHOD *default_method;
  164. default_method = RAND_OpenSSL();
  165. if (RAND_get_rand_method() != default_method) {
  166. log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
  167. "a replacement the OpenSSL RNG. Resetting it to the default "
  168. "implementation.");
  169. RAND_set_rand_method(default_method);
  170. return 1;
  171. }
  172. return 0;
  173. }
  174. /** Set up the siphash key if we haven't already done so. */
  175. int
  176. crypto_init_siphash_key(void)
  177. {
  178. static int have_seeded_siphash = 0;
  179. struct sipkey key;
  180. if (have_seeded_siphash)
  181. return 0;
  182. crypto_rand((char*) &key, sizeof(key));
  183. siphash_set_global_key(&key);
  184. have_seeded_siphash = 1;
  185. return 0;
  186. }
  187. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  188. */
  189. int
  190. crypto_early_init(void)
  191. {
  192. if (!crypto_early_initialized_) {
  193. crypto_early_initialized_ = 1;
  194. ERR_load_crypto_strings();
  195. OpenSSL_add_all_algorithms();
  196. setup_openssl_threading();
  197. unsigned long version_num = OpenSSL_version_num();
  198. const char *version_str = OpenSSL_version(OPENSSL_VERSION);
  199. if (version_num == OPENSSL_VERSION_NUMBER &&
  200. !strcmp(version_str, OPENSSL_VERSION_TEXT)) {
  201. log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
  202. "(%lx: %s).", version_num, version_str);
  203. } else {
  204. log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
  205. "version we're running with. If you get weird crashes, that "
  206. "might be why. (Compiled with %lx: %s; running with %lx: %s).",
  207. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  208. version_num, version_str);
  209. }
  210. crypto_force_rand_ssleay();
  211. if (crypto_seed_rng() < 0)
  212. return -1;
  213. if (crypto_init_siphash_key() < 0)
  214. return -1;
  215. curve25519_init();
  216. ed25519_init();
  217. }
  218. return 0;
  219. }
  220. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  221. */
  222. int
  223. crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
  224. {
  225. if (!crypto_global_initialized_) {
  226. if (crypto_early_init() < 0)
  227. return -1;
  228. crypto_global_initialized_ = 1;
  229. if (useAccel > 0) {
  230. #ifdef DISABLE_ENGINES
  231. (void)accelName;
  232. (void)accelDir;
  233. log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
  234. #else
  235. ENGINE *e = NULL;
  236. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  237. ENGINE_load_builtin_engines();
  238. ENGINE_register_all_complete();
  239. if (accelName) {
  240. if (accelDir) {
  241. log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
  242. " via path \"%s\".", accelName, accelDir);
  243. e = try_load_engine(accelName, accelDir);
  244. } else {
  245. log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
  246. " acceleration support.", accelName);
  247. e = ENGINE_by_id(accelName);
  248. }
  249. if (!e) {
  250. log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
  251. accelName);
  252. } else {
  253. log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
  254. accelName);
  255. }
  256. }
  257. if (e) {
  258. log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
  259. " setting default ciphers.");
  260. ENGINE_set_default(e, ENGINE_METHOD_ALL);
  261. }
  262. /* Log, if available, the intersection of the set of algorithms
  263. used by Tor and the set of algorithms available in the engine */
  264. log_engine("RSA", ENGINE_get_default_RSA());
  265. log_engine("DH", ENGINE_get_default_DH());
  266. #ifdef OPENSSL_1_1_API
  267. log_engine("EC", ENGINE_get_default_EC());
  268. #else
  269. log_engine("ECDH", ENGINE_get_default_ECDH());
  270. log_engine("ECDSA", ENGINE_get_default_ECDSA());
  271. #endif /* defined(OPENSSL_1_1_API) */
  272. log_engine("RAND", ENGINE_get_default_RAND());
  273. log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
  274. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  275. log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
  276. log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  277. log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
  278. #ifdef NID_aes_128_ctr
  279. log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
  280. #endif
  281. #ifdef NID_aes_128_gcm
  282. log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
  283. #endif
  284. log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
  285. #ifdef NID_aes_256_gcm
  286. log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
  287. #endif
  288. #endif /* defined(DISABLE_ENGINES) */
  289. } else {
  290. log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
  291. }
  292. if (crypto_force_rand_ssleay()) {
  293. if (crypto_seed_rng() < 0)
  294. return -1;
  295. }
  296. evaluate_evp_for_aes(-1);
  297. evaluate_ctr_for_aes();
  298. }
  299. return 0;
  300. }
  301. /** Free crypto resources held by this thread. */
  302. void
  303. crypto_thread_cleanup(void)
  304. {
  305. #ifndef NEW_THREAD_API
  306. ERR_remove_thread_state(NULL);
  307. #endif
  308. }
  309. /** used internally: quicly validate a crypto_pk_t object as a private key.
  310. * Return 1 iff the public key is valid, 0 if obviously invalid.
  311. */
  312. static int
  313. crypto_pk_private_ok(const crypto_pk_t *k)
  314. {
  315. #ifdef OPENSSL_1_1_API
  316. if (!k || !k->key)
  317. return 0;
  318. const BIGNUM *p, *q;
  319. RSA_get0_factors(k->key, &p, &q);
  320. return p != NULL; /* XXX/yawning: Should we check q? */
  321. #else /* !(defined(OPENSSL_1_1_API)) */
  322. return k && k->key && k->key->p;
  323. #endif /* defined(OPENSSL_1_1_API) */
  324. }
  325. /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
  326. crypto_pk_t *
  327. crypto_new_pk_from_rsa_(RSA *rsa)
  328. {
  329. crypto_pk_t *env;
  330. tor_assert(rsa);
  331. env = tor_malloc(sizeof(crypto_pk_t));
  332. env->refs = 1;
  333. env->key = rsa;
  334. return env;
  335. }
  336. /** Helper, used by tor-gencert.c. Return the RSA from a
  337. * crypto_pk_t. */
  338. RSA *
  339. crypto_pk_get_rsa_(crypto_pk_t *env)
  340. {
  341. return env->key;
  342. }
  343. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
  344. * private is set, include the private-key portion of the key. Return a valid
  345. * pointer on success, and NULL on failure. */
  346. MOCK_IMPL(EVP_PKEY *,
  347. crypto_pk_get_evp_pkey_,(crypto_pk_t *env, int private))
  348. {
  349. RSA *key = NULL;
  350. EVP_PKEY *pkey = NULL;
  351. tor_assert(env->key);
  352. if (private) {
  353. if (!(key = RSAPrivateKey_dup(env->key)))
  354. goto error;
  355. } else {
  356. if (!(key = RSAPublicKey_dup(env->key)))
  357. goto error;
  358. }
  359. if (!(pkey = EVP_PKEY_new()))
  360. goto error;
  361. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  362. goto error;
  363. return pkey;
  364. error:
  365. if (pkey)
  366. EVP_PKEY_free(pkey);
  367. if (key)
  368. RSA_free(key);
  369. return NULL;
  370. }
  371. /** Used by tortls.c: Get the DH* from a crypto_dh_t.
  372. */
  373. DH *
  374. crypto_dh_get_dh_(crypto_dh_t *dh)
  375. {
  376. return dh->dh;
  377. }
  378. /** Allocate and return storage for a public key. The key itself will not yet
  379. * be set.
  380. */
  381. MOCK_IMPL(crypto_pk_t *,
  382. crypto_pk_new,(void))
  383. {
  384. RSA *rsa;
  385. rsa = RSA_new();
  386. tor_assert(rsa);
  387. return crypto_new_pk_from_rsa_(rsa);
  388. }
  389. /** Release a reference to an asymmetric key; when all the references
  390. * are released, free the key.
  391. */
  392. void
  393. crypto_pk_free(crypto_pk_t *env)
  394. {
  395. if (!env)
  396. return;
  397. if (--env->refs > 0)
  398. return;
  399. tor_assert(env->refs == 0);
  400. if (env->key)
  401. RSA_free(env->key);
  402. tor_free(env);
  403. }
  404. /** Allocate and return a new symmetric cipher using the provided key and iv.
  405. * The key is <b>bits</b> bits long; the IV is CIPHER_IV_LEN bytes. Both
  406. * must be provided. Key length must be 128, 192, or 256 */
  407. crypto_cipher_t *
  408. crypto_cipher_new_with_iv_and_bits(const uint8_t *key,
  409. const uint8_t *iv,
  410. int bits)
  411. {
  412. tor_assert(key);
  413. tor_assert(iv);
  414. return aes_new_cipher((const uint8_t*)key, (const uint8_t*)iv, bits);
  415. }
  416. /** Allocate and return a new symmetric cipher using the provided key and iv.
  417. * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. Both
  418. * must be provided.
  419. */
  420. crypto_cipher_t *
  421. crypto_cipher_new_with_iv(const char *key, const char *iv)
  422. {
  423. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)iv,
  424. 128);
  425. }
  426. /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
  427. * zero bytes and key length <b>bits</b>. Key length must be 128, 192, or
  428. * 256. */
  429. crypto_cipher_t *
  430. crypto_cipher_new_with_bits(const char *key, int bits)
  431. {
  432. char zeroiv[CIPHER_IV_LEN];
  433. memset(zeroiv, 0, sizeof(zeroiv));
  434. return crypto_cipher_new_with_iv_and_bits((uint8_t*)key, (uint8_t*)zeroiv,
  435. bits);
  436. }
  437. /** Return a new crypto_cipher_t with the provided <b>key</b> (of
  438. * CIPHER_KEY_LEN bytes) and an IV of all zero bytes. */
  439. crypto_cipher_t *
  440. crypto_cipher_new(const char *key)
  441. {
  442. return crypto_cipher_new_with_bits(key, 128);
  443. }
  444. /** Free a symmetric cipher.
  445. */
  446. void
  447. crypto_cipher_free(crypto_cipher_t *env)
  448. {
  449. if (!env)
  450. return;
  451. aes_cipher_free(env);
  452. }
  453. /* public key crypto */
  454. /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
  455. * Return 0 on success, -1 on failure.
  456. */
  457. MOCK_IMPL(int,
  458. crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
  459. {
  460. tor_assert(env);
  461. if (env->key) {
  462. RSA_free(env->key);
  463. env->key = NULL;
  464. }
  465. {
  466. BIGNUM *e = BN_new();
  467. RSA *r = NULL;
  468. if (!e)
  469. goto done;
  470. if (! BN_set_word(e, 65537))
  471. goto done;
  472. r = RSA_new();
  473. if (!r)
  474. goto done;
  475. if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
  476. goto done;
  477. env->key = r;
  478. r = NULL;
  479. done:
  480. if (e)
  481. BN_clear_free(e);
  482. if (r)
  483. RSA_free(r);
  484. }
  485. if (!env->key) {
  486. crypto_log_errors(LOG_WARN, "generating RSA key");
  487. return -1;
  488. }
  489. return 0;
  490. }
  491. /** A PEM callback that always reports a failure to get a password */
  492. static int
  493. pem_no_password_cb(char *buf, int size, int rwflag, void *u)
  494. {
  495. (void)buf;
  496. (void)size;
  497. (void)rwflag;
  498. (void)u;
  499. return 0;
  500. }
  501. /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
  502. * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
  503. * the string is nul-terminated.
  504. */
  505. int
  506. crypto_pk_read_private_key_from_string(crypto_pk_t *env,
  507. const char *s, ssize_t len)
  508. {
  509. BIO *b;
  510. tor_assert(env);
  511. tor_assert(s);
  512. tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
  513. /* Create a read-only memory BIO, backed by the string 's' */
  514. b = BIO_new_mem_buf((char*)s, (int)len);
  515. if (!b)
  516. return -1;
  517. if (env->key)
  518. RSA_free(env->key);
  519. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,pem_no_password_cb,NULL);
  520. BIO_free(b);
  521. if (!env->key) {
  522. crypto_log_errors(LOG_WARN, "Error parsing private key");
  523. return -1;
  524. }
  525. return 0;
  526. }
  527. /** Read a PEM-encoded private key from the file named by
  528. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  529. */
  530. int
  531. crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
  532. const char *keyfile)
  533. {
  534. char *contents;
  535. int r;
  536. /* Read the file into a string. */
  537. contents = read_file_to_str(keyfile, 0, NULL);
  538. if (!contents) {
  539. log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
  540. return -1;
  541. }
  542. /* Try to parse it. */
  543. r = crypto_pk_read_private_key_from_string(env, contents, -1);
  544. memwipe(contents, 0, strlen(contents));
  545. tor_free(contents);
  546. if (r)
  547. return -1; /* read_private_key_from_string already warned, so we don't.*/
  548. /* Make sure it's valid. */
  549. if (crypto_pk_check_key(env) <= 0)
  550. return -1;
  551. return 0;
  552. }
  553. /** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
  554. * success, -1 on failure. */
  555. static int
  556. crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
  557. size_t *len, int is_public)
  558. {
  559. BUF_MEM *buf;
  560. BIO *b;
  561. int r;
  562. tor_assert(env);
  563. tor_assert(env->key);
  564. tor_assert(dest);
  565. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  566. if (!b)
  567. return -1;
  568. /* Now you can treat b as if it were a file. Just use the
  569. * PEM_*_bio_* functions instead of the non-bio variants.
  570. */
  571. if (is_public)
  572. r = PEM_write_bio_RSAPublicKey(b, env->key);
  573. else
  574. r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
  575. if (!r) {
  576. crypto_log_errors(LOG_WARN, "writing RSA key to string");
  577. BIO_free(b);
  578. return -1;
  579. }
  580. BIO_get_mem_ptr(b, &buf);
  581. *dest = tor_malloc(buf->length+1);
  582. memcpy(*dest, buf->data, buf->length);
  583. (*dest)[buf->length] = 0; /* nul terminate it */
  584. *len = buf->length;
  585. BIO_free(b);
  586. return 0;
  587. }
  588. /** PEM-encode the public key portion of <b>env</b> and write it to a
  589. * newly allocated string. On success, set *<b>dest</b> to the new
  590. * string, *<b>len</b> to the string's length, and return 0. On
  591. * failure, return -1.
  592. */
  593. int
  594. crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
  595. size_t *len)
  596. {
  597. return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
  598. }
  599. /** PEM-encode the private key portion of <b>env</b> and write it to a
  600. * newly allocated string. On success, set *<b>dest</b> to the new
  601. * string, *<b>len</b> to the string's length, and return 0. On
  602. * failure, return -1.
  603. */
  604. int
  605. crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
  606. size_t *len)
  607. {
  608. return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
  609. }
  610. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  611. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  612. * failure.
  613. */
  614. int
  615. crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
  616. size_t len)
  617. {
  618. BIO *b;
  619. tor_assert(env);
  620. tor_assert(src);
  621. tor_assert(len<INT_MAX);
  622. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  623. if (!b)
  624. return -1;
  625. BIO_write(b, src, (int)len);
  626. if (env->key)
  627. RSA_free(env->key);
  628. env->key = PEM_read_bio_RSAPublicKey(b, NULL, pem_no_password_cb, NULL);
  629. BIO_free(b);
  630. if (!env->key) {
  631. crypto_log_errors(LOG_WARN, "reading public key from string");
  632. return -1;
  633. }
  634. return 0;
  635. }
  636. /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
  637. * PEM-encoded. Return 0 on success, -1 on failure.
  638. */
  639. int
  640. crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
  641. const char *fname)
  642. {
  643. BIO *bio;
  644. char *cp;
  645. long len;
  646. char *s;
  647. int r;
  648. tor_assert(crypto_pk_private_ok(env));
  649. if (!(bio = BIO_new(BIO_s_mem())))
  650. return -1;
  651. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  652. == 0) {
  653. crypto_log_errors(LOG_WARN, "writing private key");
  654. BIO_free(bio);
  655. return -1;
  656. }
  657. len = BIO_get_mem_data(bio, &cp);
  658. tor_assert(len >= 0);
  659. s = tor_malloc(len+1);
  660. memcpy(s, cp, len);
  661. s[len]='\0';
  662. r = write_str_to_file(fname, s, 0);
  663. BIO_free(bio);
  664. memwipe(s, 0, strlen(s));
  665. tor_free(s);
  666. return r;
  667. }
  668. /** Return true iff <b>env</b> has a valid key.
  669. */
  670. int
  671. crypto_pk_check_key(crypto_pk_t *env)
  672. {
  673. int r;
  674. tor_assert(env);
  675. r = RSA_check_key(env->key);
  676. if (r <= 0)
  677. crypto_log_errors(LOG_WARN,"checking RSA key");
  678. return r;
  679. }
  680. /** Return true iff <b>key</b> contains the private-key portion of the RSA
  681. * key. */
  682. int
  683. crypto_pk_key_is_private(const crypto_pk_t *key)
  684. {
  685. tor_assert(key);
  686. return crypto_pk_private_ok(key);
  687. }
  688. /** Return true iff <b>env</b> contains a public key whose public exponent
  689. * equals 65537.
  690. */
  691. int
  692. crypto_pk_public_exponent_ok(crypto_pk_t *env)
  693. {
  694. tor_assert(env);
  695. tor_assert(env->key);
  696. const BIGNUM *e;
  697. #ifdef OPENSSL_1_1_API
  698. const BIGNUM *n, *d;
  699. RSA_get0_key(env->key, &n, &e, &d);
  700. #else
  701. e = env->key->e;
  702. #endif /* defined(OPENSSL_1_1_API) */
  703. return BN_is_word(e, 65537);
  704. }
  705. /** Compare the public-key components of a and b. Return less than 0
  706. * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
  707. * considered to be less than all non-NULL keys, and equal to itself.
  708. *
  709. * Note that this may leak information about the keys through timing.
  710. */
  711. int
  712. crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  713. {
  714. int result;
  715. char a_is_non_null = (a != NULL) && (a->key != NULL);
  716. char b_is_non_null = (b != NULL) && (b->key != NULL);
  717. char an_argument_is_null = !a_is_non_null | !b_is_non_null;
  718. result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
  719. if (an_argument_is_null)
  720. return result;
  721. const BIGNUM *a_n, *a_e;
  722. const BIGNUM *b_n, *b_e;
  723. #ifdef OPENSSL_1_1_API
  724. const BIGNUM *a_d, *b_d;
  725. RSA_get0_key(a->key, &a_n, &a_e, &a_d);
  726. RSA_get0_key(b->key, &b_n, &b_e, &b_d);
  727. #else
  728. a_n = a->key->n;
  729. a_e = a->key->e;
  730. b_n = b->key->n;
  731. b_e = b->key->e;
  732. #endif /* defined(OPENSSL_1_1_API) */
  733. tor_assert(a_n != NULL && a_e != NULL);
  734. tor_assert(b_n != NULL && b_e != NULL);
  735. result = BN_cmp(a_n, b_n);
  736. if (result)
  737. return result;
  738. return BN_cmp(a_e, b_e);
  739. }
  740. /** Compare the public-key components of a and b. Return non-zero iff
  741. * a==b. A NULL key is considered to be distinct from all non-NULL
  742. * keys, and equal to itself.
  743. *
  744. * Note that this may leak information about the keys through timing.
  745. */
  746. int
  747. crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  748. {
  749. return (crypto_pk_cmp_keys(a, b) == 0);
  750. }
  751. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  752. size_t
  753. crypto_pk_keysize(const crypto_pk_t *env)
  754. {
  755. tor_assert(env);
  756. tor_assert(env->key);
  757. return (size_t) RSA_size((RSA*)env->key);
  758. }
  759. /** Return the size of the public key modulus of <b>env</b>, in bits. */
  760. int
  761. crypto_pk_num_bits(crypto_pk_t *env)
  762. {
  763. tor_assert(env);
  764. tor_assert(env->key);
  765. #ifdef OPENSSL_1_1_API
  766. /* It's so stupid that there's no other way to check that n is valid
  767. * before calling RSA_bits().
  768. */
  769. const BIGNUM *n, *e, *d;
  770. RSA_get0_key(env->key, &n, &e, &d);
  771. tor_assert(n != NULL);
  772. return RSA_bits(env->key);
  773. #else /* !(defined(OPENSSL_1_1_API)) */
  774. tor_assert(env->key->n);
  775. return BN_num_bits(env->key->n);
  776. #endif /* defined(OPENSSL_1_1_API) */
  777. }
  778. /** Increase the reference count of <b>env</b>, and return it.
  779. */
  780. crypto_pk_t *
  781. crypto_pk_dup_key(crypto_pk_t *env)
  782. {
  783. tor_assert(env);
  784. tor_assert(env->key);
  785. env->refs++;
  786. return env;
  787. }
  788. #ifdef TOR_UNIT_TESTS
  789. /** For testing: replace dest with src. (Dest must have a refcount
  790. * of 1) */
  791. void
  792. crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src)
  793. {
  794. tor_assert(dest);
  795. tor_assert(dest->refs == 1);
  796. tor_assert(src);
  797. RSA_free(dest->key);
  798. dest->key = RSAPrivateKey_dup(src->key);
  799. }
  800. #endif /* defined(TOR_UNIT_TESTS) */
  801. /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
  802. * Returns NULL on failure. */
  803. crypto_pk_t *
  804. crypto_pk_copy_full(crypto_pk_t *env)
  805. {
  806. RSA *new_key;
  807. int privatekey = 0;
  808. tor_assert(env);
  809. tor_assert(env->key);
  810. if (crypto_pk_private_ok(env)) {
  811. new_key = RSAPrivateKey_dup(env->key);
  812. privatekey = 1;
  813. } else {
  814. new_key = RSAPublicKey_dup(env->key);
  815. }
  816. if (!new_key) {
  817. /* LCOV_EXCL_START
  818. *
  819. * We can't cause RSA*Key_dup() to fail, so we can't really test this.
  820. */
  821. log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
  822. privatekey?"private":"public");
  823. crypto_log_errors(LOG_ERR,
  824. privatekey ? "Duplicating a private key" :
  825. "Duplicating a public key");
  826. tor_fragile_assert();
  827. return NULL;
  828. /* LCOV_EXCL_STOP */
  829. }
  830. return crypto_new_pk_from_rsa_(new_key);
  831. }
  832. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public 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_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
  842. const char *from, size_t fromlen, int padding)
  843. {
  844. int r;
  845. tor_assert(env);
  846. tor_assert(from);
  847. tor_assert(to);
  848. tor_assert(fromlen<INT_MAX);
  849. tor_assert(tolen >= crypto_pk_keysize(env));
  850. r = RSA_public_encrypt((int)fromlen,
  851. (unsigned char*)from, (unsigned char*)to,
  852. env->key, crypto_get_rsa_padding(padding));
  853. if (r<0) {
  854. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  855. return -1;
  856. }
  857. return r;
  858. }
  859. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  860. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  861. * write the result to <b>to</b>, and return the number of bytes
  862. * written. On failure, return -1.
  863. *
  864. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  865. * at least the length of the modulus of <b>env</b>.
  866. */
  867. int
  868. crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
  869. size_t tolen,
  870. const char *from, size_t fromlen,
  871. int padding, int warnOnFailure)
  872. {
  873. int r;
  874. tor_assert(env);
  875. tor_assert(from);
  876. tor_assert(to);
  877. tor_assert(env->key);
  878. tor_assert(fromlen<INT_MAX);
  879. tor_assert(tolen >= crypto_pk_keysize(env));
  880. if (!crypto_pk_key_is_private(env))
  881. /* Not a private key */
  882. return -1;
  883. r = RSA_private_decrypt((int)fromlen,
  884. (unsigned char*)from, (unsigned char*)to,
  885. env->key, crypto_get_rsa_padding(padding));
  886. if (r<0) {
  887. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  888. "performing RSA decryption");
  889. return -1;
  890. }
  891. return r;
  892. }
  893. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  894. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  895. * signed data to <b>to</b>, and return the number of bytes written.
  896. * On failure, return -1.
  897. *
  898. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  899. * at least the length of the modulus of <b>env</b>.
  900. */
  901. MOCK_IMPL(int,
  902. crypto_pk_public_checksig,(const crypto_pk_t *env, char *to,
  903. size_t tolen,
  904. const char *from, size_t fromlen))
  905. {
  906. int r;
  907. tor_assert(env);
  908. tor_assert(from);
  909. tor_assert(to);
  910. tor_assert(fromlen < INT_MAX);
  911. tor_assert(tolen >= crypto_pk_keysize(env));
  912. r = RSA_public_decrypt((int)fromlen,
  913. (unsigned char*)from, (unsigned char*)to,
  914. env->key, RSA_PKCS1_PADDING);
  915. if (r<0) {
  916. crypto_log_errors(LOG_INFO, "checking RSA signature");
  917. return -1;
  918. }
  919. return r;
  920. }
  921. /** Check a siglen-byte long signature at <b>sig</b> against
  922. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  923. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  924. * SHA1(data). Else return -1.
  925. */
  926. MOCK_IMPL(int,
  927. crypto_pk_public_checksig_digest,(crypto_pk_t *env, const char *data,
  928. size_t datalen, const char *sig,
  929. size_t siglen))
  930. {
  931. char digest[DIGEST_LEN];
  932. char *buf;
  933. size_t buflen;
  934. int r;
  935. tor_assert(env);
  936. tor_assert(data);
  937. tor_assert(sig);
  938. tor_assert(datalen < SIZE_T_CEILING);
  939. tor_assert(siglen < SIZE_T_CEILING);
  940. if (crypto_digest(digest,data,datalen)<0) {
  941. log_warn(LD_BUG, "couldn't compute digest");
  942. return -1;
  943. }
  944. buflen = crypto_pk_keysize(env);
  945. buf = tor_malloc(buflen);
  946. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  947. if (r != DIGEST_LEN) {
  948. log_warn(LD_CRYPTO, "Invalid signature");
  949. tor_free(buf);
  950. return -1;
  951. }
  952. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  953. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  954. tor_free(buf);
  955. return -1;
  956. }
  957. tor_free(buf);
  958. return 0;
  959. }
  960. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  961. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  962. * <b>to</b>, and return the number of bytes written. On failure, return
  963. * -1.
  964. *
  965. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  966. * at least the length of the modulus of <b>env</b>.
  967. */
  968. int
  969. crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
  970. const char *from, size_t fromlen)
  971. {
  972. int r;
  973. tor_assert(env);
  974. tor_assert(from);
  975. tor_assert(to);
  976. tor_assert(fromlen < INT_MAX);
  977. tor_assert(tolen >= crypto_pk_keysize(env));
  978. if (!crypto_pk_key_is_private(env))
  979. /* Not a private key */
  980. return -1;
  981. r = RSA_private_encrypt((int)fromlen,
  982. (unsigned char*)from, (unsigned char*)to,
  983. (RSA*)env->key, RSA_PKCS1_PADDING);
  984. if (r<0) {
  985. crypto_log_errors(LOG_WARN, "generating RSA signature");
  986. return -1;
  987. }
  988. return r;
  989. }
  990. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  991. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  992. * store it in <b>to</b>. Return the number of bytes written on
  993. * success, and -1 on failure.
  994. *
  995. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  996. * at least the length of the modulus of <b>env</b>.
  997. */
  998. int
  999. crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
  1000. const char *from, size_t fromlen)
  1001. {
  1002. int r;
  1003. char digest[DIGEST_LEN];
  1004. if (crypto_digest(digest,from,fromlen)<0)
  1005. return -1;
  1006. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  1007. memwipe(digest, 0, sizeof(digest));
  1008. return r;
  1009. }
  1010. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  1011. * bytes of data from <b>from</b>, with padding type 'padding',
  1012. * storing the results on <b>to</b>.
  1013. *
  1014. * Returns the number of bytes written on success, -1 on failure.
  1015. *
  1016. * The encrypted data consists of:
  1017. * - The source data, padded and encrypted with the public key, if the
  1018. * padded source data is no longer than the public key, and <b>force</b>
  1019. * is false, OR
  1020. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  1021. * padded and encrypted with the public key; followed by the rest of
  1022. * the source data encrypted in AES-CTR mode with the symmetric key.
  1023. *
  1024. * NOTE that this format does not authenticate the symmetrically encrypted
  1025. * part of the data, and SHOULD NOT BE USED for new protocols.
  1026. */
  1027. int
  1028. crypto_pk_obsolete_public_hybrid_encrypt(crypto_pk_t *env,
  1029. char *to, size_t tolen,
  1030. const char *from,
  1031. size_t fromlen,
  1032. int padding, int force)
  1033. {
  1034. int overhead, outlen, r;
  1035. size_t pkeylen, symlen;
  1036. crypto_cipher_t *cipher = NULL;
  1037. char *buf = NULL;
  1038. tor_assert(env);
  1039. tor_assert(from);
  1040. tor_assert(to);
  1041. tor_assert(fromlen < SIZE_T_CEILING);
  1042. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  1043. pkeylen = crypto_pk_keysize(env);
  1044. if (!force && fromlen+overhead <= pkeylen) {
  1045. /* It all fits in a single encrypt. */
  1046. return crypto_pk_public_encrypt(env,to,
  1047. tolen,
  1048. from,fromlen,padding);
  1049. }
  1050. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  1051. tor_assert(tolen >= pkeylen);
  1052. char key[CIPHER_KEY_LEN];
  1053. crypto_rand(key, sizeof(key)); /* generate a new key. */
  1054. cipher = crypto_cipher_new(key);
  1055. buf = tor_malloc(pkeylen+1);
  1056. memcpy(buf, key, CIPHER_KEY_LEN);
  1057. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  1058. /* Length of symmetrically encrypted data. */
  1059. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  1060. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  1061. if (outlen!=(int)pkeylen) {
  1062. goto err;
  1063. }
  1064. r = crypto_cipher_encrypt(cipher, to+outlen,
  1065. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  1066. if (r<0) goto err;
  1067. memwipe(buf, 0, pkeylen);
  1068. memwipe(key, 0, sizeof(key));
  1069. tor_free(buf);
  1070. crypto_cipher_free(cipher);
  1071. tor_assert(outlen+symlen < INT_MAX);
  1072. return (int)(outlen + symlen);
  1073. err:
  1074. memwipe(buf, 0, pkeylen);
  1075. memwipe(key, 0, sizeof(key));
  1076. tor_free(buf);
  1077. crypto_cipher_free(cipher);
  1078. return -1;
  1079. }
  1080. /** Invert crypto_pk_obsolete_public_hybrid_encrypt. Returns the number of
  1081. * bytes written on success, -1 on failure.
  1082. *
  1083. * NOTE that this format does not authenticate the symmetrically encrypted
  1084. * part of the data, and SHOULD NOT BE USED for new protocols.
  1085. */
  1086. int
  1087. crypto_pk_obsolete_private_hybrid_decrypt(crypto_pk_t *env,
  1088. char *to,
  1089. size_t tolen,
  1090. const char *from,
  1091. size_t fromlen,
  1092. int padding, int warnOnFailure)
  1093. {
  1094. int outlen, r;
  1095. size_t pkeylen;
  1096. crypto_cipher_t *cipher = NULL;
  1097. char *buf = NULL;
  1098. tor_assert(fromlen < SIZE_T_CEILING);
  1099. pkeylen = crypto_pk_keysize(env);
  1100. if (fromlen <= pkeylen) {
  1101. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  1102. warnOnFailure);
  1103. }
  1104. buf = tor_malloc(pkeylen);
  1105. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  1106. warnOnFailure);
  1107. if (outlen<0) {
  1108. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  1109. "Error decrypting public-key data");
  1110. goto err;
  1111. }
  1112. if (outlen < CIPHER_KEY_LEN) {
  1113. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  1114. "No room for a symmetric key");
  1115. goto err;
  1116. }
  1117. cipher = crypto_cipher_new(buf);
  1118. if (!cipher) {
  1119. goto err;
  1120. }
  1121. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  1122. outlen -= CIPHER_KEY_LEN;
  1123. tor_assert(tolen - outlen >= fromlen - pkeylen);
  1124. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  1125. if (r<0)
  1126. goto err;
  1127. memwipe(buf,0,pkeylen);
  1128. tor_free(buf);
  1129. crypto_cipher_free(cipher);
  1130. tor_assert(outlen + fromlen < INT_MAX);
  1131. return (int)(outlen + (fromlen-pkeylen));
  1132. err:
  1133. memwipe(buf,0,pkeylen);
  1134. tor_free(buf);
  1135. crypto_cipher_free(cipher);
  1136. return -1;
  1137. }
  1138. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  1139. * Return -1 on error, or the number of characters used on success.
  1140. */
  1141. int
  1142. crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
  1143. {
  1144. int len;
  1145. unsigned char *buf = NULL;
  1146. len = i2d_RSAPublicKey(pk->key, &buf);
  1147. if (len < 0 || buf == NULL)
  1148. return -1;
  1149. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  1150. OPENSSL_free(buf);
  1151. return -1;
  1152. }
  1153. /* We don't encode directly into 'dest', because that would be illegal
  1154. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  1155. */
  1156. memcpy(dest,buf,len);
  1157. OPENSSL_free(buf);
  1158. return len;
  1159. }
  1160. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  1161. * success and NULL on failure.
  1162. */
  1163. crypto_pk_t *
  1164. crypto_pk_asn1_decode(const char *str, size_t len)
  1165. {
  1166. RSA *rsa;
  1167. unsigned char *buf;
  1168. const unsigned char *cp;
  1169. cp = buf = tor_malloc(len);
  1170. memcpy(buf,str,len);
  1171. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  1172. tor_free(buf);
  1173. if (!rsa) {
  1174. crypto_log_errors(LOG_WARN,"decoding public key");
  1175. return NULL;
  1176. }
  1177. return crypto_new_pk_from_rsa_(rsa);
  1178. }
  1179. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  1180. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  1181. * Return 0 on success, -1 on failure.
  1182. */
  1183. int
  1184. crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
  1185. {
  1186. unsigned char *buf = NULL;
  1187. int len;
  1188. len = i2d_RSAPublicKey((RSA*)pk->key, &buf);
  1189. if (len < 0 || buf == NULL)
  1190. return -1;
  1191. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  1192. OPENSSL_free(buf);
  1193. return -1;
  1194. }
  1195. OPENSSL_free(buf);
  1196. return 0;
  1197. }
  1198. /** Compute all digests of the DER encoding of <b>pk</b>, and store them
  1199. * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
  1200. int
  1201. crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
  1202. {
  1203. unsigned char *buf = NULL;
  1204. int len;
  1205. len = i2d_RSAPublicKey(pk->key, &buf);
  1206. if (len < 0 || buf == NULL)
  1207. return -1;
  1208. if (crypto_common_digests(digests_out, (char*)buf, len) < 0) {
  1209. OPENSSL_free(buf);
  1210. return -1;
  1211. }
  1212. OPENSSL_free(buf);
  1213. return 0;
  1214. }
  1215. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  1216. * every four characters. */
  1217. void
  1218. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  1219. {
  1220. int n = 0;
  1221. char *end = out+outlen;
  1222. tor_assert(outlen < SIZE_T_CEILING);
  1223. while (*in && out<end) {
  1224. *out++ = *in++;
  1225. if (++n == 4 && *in && out<end) {
  1226. n = 0;
  1227. *out++ = ' ';
  1228. }
  1229. }
  1230. tor_assert(out<end);
  1231. *out = '\0';
  1232. }
  1233. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  1234. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  1235. * space). Return 0 on success, -1 on failure.
  1236. *
  1237. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  1238. * of the public key, converted to hexadecimal, in upper case, with a
  1239. * space after every four digits.
  1240. *
  1241. * If <b>add_space</b> is false, omit the spaces.
  1242. */
  1243. int
  1244. crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
  1245. {
  1246. char digest[DIGEST_LEN];
  1247. char hexdigest[HEX_DIGEST_LEN+1];
  1248. if (crypto_pk_get_digest(pk, digest)) {
  1249. return -1;
  1250. }
  1251. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  1252. if (add_space) {
  1253. crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  1254. } else {
  1255. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  1256. }
  1257. return 0;
  1258. }
  1259. /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
  1260. * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
  1261. * bytes of space). Return 0 on success, -1 on failure.
  1262. *
  1263. * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
  1264. * of the ASN.1 encoding of the public key, converted to hexadecimal, in
  1265. * upper case.
  1266. */
  1267. int
  1268. crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
  1269. {
  1270. char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
  1271. if (crypto_pk_get_digest(pk, digest)) {
  1272. return -1;
  1273. }
  1274. if (crypto_digest(hashed_digest, digest, DIGEST_LEN) < 0) {
  1275. return -1;
  1276. }
  1277. base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
  1278. return 0;
  1279. }
  1280. /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
  1281. * Base64 encoding of the DER representation of the private key as a NUL
  1282. * terminated string, and return it via <b>priv_out</b>. Return 0 on
  1283. * sucess, -1 on failure.
  1284. *
  1285. * It is the caller's responsibility to sanitize and free the resulting buffer.
  1286. */
  1287. int
  1288. crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
  1289. {
  1290. unsigned char *der = NULL;
  1291. int der_len;
  1292. int ret = -1;
  1293. *priv_out = NULL;
  1294. der_len = i2d_RSAPrivateKey(pk->key, &der);
  1295. if (der_len < 0 || der == NULL)
  1296. return ret;
  1297. size_t priv_len = base64_encode_size(der_len, 0) + 1;
  1298. char *priv = tor_malloc_zero(priv_len);
  1299. if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
  1300. *priv_out = priv;
  1301. ret = 0;
  1302. } else {
  1303. tor_free(priv);
  1304. }
  1305. memwipe(der, 0, der_len);
  1306. OPENSSL_free(der);
  1307. return ret;
  1308. }
  1309. /** Given a string containing the Base64 encoded DER representation of the
  1310. * private key <b>str</b>, decode and return the result on success, or NULL
  1311. * on failure.
  1312. */
  1313. crypto_pk_t *
  1314. crypto_pk_base64_decode(const char *str, size_t len)
  1315. {
  1316. crypto_pk_t *pk = NULL;
  1317. char *der = tor_malloc_zero(len + 1);
  1318. int der_len = base64_decode(der, len, str, len);
  1319. if (der_len <= 0) {
  1320. log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
  1321. goto out;
  1322. }
  1323. const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
  1324. RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
  1325. if (!rsa) {
  1326. crypto_log_errors(LOG_WARN, "decoding private key");
  1327. goto out;
  1328. }
  1329. pk = crypto_new_pk_from_rsa_(rsa);
  1330. /* Make sure it's valid. */
  1331. if (crypto_pk_check_key(pk) <= 0) {
  1332. crypto_pk_free(pk);
  1333. pk = NULL;
  1334. goto out;
  1335. }
  1336. out:
  1337. memwipe(der, 0, len + 1);
  1338. tor_free(der);
  1339. return pk;
  1340. }
  1341. /* symmetric crypto */
  1342. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1343. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1344. * Does not check for failure.
  1345. */
  1346. int
  1347. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  1348. const char *from, size_t fromlen)
  1349. {
  1350. tor_assert(env);
  1351. tor_assert(env);
  1352. tor_assert(from);
  1353. tor_assert(fromlen);
  1354. tor_assert(to);
  1355. tor_assert(fromlen < SIZE_T_CEILING);
  1356. memcpy(to, from, fromlen);
  1357. aes_crypt_inplace(env, to, fromlen);
  1358. return 0;
  1359. }
  1360. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1361. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1362. * Does not check for failure.
  1363. */
  1364. int
  1365. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  1366. const char *from, size_t fromlen)
  1367. {
  1368. tor_assert(env);
  1369. tor_assert(from);
  1370. tor_assert(to);
  1371. tor_assert(fromlen < SIZE_T_CEILING);
  1372. memcpy(to, from, fromlen);
  1373. aes_crypt_inplace(env, to, fromlen);
  1374. return 0;
  1375. }
  1376. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  1377. * on success. Does not check for failure.
  1378. */
  1379. void
  1380. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  1381. {
  1382. tor_assert(len < SIZE_T_CEILING);
  1383. aes_crypt_inplace(env, buf, len);
  1384. }
  1385. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1386. * <b>key</b> to the buffer in <b>to</b> of length
  1387. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1388. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1389. * number of bytes written, on failure, return -1.
  1390. */
  1391. int
  1392. crypto_cipher_encrypt_with_iv(const char *key,
  1393. char *to, size_t tolen,
  1394. const char *from, size_t fromlen)
  1395. {
  1396. crypto_cipher_t *cipher;
  1397. tor_assert(from);
  1398. tor_assert(to);
  1399. tor_assert(fromlen < INT_MAX);
  1400. if (fromlen < 1)
  1401. return -1;
  1402. if (tolen < fromlen + CIPHER_IV_LEN)
  1403. return -1;
  1404. char iv[CIPHER_IV_LEN];
  1405. crypto_rand(iv, sizeof(iv));
  1406. cipher = crypto_cipher_new_with_iv(key, iv);
  1407. memcpy(to, iv, CIPHER_IV_LEN);
  1408. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1409. crypto_cipher_free(cipher);
  1410. memwipe(iv, 0, sizeof(iv));
  1411. return (int)(fromlen + CIPHER_IV_LEN);
  1412. }
  1413. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1414. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  1415. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1416. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1417. * number of bytes written, on failure, return -1.
  1418. */
  1419. int
  1420. crypto_cipher_decrypt_with_iv(const char *key,
  1421. char *to, size_t tolen,
  1422. const char *from, size_t fromlen)
  1423. {
  1424. crypto_cipher_t *cipher;
  1425. tor_assert(key);
  1426. tor_assert(from);
  1427. tor_assert(to);
  1428. tor_assert(fromlen < INT_MAX);
  1429. if (fromlen <= CIPHER_IV_LEN)
  1430. return -1;
  1431. if (tolen < fromlen - CIPHER_IV_LEN)
  1432. return -1;
  1433. cipher = crypto_cipher_new_with_iv(key, from);
  1434. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1435. crypto_cipher_free(cipher);
  1436. return (int)(fromlen - CIPHER_IV_LEN);
  1437. }
  1438. /* SHA-1 */
  1439. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  1440. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1441. * Return 0 on success, -1 on failure.
  1442. */
  1443. int
  1444. crypto_digest(char *digest, const char *m, size_t len)
  1445. {
  1446. tor_assert(m);
  1447. tor_assert(digest);
  1448. if (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL)
  1449. return -1;
  1450. return 0;
  1451. }
  1452. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1453. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  1454. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  1455. int
  1456. crypto_digest256(char *digest, const char *m, size_t len,
  1457. digest_algorithm_t algorithm)
  1458. {
  1459. tor_assert(m);
  1460. tor_assert(digest);
  1461. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1462. int ret = 0;
  1463. if (algorithm == DIGEST_SHA256)
  1464. ret = (SHA256((const uint8_t*)m,len,(uint8_t*)digest) != NULL);
  1465. else
  1466. ret = (sha3_256((uint8_t *)digest, DIGEST256_LEN,(const uint8_t *)m, len)
  1467. > -1);
  1468. if (!ret)
  1469. return -1;
  1470. return 0;
  1471. }
  1472. /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1473. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
  1474. * into <b>digest</b>. Return 0 on success, -1 on failure. */
  1475. int
  1476. crypto_digest512(char *digest, const char *m, size_t len,
  1477. digest_algorithm_t algorithm)
  1478. {
  1479. tor_assert(m);
  1480. tor_assert(digest);
  1481. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1482. int ret = 0;
  1483. if (algorithm == DIGEST_SHA512)
  1484. ret = (SHA512((const unsigned char*)m,len,(unsigned char*)digest)
  1485. != NULL);
  1486. else
  1487. ret = (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len)
  1488. > -1);
  1489. if (!ret)
  1490. return -1;
  1491. return 0;
  1492. }
  1493. /** Set the common_digests_t in <b>ds_out</b> to contain every digest on the
  1494. * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
  1495. * success, -1 on failure. */
  1496. int
  1497. crypto_common_digests(common_digests_t *ds_out, const char *m, size_t len)
  1498. {
  1499. tor_assert(ds_out);
  1500. memset(ds_out, 0, sizeof(*ds_out));
  1501. if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
  1502. return -1;
  1503. if (crypto_digest256(ds_out->d[DIGEST_SHA256], m, len, DIGEST_SHA256) < 0)
  1504. return -1;
  1505. return 0;
  1506. }
  1507. /** Return the name of an algorithm, as used in directory documents. */
  1508. const char *
  1509. crypto_digest_algorithm_get_name(digest_algorithm_t alg)
  1510. {
  1511. switch (alg) {
  1512. case DIGEST_SHA1:
  1513. return "sha1";
  1514. case DIGEST_SHA256:
  1515. return "sha256";
  1516. case DIGEST_SHA512:
  1517. return "sha512";
  1518. case DIGEST_SHA3_256:
  1519. return "sha3-256";
  1520. case DIGEST_SHA3_512:
  1521. return "sha3-512";
  1522. // LCOV_EXCL_START
  1523. default:
  1524. tor_fragile_assert();
  1525. return "??unknown_digest??";
  1526. // LCOV_EXCL_STOP
  1527. }
  1528. }
  1529. /** Given the name of a digest algorithm, return its integer value, or -1 if
  1530. * the name is not recognized. */
  1531. int
  1532. crypto_digest_algorithm_parse_name(const char *name)
  1533. {
  1534. if (!strcmp(name, "sha1"))
  1535. return DIGEST_SHA1;
  1536. else if (!strcmp(name, "sha256"))
  1537. return DIGEST_SHA256;
  1538. else if (!strcmp(name, "sha512"))
  1539. return DIGEST_SHA512;
  1540. else if (!strcmp(name, "sha3-256"))
  1541. return DIGEST_SHA3_256;
  1542. else if (!strcmp(name, "sha3-512"))
  1543. return DIGEST_SHA3_512;
  1544. else
  1545. return -1;
  1546. }
  1547. /** Given an algorithm, return the digest length in bytes. */
  1548. size_t
  1549. crypto_digest_algorithm_get_length(digest_algorithm_t alg)
  1550. {
  1551. switch (alg) {
  1552. case DIGEST_SHA1:
  1553. return DIGEST_LEN;
  1554. case DIGEST_SHA256:
  1555. return DIGEST256_LEN;
  1556. case DIGEST_SHA512:
  1557. return DIGEST512_LEN;
  1558. case DIGEST_SHA3_256:
  1559. return DIGEST256_LEN;
  1560. case DIGEST_SHA3_512:
  1561. return DIGEST512_LEN;
  1562. default:
  1563. tor_assert(0); // LCOV_EXCL_LINE
  1564. return 0; /* Unreachable */ // LCOV_EXCL_LINE
  1565. }
  1566. }
  1567. /** Intermediate information about the digest of a stream of data. */
  1568. struct crypto_digest_t {
  1569. digest_algorithm_t algorithm; /**< Which algorithm is in use? */
  1570. /** State for the digest we're using. Only one member of the
  1571. * union is usable, depending on the value of <b>algorithm</b>. Note also
  1572. * that space for other members might not even be allocated!
  1573. */
  1574. union {
  1575. SHA_CTX sha1; /**< state for SHA1 */
  1576. SHA256_CTX sha2; /**< state for SHA256 */
  1577. SHA512_CTX sha512; /**< state for SHA512 */
  1578. keccak_state sha3; /**< state for SHA3-[256,512] */
  1579. } d;
  1580. };
  1581. #ifdef TOR_UNIT_TESTS
  1582. digest_algorithm_t
  1583. crypto_digest_get_algorithm(crypto_digest_t *digest)
  1584. {
  1585. tor_assert(digest);
  1586. return digest->algorithm;
  1587. }
  1588. #endif /* defined(TOR_UNIT_TESTS) */
  1589. /**
  1590. * Return the number of bytes we need to malloc in order to get a
  1591. * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
  1592. * when we free one.
  1593. */
  1594. static size_t
  1595. crypto_digest_alloc_bytes(digest_algorithm_t alg)
  1596. {
  1597. /* Helper: returns the number of bytes in the 'f' field of 'st' */
  1598. #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
  1599. /* Gives the length of crypto_digest_t through the end of the field 'd' */
  1600. #define END_OF_FIELD(f) (offsetof(crypto_digest_t, f) + \
  1601. STRUCT_FIELD_SIZE(crypto_digest_t, f))
  1602. switch (alg) {
  1603. case DIGEST_SHA1:
  1604. return END_OF_FIELD(d.sha1);
  1605. case DIGEST_SHA256:
  1606. return END_OF_FIELD(d.sha2);
  1607. case DIGEST_SHA512:
  1608. return END_OF_FIELD(d.sha512);
  1609. case DIGEST_SHA3_256:
  1610. case DIGEST_SHA3_512:
  1611. return END_OF_FIELD(d.sha3);
  1612. default:
  1613. tor_assert(0); // LCOV_EXCL_LINE
  1614. return 0; // LCOV_EXCL_LINE
  1615. }
  1616. #undef END_OF_FIELD
  1617. #undef STRUCT_FIELD_SIZE
  1618. }
  1619. /**
  1620. * Internal function: create and return a new digest object for 'algorithm'.
  1621. * Does not typecheck the algorithm.
  1622. */
  1623. static crypto_digest_t *
  1624. crypto_digest_new_internal(digest_algorithm_t algorithm)
  1625. {
  1626. crypto_digest_t *r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
  1627. r->algorithm = algorithm;
  1628. switch (algorithm)
  1629. {
  1630. case DIGEST_SHA1:
  1631. SHA1_Init(&r->d.sha1);
  1632. break;
  1633. case DIGEST_SHA256:
  1634. SHA256_Init(&r->d.sha2);
  1635. break;
  1636. case DIGEST_SHA512:
  1637. SHA512_Init(&r->d.sha512);
  1638. break;
  1639. case DIGEST_SHA3_256:
  1640. keccak_digest_init(&r->d.sha3, 256);
  1641. break;
  1642. case DIGEST_SHA3_512:
  1643. keccak_digest_init(&r->d.sha3, 512);
  1644. break;
  1645. default:
  1646. tor_assert_unreached();
  1647. }
  1648. return r;
  1649. }
  1650. /** Allocate and return a new digest object to compute SHA1 digests.
  1651. */
  1652. crypto_digest_t *
  1653. crypto_digest_new(void)
  1654. {
  1655. return crypto_digest_new_internal(DIGEST_SHA1);
  1656. }
  1657. /** Allocate and return a new digest object to compute 256-bit digests
  1658. * using <b>algorithm</b>. */
  1659. crypto_digest_t *
  1660. crypto_digest256_new(digest_algorithm_t algorithm)
  1661. {
  1662. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1663. return crypto_digest_new_internal(algorithm);
  1664. }
  1665. /** Allocate and return a new digest object to compute 512-bit digests
  1666. * using <b>algorithm</b>. */
  1667. crypto_digest_t *
  1668. crypto_digest512_new(digest_algorithm_t algorithm)
  1669. {
  1670. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1671. return crypto_digest_new_internal(algorithm);
  1672. }
  1673. /** Deallocate a digest object.
  1674. */
  1675. void
  1676. crypto_digest_free(crypto_digest_t *digest)
  1677. {
  1678. if (!digest)
  1679. return;
  1680. size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1681. memwipe(digest, 0, bytes);
  1682. tor_free(digest);
  1683. }
  1684. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1685. */
  1686. void
  1687. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  1688. size_t len)
  1689. {
  1690. tor_assert(digest);
  1691. tor_assert(data);
  1692. /* Using the SHA*_*() calls directly means we don't support doing
  1693. * SHA in hardware. But so far the delay of getting the question
  1694. * to the hardware, and hearing the answer, is likely higher than
  1695. * just doing it ourselves. Hashes are fast.
  1696. */
  1697. switch (digest->algorithm) {
  1698. case DIGEST_SHA1:
  1699. SHA1_Update(&digest->d.sha1, (void*)data, len);
  1700. break;
  1701. case DIGEST_SHA256:
  1702. SHA256_Update(&digest->d.sha2, (void*)data, len);
  1703. break;
  1704. case DIGEST_SHA512:
  1705. SHA512_Update(&digest->d.sha512, (void*)data, len);
  1706. break;
  1707. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1708. case DIGEST_SHA3_512:
  1709. keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
  1710. break;
  1711. default:
  1712. /* LCOV_EXCL_START */
  1713. tor_fragile_assert();
  1714. break;
  1715. /* LCOV_EXCL_STOP */
  1716. }
  1717. }
  1718. /** Compute the hash of the data that has been passed to the digest
  1719. * object; write the first out_len bytes of the result to <b>out</b>.
  1720. * <b>out_len</b> must be \<= DIGEST512_LEN.
  1721. */
  1722. void
  1723. crypto_digest_get_digest(crypto_digest_t *digest,
  1724. char *out, size_t out_len)
  1725. {
  1726. unsigned char r[DIGEST512_LEN];
  1727. crypto_digest_t tmpenv;
  1728. tor_assert(digest);
  1729. tor_assert(out);
  1730. tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
  1731. /* The SHA-3 code handles copying into a temporary ctx, and also can handle
  1732. * short output buffers by truncating appropriately. */
  1733. if (digest->algorithm == DIGEST_SHA3_256 ||
  1734. digest->algorithm == DIGEST_SHA3_512) {
  1735. keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
  1736. return;
  1737. }
  1738. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1739. /* memcpy into a temporary ctx, since SHA*_Final clears the context */
  1740. memcpy(&tmpenv, digest, alloc_bytes);
  1741. switch (digest->algorithm) {
  1742. case DIGEST_SHA1:
  1743. SHA1_Final(r, &tmpenv.d.sha1);
  1744. break;
  1745. case DIGEST_SHA256:
  1746. SHA256_Final(r, &tmpenv.d.sha2);
  1747. break;
  1748. case DIGEST_SHA512:
  1749. SHA512_Final(r, &tmpenv.d.sha512);
  1750. break;
  1751. //LCOV_EXCL_START
  1752. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1753. case DIGEST_SHA3_512:
  1754. default:
  1755. log_warn(LD_BUG, "Handling unexpected algorithm %d", digest->algorithm);
  1756. /* This is fatal, because it should never happen. */
  1757. tor_assert_unreached();
  1758. break;
  1759. //LCOV_EXCL_STOP
  1760. }
  1761. memcpy(out, r, out_len);
  1762. memwipe(r, 0, sizeof(r));
  1763. }
  1764. /** Allocate and return a new digest object with the same state as
  1765. * <b>digest</b>
  1766. */
  1767. crypto_digest_t *
  1768. crypto_digest_dup(const crypto_digest_t *digest)
  1769. {
  1770. tor_assert(digest);
  1771. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1772. return tor_memdup(digest, alloc_bytes);
  1773. }
  1774. /** Replace the state of the digest object <b>into</b> with the state
  1775. * of the digest object <b>from</b>. Requires that 'into' and 'from'
  1776. * have the same digest type.
  1777. */
  1778. void
  1779. crypto_digest_assign(crypto_digest_t *into,
  1780. const crypto_digest_t *from)
  1781. {
  1782. tor_assert(into);
  1783. tor_assert(from);
  1784. tor_assert(into->algorithm == from->algorithm);
  1785. const size_t alloc_bytes = crypto_digest_alloc_bytes(from->algorithm);
  1786. memcpy(into,from,alloc_bytes);
  1787. }
  1788. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1789. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  1790. * plus the optional string <b>append</b>, computed with the algorithm
  1791. * <b>alg</b>.
  1792. * <b>out_len</b> must be \<= DIGEST512_LEN. */
  1793. void
  1794. crypto_digest_smartlist(char *digest_out, size_t len_out,
  1795. const smartlist_t *lst,
  1796. const char *append,
  1797. digest_algorithm_t alg)
  1798. {
  1799. crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
  1800. }
  1801. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1802. * at <b>digest_out</b> to the hash of the concatenation of: the
  1803. * optional string <b>prepend</b>, those strings,
  1804. * and the optional string <b>append</b>, computed with the algorithm
  1805. * <b>alg</b>.
  1806. * <b>len_out</b> must be \<= DIGEST512_LEN. */
  1807. void
  1808. crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
  1809. const char *prepend,
  1810. const smartlist_t *lst,
  1811. const char *append,
  1812. digest_algorithm_t alg)
  1813. {
  1814. crypto_digest_t *d = crypto_digest_new_internal(alg);
  1815. if (prepend)
  1816. crypto_digest_add_bytes(d, prepend, strlen(prepend));
  1817. SMARTLIST_FOREACH(lst, const char *, cp,
  1818. crypto_digest_add_bytes(d, cp, strlen(cp)));
  1819. if (append)
  1820. crypto_digest_add_bytes(d, append, strlen(append));
  1821. crypto_digest_get_digest(d, digest_out, len_out);
  1822. crypto_digest_free(d);
  1823. }
  1824. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1825. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  1826. * result in <b>hmac_out</b>. Asserts on failure.
  1827. */
  1828. void
  1829. crypto_hmac_sha256(char *hmac_out,
  1830. const char *key, size_t key_len,
  1831. const char *msg, size_t msg_len)
  1832. {
  1833. unsigned char *rv = NULL;
  1834. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  1835. tor_assert(key_len < INT_MAX);
  1836. tor_assert(msg_len < INT_MAX);
  1837. tor_assert(hmac_out);
  1838. rv = HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  1839. (unsigned char*)hmac_out, NULL);
  1840. tor_assert(rv);
  1841. }
  1842. /** Compute a MAC using SHA3-256 of <b>msg_len</b> bytes in <b>msg</b> using a
  1843. * <b>key</b> of length <b>key_len</b> and a <b>salt</b> of length
  1844. * <b>salt_len</b>. Store the result of <b>len_out</b> bytes in in
  1845. * <b>mac_out</b>. This function can't fail. */
  1846. void
  1847. crypto_mac_sha3_256(uint8_t *mac_out, size_t len_out,
  1848. const uint8_t *key, size_t key_len,
  1849. const uint8_t *msg, size_t msg_len)
  1850. {
  1851. crypto_digest_t *digest;
  1852. const uint64_t key_len_netorder = tor_htonll(key_len);
  1853. tor_assert(mac_out);
  1854. tor_assert(key);
  1855. tor_assert(msg);
  1856. digest = crypto_digest256_new(DIGEST_SHA3_256);
  1857. /* Order matters here that is any subsystem using this function should
  1858. * expect this very precise ordering in the MAC construction. */
  1859. crypto_digest_add_bytes(digest, (const char *) &key_len_netorder,
  1860. sizeof(key_len_netorder));
  1861. crypto_digest_add_bytes(digest, (const char *) key, key_len);
  1862. crypto_digest_add_bytes(digest, (const char *) msg, msg_len);
  1863. crypto_digest_get_digest(digest, (char *) mac_out, len_out);
  1864. crypto_digest_free(digest);
  1865. }
  1866. /** Internal state for a eXtendable-Output Function (XOF). */
  1867. struct crypto_xof_t {
  1868. keccak_state s;
  1869. };
  1870. /** Allocate a new XOF object backed by SHAKE-256. The security level
  1871. * provided is a function of the length of the output used. Read and
  1872. * understand FIPS-202 A.2 "Additional Consideration for Extendable-Output
  1873. * Functions" before using this construct.
  1874. */
  1875. crypto_xof_t *
  1876. crypto_xof_new(void)
  1877. {
  1878. crypto_xof_t *xof;
  1879. xof = tor_malloc(sizeof(crypto_xof_t));
  1880. keccak_xof_init(&xof->s, 256);
  1881. return xof;
  1882. }
  1883. /** Absorb bytes into a XOF object. Must not be called after a call to
  1884. * crypto_xof_squeeze_bytes() for the same instance, and will assert
  1885. * if attempted.
  1886. */
  1887. void
  1888. crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
  1889. {
  1890. int i = keccak_xof_absorb(&xof->s, data, len);
  1891. tor_assert(i == 0);
  1892. }
  1893. /** Squeeze bytes out of a XOF object. Calling this routine will render
  1894. * the XOF instance ineligible to absorb further data.
  1895. */
  1896. void
  1897. crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
  1898. {
  1899. int i = keccak_xof_squeeze(&xof->s, out, len);
  1900. tor_assert(i == 0);
  1901. }
  1902. /** Cleanse and deallocate a XOF object. */
  1903. void
  1904. crypto_xof_free(crypto_xof_t *xof)
  1905. {
  1906. if (!xof)
  1907. return;
  1908. memwipe(xof, 0, sizeof(crypto_xof_t));
  1909. tor_free(xof);
  1910. }
  1911. /* DH */
  1912. /** Our DH 'g' parameter */
  1913. #define DH_GENERATOR 2
  1914. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  1915. static BIGNUM *dh_param_p = NULL;
  1916. /** Shared P parameter for our TLS DH key exchanges. */
  1917. static BIGNUM *dh_param_p_tls = NULL;
  1918. /** Shared G parameter for our DH key exchanges. */
  1919. static BIGNUM *dh_param_g = NULL;
  1920. /** Validate a given set of Diffie-Hellman parameters. This is moderately
  1921. * computationally expensive (milliseconds), so should only be called when
  1922. * the DH parameters change. Returns 0 on success, * -1 on failure.
  1923. */
  1924. static int
  1925. crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
  1926. {
  1927. DH *dh = NULL;
  1928. int ret = -1;
  1929. /* Copy into a temporary DH object, just so that DH_check() can be called. */
  1930. if (!(dh = DH_new()))
  1931. goto out;
  1932. #ifdef OPENSSL_1_1_API
  1933. BIGNUM *dh_p, *dh_g;
  1934. if (!(dh_p = BN_dup(p)))
  1935. goto out;
  1936. if (!(dh_g = BN_dup(g)))
  1937. goto out;
  1938. if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
  1939. goto out;
  1940. #else /* !(defined(OPENSSL_1_1_API)) */
  1941. if (!(dh->p = BN_dup(p)))
  1942. goto out;
  1943. if (!(dh->g = BN_dup(g)))
  1944. goto out;
  1945. #endif /* defined(OPENSSL_1_1_API) */
  1946. /* Perform the validation. */
  1947. int codes = 0;
  1948. if (!DH_check(dh, &codes))
  1949. goto out;
  1950. if (BN_is_word(g, DH_GENERATOR_2)) {
  1951. /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
  1952. *
  1953. * OpenSSL checks the prime is congruent to 11 when g = 2; while the
  1954. * IETF's primes are congruent to 23 when g = 2.
  1955. */
  1956. BN_ULONG residue = BN_mod_word(p, 24);
  1957. if (residue == 11 || residue == 23)
  1958. codes &= ~DH_NOT_SUITABLE_GENERATOR;
  1959. }
  1960. if (codes != 0) /* Specifics on why the params suck is irrelevant. */
  1961. goto out;
  1962. /* Things are probably not evil. */
  1963. ret = 0;
  1964. out:
  1965. if (dh)
  1966. DH_free(dh);
  1967. return ret;
  1968. }
  1969. /** Set the global Diffie-Hellman generator, used for both TLS and internal
  1970. * DH stuff.
  1971. */
  1972. static void
  1973. crypto_set_dh_generator(void)
  1974. {
  1975. BIGNUM *generator;
  1976. int r;
  1977. if (dh_param_g)
  1978. return;
  1979. generator = BN_new();
  1980. tor_assert(generator);
  1981. r = BN_set_word(generator, DH_GENERATOR);
  1982. tor_assert(r);
  1983. dh_param_g = generator;
  1984. }
  1985. /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
  1986. * modulus. */
  1987. void
  1988. crypto_set_tls_dh_prime(void)
  1989. {
  1990. BIGNUM *tls_prime = NULL;
  1991. int r;
  1992. /* If the space is occupied, free the previous TLS DH prime */
  1993. if (BUG(dh_param_p_tls)) {
  1994. /* LCOV_EXCL_START
  1995. *
  1996. * We shouldn't be calling this twice.
  1997. */
  1998. BN_clear_free(dh_param_p_tls);
  1999. dh_param_p_tls = NULL;
  2000. /* LCOV_EXCL_STOP */
  2001. }
  2002. tls_prime = BN_new();
  2003. tor_assert(tls_prime);
  2004. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  2005. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  2006. * prime.
  2007. */
  2008. r = BN_hex2bn(&tls_prime,
  2009. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  2010. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  2011. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  2012. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  2013. "B0E7393E0F24218EB3");
  2014. tor_assert(r);
  2015. tor_assert(tls_prime);
  2016. dh_param_p_tls = tls_prime;
  2017. crypto_set_dh_generator();
  2018. tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
  2019. }
  2020. /** Initialize dh_param_p and dh_param_g if they are not already
  2021. * set. */
  2022. static void
  2023. init_dh_param(void)
  2024. {
  2025. BIGNUM *circuit_dh_prime;
  2026. int r;
  2027. if (BUG(dh_param_p && dh_param_g))
  2028. return; // LCOV_EXCL_LINE This function isn't supposed to be called twice.
  2029. circuit_dh_prime = BN_new();
  2030. tor_assert(circuit_dh_prime);
  2031. /* This is from rfc2409, section 6.2. It's a safe prime, and
  2032. supposedly it equals:
  2033. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  2034. */
  2035. r = BN_hex2bn(&circuit_dh_prime,
  2036. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  2037. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  2038. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  2039. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  2040. "49286651ECE65381FFFFFFFFFFFFFFFF");
  2041. tor_assert(r);
  2042. /* Set the new values as the global DH parameters. */
  2043. dh_param_p = circuit_dh_prime;
  2044. crypto_set_dh_generator();
  2045. tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
  2046. if (!dh_param_p_tls) {
  2047. crypto_set_tls_dh_prime();
  2048. }
  2049. }
  2050. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  2051. * handshake. Since we exponentiate by this value, choosing a smaller one
  2052. * lets our handhake go faster.
  2053. */
  2054. #define DH_PRIVATE_KEY_BITS 320
  2055. /** Allocate and return a new DH object for a key exchange. Returns NULL on
  2056. * failure.
  2057. */
  2058. crypto_dh_t *
  2059. crypto_dh_new(int dh_type)
  2060. {
  2061. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  2062. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  2063. dh_type == DH_TYPE_REND);
  2064. if (!dh_param_p)
  2065. init_dh_param();
  2066. if (!(res->dh = DH_new()))
  2067. goto err;
  2068. #ifdef OPENSSL_1_1_API
  2069. BIGNUM *dh_p = NULL, *dh_g = NULL;
  2070. if (dh_type == DH_TYPE_TLS) {
  2071. dh_p = BN_dup(dh_param_p_tls);
  2072. } else {
  2073. dh_p = BN_dup(dh_param_p);
  2074. }
  2075. if (!dh_p)
  2076. goto err;
  2077. dh_g = BN_dup(dh_param_g);
  2078. if (!dh_g) {
  2079. BN_free(dh_p);
  2080. goto err;
  2081. }
  2082. if (!DH_set0_pqg(res->dh, dh_p, NULL, dh_g)) {
  2083. goto err;
  2084. }
  2085. if (!DH_set_length(res->dh, DH_PRIVATE_KEY_BITS))
  2086. goto err;
  2087. #else /* !(defined(OPENSSL_1_1_API)) */
  2088. if (dh_type == DH_TYPE_TLS) {
  2089. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  2090. goto err;
  2091. } else {
  2092. if (!(res->dh->p = BN_dup(dh_param_p)))
  2093. goto err;
  2094. }
  2095. if (!(res->dh->g = BN_dup(dh_param_g)))
  2096. goto err;
  2097. res->dh->length = DH_PRIVATE_KEY_BITS;
  2098. #endif /* defined(OPENSSL_1_1_API) */
  2099. return res;
  2100. /* LCOV_EXCL_START
  2101. * This error condition is only reached when an allocation fails */
  2102. err:
  2103. crypto_log_errors(LOG_WARN, "creating DH object");
  2104. if (res->dh) DH_free(res->dh); /* frees p and g too */
  2105. tor_free(res);
  2106. return NULL;
  2107. /* LCOV_EXCL_STOP */
  2108. }
  2109. /** Return a copy of <b>dh</b>, sharing its internal state. */
  2110. crypto_dh_t *
  2111. crypto_dh_dup(const crypto_dh_t *dh)
  2112. {
  2113. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  2114. tor_assert(dh);
  2115. tor_assert(dh->dh);
  2116. dh_new->dh = dh->dh;
  2117. DH_up_ref(dh->dh);
  2118. return dh_new;
  2119. }
  2120. /** Return the length of the DH key in <b>dh</b>, in bytes.
  2121. */
  2122. int
  2123. crypto_dh_get_bytes(crypto_dh_t *dh)
  2124. {
  2125. tor_assert(dh);
  2126. return DH_size(dh->dh);
  2127. }
  2128. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  2129. * success, -1 on failure.
  2130. */
  2131. int
  2132. crypto_dh_generate_public(crypto_dh_t *dh)
  2133. {
  2134. #ifndef OPENSSL_1_1_API
  2135. again:
  2136. #endif
  2137. if (!DH_generate_key(dh->dh)) {
  2138. /* LCOV_EXCL_START
  2139. * To test this we would need some way to tell openssl to break DH. */
  2140. crypto_log_errors(LOG_WARN, "generating DH key");
  2141. return -1;
  2142. /* LCOV_EXCL_STOP */
  2143. }
  2144. #ifdef OPENSSL_1_1_API
  2145. /* OpenSSL 1.1.x doesn't appear to let you regenerate a DH key, without
  2146. * recreating the DH object. I have no idea what sort of aliasing madness
  2147. * can occur here, so do the check, and just bail on failure.
  2148. */
  2149. const BIGNUM *pub_key, *priv_key;
  2150. DH_get0_key(dh->dh, &pub_key, &priv_key);
  2151. if (tor_check_dh_key(LOG_WARN, pub_key)<0) {
  2152. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  2153. "the-universe chances really do happen. Treating as a failure.");
  2154. return -1;
  2155. }
  2156. #else /* !(defined(OPENSSL_1_1_API)) */
  2157. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  2158. /* LCOV_EXCL_START
  2159. * If this happens, then openssl's DH implementation is busted. */
  2160. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  2161. "the-universe chances really do happen. Trying again.");
  2162. /* Free and clear the keys, so OpenSSL will actually try again. */
  2163. BN_clear_free(dh->dh->pub_key);
  2164. BN_clear_free(dh->dh->priv_key);
  2165. dh->dh->pub_key = dh->dh->priv_key = NULL;
  2166. goto again;
  2167. /* LCOV_EXCL_STOP */
  2168. }
  2169. #endif /* defined(OPENSSL_1_1_API) */
  2170. return 0;
  2171. }
  2172. /** Generate g^x as necessary, and write the g^x for the key exchange
  2173. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  2174. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  2175. */
  2176. int
  2177. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  2178. {
  2179. int bytes;
  2180. tor_assert(dh);
  2181. const BIGNUM *dh_pub;
  2182. #ifdef OPENSSL_1_1_API
  2183. const BIGNUM *dh_priv;
  2184. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  2185. #else
  2186. dh_pub = dh->dh->pub_key;
  2187. #endif /* defined(OPENSSL_1_1_API) */
  2188. if (!dh_pub) {
  2189. if (crypto_dh_generate_public(dh)<0)
  2190. return -1;
  2191. else {
  2192. #ifdef OPENSSL_1_1_API
  2193. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  2194. #else
  2195. dh_pub = dh->dh->pub_key;
  2196. #endif
  2197. }
  2198. }
  2199. tor_assert(dh_pub);
  2200. bytes = BN_num_bytes(dh_pub);
  2201. tor_assert(bytes >= 0);
  2202. if (pubkey_len < (size_t)bytes) {
  2203. log_warn(LD_CRYPTO,
  2204. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  2205. (int) pubkey_len, bytes);
  2206. return -1;
  2207. }
  2208. memset(pubkey, 0, pubkey_len);
  2209. BN_bn2bin(dh_pub, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  2210. return 0;
  2211. }
  2212. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  2213. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  2214. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  2215. */
  2216. static int
  2217. tor_check_dh_key(int severity, const BIGNUM *bn)
  2218. {
  2219. BIGNUM *x;
  2220. char *s;
  2221. tor_assert(bn);
  2222. x = BN_new();
  2223. tor_assert(x);
  2224. if (BUG(!dh_param_p))
  2225. init_dh_param(); //LCOV_EXCL_LINE we already checked whether we did this.
  2226. BN_set_word(x, 1);
  2227. if (BN_cmp(bn,x)<=0) {
  2228. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  2229. goto err;
  2230. }
  2231. BN_copy(x,dh_param_p);
  2232. BN_sub_word(x, 1);
  2233. if (BN_cmp(bn,x)>=0) {
  2234. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  2235. goto err;
  2236. }
  2237. BN_clear_free(x);
  2238. return 0;
  2239. err:
  2240. BN_clear_free(x);
  2241. s = BN_bn2hex(bn);
  2242. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  2243. OPENSSL_free(s);
  2244. return -1;
  2245. }
  2246. /** Given a DH key exchange object, and our peer's value of g^y (as a
  2247. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  2248. * <b>secret_bytes_out</b> bytes of shared key material and write them
  2249. * to <b>secret_out</b>. Return the number of bytes generated on success,
  2250. * or -1 on failure.
  2251. *
  2252. * (We generate key material by computing
  2253. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  2254. * where || is concatenation.)
  2255. */
  2256. ssize_t
  2257. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  2258. const char *pubkey, size_t pubkey_len,
  2259. char *secret_out, size_t secret_bytes_out)
  2260. {
  2261. char *secret_tmp = NULL;
  2262. BIGNUM *pubkey_bn = NULL;
  2263. size_t secret_len=0, secret_tmp_len=0;
  2264. int result=0;
  2265. tor_assert(dh);
  2266. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  2267. tor_assert(pubkey_len < INT_MAX);
  2268. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  2269. (int)pubkey_len, NULL)))
  2270. goto error;
  2271. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  2272. /* Check for invalid public keys. */
  2273. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  2274. goto error;
  2275. }
  2276. secret_tmp_len = crypto_dh_get_bytes(dh);
  2277. secret_tmp = tor_malloc(secret_tmp_len);
  2278. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  2279. if (result < 0) {
  2280. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  2281. goto error;
  2282. }
  2283. secret_len = result;
  2284. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  2285. (uint8_t*)secret_out, secret_bytes_out)<0)
  2286. goto error;
  2287. secret_len = secret_bytes_out;
  2288. goto done;
  2289. error:
  2290. result = -1;
  2291. done:
  2292. crypto_log_errors(LOG_WARN, "completing DH handshake");
  2293. if (pubkey_bn)
  2294. BN_clear_free(pubkey_bn);
  2295. if (secret_tmp) {
  2296. memwipe(secret_tmp, 0, secret_tmp_len);
  2297. tor_free(secret_tmp);
  2298. }
  2299. if (result < 0)
  2300. return result;
  2301. else
  2302. return secret_len;
  2303. }
  2304. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  2305. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  2306. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  2307. * H(K | [00]) | H(K | [01]) | ....
  2308. *
  2309. * This is the key expansion algorithm used in the "TAP" circuit extension
  2310. * mechanism; it shouldn't be used for new protocols.
  2311. *
  2312. * Return 0 on success, -1 on failure.
  2313. */
  2314. int
  2315. crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
  2316. uint8_t *key_out, size_t key_out_len)
  2317. {
  2318. int i, r = -1;
  2319. uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
  2320. uint8_t digest[DIGEST_LEN];
  2321. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  2322. tor_assert(key_out_len <= DIGEST_LEN*256);
  2323. memcpy(tmp, key_in, key_in_len);
  2324. for (cp = key_out, i=0; cp < key_out+key_out_len;
  2325. ++i, cp += DIGEST_LEN) {
  2326. tmp[key_in_len] = i;
  2327. if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1) < 0)
  2328. goto exit;
  2329. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  2330. }
  2331. r = 0;
  2332. exit:
  2333. memwipe(tmp, 0, key_in_len+1);
  2334. tor_free(tmp);
  2335. memwipe(digest, 0, sizeof(digest));
  2336. return r;
  2337. }
  2338. /** Expand some secret key material according to RFC5869, using SHA256 as the
  2339. * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
  2340. * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
  2341. * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
  2342. * and "info" parameters respectively. On success, write <b>key_out_len</b>
  2343. * bytes to <b>key_out</b> and return 0. Assert on failure.
  2344. */
  2345. int
  2346. crypto_expand_key_material_rfc5869_sha256(
  2347. const uint8_t *key_in, size_t key_in_len,
  2348. const uint8_t *salt_in, size_t salt_in_len,
  2349. const uint8_t *info_in, size_t info_in_len,
  2350. uint8_t *key_out, size_t key_out_len)
  2351. {
  2352. uint8_t prk[DIGEST256_LEN];
  2353. uint8_t tmp[DIGEST256_LEN + 128 + 1];
  2354. uint8_t mac[DIGEST256_LEN];
  2355. int i;
  2356. uint8_t *outp;
  2357. size_t tmp_len;
  2358. crypto_hmac_sha256((char*)prk,
  2359. (const char*)salt_in, salt_in_len,
  2360. (const char*)key_in, key_in_len);
  2361. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  2362. tor_assert(key_out_len <= DIGEST256_LEN * 256);
  2363. tor_assert(info_in_len <= 128);
  2364. memset(tmp, 0, sizeof(tmp));
  2365. outp = key_out;
  2366. i = 1;
  2367. while (key_out_len) {
  2368. size_t n;
  2369. if (i > 1) {
  2370. memcpy(tmp, mac, DIGEST256_LEN);
  2371. memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
  2372. tmp[DIGEST256_LEN+info_in_len] = i;
  2373. tmp_len = DIGEST256_LEN + info_in_len + 1;
  2374. } else {
  2375. memcpy(tmp, info_in, info_in_len);
  2376. tmp[info_in_len] = i;
  2377. tmp_len = info_in_len + 1;
  2378. }
  2379. crypto_hmac_sha256((char*)mac,
  2380. (const char*)prk, DIGEST256_LEN,
  2381. (const char*)tmp, tmp_len);
  2382. n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
  2383. memcpy(outp, mac, n);
  2384. key_out_len -= n;
  2385. outp += n;
  2386. ++i;
  2387. }
  2388. memwipe(tmp, 0, sizeof(tmp));
  2389. memwipe(mac, 0, sizeof(mac));
  2390. return 0;
  2391. }
  2392. /** Free a DH key exchange object.
  2393. */
  2394. void
  2395. crypto_dh_free(crypto_dh_t *dh)
  2396. {
  2397. if (!dh)
  2398. return;
  2399. tor_assert(dh->dh);
  2400. DH_free(dh->dh);
  2401. tor_free(dh);
  2402. }
  2403. /* random numbers */
  2404. /** How many bytes of entropy we add at once.
  2405. *
  2406. * This is how much entropy OpenSSL likes to add right now, so maybe it will
  2407. * work for us too. */
  2408. #define ADD_ENTROPY 32
  2409. /** Set the seed of the weak RNG to a random value. */
  2410. void
  2411. crypto_seed_weak_rng(tor_weak_rng_t *rng)
  2412. {
  2413. unsigned seed;
  2414. crypto_rand((void*)&seed, sizeof(seed));
  2415. tor_init_weak_random(rng, seed);
  2416. }
  2417. #ifdef TOR_UNIT_TESTS
  2418. int break_strongest_rng_syscall = 0;
  2419. int break_strongest_rng_fallback = 0;
  2420. #endif
  2421. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2422. * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
  2423. * failure. A maximum request size of 256 bytes is imposed.
  2424. */
  2425. static int
  2426. crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
  2427. {
  2428. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  2429. #ifdef TOR_UNIT_TESTS
  2430. if (break_strongest_rng_syscall)
  2431. return -1;
  2432. #endif
  2433. #if defined(_WIN32)
  2434. static int provider_set = 0;
  2435. static HCRYPTPROV provider;
  2436. if (!provider_set) {
  2437. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  2438. CRYPT_VERIFYCONTEXT)) {
  2439. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  2440. return -1;
  2441. }
  2442. provider_set = 1;
  2443. }
  2444. if (!CryptGenRandom(provider, out_len, out)) {
  2445. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  2446. return -1;
  2447. }
  2448. return 0;
  2449. #elif defined(__linux__) && defined(SYS_getrandom)
  2450. static int getrandom_works = 1; /* Be optimitic about our chances... */
  2451. /* getrandom() isn't as straight foward as getentropy(), and has
  2452. * no glibc wrapper.
  2453. *
  2454. * As far as I can tell from getrandom(2) and the source code, the
  2455. * requests we issue will always succeed (though it will block on the
  2456. * call if /dev/urandom isn't seeded yet), since we are NOT specifying
  2457. * GRND_NONBLOCK and the request is <= 256 bytes.
  2458. *
  2459. * The manpage is unclear on what happens if a signal interrupts the call
  2460. * while the request is blocked due to lack of entropy....
  2461. *
  2462. * We optimistically assume that getrandom() is available and functional
  2463. * because it is the way of the future, and 2 branch mispredicts pale in
  2464. * comparision to the overheads involved with failing to open
  2465. * /dev/srandom followed by opening and reading from /dev/urandom.
  2466. */
  2467. if (PREDICT_LIKELY(getrandom_works)) {
  2468. long ret;
  2469. /* A flag of '0' here means to read from '/dev/urandom', and to
  2470. * block if insufficient entropy is available to service the
  2471. * request.
  2472. */
  2473. const unsigned int flags = 0;
  2474. do {
  2475. ret = syscall(SYS_getrandom, out, out_len, flags);
  2476. } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
  2477. if (PREDICT_UNLIKELY(ret == -1)) {
  2478. /* LCOV_EXCL_START we can't actually make the syscall fail in testing. */
  2479. tor_assert(errno != EAGAIN);
  2480. tor_assert(errno != EINTR);
  2481. /* Useful log message for errno. */
  2482. if (errno == ENOSYS) {
  2483. log_warn(LD_CRYPTO, "Can't get entropy from getrandom()."
  2484. " You are running a version of Tor built to support"
  2485. " getrandom(), but the kernel doesn't implement this"
  2486. " function--probably because it is too old?");
  2487. } else {
  2488. log_warn(LD_CRYPTO, "Can't get entropy from getrandom(): %s.",
  2489. strerror(errno));
  2490. }
  2491. getrandom_works = 0; /* Don't bother trying again. */
  2492. return -1;
  2493. /* LCOV_EXCL_STOP */
  2494. }
  2495. tor_assert(ret == (long)out_len);
  2496. return 0;
  2497. }
  2498. return -1; /* getrandom() previously failed unexpectedly. */
  2499. #elif defined(HAVE_GETENTROPY)
  2500. /* getentropy() is what Linux's getrandom() wants to be when it grows up.
  2501. * the only gotcha is that requests are limited to 256 bytes.
  2502. */
  2503. return getentropy(out, out_len);
  2504. #else
  2505. (void) out;
  2506. #endif /* defined(_WIN32) || ... */
  2507. /* This platform doesn't have a supported syscall based random. */
  2508. return -1;
  2509. }
  2510. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2511. * via the per-platform fallback mechanism, storing it into <b>out</b>.
  2512. * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
  2513. * is imposed.
  2514. */
  2515. static int
  2516. crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
  2517. {
  2518. #ifdef TOR_UNIT_TESTS
  2519. if (break_strongest_rng_fallback)
  2520. return -1;
  2521. #endif
  2522. #ifdef _WIN32
  2523. /* Windows exclusively uses crypto_strongest_rand_syscall(). */
  2524. (void)out;
  2525. (void)out_len;
  2526. return -1;
  2527. #else /* !(defined(_WIN32)) */
  2528. static const char *filenames[] = {
  2529. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  2530. };
  2531. int fd, i;
  2532. size_t n;
  2533. for (i = 0; filenames[i]; ++i) {
  2534. log_debug(LD_FS, "Considering %s for entropy", filenames[i]);
  2535. fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
  2536. if (fd<0) continue;
  2537. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  2538. n = read_all(fd, (char*)out, out_len, 0);
  2539. close(fd);
  2540. if (n != out_len) {
  2541. /* LCOV_EXCL_START
  2542. * We can't make /dev/foorandom actually fail. */
  2543. log_warn(LD_CRYPTO,
  2544. "Error reading from entropy source (read only %lu bytes).",
  2545. (unsigned long)n);
  2546. return -1;
  2547. /* LCOV_EXCL_STOP */
  2548. }
  2549. return 0;
  2550. }
  2551. return -1;
  2552. #endif /* defined(_WIN32) */
  2553. }
  2554. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2555. * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
  2556. * request size of 256 bytes is imposed.
  2557. */
  2558. STATIC int
  2559. crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
  2560. {
  2561. static const size_t sanity_min_size = 16;
  2562. static const int max_attempts = 3;
  2563. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  2564. /* For buffers >= 16 bytes (128 bits), we sanity check the output by
  2565. * zero filling the buffer and ensuring that it actually was at least
  2566. * partially modified.
  2567. *
  2568. * Checking that any individual byte is non-zero seems like it would
  2569. * fail too often (p = out_len * 1/256) for comfort, but this is an
  2570. * "adjust according to taste" sort of check.
  2571. */
  2572. memwipe(out, 0, out_len);
  2573. for (int i = 0; i < max_attempts; i++) {
  2574. /* Try to use the syscall/OS favored mechanism to get strong entropy. */
  2575. if (crypto_strongest_rand_syscall(out, out_len) != 0) {
  2576. /* Try to use the less-favored mechanism to get strong entropy. */
  2577. if (crypto_strongest_rand_fallback(out, out_len) != 0) {
  2578. /* Welp, we tried. Hopefully the calling code terminates the process
  2579. * since we're basically boned without good entropy.
  2580. */
  2581. log_warn(LD_CRYPTO,
  2582. "Cannot get strong entropy: no entropy source found.");
  2583. return -1;
  2584. }
  2585. }
  2586. if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
  2587. return 0;
  2588. }
  2589. /* LCOV_EXCL_START
  2590. *
  2591. * We tried max_attempts times to fill a buffer >= 128 bits long,
  2592. * and each time it returned all '0's. Either the system entropy
  2593. * source is busted, or the user should go out and buy a ticket to
  2594. * every lottery on the planet.
  2595. */
  2596. log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
  2597. return -1;
  2598. /* LCOV_EXCL_STOP */
  2599. }
  2600. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2601. * storing it into <b>out</b>.
  2602. */
  2603. void
  2604. crypto_strongest_rand(uint8_t *out, size_t out_len)
  2605. {
  2606. #define DLEN SHA512_DIGEST_LENGTH
  2607. /* We're going to hash DLEN bytes from the system RNG together with some
  2608. * bytes from the openssl PRNG, in order to yield DLEN bytes.
  2609. */
  2610. uint8_t inp[DLEN*2];
  2611. uint8_t tmp[DLEN];
  2612. tor_assert(out);
  2613. while (out_len) {
  2614. crypto_rand((char*) inp, DLEN);
  2615. if (crypto_strongest_rand_raw(inp+DLEN, DLEN) < 0) {
  2616. // LCOV_EXCL_START
  2617. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  2618. "important key. Exiting.");
  2619. /* Die with an assertion so we get a stack trace. */
  2620. tor_assert(0);
  2621. // LCOV_EXCL_STOP
  2622. }
  2623. if (out_len >= DLEN) {
  2624. SHA512(inp, sizeof(inp), out);
  2625. out += DLEN;
  2626. out_len -= DLEN;
  2627. } else {
  2628. SHA512(inp, sizeof(inp), tmp);
  2629. memcpy(out, tmp, out_len);
  2630. break;
  2631. }
  2632. }
  2633. memwipe(tmp, 0, sizeof(tmp));
  2634. memwipe(inp, 0, sizeof(inp));
  2635. #undef DLEN
  2636. }
  2637. /** Seed OpenSSL's random number generator with bytes from the operating
  2638. * system. Return 0 on success, -1 on failure.
  2639. */
  2640. int
  2641. crypto_seed_rng(void)
  2642. {
  2643. int rand_poll_ok = 0, load_entropy_ok = 0;
  2644. uint8_t buf[ADD_ENTROPY];
  2645. /* OpenSSL has a RAND_poll function that knows about more kinds of
  2646. * entropy than we do. We'll try calling that, *and* calling our own entropy
  2647. * functions. If one succeeds, we'll accept the RNG as seeded. */
  2648. rand_poll_ok = RAND_poll();
  2649. if (rand_poll_ok == 0)
  2650. log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
  2651. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  2652. if (load_entropy_ok) {
  2653. RAND_seed(buf, sizeof(buf));
  2654. }
  2655. memwipe(buf, 0, sizeof(buf));
  2656. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  2657. return 0;
  2658. else
  2659. return -1;
  2660. }
  2661. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  2662. * for unit tests.
  2663. *
  2664. * This function is not allowed to fail; if it would fail to generate strong
  2665. * entropy, it must terminate the process instead.
  2666. */
  2667. MOCK_IMPL(void,
  2668. crypto_rand, (char *to, size_t n))
  2669. {
  2670. crypto_rand_unmocked(to, n);
  2671. }
  2672. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  2673. * will want crypto_rand instead.
  2674. *
  2675. * This function is not allowed to fail; if it would fail to generate strong
  2676. * entropy, it must terminate the process instead.
  2677. */
  2678. void
  2679. crypto_rand_unmocked(char *to, size_t n)
  2680. {
  2681. int r;
  2682. if (n == 0)
  2683. return;
  2684. tor_assert(n < INT_MAX);
  2685. tor_assert(to);
  2686. r = RAND_bytes((unsigned char*)to, (int)n);
  2687. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  2688. * stack trace about where it happened.
  2689. */
  2690. tor_assert(r >= 0);
  2691. }
  2692. /** Return a pseudorandom integer, chosen uniformly from the values
  2693. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  2694. * INT_MAX+1, inclusive. */
  2695. int
  2696. crypto_rand_int(unsigned int max)
  2697. {
  2698. unsigned int val;
  2699. unsigned int cutoff;
  2700. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  2701. tor_assert(max > 0); /* don't div by 0 */
  2702. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2703. * distribution with clipping at the upper end of unsigned int's
  2704. * range.
  2705. */
  2706. cutoff = UINT_MAX - (UINT_MAX%max);
  2707. while (1) {
  2708. crypto_rand((char*)&val, sizeof(val));
  2709. if (val < cutoff)
  2710. return val % max;
  2711. }
  2712. }
  2713. /** Return a pseudorandom integer, chosen uniformly from the values i such
  2714. * that min <= i < max.
  2715. *
  2716. * <b>min</b> MUST be in range [0, <b>max</b>).
  2717. * <b>max</b> MUST be in range (min, INT_MAX].
  2718. */
  2719. int
  2720. crypto_rand_int_range(unsigned int min, unsigned int max)
  2721. {
  2722. tor_assert(min < max);
  2723. tor_assert(max <= INT_MAX);
  2724. /* The overflow is avoided here because crypto_rand_int() returns a value
  2725. * between 0 and (max - min) inclusive. */
  2726. return min + crypto_rand_int(max - min);
  2727. }
  2728. /** As crypto_rand_int_range, but supports uint64_t. */
  2729. uint64_t
  2730. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  2731. {
  2732. tor_assert(min < max);
  2733. return min + crypto_rand_uint64(max - min);
  2734. }
  2735. /** As crypto_rand_int_range, but supports time_t. */
  2736. time_t
  2737. crypto_rand_time_range(time_t min, time_t max)
  2738. {
  2739. tor_assert(min < max);
  2740. return min + (time_t)crypto_rand_uint64(max - min);
  2741. }
  2742. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  2743. * between 0 and <b>max</b>-1 inclusive. */
  2744. uint64_t
  2745. crypto_rand_uint64(uint64_t max)
  2746. {
  2747. uint64_t val;
  2748. uint64_t cutoff;
  2749. tor_assert(max < UINT64_MAX);
  2750. tor_assert(max > 0); /* don't div by 0 */
  2751. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2752. * distribution with clipping at the upper end of unsigned int's
  2753. * range.
  2754. */
  2755. cutoff = UINT64_MAX - (UINT64_MAX%max);
  2756. while (1) {
  2757. crypto_rand((char*)&val, sizeof(val));
  2758. if (val < cutoff)
  2759. return val % max;
  2760. }
  2761. }
  2762. /** Return a pseudorandom double d, chosen uniformly from the range
  2763. * 0.0 <= d < 1.0.
  2764. */
  2765. double
  2766. crypto_rand_double(void)
  2767. {
  2768. /* We just use an unsigned int here; we don't really care about getting
  2769. * more than 32 bits of resolution */
  2770. unsigned int u;
  2771. crypto_rand((char*)&u, sizeof(u));
  2772. #if SIZEOF_INT == 4
  2773. #define UINT_MAX_AS_DOUBLE 4294967296.0
  2774. #elif SIZEOF_INT == 8
  2775. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  2776. #else
  2777. #error SIZEOF_INT is neither 4 nor 8
  2778. #endif /* SIZEOF_INT == 4 || ... */
  2779. return ((double)u) / UINT_MAX_AS_DOUBLE;
  2780. }
  2781. /** Generate and return a new random hostname starting with <b>prefix</b>,
  2782. * ending with <b>suffix</b>, and containing no fewer than
  2783. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  2784. * characters. Does not check for failure.
  2785. *
  2786. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  2787. **/
  2788. char *
  2789. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  2790. const char *suffix)
  2791. {
  2792. char *result, *rand_bytes;
  2793. int randlen, rand_bytes_len;
  2794. size_t resultlen, prefixlen;
  2795. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  2796. max_rand_len = MAX_DNS_LABEL_SIZE;
  2797. if (min_rand_len > max_rand_len)
  2798. min_rand_len = max_rand_len;
  2799. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  2800. prefixlen = strlen(prefix);
  2801. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  2802. rand_bytes_len = ((randlen*5)+7)/8;
  2803. if (rand_bytes_len % 5)
  2804. rand_bytes_len += 5 - (rand_bytes_len%5);
  2805. rand_bytes = tor_malloc(rand_bytes_len);
  2806. crypto_rand(rand_bytes, rand_bytes_len);
  2807. result = tor_malloc(resultlen);
  2808. memcpy(result, prefix, prefixlen);
  2809. base32_encode(result+prefixlen, resultlen-prefixlen,
  2810. rand_bytes, rand_bytes_len);
  2811. tor_free(rand_bytes);
  2812. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  2813. return result;
  2814. }
  2815. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  2816. * is empty. */
  2817. void *
  2818. smartlist_choose(const smartlist_t *sl)
  2819. {
  2820. int len = smartlist_len(sl);
  2821. if (len)
  2822. return smartlist_get(sl,crypto_rand_int(len));
  2823. return NULL; /* no elements to choose from */
  2824. }
  2825. /** Scramble the elements of <b>sl</b> into a random order. */
  2826. void
  2827. smartlist_shuffle(smartlist_t *sl)
  2828. {
  2829. int i;
  2830. /* From the end of the list to the front, choose at random from the
  2831. positions we haven't looked at yet, and swap that position into the
  2832. current position. Remember to give "no swap" the same probability as
  2833. any other swap. */
  2834. for (i = smartlist_len(sl)-1; i > 0; --i) {
  2835. int j = crypto_rand_int(i+1);
  2836. smartlist_swap(sl, i, j);
  2837. }
  2838. }
  2839. /**
  2840. * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
  2841. * the value <b>byte</b>.
  2842. * If <b>mem</b> is NULL or <b>sz</b> is zero, nothing happens.
  2843. *
  2844. * This function is preferable to memset, since many compilers will happily
  2845. * optimize out memset() when they can convince themselves that the data being
  2846. * cleared will never be read.
  2847. *
  2848. * Right now, our convention is to use this function when we are wiping data
  2849. * that's about to become inaccessible, such as stack buffers that are about
  2850. * to go out of scope or structures that are about to get freed. (In
  2851. * practice, it appears that the compilers we're currently using will optimize
  2852. * out the memset()s for stack-allocated buffers, but not those for
  2853. * about-to-be-freed structures. That could change, though, so we're being
  2854. * wary.) If there are live reads for the data, then you can just use
  2855. * memset().
  2856. */
  2857. void
  2858. memwipe(void *mem, uint8_t byte, size_t sz)
  2859. {
  2860. if (sz == 0) {
  2861. return;
  2862. }
  2863. /* If sz is nonzero, then mem must not be NULL. */
  2864. tor_assert(mem != NULL);
  2865. /* Data this large is likely to be an underflow. */
  2866. tor_assert(sz < SIZE_T_CEILING);
  2867. /* Because whole-program-optimization exists, we may not be able to just
  2868. * have this function call "memset". A smart compiler could inline it, then
  2869. * eliminate dead memsets, and declare itself to be clever. */
  2870. #if defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY)
  2871. /* Here's what you do on windows. */
  2872. SecureZeroMemory(mem,sz);
  2873. #elif defined(HAVE_RTLSECUREZEROMEMORY)
  2874. RtlSecureZeroMemory(mem,sz);
  2875. #elif defined(HAVE_EXPLICIT_BZERO)
  2876. /* The BSDs provide this. */
  2877. explicit_bzero(mem, sz);
  2878. #elif defined(HAVE_MEMSET_S)
  2879. /* This is in the C99 standard. */
  2880. memset_s(mem, sz, 0, sz);
  2881. #else
  2882. /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
  2883. * based on the pointer value, then uses that junk to update a global
  2884. * variable. It's an elaborate ruse to trick the compiler into not
  2885. * optimizing out the "wipe this memory" code. Read it if you like zany
  2886. * programming tricks! In later versions of Tor, we should look for better
  2887. * not-optimized-out memory wiping stuff...
  2888. *
  2889. * ...or maybe not. In practice, there are pure-asm implementations of
  2890. * OPENSSL_cleanse() on most platforms, which ought to do the job.
  2891. **/
  2892. OPENSSL_cleanse(mem, sz);
  2893. #endif /* defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY) || ... */
  2894. /* Just in case some caller of memwipe() is relying on getting a buffer
  2895. * filled with a particular value, fill the buffer.
  2896. *
  2897. * If this function gets inlined, this memset might get eliminated, but
  2898. * that's okay: We only care about this particular memset in the case where
  2899. * the caller should have been using memset(), and the memset() wouldn't get
  2900. * eliminated. In other words, this is here so that we won't break anything
  2901. * if somebody accidentally calls memwipe() instead of memset().
  2902. **/
  2903. memset(mem, byte, sz);
  2904. }
  2905. #if 0
  2906. /* This code is disabled, because OpenSSL never actually uses these callbacks.
  2907. */
  2908. /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
  2909. * as a lock. */
  2910. struct CRYPTO_dynlock_value {
  2911. tor_mutex_t *lock;
  2912. };
  2913. /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
  2914. * documentation in OpenSSL's docs for more info. */
  2915. static struct CRYPTO_dynlock_value *
  2916. openssl_dynlock_create_cb_(const char *file, int line)
  2917. {
  2918. struct CRYPTO_dynlock_value *v;
  2919. (void)file;
  2920. (void)line;
  2921. v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
  2922. v->lock = tor_mutex_new();
  2923. return v;
  2924. }
  2925. /** OpenSSL callback function to acquire or release a lock: see
  2926. * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
  2927. static void
  2928. openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
  2929. const char *file, int line)
  2930. {
  2931. (void)file;
  2932. (void)line;
  2933. if (mode & CRYPTO_LOCK)
  2934. tor_mutex_acquire(v->lock);
  2935. else
  2936. tor_mutex_release(v->lock);
  2937. }
  2938. /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
  2939. * documentation in OpenSSL's docs for more info. */
  2940. static void
  2941. openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
  2942. const char *file, int line)
  2943. {
  2944. (void)file;
  2945. (void)line;
  2946. tor_mutex_free(v->lock);
  2947. tor_free(v);
  2948. }
  2949. #endif /* 0 */
  2950. /** @{ */
  2951. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  2952. * failure.
  2953. */
  2954. int
  2955. crypto_global_cleanup(void)
  2956. {
  2957. EVP_cleanup();
  2958. #ifndef NEW_THREAD_API
  2959. ERR_remove_thread_state(NULL);
  2960. #endif
  2961. ERR_free_strings();
  2962. if (dh_param_p)
  2963. BN_clear_free(dh_param_p);
  2964. if (dh_param_p_tls)
  2965. BN_clear_free(dh_param_p_tls);
  2966. if (dh_param_g)
  2967. BN_clear_free(dh_param_g);
  2968. #ifndef DISABLE_ENGINES
  2969. ENGINE_cleanup();
  2970. #endif
  2971. CONF_modules_unload(1);
  2972. CRYPTO_cleanup_all_ex_data();
  2973. #ifndef NEW_THREAD_API
  2974. if (n_openssl_mutexes_) {
  2975. int n = n_openssl_mutexes_;
  2976. tor_mutex_t **ms = openssl_mutexes_;
  2977. int i;
  2978. openssl_mutexes_ = NULL;
  2979. n_openssl_mutexes_ = 0;
  2980. for (i=0;i<n;++i) {
  2981. tor_mutex_free(ms[i]);
  2982. }
  2983. tor_free(ms);
  2984. }
  2985. #endif /* !defined(NEW_THREAD_API) */
  2986. free_openssl();
  2987. return 0;
  2988. }
  2989. /** @} */
  2990. #ifdef USE_DMALLOC
  2991. /** Tell the crypto library to use Tor's allocation functions rather than
  2992. * calling libc's allocation functions directly. Return 0 on success, -1
  2993. * on failure. */
  2994. int
  2995. crypto_use_tor_alloc_functions(void)
  2996. {
  2997. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  2998. return r ? 0 : -1;
  2999. }
  3000. #endif /* defined(USE_DMALLOC) */