tortls_openssl.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  1. /* Copyright (c) 2003, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, 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. #define TORTLS_PRIVATE
  16. #define TORTLS_OPENSSL_PRIVATE
  17. #ifdef _WIN32 /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
  18. #include <winsock2.h>
  19. #include <ws2tcpip.h>
  20. #endif
  21. #include "lib/crypt_ops/crypto_cipher.h"
  22. #include "lib/crypt_ops/crypto_rand.h"
  23. #include "lib/crypt_ops/crypto_dh.h"
  24. #include "lib/crypt_ops/crypto_util.h"
  25. #include "lib/crypt_ops/compat_openssl.h"
  26. #include "lib/tls/x509.h"
  27. #include "lib/tls/x509_internal.h"
  28. /* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
  29. * srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
  30. DISABLE_GCC_WARNING(redundant-decls)
  31. #include <openssl/opensslv.h>
  32. #ifdef OPENSSL_NO_EC
  33. #error "We require OpenSSL with ECC support"
  34. #endif
  35. #include <openssl/ssl.h>
  36. #include <openssl/ssl3.h>
  37. #include <openssl/err.h>
  38. #include <openssl/tls1.h>
  39. #include <openssl/asn1.h>
  40. #include <openssl/bio.h>
  41. #include <openssl/bn.h>
  42. #include <openssl/rsa.h>
  43. ENABLE_GCC_WARNING(redundant-decls)
  44. #include "lib/tls/tortls.h"
  45. #include "lib/tls/tortls_st.h"
  46. #include "lib/tls/tortls_internal.h"
  47. #include "lib/log/log.h"
  48. #include "lib/log/util_bug.h"
  49. #include "lib/container/smartlist.h"
  50. #include "lib/string/compat_string.h"
  51. #include "lib/string/printf.h"
  52. #include "lib/net/socket.h"
  53. #include "lib/intmath/cmp.h"
  54. #include "lib/ctime/di_ops.h"
  55. #include "lib/encoding/time_fmt.h"
  56. #include <stdlib.h>
  57. #include <string.h>
  58. #include "lib/arch/bytes.h"
  59. /* Copied from or.h */
  60. #define LEGAL_NICKNAME_CHARACTERS \
  61. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  62. /** How long do identity certificates live? (sec) */
  63. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  64. #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
  65. #if OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f')
  66. /* This is a version of OpenSSL before 1.0.0f. It does not have
  67. * the CVE-2011-4576 fix, and as such it can't use RELEASE_BUFFERS and
  68. * SSL3 safely at the same time.
  69. */
  70. #define DISABLE_SSL3_HANDSHAKE
  71. #endif /* OPENSSL_VERSION_NUMBER < OPENSSL_V(1,0,0,'f') */
  72. /* We redefine these so that we can run correctly even if the vendor gives us
  73. * a version of OpenSSL that does not match its header files. (Apple: I am
  74. * looking at you.)
  75. */
  76. #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  77. #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
  78. #endif
  79. #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  80. #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
  81. #endif
  82. /** Return values for tor_tls_classify_client_ciphers.
  83. *
  84. * @{
  85. */
  86. /** An error occurred when examining the client ciphers */
  87. #define CIPHERS_ERR -1
  88. /** The client cipher list indicates that a v1 handshake was in use. */
  89. #define CIPHERS_V1 1
  90. /** The client cipher list indicates that the client is using the v2 or the
  91. * v3 handshake, but that it is (probably!) lying about what ciphers it
  92. * supports */
  93. #define CIPHERS_V2 2
  94. /** The client cipher list indicates that the client is using the v2 or the
  95. * v3 handshake, and that it is telling the truth about what ciphers it
  96. * supports */
  97. #define CIPHERS_UNRESTRICTED 3
  98. /** @} */
  99. /** The ex_data index in which we store a pointer to an SSL object's
  100. * corresponding tor_tls_t object. */
  101. STATIC int tor_tls_object_ex_data_index = -1;
  102. /** Helper: Allocate tor_tls_object_ex_data_index. */
  103. void
  104. tor_tls_allocate_tor_tls_object_ex_data_index(void)
  105. {
  106. if (tor_tls_object_ex_data_index == -1) {
  107. tor_tls_object_ex_data_index =
  108. SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  109. tor_assert(tor_tls_object_ex_data_index != -1);
  110. }
  111. }
  112. /** Helper: given a SSL* pointer, return the tor_tls_t object using that
  113. * pointer. */
  114. tor_tls_t *
  115. tor_tls_get_by_ssl(const SSL *ssl)
  116. {
  117. tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
  118. if (result)
  119. tor_assert(result->magic == TOR_TLS_MAGIC);
  120. return result;
  121. }
  122. /** True iff tor_tls_init() has been called. */
  123. static int tls_library_is_initialized = 0;
  124. /* Module-internal error codes. */
  125. #define TOR_TLS_SYSCALL_ (MIN_TOR_TLS_ERROR_VAL_ - 2)
  126. #define TOR_TLS_ZERORETURN_ (MIN_TOR_TLS_ERROR_VAL_ - 1)
  127. /** Write a description of the current state of <b>tls</b> into the
  128. * <b>sz</b>-byte buffer at <b>buf</b>. */
  129. void
  130. tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
  131. {
  132. const char *ssl_state;
  133. const char *tortls_state;
  134. if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
  135. strlcpy(buf, "(No SSL object)", sz);
  136. return;
  137. }
  138. ssl_state = SSL_state_string_long(tls->ssl);
  139. switch (tls->state) {
  140. #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
  141. CASE(HANDSHAKE);
  142. CASE(OPEN);
  143. CASE(GOTCLOSE);
  144. CASE(SENTCLOSE);
  145. CASE(CLOSED);
  146. CASE(RENEGOTIATE);
  147. #undef CASE
  148. case TOR_TLS_ST_BUFFEREVENT:
  149. tortls_state = "";
  150. break;
  151. default:
  152. tortls_state = " in unknown TLS state";
  153. break;
  154. }
  155. tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
  156. }
  157. /** Log a single error <b>err</b> as returned by ERR_get_error(), which was
  158. * received while performing an operation <b>doing</b> on <b>tls</b>. Log
  159. * the message at <b>severity</b>, in log domain <b>domain</b>. */
  160. void
  161. tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
  162. int severity, int domain, const char *doing)
  163. {
  164. const char *state = NULL, *addr;
  165. const char *msg, *lib, *func;
  166. state = (tls && tls->ssl)?SSL_state_string_long(tls->ssl):"---";
  167. addr = tls ? tls->address : NULL;
  168. /* Some errors are known-benign, meaning they are the fault of the other
  169. * side of the connection. The caller doesn't know this, so override the
  170. * priority for those cases. */
  171. switch (ERR_GET_REASON(err)) {
  172. case SSL_R_HTTP_REQUEST:
  173. case SSL_R_HTTPS_PROXY_REQUEST:
  174. case SSL_R_RECORD_LENGTH_MISMATCH:
  175. #ifndef OPENSSL_1_1_API
  176. case SSL_R_RECORD_TOO_LARGE:
  177. #endif
  178. case SSL_R_UNKNOWN_PROTOCOL:
  179. case SSL_R_UNSUPPORTED_PROTOCOL:
  180. severity = LOG_INFO;
  181. break;
  182. default:
  183. break;
  184. }
  185. msg = (const char*)ERR_reason_error_string(err);
  186. lib = (const char*)ERR_lib_error_string(err);
  187. func = (const char*)ERR_func_error_string(err);
  188. if (!msg) msg = "(null)";
  189. if (!lib) lib = "(null)";
  190. if (!func) func = "(null)";
  191. if (doing) {
  192. tor_log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
  193. doing, addr?" with ":"", addr?addr:"",
  194. msg, lib, func, state);
  195. } else {
  196. tor_log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
  197. addr?" with ":"", addr?addr:"",
  198. msg, lib, func, state);
  199. }
  200. }
  201. /** Log all pending tls errors at level <b>severity</b> in log domain
  202. * <b>domain</b>. Use <b>doing</b> to describe our current activities.
  203. */
  204. void
  205. tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
  206. {
  207. unsigned long err;
  208. while ((err = ERR_get_error()) != 0) {
  209. tor_tls_log_one_error(tls, err, severity, domain, doing);
  210. }
  211. }
  212. /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
  213. * code. */
  214. int
  215. tor_errno_to_tls_error(int e)
  216. {
  217. switch (e) {
  218. case SOCK_ERRNO(ECONNRESET): // most common
  219. return TOR_TLS_ERROR_CONNRESET;
  220. case SOCK_ERRNO(ETIMEDOUT):
  221. return TOR_TLS_ERROR_TIMEOUT;
  222. case SOCK_ERRNO(EHOSTUNREACH):
  223. case SOCK_ERRNO(ENETUNREACH):
  224. return TOR_TLS_ERROR_NO_ROUTE;
  225. case SOCK_ERRNO(ECONNREFUSED):
  226. return TOR_TLS_ERROR_CONNREFUSED; // least common
  227. default:
  228. return TOR_TLS_ERROR_MISC;
  229. }
  230. }
  231. #define CATCH_SYSCALL 1
  232. #define CATCH_ZERO 2
  233. /** Given a TLS object and the result of an SSL_* call, use
  234. * SSL_get_error to determine whether an error has occurred, and if so
  235. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  236. * If extra&CATCH_SYSCALL is true, return TOR_TLS_SYSCALL_ instead of
  237. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  238. * TOR_TLS_ZERORETURN_ instead of reporting zero-return errors.
  239. *
  240. * If an error has occurred, log it at level <b>severity</b> and describe the
  241. * current action as <b>doing</b>.
  242. */
  243. int
  244. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  245. const char *doing, int severity, int domain)
  246. {
  247. int err = SSL_get_error(tls->ssl, r);
  248. int tor_error = TOR_TLS_ERROR_MISC;
  249. switch (err) {
  250. case SSL_ERROR_NONE:
  251. return TOR_TLS_DONE;
  252. case SSL_ERROR_WANT_READ:
  253. return TOR_TLS_WANTREAD;
  254. case SSL_ERROR_WANT_WRITE:
  255. return TOR_TLS_WANTWRITE;
  256. case SSL_ERROR_SYSCALL:
  257. if (extra&CATCH_SYSCALL)
  258. return TOR_TLS_SYSCALL_;
  259. if (r == 0) {
  260. tor_log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
  261. doing, SSL_state_string_long(tls->ssl));
  262. tor_error = TOR_TLS_ERROR_IO;
  263. } else {
  264. int e = tor_socket_errno(tls->socket);
  265. tor_log(severity, LD_NET,
  266. "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
  267. doing, e, tor_socket_strerror(e),
  268. SSL_state_string_long(tls->ssl));
  269. tor_error = tor_errno_to_tls_error(e);
  270. }
  271. tls_log_errors(tls, severity, domain, doing);
  272. return tor_error;
  273. case SSL_ERROR_ZERO_RETURN:
  274. if (extra&CATCH_ZERO)
  275. return TOR_TLS_ZERORETURN_;
  276. tor_log(severity, LD_NET, "TLS connection closed while %s in state %s",
  277. doing, SSL_state_string_long(tls->ssl));
  278. tls_log_errors(tls, severity, domain, doing);
  279. return TOR_TLS_CLOSE;
  280. default:
  281. tls_log_errors(tls, severity, domain, doing);
  282. return TOR_TLS_ERROR_MISC;
  283. }
  284. }
  285. /** Initialize OpenSSL, unless it has already been initialized.
  286. */
  287. void
  288. tor_tls_init(void)
  289. {
  290. check_no_tls_errors();
  291. if (!tls_library_is_initialized) {
  292. #ifdef OPENSSL_1_1_API
  293. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
  294. #else
  295. SSL_library_init();
  296. SSL_load_error_strings();
  297. #endif
  298. #if (SIZEOF_VOID_P >= 8 && \
  299. OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,0,1))
  300. long version = OpenSSL_version_num();
  301. /* LCOV_EXCL_START : we can't test these lines on the same machine */
  302. if (version >= OPENSSL_V_SERIES(1,0,1)) {
  303. /* Warn if we could *almost* be running with much faster ECDH.
  304. If we're built for a 64-bit target, using OpenSSL 1.0.1, but we
  305. don't have one of the built-in __uint128-based speedups, we are
  306. just one build operation away from an accelerated handshake.
  307. (We could be looking at OPENSSL_NO_EC_NISTP_64_GCC_128 instead of
  308. doing this test, but that gives compile-time options, not runtime
  309. behavior.)
  310. */
  311. EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  312. const EC_GROUP *g = key ? EC_KEY_get0_group(key) : NULL;
  313. const EC_METHOD *m = g ? EC_GROUP_method_of(g) : NULL;
  314. const int warn = (m == EC_GFp_simple_method() ||
  315. m == EC_GFp_mont_method() ||
  316. m == EC_GFp_nist_method());
  317. EC_KEY_free(key);
  318. if (warn)
  319. log_notice(LD_GENERAL, "We were built to run on a 64-bit CPU, with "
  320. "OpenSSL 1.0.1 or later, but with a version of OpenSSL "
  321. "that apparently lacks accelerated support for the NIST "
  322. "P-224 and P-256 groups. Building openssl with such "
  323. "support (using the enable-ec_nistp_64_gcc_128 option "
  324. "when configuring it) would make ECDH much faster.");
  325. }
  326. /* LCOV_EXCL_STOP */
  327. #endif /* (SIZEOF_VOID_P >= 8 && ... */
  328. tor_tls_allocate_tor_tls_object_ex_data_index();
  329. tls_library_is_initialized = 1;
  330. }
  331. }
  332. /** We need to give OpenSSL a callback to verify certificates. This is
  333. * it: We always accept peer certs and complete the handshake. We
  334. * don't validate them until later.
  335. */
  336. int
  337. always_accept_verify_cb(int preverify_ok,
  338. X509_STORE_CTX *x509_ctx)
  339. {
  340. (void) preverify_ok;
  341. (void) x509_ctx;
  342. return 1;
  343. }
  344. /** List of ciphers that servers should select from when the client might be
  345. * claiming extra unsupported ciphers in order to avoid fingerprinting. */
  346. static const char SERVER_CIPHER_LIST[] =
  347. #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
  348. /* This one can never actually get selected, since if the client lists it,
  349. * we will assume that the client is honest, and not use this list.
  350. * Nonetheless we list it if it's available, so that the server doesn't
  351. * conclude that it has no valid ciphers if it's running with TLS1.3.
  352. */
  353. TLS1_3_TXT_AES_128_GCM_SHA256 ":"
  354. #endif
  355. TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
  356. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA;
  357. /** List of ciphers that servers should select from when we actually have
  358. * our choice of what cipher to use. */
  359. static const char UNRESTRICTED_SERVER_CIPHER_LIST[] =
  360. /* Here are the TLS 1.3 ciphers we like, in the order we prefer. */
  361. #ifdef TLS1_3_TXT_AES_256_GCM_SHA384
  362. TLS1_3_TXT_AES_256_GCM_SHA384 ":"
  363. #endif
  364. #ifdef TLS1_3_TXT_CHACHA20_POLY1305_SHA256
  365. TLS1_3_TXT_CHACHA20_POLY1305_SHA256 ":"
  366. #endif
  367. #ifdef TLS1_3_TXT_AES_128_GCM_SHA256
  368. TLS1_3_TXT_AES_128_GCM_SHA256 ":"
  369. #endif
  370. #ifdef TLS1_3_TXT_AES_128_CCM_SHA256
  371. TLS1_3_TXT_AES_128_CCM_SHA256 ":"
  372. #endif
  373. /* This list is autogenerated with the gen_server_ciphers.py script;
  374. * don't hand-edit it. */
  375. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384
  376. TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ":"
  377. #endif
  378. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  379. TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ":"
  380. #endif
  381. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384
  382. TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 ":"
  383. #endif
  384. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256
  385. TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 ":"
  386. #endif
  387. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA
  388. TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":"
  389. #endif
  390. #ifdef TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA
  391. TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":"
  392. #endif
  393. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384
  394. TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 ":"
  395. #endif
  396. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256
  397. TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 ":"
  398. #endif
  399. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_CCM
  400. TLS1_TXT_DHE_RSA_WITH_AES_256_CCM ":"
  401. #endif
  402. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_CCM
  403. TLS1_TXT_DHE_RSA_WITH_AES_128_CCM ":"
  404. #endif
  405. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256
  406. TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 ":"
  407. #endif
  408. #ifdef TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256
  409. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 ":"
  410. #endif
  411. /* Required */
  412. TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":"
  413. /* Required */
  414. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":"
  415. #ifdef TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305
  416. TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 ":"
  417. #endif
  418. #ifdef TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
  419. TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305
  420. #endif
  421. ;
  422. /* Note: to set up your own private testing network with link crypto
  423. * disabled, set your Tors' cipher list to
  424. * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
  425. * with any of the "real" Tors, though. */
  426. #define CIPHER(id, name) name ":"
  427. #define XCIPHER(id, name)
  428. /** List of ciphers that clients should advertise, omitting items that
  429. * our OpenSSL doesn't know about. */
  430. static const char CLIENT_CIPHER_LIST[] =
  431. #include "ciphers.inc"
  432. /* Tell it not to use SSLv2 ciphers, so that it can select an SSLv3 version
  433. * of any cipher we say. */
  434. "!SSLv2"
  435. ;
  436. #undef CIPHER
  437. #undef XCIPHER
  438. /** Set *<b>link_cert_out</b> and *<b>id_cert_out</b> to the link certificate
  439. * and ID certificate that we're currently using for our V3 in-protocol
  440. * handshake's certificate chain. If <b>server</b> is true, provide the certs
  441. * that we use in server mode (auth, ID); otherwise, provide the certs that we
  442. * use in client mode. (link, ID) */
  443. int
  444. tor_tls_get_my_certs(int server,
  445. const tor_x509_cert_t **link_cert_out,
  446. const tor_x509_cert_t **id_cert_out)
  447. {
  448. tor_tls_context_t *ctx = tor_tls_context_get(server);
  449. if (! ctx)
  450. return -1;
  451. if (link_cert_out)
  452. *link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
  453. if (id_cert_out)
  454. *id_cert_out = ctx->my_id_cert;
  455. return 0;
  456. }
  457. /**
  458. * Return the authentication key that we use to authenticate ourselves as a
  459. * client in the V3 in-protocol handshake.
  460. */
  461. crypto_pk_t *
  462. tor_tls_get_my_client_auth_key(void)
  463. {
  464. tor_tls_context_t *context = tor_tls_context_get(0);
  465. if (! context)
  466. return NULL;
  467. return context->auth_key;
  468. }
  469. /** Return true iff the other side of <b>tls</b> has authenticated to us, and
  470. * the key certified in <b>cert</b> is the same as the key they used to do it.
  471. */
  472. MOCK_IMPL(int,
  473. tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
  474. {
  475. X509 *peercert = SSL_get_peer_certificate(tls->ssl);
  476. EVP_PKEY *link_key = NULL, *cert_key = NULL;
  477. int result;
  478. if (!peercert)
  479. return 0;
  480. link_key = X509_get_pubkey(peercert);
  481. cert_key = X509_get_pubkey((X509 *)tor_x509_cert_get_impl(cert));
  482. result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
  483. X509_free(peercert);
  484. if (link_key)
  485. EVP_PKEY_free(link_key);
  486. if (cert_key)
  487. EVP_PKEY_free(cert_key);
  488. return result;
  489. }
  490. /** Create a new global TLS context.
  491. *
  492. * You can call this function multiple times. Each time you call it,
  493. * it generates new certificates; all new connections will use
  494. * the new SSL context.
  495. */
  496. int
  497. tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  498. crypto_pk_t *identity,
  499. unsigned int key_lifetime,
  500. unsigned int flags,
  501. int is_client)
  502. {
  503. tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
  504. key_lifetime,
  505. flags,
  506. is_client);
  507. tor_tls_context_t *old_ctx = *ppcontext;
  508. if (new_ctx != NULL) {
  509. *ppcontext = new_ctx;
  510. /* Free the old context if one existed. */
  511. if (old_ctx != NULL) {
  512. /* This is safe even if there are open connections: we reference-
  513. * count tor_tls_context_t objects. */
  514. tor_tls_context_decref(old_ctx);
  515. }
  516. }
  517. return ((new_ctx != NULL) ? 0 : -1);
  518. }
  519. void
  520. tor_tls_context_impl_free(struct ssl_ctx_st *ctx)
  521. {
  522. if (!ctx)
  523. return;
  524. SSL_CTX_free(ctx);
  525. }
  526. /** The group we should use for ecdhe when none was selected. */
  527. #define NID_tor_default_ecdhe_group NID_X9_62_prime256v1
  528. #define RSA_LINK_KEY_BITS 2048
  529. /** Create a new TLS context for use with Tor TLS handshakes.
  530. * <b>identity</b> should be set to the identity key used to sign the
  531. * certificate.
  532. */
  533. tor_tls_context_t *
  534. tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
  535. unsigned flags, int is_client)
  536. {
  537. crypto_pk_t *rsa = NULL, *rsa_auth = NULL;
  538. EVP_PKEY *pkey = NULL;
  539. tor_tls_context_t *result = NULL;
  540. X509 *cert = NULL, *idcert = NULL, *authcert = NULL;
  541. char *nickname = NULL, *nn2 = NULL;
  542. tor_tls_init();
  543. nickname = crypto_random_hostname(8, 20, "www.", ".net");
  544. #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
  545. nn2 = crypto_random_hostname(8, 20, "www.", ".net");
  546. #else
  547. nn2 = crypto_random_hostname(8, 20, "www.", ".com");
  548. #endif
  549. /* Generate short-term RSA key for use with TLS. */
  550. if (!(rsa = crypto_pk_new()))
  551. goto error;
  552. if (crypto_pk_generate_key_with_bits(rsa, RSA_LINK_KEY_BITS)<0)
  553. goto error;
  554. if (!is_client) {
  555. /* Generate short-term RSA key for use in the in-protocol ("v3")
  556. * authentication handshake. */
  557. if (!(rsa_auth = crypto_pk_new()))
  558. goto error;
  559. if (crypto_pk_generate_key(rsa_auth)<0)
  560. goto error;
  561. /* Create a link certificate signed by identity key. */
  562. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  563. key_lifetime);
  564. /* Create self-signed certificate for identity key. */
  565. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  566. IDENTITY_CERT_LIFETIME);
  567. /* Create an authentication certificate signed by identity key. */
  568. authcert = tor_tls_create_certificate(rsa_auth, identity, nickname, nn2,
  569. key_lifetime);
  570. if (!cert || !idcert || !authcert) {
  571. log_warn(LD_CRYPTO, "Error creating certificate");
  572. goto error;
  573. }
  574. }
  575. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  576. result->refcnt = 1;
  577. if (!is_client) {
  578. result->my_link_cert = tor_x509_cert_new(X509_dup(cert));
  579. result->my_id_cert = tor_x509_cert_new(X509_dup(idcert));
  580. result->my_auth_cert = tor_x509_cert_new(X509_dup(authcert));
  581. if (!result->my_link_cert || !result->my_id_cert || !result->my_auth_cert)
  582. goto error;
  583. result->link_key = crypto_pk_dup_key(rsa);
  584. result->auth_key = crypto_pk_dup_key(rsa_auth);
  585. }
  586. #if 0
  587. /* Tell OpenSSL to only use TLS1. This may have subtly different results
  588. * from SSLv23_method() with SSLv2 and SSLv3 disabled, so we need to do some
  589. * investigation before we consider adjusting it. It should be compatible
  590. * with existing Tors. */
  591. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  592. goto error;
  593. #endif /* 0 */
  594. /* Tell OpenSSL to use TLS 1.0 or later but not SSL2 or SSL3. */
  595. #ifdef HAVE_TLS_METHOD
  596. if (!(result->ctx = SSL_CTX_new(TLS_method())))
  597. goto error;
  598. #else
  599. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  600. goto error;
  601. #endif /* defined(HAVE_TLS_METHOD) */
  602. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  603. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
  604. /* Prefer the server's ordering of ciphers: the client's ordering has
  605. * historically been chosen for fingerprinting resistance. */
  606. SSL_CTX_set_options(result->ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  607. /* Disable TLS tickets if they're supported. We never want to use them;
  608. * using them can make our perfect forward secrecy a little worse, *and*
  609. * create an opportunity to fingerprint us (since it's unusual to use them
  610. * with TLS sessions turned off).
  611. *
  612. * In 0.2.4, clients advertise support for them though, to avoid a TLS
  613. * distinguishability vector. This can give us worse PFS, though, if we
  614. * get a server that doesn't set SSL_OP_NO_TICKET. With luck, there will
  615. * be few such servers by the time 0.2.4 is more stable.
  616. */
  617. #ifdef SSL_OP_NO_TICKET
  618. if (! is_client) {
  619. SSL_CTX_set_options(result->ctx, SSL_OP_NO_TICKET);
  620. }
  621. #endif
  622. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  623. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_ECDH_USE);
  624. #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  625. SSL_CTX_set_options(result->ctx,
  626. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  627. #endif
  628. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  629. * as authenticating any earlier-received data.
  630. */
  631. {
  632. SSL_CTX_set_options(result->ctx,
  633. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  634. }
  635. /* Don't actually allow compression; it uses RAM and time, it makes TLS
  636. * vulnerable to CRIME-style attacks, and most of the data we transmit over
  637. * TLS is encrypted (and therefore uncompressible) anyway. */
  638. #ifdef SSL_OP_NO_COMPRESSION
  639. SSL_CTX_set_options(result->ctx, SSL_OP_NO_COMPRESSION);
  640. #endif
  641. #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0)
  642. #ifndef OPENSSL_NO_COMP
  643. if (result->ctx->comp_methods)
  644. result->ctx->comp_methods = NULL;
  645. #endif
  646. #endif /* OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(1,1,0) */
  647. #ifdef SSL_MODE_RELEASE_BUFFERS
  648. SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
  649. #endif
  650. if (! is_client) {
  651. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  652. goto error;
  653. X509_free(cert); /* We just added a reference to cert. */
  654. cert=NULL;
  655. if (idcert) {
  656. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  657. tor_assert(s);
  658. X509_STORE_add_cert(s, idcert);
  659. X509_free(idcert); /* The context now owns the reference to idcert */
  660. idcert = NULL;
  661. }
  662. }
  663. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  664. if (!is_client) {
  665. tor_assert(rsa);
  666. if (!(pkey = crypto_pk_get_openssl_evp_pkey_(rsa,1)))
  667. goto error;
  668. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  669. goto error;
  670. EVP_PKEY_free(pkey);
  671. pkey = NULL;
  672. if (!SSL_CTX_check_private_key(result->ctx))
  673. goto error;
  674. }
  675. {
  676. DH *dh = crypto_dh_new_openssl_tls();
  677. tor_assert(dh);
  678. SSL_CTX_set_tmp_dh(result->ctx, dh);
  679. DH_free(dh);
  680. }
  681. if (! is_client) {
  682. int nid;
  683. EC_KEY *ec_key;
  684. if (flags & TOR_TLS_CTX_USE_ECDHE_P224)
  685. nid = NID_secp224r1;
  686. else if (flags & TOR_TLS_CTX_USE_ECDHE_P256)
  687. nid = NID_X9_62_prime256v1;
  688. else
  689. nid = NID_tor_default_ecdhe_group;
  690. /* Use P-256 for ECDHE. */
  691. ec_key = EC_KEY_new_by_curve_name(nid);
  692. if (ec_key != NULL) /*XXXX Handle errors? */
  693. SSL_CTX_set_tmp_ecdh(result->ctx, ec_key);
  694. EC_KEY_free(ec_key);
  695. }
  696. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  697. always_accept_verify_cb);
  698. /* let us realloc bufs that we're writing from */
  699. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  700. if (rsa)
  701. crypto_pk_free(rsa);
  702. if (rsa_auth)
  703. crypto_pk_free(rsa_auth);
  704. X509_free(authcert);
  705. tor_free(nickname);
  706. tor_free(nn2);
  707. return result;
  708. error:
  709. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
  710. tor_free(nickname);
  711. tor_free(nn2);
  712. if (pkey)
  713. EVP_PKEY_free(pkey);
  714. if (rsa)
  715. crypto_pk_free(rsa);
  716. if (rsa_auth)
  717. crypto_pk_free(rsa_auth);
  718. if (result)
  719. tor_tls_context_decref(result);
  720. if (cert)
  721. X509_free(cert);
  722. if (idcert)
  723. X509_free(idcert);
  724. if (authcert)
  725. X509_free(authcert);
  726. return NULL;
  727. }
  728. /** Invoked when a TLS state changes: log the change at severity 'debug' */
  729. void
  730. tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
  731. {
  732. /* LCOV_EXCL_START since this depends on whether debug is captured or not */
  733. log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
  734. ssl, SSL_state_string_long(ssl), type, val);
  735. /* LCOV_EXCL_STOP */
  736. }
  737. /* Return the name of the negotiated ciphersuite in use on <b>tls</b> */
  738. const char *
  739. tor_tls_get_ciphersuite_name(tor_tls_t *tls)
  740. {
  741. return SSL_get_cipher(tls->ssl);
  742. }
  743. /* Here's the old V2 cipher list we sent from 0.2.1.1-alpha up to
  744. * 0.2.3.17-beta. If a client is using this list, we can't believe the ciphers
  745. * that it claims to support. We'll prune this list to remove the ciphers
  746. * *we* don't recognize. */
  747. STATIC uint16_t v2_cipher_list[] = {
  748. 0xc00a, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA */
  749. 0xc014, /* TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA */
  750. 0x0039, /* TLS1_TXT_DHE_RSA_WITH_AES_256_SHA */
  751. 0x0038, /* TLS1_TXT_DHE_DSS_WITH_AES_256_SHA */
  752. 0xc00f, /* TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA */
  753. 0xc005, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA */
  754. 0x0035, /* TLS1_TXT_RSA_WITH_AES_256_SHA */
  755. 0xc007, /* TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA */
  756. 0xc009, /* TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA */
  757. 0xc011, /* TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA */
  758. 0xc013, /* TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA */
  759. 0x0033, /* TLS1_TXT_DHE_RSA_WITH_AES_128_SHA */
  760. 0x0032, /* TLS1_TXT_DHE_DSS_WITH_AES_128_SHA */
  761. 0xc00c, /* TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA */
  762. 0xc00e, /* TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA */
  763. 0xc002, /* TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA */
  764. 0xc004, /* TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA */
  765. 0x0004, /* SSL3_TXT_RSA_RC4_128_MD5 */
  766. 0x0005, /* SSL3_TXT_RSA_RC4_128_SHA */
  767. 0x002f, /* TLS1_TXT_RSA_WITH_AES_128_SHA */
  768. 0xc008, /* TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA */
  769. 0xc012, /* TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA */
  770. 0x0016, /* SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA */
  771. 0x0013, /* SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA */
  772. 0xc00d, /* TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA */
  773. 0xc003, /* TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA */
  774. 0xfeff, /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA */
  775. 0x000a, /* SSL3_TXT_RSA_DES_192_CBC3_SHA */
  776. 0
  777. };
  778. /** Have we removed the unrecognized ciphers from v2_cipher_list yet? */
  779. static int v2_cipher_list_pruned = 0;
  780. /** Return 0 if <b>m</b> does not support the cipher with ID <b>cipher</b>;
  781. * return 1 if it does support it, or if we have no way to tell. */
  782. int
  783. find_cipher_by_id(const SSL *ssl, const SSL_METHOD *m, uint16_t cipher)
  784. {
  785. const SSL_CIPHER *c;
  786. #ifdef HAVE_SSL_CIPHER_FIND
  787. (void) m;
  788. {
  789. unsigned char cipherid[3];
  790. tor_assert(ssl);
  791. set_uint16(cipherid, tor_htons(cipher));
  792. cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
  793. * with a two-byte 'cipherid', it may look for a v2
  794. * cipher with the appropriate 3 bytes. */
  795. c = SSL_CIPHER_find((SSL*)ssl, cipherid);
  796. if (c)
  797. tor_assert((SSL_CIPHER_get_id(c) & 0xffff) == cipher);
  798. return c != NULL;
  799. }
  800. #else /* !(defined(HAVE_SSL_CIPHER_FIND)) */
  801. # if defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR)
  802. if (m && m->get_cipher_by_char) {
  803. unsigned char cipherid[3];
  804. set_uint16(cipherid, tor_htons(cipher));
  805. cipherid[2] = 0; /* If ssl23_get_cipher_by_char finds no cipher starting
  806. * with a two-byte 'cipherid', it may look for a v2
  807. * cipher with the appropriate 3 bytes. */
  808. c = m->get_cipher_by_char(cipherid);
  809. if (c)
  810. tor_assert((c->id & 0xffff) == cipher);
  811. return c != NULL;
  812. }
  813. #endif /* defined(HAVE_STRUCT_SSL_METHOD_ST_GET_CIPHER_BY_CHAR) */
  814. # ifndef OPENSSL_1_1_API
  815. if (m && m->get_cipher && m->num_ciphers) {
  816. /* It would seem that some of the "let's-clean-up-openssl" forks have
  817. * removed the get_cipher_by_char function. Okay, so now you get a
  818. * quadratic search.
  819. */
  820. int i;
  821. for (i = 0; i < m->num_ciphers(); ++i) {
  822. c = m->get_cipher(i);
  823. if (c && (c->id & 0xffff) == cipher) {
  824. return 1;
  825. }
  826. }
  827. return 0;
  828. }
  829. #endif /* !defined(OPENSSL_1_1_API) */
  830. (void) ssl;
  831. (void) m;
  832. (void) cipher;
  833. return 1; /* No way to search */
  834. #endif /* defined(HAVE_SSL_CIPHER_FIND) */
  835. }
  836. /** Remove from v2_cipher_list every cipher that we don't support, so that
  837. * comparing v2_cipher_list to a client's cipher list will give a sensible
  838. * result. */
  839. static void
  840. prune_v2_cipher_list(const SSL *ssl)
  841. {
  842. uint16_t *inp, *outp;
  843. #ifdef HAVE_TLS_METHOD
  844. const SSL_METHOD *m = TLS_method();
  845. #else
  846. const SSL_METHOD *m = SSLv23_method();
  847. #endif
  848. inp = outp = v2_cipher_list;
  849. while (*inp) {
  850. if (find_cipher_by_id(ssl, m, *inp)) {
  851. *outp++ = *inp++;
  852. } else {
  853. inp++;
  854. }
  855. }
  856. *outp = 0;
  857. v2_cipher_list_pruned = 1;
  858. }
  859. /** Examine the client cipher list in <b>ssl</b>, and determine what kind of
  860. * client it is. Return one of CIPHERS_ERR, CIPHERS_V1, CIPHERS_V2,
  861. * CIPHERS_UNRESTRICTED.
  862. **/
  863. int
  864. tor_tls_classify_client_ciphers(const SSL *ssl,
  865. STACK_OF(SSL_CIPHER) *peer_ciphers)
  866. {
  867. int i, res;
  868. tor_tls_t *tor_tls;
  869. if (PREDICT_UNLIKELY(!v2_cipher_list_pruned))
  870. prune_v2_cipher_list(ssl);
  871. tor_tls = tor_tls_get_by_ssl(ssl);
  872. if (tor_tls && tor_tls->client_cipher_list_type)
  873. return tor_tls->client_cipher_list_type;
  874. /* If we reached this point, we just got a client hello. See if there is
  875. * a cipher list. */
  876. if (!peer_ciphers) {
  877. log_info(LD_NET, "No ciphers on session");
  878. res = CIPHERS_ERR;
  879. goto done;
  880. }
  881. /* Now we need to see if there are any ciphers whose presence means we're
  882. * dealing with an updated Tor. */
  883. for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
  884. const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
  885. const char *ciphername = SSL_CIPHER_get_name(cipher);
  886. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  887. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  888. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  889. strcmp(ciphername, "(NONE)")) {
  890. log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
  891. // return 1;
  892. goto v2_or_higher;
  893. }
  894. }
  895. res = CIPHERS_V1;
  896. goto done;
  897. v2_or_higher:
  898. {
  899. const uint16_t *v2_cipher = v2_cipher_list;
  900. for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
  901. const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
  902. uint16_t id = SSL_CIPHER_get_id(cipher) & 0xffff;
  903. if (id == 0x00ff) /* extended renegotiation indicator. */
  904. continue;
  905. if (!id || id != *v2_cipher) {
  906. res = CIPHERS_UNRESTRICTED;
  907. goto dump_ciphers;
  908. }
  909. ++v2_cipher;
  910. }
  911. if (*v2_cipher != 0) {
  912. res = CIPHERS_UNRESTRICTED;
  913. goto dump_ciphers;
  914. }
  915. res = CIPHERS_V2;
  916. }
  917. dump_ciphers:
  918. {
  919. smartlist_t *elts = smartlist_new();
  920. char *s;
  921. for (i = 0; i < sk_SSL_CIPHER_num(peer_ciphers); ++i) {
  922. const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(peer_ciphers, i);
  923. const char *ciphername = SSL_CIPHER_get_name(cipher);
  924. smartlist_add(elts, (char*)ciphername);
  925. }
  926. s = smartlist_join_strings(elts, ":", 0, NULL);
  927. log_debug(LD_NET, "Got a %s V2/V3 cipher list from %s. It is: '%s'",
  928. (res == CIPHERS_V2) ? "fictitious" : "real", ADDR(tor_tls), s);
  929. tor_free(s);
  930. smartlist_free(elts);
  931. }
  932. done:
  933. if (tor_tls)
  934. return tor_tls->client_cipher_list_type = res;
  935. return res;
  936. }
  937. /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
  938. * a list that indicates that the client knows how to do the v2 TLS connection
  939. * handshake. */
  940. int
  941. tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
  942. {
  943. STACK_OF(SSL_CIPHER) *ciphers;
  944. #ifdef HAVE_SSL_GET_CLIENT_CIPHERS
  945. ciphers = SSL_get_client_ciphers(ssl);
  946. #else
  947. SSL_SESSION *session;
  948. if (!(session = SSL_get_session((SSL *)ssl))) {
  949. log_info(LD_NET, "No session on TLS?");
  950. return CIPHERS_ERR;
  951. }
  952. ciphers = session->ciphers;
  953. #endif /* defined(HAVE_SSL_GET_CLIENT_CIPHERS) */
  954. return tor_tls_classify_client_ciphers(ssl, ciphers) >= CIPHERS_V2;
  955. }
  956. /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
  957. * changes state. We use this:
  958. * <ul><li>To alter the state of the handshake partway through, so we
  959. * do not send or request extra certificates in v2 handshakes.</li>
  960. * <li>To detect renegotiation</li></ul>
  961. */
  962. void
  963. tor_tls_server_info_callback(const SSL *ssl, int type, int val)
  964. {
  965. tor_tls_t *tls;
  966. (void) val;
  967. IF_BUG_ONCE(ssl == NULL) {
  968. return; // LCOV_EXCL_LINE
  969. }
  970. tor_tls_debug_state_callback(ssl, type, val);
  971. if (type != SSL_CB_ACCEPT_LOOP)
  972. return;
  973. OSSL_HANDSHAKE_STATE ssl_state = SSL_get_state(ssl);
  974. if (! STATE_IS_SW_SERVER_HELLO(ssl_state))
  975. return;
  976. tls = tor_tls_get_by_ssl(ssl);
  977. if (tls) {
  978. /* Check whether we're watching for renegotiates. If so, this is one! */
  979. if (tls->negotiated_callback)
  980. tls->got_renegotiate = 1;
  981. if (tls->server_handshake_count < 127) /*avoid any overflow possibility*/
  982. ++tls->server_handshake_count;
  983. } else {
  984. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  985. return;
  986. }
  987. /* Now check the cipher list. */
  988. if (tor_tls_client_is_using_v2_ciphers(ssl)) {
  989. if (tls->wasV2Handshake)
  990. return; /* We already turned this stuff off for the first handshake;
  991. * This is a renegotiation. */
  992. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  993. * Let's hope openssl doesn't notice! */
  994. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  995. SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
  996. /* Don't send a hello request. */
  997. SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
  998. if (tls) {
  999. tls->wasV2Handshake = 1;
  1000. } else {
  1001. /* LCOV_EXCL_START this line is not reachable */
  1002. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  1003. /* LCOV_EXCL_STOP */
  1004. }
  1005. }
  1006. }
  1007. /** Callback to get invoked on a server after we've read the list of ciphers
  1008. * the client supports, but before we pick our own ciphersuite.
  1009. *
  1010. * We can't abuse an info_cb for this, since by the time one of the
  1011. * client_hello info_cbs is called, we've already picked which ciphersuite to
  1012. * use.
  1013. *
  1014. * Technically, this function is an abuse of this callback, since the point of
  1015. * a session_secret_cb is to try to set up and/or verify a shared-secret for
  1016. * authentication on the fly. But as long as we return 0, we won't actually be
  1017. * setting up a shared secret, and all will be fine.
  1018. */
  1019. int
  1020. tor_tls_session_secret_cb(SSL *ssl, void *secret, int *secret_len,
  1021. STACK_OF(SSL_CIPHER) *peer_ciphers,
  1022. CONST_IF_OPENSSL_1_1_API SSL_CIPHER **cipher,
  1023. void *arg)
  1024. {
  1025. (void) secret;
  1026. (void) secret_len;
  1027. (void) peer_ciphers;
  1028. (void) cipher;
  1029. (void) arg;
  1030. if (tor_tls_classify_client_ciphers(ssl, peer_ciphers) ==
  1031. CIPHERS_UNRESTRICTED) {
  1032. SSL_set_cipher_list(ssl, UNRESTRICTED_SERVER_CIPHER_LIST);
  1033. }
  1034. SSL_set_session_secret_cb(ssl, NULL, NULL);
  1035. return 0;
  1036. }
  1037. static void
  1038. tor_tls_setup_session_secret_cb(tor_tls_t *tls)
  1039. {
  1040. SSL_set_session_secret_cb(tls->ssl, tor_tls_session_secret_cb, NULL);
  1041. }
  1042. /** Create a new TLS object from a file descriptor, and a flag to
  1043. * determine whether it is functioning as a server.
  1044. */
  1045. tor_tls_t *
  1046. tor_tls_new(int sock, int isServer)
  1047. {
  1048. BIO *bio = NULL;
  1049. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  1050. tor_tls_context_t *context = tor_tls_context_get(isServer);
  1051. result->magic = TOR_TLS_MAGIC;
  1052. check_no_tls_errors();
  1053. tor_assert(context); /* make sure somebody made it first */
  1054. if (!(result->ssl = SSL_new(context->ctx))) {
  1055. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
  1056. tor_free(result);
  1057. goto err;
  1058. }
  1059. #ifdef SSL_set_tlsext_host_name
  1060. /* Browsers use the TLS hostname extension, so we should too. */
  1061. if (!isServer) {
  1062. char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
  1063. SSL_set_tlsext_host_name(result->ssl, fake_hostname);
  1064. tor_free(fake_hostname);
  1065. }
  1066. #endif /* defined(SSL_set_tlsext_host_name) */
  1067. if (!SSL_set_cipher_list(result->ssl,
  1068. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  1069. tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
  1070. #ifdef SSL_set_tlsext_host_name
  1071. SSL_set_tlsext_host_name(result->ssl, NULL);
  1072. #endif
  1073. SSL_free(result->ssl);
  1074. tor_free(result);
  1075. goto err;
  1076. }
  1077. result->socket = sock;
  1078. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1079. if (! bio) {
  1080. tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
  1081. #ifdef SSL_set_tlsext_host_name
  1082. SSL_set_tlsext_host_name(result->ssl, NULL);
  1083. #endif
  1084. SSL_free(result->ssl);
  1085. tor_free(result);
  1086. goto err;
  1087. }
  1088. {
  1089. int set_worked =
  1090. SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
  1091. if (!set_worked) {
  1092. log_warn(LD_BUG,
  1093. "Couldn't set the tls for an SSL*; connection will fail");
  1094. }
  1095. }
  1096. SSL_set_bio(result->ssl, bio, bio);
  1097. tor_tls_context_incref(context);
  1098. result->context = context;
  1099. result->state = TOR_TLS_ST_HANDSHAKE;
  1100. result->isServer = isServer;
  1101. result->wantwrite_n = 0;
  1102. result->last_write_count = (unsigned long) BIO_number_written(bio);
  1103. result->last_read_count = (unsigned long) BIO_number_read(bio);
  1104. if (result->last_write_count || result->last_read_count) {
  1105. log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
  1106. result->last_read_count, result->last_write_count);
  1107. }
  1108. if (isServer) {
  1109. SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
  1110. } else {
  1111. SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
  1112. }
  1113. if (isServer)
  1114. tor_tls_setup_session_secret_cb(result);
  1115. goto done;
  1116. err:
  1117. result = NULL;
  1118. done:
  1119. /* Not expected to get called. */
  1120. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
  1121. return result;
  1122. }
  1123. /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
  1124. * next gets a client-side renegotiate in the middle of a read. Do not
  1125. * invoke this function until <em>after</em> initial handshaking is done!
  1126. */
  1127. void
  1128. tor_tls_set_renegotiate_callback(tor_tls_t *tls,
  1129. void (*cb)(tor_tls_t *, void *arg),
  1130. void *arg)
  1131. {
  1132. tls->negotiated_callback = cb;
  1133. tls->callback_arg = arg;
  1134. tls->got_renegotiate = 0;
  1135. if (cb) {
  1136. SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
  1137. } else {
  1138. SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
  1139. }
  1140. }
  1141. /** If this version of openssl requires it, turn on renegotiation on
  1142. * <b>tls</b>.
  1143. */
  1144. void
  1145. tor_tls_unblock_renegotiation(tor_tls_t *tls)
  1146. {
  1147. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1148. * as authenticating any earlier-received data. */
  1149. SSL_set_options(tls->ssl,
  1150. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1151. }
  1152. /** If this version of openssl supports it, turn off renegotiation on
  1153. * <b>tls</b>. (Our protocol never requires this for security, but it's nice
  1154. * to use belt-and-suspenders here.)
  1155. */
  1156. void
  1157. tor_tls_block_renegotiation(tor_tls_t *tls)
  1158. {
  1159. #ifdef SUPPORT_UNSAFE_RENEGOTIATION_FLAG
  1160. tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1161. #else
  1162. (void) tls;
  1163. #endif
  1164. }
  1165. /** Assert that the flags that allow legacy renegotiation are still set */
  1166. void
  1167. tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
  1168. {
  1169. #if defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) && \
  1170. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION != 0
  1171. long options = SSL_get_options(tls->ssl);
  1172. tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1173. #else
  1174. (void) tls;
  1175. #endif /* defined(SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) && ... */
  1176. }
  1177. /** Release resources associated with a TLS object. Does not close the
  1178. * underlying file descriptor.
  1179. */
  1180. void
  1181. tor_tls_free_(tor_tls_t *tls)
  1182. {
  1183. if (!tls)
  1184. return;
  1185. tor_assert(tls->ssl);
  1186. {
  1187. size_t r,w;
  1188. tor_tls_get_n_raw_bytes(tls,&r,&w); /* ensure written_by_tls is updated */
  1189. }
  1190. #ifdef SSL_set_tlsext_host_name
  1191. SSL_set_tlsext_host_name(tls->ssl, NULL);
  1192. #endif
  1193. SSL_free(tls->ssl);
  1194. tls->ssl = NULL;
  1195. tls->negotiated_callback = NULL;
  1196. if (tls->context)
  1197. tor_tls_context_decref(tls->context);
  1198. tor_free(tls->address);
  1199. tls->magic = 0x99999999;
  1200. tor_free(tls);
  1201. }
  1202. /** Underlying function for TLS reading. Reads up to <b>len</b>
  1203. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  1204. * number of characters read. On failure, returns TOR_TLS_ERROR,
  1205. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1206. */
  1207. MOCK_IMPL(int,
  1208. tor_tls_read,(tor_tls_t *tls, char *cp, size_t len))
  1209. {
  1210. int r, err;
  1211. tor_assert(tls);
  1212. tor_assert(tls->ssl);
  1213. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1214. tor_assert(len<INT_MAX);
  1215. r = SSL_read(tls->ssl, cp, (int)len);
  1216. if (r > 0) {
  1217. if (tls->got_renegotiate) {
  1218. /* Renegotiation happened! */
  1219. log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
  1220. if (tls->negotiated_callback)
  1221. tls->negotiated_callback(tls, tls->callback_arg);
  1222. tls->got_renegotiate = 0;
  1223. }
  1224. return r;
  1225. }
  1226. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
  1227. if (err == TOR_TLS_ZERORETURN_ || err == TOR_TLS_CLOSE) {
  1228. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  1229. tls->state = TOR_TLS_ST_CLOSED;
  1230. return TOR_TLS_CLOSE;
  1231. } else {
  1232. tor_assert(err != TOR_TLS_DONE);
  1233. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  1234. return err;
  1235. }
  1236. }
  1237. /** Total number of bytes that we've used TLS to send. Used to track TLS
  1238. * overhead. */
  1239. STATIC uint64_t total_bytes_written_over_tls = 0;
  1240. /** Total number of bytes that TLS has put on the network for us. Used to
  1241. * track TLS overhead. */
  1242. STATIC uint64_t total_bytes_written_by_tls = 0;
  1243. /** Underlying function for TLS writing. Write up to <b>n</b>
  1244. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  1245. * number of characters written. On failure, returns TOR_TLS_ERROR,
  1246. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1247. */
  1248. int
  1249. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  1250. {
  1251. int r, err;
  1252. tor_assert(tls);
  1253. tor_assert(tls->ssl);
  1254. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1255. tor_assert(n < INT_MAX);
  1256. if (n == 0)
  1257. return 0;
  1258. if (tls->wantwrite_n) {
  1259. /* if WANTWRITE last time, we must use the _same_ n as before */
  1260. tor_assert(n >= tls->wantwrite_n);
  1261. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  1262. (int)n, (int)tls->wantwrite_n);
  1263. n = tls->wantwrite_n;
  1264. tls->wantwrite_n = 0;
  1265. }
  1266. r = SSL_write(tls->ssl, cp, (int)n);
  1267. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
  1268. if (err == TOR_TLS_DONE) {
  1269. total_bytes_written_over_tls += r;
  1270. return r;
  1271. }
  1272. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  1273. tls->wantwrite_n = n;
  1274. }
  1275. return err;
  1276. }
  1277. /** Perform initial handshake on <b>tls</b>. When finished, returns
  1278. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1279. * or TOR_TLS_WANTWRITE.
  1280. */
  1281. int
  1282. tor_tls_handshake(tor_tls_t *tls)
  1283. {
  1284. int r;
  1285. tor_assert(tls);
  1286. tor_assert(tls->ssl);
  1287. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  1288. check_no_tls_errors();
  1289. OSSL_HANDSHAKE_STATE oldstate = SSL_get_state(tls->ssl);
  1290. if (tls->isServer) {
  1291. log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
  1292. SSL_state_string_long(tls->ssl));
  1293. r = SSL_accept(tls->ssl);
  1294. } else {
  1295. log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
  1296. SSL_state_string_long(tls->ssl));
  1297. r = SSL_connect(tls->ssl);
  1298. }
  1299. OSSL_HANDSHAKE_STATE newstate = SSL_get_state(tls->ssl);
  1300. if (oldstate != newstate)
  1301. log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
  1302. tls, SSL_state_string_long(tls->ssl));
  1303. /* We need to call this here and not earlier, since OpenSSL has a penchant
  1304. * for clearing its flags when you say accept or connect. */
  1305. tor_tls_unblock_renegotiation(tls);
  1306. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
  1307. if (ERR_peek_error() != 0) {
  1308. tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
  1309. "handshaking");
  1310. return TOR_TLS_ERROR_MISC;
  1311. }
  1312. if (r == TOR_TLS_DONE) {
  1313. tls->state = TOR_TLS_ST_OPEN;
  1314. return tor_tls_finish_handshake(tls);
  1315. }
  1316. return r;
  1317. }
  1318. /** Perform the final part of the initial TLS handshake on <b>tls</b>. This
  1319. * should be called for the first handshake only: it determines whether the v1
  1320. * or the v2 handshake was used, and adjusts things for the renegotiation
  1321. * handshake as appropriate.
  1322. *
  1323. * tor_tls_handshake() calls this on its own; you only need to call this if
  1324. * bufferevent is doing the handshake for you.
  1325. */
  1326. int
  1327. tor_tls_finish_handshake(tor_tls_t *tls)
  1328. {
  1329. int r = TOR_TLS_DONE;
  1330. check_no_tls_errors();
  1331. if (tls->isServer) {
  1332. SSL_set_info_callback(tls->ssl, NULL);
  1333. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
  1334. SSL_clear_mode(tls->ssl, SSL_MODE_NO_AUTO_CHAIN);
  1335. if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
  1336. /* This check is redundant, but back when we did it in the callback,
  1337. * we might have not been able to look up the tor_tls_t if the code
  1338. * was buggy. Fixing that. */
  1339. if (!tls->wasV2Handshake) {
  1340. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  1341. " get set. Fixing that.");
  1342. }
  1343. tls->wasV2Handshake = 1;
  1344. log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
  1345. " for renegotiation.");
  1346. } else {
  1347. tls->wasV2Handshake = 0;
  1348. }
  1349. } else {
  1350. /* Client-side */
  1351. tls->wasV2Handshake = 1;
  1352. /* XXXX this can move, probably? -NM */
  1353. if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
  1354. tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
  1355. r = TOR_TLS_ERROR_MISC;
  1356. }
  1357. }
  1358. tls_log_errors(NULL, LOG_WARN, LD_NET, "finishing the handshake");
  1359. return r;
  1360. }
  1361. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  1362. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1363. * or TOR_TLS_WANTWRITE.
  1364. */
  1365. int
  1366. tor_tls_shutdown(tor_tls_t *tls)
  1367. {
  1368. int r, err;
  1369. char buf[128];
  1370. tor_assert(tls);
  1371. tor_assert(tls->ssl);
  1372. check_no_tls_errors();
  1373. while (1) {
  1374. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  1375. /* If we've already called shutdown once to send a close message,
  1376. * we read until the other side has closed too.
  1377. */
  1378. do {
  1379. r = SSL_read(tls->ssl, buf, 128);
  1380. } while (r>0);
  1381. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  1382. LOG_INFO, LD_NET);
  1383. if (err == TOR_TLS_ZERORETURN_) {
  1384. tls->state = TOR_TLS_ST_GOTCLOSE;
  1385. /* fall through... */
  1386. } else {
  1387. return err;
  1388. }
  1389. }
  1390. r = SSL_shutdown(tls->ssl);
  1391. if (r == 1) {
  1392. /* If shutdown returns 1, the connection is entirely closed. */
  1393. tls->state = TOR_TLS_ST_CLOSED;
  1394. return TOR_TLS_DONE;
  1395. }
  1396. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  1397. LOG_INFO, LD_NET);
  1398. if (err == TOR_TLS_SYSCALL_) {
  1399. /* The underlying TCP connection closed while we were shutting down. */
  1400. tls->state = TOR_TLS_ST_CLOSED;
  1401. return TOR_TLS_DONE;
  1402. } else if (err == TOR_TLS_ZERORETURN_) {
  1403. /* The TLS connection says that it sent a shutdown record, but
  1404. * isn't done shutting down yet. Make sure that this hasn't
  1405. * happened before, then go back to the start of the function
  1406. * and try to read.
  1407. */
  1408. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  1409. tls->state == TOR_TLS_ST_SENTCLOSE) {
  1410. log_warn(LD_NET,
  1411. "TLS returned \"half-closed\" value while already half-closed");
  1412. return TOR_TLS_ERROR_MISC;
  1413. }
  1414. tls->state = TOR_TLS_ST_SENTCLOSE;
  1415. /* fall through ... */
  1416. } else {
  1417. return err;
  1418. }
  1419. } /* end loop */
  1420. }
  1421. /** Return true iff this TLS connection is authenticated.
  1422. */
  1423. int
  1424. tor_tls_peer_has_cert(tor_tls_t *tls)
  1425. {
  1426. X509 *cert;
  1427. cert = SSL_get_peer_certificate(tls->ssl);
  1428. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1429. if (!cert)
  1430. return 0;
  1431. X509_free(cert);
  1432. return 1;
  1433. }
  1434. /** Return a newly allocated copy of the peer certificate, or NULL if there
  1435. * isn't one. */
  1436. MOCK_IMPL(tor_x509_cert_t *,
  1437. tor_tls_get_peer_cert,(tor_tls_t *tls))
  1438. {
  1439. X509 *cert;
  1440. cert = SSL_get_peer_certificate(tls->ssl);
  1441. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1442. if (!cert)
  1443. return NULL;
  1444. return tor_x509_cert_new(cert);
  1445. }
  1446. /** Return a newly allocated copy of the cerficate we used on the connection,
  1447. * or NULL if somehow we didn't use one. */
  1448. MOCK_IMPL(tor_x509_cert_t *,
  1449. tor_tls_get_own_cert,(tor_tls_t *tls))
  1450. {
  1451. X509 *cert = SSL_get_certificate(tls->ssl);
  1452. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE,
  1453. "getting own-connection certificate");
  1454. if (!cert)
  1455. return NULL;
  1456. /* Fun inconsistency: SSL_get_peer_certificate increments the reference
  1457. * count, but SSL_get_certificate does not. */
  1458. X509 *duplicate = X509_dup(cert);
  1459. if (BUG(duplicate == NULL))
  1460. return NULL;
  1461. return tor_x509_cert_new(duplicate);
  1462. }
  1463. /** Helper function: try to extract a link certificate and an identity
  1464. * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
  1465. * *<b>id_cert_out</b> respectively. Log all messages at level
  1466. * <b>severity</b>.
  1467. *
  1468. * Note that a reference is added to cert_out, so it needs to be
  1469. * freed. id_cert_out doesn't. */
  1470. MOCK_IMPL(void,
  1471. try_to_extract_certs_from_tls,(int severity, tor_tls_t *tls,
  1472. X509 **cert_out, X509 **id_cert_out))
  1473. {
  1474. X509 *cert = NULL, *id_cert = NULL;
  1475. STACK_OF(X509) *chain = NULL;
  1476. int num_in_chain, i;
  1477. *cert_out = *id_cert_out = NULL;
  1478. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1479. return;
  1480. *cert_out = cert;
  1481. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1482. return;
  1483. num_in_chain = sk_X509_num(chain);
  1484. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1485. * 2 means we're connecting (client-side), and it's both the link
  1486. * cert and the id_cert.
  1487. */
  1488. if (num_in_chain < 1) {
  1489. log_fn(severity,LD_PROTOCOL,
  1490. "Unexpected number of certificates in chain (%d)",
  1491. num_in_chain);
  1492. return;
  1493. }
  1494. for (i=0; i<num_in_chain; ++i) {
  1495. id_cert = sk_X509_value(chain, i);
  1496. if (X509_cmp(id_cert, cert) != 0)
  1497. break;
  1498. }
  1499. *id_cert_out = id_cert;
  1500. }
  1501. /** If the provided tls connection is authenticated and has a
  1502. * certificate chain that is currently valid and signed, then set
  1503. * *<b>identity_key</b> to the identity certificate's key and return
  1504. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1505. */
  1506. int
  1507. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity_key)
  1508. {
  1509. X509 *cert = NULL, *id_cert = NULL;
  1510. EVP_PKEY *id_pkey = NULL;
  1511. RSA *rsa;
  1512. int r = -1;
  1513. check_no_tls_errors();
  1514. *identity_key = NULL;
  1515. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1516. if (!cert)
  1517. goto done;
  1518. if (!id_cert) {
  1519. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1520. goto done;
  1521. }
  1522. tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
  1523. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1524. X509_verify(cert, id_pkey) <= 0) {
  1525. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1526. tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
  1527. goto done;
  1528. }
  1529. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1530. if (!rsa)
  1531. goto done;
  1532. *identity_key = crypto_new_pk_from_openssl_rsa_(rsa);
  1533. r = 0;
  1534. done:
  1535. if (cert)
  1536. X509_free(cert);
  1537. if (id_pkey)
  1538. EVP_PKEY_free(id_pkey);
  1539. /* This should never get invoked, but let's make sure in case OpenSSL
  1540. * acts unexpectedly. */
  1541. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
  1542. return r;
  1543. }
  1544. /** Check whether the certificate set on the connection <b>tls</b> is expired
  1545. * give or take <b>past_tolerance</b> seconds, or not-yet-valid give or take
  1546. * <b>future_tolerance</b> seconds. Return 0 for valid, -1 for failure.
  1547. *
  1548. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1549. */
  1550. int
  1551. tor_tls_check_lifetime(int severity, tor_tls_t *tls,
  1552. time_t now,
  1553. int past_tolerance, int future_tolerance)
  1554. {
  1555. X509 *cert;
  1556. int r = -1;
  1557. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1558. goto done;
  1559. if (tor_x509_check_cert_lifetime_internal(severity, cert, now,
  1560. past_tolerance,
  1561. future_tolerance) < 0)
  1562. goto done;
  1563. r = 0;
  1564. done:
  1565. if (cert)
  1566. X509_free(cert);
  1567. /* Not expected to get invoked */
  1568. tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
  1569. return r;
  1570. }
  1571. /** Return the number of bytes available for reading from <b>tls</b>.
  1572. */
  1573. int
  1574. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1575. {
  1576. tor_assert(tls);
  1577. return SSL_pending(tls->ssl);
  1578. }
  1579. /** If <b>tls</b> requires that the next write be of a particular size,
  1580. * return that size. Otherwise, return 0. */
  1581. size_t
  1582. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1583. {
  1584. return tls->wantwrite_n;
  1585. }
  1586. /** Sets n_read and n_written to the number of bytes read and written,
  1587. * respectively, on the raw socket used by <b>tls</b> since the last time this
  1588. * function was called on <b>tls</b>. */
  1589. void
  1590. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1591. {
  1592. BIO *wbio, *tmpbio;
  1593. unsigned long r, w;
  1594. r = (unsigned long) BIO_number_read(SSL_get_rbio(tls->ssl));
  1595. /* We want the number of bytes actually for real written. Unfortunately,
  1596. * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
  1597. * which makes the answer turn out wrong. Let's cope with that. Note
  1598. * that this approach will fail if we ever replace tls->ssl's BIOs with
  1599. * buffering bios for reasons of our own. As an alternative, we could
  1600. * save the original BIO for tls->ssl in the tor_tls_t structure, but
  1601. * that would be tempting fate. */
  1602. wbio = SSL_get_wbio(tls->ssl);
  1603. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)
  1604. /* BIO structure is opaque as of OpenSSL 1.1.0-pre5-dev. Again, not
  1605. * supposed to use this form of the version macro, but the OpenSSL developers
  1606. * introduced major API changes in the pre-release stage.
  1607. */
  1608. if (BIO_method_type(wbio) == BIO_TYPE_BUFFER &&
  1609. (tmpbio = BIO_next(wbio)) != NULL)
  1610. wbio = tmpbio;
  1611. #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5)) */
  1612. if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
  1613. wbio = tmpbio;
  1614. #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_VER(1,1,0,0,5) */
  1615. w = (unsigned long) BIO_number_written(wbio);
  1616. /* We are ok with letting these unsigned ints go "negative" here:
  1617. * If we wrapped around, this should still give us the right answer, unless
  1618. * we wrapped around by more than ULONG_MAX since the last time we called
  1619. * this function.
  1620. */
  1621. *n_read = (size_t)(r - tls->last_read_count);
  1622. *n_written = (size_t)(w - tls->last_write_count);
  1623. if (*n_read > INT_MAX || *n_written > INT_MAX) {
  1624. log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
  1625. "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
  1626. r, tls->last_read_count, w, tls->last_write_count);
  1627. }
  1628. total_bytes_written_by_tls += *n_written;
  1629. tls->last_read_count = r;
  1630. tls->last_write_count = w;
  1631. }
  1632. /** Return a ratio of the bytes that TLS has sent to the bytes that we've told
  1633. * it to send. Used to track whether our TLS records are getting too tiny. */
  1634. MOCK_IMPL(double,
  1635. tls_get_write_overhead_ratio,(void))
  1636. {
  1637. if (total_bytes_written_over_tls == 0)
  1638. return 1.0;
  1639. return ((double)total_bytes_written_by_tls) /
  1640. ((double)total_bytes_written_over_tls);
  1641. }
  1642. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1643. * errors, log an error message. */
  1644. void
  1645. check_no_tls_errors_(const char *fname, int line)
  1646. {
  1647. if (ERR_peek_error() == 0)
  1648. return;
  1649. log_warn(LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1650. tor_fix_source_file(fname), line);
  1651. tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
  1652. }
  1653. /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
  1654. * TLS handshake. Output is undefined if the handshake isn't finished. */
  1655. int
  1656. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1657. {
  1658. return ! tls->wasV2Handshake;
  1659. }
  1660. /** Return the number of server handshakes that we've noticed doing on
  1661. * <b>tls</b>. */
  1662. int
  1663. tor_tls_get_num_server_handshakes(tor_tls_t *tls)
  1664. {
  1665. return tls->server_handshake_count;
  1666. }
  1667. /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
  1668. * request it was waiting for. */
  1669. int
  1670. tor_tls_server_got_renegotiate(tor_tls_t *tls)
  1671. {
  1672. return tls->got_renegotiate;
  1673. }
  1674. #ifndef HAVE_SSL_GET_CLIENT_RANDOM
  1675. static size_t
  1676. SSL_get_client_random(SSL *s, uint8_t *out, size_t len)
  1677. {
  1678. if (len == 0)
  1679. return SSL3_RANDOM_SIZE;
  1680. tor_assert(len == SSL3_RANDOM_SIZE);
  1681. tor_assert(s->s3);
  1682. memcpy(out, s->s3->client_random, len);
  1683. return len;
  1684. }
  1685. #endif /* !defined(HAVE_SSL_GET_CLIENT_RANDOM) */
  1686. #ifndef HAVE_SSL_GET_SERVER_RANDOM
  1687. static size_t
  1688. SSL_get_server_random(SSL *s, uint8_t *out, size_t len)
  1689. {
  1690. if (len == 0)
  1691. return SSL3_RANDOM_SIZE;
  1692. tor_assert(len == SSL3_RANDOM_SIZE);
  1693. tor_assert(s->s3);
  1694. memcpy(out, s->s3->server_random, len);
  1695. return len;
  1696. }
  1697. #endif /* !defined(HAVE_SSL_GET_SERVER_RANDOM) */
  1698. #ifndef HAVE_SSL_SESSION_GET_MASTER_KEY
  1699. size_t
  1700. SSL_SESSION_get_master_key(SSL_SESSION *s, uint8_t *out, size_t len)
  1701. {
  1702. tor_assert(s);
  1703. if (len == 0)
  1704. return s->master_key_length;
  1705. tor_assert(len == (size_t)s->master_key_length);
  1706. tor_assert(out);
  1707. memcpy(out, s->master_key, len);
  1708. return len;
  1709. }
  1710. #endif /* !defined(HAVE_SSL_SESSION_GET_MASTER_KEY) */
  1711. /** Set the DIGEST256_LEN buffer at <b>secrets_out</b> to the value used in
  1712. * the v3 handshake to prove that the client knows the TLS secrets for the
  1713. * connection <b>tls</b>. Return 0 on success, -1 on failure.
  1714. */
  1715. MOCK_IMPL(int,
  1716. tor_tls_get_tlssecrets,(tor_tls_t *tls, uint8_t *secrets_out))
  1717. {
  1718. #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
  1719. uint8_t buf[128];
  1720. size_t len;
  1721. tor_assert(tls);
  1722. SSL *const ssl = tls->ssl;
  1723. SSL_SESSION *const session = SSL_get_session(ssl);
  1724. tor_assert(ssl);
  1725. tor_assert(session);
  1726. const size_t server_random_len = SSL_get_server_random(ssl, NULL, 0);
  1727. const size_t client_random_len = SSL_get_client_random(ssl, NULL, 0);
  1728. const size_t master_key_len = SSL_SESSION_get_master_key(session, NULL, 0);
  1729. tor_assert(server_random_len);
  1730. tor_assert(client_random_len);
  1731. tor_assert(master_key_len);
  1732. len = client_random_len + server_random_len + strlen(TLSSECRET_MAGIC) + 1;
  1733. tor_assert(len <= sizeof(buf));
  1734. {
  1735. size_t r = SSL_get_client_random(ssl, buf, client_random_len);
  1736. tor_assert(r == client_random_len);
  1737. }
  1738. {
  1739. size_t r = SSL_get_server_random(ssl,
  1740. buf+client_random_len,
  1741. server_random_len);
  1742. tor_assert(r == server_random_len);
  1743. }
  1744. uint8_t *master_key = tor_malloc_zero(master_key_len);
  1745. {
  1746. size_t r = SSL_SESSION_get_master_key(session, master_key, master_key_len);
  1747. tor_assert(r == master_key_len);
  1748. }
  1749. uint8_t *nextbuf = buf + client_random_len + server_random_len;
  1750. memcpy(nextbuf, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
  1751. /*
  1752. The value is an HMAC, using the TLS master key as the HMAC key, of
  1753. client_random | server_random | TLSSECRET_MAGIC
  1754. */
  1755. crypto_hmac_sha256((char*)secrets_out,
  1756. (char*)master_key,
  1757. master_key_len,
  1758. (char*)buf, len);
  1759. memwipe(buf, 0, sizeof(buf));
  1760. memwipe(master_key, 0, master_key_len);
  1761. tor_free(master_key);
  1762. return 0;
  1763. }
  1764. /** Using the RFC5705 key material exporting construction, and the
  1765. * provided <b>context</b> (<b>context_len</b> bytes long) and
  1766. * <b>label</b> (a NUL-terminated string), compute a 32-byte secret in
  1767. * <b>secrets_out</b> that only the parties to this TLS session can
  1768. * compute. Return 0 on success and -1 on failure.
  1769. */
  1770. MOCK_IMPL(int,
  1771. tor_tls_export_key_material,(tor_tls_t *tls, uint8_t *secrets_out,
  1772. const uint8_t *context,
  1773. size_t context_len,
  1774. const char *label))
  1775. {
  1776. tor_assert(tls);
  1777. tor_assert(tls->ssl);
  1778. int r = SSL_export_keying_material(tls->ssl,
  1779. secrets_out, DIGEST256_LEN,
  1780. label, strlen(label),
  1781. context, context_len, 1);
  1782. return (r == 1) ? 0 : -1;
  1783. }
  1784. /** Examine the amount of memory used and available for buffers in <b>tls</b>.
  1785. * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
  1786. * buffer and *<b>rbuf_bytes</b> to the amount actually used.
  1787. * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
  1788. * buffer and *<b>wbuf_bytes</b> to the amount actually used.
  1789. *
  1790. * Return 0 on success, -1 on failure.*/
  1791. int
  1792. tor_tls_get_buffer_sizes(tor_tls_t *tls,
  1793. size_t *rbuf_capacity, size_t *rbuf_bytes,
  1794. size_t *wbuf_capacity, size_t *wbuf_bytes)
  1795. {
  1796. #if OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)
  1797. (void)tls;
  1798. (void)rbuf_capacity;
  1799. (void)rbuf_bytes;
  1800. (void)wbuf_capacity;
  1801. (void)wbuf_bytes;
  1802. return -1;
  1803. #else /* !(OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0)) */
  1804. if (tls->ssl->s3->rbuf.buf)
  1805. *rbuf_capacity = tls->ssl->s3->rbuf.len;
  1806. else
  1807. *rbuf_capacity = 0;
  1808. if (tls->ssl->s3->wbuf.buf)
  1809. *wbuf_capacity = tls->ssl->s3->wbuf.len;
  1810. else
  1811. *wbuf_capacity = 0;
  1812. *rbuf_bytes = tls->ssl->s3->rbuf.left;
  1813. *wbuf_bytes = tls->ssl->s3->wbuf.left;
  1814. return 0;
  1815. #endif /* OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
  1816. }
  1817. /** Check whether the ECC group requested is supported by the current OpenSSL
  1818. * library instance. Return 1 if the group is supported, and 0 if not.
  1819. */
  1820. int
  1821. evaluate_ecgroup_for_tls(const char *ecgroup)
  1822. {
  1823. EC_KEY *ec_key;
  1824. int nid;
  1825. int ret;
  1826. if (!ecgroup)
  1827. nid = NID_tor_default_ecdhe_group;
  1828. else if (!strcasecmp(ecgroup, "P256"))
  1829. nid = NID_X9_62_prime256v1;
  1830. else if (!strcasecmp(ecgroup, "P224"))
  1831. nid = NID_secp224r1;
  1832. else
  1833. return 0;
  1834. ec_key = EC_KEY_new_by_curve_name(nid);
  1835. ret = (ec_key != NULL);
  1836. EC_KEY_free(ec_key);
  1837. return ret;
  1838. }