crypto.c 94 KB

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