crypto.c 88 KB

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