tortls.c 79 KB

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