tortls.c 55 KB

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