tortls.c 92 KB

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