crypto.c 91 KB

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