crypto.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194
  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, 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. /* XXX020 leaks b? maybe "BIO_free(b);" would be smart here. -RD */
  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. memset(buf, 0, pkeylen);
  755. tor_free(buf);
  756. if (cipher) crypto_free_cipher_env(cipher);
  757. return -1;
  758. }
  759. /** Invert crypto_pk_public_hybrid_encrypt. */
  760. int
  761. crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env,
  762. char *to,
  763. const char *from,
  764. size_t fromlen,
  765. int padding, int warnOnFailure)
  766. {
  767. int outlen, r;
  768. size_t pkeylen;
  769. crypto_cipher_env_t *cipher = NULL;
  770. char *buf = NULL;
  771. pkeylen = crypto_pk_keysize(env);
  772. if (fromlen <= pkeylen) {
  773. return crypto_pk_private_decrypt(env,to,from,fromlen,padding,
  774. warnOnFailure);
  775. }
  776. buf = tor_malloc(pkeylen+1);
  777. outlen = crypto_pk_private_decrypt(env,buf,from,pkeylen,padding,
  778. warnOnFailure);
  779. if (outlen<0) {
  780. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  781. "Error decrypting public-key data");
  782. goto err;
  783. }
  784. if (outlen < CIPHER_KEY_LEN) {
  785. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  786. "No room for a symmetric key");
  787. goto err;
  788. }
  789. cipher = crypto_create_init_cipher(buf, 0);
  790. if (!cipher) {
  791. goto err;
  792. }
  793. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  794. outlen -= CIPHER_KEY_LEN;
  795. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  796. if (r<0)
  797. goto err;
  798. memset(buf,0,pkeylen);
  799. tor_free(buf);
  800. crypto_free_cipher_env(cipher);
  801. return outlen + (fromlen-pkeylen);
  802. err:
  803. memset(buf,0,pkeylen);
  804. tor_free(buf);
  805. if (cipher) crypto_free_cipher_env(cipher);
  806. return -1;
  807. }
  808. /** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
  809. * Return -1 on error, or the number of characters used on success.
  810. */
  811. int
  812. crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
  813. {
  814. int len;
  815. unsigned char *buf, *cp;
  816. len = i2d_RSAPublicKey(pk->key, NULL);
  817. if (len < 0 || len > dest_len)
  818. return -1;
  819. cp = buf = tor_malloc(len+1);
  820. len = i2d_RSAPublicKey(pk->key, &cp);
  821. if (len < 0) {
  822. crypto_log_errors(LOG_WARN,"encoding public key");
  823. tor_free(buf);
  824. return -1;
  825. }
  826. /* We don't encode directly into 'dest', because that would be illegal
  827. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  828. */
  829. memcpy(dest,buf,len);
  830. tor_free(buf);
  831. return len;
  832. }
  833. /** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
  834. * success and NULL on failure.
  835. */
  836. crypto_pk_env_t *
  837. crypto_pk_asn1_decode(const char *str, size_t len)
  838. {
  839. RSA *rsa;
  840. unsigned char *buf;
  841. /* This ifdef suppresses a type warning. Take out the first case once
  842. * everybody is using openssl 0.9.7 or later.
  843. */
  844. const unsigned char *cp;
  845. cp = buf = tor_malloc(len);
  846. memcpy(buf,str,len);
  847. rsa = d2i_RSAPublicKey(NULL, &cp, len);
  848. tor_free(buf);
  849. if (!rsa) {
  850. crypto_log_errors(LOG_WARN,"decoding public key");
  851. return NULL;
  852. }
  853. return _crypto_new_pk_env_rsa(rsa);
  854. }
  855. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  856. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  857. * Return 0 on success, -1 on failure.
  858. */
  859. int
  860. crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
  861. {
  862. unsigned char *buf, *bufp;
  863. int len;
  864. len = i2d_RSAPublicKey(pk->key, NULL);
  865. if (len < 0)
  866. return -1;
  867. buf = bufp = tor_malloc(len+1);
  868. len = i2d_RSAPublicKey(pk->key, &bufp);
  869. if (len < 0) {
  870. crypto_log_errors(LOG_WARN,"encoding public key");
  871. tor_free(buf);
  872. return -1;
  873. }
  874. if (crypto_digest(digest_out, (char*)buf, len) < 0) {
  875. tor_free(buf);
  876. return -1;
  877. }
  878. tor_free(buf);
  879. return 0;
  880. }
  881. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  882. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  883. * space). Return 0 on success, -1 on failure.
  884. *
  885. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  886. * of the public key, converted to hexadecimal, in upper case, with a
  887. * space after every four digits.
  888. *
  889. * If <b>add_space</b> is false, omit the spaces.
  890. */
  891. int
  892. crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out, int add_space)
  893. {
  894. char digest[DIGEST_LEN];
  895. char hexdigest[HEX_DIGEST_LEN+1];
  896. if (crypto_pk_get_digest(pk, digest)) {
  897. return -1;
  898. }
  899. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  900. if (add_space) {
  901. if (tor_strpartition(fp_out, FINGERPRINT_LEN+1, hexdigest, " ", 4)<0)
  902. return -1;
  903. } else {
  904. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  905. }
  906. return 0;
  907. }
  908. /** Return true iff <b>s</b> is in the correct format for a fingerprint.
  909. */
  910. int
  911. crypto_pk_check_fingerprint_syntax(const char *s)
  912. {
  913. int i;
  914. for (i = 0; i < FINGERPRINT_LEN; ++i) {
  915. if ((i%5) == 4) {
  916. if (!TOR_ISSPACE(s[i])) return 0;
  917. } else {
  918. if (!TOR_ISXDIGIT(s[i])) return 0;
  919. }
  920. }
  921. if (s[FINGERPRINT_LEN]) return 0;
  922. return 1;
  923. }
  924. /* symmetric crypto */
  925. /** Generate a new random key for the symmetric cipher in <b>env</b>.
  926. * Return 0 on success, -1 on failure. Does not initialize the cipher.
  927. */
  928. int
  929. crypto_cipher_generate_key(crypto_cipher_env_t *env)
  930. {
  931. tor_assert(env);
  932. return crypto_rand(env->key, CIPHER_KEY_LEN);
  933. }
  934. /** Set the symmetric key for the cipher in <b>env</b> to the first
  935. * CIPHER_KEY_LEN bytes of <b>key</b>. Does not initialize the cipher.
  936. * Return 0 on success, -1 on failure.
  937. */
  938. int
  939. crypto_cipher_set_key(crypto_cipher_env_t *env, const char *key)
  940. {
  941. tor_assert(env);
  942. tor_assert(key);
  943. if (!env->key)
  944. return -1;
  945. memcpy(env->key, key, CIPHER_KEY_LEN);
  946. return 0;
  947. }
  948. /** Generate an initialization vector for our AES-CTR cipher; store it
  949. * in the first CIPHER_IV_LEN bytes of <b>iv_out</b>. */
  950. void
  951. crypto_cipher_generate_iv(char *iv_out)
  952. {
  953. crypto_rand(iv_out, CIPHER_IV_LEN);
  954. }
  955. /** Adjust the counter of <b>env</b> to point to the first byte of the block
  956. * corresponding to the encryption of the CIPHER_IV_LEN bytes at
  957. * <b>iv</b>. */
  958. int
  959. crypto_cipher_set_iv(crypto_cipher_env_t *env, const char *iv)
  960. {
  961. tor_assert(env);
  962. tor_assert(iv);
  963. aes_set_iv(env->cipher, iv);
  964. return 0;
  965. }
  966. /** Return a pointer to the key set for the cipher in <b>env</b>.
  967. */
  968. const char *
  969. crypto_cipher_get_key(crypto_cipher_env_t *env)
  970. {
  971. return env->key;
  972. }
  973. /** Initialize the cipher in <b>env</b> for encryption. Return 0 on
  974. * success, -1 on failure.
  975. */
  976. int
  977. crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
  978. {
  979. tor_assert(env);
  980. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  981. return 0;
  982. }
  983. /** Initialize the cipher in <b>env</b> for decryption. Return 0 on
  984. * success, -1 on failure.
  985. */
  986. int
  987. crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
  988. {
  989. tor_assert(env);
  990. aes_set_key(env->cipher, env->key, CIPHER_KEY_LEN*8);
  991. return 0;
  992. }
  993. /** Encrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  994. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  995. * On failure, return -1.
  996. */
  997. int
  998. crypto_cipher_encrypt(crypto_cipher_env_t *env, char *to,
  999. const char *from, size_t fromlen)
  1000. {
  1001. tor_assert(env);
  1002. tor_assert(env->cipher);
  1003. tor_assert(from);
  1004. tor_assert(fromlen);
  1005. tor_assert(to);
  1006. aes_crypt(env->cipher, from, fromlen, to);
  1007. return 0;
  1008. }
  1009. /** Decrypt <b>fromlen</b> bytes from <b>from</b> using the cipher
  1010. * <b>env</b>; on success, store the result to <b>to</b> and return 0.
  1011. * On failure, return -1.
  1012. */
  1013. int
  1014. crypto_cipher_decrypt(crypto_cipher_env_t *env, char *to,
  1015. const char *from, size_t fromlen)
  1016. {
  1017. tor_assert(env);
  1018. tor_assert(from);
  1019. tor_assert(to);
  1020. aes_crypt(env->cipher, from, fromlen, to);
  1021. return 0;
  1022. }
  1023. /** Encrypt <b>fromlen</b> bytes (at least 1) from <b>from</b> with the key in
  1024. * <b>cipher</b> to the buffer in <b>to</b> of length
  1025. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> plus
  1026. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1027. * number of bytes written, on failure, return -1.
  1028. *
  1029. * This function adjusts the current position of the counter in <b>cipher</b>
  1030. * to immediately after the encrypted data.
  1031. */
  1032. int
  1033. crypto_cipher_encrypt_with_iv(crypto_cipher_env_t *cipher,
  1034. char *to, size_t tolen,
  1035. const char *from, size_t fromlen)
  1036. {
  1037. tor_assert(cipher);
  1038. tor_assert(from);
  1039. tor_assert(to);
  1040. if (fromlen < 1)
  1041. return -1;
  1042. if (tolen < fromlen + CIPHER_IV_LEN)
  1043. return -1;
  1044. crypto_cipher_generate_iv(to);
  1045. if (crypto_cipher_set_iv(cipher, to)<0)
  1046. return -1;
  1047. crypto_cipher_encrypt(cipher, to+CIPHER_IV_LEN, from, fromlen);
  1048. return fromlen + CIPHER_IV_LEN;
  1049. }
  1050. /** Decrypt <b>fromlen</b> bytes (at least 1+CIPHER_IV_LEN) from <b>from</b>
  1051. * with the key in <b>cipher</b> to the buffer in <b>to</b> of length
  1052. * <b>tolen</b>. <b>tolen</b> must be at least <b>fromlen</b> minus
  1053. * CIPHER_IV_LEN bytes for the initialization vector. On success, return the
  1054. * number of bytes written, on failure, return -1.
  1055. *
  1056. * This function adjusts the current position of the counter in <b>cipher</b>
  1057. * to immediately after the decrypted data.
  1058. */
  1059. int
  1060. crypto_cipher_decrypt_with_iv(crypto_cipher_env_t *cipher,
  1061. char *to, size_t tolen,
  1062. const char *from, size_t fromlen)
  1063. {
  1064. tor_assert(cipher);
  1065. tor_assert(from);
  1066. tor_assert(to);
  1067. if (fromlen <= CIPHER_IV_LEN)
  1068. return -1;
  1069. if (tolen < fromlen - CIPHER_IV_LEN)
  1070. return -1;
  1071. if (crypto_cipher_set_iv(cipher, from)<0)
  1072. return -1;
  1073. crypto_cipher_encrypt(cipher, to, from+CIPHER_IV_LEN, fromlen-CIPHER_IV_LEN);
  1074. return fromlen - CIPHER_IV_LEN;
  1075. }
  1076. /* SHA-1 */
  1077. /** Compute the SHA1 digest of <b>len</b> bytes in data stored in
  1078. * <b>m</b>. Write the DIGEST_LEN byte result into <b>digest</b>.
  1079. * Return 0 on success, -1 on failure.
  1080. */
  1081. int
  1082. crypto_digest(char *digest, const char *m, size_t len)
  1083. {
  1084. tor_assert(m);
  1085. tor_assert(digest);
  1086. return (SHA1((const unsigned char*)m,len,(unsigned char*)digest) == NULL);
  1087. }
  1088. /** Intermediate information about the digest of a stream of data. */
  1089. struct crypto_digest_env_t {
  1090. SHA_CTX d;
  1091. };
  1092. /** Allocate and return a new digest object.
  1093. */
  1094. crypto_digest_env_t *
  1095. crypto_new_digest_env(void)
  1096. {
  1097. crypto_digest_env_t *r;
  1098. r = tor_malloc(sizeof(crypto_digest_env_t));
  1099. SHA1_Init(&r->d);
  1100. return r;
  1101. }
  1102. /** Deallocate a digest object.
  1103. */
  1104. void
  1105. crypto_free_digest_env(crypto_digest_env_t *digest)
  1106. {
  1107. tor_free(digest);
  1108. }
  1109. /** Add <b>len</b> bytes from <b>data</b> to the digest object.
  1110. */
  1111. void
  1112. crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
  1113. size_t len)
  1114. {
  1115. tor_assert(digest);
  1116. tor_assert(data);
  1117. /* Using the SHA1_*() calls directly means we don't support doing
  1118. * sha1 in hardware. But so far the delay of getting the question
  1119. * to the hardware, and hearing the answer, is likely higher than
  1120. * just doing it ourselves. Hashes are fast.
  1121. */
  1122. SHA1_Update(&digest->d, (void*)data, len);
  1123. }
  1124. /** Compute the hash of the data that has been passed to the digest
  1125. * object; write the first out_len bytes of the result to <b>out</b>.
  1126. * <b>out_len</b> must be \<= DIGEST_LEN.
  1127. */
  1128. void
  1129. crypto_digest_get_digest(crypto_digest_env_t *digest,
  1130. char *out, size_t out_len)
  1131. {
  1132. static unsigned char r[DIGEST_LEN]; /*XXXXX020 why static? */
  1133. SHA_CTX tmpctx;
  1134. tor_assert(digest);
  1135. tor_assert(out);
  1136. tor_assert(out_len <= DIGEST_LEN);
  1137. /* memcpy into a temporary ctx, since SHA1_Final clears the context */
  1138. memcpy(&tmpctx, &digest->d, sizeof(SHA_CTX));
  1139. SHA1_Final(r, &tmpctx);
  1140. memcpy(out, r, out_len);
  1141. }
  1142. /** Allocate and return a new digest object with the same state as
  1143. * <b>digest</b>
  1144. */
  1145. crypto_digest_env_t *
  1146. crypto_digest_dup(const crypto_digest_env_t *digest)
  1147. {
  1148. crypto_digest_env_t *r;
  1149. tor_assert(digest);
  1150. r = tor_malloc(sizeof(crypto_digest_env_t));
  1151. memcpy(r,digest,sizeof(crypto_digest_env_t));
  1152. return r;
  1153. }
  1154. /** Replace the state of the digest object <b>into</b> with the state
  1155. * of the digest object <b>from</b>.
  1156. */
  1157. void
  1158. crypto_digest_assign(crypto_digest_env_t *into,
  1159. const crypto_digest_env_t *from)
  1160. {
  1161. tor_assert(into);
  1162. tor_assert(from);
  1163. memcpy(into,from,sizeof(crypto_digest_env_t));
  1164. }
  1165. #if 0
  1166. /**DOCDOC */
  1167. #define DIGEST_BLOCKSIZE 64
  1168. /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1169. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
  1170. * in <b>hmac_out</b>.
  1171. */
  1172. void
  1173. crypto_hmac_sha1(char *hmac_out,
  1174. const char *key, size_t key_len,
  1175. const char *msg, size_t msg_len)
  1176. {
  1177. SHA_CTX sha;
  1178. uint8_t K[DIGEST_BLOCKSIZE], D[DIGEST_LEN], K_SHORT[DIGEST_LEN];
  1179. const uint8_t *real_key;
  1180. unsigned int i;
  1181. if (key_len > DIGEST_BLOCKSIZE) {
  1182. SHA1((const unsigned char*)key, key_len, K_SHORT);
  1183. key_len = DIGEST_LEN;
  1184. real_key = K_SHORT;
  1185. } else {
  1186. real_key = (const uint8_t*)key;
  1187. }
  1188. memset(K, 0, sizeof(K));
  1189. memcpy(K, real_key, key_len);
  1190. for (i=0; i < sizeof(K); ++i)
  1191. K[i] ^= 0x36;
  1192. SHA1_Init(&sha);
  1193. SHA1_Update(&sha, K, sizeof(K));
  1194. SHA1_Update(&sha, msg, msg_len);
  1195. SHA1_Final(D, &sha);
  1196. /*
  1197. memset(K, 0, sizeof(K));
  1198. memcpy(K, real_key, key_len);
  1199. for (i=0; i < sizeof(K); ++i)
  1200. K[i] ^= 0x5c;
  1201. */
  1202. for (i=0; i < sizeof(K); ++i)
  1203. K[i] ^= (0x36 ^ 0x5c);
  1204. SHA1_Init(&sha);
  1205. SHA1_Update(&sha, K, sizeof(K));
  1206. SHA1_Update(&sha, D, sizeof(D));
  1207. SHA1_Final((unsigned char*)hmac_out, &sha);
  1208. }
  1209. #endif
  1210. /** Compute the HMAC-SHA-1 of the <b>msg_len</b> bytes in <b>msg</b>, using
  1211. * the <b>key</b> of length <b>key_len</b>. Store the DIGEST_LEN-byte result
  1212. * in <b>hmac_out</b>.
  1213. */
  1214. void
  1215. crypto_hmac_sha1(char *hmac_out,
  1216. const char *key, size_t key_len,
  1217. const char *msg, size_t msg_len)
  1218. {
  1219. HMAC(EVP_sha1(), key, key_len, (unsigned char*)msg, msg_len,
  1220. (unsigned char*)hmac_out, NULL);
  1221. }
  1222. /* DH */
  1223. /** Shared P parameter for our DH key exchanged. */
  1224. static BIGNUM *dh_param_p = NULL;
  1225. /** Shared G parameter for our DH key exchanges. */
  1226. static BIGNUM *dh_param_g = NULL;
  1227. /** Initialize dh_param_p and dh_param_g if they are not already
  1228. * set. */
  1229. static void
  1230. init_dh_param(void)
  1231. {
  1232. BIGNUM *p, *g;
  1233. int r;
  1234. if (dh_param_p && dh_param_g)
  1235. return;
  1236. p = BN_new();
  1237. g = BN_new();
  1238. tor_assert(p);
  1239. tor_assert(g);
  1240. /* This is from rfc2409, section 6.2. It's a safe prime, and
  1241. supposedly it equals:
  1242. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  1243. */
  1244. r = BN_hex2bn(&p,
  1245. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  1246. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  1247. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  1248. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  1249. "49286651ECE65381FFFFFFFFFFFFFFFF");
  1250. tor_assert(r);
  1251. r = BN_set_word(g, 2);
  1252. tor_assert(r);
  1253. dh_param_p = p;
  1254. dh_param_g = g;
  1255. }
  1256. #define DH_PRIVATE_KEY_BITS 320
  1257. /** Allocate and return a new DH object for a key exchange.
  1258. */
  1259. crypto_dh_env_t *
  1260. crypto_dh_new(void)
  1261. {
  1262. crypto_dh_env_t *res = NULL;
  1263. if (!dh_param_p)
  1264. init_dh_param();
  1265. res = tor_malloc_zero(sizeof(crypto_dh_env_t));
  1266. if (!(res->dh = DH_new()))
  1267. goto err;
  1268. if (!(res->dh->p = BN_dup(dh_param_p)))
  1269. goto err;
  1270. if (!(res->dh->g = BN_dup(dh_param_g)))
  1271. goto err;
  1272. res->dh->length = DH_PRIVATE_KEY_BITS;
  1273. return res;
  1274. err:
  1275. crypto_log_errors(LOG_WARN, "creating DH object");
  1276. if (res && res->dh) DH_free(res->dh); /* frees p and g too */
  1277. if (res) tor_free(res);
  1278. return NULL;
  1279. }
  1280. /** Return the length of the DH key in <b>dh</b>, in bytes.
  1281. */
  1282. int
  1283. crypto_dh_get_bytes(crypto_dh_env_t *dh)
  1284. {
  1285. tor_assert(dh);
  1286. return DH_size(dh->dh);
  1287. }
  1288. /** Generate \<x,g^x\> for our part of the key exchange. Return 0 on
  1289. * success, -1 on failure.
  1290. */
  1291. int
  1292. crypto_dh_generate_public(crypto_dh_env_t *dh)
  1293. {
  1294. again:
  1295. if (!DH_generate_key(dh->dh)) {
  1296. crypto_log_errors(LOG_WARN, "generating DH key");
  1297. return -1;
  1298. }
  1299. if (tor_check_dh_key(dh->dh->pub_key)<0) {
  1300. log_warn(LD_CRYPTO, "Weird! Our own DH key was invalid. I guess once-in-"
  1301. "the-universe chances really do happen. Trying again.");
  1302. /* Free and clear the keys, so openssl will actually try again. */
  1303. BN_free(dh->dh->pub_key);
  1304. BN_free(dh->dh->priv_key);
  1305. dh->dh->pub_key = dh->dh->priv_key = NULL;
  1306. goto again;
  1307. }
  1308. return 0;
  1309. }
  1310. /** Generate g^x as necessary, and write the g^x for the key exchange
  1311. * as a <b>pubkey_len</b>-byte value into <b>pubkey</b>. Return 0 on
  1312. * success, -1 on failure. <b>pubkey_len</b> must be \>= DH_BYTES.
  1313. */
  1314. int
  1315. crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, size_t pubkey_len)
  1316. {
  1317. int bytes;
  1318. tor_assert(dh);
  1319. if (!dh->dh->pub_key) {
  1320. if (crypto_dh_generate_public(dh)<0)
  1321. return -1;
  1322. }
  1323. tor_assert(dh->dh->pub_key);
  1324. bytes = BN_num_bytes(dh->dh->pub_key);
  1325. tor_assert(bytes >= 0);
  1326. if (pubkey_len < (size_t)bytes) {
  1327. log_warn(LD_CRYPTO,
  1328. "Weird! pubkey_len (%d) was smaller than DH_BYTES (%d)",
  1329. (int) pubkey_len, bytes);
  1330. return -1;
  1331. }
  1332. memset(pubkey, 0, pubkey_len);
  1333. BN_bn2bin(dh->dh->pub_key, (unsigned char*)(pubkey+(pubkey_len-bytes)));
  1334. return 0;
  1335. }
  1336. /** Check for bad diffie-hellman public keys (g^x). Return 0 if the key is
  1337. * okay (in the subgroup [2,p-2]), or -1 if it's bad.
  1338. * See http://www.cl.cam.ac.uk/ftp/users/rja14/psandqs.ps.gz for some tips.
  1339. */
  1340. static int
  1341. tor_check_dh_key(BIGNUM *bn)
  1342. {
  1343. BIGNUM *x;
  1344. char *s;
  1345. tor_assert(bn);
  1346. x = BN_new();
  1347. tor_assert(x);
  1348. if (!dh_param_p)
  1349. init_dh_param();
  1350. BN_set_word(x, 1);
  1351. if (BN_cmp(bn,x)<=0) {
  1352. log_warn(LD_CRYPTO, "DH key must be at least 2.");
  1353. goto err;
  1354. }
  1355. BN_copy(x,dh_param_p);
  1356. BN_sub_word(x, 1);
  1357. if (BN_cmp(bn,x)>=0) {
  1358. log_warn(LD_CRYPTO, "DH key must be at most p-2.");
  1359. goto err;
  1360. }
  1361. BN_free(x);
  1362. return 0;
  1363. err:
  1364. BN_free(x);
  1365. s = BN_bn2hex(bn);
  1366. log_warn(LD_CRYPTO, "Rejecting insecure DH key [%s]", s);
  1367. OPENSSL_free(s);
  1368. return -1;
  1369. }
  1370. #undef MIN
  1371. #define MIN(a,b) ((a)<(b)?(a):(b))
  1372. /** Given a DH key exchange object, and our peer's value of g^y (as a
  1373. * <b>pubkey_len</b>-byte value in <b>pubkey</b>) generate
  1374. * <b>secret_bytes_out</b> bytes of shared key material and write them
  1375. * to <b>secret_out</b>. Return the number of bytes generated on success,
  1376. * or -1 on failure.
  1377. *
  1378. * (We generate key material by computing
  1379. * SHA1( g^xy || "\x00" ) || SHA1( g^xy || "\x01" ) || ...
  1380. * where || is concatenation.)
  1381. */
  1382. int
  1383. crypto_dh_compute_secret(crypto_dh_env_t *dh,
  1384. const char *pubkey, size_t pubkey_len,
  1385. char *secret_out, size_t secret_bytes_out)
  1386. {
  1387. char *secret_tmp = NULL;
  1388. BIGNUM *pubkey_bn = NULL;
  1389. size_t secret_len=0;
  1390. int result=0;
  1391. tor_assert(dh);
  1392. tor_assert(secret_bytes_out/DIGEST_LEN <= 255);
  1393. if (!(pubkey_bn = BN_bin2bn((const unsigned char*)pubkey, pubkey_len, NULL)))
  1394. goto error;
  1395. if (tor_check_dh_key(pubkey_bn)<0) {
  1396. /* Check for invalid public keys. */
  1397. log_warn(LD_CRYPTO,"Rejected invalid g^x");
  1398. goto error;
  1399. }
  1400. secret_tmp = tor_malloc(crypto_dh_get_bytes(dh));
  1401. result = DH_compute_key((unsigned char*)secret_tmp, pubkey_bn, dh->dh);
  1402. if (result < 0) {
  1403. log_warn(LD_CRYPTO,"DH_compute_key() failed.");
  1404. goto error;
  1405. }
  1406. secret_len = result;
  1407. /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
  1408. /* Actually, http://www.faqs.org/rfcs/rfc2631.html says:
  1409. * Leading zeros MUST be preserved, so that ZZ occupies as many
  1410. * octets as p. For instance, if p is 1024 bits, ZZ should be 128
  1411. * bytes long.
  1412. * What are the security implications here?
  1413. */
  1414. if (crypto_expand_key_material(secret_tmp, secret_len,
  1415. secret_out, secret_bytes_out)<0)
  1416. goto error;
  1417. secret_len = secret_bytes_out;
  1418. goto done;
  1419. error:
  1420. result = -1;
  1421. done:
  1422. crypto_log_errors(LOG_WARN, "completing DH handshake");
  1423. if (pubkey_bn)
  1424. BN_free(pubkey_bn);
  1425. tor_free(secret_tmp);
  1426. if (result < 0)
  1427. return result;
  1428. else
  1429. return secret_len;
  1430. }
  1431. /** Given <b>key_in_len</b> bytes of negotiated randomness in <b>key_in</b>
  1432. * ("K"), expand it into <b>key_out_len</b> bytes of negotiated key material in
  1433. * <b>key_out</b> by taking the first key_out_len bytes of
  1434. * H(K | [00]) | H(K | [01]) | ....
  1435. *
  1436. * Return 0 on success, -1 on failure.
  1437. */
  1438. int
  1439. crypto_expand_key_material(const char *key_in, size_t key_in_len,
  1440. char *key_out, size_t key_out_len)
  1441. {
  1442. int i;
  1443. char *cp, *tmp = tor_malloc(key_in_len+1);
  1444. char digest[DIGEST_LEN];
  1445. /* If we try to get more than this amount of key data, we'll repeat blocks.*/
  1446. tor_assert(key_out_len <= DIGEST_LEN*256);
  1447. memcpy(tmp, key_in, key_in_len);
  1448. for (cp = key_out, i=0; cp < key_out+key_out_len;
  1449. ++i, cp += DIGEST_LEN) {
  1450. tmp[key_in_len] = i;
  1451. if (crypto_digest(digest, tmp, key_in_len+1))
  1452. goto err;
  1453. memcpy(cp, digest, MIN(DIGEST_LEN, key_out_len-(cp-key_out)));
  1454. }
  1455. memset(tmp, 0, key_in_len+1);
  1456. tor_free(tmp);
  1457. return 0;
  1458. err:
  1459. memset(tmp, 0, key_in_len+1);
  1460. tor_free(tmp);
  1461. return -1;
  1462. }
  1463. /** Free a DH key exchange object.
  1464. */
  1465. void
  1466. crypto_dh_free(crypto_dh_env_t *dh)
  1467. {
  1468. tor_assert(dh);
  1469. tor_assert(dh->dh);
  1470. DH_free(dh->dh);
  1471. tor_free(dh);
  1472. }
  1473. /* random numbers */
  1474. /* This is how much entropy OpenSSL likes to add right now, so maybe it will
  1475. * work for us too. */
  1476. #define ADD_ENTROPY 32
  1477. /* Use RAND_poll if openssl is 0.9.6 release or later. (The "f" means
  1478. "release".) */
  1479. //#define USE_RAND_POLL (OPENSSL_VERSION_NUMBER >= 0x0090600fl)
  1480. #define USE_RAND_POLL 0
  1481. /* XXX Somehow setting USE_RAND_POLL on causes stack smashes. We're
  1482. * not sure where. This was the big bug with Tor 0.1.1.9-alpha. */
  1483. /** Seed OpenSSL's random number generator with bytes from the
  1484. * operating system. Return 0 on success, -1 on failure.
  1485. */
  1486. int
  1487. crypto_seed_rng(void)
  1488. {
  1489. char buf[ADD_ENTROPY];
  1490. int rand_poll_status;
  1491. /* local variables */
  1492. #ifdef MS_WINDOWS
  1493. static int provider_set = 0;
  1494. static HCRYPTPROV provider;
  1495. #else
  1496. static const char *filenames[] = {
  1497. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1498. };
  1499. int fd;
  1500. int i, n;
  1501. #endif
  1502. #if USE_RAND_POLL
  1503. /* OpenSSL 0.9.6 adds a RAND_poll function that knows about more kinds of
  1504. * entropy than we do. We'll try calling that, *and* calling our own entropy
  1505. * functions. If one succeeds, we'll accept the RNG as seeded. */
  1506. rand_poll_status = RAND_poll();
  1507. if (rand_poll_status == 0)
  1508. log_warn(LD_CRYPTO, "RAND_poll() failed.");
  1509. #else
  1510. rand_poll_status = 0;
  1511. #endif
  1512. #ifdef MS_WINDOWS
  1513. if (!provider_set) {
  1514. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  1515. CRYPT_VERIFYCONTEXT)) {
  1516. if ((unsigned long)GetLastError() != (unsigned long)NTE_BAD_KEYSET) {
  1517. log_warn(LD_CRYPTO, "Can't get CryptoAPI provider [1]");
  1518. return rand_poll_status ? 0 : -1;
  1519. }
  1520. }
  1521. provider_set = 1;
  1522. }
  1523. if (!CryptGenRandom(provider, sizeof(buf), buf)) {
  1524. log_warn(LD_CRYPTO, "Can't get entropy from CryptoAPI.");
  1525. return rand_poll_status ? 0 : -1;
  1526. }
  1527. RAND_seed(buf, sizeof(buf));
  1528. return 0;
  1529. #else
  1530. for (i = 0; filenames[i]; ++i) {
  1531. fd = open(filenames[i], O_RDONLY, 0);
  1532. if (fd<0) continue;
  1533. log_info(LD_CRYPTO, "Seeding RNG from \"%s\"", filenames[i]);
  1534. n = read_all(fd, buf, sizeof(buf), 0);
  1535. close(fd);
  1536. if (n != sizeof(buf)) {
  1537. log_warn(LD_CRYPTO,
  1538. "Error reading from entropy source (read only %d bytes).", n);
  1539. return -1;
  1540. }
  1541. RAND_seed(buf, sizeof(buf));
  1542. return 0;
  1543. }
  1544. log_warn(LD_CRYPTO, "Cannot seed RNG -- no entropy source found.");
  1545. return rand_poll_status ? 0 : -1;
  1546. #endif
  1547. }
  1548. /** Write n bytes of strong random data to <b>to</b>. Return 0 on
  1549. * success, -1 on failure.
  1550. */
  1551. int
  1552. crypto_rand(char *to, size_t n)
  1553. {
  1554. int r;
  1555. tor_assert(to);
  1556. r = RAND_bytes((unsigned char*)to, n);
  1557. if (r == 0)
  1558. crypto_log_errors(LOG_WARN, "generating random data");
  1559. return (r == 1) ? 0 : -1;
  1560. }
  1561. /** Return a pseudorandom integer, chosen uniformly from the values
  1562. * between 0 and max-1. */
  1563. int
  1564. crypto_rand_int(unsigned int max)
  1565. {
  1566. unsigned int val;
  1567. unsigned int cutoff;
  1568. tor_assert(max < UINT_MAX);
  1569. tor_assert(max > 0); /* don't div by 0 */
  1570. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1571. * distribution with clipping at the upper end of unsigned int's
  1572. * range.
  1573. */
  1574. cutoff = UINT_MAX - (UINT_MAX%max);
  1575. while (1) {
  1576. crypto_rand((char*)&val, sizeof(val));
  1577. if (val < cutoff)
  1578. return val % max;
  1579. }
  1580. }
  1581. /** Return a pseudorandom integer, chosen uniformly from the values
  1582. * between 0 and max-1. */
  1583. uint64_t
  1584. crypto_rand_uint64(uint64_t max)
  1585. {
  1586. uint64_t val;
  1587. uint64_t cutoff;
  1588. tor_assert(max < UINT64_MAX);
  1589. tor_assert(max > 0); /* don't div by 0 */
  1590. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1591. * distribution with clipping at the upper end of unsigned int's
  1592. * range.
  1593. */
  1594. cutoff = UINT64_MAX - (UINT64_MAX%max);
  1595. while (1) {
  1596. crypto_rand((char*)&val, sizeof(val));
  1597. if (val < cutoff)
  1598. return val % max;
  1599. }
  1600. }
  1601. /** Return a randomly chosen element of sl; or NULL if sl is empty.
  1602. */
  1603. void *
  1604. smartlist_choose(const smartlist_t *sl)
  1605. {
  1606. size_t len;
  1607. len = smartlist_len(sl);
  1608. if (len)
  1609. return smartlist_get(sl,crypto_rand_int(len));
  1610. return NULL; /* no elements to choose from */
  1611. }
  1612. /** Scramble the elements of sl into a random order. */
  1613. void
  1614. smartlist_shuffle(smartlist_t *sl)
  1615. {
  1616. int i;
  1617. /* From the end of the list to the front, choose at random from the
  1618. positions we haven't looked at yet, and swap that position into the
  1619. current position. Remember to give "no swap" the same probability as
  1620. any other swap. */
  1621. for (i = smartlist_len(sl)-1; i > 0; --i) {
  1622. int j = crypto_rand_int(i+1);
  1623. smartlist_swap(sl, i, j);
  1624. }
  1625. }
  1626. /** Base-64 encode <b>srclen</b> bytes of data from <b>src</b>. Write
  1627. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1628. * bytes. Return the number of bytes written on success; -1 if
  1629. * destlen is too short, or other failure.
  1630. */
  1631. int
  1632. base64_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1633. {
  1634. /* XXXX we might want to rewrite this along the lines of base64_decode, if
  1635. * it ever shows up in the profile. */
  1636. EVP_ENCODE_CTX ctx;
  1637. int len, ret;
  1638. /* 48 bytes of input -> 64 bytes of output plus newline.
  1639. Plus one more byte, in case I'm wrong.
  1640. */
  1641. if (destlen < ((srclen/48)+1)*66)
  1642. return -1;
  1643. if (destlen > SIZE_T_CEILING)
  1644. return -1;
  1645. EVP_EncodeInit(&ctx);
  1646. EVP_EncodeUpdate(&ctx, (unsigned char*)dest, &len,
  1647. (unsigned char*)src, srclen);
  1648. EVP_EncodeFinal(&ctx, (unsigned char*)(dest+len), &ret);
  1649. ret += len;
  1650. return ret;
  1651. }
  1652. #define X 255
  1653. #define SP 64
  1654. #define PAD 65
  1655. /** Internal table mapping byte values to what they represent in base64.
  1656. * Numbers 0..63 are 6-bit integers. SPs are spaces, and should be
  1657. * skipped. Xs are invalid and must not appear in base64. PAD indicates
  1658. * end-of-string. */
  1659. static const uint8_t base64_decode_table[256] = {
  1660. X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X, /* */
  1661. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1662. SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
  1663. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
  1664. X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  1665. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
  1666. X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  1667. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
  1668. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1669. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1670. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1671. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1672. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1673. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1674. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1675. X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
  1676. };
  1677. /** Base-64 decode <b>srclen</b> bytes of data from <b>src</b>. Write
  1678. * the result into <b>dest</b>, if it will fit within <b>destlen</b>
  1679. * bytes. Return the number of bytes written on success; -1 if
  1680. * destlen is too short, or other failure.
  1681. *
  1682. * NOTE 1: destlen is checked conservatively, as though srclen contained no
  1683. * spaces or padding.
  1684. *
  1685. * NOTE 2: This implementation does not check for the correct number of
  1686. * padding "=" characters at the end of the string, and does not check
  1687. * for internal padding characters.
  1688. */
  1689. int
  1690. base64_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  1691. {
  1692. #ifdef USE_OPENSSL_BASE64
  1693. EVP_ENCODE_CTX ctx;
  1694. int len, ret;
  1695. /* 64 bytes of input -> *up to* 48 bytes of output.
  1696. Plus one more byte, in case I'm wrong.
  1697. */
  1698. if (destlen < ((srclen/64)+1)*49)
  1699. return -1;
  1700. if (destlen > SIZE_T_CEILING)
  1701. return -1;
  1702. EVP_DecodeInit(&ctx);
  1703. EVP_DecodeUpdate(&ctx, (unsigned char*)dest, &len,
  1704. (unsigned char*)src, srclen);
  1705. EVP_DecodeFinal(&ctx, (unsigned char*)dest, &ret);
  1706. ret += len;
  1707. return ret;
  1708. #else
  1709. #define ACC32
  1710. const char *eos = src+srclen;
  1711. uint32_t n=0;
  1712. int n_idx=0;
  1713. char *dest_orig = dest;
  1714. /* Max number of bits == srclen*6.
  1715. * Number of bytes required to hold all bits == (srclen*6)/8.
  1716. * Yes, we want to round down: anything that hangs over the end of a
  1717. * byte is padding. */
  1718. if (destlen < (srclen*3)/4)
  1719. return -1;
  1720. if (destlen > SIZE_T_CEILING)
  1721. return -1;
  1722. /* Iterate over all the bytes in src. Each one will add 0 or 6 bits to the
  1723. * value we're decoding. Accumulate bits in <b>n</b>, and whenever we have
  1724. * 24 bits, batch them into 3 bytes and flush those bytes to dest.
  1725. */
  1726. for ( ; src < eos; ++src) {
  1727. unsigned char c = (unsigned char) *src;
  1728. uint8_t v = base64_decode_table[c];
  1729. switch (v) {
  1730. case X:
  1731. /* This character isn't allowed in base64. */
  1732. return -1;
  1733. case SP:
  1734. /* This character is whitespace, and has no effect. */
  1735. continue;
  1736. case PAD:
  1737. /* We've hit an = character: the data is over. */
  1738. goto end_of_loop;
  1739. default:
  1740. /* We have an actual 6-bit value. Append it to the bits in n. */
  1741. n = (n<<6) | v;
  1742. if ((++n_idx) == 4) {
  1743. /* We've accumulated 24 bits in n. Flush them. */
  1744. *dest++ = (n>>16);
  1745. *dest++ = (n>>8) & 0xff;
  1746. *dest++ = (n) & 0xff;
  1747. n_idx = 0;
  1748. n = 0;
  1749. }
  1750. }
  1751. }
  1752. end_of_loop:
  1753. /* If we have leftover bits, we need to cope. */
  1754. switch (n_idx) {
  1755. case 0:
  1756. default:
  1757. /* No leftover bits. We win. */
  1758. break;
  1759. case 1:
  1760. /* 6 leftover bits. That's invalid; we can't form a byte out of that. */
  1761. return -1;
  1762. case 2:
  1763. /* 12 leftover bits: The last 4 are padding and the first 8 are data. */
  1764. *dest++ = n >> 4;
  1765. break;
  1766. case 3:
  1767. /* 18 leftover bits: The last 2 are padding and the first 16 are data. */
  1768. *dest++ = n >> 10;
  1769. *dest++ = n >> 2;
  1770. }
  1771. tor_assert((dest-dest_orig) <= (ssize_t)destlen);
  1772. return dest-dest_orig;
  1773. #endif
  1774. }
  1775. #undef X
  1776. #undef SP
  1777. #undef NIL
  1778. /** Base-64 encode DIGEST_LINE bytes from <b>digest</b>, remove the trailing =
  1779. * and newline characters, and store the nul-terminated result in the first
  1780. * BASE64_DIGEST_LEN+1 bytes of <b>d64</b>. */
  1781. int
  1782. digest_to_base64(char *d64, const char *digest)
  1783. {
  1784. char buf[256];
  1785. base64_encode(buf, sizeof(buf), digest, DIGEST_LEN);
  1786. buf[BASE64_DIGEST_LEN] = '\0';
  1787. memcpy(d64, buf, BASE64_DIGEST_LEN+1);
  1788. return 0;
  1789. }
  1790. /** Given a base-64 encoded, nul-terminated digest in <b>d64</b> (without
  1791. * trailing newline or = characters), decode it and store the result in the
  1792. * first DIGEST_LEN bytes at <b>digest</b>. */
  1793. int
  1794. digest_from_base64(char *digest, const char *d64)
  1795. {
  1796. #ifdef USE_OPENSSL_BASE64
  1797. char buf_in[BASE64_DIGEST_LEN+3];
  1798. char buf[256];
  1799. if (strlen(d64) != BASE64_DIGEST_LEN)
  1800. return -1;
  1801. memcpy(buf_in, d64, BASE64_DIGEST_LEN);
  1802. memcpy(buf_in+BASE64_DIGEST_LEN, "=\n\0", 3);
  1803. if (base64_decode(buf, sizeof(buf), buf_in, strlen(buf_in)) != DIGEST_LEN)
  1804. return -1;
  1805. memcpy(digest, buf, DIGEST_LEN);
  1806. return 0;
  1807. #else
  1808. if (base64_decode(digest, DIGEST_LEN, d64, strlen(d64)) == DIGEST_LEN)
  1809. return 0;
  1810. else
  1811. return -1;
  1812. #endif
  1813. }
  1814. /** Implements base32 encoding as in rfc3548. Limitation: Requires
  1815. * that srclen*8 is a multiple of 5.
  1816. */
  1817. void
  1818. base32_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  1819. {
  1820. unsigned int nbits, i, bit, v, u;
  1821. nbits = srclen * 8;
  1822. tor_assert((nbits%5) == 0); /* We need an even multiple of 5 bits. */
  1823. tor_assert((nbits/5)+1 <= destlen); /* We need enough space. */
  1824. tor_assert(destlen < SIZE_T_CEILING);
  1825. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  1826. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  1827. v = ((uint8_t)src[bit/8]) << 8;
  1828. if (bit+5<nbits) v += (uint8_t)src[(bit/8)+1];
  1829. /* set u to the 5-bit value at the bit'th bit of src. */
  1830. u = (v >> (11-(bit%8))) & 0x1F;
  1831. dest[i] = BASE32_CHARS[u];
  1832. }
  1833. dest[i] = '\0';
  1834. }
  1835. /** Implements base32 decoding as in rfc3548. Limitation: Requires
  1836. * that srclen*5 is a multiple of 8. Returns 0 if successful, -1 otherwise.
  1837. */
  1838. int
  1839. base32_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  1840. {
  1841. /* XXXX we might want to rewrite this along the lines of base64_decode, if
  1842. * it ever shows up in the profile. */
  1843. unsigned int nbits, i, j, bit;
  1844. char *tmp;
  1845. nbits = srclen * 5;
  1846. tor_assert((nbits%8) == 0); /* We need an even multiple of 8 bits. */
  1847. tor_assert((nbits/8) <= destlen); /* We need enough space. */
  1848. tor_assert(destlen < SIZE_T_CEILING);
  1849. /* Convert base32 encoded chars to the 5-bit values that they represent. */
  1850. tmp = tor_malloc_zero(srclen);
  1851. for (j = 0; j < srclen; ++j) {
  1852. if (src[j] > 0x60 && src[j] < 0x7B) tmp[j] = src[j] - 0x61;
  1853. else if (src[j] > 0x31 && src[j] < 0x38) tmp[j] = src[j] - 0x18;
  1854. else if (src[j] > 0x40 && src[j] < 0x5B) tmp[j] = src[j] - 0x41;
  1855. else {
  1856. log_warn(LD_BUG, "illegal character in base32 encoded string");
  1857. tor_free(tmp);
  1858. return -1;
  1859. }
  1860. }
  1861. /* Assemble result byte-wise by applying five possible cases. */
  1862. for (i = 0, bit = 0; bit < nbits; ++i, bit += 8) {
  1863. switch (bit % 40) {
  1864. case 0:
  1865. dest[i] = (((uint8_t)tmp[(bit/5)]) << 3) +
  1866. (((uint8_t)tmp[(bit/5)+1]) >> 2);
  1867. break;
  1868. case 8:
  1869. dest[i] = (((uint8_t)tmp[(bit/5)]) << 6) +
  1870. (((uint8_t)tmp[(bit/5)+1]) << 1) +
  1871. (((uint8_t)tmp[(bit/5)+2]) >> 4);
  1872. break;
  1873. case 16:
  1874. dest[i] = (((uint8_t)tmp[(bit/5)]) << 4) +
  1875. (((uint8_t)tmp[(bit/5)+1]) >> 1);
  1876. break;
  1877. case 24:
  1878. dest[i] = (((uint8_t)tmp[(bit/5)]) << 7) +
  1879. (((uint8_t)tmp[(bit/5)+1]) << 2) +
  1880. (((uint8_t)tmp[(bit/5)+2]) >> 3);
  1881. break;
  1882. case 32:
  1883. dest[i] = (((uint8_t)tmp[(bit/5)]) << 5) +
  1884. ((uint8_t)tmp[(bit/5)+1]);
  1885. break;
  1886. }
  1887. }
  1888. tor_free(tmp);
  1889. tmp = NULL;
  1890. return 0;
  1891. }
  1892. /** Implement RFC2440-style iterated-salted S2K conversion: convert the
  1893. * <b>secret_len</b>-byte <b>secret</b> into a <b>key_out_len</b> byte
  1894. * <b>key_out</b>. As in RFC2440, the first 8 bytes of s2k_specifier
  1895. * are a salt; the 9th byte describes how much iteration to do.
  1896. * Does not support <b>key_out_len</b> &gt; DIGEST_LEN.
  1897. */
  1898. void
  1899. secret_to_key(char *key_out, size_t key_out_len, const char *secret,
  1900. size_t secret_len, const char *s2k_specifier)
  1901. {
  1902. crypto_digest_env_t *d;
  1903. uint8_t c;
  1904. size_t count;
  1905. char *tmp;
  1906. tor_assert(key_out_len < SIZE_T_CEILING);
  1907. #define EXPBIAS 6
  1908. c = s2k_specifier[8];
  1909. count = ((uint32_t)16 + (c & 15)) << ((c >> 4) + EXPBIAS);
  1910. #undef EXPBIAS
  1911. tor_assert(key_out_len <= DIGEST_LEN);
  1912. d = crypto_new_digest_env();
  1913. tmp = tor_malloc(8+secret_len);
  1914. memcpy(tmp,s2k_specifier,8);
  1915. memcpy(tmp+8,secret,secret_len);
  1916. secret_len += 8;
  1917. while (count) {
  1918. if (count >= secret_len) {
  1919. crypto_digest_add_bytes(d, tmp, secret_len);
  1920. count -= secret_len;
  1921. } else {
  1922. crypto_digest_add_bytes(d, tmp, count);
  1923. count = 0;
  1924. }
  1925. }
  1926. crypto_digest_get_digest(d, key_out, key_out_len);
  1927. tor_free(tmp);
  1928. crypto_free_digest_env(d);
  1929. }
  1930. #ifdef TOR_IS_MULTITHREADED
  1931. /** Helper: openssl uses this callback to manipulate mutexes. */
  1932. static void
  1933. _openssl_locking_cb(int mode, int n, const char *file, int line)
  1934. {
  1935. (void)file;
  1936. (void)line;
  1937. if (!_openssl_mutexes)
  1938. /* This is not a really good fix for the
  1939. * "release-freed-lock-from-separate-thread-on-shutdown" problem, but
  1940. * it can't hurt. */
  1941. return;
  1942. if (mode & CRYPTO_LOCK)
  1943. tor_mutex_acquire(_openssl_mutexes[n]);
  1944. else
  1945. tor_mutex_release(_openssl_mutexes[n]);
  1946. }
  1947. /** Helper: Construct mutexes, and set callbacks to help OpenSSL handle being
  1948. * multithreaded. */
  1949. static int
  1950. setup_openssl_threading(void)
  1951. {
  1952. int i;
  1953. int n = CRYPTO_num_locks();
  1954. _n_openssl_mutexes = n;
  1955. _openssl_mutexes = tor_malloc(n*sizeof(tor_mutex_t *));
  1956. for (i=0; i < n; ++i)
  1957. _openssl_mutexes[i] = tor_mutex_new();
  1958. CRYPTO_set_locking_callback(_openssl_locking_cb);
  1959. CRYPTO_set_id_callback(tor_get_thread_id);
  1960. return 0;
  1961. }
  1962. #else
  1963. static int
  1964. setup_openssl_threading(void)
  1965. {
  1966. return 0;
  1967. }
  1968. #endif