crypto.c 70 KB

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