crypto.c 96 KB

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