crypto.c 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407
  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-2016, 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
  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
  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. #include "torlog.h"
  62. #include "torint.h"
  63. #include "aes.h"
  64. #include "util.h"
  65. #include "container.h"
  66. #include "compat.h"
  67. #include "sandbox.h"
  68. #include "util_format.h"
  69. #include "keccak-tiny/keccak-tiny.h"
  70. #ifdef ANDROID
  71. /* Android's OpenSSL seems to have removed all of its Engine support. */
  72. #define DISABLE_ENGINES
  73. #endif
  74. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5) && \
  75. !defined(LIBRESSL_VERSION_NUMBER)
  76. /* OpenSSL as of 1.1.0pre4 has an "new" thread API, which doesn't require
  77. * seting up various callbacks.
  78. *
  79. * OpenSSL 1.1.0pre4 has a messed up `ERR_remove_thread_state()` prototype,
  80. * while the previous one was restored in pre5, and the function made a no-op
  81. * (along with a deprecated annotation, which produces a compiler warning).
  82. *
  83. * While it is possible to support all three versions of the thread API,
  84. * a version that existed only for one snapshot pre-release is kind of
  85. * pointless, so let's not.
  86. */
  87. #define NEW_THREAD_API
  88. #endif
  89. /** Longest recognized */
  90. #define MAX_DNS_LABEL_SIZE 63
  91. /** Largest strong entropy request */
  92. #define MAX_STRONGEST_RAND_SIZE 256
  93. #ifndef NEW_THREAD_API
  94. /** A number of preallocated mutexes for use by OpenSSL. */
  95. static tor_mutex_t **openssl_mutexes_ = NULL;
  96. /** How many mutexes have we allocated for use by OpenSSL? */
  97. static int n_openssl_mutexes_ = 0;
  98. #endif
  99. /** A public key, or a public/private key-pair. */
  100. struct crypto_pk_t
  101. {
  102. int refs; /**< reference count, so we don't have to copy keys */
  103. RSA *key; /**< The key itself */
  104. };
  105. /** Key and stream information for a stream cipher. */
  106. struct crypto_cipher_t
  107. {
  108. aes_cnt_cipher_t *cipher; /**< The key in format usable for counter-mode AES
  109. * encryption */
  110. };
  111. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  112. * while we're waiting for the second.*/
  113. struct crypto_dh_t {
  114. DH *dh; /**< The openssl DH object */
  115. };
  116. static int setup_openssl_threading(void);
  117. static int tor_check_dh_key(int severity, const BIGNUM *bn);
  118. /** Return the number of bytes added by padding method <b>padding</b>.
  119. */
  120. static inline int
  121. crypto_get_rsa_padding_overhead(int padding)
  122. {
  123. switch (padding)
  124. {
  125. case RSA_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
  126. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  127. }
  128. }
  129. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  130. */
  131. static inline int
  132. crypto_get_rsa_padding(int padding)
  133. {
  134. switch (padding)
  135. {
  136. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  137. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  138. }
  139. }
  140. /** Boolean: has OpenSSL's crypto been initialized? */
  141. static int crypto_early_initialized_ = 0;
  142. /** Boolean: has OpenSSL's crypto been initialized? */
  143. static int crypto_global_initialized_ = 0;
  144. /** Log all pending crypto errors at level <b>severity</b>. Use
  145. * <b>doing</b> to describe our current activities.
  146. */
  147. static void
  148. crypto_log_errors(int severity, const char *doing)
  149. {
  150. unsigned long err;
  151. const char *msg, *lib, *func;
  152. while ((err = ERR_get_error()) != 0) {
  153. msg = (const char*)ERR_reason_error_string(err);
  154. lib = (const char*)ERR_lib_error_string(err);
  155. func = (const char*)ERR_func_error_string(err);
  156. if (!msg) msg = "(null)";
  157. if (!lib) lib = "(null)";
  158. if (!func) func = "(null)";
  159. if (BUG(!doing)) doing = "(null)";
  160. tor_log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  161. doing, msg, lib, func);
  162. }
  163. }
  164. #ifndef DISABLE_ENGINES
  165. /** Log any OpenSSL engines we're using at NOTICE. */
  166. static void
  167. log_engine(const char *fn, ENGINE *e)
  168. {
  169. if (e) {
  170. const char *name, *id;
  171. name = ENGINE_get_name(e);
  172. id = ENGINE_get_id(e);
  173. log_notice(LD_CRYPTO, "Default OpenSSL engine for %s is %s [%s]",
  174. fn, name?name:"?", id?id:"?");
  175. } else {
  176. log_info(LD_CRYPTO, "Using default implementation for %s", fn);
  177. }
  178. }
  179. #endif
  180. #ifndef DISABLE_ENGINES
  181. /** Try to load an engine in a shared library via fully qualified path.
  182. */
  183. static ENGINE *
  184. try_load_engine(const char *path, const char *engine)
  185. {
  186. ENGINE *e = ENGINE_by_id("dynamic");
  187. if (e) {
  188. if (!ENGINE_ctrl_cmd_string(e, "ID", engine, 0) ||
  189. !ENGINE_ctrl_cmd_string(e, "DIR_LOAD", "2", 0) ||
  190. !ENGINE_ctrl_cmd_string(e, "DIR_ADD", path, 0) ||
  191. !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
  192. ENGINE_free(e);
  193. e = NULL;
  194. }
  195. }
  196. return e;
  197. }
  198. #endif
  199. /* Returns a trimmed and human-readable version of an openssl version string
  200. * <b>raw_version</b>. They are usually in the form of 'OpenSSL 1.0.0b 10
  201. * May 2012' and this will parse them into a form similar to '1.0.0b' */
  202. static char *
  203. parse_openssl_version_str(const char *raw_version)
  204. {
  205. const char *end_of_version = NULL;
  206. /* The output should be something like "OpenSSL 1.0.0b 10 May 2012. Let's
  207. trim that down. */
  208. if (!strcmpstart(raw_version, "OpenSSL ")) {
  209. raw_version += strlen("OpenSSL ");
  210. end_of_version = strchr(raw_version, ' ');
  211. }
  212. if (end_of_version)
  213. return tor_strndup(raw_version,
  214. end_of_version-raw_version);
  215. else
  216. return tor_strdup(raw_version);
  217. }
  218. static char *crypto_openssl_version_str = NULL;
  219. /* Return a human-readable version of the run-time openssl version number. */
  220. const char *
  221. crypto_openssl_get_version_str(void)
  222. {
  223. if (crypto_openssl_version_str == NULL) {
  224. const char *raw_version = OpenSSL_version(OPENSSL_VERSION);
  225. crypto_openssl_version_str = parse_openssl_version_str(raw_version);
  226. }
  227. return crypto_openssl_version_str;
  228. }
  229. static char *crypto_openssl_header_version_str = NULL;
  230. /* Return a human-readable version of the compile-time openssl version
  231. * number. */
  232. const char *
  233. crypto_openssl_get_header_version_str(void)
  234. {
  235. if (crypto_openssl_header_version_str == NULL) {
  236. crypto_openssl_header_version_str =
  237. parse_openssl_version_str(OPENSSL_VERSION_TEXT);
  238. }
  239. return crypto_openssl_header_version_str;
  240. }
  241. /** Make sure that openssl is using its default PRNG. Return 1 if we had to
  242. * adjust it; 0 otherwise. */
  243. STATIC int
  244. crypto_force_rand_ssleay(void)
  245. {
  246. RAND_METHOD *default_method;
  247. default_method = RAND_OpenSSL();
  248. if (RAND_get_rand_method() != default_method) {
  249. log_notice(LD_CRYPTO, "It appears that one of our engines has provided "
  250. "a replacement the OpenSSL RNG. Resetting it to the default "
  251. "implementation.");
  252. RAND_set_rand_method(default_method);
  253. return 1;
  254. }
  255. return 0;
  256. }
  257. /** Set up the siphash key if we haven't already done so. */
  258. int
  259. crypto_init_siphash_key(void)
  260. {
  261. static int have_seeded_siphash = 0;
  262. struct sipkey key;
  263. if (have_seeded_siphash)
  264. return 0;
  265. crypto_rand((char*) &key, sizeof(key));
  266. siphash_set_global_key(&key);
  267. have_seeded_siphash = 1;
  268. return 0;
  269. }
  270. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  271. */
  272. int
  273. crypto_early_init(void)
  274. {
  275. if (!crypto_early_initialized_) {
  276. crypto_early_initialized_ = 1;
  277. ERR_load_crypto_strings();
  278. OpenSSL_add_all_algorithms();
  279. setup_openssl_threading();
  280. unsigned long version_num = OpenSSL_version_num();
  281. const char *version_str = OpenSSL_version(OPENSSL_VERSION);
  282. if (version_num == OPENSSL_VERSION_NUMBER &&
  283. !strcmp(version_str, OPENSSL_VERSION_TEXT)) {
  284. log_info(LD_CRYPTO, "OpenSSL version matches version from headers "
  285. "(%lx: %s).", version_num, version_str);
  286. } else {
  287. log_warn(LD_CRYPTO, "OpenSSL version from headers does not match the "
  288. "version we're running with. If you get weird crashes, that "
  289. "might be why. (Compiled with %lx: %s; running with %lx: %s).",
  290. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  291. version_num, version_str);
  292. }
  293. crypto_force_rand_ssleay();
  294. if (crypto_seed_rng() < 0)
  295. return -1;
  296. if (crypto_init_siphash_key() < 0)
  297. return -1;
  298. curve25519_init();
  299. ed25519_init();
  300. }
  301. return 0;
  302. }
  303. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  304. */
  305. int
  306. crypto_global_init(int useAccel, const char *accelName, const char *accelDir)
  307. {
  308. if (!crypto_global_initialized_) {
  309. if (crypto_early_init() < 0)
  310. return -1;
  311. crypto_global_initialized_ = 1;
  312. if (useAccel > 0) {
  313. #ifdef DISABLE_ENGINES
  314. (void)accelName;
  315. (void)accelDir;
  316. log_warn(LD_CRYPTO, "No OpenSSL hardware acceleration support enabled.");
  317. #else
  318. ENGINE *e = NULL;
  319. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  320. ENGINE_load_builtin_engines();
  321. ENGINE_register_all_complete();
  322. if (accelName) {
  323. if (accelDir) {
  324. log_info(LD_CRYPTO, "Trying to load dynamic OpenSSL engine \"%s\""
  325. " via path \"%s\".", accelName, accelDir);
  326. e = try_load_engine(accelName, accelDir);
  327. } else {
  328. log_info(LD_CRYPTO, "Initializing dynamic OpenSSL engine \"%s\""
  329. " acceleration support.", accelName);
  330. e = ENGINE_by_id(accelName);
  331. }
  332. if (!e) {
  333. log_warn(LD_CRYPTO, "Unable to load dynamic OpenSSL engine \"%s\".",
  334. accelName);
  335. } else {
  336. log_info(LD_CRYPTO, "Loaded dynamic OpenSSL engine \"%s\".",
  337. accelName);
  338. }
  339. }
  340. if (e) {
  341. log_info(LD_CRYPTO, "Loaded OpenSSL hardware acceleration engine,"
  342. " setting default ciphers.");
  343. ENGINE_set_default(e, ENGINE_METHOD_ALL);
  344. }
  345. /* Log, if available, the intersection of the set of algorithms
  346. used by Tor and the set of algorithms available in the engine */
  347. log_engine("RSA", ENGINE_get_default_RSA());
  348. log_engine("DH", ENGINE_get_default_DH());
  349. #ifdef OPENSSL_1_1_API
  350. log_engine("EC", ENGINE_get_default_EC());
  351. #else
  352. log_engine("ECDH", ENGINE_get_default_ECDH());
  353. log_engine("ECDSA", ENGINE_get_default_ECDSA());
  354. #endif
  355. log_engine("RAND", ENGINE_get_default_RAND());
  356. log_engine("RAND (which we will not use)", ENGINE_get_default_RAND());
  357. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  358. log_engine("3DES-CBC", ENGINE_get_cipher_engine(NID_des_ede3_cbc));
  359. log_engine("AES-128-ECB", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  360. log_engine("AES-128-CBC", ENGINE_get_cipher_engine(NID_aes_128_cbc));
  361. #ifdef NID_aes_128_ctr
  362. log_engine("AES-128-CTR", ENGINE_get_cipher_engine(NID_aes_128_ctr));
  363. #endif
  364. #ifdef NID_aes_128_gcm
  365. log_engine("AES-128-GCM", ENGINE_get_cipher_engine(NID_aes_128_gcm));
  366. #endif
  367. log_engine("AES-256-CBC", ENGINE_get_cipher_engine(NID_aes_256_cbc));
  368. #ifdef NID_aes_256_gcm
  369. log_engine("AES-256-GCM", ENGINE_get_cipher_engine(NID_aes_256_gcm));
  370. #endif
  371. #endif
  372. } else {
  373. log_info(LD_CRYPTO, "NOT using OpenSSL engine support.");
  374. }
  375. if (crypto_force_rand_ssleay()) {
  376. if (crypto_seed_rng() < 0)
  377. return -1;
  378. }
  379. evaluate_evp_for_aes(-1);
  380. evaluate_ctr_for_aes();
  381. }
  382. return 0;
  383. }
  384. /** Free crypto resources held by this thread. */
  385. void
  386. crypto_thread_cleanup(void)
  387. {
  388. #ifndef NEW_THREAD_API
  389. ERR_remove_thread_state(NULL);
  390. #endif
  391. }
  392. /** used internally: quicly validate a crypto_pk_t object as a private key.
  393. * Return 1 iff the public key is valid, 0 if obviously invalid.
  394. */
  395. static int
  396. crypto_pk_private_ok(const crypto_pk_t *k)
  397. {
  398. #ifdef OPENSSL_1_1_API
  399. if (!k || !k->key)
  400. return 0;
  401. const BIGNUM *p, *q;
  402. RSA_get0_factors(k->key, &p, &q);
  403. return p != NULL; /* XXX/yawning: Should we check q? */
  404. #else
  405. return k && k->key && k->key->p;
  406. #endif
  407. }
  408. /** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
  409. crypto_pk_t *
  410. crypto_new_pk_from_rsa_(RSA *rsa)
  411. {
  412. crypto_pk_t *env;
  413. tor_assert(rsa);
  414. env = tor_malloc(sizeof(crypto_pk_t));
  415. env->refs = 1;
  416. env->key = rsa;
  417. return env;
  418. }
  419. /** Helper, used by tor-checkkey.c and tor-gencert.c. Return the RSA from a
  420. * crypto_pk_t. */
  421. RSA *
  422. crypto_pk_get_rsa_(crypto_pk_t *env)
  423. {
  424. return env->key;
  425. }
  426. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
  427. * private is set, include the private-key portion of the key. Return a valid
  428. * pointer on success, and NULL on failure. */
  429. MOCK_IMPL(EVP_PKEY *,
  430. crypto_pk_get_evp_pkey_,(crypto_pk_t *env, int private))
  431. {
  432. RSA *key = NULL;
  433. EVP_PKEY *pkey = NULL;
  434. tor_assert(env->key);
  435. if (private) {
  436. if (!(key = RSAPrivateKey_dup(env->key)))
  437. goto error;
  438. } else {
  439. if (!(key = RSAPublicKey_dup(env->key)))
  440. goto error;
  441. }
  442. if (!(pkey = EVP_PKEY_new()))
  443. goto error;
  444. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  445. goto error;
  446. return pkey;
  447. error:
  448. if (pkey)
  449. EVP_PKEY_free(pkey);
  450. if (key)
  451. RSA_free(key);
  452. return NULL;
  453. }
  454. /** Used by tortls.c: Get the DH* from a crypto_dh_t.
  455. */
  456. DH *
  457. crypto_dh_get_dh_(crypto_dh_t *dh)
  458. {
  459. return dh->dh;
  460. }
  461. /** Allocate and return storage for a public key. The key itself will not yet
  462. * be set.
  463. */
  464. MOCK_IMPL(crypto_pk_t *,
  465. crypto_pk_new,(void))
  466. {
  467. RSA *rsa;
  468. rsa = RSA_new();
  469. tor_assert(rsa);
  470. return crypto_new_pk_from_rsa_(rsa);
  471. }
  472. /** Release a reference to an asymmetric key; when all the references
  473. * are released, free the key.
  474. */
  475. void
  476. crypto_pk_free(crypto_pk_t *env)
  477. {
  478. if (!env)
  479. return;
  480. if (--env->refs > 0)
  481. return;
  482. tor_assert(env->refs == 0);
  483. if (env->key)
  484. RSA_free(env->key);
  485. tor_free(env);
  486. }
  487. /** Allocate and return a new symmetric cipher using the provided key and iv.
  488. * The key is CIPHER_KEY_LEN bytes; the IV is CIPHER_IV_LEN bytes. Both
  489. * must be provided.
  490. */
  491. crypto_cipher_t *
  492. crypto_cipher_new_with_iv(const char *key, const char *iv)
  493. {
  494. crypto_cipher_t *env;
  495. tor_assert(key);
  496. tor_assert(iv);
  497. env = tor_malloc(sizeof(crypto_cipher_t));
  498. env->cipher = aes_new_cipher((const uint8_t*)key, (const uint8_t*)iv, 128);
  499. return env;
  500. }
  501. /** Return a new crypto_cipher_t with the provided <b>key</b> and an IV of all
  502. * zero bytes. */
  503. crypto_cipher_t *
  504. crypto_cipher_new(const char *key)
  505. {
  506. char zeroiv[CIPHER_IV_LEN];
  507. memset(zeroiv, 0, sizeof(zeroiv));
  508. return crypto_cipher_new_with_iv(key, zeroiv);
  509. }
  510. /** Free a symmetric cipher.
  511. */
  512. void
  513. crypto_cipher_free(crypto_cipher_t *env)
  514. {
  515. if (!env)
  516. return;
  517. tor_assert(env->cipher);
  518. aes_cipher_free(env->cipher);
  519. memwipe(env, 0, sizeof(crypto_cipher_t));
  520. tor_free(env);
  521. }
  522. /* public key crypto */
  523. /** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
  524. * Return 0 on success, -1 on failure.
  525. */
  526. MOCK_IMPL(int,
  527. crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
  528. {
  529. tor_assert(env);
  530. if (env->key) {
  531. RSA_free(env->key);
  532. env->key = NULL;
  533. }
  534. {
  535. BIGNUM *e = BN_new();
  536. RSA *r = NULL;
  537. if (!e)
  538. goto done;
  539. if (! BN_set_word(e, 65537))
  540. goto done;
  541. r = RSA_new();
  542. if (!r)
  543. goto done;
  544. if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
  545. goto done;
  546. env->key = r;
  547. r = NULL;
  548. done:
  549. if (e)
  550. BN_clear_free(e);
  551. if (r)
  552. RSA_free(r);
  553. }
  554. if (!env->key) {
  555. crypto_log_errors(LOG_WARN, "generating RSA key");
  556. return -1;
  557. }
  558. return 0;
  559. }
  560. /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
  561. * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
  562. * the string is nul-terminated.
  563. */
  564. /* Used here, and used for testing. */
  565. int
  566. crypto_pk_read_private_key_from_string(crypto_pk_t *env,
  567. const char *s, ssize_t len)
  568. {
  569. BIO *b;
  570. tor_assert(env);
  571. tor_assert(s);
  572. tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
  573. /* Create a read-only memory BIO, backed by the string 's' */
  574. b = BIO_new_mem_buf((char*)s, (int)len);
  575. if (!b)
  576. return -1;
  577. if (env->key)
  578. RSA_free(env->key);
  579. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
  580. BIO_free(b);
  581. if (!env->key) {
  582. crypto_log_errors(LOG_WARN, "Error parsing private key");
  583. return -1;
  584. }
  585. return 0;
  586. }
  587. /** Read a PEM-encoded private key from the file named by
  588. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  589. */
  590. int
  591. crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
  592. const char *keyfile)
  593. {
  594. char *contents;
  595. int r;
  596. /* Read the file into a string. */
  597. contents = read_file_to_str(keyfile, 0, NULL);
  598. if (!contents) {
  599. log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
  600. return -1;
  601. }
  602. /* Try to parse it. */
  603. r = crypto_pk_read_private_key_from_string(env, contents, -1);
  604. memwipe(contents, 0, strlen(contents));
  605. tor_free(contents);
  606. if (r)
  607. return -1; /* read_private_key_from_string already warned, so we don't.*/
  608. /* Make sure it's valid. */
  609. if (crypto_pk_check_key(env) <= 0)
  610. return -1;
  611. return 0;
  612. }
  613. /** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
  614. * success, -1 on failure. */
  615. static int
  616. crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
  617. size_t *len, int is_public)
  618. {
  619. BUF_MEM *buf;
  620. BIO *b;
  621. int r;
  622. tor_assert(env);
  623. tor_assert(env->key);
  624. tor_assert(dest);
  625. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  626. if (!b)
  627. return -1;
  628. /* Now you can treat b as if it were a file. Just use the
  629. * PEM_*_bio_* functions instead of the non-bio variants.
  630. */
  631. if (is_public)
  632. r = PEM_write_bio_RSAPublicKey(b, env->key);
  633. else
  634. r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
  635. if (!r) {
  636. crypto_log_errors(LOG_WARN, "writing RSA key to string");
  637. BIO_free(b);
  638. return -1;
  639. }
  640. BIO_get_mem_ptr(b, &buf);
  641. (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  642. BIO_free(b);
  643. *dest = tor_malloc(buf->length+1);
  644. memcpy(*dest, buf->data, buf->length);
  645. (*dest)[buf->length] = 0; /* nul terminate it */
  646. *len = buf->length;
  647. BUF_MEM_free(buf);
  648. return 0;
  649. }
  650. /** PEM-encode the public key portion of <b>env</b> and write it to a
  651. * newly allocated string. On success, set *<b>dest</b> to the new
  652. * string, *<b>len</b> to the string's length, and return 0. On
  653. * failure, return -1.
  654. */
  655. int
  656. crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
  657. size_t *len)
  658. {
  659. return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
  660. }
  661. /** PEM-encode the private key portion of <b>env</b> and write it to a
  662. * newly allocated string. On success, set *<b>dest</b> to the new
  663. * string, *<b>len</b> to the string's length, and return 0. On
  664. * failure, return -1.
  665. */
  666. int
  667. crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
  668. size_t *len)
  669. {
  670. return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
  671. }
  672. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  673. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  674. * failure.
  675. */
  676. int
  677. crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
  678. size_t len)
  679. {
  680. BIO *b;
  681. tor_assert(env);
  682. tor_assert(src);
  683. tor_assert(len<INT_MAX);
  684. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  685. if (!b)
  686. return -1;
  687. BIO_write(b, src, (int)len);
  688. if (env->key)
  689. RSA_free(env->key);
  690. env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  691. BIO_free(b);
  692. if (!env->key) {
  693. crypto_log_errors(LOG_WARN, "reading public key from string");
  694. return -1;
  695. }
  696. return 0;
  697. }
  698. /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
  699. * PEM-encoded. Return 0 on success, -1 on failure.
  700. */
  701. int
  702. crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
  703. const char *fname)
  704. {
  705. BIO *bio;
  706. char *cp;
  707. long len;
  708. char *s;
  709. int r;
  710. tor_assert(crypto_pk_private_ok(env));
  711. if (!(bio = BIO_new(BIO_s_mem())))
  712. return -1;
  713. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  714. == 0) {
  715. crypto_log_errors(LOG_WARN, "writing private key");
  716. BIO_free(bio);
  717. return -1;
  718. }
  719. len = BIO_get_mem_data(bio, &cp);
  720. tor_assert(len >= 0);
  721. s = tor_malloc(len+1);
  722. memcpy(s, cp, len);
  723. s[len]='\0';
  724. r = write_str_to_file(fname, s, 0);
  725. BIO_free(bio);
  726. memwipe(s, 0, strlen(s));
  727. tor_free(s);
  728. return r;
  729. }
  730. /** Return true iff <b>env</b> has a valid key.
  731. */
  732. int
  733. crypto_pk_check_key(crypto_pk_t *env)
  734. {
  735. int r;
  736. tor_assert(env);
  737. r = RSA_check_key(env->key);
  738. if (r <= 0)
  739. crypto_log_errors(LOG_WARN,"checking RSA key");
  740. return r;
  741. }
  742. /** Return true iff <b>key</b> contains the private-key portion of the RSA
  743. * key. */
  744. int
  745. crypto_pk_key_is_private(const crypto_pk_t *key)
  746. {
  747. tor_assert(key);
  748. return crypto_pk_private_ok(key);
  749. }
  750. /** Return true iff <b>env</b> contains a public key whose public exponent
  751. * equals 65537.
  752. */
  753. int
  754. crypto_pk_public_exponent_ok(crypto_pk_t *env)
  755. {
  756. tor_assert(env);
  757. tor_assert(env->key);
  758. const BIGNUM *e;
  759. #ifdef OPENSSL_1_1_API
  760. const BIGNUM *n, *d;
  761. RSA_get0_key(env->key, &n, &e, &d);
  762. #else
  763. e = env->key->e;
  764. #endif
  765. return BN_is_word(e, 65537);
  766. }
  767. /** Compare the public-key components of a and b. Return less than 0
  768. * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
  769. * considered to be less than all non-NULL keys, and equal to itself.
  770. *
  771. * Note that this may leak information about the keys through timing.
  772. */
  773. int
  774. crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  775. {
  776. int result;
  777. char a_is_non_null = (a != NULL) && (a->key != NULL);
  778. char b_is_non_null = (b != NULL) && (b->key != NULL);
  779. char an_argument_is_null = !a_is_non_null | !b_is_non_null;
  780. result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
  781. if (an_argument_is_null)
  782. return result;
  783. const BIGNUM *a_n, *a_e;
  784. const BIGNUM *b_n, *b_e;
  785. #ifdef OPENSSL_1_1_API
  786. const BIGNUM *a_d, *b_d;
  787. RSA_get0_key(a->key, &a_n, &a_e, &a_d);
  788. RSA_get0_key(b->key, &b_n, &b_e, &b_d);
  789. #else
  790. a_n = a->key->n;
  791. a_e = a->key->e;
  792. b_n = b->key->n;
  793. b_e = b->key->e;
  794. #endif
  795. tor_assert(a_n != NULL && a_e != NULL);
  796. tor_assert(b_n != NULL && b_e != NULL);
  797. result = BN_cmp(a_n, b_n);
  798. if (result)
  799. return result;
  800. return BN_cmp(a_e, b_e);
  801. }
  802. /** Compare the public-key components of a and b. Return non-zero iff
  803. * a==b. A NULL key is considered to be distinct from all non-NULL
  804. * keys, and equal to itself.
  805. *
  806. * Note that this may leak information about the keys through timing.
  807. */
  808. int
  809. crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  810. {
  811. return (crypto_pk_cmp_keys(a, b) == 0);
  812. }
  813. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  814. size_t
  815. crypto_pk_keysize(const crypto_pk_t *env)
  816. {
  817. tor_assert(env);
  818. tor_assert(env->key);
  819. return (size_t) RSA_size((RSA*)env->key);
  820. }
  821. /** Return the size of the public key modulus of <b>env</b>, in bits. */
  822. int
  823. crypto_pk_num_bits(crypto_pk_t *env)
  824. {
  825. tor_assert(env);
  826. tor_assert(env->key);
  827. #ifdef OPENSSL_1_1_API
  828. /* It's so stupid that there's no other way to check that n is valid
  829. * before calling RSA_bits().
  830. */
  831. const BIGNUM *n, *e, *d;
  832. RSA_get0_key(env->key, &n, &e, &d);
  833. tor_assert(n != NULL);
  834. return RSA_bits(env->key);
  835. #else
  836. tor_assert(env->key->n);
  837. return BN_num_bits(env->key->n);
  838. #endif
  839. }
  840. /** Increase the reference count of <b>env</b>, and return it.
  841. */
  842. crypto_pk_t *
  843. crypto_pk_dup_key(crypto_pk_t *env)
  844. {
  845. tor_assert(env);
  846. tor_assert(env->key);
  847. env->refs++;
  848. return env;
  849. }
  850. #ifdef TOR_UNIT_TESTS
  851. /** For testing: replace dest with src. (Dest must have a refcount
  852. * of 1) */
  853. void
  854. crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src)
  855. {
  856. tor_assert(dest);
  857. tor_assert(dest->refs == 1);
  858. tor_assert(src);
  859. RSA_free(dest->key);
  860. dest->key = RSAPrivateKey_dup(src->key);
  861. }
  862. #endif
  863. /** Make a real honest-to-goodness copy of <b>env</b>, and return it.
  864. * Returns NULL on failure. */
  865. crypto_pk_t *
  866. crypto_pk_copy_full(crypto_pk_t *env)
  867. {
  868. RSA *new_key;
  869. int privatekey = 0;
  870. tor_assert(env);
  871. tor_assert(env->key);
  872. if (crypto_pk_private_ok(env)) {
  873. new_key = RSAPrivateKey_dup(env->key);
  874. privatekey = 1;
  875. } else {
  876. new_key = RSAPublicKey_dup(env->key);
  877. }
  878. if (!new_key) {
  879. /* LCOV_EXCL_START
  880. *
  881. * We can't cause RSA*Key_dup() to fail, so we can't really test this.
  882. */
  883. log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
  884. privatekey?"private":"public");
  885. crypto_log_errors(LOG_ERR,
  886. privatekey ? "Duplicating a private key" :
  887. "Duplicating a public key");
  888. tor_fragile_assert();
  889. return NULL;
  890. /* LCOV_EXCL_STOP */
  891. }
  892. return crypto_new_pk_from_rsa_(new_key);
  893. }
  894. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  895. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  896. * write the result to <b>to</b>, and return the number of bytes
  897. * written. On failure, return -1.
  898. *
  899. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  900. * at least the length of the modulus of <b>env</b>.
  901. */
  902. int
  903. crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
  904. const char *from, size_t fromlen, int padding)
  905. {
  906. int r;
  907. tor_assert(env);
  908. tor_assert(from);
  909. tor_assert(to);
  910. tor_assert(fromlen<INT_MAX);
  911. tor_assert(tolen >= crypto_pk_keysize(env));
  912. r = RSA_public_encrypt((int)fromlen,
  913. (unsigned char*)from, (unsigned char*)to,
  914. env->key, crypto_get_rsa_padding(padding));
  915. if (r<0) {
  916. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  917. return -1;
  918. }
  919. return r;
  920. }
  921. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  922. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  923. * write the result to <b>to</b>, and return the number of bytes
  924. * written. On failure, return -1.
  925. *
  926. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  927. * at least the length of the modulus of <b>env</b>.
  928. */
  929. int
  930. crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
  931. size_t tolen,
  932. const char *from, size_t fromlen,
  933. int padding, int warnOnFailure)
  934. {
  935. int r;
  936. tor_assert(env);
  937. tor_assert(from);
  938. tor_assert(to);
  939. tor_assert(env->key);
  940. tor_assert(fromlen<INT_MAX);
  941. tor_assert(tolen >= crypto_pk_keysize(env));
  942. if (!crypto_pk_key_is_private(env))
  943. /* Not a private key */
  944. return -1;
  945. r = RSA_private_decrypt((int)fromlen,
  946. (unsigned char*)from, (unsigned char*)to,
  947. env->key, crypto_get_rsa_padding(padding));
  948. if (r<0) {
  949. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  950. "performing RSA decryption");
  951. return -1;
  952. }
  953. return r;
  954. }
  955. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  956. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  957. * signed data to <b>to</b>, and return the number of bytes written.
  958. * On failure, return -1.
  959. *
  960. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  961. * at least the length of the modulus of <b>env</b>.
  962. */
  963. int
  964. crypto_pk_public_checksig(const crypto_pk_t *env, char *to,
  965. size_t tolen,
  966. const char *from, size_t fromlen)
  967. {
  968. int r;
  969. tor_assert(env);
  970. tor_assert(from);
  971. tor_assert(to);
  972. tor_assert(fromlen < INT_MAX);
  973. tor_assert(tolen >= crypto_pk_keysize(env));
  974. r = RSA_public_decrypt((int)fromlen,
  975. (unsigned char*)from, (unsigned char*)to,
  976. env->key, RSA_PKCS1_PADDING);
  977. if (r<0) {
  978. crypto_log_errors(LOG_INFO, "checking RSA signature");
  979. return -1;
  980. }
  981. return r;
  982. }
  983. /** Check a siglen-byte long signature at <b>sig</b> against
  984. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  985. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  986. * SHA1(data). Else return -1.
  987. */
  988. int
  989. crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
  990. size_t datalen, const char *sig, size_t siglen)
  991. {
  992. char digest[DIGEST_LEN];
  993. char *buf;
  994. size_t buflen;
  995. int r;
  996. tor_assert(env);
  997. tor_assert(data);
  998. tor_assert(sig);
  999. tor_assert(datalen < SIZE_T_CEILING);
  1000. tor_assert(siglen < SIZE_T_CEILING);
  1001. if (crypto_digest(digest,data,datalen)<0) {
  1002. log_warn(LD_BUG, "couldn't compute digest");
  1003. return -1;
  1004. }
  1005. buflen = crypto_pk_keysize(env);
  1006. buf = tor_malloc(buflen);
  1007. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  1008. if (r != DIGEST_LEN) {
  1009. log_warn(LD_CRYPTO, "Invalid signature");
  1010. tor_free(buf);
  1011. return -1;
  1012. }
  1013. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  1014. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  1015. tor_free(buf);
  1016. return -1;
  1017. }
  1018. tor_free(buf);
  1019. return 0;
  1020. }
  1021. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  1022. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  1023. * <b>to</b>, and return the number of bytes written. On failure, return
  1024. * -1.
  1025. *
  1026. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  1027. * at least the length of the modulus of <b>env</b>.
  1028. */
  1029. int
  1030. crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
  1031. const char *from, size_t fromlen)
  1032. {
  1033. int r;
  1034. tor_assert(env);
  1035. tor_assert(from);
  1036. tor_assert(to);
  1037. tor_assert(fromlen < INT_MAX);
  1038. tor_assert(tolen >= crypto_pk_keysize(env));
  1039. if (!crypto_pk_key_is_private(env))
  1040. /* Not a private key */
  1041. return -1;
  1042. r = RSA_private_encrypt((int)fromlen,
  1043. (unsigned char*)from, (unsigned char*)to,
  1044. (RSA*)env->key, RSA_PKCS1_PADDING);
  1045. if (r<0) {
  1046. crypto_log_errors(LOG_WARN, "generating RSA signature");
  1047. return -1;
  1048. }
  1049. return r;
  1050. }
  1051. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  1052. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  1053. * store it in <b>to</b>. Return the number of bytes written on
  1054. * success, and -1 on failure.
  1055. *
  1056. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  1057. * at least the length of the modulus of <b>env</b>.
  1058. */
  1059. int
  1060. crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
  1061. const char *from, size_t fromlen)
  1062. {
  1063. int r;
  1064. char digest[DIGEST_LEN];
  1065. if (crypto_digest(digest,from,fromlen)<0)
  1066. return -1;
  1067. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  1068. memwipe(digest, 0, sizeof(digest));
  1069. return r;
  1070. }
  1071. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  1072. * bytes of data from <b>from</b>, with padding type 'padding',
  1073. * storing the results on <b>to</b>.
  1074. *
  1075. * Returns the number of bytes written on success, -1 on failure.
  1076. *
  1077. * The encrypted data consists of:
  1078. * - The source data, padded and encrypted with the public key, if the
  1079. * padded source data is no longer than the public key, and <b>force</b>
  1080. * is false, OR
  1081. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  1082. * padded and encrypted with the public key; followed by the rest of
  1083. * the source data encrypted in AES-CTR mode with the symmetric key.
  1084. */
  1085. int
  1086. crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
  1087. char *to, size_t tolen,
  1088. const char *from,
  1089. size_t fromlen,
  1090. int padding, int force)
  1091. {
  1092. int overhead, outlen, r;
  1093. size_t pkeylen, symlen;
  1094. crypto_cipher_t *cipher = NULL;
  1095. char *buf = NULL;
  1096. tor_assert(env);
  1097. tor_assert(from);
  1098. tor_assert(to);
  1099. tor_assert(fromlen < SIZE_T_CEILING);
  1100. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  1101. pkeylen = crypto_pk_keysize(env);
  1102. if (!force && fromlen+overhead <= pkeylen) {
  1103. /* It all fits in a single encrypt. */
  1104. return crypto_pk_public_encrypt(env,to,
  1105. tolen,
  1106. from,fromlen,padding);
  1107. }
  1108. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  1109. tor_assert(tolen >= pkeylen);
  1110. char key[CIPHER_KEY_LEN];
  1111. crypto_rand(key, sizeof(key)); /* generate a new key. */
  1112. cipher = crypto_cipher_new(key);
  1113. buf = tor_malloc(pkeylen+1);
  1114. memcpy(buf, key, CIPHER_KEY_LEN);
  1115. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  1116. /* Length of symmetrically encrypted data. */
  1117. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  1118. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  1119. if (outlen!=(int)pkeylen) {
  1120. goto err;
  1121. }
  1122. r = crypto_cipher_encrypt(cipher, to+outlen,
  1123. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  1124. if (r<0) goto err;
  1125. memwipe(buf, 0, pkeylen);
  1126. memwipe(key, 0, sizeof(key));
  1127. tor_free(buf);
  1128. crypto_cipher_free(cipher);
  1129. tor_assert(outlen+symlen < INT_MAX);
  1130. return (int)(outlen + symlen);
  1131. err:
  1132. memwipe(buf, 0, pkeylen);
  1133. memwipe(key, 0, sizeof(key));
  1134. tor_free(buf);
  1135. crypto_cipher_free(cipher);
  1136. return -1;
  1137. }
  1138. /** Invert crypto_pk_public_hybrid_encrypt. Returns the number of bytes
  1139. * written on success, -1 on failure. */
  1140. int
  1141. crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
  1142. char *to,
  1143. size_t tolen,
  1144. const char *from,
  1145. size_t fromlen,
  1146. int padding, int warnOnFailure)
  1147. {
  1148. int outlen, r;
  1149. size_t pkeylen;
  1150. crypto_cipher_t *cipher = NULL;
  1151. char *buf = NULL;
  1152. tor_assert(fromlen < SIZE_T_CEILING);
  1153. pkeylen = crypto_pk_keysize(env);
  1154. if (fromlen <= pkeylen) {
  1155. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  1156. warnOnFailure);
  1157. }
  1158. buf = tor_malloc(pkeylen);
  1159. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  1160. warnOnFailure);
  1161. if (outlen<0) {
  1162. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  1163. "Error decrypting public-key data");
  1164. goto err;
  1165. }
  1166. if (outlen < CIPHER_KEY_LEN) {
  1167. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  1168. "No room for a symmetric key");
  1169. goto err;
  1170. }
  1171. cipher = crypto_cipher_new(buf);
  1172. if (!cipher) {
  1173. goto err;
  1174. }
  1175. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  1176. outlen -= CIPHER_KEY_LEN;
  1177. tor_assert(tolen - outlen >= fromlen - pkeylen);
  1178. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  1179. if (r<0)
  1180. goto err;
  1181. memwipe(buf,0,pkeylen);
  1182. tor_free(buf);
  1183. crypto_cipher_free(cipher);
  1184. tor_assert(outlen + fromlen < INT_MAX);
  1185. return (int)(outlen + (fromlen-pkeylen));
  1186. err:
  1187. memwipe(buf,0,pkeylen);
  1188. tor_free(buf);
  1189. crypto_cipher_free(cipher);
  1190. return -1;
  1191. }
  1192. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  1193. * Return -1 on error, or the number of characters used on success.
  1194. */
  1195. int
  1196. crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
  1197. {
  1198. int len;
  1199. unsigned char *buf = NULL;
  1200. len = i2d_RSAPublicKey(pk->key, &buf);
  1201. if (len < 0 || buf == NULL)
  1202. return -1;
  1203. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  1204. OPENSSL_free(buf);
  1205. return -1;
  1206. }
  1207. /* We don't encode directly into 'dest', because that would be illegal
  1208. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  1209. */
  1210. memcpy(dest,buf,len);
  1211. OPENSSL_free(buf);
  1212. return len;
  1213. }
  1214. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  1215. * success and NULL on failure.
  1216. */
  1217. crypto_pk_t *
  1218. crypto_pk_asn1_decode(const char *str, size_t len)
  1219. {
  1220. RSA *rsa;
  1221. unsigned char *buf;
  1222. const unsigned char *cp;
  1223. cp = buf = tor_malloc(len);
  1224. memcpy(buf,str,len);
  1225. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  1226. tor_free(buf);
  1227. if (!rsa) {
  1228. crypto_log_errors(LOG_WARN,"decoding public key");
  1229. return NULL;
  1230. }
  1231. return crypto_new_pk_from_rsa_(rsa);
  1232. }
  1233. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  1234. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  1235. * Return 0 on success, -1 on failure.
  1236. */
  1237. int
  1238. crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
  1239. {
  1240. unsigned char *buf = NULL;
  1241. int len;
  1242. len = i2d_RSAPublicKey((RSA*)pk->key, &buf);
  1243. if (len < 0 || buf == NULL)
  1244. return -1;
  1245. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  1246. OPENSSL_free(buf);
  1247. return -1;
  1248. }
  1249. OPENSSL_free(buf);
  1250. return 0;
  1251. }
  1252. /** Compute all digests of the DER encoding of <b>pk</b>, and store them
  1253. * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
  1254. int
  1255. crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
  1256. {
  1257. unsigned char *buf = NULL;
  1258. int len;
  1259. len = i2d_RSAPublicKey(pk->key, &buf);
  1260. if (len < 0 || buf == NULL)
  1261. return -1;
  1262. if (crypto_common_digests(digests_out, (char*)buf, len) < 0) {
  1263. OPENSSL_free(buf);
  1264. return -1;
  1265. }
  1266. OPENSSL_free(buf);
  1267. return 0;
  1268. }
  1269. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  1270. * every four characters. */
  1271. void
  1272. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  1273. {
  1274. int n = 0;
  1275. char *end = out+outlen;
  1276. tor_assert(outlen < SIZE_T_CEILING);
  1277. while (*in && out<end) {
  1278. *out++ = *in++;
  1279. if (++n == 4 && *in && out<end) {
  1280. n = 0;
  1281. *out++ = ' ';
  1282. }
  1283. }
  1284. tor_assert(out<end);
  1285. *out = '\0';
  1286. }
  1287. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  1288. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  1289. * space). Return 0 on success, -1 on failure.
  1290. *
  1291. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  1292. * of the public key, converted to hexadecimal, in upper case, with a
  1293. * space after every four digits.
  1294. *
  1295. * If <b>add_space</b> is false, omit the spaces.
  1296. */
  1297. int
  1298. crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
  1299. {
  1300. char digest[DIGEST_LEN];
  1301. char hexdigest[HEX_DIGEST_LEN+1];
  1302. if (crypto_pk_get_digest(pk, digest)) {
  1303. return -1;
  1304. }
  1305. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  1306. if (add_space) {
  1307. crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  1308. } else {
  1309. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  1310. }
  1311. return 0;
  1312. }
  1313. /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
  1314. * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
  1315. * bytes of space). Return 0 on success, -1 on failure.
  1316. *
  1317. * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
  1318. * of the ASN.1 encoding of the public key, converted to hexadecimal, in
  1319. * upper case.
  1320. */
  1321. int
  1322. crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
  1323. {
  1324. char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
  1325. if (crypto_pk_get_digest(pk, digest)) {
  1326. return -1;
  1327. }
  1328. if (crypto_digest(hashed_digest, digest, DIGEST_LEN)) {
  1329. return -1;
  1330. }
  1331. base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
  1332. return 0;
  1333. }
  1334. /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
  1335. * Base64 encoding of the DER representation of the private key as a NUL
  1336. * terminated string, and return it via <b>priv_out</b>. Return 0 on
  1337. * sucess, -1 on failure.
  1338. *
  1339. * It is the caller's responsibility to sanitize and free the resulting buffer.
  1340. */
  1341. int
  1342. crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
  1343. {
  1344. unsigned char *der = NULL;
  1345. int der_len;
  1346. int ret = -1;
  1347. *priv_out = NULL;
  1348. der_len = i2d_RSAPrivateKey(pk->key, &der);
  1349. if (der_len < 0 || der == NULL)
  1350. return ret;
  1351. size_t priv_len = base64_encode_size(der_len, 0) + 1;
  1352. char *priv = tor_malloc_zero(priv_len);
  1353. if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
  1354. *priv_out = priv;
  1355. ret = 0;
  1356. } else {
  1357. tor_free(priv);
  1358. }
  1359. memwipe(der, 0, der_len);
  1360. OPENSSL_free(der);
  1361. return ret;
  1362. }
  1363. /** Given a string containing the Base64 encoded DER representation of the
  1364. * private key <b>str</b>, decode and return the result on success, or NULL
  1365. * on failure.
  1366. */
  1367. crypto_pk_t *
  1368. crypto_pk_base64_decode(const char *str, size_t len)
  1369. {
  1370. crypto_pk_t *pk = NULL;
  1371. char *der = tor_malloc_zero(len + 1);
  1372. int der_len = base64_decode(der, len, str, len);
  1373. if (der_len <= 0) {
  1374. log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
  1375. goto out;
  1376. }
  1377. const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
  1378. RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
  1379. if (!rsa) {
  1380. crypto_log_errors(LOG_WARN, "decoding private key");
  1381. goto out;
  1382. }
  1383. pk = crypto_new_pk_from_rsa_(rsa);
  1384. /* Make sure it's valid. */
  1385. if (crypto_pk_check_key(pk) <= 0) {
  1386. crypto_pk_free(pk);
  1387. pk = NULL;
  1388. goto out;
  1389. }
  1390. out:
  1391. memwipe(der, 0, len + 1);
  1392. tor_free(der);
  1393. return pk;
  1394. }
  1395. /* symmetric crypto */
  1396. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1397. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1398. * Does not check for failure.
  1399. */
  1400. int
  1401. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  1402. const char *from, size_t fromlen)
  1403. {
  1404. tor_assert(env);
  1405. tor_assert(env->cipher);
  1406. tor_assert(from);
  1407. tor_assert(fromlen);
  1408. tor_assert(to);
  1409. tor_assert(fromlen < SIZE_T_CEILING);
  1410. memcpy(to, from, fromlen);
  1411. aes_crypt_inplace(env->cipher, to, fromlen);
  1412. return 0;
  1413. }
  1414. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1415. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1416. * Does not check for failure.
  1417. */
  1418. int
  1419. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  1420. const char *from, size_t fromlen)
  1421. {
  1422. tor_assert(env);
  1423. tor_assert(from);
  1424. tor_assert(to);
  1425. tor_assert(fromlen < SIZE_T_CEILING);
  1426. memcpy(to, from, fromlen);
  1427. aes_crypt_inplace(env->cipher, to, fromlen);
  1428. return 0;
  1429. }
  1430. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  1431. * on success. Does not check for failure.
  1432. */
  1433. void
  1434. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  1435. {
  1436. tor_assert(len < SIZE_T_CEILING);
  1437. aes_crypt_inplace(env->cipher, buf, len);
  1438. }
  1439. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1440. * <b>key</b> to the buffer in <b>to</b> of length
  1441. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1442. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1443. * number of bytes written, on failure, return -1.
  1444. */
  1445. int
  1446. crypto_cipher_encrypt_with_iv(const char *key,
  1447. char *to, size_t tolen,
  1448. const char *from, size_t fromlen)
  1449. {
  1450. crypto_cipher_t *cipher;
  1451. tor_assert(from);
  1452. tor_assert(to);
  1453. tor_assert(fromlen < INT_MAX);
  1454. if (fromlen < 1)
  1455. return -1;
  1456. if (tolen < fromlen + CIPHER_IV_LEN)
  1457. return -1;
  1458. char iv[CIPHER_IV_LEN];
  1459. crypto_rand(iv, sizeof(iv));
  1460. cipher = crypto_cipher_new_with_iv(key, iv);
  1461. memcpy(to, iv, CIPHER_IV_LEN);
  1462. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1463. crypto_cipher_free(cipher);
  1464. memwipe(iv, 0, sizeof(iv));
  1465. return (int)(fromlen + CIPHER_IV_LEN);
  1466. }
  1467. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1468. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  1469. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1470. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1471. * number of bytes written, on failure, return -1.
  1472. */
  1473. int
  1474. crypto_cipher_decrypt_with_iv(const char *key,
  1475. char *to, size_t tolen,
  1476. const char *from, size_t fromlen)
  1477. {
  1478. crypto_cipher_t *cipher;
  1479. tor_assert(key);
  1480. tor_assert(from);
  1481. tor_assert(to);
  1482. tor_assert(fromlen < INT_MAX);
  1483. if (fromlen <= CIPHER_IV_LEN)
  1484. return -1;
  1485. if (tolen < fromlen - CIPHER_IV_LEN)
  1486. return -1;
  1487. cipher = crypto_cipher_new_with_iv(key, from);
  1488. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1489. crypto_cipher_free(cipher);
  1490. return (int)(fromlen - CIPHER_IV_LEN);
  1491. }
  1492. /* SHA-1 */
  1493. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  1494. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1495. * Return 0 on success, 1 on failure.
  1496. */
  1497. int
  1498. crypto_digest(char *digest, const char *m, size_t len)
  1499. {
  1500. tor_assert(m);
  1501. tor_assert(digest);
  1502. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1503. }
  1504. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1505. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  1506. * into <b>digest</b>. Return 0 on success, 1 on failure. */
  1507. int
  1508. crypto_digest256(char *digest, const char *m, size_t len,
  1509. digest_algorithm_t algorithm)
  1510. {
  1511. tor_assert(m);
  1512. tor_assert(digest);
  1513. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1514. if (algorithm == DIGEST_SHA256)
  1515. return (SHA256((const uint8_t*)m,len,(uint8_t*)digest) == NULL);
  1516. else
  1517. return (sha3_256((uint8_t *)digest, DIGEST256_LEN,(const uint8_t *)m, len)
  1518. == -1);
  1519. }
  1520. /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1521. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
  1522. * into <b>digest</b>. Return 0 on success, 1 on failure. */
  1523. int
  1524. crypto_digest512(char *digest, const char *m, size_t len,
  1525. digest_algorithm_t algorithm)
  1526. {
  1527. tor_assert(m);
  1528. tor_assert(digest);
  1529. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1530. if (algorithm == DIGEST_SHA512)
  1531. return (SHA512((const unsigned char*)m,len,(unsigned char*)digest)
  1532. == NULL);
  1533. else
  1534. return (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len)
  1535. == -1);
  1536. }
  1537. /** Set the common_digests_t in <b>ds_out</b> to contain every digest on the
  1538. * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
  1539. * success, -1 on failure. */
  1540. int
  1541. crypto_common_digests(common_digests_t *ds_out, const char *m, size_t len)
  1542. {
  1543. tor_assert(ds_out);
  1544. memset(ds_out, 0, sizeof(*ds_out));
  1545. if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
  1546. return -1;
  1547. if (crypto_digest256(ds_out->d[DIGEST_SHA256], m, len, DIGEST_SHA256) < 0)
  1548. return -1;
  1549. return 0;
  1550. }
  1551. /** Return the name of an algorithm, as used in directory documents. */
  1552. const char *
  1553. crypto_digest_algorithm_get_name(digest_algorithm_t alg)
  1554. {
  1555. switch (alg) {
  1556. case DIGEST_SHA1:
  1557. return "sha1";
  1558. case DIGEST_SHA256:
  1559. return "sha256";
  1560. case DIGEST_SHA512:
  1561. return "sha512";
  1562. case DIGEST_SHA3_256:
  1563. return "sha3-256";
  1564. case DIGEST_SHA3_512:
  1565. return "sha3-512";
  1566. default:
  1567. // LCOV_EXCL_START
  1568. tor_fragile_assert();
  1569. return "??unknown_digest??";
  1570. // LCOV_EXCL_STOP
  1571. }
  1572. }
  1573. /** Given the name of a digest algorithm, return its integer value, or -1 if
  1574. * the name is not recognized. */
  1575. int
  1576. crypto_digest_algorithm_parse_name(const char *name)
  1577. {
  1578. if (!strcmp(name, "sha1"))
  1579. return DIGEST_SHA1;
  1580. else if (!strcmp(name, "sha256"))
  1581. return DIGEST_SHA256;
  1582. else if (!strcmp(name, "sha512"))
  1583. return DIGEST_SHA512;
  1584. else if (!strcmp(name, "sha3-256"))
  1585. return DIGEST_SHA3_256;
  1586. else if (!strcmp(name, "sha3-512"))
  1587. return DIGEST_SHA3_512;
  1588. else
  1589. return -1;
  1590. }
  1591. /** Given an algorithm, return the digest length in bytes. */
  1592. size_t
  1593. crypto_digest_algorithm_get_length(digest_algorithm_t alg)
  1594. {
  1595. switch (alg) {
  1596. case DIGEST_SHA1:
  1597. return DIGEST_LEN;
  1598. case DIGEST_SHA256:
  1599. return DIGEST256_LEN;
  1600. case DIGEST_SHA512:
  1601. return DIGEST512_LEN;
  1602. case DIGEST_SHA3_256:
  1603. return DIGEST256_LEN;
  1604. case DIGEST_SHA3_512:
  1605. return DIGEST512_LEN;
  1606. default:
  1607. tor_assert(0); // LCOV_EXCL_LINE
  1608. return 0; /* Unreachable */ // LCOV_EXCL_LINE
  1609. }
  1610. }
  1611. /** Intermediate information about the digest of a stream of data. */
  1612. struct crypto_digest_t {
  1613. digest_algorithm_t algorithm; /**< Which algorithm is in use? */
  1614. /** State for the digest we're using. Only one member of the
  1615. * union is usable, depending on the value of <b>algorithm</b>. Note also
  1616. * that space for other members might not even be allocated!
  1617. */
  1618. union {
  1619. SHA_CTX sha1; /**< state for SHA1 */
  1620. SHA256_CTX sha2; /**< state for SHA256 */
  1621. SHA512_CTX sha512; /**< state for SHA512 */
  1622. keccak_state sha3; /**< state for SHA3-[256,512] */
  1623. } d;
  1624. };
  1625. /**
  1626. * Return the number of bytes we need to malloc in order to get a
  1627. * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
  1628. * when we free one.
  1629. */
  1630. static size_t
  1631. crypto_digest_alloc_bytes(digest_algorithm_t alg)
  1632. {
  1633. /* Helper: returns the number of bytes in the 'f' field of 'st' */
  1634. #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
  1635. /* Gives the length of crypto_digest_t through the end of the field 'd' */
  1636. #define END_OF_FIELD(f) (STRUCT_OFFSET(crypto_digest_t, f) + \
  1637. STRUCT_FIELD_SIZE(crypto_digest_t, f))
  1638. switch (alg) {
  1639. case DIGEST_SHA1:
  1640. return END_OF_FIELD(d.sha1);
  1641. case DIGEST_SHA256:
  1642. return END_OF_FIELD(d.sha2);
  1643. case DIGEST_SHA512:
  1644. return END_OF_FIELD(d.sha512);
  1645. case DIGEST_SHA3_256:
  1646. case DIGEST_SHA3_512:
  1647. return END_OF_FIELD(d.sha3);
  1648. default:
  1649. tor_assert(0); // LCOV_EXCL_LINE
  1650. return 0; // LCOV_EXCL_LINE
  1651. }
  1652. #undef END_OF_FIELD
  1653. #undef STRUCT_FIELD_SIZE
  1654. }
  1655. /**
  1656. * Internal function: create and return a new digest object for 'algorithm'.
  1657. * Does not typecheck the algorithm.
  1658. */
  1659. static crypto_digest_t *
  1660. crypto_digest_new_internal(digest_algorithm_t algorithm)
  1661. {
  1662. crypto_digest_t *r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
  1663. r->algorithm = algorithm;
  1664. switch (algorithm)
  1665. {
  1666. case DIGEST_SHA1:
  1667. SHA1_Init(&r->d.sha1);
  1668. break;
  1669. case DIGEST_SHA256:
  1670. SHA256_Init(&r->d.sha2);
  1671. break;
  1672. case DIGEST_SHA512:
  1673. SHA512_Init(&r->d.sha512);
  1674. break;
  1675. case DIGEST_SHA3_256:
  1676. keccak_digest_init(&r->d.sha3, 256);
  1677. break;
  1678. case DIGEST_SHA3_512:
  1679. keccak_digest_init(&r->d.sha3, 512);
  1680. break;
  1681. default:
  1682. tor_assert_unreached();
  1683. }
  1684. return r;
  1685. }
  1686. /** Allocate and return a new digest object to compute SHA1 digests.
  1687. */
  1688. crypto_digest_t *
  1689. crypto_digest_new(void)
  1690. {
  1691. return crypto_digest_new_internal(DIGEST_SHA1);
  1692. }
  1693. /** Allocate and return a new digest object to compute 256-bit digests
  1694. * using <b>algorithm</b>. */
  1695. crypto_digest_t *
  1696. crypto_digest256_new(digest_algorithm_t algorithm)
  1697. {
  1698. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1699. return crypto_digest_new_internal(algorithm);
  1700. }
  1701. /** Allocate and return a new digest object to compute 512-bit digests
  1702. * using <b>algorithm</b>. */
  1703. crypto_digest_t *
  1704. crypto_digest512_new(digest_algorithm_t algorithm)
  1705. {
  1706. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1707. return crypto_digest_new_internal(algorithm);
  1708. }
  1709. /** Deallocate a digest object.
  1710. */
  1711. void
  1712. crypto_digest_free(crypto_digest_t *digest)
  1713. {
  1714. if (!digest)
  1715. return;
  1716. size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1717. memwipe(digest, 0, bytes);
  1718. tor_free(digest);
  1719. }
  1720. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1721. */
  1722. void
  1723. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  1724. size_t len)
  1725. {
  1726. tor_assert(digest);
  1727. tor_assert(data);
  1728. /* Using the SHA*_*() calls directly means we don't support doing
  1729. * SHA in hardware. But so far the delay of getting the question
  1730. * to the hardware, and hearing the answer, is likely higher than
  1731. * just doing it ourselves. Hashes are fast.
  1732. */
  1733. switch (digest->algorithm) {
  1734. case DIGEST_SHA1:
  1735. SHA1_Update(&digest->d.sha1, (void*)data, len);
  1736. break;
  1737. case DIGEST_SHA256:
  1738. SHA256_Update(&digest->d.sha2, (void*)data, len);
  1739. break;
  1740. case DIGEST_SHA512:
  1741. SHA512_Update(&digest->d.sha512, (void*)data, len);
  1742. break;
  1743. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1744. case DIGEST_SHA3_512:
  1745. keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
  1746. break;
  1747. default:
  1748. /* LCOV_EXCL_START */
  1749. tor_fragile_assert();
  1750. break;
  1751. /* LCOV_EXCL_STOP */
  1752. }
  1753. }
  1754. /** Compute the hash of the data that has been passed to the digest
  1755. * object; write the first out_len bytes of the result to <b>out</b>.
  1756. * <b>out_len</b> must be \<= DIGEST512_LEN.
  1757. */
  1758. void
  1759. crypto_digest_get_digest(crypto_digest_t *digest,
  1760. char *out, size_t out_len)
  1761. {
  1762. unsigned char r[DIGEST512_LEN];
  1763. crypto_digest_t tmpenv;
  1764. tor_assert(digest);
  1765. tor_assert(out);
  1766. tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
  1767. /* The SHA-3 code handles copying into a temporary ctx, and also can handle
  1768. * short output buffers by truncating appropriately. */
  1769. if (digest->algorithm == DIGEST_SHA3_256 ||
  1770. digest->algorithm == DIGEST_SHA3_512) {
  1771. keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
  1772. return;
  1773. }
  1774. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1775. /* memcpy into a temporary ctx, since SHA*_Final clears the context */
  1776. memcpy(&tmpenv, digest, alloc_bytes);
  1777. switch (digest->algorithm) {
  1778. case DIGEST_SHA1:
  1779. SHA1_Final(r, &tmpenv.d.sha1);
  1780. break;
  1781. case DIGEST_SHA256:
  1782. SHA256_Final(r, &tmpenv.d.sha2);
  1783. break;
  1784. case DIGEST_SHA512:
  1785. SHA512_Final(r, &tmpenv.d.sha512);
  1786. break;
  1787. //LCOV_EXCL_START
  1788. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1789. case DIGEST_SHA3_512:
  1790. default:
  1791. log_warn(LD_BUG, "Handling unexpected algorithm %d", digest->algorithm);
  1792. /* This is fatal, because it should never happen. */
  1793. tor_assert_unreached();
  1794. break;
  1795. //LCOV_EXCL_STOP
  1796. }
  1797. memcpy(out, r, out_len);
  1798. memwipe(r, 0, sizeof(r));
  1799. }
  1800. /** Allocate and return a new digest object with the same state as
  1801. * <b>digest</b>
  1802. */
  1803. crypto_digest_t *
  1804. crypto_digest_dup(const crypto_digest_t *digest)
  1805. {
  1806. tor_assert(digest);
  1807. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1808. return tor_memdup(digest, alloc_bytes);
  1809. }
  1810. /** Replace the state of the digest object <b>into</b> with the state
  1811. * of the digest object <b>from</b>. Requires that 'into' and 'from'
  1812. * have the same digest type.
  1813. */
  1814. void
  1815. crypto_digest_assign(crypto_digest_t *into,
  1816. const crypto_digest_t *from)
  1817. {
  1818. tor_assert(into);
  1819. tor_assert(from);
  1820. tor_assert(into->algorithm == from->algorithm);
  1821. const size_t alloc_bytes = crypto_digest_alloc_bytes(from->algorithm);
  1822. memcpy(into,from,alloc_bytes);
  1823. }
  1824. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1825. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  1826. * plus the optional string <b>append</b>, computed with the algorithm
  1827. * <b>alg</b>.
  1828. * <b>out_len</b> must be \<= DIGEST512_LEN. */
  1829. void
  1830. crypto_digest_smartlist(char *digest_out, size_t len_out,
  1831. const smartlist_t *lst,
  1832. const char *append,
  1833. digest_algorithm_t alg)
  1834. {
  1835. crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
  1836. }
  1837. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1838. * at <b>digest_out</b> to the hash of the concatenation of: the
  1839. * optional string <b>prepend</b>, those strings,
  1840. * and the optional string <b>append</b>, computed with the algorithm
  1841. * <b>alg</b>.
  1842. * <b>len_out</b> must be \<= DIGEST512_LEN. */
  1843. void
  1844. crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
  1845. const char *prepend,
  1846. const smartlist_t *lst,
  1847. const char *append,
  1848. digest_algorithm_t alg)
  1849. {
  1850. crypto_digest_t *d = crypto_digest_new_internal(alg);
  1851. if (prepend)
  1852. crypto_digest_add_bytes(d, prepend, strlen(prepend));
  1853. SMARTLIST_FOREACH(lst, const char *, cp,
  1854. crypto_digest_add_bytes(d, cp, strlen(cp)));
  1855. if (append)
  1856. crypto_digest_add_bytes(d, append, strlen(append));
  1857. crypto_digest_get_digest(d, digest_out, len_out);
  1858. crypto_digest_free(d);
  1859. }
  1860. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1861. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  1862. * result in <b>hmac_out</b>. Asserts on failure.
  1863. */
  1864. void
  1865. crypto_hmac_sha256(char *hmac_out,
  1866. const char *key, size_t key_len,
  1867. const char *msg, size_t msg_len)
  1868. {
  1869. unsigned char *rv = NULL;
  1870. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  1871. tor_assert(key_len < INT_MAX);
  1872. tor_assert(msg_len < INT_MAX);
  1873. tor_assert(hmac_out);
  1874. rv = HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  1875. (unsigned char*)hmac_out, NULL);
  1876. tor_assert(rv);
  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
  1953. if (!(dh->p = BN_dup(p)))
  1954. goto out;
  1955. if (!(dh->g = BN_dup(g)))
  1956. goto out;
  1957. #endif
  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
  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
  2111. return res;
  2112. err:
  2113. /* LCOV_EXCL_START
  2114. * This error condition is only reached when an allocation fails */
  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
  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
  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
  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))
  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. /* Probably ENOSYS. */
  2494. log_warn(LD_CRYPTO, "Can't get entropy from getrandom().");
  2495. getrandom_works = 0; /* Don't bother trying again. */
  2496. return -1;
  2497. /* LCOV_EXCL_STOP */
  2498. }
  2499. tor_assert(ret == (long)out_len);
  2500. return 0;
  2501. }
  2502. return -1; /* getrandom() previously failed unexpectedly. */
  2503. #elif defined(HAVE_GETENTROPY)
  2504. /* getentropy() is what Linux's getrandom() wants to be when it grows up.
  2505. * the only gotcha is that requests are limited to 256 bytes.
  2506. */
  2507. return getentropy(out, out_len);
  2508. #else
  2509. (void) out;
  2510. #endif
  2511. /* This platform doesn't have a supported syscall based random. */
  2512. return -1;
  2513. }
  2514. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2515. * via the per-platform fallback mechanism, storing it into <b>out</b>.
  2516. * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
  2517. * is imposed.
  2518. */
  2519. static int
  2520. crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
  2521. {
  2522. #ifdef TOR_UNIT_TESTS
  2523. if (break_strongest_rng_fallback)
  2524. return -1;
  2525. #endif
  2526. #ifdef _WIN32
  2527. /* Windows exclusively uses crypto_strongest_rand_syscall(). */
  2528. (void)out;
  2529. (void)out_len;
  2530. return -1;
  2531. #else
  2532. static const char *filenames[] = {
  2533. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  2534. };
  2535. int fd, i;
  2536. size_t n;
  2537. for (i = 0; filenames[i]; ++i) {
  2538. log_debug(LD_FS, "Opening %s for entropy", filenames[i]);
  2539. fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
  2540. if (fd<0) continue;
  2541. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  2542. n = read_all(fd, (char*)out, out_len, 0);
  2543. close(fd);
  2544. if (n != out_len) {
  2545. /* LCOV_EXCL_START
  2546. * We can't make /dev/foorandom actually fail. */
  2547. log_warn(LD_CRYPTO,
  2548. "Error reading from entropy source (read only %lu bytes).",
  2549. (unsigned long)n);
  2550. return -1;
  2551. /* LCOV_EXCL_STOP */
  2552. }
  2553. return 0;
  2554. }
  2555. return -1;
  2556. #endif
  2557. }
  2558. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2559. * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
  2560. * request size of 256 bytes is imposed.
  2561. */
  2562. STATIC int
  2563. crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
  2564. {
  2565. static const size_t sanity_min_size = 16;
  2566. static const int max_attempts = 3;
  2567. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  2568. /* For buffers >= 16 bytes (128 bits), we sanity check the output by
  2569. * zero filling the buffer and ensuring that it actually was at least
  2570. * partially modified.
  2571. *
  2572. * Checking that any individual byte is non-zero seems like it would
  2573. * fail too often (p = out_len * 1/256) for comfort, but this is an
  2574. * "adjust according to taste" sort of check.
  2575. */
  2576. memwipe(out, 0, out_len);
  2577. for (int i = 0; i < max_attempts; i++) {
  2578. /* Try to use the syscall/OS favored mechanism to get strong entropy. */
  2579. if (crypto_strongest_rand_syscall(out, out_len) != 0) {
  2580. /* Try to use the less-favored mechanism to get strong entropy. */
  2581. if (crypto_strongest_rand_fallback(out, out_len) != 0) {
  2582. /* Welp, we tried. Hopefully the calling code terminates the process
  2583. * since we're basically boned without good entropy.
  2584. */
  2585. log_warn(LD_CRYPTO,
  2586. "Cannot get strong entropy: no entropy source found.");
  2587. return -1;
  2588. }
  2589. }
  2590. if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
  2591. return 0;
  2592. }
  2593. /* LCOV_EXCL_START
  2594. *
  2595. * We tried max_attempts times to fill a buffer >= 128 bits long,
  2596. * and each time it returned all '0's. Either the system entropy
  2597. * source is busted, or the user should go out and buy a ticket to
  2598. * every lottery on the planet.
  2599. */
  2600. log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
  2601. return -1;
  2602. /* LCOV_EXCL_STOP */
  2603. }
  2604. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2605. * storing it into <b>out</b>.
  2606. */
  2607. void
  2608. crypto_strongest_rand(uint8_t *out, size_t out_len)
  2609. {
  2610. #define DLEN SHA512_DIGEST_LENGTH
  2611. /* We're going to hash DLEN bytes from the system RNG together with some
  2612. * bytes from the openssl PRNG, in order to yield DLEN bytes.
  2613. */
  2614. uint8_t inp[DLEN*2];
  2615. uint8_t tmp[DLEN];
  2616. tor_assert(out);
  2617. while (out_len) {
  2618. crypto_rand((char*) inp, DLEN);
  2619. if (crypto_strongest_rand_raw(inp+DLEN, DLEN) < 0) {
  2620. // LCOV_EXCL_START
  2621. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  2622. "important key. Exiting.");
  2623. /* Die with an assertion so we get a stack trace. */
  2624. tor_assert(0);
  2625. // LCOV_EXCL_STOP
  2626. }
  2627. if (out_len >= DLEN) {
  2628. SHA512(inp, sizeof(inp), out);
  2629. out += DLEN;
  2630. out_len -= DLEN;
  2631. } else {
  2632. SHA512(inp, sizeof(inp), tmp);
  2633. memcpy(out, tmp, out_len);
  2634. break;
  2635. }
  2636. }
  2637. memwipe(tmp, 0, sizeof(tmp));
  2638. memwipe(inp, 0, sizeof(inp));
  2639. #undef DLEN
  2640. }
  2641. /** Seed OpenSSL's random number generator with bytes from the operating
  2642. * system. Return 0 on success, -1 on failure.
  2643. */
  2644. int
  2645. crypto_seed_rng(void)
  2646. {
  2647. int rand_poll_ok = 0, load_entropy_ok = 0;
  2648. uint8_t buf[ADD_ENTROPY];
  2649. /* OpenSSL has a RAND_poll function that knows about more kinds of
  2650. * entropy than we do. We'll try calling that, *and* calling our own entropy
  2651. * functions. If one succeeds, we'll accept the RNG as seeded. */
  2652. rand_poll_ok = RAND_poll();
  2653. if (rand_poll_ok == 0)
  2654. log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
  2655. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  2656. if (load_entropy_ok) {
  2657. RAND_seed(buf, sizeof(buf));
  2658. }
  2659. memwipe(buf, 0, sizeof(buf));
  2660. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  2661. return 0;
  2662. else
  2663. return -1;
  2664. }
  2665. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  2666. * for unit tests.
  2667. *
  2668. * This function is not allowed to fail; if it would fail to generate strong
  2669. * entropy, it must terminate the process instead.
  2670. */
  2671. MOCK_IMPL(void,
  2672. crypto_rand, (char *to, size_t n))
  2673. {
  2674. crypto_rand_unmocked(to, n);
  2675. }
  2676. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  2677. * will want crypto_rand instead.
  2678. *
  2679. * This function is not allowed to fail; if it would fail to generate strong
  2680. * entropy, it must terminate the process instead.
  2681. */
  2682. void
  2683. crypto_rand_unmocked(char *to, size_t n)
  2684. {
  2685. int r;
  2686. if (n == 0)
  2687. return;
  2688. tor_assert(n < INT_MAX);
  2689. tor_assert(to);
  2690. r = RAND_bytes((unsigned char*)to, (int)n);
  2691. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  2692. * stack trace about where it happened.
  2693. */
  2694. tor_assert(r >= 0);
  2695. }
  2696. /** Return a pseudorandom integer, chosen uniformly from the values
  2697. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  2698. * INT_MAX+1, inclusive. */
  2699. int
  2700. crypto_rand_int(unsigned int max)
  2701. {
  2702. unsigned int val;
  2703. unsigned int cutoff;
  2704. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  2705. tor_assert(max > 0); /* don't div by 0 */
  2706. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2707. * distribution with clipping at the upper end of unsigned int's
  2708. * range.
  2709. */
  2710. cutoff = UINT_MAX - (UINT_MAX%max);
  2711. while (1) {
  2712. crypto_rand((char*)&val, sizeof(val));
  2713. if (val < cutoff)
  2714. return val % max;
  2715. }
  2716. }
  2717. /** Return a pseudorandom integer, chosen uniformly from the values i such
  2718. * that min <= i < max.
  2719. *
  2720. * <b>min</b> MUST be in range [0, <b>max</b>).
  2721. * <b>max</b> MUST be in range (min, INT_MAX].
  2722. */
  2723. int
  2724. crypto_rand_int_range(unsigned int min, unsigned int max)
  2725. {
  2726. tor_assert(min < max);
  2727. tor_assert(max <= INT_MAX);
  2728. /* The overflow is avoided here because crypto_rand_int() returns a value
  2729. * between 0 and (max - min) inclusive. */
  2730. return min + crypto_rand_int(max - min);
  2731. }
  2732. /** As crypto_rand_int_range, but supports uint64_t. */
  2733. uint64_t
  2734. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  2735. {
  2736. tor_assert(min < max);
  2737. return min + crypto_rand_uint64(max - min);
  2738. }
  2739. /** As crypto_rand_int_range, but supports time_t. */
  2740. time_t
  2741. crypto_rand_time_range(time_t min, time_t max)
  2742. {
  2743. tor_assert(min < max);
  2744. return min + (time_t)crypto_rand_uint64(max - min);
  2745. }
  2746. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  2747. * between 0 and <b>max</b>-1 inclusive. */
  2748. uint64_t
  2749. crypto_rand_uint64(uint64_t max)
  2750. {
  2751. uint64_t val;
  2752. uint64_t cutoff;
  2753. tor_assert(max < UINT64_MAX);
  2754. tor_assert(max > 0); /* don't div by 0 */
  2755. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2756. * distribution with clipping at the upper end of unsigned int's
  2757. * range.
  2758. */
  2759. cutoff = UINT64_MAX - (UINT64_MAX%max);
  2760. while (1) {
  2761. crypto_rand((char*)&val, sizeof(val));
  2762. if (val < cutoff)
  2763. return val % max;
  2764. }
  2765. }
  2766. /** Return a pseudorandom double d, chosen uniformly from the range
  2767. * 0.0 <= d < 1.0.
  2768. */
  2769. double
  2770. crypto_rand_double(void)
  2771. {
  2772. /* We just use an unsigned int here; we don't really care about getting
  2773. * more than 32 bits of resolution */
  2774. unsigned int u;
  2775. crypto_rand((char*)&u, sizeof(u));
  2776. #if SIZEOF_INT == 4
  2777. #define UINT_MAX_AS_DOUBLE 4294967296.0
  2778. #elif SIZEOF_INT == 8
  2779. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  2780. #else
  2781. #error SIZEOF_INT is neither 4 nor 8
  2782. #endif
  2783. return ((double)u) / UINT_MAX_AS_DOUBLE;
  2784. }
  2785. /** Generate and return a new random hostname starting with <b>prefix</b>,
  2786. * ending with <b>suffix</b>, and containing no fewer than
  2787. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  2788. * characters. Does not check for failure.
  2789. *
  2790. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  2791. **/
  2792. char *
  2793. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  2794. const char *suffix)
  2795. {
  2796. char *result, *rand_bytes;
  2797. int randlen, rand_bytes_len;
  2798. size_t resultlen, prefixlen;
  2799. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  2800. max_rand_len = MAX_DNS_LABEL_SIZE;
  2801. if (min_rand_len > max_rand_len)
  2802. min_rand_len = max_rand_len;
  2803. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  2804. prefixlen = strlen(prefix);
  2805. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  2806. rand_bytes_len = ((randlen*5)+7)/8;
  2807. if (rand_bytes_len % 5)
  2808. rand_bytes_len += 5 - (rand_bytes_len%5);
  2809. rand_bytes = tor_malloc(rand_bytes_len);
  2810. crypto_rand(rand_bytes, rand_bytes_len);
  2811. result = tor_malloc(resultlen);
  2812. memcpy(result, prefix, prefixlen);
  2813. base32_encode(result+prefixlen, resultlen-prefixlen,
  2814. rand_bytes, rand_bytes_len);
  2815. tor_free(rand_bytes);
  2816. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  2817. return result;
  2818. }
  2819. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  2820. * is empty. */
  2821. void *
  2822. smartlist_choose(const smartlist_t *sl)
  2823. {
  2824. int len = smartlist_len(sl);
  2825. if (len)
  2826. return smartlist_get(sl,crypto_rand_int(len));
  2827. return NULL; /* no elements to choose from */
  2828. }
  2829. /** Scramble the elements of <b>sl</b> into a random order. */
  2830. void
  2831. smartlist_shuffle(smartlist_t *sl)
  2832. {
  2833. int i;
  2834. /* From the end of the list to the front, choose at random from the
  2835. positions we haven't looked at yet, and swap that position into the
  2836. current position. Remember to give "no swap" the same probability as
  2837. any other swap. */
  2838. for (i = smartlist_len(sl)-1; i > 0; --i) {
  2839. int j = crypto_rand_int(i+1);
  2840. smartlist_swap(sl, i, j);
  2841. }
  2842. }
  2843. /**
  2844. * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
  2845. * the value <b>byte</b>.
  2846. * If <b>mem</b> is NULL or <b>sz</b> is zero, nothing happens.
  2847. *
  2848. * This function is preferable to memset, since many compilers will happily
  2849. * optimize out memset() when they can convince themselves that the data being
  2850. * cleared will never be read.
  2851. *
  2852. * Right now, our convention is to use this function when we are wiping data
  2853. * that's about to become inaccessible, such as stack buffers that are about
  2854. * to go out of scope or structures that are about to get freed. (In
  2855. * practice, it appears that the compilers we're currently using will optimize
  2856. * out the memset()s for stack-allocated buffers, but not those for
  2857. * about-to-be-freed structures. That could change, though, so we're being
  2858. * wary.) If there are live reads for the data, then you can just use
  2859. * memset().
  2860. */
  2861. void
  2862. memwipe(void *mem, uint8_t byte, size_t sz)
  2863. {
  2864. if (sz == 0) {
  2865. return;
  2866. }
  2867. /* If sz is nonzero, then mem must not be NULL. */
  2868. tor_assert(mem != NULL);
  2869. /* Data this large is likely to be an underflow. */
  2870. tor_assert(sz < SIZE_T_CEILING);
  2871. /* Because whole-program-optimization exists, we may not be able to just
  2872. * have this function call "memset". A smart compiler could inline it, then
  2873. * eliminate dead memsets, and declare itself to be clever. */
  2874. #if defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY)
  2875. /* Here's what you do on windows. */
  2876. SecureZeroMemory(mem,sz);
  2877. #elif defined(HAVE_RTLSECUREZEROMEMORY)
  2878. RtlSecureZeroMemory(mem,sz);
  2879. #elif defined(HAVE_EXPLICIT_BZERO)
  2880. /* The BSDs provide this. */
  2881. explicit_bzero(mem, sz);
  2882. #elif defined(HAVE_MEMSET_S)
  2883. /* This is in the C99 standard. */
  2884. memset_s(mem, sz, 0, sz);
  2885. #else
  2886. /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
  2887. * based on the pointer value, then uses that junk to update a global
  2888. * variable. It's an elaborate ruse to trick the compiler into not
  2889. * optimizing out the "wipe this memory" code. Read it if you like zany
  2890. * programming tricks! In later versions of Tor, we should look for better
  2891. * not-optimized-out memory wiping stuff...
  2892. *
  2893. * ...or maybe not. In practice, there are pure-asm implementations of
  2894. * OPENSSL_cleanse() on most platforms, which ought to do the job.
  2895. **/
  2896. OPENSSL_cleanse(mem, sz);
  2897. #endif
  2898. /* Just in case some caller of memwipe() is relying on getting a buffer
  2899. * filled with a particular value, fill the buffer.
  2900. *
  2901. * If this function gets inlined, this memset might get eliminated, but
  2902. * that's okay: We only care about this particular memset in the case where
  2903. * the caller should have been using memset(), and the memset() wouldn't get
  2904. * eliminated. In other words, this is here so that we won't break anything
  2905. * if somebody accidentally calls memwipe() instead of memset().
  2906. **/
  2907. memset(mem, byte, sz);
  2908. }
  2909. #ifndef OPENSSL_THREADS
  2910. #error OpenSSL has been built without thread support. Tor requires an \
  2911. OpenSSL library with thread support enabled.
  2912. #endif
  2913. #ifndef NEW_THREAD_API
  2914. /** Helper: OpenSSL uses this callback to manipulate mutexes. */
  2915. static void
  2916. openssl_locking_cb_(int mode, int n, const char *file, int line)
  2917. {
  2918. (void)file;
  2919. (void)line;
  2920. if (!openssl_mutexes_)
  2921. /* This is not a really good fix for the
  2922. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  2923. * it can't hurt. */
  2924. return;
  2925. if (mode & CRYPTO_LOCK)
  2926. tor_mutex_acquire(openssl_mutexes_[n]);
  2927. else
  2928. tor_mutex_release(openssl_mutexes_[n]);
  2929. }
  2930. static void
  2931. tor_set_openssl_thread_id(CRYPTO_THREADID *threadid)
  2932. {
  2933. CRYPTO_THREADID_set_numeric(threadid, tor_get_thread_id());
  2934. }
  2935. #endif
  2936. #if 0
  2937. /* This code is disabled, because OpenSSL never actually uses these callbacks.
  2938. */
  2939. /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
  2940. * as a lock. */
  2941. struct CRYPTO_dynlock_value {
  2942. tor_mutex_t *lock;
  2943. };
  2944. /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
  2945. * documentation in OpenSSL's docs for more info. */
  2946. static struct CRYPTO_dynlock_value *
  2947. openssl_dynlock_create_cb_(const char *file, int line)
  2948. {
  2949. struct CRYPTO_dynlock_value *v;
  2950. (void)file;
  2951. (void)line;
  2952. v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
  2953. v->lock = tor_mutex_new();
  2954. return v;
  2955. }
  2956. /** OpenSSL callback function to acquire or release a lock: see
  2957. * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
  2958. static void
  2959. openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
  2960. const char *file, int line)
  2961. {
  2962. (void)file;
  2963. (void)line;
  2964. if (mode & CRYPTO_LOCK)
  2965. tor_mutex_acquire(v->lock);
  2966. else
  2967. tor_mutex_release(v->lock);
  2968. }
  2969. /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
  2970. * documentation in OpenSSL's docs for more info. */
  2971. static void
  2972. openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
  2973. const char *file, int line)
  2974. {
  2975. (void)file;
  2976. (void)line;
  2977. tor_mutex_free(v->lock);
  2978. tor_free(v);
  2979. }
  2980. #endif
  2981. /** @{ */
  2982. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  2983. * multithreaded. Returns 0. */
  2984. static int
  2985. setup_openssl_threading(void)
  2986. {
  2987. #ifndef NEW_THREAD_API
  2988. int i;
  2989. int n = CRYPTO_num_locks();
  2990. n_openssl_mutexes_ = n;
  2991. openssl_mutexes_ = tor_calloc(n, sizeof(tor_mutex_t *));
  2992. for (i=0; i < n; ++i)
  2993. openssl_mutexes_[i] = tor_mutex_new();
  2994. CRYPTO_set_locking_callback(openssl_locking_cb_);
  2995. CRYPTO_THREADID_set_callback(tor_set_openssl_thread_id);
  2996. #endif
  2997. #if 0
  2998. CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_);
  2999. CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_);
  3000. CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_);
  3001. #endif
  3002. return 0;
  3003. }
  3004. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  3005. * failure.
  3006. */
  3007. int
  3008. crypto_global_cleanup(void)
  3009. {
  3010. EVP_cleanup();
  3011. #ifndef NEW_THREAD_API
  3012. ERR_remove_thread_state(NULL);
  3013. #endif
  3014. ERR_free_strings();
  3015. if (dh_param_p)
  3016. BN_clear_free(dh_param_p);
  3017. if (dh_param_p_tls)
  3018. BN_clear_free(dh_param_p_tls);
  3019. if (dh_param_g)
  3020. BN_clear_free(dh_param_g);
  3021. #ifndef DISABLE_ENGINES
  3022. ENGINE_cleanup();
  3023. #endif
  3024. CONF_modules_unload(1);
  3025. CRYPTO_cleanup_all_ex_data();
  3026. #ifndef NEW_THREAD_API
  3027. if (n_openssl_mutexes_) {
  3028. int n = n_openssl_mutexes_;
  3029. tor_mutex_t **ms = openssl_mutexes_;
  3030. int i;
  3031. openssl_mutexes_ = NULL;
  3032. n_openssl_mutexes_ = 0;
  3033. for (i=0;i<n;++i) {
  3034. tor_mutex_free(ms[i]);
  3035. }
  3036. tor_free(ms);
  3037. }
  3038. #endif
  3039. tor_free(crypto_openssl_version_str);
  3040. tor_free(crypto_openssl_header_version_str);
  3041. return 0;
  3042. }
  3043. /** @} */