tortls.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779
  1. /* Copyright (c) 2003, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file tortls.c
  7. * \brief Wrapper functions to present a consistent interface to
  8. * TLS, SSL, and X.509 functions from OpenSSL.
  9. **/
  10. /* (Unlike other tor functions, these
  11. * are prefixed with tor_ in order to avoid conflicting with OpenSSL
  12. * functions and variables.)
  13. */
  14. #include "orconfig.h"
  15. #if defined (WINCE)
  16. #include <WinSock2.h>
  17. #endif
  18. #include <assert.h>
  19. #ifdef MS_WINDOWS /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
  20. #define WIN32_WINNT 0x400
  21. #define _WIN32_WINNT 0x400
  22. #define WIN32_LEAN_AND_MEAN
  23. #if defined(_MSC_VER) && (_MSC_VER < 1300)
  24. #include <winsock.h>
  25. #else
  26. #include <winsock2.h>
  27. #include <ws2tcpip.h>
  28. #endif
  29. #endif
  30. #include <openssl/ssl.h>
  31. #include <openssl/ssl3.h>
  32. #include <openssl/err.h>
  33. #include <openssl/tls1.h>
  34. #include <openssl/asn1.h>
  35. #include <openssl/bio.h>
  36. #include <openssl/opensslv.h>
  37. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  38. #error "We require OpenSSL >= 0.9.7"
  39. #endif
  40. #ifdef USE_BUFFEREVENTS
  41. #include <event2/bufferevent_ssl.h>
  42. #include <event2/buffer.h>
  43. #include "compat_libevent.h"
  44. #endif
  45. #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
  46. #define TORTLS_PRIVATE
  47. #include "crypto.h"
  48. #include "tortls.h"
  49. #include "util.h"
  50. #include "torlog.h"
  51. #include "container.h"
  52. #include "ht.h"
  53. #include <string.h>
  54. /* Enable the "v2" TLS handshake.
  55. */
  56. #define V2_HANDSHAKE_SERVER
  57. #define V2_HANDSHAKE_CLIENT
  58. /* Copied from or.h */
  59. #define LEGAL_NICKNAME_CHARACTERS \
  60. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  61. /** How long do identity certificates live? (sec) */
  62. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  63. #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
  64. /* We redefine these so that we can run correctly even if the vendor gives us
  65. * a version of OpenSSL that does not match its header files. (Apple: I am
  66. * looking at you.)
  67. */
  68. #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  69. #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
  70. #endif
  71. #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  72. #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
  73. #endif
  74. /** Does the run-time openssl version look like we need
  75. * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  76. static int use_unsafe_renegotiation_op = 0;
  77. /** Does the run-time openssl version look like we need
  78. * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  79. static int use_unsafe_renegotiation_flag = 0;
  80. /** Holds a SSL_CTX object and related state used to configure TLS
  81. * connections.
  82. */
  83. typedef struct tor_tls_context_t {
  84. int refcnt;
  85. SSL_CTX *ctx;
  86. X509 *my_cert;
  87. X509 *my_id_cert;
  88. crypto_pk_env_t *key;
  89. } tor_tls_context_t;
  90. /** Holds a SSL object and its associated data. Members are only
  91. * accessed from within tortls.c.
  92. */
  93. struct tor_tls_t {
  94. HT_ENTRY(tor_tls_t) node;
  95. tor_tls_context_t *context; /** A link to the context object for this tls. */
  96. SSL *ssl; /**< An OpenSSL SSL object. */
  97. int socket; /**< The underlying file descriptor for this TLS connection. */
  98. char *address; /**< An address to log when describing this connection. */
  99. enum {
  100. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  101. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
  102. TOR_TLS_ST_BUFFEREVENT
  103. } state : 3; /**< The current SSL state, depending on which operations have
  104. * completed successfully. */
  105. unsigned int isServer:1; /**< True iff this is a server-side connection */
  106. unsigned int wasV2Handshake:1; /**< True iff the original handshake for
  107. * this connection used the updated version
  108. * of the connection protocol (client sends
  109. * different cipher list, server sends only
  110. * one certificate). */
  111. /** True iff we should call negotiated_callback when we're done reading. */
  112. unsigned int got_renegotiate:1;
  113. /** Incremented every time we start the server side of a handshake. */
  114. uint8_t server_handshake_count;
  115. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
  116. * time. */
  117. /** Last values retrieved from BIO_number_read()/write(); see
  118. * tor_tls_get_n_raw_bytes() for usage.
  119. */
  120. unsigned long last_write_count;
  121. unsigned long last_read_count;
  122. /** If set, a callback to invoke whenever the client tries to renegotiate
  123. * the handshake. */
  124. void (*negotiated_callback)(tor_tls_t *tls, void *arg);
  125. /** Argument to pass to negotiated_callback. */
  126. void *callback_arg;
  127. };
  128. #ifdef V2_HANDSHAKE_CLIENT
  129. /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
  130. * in client mode into advertising the ciphers we want. See
  131. * rectify_client_ciphers() for details. */
  132. static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
  133. /** A stack of SSL_CIPHER objects, some real, some fake.
  134. * See rectify_client_ciphers() for details. */
  135. static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
  136. #endif
  137. /** Helper: compare tor_tls_t objects by its SSL. */
  138. static INLINE int
  139. tor_tls_entries_eq(const tor_tls_t *a, const tor_tls_t *b)
  140. {
  141. return a->ssl == b->ssl;
  142. }
  143. /** Helper: return a hash value for a tor_tls_t by its SSL. */
  144. static INLINE unsigned int
  145. tor_tls_entry_hash(const tor_tls_t *a)
  146. {
  147. #if SIZEOF_INT == SIZEOF_VOID_P
  148. return ((unsigned int)(uintptr_t)a->ssl);
  149. #else
  150. return (unsigned int) ((((uint64_t)a->ssl)>>2) & UINT_MAX);
  151. #endif
  152. }
  153. /** Map from SSL* pointers to tor_tls_t objects using those pointers.
  154. */
  155. static HT_HEAD(tlsmap, tor_tls_t) tlsmap_root = HT_INITIALIZER();
  156. HT_PROTOTYPE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
  157. tor_tls_entries_eq)
  158. HT_GENERATE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
  159. tor_tls_entries_eq, 0.6, malloc, realloc, free)
  160. /** Helper: given a SSL* pointer, return the tor_tls_t object using that
  161. * pointer. */
  162. static INLINE tor_tls_t *
  163. tor_tls_get_by_ssl(const SSL *ssl)
  164. {
  165. tor_tls_t search, *result;
  166. memset(&search, 0, sizeof(search));
  167. search.ssl = (SSL*)ssl;
  168. result = HT_FIND(tlsmap, &tlsmap_root, &search);
  169. return result;
  170. }
  171. static void tor_tls_context_decref(tor_tls_context_t *ctx);
  172. static void tor_tls_context_incref(tor_tls_context_t *ctx);
  173. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  174. crypto_pk_env_t *rsa_sign,
  175. const char *cname,
  176. const char *cname_sign,
  177. unsigned int lifetime);
  178. /** Global tls context. We keep it here because nobody else needs to
  179. * touch it. */
  180. static tor_tls_context_t *global_tls_context = NULL;
  181. /** True iff tor_tls_init() has been called. */
  182. static int tls_library_is_initialized = 0;
  183. /* Module-internal error codes. */
  184. #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
  185. #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
  186. #include "tortls_states.h"
  187. /** Return the symbolic name of an OpenSSL state. */
  188. static const char *
  189. ssl_state_to_string(int ssl_state)
  190. {
  191. static char buf[40];
  192. int i;
  193. for (i = 0; state_map[i].name; ++i) {
  194. if (state_map[i].state == ssl_state)
  195. return state_map[i].name;
  196. }
  197. tor_snprintf(buf, sizeof(buf), "Unknown state %d", ssl_state);
  198. return buf;
  199. }
  200. void
  201. tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
  202. int severity, int domain, const char *doing)
  203. {
  204. const char *state = NULL, *addr;
  205. const char *msg, *lib, *func;
  206. int st;
  207. st = (tls && tls->ssl) ? tls->ssl->state : -1;
  208. state = (st>=0)?ssl_state_to_string(st):"---";
  209. addr = tls ? tls->address : NULL;
  210. msg = (const char*)ERR_reason_error_string(err);
  211. lib = (const char*)ERR_lib_error_string(err);
  212. func = (const char*)ERR_func_error_string(err);
  213. if (!msg) msg = "(null)";
  214. if (!lib) lib = "(null)";
  215. if (!func) func = "(null)";
  216. if (doing) {
  217. log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
  218. doing, addr?" with ":"", addr?addr:"",
  219. msg, lib, func, state);
  220. } else {
  221. log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
  222. addr?" with ":"", addr?addr:"",
  223. msg, lib, func, state);
  224. }
  225. }
  226. /** Log all pending tls errors at level <b>severity</b>. Use
  227. * <b>doing</b> to describe our current activities.
  228. */
  229. static void
  230. tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
  231. {
  232. unsigned long err;
  233. while ((err = ERR_get_error()) != 0) {
  234. tor_tls_log_one_error(tls, err, severity, domain, doing);
  235. }
  236. }
  237. /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
  238. * code. */
  239. static int
  240. tor_errno_to_tls_error(int e)
  241. {
  242. #if defined(MS_WINDOWS)
  243. switch (e) {
  244. case WSAECONNRESET: // most common
  245. return TOR_TLS_ERROR_CONNRESET;
  246. case WSAETIMEDOUT:
  247. return TOR_TLS_ERROR_TIMEOUT;
  248. case WSAENETUNREACH:
  249. case WSAEHOSTUNREACH:
  250. return TOR_TLS_ERROR_NO_ROUTE;
  251. case WSAECONNREFUSED:
  252. return TOR_TLS_ERROR_CONNREFUSED; // least common
  253. default:
  254. return TOR_TLS_ERROR_MISC;
  255. }
  256. #else
  257. switch (e) {
  258. case ECONNRESET: // most common
  259. return TOR_TLS_ERROR_CONNRESET;
  260. case ETIMEDOUT:
  261. return TOR_TLS_ERROR_TIMEOUT;
  262. case EHOSTUNREACH:
  263. case ENETUNREACH:
  264. return TOR_TLS_ERROR_NO_ROUTE;
  265. case ECONNREFUSED:
  266. return TOR_TLS_ERROR_CONNREFUSED; // least common
  267. default:
  268. return TOR_TLS_ERROR_MISC;
  269. }
  270. #endif
  271. }
  272. /** Given a TOR_TLS_* error code, return a string equivalent. */
  273. const char *
  274. tor_tls_err_to_string(int err)
  275. {
  276. if (err >= 0)
  277. return "[Not an error.]";
  278. switch (err) {
  279. case TOR_TLS_ERROR_MISC: return "misc error";
  280. case TOR_TLS_ERROR_IO: return "unexpected close";
  281. case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
  282. case TOR_TLS_ERROR_CONNRESET: return "connection reset";
  283. case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
  284. case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
  285. case TOR_TLS_CLOSE: return "closed";
  286. case TOR_TLS_WANTREAD: return "want to read";
  287. case TOR_TLS_WANTWRITE: return "want to write";
  288. default: return "(unknown error code)";
  289. }
  290. }
  291. #define CATCH_SYSCALL 1
  292. #define CATCH_ZERO 2
  293. /** Given a TLS object and the result of an SSL_* call, use
  294. * SSL_get_error to determine whether an error has occurred, and if so
  295. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  296. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  297. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  298. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  299. *
  300. * If an error has occurred, log it at level <b>severity</b> and describe the
  301. * current action as <b>doing</b>.
  302. */
  303. static int
  304. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  305. const char *doing, int severity, int domain)
  306. {
  307. int err = SSL_get_error(tls->ssl, r);
  308. int tor_error = TOR_TLS_ERROR_MISC;
  309. switch (err) {
  310. case SSL_ERROR_NONE:
  311. return TOR_TLS_DONE;
  312. case SSL_ERROR_WANT_READ:
  313. return TOR_TLS_WANTREAD;
  314. case SSL_ERROR_WANT_WRITE:
  315. return TOR_TLS_WANTWRITE;
  316. case SSL_ERROR_SYSCALL:
  317. if (extra&CATCH_SYSCALL)
  318. return _TOR_TLS_SYSCALL;
  319. if (r == 0) {
  320. log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
  321. doing, ssl_state_to_string(tls->ssl->state));
  322. tor_error = TOR_TLS_ERROR_IO;
  323. } else {
  324. int e = tor_socket_errno(tls->socket);
  325. log(severity, LD_NET,
  326. "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
  327. doing, e, tor_socket_strerror(e),
  328. ssl_state_to_string(tls->ssl->state));
  329. tor_error = tor_errno_to_tls_error(e);
  330. }
  331. tls_log_errors(tls, severity, domain, doing);
  332. return tor_error;
  333. case SSL_ERROR_ZERO_RETURN:
  334. if (extra&CATCH_ZERO)
  335. return _TOR_TLS_ZERORETURN;
  336. log(severity, LD_NET, "TLS connection closed while %s in state %s",
  337. doing, ssl_state_to_string(tls->ssl->state));
  338. tls_log_errors(tls, severity, domain, doing);
  339. return TOR_TLS_CLOSE;
  340. default:
  341. tls_log_errors(tls, severity, domain, doing);
  342. return TOR_TLS_ERROR_MISC;
  343. }
  344. }
  345. /** Initialize OpenSSL, unless it has already been initialized.
  346. */
  347. static void
  348. tor_tls_init(void)
  349. {
  350. if (!tls_library_is_initialized) {
  351. long version;
  352. SSL_library_init();
  353. SSL_load_error_strings();
  354. version = SSLeay();
  355. /* OpenSSL 0.9.8l introduced SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  356. * here, but without thinking too hard about it: it turns out that the
  357. * flag in question needed to be set at the last minute, and that it
  358. * conflicted with an existing flag number that had already been added
  359. * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
  360. * the flag with an option and (it seems) broke anything that used
  361. * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
  362. * and we mustn't use the SSL3_FLAGS option with anything besides
  363. * OpenSSL 0.9.8l.
  364. *
  365. * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
  366. * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
  367. * set option 0x00040000L everywhere.
  368. *
  369. * No, we can't simply detect whether the flag or the option is present
  370. * in the headers at build-time: some vendors (notably Apple) like to
  371. * leave their headers out of sync with their libraries.
  372. *
  373. * Yes, it _is_ almost as if the OpenSSL developers decided that no
  374. * program should be allowed to use renegotiation unless it first passed
  375. * a test of intelligence and determination.
  376. */
  377. if (version >= 0x009080c0L && version < 0x009080d0L) {
  378. log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l; "
  379. "I will try SSL3_FLAGS to enable renegotation.",
  380. SSLeay_version(SSLEAY_VERSION));
  381. use_unsafe_renegotiation_flag = 1;
  382. use_unsafe_renegotiation_op = 1;
  383. } else if (version >= 0x009080d0L) {
  384. log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
  385. "I will try SSL_OP to enable renegotiation",
  386. SSLeay_version(SSLEAY_VERSION));
  387. use_unsafe_renegotiation_op = 1;
  388. } else if (version < 0x009080c0L) {
  389. log_notice(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
  390. "0.9.8l, but some vendors have backported 0.9.8l's "
  391. "renegotiation code to earlier versions, and some have "
  392. "backported the code from 0.9.8m or 0.9.8n. I'll set both "
  393. "SSL3_FLAGS and SSL_OP just to be safe.",
  394. SSLeay_version(SSLEAY_VERSION), version);
  395. use_unsafe_renegotiation_flag = 1;
  396. use_unsafe_renegotiation_op = 1;
  397. } else {
  398. log_info(LD_GENERAL, "OpenSSL %s has version %lx",
  399. SSLeay_version(SSLEAY_VERSION), version);
  400. }
  401. tls_library_is_initialized = 1;
  402. }
  403. }
  404. /** Free all global TLS structures. */
  405. void
  406. tor_tls_free_all(void)
  407. {
  408. if (global_tls_context) {
  409. tor_tls_context_decref(global_tls_context);
  410. global_tls_context = NULL;
  411. }
  412. if (!HT_EMPTY(&tlsmap_root)) {
  413. log_warn(LD_MM, "Still have entries in the tlsmap at shutdown.");
  414. }
  415. HT_CLEAR(tlsmap, &tlsmap_root);
  416. #ifdef V2_HANDSHAKE_CLIENT
  417. if (CLIENT_CIPHER_DUMMIES)
  418. tor_free(CLIENT_CIPHER_DUMMIES);
  419. if (CLIENT_CIPHER_STACK)
  420. sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
  421. #endif
  422. }
  423. /** We need to give OpenSSL a callback to verify certificates. This is
  424. * it: We always accept peer certs and complete the handshake. We
  425. * don't validate them until later.
  426. */
  427. static int
  428. always_accept_verify_cb(int preverify_ok,
  429. X509_STORE_CTX *x509_ctx)
  430. {
  431. (void) preverify_ok;
  432. (void) x509_ctx;
  433. return 1;
  434. }
  435. /** Return a newly allocated X509 name with commonName <b>cname</b>. */
  436. static X509_NAME *
  437. tor_x509_name_new(const char *cname)
  438. {
  439. int nid;
  440. X509_NAME *name;
  441. if (!(name = X509_NAME_new()))
  442. return NULL;
  443. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  444. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  445. (unsigned char*)cname, -1, -1, 0)))
  446. goto error;
  447. return name;
  448. error:
  449. X509_NAME_free(name);
  450. return NULL;
  451. }
  452. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  453. * signed by the private key <b>rsa_sign</b>. The commonName of the
  454. * certificate will be <b>cname</b>; the commonName of the issuer will be
  455. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  456. * starting from now. Return a certificate on success, NULL on
  457. * failure.
  458. */
  459. static X509 *
  460. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  461. crypto_pk_env_t *rsa_sign,
  462. const char *cname,
  463. const char *cname_sign,
  464. unsigned int cert_lifetime)
  465. {
  466. time_t start_time, end_time;
  467. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  468. X509 *x509 = NULL;
  469. X509_NAME *name = NULL, *name_issuer=NULL;
  470. tor_tls_init();
  471. start_time = time(NULL);
  472. tor_assert(rsa);
  473. tor_assert(cname);
  474. tor_assert(rsa_sign);
  475. tor_assert(cname_sign);
  476. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  477. goto error;
  478. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  479. goto error;
  480. if (!(x509 = X509_new()))
  481. goto error;
  482. if (!(X509_set_version(x509, 2)))
  483. goto error;
  484. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  485. goto error;
  486. if (!(name = tor_x509_name_new(cname)))
  487. goto error;
  488. if (!(X509_set_subject_name(x509, name)))
  489. goto error;
  490. if (!(name_issuer = tor_x509_name_new(cname_sign)))
  491. goto error;
  492. if (!(X509_set_issuer_name(x509, name_issuer)))
  493. goto error;
  494. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  495. goto error;
  496. end_time = start_time + cert_lifetime;
  497. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  498. goto error;
  499. if (!X509_set_pubkey(x509, pkey))
  500. goto error;
  501. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  502. goto error;
  503. goto done;
  504. error:
  505. if (x509) {
  506. X509_free(x509);
  507. x509 = NULL;
  508. }
  509. done:
  510. tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
  511. if (sign_pkey)
  512. EVP_PKEY_free(sign_pkey);
  513. if (pkey)
  514. EVP_PKEY_free(pkey);
  515. if (name)
  516. X509_NAME_free(name);
  517. if (name_issuer)
  518. X509_NAME_free(name_issuer);
  519. return x509;
  520. }
  521. /** List of ciphers that servers should select from.*/
  522. #define SERVER_CIPHER_LIST \
  523. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  524. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  525. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  526. /* Note: to set up your own private testing network with link crypto
  527. * disabled, set your Tors' cipher list to
  528. * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
  529. * with any of the "real" Tors, though. */
  530. #ifdef V2_HANDSHAKE_CLIENT
  531. #define CIPHER(id, name) name ":"
  532. #define XCIPHER(id, name)
  533. /** List of ciphers that clients should advertise, omitting items that
  534. * our OpenSSL doesn't know about. */
  535. static const char CLIENT_CIPHER_LIST[] =
  536. #include "./ciphers.inc"
  537. ;
  538. #undef CIPHER
  539. #undef XCIPHER
  540. /** Holds a cipher that we want to advertise, and its 2-byte ID. */
  541. typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
  542. /** A list of all the ciphers that clients should advertise, including items
  543. * that OpenSSL might not know about. */
  544. static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
  545. #define CIPHER(id, name) { id, name },
  546. #define XCIPHER(id, name) { id, #name },
  547. #include "./ciphers.inc"
  548. #undef CIPHER
  549. #undef XCIPHER
  550. };
  551. /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
  552. static const int N_CLIENT_CIPHERS =
  553. sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
  554. #endif
  555. #ifndef V2_HANDSHAKE_CLIENT
  556. #undef CLIENT_CIPHER_LIST
  557. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  558. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  559. #endif
  560. /** Remove a reference to <b>ctx</b>, and free it if it has no more
  561. * references. */
  562. static void
  563. tor_tls_context_decref(tor_tls_context_t *ctx)
  564. {
  565. tor_assert(ctx);
  566. if (--ctx->refcnt == 0) {
  567. SSL_CTX_free(ctx->ctx);
  568. X509_free(ctx->my_cert);
  569. X509_free(ctx->my_id_cert);
  570. crypto_free_pk_env(ctx->key);
  571. tor_free(ctx);
  572. }
  573. }
  574. /** Increase the reference count of <b>ctx</b>. */
  575. static void
  576. tor_tls_context_incref(tor_tls_context_t *ctx)
  577. {
  578. ++ctx->refcnt;
  579. }
  580. /** Create a new TLS context for use with Tor TLS handshakes.
  581. * <b>identity</b> should be set to the identity key used to sign the
  582. * certificate.
  583. *
  584. * You can call this function multiple times. Each time you call it,
  585. * it generates new certificates; all new connections will use
  586. * the new SSL context.
  587. */
  588. int
  589. tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
  590. {
  591. crypto_pk_env_t *rsa = NULL;
  592. EVP_PKEY *pkey = NULL;
  593. tor_tls_context_t *result = NULL;
  594. X509 *cert = NULL, *idcert = NULL;
  595. char *nickname = NULL, *nn2 = NULL;
  596. tor_tls_init();
  597. nickname = crypto_random_hostname(8, 20, "www.", ".net");
  598. nn2 = crypto_random_hostname(8, 20, "www.", ".net");
  599. /* Generate short-term RSA key. */
  600. if (!(rsa = crypto_new_pk_env()))
  601. goto error;
  602. if (crypto_pk_generate_key(rsa)<0)
  603. goto error;
  604. /* Create certificate signed by identity key. */
  605. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  606. key_lifetime);
  607. /* Create self-signed certificate for identity key. */
  608. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  609. IDENTITY_CERT_LIFETIME);
  610. if (!cert || !idcert) {
  611. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  612. goto error;
  613. }
  614. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  615. result->refcnt = 1;
  616. result->my_cert = X509_dup(cert);
  617. result->my_id_cert = X509_dup(idcert);
  618. result->key = crypto_pk_dup_key(rsa);
  619. #ifdef EVERYONE_HAS_AES
  620. /* Tell OpenSSL to only use TLS1 */
  621. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  622. goto error;
  623. #else
  624. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  625. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  626. goto error;
  627. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  628. #endif
  629. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  630. #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  631. SSL_CTX_set_options(result->ctx,
  632. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  633. #endif
  634. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  635. * as authenticating any earlier-received data.
  636. */
  637. if (use_unsafe_renegotiation_op) {
  638. SSL_CTX_set_options(result->ctx,
  639. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  640. }
  641. /* Don't actually allow compression; it uses ram and time, but the data
  642. * we transmit is all encrypted anyway. */
  643. if (result->ctx->comp_methods)
  644. result->ctx->comp_methods = NULL;
  645. #ifdef SSL_MODE_RELEASE_BUFFERS
  646. SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
  647. #endif
  648. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  649. goto error;
  650. X509_free(cert); /* We just added a reference to cert. */
  651. cert=NULL;
  652. if (idcert) {
  653. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  654. tor_assert(s);
  655. X509_STORE_add_cert(s, idcert);
  656. X509_free(idcert); /* The context now owns the reference to idcert */
  657. idcert = NULL;
  658. }
  659. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  660. tor_assert(rsa);
  661. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  662. goto error;
  663. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  664. goto error;
  665. EVP_PKEY_free(pkey);
  666. pkey = NULL;
  667. if (!SSL_CTX_check_private_key(result->ctx))
  668. goto error;
  669. {
  670. crypto_dh_env_t *dh = crypto_dh_new();
  671. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  672. crypto_dh_free(dh);
  673. }
  674. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  675. always_accept_verify_cb);
  676. /* let us realloc bufs that we're writing from */
  677. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  678. /* Free the old context if one exists. */
  679. if (global_tls_context) {
  680. /* This is safe even if there are open connections: we reference-
  681. * count tor_tls_context_t objects. */
  682. tor_tls_context_decref(global_tls_context);
  683. }
  684. global_tls_context = result;
  685. if (rsa)
  686. crypto_free_pk_env(rsa);
  687. tor_free(nickname);
  688. tor_free(nn2);
  689. return 0;
  690. error:
  691. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
  692. tor_free(nickname);
  693. tor_free(nn2);
  694. if (pkey)
  695. EVP_PKEY_free(pkey);
  696. if (rsa)
  697. crypto_free_pk_env(rsa);
  698. if (result)
  699. tor_tls_context_decref(result);
  700. if (cert)
  701. X509_free(cert);
  702. if (idcert)
  703. X509_free(idcert);
  704. return -1;
  705. }
  706. #ifdef V2_HANDSHAKE_SERVER
  707. /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
  708. * a list that indicates that the client knows how to do the v2 TLS connection
  709. * handshake. */
  710. static int
  711. tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
  712. {
  713. int i;
  714. SSL_SESSION *session;
  715. /* If we reached this point, we just got a client hello. See if there is
  716. * a cipher list. */
  717. if (!(session = SSL_get_session((SSL *)ssl))) {
  718. log_info(LD_NET, "No session on TLS?");
  719. return 0;
  720. }
  721. if (!session->ciphers) {
  722. log_info(LD_NET, "No ciphers on session");
  723. return 0;
  724. }
  725. /* Now we need to see if there are any ciphers whose presence means we're
  726. * dealing with an updated Tor. */
  727. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  728. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  729. const char *ciphername = SSL_CIPHER_get_name(cipher);
  730. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  731. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  732. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  733. strcmp(ciphername, "(NONE)")) {
  734. log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
  735. // return 1;
  736. goto dump_list;
  737. }
  738. }
  739. return 0;
  740. dump_list:
  741. {
  742. smartlist_t *elts = smartlist_create();
  743. char *s;
  744. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  745. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  746. const char *ciphername = SSL_CIPHER_get_name(cipher);
  747. smartlist_add(elts, (char*)ciphername);
  748. }
  749. s = smartlist_join_strings(elts, ":", 0, NULL);
  750. log_debug(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
  751. address, s);
  752. tor_free(s);
  753. smartlist_free(elts);
  754. }
  755. return 1;
  756. }
  757. /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
  758. * changes state. We use this:
  759. * <ul><li>To alter the state of the handshake partway through, so we
  760. * do not send or request extra certificates in v2 handshakes.</li>
  761. * <li>To detect renegotiation</li></ul>
  762. */
  763. static void
  764. tor_tls_server_info_callback(const SSL *ssl, int type, int val)
  765. {
  766. tor_tls_t *tls;
  767. (void) val;
  768. if (type != SSL_CB_ACCEPT_LOOP)
  769. return;
  770. if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
  771. return;
  772. tls = tor_tls_get_by_ssl(ssl);
  773. if (tls) {
  774. /* Check whether we're watching for renegotiates. If so, this is one! */
  775. if (tls->negotiated_callback)
  776. tls->got_renegotiate = 1;
  777. if (tls->server_handshake_count < 127) /*avoid any overflow possibility*/
  778. ++tls->server_handshake_count;
  779. } else {
  780. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  781. }
  782. /* Now check the cipher list. */
  783. if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
  784. /*XXXX_TLS keep this from happening more than once! */
  785. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  786. * Let's hope openssl doesn't notice! */
  787. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  788. SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
  789. /* Don't send a hello request. */
  790. SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
  791. if (tls) {
  792. tls->wasV2Handshake = 1;
  793. #ifdef USE_BUFFEREVENTS
  794. if (use_unsafe_renegotiation_flag)
  795. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  796. #endif
  797. } else {
  798. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  799. }
  800. }
  801. }
  802. #endif
  803. /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
  804. * a list designed to mimic a common web browser. Some of the ciphers in the
  805. * list won't actually be implemented by OpenSSL: that's okay so long as the
  806. * server doesn't select them, and the server won't select anything besides
  807. * what's in SERVER_CIPHER_LIST.
  808. *
  809. * [If the server <b>does</b> select a bogus cipher, we won't crash or
  810. * anything; we'll just fail later when we try to look up the cipher in
  811. * ssl->cipher_list_by_id.]
  812. */
  813. static void
  814. rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
  815. {
  816. #ifdef V2_HANDSHAKE_CLIENT
  817. if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
  818. /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
  819. * we want.*/
  820. int i = 0, j = 0;
  821. /* First, create a dummy SSL_CIPHER for every cipher. */
  822. CLIENT_CIPHER_DUMMIES =
  823. tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
  824. for (i=0; i < N_CLIENT_CIPHERS; ++i) {
  825. CLIENT_CIPHER_DUMMIES[i].valid = 1;
  826. CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
  827. CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
  828. }
  829. CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
  830. tor_assert(CLIENT_CIPHER_STACK);
  831. log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
  832. for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
  833. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
  834. log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
  835. }
  836. /* Then copy as many ciphers as we can from the good list, inserting
  837. * dummies as needed. */
  838. j=0;
  839. for (i = 0; i < N_CLIENT_CIPHERS; ) {
  840. SSL_CIPHER *cipher = NULL;
  841. if (j < sk_SSL_CIPHER_num(*ciphers))
  842. cipher = sk_SSL_CIPHER_value(*ciphers, j);
  843. if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
  844. log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
  845. ++j;
  846. } else if (cipher &&
  847. (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
  848. log_debug(LD_NET, "Found cipher %s", cipher->name);
  849. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
  850. ++j;
  851. ++i;
  852. } else {
  853. log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
  854. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
  855. ++i;
  856. }
  857. }
  858. }
  859. sk_SSL_CIPHER_free(*ciphers);
  860. *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
  861. tor_assert(*ciphers);
  862. #else
  863. (void)ciphers;
  864. #endif
  865. }
  866. /** Create a new TLS object from a file descriptor, and a flag to
  867. * determine whether it is functioning as a server.
  868. */
  869. tor_tls_t *
  870. tor_tls_new(int sock, int isServer)
  871. {
  872. BIO *bio = NULL;
  873. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  874. tor_assert(global_tls_context); /* make sure somebody made it first */
  875. if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
  876. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
  877. tor_free(result);
  878. return NULL;
  879. }
  880. #ifdef SSL_set_tlsext_host_name
  881. /* Browsers use the TLS hostname extension, so we should too. */
  882. {
  883. char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
  884. SSL_set_tlsext_host_name(result->ssl, fake_hostname);
  885. tor_free(fake_hostname);
  886. }
  887. #endif
  888. if (!SSL_set_cipher_list(result->ssl,
  889. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  890. tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
  891. #ifdef SSL_set_tlsext_host_name
  892. SSL_set_tlsext_host_name(result->ssl, NULL);
  893. #endif
  894. SSL_free(result->ssl);
  895. tor_free(result);
  896. return NULL;
  897. }
  898. if (!isServer)
  899. rectify_client_ciphers(&result->ssl->cipher_list);
  900. result->socket = sock;
  901. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  902. if (! bio) {
  903. tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
  904. #ifdef SSL_set_tlsext_host_name
  905. SSL_set_tlsext_host_name(result->ssl, NULL);
  906. #endif
  907. SSL_free(result->ssl);
  908. tor_free(result);
  909. return NULL;
  910. }
  911. HT_INSERT(tlsmap, &tlsmap_root, result);
  912. SSL_set_bio(result->ssl, bio, bio);
  913. tor_tls_context_incref(global_tls_context);
  914. result->context = global_tls_context;
  915. result->state = TOR_TLS_ST_HANDSHAKE;
  916. result->isServer = isServer;
  917. result->wantwrite_n = 0;
  918. result->last_write_count = BIO_number_written(bio);
  919. result->last_read_count = BIO_number_read(bio);
  920. if (result->last_write_count || result->last_read_count) {
  921. log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
  922. result->last_read_count, result->last_write_count);
  923. }
  924. #ifdef V2_HANDSHAKE_SERVER
  925. if (isServer) {
  926. SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
  927. }
  928. #endif
  929. /* Not expected to get called. */
  930. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
  931. return result;
  932. }
  933. /** Make future log messages about <b>tls</b> display the address
  934. * <b>address</b>.
  935. */
  936. void
  937. tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
  938. {
  939. tor_assert(tls);
  940. tor_free(tls->address);
  941. tls->address = tor_strdup(address);
  942. }
  943. /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
  944. * next gets a client-side renegotiate in the middle of a read. Do not
  945. * invoke this function until <em>after</em> initial handshaking is done!
  946. */
  947. void
  948. tor_tls_set_renegotiate_callback(tor_tls_t *tls,
  949. void (*cb)(tor_tls_t *, void *arg),
  950. void *arg)
  951. {
  952. tls->negotiated_callback = cb;
  953. tls->callback_arg = arg;
  954. tls->got_renegotiate = 0;
  955. #ifdef V2_HANDSHAKE_SERVER
  956. if (cb) {
  957. SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
  958. } else {
  959. SSL_set_info_callback(tls->ssl, NULL);
  960. }
  961. #endif
  962. }
  963. /** If this version of openssl requires it, turn on renegotiation on
  964. * <b>tls</b>.
  965. */
  966. void
  967. tor_tls_unblock_renegotiation(tor_tls_t *tls)
  968. {
  969. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  970. * as authenticating any earlier-received data. */
  971. if (use_unsafe_renegotiation_flag) {
  972. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  973. }
  974. if (use_unsafe_renegotiation_op) {
  975. SSL_set_options(tls->ssl,
  976. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  977. }
  978. }
  979. /** If this version of openssl supports it, turn off renegotiation on
  980. * <b>tls</b>. (Our protocol never requires this for security, but it's nice
  981. * to use belt-and-suspenders here.)
  982. */
  983. void
  984. tor_tls_block_renegotiation(tor_tls_t *tls)
  985. {
  986. tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  987. }
  988. void
  989. tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
  990. {
  991. if (use_unsafe_renegotiation_flag) {
  992. tor_assert(0 != (tls->ssl->s3->flags &
  993. SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  994. }
  995. if (use_unsafe_renegotiation_op) {
  996. long options = SSL_get_options(tls->ssl);
  997. tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  998. }
  999. }
  1000. /** Return whether this tls initiated the connect (client) or
  1001. * received it (server). */
  1002. int
  1003. tor_tls_is_server(tor_tls_t *tls)
  1004. {
  1005. tor_assert(tls);
  1006. return tls->isServer;
  1007. }
  1008. /** Release resources associated with a TLS object. Does not close the
  1009. * underlying file descriptor.
  1010. */
  1011. void
  1012. tor_tls_free(tor_tls_t *tls)
  1013. {
  1014. tor_tls_t *removed;
  1015. if (!tls)
  1016. return;
  1017. tor_assert(tls->ssl);
  1018. removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
  1019. if (!removed) {
  1020. log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
  1021. }
  1022. #ifdef SSL_set_tlsext_host_name
  1023. SSL_set_tlsext_host_name(tls->ssl, NULL);
  1024. #endif
  1025. SSL_free(tls->ssl);
  1026. tls->ssl = NULL;
  1027. tls->negotiated_callback = NULL;
  1028. if (tls->context)
  1029. tor_tls_context_decref(tls->context);
  1030. tor_free(tls->address);
  1031. tor_free(tls);
  1032. }
  1033. /** Underlying function for TLS reading. Reads up to <b>len</b>
  1034. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  1035. * number of characters read. On failure, returns TOR_TLS_ERROR,
  1036. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1037. */
  1038. int
  1039. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  1040. {
  1041. int r, err;
  1042. tor_assert(tls);
  1043. tor_assert(tls->ssl);
  1044. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1045. tor_assert(len<INT_MAX);
  1046. r = SSL_read(tls->ssl, cp, (int)len);
  1047. if (r > 0) {
  1048. #ifdef V2_HANDSHAKE_SERVER
  1049. if (tls->got_renegotiate) {
  1050. /* Renegotiation happened! */
  1051. log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
  1052. if (tls->negotiated_callback)
  1053. tls->negotiated_callback(tls, tls->callback_arg);
  1054. tls->got_renegotiate = 0;
  1055. }
  1056. #endif
  1057. return r;
  1058. }
  1059. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
  1060. if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
  1061. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  1062. tls->state = TOR_TLS_ST_CLOSED;
  1063. return TOR_TLS_CLOSE;
  1064. } else {
  1065. tor_assert(err != TOR_TLS_DONE);
  1066. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  1067. return err;
  1068. }
  1069. }
  1070. /** Underlying function for TLS writing. Write up to <b>n</b>
  1071. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  1072. * number of characters written. On failure, returns TOR_TLS_ERROR,
  1073. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1074. */
  1075. int
  1076. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  1077. {
  1078. int r, err;
  1079. tor_assert(tls);
  1080. tor_assert(tls->ssl);
  1081. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1082. tor_assert(n < INT_MAX);
  1083. if (n == 0)
  1084. return 0;
  1085. if (tls->wantwrite_n) {
  1086. /* if WANTWRITE last time, we must use the _same_ n as before */
  1087. tor_assert(n >= tls->wantwrite_n);
  1088. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  1089. (int)n, (int)tls->wantwrite_n);
  1090. n = tls->wantwrite_n;
  1091. tls->wantwrite_n = 0;
  1092. }
  1093. r = SSL_write(tls->ssl, cp, (int)n);
  1094. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
  1095. if (err == TOR_TLS_DONE) {
  1096. return r;
  1097. }
  1098. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  1099. tls->wantwrite_n = n;
  1100. }
  1101. return err;
  1102. }
  1103. /** Perform initial handshake on <b>tls</b>. When finished, returns
  1104. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1105. * or TOR_TLS_WANTWRITE.
  1106. */
  1107. int
  1108. tor_tls_handshake(tor_tls_t *tls)
  1109. {
  1110. int r;
  1111. int oldstate;
  1112. tor_assert(tls);
  1113. tor_assert(tls->ssl);
  1114. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  1115. check_no_tls_errors();
  1116. oldstate = tls->ssl->state;
  1117. if (tls->isServer) {
  1118. log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
  1119. ssl_state_to_string(tls->ssl->state));
  1120. r = SSL_accept(tls->ssl);
  1121. } else {
  1122. log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
  1123. ssl_state_to_string(tls->ssl->state));
  1124. r = SSL_connect(tls->ssl);
  1125. }
  1126. if (oldstate != tls->ssl->state)
  1127. log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
  1128. tls, ssl_state_to_string(tls->ssl->state));
  1129. /* We need to call this here and not earlier, since OpenSSL has a penchant
  1130. * for clearing its flags when you say accept or connect. */
  1131. tor_tls_unblock_renegotiation(tls);
  1132. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
  1133. if (ERR_peek_error() != 0) {
  1134. tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
  1135. "handshaking");
  1136. return TOR_TLS_ERROR_MISC;
  1137. }
  1138. if (r == TOR_TLS_DONE) {
  1139. tls->state = TOR_TLS_ST_OPEN;
  1140. return tor_tls_finish_handshake(tls);
  1141. }
  1142. return r;
  1143. }
  1144. /** Perform the final part of the intial TLS handshake on <b>tls</b>. This
  1145. * should be called for the first handshake only: it determines whether the v1
  1146. * or the v2 handshake was used, and adjusts things for the renegotiation
  1147. * handshake as appropriate.
  1148. *
  1149. * tor_tls_handshake() calls this on its own; you only need to call this if
  1150. * bufferevent is doing the handshake for you.
  1151. */
  1152. int
  1153. tor_tls_finish_handshake(tor_tls_t *tls)
  1154. {
  1155. int r = TOR_TLS_DONE;
  1156. if (tls->isServer) {
  1157. SSL_set_info_callback(tls->ssl, NULL);
  1158. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
  1159. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  1160. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  1161. #ifdef V2_HANDSHAKE_SERVER
  1162. if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
  1163. /* This check is redundant, but back when we did it in the callback,
  1164. * we might have not been able to look up the tor_tls_t if the code
  1165. * was buggy. Fixing that. */
  1166. if (!tls->wasV2Handshake) {
  1167. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  1168. " get set. Fixing that.");
  1169. }
  1170. tls->wasV2Handshake = 1;
  1171. log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
  1172. " for renegotiation.");
  1173. } else {
  1174. tls->wasV2Handshake = 0;
  1175. }
  1176. #endif
  1177. } else {
  1178. #ifdef V2_HANDSHAKE_CLIENT
  1179. /* If we got no ID cert, we're a v2 handshake. */
  1180. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  1181. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  1182. int n_certs = sk_X509_num(chain);
  1183. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0))) {
  1184. log_debug(LD_HANDSHAKE, "Server sent back multiple certificates; it "
  1185. "looks like a v1 handshake on %p", tls);
  1186. tls->wasV2Handshake = 0;
  1187. } else {
  1188. log_debug(LD_HANDSHAKE,
  1189. "Server sent back a single certificate; looks like "
  1190. "a v2 handshake on %p.", tls);
  1191. tls->wasV2Handshake = 1;
  1192. }
  1193. if (cert)
  1194. X509_free(cert);
  1195. #endif
  1196. if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
  1197. tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
  1198. r = TOR_TLS_ERROR_MISC;
  1199. }
  1200. }
  1201. return r;
  1202. }
  1203. #ifdef USE_BUFFEREVENTS
  1204. /** Put <b>tls</b>, which must be a client connection, into renegotiation
  1205. * mode. */
  1206. int
  1207. tor_tls_start_renegotiating(tor_tls_t *tls)
  1208. {
  1209. int r = SSL_renegotiate(tls->ssl);
  1210. if (r <= 0) {
  1211. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1212. LD_HANDSHAKE);
  1213. }
  1214. return 0;
  1215. }
  1216. #endif
  1217. /** Client only: Renegotiate a TLS session. When finished, returns
  1218. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  1219. * TOR_TLS_WANTWRITE.
  1220. */
  1221. int
  1222. tor_tls_renegotiate(tor_tls_t *tls)
  1223. {
  1224. int r;
  1225. tor_assert(tls);
  1226. /* We could do server-initiated renegotiation too, but that would be tricky.
  1227. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  1228. tor_assert(!tls->isServer);
  1229. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  1230. int r = SSL_renegotiate(tls->ssl);
  1231. if (r <= 0) {
  1232. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1233. LD_HANDSHAKE);
  1234. }
  1235. tls->state = TOR_TLS_ST_RENEGOTIATE;
  1236. }
  1237. r = SSL_do_handshake(tls->ssl);
  1238. if (r == 1) {
  1239. tls->state = TOR_TLS_ST_OPEN;
  1240. return TOR_TLS_DONE;
  1241. } else
  1242. return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO,
  1243. LD_HANDSHAKE);
  1244. }
  1245. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  1246. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1247. * or TOR_TLS_WANTWRITE.
  1248. */
  1249. int
  1250. tor_tls_shutdown(tor_tls_t *tls)
  1251. {
  1252. int r, err;
  1253. char buf[128];
  1254. tor_assert(tls);
  1255. tor_assert(tls->ssl);
  1256. while (1) {
  1257. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  1258. /* If we've already called shutdown once to send a close message,
  1259. * we read until the other side has closed too.
  1260. */
  1261. do {
  1262. r = SSL_read(tls->ssl, buf, 128);
  1263. } while (r>0);
  1264. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  1265. LOG_INFO, LD_NET);
  1266. if (err == _TOR_TLS_ZERORETURN) {
  1267. tls->state = TOR_TLS_ST_GOTCLOSE;
  1268. /* fall through... */
  1269. } else {
  1270. return err;
  1271. }
  1272. }
  1273. r = SSL_shutdown(tls->ssl);
  1274. if (r == 1) {
  1275. /* If shutdown returns 1, the connection is entirely closed. */
  1276. tls->state = TOR_TLS_ST_CLOSED;
  1277. return TOR_TLS_DONE;
  1278. }
  1279. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  1280. LOG_INFO, LD_NET);
  1281. if (err == _TOR_TLS_SYSCALL) {
  1282. /* The underlying TCP connection closed while we were shutting down. */
  1283. tls->state = TOR_TLS_ST_CLOSED;
  1284. return TOR_TLS_DONE;
  1285. } else if (err == _TOR_TLS_ZERORETURN) {
  1286. /* The TLS connection says that it sent a shutdown record, but
  1287. * isn't done shutting down yet. Make sure that this hasn't
  1288. * happened before, then go back to the start of the function
  1289. * and try to read.
  1290. */
  1291. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  1292. tls->state == TOR_TLS_ST_SENTCLOSE) {
  1293. log(LOG_WARN, LD_NET,
  1294. "TLS returned \"half-closed\" value while already half-closed");
  1295. return TOR_TLS_ERROR_MISC;
  1296. }
  1297. tls->state = TOR_TLS_ST_SENTCLOSE;
  1298. /* fall through ... */
  1299. } else {
  1300. return err;
  1301. }
  1302. } /* end loop */
  1303. }
  1304. /** Return true iff this TLS connection is authenticated.
  1305. */
  1306. int
  1307. tor_tls_peer_has_cert(tor_tls_t *tls)
  1308. {
  1309. X509 *cert;
  1310. cert = SSL_get_peer_certificate(tls->ssl);
  1311. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1312. if (!cert)
  1313. return 0;
  1314. X509_free(cert);
  1315. return 1;
  1316. }
  1317. /** Warn that a certificate lifetime extends through a certain range. */
  1318. static void
  1319. log_cert_lifetime(X509 *cert, const char *problem)
  1320. {
  1321. BIO *bio = NULL;
  1322. BUF_MEM *buf;
  1323. char *s1=NULL, *s2=NULL;
  1324. char mytime[33];
  1325. time_t now = time(NULL);
  1326. struct tm tm;
  1327. if (problem)
  1328. log_warn(LD_GENERAL,
  1329. "Certificate %s: is your system clock set incorrectly?",
  1330. problem);
  1331. if (!(bio = BIO_new(BIO_s_mem()))) {
  1332. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1333. }
  1334. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1335. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1336. goto end;
  1337. }
  1338. BIO_get_mem_ptr(bio, &buf);
  1339. s1 = tor_strndup(buf->data, buf->length);
  1340. (void)BIO_reset(bio);
  1341. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1342. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1343. goto end;
  1344. }
  1345. BIO_get_mem_ptr(bio, &buf);
  1346. s2 = tor_strndup(buf->data, buf->length);
  1347. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1348. log_warn(LD_GENERAL,
  1349. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1350. s1,s2,mytime);
  1351. end:
  1352. /* Not expected to get invoked */
  1353. tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
  1354. if (bio)
  1355. BIO_free(bio);
  1356. tor_free(s1);
  1357. tor_free(s2);
  1358. }
  1359. /** Helper function: try to extract a link certificate and an identity
  1360. * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
  1361. * *<b>id_cert_out</b> respectively. Log all messages at level
  1362. * <b>severity</b>.
  1363. *
  1364. * Note that a reference is added to cert_out, so it needs to be
  1365. * freed. id_cert_out doesn't. */
  1366. static void
  1367. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1368. X509 **cert_out, X509 **id_cert_out)
  1369. {
  1370. X509 *cert = NULL, *id_cert = NULL;
  1371. STACK_OF(X509) *chain = NULL;
  1372. int num_in_chain, i;
  1373. *cert_out = *id_cert_out = NULL;
  1374. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1375. return;
  1376. *cert_out = cert;
  1377. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1378. return;
  1379. num_in_chain = sk_X509_num(chain);
  1380. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1381. * 2 means we're connecting (client-side), and it's both the link
  1382. * cert and the id_cert.
  1383. */
  1384. if (num_in_chain < 1) {
  1385. log_fn(severity,LD_PROTOCOL,
  1386. "Unexpected number of certificates in chain (%d)",
  1387. num_in_chain);
  1388. return;
  1389. }
  1390. for (i=0; i<num_in_chain; ++i) {
  1391. id_cert = sk_X509_value(chain, i);
  1392. if (X509_cmp(id_cert, cert) != 0)
  1393. break;
  1394. }
  1395. *id_cert_out = id_cert;
  1396. }
  1397. /** If the provided tls connection is authenticated and has a
  1398. * certificate chain that is currently valid and signed, then set
  1399. * *<b>identity_key</b> to the identity certificate's key and return
  1400. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1401. */
  1402. int
  1403. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1404. {
  1405. X509 *cert = NULL, *id_cert = NULL;
  1406. EVP_PKEY *id_pkey = NULL;
  1407. RSA *rsa;
  1408. int r = -1;
  1409. *identity_key = NULL;
  1410. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1411. if (!cert)
  1412. goto done;
  1413. if (!id_cert) {
  1414. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1415. goto done;
  1416. }
  1417. tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
  1418. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1419. X509_verify(cert, id_pkey) <= 0) {
  1420. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1421. tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
  1422. goto done;
  1423. }
  1424. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1425. if (!rsa)
  1426. goto done;
  1427. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1428. r = 0;
  1429. done:
  1430. if (cert)
  1431. X509_free(cert);
  1432. if (id_pkey)
  1433. EVP_PKEY_free(id_pkey);
  1434. /* This should never get invoked, but let's make sure in case OpenSSL
  1435. * acts unexpectedly. */
  1436. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
  1437. return r;
  1438. }
  1439. /** Check whether the certificate set on the connection <b>tls</b> is
  1440. * expired or not-yet-valid, give or take <b>tolerance</b>
  1441. * seconds. Return 0 for valid, -1 for failure.
  1442. *
  1443. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1444. */
  1445. int
  1446. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  1447. {
  1448. time_t now, t;
  1449. X509 *cert;
  1450. int r = -1;
  1451. now = time(NULL);
  1452. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1453. goto done;
  1454. t = now + tolerance;
  1455. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1456. log_cert_lifetime(cert, "not yet valid");
  1457. goto done;
  1458. }
  1459. t = now - tolerance;
  1460. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1461. log_cert_lifetime(cert, "already expired");
  1462. goto done;
  1463. }
  1464. r = 0;
  1465. done:
  1466. if (cert)
  1467. X509_free(cert);
  1468. /* Not expected to get invoked */
  1469. tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
  1470. return r;
  1471. }
  1472. /** Return the number of bytes available for reading from <b>tls</b>.
  1473. */
  1474. int
  1475. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1476. {
  1477. tor_assert(tls);
  1478. return SSL_pending(tls->ssl);
  1479. }
  1480. /** If <b>tls</b> requires that the next write be of a particular size,
  1481. * return that size. Otherwise, return 0. */
  1482. size_t
  1483. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1484. {
  1485. return tls->wantwrite_n;
  1486. }
  1487. /** Sets n_read and n_written to the number of bytes read and written,
  1488. * respectively, on the raw socket used by <b>tls</b> since the last time this
  1489. * function was called on <b>tls</b>. */
  1490. void
  1491. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1492. {
  1493. BIO *wbio, *tmpbio;
  1494. unsigned long r, w;
  1495. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1496. /* We want the number of bytes actually for real written. Unfortunately,
  1497. * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
  1498. * which makes the answer turn out wrong. Let's cope with that. Note
  1499. * that this approach will fail if we ever replace tls->ssl's BIOs with
  1500. * buffering bios for reasons of our own. As an alternative, we could
  1501. * save the original BIO for tls->ssl in the tor_tls_t structure, but
  1502. * that would be tempting fate. */
  1503. wbio = SSL_get_wbio(tls->ssl);
  1504. if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
  1505. wbio = tmpbio;
  1506. w = BIO_number_written(wbio);
  1507. /* We are ok with letting these unsigned ints go "negative" here:
  1508. * If we wrapped around, this should still give us the right answer, unless
  1509. * we wrapped around by more than ULONG_MAX since the last time we called
  1510. * this function.
  1511. */
  1512. *n_read = (size_t)(r - tls->last_read_count);
  1513. *n_written = (size_t)(w - tls->last_write_count);
  1514. if (*n_read > INT_MAX || *n_written > INT_MAX) {
  1515. log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
  1516. "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
  1517. r, tls->last_read_count, w, tls->last_write_count);
  1518. }
  1519. tls->last_read_count = r;
  1520. tls->last_write_count = w;
  1521. }
  1522. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1523. * errors, log an error message. */
  1524. void
  1525. _check_no_tls_errors(const char *fname, int line)
  1526. {
  1527. if (ERR_peek_error() == 0)
  1528. return;
  1529. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1530. tor_fix_source_file(fname), line);
  1531. tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
  1532. }
  1533. /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
  1534. * TLS handshake. Output is undefined if the handshake isn't finished. */
  1535. int
  1536. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1537. {
  1538. if (tls->isServer) {
  1539. #ifdef V2_HANDSHAKE_SERVER
  1540. return ! tls->wasV2Handshake;
  1541. #endif
  1542. } else {
  1543. #ifdef V2_HANDSHAKE_CLIENT
  1544. return ! tls->wasV2Handshake;
  1545. #endif
  1546. }
  1547. return 1;
  1548. }
  1549. /** Return the number of server handshakes that we've noticed doing on
  1550. * <b>tls</b>. */
  1551. int
  1552. tor_tls_get_num_server_handshakes(tor_tls_t *tls)
  1553. {
  1554. return tls->server_handshake_count;
  1555. }
  1556. /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
  1557. * request it was waiting for. */
  1558. int
  1559. tor_tls_server_got_renegotiate(tor_tls_t *tls)
  1560. {
  1561. return tls->got_renegotiate;
  1562. }
  1563. /** Examine the amount of memory used and available for buffers in <b>tls</b>.
  1564. * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
  1565. * buffer and *<b>rbuf_bytes</b> to the amount actually used.
  1566. * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
  1567. * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
  1568. void
  1569. tor_tls_get_buffer_sizes(tor_tls_t *tls,
  1570. size_t *rbuf_capacity, size_t *rbuf_bytes,
  1571. size_t *wbuf_capacity, size_t *wbuf_bytes)
  1572. {
  1573. if (tls->ssl->s3->rbuf.buf)
  1574. *rbuf_capacity = tls->ssl->s3->rbuf.len;
  1575. else
  1576. *rbuf_capacity = 0;
  1577. if (tls->ssl->s3->wbuf.buf)
  1578. *wbuf_capacity = tls->ssl->s3->wbuf.len;
  1579. else
  1580. *wbuf_capacity = 0;
  1581. *rbuf_bytes = tls->ssl->s3->rbuf.left;
  1582. *wbuf_bytes = tls->ssl->s3->wbuf.left;
  1583. }
  1584. #ifdef USE_BUFFEREVENTS
  1585. /** Construct and return an TLS-encrypting bufferevent to send data over
  1586. * <b>socket</b>, which must match the socket of the underlying bufferevent
  1587. * <b>bufev_in</b>. The TLS object <b>tls</b> is used for encryption.
  1588. *
  1589. * This function will either create a filtering bufferevent that wraps around
  1590. * <b>bufev_in</b>, or it will free bufev_in and return a new bufferevent that
  1591. * uses the <b>tls</b> to talk to the network directly. Do not use
  1592. * <b>bufev_in</b> after calling this function.
  1593. *
  1594. * The connection will start out doing a server handshake if <b>receiving</b>
  1595. * is strue, and a client handshake otherwise.
  1596. *
  1597. * Returns NULL on failure.
  1598. */
  1599. struct bufferevent *
  1600. tor_tls_init_bufferevent(tor_tls_t *tls, struct bufferevent *bufev_in,
  1601. evutil_socket_t socket, int receiving)
  1602. {
  1603. struct bufferevent *out;
  1604. const enum bufferevent_ssl_state state = receiving ?
  1605. BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
  1606. #if 0
  1607. (void) socket;
  1608. out = bufferevent_openssl_filter_new(tor_libevent_get_base(),
  1609. bufev_in,
  1610. tls->ssl,
  1611. state,
  1612. BEV_OPT_DEFER_CALLBACKS);
  1613. #else
  1614. if (bufev_in) {
  1615. evutil_socket_t s = bufferevent_getfd(bufev_in);
  1616. tor_assert(s == -1 || s == socket);
  1617. tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in)) == 0);
  1618. tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in)) == 0);
  1619. tor_assert(BIO_number_read(SSL_get_rbio(tls->ssl)) == 0);
  1620. tor_assert(BIO_number_written(SSL_get_rbio(tls->ssl)) == 0);
  1621. bufferevent_free(bufev_in);
  1622. }
  1623. tls->state = TOR_TLS_ST_BUFFEREVENT;
  1624. /* Current versions (as of 2.0.7-rc) of Libevent need to defer
  1625. * bufferevent_openssl callbacks, or else our callback functions will
  1626. * get called reentrantly, which is bad for us.
  1627. */
  1628. out = bufferevent_openssl_socket_new(tor_libevent_get_base(),
  1629. socket,
  1630. tls->ssl,
  1631. state,
  1632. BEV_OPT_DEFER_CALLBACKS);
  1633. #endif
  1634. /* Unblock _after_ creating the bufferevent, since accept/connect tend to
  1635. * clear flags. */
  1636. tor_tls_unblock_renegotiation(tls);
  1637. return out;
  1638. }
  1639. #endif