tortls.c 73 KB

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