tortls_openssl.c 54 KB

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