tortls.c 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470
  1. /* Copyright (c) 2003, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, 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. #if defined (WINCE)
  16. #include <WinSock2.h>
  17. #endif
  18. #include <assert.h>
  19. #ifdef MS_WINDOWS /*wrkard for dtls1.h >= 0.9.8m of "#include <winsock.h>"*/
  20. #ifndef WIN32_WINNT
  21. #define WIN32_WINNT 0x400
  22. #endif
  23. #ifndef _WIN32_WINNT
  24. #define _WIN32_WINNT 0x400
  25. #endif
  26. #define WIN32_LEAN_AND_MEAN
  27. #if defined(_MSC_VER) && (_MSC_VER < 1300)
  28. #include <winsock.h>
  29. #else
  30. #include <winsock2.h>
  31. #include <ws2tcpip.h>
  32. #endif
  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/opensslv.h>
  41. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  42. #error "We require OpenSSL >= 0.9.7"
  43. #endif
  44. #ifdef USE_BUFFEREVENTS
  45. #include <event2/bufferevent_ssl.h>
  46. #include <event2/buffer.h>
  47. #include <event2/event.h>
  48. #endif
  49. #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
  50. #define TORTLS_PRIVATE
  51. #include "crypto.h"
  52. #include "tortls.h"
  53. #include "util.h"
  54. #include "torlog.h"
  55. #include "container.h"
  56. #include <string.h>
  57. #include "compat_libevent.h"
  58. /* Enable the "v2" TLS handshake.
  59. */
  60. #define V2_HANDSHAKE_SERVER
  61. #define V2_HANDSHAKE_CLIENT
  62. /* Copied from or.h */
  63. #define LEGAL_NICKNAME_CHARACTERS \
  64. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  65. /** How long do identity certificates live? (sec) */
  66. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  67. #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
  68. /* We redefine these so that we can run correctly even if the vendor gives us
  69. * a version of OpenSSL that does not match its header files. (Apple: I am
  70. * looking at you.)
  71. */
  72. #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  73. #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
  74. #endif
  75. #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  76. #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
  77. #endif
  78. /** Does the run-time openssl version look like we need
  79. * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  80. static int use_unsafe_renegotiation_op = 0;
  81. /** Does the run-time openssl version look like we need
  82. * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  83. static int use_unsafe_renegotiation_flag = 0;
  84. /** Structure that we use for a single certificate. */
  85. struct tor_cert_t {
  86. X509 *cert;
  87. uint8_t *encoded;
  88. size_t encoded_len;
  89. unsigned pkey_digests_set : 1;
  90. digests_t cert_digests;
  91. digests_t pkey_digests;
  92. };
  93. /** Holds a SSL_CTX object and related state used to configure TLS
  94. * connections.
  95. */
  96. typedef struct tor_tls_context_t {
  97. int refcnt;
  98. SSL_CTX *ctx;
  99. tor_cert_t *my_link_cert;
  100. tor_cert_t *my_id_cert;
  101. tor_cert_t *my_auth_cert;
  102. crypto_pk_env_t *link_key;
  103. crypto_pk_env_t *auth_key;
  104. } tor_tls_context_t;
  105. #define TOR_TLS_MAGIC 0x71571571
  106. /** Holds a SSL object and its associated data. Members are only
  107. * accessed from within tortls.c.
  108. */
  109. struct tor_tls_t {
  110. uint32_t magic;
  111. tor_tls_context_t *context; /** A link to the context object for this tls. */
  112. SSL *ssl; /**< An OpenSSL SSL object. */
  113. int socket; /**< The underlying file descriptor for this TLS connection. */
  114. char *address; /**< An address to log when describing this connection. */
  115. enum {
  116. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  117. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
  118. TOR_TLS_ST_BUFFEREVENT
  119. } state : 3; /**< The current SSL state, depending on which operations have
  120. * completed successfully. */
  121. unsigned int isServer:1; /**< True iff this is a server-side connection */
  122. unsigned int wasV2Handshake:1; /**< True iff the original handshake for
  123. * this connection used the updated version
  124. * of the connection protocol (client sends
  125. * different cipher list, server sends only
  126. * one certificate). */
  127. /** True iff we should call negotiated_callback when we're done reading. */
  128. unsigned int got_renegotiate:1;
  129. /** Incremented every time we start the server side of a handshake. */
  130. unsigned int server_handshake_count:2;
  131. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
  132. * time. */
  133. /** Last values retrieved from BIO_number_read()/write(); see
  134. * tor_tls_get_n_raw_bytes() for usage.
  135. */
  136. unsigned long last_write_count;
  137. unsigned long last_read_count;
  138. /** If set, a callback to invoke whenever the client tries to renegotiate
  139. * the handshake. */
  140. void (*negotiated_callback)(tor_tls_t *tls, void *arg);
  141. /** Callback to invoke whenever a client tries to renegotiate more
  142. than once. */
  143. void (*excess_renegotiations_callback)(evutil_socket_t, short, void *);
  144. /** Argument to pass to negotiated_callback. */
  145. void *callback_arg;
  146. };
  147. #ifdef V2_HANDSHAKE_CLIENT
  148. /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
  149. * in client mode into advertising the ciphers we want. See
  150. * rectify_client_ciphers() for details. */
  151. static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
  152. /** A stack of SSL_CIPHER objects, some real, some fake.
  153. * See rectify_client_ciphers() for details. */
  154. static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
  155. #endif
  156. /** The ex_data index in which we store a pointer to an SSL object's
  157. * corresponding tor_tls_t object. */
  158. static int tor_tls_object_ex_data_index = -1;
  159. /** Helper: Allocate tor_tls_object_ex_data_index. */
  160. static void
  161. tor_tls_allocate_tor_tls_object_ex_data_index(void)
  162. {
  163. if (tor_tls_object_ex_data_index == -1) {
  164. tor_tls_object_ex_data_index =
  165. SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  166. tor_assert(tor_tls_object_ex_data_index != -1);
  167. }
  168. }
  169. /** Helper: given a SSL* pointer, return the tor_tls_t object using that
  170. * pointer. */
  171. static INLINE tor_tls_t *
  172. tor_tls_get_by_ssl(const SSL *ssl)
  173. {
  174. tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
  175. if (result)
  176. tor_assert(result->magic == TOR_TLS_MAGIC);
  177. return result;
  178. }
  179. static void tor_tls_context_decref(tor_tls_context_t *ctx);
  180. static void tor_tls_context_incref(tor_tls_context_t *ctx);
  181. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  182. crypto_pk_env_t *rsa_sign,
  183. const char *cname,
  184. const char *cname_sign,
  185. unsigned int lifetime);
  186. static int tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  187. crypto_pk_env_t *identity,
  188. unsigned int key_lifetime,
  189. int is_client);
  190. static tor_tls_context_t *tor_tls_context_new(crypto_pk_env_t *identity,
  191. unsigned int key_lifetime,
  192. int is_client);
  193. static int check_cert_lifetime_internal(int severity, const X509 *cert,
  194. int past_tolerance, int future_tolerance);
  195. /** Global TLS contexts. We keep them here because nobody else needs
  196. * to touch them. */
  197. static tor_tls_context_t *server_tls_context = NULL;
  198. static tor_tls_context_t *client_tls_context = NULL;
  199. /** True iff tor_tls_init() has been called. */
  200. static int tls_library_is_initialized = 0;
  201. /* Module-internal error codes. */
  202. #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
  203. #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
  204. #include "tortls_states.h"
  205. /** Return the symbolic name of an OpenSSL state. */
  206. static const char *
  207. ssl_state_to_string(int ssl_state)
  208. {
  209. static char buf[40];
  210. int i;
  211. for (i = 0; state_map[i].name; ++i) {
  212. if (state_map[i].state == ssl_state)
  213. return state_map[i].name;
  214. }
  215. tor_snprintf(buf, sizeof(buf), "Unknown state %d", ssl_state);
  216. return buf;
  217. }
  218. /** Write a description of the current state of <b>tls</b> into the
  219. * <b>sz</b>-byte buffer at <b>buf</b>. */
  220. void
  221. tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
  222. {
  223. const char *ssl_state;
  224. const char *tortls_state;
  225. if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
  226. strlcpy(buf, "(No SSL object)", sz);
  227. return;
  228. }
  229. ssl_state = ssl_state_to_string(tls->ssl->state);
  230. switch (tls->state) {
  231. #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
  232. CASE(HANDSHAKE);
  233. CASE(OPEN);
  234. CASE(GOTCLOSE);
  235. CASE(SENTCLOSE);
  236. CASE(CLOSED);
  237. CASE(RENEGOTIATE);
  238. #undef CASE
  239. case TOR_TLS_ST_BUFFEREVENT:
  240. tortls_state = "";
  241. break;
  242. default:
  243. tortls_state = " in unknown TLS state";
  244. break;
  245. }
  246. tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
  247. }
  248. void
  249. tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
  250. int severity, int domain, const char *doing)
  251. {
  252. const char *state = NULL, *addr;
  253. const char *msg, *lib, *func;
  254. int st;
  255. st = (tls && tls->ssl) ? tls->ssl->state : -1;
  256. state = (st>=0)?ssl_state_to_string(st):"---";
  257. addr = tls ? tls->address : NULL;
  258. /* Some errors are known-benign, meaning they are the fault of the other
  259. * side of the connection. The caller doesn't know this, so override the
  260. * priority for those cases. */
  261. switch (ERR_GET_REASON(err)) {
  262. case SSL_R_HTTP_REQUEST:
  263. case SSL_R_HTTPS_PROXY_REQUEST:
  264. case SSL_R_RECORD_LENGTH_MISMATCH:
  265. case SSL_R_RECORD_TOO_LARGE:
  266. case SSL_R_UNKNOWN_PROTOCOL:
  267. case SSL_R_UNSUPPORTED_PROTOCOL:
  268. severity = LOG_INFO;
  269. break;
  270. default:
  271. break;
  272. }
  273. msg = (const char*)ERR_reason_error_string(err);
  274. lib = (const char*)ERR_lib_error_string(err);
  275. func = (const char*)ERR_func_error_string(err);
  276. if (!msg) msg = "(null)";
  277. if (!lib) lib = "(null)";
  278. if (!func) func = "(null)";
  279. if (doing) {
  280. log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
  281. doing, addr?" with ":"", addr?addr:"",
  282. msg, lib, func, state);
  283. } else {
  284. log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
  285. addr?" with ":"", addr?addr:"",
  286. msg, lib, func, state);
  287. }
  288. }
  289. /** Log all pending tls errors at level <b>severity</b>. Use
  290. * <b>doing</b> to describe our current activities.
  291. */
  292. static void
  293. tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
  294. {
  295. unsigned long err;
  296. while ((err = ERR_get_error()) != 0) {
  297. tor_tls_log_one_error(tls, err, severity, domain, doing);
  298. }
  299. }
  300. /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
  301. * code. */
  302. static int
  303. tor_errno_to_tls_error(int e)
  304. {
  305. #if defined(MS_WINDOWS)
  306. switch (e) {
  307. case WSAECONNRESET: // most common
  308. return TOR_TLS_ERROR_CONNRESET;
  309. case WSAETIMEDOUT:
  310. return TOR_TLS_ERROR_TIMEOUT;
  311. case WSAENETUNREACH:
  312. case WSAEHOSTUNREACH:
  313. return TOR_TLS_ERROR_NO_ROUTE;
  314. case WSAECONNREFUSED:
  315. return TOR_TLS_ERROR_CONNREFUSED; // least common
  316. default:
  317. return TOR_TLS_ERROR_MISC;
  318. }
  319. #else
  320. switch (e) {
  321. case ECONNRESET: // most common
  322. return TOR_TLS_ERROR_CONNRESET;
  323. case ETIMEDOUT:
  324. return TOR_TLS_ERROR_TIMEOUT;
  325. case EHOSTUNREACH:
  326. case ENETUNREACH:
  327. return TOR_TLS_ERROR_NO_ROUTE;
  328. case ECONNREFUSED:
  329. return TOR_TLS_ERROR_CONNREFUSED; // least common
  330. default:
  331. return TOR_TLS_ERROR_MISC;
  332. }
  333. #endif
  334. }
  335. /** Given a TOR_TLS_* error code, return a string equivalent. */
  336. const char *
  337. tor_tls_err_to_string(int err)
  338. {
  339. if (err >= 0)
  340. return "[Not an error.]";
  341. switch (err) {
  342. case TOR_TLS_ERROR_MISC: return "misc error";
  343. case TOR_TLS_ERROR_IO: return "unexpected close";
  344. case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
  345. case TOR_TLS_ERROR_CONNRESET: return "connection reset";
  346. case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
  347. case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
  348. case TOR_TLS_CLOSE: return "closed";
  349. case TOR_TLS_WANTREAD: return "want to read";
  350. case TOR_TLS_WANTWRITE: return "want to write";
  351. default: return "(unknown error code)";
  352. }
  353. }
  354. #define CATCH_SYSCALL 1
  355. #define CATCH_ZERO 2
  356. /** Given a TLS object and the result of an SSL_* call, use
  357. * SSL_get_error to determine whether an error has occurred, and if so
  358. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  359. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  360. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  361. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  362. *
  363. * If an error has occurred, log it at level <b>severity</b> and describe the
  364. * current action as <b>doing</b>.
  365. */
  366. static int
  367. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  368. const char *doing, int severity, int domain)
  369. {
  370. int err = SSL_get_error(tls->ssl, r);
  371. int tor_error = TOR_TLS_ERROR_MISC;
  372. switch (err) {
  373. case SSL_ERROR_NONE:
  374. return TOR_TLS_DONE;
  375. case SSL_ERROR_WANT_READ:
  376. return TOR_TLS_WANTREAD;
  377. case SSL_ERROR_WANT_WRITE:
  378. return TOR_TLS_WANTWRITE;
  379. case SSL_ERROR_SYSCALL:
  380. if (extra&CATCH_SYSCALL)
  381. return _TOR_TLS_SYSCALL;
  382. if (r == 0) {
  383. log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
  384. doing, ssl_state_to_string(tls->ssl->state));
  385. tor_error = TOR_TLS_ERROR_IO;
  386. } else {
  387. int e = tor_socket_errno(tls->socket);
  388. log(severity, LD_NET,
  389. "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
  390. doing, e, tor_socket_strerror(e),
  391. ssl_state_to_string(tls->ssl->state));
  392. tor_error = tor_errno_to_tls_error(e);
  393. }
  394. tls_log_errors(tls, severity, domain, doing);
  395. return tor_error;
  396. case SSL_ERROR_ZERO_RETURN:
  397. if (extra&CATCH_ZERO)
  398. return _TOR_TLS_ZERORETURN;
  399. log(severity, LD_NET, "TLS connection closed while %s in state %s",
  400. doing, ssl_state_to_string(tls->ssl->state));
  401. tls_log_errors(tls, severity, domain, doing);
  402. return TOR_TLS_CLOSE;
  403. default:
  404. tls_log_errors(tls, severity, domain, doing);
  405. return TOR_TLS_ERROR_MISC;
  406. }
  407. }
  408. /** Initialize OpenSSL, unless it has already been initialized.
  409. */
  410. static void
  411. tor_tls_init(void)
  412. {
  413. if (!tls_library_is_initialized) {
  414. long version;
  415. SSL_library_init();
  416. SSL_load_error_strings();
  417. version = SSLeay();
  418. /* OpenSSL 0.9.8l introduced SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  419. * here, but without thinking too hard about it: it turns out that the
  420. * flag in question needed to be set at the last minute, and that it
  421. * conflicted with an existing flag number that had already been added
  422. * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
  423. * the flag with an option and (it seems) broke anything that used
  424. * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
  425. * and we mustn't use the SSL3_FLAGS option with anything besides
  426. * OpenSSL 0.9.8l.
  427. *
  428. * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
  429. * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
  430. * set option 0x00040000L everywhere.
  431. *
  432. * No, we can't simply detect whether the flag or the option is present
  433. * in the headers at build-time: some vendors (notably Apple) like to
  434. * leave their headers out of sync with their libraries.
  435. *
  436. * Yes, it _is_ almost as if the OpenSSL developers decided that no
  437. * program should be allowed to use renegotiation unless it first passed
  438. * a test of intelligence and determination.
  439. */
  440. if (version >= 0x009080c0L && version < 0x009080d0L) {
  441. log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l; "
  442. "I will try SSL3_FLAGS to enable renegotation.",
  443. SSLeay_version(SSLEAY_VERSION));
  444. use_unsafe_renegotiation_flag = 1;
  445. use_unsafe_renegotiation_op = 1;
  446. } else if (version >= 0x009080d0L) {
  447. log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
  448. "I will try SSL_OP to enable renegotiation",
  449. SSLeay_version(SSLEAY_VERSION));
  450. use_unsafe_renegotiation_op = 1;
  451. } else if (version < 0x009080c0L) {
  452. log_notice(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
  453. "0.9.8l, but some vendors have backported 0.9.8l's "
  454. "renegotiation code to earlier versions, and some have "
  455. "backported the code from 0.9.8m or 0.9.8n. I'll set both "
  456. "SSL3_FLAGS and SSL_OP just to be safe.",
  457. SSLeay_version(SSLEAY_VERSION), version);
  458. use_unsafe_renegotiation_flag = 1;
  459. use_unsafe_renegotiation_op = 1;
  460. } else {
  461. log_info(LD_GENERAL, "OpenSSL %s has version %lx",
  462. SSLeay_version(SSLEAY_VERSION), version);
  463. }
  464. tor_tls_allocate_tor_tls_object_ex_data_index();
  465. tls_library_is_initialized = 1;
  466. }
  467. }
  468. /** Free all global TLS structures. */
  469. void
  470. tor_tls_free_all(void)
  471. {
  472. if (server_tls_context) {
  473. tor_tls_context_t *ctx = server_tls_context;
  474. server_tls_context = NULL;
  475. tor_tls_context_decref(ctx);
  476. }
  477. if (client_tls_context) {
  478. tor_tls_context_t *ctx = client_tls_context;
  479. client_tls_context = NULL;
  480. tor_tls_context_decref(ctx);
  481. }
  482. #ifdef V2_HANDSHAKE_CLIENT
  483. if (CLIENT_CIPHER_DUMMIES)
  484. tor_free(CLIENT_CIPHER_DUMMIES);
  485. if (CLIENT_CIPHER_STACK)
  486. sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
  487. #endif
  488. }
  489. /** We need to give OpenSSL a callback to verify certificates. This is
  490. * it: We always accept peer certs and complete the handshake. We
  491. * don't validate them until later.
  492. */
  493. static int
  494. always_accept_verify_cb(int preverify_ok,
  495. X509_STORE_CTX *x509_ctx)
  496. {
  497. (void) preverify_ok;
  498. (void) x509_ctx;
  499. return 1;
  500. }
  501. /** Return a newly allocated X509 name with commonName <b>cname</b>. */
  502. static X509_NAME *
  503. tor_x509_name_new(const char *cname)
  504. {
  505. int nid;
  506. X509_NAME *name;
  507. if (!(name = X509_NAME_new()))
  508. return NULL;
  509. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  510. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  511. (unsigned char*)cname, -1, -1, 0)))
  512. goto error;
  513. return name;
  514. error:
  515. X509_NAME_free(name);
  516. return NULL;
  517. }
  518. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  519. * signed by the private key <b>rsa_sign</b>. The commonName of the
  520. * certificate will be <b>cname</b>; the commonName of the issuer will be
  521. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  522. * starting from now. Return a certificate on success, NULL on
  523. * failure.
  524. */
  525. static X509 *
  526. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  527. crypto_pk_env_t *rsa_sign,
  528. const char *cname,
  529. const char *cname_sign,
  530. unsigned int cert_lifetime)
  531. {
  532. #define SERIAL_NUMBER_SIZE 8
  533. time_t start_time, end_time;
  534. BIGNUM *serial_number = NULL;
  535. unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
  536. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  537. X509 *x509 = NULL;
  538. X509_NAME *name = NULL, *name_issuer=NULL;
  539. tor_tls_init();
  540. start_time = time(NULL);
  541. tor_assert(rsa);
  542. tor_assert(cname);
  543. tor_assert(rsa_sign);
  544. tor_assert(cname_sign);
  545. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  546. goto error;
  547. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  548. goto error;
  549. if (!(x509 = X509_new()))
  550. goto error;
  551. if (!(X509_set_version(x509, 2)))
  552. goto error;
  553. { /* our serial number is 8 random bytes. */
  554. if (crypto_rand((char *)serial_tmp, sizeof(serial_tmp)) < 0)
  555. goto error;
  556. if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
  557. goto error;
  558. if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
  559. goto error;
  560. }
  561. if (!(name = tor_x509_name_new(cname)))
  562. goto error;
  563. if (!(X509_set_subject_name(x509, name)))
  564. goto error;
  565. if (!(name_issuer = tor_x509_name_new(cname_sign)))
  566. goto error;
  567. if (!(X509_set_issuer_name(x509, name_issuer)))
  568. goto error;
  569. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  570. goto error;
  571. end_time = start_time + cert_lifetime;
  572. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  573. goto error;
  574. if (!X509_set_pubkey(x509, pkey))
  575. goto error;
  576. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  577. goto error;
  578. goto done;
  579. error:
  580. if (x509) {
  581. X509_free(x509);
  582. x509 = NULL;
  583. }
  584. done:
  585. tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
  586. if (sign_pkey)
  587. EVP_PKEY_free(sign_pkey);
  588. if (pkey)
  589. EVP_PKEY_free(pkey);
  590. if (serial_number)
  591. BN_free(serial_number);
  592. if (name)
  593. X509_NAME_free(name);
  594. if (name_issuer)
  595. X509_NAME_free(name_issuer);
  596. return x509;
  597. #undef SERIAL_NUMBER_SIZE
  598. }
  599. /** List of ciphers that servers should select from.*/
  600. #define SERVER_CIPHER_LIST \
  601. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  602. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  603. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  604. /* Note: to set up your own private testing network with link crypto
  605. * disabled, set your Tors' cipher list to
  606. * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
  607. * with any of the "real" Tors, though. */
  608. #ifdef V2_HANDSHAKE_CLIENT
  609. #define CIPHER(id, name) name ":"
  610. #define XCIPHER(id, name)
  611. /** List of ciphers that clients should advertise, omitting items that
  612. * our OpenSSL doesn't know about. */
  613. static const char CLIENT_CIPHER_LIST[] =
  614. #include "./ciphers.inc"
  615. ;
  616. #undef CIPHER
  617. #undef XCIPHER
  618. /** Holds a cipher that we want to advertise, and its 2-byte ID. */
  619. typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
  620. /** A list of all the ciphers that clients should advertise, including items
  621. * that OpenSSL might not know about. */
  622. static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
  623. #define CIPHER(id, name) { id, name },
  624. #define XCIPHER(id, name) { id, #name },
  625. #include "./ciphers.inc"
  626. #undef CIPHER
  627. #undef XCIPHER
  628. };
  629. /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
  630. static const int N_CLIENT_CIPHERS =
  631. sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
  632. #endif
  633. #ifndef V2_HANDSHAKE_CLIENT
  634. #undef CLIENT_CIPHER_LIST
  635. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  636. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  637. #endif
  638. /** Free all storage held in <b>cert</b> */
  639. void
  640. tor_cert_free(tor_cert_t *cert)
  641. {
  642. if (! cert)
  643. return;
  644. if (cert->cert)
  645. X509_free(cert->cert);
  646. tor_free(cert->encoded);
  647. memset(cert, 0x03, sizeof(*cert));
  648. tor_free(cert);
  649. }
  650. /**
  651. * Allocate a new tor_cert_t to hold the certificate "x509_cert".
  652. *
  653. * Steals a reference to x509_cert.
  654. */
  655. static tor_cert_t *
  656. tor_cert_new(X509 *x509_cert)
  657. {
  658. tor_cert_t *cert;
  659. EVP_PKEY *pkey;
  660. RSA *rsa;
  661. int length, length2;
  662. unsigned char *cp;
  663. if (!x509_cert)
  664. return NULL;
  665. length = i2d_X509(x509_cert, NULL);
  666. cert = tor_malloc_zero(sizeof(tor_cert_t));
  667. if (length <= 0) {
  668. tor_free(cert);
  669. log_err(LD_CRYPTO, "Couldn't get length of encoded x509 certificate");
  670. X509_free(x509_cert);
  671. return NULL;
  672. }
  673. cert->encoded_len = (size_t) length;
  674. cp = cert->encoded = tor_malloc(length);
  675. length2 = i2d_X509(x509_cert, &cp);
  676. tor_assert(length2 == length);
  677. cert->cert = x509_cert;
  678. crypto_digest_all(&cert->cert_digests,
  679. (char*)cert->encoded, cert->encoded_len);
  680. if ((pkey = X509_get_pubkey(x509_cert)) &&
  681. (rsa = EVP_PKEY_get1_RSA(pkey))) {
  682. crypto_pk_env_t *pk = _crypto_new_pk_env_rsa(rsa);
  683. crypto_pk_get_all_digests(pk, &cert->pkey_digests);
  684. cert->pkey_digests_set = 1;
  685. crypto_free_pk_env(pk);
  686. EVP_PKEY_free(pkey);
  687. }
  688. return cert;
  689. }
  690. /** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
  691. * from a <b>certificate</b>. Return a newly allocated tor_cert_t on success
  692. * and NULL on failure. */
  693. tor_cert_t *
  694. tor_cert_decode(const uint8_t *certificate, size_t certificate_len)
  695. {
  696. X509 *x509;
  697. const unsigned char *cp = (const unsigned char *)certificate;
  698. tor_cert_t *newcert;
  699. tor_assert(certificate);
  700. if (certificate_len > INT_MAX)
  701. return NULL;
  702. #if OPENSSL_VERSION_NUMBER < 0x00908000l
  703. /* This ifdef suppresses a type warning. Take out this case once everybody
  704. * is using OpenSSL 0.9.8 or later. */
  705. x509 = d2i_X509(NULL, (unsigned char**)&cp, (int)certificate_len);
  706. #else
  707. x509 = d2i_X509(NULL, &cp, (int)certificate_len);
  708. #endif
  709. if (!x509)
  710. return NULL; /* Couldn't decode */
  711. if (cp - certificate != (int)certificate_len) {
  712. X509_free(x509);
  713. return NULL; /* Didn't use all the bytes */
  714. }
  715. newcert = tor_cert_new(x509);
  716. if (!newcert) {
  717. return NULL;
  718. }
  719. if (newcert->encoded_len != certificate_len ||
  720. fast_memneq(newcert->encoded, certificate, certificate_len)) {
  721. /* Cert wasn't in DER */
  722. tor_cert_free(newcert);
  723. return NULL;
  724. }
  725. return newcert;
  726. }
  727. /** Set *<b>encoded_out</b> and *<b>size_out/b> to <b>cert</b>'s encoded DER
  728. * representation and length, respectively. */
  729. void
  730. tor_cert_get_der(const tor_cert_t *cert,
  731. const uint8_t **encoded_out, size_t *size_out)
  732. {
  733. tor_assert(cert);
  734. tor_assert(encoded_out);
  735. tor_assert(size_out);
  736. *encoded_out = cert->encoded;
  737. *size_out = cert->encoded_len;
  738. }
  739. /** Return a set of digests for the public key in <b>cert</b>, or NULL if this
  740. * cert's public key is not one we know how to take the digest of. */
  741. const digests_t *
  742. tor_cert_get_id_digests(const tor_cert_t *cert)
  743. {
  744. if (cert->pkey_digests_set)
  745. return &cert->pkey_digests;
  746. else
  747. return NULL;
  748. }
  749. /** Return a set of digests for the public key in <b>cert</b>. */
  750. const digests_t *
  751. tor_cert_get_cert_digests(const tor_cert_t *cert)
  752. {
  753. return &cert->cert_digests;
  754. }
  755. /** Remove a reference to <b>ctx</b>, and free it if it has no more
  756. * references. */
  757. static void
  758. tor_tls_context_decref(tor_tls_context_t *ctx)
  759. {
  760. tor_assert(ctx);
  761. if (--ctx->refcnt == 0) {
  762. SSL_CTX_free(ctx->ctx);
  763. tor_cert_free(ctx->my_link_cert);
  764. tor_cert_free(ctx->my_id_cert);
  765. tor_cert_free(ctx->my_auth_cert);
  766. crypto_free_pk_env(ctx->link_key);
  767. crypto_free_pk_env(ctx->auth_key);
  768. tor_free(ctx);
  769. }
  770. }
  771. /** Set *<b>link_cert_out</b> and *<b>id_cert_out</b> to the link certificate
  772. * and ID certificate that we're currently using for our V3 in-protocol
  773. * handshake's certificate chain. If <b>server</b> is true, provide the certs
  774. * that we use in server mode; otherwise, provide the certs that we use in
  775. * client mode. */
  776. int
  777. tor_tls_get_my_certs(int server,
  778. const tor_cert_t **link_cert_out,
  779. const tor_cert_t **id_cert_out)
  780. {
  781. tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
  782. if (! ctx)
  783. return -1;
  784. if (link_cert_out)
  785. *link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
  786. if (id_cert_out)
  787. *id_cert_out = ctx->my_id_cert;
  788. return 0;
  789. }
  790. /**
  791. * Return the authentication key that we use to authenticate ourselves as a
  792. * client in the V3 in-protocol handshake.
  793. */
  794. crypto_pk_env_t *
  795. tor_tls_get_my_client_auth_key(void)
  796. {
  797. if (! client_tls_context)
  798. return NULL;
  799. return client_tls_context->auth_key;
  800. }
  801. /**
  802. * Return a newly allocated copy of the public key that a certificate
  803. * certifies. Return NULL if the cert's key is not RSA.
  804. */
  805. crypto_pk_env_t *
  806. tor_tls_cert_get_key(tor_cert_t *cert)
  807. {
  808. crypto_pk_env_t *result = NULL;
  809. EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
  810. RSA *rsa;
  811. if (!pkey)
  812. return NULL;
  813. rsa = EVP_PKEY_get1_RSA(pkey);
  814. if (!rsa) {
  815. EVP_PKEY_free(pkey);
  816. return NULL;
  817. }
  818. result = _crypto_new_pk_env_rsa(rsa);
  819. EVP_PKEY_free(pkey);
  820. return result;
  821. }
  822. /** Return true iff <b>a</b> and <b>b</b> represent the same public key. */
  823. static int
  824. pkey_eq(EVP_PKEY *a, EVP_PKEY *b)
  825. {
  826. /* We'd like to do this, but openssl 0.9.7 doesn't have it:
  827. return EVP_PKEY_cmp(a,b) == 1;
  828. */
  829. unsigned char *a_enc=NULL, *b_enc=NULL, *a_ptr, *b_ptr;
  830. int a_len1, b_len1, a_len2, b_len2, result;
  831. a_len1 = i2d_PublicKey(a, NULL);
  832. b_len1 = i2d_PublicKey(b, NULL);
  833. if (a_len1 != b_len1)
  834. return 0;
  835. a_ptr = a_enc = tor_malloc(a_len1);
  836. b_ptr = b_enc = tor_malloc(b_len1);
  837. a_len2 = i2d_PublicKey(a, &a_ptr);
  838. b_len2 = i2d_PublicKey(b, &b_ptr);
  839. tor_assert(a_len2 == a_len1);
  840. tor_assert(b_len2 == b_len1);
  841. result = tor_memeq(a_enc, b_enc, a_len1);
  842. tor_free(a_enc);
  843. tor_free(b_enc);
  844. return result;
  845. }
  846. /** Return true iff the other side of <b>tls</b> has authenticated to us, and
  847. * the key certified in <b>cert</b> is the same as the key they used to do it.
  848. */
  849. int
  850. tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_cert_t *cert)
  851. {
  852. X509 *peercert = SSL_get_peer_certificate(tls->ssl);
  853. EVP_PKEY *link_key = NULL, *cert_key = NULL;
  854. int result;
  855. if (!peercert)
  856. return 0;
  857. link_key = X509_get_pubkey(peercert);
  858. cert_key = X509_get_pubkey(cert->cert);
  859. result = link_key && cert_key && pkey_eq(cert_key, link_key);
  860. X509_free(peercert);
  861. if (link_key)
  862. EVP_PKEY_free(link_key);
  863. if (cert_key)
  864. EVP_PKEY_free(cert_key);
  865. return result;
  866. }
  867. /** Check whether <b>cert</b> is well-formed, currently live, and correctly
  868. * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
  869. * make sure that it has an RSA key with 1024 bits; otherwise, just check that
  870. * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
  871. * we couldn't check it. */
  872. int
  873. tor_tls_cert_is_valid(int severity,
  874. const tor_cert_t *cert,
  875. const tor_cert_t *signing_cert,
  876. int check_rsa_1024)
  877. {
  878. EVP_PKEY *cert_key;
  879. EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
  880. int r, key_ok = 0;
  881. if (!signing_key)
  882. return 0;
  883. r = X509_verify(cert->cert, signing_key);
  884. EVP_PKEY_free(signing_key);
  885. if (r <= 0)
  886. return 0;
  887. /* okay, the signature checked out right. Now let's check the check the
  888. * lifetime. */
  889. if (check_cert_lifetime_internal(severity, cert->cert,
  890. 48*60*60, 30*24*60*60) < 0)
  891. return 0;
  892. cert_key = X509_get_pubkey(cert->cert);
  893. if (check_rsa_1024 && cert_key) {
  894. RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
  895. if (rsa && BN_num_bits(rsa->n) == 1024)
  896. key_ok = 1;
  897. if (rsa)
  898. RSA_free(rsa);
  899. } else if (cert_key) {
  900. int min_bits = 1024;
  901. #ifdef EVP_PKEY_EC
  902. if (EVP_PKEY_type(cert_key->type) == EVP_PKEY_EC)
  903. min_bits = 128;
  904. #endif
  905. if (EVP_PKEY_bits(cert_key) >= min_bits)
  906. key_ok = 1;
  907. }
  908. EVP_PKEY_free(cert_key);
  909. if (!key_ok)
  910. return 0;
  911. /* XXXX compare DNs or anything? */
  912. return 1;
  913. }
  914. /** Increase the reference count of <b>ctx</b>. */
  915. static void
  916. tor_tls_context_incref(tor_tls_context_t *ctx)
  917. {
  918. ++ctx->refcnt;
  919. }
  920. /** Create new global client and server TLS contexts.
  921. *
  922. * If <b>server_identity</b> is NULL, this will not generate a server
  923. * TLS context. If <b>is_public_server</b> is non-zero, this will use
  924. * the same TLS context for incoming and outgoing connections, and
  925. * ignore <b>client_identity</b>. */
  926. int
  927. tor_tls_context_init(int is_public_server,
  928. crypto_pk_env_t *client_identity,
  929. crypto_pk_env_t *server_identity,
  930. unsigned int key_lifetime)
  931. {
  932. int rv1 = 0;
  933. int rv2 = 0;
  934. if (is_public_server) {
  935. tor_tls_context_t *new_ctx;
  936. tor_tls_context_t *old_ctx;
  937. tor_assert(server_identity != NULL);
  938. rv1 = tor_tls_context_init_one(&server_tls_context,
  939. server_identity,
  940. key_lifetime, 0);
  941. if (rv1 >= 0) {
  942. new_ctx = server_tls_context;
  943. tor_tls_context_incref(new_ctx);
  944. old_ctx = client_tls_context;
  945. client_tls_context = new_ctx;
  946. if (old_ctx != NULL) {
  947. tor_tls_context_decref(old_ctx);
  948. }
  949. }
  950. } else {
  951. if (server_identity != NULL) {
  952. rv1 = tor_tls_context_init_one(&server_tls_context,
  953. server_identity,
  954. key_lifetime,
  955. 0);
  956. } else {
  957. tor_tls_context_t *old_ctx = server_tls_context;
  958. server_tls_context = NULL;
  959. if (old_ctx != NULL) {
  960. tor_tls_context_decref(old_ctx);
  961. }
  962. }
  963. rv2 = tor_tls_context_init_one(&client_tls_context,
  964. client_identity,
  965. key_lifetime,
  966. 1);
  967. }
  968. return MIN(rv1, rv2);
  969. }
  970. /** Create a new global TLS context.
  971. *
  972. * You can call this function multiple times. Each time you call it,
  973. * it generates new certificates; all new connections will use
  974. * the new SSL context.
  975. */
  976. static int
  977. tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  978. crypto_pk_env_t *identity,
  979. unsigned int key_lifetime,
  980. int is_client)
  981. {
  982. tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
  983. key_lifetime,
  984. is_client);
  985. tor_tls_context_t *old_ctx = *ppcontext;
  986. if (new_ctx != NULL) {
  987. *ppcontext = new_ctx;
  988. /* Free the old context if one existed. */
  989. if (old_ctx != NULL) {
  990. /* This is safe even if there are open connections: we reference-
  991. * count tor_tls_context_t objects. */
  992. tor_tls_context_decref(old_ctx);
  993. }
  994. }
  995. return ((new_ctx != NULL) ? 0 : -1);
  996. }
  997. /** Create a new TLS context for use with Tor TLS handshakes.
  998. * <b>identity</b> should be set to the identity key used to sign the
  999. * certificate.
  1000. */
  1001. static tor_tls_context_t *
  1002. tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime,
  1003. int is_client)
  1004. {
  1005. crypto_pk_env_t *rsa = NULL, *rsa_auth = NULL;
  1006. EVP_PKEY *pkey = NULL;
  1007. tor_tls_context_t *result = NULL;
  1008. X509 *cert = NULL, *idcert = NULL, *authcert = NULL;
  1009. char *nickname = NULL, *nn2 = NULL;
  1010. tor_tls_init();
  1011. nickname = crypto_random_hostname(8, 20, "www.", ".net");
  1012. #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
  1013. nn2 = crypto_random_hostname(8, 20, "www.", ".net");
  1014. #else
  1015. nn2 = crypto_random_hostname(8, 20, "www.", ".com");
  1016. #endif
  1017. /* Generate short-term RSA key for use with TLS. */
  1018. if (!(rsa = crypto_new_pk_env()))
  1019. goto error;
  1020. if (crypto_pk_generate_key(rsa)<0)
  1021. goto error;
  1022. if (!is_client) {
  1023. /* Generate short-term RSA key for use in the in-protocol ("v3")
  1024. * authentication handshake. */
  1025. if (!(rsa_auth = crypto_new_pk_env()))
  1026. goto error;
  1027. if (crypto_pk_generate_key(rsa_auth)<0)
  1028. goto error;
  1029. /* Create a link certificate signed by identity key. */
  1030. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  1031. key_lifetime);
  1032. /* Create self-signed certificate for identity key. */
  1033. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  1034. IDENTITY_CERT_LIFETIME);
  1035. /* Create an authentication certificate signed by identity key. */
  1036. authcert = tor_tls_create_certificate(rsa_auth, identity, nickname, nn2,
  1037. key_lifetime);
  1038. if (!cert || !idcert || !authcert) {
  1039. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  1040. goto error;
  1041. }
  1042. }
  1043. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  1044. result->refcnt = 1;
  1045. if (!is_client) {
  1046. result->my_link_cert = tor_cert_new(X509_dup(cert));
  1047. result->my_id_cert = tor_cert_new(X509_dup(idcert));
  1048. result->my_auth_cert = tor_cert_new(X509_dup(authcert));
  1049. if (!result->my_link_cert || !result->my_id_cert || !result->my_auth_cert)
  1050. goto error;
  1051. result->link_key = crypto_pk_dup_key(rsa);
  1052. result->auth_key = crypto_pk_dup_key(rsa_auth);
  1053. }
  1054. #ifdef EVERYONE_HAS_AES
  1055. /* Tell OpenSSL to only use TLS1 */
  1056. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  1057. goto error;
  1058. #else
  1059. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  1060. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  1061. goto error;
  1062. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  1063. #endif
  1064. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  1065. #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  1066. SSL_CTX_set_options(result->ctx,
  1067. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1068. #endif
  1069. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1070. * as authenticating any earlier-received data.
  1071. */
  1072. if (use_unsafe_renegotiation_op) {
  1073. SSL_CTX_set_options(result->ctx,
  1074. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1075. }
  1076. /* Don't actually allow compression; it uses ram and time, but the data
  1077. * we transmit is all encrypted anyway. */
  1078. if (result->ctx->comp_methods)
  1079. result->ctx->comp_methods = NULL;
  1080. #ifdef SSL_MODE_RELEASE_BUFFERS
  1081. SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
  1082. #endif
  1083. if (! is_client) {
  1084. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  1085. goto error;
  1086. X509_free(cert); /* We just added a reference to cert. */
  1087. cert=NULL;
  1088. if (idcert) {
  1089. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  1090. tor_assert(s);
  1091. X509_STORE_add_cert(s, idcert);
  1092. X509_free(idcert); /* The context now owns the reference to idcert */
  1093. idcert = NULL;
  1094. }
  1095. }
  1096. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  1097. if (!is_client) {
  1098. tor_assert(rsa);
  1099. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  1100. goto error;
  1101. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  1102. goto error;
  1103. EVP_PKEY_free(pkey);
  1104. pkey = NULL;
  1105. if (!SSL_CTX_check_private_key(result->ctx))
  1106. goto error;
  1107. }
  1108. {
  1109. crypto_dh_env_t *dh = crypto_dh_new(DH_TYPE_TLS);
  1110. tor_assert(dh);
  1111. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  1112. crypto_dh_free(dh);
  1113. }
  1114. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  1115. always_accept_verify_cb);
  1116. /* let us realloc bufs that we're writing from */
  1117. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  1118. if (rsa)
  1119. crypto_free_pk_env(rsa);
  1120. if (rsa_auth)
  1121. crypto_free_pk_env(rsa_auth);
  1122. X509_free(authcert);
  1123. tor_free(nickname);
  1124. tor_free(nn2);
  1125. return result;
  1126. error:
  1127. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
  1128. tor_free(nickname);
  1129. tor_free(nn2);
  1130. if (pkey)
  1131. EVP_PKEY_free(pkey);
  1132. if (rsa)
  1133. crypto_free_pk_env(rsa);
  1134. if (rsa_auth)
  1135. crypto_free_pk_env(rsa_auth);
  1136. if (result)
  1137. tor_tls_context_decref(result);
  1138. if (cert)
  1139. X509_free(cert);
  1140. if (idcert)
  1141. X509_free(idcert);
  1142. if (authcert)
  1143. X509_free(authcert);
  1144. return NULL;
  1145. }
  1146. #ifdef V2_HANDSHAKE_SERVER
  1147. /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
  1148. * a list that indicates that the client knows how to do the v2 TLS connection
  1149. * handshake. */
  1150. static int
  1151. tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
  1152. {
  1153. int i;
  1154. SSL_SESSION *session;
  1155. /* If we reached this point, we just got a client hello. See if there is
  1156. * a cipher list. */
  1157. if (!(session = SSL_get_session((SSL *)ssl))) {
  1158. log_info(LD_NET, "No session on TLS?");
  1159. return 0;
  1160. }
  1161. if (!session->ciphers) {
  1162. log_info(LD_NET, "No ciphers on session");
  1163. return 0;
  1164. }
  1165. /* Now we need to see if there are any ciphers whose presence means we're
  1166. * dealing with an updated Tor. */
  1167. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  1168. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  1169. const char *ciphername = SSL_CIPHER_get_name(cipher);
  1170. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  1171. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  1172. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  1173. strcmp(ciphername, "(NONE)")) {
  1174. log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
  1175. // return 1;
  1176. goto dump_list;
  1177. }
  1178. }
  1179. return 0;
  1180. dump_list:
  1181. {
  1182. smartlist_t *elts = smartlist_create();
  1183. char *s;
  1184. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  1185. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  1186. const char *ciphername = SSL_CIPHER_get_name(cipher);
  1187. smartlist_add(elts, (char*)ciphername);
  1188. }
  1189. s = smartlist_join_strings(elts, ":", 0, NULL);
  1190. log_debug(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
  1191. address, s);
  1192. tor_free(s);
  1193. smartlist_free(elts);
  1194. }
  1195. return 1;
  1196. }
  1197. /** We got an SSL ClientHello message. This might mean that the
  1198. * client wants to initiate a renegotiation and appropriate actions
  1199. * must be taken. */
  1200. static void
  1201. tor_tls_got_client_hello(tor_tls_t *tls)
  1202. {
  1203. if (tls->server_handshake_count < 3)
  1204. ++tls->server_handshake_count;
  1205. if (tls->server_handshake_count == 2) {
  1206. if (!tls->negotiated_callback) {
  1207. log_warn(LD_BUG, "Got a renegotiation request but we don't"
  1208. " have a renegotiation callback set!");
  1209. }
  1210. tls->got_renegotiate = 1;
  1211. } else if (tls->server_handshake_count > 2) {
  1212. /* We got more than one renegotiation requests. The Tor protocol
  1213. needs just one renegotiation; more than that probably means
  1214. They are trying to DoS us and we have to stop them. We can't
  1215. close their connection from in here since it's an OpenSSL
  1216. callback, so we set a libevent timer that triggers in the next
  1217. event loop and closes the connection. */
  1218. struct timeval zero_seconds_timer = {0,0};
  1219. if (tor_event_base_once(tls->excess_renegotiations_callback,
  1220. tls->callback_arg, &zero_seconds_timer) < 0) {
  1221. log_warn(LD_GENERAL, "Didn't manage to set a renegotiation limiting callback.");
  1222. }
  1223. }
  1224. /* Now check the cipher list. */
  1225. if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
  1226. /*XXXX_TLS keep this from happening more than once! */
  1227. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  1228. * Let's hope openssl doesn't notice! */
  1229. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  1230. SSL_set_mode((SSL*) tls->ssl, SSL_MODE_NO_AUTO_CHAIN);
  1231. /* Don't send a hello request. */
  1232. SSL_set_verify((SSL*) tls->ssl, SSL_VERIFY_NONE, NULL);
  1233. if (tls) {
  1234. tls->wasV2Handshake = 1;
  1235. #ifdef USE_BUFFEREVENTS
  1236. if (use_unsafe_renegotiation_flag)
  1237. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1238. #endif
  1239. } else {
  1240. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  1241. }
  1242. }
  1243. }
  1244. #endif
  1245. /** This is a callback function for SSL_set_info_callback() and it
  1246. * will be called in every SSL state change.
  1247. * It logs the SSL state change, and executes any actions that must be
  1248. * taken. */
  1249. static void
  1250. tor_tls_state_changed_callback(const SSL *ssl, int type, int val)
  1251. {
  1252. log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
  1253. ssl, ssl_state_to_string(ssl->state), type, val);
  1254. #ifdef V2_HANDSHAKE_SERVER
  1255. if (type == SSL_CB_ACCEPT_LOOP &&
  1256. ssl->state == SSL3_ST_SW_SRVR_HELLO_A) {
  1257. /* Call tor_tls_got_client_hello() for every SSL ClientHello we
  1258. receive. */
  1259. tor_tls_t *tls = tor_tls_get_by_ssl(ssl);
  1260. if (!tls) {
  1261. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  1262. return;
  1263. }
  1264. tor_tls_got_client_hello(tls);
  1265. }
  1266. #endif
  1267. }
  1268. /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
  1269. * a list designed to mimic a common web browser. Some of the ciphers in the
  1270. * list won't actually be implemented by OpenSSL: that's okay so long as the
  1271. * server doesn't select them, and the server won't select anything besides
  1272. * what's in SERVER_CIPHER_LIST.
  1273. *
  1274. * [If the server <b>does</b> select a bogus cipher, we won't crash or
  1275. * anything; we'll just fail later when we try to look up the cipher in
  1276. * ssl->cipher_list_by_id.]
  1277. */
  1278. static void
  1279. rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
  1280. {
  1281. #ifdef V2_HANDSHAKE_CLIENT
  1282. if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
  1283. /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
  1284. * we want.*/
  1285. int i = 0, j = 0;
  1286. /* First, create a dummy SSL_CIPHER for every cipher. */
  1287. CLIENT_CIPHER_DUMMIES =
  1288. tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
  1289. for (i=0; i < N_CLIENT_CIPHERS; ++i) {
  1290. CLIENT_CIPHER_DUMMIES[i].valid = 1;
  1291. CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
  1292. CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
  1293. }
  1294. CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
  1295. tor_assert(CLIENT_CIPHER_STACK);
  1296. log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
  1297. for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
  1298. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
  1299. log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
  1300. }
  1301. /* Then copy as many ciphers as we can from the good list, inserting
  1302. * dummies as needed. */
  1303. j=0;
  1304. for (i = 0; i < N_CLIENT_CIPHERS; ) {
  1305. SSL_CIPHER *cipher = NULL;
  1306. if (j < sk_SSL_CIPHER_num(*ciphers))
  1307. cipher = sk_SSL_CIPHER_value(*ciphers, j);
  1308. if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
  1309. log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
  1310. ++j;
  1311. } else if (cipher &&
  1312. (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
  1313. log_debug(LD_NET, "Found cipher %s", cipher->name);
  1314. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
  1315. ++j;
  1316. ++i;
  1317. } else {
  1318. log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
  1319. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
  1320. ++i;
  1321. }
  1322. }
  1323. }
  1324. sk_SSL_CIPHER_free(*ciphers);
  1325. *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
  1326. tor_assert(*ciphers);
  1327. #else
  1328. (void)ciphers;
  1329. #endif
  1330. }
  1331. /** Create a new TLS object from a file descriptor, and a flag to
  1332. * determine whether it is functioning as a server.
  1333. */
  1334. tor_tls_t *
  1335. tor_tls_new(int sock, int isServer)
  1336. {
  1337. BIO *bio = NULL;
  1338. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  1339. tor_tls_context_t *context = isServer ? server_tls_context :
  1340. client_tls_context;
  1341. result->magic = TOR_TLS_MAGIC;
  1342. tor_assert(context); /* make sure somebody made it first */
  1343. if (!(result->ssl = SSL_new(context->ctx))) {
  1344. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
  1345. tor_free(result);
  1346. return NULL;
  1347. }
  1348. #ifdef SSL_set_tlsext_host_name
  1349. /* Browsers use the TLS hostname extension, so we should too. */
  1350. if (!isServer) {
  1351. char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
  1352. SSL_set_tlsext_host_name(result->ssl, fake_hostname);
  1353. tor_free(fake_hostname);
  1354. }
  1355. #endif
  1356. if (!SSL_set_cipher_list(result->ssl,
  1357. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  1358. tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
  1359. #ifdef SSL_set_tlsext_host_name
  1360. SSL_set_tlsext_host_name(result->ssl, NULL);
  1361. #endif
  1362. SSL_free(result->ssl);
  1363. tor_free(result);
  1364. return NULL;
  1365. }
  1366. if (!isServer)
  1367. rectify_client_ciphers(&result->ssl->cipher_list);
  1368. result->socket = sock;
  1369. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1370. if (! bio) {
  1371. tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
  1372. #ifdef SSL_set_tlsext_host_name
  1373. SSL_set_tlsext_host_name(result->ssl, NULL);
  1374. #endif
  1375. SSL_free(result->ssl);
  1376. tor_free(result);
  1377. return NULL;
  1378. }
  1379. {
  1380. int set_worked =
  1381. SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
  1382. if (!set_worked) {
  1383. log_warn(LD_BUG,
  1384. "Couldn't set the tls for an SSL*; connection will fail");
  1385. }
  1386. }
  1387. SSL_set_bio(result->ssl, bio, bio);
  1388. tor_tls_context_incref(context);
  1389. result->context = context;
  1390. result->state = TOR_TLS_ST_HANDSHAKE;
  1391. result->isServer = isServer;
  1392. result->wantwrite_n = 0;
  1393. result->last_write_count = BIO_number_written(bio);
  1394. result->last_read_count = BIO_number_read(bio);
  1395. if (result->last_write_count || result->last_read_count) {
  1396. log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
  1397. result->last_read_count, result->last_write_count);
  1398. }
  1399. SSL_set_info_callback(result->ssl, tor_tls_state_changed_callback);
  1400. /* Not expected to get called. */
  1401. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
  1402. return result;
  1403. }
  1404. /** Make future log messages about <b>tls</b> display the address
  1405. * <b>address</b>.
  1406. */
  1407. void
  1408. tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
  1409. {
  1410. tor_assert(tls);
  1411. tor_free(tls->address);
  1412. tls->address = tor_strdup(address);
  1413. }
  1414. /** Set <b>cb</b> to be called with argument <b>arg</b> whenever
  1415. * <b>tls</b> next gets a client-side renegotiate in the middle of a
  1416. * read. Set <b>cb2</b> to be called with argument <b>arg</b> whenever
  1417. * <b>tls</b> gets excess renegotiation requests. Do not invoke this
  1418. * function until <em>after</em> initial handshaking is done!
  1419. */
  1420. void
  1421. tor_tls_set_renegotiate_callbacks(tor_tls_t *tls,
  1422. void (*cb)(tor_tls_t *, void *arg),
  1423. void (*cb2)(evutil_socket_t, short, void *),
  1424. void *arg)
  1425. {
  1426. tls->negotiated_callback = cb;
  1427. tls->excess_renegotiations_callback = cb2;
  1428. tls->callback_arg = arg;
  1429. tls->got_renegotiate = 0;
  1430. SSL_set_info_callback(tls->ssl, tor_tls_state_changed_callback);
  1431. }
  1432. /** If this version of openssl requires it, turn on renegotiation on
  1433. * <b>tls</b>.
  1434. */
  1435. void
  1436. tor_tls_unblock_renegotiation(tor_tls_t *tls)
  1437. {
  1438. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1439. * as authenticating any earlier-received data. */
  1440. if (use_unsafe_renegotiation_flag) {
  1441. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1442. }
  1443. if (use_unsafe_renegotiation_op) {
  1444. SSL_set_options(tls->ssl,
  1445. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1446. }
  1447. }
  1448. void
  1449. tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
  1450. {
  1451. if (use_unsafe_renegotiation_flag) {
  1452. tor_assert(0 != (tls->ssl->s3->flags &
  1453. SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1454. }
  1455. if (use_unsafe_renegotiation_op) {
  1456. long options = SSL_get_options(tls->ssl);
  1457. tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1458. }
  1459. }
  1460. /** Return whether this tls initiated the connect (client) or
  1461. * received it (server). */
  1462. int
  1463. tor_tls_is_server(tor_tls_t *tls)
  1464. {
  1465. tor_assert(tls);
  1466. return tls->isServer;
  1467. }
  1468. /** Release resources associated with a TLS object. Does not close the
  1469. * underlying file descriptor.
  1470. */
  1471. void
  1472. tor_tls_free(tor_tls_t *tls)
  1473. {
  1474. if (!tls)
  1475. return;
  1476. tor_assert(tls->ssl);
  1477. #ifdef SSL_set_tlsext_host_name
  1478. SSL_set_tlsext_host_name(tls->ssl, NULL);
  1479. #endif
  1480. SSL_free(tls->ssl);
  1481. tls->ssl = NULL;
  1482. tls->negotiated_callback = NULL;
  1483. tls->excess_renegotiations_callback = NULL;
  1484. if (tls->context)
  1485. tor_tls_context_decref(tls->context);
  1486. tor_free(tls->address);
  1487. tls->magic = 0x99999999;
  1488. tor_free(tls);
  1489. }
  1490. /** Underlying function for TLS reading. Reads up to <b>len</b>
  1491. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  1492. * number of characters read. On failure, returns TOR_TLS_ERROR,
  1493. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1494. */
  1495. int
  1496. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  1497. {
  1498. int r, err;
  1499. tor_assert(tls);
  1500. tor_assert(tls->ssl);
  1501. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1502. tor_assert(len<INT_MAX);
  1503. r = SSL_read(tls->ssl, cp, (int)len);
  1504. if (r > 0) /* return the number of characters read */
  1505. return r;
  1506. /* If we got here, SSL_read() did not go as expected. */
  1507. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
  1508. #ifdef V2_HANDSHAKE_SERVER
  1509. if (tls->got_renegotiate) {
  1510. if (tls->server_handshake_count != 2) {
  1511. log_warn(LD_BUG, "We did not notice renegotiation in a timely fashion (%u)!",
  1512. tls->server_handshake_count);
  1513. }
  1514. /* Renegotiation happened! */
  1515. log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
  1516. if (tls->negotiated_callback)
  1517. tls->negotiated_callback(tls, tls->callback_arg);
  1518. tls->got_renegotiate = 0;
  1519. return r;
  1520. }
  1521. #endif
  1522. if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
  1523. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  1524. tls->state = TOR_TLS_ST_CLOSED;
  1525. return TOR_TLS_CLOSE;
  1526. } else {
  1527. tor_assert(err != TOR_TLS_DONE);
  1528. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  1529. return err;
  1530. }
  1531. }
  1532. /** Underlying function for TLS writing. Write up to <b>n</b>
  1533. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  1534. * number of characters written. On failure, returns TOR_TLS_ERROR,
  1535. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1536. */
  1537. int
  1538. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  1539. {
  1540. int r, err;
  1541. tor_assert(tls);
  1542. tor_assert(tls->ssl);
  1543. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1544. tor_assert(n < INT_MAX);
  1545. if (n == 0)
  1546. return 0;
  1547. if (tls->wantwrite_n) {
  1548. /* if WANTWRITE last time, we must use the _same_ n as before */
  1549. tor_assert(n >= tls->wantwrite_n);
  1550. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  1551. (int)n, (int)tls->wantwrite_n);
  1552. n = tls->wantwrite_n;
  1553. tls->wantwrite_n = 0;
  1554. }
  1555. r = SSL_write(tls->ssl, cp, (int)n);
  1556. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
  1557. if (err == TOR_TLS_DONE) {
  1558. return r;
  1559. }
  1560. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  1561. tls->wantwrite_n = n;
  1562. }
  1563. return err;
  1564. }
  1565. /** Perform initial handshake on <b>tls</b>. When finished, returns
  1566. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1567. * or TOR_TLS_WANTWRITE.
  1568. */
  1569. int
  1570. tor_tls_handshake(tor_tls_t *tls)
  1571. {
  1572. int r;
  1573. int oldstate;
  1574. tor_assert(tls);
  1575. tor_assert(tls->ssl);
  1576. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  1577. check_no_tls_errors();
  1578. oldstate = tls->ssl->state;
  1579. if (tls->isServer) {
  1580. log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
  1581. ssl_state_to_string(tls->ssl->state));
  1582. r = SSL_accept(tls->ssl);
  1583. } else {
  1584. log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
  1585. ssl_state_to_string(tls->ssl->state));
  1586. r = SSL_connect(tls->ssl);
  1587. }
  1588. if (oldstate != tls->ssl->state)
  1589. log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
  1590. tls, ssl_state_to_string(tls->ssl->state));
  1591. /* We need to call this here and not earlier, since OpenSSL has a penchant
  1592. * for clearing its flags when you say accept or connect. */
  1593. tor_tls_unblock_renegotiation(tls);
  1594. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
  1595. if (ERR_peek_error() != 0) {
  1596. tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
  1597. "handshaking");
  1598. return TOR_TLS_ERROR_MISC;
  1599. }
  1600. if (r == TOR_TLS_DONE) {
  1601. tls->state = TOR_TLS_ST_OPEN;
  1602. return tor_tls_finish_handshake(tls);
  1603. }
  1604. return r;
  1605. }
  1606. /** Perform the final part of the intial TLS handshake on <b>tls</b>. This
  1607. * should be called for the first handshake only: it determines whether the v1
  1608. * or the v2 handshake was used, and adjusts things for the renegotiation
  1609. * handshake as appropriate.
  1610. *
  1611. * tor_tls_handshake() calls this on its own; you only need to call this if
  1612. * bufferevent is doing the handshake for you.
  1613. */
  1614. int
  1615. tor_tls_finish_handshake(tor_tls_t *tls)
  1616. {
  1617. int r = TOR_TLS_DONE;
  1618. if (tls->isServer) {
  1619. SSL_set_info_callback(tls->ssl, NULL);
  1620. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
  1621. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  1622. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  1623. #ifdef V2_HANDSHAKE_SERVER
  1624. if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
  1625. /* This check is redundant, but back when we did it in the callback,
  1626. * we might have not been able to look up the tor_tls_t if the code
  1627. * was buggy. Fixing that. */
  1628. if (!tls->wasV2Handshake) {
  1629. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  1630. " get set. Fixing that.");
  1631. }
  1632. tls->wasV2Handshake = 1;
  1633. log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
  1634. " for renegotiation.");
  1635. } else {
  1636. tls->wasV2Handshake = 0;
  1637. }
  1638. #endif
  1639. } else {
  1640. #ifdef V2_HANDSHAKE_CLIENT
  1641. /* If we got no ID cert, we're a v2 handshake. */
  1642. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  1643. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  1644. int n_certs = sk_X509_num(chain);
  1645. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0))) {
  1646. log_debug(LD_HANDSHAKE, "Server sent back multiple certificates; it "
  1647. "looks like a v1 handshake on %p", tls);
  1648. tls->wasV2Handshake = 0;
  1649. } else {
  1650. log_debug(LD_HANDSHAKE,
  1651. "Server sent back a single certificate; looks like "
  1652. "a v2 handshake on %p.", tls);
  1653. tls->wasV2Handshake = 1;
  1654. }
  1655. if (cert)
  1656. X509_free(cert);
  1657. #endif
  1658. if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
  1659. tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
  1660. r = TOR_TLS_ERROR_MISC;
  1661. }
  1662. }
  1663. return r;
  1664. }
  1665. #ifdef USE_BUFFEREVENTS
  1666. /** Put <b>tls</b>, which must be a client connection, into renegotiation
  1667. * mode. */
  1668. int
  1669. tor_tls_start_renegotiating(tor_tls_t *tls)
  1670. {
  1671. int r = SSL_renegotiate(tls->ssl);
  1672. if (r <= 0) {
  1673. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1674. LD_HANDSHAKE);
  1675. }
  1676. return 0;
  1677. }
  1678. #endif
  1679. /** Client only: Renegotiate a TLS session. When finished, returns
  1680. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  1681. * TOR_TLS_WANTWRITE.
  1682. */
  1683. int
  1684. tor_tls_renegotiate(tor_tls_t *tls)
  1685. {
  1686. int r;
  1687. tor_assert(tls);
  1688. /* We could do server-initiated renegotiation too, but that would be tricky.
  1689. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  1690. tor_assert(!tls->isServer);
  1691. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  1692. int r = SSL_renegotiate(tls->ssl);
  1693. if (r <= 0) {
  1694. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1695. LD_HANDSHAKE);
  1696. }
  1697. tls->state = TOR_TLS_ST_RENEGOTIATE;
  1698. }
  1699. r = SSL_do_handshake(tls->ssl);
  1700. if (r == 1) {
  1701. tls->state = TOR_TLS_ST_OPEN;
  1702. return TOR_TLS_DONE;
  1703. } else
  1704. return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO,
  1705. LD_HANDSHAKE);
  1706. }
  1707. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  1708. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1709. * or TOR_TLS_WANTWRITE.
  1710. */
  1711. int
  1712. tor_tls_shutdown(tor_tls_t *tls)
  1713. {
  1714. int r, err;
  1715. char buf[128];
  1716. tor_assert(tls);
  1717. tor_assert(tls->ssl);
  1718. while (1) {
  1719. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  1720. /* If we've already called shutdown once to send a close message,
  1721. * we read until the other side has closed too.
  1722. */
  1723. do {
  1724. r = SSL_read(tls->ssl, buf, 128);
  1725. } while (r>0);
  1726. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  1727. LOG_INFO, LD_NET);
  1728. if (err == _TOR_TLS_ZERORETURN) {
  1729. tls->state = TOR_TLS_ST_GOTCLOSE;
  1730. /* fall through... */
  1731. } else {
  1732. return err;
  1733. }
  1734. }
  1735. r = SSL_shutdown(tls->ssl);
  1736. if (r == 1) {
  1737. /* If shutdown returns 1, the connection is entirely closed. */
  1738. tls->state = TOR_TLS_ST_CLOSED;
  1739. return TOR_TLS_DONE;
  1740. }
  1741. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  1742. LOG_INFO, LD_NET);
  1743. if (err == _TOR_TLS_SYSCALL) {
  1744. /* The underlying TCP connection closed while we were shutting down. */
  1745. tls->state = TOR_TLS_ST_CLOSED;
  1746. return TOR_TLS_DONE;
  1747. } else if (err == _TOR_TLS_ZERORETURN) {
  1748. /* The TLS connection says that it sent a shutdown record, but
  1749. * isn't done shutting down yet. Make sure that this hasn't
  1750. * happened before, then go back to the start of the function
  1751. * and try to read.
  1752. */
  1753. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  1754. tls->state == TOR_TLS_ST_SENTCLOSE) {
  1755. log(LOG_WARN, LD_NET,
  1756. "TLS returned \"half-closed\" value while already half-closed");
  1757. return TOR_TLS_ERROR_MISC;
  1758. }
  1759. tls->state = TOR_TLS_ST_SENTCLOSE;
  1760. /* fall through ... */
  1761. } else {
  1762. return err;
  1763. }
  1764. } /* end loop */
  1765. }
  1766. /** Return true iff this TLS connection is authenticated.
  1767. */
  1768. int
  1769. tor_tls_peer_has_cert(tor_tls_t *tls)
  1770. {
  1771. X509 *cert;
  1772. cert = SSL_get_peer_certificate(tls->ssl);
  1773. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1774. if (!cert)
  1775. return 0;
  1776. X509_free(cert);
  1777. return 1;
  1778. }
  1779. /** Return the peer certificate, or NULL if there isn't one. */
  1780. tor_cert_t *
  1781. tor_tls_get_peer_cert(tor_tls_t *tls)
  1782. {
  1783. X509 *cert;
  1784. cert = SSL_get_peer_certificate(tls->ssl);
  1785. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1786. if (!cert)
  1787. return NULL;
  1788. return tor_cert_new(cert);
  1789. }
  1790. /** Warn that a certificate lifetime extends through a certain range. */
  1791. static void
  1792. log_cert_lifetime(int severity, const X509 *cert, const char *problem)
  1793. {
  1794. BIO *bio = NULL;
  1795. BUF_MEM *buf;
  1796. char *s1=NULL, *s2=NULL;
  1797. char mytime[33];
  1798. time_t now = time(NULL);
  1799. struct tm tm;
  1800. if (problem)
  1801. log(severity, LD_GENERAL,
  1802. "Certificate %s. Either their clock is set wrong, or your clock "
  1803. "is wrong.",
  1804. problem);
  1805. if (!(bio = BIO_new(BIO_s_mem()))) {
  1806. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1807. }
  1808. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1809. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1810. goto end;
  1811. }
  1812. BIO_get_mem_ptr(bio, &buf);
  1813. s1 = tor_strndup(buf->data, buf->length);
  1814. (void)BIO_reset(bio);
  1815. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1816. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1817. goto end;
  1818. }
  1819. BIO_get_mem_ptr(bio, &buf);
  1820. s2 = tor_strndup(buf->data, buf->length);
  1821. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1822. log(severity, LD_GENERAL,
  1823. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1824. s1,s2,mytime);
  1825. end:
  1826. /* Not expected to get invoked */
  1827. tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
  1828. if (bio)
  1829. BIO_free(bio);
  1830. tor_free(s1);
  1831. tor_free(s2);
  1832. }
  1833. /** Helper function: try to extract a link certificate and an identity
  1834. * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
  1835. * *<b>id_cert_out</b> respectively. Log all messages at level
  1836. * <b>severity</b>.
  1837. *
  1838. * Note that a reference is added to cert_out, so it needs to be
  1839. * freed. id_cert_out doesn't. */
  1840. static void
  1841. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1842. X509 **cert_out, X509 **id_cert_out)
  1843. {
  1844. X509 *cert = NULL, *id_cert = NULL;
  1845. STACK_OF(X509) *chain = NULL;
  1846. int num_in_chain, i;
  1847. *cert_out = *id_cert_out = NULL;
  1848. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1849. return;
  1850. *cert_out = cert;
  1851. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1852. return;
  1853. num_in_chain = sk_X509_num(chain);
  1854. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1855. * 2 means we're connecting (client-side), and it's both the link
  1856. * cert and the id_cert.
  1857. */
  1858. if (num_in_chain < 1) {
  1859. log_fn(severity,LD_PROTOCOL,
  1860. "Unexpected number of certificates in chain (%d)",
  1861. num_in_chain);
  1862. return;
  1863. }
  1864. for (i=0; i<num_in_chain; ++i) {
  1865. id_cert = sk_X509_value(chain, i);
  1866. if (X509_cmp(id_cert, cert) != 0)
  1867. break;
  1868. }
  1869. *id_cert_out = id_cert;
  1870. }
  1871. /** If the provided tls connection is authenticated and has a
  1872. * certificate chain that is currently valid and signed, then set
  1873. * *<b>identity_key</b> to the identity certificate's key and return
  1874. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1875. */
  1876. int
  1877. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1878. {
  1879. X509 *cert = NULL, *id_cert = NULL;
  1880. EVP_PKEY *id_pkey = NULL;
  1881. RSA *rsa;
  1882. int r = -1;
  1883. *identity_key = NULL;
  1884. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1885. if (!cert)
  1886. goto done;
  1887. if (!id_cert) {
  1888. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1889. goto done;
  1890. }
  1891. tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
  1892. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1893. X509_verify(cert, id_pkey) <= 0) {
  1894. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1895. tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
  1896. goto done;
  1897. }
  1898. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1899. if (!rsa)
  1900. goto done;
  1901. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1902. r = 0;
  1903. done:
  1904. if (cert)
  1905. X509_free(cert);
  1906. if (id_pkey)
  1907. EVP_PKEY_free(id_pkey);
  1908. /* This should never get invoked, but let's make sure in case OpenSSL
  1909. * acts unexpectedly. */
  1910. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
  1911. return r;
  1912. }
  1913. /** Check whether the certificate set on the connection <b>tls</b> is expired
  1914. * give or take <b>past_tolerance</b> seconds, or not-yet-valid give or take
  1915. * <b>future_tolerance</b> seconds. Return 0 for valid, -1 for failure.
  1916. *
  1917. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1918. */
  1919. int
  1920. tor_tls_check_lifetime(int severity, tor_tls_t *tls,
  1921. int past_tolerance, int future_tolerance)
  1922. {
  1923. X509 *cert;
  1924. int r = -1;
  1925. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1926. goto done;
  1927. if (check_cert_lifetime_internal(severity, cert,
  1928. past_tolerance, future_tolerance) < 0)
  1929. goto done;
  1930. r = 0;
  1931. done:
  1932. if (cert)
  1933. X509_free(cert);
  1934. /* Not expected to get invoked */
  1935. tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
  1936. return r;
  1937. }
  1938. /** Helper: check whether <b>cert</b> is expired give or take
  1939. * <b>past_tolerance</b> seconds, or not-yet-valid give or take
  1940. * <b>future_tolerance</b> seconds. If it is live, return 0. If it is not
  1941. * live, log a message and return -1. */
  1942. static int
  1943. check_cert_lifetime_internal(int severity, const X509 *cert,
  1944. int past_tolerance, int future_tolerance)
  1945. {
  1946. time_t now, t;
  1947. now = time(NULL);
  1948. t = now + future_tolerance;
  1949. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1950. log_cert_lifetime(severity, cert, "not yet valid");
  1951. return -1;
  1952. }
  1953. t = now - past_tolerance;
  1954. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1955. log_cert_lifetime(severity, cert, "already expired");
  1956. return -1;
  1957. }
  1958. return 0;
  1959. }
  1960. /** Return the number of bytes available for reading from <b>tls</b>.
  1961. */
  1962. int
  1963. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1964. {
  1965. tor_assert(tls);
  1966. return SSL_pending(tls->ssl);
  1967. }
  1968. /** If <b>tls</b> requires that the next write be of a particular size,
  1969. * return that size. Otherwise, return 0. */
  1970. size_t
  1971. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1972. {
  1973. return tls->wantwrite_n;
  1974. }
  1975. /** Sets n_read and n_written to the number of bytes read and written,
  1976. * respectively, on the raw socket used by <b>tls</b> since the last time this
  1977. * function was called on <b>tls</b>. */
  1978. void
  1979. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1980. {
  1981. BIO *wbio, *tmpbio;
  1982. unsigned long r, w;
  1983. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1984. /* We want the number of bytes actually for real written. Unfortunately,
  1985. * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
  1986. * which makes the answer turn out wrong. Let's cope with that. Note
  1987. * that this approach will fail if we ever replace tls->ssl's BIOs with
  1988. * buffering bios for reasons of our own. As an alternative, we could
  1989. * save the original BIO for tls->ssl in the tor_tls_t structure, but
  1990. * that would be tempting fate. */
  1991. wbio = SSL_get_wbio(tls->ssl);
  1992. if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
  1993. wbio = tmpbio;
  1994. w = BIO_number_written(wbio);
  1995. /* We are ok with letting these unsigned ints go "negative" here:
  1996. * If we wrapped around, this should still give us the right answer, unless
  1997. * we wrapped around by more than ULONG_MAX since the last time we called
  1998. * this function.
  1999. */
  2000. *n_read = (size_t)(r - tls->last_read_count);
  2001. *n_written = (size_t)(w - tls->last_write_count);
  2002. if (*n_read > INT_MAX || *n_written > INT_MAX) {
  2003. log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
  2004. "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
  2005. r, tls->last_read_count, w, tls->last_write_count);
  2006. }
  2007. tls->last_read_count = r;
  2008. tls->last_write_count = w;
  2009. }
  2010. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  2011. * errors, log an error message. */
  2012. void
  2013. _check_no_tls_errors(const char *fname, int line)
  2014. {
  2015. if (ERR_peek_error() == 0)
  2016. return;
  2017. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  2018. tor_fix_source_file(fname), line);
  2019. tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
  2020. }
  2021. /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
  2022. * TLS handshake. Output is undefined if the handshake isn't finished. */
  2023. int
  2024. tor_tls_used_v1_handshake(tor_tls_t *tls)
  2025. {
  2026. if (tls->isServer) {
  2027. #ifdef V2_HANDSHAKE_SERVER
  2028. return ! tls->wasV2Handshake;
  2029. #endif
  2030. } else {
  2031. #ifdef V2_HANDSHAKE_CLIENT
  2032. return ! tls->wasV2Handshake;
  2033. #endif
  2034. }
  2035. return 1;
  2036. }
  2037. /** Return true iff <b>name</b> is a DN of a kind that could only
  2038. * occur in a v3-handshake-indicating certificate */
  2039. static int
  2040. dn_indicates_v3_cert(X509_NAME *name)
  2041. {
  2042. #ifdef DISABLE_V3_LINKPROTO_CLIENTSIDE
  2043. (void)name;
  2044. return 0;
  2045. #else
  2046. X509_NAME_ENTRY *entry;
  2047. int n_entries;
  2048. ASN1_OBJECT *obj;
  2049. ASN1_STRING *str;
  2050. unsigned char *s;
  2051. int len, r;
  2052. n_entries = X509_NAME_entry_count(name);
  2053. if (n_entries != 1)
  2054. return 1; /* More than one entry in the DN. */
  2055. entry = X509_NAME_get_entry(name, 0);
  2056. obj = X509_NAME_ENTRY_get_object(entry);
  2057. if (OBJ_obj2nid(obj) != OBJ_txt2nid("commonName"))
  2058. return 1; /* The entry isn't a commonName. */
  2059. str = X509_NAME_ENTRY_get_data(entry);
  2060. len = ASN1_STRING_to_UTF8(&s, str);
  2061. if (len < 0)
  2062. return 0;
  2063. r = fast_memneq(s + len - 4, ".net", 4);
  2064. OPENSSL_free(s);
  2065. return r;
  2066. #endif
  2067. }
  2068. /** Return true iff the peer certificate we're received on <b>tls</b>
  2069. * indicates that this connection should use the v3 (in-protocol)
  2070. * authentication handshake.
  2071. *
  2072. * Only the connection initiator should use this, and only once the initial
  2073. * handshake is done; the responder detects a v1 handshake by cipher types,
  2074. * and a v3/v2 handshake by Versions cell vs renegotiation.
  2075. */
  2076. int
  2077. tor_tls_received_v3_certificate(tor_tls_t *tls)
  2078. {
  2079. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  2080. EVP_PKEY *key = NULL;
  2081. X509_NAME *issuer_name, *subject_name;
  2082. int is_v3 = 0;
  2083. if (!cert) {
  2084. log_warn(LD_BUG, "Called on a connection with no peer certificate");
  2085. goto done;
  2086. }
  2087. subject_name = X509_get_subject_name(cert);
  2088. issuer_name = X509_get_issuer_name(cert);
  2089. if (X509_name_cmp(subject_name, issuer_name) == 0) {
  2090. is_v3 = 1; /* purportedly self signed */
  2091. goto done;
  2092. }
  2093. if (dn_indicates_v3_cert(subject_name) ||
  2094. dn_indicates_v3_cert(issuer_name)) {
  2095. is_v3 = 1; /* DN is fancy */
  2096. goto done;
  2097. }
  2098. key = X509_get_pubkey(cert);
  2099. if (EVP_PKEY_bits(key) != 1024 ||
  2100. EVP_PKEY_type(key->type) != EVP_PKEY_RSA) {
  2101. is_v3 = 1; /* Key is fancy */
  2102. goto done;
  2103. }
  2104. done:
  2105. if (key)
  2106. EVP_PKEY_free(key);
  2107. if (cert)
  2108. X509_free(cert);
  2109. return is_v3;
  2110. }
  2111. /** Return the number of server handshakes that we've noticed doing on
  2112. * <b>tls</b>. */
  2113. int
  2114. tor_tls_get_num_server_handshakes(tor_tls_t *tls)
  2115. {
  2116. return tls->server_handshake_count;
  2117. }
  2118. /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
  2119. * request it was waiting for. */
  2120. int
  2121. tor_tls_server_got_renegotiate(tor_tls_t *tls)
  2122. {
  2123. return tls->got_renegotiate;
  2124. }
  2125. /** Set the DIGEST256_LEN buffer at <b>secrets_out</b> to the value used in
  2126. * the v3 handshake to prove that the client knows the TLS secrets for the
  2127. * connection <b>tls</b>. Return 0 on success, -1 on failure.
  2128. */
  2129. int
  2130. tor_tls_get_tlssecrets(tor_tls_t *tls, uint8_t *secrets_out)
  2131. {
  2132. #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
  2133. char buf[128];
  2134. size_t len;
  2135. tor_assert(tls);
  2136. tor_assert(tls->ssl);
  2137. tor_assert(tls->ssl->s3);
  2138. tor_assert(tls->ssl->session);
  2139. /*
  2140. The value is an HMAC, using the TLS master key as the HMAC key, of
  2141. client_random | server_random | TLSSECRET_MAGIC
  2142. */
  2143. memcpy(buf + 0, tls->ssl->s3->client_random, 32);
  2144. memcpy(buf + 32, tls->ssl->s3->server_random, 32);
  2145. memcpy(buf + 64, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
  2146. len = 64 + strlen(TLSSECRET_MAGIC) + 1;
  2147. crypto_hmac_sha256((char*)secrets_out,
  2148. (char*)tls->ssl->session->master_key,
  2149. tls->ssl->session->master_key_length,
  2150. buf, len);
  2151. memset(buf, 0, sizeof(buf));
  2152. return 0;
  2153. }
  2154. /** Examine the amount of memory used and available for buffers in <b>tls</b>.
  2155. * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
  2156. * buffer and *<b>rbuf_bytes</b> to the amount actually used.
  2157. * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
  2158. * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
  2159. void
  2160. tor_tls_get_buffer_sizes(tor_tls_t *tls,
  2161. size_t *rbuf_capacity, size_t *rbuf_bytes,
  2162. size_t *wbuf_capacity, size_t *wbuf_bytes)
  2163. {
  2164. if (tls->ssl->s3->rbuf.buf)
  2165. *rbuf_capacity = tls->ssl->s3->rbuf.len;
  2166. else
  2167. *rbuf_capacity = 0;
  2168. if (tls->ssl->s3->wbuf.buf)
  2169. *wbuf_capacity = tls->ssl->s3->wbuf.len;
  2170. else
  2171. *wbuf_capacity = 0;
  2172. *rbuf_bytes = tls->ssl->s3->rbuf.left;
  2173. *wbuf_bytes = tls->ssl->s3->wbuf.left;
  2174. }
  2175. #ifdef USE_BUFFEREVENTS
  2176. /** Construct and return an TLS-encrypting bufferevent to send data over
  2177. * <b>socket</b>, which must match the socket of the underlying bufferevent
  2178. * <b>bufev_in</b>. The TLS object <b>tls</b> is used for encryption.
  2179. *
  2180. * This function will either create a filtering bufferevent that wraps around
  2181. * <b>bufev_in</b>, or it will free bufev_in and return a new bufferevent that
  2182. * uses the <b>tls</b> to talk to the network directly. Do not use
  2183. * <b>bufev_in</b> after calling this function.
  2184. *
  2185. * The connection will start out doing a server handshake if <b>receiving</b>
  2186. * is strue, and a client handshake otherwise.
  2187. *
  2188. * Returns NULL on failure.
  2189. */
  2190. struct bufferevent *
  2191. tor_tls_init_bufferevent(tor_tls_t *tls, struct bufferevent *bufev_in,
  2192. evutil_socket_t socket, int receiving,
  2193. int filter)
  2194. {
  2195. struct bufferevent *out;
  2196. const enum bufferevent_ssl_state state = receiving ?
  2197. BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
  2198. if (filter || tor_libevent_using_iocp_bufferevents()) {
  2199. /* Grab an extra reference to the SSL, since BEV_OPT_CLOSE_ON_FREE
  2200. means that the SSL will get freed too.
  2201. This increment makes our SSL usage not-threadsafe, BTW. We should
  2202. see if we're allowed to use CRYPTO_add from outside openssl. */
  2203. tls->ssl->references += 1;
  2204. out = bufferevent_openssl_filter_new(tor_libevent_get_base(),
  2205. bufev_in,
  2206. tls->ssl,
  2207. state,
  2208. BEV_OPT_DEFER_CALLBACKS|
  2209. BEV_OPT_CLOSE_ON_FREE);
  2210. /* Tell the underlying bufferevent when to accept more data from the SSL
  2211. filter (only when it's got less than 32K to write), and when to notify
  2212. the SSL filter that it could write more (when it drops under 24K). */
  2213. bufferevent_setwatermark(bufev_in, EV_WRITE, 24*1024, 32*1024);
  2214. } else {
  2215. if (bufev_in) {
  2216. evutil_socket_t s = bufferevent_getfd(bufev_in);
  2217. tor_assert(s == -1 || s == socket);
  2218. tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in)) == 0);
  2219. tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in)) == 0);
  2220. tor_assert(BIO_number_read(SSL_get_rbio(tls->ssl)) == 0);
  2221. tor_assert(BIO_number_written(SSL_get_rbio(tls->ssl)) == 0);
  2222. bufferevent_free(bufev_in);
  2223. }
  2224. /* Current versions (as of 2.0.x) of Libevent need to defer
  2225. * bufferevent_openssl callbacks, or else our callback functions will
  2226. * get called reentrantly, which is bad for us.
  2227. */
  2228. out = bufferevent_openssl_socket_new(tor_libevent_get_base(),
  2229. socket,
  2230. tls->ssl,
  2231. state,
  2232. BEV_OPT_DEFER_CALLBACKS);
  2233. }
  2234. tls->state = TOR_TLS_ST_BUFFEREVENT;
  2235. /* Unblock _after_ creating the bufferevent, since accept/connect tend to
  2236. * clear flags. */
  2237. tor_tls_unblock_renegotiation(tls);
  2238. return out;
  2239. }
  2240. #endif