crypto.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249
  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-2008, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /* $Id$ */
  7. const char crypto_c_id[] =
  8. "$Id$";
  9. /**
  10. * \file crypto.c
  11. * \brief Wrapper functions to present a consistent interface to
  12. * public-key and symmetric cryptography operations from OpenSSL.
  13. **/
  14. #include "orconfig.h"
  15. #ifdef MS_WINDOWS
  16. #define WIN32_WINNT 0x400
  17. #define _WIN32_WINNT 0x400
  18. #define WIN32_LEAN_AND_MEAN
  19. #include <windows.h>
  20. #include <wincrypt.h>
  21. #endif
  22. #include <openssl/err.h>
  23. #include <openssl/rsa.h>
  24. #include <openssl/pem.h>
  25. #include <openssl/evp.h>
  26. #include <openssl/rand.h>
  27. #include <openssl/opensslv.h>
  28. #include <openssl/bn.h>
  29. #include <openssl/dh.h>
  30. #include <openssl/conf.h>
  31. #include <openssl/hmac.h>
  32. #ifdef HAVE_CTYPE_H
  33. #include <ctype.h>
  34. #endif
  35. #ifdef HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38. #ifdef HAVE_FCNTL_H
  39. #include <fcntl.h>
  40. #endif
  41. #ifdef HAVE_SYS_FCNTL_H
  42. #include <sys/fcntl.h>
  43. #endif
  44. #define CRYPTO_PRIVATE
  45. #include "crypto.h"
  46. #include "log.h"
  47. #include "aes.h"
  48. #include "util.h"
  49. #include "container.h"
  50. #include "compat.h"
  51. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  52. #error "We require openssl >= 0.9.7"
  53. #endif
  54. #include <openssl/engine.h>
  55. /** Macro: is k a valid RSA public or private key? */
  56. #define PUBLIC_KEY_OK(k) ((k) && (k)->key && (k)->key->n)
  57. /** Macro: is k a valid RSA private key? */
  58. #define PRIVATE_KEY_OK(k) ((k) && (k)->key && (k)->key->p)
  59. #ifdef TOR_IS_MULTITHREADED
  60. /** A number of prealloced mutexes for use by openssl. */
  61. static tor_mutex_t **_openssl_mutexes = NULL;
  62. /** How many mutexes have we allocated for use by openssl? */
  63. static int _n_openssl_mutexes = 0;
  64. #endif
  65. /** A public key, or a public/private keypair. */
  66. struct crypto_pk_env_t
  67. {
  68. int refs; /* reference counting so we don't have to copy keys */
  69. RSA *key;
  70. };
  71. /** Key and stream information for a stream cipher. */
  72. struct crypto_cipher_env_t
  73. {
  74. char key[CIPHER_KEY_LEN];
  75. aes_cnt_cipher_t *cipher;
  76. };
  77. /** A structure to hold the first half (x, g^x) of a Diffie-Hellman handshake
  78. * while we're waiting for the second.*/
  79. struct crypto_dh_env_t {
  80. DH *dh;
  81. };
  82. static int setup_openssl_threading(void);
  83. static int tor_check_dh_key(BIGNUM *bn);
  84. /** Return the number of bytes added by padding method <b>padding</b>.
  85. */
  86. static INLINE int
  87. crypto_get_rsa_padding_overhead(int padding)
  88. {
  89. switch (padding)
  90. {
  91. case RSA_NO_PADDING: return 0;
  92. case RSA_PKCS1_OAEP_PADDING: return 42;
  93. case RSA_PKCS1_PADDING: return 11;
  94. default: tor_assert(0); return -1;
  95. }
  96. }
  97. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  98. */
  99. static INLINE int
  100. crypto_get_rsa_padding(int padding)
  101. {
  102. switch (padding)
  103. {
  104. case PK_NO_PADDING: return RSA_NO_PADDING;
  105. case PK_PKCS1_PADDING: return RSA_PKCS1_PADDING;
  106. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  107. default: tor_assert(0); return -1;
  108. }
  109. }
  110. /** Boolean: has OpenSSL's crypto been initialized? */
  111. static int _crypto_global_initialized = 0;
  112. /** Log all pending crypto errors at level <b>severity</b>. Use
  113. * <b>doing</b> to describe our current activities.
  114. */
  115. static void
  116. crypto_log_errors(int severity, const char *doing)
  117. {
  118. unsigned long err;
  119. const char *msg, *lib, *func;
  120. while ((err = ERR_get_error()) != 0) {
  121. msg = (const char*)ERR_reason_error_string(err);
  122. lib = (const char*)ERR_lib_error_string(err);
  123. func = (const char*)ERR_func_error_string(err);
  124. if (!msg) msg = "(null)";
  125. if (!lib) lib = "(null)";
  126. if (!func) func = "(null)";
  127. if (doing) {
  128. log(severity, LD_CRYPTO, "crypto error while %s: %s (in %s:%s)",
  129. doing, msg, lib, func);
  130. } else {
  131. log(severity, LD_CRYPTO, "crypto error: %s (in %s:%s)", msg, lib, func);
  132. }
  133. }
  134. }
  135. /** Log any OpenSSL engines we're using at NOTICE. */
  136. static void
  137. log_engine(const char *fn, ENGINE *e)
  138. {
  139. if (e) {
  140. const char *name, *id;
  141. name = ENGINE_get_name(e);
  142. id = ENGINE_get_id(e);
  143. log(LOG_NOTICE, LD_CRYPTO, "Using OpenSSL engine %s [%s] for %s",
  144. name?name:"?", id?id:"?", fn);
  145. } else {
  146. log(LOG_INFO, LD_CRYPTO, "Using default implementation for %s", fn);
  147. }
  148. }
  149. /** Initialize the crypto library. Return 0 on success, -1 on failure.
  150. */
  151. int
  152. crypto_global_init(int useAccel)
  153. {
  154. if (!_crypto_global_initialized) {
  155. ERR_load_crypto_strings();
  156. OpenSSL_add_all_algorithms();
  157. _crypto_global_initialized = 1;
  158. setup_openssl_threading();
  159. /* XXX the below is a bug, since we can't know if we're supposed
  160. * to be using hardware acceleration or not. we should arrange
  161. * for this function to be called before init_keys. But make it
  162. * not complain loudly, at least until we make acceleration work. */
  163. if (useAccel < 0) {
  164. log_info(LD_CRYPTO, "Initializing OpenSSL via tor_tls_init().");
  165. }
  166. if (useAccel > 0) {
  167. log_info(LD_CRYPTO, "Initializing OpenSSL engine support.");
  168. ENGINE_load_builtin_engines();
  169. if (!ENGINE_register_all_complete())
  170. return -1;
  171. /* XXXX make sure this isn't leaking. */
  172. log_engine("RSA", ENGINE_get_default_RSA());
  173. log_engine("DH", ENGINE_get_default_DH());
  174. log_engine("RAND", ENGINE_get_default_RAND());
  175. log_engine("SHA1", ENGINE_get_digest_engine(NID_sha1));
  176. log_engine("3DES", ENGINE_get_cipher_engine(NID_des_ede3_ecb));
  177. log_engine("AES", ENGINE_get_cipher_engine(NID_aes_128_ecb));
  178. }
  179. }
  180. return 0;
  181. }
  182. /** Free crypto resources held by this thread. */
  183. void
  184. crypto_thread_cleanup(void)
  185. {
  186. ERR_remove_state(0);
  187. }
  188. /** Uninitialize the crypto library. Return 0 on success, -1 on failure.
  189. */
  190. int
  191. crypto_global_cleanup(void)
  192. {
  193. EVP_cleanup();
  194. ERR_remove_state(0);
  195. ERR_free_strings();
  196. ENGINE_cleanup();
  197. CONF_modules_unload(1);
  198. CRYPTO_cleanup_all_ex_data();
  199. #ifdef TOR_IS_MULTITHREADED
  200. if (_n_openssl_mutexes) {
  201. int n = _n_openssl_mutexes;
  202. tor_mutex_t **ms = _openssl_mutexes;
  203. int i;
  204. _openssl_mutexes = NULL;
  205. _n_openssl_mutexes = 0;
  206. for (i=0;i<n;++i) {
  207. tor_mutex_free(ms[i]);
  208. }
  209. tor_free(ms);
  210. }
  211. #endif
  212. return 0;
  213. }
  214. /** used by tortls.c: wrap an RSA* in a crypto_pk_env_t. */
  215. crypto_pk_env_t *
  216. _crypto_new_pk_env_rsa(RSA *rsa)
  217. {
  218. crypto_pk_env_t *env;
  219. tor_assert(rsa);
  220. env = tor_malloc(sizeof(crypto_pk_env_t));
  221. env->refs = 1;
  222. env->key = rsa;
  223. return env;
  224. }
  225. /** used by tortls.c: wrap the RSA from an evp_pkey in a crypto_pk_env_t.
  226. * returns NULL if this isn't an RSA key. */
  227. crypto_pk_env_t *
  228. _crypto_new_pk_env_evp_pkey(EVP_PKEY *pkey)
  229. {
  230. RSA *rsa;
  231. if (!(rsa = EVP_PKEY_get1_RSA(pkey)))
  232. return NULL;
  233. return _crypto_new_pk_env_rsa(rsa);
  234. }
  235. /** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_env_t. Iff
  236. * private is set, include the private-key portion of the key. */
  237. EVP_PKEY *
  238. _crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private)
  239. {
  240. RSA *key = NULL;
  241. EVP_PKEY *pkey = NULL;
  242. tor_assert(env->key);
  243. if (private) {
  244. if (!(key = RSAPrivateKey_dup(env->key)))
  245. goto error;
  246. } else {
  247. if (!(key = RSAPublicKey_dup(env->key)))
  248. goto error;
  249. }
  250. if (!(pkey = EVP_PKEY_new()))
  251. goto error;
  252. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  253. goto error;
  254. return pkey;
  255. error:
  256. if (pkey)
  257. EVP_PKEY_free(pkey);
  258. if (key)
  259. RSA_free(key);
  260. return NULL;
  261. }
  262. /** Used by tortls.c: Get the DH* from a crypto_dh_env_t.
  263. */
  264. DH *
  265. _crypto_dh_env_get_dh(crypto_dh_env_t *dh)
  266. {
  267. return dh->dh;
  268. }
  269. /** Allocate and return storage for a public key. The key itself will not yet
  270. * be set.
  271. */
  272. crypto_pk_env_t *
  273. crypto_new_pk_env(void)
  274. {
  275. RSA *rsa;
  276. rsa = RSA_new();
  277. if (!rsa) return NULL;
  278. return _crypto_new_pk_env_rsa(rsa);
  279. }
  280. /** Release a reference to an asymmetric key; when all the references
  281. * are released, free the key.
  282. */
  283. void
  284. crypto_free_pk_env(crypto_pk_env_t *env)
  285. {
  286. tor_assert(env);
  287. if (--env->refs > 0)
  288. return;
  289. if (env->key)
  290. RSA_free(env->key);
  291. tor_free(env);
  292. }
  293. /** Create a new symmetric cipher for a given key and encryption flag
  294. * (1=encrypt, 0=decrypt). Return the crypto object on success; NULL
  295. * on failure.
  296. */
  297. crypto_cipher_env_t *
  298. crypto_create_init_cipher(const char *key, int encrypt_mode)
  299. {
  300. int r;
  301. crypto_cipher_env_t *crypto = NULL;
  302. if (! (crypto = crypto_new_cipher_env())) {
  303. log_warn(LD_CRYPTO, "Unable to allocate crypto object");
  304. return NULL;
  305. }
  306. if (crypto_cipher_set_key(crypto, key)) {
  307. crypto_log_errors(LOG_WARN, "setting symmetric key");
  308. goto error;
  309. }
  310. if (encrypt_mode)
  311. r = crypto_cipher_encrypt_init_cipher(crypto);
  312. else
  313. r = crypto_cipher_decrypt_init_cipher(crypto);
  314. if (r)
  315. goto error;
  316. return crypto;
  317. error:
  318. if (crypto)
  319. crypto_free_cipher_env(crypto);
  320. return NULL;
  321. }
  322. /** Allocate and return a new symmetric cipher.
  323. */
  324. crypto_cipher_env_t *
  325. crypto_new_cipher_env(void)
  326. {
  327. crypto_cipher_env_t *env;
  328. env = tor_malloc_zero(sizeof(crypto_cipher_env_t));
  329. env->cipher = aes_new_cipher();
  330. return env;
  331. }
  332. /** Free a symmetric cipher.
  333. */
  334. void
  335. crypto_free_cipher_env(crypto_cipher_env_t *env)
  336. {
  337. tor_assert(env);
  338. tor_assert(env->cipher);
  339. aes_free_cipher(env->cipher);
  340. memset(env, 0, sizeof(crypto_cipher_env_t));
  341. tor_free(env);
  342. }
  343. /* public key crypto */
  344. /** Generate a new public/private keypair in <b>env</b>. Return 0 on
  345. * success, -1 on failure.
  346. */
  347. int
  348. crypto_pk_generate_key(crypto_pk_env_t *env)
  349. {
  350. tor_assert(env);
  351. if (env->key)
  352. RSA_free(env->key);
  353. env->key = RSA_generate_key(PK_BYTES*8,65537, NULL, NULL);
  354. if (!env->key) {
  355. crypto_log_errors(LOG_WARN, "generating RSA key");
  356. return -1;
  357. }
  358. return 0;
  359. }
  360. /** Read a PEM-encoded private key from the string <b>s</b> into <b>env</b>.
  361. * Return 0 on success, -1 on failure.
  362. */
  363. /* Used here, and used for testing. */
  364. int
  365. crypto_pk_read_private_key_from_string(crypto_pk_env_t *env,
  366. const char *s)
  367. {
  368. BIO *b;
  369. tor_assert(env);
  370. tor_assert(s);
  371. /* Create a read-only memory BIO, backed by the nul-terminated string 's' */
  372. b = BIO_new_mem_buf((char*)s, -1);
  373. if (env->key)
  374. RSA_free(env->key);
  375. env->key = PEM_read_bio_RSAPrivateKey(b,NULL,NULL,NULL);
  376. BIO_free(b);
  377. if (!env->key) {
  378. crypto_log_errors(LOG_WARN, "Error parsing private key");
  379. return -1;
  380. }
  381. return 0;
  382. }
  383. /** Read a PEM-encoded private key from the file named by
  384. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  385. */
  386. int
  387. crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env,
  388. const char *keyfile)
  389. {
  390. char *contents;
  391. int r;
  392. /* Read the file into a string. */
  393. contents = read_file_to_str(keyfile, 0, NULL);
  394. if (!contents) {
  395. log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
  396. return -1;
  397. }
  398. /* Try to parse it. */
  399. r = crypto_pk_read_private_key_from_string(env, contents);
  400. tor_free(contents);
  401. if (r)
  402. return -1; /* read_private_key_from_string already warned, so we don't.*/
  403. /* Make sure it's valid. */
  404. if (crypto_pk_check_key(env) <= 0)
  405. return -1;
  406. return 0;
  407. }
  408. /** PEM-encode the public key portion of <b>env</b> and write it to a
  409. * newly allocated string. On success, set *<b>dest</b> to the new
  410. * string, *<b>len</b> to the string's length, and return 0. On
  411. * failure, return -1.
  412. */
  413. int
  414. crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest,
  415. size_t *len)
  416. {
  417. BUF_MEM *buf;
  418. BIO *b;
  419. tor_assert(env);
  420. tor_assert(env->key);
  421. tor_assert(dest);
  422. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  423. /* Now you can treat b as if it were a file. Just use the
  424. * PEM_*_bio_* functions instead of the non-bio variants.
  425. */
  426. if (!PEM_write_bio_RSAPublicKey(b, env->key)) {
  427. crypto_log_errors(LOG_WARN, "writing public key to string");
  428. BIO_free(b);
  429. return -1;
  430. }
  431. BIO_get_mem_ptr(b, &buf);
  432. (void)BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  433. BIO_free(b);
  434. tor_assert(buf->length >= 0);
  435. *dest = tor_malloc(buf->length+1);
  436. memcpy(*dest, buf->data, buf->length);
  437. (*dest)[buf->length] = 0; /* nul terminate it */
  438. *len = buf->length;
  439. BUF_MEM_free(buf);
  440. return 0;
  441. }
  442. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  443. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  444. * failure.
  445. */
  446. int
  447. crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src,
  448. size_t len)
  449. {
  450. BIO *b;
  451. tor_assert(env);
  452. tor_assert(src);
  453. tor_assert(len<INT_MAX);
  454. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  455. BIO_write(b, src, (int)len);
  456. if (env->key)
  457. RSA_free(env->key);
  458. env->key = PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  459. BIO_free(b);
  460. if (!env->key) {
  461. crypto_log_errors(LOG_WARN, "reading public key from string");
  462. return -1;
  463. }
  464. return 0;
  465. }
  466. /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
  467. * PEM-encoded. Return 0 on success, -1 on failure.
  468. */
  469. int
  470. crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
  471. const char *fname)
  472. {
  473. BIO *bio;
  474. char *cp;
  475. long len;
  476. char *s;
  477. int r;
  478. tor_assert(PRIVATE_KEY_OK(env));
  479. if (!(bio = BIO_new(BIO_s_mem())))
  480. return -1;
  481. if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
  482. == 0) {
  483. crypto_log_errors(LOG_WARN, "writing private key");
  484. BIO_free(bio);
  485. return -1;
  486. }
  487. len = BIO_get_mem_data(bio, &cp);
  488. tor_assert(len >= 0);
  489. s = tor_malloc(len+1);
  490. memcpy(s, cp, len);
  491. s[len]='\0';
  492. r = write_str_to_file(fname, s, 0);
  493. BIO_free(bio);
  494. tor_free(s);
  495. return r;
  496. }
  497. /** Return true iff <b>env</b> has a valid key.
  498. */
  499. int
  500. crypto_pk_check_key(crypto_pk_env_t *env)
  501. {
  502. int r;
  503. tor_assert(env);
  504. r = RSA_check_key(env->key);
  505. if (r <= 0)
  506. crypto_log_errors(LOG_WARN,"checking RSA key");
  507. return r;
  508. }
  509. /** Compare the public-key components of a and b. Return -1 if a\<b, 0
  510. * if a==b, and 1 if a\>b.
  511. */
  512. int
  513. crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b)
  514. {
  515. int result;
  516. if (!a || !b)
  517. return -1;
  518. if (!a->key || !b->key)
  519. return -1;
  520. tor_assert(PUBLIC_KEY_OK(a));
  521. tor_assert(PUBLIC_KEY_OK(b));
  522. result = BN_cmp((a->key)->n, (b->key)->n);
  523. if (result)
  524. return result;
  525. return BN_cmp((a->key)->e, (b->key)->e);
  526. }
  527. /** Return the size of the public key modulus in <b>env</b>, in bytes. */
  528. size_t
  529. crypto_pk_keysize(crypto_pk_env_t *env)
  530. {
  531. tor_assert(env);
  532. tor_assert(env->key);
  533. return (size_t) RSA_size(env->key);
  534. }
  535. /** Increase the reference count of <b>env</b>, and return it.
  536. */
  537. crypto_pk_env_t *
  538. crypto_pk_dup_key(crypto_pk_env_t *env)
  539. {
  540. tor_assert(env);
  541. tor_assert(env->key);
  542. env->refs++;
  543. return env;
  544. }
  545. /** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
  546. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  547. * write the result to <b>to</b>, and return the number of bytes
  548. * written. On failure, return -1.
  549. */
  550. int
  551. crypto_pk_public_encrypt(crypto_pk_env_t *env, char *to,
  552. const char *from, size_t fromlen, int padding)
  553. {
  554. int r;
  555. tor_assert(env);
  556. tor_assert(from);
  557. tor_assert(to);
  558. tor_assert(fromlen<INT_MAX);
  559. r = RSA_public_encrypt((int)fromlen,
  560. (unsigned char*)from, (unsigned char*)to,
  561. env->key, crypto_get_rsa_padding(padding));
  562. if (r<0) {
  563. crypto_log_errors(LOG_WARN, "performing RSA encryption");
  564. return -1;
  565. }
  566. return r;
  567. }
  568. /** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
  569. * in <b>env</b>, using the padding method <b>padding</b>. On success,
  570. * write the result to <b>to</b>, and return the number of bytes
  571. * written. On failure, return -1.
  572. */
  573. int
  574. crypto_pk_private_decrypt(crypto_pk_env_t *env, char *to,
  575. const char *from, size_t fromlen,
  576. int padding, int warnOnFailure)
  577. {
  578. int r;
  579. tor_assert(env);
  580. tor_assert(from);
  581. tor_assert(to);
  582. tor_assert(env->key);
  583. tor_assert(fromlen<INT_MAX);
  584. if (!env->key->p)
  585. /* Not a private key */
  586. return -1;
  587. r = RSA_private_decrypt((int)fromlen,
  588. (unsigned char*)from, (unsigned char*)to,
  589. env->key, crypto_get_rsa_padding(padding));
  590. if (r<0) {
  591. crypto_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
  592. "performing RSA decryption");
  593. return -1;
  594. }
  595. return r;
  596. }
  597. /** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
  598. * public key in <b>env</b>, using PKCS1 padding. On success, write the
  599. * signed data to <b>to</b>, and return the number of bytes written.
  600. * On failure, return -1.
  601. */
  602. int
  603. crypto_pk_public_checksig(crypto_pk_env_t *env, char *to,
  604. const char *from, size_t fromlen)
  605. {
  606. int r;
  607. tor_assert(env);
  608. tor_assert(from);
  609. tor_assert(to);
  610. tor_assert(fromlen < INT_MAX);
  611. r = RSA_public_decrypt((int)fromlen,
  612. (unsigned char*)from, (unsigned char*)to,
  613. env->key, RSA_PKCS1_PADDING);
  614. if (r<0) {
  615. crypto_log_errors(LOG_WARN, "checking RSA signature");
  616. return -1;
  617. }
  618. return r;
  619. }
  620. /** Check a siglen-byte long signature at <b>sig</b> against
  621. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  622. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  623. * SHA1(data). Else return -1.
  624. */
  625. int
  626. crypto_pk_public_checksig_digest(crypto_pk_env_t *env, const char *data,
  627. size_t datalen, const char *sig, size_t siglen)
  628. {
  629. char digest[DIGEST_LEN];
  630. char *buf;
  631. int r;
  632. tor_assert(env);
  633. tor_assert(data);
  634. tor_assert(sig);
  635. if (crypto_digest(digest,data,datalen)<0) {
  636. log_warn(LD_BUG, "couldn't compute digest");
  637. return -1;
  638. }
  639. buf = tor_malloc(crypto_pk_keysize(env)+1);
  640. r = crypto_pk_public_checksig(env,buf,sig,siglen);
  641. if (r != DIGEST_LEN) {
  642. log_warn(LD_CRYPTO, "Invalid signature");
  643. tor_free(buf);
  644. return -1;
  645. }
  646. if (memcmp(buf, digest, DIGEST_LEN)) {
  647. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  648. tor_free(buf);
  649. return -1;
  650. }
  651. tor_free(buf);
  652. return 0;
  653. }
  654. /** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
  655. * <b>env</b>, using PKCS1 padding. On success, write the signature to
  656. * <b>to</b>, and return the number of bytes written. On failure, return
  657. * -1.
  658. */
  659. int
  660. crypto_pk_private_sign(crypto_pk_env_t *env, char *to,
  661. const char *from, size_t fromlen)
  662. {
  663. int r;
  664. tor_assert(env);
  665. tor_assert(from);
  666. tor_assert(to);
  667. tor_assert(fromlen < INT_MAX);
  668. if (!env->key->p)
  669. /* Not a private key */
  670. return -1;
  671. r = RSA_private_encrypt((int)fromlen,
  672. (unsigned char*)from, (unsigned char*)to,
  673. env->key, RSA_PKCS1_PADDING);
  674. if (r<0) {
  675. crypto_log_errors(LOG_WARN, "generating RSA signature");
  676. return -1;
  677. }
  678. return r;
  679. }
  680. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  681. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  682. * store it in <b>to</b>. Return the number of bytes written on
  683. * success, and -1 on failure.
  684. */
  685. int
  686. crypto_pk_private_sign_digest(crypto_pk_env_t *env, char *to,
  687. const char *from, size_t fromlen)
  688. {
  689. int r;
  690. char digest[DIGEST_LEN];
  691. if (crypto_digest(digest,from,fromlen)<0)
  692. return -1;
  693. r = crypto_pk_private_sign(env,to,digest,DIGEST_LEN);
  694. memset(digest, 0, sizeof(digest));
  695. return r;
  696. }
  697. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  698. * bytes of data from <b>from</b>, with padding type 'padding',
  699. * storing the results on <b>to</b>.
  700. *
  701. * If no padding is used, the public key must be at least as large as
  702. * <b>from</b>.
  703. *
  704. * Returns the number of bytes written on success, -1 on failure.
  705. *
  706. * The encrypted data consists of:
  707. * - The source data, padded and encrypted with the public key, if the
  708. * padded source data is no longer than the public key, and <b>force</b>
  709. * is false, OR
  710. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  711. * padded and encrypted with the public key; followed by the rest of
  712. * the source data encrypted in AES-CTR mode with the symmetric key.
  713. */
  714. int
  715. crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env,
  716. char *to,
  717. const char *from,
  718. size_t fromlen,
  719. int padding, int force)
  720. {
  721. int overhead, outlen, r;
  722. size_t pkeylen, symlen;
  723. crypto_cipher_env_t *cipher = NULL;
  724. char *buf = NULL;
  725. tor_assert(env);
  726. tor_assert(from);
  727. tor_assert(to);
  728. overhead = crypto_get_rsa_padding_overhead(crypto_get_rsa_padding(padding));
  729. pkeylen = crypto_pk_keysize(env);
  730. if (padding == PK_NO_PADDING && fromlen < pkeylen)
  731. return -1;
  732. if (!force && fromlen+overhead <= pkeylen) {
  733. /* It all fits in a single encrypt. */
  734. return crypto_pk_public_encrypt(env,to,from,fromlen,padding);
  735. }
  736. cipher = crypto_new_cipher_env();
  737. if (!cipher) return -1;
  738. if (crypto_cipher_generate_key(cipher)<0)
  739. goto err;
  740. /* You can't just run around RSA-encrypting any bitstream: if it's
  741. * greater than the RSA key, then OpenSSL will happily encrypt, and
  742. * later decrypt to the wrong value. So we set the first bit of
  743. * 'cipher->key' to 0 if we aren't padding. This means that our
  744. * symmetric key is really only 127 bits.
  745. */
  746. if (padding == PK_NO_PADDING)
  747. cipher->key[0] &= 0x7f;
  748. if (crypto_cipher_encrypt_init_cipher(cipher)<0)
  749. goto err;
  750. buf = tor_malloc(pkeylen+1);
  751. memcpy(buf, cipher->key, CIPHER_KEY_LEN);
  752. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  753. /* Length of symmetrically encrypted data. */
  754. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  755. outlen = crypto_pk_public_encrypt(env,to,buf,pkeylen-overhead,padding);
  756. if (outlen!=(int)pkeylen) {
  757. goto err;
  758. }
  759. r = crypto_cipher_encrypt(cipher, to+outlen,
  760. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  761. if (r<0) goto err;
  762. memset(buf, 0, pkeylen);
  763. tor_free(buf);
  764. crypto_free_cipher_env(cipher);
  765. tor_assert(outlen+symlen < INT_MAX);
  766. return (int)(outlen + symlen);
  767. err:
  768. if (buf) {
  769. memset(buf, 0, pkeylen);
  770. tor_free(buf);
  771. }
  772. if (cipher) crypto_free_cipher_env(cipher);
  773. return -1;
  774. }
  775. /** Invert crypto_pk_public_hybrid_encrypt. */
  776. int
  777. crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
  778. char *to,
  779. const char *from,
  780. size_t fromlen,
  781. int padding, int warnOnFailure)
  782. {
  783. int outlen, r;
  784. size_t pkeylen;
  785. crypto_cipher_env_t *cipher = NULL;
  786. char *buf = NULL;
  787. pkeylen = crypto_pk_keysize(env);
  788. if (fromlen <= pkeylen) {
  789. return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
  790. warnOnFailure);
  791. }
  792. buf = tor_malloc(pkeylen+1);
  793. outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
  794. warnOnFailure);
  795. if (outlen<0) {
  796. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  797. "Error decrypting public-key data");
  798. goto err;
  799. }
  800. if (outlen < CIPHER_KEY_LEN) {
  801. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  802. "No room for a symmetric key");
  803. goto err;
  804. }
  805. cipher = crypto_create_init_cipher(buf, 0);
  806. if (!cipher) {
  807. goto err;
  808. }
  809. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  810. outlen -= CIPHER_KEY_LEN;
  811. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  812. if (r<0)
  813. goto err;
  814. memset(buf,0,pkeylen);
  815. tor_free(buf);
  816. crypto_free_cipher_env(cipher);
  817. tor_assert(outlen + fromlen < INT_MAX);
  818. return (int)(outlen + (fromlen-pkeylen));
  819. err:
  820. memset(buf,0,pkeylen);
  821. tor_free(buf);
  822. if (cipher) crypto_free_cipher_env(cipher);
  823. return -1;
  824. }
  825. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  826. * Return -1 on error, or the number of characters used on success.
  827. */
  828. int
  829. crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, size_t dest_len)
  830. {
  831. int len;
  832. unsigned char *buf, *cp;
  833. len = i2d_RSAPublicKey(pk->key, NULL);
  834. if (len < 0 || (size_t)len > dest_len)
  835. return -1;
  836. cp = buf = tor_malloc(len+1);
  837. len = i2d_RSAPublicKey(pk->key, &cp);
  838. if (len < 0) {
  839. crypto_log_errors(LOG_WARN,"encoding public key");
  840. tor_free(buf);
  841. return -1;
  842. }
  843. /* We don't encode directly into 'dest', because that would be illegal
  844. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  845. */
  846. memcpy(dest,buf,len);
  847. tor_free(buf);
  848. return len;
  849. }
  850. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  851. * success and NULL on failure.
  852. */
  853. crypto_pk_env_t *
  854. crypto_pk_asn1_decode(const char *str, size_t len)
  855. {
  856. RSA *rsa;
  857. unsigned char *buf;
  858. /* This ifdef suppresses a type warning. Take out the first case once
  859. * everybody is using openssl 0.9.7 or later.
  860. */
  861. const unsigned char *cp;
  862. cp = buf = tor_malloc(len);
  863. memcpy(buf,str,len);
  864. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  865. tor_free(buf);
  866. if (!rsa) {
  867. crypto_log_errors(LOG_WARN,"decoding public key");
  868. return NULL;
  869. }
  870. return _crypto_new_pk_env_rsa(rsa);
  871. }
  872. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  873. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  874. * Return 0 on success, -1 on failure.
  875. */
  876. int
  877. crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
  878. {
  879. unsigned char *buf, *bufp;
  880. int len;
  881. len = i2d_RSAPublicKey(pk->key, NULL);
  882. if (len < 0)
  883. return -1;
  884. buf = bufp = tor_malloc(len+1);
  885. len = i2d_RSAPublicKey(pk->key, &bufp);
  886. if (len < 0) {
  887. crypto_log_errors(LOG_WARN,"encoding public key");
  888. tor_free(buf);
  889. return -1;
  890. }
  891. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  892. tor_free(buf);
  893. return -1;
  894. }
  895. tor_free(buf);
  896. return 0;
  897. }
  898. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  899. * every four spaces. */
  900. /* static */ void
  901. add_spaces_to_fp(char *out, size_t outlen, const char *in)
  902. {
  903. int n = 0;
  904. char *end = out+outlen;
  905. while (*in && out<end) {
  906. *out++ = *in++;
  907. if (++n == 4 && *in && out<end) {
  908. n = 0;
  909. *out++ = ' ';
  910. }
  911. }
  912. tor_assert(out<end);
  913. *out = '\0';
  914. }
  915. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  916. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  917. * space). Return 0 on success, -1 on failure.
  918. *
  919. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  920. * of the public key, converted to hexadecimal, in upper case, with a
  921. * space after every four digits.
  922. *
  923. * If <b>add_space</b> is false, omit the spaces.
  924. */
  925. int
  926. crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
  927. {
  928. char digest[DIGEST_LEN];
  929. char hexdigest[HEX_DIGEST_LEN+1];
  930. if (crypto_pk_get_digest(pk, digest)) {
  931. return -1;
  932. }
  933. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  934. if (add_space) {
  935. add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  936. } else {
  937. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  938. }
  939. return 0;
  940. }
  941. /** Return true iff <b>s</b> is in the correct format for a fingerprint.
  942. */
  943. int
  944. crypto_pk_check_fingerprint_syntax(const char *s)
  945. {
  946. int i;
  947. for (i = 0; i < FINGERPRINT_LEN; ++i) {
  948. if ((i%5) == 4) {
  949. if (!TOR_ISSPACE(s[i])) return 0;
  950. } else {
  951. if (!TOR_ISXDIGIT(s[i])) return 0;
  952. }
  953. }
  954. if (s[FINGERPRINT_LEN]) return 0;
  955. return 1;
  956. }
  957. /* symmetric crypto */
  958. /** Generate a new random key for the symmetric cipher in <b>env</b>.
  959. * Return 0 on success, -1 on failure. Does not initialize the cipher.
  960. */
  961. int
  962. crypto_cipher_generate_key(crypto_cipher_env_t *env)
  963. {
  964. tor_assert(env);
  965. return crypto_rand(env->key, CIPHER_KEY_LEN);
  966. }
  967. /** Set the symmetric key for the cipher in <b>env</b> to the first
  968. * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
  969. * Return 0 on success, -1 on failure.
  970. */
  971. int
  972. crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
  973. {
  974. tor_assert(env);
  975. tor_assert(key);
  976. if (!env->key)
  977. return -1;
  978. memcpy(env->key, key, CIPHER_KEY_LEN);
  979. return 0;
  980. }
  981. /** Generate an initialization vector for our AES-CTR cipher; store it
  982. * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
  983. void
  984. crypto_cipher_generate_iv(char *iv_out)
  985. {
  986. crypto_rand(iv_out, CIPHER_IV_LEN);
  987. }
  988. /** Adjust the counter of <b>env</b> to point to the first byte of the block
  989. * corresponding to the encryption of the CIPHER_IV_LEN bytes at
  990. * <b>iv</b>. */
  991. int
  992. crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
  993. {
  994. tor_assert(env);
  995. tor_assert(iv);
  996. aes_set_iv(env->cipher, iv);
  997. return 0;
  998. }
  999. /** Return a pointer to the key set for the cipher in <b>env</b>.
  1000. */
  1001. const char *
  1002. crypto_cipher_get_key(crypto_cipher_env_t *env)
  1003. {
  1004. return env->key;
  1005. }
  1006. /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
  1007. * success, -1 on failure.
  1008. */
  1009. int
  1010. crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
  1011. {
  1012. tor_assert(env);
  1013. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  1014. return 0;
  1015. }
  1016. /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
  1017. * success, -1 on failure.
  1018. */
  1019. int
  1020. crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
  1021. {
  1022. tor_assert(env);
  1023. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  1024. return 0;
  1025. }
  1026. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1027. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1028. * On failure, return -1.
  1029. */
  1030. int
  1031. crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
  1032. const char *from, size_t fromlen)
  1033. {
  1034. tor_assert(env);
  1035. tor_assert(env->cipher);
  1036. tor_assert(from);
  1037. tor_assert(fromlen);
  1038. tor_assert(to);
  1039. aes_crypt(env->cipher, from, fromlen, to);
  1040. return 0;
  1041. }
  1042. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1043. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1044. * On failure, return -1.
  1045. */
  1046. int
  1047. crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
  1048. const char *from, size_t fromlen)
  1049. {
  1050. tor_assert(env);
  1051. tor_assert(from);
  1052. tor_assert(to);
  1053. aes_crypt(env->cipher, from, fromlen, to);
  1054. return 0;
  1055. }
  1056. /** Encrypt <b>len</b> bytes on <b>from</b> using the cipher in <b>env</b>;
  1057. * on success, return 0. On failure, return -1.
  1058. */
  1059. int
  1060. crypto_cipher_crypt_inplace(crypto_cipher_env_t *env, char *buf, size_t len)
  1061. {
  1062. aes_crypt_inplace(env->cipher, buf, len);
  1063. return 0;
  1064. }
  1065. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1066. * <b>cipher</b> to the buffer in <b>to</b> of length
  1067. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1068. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1069. * number of bytes written, on failure, return -1.
  1070. *
  1071. * This function adjusts the current position of the counter in <b>cipher</b>
  1072. * to immediately after the encrypted data.
  1073. */
  1074. int
  1075. crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
  1076. char *to, size_t tolen,
  1077. const char *from, size_t fromlen)
  1078. {
  1079. tor_assert(cipher);
  1080. tor_assert(from);
  1081. tor_assert(to);
  1082. tor_assert(fromlen < INT_MAX);
  1083. if (fromlen < 1)
  1084. return -1;
  1085. if (tolen < fromlen + CIPHER_IV_LEN)
  1086. return -1;
  1087. crypto_cipher_generate_iv(to);
  1088. if (crypto_cipher_set_iv(cipher, to)<0)
  1089. return -1;
  1090. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1091. return (int)(fromlen + CIPHER_IV_LEN);
  1092. }
  1093. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1094. * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
  1095. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1096. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1097. * number of bytes written, on failure, return -1.
  1098. *
  1099. * This function adjusts the current position of the counter in <b>cipher</b>
  1100. * to immediately after the decrypted data.
  1101. */
  1102. int
  1103. crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
  1104. char *to, size_t tolen,
  1105. const char *from, size_t fromlen)
  1106. {
  1107. tor_assert(cipher);
  1108. tor_assert(from);
  1109. tor_assert(to);
  1110. tor_assert(fromlen < INT_MAX);
  1111. if (fromlen <= CIPHER_IV_LEN)
  1112. return -1;
  1113. if (tolen < fromlen - CIPHER_IV_LEN)
  1114. return -1;
  1115. if (crypto_cipher_set_iv(cipher, from)<0)
  1116. return -1;
  1117. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1118. return (int)(fromlen - CIPHER_IV_LEN);
  1119. }
  1120. /* SHA-1 */
  1121. /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
  1122. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1123. * Return 0 on success, -1 on failure.
  1124. */
  1125. int
  1126. crypto_digest(char *digest, const char *m, size_t len)
  1127. {
  1128. tor_assert(m);
  1129. tor_assert(digest);
  1130. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1131. }
  1132. /** Intermediate information about the digest of a stream of data. */
  1133. struct crypto_digest_env_t {
  1134. SHA_CTX d;
  1135. };
  1136. /** Allocate and return a new digest object.
  1137. */
  1138. crypto_digest_env_t *
  1139. crypto_new_digest_env(void)
  1140. {
  1141. crypto_digest_env_t *r;
  1142. r = tor_malloc(sizeof(crypto_digest_env_t));
  1143. SHA1_Init(&r->d);
  1144. return r;
  1145. }
  1146. /** Deallocate a digest object.
  1147. */
  1148. void
  1149. crypto_free_digest_env(crypto_digest_env_t *digest)
  1150. {
  1151. memset(digest, 0, sizeof(crypto_digest_env_t));
  1152. tor_free(digest);
  1153. }
  1154. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1155. */
  1156. void
  1157. crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
  1158. size_t len)
  1159. {
  1160. tor_assert(digest);
  1161. tor_assert(data);
  1162. /* Using the SHA1_*() calls directly means we don't support doing
  1163. * sha1 in hardware. But so far the delay of getting the question
  1164. * to the hardware, and hearing the answer, is likely higher than
  1165. * just doing it ourselves. Hashes are fast.
  1166. */
  1167. SHA1_Update(&digest->d, (void*)data, len);
  1168. }
  1169. /** Compute the hash of the data that has been passed to the digest
  1170. * object; write the first out_len bytes of the result to <b>out</b>.
  1171. * <b>out_len</b> must be \<= DIGEST_LEN.
  1172. */
  1173. void
  1174. crypto_digest_get_digest(crypto_digest_env_t *digest,
  1175. char *out, size_t out_len)
  1176. {
  1177. unsigned char r[DIGEST_LEN];
  1178. SHA_CTX tmpctx;
  1179. tor_assert(digest);
  1180. tor_assert(out);
  1181. tor_assert(out_len <= DIGEST_LEN);
  1182. /* memcpy into a temporary ctx, since SHA1_Final clears the context */
  1183. memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
  1184. SHA1_Final(r, &tmpctx);
  1185. memcpy(out, r, out_len);
  1186. memset(r, 0, sizeof(r));
  1187. }
  1188. /** Allocate and return a new digest object with the same state as
  1189. * <b>digest</b>
  1190. */
  1191. crypto_digest_env_t *
  1192. crypto_digest_dup(const crypto_digest_env_t *digest)
  1193. {
  1194. crypto_digest_env_t *r;
  1195. tor_assert(digest);
  1196. r = tor_malloc(sizeof(crypto_digest_env_t));
  1197. memcpy(r,digest,sizeof(crypto_digest_env_t));
  1198. return r;
  1199. }
  1200. /** Replace the state of the digest object <b>into</b> with the state
  1201. * of the digest object <b>from</b>.
  1202. */
  1203. void
  1204. crypto_digest_assign(crypto_digest_env_t *into,
  1205. const crypto_digest_env_t *from)
  1206. {
  1207. tor_assert(into);
  1208. tor_assert(from);
  1209. memcpy(into,from,sizeof(crypto_digest_env_t));
  1210. }
  1211. /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1212. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
  1213. * in <b>hmac_out</b>.
  1214. */
  1215. void
  1216. crypto_hmac_sha1(char *hmac_out,
  1217. const char *key, size_t key_len,
  1218. const char *msg, size_t msg_len)
  1219. {
  1220. tor_assert(key_len < INT_MAX);
  1221. tor_assert(msg_len < INT_MAX);
  1222. HMAC(EVP_sha1(), key, (int)key_len, (unsigned char*)msg, (int)msg_len,
  1223. (unsigned char*)hmac_out, NULL);
  1224. }
  1225. /* DH */
  1226. /** Shared P parameter for our DH key exchanged. */
  1227. static BIGNUM *dh_param_p = NULL;
  1228. /** Shared G parameter for our DH key exchanges. */
  1229. static BIGNUM *dh_param_g = NULL;
  1230. /** Initialize dh_param_p and dh_param_g if they are not already
  1231. * set. */
  1232. static void
  1233. init_dh_param(void)
  1234. {
  1235. BIGNUM *p, *g;
  1236. int r;
  1237. if (dh_param_p && dh_param_g)
  1238. return;
  1239. p = BN_new();
  1240. g = BN_new();
  1241. tor_assert(p);
  1242. tor_assert(g);
  1243. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1244. supposedly it equals:
  1245. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1246. */
  1247. r = BN_hex2bn(&p,
  1248. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1249. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1250. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1251. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1252. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1253. tor_assert(r);
  1254. r = BN_set_word(g, 2);
  1255. tor_assert(r);
  1256. dh_param_p = p;
  1257. dh_param_g = g;
  1258. }
  1259. #define DH_PRIVATE_KEY_BITS 320
  1260. /** Allocate and return a new DH object for a key exchange.
  1261. */
  1262. crypto_dh_env_t *
  1263. crypto_dh_new(void)
  1264. {
  1265. crypto_dh_env_t *res = NULL;
  1266. if (!dh_param_p)
  1267. init_dh_param();
  1268. res = tor_malloc_zero(sizeof(crypto_dh_env_t));
  1269. if (!(res->dh = DH_new()))
  1270. goto err;
  1271. if (!(res->dh->p = BN_dup(dh_param_p)))
  1272. goto err;
  1273. if (!(res->dh->g = BN_dup(dh_param_g)))
  1274. goto err;
  1275. res->dh->length = DH_PRIVATE_KEY_BITS;
  1276. return res;
  1277. err:
  1278. crypto_log_errors(LOG_WARN, "creating DH object");
  1279. if (res && res->dh) DH_free(res->dh); /* frees p and g too */
  1280. if (res) tor_free(res);
  1281. return NULL;
  1282. }
  1283. /** Return the length of the DH key in <b>dh</b>, in bytes.
  1284. */
  1285. int
  1286. crypto_dh_get_bytes(crypto_dh_env_t *dh)
  1287. {
  1288. tor_assert(dh);
  1289. return DH_size(dh->dh);
  1290. }
  1291. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  1292. * success, -1 on failure.
  1293. */
  1294. int
  1295. crypto_dh_generate_public(crypto_dh_env_t *dh)
  1296. {
  1297. again:
  1298. if (!DH_generate_key(dh->dh)) {
  1299. crypto_log_errors(LOG_WARN, "generating DH key");
  1300. return -1;
  1301. }
  1302. if (tor_check_dh_key(dh->dh->pub_key)<0) {
  1303. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  1304. "the-universe chances really do happen. Trying again.");
  1305. /* Free and clear the keys, so openssl will actually try again. */
  1306. BN_free(dh->dh->pub_key);
  1307. BN_free(dh->dh->priv_key);
  1308. dh->dh->pub_key = dh->dh->priv_key = NULL;
  1309. goto again;
  1310. }
  1311. return 0;
  1312. }
  1313. /** Generate g^x as necessary, and write the g^x for the key exchange
  1314. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  1315. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  1316. */
  1317. int
  1318. crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
  1319. {
  1320. int bytes;
  1321. tor_assert(dh);
  1322. if (!dh->dh->pub_key) {
  1323. if (crypto_dh_generate_public(dh)<0)
  1324. return -1;
  1325. }
  1326. tor_assert(dh->dh->pub_key);
  1327. bytes = BN_num_bytes(dh->dh->pub_key);
  1328. tor_assert(bytes >= 0);
  1329. if (pubkey_len < (size_t)bytes) {
  1330. log_warn(LD_CRYPTO,
  1331. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  1332. (int) pubkey_len, bytes);
  1333. return -1;
  1334. }
  1335. memset(pubkey, 0, pubkey_len);
  1336. BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  1337. return 0;
  1338. }
  1339. /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
  1340. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  1341. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  1342. */
  1343. static int
  1344. tor_check_dh_key(BIGNUM *bn)
  1345. {
  1346. BIGNUM *x;
  1347. char *s;
  1348. tor_assert(bn);
  1349. x = BN_new();
  1350. tor_assert(x);
  1351. if (!dh_param_p)
  1352. init_dh_param();
  1353. BN_set_word(x, 1);
  1354. if (BN_cmp(bn,x)<=0) {
  1355. log_warn(LD_CRYPTO, "DH key must be at least 2.");
  1356. goto err;
  1357. }
  1358. BN_copy(x,dh_param_p);
  1359. BN_sub_word(x, 1);
  1360. if (BN_cmp(bn,x)>=0) {
  1361. log_warn(LD_CRYPTO, "DH key must be at most p-2.");
  1362. goto err;
  1363. }
  1364. BN_free(x);
  1365. return 0;
  1366. err:
  1367. BN_free(x);
  1368. s = BN_bn2hex(bn);
  1369. log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  1370. OPENSSL_free(s);
  1371. return -1;
  1372. }
  1373. #undef MIN
  1374. #define MIN(a,b) ((a)<(b)?(a):(b))
  1375. /** Given a DH key exchange object, and our peer's value of g^y (as a
  1376. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  1377. * <b>secret_bytes_out</b> bytes of shared key material and write them
  1378. * to <b>secret_out</b>. Return the number of bytes generated on success,
  1379. * or -1 on failure.
  1380. *
  1381. * (We generate key material by computing
  1382. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  1383. * where || is concatenation.)
  1384. */
  1385. ssize_t
  1386. crypto_dh_compute_secret(crypto_dh_env_t *dh,
  1387. const char *pubkey, size_t pubkey_len,
  1388. char *secret_out, size_t secret_bytes_out)
  1389. {
  1390. char *secret_tmp = NULL;
  1391. BIGNUM *pubkey_bn = NULL;
  1392. size_t secret_len=0;
  1393. int result=0;
  1394. tor_assert(dh);
  1395. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  1396. tor_assert(pubkey_len < INT_MAX);
  1397. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey,
  1398. (int)pubkey_len, NULL)))
  1399. goto error;
  1400. if (tor_check_dh_key(pubkey_bn)<0) {
  1401. /* Check for invalid public keys. */
  1402. log_warn(LD_CRYPTO,"Rejected invalid g^x");
  1403. goto error;
  1404. }
  1405. secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
  1406. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  1407. if (result < 0) {
  1408. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  1409. goto error;
  1410. }
  1411. secret_len = result;
  1412. /* sometimes secret_len might be less than 128, e.g., 127. that's ok. -RD */
  1413. /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
  1414. * Leading zeros MUST be preserved, so that ZZ occupies as many
  1415. * octets as p. For instance, if p is 1024 bits, ZZ should be 128
  1416. * bytes long.
  1417. * XXX021 What are the security implications here? -NM
  1418. */
  1419. if (crypto_expand_key_material(secret_tmp, secret_len,
  1420. secret_out, secret_bytes_out)<0)
  1421. goto error;
  1422. secret_len = secret_bytes_out;
  1423. goto done;
  1424. error:
  1425. result = -1;
  1426. done:
  1427. crypto_log_errors(LOG_WARN, "completing DH handshake");
  1428. if (pubkey_bn)
  1429. BN_free(pubkey_bn);
  1430. tor_free(secret_tmp);
  1431. if (result < 0)
  1432. return result;
  1433. else
  1434. return secret_len;
  1435. }
  1436. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  1437. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  1438. * <b>key_out</b> by taking the first <b>key_out_len</b> bytes of
  1439. * H(K | [00]) | H(K | [01]) | ....
  1440. *
  1441. * Return 0 on success, -1 on failure.
  1442. */
  1443. int
  1444. crypto_expand_key_material(const char *key_in, size_t key_in_len,
  1445. char *key_out, size_t key_out_len)
  1446. {
  1447. int i;
  1448. char *cp, *tmp = tor_malloc(key_in_len+1);
  1449. char digest[DIGEST_LEN];
  1450. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1451. tor_assert(key_out_len <= DIGEST_LEN*256);
  1452. memcpy(tmp, key_in, key_in_len);
  1453. for (cp = key_out, i=0; cp < key_out+key_out_len;
  1454. ++i, cp += DIGEST_LEN) {
  1455. tmp[key_in_len] = i;
  1456. if (crypto_digest(digest, tmp, key_in_len+1))
  1457. goto err;
  1458. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  1459. }
  1460. memset(tmp, 0, key_in_len+1);
  1461. tor_free(tmp);
  1462. memset(digest, 0, sizeof(digest));
  1463. return 0;
  1464. err:
  1465. memset(tmp, 0, key_in_len+1);
  1466. tor_free(tmp);
  1467. memset(digest, 0, sizeof(digest));
  1468. return -1;
  1469. }
  1470. /** Free a DH key exchange object.
  1471. */
  1472. void
  1473. crypto_dh_free(crypto_dh_env_t *dh)
  1474. {
  1475. tor_assert(dh);
  1476. tor_assert(dh->dh);
  1477. DH_free(dh->dh);
  1478. tor_free(dh);
  1479. }
  1480. /* random numbers */
  1481. /* This is how much entropy OpenSSL likes to add right now, so maybe it will
  1482. * work for us too. */
  1483. #define ADD_ENTROPY 32
  1484. /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
  1485. "release".) */
  1486. #define HAVE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
  1487. /* Versions of openssl prior to 0.9.7k and 0.9.8c had a bug where RAND_poll
  1488. * would allocate an fd_set on the stack, open a new file, and try to FD_SET
  1489. * that fd without checking whether it fit in the fd_set. Thus, if the
  1490. * system has not just been started up, it is unsafe to call */
  1491. #define RAND_POLL_IS_SAFE \
  1492. ((OPENSSL_VERSION_NUMBER >= 0x009070afl && \
  1493. OPENSSL_VERSION_NUMBER <= 0x00907fffl) || \
  1494. (OPENSSL_VERSION_NUMBER >= 0x0090803fl))
  1495. /* We could actually get away with calling RAND_poll */
  1496. #define USE_RAND_POLL (HAVE_RAND_POLL && RAND_POLL_IS_SAFE)
  1497. /** Seed OpenSSL's random number generator with bytes from the operating
  1498. * system. <b>startup</b> should be true iff we have just started Tor and
  1499. * have not yet allocated a bunch of fds. Return 0 on success, -1 on failure.
  1500. */
  1501. int
  1502. crypto_seed_rng(int startup)
  1503. {
  1504. char buf[ADD_ENTROPY];
  1505. int rand_poll_status = 0;
  1506. /* local variables */
  1507. #ifdef MS_WINDOWS
  1508. static int provider_set = 0;
  1509. static HCRYPTPROV provider;
  1510. #else
  1511. static const char *filenames[] = {
  1512. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1513. };
  1514. int fd, i;
  1515. size_t n;
  1516. #endif
  1517. #if HAVE_RAND_POLL
  1518. /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
  1519. * entropy than we do. We'll try calling that, *and* calling our own entropy
  1520. * functions. If one succeeds, we'll accept the RNG as seeded. */
  1521. if (startup || RAND_POLL_IS_SAFE) {
  1522. rand_poll_status = RAND_poll();
  1523. if (rand_poll_status == 0)
  1524. log_warn(LD_CRYPTO, "RAND_poll() failed.");
  1525. }
  1526. #endif
  1527. #ifdef MS_WINDOWS
  1528. if (!provider_set) {
  1529. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  1530. CRYPT_VERIFYCONTEXT)) {
  1531. if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
  1532. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  1533. return rand_poll_status ? 0 : -1;
  1534. }
  1535. }
  1536. provider_set = 1;
  1537. }
  1538. if (!CryptGenRandom(provider, sizeof(buf), buf)) {
  1539. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  1540. return rand_poll_status ? 0 : -1;
  1541. }
  1542. RAND_seed(buf, sizeof(buf));
  1543. memset(buf, 0, sizeof(buf));
  1544. return 0;
  1545. #else
  1546. for (i = 0; filenames[i]; ++i) {
  1547. fd = open(filenames[i], O_RDONLY, 0);
  1548. if (fd<0) continue;
  1549. log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
  1550. n = read_all(fd, buf, sizeof(buf), 0);
  1551. close(fd);
  1552. if (n != sizeof(buf)) {
  1553. log_warn(LD_CRYPTO,
  1554. "Error reading from entropy source (read only %lu bytes).",
  1555. (unsigned long)n);
  1556. return -1;
  1557. }
  1558. RAND_seed(buf, (int)sizeof(buf));
  1559. memset(buf, 0, sizeof(buf));
  1560. return 0;
  1561. }
  1562. log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
  1563. return rand_poll_status ? 0 : -1;
  1564. #endif
  1565. }
  1566. /** Write <b>n</b> bytes of strong random data to <b>to</b>. Return 0 on
  1567. * success, -1 on failure.
  1568. */
  1569. int
  1570. crypto_rand(char *to, size_t n)
  1571. {
  1572. int r;
  1573. tor_assert(n < INT_MAX);
  1574. tor_assert(to);
  1575. r = RAND_bytes((unsigned char*)to, (int)n);
  1576. if (r == 0)
  1577. crypto_log_errors(LOG_WARN, "generating random data");
  1578. return (r == 1) ? 0 : -1;
  1579. }
  1580. /** Return a pseudorandom integer, chosen uniformly from the values
  1581. * between 0 and <b>max</b>-1. */
  1582. int
  1583. crypto_rand_int(unsigned int max)
  1584. {
  1585. unsigned int val;
  1586. unsigned int cutoff;
  1587. tor_assert(max < UINT_MAX);
  1588. tor_assert(max > 0); /* don't div by 0 */
  1589. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1590. * distribution with clipping at the upper end of unsigned int's
  1591. * range.
  1592. */
  1593. cutoff = UINT_MAX - (UINT_MAX%max);
  1594. while (1) {
  1595. crypto_rand((char*)&val, sizeof(val));
  1596. if (val < cutoff)
  1597. return val % max;
  1598. }
  1599. }
  1600. /** Return a pseudorandom 64-bit integer, chosen uniformly from the values
  1601. * between 0 and <b>max</b>-1. */
  1602. uint64_t
  1603. crypto_rand_uint64(uint64_t max)
  1604. {
  1605. uint64_t val;
  1606. uint64_t cutoff;
  1607. tor_assert(max < UINT64_MAX);
  1608. tor_assert(max > 0); /* don't div by 0 */
  1609. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1610. * distribution with clipping at the upper end of unsigned int's
  1611. * range.
  1612. */
  1613. cutoff = UINT64_MAX - (UINT64_MAX%max);
  1614. while (1) {
  1615. crypto_rand((char*)&val, sizeof(val));
  1616. if (val < cutoff)
  1617. return val % max;
  1618. }
  1619. }
  1620. /** Generate and return a new random hostname starting with <b>prefix</b>,
  1621. * ending with <b>suffix</b>, and containing no less than
  1622. * <b>min_rand_len</b> and no more than <b>max_rand_len</b> random base32
  1623. * characters between. */
  1624. char *
  1625. crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix,
  1626. const char *suffix)
  1627. {
  1628. char *result, *rand_bytes;
  1629. int randlen, rand_bytes_len;
  1630. size_t resultlen, prefixlen;
  1631. tor_assert(max_rand_len >= min_rand_len);
  1632. randlen = min_rand_len + crypto_rand_int(max_rand_len - min_rand_len + 1);
  1633. prefixlen = strlen(prefix);
  1634. resultlen = prefixlen + strlen(suffix) + randlen + 16;
  1635. rand_bytes_len = ((randlen*5)+7)/8;
  1636. if (rand_bytes_len % 5)
  1637. rand_bytes_len += 5 - (rand_bytes_len%5);
  1638. rand_bytes = tor_malloc(rand_bytes_len);
  1639. crypto_rand(rand_bytes, rand_bytes_len);
  1640. result = tor_malloc(resultlen);
  1641. memcpy(result, prefix, prefixlen);
  1642. base32_encode(result+prefixlen, resultlen-prefixlen,
  1643. rand_bytes, rand_bytes_len);
  1644. tor_free(rand_bytes);
  1645. strlcpy(result+prefixlen+randlen, suffix, resultlen-(prefixlen+randlen));
  1646. return result;
  1647. }
  1648. /** Return a randomly chosen element of <b>sl</b>; or NULL if <b>sl</b>
  1649. * is empty. */
  1650. void *
  1651. smartlist_choose(const smartlist_t *sl)
  1652. {
  1653. int len = smartlist_len(sl);
  1654. if (len)
  1655. return smartlist_get(sl,crypto_rand_int(len));
  1656. return NULL; /* no elements to choose from */
  1657. }
  1658. /** Scramble the elements of <b>sl</b> into a random order. */
  1659. void
  1660. smartlist_shuffle(smartlist_t *sl)
  1661. {
  1662. int i;
  1663. /* From the end of the list to the front, choose at random from the
  1664. positions we haven't looked at yet, and swap that position into the
  1665. current position. Remember to give "no swap" the same probability as
  1666. any other swap. */
  1667. for (i = smartlist_len(sl)-1; i > 0; --i) {
  1668. int j = crypto_rand_int(i+1);
  1669. smartlist_swap(sl, i, j);
  1670. }
  1671. }
  1672. /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
  1673. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1674. * bytes. Return the number of bytes written on success; -1 if
  1675. * destlen is too short, or other failure.
  1676. */
  1677. int
  1678. base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1679. {
  1680. /* FFFF we might want to rewrite this along the lines of base64_decode, if
  1681. * it ever shows up in the profile. */
  1682. EVP_ENCODE_CTX ctx;
  1683. int len, ret;
  1684. tor_assert(srclen < INT_MAX);
  1685. /* 48 bytes of input -> 64 bytes of output plus newline.
  1686. Plus one more byte, in case I'm wrong.
  1687. */
  1688. if (destlen < ((srclen/48)+1)*66)
  1689. return -1;
  1690. if (destlen > SIZE_T_CEILING)
  1691. return -1;
  1692. EVP_EncodeInit(&ctx);
  1693. EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
  1694. (unsigned char*)src, (int)srclen);
  1695. EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
  1696. ret += len;
  1697. return ret;
  1698. }
  1699. #define X 255
  1700. #define SP 64
  1701. #define PAD 65
  1702. /** Internal table mapping byte values to what they represent in base64.
  1703. * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
  1704. * skipped. Xs are invalid and must not appear in base64. PAD indicates
  1705. * end-of-string. */
  1706. static const uint8_t base64_decode_table[256] = {
  1707. X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
  1708. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1709. SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
  1710. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
  1711. X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  1712. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
  1713. X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  1714. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
  1715. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1716. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1717. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1718. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1719. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1720. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1721. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1722. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1723. };
  1724. /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
  1725. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1726. * bytes. Return the number of bytes written on success; -1 if
  1727. * destlen is too short, or other failure.
  1728. *
  1729. * NOTE 1: destlen is checked conservatively, as though srclen contained no
  1730. * spaces or padding.
  1731. *
  1732. * NOTE 2: This implementation does not check for the correct number of
  1733. * padding "=" characters at the end of the string, and does not check
  1734. * for internal padding characters.
  1735. */
  1736. int
  1737. base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  1738. {
  1739. #ifdef USE_OPENSSL_BASE64
  1740. EVP_ENCODE_CTX ctx;
  1741. int len, ret;
  1742. /* 64 bytes of input -> *up to* 48 bytes of output.
  1743. Plus one more byte, in case I'm wrong.
  1744. */
  1745. if (destlen < ((srclen/64)+1)*49)
  1746. return -1;
  1747. if (destlen > SIZE_T_CEILING)
  1748. return -1;
  1749. EVP_DecodeInit(&ctx);
  1750. EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
  1751. (unsigned char*)src, srclen);
  1752. EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
  1753. ret += len;
  1754. return ret;
  1755. #else
  1756. const char *eos = src+srclen;
  1757. uint32_t n=0;
  1758. int n_idx=0;
  1759. char *dest_orig = dest;
  1760. /* Max number of bits == srclen*6.
  1761. * Number of bytes required to hold all bits == (srclen*6)/8.
  1762. * Yes, we want to round down: anything that hangs over the end of a
  1763. * byte is padding. */
  1764. if (destlen < (srclen*3)/4)
  1765. return -1;
  1766. if (destlen > SIZE_T_CEILING)
  1767. return -1;
  1768. /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
  1769. * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
  1770. * 24 bits, batch them into 3 bytes and flush those bytes to dest.
  1771. */
  1772. for ( ; src < eos; ++src) {
  1773. unsigned char c = (unsigned char) *src;
  1774. uint8_t v = base64_decode_table[c];
  1775. switch (v) {
  1776. case X:
  1777. /* This character isn't allowed in base64. */
  1778. return -1;
  1779. case SP:
  1780. /* This character is whitespace, and has no effect. */
  1781. continue;
  1782. case PAD:
  1783. /* We've hit an = character: the data is over. */
  1784. goto end_of_loop;
  1785. default:
  1786. /* We have an actual 6-bit value. Append it to the bits in n. */
  1787. n = (n<<6) | v;
  1788. if ((++n_idx) == 4) {
  1789. /* We've accumulated 24 bits in n. Flush them. */
  1790. *dest++ = (n>>16);
  1791. *dest++ = (n>>8) & 0xff;
  1792. *dest++ = (n) & 0xff;
  1793. n_idx = 0;
  1794. n = 0;
  1795. }
  1796. }
  1797. }
  1798. end_of_loop:
  1799. /* If we have leftover bits, we need to cope. */
  1800. switch (n_idx) {
  1801. case 0:
  1802. default:
  1803. /* No leftover bits. We win. */
  1804. break;
  1805. case 1:
  1806. /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
  1807. return -1;
  1808. case 2:
  1809. /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
  1810. *dest++ = n >> 4;
  1811. break;
  1812. case 3:
  1813. /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
  1814. *dest++ = n >> 10;
  1815. *dest++ = n >> 2;
  1816. }
  1817. tor_assert((dest-dest_orig) <= (ssize_t)destlen);
  1818. tor_assert((dest-dest_orig) <= INT_MAX);
  1819. return (int)(dest-dest_orig);
  1820. #endif
  1821. }
  1822. #undef X
  1823. #undef SP
  1824. #undef NIL
  1825. /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
  1826. * and newline characters, and store the nul-terminated result in the first
  1827. * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
  1828. int
  1829. digest_to_base64(char *d64, const char *digest)
  1830. {
  1831. char buf[256];
  1832. base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
  1833. buf[BASE64_DIGEST_LEN] = '\0';
  1834. memcpy(d64, buf, BASE64_DIGEST_LEN+1);
  1835. return 0;
  1836. }
  1837. /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
  1838. * trailing newline or = characters), decode it and store the result in the
  1839. * first DIGEST_LEN bytes at <b>digest</b>. */
  1840. int
  1841. digest_from_base64(char *digest, const char *d64)
  1842. {
  1843. #ifdef USE_OPENSSL_BASE64
  1844. char buf_in[BASE64_DIGEST_LEN+3];
  1845. char buf[256];
  1846. if (strlen(d64) != BASE64_DIGEST_LEN)
  1847. return -1;
  1848. memcpy(buf_in, d64, BASE64_DIGEST_LEN);
  1849. memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
  1850. if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
  1851. return -1;
  1852. memcpy(digest, buf, DIGEST_LEN);
  1853. return 0;
  1854. #else
  1855. if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
  1856. return 0;
  1857. else
  1858. return -1;
  1859. #endif
  1860. }
  1861. /** Implements base32 encoding as in rfc3548. Limitation: Requires
  1862. * that srclen*8 is a multiple of 5.
  1863. */
  1864. void
  1865. base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1866. {
  1867. unsigned int i, bit, v, u;
  1868. size_t nbits = srclen * 8;
  1869. tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
  1870. tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
  1871. tor_assert(destlen < SIZE_T_CEILING);
  1872. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  1873. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  1874. v = ((uint8_t)src[bit/8]) << 8;
  1875. if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
  1876. /* set u to the 5-bit value at the bit'th bit of src. */
  1877. u = (v >> (11-(bit%8))) & 0x1F;
  1878. dest[i] = BASE32_CHARS[u];
  1879. }
  1880. dest[i] = '\0';
  1881. }
  1882. /** Implements base32 decoding as in rfc3548. Limitation: Requires
  1883. * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
  1884. */
  1885. int
  1886. base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  1887. {
  1888. /* XXXX we might want to rewrite this along the lines of base64_decode, if
  1889. * it ever shows up in the profile. */
  1890. unsigned int i, j, bit;
  1891. size_t nbits;
  1892. char *tmp;
  1893. nbits = srclen * 5;
  1894. tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
  1895. tor_assert((nbits/8) <= destlen); /* We need enough space. */
  1896. tor_assert(destlen < SIZE_T_CEILING);
  1897. /* Convert base32 encoded chars to the 5-bit values that they represent. */
  1898. tmp = tor_malloc_zero(srclen);
  1899. for (j = 0; j < srclen; ++j) {
  1900. if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
  1901. else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
  1902. else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
  1903. else {
  1904. log_warn(LD_BUG, "illegal character in base32 encoded string");
  1905. tor_free(tmp);
  1906. return -1;
  1907. }
  1908. }
  1909. /* Assemble result byte-wise by applying five possible cases. */
  1910. for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
  1911. switch (bit % 40) {
  1912. case 0:
  1913. dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
  1914. (((uint8_t)tmp[(bit/5)+1]) >> 2);
  1915. break;
  1916. case 8:
  1917. dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
  1918. (((uint8_t)tmp[(bit/5)+1]) << 1) +
  1919. (((uint8_t)tmp[(bit/5)+2]) >> 4);
  1920. break;
  1921. case 16:
  1922. dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
  1923. (((uint8_t)tmp[(bit/5)+1]) >> 1);
  1924. break;
  1925. case 24:
  1926. dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
  1927. (((uint8_t)tmp[(bit/5)+1]) << 2) +
  1928. (((uint8_t)tmp[(bit/5)+2]) >> 3);
  1929. break;
  1930. case 32:
  1931. dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
  1932. ((uint8_t)tmp[(bit/5)+1]);
  1933. break;
  1934. }
  1935. }
  1936. memset(tmp, 0, srclen);
  1937. tor_free(tmp);
  1938. tmp = NULL;
  1939. return 0;
  1940. }
  1941. /** Implement RFC2440-style iterated-salted S2K conversion: convert the
  1942. * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
  1943. * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
  1944. * are a salt; the 9th byte describes how much iteration to do.
  1945. * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
  1946. */
  1947. void
  1948. secret_to_key(char *key_out, size_t key_out_len, const char *secret,
  1949. size_t secret_len, const char *s2k_specifier)
  1950. {
  1951. crypto_digest_env_t *d;
  1952. uint8_t c;
  1953. size_t count, tmplen;
  1954. char *tmp;
  1955. tor_assert(key_out_len < SIZE_T_CEILING);
  1956. #define EXPBIAS 6
  1957. c = s2k_specifier[8];
  1958. count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
  1959. #undef EXPBIAS
  1960. tor_assert(key_out_len <= DIGEST_LEN);
  1961. d = crypto_new_digest_env();
  1962. tmplen = 8+secret_len;
  1963. tmp = tor_malloc(tmplen);
  1964. memcpy(tmp,s2k_specifier,8);
  1965. memcpy(tmp+8,secret,secret_len);
  1966. secret_len += 8;
  1967. while (count) {
  1968. if (count >= secret_len) {
  1969. crypto_digest_add_bytes(d, tmp, secret_len);
  1970. count -= secret_len;
  1971. } else {
  1972. crypto_digest_add_bytes(d, tmp, count);
  1973. count = 0;
  1974. }
  1975. }
  1976. crypto_digest_get_digest(d, key_out, key_out_len);
  1977. memset(tmp, 0, tmplen);
  1978. tor_free(tmp);
  1979. crypto_free_digest_env(d);
  1980. }
  1981. #ifdef TOR_IS_MULTITHREADED
  1982. /** Helper: openssl uses this callback to manipulate mutexes. */
  1983. static void
  1984. _openssl_locking_cb(int mode, int n, const char *file, int line)
  1985. {
  1986. (void)file;
  1987. (void)line;
  1988. if (!_openssl_mutexes)
  1989. /* This is not a really good fix for the
  1990. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  1991. * it can't hurt. */
  1992. return;
  1993. if (mode & CRYPTO_LOCK)
  1994. tor_mutex_acquire(_openssl_mutexes[n]);
  1995. else
  1996. tor_mutex_release(_openssl_mutexes[n]);
  1997. }
  1998. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  1999. * multithreaded. */
  2000. static int
  2001. setup_openssl_threading(void)
  2002. {
  2003. int i;
  2004. int n = CRYPTO_num_locks();
  2005. _n_openssl_mutexes = n;
  2006. _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
  2007. for (i=0; i < n; ++i)
  2008. _openssl_mutexes[i] = tor_mutex_new();
  2009. CRYPTO_set_locking_callback(_openssl_locking_cb);
  2010. CRYPTO_set_id_callback(tor_get_thread_id);
  2011. return 0;
  2012. }
  2013. #else
  2014. static int
  2015. setup_openssl_threading(void)
  2016. {
  2017. return 0;
  2018. }
  2019. #endif