tortls.c 51 KB

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