crypto.c 74 KB

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