crypto.c 57 KB

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