crypto.c 75 KB

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