tortls.c 74 KB

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