crypto.c 93 KB

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