tortls.c 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  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,7)
  53. #error "We require OpenSSL >= 0.9.7"
  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_notice(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_notice(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_notice(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. ;
  614. #undef CIPHER
  615. #undef XCIPHER
  616. /** Holds a cipher that we want to advertise, and its 2-byte ID. */
  617. typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
  618. /** A list of all the ciphers that clients should advertise, including items
  619. * that OpenSSL might not know about. */
  620. static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
  621. #define CIPHER(id, name) { id, name },
  622. #define XCIPHER(id, name) { id, #name },
  623. #include "./ciphers.inc"
  624. #undef CIPHER
  625. #undef XCIPHER
  626. };
  627. /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
  628. static const int N_CLIENT_CIPHERS =
  629. sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
  630. #endif
  631. #ifndef V2_HANDSHAKE_CLIENT
  632. #undef CLIENT_CIPHER_LIST
  633. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  634. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  635. #endif
  636. /** Free all storage held in <b>cert</b> */
  637. void
  638. tor_cert_free(tor_cert_t *cert)
  639. {
  640. if (! cert)
  641. return;
  642. if (cert->cert)
  643. X509_free(cert->cert);
  644. tor_free(cert->encoded);
  645. memset(cert, 0x03, sizeof(*cert));
  646. tor_free(cert);
  647. }
  648. /**
  649. * Allocate a new tor_cert_t to hold the certificate "x509_cert".
  650. *
  651. * Steals a reference to x509_cert.
  652. */
  653. static tor_cert_t *
  654. tor_cert_new(X509 *x509_cert)
  655. {
  656. tor_cert_t *cert;
  657. EVP_PKEY *pkey;
  658. RSA *rsa;
  659. int length, length2;
  660. unsigned char *cp;
  661. if (!x509_cert)
  662. return NULL;
  663. length = i2d_X509(x509_cert, NULL);
  664. cert = tor_malloc_zero(sizeof(tor_cert_t));
  665. if (length <= 0) {
  666. tor_free(cert);
  667. log_err(LD_CRYPTO, "Couldn't get length of encoded x509 certificate");
  668. X509_free(x509_cert);
  669. return NULL;
  670. }
  671. cert->encoded_len = (size_t) length;
  672. cp = cert->encoded = tor_malloc(length);
  673. length2 = i2d_X509(x509_cert, &cp);
  674. tor_assert(length2 == length);
  675. cert->cert = x509_cert;
  676. crypto_digest_all(&cert->cert_digests,
  677. (char*)cert->encoded, cert->encoded_len);
  678. if ((pkey = X509_get_pubkey(x509_cert)) &&
  679. (rsa = EVP_PKEY_get1_RSA(pkey))) {
  680. crypto_pk_t *pk = _crypto_new_pk_from_rsa(rsa);
  681. crypto_pk_get_all_digests(pk, &cert->pkey_digests);
  682. cert->pkey_digests_set = 1;
  683. crypto_pk_free(pk);
  684. EVP_PKEY_free(pkey);
  685. }
  686. return cert;
  687. }
  688. /** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
  689. * from a <b>certificate</b>. Return a newly allocated tor_cert_t on success
  690. * and NULL on failure. */
  691. tor_cert_t *
  692. tor_cert_decode(const uint8_t *certificate, size_t certificate_len)
  693. {
  694. X509 *x509;
  695. const unsigned char *cp = (const unsigned char *)certificate;
  696. tor_cert_t *newcert;
  697. tor_assert(certificate);
  698. if (certificate_len > INT_MAX)
  699. return NULL;
  700. #if OPENSSL_VERSION_NUMBER < OPENSSL_V_SERIES(0,9,8)
  701. /* This ifdef suppresses a type warning. Take out this case once everybody
  702. * is using OpenSSL 0.9.8 or later. */
  703. x509 = d2i_X509(NULL, (unsigned char**)&cp, (int)certificate_len);
  704. #else
  705. x509 = d2i_X509(NULL, &cp, (int)certificate_len);
  706. #endif
  707. if (!x509)
  708. return NULL; /* Couldn't decode */
  709. if (cp - certificate != (int)certificate_len) {
  710. X509_free(x509);
  711. return NULL; /* Didn't use all the bytes */
  712. }
  713. newcert = tor_cert_new(x509);
  714. if (!newcert) {
  715. return NULL;
  716. }
  717. if (newcert->encoded_len != certificate_len ||
  718. fast_memneq(newcert->encoded, certificate, certificate_len)) {
  719. /* Cert wasn't in DER */
  720. tor_cert_free(newcert);
  721. return NULL;
  722. }
  723. return newcert;
  724. }
  725. /** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
  726. * representation and length, respectively. */
  727. void
  728. tor_cert_get_der(const tor_cert_t *cert,
  729. const uint8_t **encoded_out, size_t *size_out)
  730. {
  731. tor_assert(cert);
  732. tor_assert(encoded_out);
  733. tor_assert(size_out);
  734. *encoded_out = cert->encoded;
  735. *size_out = cert->encoded_len;
  736. }
  737. /** Return a set of digests for the public key in <b>cert</b>, or NULL if this
  738. * cert's public key is not one we know how to take the digest of. */
  739. const digests_t *
  740. tor_cert_get_id_digests(const tor_cert_t *cert)
  741. {
  742. if (cert->pkey_digests_set)
  743. return &cert->pkey_digests;
  744. else
  745. return NULL;
  746. }
  747. /** Return a set of digests for the public key in <b>cert</b>. */
  748. const digests_t *
  749. tor_cert_get_cert_digests(const tor_cert_t *cert)
  750. {
  751. return &cert->cert_digests;
  752. }
  753. /** Remove a reference to <b>ctx</b>, and free it if it has no more
  754. * references. */
  755. static void
  756. tor_tls_context_decref(tor_tls_context_t *ctx)
  757. {
  758. tor_assert(ctx);
  759. if (--ctx->refcnt == 0) {
  760. SSL_CTX_free(ctx->ctx);
  761. tor_cert_free(ctx->my_link_cert);
  762. tor_cert_free(ctx->my_id_cert);
  763. tor_cert_free(ctx->my_auth_cert);
  764. crypto_pk_free(ctx->link_key);
  765. crypto_pk_free(ctx->auth_key);
  766. tor_free(ctx);
  767. }
  768. }
  769. /** Set *<b>link_cert_out</b> and *<b>id_cert_out</b> to the link certificate
  770. * and ID certificate that we're currently using for our V3 in-protocol
  771. * handshake's certificate chain. If <b>server</b> is true, provide the certs
  772. * that we use in server mode; otherwise, provide the certs that we use in
  773. * client mode. */
  774. int
  775. tor_tls_get_my_certs(int server,
  776. const tor_cert_t **link_cert_out,
  777. const tor_cert_t **id_cert_out)
  778. {
  779. tor_tls_context_t *ctx = server ? server_tls_context : client_tls_context;
  780. if (! ctx)
  781. return -1;
  782. if (link_cert_out)
  783. *link_cert_out = server ? ctx->my_link_cert : ctx->my_auth_cert;
  784. if (id_cert_out)
  785. *id_cert_out = ctx->my_id_cert;
  786. return 0;
  787. }
  788. /**
  789. * Return the authentication key that we use to authenticate ourselves as a
  790. * client in the V3 in-protocol handshake.
  791. */
  792. crypto_pk_t *
  793. tor_tls_get_my_client_auth_key(void)
  794. {
  795. if (! client_tls_context)
  796. return NULL;
  797. return client_tls_context->auth_key;
  798. }
  799. /**
  800. * Return a newly allocated copy of the public key that a certificate
  801. * certifies. Return NULL if the cert's key is not RSA.
  802. */
  803. crypto_pk_t *
  804. tor_tls_cert_get_key(tor_cert_t *cert)
  805. {
  806. crypto_pk_t *result = NULL;
  807. EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
  808. RSA *rsa;
  809. if (!pkey)
  810. return NULL;
  811. rsa = EVP_PKEY_get1_RSA(pkey);
  812. if (!rsa) {
  813. EVP_PKEY_free(pkey);
  814. return NULL;
  815. }
  816. result = _crypto_new_pk_from_rsa(rsa);
  817. EVP_PKEY_free(pkey);
  818. return result;
  819. }
  820. /** Return true iff <b>a</b> and <b>b</b> represent the same public key. */
  821. static int
  822. pkey_eq(EVP_PKEY *a, EVP_PKEY *b)
  823. {
  824. /* We'd like to do this, but openssl 0.9.7 doesn't have it:
  825. return EVP_PKEY_cmp(a,b) == 1;
  826. */
  827. unsigned char *a_enc=NULL, *b_enc=NULL, *a_ptr, *b_ptr;
  828. int a_len1, b_len1, a_len2, b_len2, result;
  829. a_len1 = i2d_PublicKey(a, NULL);
  830. b_len1 = i2d_PublicKey(b, NULL);
  831. if (a_len1 != b_len1)
  832. return 0;
  833. a_ptr = a_enc = tor_malloc(a_len1);
  834. b_ptr = b_enc = tor_malloc(b_len1);
  835. a_len2 = i2d_PublicKey(a, &a_ptr);
  836. b_len2 = i2d_PublicKey(b, &b_ptr);
  837. tor_assert(a_len2 == a_len1);
  838. tor_assert(b_len2 == b_len1);
  839. result = tor_memeq(a_enc, b_enc, a_len1);
  840. tor_free(a_enc);
  841. tor_free(b_enc);
  842. return result;
  843. }
  844. /** Return true iff the other side of <b>tls</b> has authenticated to us, and
  845. * the key certified in <b>cert</b> is the same as the key they used to do it.
  846. */
  847. int
  848. tor_tls_cert_matches_key(const tor_tls_t *tls, const tor_cert_t *cert)
  849. {
  850. X509 *peercert = SSL_get_peer_certificate(tls->ssl);
  851. EVP_PKEY *link_key = NULL, *cert_key = NULL;
  852. int result;
  853. if (!peercert)
  854. return 0;
  855. link_key = X509_get_pubkey(peercert);
  856. cert_key = X509_get_pubkey(cert->cert);
  857. result = link_key && cert_key && pkey_eq(cert_key, link_key);
  858. X509_free(peercert);
  859. if (link_key)
  860. EVP_PKEY_free(link_key);
  861. if (cert_key)
  862. EVP_PKEY_free(cert_key);
  863. return result;
  864. }
  865. /** Check whether <b>cert</b> is well-formed, currently live, and correctly
  866. * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
  867. * make sure that it has an RSA key with 1024 bits; otherwise, just check that
  868. * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
  869. * we couldn't check it. */
  870. int
  871. tor_tls_cert_is_valid(int severity,
  872. const tor_cert_t *cert,
  873. const tor_cert_t *signing_cert,
  874. int check_rsa_1024)
  875. {
  876. EVP_PKEY *cert_key;
  877. EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
  878. int r, key_ok = 0;
  879. if (!signing_key)
  880. return 0;
  881. r = X509_verify(cert->cert, signing_key);
  882. EVP_PKEY_free(signing_key);
  883. if (r <= 0)
  884. return 0;
  885. /* okay, the signature checked out right. Now let's check the check the
  886. * lifetime. */
  887. if (check_cert_lifetime_internal(severity, cert->cert,
  888. 48*60*60, 30*24*60*60) < 0)
  889. return 0;
  890. cert_key = X509_get_pubkey(cert->cert);
  891. if (check_rsa_1024 && cert_key) {
  892. RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
  893. if (rsa && BN_num_bits(rsa->n) == 1024)
  894. key_ok = 1;
  895. if (rsa)
  896. RSA_free(rsa);
  897. } else if (cert_key) {
  898. int min_bits = 1024;
  899. #ifdef EVP_PKEY_EC
  900. if (EVP_PKEY_type(cert_key->type) == EVP_PKEY_EC)
  901. min_bits = 128;
  902. #endif
  903. if (EVP_PKEY_bits(cert_key) >= min_bits)
  904. key_ok = 1;
  905. }
  906. EVP_PKEY_free(cert_key);
  907. if (!key_ok)
  908. return 0;
  909. /* XXXX compare DNs or anything? */
  910. return 1;
  911. }
  912. /** Increase the reference count of <b>ctx</b>. */
  913. static void
  914. tor_tls_context_incref(tor_tls_context_t *ctx)
  915. {
  916. ++ctx->refcnt;
  917. }
  918. /** Create new global client and server TLS contexts.
  919. *
  920. * If <b>server_identity</b> is NULL, this will not generate a server
  921. * TLS context. If <b>is_public_server</b> is non-zero, this will use
  922. * the same TLS context for incoming and outgoing connections, and
  923. * ignore <b>client_identity</b>. */
  924. int
  925. tor_tls_context_init(int is_public_server,
  926. crypto_pk_t *client_identity,
  927. crypto_pk_t *server_identity,
  928. unsigned int key_lifetime)
  929. {
  930. int rv1 = 0;
  931. int rv2 = 0;
  932. if (is_public_server) {
  933. tor_tls_context_t *new_ctx;
  934. tor_tls_context_t *old_ctx;
  935. tor_assert(server_identity != NULL);
  936. rv1 = tor_tls_context_init_one(&server_tls_context,
  937. server_identity,
  938. key_lifetime, 0);
  939. if (rv1 >= 0) {
  940. new_ctx = server_tls_context;
  941. tor_tls_context_incref(new_ctx);
  942. old_ctx = client_tls_context;
  943. client_tls_context = new_ctx;
  944. if (old_ctx != NULL) {
  945. tor_tls_context_decref(old_ctx);
  946. }
  947. }
  948. } else {
  949. if (server_identity != NULL) {
  950. rv1 = tor_tls_context_init_one(&server_tls_context,
  951. server_identity,
  952. key_lifetime,
  953. 0);
  954. } else {
  955. tor_tls_context_t *old_ctx = server_tls_context;
  956. server_tls_context = NULL;
  957. if (old_ctx != NULL) {
  958. tor_tls_context_decref(old_ctx);
  959. }
  960. }
  961. rv2 = tor_tls_context_init_one(&client_tls_context,
  962. client_identity,
  963. key_lifetime,
  964. 1);
  965. }
  966. return MIN(rv1, rv2);
  967. }
  968. /** Create a new global TLS context.
  969. *
  970. * You can call this function multiple times. Each time you call it,
  971. * it generates new certificates; all new connections will use
  972. * the new SSL context.
  973. */
  974. static int
  975. tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  976. crypto_pk_t *identity,
  977. unsigned int key_lifetime,
  978. int is_client)
  979. {
  980. tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
  981. key_lifetime,
  982. is_client);
  983. tor_tls_context_t *old_ctx = *ppcontext;
  984. if (new_ctx != NULL) {
  985. *ppcontext = new_ctx;
  986. /* Free the old context if one existed. */
  987. if (old_ctx != NULL) {
  988. /* This is safe even if there are open connections: we reference-
  989. * count tor_tls_context_t objects. */
  990. tor_tls_context_decref(old_ctx);
  991. }
  992. }
  993. return ((new_ctx != NULL) ? 0 : -1);
  994. }
  995. /** Create a new TLS context for use with Tor TLS handshakes.
  996. * <b>identity</b> should be set to the identity key used to sign the
  997. * certificate.
  998. */
  999. static tor_tls_context_t *
  1000. tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
  1001. int is_client)
  1002. {
  1003. crypto_pk_t *rsa = NULL, *rsa_auth = NULL;
  1004. EVP_PKEY *pkey = NULL;
  1005. tor_tls_context_t *result = NULL;
  1006. X509 *cert = NULL, *idcert = NULL, *authcert = NULL;
  1007. char *nickname = NULL, *nn2 = NULL;
  1008. tor_tls_init();
  1009. nickname = crypto_random_hostname(8, 20, "www.", ".net");
  1010. #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
  1011. nn2 = crypto_random_hostname(8, 20, "www.", ".net");
  1012. #else
  1013. nn2 = crypto_random_hostname(8, 20, "www.", ".com");
  1014. #endif
  1015. /* Generate short-term RSA key for use with TLS. */
  1016. if (!(rsa = crypto_pk_new()))
  1017. goto error;
  1018. if (crypto_pk_generate_key(rsa)<0)
  1019. goto error;
  1020. if (!is_client) {
  1021. /* Generate short-term RSA key for use in the in-protocol ("v3")
  1022. * authentication handshake. */
  1023. if (!(rsa_auth = crypto_pk_new()))
  1024. goto error;
  1025. if (crypto_pk_generate_key(rsa_auth)<0)
  1026. goto error;
  1027. /* Create a link certificate signed by identity key. */
  1028. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  1029. key_lifetime);
  1030. /* Create self-signed certificate for identity key. */
  1031. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  1032. IDENTITY_CERT_LIFETIME);
  1033. /* Create an authentication certificate signed by identity key. */
  1034. authcert = tor_tls_create_certificate(rsa_auth, identity, nickname, nn2,
  1035. key_lifetime);
  1036. if (!cert || !idcert || !authcert) {
  1037. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  1038. goto error;
  1039. }
  1040. }
  1041. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  1042. result->refcnt = 1;
  1043. if (!is_client) {
  1044. result->my_link_cert = tor_cert_new(X509_dup(cert));
  1045. result->my_id_cert = tor_cert_new(X509_dup(idcert));
  1046. result->my_auth_cert = tor_cert_new(X509_dup(authcert));
  1047. if (!result->my_link_cert || !result->my_id_cert || !result->my_auth_cert)
  1048. goto error;
  1049. result->link_key = crypto_pk_dup_key(rsa);
  1050. result->auth_key = crypto_pk_dup_key(rsa_auth);
  1051. }
  1052. #if 0
  1053. /* Tell OpenSSL to only use TLS1. This may have subtly different results
  1054. * from SSLv23_method() with SSLv2 and SSLv3 disabled, so we need to do some
  1055. * investigation before we consider adjusting it. It should be compatible
  1056. * with existing Tors. */
  1057. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  1058. goto error;
  1059. #endif
  1060. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  1061. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  1062. goto error;
  1063. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  1064. /* Disable TLS1.1 and TLS1.2 if they exist. We need to do this to
  1065. * workaround a bug present in all OpenSSL 1.0.1 versions (as of 1
  1066. * June 2012), wherein renegotiating while using one of these TLS
  1067. * protocols will cause the client to send a TLS 1.0 ServerHello
  1068. * rather than a ServerHello written with the appropriate protocol
  1069. * version. Once some version of OpenSSL does TLS1.1 and TLS1.2
  1070. * renegotiation properly, we can turn them back on when built with
  1071. * that version. */
  1072. #ifdef SSL_OP_NO_TLSv1_2
  1073. SSL_CTX_set_options(result->ctx, SSL_OP_NO_TLSv1_2);
  1074. #endif
  1075. #ifdef SSL_OP_NO_TLSv1_1
  1076. SSL_CTX_set_options(result->ctx, SSL_OP_NO_TLSv1_1);
  1077. #endif
  1078. if (
  1079. #ifdef DISABLE_SSL3_HANDSHAKE
  1080. 1 ||
  1081. #endif
  1082. SSLeay() < OPENSSL_V(0,9,8,'s') ||
  1083. (SSLeay() >= OPENSSL_V_SERIES(0,9,9) &&
  1084. SSLeay() < OPENSSL_V(1,0,0,'f'))) {
  1085. /* And not SSL3 if it's subject to CVE-2011-4576. */
  1086. log_info(LD_NET, "Disabling SSLv3 because this OpenSSL version "
  1087. "might otherwise be vulnerable to CVE-2011-4576 "
  1088. "(compile-time version %08lx (%s); "
  1089. "runtime version %08lx (%s))",
  1090. (unsigned long)OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT,
  1091. (unsigned long)SSLeay(), SSLeay_version(SSLEAY_VERSION));
  1092. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv3);
  1093. }
  1094. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  1095. #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  1096. SSL_CTX_set_options(result->ctx,
  1097. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1098. #endif
  1099. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1100. * as authenticating any earlier-received data.
  1101. */
  1102. if (use_unsafe_renegotiation_op) {
  1103. SSL_CTX_set_options(result->ctx,
  1104. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1105. }
  1106. /* Don't actually allow compression; it uses ram and time, but the data
  1107. * we transmit is all encrypted anyway. */
  1108. if (result->ctx->comp_methods)
  1109. result->ctx->comp_methods = NULL;
  1110. #ifdef SSL_MODE_RELEASE_BUFFERS
  1111. SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
  1112. #endif
  1113. if (! is_client) {
  1114. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  1115. goto error;
  1116. X509_free(cert); /* We just added a reference to cert. */
  1117. cert=NULL;
  1118. if (idcert) {
  1119. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  1120. tor_assert(s);
  1121. X509_STORE_add_cert(s, idcert);
  1122. X509_free(idcert); /* The context now owns the reference to idcert */
  1123. idcert = NULL;
  1124. }
  1125. }
  1126. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  1127. if (!is_client) {
  1128. tor_assert(rsa);
  1129. if (!(pkey = _crypto_pk_get_evp_pkey(rsa,1)))
  1130. goto error;
  1131. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  1132. goto error;
  1133. EVP_PKEY_free(pkey);
  1134. pkey = NULL;
  1135. if (!SSL_CTX_check_private_key(result->ctx))
  1136. goto error;
  1137. }
  1138. {
  1139. crypto_dh_t *dh = crypto_dh_new(DH_TYPE_TLS);
  1140. tor_assert(dh);
  1141. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_get_dh(dh));
  1142. crypto_dh_free(dh);
  1143. }
  1144. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  1145. always_accept_verify_cb);
  1146. /* let us realloc bufs that we're writing from */
  1147. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  1148. if (rsa)
  1149. crypto_pk_free(rsa);
  1150. if (rsa_auth)
  1151. crypto_pk_free(rsa_auth);
  1152. X509_free(authcert);
  1153. tor_free(nickname);
  1154. tor_free(nn2);
  1155. return result;
  1156. error:
  1157. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
  1158. tor_free(nickname);
  1159. tor_free(nn2);
  1160. if (pkey)
  1161. EVP_PKEY_free(pkey);
  1162. if (rsa)
  1163. crypto_pk_free(rsa);
  1164. if (rsa_auth)
  1165. crypto_pk_free(rsa_auth);
  1166. if (result)
  1167. tor_tls_context_decref(result);
  1168. if (cert)
  1169. X509_free(cert);
  1170. if (idcert)
  1171. X509_free(idcert);
  1172. if (authcert)
  1173. X509_free(authcert);
  1174. return NULL;
  1175. }
  1176. #ifdef V2_HANDSHAKE_SERVER
  1177. /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
  1178. * a list that indicates that the client knows how to do the v2 TLS connection
  1179. * handshake. */
  1180. static int
  1181. tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
  1182. {
  1183. int i;
  1184. SSL_SESSION *session;
  1185. /* If we reached this point, we just got a client hello. See if there is
  1186. * a cipher list. */
  1187. if (!(session = SSL_get_session((SSL *)ssl))) {
  1188. log_info(LD_NET, "No session on TLS?");
  1189. return 0;
  1190. }
  1191. if (!session->ciphers) {
  1192. log_info(LD_NET, "No ciphers on session");
  1193. return 0;
  1194. }
  1195. /* Now we need to see if there are any ciphers whose presence means we're
  1196. * dealing with an updated Tor. */
  1197. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  1198. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  1199. const char *ciphername = SSL_CIPHER_get_name(cipher);
  1200. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  1201. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  1202. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  1203. strcmp(ciphername, "(NONE)")) {
  1204. log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
  1205. // return 1;
  1206. goto dump_list;
  1207. }
  1208. }
  1209. return 0;
  1210. dump_list:
  1211. {
  1212. smartlist_t *elts = smartlist_new();
  1213. char *s;
  1214. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  1215. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  1216. const char *ciphername = SSL_CIPHER_get_name(cipher);
  1217. smartlist_add(elts, (char*)ciphername);
  1218. }
  1219. s = smartlist_join_strings(elts, ":", 0, NULL);
  1220. log_debug(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
  1221. address, s);
  1222. tor_free(s);
  1223. smartlist_free(elts);
  1224. }
  1225. return 1;
  1226. }
  1227. /** Invoked when a TLS state changes: log the change at severity 'debug' */
  1228. static void
  1229. tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
  1230. {
  1231. log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
  1232. ssl, SSL_state_string_long(ssl), type, val);
  1233. }
  1234. /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
  1235. * changes state. We use this:
  1236. * <ul><li>To alter the state of the handshake partway through, so we
  1237. * do not send or request extra certificates in v2 handshakes.</li>
  1238. * <li>To detect renegotiation</li></ul>
  1239. */
  1240. static void
  1241. tor_tls_server_info_callback(const SSL *ssl, int type, int val)
  1242. {
  1243. tor_tls_t *tls;
  1244. (void) val;
  1245. tor_tls_debug_state_callback(ssl, type, val);
  1246. if (type != SSL_CB_ACCEPT_LOOP)
  1247. return;
  1248. if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
  1249. return;
  1250. tls = tor_tls_get_by_ssl(ssl);
  1251. if (tls) {
  1252. /* Check whether we're watching for renegotiates. If so, this is one! */
  1253. if (tls->negotiated_callback)
  1254. tls->got_renegotiate = 1;
  1255. if (tls->server_handshake_count < 127) /*avoid any overflow possibility*/
  1256. ++tls->server_handshake_count;
  1257. } else {
  1258. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  1259. return;
  1260. }
  1261. /* Now check the cipher list. */
  1262. if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
  1263. if (tls->wasV2Handshake)
  1264. return; /* We already turned this stuff off for the first handshake;
  1265. * This is a renegotiation. */
  1266. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  1267. * Let's hope openssl doesn't notice! */
  1268. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  1269. SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
  1270. /* Don't send a hello request. */
  1271. SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
  1272. if (tls) {
  1273. tls->wasV2Handshake = 1;
  1274. #ifdef USE_BUFFEREVENTS
  1275. if (use_unsafe_renegotiation_flag)
  1276. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1277. #endif
  1278. } else {
  1279. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  1280. }
  1281. }
  1282. }
  1283. #endif
  1284. /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
  1285. * a list designed to mimic a common web browser. Some of the ciphers in the
  1286. * list won't actually be implemented by OpenSSL: that's okay so long as the
  1287. * server doesn't select them, and the server won't select anything besides
  1288. * what's in SERVER_CIPHER_LIST.
  1289. *
  1290. * [If the server <b>does</b> select a bogus cipher, we won't crash or
  1291. * anything; we'll just fail later when we try to look up the cipher in
  1292. * ssl->cipher_list_by_id.]
  1293. */
  1294. static void
  1295. rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
  1296. {
  1297. #ifdef V2_HANDSHAKE_CLIENT
  1298. if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
  1299. /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
  1300. * we want.*/
  1301. int i = 0, j = 0;
  1302. /* First, create a dummy SSL_CIPHER for every cipher. */
  1303. CLIENT_CIPHER_DUMMIES =
  1304. tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
  1305. for (i=0; i < N_CLIENT_CIPHERS; ++i) {
  1306. CLIENT_CIPHER_DUMMIES[i].valid = 1;
  1307. CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
  1308. CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
  1309. }
  1310. CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
  1311. tor_assert(CLIENT_CIPHER_STACK);
  1312. log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
  1313. for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
  1314. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
  1315. log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
  1316. }
  1317. /* Then copy as many ciphers as we can from the good list, inserting
  1318. * dummies as needed. */
  1319. j=0;
  1320. for (i = 0; i < N_CLIENT_CIPHERS; ) {
  1321. SSL_CIPHER *cipher = NULL;
  1322. if (j < sk_SSL_CIPHER_num(*ciphers))
  1323. cipher = sk_SSL_CIPHER_value(*ciphers, j);
  1324. if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
  1325. log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
  1326. ++j;
  1327. } else if (cipher &&
  1328. (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
  1329. log_debug(LD_NET, "Found cipher %s", cipher->name);
  1330. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
  1331. ++j;
  1332. ++i;
  1333. } else {
  1334. log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
  1335. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
  1336. ++i;
  1337. }
  1338. }
  1339. }
  1340. sk_SSL_CIPHER_free(*ciphers);
  1341. *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
  1342. tor_assert(*ciphers);
  1343. #else
  1344. (void)ciphers;
  1345. #endif
  1346. }
  1347. /** Create a new TLS object from a file descriptor, and a flag to
  1348. * determine whether it is functioning as a server.
  1349. */
  1350. tor_tls_t *
  1351. tor_tls_new(int sock, int isServer)
  1352. {
  1353. BIO *bio = NULL;
  1354. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  1355. tor_tls_context_t *context = isServer ? server_tls_context :
  1356. client_tls_context;
  1357. result->magic = TOR_TLS_MAGIC;
  1358. tor_assert(context); /* make sure somebody made it first */
  1359. if (!(result->ssl = SSL_new(context->ctx))) {
  1360. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
  1361. tor_free(result);
  1362. return NULL;
  1363. }
  1364. #ifdef SSL_set_tlsext_host_name
  1365. /* Browsers use the TLS hostname extension, so we should too. */
  1366. if (!isServer) {
  1367. char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
  1368. SSL_set_tlsext_host_name(result->ssl, fake_hostname);
  1369. tor_free(fake_hostname);
  1370. }
  1371. #endif
  1372. if (!SSL_set_cipher_list(result->ssl,
  1373. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  1374. tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
  1375. #ifdef SSL_set_tlsext_host_name
  1376. SSL_set_tlsext_host_name(result->ssl, NULL);
  1377. #endif
  1378. SSL_free(result->ssl);
  1379. tor_free(result);
  1380. return NULL;
  1381. }
  1382. if (!isServer)
  1383. rectify_client_ciphers(&result->ssl->cipher_list);
  1384. result->socket = sock;
  1385. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1386. if (! bio) {
  1387. tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
  1388. #ifdef SSL_set_tlsext_host_name
  1389. SSL_set_tlsext_host_name(result->ssl, NULL);
  1390. #endif
  1391. SSL_free(result->ssl);
  1392. tor_free(result);
  1393. return NULL;
  1394. }
  1395. {
  1396. int set_worked =
  1397. SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
  1398. if (!set_worked) {
  1399. log_warn(LD_BUG,
  1400. "Couldn't set the tls for an SSL*; connection will fail");
  1401. }
  1402. }
  1403. SSL_set_bio(result->ssl, bio, bio);
  1404. tor_tls_context_incref(context);
  1405. result->context = context;
  1406. result->state = TOR_TLS_ST_HANDSHAKE;
  1407. result->isServer = isServer;
  1408. result->wantwrite_n = 0;
  1409. result->last_write_count = BIO_number_written(bio);
  1410. result->last_read_count = BIO_number_read(bio);
  1411. if (result->last_write_count || result->last_read_count) {
  1412. log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
  1413. result->last_read_count, result->last_write_count);
  1414. }
  1415. #ifdef V2_HANDSHAKE_SERVER
  1416. if (isServer) {
  1417. SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
  1418. } else
  1419. #endif
  1420. {
  1421. SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
  1422. }
  1423. /* Not expected to get called. */
  1424. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
  1425. return result;
  1426. }
  1427. /** Make future log messages about <b>tls</b> display the address
  1428. * <b>address</b>.
  1429. */
  1430. void
  1431. tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
  1432. {
  1433. tor_assert(tls);
  1434. tor_free(tls->address);
  1435. tls->address = tor_strdup(address);
  1436. }
  1437. /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
  1438. * next gets a client-side renegotiate in the middle of a read. Do not
  1439. * invoke this function until <em>after</em> initial handshaking is done!
  1440. */
  1441. void
  1442. tor_tls_set_renegotiate_callback(tor_tls_t *tls,
  1443. void (*cb)(tor_tls_t *, void *arg),
  1444. void *arg)
  1445. {
  1446. tls->negotiated_callback = cb;
  1447. tls->callback_arg = arg;
  1448. tls->got_renegotiate = 0;
  1449. #ifdef V2_HANDSHAKE_SERVER
  1450. if (cb) {
  1451. SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
  1452. } else {
  1453. SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
  1454. }
  1455. #endif
  1456. }
  1457. /** If this version of openssl requires it, turn on renegotiation on
  1458. * <b>tls</b>.
  1459. */
  1460. void
  1461. tor_tls_unblock_renegotiation(tor_tls_t *tls)
  1462. {
  1463. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1464. * as authenticating any earlier-received data. */
  1465. if (use_unsafe_renegotiation_flag) {
  1466. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1467. }
  1468. if (use_unsafe_renegotiation_op) {
  1469. SSL_set_options(tls->ssl,
  1470. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1471. }
  1472. }
  1473. /** If this version of openssl supports it, turn off renegotiation on
  1474. * <b>tls</b>. (Our protocol never requires this for security, but it's nice
  1475. * to use belt-and-suspenders here.)
  1476. */
  1477. void
  1478. tor_tls_block_renegotiation(tor_tls_t *tls)
  1479. {
  1480. tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1481. }
  1482. /** Assert that the flags that allow legacy renegotiation are still set */
  1483. void
  1484. tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
  1485. {
  1486. if (use_unsafe_renegotiation_flag) {
  1487. tor_assert(0 != (tls->ssl->s3->flags &
  1488. SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1489. }
  1490. if (use_unsafe_renegotiation_op) {
  1491. long options = SSL_get_options(tls->ssl);
  1492. tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1493. }
  1494. }
  1495. /** Return whether this tls initiated the connect (client) or
  1496. * received it (server). */
  1497. int
  1498. tor_tls_is_server(tor_tls_t *tls)
  1499. {
  1500. tor_assert(tls);
  1501. return tls->isServer;
  1502. }
  1503. /** Release resources associated with a TLS object. Does not close the
  1504. * underlying file descriptor.
  1505. */
  1506. void
  1507. tor_tls_free(tor_tls_t *tls)
  1508. {
  1509. if (!tls)
  1510. return;
  1511. tor_assert(tls->ssl);
  1512. #ifdef SSL_set_tlsext_host_name
  1513. SSL_set_tlsext_host_name(tls->ssl, NULL);
  1514. #endif
  1515. SSL_free(tls->ssl);
  1516. tls->ssl = NULL;
  1517. tls->negotiated_callback = NULL;
  1518. if (tls->context)
  1519. tor_tls_context_decref(tls->context);
  1520. tor_free(tls->address);
  1521. tls->magic = 0x99999999;
  1522. tor_free(tls);
  1523. }
  1524. /** Underlying function for TLS reading. Reads up to <b>len</b>
  1525. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  1526. * number of characters read. On failure, returns TOR_TLS_ERROR,
  1527. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1528. */
  1529. int
  1530. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  1531. {
  1532. int r, err;
  1533. tor_assert(tls);
  1534. tor_assert(tls->ssl);
  1535. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1536. tor_assert(len<INT_MAX);
  1537. r = SSL_read(tls->ssl, cp, (int)len);
  1538. if (r > 0) {
  1539. #ifdef V2_HANDSHAKE_SERVER
  1540. if (tls->got_renegotiate) {
  1541. /* Renegotiation happened! */
  1542. log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
  1543. if (tls->negotiated_callback)
  1544. tls->negotiated_callback(tls, tls->callback_arg);
  1545. tls->got_renegotiate = 0;
  1546. }
  1547. #endif
  1548. return r;
  1549. }
  1550. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
  1551. if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
  1552. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  1553. tls->state = TOR_TLS_ST_CLOSED;
  1554. return TOR_TLS_CLOSE;
  1555. } else {
  1556. tor_assert(err != TOR_TLS_DONE);
  1557. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  1558. return err;
  1559. }
  1560. }
  1561. /** Underlying function for TLS writing. Write up to <b>n</b>
  1562. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  1563. * number of characters written. On failure, returns TOR_TLS_ERROR,
  1564. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1565. */
  1566. int
  1567. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  1568. {
  1569. int r, err;
  1570. tor_assert(tls);
  1571. tor_assert(tls->ssl);
  1572. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1573. tor_assert(n < INT_MAX);
  1574. if (n == 0)
  1575. return 0;
  1576. if (tls->wantwrite_n) {
  1577. /* if WANTWRITE last time, we must use the _same_ n as before */
  1578. tor_assert(n >= tls->wantwrite_n);
  1579. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  1580. (int)n, (int)tls->wantwrite_n);
  1581. n = tls->wantwrite_n;
  1582. tls->wantwrite_n = 0;
  1583. }
  1584. r = SSL_write(tls->ssl, cp, (int)n);
  1585. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
  1586. if (err == TOR_TLS_DONE) {
  1587. return r;
  1588. }
  1589. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  1590. tls->wantwrite_n = n;
  1591. }
  1592. return err;
  1593. }
  1594. /** Perform initial handshake on <b>tls</b>. When finished, returns
  1595. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1596. * or TOR_TLS_WANTWRITE.
  1597. */
  1598. int
  1599. tor_tls_handshake(tor_tls_t *tls)
  1600. {
  1601. int r;
  1602. int oldstate;
  1603. tor_assert(tls);
  1604. tor_assert(tls->ssl);
  1605. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  1606. check_no_tls_errors();
  1607. oldstate = tls->ssl->state;
  1608. if (tls->isServer) {
  1609. log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
  1610. SSL_state_string_long(tls->ssl));
  1611. r = SSL_accept(tls->ssl);
  1612. } else {
  1613. log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
  1614. SSL_state_string_long(tls->ssl));
  1615. r = SSL_connect(tls->ssl);
  1616. }
  1617. if (oldstate != tls->ssl->state)
  1618. log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
  1619. tls, SSL_state_string_long(tls->ssl));
  1620. /* We need to call this here and not earlier, since OpenSSL has a penchant
  1621. * for clearing its flags when you say accept or connect. */
  1622. tor_tls_unblock_renegotiation(tls);
  1623. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
  1624. if (ERR_peek_error() != 0) {
  1625. tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
  1626. "handshaking");
  1627. return TOR_TLS_ERROR_MISC;
  1628. }
  1629. if (r == TOR_TLS_DONE) {
  1630. tls->state = TOR_TLS_ST_OPEN;
  1631. return tor_tls_finish_handshake(tls);
  1632. }
  1633. return r;
  1634. }
  1635. /** Perform the final part of the intial TLS handshake on <b>tls</b>. This
  1636. * should be called for the first handshake only: it determines whether the v1
  1637. * or the v2 handshake was used, and adjusts things for the renegotiation
  1638. * handshake as appropriate.
  1639. *
  1640. * tor_tls_handshake() calls this on its own; you only need to call this if
  1641. * bufferevent is doing the handshake for you.
  1642. */
  1643. int
  1644. tor_tls_finish_handshake(tor_tls_t *tls)
  1645. {
  1646. int r = TOR_TLS_DONE;
  1647. if (tls->isServer) {
  1648. SSL_set_info_callback(tls->ssl, NULL);
  1649. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
  1650. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  1651. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  1652. #ifdef V2_HANDSHAKE_SERVER
  1653. if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
  1654. /* This check is redundant, but back when we did it in the callback,
  1655. * we might have not been able to look up the tor_tls_t if the code
  1656. * was buggy. Fixing that. */
  1657. if (!tls->wasV2Handshake) {
  1658. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  1659. " get set. Fixing that.");
  1660. }
  1661. tls->wasV2Handshake = 1;
  1662. log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
  1663. " for renegotiation.");
  1664. } else {
  1665. tls->wasV2Handshake = 0;
  1666. }
  1667. #endif
  1668. } else {
  1669. #ifdef V2_HANDSHAKE_CLIENT
  1670. /* If we got no ID cert, we're a v2 handshake. */
  1671. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  1672. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  1673. int n_certs = sk_X509_num(chain);
  1674. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0))) {
  1675. log_debug(LD_HANDSHAKE, "Server sent back multiple certificates; it "
  1676. "looks like a v1 handshake on %p", tls);
  1677. tls->wasV2Handshake = 0;
  1678. } else {
  1679. log_debug(LD_HANDSHAKE,
  1680. "Server sent back a single certificate; looks like "
  1681. "a v2 handshake on %p.", tls);
  1682. tls->wasV2Handshake = 1;
  1683. }
  1684. if (cert)
  1685. X509_free(cert);
  1686. #endif
  1687. if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
  1688. tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
  1689. r = TOR_TLS_ERROR_MISC;
  1690. }
  1691. }
  1692. return r;
  1693. }
  1694. #ifdef USE_BUFFEREVENTS
  1695. /** Put <b>tls</b>, which must be a client connection, into renegotiation
  1696. * mode. */
  1697. int
  1698. tor_tls_start_renegotiating(tor_tls_t *tls)
  1699. {
  1700. int r = SSL_renegotiate(tls->ssl);
  1701. if (r <= 0) {
  1702. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1703. LD_HANDSHAKE);
  1704. }
  1705. return 0;
  1706. }
  1707. #endif
  1708. /** Client only: Renegotiate a TLS session. When finished, returns
  1709. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  1710. * TOR_TLS_WANTWRITE.
  1711. */
  1712. int
  1713. tor_tls_renegotiate(tor_tls_t *tls)
  1714. {
  1715. int r;
  1716. tor_assert(tls);
  1717. /* We could do server-initiated renegotiation too, but that would be tricky.
  1718. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  1719. tor_assert(!tls->isServer);
  1720. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  1721. int r = SSL_renegotiate(tls->ssl);
  1722. if (r <= 0) {
  1723. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1724. LD_HANDSHAKE);
  1725. }
  1726. tls->state = TOR_TLS_ST_RENEGOTIATE;
  1727. }
  1728. r = SSL_do_handshake(tls->ssl);
  1729. if (r == 1) {
  1730. tls->state = TOR_TLS_ST_OPEN;
  1731. return TOR_TLS_DONE;
  1732. } else
  1733. return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO,
  1734. LD_HANDSHAKE);
  1735. }
  1736. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  1737. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1738. * or TOR_TLS_WANTWRITE.
  1739. */
  1740. int
  1741. tor_tls_shutdown(tor_tls_t *tls)
  1742. {
  1743. int r, err;
  1744. char buf[128];
  1745. tor_assert(tls);
  1746. tor_assert(tls->ssl);
  1747. while (1) {
  1748. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  1749. /* If we've already called shutdown once to send a close message,
  1750. * we read until the other side has closed too.
  1751. */
  1752. do {
  1753. r = SSL_read(tls->ssl, buf, 128);
  1754. } while (r>0);
  1755. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  1756. LOG_INFO, LD_NET);
  1757. if (err == _TOR_TLS_ZERORETURN) {
  1758. tls->state = TOR_TLS_ST_GOTCLOSE;
  1759. /* fall through... */
  1760. } else {
  1761. return err;
  1762. }
  1763. }
  1764. r = SSL_shutdown(tls->ssl);
  1765. if (r == 1) {
  1766. /* If shutdown returns 1, the connection is entirely closed. */
  1767. tls->state = TOR_TLS_ST_CLOSED;
  1768. return TOR_TLS_DONE;
  1769. }
  1770. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  1771. LOG_INFO, LD_NET);
  1772. if (err == _TOR_TLS_SYSCALL) {
  1773. /* The underlying TCP connection closed while we were shutting down. */
  1774. tls->state = TOR_TLS_ST_CLOSED;
  1775. return TOR_TLS_DONE;
  1776. } else if (err == _TOR_TLS_ZERORETURN) {
  1777. /* The TLS connection says that it sent a shutdown record, but
  1778. * isn't done shutting down yet. Make sure that this hasn't
  1779. * happened before, then go back to the start of the function
  1780. * and try to read.
  1781. */
  1782. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  1783. tls->state == TOR_TLS_ST_SENTCLOSE) {
  1784. log(LOG_WARN, LD_NET,
  1785. "TLS returned \"half-closed\" value while already half-closed");
  1786. return TOR_TLS_ERROR_MISC;
  1787. }
  1788. tls->state = TOR_TLS_ST_SENTCLOSE;
  1789. /* fall through ... */
  1790. } else {
  1791. return err;
  1792. }
  1793. } /* end loop */
  1794. }
  1795. /** Return true iff this TLS connection is authenticated.
  1796. */
  1797. int
  1798. tor_tls_peer_has_cert(tor_tls_t *tls)
  1799. {
  1800. X509 *cert;
  1801. cert = SSL_get_peer_certificate(tls->ssl);
  1802. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1803. if (!cert)
  1804. return 0;
  1805. X509_free(cert);
  1806. return 1;
  1807. }
  1808. /** Return the peer certificate, or NULL if there isn't one. */
  1809. tor_cert_t *
  1810. tor_tls_get_peer_cert(tor_tls_t *tls)
  1811. {
  1812. X509 *cert;
  1813. cert = SSL_get_peer_certificate(tls->ssl);
  1814. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1815. if (!cert)
  1816. return NULL;
  1817. return tor_cert_new(cert);
  1818. }
  1819. /** Warn that a certificate lifetime extends through a certain range. */
  1820. static void
  1821. log_cert_lifetime(int severity, const X509 *cert, const char *problem)
  1822. {
  1823. BIO *bio = NULL;
  1824. BUF_MEM *buf;
  1825. char *s1=NULL, *s2=NULL;
  1826. char mytime[33];
  1827. time_t now = time(NULL);
  1828. struct tm tm;
  1829. if (problem)
  1830. log(severity, LD_GENERAL,
  1831. "Certificate %s. Either their clock is set wrong, or your clock "
  1832. "is wrong.",
  1833. problem);
  1834. if (!(bio = BIO_new(BIO_s_mem()))) {
  1835. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1836. }
  1837. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1838. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1839. goto end;
  1840. }
  1841. BIO_get_mem_ptr(bio, &buf);
  1842. s1 = tor_strndup(buf->data, buf->length);
  1843. (void)BIO_reset(bio);
  1844. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1845. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1846. goto end;
  1847. }
  1848. BIO_get_mem_ptr(bio, &buf);
  1849. s2 = tor_strndup(buf->data, buf->length);
  1850. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1851. log(severity, LD_GENERAL,
  1852. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1853. s1,s2,mytime);
  1854. end:
  1855. /* Not expected to get invoked */
  1856. tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
  1857. if (bio)
  1858. BIO_free(bio);
  1859. tor_free(s1);
  1860. tor_free(s2);
  1861. }
  1862. /** Helper function: try to extract a link certificate and an identity
  1863. * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
  1864. * *<b>id_cert_out</b> respectively. Log all messages at level
  1865. * <b>severity</b>.
  1866. *
  1867. * Note that a reference is added to cert_out, so it needs to be
  1868. * freed. id_cert_out doesn't. */
  1869. static void
  1870. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1871. X509 **cert_out, X509 **id_cert_out)
  1872. {
  1873. X509 *cert = NULL, *id_cert = NULL;
  1874. STACK_OF(X509) *chain = NULL;
  1875. int num_in_chain, i;
  1876. *cert_out = *id_cert_out = NULL;
  1877. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1878. return;
  1879. *cert_out = cert;
  1880. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1881. return;
  1882. num_in_chain = sk_X509_num(chain);
  1883. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1884. * 2 means we're connecting (client-side), and it's both the link
  1885. * cert and the id_cert.
  1886. */
  1887. if (num_in_chain < 1) {
  1888. log_fn(severity,LD_PROTOCOL,
  1889. "Unexpected number of certificates in chain (%d)",
  1890. num_in_chain);
  1891. return;
  1892. }
  1893. for (i=0; i<num_in_chain; ++i) {
  1894. id_cert = sk_X509_value(chain, i);
  1895. if (X509_cmp(id_cert, cert) != 0)
  1896. break;
  1897. }
  1898. *id_cert_out = id_cert;
  1899. }
  1900. /** If the provided tls connection is authenticated and has a
  1901. * certificate chain that is currently valid and signed, then set
  1902. * *<b>identity_key</b> to the identity certificate's key and return
  1903. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1904. */
  1905. int
  1906. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity_key)
  1907. {
  1908. X509 *cert = NULL, *id_cert = NULL;
  1909. EVP_PKEY *id_pkey = NULL;
  1910. RSA *rsa;
  1911. int r = -1;
  1912. *identity_key = NULL;
  1913. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1914. if (!cert)
  1915. goto done;
  1916. if (!id_cert) {
  1917. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1918. goto done;
  1919. }
  1920. tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
  1921. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1922. X509_verify(cert, id_pkey) <= 0) {
  1923. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1924. tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
  1925. goto done;
  1926. }
  1927. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1928. if (!rsa)
  1929. goto done;
  1930. *identity_key = _crypto_new_pk_from_rsa(rsa);
  1931. r = 0;
  1932. done:
  1933. if (cert)
  1934. X509_free(cert);
  1935. if (id_pkey)
  1936. EVP_PKEY_free(id_pkey);
  1937. /* This should never get invoked, but let's make sure in case OpenSSL
  1938. * acts unexpectedly. */
  1939. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
  1940. return r;
  1941. }
  1942. /** Check whether the certificate set on the connection <b>tls</b> is expired
  1943. * give or take <b>past_tolerance</b> seconds, or not-yet-valid give or take
  1944. * <b>future_tolerance</b> seconds. Return 0 for valid, -1 for failure.
  1945. *
  1946. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1947. */
  1948. int
  1949. tor_tls_check_lifetime(int severity, tor_tls_t *tls,
  1950. int past_tolerance, int future_tolerance)
  1951. {
  1952. X509 *cert;
  1953. int r = -1;
  1954. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1955. goto done;
  1956. if (check_cert_lifetime_internal(severity, cert,
  1957. past_tolerance, future_tolerance) < 0)
  1958. goto done;
  1959. r = 0;
  1960. done:
  1961. if (cert)
  1962. X509_free(cert);
  1963. /* Not expected to get invoked */
  1964. tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
  1965. return r;
  1966. }
  1967. /** Helper: check whether <b>cert</b> is expired give or take
  1968. * <b>past_tolerance</b> seconds, or not-yet-valid give or take
  1969. * <b>future_tolerance</b> seconds. If it is live, return 0. If it is not
  1970. * live, log a message and return -1. */
  1971. static int
  1972. check_cert_lifetime_internal(int severity, const X509 *cert,
  1973. int past_tolerance, int future_tolerance)
  1974. {
  1975. time_t now, t;
  1976. now = time(NULL);
  1977. t = now + future_tolerance;
  1978. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1979. log_cert_lifetime(severity, cert, "not yet valid");
  1980. return -1;
  1981. }
  1982. t = now - past_tolerance;
  1983. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1984. log_cert_lifetime(severity, cert, "already expired");
  1985. return -1;
  1986. }
  1987. return 0;
  1988. }
  1989. /** Return the number of bytes available for reading from <b>tls</b>.
  1990. */
  1991. int
  1992. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1993. {
  1994. tor_assert(tls);
  1995. return SSL_pending(tls->ssl);
  1996. }
  1997. /** If <b>tls</b> requires that the next write be of a particular size,
  1998. * return that size. Otherwise, return 0. */
  1999. size_t
  2000. tor_tls_get_forced_write_size(tor_tls_t *tls)
  2001. {
  2002. return tls->wantwrite_n;
  2003. }
  2004. /** Sets n_read and n_written to the number of bytes read and written,
  2005. * respectively, on the raw socket used by <b>tls</b> since the last time this
  2006. * function was called on <b>tls</b>. */
  2007. void
  2008. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  2009. {
  2010. BIO *wbio, *tmpbio;
  2011. unsigned long r, w;
  2012. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  2013. /* We want the number of bytes actually for real written. Unfortunately,
  2014. * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
  2015. * which makes the answer turn out wrong. Let's cope with that. Note
  2016. * that this approach will fail if we ever replace tls->ssl's BIOs with
  2017. * buffering bios for reasons of our own. As an alternative, we could
  2018. * save the original BIO for tls->ssl in the tor_tls_t structure, but
  2019. * that would be tempting fate. */
  2020. wbio = SSL_get_wbio(tls->ssl);
  2021. if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
  2022. wbio = tmpbio;
  2023. w = BIO_number_written(wbio);
  2024. /* We are ok with letting these unsigned ints go "negative" here:
  2025. * If we wrapped around, this should still give us the right answer, unless
  2026. * we wrapped around by more than ULONG_MAX since the last time we called
  2027. * this function.
  2028. */
  2029. *n_read = (size_t)(r - tls->last_read_count);
  2030. *n_written = (size_t)(w - tls->last_write_count);
  2031. if (*n_read > INT_MAX || *n_written > INT_MAX) {
  2032. log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
  2033. "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
  2034. r, tls->last_read_count, w, tls->last_write_count);
  2035. }
  2036. tls->last_read_count = r;
  2037. tls->last_write_count = w;
  2038. }
  2039. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  2040. * errors, log an error message. */
  2041. void
  2042. _check_no_tls_errors(const char *fname, int line)
  2043. {
  2044. if (ERR_peek_error() == 0)
  2045. return;
  2046. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  2047. tor_fix_source_file(fname), line);
  2048. tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
  2049. }
  2050. /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
  2051. * TLS handshake. Output is undefined if the handshake isn't finished. */
  2052. int
  2053. tor_tls_used_v1_handshake(tor_tls_t *tls)
  2054. {
  2055. if (tls->isServer) {
  2056. #ifdef V2_HANDSHAKE_SERVER
  2057. return ! tls->wasV2Handshake;
  2058. #endif
  2059. } else {
  2060. #ifdef V2_HANDSHAKE_CLIENT
  2061. return ! tls->wasV2Handshake;
  2062. #endif
  2063. }
  2064. return 1;
  2065. }
  2066. /** Return true iff <b>name</b> is a DN of a kind that could only
  2067. * occur in a v3-handshake-indicating certificate */
  2068. static int
  2069. dn_indicates_v3_cert(X509_NAME *name)
  2070. {
  2071. #ifdef DISABLE_V3_LINKPROTO_CLIENTSIDE
  2072. (void)name;
  2073. return 0;
  2074. #else
  2075. X509_NAME_ENTRY *entry;
  2076. int n_entries;
  2077. ASN1_OBJECT *obj;
  2078. ASN1_STRING *str;
  2079. unsigned char *s;
  2080. int len, r;
  2081. n_entries = X509_NAME_entry_count(name);
  2082. if (n_entries != 1)
  2083. return 1; /* More than one entry in the DN. */
  2084. entry = X509_NAME_get_entry(name, 0);
  2085. obj = X509_NAME_ENTRY_get_object(entry);
  2086. if (OBJ_obj2nid(obj) != OBJ_txt2nid("commonName"))
  2087. return 1; /* The entry isn't a commonName. */
  2088. str = X509_NAME_ENTRY_get_data(entry);
  2089. len = ASN1_STRING_to_UTF8(&s, str);
  2090. if (len < 0)
  2091. return 0;
  2092. r = fast_memneq(s + len - 4, ".net", 4);
  2093. OPENSSL_free(s);
  2094. return r;
  2095. #endif
  2096. }
  2097. /** Return true iff the peer certificate we're received on <b>tls</b>
  2098. * indicates that this connection should use the v3 (in-protocol)
  2099. * authentication handshake.
  2100. *
  2101. * Only the connection initiator should use this, and only once the initial
  2102. * handshake is done; the responder detects a v1 handshake by cipher types,
  2103. * and a v3/v2 handshake by Versions cell vs renegotiation.
  2104. */
  2105. int
  2106. tor_tls_received_v3_certificate(tor_tls_t *tls)
  2107. {
  2108. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  2109. EVP_PKEY *key = NULL;
  2110. X509_NAME *issuer_name, *subject_name;
  2111. int is_v3 = 0;
  2112. if (!cert) {
  2113. log_warn(LD_BUG, "Called on a connection with no peer certificate");
  2114. goto done;
  2115. }
  2116. subject_name = X509_get_subject_name(cert);
  2117. issuer_name = X509_get_issuer_name(cert);
  2118. if (X509_name_cmp(subject_name, issuer_name) == 0) {
  2119. is_v3 = 1; /* purportedly self signed */
  2120. goto done;
  2121. }
  2122. if (dn_indicates_v3_cert(subject_name) ||
  2123. dn_indicates_v3_cert(issuer_name)) {
  2124. is_v3 = 1; /* DN is fancy */
  2125. goto done;
  2126. }
  2127. key = X509_get_pubkey(cert);
  2128. if (EVP_PKEY_bits(key) != 1024 ||
  2129. EVP_PKEY_type(key->type) != EVP_PKEY_RSA) {
  2130. is_v3 = 1; /* Key is fancy */
  2131. goto done;
  2132. }
  2133. done:
  2134. if (key)
  2135. EVP_PKEY_free(key);
  2136. if (cert)
  2137. X509_free(cert);
  2138. return is_v3;
  2139. }
  2140. /** Return the number of server handshakes that we've noticed doing on
  2141. * <b>tls</b>. */
  2142. int
  2143. tor_tls_get_num_server_handshakes(tor_tls_t *tls)
  2144. {
  2145. return tls->server_handshake_count;
  2146. }
  2147. /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
  2148. * request it was waiting for. */
  2149. int
  2150. tor_tls_server_got_renegotiate(tor_tls_t *tls)
  2151. {
  2152. return tls->got_renegotiate;
  2153. }
  2154. /** Set the DIGEST256_LEN buffer at <b>secrets_out</b> to the value used in
  2155. * the v3 handshake to prove that the client knows the TLS secrets for the
  2156. * connection <b>tls</b>. Return 0 on success, -1 on failure.
  2157. */
  2158. int
  2159. tor_tls_get_tlssecrets(tor_tls_t *tls, uint8_t *secrets_out)
  2160. {
  2161. #define TLSSECRET_MAGIC "Tor V3 handshake TLS cross-certification"
  2162. char buf[128];
  2163. size_t len;
  2164. tor_assert(tls);
  2165. tor_assert(tls->ssl);
  2166. tor_assert(tls->ssl->s3);
  2167. tor_assert(tls->ssl->session);
  2168. /*
  2169. The value is an HMAC, using the TLS master key as the HMAC key, of
  2170. client_random | server_random | TLSSECRET_MAGIC
  2171. */
  2172. memcpy(buf + 0, tls->ssl->s3->client_random, 32);
  2173. memcpy(buf + 32, tls->ssl->s3->server_random, 32);
  2174. memcpy(buf + 64, TLSSECRET_MAGIC, strlen(TLSSECRET_MAGIC) + 1);
  2175. len = 64 + strlen(TLSSECRET_MAGIC) + 1;
  2176. crypto_hmac_sha256((char*)secrets_out,
  2177. (char*)tls->ssl->session->master_key,
  2178. tls->ssl->session->master_key_length,
  2179. buf, len);
  2180. memset(buf, 0, sizeof(buf));
  2181. return 0;
  2182. }
  2183. /** Examine the amount of memory used and available for buffers in <b>tls</b>.
  2184. * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
  2185. * buffer and *<b>rbuf_bytes</b> to the amount actually used.
  2186. * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
  2187. * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
  2188. void
  2189. tor_tls_get_buffer_sizes(tor_tls_t *tls,
  2190. size_t *rbuf_capacity, size_t *rbuf_bytes,
  2191. size_t *wbuf_capacity, size_t *wbuf_bytes)
  2192. {
  2193. if (tls->ssl->s3->rbuf.buf)
  2194. *rbuf_capacity = tls->ssl->s3->rbuf.len;
  2195. else
  2196. *rbuf_capacity = 0;
  2197. if (tls->ssl->s3->wbuf.buf)
  2198. *wbuf_capacity = tls->ssl->s3->wbuf.len;
  2199. else
  2200. *wbuf_capacity = 0;
  2201. *rbuf_bytes = tls->ssl->s3->rbuf.left;
  2202. *wbuf_bytes = tls->ssl->s3->wbuf.left;
  2203. }
  2204. #ifdef USE_BUFFEREVENTS
  2205. /** Construct and return an TLS-encrypting bufferevent to send data over
  2206. * <b>socket</b>, which must match the socket of the underlying bufferevent
  2207. * <b>bufev_in</b>. The TLS object <b>tls</b> is used for encryption.
  2208. *
  2209. * This function will either create a filtering bufferevent that wraps around
  2210. * <b>bufev_in</b>, or it will free bufev_in and return a new bufferevent that
  2211. * uses the <b>tls</b> to talk to the network directly. Do not use
  2212. * <b>bufev_in</b> after calling this function.
  2213. *
  2214. * The connection will start out doing a server handshake if <b>receiving</b>
  2215. * is strue, and a client handshake otherwise.
  2216. *
  2217. * Returns NULL on failure.
  2218. */
  2219. struct bufferevent *
  2220. tor_tls_init_bufferevent(tor_tls_t *tls, struct bufferevent *bufev_in,
  2221. evutil_socket_t socket, int receiving,
  2222. int filter)
  2223. {
  2224. struct bufferevent *out;
  2225. const enum bufferevent_ssl_state state = receiving ?
  2226. BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
  2227. if (filter || tor_libevent_using_iocp_bufferevents()) {
  2228. /* Grab an extra reference to the SSL, since BEV_OPT_CLOSE_ON_FREE
  2229. means that the SSL will get freed too.
  2230. This increment makes our SSL usage not-threadsafe, BTW. We should
  2231. see if we're allowed to use CRYPTO_add from outside openssl. */
  2232. tls->ssl->references += 1;
  2233. out = bufferevent_openssl_filter_new(tor_libevent_get_base(),
  2234. bufev_in,
  2235. tls->ssl,
  2236. state,
  2237. BEV_OPT_DEFER_CALLBACKS|
  2238. BEV_OPT_CLOSE_ON_FREE);
  2239. /* Tell the underlying bufferevent when to accept more data from the SSL
  2240. filter (only when it's got less than 32K to write), and when to notify
  2241. the SSL filter that it could write more (when it drops under 24K). */
  2242. bufferevent_setwatermark(bufev_in, EV_WRITE, 24*1024, 32*1024);
  2243. } else {
  2244. if (bufev_in) {
  2245. evutil_socket_t s = bufferevent_getfd(bufev_in);
  2246. tor_assert(s == -1 || s == socket);
  2247. tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in)) == 0);
  2248. tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in)) == 0);
  2249. tor_assert(BIO_number_read(SSL_get_rbio(tls->ssl)) == 0);
  2250. tor_assert(BIO_number_written(SSL_get_rbio(tls->ssl)) == 0);
  2251. bufferevent_free(bufev_in);
  2252. }
  2253. /* Current versions (as of 2.0.x) of Libevent need to defer
  2254. * bufferevent_openssl callbacks, or else our callback functions will
  2255. * get called reentrantly, which is bad for us.
  2256. */
  2257. out = bufferevent_openssl_socket_new(tor_libevent_get_base(),
  2258. socket,
  2259. tls->ssl,
  2260. state,
  2261. BEV_OPT_DEFER_CALLBACKS);
  2262. }
  2263. tls->state = TOR_TLS_ST_BUFFEREVENT;
  2264. /* Unblock _after_ creating the bufferevent, since accept/connect tend to
  2265. * clear flags. */
  2266. tor_tls_unblock_renegotiation(tls);
  2267. return out;
  2268. }
  2269. #endif