tortls.c 90 KB

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