crypto.c 84 KB

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