tortls.c 92 KB

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