crypto.c 91 KB

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