crypto.c 94 KB

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