crypto.c 93 KB

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