crypto.c 87 KB

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