crypto.c 90 KB

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