crypto.c 79 KB

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