crypto.c 57 KB

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