tortls.c 51 KB

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