tortls.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. /* Copyright (c) 2003, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char tortls_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file tortls.c
  10. * \brief Wrapper functions to present a consistent interface to
  11. * TLS, SSL, and X.509 functions from OpenSSL.
  12. **/
  13. /* (Unlike other tor functions, these
  14. * are prefixed with tor_ in order to avoid conflicting with OpenSSL
  15. * functions and variables.)
  16. */
  17. #include "orconfig.h"
  18. #include <assert.h>
  19. #include <openssl/ssl.h>
  20. #include <openssl/ssl3.h>
  21. #include <openssl/err.h>
  22. #include <openssl/tls1.h>
  23. #include <openssl/asn1.h>
  24. #include <openssl/bio.h>
  25. #include <openssl/opensslv.h>
  26. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  27. #error "We require openssl >= 0.9.7"
  28. #endif
  29. #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
  30. #include "crypto.h"
  31. #include "tortls.h"
  32. #include "util.h"
  33. #include "log.h"
  34. #include "container.h"
  35. #include <string.h>
  36. // #define V2_HANDSHAKE_SERVER
  37. // #define V2_HANDSHAKE_CLIENT
  38. /* Copied from or.h */
  39. #define LEGAL_NICKNAME_CHARACTERS \
  40. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  41. /** How long do identity certificates live? (sec) */
  42. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  43. /** Structure holding the TLS state for a single connection. */
  44. typedef struct tor_tls_context_t {
  45. int refcnt;
  46. SSL_CTX *ctx;
  47. X509 *my_cert;
  48. X509 *my_id_cert;
  49. crypto_pk_env_t *key;
  50. } tor_tls_context_t;
  51. /** Holds a SSL object and its associated data. Members are only
  52. * accessed from within tortls.c.
  53. */
  54. struct tor_tls_t {
  55. tor_tls_context_t *context; /**DOCDOC */
  56. SSL *ssl; /**< An OpenSSL SSL object. */
  57. int socket; /**< The underlying file descriptor for this TLS connection. */
  58. enum {
  59. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  60. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
  61. } state : 3; /**< The current SSL state, depending on which operations have
  62. * completed successfully. */
  63. unsigned int isServer:1; /**< True iff this is a server-side connection */
  64. unsigned int hadCert:1; /**< Docdoc */
  65. unsigned int wasV2Handshake:1; /**< DOCDOC */
  66. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
  67. * time. */
  68. unsigned long last_write_count;
  69. unsigned long last_read_count;
  70. void (*negotiated_callback)(tor_tls_t *tls, void *arg);
  71. void *callback_arg;
  72. };
  73. static void tor_tls_context_decref(tor_tls_context_t *ctx);
  74. static void tor_tls_context_incref(tor_tls_context_t *ctx);
  75. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  76. crypto_pk_env_t *rsa_sign,
  77. const char *cname,
  78. const char *cname_sign,
  79. unsigned int lifetime);
  80. /** Global tls context. We keep it here because nobody else needs to
  81. * touch it. */
  82. static tor_tls_context_t *global_tls_context = NULL;
  83. /** True iff tor_tls_init() has been called. */
  84. static int tls_library_is_initialized = 0;
  85. /* Module-internal error codes. */
  86. #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
  87. #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
  88. /** Log all pending tls errors at level <b>severity</b>. Use
  89. * <b>doing</b> to describe our current activities.
  90. */
  91. static void
  92. tls_log_errors(int severity, const char *doing)
  93. {
  94. int err;
  95. const char *msg, *lib, *func;
  96. while ((err = ERR_get_error()) != 0) {
  97. msg = (const char*)ERR_reason_error_string(err);
  98. lib = (const char*)ERR_lib_error_string(err);
  99. func = (const char*)ERR_func_error_string(err);
  100. if (!msg) msg = "(null)";
  101. if (doing) {
  102. log(severity, LD_NET, "TLS error while %s: %s (in %s:%s)",
  103. doing, msg, lib,func);
  104. } else {
  105. log(severity, LD_NET, "TLS error: %s (in %s:%s)", msg, lib, func);
  106. }
  107. }
  108. }
  109. /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
  110. * code. */
  111. static int
  112. tor_errno_to_tls_error(int e)
  113. {
  114. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  115. switch (e) {
  116. case WSAECONNRESET: // most common
  117. return TOR_TLS_ERROR_CONNRESET;
  118. case WSAETIMEDOUT:
  119. return TOR_TLS_ERROR_TIMEOUT;
  120. case WSAENETUNREACH:
  121. case WSAEHOSTUNREACH:
  122. return TOR_TLS_ERROR_NO_ROUTE;
  123. case WSAECONNREFUSED:
  124. return TOR_TLS_ERROR_CONNREFUSED; // least common
  125. default:
  126. return TOR_TLS_ERROR_MISC;
  127. }
  128. #else
  129. switch (e) {
  130. case ECONNRESET: // most common
  131. return TOR_TLS_ERROR_CONNRESET;
  132. case ETIMEDOUT:
  133. return TOR_TLS_ERROR_TIMEOUT;
  134. case EHOSTUNREACH:
  135. case ENETUNREACH:
  136. return TOR_TLS_ERROR_NO_ROUTE;
  137. case ECONNREFUSED:
  138. return TOR_TLS_ERROR_CONNREFUSED; // least common
  139. default:
  140. return TOR_TLS_ERROR_MISC;
  141. }
  142. #endif
  143. }
  144. /** DOCDOC */
  145. const char *
  146. tor_tls_err_to_string(int err)
  147. {
  148. if (err >= 0)
  149. return "[Not an error.]";
  150. switch (err) {
  151. case TOR_TLS_ERROR_MISC: return "misc error";
  152. case TOR_TLS_ERROR_IO: return "unexpected close";
  153. case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
  154. case TOR_TLS_ERROR_CONNRESET: return "connection reset";
  155. case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
  156. case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
  157. case TOR_TLS_CLOSE: return "closed";
  158. case TOR_TLS_WANTREAD: return "want to read";
  159. case TOR_TLS_WANTWRITE: return "want to write";
  160. default: return "(unknown error code)";
  161. }
  162. }
  163. #define CATCH_SYSCALL 1
  164. #define CATCH_ZERO 2
  165. /** Given a TLS object and the result of an SSL_* call, use
  166. * SSL_get_error to determine whether an error has occurred, and if so
  167. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  168. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  169. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  170. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  171. *
  172. * If an error has occurred, log it at level <b>severity</b> and describe the
  173. * current action as <b>doing</b>.
  174. */
  175. static int
  176. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  177. const char *doing, int severity)
  178. {
  179. int err = SSL_get_error(tls->ssl, r);
  180. int tor_error = TOR_TLS_ERROR_MISC;
  181. switch (err) {
  182. case SSL_ERROR_NONE:
  183. return TOR_TLS_DONE;
  184. case SSL_ERROR_WANT_READ:
  185. return TOR_TLS_WANTREAD;
  186. case SSL_ERROR_WANT_WRITE:
  187. return TOR_TLS_WANTWRITE;
  188. case SSL_ERROR_SYSCALL:
  189. if (extra&CATCH_SYSCALL)
  190. return _TOR_TLS_SYSCALL;
  191. if (r == 0) {
  192. log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
  193. tor_error = TOR_TLS_ERROR_IO;
  194. } else {
  195. int e = tor_socket_errno(tls->socket);
  196. log(severity, LD_NET,
  197. "TLS error: <syscall error while %s> (errno=%d: %s)",
  198. doing, e, tor_socket_strerror(e));
  199. tor_error = tor_errno_to_tls_error(e);
  200. }
  201. tls_log_errors(severity, doing);
  202. return tor_error;
  203. case SSL_ERROR_ZERO_RETURN:
  204. if (extra&CATCH_ZERO)
  205. return _TOR_TLS_ZERORETURN;
  206. log(severity, LD_NET, "TLS error: Zero return");
  207. tls_log_errors(severity, doing);
  208. /* XXXX020 Actually, a 'zero return' error has a pretty specific meaning:
  209. * the connection has been closed cleanly. */
  210. return TOR_TLS_ERROR_MISC;
  211. default:
  212. tls_log_errors(severity, doing);
  213. return TOR_TLS_ERROR_MISC;
  214. }
  215. }
  216. /** Initialize OpenSSL, unless it has already been initialized.
  217. */
  218. static void
  219. tor_tls_init(void)
  220. {
  221. if (!tls_library_is_initialized) {
  222. SSL_library_init();
  223. SSL_load_error_strings();
  224. crypto_global_init(-1);
  225. tls_library_is_initialized = 1;
  226. }
  227. }
  228. /** Free all global TLS structures. */
  229. void
  230. tor_tls_free_all(void)
  231. {
  232. if (global_tls_context) {
  233. tor_tls_context_decref(global_tls_context);
  234. global_tls_context = NULL;
  235. }
  236. }
  237. /** We need to give OpenSSL a callback to verify certificates. This is
  238. * it: We always accept peer certs and complete the handshake. We
  239. * don't validate them until later.
  240. */
  241. static int
  242. always_accept_verify_cb(int preverify_ok,
  243. X509_STORE_CTX *x509_ctx)
  244. {
  245. /* avoid "unused parameter" warning. */
  246. preverify_ok = 0;
  247. x509_ctx = NULL;
  248. return 1;
  249. }
  250. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  251. * signed by the private key <b>rsa_sign</b>. The commonName of the
  252. * certificate will be <b>cname</b>; the commonName of the issuer will be
  253. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  254. * starting from now. Return a certificate on success, NULL on
  255. * failure.
  256. */
  257. static X509 *
  258. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  259. crypto_pk_env_t *rsa_sign,
  260. const char *cname,
  261. const char *cname_sign,
  262. unsigned int cert_lifetime)
  263. {
  264. time_t start_time, end_time;
  265. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  266. X509 *x509 = NULL;
  267. X509_NAME *name = NULL, *name_issuer=NULL;
  268. int nid;
  269. tor_tls_init();
  270. start_time = time(NULL);
  271. tor_assert(rsa);
  272. tor_assert(cname);
  273. tor_assert(rsa_sign);
  274. tor_assert(cname_sign);
  275. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  276. goto error;
  277. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  278. goto error;
  279. if (!(x509 = X509_new()))
  280. goto error;
  281. if (!(X509_set_version(x509, 2)))
  282. goto error;
  283. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  284. goto error;
  285. if (!(name = X509_NAME_new()))
  286. goto error;
  287. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
  288. goto error;
  289. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  290. (unsigned char*)"t o r", -1, -1, 0)))
  291. goto error;
  292. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  293. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  294. (unsigned char*)cname, -1, -1, 0)))
  295. goto error;
  296. if (!(X509_set_subject_name(x509, name)))
  297. goto error;
  298. if (!(name_issuer = X509_NAME_new()))
  299. goto error;
  300. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
  301. goto error;
  302. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  303. (unsigned char*)"t o r", -1, -1, 0)))
  304. goto error;
  305. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  306. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  307. (unsigned char*)cname_sign, -1, -1, 0)))
  308. goto error;
  309. if (!(X509_set_issuer_name(x509, name_issuer)))
  310. goto error;
  311. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  312. goto error;
  313. end_time = start_time + cert_lifetime;
  314. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  315. goto error;
  316. if (!X509_set_pubkey(x509, pkey))
  317. goto error;
  318. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  319. goto error;
  320. goto done;
  321. error:
  322. if (x509) {
  323. X509_free(x509);
  324. x509 = NULL;
  325. }
  326. done:
  327. tls_log_errors(LOG_WARN, "generating certificate");
  328. if (sign_pkey)
  329. EVP_PKEY_free(sign_pkey);
  330. if (pkey)
  331. EVP_PKEY_free(pkey);
  332. if (name)
  333. X509_NAME_free(name);
  334. if (name_issuer)
  335. X509_NAME_free(name_issuer);
  336. return x509;
  337. }
  338. #define SERVER_CIPHER_LIST \
  339. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  340. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  341. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  342. /* Note: for setting up your own private testing network with link crypto
  343. * disabled, set the cipher lists to your cipher list to
  344. * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
  345. * with any of the "real" Tors, though. */
  346. #if OPENSSL_VERSION_NUMBER >= 0x00908000l
  347. #define CLIENT_CIPHER_LIST \
  348. (TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ":" \
  349. TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":" \
  350. TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  351. TLS1_TXT_DHE_DSS_WITH_AES_256_SHA ":" \
  352. TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA ":" \
  353. TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA ":" \
  354. TLS1_TXT_RSA_WITH_AES_256_SHA ":" \
  355. TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA ":" \
  356. TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA ":" \
  357. TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA ":" \
  358. TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":" \
  359. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  360. TLS1_TXT_DHE_DSS_WITH_AES_128_SHA ":" \
  361. TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA":" \
  362. TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA":" \
  363. TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA ":" \
  364. TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA ":" \
  365. SSL3_TXT_RSA_RC4_128_MD5 ":" \
  366. SSL3_TXT_RSA_RC4_128_SHA ":" \
  367. TLS1_TXT_RSA_WITH_AES_128_SHA ":" \
  368. TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA ":" \
  369. TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA ":" \
  370. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
  371. SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA ":" \
  372. TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA ":" \
  373. TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA ":" \
  374. SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA ":" \
  375. SSL3_TXT_RSA_DES_192_CBC3_SHA)
  376. #else
  377. /* Ug. We don't have as many ciphers with openssl 0.9.7 as we'd like. Fix
  378. * this list into something that sucks less. */
  379. #define CLIENT_CIPHER_LIST \
  380. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  381. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  382. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
  383. SSL3_TXT_RSA_RC4_128_SHA)
  384. #endif
  385. #ifndef V2_HANDSHAKE_CLIENT
  386. #undef CLIENT_CIPHER_LIST
  387. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  388. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  389. #endif
  390. /** DOCDOC */
  391. static void
  392. tor_tls_context_decref(tor_tls_context_t *ctx)
  393. {
  394. tor_assert(ctx);
  395. if (--ctx->refcnt == 0) {
  396. SSL_CTX_free(ctx->ctx);
  397. X509_free(ctx->my_cert);
  398. X509_free(ctx->my_id_cert);
  399. crypto_free_pk_env(ctx->key);
  400. tor_free(ctx);
  401. }
  402. }
  403. /** DOCDOC */
  404. static void
  405. tor_tls_context_incref(tor_tls_context_t *ctx)
  406. {
  407. ++ctx->refcnt;
  408. }
  409. /** Create a new TLS context for use with Tor TLS handshakes.
  410. * <b>identity</b> should be set to the identity key used to sign the
  411. * certificate, and <b>nickname</b> set to the nickname to use.
  412. *
  413. * You can call this function multiple times. Each time you call it,
  414. * it generates new certificates; all new connections will use
  415. * the new SSL context.
  416. */
  417. int
  418. tor_tls_context_new(crypto_pk_env_t *identity, const char *nickname,
  419. unsigned int key_lifetime)
  420. {
  421. crypto_pk_env_t *rsa = NULL;
  422. crypto_dh_env_t *dh = NULL;
  423. EVP_PKEY *pkey = NULL;
  424. tor_tls_context_t *result = NULL;
  425. X509 *cert = NULL, *idcert = NULL;
  426. char nn2[128];
  427. if (!nickname)
  428. nickname = "null";
  429. tor_snprintf(nn2, sizeof(nn2), "%s <signing>", nickname);
  430. tor_tls_init();
  431. /* Generate short-term RSA key. */
  432. if (!(rsa = crypto_new_pk_env()))
  433. goto error;
  434. if (crypto_pk_generate_key(rsa)<0)
  435. goto error;
  436. /* Create certificate signed by identity key. */
  437. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  438. key_lifetime);
  439. /* Create self-signed certificate for identity key. */
  440. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  441. IDENTITY_CERT_LIFETIME);
  442. if (!cert || !idcert) {
  443. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  444. goto error;
  445. }
  446. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  447. result->refcnt = 1;
  448. result->my_cert = X509_dup(cert);
  449. result->my_id_cert = X509_dup(idcert);
  450. result->key = crypto_pk_dup_key(rsa);
  451. #ifdef EVERYONE_HAS_AES
  452. /* Tell OpenSSL to only use TLS1 */
  453. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  454. goto error;
  455. #else
  456. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  457. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  458. goto error;
  459. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  460. #endif
  461. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  462. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  463. goto error;
  464. X509_free(cert); /* We just added a reference to cert. */
  465. cert=NULL;
  466. #if 0
  467. if (idcert && !SSL_CTX_add_extra_chain_cert(result->ctx,idcert))
  468. goto error;
  469. #else
  470. if (idcert) {
  471. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  472. tor_assert(s);
  473. X509_STORE_add_cert(s, idcert);
  474. }
  475. #endif
  476. idcert=NULL; /* The context now owns the reference to idcert */
  477. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  478. tor_assert(rsa);
  479. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  480. goto error;
  481. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  482. goto error;
  483. EVP_PKEY_free(pkey);
  484. pkey = NULL;
  485. if (!SSL_CTX_check_private_key(result->ctx))
  486. goto error;
  487. dh = crypto_dh_new();
  488. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  489. crypto_dh_free(dh);
  490. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  491. always_accept_verify_cb);
  492. /* let us realloc bufs that we're writing from */
  493. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  494. /* Free the old context if one exists. */
  495. if (global_tls_context) {
  496. /* This is safe even if there are open connections: OpenSSL does
  497. * reference counting with SSL and SSL_CTX objects. */
  498. tor_tls_context_decref(global_tls_context);
  499. }
  500. global_tls_context = result;
  501. if (rsa)
  502. crypto_free_pk_env(rsa);
  503. return 0;
  504. error:
  505. tls_log_errors(LOG_WARN, "creating TLS context");
  506. if (pkey)
  507. EVP_PKEY_free(pkey);
  508. if (rsa)
  509. crypto_free_pk_env(rsa);
  510. if (dh)
  511. crypto_dh_free(dh);
  512. if (result)
  513. tor_tls_context_decref(result);
  514. if (cert)
  515. X509_free(cert);
  516. if (idcert)
  517. X509_free(idcert);
  518. return -1;
  519. }
  520. #ifdef V2_HANDSHAKE_SERVER
  521. /** DOCDOC */
  522. static int
  523. tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
  524. {
  525. int i;
  526. SSL_SESSION *session;
  527. /* If we reached this point, we just got a client hello. See if there is
  528. * a cipher list. */
  529. if (!(session = SSL_get_session(ssl))) {
  530. log_warn(LD_NET, "No session on TLS?");
  531. return 0;
  532. }
  533. if (!session->ciphers) {
  534. log_warn(LD_NET, "No ciphers on session");
  535. return 0;
  536. }
  537. /* Now we need to see if there are any ciphers whose presence means we're
  538. * dealing with an updated Tor. */
  539. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  540. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  541. const char *ciphername = SSL_CIPHER_get_name(cipher);
  542. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  543. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  544. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  545. strcmp(ciphername, "(NONE)")) {
  546. /* XXXX should be ld_debug */
  547. log_info(LD_NET, "Got a non-version-1 cipher called '%s'",ciphername);
  548. // return 1;
  549. goto dump_list;
  550. }
  551. }
  552. return 0;
  553. dump_list:
  554. {
  555. smartlist_t *elts = smartlist_create();
  556. char *s;
  557. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  558. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  559. const char *ciphername = SSL_CIPHER_get_name(cipher);
  560. smartlist_add(elts, (char*)ciphername);
  561. }
  562. s = smartlist_join_strings(elts, ":", 0, NULL);
  563. log_info(LD_NET, "Got a non-version-1 cipher list. It is: '%s'", s);
  564. tor_free(s);
  565. smartlist_free(elts);
  566. }
  567. return 1;
  568. }
  569. /** DOCDOC */
  570. static void
  571. tor_tls_server_info_callback(const SSL *ssl, int type, int val)
  572. {
  573. (void) val;
  574. if (type != SSL_CB_ACCEPT_LOOP)
  575. return;
  576. if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
  577. return;
  578. if (tor_tls_client_is_using_v2_ciphers(ssl)) {
  579. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  580. * Let's hope openssl doesn't notice! */
  581. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  582. SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
  583. /* Don't send a hello request. */
  584. SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
  585. }
  586. }
  587. #endif
  588. /** Create a new TLS object from a file descriptor, and a flag to
  589. * determine whether it is functioning as a server.
  590. */
  591. tor_tls_t *
  592. tor_tls_new(int sock, int isServer)
  593. {
  594. BIO *bio = NULL;
  595. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  596. tor_assert(global_tls_context); /* make sure somebody made it first */
  597. if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
  598. tls_log_errors(LOG_WARN, "generating TLS context");
  599. tor_free(result);
  600. return NULL;
  601. }
  602. if (!SSL_set_cipher_list(result->ssl,
  603. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  604. SSL_free(result->ssl);
  605. tor_free(result);
  606. return NULL;
  607. }
  608. result->socket = sock;
  609. #ifdef USE_BSOCKETS
  610. bio = BIO_new_bsocket(sock, BIO_NOCLOSE);
  611. #else
  612. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  613. #endif
  614. if (! bio) {
  615. tls_log_errors(LOG_WARN, "opening BIO");
  616. SSL_free(result->ssl);
  617. tor_free(result);
  618. return NULL;
  619. }
  620. SSL_set_bio(result->ssl, bio, bio);
  621. tor_tls_context_incref(global_tls_context);
  622. result->context = global_tls_context;
  623. result->state = TOR_TLS_ST_HANDSHAKE;
  624. result->isServer = isServer;
  625. result->wantwrite_n = 0;
  626. #ifdef V2_HANDSHAKE_SERVER
  627. if (isServer) {
  628. SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
  629. }
  630. #endif
  631. /* Not expected to get called. */
  632. tls_log_errors(LOG_WARN, "generating TLS context");
  633. return result;
  634. }
  635. /**DOCDOC*/
  636. void
  637. tor_tls_set_renegotiate_callback(tor_tls_t *tls,
  638. void (*cb)(tor_tls_t *, void *arg),
  639. void *arg)
  640. {
  641. tls->negotiated_callback = cb;
  642. tls->callback_arg = arg;
  643. }
  644. /** Return whether this tls initiated the connect (client) or
  645. * received it (server). */
  646. int
  647. tor_tls_is_server(tor_tls_t *tls)
  648. {
  649. tor_assert(tls);
  650. return tls->isServer;
  651. }
  652. /** Release resources associated with a TLS object. Does not close the
  653. * underlying file descriptor.
  654. */
  655. void
  656. tor_tls_free(tor_tls_t *tls)
  657. {
  658. tor_assert(tls && tls->ssl);
  659. SSL_free(tls->ssl);
  660. tls->ssl = NULL;
  661. tls->negotiated_callback = NULL;
  662. if (tls->context)
  663. tor_tls_context_decref(tls->context);
  664. tor_free(tls);
  665. }
  666. /** Underlying function for TLS reading. Reads up to <b>len</b>
  667. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  668. * number of characters read. On failure, returns TOR_TLS_ERROR,
  669. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  670. */
  671. int
  672. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  673. {
  674. int r, err;
  675. tor_assert(tls);
  676. tor_assert(tls->ssl);
  677. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  678. r = SSL_read(tls->ssl, cp, len);
  679. if (r > 0) {
  680. #ifdef V2_HANDSHAKE_SERVER
  681. if (!tls->hadCert && tls->ssl->session && tls->ssl->session->peer) {
  682. tls->hadCert = 1;
  683. /* New certificate! */
  684. log_info(LD_NET, "Got a TLS renegotiation.");
  685. if (tls->negotiated_callback)
  686. tls->negotiated_callback(tls, tls->callback_arg);
  687. }
  688. #endif
  689. return r;
  690. }
  691. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
  692. if (err == _TOR_TLS_ZERORETURN) {
  693. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  694. tls->state = TOR_TLS_ST_CLOSED;
  695. return TOR_TLS_CLOSE;
  696. } else {
  697. tor_assert(err != TOR_TLS_DONE);
  698. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  699. return err;
  700. }
  701. }
  702. /** Underlying function for TLS writing. Write up to <b>n</b>
  703. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  704. * number of characters written. On failure, returns TOR_TLS_ERROR,
  705. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  706. */
  707. int
  708. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  709. {
  710. int r, err;
  711. tor_assert(tls);
  712. tor_assert(tls->ssl);
  713. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  714. if (n == 0)
  715. return 0;
  716. if (tls->wantwrite_n) {
  717. /* if WANTWRITE last time, we must use the _same_ n as before */
  718. tor_assert(n >= tls->wantwrite_n);
  719. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  720. (int)n, (int)tls->wantwrite_n);
  721. n = tls->wantwrite_n;
  722. tls->wantwrite_n = 0;
  723. }
  724. r = SSL_write(tls->ssl, cp, n);
  725. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  726. if (err == TOR_TLS_DONE) {
  727. return r;
  728. }
  729. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  730. tls->wantwrite_n = n;
  731. }
  732. return err;
  733. }
  734. /** Perform initial handshake on <b>tls</b>. When finished, returns
  735. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  736. * or TOR_TLS_WANTWRITE.
  737. */
  738. int
  739. tor_tls_handshake(tor_tls_t *tls)
  740. {
  741. int r;
  742. tor_assert(tls);
  743. tor_assert(tls->ssl);
  744. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  745. check_no_tls_errors();
  746. if (tls->isServer) {
  747. r = SSL_accept(tls->ssl);
  748. } else {
  749. r = SSL_connect(tls->ssl);
  750. }
  751. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  752. if (ERR_peek_error() != 0) {
  753. tls_log_errors(tls->isServer ? LOG_INFO : LOG_WARN,
  754. "handshaking");
  755. return TOR_TLS_ERROR_MISC;
  756. }
  757. if (r == TOR_TLS_DONE) {
  758. tls->state = TOR_TLS_ST_OPEN;
  759. tls->hadCert = tor_tls_peer_has_cert(tls) ? 1 : 0;
  760. if (tls->isServer) {
  761. SSL_set_info_callback(tls->ssl, NULL);
  762. SSL_set_verify(tls->ssl, SSL_VERIFY_NONE, always_accept_verify_cb);
  763. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  764. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  765. #ifdef V2_HANDSHAKE_SERVER
  766. if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
  767. /* This check is redundant, but back when we did it in the callback,
  768. * we didn't have access to the tor_tls_t struct. We could make some
  769. * kind of static map linking SSLs to tor_tls_ts, but that way lies
  770. * sadness. */
  771. tls->wasV2Handshake = 1;
  772. } else {
  773. tls->wasV2Handshake = 0;
  774. }
  775. #endif
  776. } else {
  777. #ifdef V2_HANDSHAKE_CLIENT
  778. /* If we got no ID cert, we're a v2 handshake. */
  779. X509 *cert = SSL_get_peer_certificate(tls->ssl);/*XXXX020 refcnt?*/
  780. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  781. int n_certs = sk_X509_num(chain);
  782. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
  783. tls->wasV2Handshake = 0;
  784. else
  785. tls->wasV2Handshake = 1;
  786. #endif
  787. SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST);
  788. }
  789. }
  790. return r;
  791. }
  792. /** Client only: Renegotiate a TLS session. When finished, returns
  793. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  794. * TOR_TLS_WANTWRITE.
  795. */
  796. int
  797. tor_tls_renegotiate(tor_tls_t *tls)
  798. {
  799. int r;
  800. tor_assert(tls);
  801. /* We could do server-initiated renegotiation too, but that would be tricky.
  802. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  803. tor_assert(!tls->isServer);
  804. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  805. int r = SSL_renegotiate(tls->ssl);
  806. if (r <= 0) {
  807. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  808. "renegotiating", LOG_WARN);
  809. }
  810. tls->state = TOR_TLS_ST_RENEGOTIATE;
  811. }
  812. r = SSL_do_handshake(tls->ssl);
  813. if (r == 1) {
  814. tls->state = TOR_TLS_ST_OPEN;
  815. return TOR_TLS_DONE;
  816. } else
  817. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  818. "renegotiating handshake", LOG_WARN);
  819. }
  820. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  821. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  822. * or TOR_TLS_WANTWRITE.
  823. */
  824. int
  825. tor_tls_shutdown(tor_tls_t *tls)
  826. {
  827. int r, err;
  828. char buf[128];
  829. tor_assert(tls);
  830. tor_assert(tls->ssl);
  831. while (1) {
  832. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  833. /* If we've already called shutdown once to send a close message,
  834. * we read until the other side has closed too.
  835. */
  836. do {
  837. r = SSL_read(tls->ssl, buf, 128);
  838. } while (r>0);
  839. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  840. LOG_INFO);
  841. if (err == _TOR_TLS_ZERORETURN) {
  842. tls->state = TOR_TLS_ST_GOTCLOSE;
  843. /* fall through... */
  844. } else {
  845. return err;
  846. }
  847. }
  848. r = SSL_shutdown(tls->ssl);
  849. if (r == 1) {
  850. /* If shutdown returns 1, the connection is entirely closed. */
  851. tls->state = TOR_TLS_ST_CLOSED;
  852. return TOR_TLS_DONE;
  853. }
  854. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  855. LOG_INFO);
  856. if (err == _TOR_TLS_SYSCALL) {
  857. /* The underlying TCP connection closed while we were shutting down. */
  858. tls->state = TOR_TLS_ST_CLOSED;
  859. return TOR_TLS_DONE;
  860. } else if (err == _TOR_TLS_ZERORETURN) {
  861. /* The TLS connection says that it sent a shutdown record, but
  862. * isn't done shutting down yet. Make sure that this hasn't
  863. * happened before, then go back to the start of the function
  864. * and try to read.
  865. */
  866. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  867. tls->state == TOR_TLS_ST_SENTCLOSE) {
  868. log(LOG_WARN, LD_NET,
  869. "TLS returned \"half-closed\" value while already half-closed");
  870. return TOR_TLS_ERROR_MISC;
  871. }
  872. tls->state = TOR_TLS_ST_SENTCLOSE;
  873. /* fall through ... */
  874. } else {
  875. return err;
  876. }
  877. } /* end loop */
  878. }
  879. /** Return true iff this TLS connection is authenticated.
  880. */
  881. int
  882. tor_tls_peer_has_cert(tor_tls_t *tls)
  883. {
  884. X509 *cert;
  885. cert = SSL_get_peer_certificate(tls->ssl);
  886. tls_log_errors(LOG_WARN, "getting peer certificate");
  887. if (!cert)
  888. return 0;
  889. X509_free(cert);
  890. return 1;
  891. }
  892. /** DOCDOC */
  893. int
  894. tor_tls_get_cert_digests(tor_tls_t *tls,
  895. char *my_digest_out,
  896. char *peer_digest_out)
  897. {
  898. X509 *cert;
  899. unsigned int len;
  900. tor_assert(tls && tls->context);
  901. cert = tls->context->my_cert;
  902. if (cert) {
  903. X509_digest(cert, EVP_sha1(), (unsigned char*)my_digest_out, &len);
  904. if (len != DIGEST_LEN)
  905. return -1;
  906. }
  907. cert = SSL_get_peer_certificate(tls->ssl);
  908. if (cert) {
  909. X509_digest(cert, EVP_sha1(), (unsigned char*)peer_digest_out, &len);
  910. if (len != DIGEST_LEN)
  911. return -1;
  912. }
  913. return 0;
  914. }
  915. /** DOCDOC */
  916. crypto_pk_env_t *
  917. tor_tls_dup_private_key(tor_tls_t *tls)
  918. {
  919. return crypto_pk_dup_key(tls->context->key);
  920. }
  921. /** DOCDOC */
  922. char *
  923. tor_tls_encode_my_certificate(tor_tls_t *tls, size_t *size_out,
  924. int conn_cert)
  925. {
  926. unsigned char *result, *cp;
  927. int certlen;
  928. X509 *cert;
  929. tor_assert(tls && tls->context);
  930. cert = conn_cert ? tls->context->my_cert : tls->context->my_id_cert;
  931. tor_assert(cert);
  932. certlen = i2d_X509(cert, NULL);
  933. tor_assert(certlen >= 0);
  934. cp = result = tor_malloc(certlen);
  935. i2d_X509(cert, &cp);
  936. tor_assert(cp-result == certlen);
  937. *size_out = (size_t)certlen;
  938. return (char*) result;
  939. }
  940. /** Warn that a certificate lifetime extends through a certain range. */
  941. static void
  942. log_cert_lifetime(X509 *cert, const char *problem)
  943. {
  944. BIO *bio = NULL;
  945. BUF_MEM *buf;
  946. char *s1=NULL, *s2=NULL;
  947. char mytime[33];
  948. time_t now = time(NULL);
  949. struct tm tm;
  950. if (problem)
  951. log_warn(LD_GENERAL,
  952. "Certificate %s: is your system clock set incorrectly?",
  953. problem);
  954. if (!(bio = BIO_new(BIO_s_mem()))) {
  955. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  956. }
  957. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  958. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  959. goto end;
  960. }
  961. BIO_get_mem_ptr(bio, &buf);
  962. s1 = tor_strndup(buf->data, buf->length);
  963. (void)BIO_reset(bio);
  964. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  965. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  966. goto end;
  967. }
  968. BIO_get_mem_ptr(bio, &buf);
  969. s2 = tor_strndup(buf->data, buf->length);
  970. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  971. log_warn(LD_GENERAL,
  972. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  973. s1,s2,mytime);
  974. end:
  975. /* Not expected to get invoked */
  976. tls_log_errors(LOG_WARN, "getting certificate lifetime");
  977. if (bio)
  978. BIO_free(bio);
  979. if (s1)
  980. tor_free(s1);
  981. if (s2)
  982. tor_free(s2);
  983. }
  984. /** DOCDOC helper.
  985. * cert_out needs to be freed. id_cert_out doesn't. */
  986. static void
  987. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  988. X509 **cert_out, X509 **id_cert_out)
  989. {
  990. X509 *cert = NULL, *id_cert = NULL;
  991. STACK_OF(X509) *chain = NULL;
  992. int num_in_chain, i;
  993. *cert_out = *id_cert_out = NULL;
  994. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  995. return;
  996. *cert_out = cert;
  997. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  998. return;
  999. num_in_chain = sk_X509_num(chain);
  1000. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1001. * 2 means we're connecting (client-side), and it's both the link
  1002. * cert and the id_cert.
  1003. */
  1004. if (num_in_chain < 1) {
  1005. log_fn(severity,LD_PROTOCOL,
  1006. "Unexpected number of certificates in chain (%d)",
  1007. num_in_chain);
  1008. return;
  1009. }
  1010. for (i=0; i<num_in_chain; ++i) {
  1011. id_cert = sk_X509_value(chain, i);
  1012. if (X509_cmp(id_cert, cert) != 0)
  1013. break;
  1014. }
  1015. *id_cert_out = id_cert;
  1016. }
  1017. /** If the provided tls connection is authenticated and has a
  1018. * certificate that is currently valid and signed, then set
  1019. * *<b>identity_key</b> to the identity certificate's key and return
  1020. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1021. */
  1022. int
  1023. tor_tls_verify_v1(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1024. {
  1025. X509 *cert = NULL, *id_cert = NULL;
  1026. EVP_PKEY *id_pkey = NULL;
  1027. RSA *rsa;
  1028. int r = -1;
  1029. *identity_key = NULL;
  1030. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1031. if (!cert)
  1032. goto done;
  1033. if (!id_cert) {
  1034. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1035. goto done;
  1036. }
  1037. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1038. X509_verify(cert, id_pkey) <= 0) {
  1039. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1040. tls_log_errors(severity,"verifying certificate");
  1041. goto done;
  1042. }
  1043. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1044. if (!rsa)
  1045. goto done;
  1046. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1047. r = 0;
  1048. done:
  1049. if (cert)
  1050. X509_free(cert);
  1051. if (id_pkey)
  1052. EVP_PKEY_free(id_pkey);
  1053. /* This should never get invoked, but let's make sure in case OpenSSL
  1054. * acts unexpectedly. */
  1055. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  1056. return r;
  1057. }
  1058. #if 0
  1059. /** DOCDOC
  1060. *
  1061. * Returns 1 on "verification is done", 0 on "still need LINK_AUTH."
  1062. */
  1063. int
  1064. tor_tls_verify_certs_v2(int severity, tor_tls_t *tls,
  1065. const char *cert_str, size_t cert_len,
  1066. const char *id_cert_str, size_t id_cert_len,
  1067. crypto_pk_env_t **cert_key_out,
  1068. char *conn_cert_digest_out,
  1069. crypto_pk_env_t **id_key_out,
  1070. char *id_digest_out)
  1071. {
  1072. X509 *cert = NULL, *id_cert = NULL;
  1073. EVP_PKEY *id_pkey = NULL, *cert_pkey = NULL;
  1074. int free_id_cert = 0, peer_used_tls_cert = 0;
  1075. int r = -1;
  1076. tor_assert(cert_key_out);
  1077. tor_assert(conn_cert_digest_out);
  1078. tor_assert(id_key_out);
  1079. tor_assert(id_digest_out);
  1080. *cert_key_out = NULL;
  1081. if (cert_str && cert_len) {
  1082. /*XXXX020 warn on error. */
  1083. const unsigned char *cp = (const unsigned char*) cert_str;
  1084. cert = d2i_X509(NULL, &cp, cert_len);
  1085. }
  1086. if (id_cert_str && id_cert_len) {
  1087. /*XXXX020 warn on error. */
  1088. const unsigned char *cp = (const unsigned char*) id_cert_str;
  1089. id_cert = d2i_X509(NULL, &cp, id_cert_len);
  1090. if (id_cert)
  1091. free_id_cert = 1;
  1092. }
  1093. if (cert) {
  1094. int cmp = 0;
  1095. X509 *cert_tmp = SSL_get_peer_certificate(tls->ssl);
  1096. if (cert_tmp) {
  1097. peer_used_tls_cert = 1;
  1098. cmp = X509_cmp(cert, cert_tmp);
  1099. X509_free(cert_tmp);
  1100. }
  1101. if (cmp != 0) {
  1102. log_fn(severity, LD_PROTOCOL,
  1103. "Certificate in CERT cell didn't match TLS cert.");
  1104. goto done;
  1105. }
  1106. }
  1107. if (!cert || !id_cert) {
  1108. X509 *c=NULL, *id=NULL;
  1109. try_to_extract_certs_from_tls(severity, tls, &c, &id);
  1110. if (c) {
  1111. if (!cert)
  1112. cert = c;
  1113. else
  1114. X509_free(c);
  1115. }
  1116. if (id && !id_cert)
  1117. id_cert = id;
  1118. }
  1119. if (!id_cert || !cert)
  1120. goto done;
  1121. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1122. X509_verify(cert, id_pkey) <= 0) {
  1123. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1124. tls_log_errors(severity,"verifying certificate");
  1125. goto done;
  1126. }
  1127. if (!(*id_key_out = _crypto_new_pk_env_evp_pkey(id_pkey)))
  1128. goto done;
  1129. crypto_pk_get_digest(*id_key_out, id_digest_out);
  1130. if (!(cert_pkey = X509_get_pubkey(cert)))
  1131. goto done;
  1132. if (!(*cert_key_out = _crypto_new_pk_env_evp_pkey(cert_pkey)))
  1133. goto done;
  1134. {
  1135. unsigned int len = 0;
  1136. X509_digest(cert, EVP_sha1(), (unsigned char*)conn_cert_digest_out, &len);
  1137. tor_assert(len == DIGEST_LEN);
  1138. }
  1139. r = peer_used_tls_cert ? 1 : 0;
  1140. done:
  1141. if (cert)
  1142. X509_free(cert);
  1143. if (id_cert && free_id_cert)
  1144. X509_free(id_cert);
  1145. if (id_pkey)
  1146. EVP_PKEY_free(id_pkey);
  1147. if (cert_pkey)
  1148. EVP_PKEY_free(cert_pkey);
  1149. return r;
  1150. }
  1151. #endif
  1152. /** Check whether the certificate set on the connection <b>tls</b> is
  1153. * expired or not-yet-valid, give or take <b>tolerance</b>
  1154. * seconds. Return 0 for valid, -1 for failure.
  1155. *
  1156. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1157. */
  1158. int
  1159. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  1160. {
  1161. time_t now, t;
  1162. X509 *cert;
  1163. int r = -1;
  1164. now = time(NULL);
  1165. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1166. goto done;
  1167. t = now + tolerance;
  1168. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1169. log_cert_lifetime(cert, "not yet valid");
  1170. goto done;
  1171. }
  1172. t = now - tolerance;
  1173. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1174. log_cert_lifetime(cert, "already expired");
  1175. goto done;
  1176. }
  1177. r = 0;
  1178. done:
  1179. if (cert)
  1180. X509_free(cert);
  1181. /* Not expected to get invoked */
  1182. tls_log_errors(LOG_WARN, "checking certificate lifetime");
  1183. return r;
  1184. }
  1185. /** Return the number of bytes available for reading from <b>tls</b>.
  1186. */
  1187. int
  1188. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1189. {
  1190. tor_assert(tls);
  1191. return SSL_pending(tls->ssl);
  1192. }
  1193. /** If <b>tls</b> requires that the next write be of a particular size,
  1194. * return that size. Otherwise, return 0. */
  1195. size_t
  1196. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1197. {
  1198. return tls->wantwrite_n;
  1199. }
  1200. /** Sets n_read and n_written to the number of bytes read and written,
  1201. * respectivey, on the raw socket used by <b>tls</b> since the last time this
  1202. * function was called on <b>tls</b>. */
  1203. void
  1204. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1205. {
  1206. unsigned long r, w;
  1207. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1208. w = BIO_number_written(SSL_get_wbio(tls->ssl));
  1209. /* We are ok with letting these unsigned ints go "negative" here:
  1210. * If we wrapped around, this should still give us the right answer, unless
  1211. * we wrapped around by more than ULONG_MAX since the last time we called
  1212. * this function.
  1213. */
  1214. *n_read = (size_t)(r - tls->last_read_count);
  1215. *n_written = (size_t)(w - tls->last_write_count);
  1216. tls->last_read_count = r;
  1217. tls->last_write_count = w;
  1218. }
  1219. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1220. * errors, log an error message. */
  1221. void
  1222. _check_no_tls_errors(const char *fname, int line)
  1223. {
  1224. if (ERR_peek_error() == 0)
  1225. return;
  1226. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1227. tor_fix_source_file(fname), line);
  1228. tls_log_errors(LOG_WARN, NULL);
  1229. }
  1230. /**DOCDOC */
  1231. int
  1232. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1233. {
  1234. if (tls->isServer) {
  1235. #ifdef V2_HANDSHAKE_SERVER
  1236. return ! tls->wasV2Handshake;
  1237. #endif
  1238. } else {
  1239. #ifdef V2_HANDSHAKE_CLIENT
  1240. return ! tls->wasV2Handshake;
  1241. #endif
  1242. }
  1243. return 1;
  1244. }
  1245. #if SSL3_RANDOM_SIZE != TOR_TLS_RANDOM_LEN
  1246. #error "The TOR_TLS_RANDOM_LEN macro is defined incorrectly. That's a bug."
  1247. #endif
  1248. /** DOCDOC */
  1249. int
  1250. tor_tls_get_random_values(tor_tls_t *tls, char *client_random_out,
  1251. char *server_random_out)
  1252. {
  1253. tor_assert(tls && tls->ssl);
  1254. if (!tls->ssl->s3)
  1255. return -1;
  1256. memcpy(client_random_out, tls->ssl->s3->client_random, SSL3_RANDOM_SIZE);
  1257. memcpy(server_random_out, tls->ssl->s3->server_random, SSL3_RANDOM_SIZE);
  1258. return 0;
  1259. }
  1260. /** DOCDOC */
  1261. int
  1262. tor_tls_hmac_with_master_secret(tor_tls_t *tls, char *hmac_out,
  1263. const char *data, size_t data_len)
  1264. {
  1265. SSL_SESSION *s;
  1266. tor_assert(tls && tls->ssl);
  1267. if (!(s = SSL_get_session(tls->ssl)))
  1268. return -1;
  1269. if (s->master_key_length < 0)
  1270. return -1;
  1271. crypto_hmac_sha1(hmac_out,
  1272. (const char*)s->master_key,
  1273. (size_t)s->master_key_length,
  1274. data, data_len);
  1275. return 0;
  1276. }