tortls.c 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464
  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)(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. /* OpenSSL generates self-signed certificates with random 64-bit serial
  533. * numbers, so let's do that too. */
  534. #define SERIAL_NUMBER_SIZE 8
  535. time_t start_time, end_time;
  536. BIGNUM *serial_number = NULL;
  537. unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
  538. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  539. X509 *x509 = NULL;
  540. X509_NAME *name = NULL, *name_issuer=NULL;
  541. tor_tls_init();
  542. start_time = time(NULL);
  543. tor_assert(rsa);
  544. tor_assert(cname);
  545. tor_assert(rsa_sign);
  546. tor_assert(cname_sign);
  547. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  548. goto error;
  549. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  550. goto error;
  551. if (!(x509 = X509_new()))
  552. goto error;
  553. if (!(X509_set_version(x509, 2)))
  554. goto error;
  555. { /* our serial number is 8 random bytes. */
  556. if (crypto_rand((char *)serial_tmp, sizeof(serial_tmp)) < 0)
  557. goto error;
  558. if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
  559. goto error;
  560. if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
  561. goto error;
  562. }
  563. if (!(name = tor_x509_name_new(cname)))
  564. goto error;
  565. if (!(X509_set_subject_name(x509, name)))
  566. goto error;
  567. if (!(name_issuer = tor_x509_name_new(cname_sign)))
  568. goto error;
  569. if (!(X509_set_issuer_name(x509, name_issuer)))
  570. goto error;
  571. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  572. goto error;
  573. end_time = start_time + cert_lifetime;
  574. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  575. goto error;
  576. if (!X509_set_pubkey(x509, pkey))
  577. goto error;
  578. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  579. goto error;
  580. goto done;
  581. error:
  582. if (x509) {
  583. X509_free(x509);
  584. x509 = NULL;
  585. }
  586. done:
  587. tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
  588. if (sign_pkey)
  589. EVP_PKEY_free(sign_pkey);
  590. if (pkey)
  591. EVP_PKEY_free(pkey);
  592. if (serial_number)
  593. BN_free(serial_number);
  594. if (name)
  595. X509_NAME_free(name);
  596. if (name_issuer)
  597. X509_NAME_free(name_issuer);
  598. return x509;
  599. #undef SERIAL_NUMBER_SIZE
  600. }
  601. /** List of ciphers that servers should select from.*/
  602. #define SERVER_CIPHER_LIST \
  603. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  604. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  605. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  606. /* Note: to set up your own private testing network with link crypto
  607. * disabled, set your Tors' cipher list to
  608. * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
  609. * with any of the "real" Tors, though. */
  610. #ifdef V2_HANDSHAKE_CLIENT
  611. #define CIPHER(id, name) name ":"
  612. #define XCIPHER(id, name)
  613. /** List of ciphers that clients should advertise, omitting items that
  614. * our OpenSSL doesn't know about. */
  615. static const char CLIENT_CIPHER_LIST[] =
  616. #include "./ciphers.inc"
  617. ;
  618. #undef CIPHER
  619. #undef XCIPHER
  620. /** Holds a cipher that we want to advertise, and its 2-byte ID. */
  621. typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
  622. /** A list of all the ciphers that clients should advertise, including items
  623. * that OpenSSL might not know about. */
  624. static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
  625. #define CIPHER(id, name) { id, name },
  626. #define XCIPHER(id, name) { id, #name },
  627. #include "./ciphers.inc"
  628. #undef CIPHER
  629. #undef XCIPHER
  630. };
  631. /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
  632. static const int N_CLIENT_CIPHERS =
  633. sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
  634. #endif
  635. #ifndef V2_HANDSHAKE_CLIENT
  636. #undef CLIENT_CIPHER_LIST
  637. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  638. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  639. #endif
  640. /** Free all storage held in <b>cert</b> */
  641. void
  642. tor_cert_free(tor_cert_t *cert)
  643. {
  644. if (! cert)
  645. return;
  646. if (cert->cert)
  647. X509_free(cert->cert);
  648. tor_free(cert->encoded);
  649. memset(cert, 0x03, sizeof(*cert));
  650. tor_free(cert);
  651. }
  652. /**
  653. * Allocate a new tor_cert_t to hold the certificate "x509_cert".
  654. *
  655. * Steals a reference to x509_cert.
  656. */
  657. static tor_cert_t *
  658. tor_cert_new(X509 *x509_cert)
  659. {
  660. tor_cert_t *cert;
  661. EVP_PKEY *pkey;
  662. RSA *rsa;
  663. int length, length2;
  664. unsigned char *cp;
  665. if (!x509_cert)
  666. return NULL;
  667. length = i2d_X509(x509_cert, NULL);
  668. cert = tor_malloc_zero(sizeof(tor_cert_t));
  669. if (length <= 0) {
  670. tor_free(cert);
  671. log_err(LD_CRYPTO, "Couldn't get length of encoded x509 certificate");
  672. X509_free(x509_cert);
  673. return NULL;
  674. }
  675. cert->encoded_len = (size_t) length;
  676. cp = cert->encoded = tor_malloc(length);
  677. length2 = i2d_X509(x509_cert, &cp);
  678. tor_assert(length2 == length);
  679. cert->cert = x509_cert;
  680. crypto_digest_all(&cert->cert_digests,
  681. (char*)cert->encoded, cert->encoded_len);
  682. if ((pkey = X509_get_pubkey(x509_cert)) &&
  683. (rsa = EVP_PKEY_get1_RSA(pkey))) {
  684. crypto_pk_env_t *pk = _crypto_new_pk_env_rsa(rsa);
  685. crypto_pk_get_all_digests(pk, &cert->pkey_digests);
  686. cert->pkey_digests_set = 1;
  687. crypto_free_pk_env(pk);
  688. EVP_PKEY_free(pkey);
  689. }
  690. return cert;
  691. }
  692. /** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
  693. * from a <b>certificate</b>. Return a newly allocated tor_cert_t on success
  694. * and NULL on failure. */
  695. tor_cert_t *
  696. tor_cert_decode(const uint8_t *certificate, size_t certificate_len)
  697. {
  698. X509 *x509;
  699. const unsigned char *cp = (const unsigned char *)certificate;
  700. tor_cert_t *newcert;
  701. tor_assert(certificate);
  702. if (certificate_len > INT_MAX)
  703. return NULL;
  704. #if OPENSSL_VERSION_NUMBER < 0x00908000l
  705. /* This ifdef suppresses a type warning. Take out this case once everybody
  706. * is using OpenSSL 0.9.8 or later. */
  707. x509 = d2i_X509(NULL, (unsigned char**)&cp, (int)certificate_len);
  708. #else
  709. x509 = d2i_X509(NULL, &cp, (int)certificate_len);
  710. #endif
  711. if (!x509)
  712. return NULL; /* Couldn't decode */
  713. if (cp - certificate != (int)certificate_len) {
  714. X509_free(x509);
  715. return NULL; /* Didn't use all the bytes */
  716. }
  717. newcert = tor_cert_new(x509);
  718. if (!newcert) {
  719. return NULL;
  720. }
  721. if (newcert->encoded_len != certificate_len ||
  722. fast_memneq(newcert->encoded, certificate, certificate_len)) {
  723. /* Cert wasn't in DER */
  724. tor_cert_free(newcert);
  725. return NULL;
  726. }
  727. return newcert;
  728. }
  729. /** Set *<b>encoded_out</b> and *<b>size_out/b> to <b>cert</b>'s encoded DER
  730. * representation and length, respectively. */
  731. void
  732. tor_cert_get_der(const tor_cert_t *cert,
  733. const uint8_t **encoded_out, size_t *size_out)
  734. {
  735. tor_assert(cert);
  736. tor_assert(encoded_out);
  737. tor_assert(size_out);
  738. *encoded_out = cert->encoded;
  739. *size_out = cert->encoded_len;
  740. }
  741. /** Return a set of digests for the public key in <b>cert</b>, or NULL if this
  742. * cert's public key is not one we know how to take the digest of. */
  743. const digests_t *
  744. tor_cert_get_id_digests(const tor_cert_t *cert)
  745. {
  746. if (cert->pkey_digests_set)
  747. return &cert->pkey_digests;
  748. else
  749. return NULL;
  750. }
  751. /** Return a set of digests for the public key in <b>cert</b>. */
  752. const digests_t *
  753. tor_cert_get_cert_digests(const tor_cert_t *cert)
  754. {
  755. return &cert->cert_digests;
  756. }
  757. /** Remove a reference to <b>ctx</b>, and free it if it has no more
  758. * references. */
  759. static void
  760. tor_tls_context_decref(tor_tls_context_t *ctx)
  761. {
  762. tor_assert(ctx);
  763. if (--ctx->refcnt == 0) {
  764. SSL_CTX_free(ctx->ctx);
  765. tor_cert_free(ctx->my_link_cert);
  766. tor_cert_free(ctx->my_id_cert);
  767. tor_cert_free(ctx->my_auth_cert);
  768. crypto_free_pk_env(ctx->link_key);
  769. crypto_free_pk_env(ctx->auth_key);
  770. tor_free(ctx);
  771. }
  772. }
  773. /** Set *<b>link_cert_out</b> and *<b>id_cert_out</b> to the link certificate
  774. * and ID certificate that we're currently using for our V3 in-protocol
  775. * handshake's certificate chain. If <b>server</b> is true, provide the certs
  776. * that we use in server mode; otherwise, provide the certs that we use in
  777. * client mode. */
  778. int
  779. tor_tls_get_my_certs(int server,
  780. const tor_cert_t **link_cert_out,
  781. const tor_cert_t **id_cert_out)
  782. {
  783. tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
  784. if (! ctx)
  785. return -1;
  786. if (link_cert_out)
  787. *link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
  788. if (id_cert_out)
  789. *id_cert_out = ctx->my_id_cert;
  790. return 0;
  791. }
  792. /**
  793. * Return the authentication key that we use to authenticate ourselves as a
  794. * client in the V3 in-protocol handshake.
  795. */
  796. crypto_pk_env_t *
  797. tor_tls_get_my_client_auth_key(void)
  798. {
  799. if (! client_tls_context)
  800. return NULL;
  801. return client_tls_context->auth_key;
  802. }
  803. /**
  804. * Return a newly allocated copy of the public key that a certificate
  805. * certifies. Return NULL if the cert's key is not RSA.
  806. */
  807. crypto_pk_env_t *
  808. tor_tls_cert_get_key(tor_cert_t *cert)
  809. {
  810. crypto_pk_env_t *result = NULL;
  811. EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
  812. RSA *rsa;
  813. if (!pkey)
  814. return NULL;
  815. rsa = EVP_PKEY_get1_RSA(pkey);
  816. if (!rsa) {
  817. EVP_PKEY_free(pkey);
  818. return NULL;
  819. }
  820. result = _crypto_new_pk_env_rsa(rsa);
  821. EVP_PKEY_free(pkey);
  822. return result;
  823. }
  824. /** Return true iff <b>a</b> and <b>b</b> represent the same public key. */
  825. static int
  826. pkey_eq(EVP_PKEY *a, EVP_PKEY *b)
  827. {
  828. /* We'd like to do this, but openssl 0.9.7 doesn't have it:
  829. return EVP_PKEY_cmp(a,b) == 1;
  830. */
  831. unsigned char *a_enc=NULL, *b_enc=NULL, *a_ptr, *b_ptr;
  832. int a_len1, b_len1, a_len2, b_len2, result;
  833. a_len1 = i2d_PublicKey(a, NULL);
  834. b_len1 = i2d_PublicKey(b, NULL);
  835. if (a_len1 != b_len1)
  836. return 0;
  837. a_ptr = a_enc = tor_malloc(a_len1);
  838. b_ptr = b_enc = tor_malloc(b_len1);
  839. a_len2 = i2d_PublicKey(a, &a_ptr);
  840. b_len2 = i2d_PublicKey(b, &b_ptr);
  841. tor_assert(a_len2 == a_len1);
  842. tor_assert(b_len2 == b_len1);
  843. result = tor_memeq(a_enc, b_enc, a_len1);
  844. tor_free(a_enc);
  845. tor_free(b_enc);
  846. return result;
  847. }
  848. /** Return true iff the other side of <b>tls</b> has authenticated to us, and
  849. * the key certified in <b>cert</b> is the same as the key they used to do it.
  850. */
  851. int
  852. tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_cert_t *cert)
  853. {
  854. X509 *peercert = SSL_get_peer_certificate(tls->ssl);
  855. EVP_PKEY *link_key = NULL, *cert_key = NULL;
  856. int result;
  857. if (!peercert)
  858. return 0;
  859. link_key = X509_get_pubkey(peercert);
  860. cert_key = X509_get_pubkey(cert->cert);
  861. result = link_key && cert_key && pkey_eq(cert_key, link_key);
  862. X509_free(peercert);
  863. if (link_key)
  864. EVP_PKEY_free(link_key);
  865. if (cert_key)
  866. EVP_PKEY_free(cert_key);
  867. return result;
  868. }
  869. /** Check whether <b>cert</b> is well-formed, currently live, and correctly
  870. * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
  871. * make sure that it has an RSA key with 1024 bits; otherwise, just check that
  872. * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
  873. * we couldn't check it. */
  874. int
  875. tor_tls_cert_is_valid(int severity,
  876. const tor_cert_t *cert,
  877. const tor_cert_t *signing_cert,
  878. int check_rsa_1024)
  879. {
  880. EVP_PKEY *cert_key;
  881. EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
  882. int r, key_ok = 0;
  883. if (!signing_key)
  884. return 0;
  885. r = X509_verify(cert->cert, signing_key);
  886. EVP_PKEY_free(signing_key);
  887. if (r <= 0)
  888. return 0;
  889. /* okay, the signature checked out right. Now let's check the check the
  890. * lifetime. */
  891. if (check_cert_lifetime_internal(severity, cert->cert,
  892. 48*60*60, 30*24*60*60) < 0)
  893. return 0;
  894. cert_key = X509_get_pubkey(cert->cert);
  895. if (check_rsa_1024 && cert_key) {
  896. RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
  897. if (rsa && BN_num_bits(rsa->n) == 1024)
  898. key_ok = 1;
  899. if (rsa)
  900. RSA_free(rsa);
  901. } else if (cert_key) {
  902. int min_bits = 1024;
  903. #ifdef EVP_PKEY_EC
  904. if (EVP_PKEY_type(cert_key->type) == EVP_PKEY_EC)
  905. min_bits = 128;
  906. #endif
  907. if (EVP_PKEY_bits(cert_key) >= min_bits)
  908. key_ok = 1;
  909. }
  910. EVP_PKEY_free(cert_key);
  911. if (!key_ok)
  912. return 0;
  913. /* XXXX compare DNs or anything? */
  914. return 1;
  915. }
  916. /** Increase the reference count of <b>ctx</b>. */
  917. static void
  918. tor_tls_context_incref(tor_tls_context_t *ctx)
  919. {
  920. ++ctx->refcnt;
  921. }
  922. /** Create new global client and server TLS contexts.
  923. *
  924. * If <b>server_identity</b> is NULL, this will not generate a server
  925. * TLS context. If <b>is_public_server</b> is non-zero, this will use
  926. * the same TLS context for incoming and outgoing connections, and
  927. * ignore <b>client_identity</b>. */
  928. int
  929. tor_tls_context_init(int is_public_server,
  930. crypto_pk_env_t *client_identity,
  931. crypto_pk_env_t *server_identity,
  932. unsigned int key_lifetime)
  933. {
  934. int rv1 = 0;
  935. int rv2 = 0;
  936. if (is_public_server) {
  937. tor_tls_context_t *new_ctx;
  938. tor_tls_context_t *old_ctx;
  939. tor_assert(server_identity != NULL);
  940. rv1 = tor_tls_context_init_one(&server_tls_context,
  941. server_identity,
  942. key_lifetime, 0);
  943. if (rv1 >= 0) {
  944. new_ctx = server_tls_context;
  945. tor_tls_context_incref(new_ctx);
  946. old_ctx = client_tls_context;
  947. client_tls_context = new_ctx;
  948. if (old_ctx != NULL) {
  949. tor_tls_context_decref(old_ctx);
  950. }
  951. }
  952. } else {
  953. if (server_identity != NULL) {
  954. rv1 = tor_tls_context_init_one(&server_tls_context,
  955. server_identity,
  956. key_lifetime,
  957. 0);
  958. } else {
  959. tor_tls_context_t *old_ctx = server_tls_context;
  960. server_tls_context = NULL;
  961. if (old_ctx != NULL) {
  962. tor_tls_context_decref(old_ctx);
  963. }
  964. }
  965. rv2 = tor_tls_context_init_one(&client_tls_context,
  966. client_identity,
  967. key_lifetime,
  968. 1);
  969. }
  970. return MIN(rv1, rv2);
  971. }
  972. /** Create a new global TLS context.
  973. *
  974. * You can call this function multiple times. Each time you call it,
  975. * it generates new certificates; all new connections will use
  976. * the new SSL context.
  977. */
  978. static int
  979. tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  980. crypto_pk_env_t *identity,
  981. unsigned int key_lifetime,
  982. int is_client)
  983. {
  984. tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
  985. key_lifetime,
  986. is_client);
  987. tor_tls_context_t *old_ctx = *ppcontext;
  988. if (new_ctx != NULL) {
  989. *ppcontext = new_ctx;
  990. /* Free the old context if one existed. */
  991. if (old_ctx != NULL) {
  992. /* This is safe even if there are open connections: we reference-
  993. * count tor_tls_context_t objects. */
  994. tor_tls_context_decref(old_ctx);
  995. }
  996. }
  997. return ((new_ctx != NULL) ? 0 : -1);
  998. }
  999. /** Create a new TLS context for use with Tor TLS handshakes.
  1000. * <b>identity</b> should be set to the identity key used to sign the
  1001. * certificate.
  1002. */
  1003. static tor_tls_context_t *
  1004. tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime,
  1005. int is_client)
  1006. {
  1007. crypto_pk_env_t *rsa = NULL, *rsa_auth = NULL;
  1008. EVP_PKEY *pkey = NULL;
  1009. tor_tls_context_t *result = NULL;
  1010. X509 *cert = NULL, *idcert = NULL, *authcert = NULL;
  1011. char *nickname = NULL, *nn2 = NULL;
  1012. tor_tls_init();
  1013. nickname = crypto_random_hostname(8, 20, "www.", ".net");
  1014. #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
  1015. nn2 = crypto_random_hostname(8, 20, "www.", ".net");
  1016. #else
  1017. nn2 = crypto_random_hostname(8, 20, "www.", ".com");
  1018. #endif
  1019. /* Generate short-term RSA key for use with TLS. */
  1020. if (!(rsa = crypto_new_pk_env()))
  1021. goto error;
  1022. if (crypto_pk_generate_key(rsa)<0)
  1023. goto error;
  1024. if (!is_client) {
  1025. /* Generate short-term RSA key for use in the in-protocol ("v3")
  1026. * authentication handshake. */
  1027. if (!(rsa_auth = crypto_new_pk_env()))
  1028. goto error;
  1029. if (crypto_pk_generate_key(rsa_auth)<0)
  1030. goto error;
  1031. /* Create a link certificate signed by identity key. */
  1032. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  1033. key_lifetime);
  1034. /* Create self-signed certificate for identity key. */
  1035. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  1036. IDENTITY_CERT_LIFETIME);
  1037. /* Create an authentication certificate signed by identity key. */
  1038. authcert = tor_tls_create_certificate(rsa_auth, identity, nickname, nn2,
  1039. key_lifetime);
  1040. if (!cert || !idcert || !authcert) {
  1041. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  1042. goto error;
  1043. }
  1044. }
  1045. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  1046. result->refcnt = 1;
  1047. if (!is_client) {
  1048. result->my_link_cert = tor_cert_new(X509_dup(cert));
  1049. result->my_id_cert = tor_cert_new(X509_dup(idcert));
  1050. result->my_auth_cert = tor_cert_new(X509_dup(authcert));
  1051. if (!result->my_link_cert || !result->my_id_cert || !result->my_auth_cert)
  1052. goto error;
  1053. result->link_key = crypto_pk_dup_key(rsa);
  1054. result->auth_key = crypto_pk_dup_key(rsa_auth);
  1055. }
  1056. #ifdef EVERYONE_HAS_AES
  1057. /* Tell OpenSSL to only use TLS1 */
  1058. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  1059. goto error;
  1060. #else
  1061. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  1062. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  1063. goto error;
  1064. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  1065. #endif
  1066. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  1067. #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  1068. SSL_CTX_set_options(result->ctx,
  1069. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1070. #endif
  1071. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1072. * as authenticating any earlier-received data.
  1073. */
  1074. if (use_unsafe_renegotiation_op) {
  1075. SSL_CTX_set_options(result->ctx,
  1076. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1077. }
  1078. /* Don't actually allow compression; it uses ram and time, but the data
  1079. * we transmit is all encrypted anyway. */
  1080. if (result->ctx->comp_methods)
  1081. result->ctx->comp_methods = NULL;
  1082. #ifdef SSL_MODE_RELEASE_BUFFERS
  1083. SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
  1084. #endif
  1085. if (! is_client) {
  1086. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  1087. goto error;
  1088. X509_free(cert); /* We just added a reference to cert. */
  1089. cert=NULL;
  1090. if (idcert) {
  1091. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  1092. tor_assert(s);
  1093. X509_STORE_add_cert(s, idcert);
  1094. X509_free(idcert); /* The context now owns the reference to idcert */
  1095. idcert = NULL;
  1096. }
  1097. }
  1098. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  1099. if (!is_client) {
  1100. tor_assert(rsa);
  1101. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  1102. goto error;
  1103. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  1104. goto error;
  1105. EVP_PKEY_free(pkey);
  1106. pkey = NULL;
  1107. if (!SSL_CTX_check_private_key(result->ctx))
  1108. goto error;
  1109. }
  1110. {
  1111. crypto_dh_env_t *dh = crypto_dh_new(DH_TYPE_TLS);
  1112. tor_assert(dh);
  1113. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  1114. crypto_dh_free(dh);
  1115. }
  1116. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  1117. always_accept_verify_cb);
  1118. /* let us realloc bufs that we're writing from */
  1119. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  1120. if (rsa)
  1121. crypto_free_pk_env(rsa);
  1122. if (rsa_auth)
  1123. crypto_free_pk_env(rsa_auth);
  1124. X509_free(authcert);
  1125. tor_free(nickname);
  1126. tor_free(nn2);
  1127. return result;
  1128. error:
  1129. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
  1130. tor_free(nickname);
  1131. tor_free(nn2);
  1132. if (pkey)
  1133. EVP_PKEY_free(pkey);
  1134. if (rsa)
  1135. crypto_free_pk_env(rsa);
  1136. if (rsa_auth)
  1137. crypto_free_pk_env(rsa_auth);
  1138. if (result)
  1139. tor_tls_context_decref(result);
  1140. if (cert)
  1141. X509_free(cert);
  1142. if (idcert)
  1143. X509_free(idcert);
  1144. if (authcert)
  1145. X509_free(authcert);
  1146. return NULL;
  1147. }
  1148. #ifdef V2_HANDSHAKE_SERVER
  1149. /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
  1150. * a list that indicates that the client knows how to do the v2 TLS connection
  1151. * handshake. */
  1152. static int
  1153. tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
  1154. {
  1155. int i;
  1156. SSL_SESSION *session;
  1157. /* If we reached this point, we just got a client hello. See if there is
  1158. * a cipher list. */
  1159. if (!(session = SSL_get_session((SSL *)ssl))) {
  1160. log_info(LD_NET, "No session on TLS?");
  1161. return 0;
  1162. }
  1163. if (!session->ciphers) {
  1164. log_info(LD_NET, "No ciphers on session");
  1165. return 0;
  1166. }
  1167. /* Now we need to see if there are any ciphers whose presence means we're
  1168. * dealing with an updated Tor. */
  1169. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  1170. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  1171. const char *ciphername = SSL_CIPHER_get_name(cipher);
  1172. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  1173. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  1174. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  1175. strcmp(ciphername, "(NONE)")) {
  1176. log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
  1177. // return 1;
  1178. goto dump_list;
  1179. }
  1180. }
  1181. return 0;
  1182. dump_list:
  1183. {
  1184. smartlist_t *elts = smartlist_create();
  1185. char *s;
  1186. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  1187. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  1188. const char *ciphername = SSL_CIPHER_get_name(cipher);
  1189. smartlist_add(elts, (char*)ciphername);
  1190. }
  1191. s = smartlist_join_strings(elts, ":", 0, NULL);
  1192. log_debug(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
  1193. address, s);
  1194. tor_free(s);
  1195. smartlist_free(elts);
  1196. }
  1197. return 1;
  1198. }
  1199. /** We got an SSL ClientHello message. This might mean that the
  1200. * client wants to initiate a renegotiation and appropriate actions
  1201. * must be taken. */
  1202. static void
  1203. tor_tls_got_client_hello(tor_tls_t *tls)
  1204. {
  1205. if (tls->server_handshake_count < 3)
  1206. ++tls->server_handshake_count;
  1207. if (tls->server_handshake_count == 2) {
  1208. if (!tls->negotiated_callback) {
  1209. log_warn(LD_BUG, "Got a renegotiation request but we don't"
  1210. " have a renegotiation callback set!");
  1211. }
  1212. tls->got_renegotiate = 1;
  1213. } else if (tls->server_handshake_count > 2 &&
  1214. tls->excess_renegotiations_callback) {
  1215. /* We got more than one renegotiation requests. The Tor protocol
  1216. needs just one renegotiation; more than that probably means
  1217. They are trying to DoS us and we have to stop them. */
  1218. tls->excess_renegotiations_callback(tls->callback_arg);
  1219. }
  1220. /* Now check the cipher list. */
  1221. if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
  1222. /*XXXX_TLS keep this from happening more than once! */
  1223. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  1224. * Let's hope openssl doesn't notice! */
  1225. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  1226. SSL_set_mode((SSL*) tls->ssl, SSL_MODE_NO_AUTO_CHAIN);
  1227. /* Don't send a hello request. */
  1228. SSL_set_verify((SSL*) tls->ssl, SSL_VERIFY_NONE, NULL);
  1229. if (tls) {
  1230. tls->wasV2Handshake = 1;
  1231. #ifdef USE_BUFFEREVENTS
  1232. if (use_unsafe_renegotiation_flag)
  1233. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1234. #endif
  1235. } else {
  1236. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  1237. }
  1238. }
  1239. }
  1240. #endif
  1241. /** This is a callback function for SSL_set_info_callback() and it
  1242. * will be called in every SSL state change.
  1243. * It logs the SSL state change, and executes any actions that must be
  1244. * taken. */
  1245. static void
  1246. tor_tls_state_changed_callback(const SSL *ssl, int type, int val)
  1247. {
  1248. log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
  1249. ssl, ssl_state_to_string(ssl->state), type, val);
  1250. #ifdef V2_HANDSHAKE_SERVER
  1251. if (type == SSL_CB_ACCEPT_LOOP &&
  1252. ssl->state == SSL3_ST_SW_SRVR_HELLO_A) {
  1253. /* Call tor_tls_got_client_hello() for every SSL ClientHello we
  1254. receive. */
  1255. tor_tls_t *tls = tor_tls_get_by_ssl(ssl);
  1256. if (!tls) {
  1257. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  1258. return;
  1259. }
  1260. tor_tls_got_client_hello(tls);
  1261. }
  1262. #endif
  1263. }
  1264. /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
  1265. * a list designed to mimic a common web browser. Some of the ciphers in the
  1266. * list won't actually be implemented by OpenSSL: that's okay so long as the
  1267. * server doesn't select them, and the server won't select anything besides
  1268. * what's in SERVER_CIPHER_LIST.
  1269. *
  1270. * [If the server <b>does</b> select a bogus cipher, we won't crash or
  1271. * anything; we'll just fail later when we try to look up the cipher in
  1272. * ssl->cipher_list_by_id.]
  1273. */
  1274. static void
  1275. rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
  1276. {
  1277. #ifdef V2_HANDSHAKE_CLIENT
  1278. if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
  1279. /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
  1280. * we want.*/
  1281. int i = 0, j = 0;
  1282. /* First, create a dummy SSL_CIPHER for every cipher. */
  1283. CLIENT_CIPHER_DUMMIES =
  1284. tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
  1285. for (i=0; i < N_CLIENT_CIPHERS; ++i) {
  1286. CLIENT_CIPHER_DUMMIES[i].valid = 1;
  1287. CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
  1288. CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
  1289. }
  1290. CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
  1291. tor_assert(CLIENT_CIPHER_STACK);
  1292. log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
  1293. for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
  1294. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
  1295. log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
  1296. }
  1297. /* Then copy as many ciphers as we can from the good list, inserting
  1298. * dummies as needed. */
  1299. j=0;
  1300. for (i = 0; i < N_CLIENT_CIPHERS; ) {
  1301. SSL_CIPHER *cipher = NULL;
  1302. if (j < sk_SSL_CIPHER_num(*ciphers))
  1303. cipher = sk_SSL_CIPHER_value(*ciphers, j);
  1304. if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
  1305. log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
  1306. ++j;
  1307. } else if (cipher &&
  1308. (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
  1309. log_debug(LD_NET, "Found cipher %s", cipher->name);
  1310. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
  1311. ++j;
  1312. ++i;
  1313. } else {
  1314. log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
  1315. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
  1316. ++i;
  1317. }
  1318. }
  1319. }
  1320. sk_SSL_CIPHER_free(*ciphers);
  1321. *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
  1322. tor_assert(*ciphers);
  1323. #else
  1324. (void)ciphers;
  1325. #endif
  1326. }
  1327. /** Create a new TLS object from a file descriptor, and a flag to
  1328. * determine whether it is functioning as a server.
  1329. */
  1330. tor_tls_t *
  1331. tor_tls_new(int sock, int isServer)
  1332. {
  1333. BIO *bio = NULL;
  1334. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  1335. tor_tls_context_t *context = isServer ? server_tls_context :
  1336. client_tls_context;
  1337. result->magic = TOR_TLS_MAGIC;
  1338. tor_assert(context); /* make sure somebody made it first */
  1339. if (!(result->ssl = SSL_new(context->ctx))) {
  1340. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
  1341. tor_free(result);
  1342. return NULL;
  1343. }
  1344. #ifdef SSL_set_tlsext_host_name
  1345. /* Browsers use the TLS hostname extension, so we should too. */
  1346. if (!isServer) {
  1347. char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
  1348. SSL_set_tlsext_host_name(result->ssl, fake_hostname);
  1349. tor_free(fake_hostname);
  1350. }
  1351. #endif
  1352. if (!SSL_set_cipher_list(result->ssl,
  1353. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  1354. tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
  1355. #ifdef SSL_set_tlsext_host_name
  1356. SSL_set_tlsext_host_name(result->ssl, NULL);
  1357. #endif
  1358. SSL_free(result->ssl);
  1359. tor_free(result);
  1360. return NULL;
  1361. }
  1362. if (!isServer)
  1363. rectify_client_ciphers(&result->ssl->cipher_list);
  1364. result->socket = sock;
  1365. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1366. if (! bio) {
  1367. tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
  1368. #ifdef SSL_set_tlsext_host_name
  1369. SSL_set_tlsext_host_name(result->ssl, NULL);
  1370. #endif
  1371. SSL_free(result->ssl);
  1372. tor_free(result);
  1373. return NULL;
  1374. }
  1375. {
  1376. int set_worked =
  1377. SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
  1378. if (!set_worked) {
  1379. log_warn(LD_BUG,
  1380. "Couldn't set the tls for an SSL*; connection will fail");
  1381. }
  1382. }
  1383. SSL_set_bio(result->ssl, bio, bio);
  1384. tor_tls_context_incref(context);
  1385. result->context = context;
  1386. result->state = TOR_TLS_ST_HANDSHAKE;
  1387. result->isServer = isServer;
  1388. result->wantwrite_n = 0;
  1389. result->last_write_count = BIO_number_written(bio);
  1390. result->last_read_count = BIO_number_read(bio);
  1391. if (result->last_write_count || result->last_read_count) {
  1392. log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
  1393. result->last_read_count, result->last_write_count);
  1394. }
  1395. SSL_set_info_callback(result->ssl, tor_tls_state_changed_callback);
  1396. /* Not expected to get called. */
  1397. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
  1398. return result;
  1399. }
  1400. /** Make future log messages about <b>tls</b> display the address
  1401. * <b>address</b>.
  1402. */
  1403. void
  1404. tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
  1405. {
  1406. tor_assert(tls);
  1407. tor_free(tls->address);
  1408. tls->address = tor_strdup(address);
  1409. }
  1410. /** Set <b>cb</b> to be called with argument <b>arg</b> whenever
  1411. * <b>tls</b> next gets a client-side renegotiate in the middle of a
  1412. * read. Set <b>cb2</b> to be called with argument <b>arg</b> whenever
  1413. * <b>tls</b> gets excess renegotiation requests. Do not invoke this
  1414. * function until <em>after</em> initial handshaking is done!
  1415. */
  1416. void
  1417. tor_tls_set_renegotiate_callbacks(tor_tls_t *tls,
  1418. void (*cb)(tor_tls_t *, void *arg),
  1419. void (*cb2)(void *),
  1420. void *arg)
  1421. {
  1422. tls->negotiated_callback = cb;
  1423. tls->excess_renegotiations_callback = cb2;
  1424. tls->callback_arg = arg;
  1425. tls->got_renegotiate = 0;
  1426. SSL_set_info_callback(tls->ssl, tor_tls_state_changed_callback);
  1427. }
  1428. /** If this version of openssl requires it, turn on renegotiation on
  1429. * <b>tls</b>.
  1430. */
  1431. void
  1432. tor_tls_unblock_renegotiation(tor_tls_t *tls)
  1433. {
  1434. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1435. * as authenticating any earlier-received data. */
  1436. if (use_unsafe_renegotiation_flag) {
  1437. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1438. }
  1439. if (use_unsafe_renegotiation_op) {
  1440. SSL_set_options(tls->ssl,
  1441. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1442. }
  1443. }
  1444. void
  1445. tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
  1446. {
  1447. if (use_unsafe_renegotiation_flag) {
  1448. tor_assert(0 != (tls->ssl->s3->flags &
  1449. SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1450. }
  1451. if (use_unsafe_renegotiation_op) {
  1452. long options = SSL_get_options(tls->ssl);
  1453. tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1454. }
  1455. }
  1456. /** Return whether this tls initiated the connect (client) or
  1457. * received it (server). */
  1458. int
  1459. tor_tls_is_server(tor_tls_t *tls)
  1460. {
  1461. tor_assert(tls);
  1462. return tls->isServer;
  1463. }
  1464. /** Release resources associated with a TLS object. Does not close the
  1465. * underlying file descriptor.
  1466. */
  1467. void
  1468. tor_tls_free(tor_tls_t *tls)
  1469. {
  1470. if (!tls)
  1471. return;
  1472. tor_assert(tls->ssl);
  1473. #ifdef SSL_set_tlsext_host_name
  1474. SSL_set_tlsext_host_name(tls->ssl, NULL);
  1475. #endif
  1476. SSL_free(tls->ssl);
  1477. tls->ssl = NULL;
  1478. tls->negotiated_callback = NULL;
  1479. tls->excess_renegotiations_callback = NULL;
  1480. if (tls->context)
  1481. tor_tls_context_decref(tls->context);
  1482. tor_free(tls->address);
  1483. tls->magic = 0x99999999;
  1484. tor_free(tls);
  1485. }
  1486. /** Underlying function for TLS reading. Reads up to <b>len</b>
  1487. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  1488. * number of characters read. On failure, returns TOR_TLS_ERROR,
  1489. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1490. */
  1491. int
  1492. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  1493. {
  1494. int r, err;
  1495. tor_assert(tls);
  1496. tor_assert(tls->ssl);
  1497. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1498. tor_assert(len<INT_MAX);
  1499. r = SSL_read(tls->ssl, cp, (int)len);
  1500. if (r > 0) /* return the number of characters read */
  1501. return r;
  1502. /* If we got here, SSL_read() did not go as expected. */
  1503. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
  1504. #ifdef V2_HANDSHAKE_SERVER
  1505. if (tls->got_renegotiate) {
  1506. if (tls->server_handshake_count != 2) {
  1507. log_warn(LD_BUG, "We did not notice renegotiation in a timely "
  1508. "fashion (%u)!", tls->server_handshake_count);
  1509. }
  1510. /* Renegotiation happened! */
  1511. log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
  1512. if (tls->negotiated_callback)
  1513. tls->negotiated_callback(tls, tls->callback_arg);
  1514. tls->got_renegotiate = 0;
  1515. return r;
  1516. }
  1517. #endif
  1518. if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
  1519. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  1520. tls->state = TOR_TLS_ST_CLOSED;
  1521. return TOR_TLS_CLOSE;
  1522. } else {
  1523. tor_assert(err != TOR_TLS_DONE);
  1524. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  1525. return err;
  1526. }
  1527. }
  1528. /** Underlying function for TLS writing. Write up to <b>n</b>
  1529. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  1530. * number of characters written. On failure, returns TOR_TLS_ERROR,
  1531. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1532. */
  1533. int
  1534. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  1535. {
  1536. int r, err;
  1537. tor_assert(tls);
  1538. tor_assert(tls->ssl);
  1539. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1540. tor_assert(n < INT_MAX);
  1541. if (n == 0)
  1542. return 0;
  1543. if (tls->wantwrite_n) {
  1544. /* if WANTWRITE last time, we must use the _same_ n as before */
  1545. tor_assert(n >= tls->wantwrite_n);
  1546. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  1547. (int)n, (int)tls->wantwrite_n);
  1548. n = tls->wantwrite_n;
  1549. tls->wantwrite_n = 0;
  1550. }
  1551. r = SSL_write(tls->ssl, cp, (int)n);
  1552. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
  1553. if (err == TOR_TLS_DONE) {
  1554. return r;
  1555. }
  1556. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  1557. tls->wantwrite_n = n;
  1558. }
  1559. return err;
  1560. }
  1561. /** Perform initial handshake on <b>tls</b>. When finished, returns
  1562. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1563. * or TOR_TLS_WANTWRITE.
  1564. */
  1565. int
  1566. tor_tls_handshake(tor_tls_t *tls)
  1567. {
  1568. int r;
  1569. int oldstate;
  1570. tor_assert(tls);
  1571. tor_assert(tls->ssl);
  1572. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  1573. check_no_tls_errors();
  1574. oldstate = tls->ssl->state;
  1575. if (tls->isServer) {
  1576. log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
  1577. ssl_state_to_string(tls->ssl->state));
  1578. r = SSL_accept(tls->ssl);
  1579. } else {
  1580. log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
  1581. ssl_state_to_string(tls->ssl->state));
  1582. r = SSL_connect(tls->ssl);
  1583. }
  1584. if (oldstate != tls->ssl->state)
  1585. log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
  1586. tls, ssl_state_to_string(tls->ssl->state));
  1587. /* We need to call this here and not earlier, since OpenSSL has a penchant
  1588. * for clearing its flags when you say accept or connect. */
  1589. tor_tls_unblock_renegotiation(tls);
  1590. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
  1591. if (ERR_peek_error() != 0) {
  1592. tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
  1593. "handshaking");
  1594. return TOR_TLS_ERROR_MISC;
  1595. }
  1596. if (r == TOR_TLS_DONE) {
  1597. tls->state = TOR_TLS_ST_OPEN;
  1598. return tor_tls_finish_handshake(tls);
  1599. }
  1600. return r;
  1601. }
  1602. /** Perform the final part of the intial TLS handshake on <b>tls</b>. This
  1603. * should be called for the first handshake only: it determines whether the v1
  1604. * or the v2 handshake was used, and adjusts things for the renegotiation
  1605. * handshake as appropriate.
  1606. *
  1607. * tor_tls_handshake() calls this on its own; you only need to call this if
  1608. * bufferevent is doing the handshake for you.
  1609. */
  1610. int
  1611. tor_tls_finish_handshake(tor_tls_t *tls)
  1612. {
  1613. int r = TOR_TLS_DONE;
  1614. if (tls->isServer) {
  1615. SSL_set_info_callback(tls->ssl, NULL);
  1616. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
  1617. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  1618. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  1619. #ifdef V2_HANDSHAKE_SERVER
  1620. if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
  1621. /* This check is redundant, but back when we did it in the callback,
  1622. * we might have not been able to look up the tor_tls_t if the code
  1623. * was buggy. Fixing that. */
  1624. if (!tls->wasV2Handshake) {
  1625. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  1626. " get set. Fixing that.");
  1627. }
  1628. tls->wasV2Handshake = 1;
  1629. log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
  1630. " for renegotiation.");
  1631. } else {
  1632. tls->wasV2Handshake = 0;
  1633. }
  1634. #endif
  1635. } else {
  1636. #ifdef V2_HANDSHAKE_CLIENT
  1637. /* If we got no ID cert, we're a v2 handshake. */
  1638. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  1639. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  1640. int n_certs = sk_X509_num(chain);
  1641. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0))) {
  1642. log_debug(LD_HANDSHAKE, "Server sent back multiple certificates; it "
  1643. "looks like a v1 handshake on %p", tls);
  1644. tls->wasV2Handshake = 0;
  1645. } else {
  1646. log_debug(LD_HANDSHAKE,
  1647. "Server sent back a single certificate; looks like "
  1648. "a v2 handshake on %p.", tls);
  1649. tls->wasV2Handshake = 1;
  1650. }
  1651. if (cert)
  1652. X509_free(cert);
  1653. #endif
  1654. if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
  1655. tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
  1656. r = TOR_TLS_ERROR_MISC;
  1657. }
  1658. }
  1659. return r;
  1660. }
  1661. #ifdef USE_BUFFEREVENTS
  1662. /** Put <b>tls</b>, which must be a client connection, into renegotiation
  1663. * mode. */
  1664. int
  1665. tor_tls_start_renegotiating(tor_tls_t *tls)
  1666. {
  1667. int r = SSL_renegotiate(tls->ssl);
  1668. if (r <= 0) {
  1669. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1670. LD_HANDSHAKE);
  1671. }
  1672. return 0;
  1673. }
  1674. #endif
  1675. /** Client only: Renegotiate a TLS session. When finished, returns
  1676. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  1677. * TOR_TLS_WANTWRITE.
  1678. */
  1679. int
  1680. tor_tls_renegotiate(tor_tls_t *tls)
  1681. {
  1682. int r;
  1683. tor_assert(tls);
  1684. /* We could do server-initiated renegotiation too, but that would be tricky.
  1685. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  1686. tor_assert(!tls->isServer);
  1687. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  1688. int r = SSL_renegotiate(tls->ssl);
  1689. if (r <= 0) {
  1690. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1691. LD_HANDSHAKE);
  1692. }
  1693. tls->state = TOR_TLS_ST_RENEGOTIATE;
  1694. }
  1695. r = SSL_do_handshake(tls->ssl);
  1696. if (r == 1) {
  1697. tls->state = TOR_TLS_ST_OPEN;
  1698. return TOR_TLS_DONE;
  1699. } else
  1700. return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO,
  1701. LD_HANDSHAKE);
  1702. }
  1703. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  1704. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1705. * or TOR_TLS_WANTWRITE.
  1706. */
  1707. int
  1708. tor_tls_shutdown(tor_tls_t *tls)
  1709. {
  1710. int r, err;
  1711. char buf[128];
  1712. tor_assert(tls);
  1713. tor_assert(tls->ssl);
  1714. while (1) {
  1715. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  1716. /* If we've already called shutdown once to send a close message,
  1717. * we read until the other side has closed too.
  1718. */
  1719. do {
  1720. r = SSL_read(tls->ssl, buf, 128);
  1721. } while (r>0);
  1722. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  1723. LOG_INFO, LD_NET);
  1724. if (err == _TOR_TLS_ZERORETURN) {
  1725. tls->state = TOR_TLS_ST_GOTCLOSE;
  1726. /* fall through... */
  1727. } else {
  1728. return err;
  1729. }
  1730. }
  1731. r = SSL_shutdown(tls->ssl);
  1732. if (r == 1) {
  1733. /* If shutdown returns 1, the connection is entirely closed. */
  1734. tls->state = TOR_TLS_ST_CLOSED;
  1735. return TOR_TLS_DONE;
  1736. }
  1737. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  1738. LOG_INFO, LD_NET);
  1739. if (err == _TOR_TLS_SYSCALL) {
  1740. /* The underlying TCP connection closed while we were shutting down. */
  1741. tls->state = TOR_TLS_ST_CLOSED;
  1742. return TOR_TLS_DONE;
  1743. } else if (err == _TOR_TLS_ZERORETURN) {
  1744. /* The TLS connection says that it sent a shutdown record, but
  1745. * isn't done shutting down yet. Make sure that this hasn't
  1746. * happened before, then go back to the start of the function
  1747. * and try to read.
  1748. */
  1749. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  1750. tls->state == TOR_TLS_ST_SENTCLOSE) {
  1751. log(LOG_WARN, LD_NET,
  1752. "TLS returned \"half-closed\" value while already half-closed");
  1753. return TOR_TLS_ERROR_MISC;
  1754. }
  1755. tls->state = TOR_TLS_ST_SENTCLOSE;
  1756. /* fall through ... */
  1757. } else {
  1758. return err;
  1759. }
  1760. } /* end loop */
  1761. }
  1762. /** Return true iff this TLS connection is authenticated.
  1763. */
  1764. int
  1765. tor_tls_peer_has_cert(tor_tls_t *tls)
  1766. {
  1767. X509 *cert;
  1768. cert = SSL_get_peer_certificate(tls->ssl);
  1769. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1770. if (!cert)
  1771. return 0;
  1772. X509_free(cert);
  1773. return 1;
  1774. }
  1775. /** Return the peer certificate, or NULL if there isn't one. */
  1776. tor_cert_t *
  1777. tor_tls_get_peer_cert(tor_tls_t *tls)
  1778. {
  1779. X509 *cert;
  1780. cert = SSL_get_peer_certificate(tls->ssl);
  1781. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1782. if (!cert)
  1783. return NULL;
  1784. return tor_cert_new(cert);
  1785. }
  1786. /** Warn that a certificate lifetime extends through a certain range. */
  1787. static void
  1788. log_cert_lifetime(int severity, const X509 *cert, const char *problem)
  1789. {
  1790. BIO *bio = NULL;
  1791. BUF_MEM *buf;
  1792. char *s1=NULL, *s2=NULL;
  1793. char mytime[33];
  1794. time_t now = time(NULL);
  1795. struct tm tm;
  1796. if (problem)
  1797. log(severity, LD_GENERAL,
  1798. "Certificate %s. Either their clock is set wrong, or your clock "
  1799. "is wrong.",
  1800. problem);
  1801. if (!(bio = BIO_new(BIO_s_mem()))) {
  1802. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1803. }
  1804. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1805. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1806. goto end;
  1807. }
  1808. BIO_get_mem_ptr(bio, &buf);
  1809. s1 = tor_strndup(buf->data, buf->length);
  1810. (void)BIO_reset(bio);
  1811. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1812. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1813. goto end;
  1814. }
  1815. BIO_get_mem_ptr(bio, &buf);
  1816. s2 = tor_strndup(buf->data, buf->length);
  1817. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1818. log(severity, LD_GENERAL,
  1819. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1820. s1,s2,mytime);
  1821. end:
  1822. /* Not expected to get invoked */
  1823. tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
  1824. if (bio)
  1825. BIO_free(bio);
  1826. tor_free(s1);
  1827. tor_free(s2);
  1828. }
  1829. /** Helper function: try to extract a link certificate and an identity
  1830. * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
  1831. * *<b>id_cert_out</b> respectively. Log all messages at level
  1832. * <b>severity</b>.
  1833. *
  1834. * Note that a reference is added to cert_out, so it needs to be
  1835. * freed. id_cert_out doesn't. */
  1836. static void
  1837. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1838. X509 **cert_out, X509 **id_cert_out)
  1839. {
  1840. X509 *cert = NULL, *id_cert = NULL;
  1841. STACK_OF(X509) *chain = NULL;
  1842. int num_in_chain, i;
  1843. *cert_out = *id_cert_out = NULL;
  1844. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1845. return;
  1846. *cert_out = cert;
  1847. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1848. return;
  1849. num_in_chain = sk_X509_num(chain);
  1850. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1851. * 2 means we're connecting (client-side), and it's both the link
  1852. * cert and the id_cert.
  1853. */
  1854. if (num_in_chain < 1) {
  1855. log_fn(severity,LD_PROTOCOL,
  1856. "Unexpected number of certificates in chain (%d)",
  1857. num_in_chain);
  1858. return;
  1859. }
  1860. for (i=0; i<num_in_chain; ++i) {
  1861. id_cert = sk_X509_value(chain, i);
  1862. if (X509_cmp(id_cert, cert) != 0)
  1863. break;
  1864. }
  1865. *id_cert_out = id_cert;
  1866. }
  1867. /** If the provided tls connection is authenticated and has a
  1868. * certificate chain that is currently valid and signed, then set
  1869. * *<b>identity_key</b> to the identity certificate's key and return
  1870. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1871. */
  1872. int
  1873. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1874. {
  1875. X509 *cert = NULL, *id_cert = NULL;
  1876. EVP_PKEY *id_pkey = NULL;
  1877. RSA *rsa;
  1878. int r = -1;
  1879. *identity_key = NULL;
  1880. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1881. if (!cert)
  1882. goto done;
  1883. if (!id_cert) {
  1884. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1885. goto done;
  1886. }
  1887. tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
  1888. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1889. X509_verify(cert, id_pkey) <= 0) {
  1890. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1891. tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
  1892. goto done;
  1893. }
  1894. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1895. if (!rsa)
  1896. goto done;
  1897. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1898. r = 0;
  1899. done:
  1900. if (cert)
  1901. X509_free(cert);
  1902. if (id_pkey)
  1903. EVP_PKEY_free(id_pkey);
  1904. /* This should never get invoked, but let's make sure in case OpenSSL
  1905. * acts unexpectedly. */
  1906. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
  1907. return r;
  1908. }
  1909. /** Check whether the certificate set on the connection <b>tls</b> is expired
  1910. * give or take <b>past_tolerance</b> seconds, or not-yet-valid give or take
  1911. * <b>future_tolerance</b> seconds. Return 0 for valid, -1 for failure.
  1912. *
  1913. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1914. */
  1915. int
  1916. tor_tls_check_lifetime(int severity, tor_tls_t *tls,
  1917. int past_tolerance, int future_tolerance)
  1918. {
  1919. X509 *cert;
  1920. int r = -1;
  1921. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1922. goto done;
  1923. if (check_cert_lifetime_internal(severity, cert,
  1924. past_tolerance, future_tolerance) < 0)
  1925. goto done;
  1926. r = 0;
  1927. done:
  1928. if (cert)
  1929. X509_free(cert);
  1930. /* Not expected to get invoked */
  1931. tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
  1932. return r;
  1933. }
  1934. /** Helper: check whether <b>cert</b> is expired give or take
  1935. * <b>past_tolerance</b> seconds, or not-yet-valid give or take
  1936. * <b>future_tolerance</b> seconds. If it is live, return 0. If it is not
  1937. * live, log a message and return -1. */
  1938. static int
  1939. check_cert_lifetime_internal(int severity, const X509 *cert,
  1940. int past_tolerance, int future_tolerance)
  1941. {
  1942. time_t now, t;
  1943. now = time(NULL);
  1944. t = now + future_tolerance;
  1945. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1946. log_cert_lifetime(severity, cert, "not yet valid");
  1947. return -1;
  1948. }
  1949. t = now - past_tolerance;
  1950. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1951. log_cert_lifetime(severity, cert, "already expired");
  1952. return -1;
  1953. }
  1954. return 0;
  1955. }
  1956. /** Return the number of bytes available for reading from <b>tls</b>.
  1957. */
  1958. int
  1959. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1960. {
  1961. tor_assert(tls);
  1962. return SSL_pending(tls->ssl);
  1963. }
  1964. /** If <b>tls</b> requires that the next write be of a particular size,
  1965. * return that size. Otherwise, return 0. */
  1966. size_t
  1967. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1968. {
  1969. return tls->wantwrite_n;
  1970. }
  1971. /** Sets n_read and n_written to the number of bytes read and written,
  1972. * respectively, on the raw socket used by <b>tls</b> since the last time this
  1973. * function was called on <b>tls</b>. */
  1974. void
  1975. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1976. {
  1977. BIO *wbio, *tmpbio;
  1978. unsigned long r, w;
  1979. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1980. /* We want the number of bytes actually for real written. Unfortunately,
  1981. * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
  1982. * which makes the answer turn out wrong. Let's cope with that. Note
  1983. * that this approach will fail if we ever replace tls->ssl's BIOs with
  1984. * buffering bios for reasons of our own. As an alternative, we could
  1985. * save the original BIO for tls->ssl in the tor_tls_t structure, but
  1986. * that would be tempting fate. */
  1987. wbio = SSL_get_wbio(tls->ssl);
  1988. if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
  1989. wbio = tmpbio;
  1990. w = BIO_number_written(wbio);
  1991. /* We are ok with letting these unsigned ints go "negative" here:
  1992. * If we wrapped around, this should still give us the right answer, unless
  1993. * we wrapped around by more than ULONG_MAX since the last time we called
  1994. * this function.
  1995. */
  1996. *n_read = (size_t)(r - tls->last_read_count);
  1997. *n_written = (size_t)(w - tls->last_write_count);
  1998. if (*n_read > INT_MAX || *n_written > INT_MAX) {
  1999. log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
  2000. "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
  2001. r, tls->last_read_count, w, tls->last_write_count);
  2002. }
  2003. tls->last_read_count = r;
  2004. tls->last_write_count = w;
  2005. }
  2006. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  2007. * errors, log an error message. */
  2008. void
  2009. _check_no_tls_errors(const char *fname, int line)
  2010. {
  2011. if (ERR_peek_error() == 0)
  2012. return;
  2013. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  2014. tor_fix_source_file(fname), line);
  2015. tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
  2016. }
  2017. /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
  2018. * TLS handshake. Output is undefined if the handshake isn't finished. */
  2019. int
  2020. tor_tls_used_v1_handshake(tor_tls_t *tls)
  2021. {
  2022. if (tls->isServer) {
  2023. #ifdef V2_HANDSHAKE_SERVER
  2024. return ! tls->wasV2Handshake;
  2025. #endif
  2026. } else {
  2027. #ifdef V2_HANDSHAKE_CLIENT
  2028. return ! tls->wasV2Handshake;
  2029. #endif
  2030. }
  2031. return 1;
  2032. }
  2033. /** Return true iff <b>name</b> is a DN of a kind that could only
  2034. * occur in a v3-handshake-indicating certificate */
  2035. static int
  2036. dn_indicates_v3_cert(X509_NAME *name)
  2037. {
  2038. #ifdef DISABLE_V3_LINKPROTO_CLIENTSIDE
  2039. (void)name;
  2040. return 0;
  2041. #else
  2042. X509_NAME_ENTRY *entry;
  2043. int n_entries;
  2044. ASN1_OBJECT *obj;
  2045. ASN1_STRING *str;
  2046. unsigned char *s;
  2047. int len, r;
  2048. n_entries = X509_NAME_entry_count(name);
  2049. if (n_entries != 1)
  2050. return 1; /* More than one entry in the DN. */
  2051. entry = X509_NAME_get_entry(name, 0);
  2052. obj = X509_NAME_ENTRY_get_object(entry);
  2053. if (OBJ_obj2nid(obj) != OBJ_txt2nid("commonName"))
  2054. return 1; /* The entry isn't a commonName. */
  2055. str = X509_NAME_ENTRY_get_data(entry);
  2056. len = ASN1_STRING_to_UTF8(&s, str);
  2057. if (len < 0)
  2058. return 0;
  2059. r = fast_memneq(s + len - 4, ".net", 4);
  2060. OPENSSL_free(s);
  2061. return r;
  2062. #endif
  2063. }
  2064. /** Return true iff the peer certificate we're received on <b>tls</b>
  2065. * indicates that this connection should use the v3 (in-protocol)
  2066. * authentication handshake.
  2067. *
  2068. * Only the connection initiator should use this, and only once the initial
  2069. * handshake is done; the responder detects a v1 handshake by cipher types,
  2070. * and a v3/v2 handshake by Versions cell vs renegotiation.
  2071. */
  2072. int
  2073. tor_tls_received_v3_certificate(tor_tls_t *tls)
  2074. {
  2075. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  2076. EVP_PKEY *key = NULL;
  2077. X509_NAME *issuer_name, *subject_name;
  2078. int is_v3 = 0;
  2079. if (!cert) {
  2080. log_warn(LD_BUG, "Called on a connection with no peer certificate");
  2081. goto done;
  2082. }
  2083. subject_name = X509_get_subject_name(cert);
  2084. issuer_name = X509_get_issuer_name(cert);
  2085. if (X509_name_cmp(subject_name, issuer_name) == 0) {
  2086. is_v3 = 1; /* purportedly self signed */
  2087. goto done;
  2088. }
  2089. if (dn_indicates_v3_cert(subject_name) ||
  2090. dn_indicates_v3_cert(issuer_name)) {
  2091. is_v3 = 1; /* DN is fancy */
  2092. goto done;
  2093. }
  2094. key = X509_get_pubkey(cert);
  2095. if (EVP_PKEY_bits(key) != 1024 ||
  2096. EVP_PKEY_type(key->type) != EVP_PKEY_RSA) {
  2097. is_v3 = 1; /* Key is fancy */
  2098. goto done;
  2099. }
  2100. done:
  2101. if (key)
  2102. EVP_PKEY_free(key);
  2103. if (cert)
  2104. X509_free(cert);
  2105. return is_v3;
  2106. }
  2107. /** Return the number of server handshakes that we've noticed doing on
  2108. * <b>tls</b>. */
  2109. int
  2110. tor_tls_get_num_server_handshakes(tor_tls_t *tls)
  2111. {
  2112. return tls->server_handshake_count;
  2113. }
  2114. /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
  2115. * request it was waiting for. */
  2116. int
  2117. tor_tls_server_got_renegotiate(tor_tls_t *tls)
  2118. {
  2119. return tls->got_renegotiate;
  2120. }
  2121. /** Set the DIGEST256_LEN buffer at <b>secrets_out</b> to the value used in
  2122. * the v3 handshake to prove that the client knows the TLS secrets for the
  2123. * connection <b>tls</b>. Return 0 on success, -1 on failure.
  2124. */
  2125. int
  2126. tor_tls_get_tlssecrets(tor_tls_t *tls, uint8_t *secrets_out)
  2127. {
  2128. #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
  2129. char buf[128];
  2130. size_t len;
  2131. tor_assert(tls);
  2132. tor_assert(tls->ssl);
  2133. tor_assert(tls->ssl->s3);
  2134. tor_assert(tls->ssl->session);
  2135. /*
  2136. The value is an HMAC, using the TLS master key as the HMAC key, of
  2137. client_random | server_random | TLSSECRET_MAGIC
  2138. */
  2139. memcpy(buf + 0, tls->ssl->s3->client_random, 32);
  2140. memcpy(buf + 32, tls->ssl->s3->server_random, 32);
  2141. memcpy(buf + 64, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
  2142. len = 64 + strlen(TLSSECRET_MAGIC) + 1;
  2143. crypto_hmac_sha256((char*)secrets_out,
  2144. (char*)tls->ssl->session->master_key,
  2145. tls->ssl->session->master_key_length,
  2146. buf, len);
  2147. memset(buf, 0, sizeof(buf));
  2148. return 0;
  2149. }
  2150. /** Examine the amount of memory used and available for buffers in <b>tls</b>.
  2151. * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
  2152. * buffer and *<b>rbuf_bytes</b> to the amount actually used.
  2153. * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
  2154. * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
  2155. void
  2156. tor_tls_get_buffer_sizes(tor_tls_t *tls,
  2157. size_t *rbuf_capacity, size_t *rbuf_bytes,
  2158. size_t *wbuf_capacity, size_t *wbuf_bytes)
  2159. {
  2160. if (tls->ssl->s3->rbuf.buf)
  2161. *rbuf_capacity = tls->ssl->s3->rbuf.len;
  2162. else
  2163. *rbuf_capacity = 0;
  2164. if (tls->ssl->s3->wbuf.buf)
  2165. *wbuf_capacity = tls->ssl->s3->wbuf.len;
  2166. else
  2167. *wbuf_capacity = 0;
  2168. *rbuf_bytes = tls->ssl->s3->rbuf.left;
  2169. *wbuf_bytes = tls->ssl->s3->wbuf.left;
  2170. }
  2171. #ifdef USE_BUFFEREVENTS
  2172. /** Construct and return an TLS-encrypting bufferevent to send data over
  2173. * <b>socket</b>, which must match the socket of the underlying bufferevent
  2174. * <b>bufev_in</b>. The TLS object <b>tls</b> is used for encryption.
  2175. *
  2176. * This function will either create a filtering bufferevent that wraps around
  2177. * <b>bufev_in</b>, or it will free bufev_in and return a new bufferevent that
  2178. * uses the <b>tls</b> to talk to the network directly. Do not use
  2179. * <b>bufev_in</b> after calling this function.
  2180. *
  2181. * The connection will start out doing a server handshake if <b>receiving</b>
  2182. * is strue, and a client handshake otherwise.
  2183. *
  2184. * Returns NULL on failure.
  2185. */
  2186. struct bufferevent *
  2187. tor_tls_init_bufferevent(tor_tls_t *tls, struct bufferevent *bufev_in,
  2188. evutil_socket_t socket, int receiving,
  2189. int filter)
  2190. {
  2191. struct bufferevent *out;
  2192. const enum bufferevent_ssl_state state = receiving ?
  2193. BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
  2194. if (filter || tor_libevent_using_iocp_bufferevents()) {
  2195. /* Grab an extra reference to the SSL, since BEV_OPT_CLOSE_ON_FREE
  2196. means that the SSL will get freed too.
  2197. This increment makes our SSL usage not-threadsafe, BTW. We should
  2198. see if we're allowed to use CRYPTO_add from outside openssl. */
  2199. tls->ssl->references += 1;
  2200. out = bufferevent_openssl_filter_new(tor_libevent_get_base(),
  2201. bufev_in,
  2202. tls->ssl,
  2203. state,
  2204. BEV_OPT_DEFER_CALLBACKS|
  2205. BEV_OPT_CLOSE_ON_FREE);
  2206. /* Tell the underlying bufferevent when to accept more data from the SSL
  2207. filter (only when it's got less than 32K to write), and when to notify
  2208. the SSL filter that it could write more (when it drops under 24K). */
  2209. bufferevent_setwatermark(bufev_in, EV_WRITE, 24*1024, 32*1024);
  2210. } else {
  2211. if (bufev_in) {
  2212. evutil_socket_t s = bufferevent_getfd(bufev_in);
  2213. tor_assert(s == -1 || s == socket);
  2214. tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in)) == 0);
  2215. tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in)) == 0);
  2216. tor_assert(BIO_number_read(SSL_get_rbio(tls->ssl)) == 0);
  2217. tor_assert(BIO_number_written(SSL_get_rbio(tls->ssl)) == 0);
  2218. bufferevent_free(bufev_in);
  2219. }
  2220. /* Current versions (as of 2.0.x) of Libevent need to defer
  2221. * bufferevent_openssl callbacks, or else our callback functions will
  2222. * get called reentrantly, which is bad for us.
  2223. */
  2224. out = bufferevent_openssl_socket_new(tor_libevent_get_base(),
  2225. socket,
  2226. tls->ssl,
  2227. state,
  2228. BEV_OPT_DEFER_CALLBACKS);
  2229. }
  2230. tls->state = TOR_TLS_ST_BUFFEREVENT;
  2231. /* Unblock _after_ creating the bufferevent, since accept/connect tend to
  2232. * clear flags. */
  2233. tor_tls_unblock_renegotiation(tls);
  2234. return out;
  2235. }
  2236. #endif