crypto.c 73 KB

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