tortls.c 51 KB

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