crypto.c 88 KB

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