tortls.c 55 KB

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