tortls.c 68 KB

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