tortls.c 87 KB

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