tortls.c 49 KB

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