tortls.c 52 KB

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