crypto.c 94 KB

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