tortls_openssl.c 54 KB

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