crypto.c 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446
  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. 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. int
  998. crypto_pk_public_checksig_digest(crypto_pk_t *env, const char *data,
  999. size_t datalen, const char *sig, size_t siglen)
  1000. {
  1001. char digest[DIGEST_LEN];
  1002. char *buf;
  1003. size_t buflen;
  1004. int r;
  1005. tor_assert(env);
  1006. tor_assert(data);
  1007. tor_assert(sig);
  1008. tor_assert(datalen < SIZE_T_CEILING);
  1009. tor_assert(siglen < SIZE_T_CEILING);
  1010. if (crypto_digest(digest,data,datalen)<0) {
  1011. log_warn(LD_BUG, "couldn't compute digest");
  1012. return -1;
  1013. }
  1014. buflen = crypto_pk_keysize(env);
  1015. buf = tor_malloc(buflen);
  1016. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  1017. if (r != DIGEST_LEN) {
  1018. log_warn(LD_CRYPTO, "Invalid signature");
  1019. tor_free(buf);
  1020. return -1;
  1021. }
  1022. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  1023. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  1024. tor_free(buf);
  1025. return -1;
  1026. }
  1027. tor_free(buf);
  1028. return 0;
  1029. }
  1030. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  1031. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  1032. * <b>to</b>, and return the number of bytes written. On failure, return
  1033. * -1.
  1034. *
  1035. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  1036. * at least the length of the modulus of <b>env</b>.
  1037. */
  1038. int
  1039. crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
  1040. const char *from, size_t fromlen)
  1041. {
  1042. int r;
  1043. tor_assert(env);
  1044. tor_assert(from);
  1045. tor_assert(to);
  1046. tor_assert(fromlen < INT_MAX);
  1047. tor_assert(tolen >= crypto_pk_keysize(env));
  1048. if (!crypto_pk_key_is_private(env))
  1049. /* Not a private key */
  1050. return -1;
  1051. r = RSA_private_encrypt((int)fromlen,
  1052. (unsigned char*)from, (unsigned char*)to,
  1053. (RSA*)env->key, RSA_PKCS1_PADDING);
  1054. if (r<0) {
  1055. crypto_log_errors(LOG_WARN, "generating RSA signature");
  1056. return -1;
  1057. }
  1058. return r;
  1059. }
  1060. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  1061. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  1062. * store it in <b>to</b>. Return the number of bytes written on
  1063. * success, and -1 on failure.
  1064. *
  1065. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  1066. * at least the length of the modulus of <b>env</b>.
  1067. */
  1068. int
  1069. crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
  1070. const char *from, size_t fromlen)
  1071. {
  1072. int r;
  1073. char digest[DIGEST_LEN];
  1074. if (crypto_digest(digest,from,fromlen)<0)
  1075. return -1;
  1076. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  1077. memwipe(digest, 0, sizeof(digest));
  1078. return r;
  1079. }
  1080. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  1081. * bytes of data from <b>from</b>, with padding type 'padding',
  1082. * storing the results on <b>to</b>.
  1083. *
  1084. * Returns the number of bytes written on success, -1 on failure.
  1085. *
  1086. * The encrypted data consists of:
  1087. * - The source data, padded and encrypted with the public key, if the
  1088. * padded source data is no longer than the public key, and <b>force</b>
  1089. * is false, OR
  1090. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  1091. * padded and encrypted with the public key; followed by the rest of
  1092. * the source data encrypted in AES-CTR mode with the symmetric key.
  1093. */
  1094. int
  1095. crypto_pk_public_hybrid_encrypt(crypto_pk_t *env,
  1096. char *to, size_t tolen,
  1097. const char *from,
  1098. size_t fromlen,
  1099. int padding, int force)
  1100. {
  1101. int overhead, outlen, r;
  1102. size_t pkeylen, symlen;
  1103. crypto_cipher_t *cipher = NULL;
  1104. char *buf = NULL;
  1105. tor_assert(env);
  1106. tor_assert(from);
  1107. tor_assert(to);
  1108. tor_assert(fromlen < SIZE_T_CEILING);
  1109. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  1110. pkeylen = crypto_pk_keysize(env);
  1111. if (!force && fromlen+overhead <= pkeylen) {
  1112. /* It all fits in a single encrypt. */
  1113. return crypto_pk_public_encrypt(env,to,
  1114. tolen,
  1115. from,fromlen,padding);
  1116. }
  1117. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  1118. tor_assert(tolen >= pkeylen);
  1119. char key[CIPHER_KEY_LEN];
  1120. crypto_rand(key, sizeof(key)); /* generate a new key. */
  1121. cipher = crypto_cipher_new(key);
  1122. buf = tor_malloc(pkeylen+1);
  1123. memcpy(buf, key, CIPHER_KEY_LEN);
  1124. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  1125. /* Length of symmetrically encrypted data. */
  1126. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  1127. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  1128. if (outlen!=(int)pkeylen) {
  1129. goto err;
  1130. }
  1131. r = crypto_cipher_encrypt(cipher, to+outlen,
  1132. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  1133. if (r<0) goto err;
  1134. memwipe(buf, 0, pkeylen);
  1135. memwipe(key, 0, sizeof(key));
  1136. tor_free(buf);
  1137. crypto_cipher_free(cipher);
  1138. tor_assert(outlen+symlen < INT_MAX);
  1139. return (int)(outlen + symlen);
  1140. err:
  1141. memwipe(buf, 0, pkeylen);
  1142. memwipe(key, 0, sizeof(key));
  1143. tor_free(buf);
  1144. crypto_cipher_free(cipher);
  1145. return -1;
  1146. }
  1147. /** Invert crypto_pk_public_hybrid_encrypt. Returns the number of bytes
  1148. * written on success, -1 on failure. */
  1149. int
  1150. crypto_pk_private_hybrid_decrypt(crypto_pk_t *env,
  1151. char *to,
  1152. size_t tolen,
  1153. const char *from,
  1154. size_t fromlen,
  1155. int padding, int warnOnFailure)
  1156. {
  1157. int outlen, r;
  1158. size_t pkeylen;
  1159. crypto_cipher_t *cipher = NULL;
  1160. char *buf = NULL;
  1161. tor_assert(fromlen < SIZE_T_CEILING);
  1162. pkeylen = crypto_pk_keysize(env);
  1163. if (fromlen <= pkeylen) {
  1164. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  1165. warnOnFailure);
  1166. }
  1167. buf = tor_malloc(pkeylen);
  1168. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  1169. warnOnFailure);
  1170. if (outlen<0) {
  1171. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  1172. "Error decrypting public-key data");
  1173. goto err;
  1174. }
  1175. if (outlen < CIPHER_KEY_LEN) {
  1176. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  1177. "No room for a symmetric key");
  1178. goto err;
  1179. }
  1180. cipher = crypto_cipher_new(buf);
  1181. if (!cipher) {
  1182. goto err;
  1183. }
  1184. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  1185. outlen -= CIPHER_KEY_LEN;
  1186. tor_assert(tolen - outlen >= fromlen - pkeylen);
  1187. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  1188. if (r<0)
  1189. goto err;
  1190. memwipe(buf,0,pkeylen);
  1191. tor_free(buf);
  1192. crypto_cipher_free(cipher);
  1193. tor_assert(outlen + fromlen < INT_MAX);
  1194. return (int)(outlen + (fromlen-pkeylen));
  1195. err:
  1196. memwipe(buf,0,pkeylen);
  1197. tor_free(buf);
  1198. crypto_cipher_free(cipher);
  1199. return -1;
  1200. }
  1201. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  1202. * Return -1 on error, or the number of characters used on success.
  1203. */
  1204. int
  1205. crypto_pk_asn1_encode(crypto_pk_t *pk, char *dest, size_t dest_len)
  1206. {
  1207. int len;
  1208. unsigned char *buf = NULL;
  1209. len = i2d_RSAPublicKey(pk->key, &buf);
  1210. if (len < 0 || buf == NULL)
  1211. return -1;
  1212. if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
  1213. OPENSSL_free(buf);
  1214. return -1;
  1215. }
  1216. /* We don't encode directly into 'dest', because that would be illegal
  1217. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  1218. */
  1219. memcpy(dest,buf,len);
  1220. OPENSSL_free(buf);
  1221. return len;
  1222. }
  1223. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  1224. * success and NULL on failure.
  1225. */
  1226. crypto_pk_t *
  1227. crypto_pk_asn1_decode(const char *str, size_t len)
  1228. {
  1229. RSA *rsa;
  1230. unsigned char *buf;
  1231. const unsigned char *cp;
  1232. cp = buf = tor_malloc(len);
  1233. memcpy(buf,str,len);
  1234. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  1235. tor_free(buf);
  1236. if (!rsa) {
  1237. crypto_log_errors(LOG_WARN,"decoding public key");
  1238. return NULL;
  1239. }
  1240. return crypto_new_pk_from_rsa_(rsa);
  1241. }
  1242. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  1243. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  1244. * Return 0 on success, -1 on failure.
  1245. */
  1246. int
  1247. crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
  1248. {
  1249. unsigned char *buf = NULL;
  1250. int len;
  1251. len = i2d_RSAPublicKey((RSA*)pk->key, &buf);
  1252. if (len < 0 || buf == NULL)
  1253. return -1;
  1254. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  1255. OPENSSL_free(buf);
  1256. return -1;
  1257. }
  1258. OPENSSL_free(buf);
  1259. return 0;
  1260. }
  1261. /** Compute all digests of the DER encoding of <b>pk</b>, and store them
  1262. * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
  1263. int
  1264. crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
  1265. {
  1266. unsigned char *buf = NULL;
  1267. int len;
  1268. len = i2d_RSAPublicKey(pk->key, &buf);
  1269. if (len < 0 || buf == NULL)
  1270. return -1;
  1271. if (crypto_common_digests(digests_out, (char*)buf, len) < 0) {
  1272. OPENSSL_free(buf);
  1273. return -1;
  1274. }
  1275. OPENSSL_free(buf);
  1276. return 0;
  1277. }
  1278. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  1279. * every four characters. */
  1280. void
  1281. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  1282. {
  1283. int n = 0;
  1284. char *end = out+outlen;
  1285. tor_assert(outlen < SIZE_T_CEILING);
  1286. while (*in && out<end) {
  1287. *out++ = *in++;
  1288. if (++n == 4 && *in && out<end) {
  1289. n = 0;
  1290. *out++ = ' ';
  1291. }
  1292. }
  1293. tor_assert(out<end);
  1294. *out = '\0';
  1295. }
  1296. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  1297. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  1298. * space). Return 0 on success, -1 on failure.
  1299. *
  1300. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  1301. * of the public key, converted to hexadecimal, in upper case, with a
  1302. * space after every four digits.
  1303. *
  1304. * If <b>add_space</b> is false, omit the spaces.
  1305. */
  1306. int
  1307. crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
  1308. {
  1309. char digest[DIGEST_LEN];
  1310. char hexdigest[HEX_DIGEST_LEN+1];
  1311. if (crypto_pk_get_digest(pk, digest)) {
  1312. return -1;
  1313. }
  1314. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  1315. if (add_space) {
  1316. crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  1317. } else {
  1318. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  1319. }
  1320. return 0;
  1321. }
  1322. /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
  1323. * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
  1324. * bytes of space). Return 0 on success, -1 on failure.
  1325. *
  1326. * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
  1327. * of the ASN.1 encoding of the public key, converted to hexadecimal, in
  1328. * upper case.
  1329. */
  1330. int
  1331. crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
  1332. {
  1333. char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
  1334. if (crypto_pk_get_digest(pk, digest)) {
  1335. return -1;
  1336. }
  1337. if (crypto_digest(hashed_digest, digest, DIGEST_LEN)) {
  1338. return -1;
  1339. }
  1340. base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
  1341. return 0;
  1342. }
  1343. /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
  1344. * Base64 encoding of the DER representation of the private key as a NUL
  1345. * terminated string, and return it via <b>priv_out</b>. Return 0 on
  1346. * sucess, -1 on failure.
  1347. *
  1348. * It is the caller's responsibility to sanitize and free the resulting buffer.
  1349. */
  1350. int
  1351. crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
  1352. {
  1353. unsigned char *der = NULL;
  1354. int der_len;
  1355. int ret = -1;
  1356. *priv_out = NULL;
  1357. der_len = i2d_RSAPrivateKey(pk->key, &der);
  1358. if (der_len < 0 || der == NULL)
  1359. return ret;
  1360. size_t priv_len = base64_encode_size(der_len, 0) + 1;
  1361. char *priv = tor_malloc_zero(priv_len);
  1362. if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
  1363. *priv_out = priv;
  1364. ret = 0;
  1365. } else {
  1366. tor_free(priv);
  1367. }
  1368. memwipe(der, 0, der_len);
  1369. OPENSSL_free(der);
  1370. return ret;
  1371. }
  1372. /** Given a string containing the Base64 encoded DER representation of the
  1373. * private key <b>str</b>, decode and return the result on success, or NULL
  1374. * on failure.
  1375. */
  1376. crypto_pk_t *
  1377. crypto_pk_base64_decode(const char *str, size_t len)
  1378. {
  1379. crypto_pk_t *pk = NULL;
  1380. char *der = tor_malloc_zero(len + 1);
  1381. int der_len = base64_decode(der, len, str, len);
  1382. if (der_len <= 0) {
  1383. log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
  1384. goto out;
  1385. }
  1386. const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
  1387. RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
  1388. if (!rsa) {
  1389. crypto_log_errors(LOG_WARN, "decoding private key");
  1390. goto out;
  1391. }
  1392. pk = crypto_new_pk_from_rsa_(rsa);
  1393. /* Make sure it's valid. */
  1394. if (crypto_pk_check_key(pk) <= 0) {
  1395. crypto_pk_free(pk);
  1396. pk = NULL;
  1397. goto out;
  1398. }
  1399. out:
  1400. memwipe(der, 0, len + 1);
  1401. tor_free(der);
  1402. return pk;
  1403. }
  1404. /* symmetric crypto */
  1405. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1406. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1407. * Does not check for failure.
  1408. */
  1409. int
  1410. crypto_cipher_encrypt(crypto_cipher_t *env, char *to,
  1411. const char *from, size_t fromlen)
  1412. {
  1413. tor_assert(env);
  1414. tor_assert(env);
  1415. tor_assert(from);
  1416. tor_assert(fromlen);
  1417. tor_assert(to);
  1418. tor_assert(fromlen < SIZE_T_CEILING);
  1419. memcpy(to, from, fromlen);
  1420. aes_crypt_inplace(env, to, fromlen);
  1421. return 0;
  1422. }
  1423. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1424. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1425. * Does not check for failure.
  1426. */
  1427. int
  1428. crypto_cipher_decrypt(crypto_cipher_t *env, char *to,
  1429. const char *from, size_t fromlen)
  1430. {
  1431. tor_assert(env);
  1432. tor_assert(from);
  1433. tor_assert(to);
  1434. tor_assert(fromlen < SIZE_T_CEILING);
  1435. memcpy(to, from, fromlen);
  1436. aes_crypt_inplace(env, to, fromlen);
  1437. return 0;
  1438. }
  1439. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  1440. * on success. Does not check for failure.
  1441. */
  1442. void
  1443. crypto_cipher_crypt_inplace(crypto_cipher_t *env, char *buf, size_t len)
  1444. {
  1445. tor_assert(len < SIZE_T_CEILING);
  1446. aes_crypt_inplace(env, buf, len);
  1447. }
  1448. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1449. * <b>key</b> to the buffer in <b>to</b> of length
  1450. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1451. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1452. * number of bytes written, on failure, return -1.
  1453. */
  1454. int
  1455. crypto_cipher_encrypt_with_iv(const char *key,
  1456. char *to, size_t tolen,
  1457. const char *from, size_t fromlen)
  1458. {
  1459. crypto_cipher_t *cipher;
  1460. tor_assert(from);
  1461. tor_assert(to);
  1462. tor_assert(fromlen < INT_MAX);
  1463. if (fromlen < 1)
  1464. return -1;
  1465. if (tolen < fromlen + CIPHER_IV_LEN)
  1466. return -1;
  1467. char iv[CIPHER_IV_LEN];
  1468. crypto_rand(iv, sizeof(iv));
  1469. cipher = crypto_cipher_new_with_iv(key, iv);
  1470. memcpy(to, iv, CIPHER_IV_LEN);
  1471. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1472. crypto_cipher_free(cipher);
  1473. memwipe(iv, 0, sizeof(iv));
  1474. return (int)(fromlen + CIPHER_IV_LEN);
  1475. }
  1476. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1477. * with the key in <b>key</b> to the buffer in <b>to</b> of length
  1478. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1479. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1480. * number of bytes written, on failure, return -1.
  1481. */
  1482. int
  1483. crypto_cipher_decrypt_with_iv(const char *key,
  1484. char *to, size_t tolen,
  1485. const char *from, size_t fromlen)
  1486. {
  1487. crypto_cipher_t *cipher;
  1488. tor_assert(key);
  1489. tor_assert(from);
  1490. tor_assert(to);
  1491. tor_assert(fromlen < INT_MAX);
  1492. if (fromlen <= CIPHER_IV_LEN)
  1493. return -1;
  1494. if (tolen < fromlen - CIPHER_IV_LEN)
  1495. return -1;
  1496. cipher = crypto_cipher_new_with_iv(key, from);
  1497. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1498. crypto_cipher_free(cipher);
  1499. return (int)(fromlen - CIPHER_IV_LEN);
  1500. }
  1501. /* SHA-1 */
  1502. /** Compute the SHA1 digest of the <b>len</b> bytes on data stored in
  1503. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1504. * Return 0 on success, 1 on failure.
  1505. */
  1506. int
  1507. crypto_digest(char *digest, const char *m, size_t len)
  1508. {
  1509. tor_assert(m);
  1510. tor_assert(digest);
  1511. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1512. }
  1513. /** Compute a 256-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1514. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN256-byte result
  1515. * into <b>digest</b>. Return 0 on success, 1 on failure. */
  1516. int
  1517. crypto_digest256(char *digest, const char *m, size_t len,
  1518. digest_algorithm_t algorithm)
  1519. {
  1520. tor_assert(m);
  1521. tor_assert(digest);
  1522. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1523. if (algorithm == DIGEST_SHA256)
  1524. return (SHA256((const uint8_t*)m,len,(uint8_t*)digest) == NULL);
  1525. else
  1526. return (sha3_256((uint8_t *)digest, DIGEST256_LEN,(const uint8_t *)m, len)
  1527. == -1);
  1528. }
  1529. /** Compute a 512-bit digest of <b>len</b> bytes in data stored in <b>m</b>,
  1530. * using the algorithm <b>algorithm</b>. Write the DIGEST_LEN512-byte result
  1531. * into <b>digest</b>. Return 0 on success, 1 on failure. */
  1532. int
  1533. crypto_digest512(char *digest, const char *m, size_t len,
  1534. digest_algorithm_t algorithm)
  1535. {
  1536. tor_assert(m);
  1537. tor_assert(digest);
  1538. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1539. if (algorithm == DIGEST_SHA512)
  1540. return (SHA512((const unsigned char*)m,len,(unsigned char*)digest)
  1541. == NULL);
  1542. else
  1543. return (sha3_512((uint8_t*)digest, DIGEST512_LEN, (const uint8_t*)m, len)
  1544. == -1);
  1545. }
  1546. /** Set the common_digests_t in <b>ds_out</b> to contain every digest on the
  1547. * <b>len</b> bytes in <b>m</b> that we know how to compute. Return 0 on
  1548. * success, -1 on failure. */
  1549. int
  1550. crypto_common_digests(common_digests_t *ds_out, const char *m, size_t len)
  1551. {
  1552. tor_assert(ds_out);
  1553. memset(ds_out, 0, sizeof(*ds_out));
  1554. if (crypto_digest(ds_out->d[DIGEST_SHA1], m, len) < 0)
  1555. return -1;
  1556. if (crypto_digest256(ds_out->d[DIGEST_SHA256], m, len, DIGEST_SHA256) < 0)
  1557. return -1;
  1558. return 0;
  1559. }
  1560. /** Return the name of an algorithm, as used in directory documents. */
  1561. const char *
  1562. crypto_digest_algorithm_get_name(digest_algorithm_t alg)
  1563. {
  1564. switch (alg) {
  1565. case DIGEST_SHA1:
  1566. return "sha1";
  1567. case DIGEST_SHA256:
  1568. return "sha256";
  1569. case DIGEST_SHA512:
  1570. return "sha512";
  1571. case DIGEST_SHA3_256:
  1572. return "sha3-256";
  1573. case DIGEST_SHA3_512:
  1574. return "sha3-512";
  1575. default:
  1576. // LCOV_EXCL_START
  1577. tor_fragile_assert();
  1578. return "??unknown_digest??";
  1579. // LCOV_EXCL_STOP
  1580. }
  1581. }
  1582. /** Given the name of a digest algorithm, return its integer value, or -1 if
  1583. * the name is not recognized. */
  1584. int
  1585. crypto_digest_algorithm_parse_name(const char *name)
  1586. {
  1587. if (!strcmp(name, "sha1"))
  1588. return DIGEST_SHA1;
  1589. else if (!strcmp(name, "sha256"))
  1590. return DIGEST_SHA256;
  1591. else if (!strcmp(name, "sha512"))
  1592. return DIGEST_SHA512;
  1593. else if (!strcmp(name, "sha3-256"))
  1594. return DIGEST_SHA3_256;
  1595. else if (!strcmp(name, "sha3-512"))
  1596. return DIGEST_SHA3_512;
  1597. else
  1598. return -1;
  1599. }
  1600. /** Given an algorithm, return the digest length in bytes. */
  1601. size_t
  1602. crypto_digest_algorithm_get_length(digest_algorithm_t alg)
  1603. {
  1604. switch (alg) {
  1605. case DIGEST_SHA1:
  1606. return DIGEST_LEN;
  1607. case DIGEST_SHA256:
  1608. return DIGEST256_LEN;
  1609. case DIGEST_SHA512:
  1610. return DIGEST512_LEN;
  1611. case DIGEST_SHA3_256:
  1612. return DIGEST256_LEN;
  1613. case DIGEST_SHA3_512:
  1614. return DIGEST512_LEN;
  1615. default:
  1616. tor_assert(0); // LCOV_EXCL_LINE
  1617. return 0; /* Unreachable */ // LCOV_EXCL_LINE
  1618. }
  1619. }
  1620. /** Intermediate information about the digest of a stream of data. */
  1621. struct crypto_digest_t {
  1622. digest_algorithm_t algorithm; /**< Which algorithm is in use? */
  1623. /** State for the digest we're using. Only one member of the
  1624. * union is usable, depending on the value of <b>algorithm</b>. Note also
  1625. * that space for other members might not even be allocated!
  1626. */
  1627. union {
  1628. SHA_CTX sha1; /**< state for SHA1 */
  1629. SHA256_CTX sha2; /**< state for SHA256 */
  1630. SHA512_CTX sha512; /**< state for SHA512 */
  1631. keccak_state sha3; /**< state for SHA3-[256,512] */
  1632. } d;
  1633. };
  1634. /**
  1635. * Return the number of bytes we need to malloc in order to get a
  1636. * crypto_digest_t for <b>alg</b>, or the number of bytes we need to wipe
  1637. * when we free one.
  1638. */
  1639. static size_t
  1640. crypto_digest_alloc_bytes(digest_algorithm_t alg)
  1641. {
  1642. /* Helper: returns the number of bytes in the 'f' field of 'st' */
  1643. #define STRUCT_FIELD_SIZE(st, f) (sizeof( ((st*)0)->f ))
  1644. /* Gives the length of crypto_digest_t through the end of the field 'd' */
  1645. #define END_OF_FIELD(f) (STRUCT_OFFSET(crypto_digest_t, f) + \
  1646. STRUCT_FIELD_SIZE(crypto_digest_t, f))
  1647. switch (alg) {
  1648. case DIGEST_SHA1:
  1649. return END_OF_FIELD(d.sha1);
  1650. case DIGEST_SHA256:
  1651. return END_OF_FIELD(d.sha2);
  1652. case DIGEST_SHA512:
  1653. return END_OF_FIELD(d.sha512);
  1654. case DIGEST_SHA3_256:
  1655. case DIGEST_SHA3_512:
  1656. return END_OF_FIELD(d.sha3);
  1657. default:
  1658. tor_assert(0); // LCOV_EXCL_LINE
  1659. return 0; // LCOV_EXCL_LINE
  1660. }
  1661. #undef END_OF_FIELD
  1662. #undef STRUCT_FIELD_SIZE
  1663. }
  1664. /**
  1665. * Internal function: create and return a new digest object for 'algorithm'.
  1666. * Does not typecheck the algorithm.
  1667. */
  1668. static crypto_digest_t *
  1669. crypto_digest_new_internal(digest_algorithm_t algorithm)
  1670. {
  1671. crypto_digest_t *r = tor_malloc(crypto_digest_alloc_bytes(algorithm));
  1672. r->algorithm = algorithm;
  1673. switch (algorithm)
  1674. {
  1675. case DIGEST_SHA1:
  1676. SHA1_Init(&r->d.sha1);
  1677. break;
  1678. case DIGEST_SHA256:
  1679. SHA256_Init(&r->d.sha2);
  1680. break;
  1681. case DIGEST_SHA512:
  1682. SHA512_Init(&r->d.sha512);
  1683. break;
  1684. case DIGEST_SHA3_256:
  1685. keccak_digest_init(&r->d.sha3, 256);
  1686. break;
  1687. case DIGEST_SHA3_512:
  1688. keccak_digest_init(&r->d.sha3, 512);
  1689. break;
  1690. default:
  1691. tor_assert_unreached();
  1692. }
  1693. return r;
  1694. }
  1695. /** Allocate and return a new digest object to compute SHA1 digests.
  1696. */
  1697. crypto_digest_t *
  1698. crypto_digest_new(void)
  1699. {
  1700. return crypto_digest_new_internal(DIGEST_SHA1);
  1701. }
  1702. /** Allocate and return a new digest object to compute 256-bit digests
  1703. * using <b>algorithm</b>. */
  1704. crypto_digest_t *
  1705. crypto_digest256_new(digest_algorithm_t algorithm)
  1706. {
  1707. tor_assert(algorithm == DIGEST_SHA256 || algorithm == DIGEST_SHA3_256);
  1708. return crypto_digest_new_internal(algorithm);
  1709. }
  1710. /** Allocate and return a new digest object to compute 512-bit digests
  1711. * using <b>algorithm</b>. */
  1712. crypto_digest_t *
  1713. crypto_digest512_new(digest_algorithm_t algorithm)
  1714. {
  1715. tor_assert(algorithm == DIGEST_SHA512 || algorithm == DIGEST_SHA3_512);
  1716. return crypto_digest_new_internal(algorithm);
  1717. }
  1718. /** Deallocate a digest object.
  1719. */
  1720. void
  1721. crypto_digest_free(crypto_digest_t *digest)
  1722. {
  1723. if (!digest)
  1724. return;
  1725. size_t bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1726. memwipe(digest, 0, bytes);
  1727. tor_free(digest);
  1728. }
  1729. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1730. */
  1731. void
  1732. crypto_digest_add_bytes(crypto_digest_t *digest, const char *data,
  1733. size_t len)
  1734. {
  1735. tor_assert(digest);
  1736. tor_assert(data);
  1737. /* Using the SHA*_*() calls directly means we don't support doing
  1738. * SHA in hardware. But so far the delay of getting the question
  1739. * to the hardware, and hearing the answer, is likely higher than
  1740. * just doing it ourselves. Hashes are fast.
  1741. */
  1742. switch (digest->algorithm) {
  1743. case DIGEST_SHA1:
  1744. SHA1_Update(&digest->d.sha1, (void*)data, len);
  1745. break;
  1746. case DIGEST_SHA256:
  1747. SHA256_Update(&digest->d.sha2, (void*)data, len);
  1748. break;
  1749. case DIGEST_SHA512:
  1750. SHA512_Update(&digest->d.sha512, (void*)data, len);
  1751. break;
  1752. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1753. case DIGEST_SHA3_512:
  1754. keccak_digest_update(&digest->d.sha3, (const uint8_t *)data, len);
  1755. break;
  1756. default:
  1757. /* LCOV_EXCL_START */
  1758. tor_fragile_assert();
  1759. break;
  1760. /* LCOV_EXCL_STOP */
  1761. }
  1762. }
  1763. /** Compute the hash of the data that has been passed to the digest
  1764. * object; write the first out_len bytes of the result to <b>out</b>.
  1765. * <b>out_len</b> must be \<= DIGEST512_LEN.
  1766. */
  1767. void
  1768. crypto_digest_get_digest(crypto_digest_t *digest,
  1769. char *out, size_t out_len)
  1770. {
  1771. unsigned char r[DIGEST512_LEN];
  1772. crypto_digest_t tmpenv;
  1773. tor_assert(digest);
  1774. tor_assert(out);
  1775. tor_assert(out_len <= crypto_digest_algorithm_get_length(digest->algorithm));
  1776. /* The SHA-3 code handles copying into a temporary ctx, and also can handle
  1777. * short output buffers by truncating appropriately. */
  1778. if (digest->algorithm == DIGEST_SHA3_256 ||
  1779. digest->algorithm == DIGEST_SHA3_512) {
  1780. keccak_digest_sum(&digest->d.sha3, (uint8_t *)out, out_len);
  1781. return;
  1782. }
  1783. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1784. /* memcpy into a temporary ctx, since SHA*_Final clears the context */
  1785. memcpy(&tmpenv, digest, alloc_bytes);
  1786. switch (digest->algorithm) {
  1787. case DIGEST_SHA1:
  1788. SHA1_Final(r, &tmpenv.d.sha1);
  1789. break;
  1790. case DIGEST_SHA256:
  1791. SHA256_Final(r, &tmpenv.d.sha2);
  1792. break;
  1793. case DIGEST_SHA512:
  1794. SHA512_Final(r, &tmpenv.d.sha512);
  1795. break;
  1796. //LCOV_EXCL_START
  1797. case DIGEST_SHA3_256: /* FALLSTHROUGH */
  1798. case DIGEST_SHA3_512:
  1799. default:
  1800. log_warn(LD_BUG, "Handling unexpected algorithm %d", digest->algorithm);
  1801. /* This is fatal, because it should never happen. */
  1802. tor_assert_unreached();
  1803. break;
  1804. //LCOV_EXCL_STOP
  1805. }
  1806. memcpy(out, r, out_len);
  1807. memwipe(r, 0, sizeof(r));
  1808. }
  1809. /** Allocate and return a new digest object with the same state as
  1810. * <b>digest</b>
  1811. */
  1812. crypto_digest_t *
  1813. crypto_digest_dup(const crypto_digest_t *digest)
  1814. {
  1815. tor_assert(digest);
  1816. const size_t alloc_bytes = crypto_digest_alloc_bytes(digest->algorithm);
  1817. return tor_memdup(digest, alloc_bytes);
  1818. }
  1819. /** Replace the state of the digest object <b>into</b> with the state
  1820. * of the digest object <b>from</b>. Requires that 'into' and 'from'
  1821. * have the same digest type.
  1822. */
  1823. void
  1824. crypto_digest_assign(crypto_digest_t *into,
  1825. const crypto_digest_t *from)
  1826. {
  1827. tor_assert(into);
  1828. tor_assert(from);
  1829. tor_assert(into->algorithm == from->algorithm);
  1830. const size_t alloc_bytes = crypto_digest_alloc_bytes(from->algorithm);
  1831. memcpy(into,from,alloc_bytes);
  1832. }
  1833. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1834. * at <b>digest_out</b> to the hash of the concatenation of those strings,
  1835. * plus the optional string <b>append</b>, computed with the algorithm
  1836. * <b>alg</b>.
  1837. * <b>out_len</b> must be \<= DIGEST512_LEN. */
  1838. void
  1839. crypto_digest_smartlist(char *digest_out, size_t len_out,
  1840. const smartlist_t *lst,
  1841. const char *append,
  1842. digest_algorithm_t alg)
  1843. {
  1844. crypto_digest_smartlist_prefix(digest_out, len_out, NULL, lst, append, alg);
  1845. }
  1846. /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
  1847. * at <b>digest_out</b> to the hash of the concatenation of: the
  1848. * optional string <b>prepend</b>, those strings,
  1849. * and the optional string <b>append</b>, computed with the algorithm
  1850. * <b>alg</b>.
  1851. * <b>len_out</b> must be \<= DIGEST512_LEN. */
  1852. void
  1853. crypto_digest_smartlist_prefix(char *digest_out, size_t len_out,
  1854. const char *prepend,
  1855. const smartlist_t *lst,
  1856. const char *append,
  1857. digest_algorithm_t alg)
  1858. {
  1859. crypto_digest_t *d = crypto_digest_new_internal(alg);
  1860. if (prepend)
  1861. crypto_digest_add_bytes(d, prepend, strlen(prepend));
  1862. SMARTLIST_FOREACH(lst, const char *, cp,
  1863. crypto_digest_add_bytes(d, cp, strlen(cp)));
  1864. if (append)
  1865. crypto_digest_add_bytes(d, append, strlen(append));
  1866. crypto_digest_get_digest(d, digest_out, len_out);
  1867. crypto_digest_free(d);
  1868. }
  1869. /** Compute the HMAC-SHA-256 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1870. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST256_LEN-byte
  1871. * result in <b>hmac_out</b>. Asserts on failure.
  1872. */
  1873. void
  1874. crypto_hmac_sha256(char *hmac_out,
  1875. const char *key, size_t key_len,
  1876. const char *msg, size_t msg_len)
  1877. {
  1878. unsigned char *rv = NULL;
  1879. /* If we've got OpenSSL >=0.9.8 we can use its hmac implementation. */
  1880. tor_assert(key_len < INT_MAX);
  1881. tor_assert(msg_len < INT_MAX);
  1882. tor_assert(hmac_out);
  1883. rv = HMAC(EVP_sha256(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  1884. (unsigned char*)hmac_out, NULL);
  1885. tor_assert(rv);
  1886. }
  1887. /** Compute a MAC using SHA3-256 of <b>msg_len</b> bytes in <b>msg</b> using a
  1888. * <b>key</b> of length <b>key_len</b> and a <b>salt</b> of length
  1889. * <b>salt_len</b>. Store the result of <b>len_out</b> bytes in in
  1890. * <b>mac_out</b>. This function can't fail. */
  1891. void
  1892. crypto_mac_sha3_256(uint8_t *mac_out, size_t len_out,
  1893. const uint8_t *key, size_t key_len,
  1894. const uint8_t *msg, size_t msg_len)
  1895. {
  1896. crypto_digest_t *digest;
  1897. const uint64_t key_len_netorder = tor_htonll(key_len);
  1898. tor_assert(mac_out);
  1899. tor_assert(key);
  1900. tor_assert(msg);
  1901. digest = crypto_digest256_new(DIGEST_SHA3_256);
  1902. /* Order matters here that is any subsystem using this function should
  1903. * expect this very precise ordering in the MAC construction. */
  1904. crypto_digest_add_bytes(digest, (const char *) &key_len_netorder,
  1905. sizeof(key_len_netorder));
  1906. crypto_digest_add_bytes(digest, (const char *) key, key_len);
  1907. crypto_digest_add_bytes(digest, (const char *) msg, msg_len);
  1908. crypto_digest_get_digest(digest, (char *) mac_out, len_out);
  1909. crypto_digest_free(digest);
  1910. }
  1911. /** Internal state for a eXtendable-Output Function (XOF). */
  1912. struct crypto_xof_t {
  1913. keccak_state s;
  1914. };
  1915. /** Allocate a new XOF object backed by SHAKE-256. The security level
  1916. * provided is a function of the length of the output used. Read and
  1917. * understand FIPS-202 A.2 "Additional Consideration for Extendable-Output
  1918. * Functions" before using this construct.
  1919. */
  1920. crypto_xof_t *
  1921. crypto_xof_new(void)
  1922. {
  1923. crypto_xof_t *xof;
  1924. xof = tor_malloc(sizeof(crypto_xof_t));
  1925. keccak_xof_init(&xof->s, 256);
  1926. return xof;
  1927. }
  1928. /** Absorb bytes into a XOF object. Must not be called after a call to
  1929. * crypto_xof_squeeze_bytes() for the same instance, and will assert
  1930. * if attempted.
  1931. */
  1932. void
  1933. crypto_xof_add_bytes(crypto_xof_t *xof, const uint8_t *data, size_t len)
  1934. {
  1935. int i = keccak_xof_absorb(&xof->s, data, len);
  1936. tor_assert(i == 0);
  1937. }
  1938. /** Squeeze bytes out of a XOF object. Calling this routine will render
  1939. * the XOF instance ineligible to absorb further data.
  1940. */
  1941. void
  1942. crypto_xof_squeeze_bytes(crypto_xof_t *xof, uint8_t *out, size_t len)
  1943. {
  1944. int i = keccak_xof_squeeze(&xof->s, out, len);
  1945. tor_assert(i == 0);
  1946. }
  1947. /** Cleanse and deallocate a XOF object. */
  1948. void
  1949. crypto_xof_free(crypto_xof_t *xof)
  1950. {
  1951. if (!xof)
  1952. return;
  1953. memwipe(xof, 0, sizeof(crypto_xof_t));
  1954. tor_free(xof);
  1955. }
  1956. /* DH */
  1957. /** Our DH 'g' parameter */
  1958. #define DH_GENERATOR 2
  1959. /** Shared P parameter for our circuit-crypto DH key exchanges. */
  1960. static BIGNUM *dh_param_p = NULL;
  1961. /** Shared P parameter for our TLS DH key exchanges. */
  1962. static BIGNUM *dh_param_p_tls = NULL;
  1963. /** Shared G parameter for our DH key exchanges. */
  1964. static BIGNUM *dh_param_g = NULL;
  1965. /** Validate a given set of Diffie-Hellman parameters. This is moderately
  1966. * computationally expensive (milliseconds), so should only be called when
  1967. * the DH parameters change. Returns 0 on success, * -1 on failure.
  1968. */
  1969. static int
  1970. crypto_validate_dh_params(const BIGNUM *p, const BIGNUM *g)
  1971. {
  1972. DH *dh = NULL;
  1973. int ret = -1;
  1974. /* Copy into a temporary DH object, just so that DH_check() can be called. */
  1975. if (!(dh = DH_new()))
  1976. goto out;
  1977. #ifdef OPENSSL_1_1_API
  1978. BIGNUM *dh_p, *dh_g;
  1979. if (!(dh_p = BN_dup(p)))
  1980. goto out;
  1981. if (!(dh_g = BN_dup(g)))
  1982. goto out;
  1983. if (!DH_set0_pqg(dh, dh_p, NULL, dh_g))
  1984. goto out;
  1985. #else
  1986. if (!(dh->p = BN_dup(p)))
  1987. goto out;
  1988. if (!(dh->g = BN_dup(g)))
  1989. goto out;
  1990. #endif
  1991. /* Perform the validation. */
  1992. int codes = 0;
  1993. if (!DH_check(dh, &codes))
  1994. goto out;
  1995. if (BN_is_word(g, DH_GENERATOR_2)) {
  1996. /* Per https://wiki.openssl.org/index.php/Diffie-Hellman_parameters
  1997. *
  1998. * OpenSSL checks the prime is congruent to 11 when g = 2; while the
  1999. * IETF's primes are congruent to 23 when g = 2.
  2000. */
  2001. BN_ULONG residue = BN_mod_word(p, 24);
  2002. if (residue == 11 || residue == 23)
  2003. codes &= ~DH_NOT_SUITABLE_GENERATOR;
  2004. }
  2005. if (codes != 0) /* Specifics on why the params suck is irrelevant. */
  2006. goto out;
  2007. /* Things are probably not evil. */
  2008. ret = 0;
  2009. out:
  2010. if (dh)
  2011. DH_free(dh);
  2012. return ret;
  2013. }
  2014. /** Set the global Diffie-Hellman generator, used for both TLS and internal
  2015. * DH stuff.
  2016. */
  2017. static void
  2018. crypto_set_dh_generator(void)
  2019. {
  2020. BIGNUM *generator;
  2021. int r;
  2022. if (dh_param_g)
  2023. return;
  2024. generator = BN_new();
  2025. tor_assert(generator);
  2026. r = BN_set_word(generator, DH_GENERATOR);
  2027. tor_assert(r);
  2028. dh_param_g = generator;
  2029. }
  2030. /** Set the global TLS Diffie-Hellman modulus. Use the Apache mod_ssl DH
  2031. * modulus. */
  2032. void
  2033. crypto_set_tls_dh_prime(void)
  2034. {
  2035. BIGNUM *tls_prime = NULL;
  2036. int r;
  2037. /* If the space is occupied, free the previous TLS DH prime */
  2038. if (BUG(dh_param_p_tls)) {
  2039. /* LCOV_EXCL_START
  2040. *
  2041. * We shouldn't be calling this twice.
  2042. */
  2043. BN_clear_free(dh_param_p_tls);
  2044. dh_param_p_tls = NULL;
  2045. /* LCOV_EXCL_STOP */
  2046. }
  2047. tls_prime = BN_new();
  2048. tor_assert(tls_prime);
  2049. /* This is the 1024-bit safe prime that Apache uses for its DH stuff; see
  2050. * modules/ssl/ssl_engine_dh.c; Apache also uses a generator of 2 with this
  2051. * prime.
  2052. */
  2053. r = BN_hex2bn(&tls_prime,
  2054. "D67DE440CBBBDC1936D693D34AFD0AD50C84D239A45F520BB88174CB98"
  2055. "BCE951849F912E639C72FB13B4B4D7177E16D55AC179BA420B2A29FE324A"
  2056. "467A635E81FF5901377BEDDCFD33168A461AAD3B72DAE8860078045B07A7"
  2057. "DBCA7874087D1510EA9FCC9DDD330507DD62DB88AEAA747DE0F4D6E2BD68"
  2058. "B0E7393E0F24218EB3");
  2059. tor_assert(r);
  2060. tor_assert(tls_prime);
  2061. dh_param_p_tls = tls_prime;
  2062. crypto_set_dh_generator();
  2063. tor_assert(0 == crypto_validate_dh_params(dh_param_p_tls, dh_param_g));
  2064. }
  2065. /** Initialize dh_param_p and dh_param_g if they are not already
  2066. * set. */
  2067. static void
  2068. init_dh_param(void)
  2069. {
  2070. BIGNUM *circuit_dh_prime;
  2071. int r;
  2072. if (BUG(dh_param_p && dh_param_g))
  2073. return; // LCOV_EXCL_LINE This function isn't supposed to be called twice.
  2074. circuit_dh_prime = BN_new();
  2075. tor_assert(circuit_dh_prime);
  2076. /* This is from rfc2409, section 6.2. It's a safe prime, and
  2077. supposedly it equals:
  2078. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  2079. */
  2080. r = BN_hex2bn(&circuit_dh_prime,
  2081. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  2082. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  2083. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  2084. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  2085. "49286651ECE65381FFFFFFFFFFFFFFFF");
  2086. tor_assert(r);
  2087. /* Set the new values as the global DH parameters. */
  2088. dh_param_p = circuit_dh_prime;
  2089. crypto_set_dh_generator();
  2090. tor_assert(0 == crypto_validate_dh_params(dh_param_p, dh_param_g));
  2091. if (!dh_param_p_tls) {
  2092. crypto_set_tls_dh_prime();
  2093. }
  2094. }
  2095. /** Number of bits to use when choosing the x or y value in a Diffie-Hellman
  2096. * handshake. Since we exponentiate by this value, choosing a smaller one
  2097. * lets our handhake go faster.
  2098. */
  2099. #define DH_PRIVATE_KEY_BITS 320
  2100. /** Allocate and return a new DH object for a key exchange. Returns NULL on
  2101. * failure.
  2102. */
  2103. crypto_dh_t *
  2104. crypto_dh_new(int dh_type)
  2105. {
  2106. crypto_dh_t *res = tor_malloc_zero(sizeof(crypto_dh_t));
  2107. tor_assert(dh_type == DH_TYPE_CIRCUIT || dh_type == DH_TYPE_TLS ||
  2108. dh_type == DH_TYPE_REND);
  2109. if (!dh_param_p)
  2110. init_dh_param();
  2111. if (!(res->dh = DH_new()))
  2112. goto err;
  2113. #ifdef OPENSSL_1_1_API
  2114. BIGNUM *dh_p = NULL, *dh_g = NULL;
  2115. if (dh_type == DH_TYPE_TLS) {
  2116. dh_p = BN_dup(dh_param_p_tls);
  2117. } else {
  2118. dh_p = BN_dup(dh_param_p);
  2119. }
  2120. if (!dh_p)
  2121. goto err;
  2122. dh_g = BN_dup(dh_param_g);
  2123. if (!dh_g) {
  2124. BN_free(dh_p);
  2125. goto err;
  2126. }
  2127. if (!DH_set0_pqg(res->dh, dh_p, NULL, dh_g)) {
  2128. goto err;
  2129. }
  2130. if (!DH_set_length(res->dh, DH_PRIVATE_KEY_BITS))
  2131. goto err;
  2132. #else
  2133. if (dh_type == DH_TYPE_TLS) {
  2134. if (!(res->dh->p = BN_dup(dh_param_p_tls)))
  2135. goto err;
  2136. } else {
  2137. if (!(res->dh->p = BN_dup(dh_param_p)))
  2138. goto err;
  2139. }
  2140. if (!(res->dh->g = BN_dup(dh_param_g)))
  2141. goto err;
  2142. res->dh->length = DH_PRIVATE_KEY_BITS;
  2143. #endif
  2144. return res;
  2145. err:
  2146. /* LCOV_EXCL_START
  2147. * This error condition is only reached when an allocation fails */
  2148. crypto_log_errors(LOG_WARN, "creating DH object");
  2149. if (res->dh) DH_free(res->dh); /* frees p and g too */
  2150. tor_free(res);
  2151. return NULL;
  2152. /* LCOV_EXCL_STOP */
  2153. }
  2154. /** Return a copy of <b>dh</b>, sharing its internal state. */
  2155. crypto_dh_t *
  2156. crypto_dh_dup(const crypto_dh_t *dh)
  2157. {
  2158. crypto_dh_t *dh_new = tor_malloc_zero(sizeof(crypto_dh_t));
  2159. tor_assert(dh);
  2160. tor_assert(dh->dh);
  2161. dh_new->dh = dh->dh;
  2162. DH_up_ref(dh->dh);
  2163. return dh_new;
  2164. }
  2165. /** Return the length of the DH key in <b>dh</b>, in bytes.
  2166. */
  2167. int
  2168. crypto_dh_get_bytes(crypto_dh_t *dh)
  2169. {
  2170. tor_assert(dh);
  2171. return DH_size(dh->dh);
  2172. }
  2173. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  2174. * success, -1 on failure.
  2175. */
  2176. int
  2177. crypto_dh_generate_public(crypto_dh_t *dh)
  2178. {
  2179. #ifndef OPENSSL_1_1_API
  2180. again:
  2181. #endif
  2182. if (!DH_generate_key(dh->dh)) {
  2183. /* LCOV_EXCL_START
  2184. * To test this we would need some way to tell openssl to break DH. */
  2185. crypto_log_errors(LOG_WARN, "generating DH key");
  2186. return -1;
  2187. /* LCOV_EXCL_STOP */
  2188. }
  2189. #ifdef OPENSSL_1_1_API
  2190. /* OpenSSL 1.1.x doesn't appear to let you regenerate a DH key, without
  2191. * recreating the DH object. I have no idea what sort of aliasing madness
  2192. * can occur here, so do the check, and just bail on failure.
  2193. */
  2194. const BIGNUM *pub_key, *priv_key;
  2195. DH_get0_key(dh->dh, &pub_key, &priv_key);
  2196. if (tor_check_dh_key(LOG_WARN, pub_key)<0) {
  2197. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  2198. "the-universe chances really do happen. Treating as a failure.");
  2199. return -1;
  2200. }
  2201. #else
  2202. if (tor_check_dh_key(LOG_WARN, dh->dh->pub_key)<0) {
  2203. /* LCOV_EXCL_START
  2204. * If this happens, then openssl's DH implementation is busted. */
  2205. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  2206. "the-universe chances really do happen. Trying again.");
  2207. /* Free and clear the keys, so OpenSSL will actually try again. */
  2208. BN_clear_free(dh->dh->pub_key);
  2209. BN_clear_free(dh->dh->priv_key);
  2210. dh->dh->pub_key = dh->dh->priv_key = NULL;
  2211. goto again;
  2212. /* LCOV_EXCL_STOP */
  2213. }
  2214. #endif
  2215. return 0;
  2216. }
  2217. /** Generate g^x as necessary, and write the g^x for the key exchange
  2218. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  2219. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  2220. */
  2221. int
  2222. crypto_dh_get_public(crypto_dh_t *dh, char *pubkey, size_t pubkey_len)
  2223. {
  2224. int bytes;
  2225. tor_assert(dh);
  2226. const BIGNUM *dh_pub;
  2227. #ifdef OPENSSL_1_1_API
  2228. const BIGNUM *dh_priv;
  2229. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  2230. #else
  2231. dh_pub = dh->dh->pub_key;
  2232. #endif
  2233. if (!dh_pub) {
  2234. if (crypto_dh_generate_public(dh)<0)
  2235. return -1;
  2236. else {
  2237. #ifdef OPENSSL_1_1_API
  2238. DH_get0_key(dh->dh, &dh_pub, &dh_priv);
  2239. #else
  2240. dh_pub = dh->dh->pub_key;
  2241. #endif
  2242. }
  2243. }
  2244. tor_assert(dh_pub);
  2245. bytes = BN_num_bytes(dh_pub);
  2246. tor_assert(bytes >= 0);
  2247. if (pubkey_len < (size_t)bytes) {
  2248. log_warn(LD_CRYPTO,
  2249. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  2250. (int) pubkey_len, bytes);
  2251. return -1;
  2252. }
  2253. memset(pubkey, 0, pubkey_len);
  2254. BN_bn2bin(dh_pub, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  2255. return 0;
  2256. }
  2257. /** Check for bad Diffie-Hellman public keys (g^x). Return 0 if the key is
  2258. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  2259. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  2260. */
  2261. static int
  2262. tor_check_dh_key(int severity, const BIGNUM *bn)
  2263. {
  2264. BIGNUM *x;
  2265. char *s;
  2266. tor_assert(bn);
  2267. x = BN_new();
  2268. tor_assert(x);
  2269. if (BUG(!dh_param_p))
  2270. init_dh_param(); //LCOV_EXCL_LINE we already checked whether we did this.
  2271. BN_set_word(x, 1);
  2272. if (BN_cmp(bn,x)<=0) {
  2273. log_fn(severity, LD_CRYPTO, "DH key must be at least 2.");
  2274. goto err;
  2275. }
  2276. BN_copy(x,dh_param_p);
  2277. BN_sub_word(x, 1);
  2278. if (BN_cmp(bn,x)>=0) {
  2279. log_fn(severity, LD_CRYPTO, "DH key must be at most p-2.");
  2280. goto err;
  2281. }
  2282. BN_clear_free(x);
  2283. return 0;
  2284. err:
  2285. BN_clear_free(x);
  2286. s = BN_bn2hex(bn);
  2287. log_fn(severity, LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  2288. OPENSSL_free(s);
  2289. return -1;
  2290. }
  2291. /** Given a DH key exchange object, and our peer's value of g^y (as a
  2292. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  2293. * <b>secret_bytes_out</b> bytes of shared key material and write them
  2294. * to <b>secret_out</b>. Return the number of bytes generated on success,
  2295. * or -1 on failure.
  2296. *
  2297. * (We generate key material by computing
  2298. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  2299. * where || is concatenation.)
  2300. */
  2301. ssize_t
  2302. crypto_dh_compute_secret(int severity, crypto_dh_t *dh,
  2303. const char *pubkey, size_t pubkey_len,
  2304. char *secret_out, size_t secret_bytes_out)
  2305. {
  2306. char *secret_tmp = NULL;
  2307. BIGNUM *pubkey_bn = NULL;
  2308. size_t secret_len=0, secret_tmp_len=0;
  2309. int result=0;
  2310. tor_assert(dh);
  2311. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  2312. tor_assert(pubkey_len < INT_MAX);
  2313. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  2314. (int)pubkey_len, NULL)))
  2315. goto error;
  2316. if (tor_check_dh_key(severity, pubkey_bn)<0) {
  2317. /* Check for invalid public keys. */
  2318. log_fn(severity, LD_CRYPTO,"Rejected invalid g^x");
  2319. goto error;
  2320. }
  2321. secret_tmp_len = crypto_dh_get_bytes(dh);
  2322. secret_tmp = tor_malloc(secret_tmp_len);
  2323. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  2324. if (result < 0) {
  2325. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  2326. goto error;
  2327. }
  2328. secret_len = result;
  2329. if (crypto_expand_key_material_TAP((uint8_t*)secret_tmp, secret_len,
  2330. (uint8_t*)secret_out, secret_bytes_out)<0)
  2331. goto error;
  2332. secret_len = secret_bytes_out;
  2333. goto done;
  2334. error:
  2335. result = -1;
  2336. done:
  2337. crypto_log_errors(LOG_WARN, "completing DH handshake");
  2338. if (pubkey_bn)
  2339. BN_clear_free(pubkey_bn);
  2340. if (secret_tmp) {
  2341. memwipe(secret_tmp, 0, secret_tmp_len);
  2342. tor_free(secret_tmp);
  2343. }
  2344. if (result < 0)
  2345. return result;
  2346. else
  2347. return secret_len;
  2348. }
  2349. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  2350. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  2351. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  2352. * H(K | [00]) | H(K | [01]) | ....
  2353. *
  2354. * This is the key expansion algorithm used in the "TAP" circuit extension
  2355. * mechanism; it shouldn't be used for new protocols.
  2356. *
  2357. * Return 0 on success, -1 on failure.
  2358. */
  2359. int
  2360. crypto_expand_key_material_TAP(const uint8_t *key_in, size_t key_in_len,
  2361. uint8_t *key_out, size_t key_out_len)
  2362. {
  2363. int i, r = -1;
  2364. uint8_t *cp, *tmp = tor_malloc(key_in_len+1);
  2365. uint8_t digest[DIGEST_LEN];
  2366. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  2367. tor_assert(key_out_len <= DIGEST_LEN*256);
  2368. memcpy(tmp, key_in, key_in_len);
  2369. for (cp = key_out, i=0; cp < key_out+key_out_len;
  2370. ++i, cp += DIGEST_LEN) {
  2371. tmp[key_in_len] = i;
  2372. if (crypto_digest((char*)digest, (const char *)tmp, key_in_len+1))
  2373. goto exit;
  2374. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  2375. }
  2376. r = 0;
  2377. exit:
  2378. memwipe(tmp, 0, key_in_len+1);
  2379. tor_free(tmp);
  2380. memwipe(digest, 0, sizeof(digest));
  2381. return r;
  2382. }
  2383. /** Expand some secret key material according to RFC5869, using SHA256 as the
  2384. * underlying hash. The <b>key_in_len</b> bytes at <b>key_in</b> are the
  2385. * secret key material; the <b>salt_in_len</b> bytes at <b>salt_in</b> and the
  2386. * <b>info_in_len</b> bytes in <b>info_in_len</b> are the algorithm's "salt"
  2387. * and "info" parameters respectively. On success, write <b>key_out_len</b>
  2388. * bytes to <b>key_out</b> and return 0. Assert on failure.
  2389. */
  2390. int
  2391. crypto_expand_key_material_rfc5869_sha256(
  2392. const uint8_t *key_in, size_t key_in_len,
  2393. const uint8_t *salt_in, size_t salt_in_len,
  2394. const uint8_t *info_in, size_t info_in_len,
  2395. uint8_t *key_out, size_t key_out_len)
  2396. {
  2397. uint8_t prk[DIGEST256_LEN];
  2398. uint8_t tmp[DIGEST256_LEN + 128 + 1];
  2399. uint8_t mac[DIGEST256_LEN];
  2400. int i;
  2401. uint8_t *outp;
  2402. size_t tmp_len;
  2403. crypto_hmac_sha256((char*)prk,
  2404. (const char*)salt_in, salt_in_len,
  2405. (const char*)key_in, key_in_len);
  2406. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  2407. tor_assert(key_out_len <= DIGEST256_LEN * 256);
  2408. tor_assert(info_in_len <= 128);
  2409. memset(tmp, 0, sizeof(tmp));
  2410. outp = key_out;
  2411. i = 1;
  2412. while (key_out_len) {
  2413. size_t n;
  2414. if (i > 1) {
  2415. memcpy(tmp, mac, DIGEST256_LEN);
  2416. memcpy(tmp+DIGEST256_LEN, info_in, info_in_len);
  2417. tmp[DIGEST256_LEN+info_in_len] = i;
  2418. tmp_len = DIGEST256_LEN + info_in_len + 1;
  2419. } else {
  2420. memcpy(tmp, info_in, info_in_len);
  2421. tmp[info_in_len] = i;
  2422. tmp_len = info_in_len + 1;
  2423. }
  2424. crypto_hmac_sha256((char*)mac,
  2425. (const char*)prk, DIGEST256_LEN,
  2426. (const char*)tmp, tmp_len);
  2427. n = key_out_len < DIGEST256_LEN ? key_out_len : DIGEST256_LEN;
  2428. memcpy(outp, mac, n);
  2429. key_out_len -= n;
  2430. outp += n;
  2431. ++i;
  2432. }
  2433. memwipe(tmp, 0, sizeof(tmp));
  2434. memwipe(mac, 0, sizeof(mac));
  2435. return 0;
  2436. }
  2437. /** Free a DH key exchange object.
  2438. */
  2439. void
  2440. crypto_dh_free(crypto_dh_t *dh)
  2441. {
  2442. if (!dh)
  2443. return;
  2444. tor_assert(dh->dh);
  2445. DH_free(dh->dh);
  2446. tor_free(dh);
  2447. }
  2448. /* random numbers */
  2449. /** How many bytes of entropy we add at once.
  2450. *
  2451. * This is how much entropy OpenSSL likes to add right now, so maybe it will
  2452. * work for us too. */
  2453. #define ADD_ENTROPY 32
  2454. /** Set the seed of the weak RNG to a random value. */
  2455. void
  2456. crypto_seed_weak_rng(tor_weak_rng_t *rng)
  2457. {
  2458. unsigned seed;
  2459. crypto_rand((void*)&seed, sizeof(seed));
  2460. tor_init_weak_random(rng, seed);
  2461. }
  2462. #ifdef TOR_UNIT_TESTS
  2463. int break_strongest_rng_syscall = 0;
  2464. int break_strongest_rng_fallback = 0;
  2465. #endif
  2466. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2467. * via system calls, storing it into <b>out</b>. Return 0 on success, -1 on
  2468. * failure. A maximum request size of 256 bytes is imposed.
  2469. */
  2470. static int
  2471. crypto_strongest_rand_syscall(uint8_t *out, size_t out_len)
  2472. {
  2473. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  2474. #ifdef TOR_UNIT_TESTS
  2475. if (break_strongest_rng_syscall)
  2476. return -1;
  2477. #endif
  2478. #if defined(_WIN32)
  2479. static int provider_set = 0;
  2480. static HCRYPTPROV provider;
  2481. if (!provider_set) {
  2482. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  2483. CRYPT_VERIFYCONTEXT)) {
  2484. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  2485. return -1;
  2486. }
  2487. provider_set = 1;
  2488. }
  2489. if (!CryptGenRandom(provider, out_len, out)) {
  2490. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  2491. return -1;
  2492. }
  2493. return 0;
  2494. #elif defined(__linux__) && defined(SYS_getrandom)
  2495. static int getrandom_works = 1; /* Be optimitic about our chances... */
  2496. /* getrandom() isn't as straight foward as getentropy(), and has
  2497. * no glibc wrapper.
  2498. *
  2499. * As far as I can tell from getrandom(2) and the source code, the
  2500. * requests we issue will always succeed (though it will block on the
  2501. * call if /dev/urandom isn't seeded yet), since we are NOT specifying
  2502. * GRND_NONBLOCK and the request is <= 256 bytes.
  2503. *
  2504. * The manpage is unclear on what happens if a signal interrupts the call
  2505. * while the request is blocked due to lack of entropy....
  2506. *
  2507. * We optimistically assume that getrandom() is available and functional
  2508. * because it is the way of the future, and 2 branch mispredicts pale in
  2509. * comparision to the overheads involved with failing to open
  2510. * /dev/srandom followed by opening and reading from /dev/urandom.
  2511. */
  2512. if (PREDICT_LIKELY(getrandom_works)) {
  2513. long ret;
  2514. /* A flag of '0' here means to read from '/dev/urandom', and to
  2515. * block if insufficient entropy is available to service the
  2516. * request.
  2517. */
  2518. const unsigned int flags = 0;
  2519. do {
  2520. ret = syscall(SYS_getrandom, out, out_len, flags);
  2521. } while (ret == -1 && ((errno == EINTR) ||(errno == EAGAIN)));
  2522. if (PREDICT_UNLIKELY(ret == -1)) {
  2523. /* LCOV_EXCL_START we can't actually make the syscall fail in testing. */
  2524. tor_assert(errno != EAGAIN);
  2525. tor_assert(errno != EINTR);
  2526. /* Probably ENOSYS. */
  2527. log_warn(LD_CRYPTO, "Can't get entropy from getrandom().");
  2528. getrandom_works = 0; /* Don't bother trying again. */
  2529. return -1;
  2530. /* LCOV_EXCL_STOP */
  2531. }
  2532. tor_assert(ret == (long)out_len);
  2533. return 0;
  2534. }
  2535. return -1; /* getrandom() previously failed unexpectedly. */
  2536. #elif defined(HAVE_GETENTROPY)
  2537. /* getentropy() is what Linux's getrandom() wants to be when it grows up.
  2538. * the only gotcha is that requests are limited to 256 bytes.
  2539. */
  2540. return getentropy(out, out_len);
  2541. #else
  2542. (void) out;
  2543. #endif
  2544. /* This platform doesn't have a supported syscall based random. */
  2545. return -1;
  2546. }
  2547. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2548. * via the per-platform fallback mechanism, storing it into <b>out</b>.
  2549. * Return 0 on success, -1 on failure. A maximum request size of 256 bytes
  2550. * is imposed.
  2551. */
  2552. static int
  2553. crypto_strongest_rand_fallback(uint8_t *out, size_t out_len)
  2554. {
  2555. #ifdef TOR_UNIT_TESTS
  2556. if (break_strongest_rng_fallback)
  2557. return -1;
  2558. #endif
  2559. #ifdef _WIN32
  2560. /* Windows exclusively uses crypto_strongest_rand_syscall(). */
  2561. (void)out;
  2562. (void)out_len;
  2563. return -1;
  2564. #else
  2565. static const char *filenames[] = {
  2566. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  2567. };
  2568. int fd, i;
  2569. size_t n;
  2570. for (i = 0; filenames[i]; ++i) {
  2571. log_debug(LD_FS, "Opening %s for entropy", filenames[i]);
  2572. fd = open(sandbox_intern_string(filenames[i]), O_RDONLY, 0);
  2573. if (fd<0) continue;
  2574. log_info(LD_CRYPTO, "Reading entropy from \"%s\"", filenames[i]);
  2575. n = read_all(fd, (char*)out, out_len, 0);
  2576. close(fd);
  2577. if (n != out_len) {
  2578. /* LCOV_EXCL_START
  2579. * We can't make /dev/foorandom actually fail. */
  2580. log_warn(LD_CRYPTO,
  2581. "Error reading from entropy source (read only %lu bytes).",
  2582. (unsigned long)n);
  2583. return -1;
  2584. /* LCOV_EXCL_STOP */
  2585. }
  2586. return 0;
  2587. }
  2588. return -1;
  2589. #endif
  2590. }
  2591. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2592. * storing it into <b>out</b>. Return 0 on success, -1 on failure. A maximum
  2593. * request size of 256 bytes is imposed.
  2594. */
  2595. STATIC int
  2596. crypto_strongest_rand_raw(uint8_t *out, size_t out_len)
  2597. {
  2598. static const size_t sanity_min_size = 16;
  2599. static const int max_attempts = 3;
  2600. tor_assert(out_len <= MAX_STRONGEST_RAND_SIZE);
  2601. /* For buffers >= 16 bytes (128 bits), we sanity check the output by
  2602. * zero filling the buffer and ensuring that it actually was at least
  2603. * partially modified.
  2604. *
  2605. * Checking that any individual byte is non-zero seems like it would
  2606. * fail too often (p = out_len * 1/256) for comfort, but this is an
  2607. * "adjust according to taste" sort of check.
  2608. */
  2609. memwipe(out, 0, out_len);
  2610. for (int i = 0; i < max_attempts; i++) {
  2611. /* Try to use the syscall/OS favored mechanism to get strong entropy. */
  2612. if (crypto_strongest_rand_syscall(out, out_len) != 0) {
  2613. /* Try to use the less-favored mechanism to get strong entropy. */
  2614. if (crypto_strongest_rand_fallback(out, out_len) != 0) {
  2615. /* Welp, we tried. Hopefully the calling code terminates the process
  2616. * since we're basically boned without good entropy.
  2617. */
  2618. log_warn(LD_CRYPTO,
  2619. "Cannot get strong entropy: no entropy source found.");
  2620. return -1;
  2621. }
  2622. }
  2623. if ((out_len < sanity_min_size) || !tor_mem_is_zero((char*)out, out_len))
  2624. return 0;
  2625. }
  2626. /* LCOV_EXCL_START
  2627. *
  2628. * We tried max_attempts times to fill a buffer >= 128 bits long,
  2629. * and each time it returned all '0's. Either the system entropy
  2630. * source is busted, or the user should go out and buy a ticket to
  2631. * every lottery on the planet.
  2632. */
  2633. log_warn(LD_CRYPTO, "Strong OS entropy returned all zero buffer.");
  2634. return -1;
  2635. /* LCOV_EXCL_STOP */
  2636. }
  2637. /** Try to get <b>out_len</b> bytes of the strongest entropy we can generate,
  2638. * storing it into <b>out</b>.
  2639. */
  2640. void
  2641. crypto_strongest_rand(uint8_t *out, size_t out_len)
  2642. {
  2643. #define DLEN SHA512_DIGEST_LENGTH
  2644. /* We're going to hash DLEN bytes from the system RNG together with some
  2645. * bytes from the openssl PRNG, in order to yield DLEN bytes.
  2646. */
  2647. uint8_t inp[DLEN*2];
  2648. uint8_t tmp[DLEN];
  2649. tor_assert(out);
  2650. while (out_len) {
  2651. crypto_rand((char*) inp, DLEN);
  2652. if (crypto_strongest_rand_raw(inp+DLEN, DLEN) < 0) {
  2653. // LCOV_EXCL_START
  2654. log_err(LD_CRYPTO, "Failed to load strong entropy when generating an "
  2655. "important key. Exiting.");
  2656. /* Die with an assertion so we get a stack trace. */
  2657. tor_assert(0);
  2658. // LCOV_EXCL_STOP
  2659. }
  2660. if (out_len >= DLEN) {
  2661. SHA512(inp, sizeof(inp), out);
  2662. out += DLEN;
  2663. out_len -= DLEN;
  2664. } else {
  2665. SHA512(inp, sizeof(inp), tmp);
  2666. memcpy(out, tmp, out_len);
  2667. break;
  2668. }
  2669. }
  2670. memwipe(tmp, 0, sizeof(tmp));
  2671. memwipe(inp, 0, sizeof(inp));
  2672. #undef DLEN
  2673. }
  2674. /** Seed OpenSSL's random number generator with bytes from the operating
  2675. * system. Return 0 on success, -1 on failure.
  2676. */
  2677. int
  2678. crypto_seed_rng(void)
  2679. {
  2680. int rand_poll_ok = 0, load_entropy_ok = 0;
  2681. uint8_t buf[ADD_ENTROPY];
  2682. /* OpenSSL has a RAND_poll function that knows about more kinds of
  2683. * entropy than we do. We'll try calling that, *and* calling our own entropy
  2684. * functions. If one succeeds, we'll accept the RNG as seeded. */
  2685. rand_poll_ok = RAND_poll();
  2686. if (rand_poll_ok == 0)
  2687. log_warn(LD_CRYPTO, "RAND_poll() failed."); // LCOV_EXCL_LINE
  2688. load_entropy_ok = !crypto_strongest_rand_raw(buf, sizeof(buf));
  2689. if (load_entropy_ok) {
  2690. RAND_seed(buf, sizeof(buf));
  2691. }
  2692. memwipe(buf, 0, sizeof(buf));
  2693. if ((rand_poll_ok || load_entropy_ok) && RAND_status() == 1)
  2694. return 0;
  2695. else
  2696. return -1;
  2697. }
  2698. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Supports mocking
  2699. * for unit tests.
  2700. *
  2701. * This function is not allowed to fail; if it would fail to generate strong
  2702. * entropy, it must terminate the process instead.
  2703. */
  2704. MOCK_IMPL(void,
  2705. crypto_rand, (char *to, size_t n))
  2706. {
  2707. crypto_rand_unmocked(to, n);
  2708. }
  2709. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Most callers
  2710. * will want crypto_rand instead.
  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. void
  2716. crypto_rand_unmocked(char *to, size_t n)
  2717. {
  2718. int r;
  2719. if (n == 0)
  2720. return;
  2721. tor_assert(n < INT_MAX);
  2722. tor_assert(to);
  2723. r = RAND_bytes((unsigned char*)to, (int)n);
  2724. /* We consider a PRNG failure non-survivable. Let's assert so that we get a
  2725. * stack trace about where it happened.
  2726. */
  2727. tor_assert(r >= 0);
  2728. }
  2729. /** Return a pseudorandom integer, chosen uniformly from the values
  2730. * between 0 and <b>max</b>-1 inclusive. <b>max</b> must be between 1 and
  2731. * INT_MAX+1, inclusive. */
  2732. int
  2733. crypto_rand_int(unsigned int max)
  2734. {
  2735. unsigned int val;
  2736. unsigned int cutoff;
  2737. tor_assert(max <= ((unsigned int)INT_MAX)+1);
  2738. tor_assert(max > 0); /* don't div by 0 */
  2739. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2740. * distribution with clipping at the upper end of unsigned int's
  2741. * range.
  2742. */
  2743. cutoff = UINT_MAX - (UINT_MAX%max);
  2744. while (1) {
  2745. crypto_rand((char*)&val, sizeof(val));
  2746. if (val < cutoff)
  2747. return val % max;
  2748. }
  2749. }
  2750. /** Return a pseudorandom integer, chosen uniformly from the values i such
  2751. * that min <= i < max.
  2752. *
  2753. * <b>min</b> MUST be in range [0, <b>max</b>).
  2754. * <b>max</b> MUST be in range (min, INT_MAX].
  2755. */
  2756. int
  2757. crypto_rand_int_range(unsigned int min, unsigned int max)
  2758. {
  2759. tor_assert(min < max);
  2760. tor_assert(max <= INT_MAX);
  2761. /* The overflow is avoided here because crypto_rand_int() returns a value
  2762. * between 0 and (max - min) inclusive. */
  2763. return min + crypto_rand_int(max - min);
  2764. }
  2765. /** As crypto_rand_int_range, but supports uint64_t. */
  2766. uint64_t
  2767. crypto_rand_uint64_range(uint64_t min, uint64_t max)
  2768. {
  2769. tor_assert(min < max);
  2770. return min + crypto_rand_uint64(max - min);
  2771. }
  2772. /** As crypto_rand_int_range, but supports time_t. */
  2773. time_t
  2774. crypto_rand_time_range(time_t min, time_t max)
  2775. {
  2776. tor_assert(min < max);
  2777. return min + (time_t)crypto_rand_uint64(max - min);
  2778. }
  2779. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  2780. * between 0 and <b>max</b>-1 inclusive. */
  2781. uint64_t
  2782. crypto_rand_uint64(uint64_t max)
  2783. {
  2784. uint64_t val;
  2785. uint64_t cutoff;
  2786. tor_assert(max < UINT64_MAX);
  2787. tor_assert(max > 0); /* don't div by 0 */
  2788. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  2789. * distribution with clipping at the upper end of unsigned int's
  2790. * range.
  2791. */
  2792. cutoff = UINT64_MAX - (UINT64_MAX%max);
  2793. while (1) {
  2794. crypto_rand((char*)&val, sizeof(val));
  2795. if (val < cutoff)
  2796. return val % max;
  2797. }
  2798. }
  2799. /** Return a pseudorandom double d, chosen uniformly from the range
  2800. * 0.0 <= d < 1.0.
  2801. */
  2802. double
  2803. crypto_rand_double(void)
  2804. {
  2805. /* We just use an unsigned int here; we don't really care about getting
  2806. * more than 32 bits of resolution */
  2807. unsigned int u;
  2808. crypto_rand((char*)&u, sizeof(u));
  2809. #if SIZEOF_INT == 4
  2810. #define UINT_MAX_AS_DOUBLE 4294967296.0
  2811. #elif SIZEOF_INT == 8
  2812. #define UINT_MAX_AS_DOUBLE 1.8446744073709552e+19
  2813. #else
  2814. #error SIZEOF_INT is neither 4 nor 8
  2815. #endif
  2816. return ((double)u) / UINT_MAX_AS_DOUBLE;
  2817. }
  2818. /** Generate and return a new random hostname starting with <b>prefix</b>,
  2819. * ending with <b>suffix</b>, and containing no fewer than
  2820. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  2821. * characters. Does not check for failure.
  2822. *
  2823. * Clip <b>max_rand_len</b> to MAX_DNS_LABEL_SIZE.
  2824. **/
  2825. char *
  2826. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  2827. const char *suffix)
  2828. {
  2829. char *result, *rand_bytes;
  2830. int randlen, rand_bytes_len;
  2831. size_t resultlen, prefixlen;
  2832. if (max_rand_len > MAX_DNS_LABEL_SIZE)
  2833. max_rand_len = MAX_DNS_LABEL_SIZE;
  2834. if (min_rand_len > max_rand_len)
  2835. min_rand_len = max_rand_len;
  2836. randlen = crypto_rand_int_range(min_rand_len, max_rand_len+1);
  2837. prefixlen = strlen(prefix);
  2838. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  2839. rand_bytes_len = ((randlen*5)+7)/8;
  2840. if (rand_bytes_len % 5)
  2841. rand_bytes_len += 5 - (rand_bytes_len%5);
  2842. rand_bytes = tor_malloc(rand_bytes_len);
  2843. crypto_rand(rand_bytes, rand_bytes_len);
  2844. result = tor_malloc(resultlen);
  2845. memcpy(result, prefix, prefixlen);
  2846. base32_encode(result+prefixlen, resultlen-prefixlen,
  2847. rand_bytes, rand_bytes_len);
  2848. tor_free(rand_bytes);
  2849. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  2850. return result;
  2851. }
  2852. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  2853. * is empty. */
  2854. void *
  2855. smartlist_choose(const smartlist_t *sl)
  2856. {
  2857. int len = smartlist_len(sl);
  2858. if (len)
  2859. return smartlist_get(sl,crypto_rand_int(len));
  2860. return NULL; /* no elements to choose from */
  2861. }
  2862. /** Scramble the elements of <b>sl</b> into a random order. */
  2863. void
  2864. smartlist_shuffle(smartlist_t *sl)
  2865. {
  2866. int i;
  2867. /* From the end of the list to the front, choose at random from the
  2868. positions we haven't looked at yet, and swap that position into the
  2869. current position. Remember to give "no swap" the same probability as
  2870. any other swap. */
  2871. for (i = smartlist_len(sl)-1; i > 0; --i) {
  2872. int j = crypto_rand_int(i+1);
  2873. smartlist_swap(sl, i, j);
  2874. }
  2875. }
  2876. /**
  2877. * Destroy the <b>sz</b> bytes of data stored at <b>mem</b>, setting them to
  2878. * the value <b>byte</b>.
  2879. * If <b>mem</b> is NULL or <b>sz</b> is zero, nothing happens.
  2880. *
  2881. * This function is preferable to memset, since many compilers will happily
  2882. * optimize out memset() when they can convince themselves that the data being
  2883. * cleared will never be read.
  2884. *
  2885. * Right now, our convention is to use this function when we are wiping data
  2886. * that's about to become inaccessible, such as stack buffers that are about
  2887. * to go out of scope or structures that are about to get freed. (In
  2888. * practice, it appears that the compilers we're currently using will optimize
  2889. * out the memset()s for stack-allocated buffers, but not those for
  2890. * about-to-be-freed structures. That could change, though, so we're being
  2891. * wary.) If there are live reads for the data, then you can just use
  2892. * memset().
  2893. */
  2894. void
  2895. memwipe(void *mem, uint8_t byte, size_t sz)
  2896. {
  2897. if (sz == 0) {
  2898. return;
  2899. }
  2900. /* If sz is nonzero, then mem must not be NULL. */
  2901. tor_assert(mem != NULL);
  2902. /* Data this large is likely to be an underflow. */
  2903. tor_assert(sz < SIZE_T_CEILING);
  2904. /* Because whole-program-optimization exists, we may not be able to just
  2905. * have this function call "memset". A smart compiler could inline it, then
  2906. * eliminate dead memsets, and declare itself to be clever. */
  2907. #if defined(SecureZeroMemory) || defined(HAVE_SECUREZEROMEMORY)
  2908. /* Here's what you do on windows. */
  2909. SecureZeroMemory(mem,sz);
  2910. #elif defined(HAVE_RTLSECUREZEROMEMORY)
  2911. RtlSecureZeroMemory(mem,sz);
  2912. #elif defined(HAVE_EXPLICIT_BZERO)
  2913. /* The BSDs provide this. */
  2914. explicit_bzero(mem, sz);
  2915. #elif defined(HAVE_MEMSET_S)
  2916. /* This is in the C99 standard. */
  2917. memset_s(mem, sz, 0, sz);
  2918. #else
  2919. /* This is a slow and ugly function from OpenSSL that fills 'mem' with junk
  2920. * based on the pointer value, then uses that junk to update a global
  2921. * variable. It's an elaborate ruse to trick the compiler into not
  2922. * optimizing out the "wipe this memory" code. Read it if you like zany
  2923. * programming tricks! In later versions of Tor, we should look for better
  2924. * not-optimized-out memory wiping stuff...
  2925. *
  2926. * ...or maybe not. In practice, there are pure-asm implementations of
  2927. * OPENSSL_cleanse() on most platforms, which ought to do the job.
  2928. **/
  2929. OPENSSL_cleanse(mem, sz);
  2930. #endif
  2931. /* Just in case some caller of memwipe() is relying on getting a buffer
  2932. * filled with a particular value, fill the buffer.
  2933. *
  2934. * If this function gets inlined, this memset might get eliminated, but
  2935. * that's okay: We only care about this particular memset in the case where
  2936. * the caller should have been using memset(), and the memset() wouldn't get
  2937. * eliminated. In other words, this is here so that we won't break anything
  2938. * if somebody accidentally calls memwipe() instead of memset().
  2939. **/
  2940. memset(mem, byte, sz);
  2941. }
  2942. #ifndef OPENSSL_THREADS
  2943. #error OpenSSL has been built without thread support. Tor requires an \
  2944. OpenSSL library with thread support enabled.
  2945. #endif
  2946. #ifndef NEW_THREAD_API
  2947. /** Helper: OpenSSL uses this callback to manipulate mutexes. */
  2948. static void
  2949. openssl_locking_cb_(int mode, int n, const char *file, int line)
  2950. {
  2951. (void)file;
  2952. (void)line;
  2953. if (!openssl_mutexes_)
  2954. /* This is not a really good fix for the
  2955. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  2956. * it can't hurt. */
  2957. return;
  2958. if (mode & CRYPTO_LOCK)
  2959. tor_mutex_acquire(openssl_mutexes_[n]);
  2960. else
  2961. tor_mutex_release(openssl_mutexes_[n]);
  2962. }
  2963. static void
  2964. tor_set_openssl_thread_id(CRYPTO_THREADID *threadid)
  2965. {
  2966. CRYPTO_THREADID_set_numeric(threadid, tor_get_thread_id());
  2967. }
  2968. #endif
  2969. #if 0
  2970. /* This code is disabled, because OpenSSL never actually uses these callbacks.
  2971. */
  2972. /** OpenSSL helper type: wraps a Tor mutex so that OpenSSL can use it
  2973. * as a lock. */
  2974. struct CRYPTO_dynlock_value {
  2975. tor_mutex_t *lock;
  2976. };
  2977. /** OpenSSL callback function to allocate a lock: see CRYPTO_set_dynlock_*
  2978. * documentation in OpenSSL's docs for more info. */
  2979. static struct CRYPTO_dynlock_value *
  2980. openssl_dynlock_create_cb_(const char *file, int line)
  2981. {
  2982. struct CRYPTO_dynlock_value *v;
  2983. (void)file;
  2984. (void)line;
  2985. v = tor_malloc(sizeof(struct CRYPTO_dynlock_value));
  2986. v->lock = tor_mutex_new();
  2987. return v;
  2988. }
  2989. /** OpenSSL callback function to acquire or release a lock: see
  2990. * CRYPTO_set_dynlock_* documentation in OpenSSL's docs for more info. */
  2991. static void
  2992. openssl_dynlock_lock_cb_(int mode, struct CRYPTO_dynlock_value *v,
  2993. const char *file, int line)
  2994. {
  2995. (void)file;
  2996. (void)line;
  2997. if (mode & CRYPTO_LOCK)
  2998. tor_mutex_acquire(v->lock);
  2999. else
  3000. tor_mutex_release(v->lock);
  3001. }
  3002. /** OpenSSL callback function to free a lock: see CRYPTO_set_dynlock_*
  3003. * documentation in OpenSSL's docs for more info. */
  3004. static void
  3005. openssl_dynlock_destroy_cb_(struct CRYPTO_dynlock_value *v,
  3006. const char *file, int line)
  3007. {
  3008. (void)file;
  3009. (void)line;
  3010. tor_mutex_free(v->lock);
  3011. tor_free(v);
  3012. }
  3013. #endif
  3014. /** @{ */
  3015. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  3016. * multithreaded. Returns 0. */
  3017. static int
  3018. setup_openssl_threading(void)
  3019. {
  3020. #ifndef NEW_THREAD_API
  3021. int i;
  3022. int n = CRYPTO_num_locks();
  3023. n_openssl_mutexes_ = n;
  3024. openssl_mutexes_ = tor_calloc(n, sizeof(tor_mutex_t *));
  3025. for (i=0; i < n; ++i)
  3026. openssl_mutexes_[i] = tor_mutex_new();
  3027. CRYPTO_set_locking_callback(openssl_locking_cb_);
  3028. CRYPTO_THREADID_set_callback(tor_set_openssl_thread_id);
  3029. #endif
  3030. #if 0
  3031. CRYPTO_set_dynlock_create_callback(openssl_dynlock_create_cb_);
  3032. CRYPTO_set_dynlock_lock_callback(openssl_dynlock_lock_cb_);
  3033. CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy_cb_);
  3034. #endif
  3035. return 0;
  3036. }
  3037. /** Uninitialize the crypto library. Return 0 on success. Does not detect
  3038. * failure.
  3039. */
  3040. int
  3041. crypto_global_cleanup(void)
  3042. {
  3043. EVP_cleanup();
  3044. #ifndef NEW_THREAD_API
  3045. ERR_remove_thread_state(NULL);
  3046. #endif
  3047. ERR_free_strings();
  3048. if (dh_param_p)
  3049. BN_clear_free(dh_param_p);
  3050. if (dh_param_p_tls)
  3051. BN_clear_free(dh_param_p_tls);
  3052. if (dh_param_g)
  3053. BN_clear_free(dh_param_g);
  3054. #ifndef DISABLE_ENGINES
  3055. ENGINE_cleanup();
  3056. #endif
  3057. CONF_modules_unload(1);
  3058. CRYPTO_cleanup_all_ex_data();
  3059. #ifndef NEW_THREAD_API
  3060. if (n_openssl_mutexes_) {
  3061. int n = n_openssl_mutexes_;
  3062. tor_mutex_t **ms = openssl_mutexes_;
  3063. int i;
  3064. openssl_mutexes_ = NULL;
  3065. n_openssl_mutexes_ = 0;
  3066. for (i=0;i<n;++i) {
  3067. tor_mutex_free(ms[i]);
  3068. }
  3069. tor_free(ms);
  3070. }
  3071. #endif
  3072. tor_free(crypto_openssl_version_str);
  3073. tor_free(crypto_openssl_header_version_str);
  3074. return 0;
  3075. }
  3076. /** @} */