crypto.c 93 KB

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