tortls_openssl.c 57 KB

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