tortls_openssl.c 64 KB

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