tortls.c 59 KB

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