tortls.c 56 KB

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