tortls.c 40 KB

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