tortls.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  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 "compat_libevent.h"
  48. #endif
  49. #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
  50. #define TORTLS_PRIVATE
  51. #include "crypto.h"
  52. #include "tortls.h"
  53. #include "util.h"
  54. #include "torlog.h"
  55. #include "container.h"
  56. #include <string.h>
  57. /* Enable the "v2" TLS handshake.
  58. */
  59. #define V2_HANDSHAKE_SERVER
  60. #define V2_HANDSHAKE_CLIENT
  61. /* Copied from or.h */
  62. #define LEGAL_NICKNAME_CHARACTERS \
  63. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  64. /** How long do identity certificates live? (sec) */
  65. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  66. #define ADDR(tls) (((tls) && (tls)->address) ? tls->address : "peer")
  67. /* We redefine these so that we can run correctly even if the vendor gives us
  68. * a version of OpenSSL that does not match its header files. (Apple: I am
  69. * looking at you.)
  70. */
  71. #ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  72. #define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x00040000L
  73. #endif
  74. #ifndef SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  75. #define SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION 0x0010
  76. #endif
  77. /** Does the run-time openssl version look like we need
  78. * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  79. static int use_unsafe_renegotiation_op = 0;
  80. /** Does the run-time openssl version look like we need
  81. * SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION? */
  82. static int use_unsafe_renegotiation_flag = 0;
  83. /** Holds a SSL_CTX object and related state used to configure TLS
  84. * connections.
  85. */
  86. typedef struct tor_tls_context_t {
  87. int refcnt;
  88. SSL_CTX *ctx;
  89. X509 *my_cert;
  90. X509 *my_id_cert;
  91. crypto_pk_env_t *key;
  92. } tor_tls_context_t;
  93. #define TOR_TLS_MAGIC 0x71571571
  94. /** Holds a SSL object and its associated data. Members are only
  95. * accessed from within tortls.c.
  96. */
  97. struct tor_tls_t {
  98. uint32_t magic;
  99. tor_tls_context_t *context; /** A link to the context object for this tls. */
  100. SSL *ssl; /**< An OpenSSL SSL object. */
  101. int socket; /**< The underlying file descriptor for this TLS connection. */
  102. char *address; /**< An address to log when describing this connection. */
  103. enum {
  104. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  105. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
  106. TOR_TLS_ST_BUFFEREVENT
  107. } state : 3; /**< The current SSL state, depending on which operations have
  108. * completed successfully. */
  109. unsigned int isServer:1; /**< True iff this is a server-side connection */
  110. unsigned int wasV2Handshake:1; /**< True iff the original handshake for
  111. * this connection used the updated version
  112. * of the connection protocol (client sends
  113. * different cipher list, server sends only
  114. * one certificate). */
  115. /** True iff we should call negotiated_callback when we're done reading. */
  116. unsigned int got_renegotiate:1;
  117. /** Incremented every time we start the server side of a handshake. */
  118. uint8_t server_handshake_count;
  119. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
  120. * time. */
  121. /** Last values retrieved from BIO_number_read()/write(); see
  122. * tor_tls_get_n_raw_bytes() for usage.
  123. */
  124. unsigned long last_write_count;
  125. unsigned long last_read_count;
  126. /** If set, a callback to invoke whenever the client tries to renegotiate
  127. * the handshake. */
  128. void (*negotiated_callback)(tor_tls_t *tls, void *arg);
  129. /** Argument to pass to negotiated_callback. */
  130. void *callback_arg;
  131. };
  132. #ifdef V2_HANDSHAKE_CLIENT
  133. /** An array of fake SSL_CIPHER objects that we use in order to trick OpenSSL
  134. * in client mode into advertising the ciphers we want. See
  135. * rectify_client_ciphers() for details. */
  136. static SSL_CIPHER *CLIENT_CIPHER_DUMMIES = NULL;
  137. /** A stack of SSL_CIPHER objects, some real, some fake.
  138. * See rectify_client_ciphers() for details. */
  139. static STACK_OF(SSL_CIPHER) *CLIENT_CIPHER_STACK = NULL;
  140. #endif
  141. /** The ex_data index in which we store a pointer to an SSL object's
  142. * corresponding tor_tls_t object. */
  143. static int tor_tls_object_ex_data_index = -1;
  144. /** Helper: Allocate tor_tls_object_ex_data_index. */
  145. static void
  146. tor_tls_allocate_tor_tls_object_ex_data_index(void)
  147. {
  148. if (tor_tls_object_ex_data_index == -1) {
  149. tor_tls_object_ex_data_index =
  150. SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
  151. tor_assert(tor_tls_object_ex_data_index != -1);
  152. }
  153. }
  154. /** Helper: given a SSL* pointer, return the tor_tls_t object using that
  155. * pointer. */
  156. static INLINE tor_tls_t *
  157. tor_tls_get_by_ssl(const SSL *ssl)
  158. {
  159. tor_tls_t *result = SSL_get_ex_data(ssl, tor_tls_object_ex_data_index);
  160. if (result)
  161. tor_assert(result->magic == TOR_TLS_MAGIC);
  162. return result;
  163. }
  164. static void tor_tls_context_decref(tor_tls_context_t *ctx);
  165. static void tor_tls_context_incref(tor_tls_context_t *ctx);
  166. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  167. crypto_pk_env_t *rsa_sign,
  168. const char *cname,
  169. const char *cname_sign,
  170. unsigned int lifetime);
  171. static int tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  172. crypto_pk_env_t *identity,
  173. unsigned int key_lifetime);
  174. static tor_tls_context_t *tor_tls_context_new(crypto_pk_env_t *identity,
  175. unsigned int key_lifetime);
  176. /** Global TLS contexts. We keep them here because nobody else needs
  177. * to touch them. */
  178. static tor_tls_context_t *server_tls_context = NULL;
  179. static tor_tls_context_t *client_tls_context = NULL;
  180. /** True iff tor_tls_init() has been called. */
  181. static int tls_library_is_initialized = 0;
  182. /* Module-internal error codes. */
  183. #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
  184. #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
  185. #include "tortls_states.h"
  186. /** Return the symbolic name of an OpenSSL state. */
  187. static const char *
  188. ssl_state_to_string(int ssl_state)
  189. {
  190. static char buf[40];
  191. int i;
  192. for (i = 0; state_map[i].name; ++i) {
  193. if (state_map[i].state == ssl_state)
  194. return state_map[i].name;
  195. }
  196. tor_snprintf(buf, sizeof(buf), "Unknown state %d", ssl_state);
  197. return buf;
  198. }
  199. /** Write a description of the current state of <b>tls</b> into the
  200. * <b>sz</b>-byte buffer at <b>buf</b>. */
  201. void
  202. tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
  203. {
  204. const char *ssl_state;
  205. const char *tortls_state;
  206. if (PREDICT_UNLIKELY(!tls || !tls->ssl)) {
  207. strlcpy(buf, "(No SSL object)", sz);
  208. return;
  209. }
  210. ssl_state = ssl_state_to_string(tls->ssl->state);
  211. switch (tls->state) {
  212. #define CASE(st) case TOR_TLS_ST_##st: tortls_state = " in "#st ; break
  213. CASE(HANDSHAKE);
  214. CASE(OPEN);
  215. CASE(GOTCLOSE);
  216. CASE(SENTCLOSE);
  217. CASE(CLOSED);
  218. CASE(RENEGOTIATE);
  219. #undef CASE
  220. case TOR_TLS_ST_BUFFEREVENT:
  221. tortls_state = "";
  222. break;
  223. default:
  224. tortls_state = " in unknown TLS state";
  225. break;
  226. }
  227. tor_snprintf(buf, sz, "%s%s", ssl_state, tortls_state);
  228. }
  229. void
  230. tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
  231. int severity, int domain, const char *doing)
  232. {
  233. const char *state = NULL, *addr;
  234. const char *msg, *lib, *func;
  235. int st;
  236. st = (tls && tls->ssl) ? tls->ssl->state : -1;
  237. state = (st>=0)?ssl_state_to_string(st):"---";
  238. addr = tls ? tls->address : NULL;
  239. /* Some errors are known-benign, meaning they are the fault of the other
  240. * side of the connection. The caller doesn't know this, so override the
  241. * priority for those cases. */
  242. switch (ERR_GET_REASON(err)) {
  243. case SSL_R_HTTP_REQUEST:
  244. case SSL_R_HTTPS_PROXY_REQUEST:
  245. case SSL_R_RECORD_LENGTH_MISMATCH:
  246. case SSL_R_RECORD_TOO_LARGE:
  247. case SSL_R_UNKNOWN_PROTOCOL:
  248. case SSL_R_UNSUPPORTED_PROTOCOL:
  249. severity = LOG_INFO;
  250. break;
  251. default:
  252. break;
  253. }
  254. msg = (const char*)ERR_reason_error_string(err);
  255. lib = (const char*)ERR_lib_error_string(err);
  256. func = (const char*)ERR_func_error_string(err);
  257. if (!msg) msg = "(null)";
  258. if (!lib) lib = "(null)";
  259. if (!func) func = "(null)";
  260. if (doing) {
  261. log(severity, domain, "TLS error while %s%s%s: %s (in %s:%s:%s)",
  262. doing, addr?" with ":"", addr?addr:"",
  263. msg, lib, func, state);
  264. } else {
  265. log(severity, domain, "TLS error%s%s: %s (in %s:%s:%s)",
  266. addr?" with ":"", addr?addr:"",
  267. msg, lib, func, state);
  268. }
  269. }
  270. /** Log all pending tls errors at level <b>severity</b>. Use
  271. * <b>doing</b> to describe our current activities.
  272. */
  273. static void
  274. tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
  275. {
  276. unsigned long err;
  277. while ((err = ERR_get_error()) != 0) {
  278. tor_tls_log_one_error(tls, err, severity, domain, doing);
  279. }
  280. }
  281. /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
  282. * code. */
  283. static int
  284. tor_errno_to_tls_error(int e)
  285. {
  286. #if defined(MS_WINDOWS)
  287. switch (e) {
  288. case WSAECONNRESET: // most common
  289. return TOR_TLS_ERROR_CONNRESET;
  290. case WSAETIMEDOUT:
  291. return TOR_TLS_ERROR_TIMEOUT;
  292. case WSAENETUNREACH:
  293. case WSAEHOSTUNREACH:
  294. return TOR_TLS_ERROR_NO_ROUTE;
  295. case WSAECONNREFUSED:
  296. return TOR_TLS_ERROR_CONNREFUSED; // least common
  297. default:
  298. return TOR_TLS_ERROR_MISC;
  299. }
  300. #else
  301. switch (e) {
  302. case ECONNRESET: // most common
  303. return TOR_TLS_ERROR_CONNRESET;
  304. case ETIMEDOUT:
  305. return TOR_TLS_ERROR_TIMEOUT;
  306. case EHOSTUNREACH:
  307. case ENETUNREACH:
  308. return TOR_TLS_ERROR_NO_ROUTE;
  309. case ECONNREFUSED:
  310. return TOR_TLS_ERROR_CONNREFUSED; // least common
  311. default:
  312. return TOR_TLS_ERROR_MISC;
  313. }
  314. #endif
  315. }
  316. /** Given a TOR_TLS_* error code, return a string equivalent. */
  317. const char *
  318. tor_tls_err_to_string(int err)
  319. {
  320. if (err >= 0)
  321. return "[Not an error.]";
  322. switch (err) {
  323. case TOR_TLS_ERROR_MISC: return "misc error";
  324. case TOR_TLS_ERROR_IO: return "unexpected close";
  325. case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
  326. case TOR_TLS_ERROR_CONNRESET: return "connection reset";
  327. case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
  328. case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
  329. case TOR_TLS_CLOSE: return "closed";
  330. case TOR_TLS_WANTREAD: return "want to read";
  331. case TOR_TLS_WANTWRITE: return "want to write";
  332. default: return "(unknown error code)";
  333. }
  334. }
  335. #define CATCH_SYSCALL 1
  336. #define CATCH_ZERO 2
  337. /** Given a TLS object and the result of an SSL_* call, use
  338. * SSL_get_error to determine whether an error has occurred, and if so
  339. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  340. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  341. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  342. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  343. *
  344. * If an error has occurred, log it at level <b>severity</b> and describe the
  345. * current action as <b>doing</b>.
  346. */
  347. static int
  348. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  349. const char *doing, int severity, int domain)
  350. {
  351. int err = SSL_get_error(tls->ssl, r);
  352. int tor_error = TOR_TLS_ERROR_MISC;
  353. switch (err) {
  354. case SSL_ERROR_NONE:
  355. return TOR_TLS_DONE;
  356. case SSL_ERROR_WANT_READ:
  357. return TOR_TLS_WANTREAD;
  358. case SSL_ERROR_WANT_WRITE:
  359. return TOR_TLS_WANTWRITE;
  360. case SSL_ERROR_SYSCALL:
  361. if (extra&CATCH_SYSCALL)
  362. return _TOR_TLS_SYSCALL;
  363. if (r == 0) {
  364. log(severity, LD_NET, "TLS error: unexpected close while %s (%s)",
  365. doing, ssl_state_to_string(tls->ssl->state));
  366. tor_error = TOR_TLS_ERROR_IO;
  367. } else {
  368. int e = tor_socket_errno(tls->socket);
  369. log(severity, LD_NET,
  370. "TLS error: <syscall error while %s> (errno=%d: %s; state=%s)",
  371. doing, e, tor_socket_strerror(e),
  372. ssl_state_to_string(tls->ssl->state));
  373. tor_error = tor_errno_to_tls_error(e);
  374. }
  375. tls_log_errors(tls, severity, domain, doing);
  376. return tor_error;
  377. case SSL_ERROR_ZERO_RETURN:
  378. if (extra&CATCH_ZERO)
  379. return _TOR_TLS_ZERORETURN;
  380. log(severity, LD_NET, "TLS connection closed while %s in state %s",
  381. doing, ssl_state_to_string(tls->ssl->state));
  382. tls_log_errors(tls, severity, domain, doing);
  383. return TOR_TLS_CLOSE;
  384. default:
  385. tls_log_errors(tls, severity, domain, doing);
  386. return TOR_TLS_ERROR_MISC;
  387. }
  388. }
  389. /** Initialize OpenSSL, unless it has already been initialized.
  390. */
  391. static void
  392. tor_tls_init(void)
  393. {
  394. if (!tls_library_is_initialized) {
  395. long version;
  396. SSL_library_init();
  397. SSL_load_error_strings();
  398. version = SSLeay();
  399. /* OpenSSL 0.9.8l introduced SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
  400. * here, but without thinking too hard about it: it turns out that the
  401. * flag in question needed to be set at the last minute, and that it
  402. * conflicted with an existing flag number that had already been added
  403. * in the OpenSSL 1.0.0 betas. OpenSSL 0.9.8m thoughtfully replaced
  404. * the flag with an option and (it seems) broke anything that used
  405. * SSL3_FLAGS_* for the purpose. So we need to know how to do both,
  406. * and we mustn't use the SSL3_FLAGS option with anything besides
  407. * OpenSSL 0.9.8l.
  408. *
  409. * No, we can't just set flag 0x0010 everywhere. It breaks Tor with
  410. * OpenSSL 1.0.0beta3 and later. On the other hand, we might be able to
  411. * set option 0x00040000L everywhere.
  412. *
  413. * No, we can't simply detect whether the flag or the option is present
  414. * in the headers at build-time: some vendors (notably Apple) like to
  415. * leave their headers out of sync with their libraries.
  416. *
  417. * Yes, it _is_ almost as if the OpenSSL developers decided that no
  418. * program should be allowed to use renegotiation unless it first passed
  419. * a test of intelligence and determination.
  420. */
  421. if (version >= 0x009080c0L && version < 0x009080d0L) {
  422. log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8l; "
  423. "I will try SSL3_FLAGS to enable renegotation.",
  424. SSLeay_version(SSLEAY_VERSION));
  425. use_unsafe_renegotiation_flag = 1;
  426. use_unsafe_renegotiation_op = 1;
  427. } else if (version >= 0x009080d0L) {
  428. log_notice(LD_GENERAL, "OpenSSL %s looks like version 0.9.8m or later; "
  429. "I will try SSL_OP to enable renegotiation",
  430. SSLeay_version(SSLEAY_VERSION));
  431. use_unsafe_renegotiation_op = 1;
  432. } else if (version < 0x009080c0L) {
  433. log_notice(LD_GENERAL, "OpenSSL %s [%lx] looks like it's older than "
  434. "0.9.8l, but some vendors have backported 0.9.8l's "
  435. "renegotiation code to earlier versions, and some have "
  436. "backported the code from 0.9.8m or 0.9.8n. I'll set both "
  437. "SSL3_FLAGS and SSL_OP just to be safe.",
  438. SSLeay_version(SSLEAY_VERSION), version);
  439. use_unsafe_renegotiation_flag = 1;
  440. use_unsafe_renegotiation_op = 1;
  441. } else {
  442. log_info(LD_GENERAL, "OpenSSL %s has version %lx",
  443. SSLeay_version(SSLEAY_VERSION), version);
  444. }
  445. tor_tls_allocate_tor_tls_object_ex_data_index();
  446. tls_library_is_initialized = 1;
  447. }
  448. }
  449. /** Free all global TLS structures. */
  450. void
  451. tor_tls_free_all(void)
  452. {
  453. if (server_tls_context) {
  454. tor_tls_context_t *ctx = server_tls_context;
  455. server_tls_context = NULL;
  456. tor_tls_context_decref(ctx);
  457. }
  458. if (client_tls_context) {
  459. tor_tls_context_t *ctx = client_tls_context;
  460. client_tls_context = NULL;
  461. tor_tls_context_decref(ctx);
  462. }
  463. #ifdef V2_HANDSHAKE_CLIENT
  464. if (CLIENT_CIPHER_DUMMIES)
  465. tor_free(CLIENT_CIPHER_DUMMIES);
  466. if (CLIENT_CIPHER_STACK)
  467. sk_SSL_CIPHER_free(CLIENT_CIPHER_STACK);
  468. #endif
  469. }
  470. /** We need to give OpenSSL a callback to verify certificates. This is
  471. * it: We always accept peer certs and complete the handshake. We
  472. * don't validate them until later.
  473. */
  474. static int
  475. always_accept_verify_cb(int preverify_ok,
  476. X509_STORE_CTX *x509_ctx)
  477. {
  478. (void) preverify_ok;
  479. (void) x509_ctx;
  480. return 1;
  481. }
  482. /** Return a newly allocated X509 name with commonName <b>cname</b>. */
  483. static X509_NAME *
  484. tor_x509_name_new(const char *cname)
  485. {
  486. int nid;
  487. X509_NAME *name;
  488. if (!(name = X509_NAME_new()))
  489. return NULL;
  490. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  491. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  492. (unsigned char*)cname, -1, -1, 0)))
  493. goto error;
  494. return name;
  495. error:
  496. X509_NAME_free(name);
  497. return NULL;
  498. }
  499. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  500. * signed by the private key <b>rsa_sign</b>. The commonName of the
  501. * certificate will be <b>cname</b>; the commonName of the issuer will be
  502. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  503. * starting from now. Return a certificate on success, NULL on
  504. * failure.
  505. */
  506. static X509 *
  507. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  508. crypto_pk_env_t *rsa_sign,
  509. const char *cname,
  510. const char *cname_sign,
  511. unsigned int cert_lifetime)
  512. {
  513. time_t start_time, end_time;
  514. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  515. X509 *x509 = NULL;
  516. X509_NAME *name = NULL, *name_issuer=NULL;
  517. tor_tls_init();
  518. start_time = time(NULL);
  519. tor_assert(rsa);
  520. tor_assert(cname);
  521. tor_assert(rsa_sign);
  522. tor_assert(cname_sign);
  523. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  524. goto error;
  525. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  526. goto error;
  527. if (!(x509 = X509_new()))
  528. goto error;
  529. if (!(X509_set_version(x509, 2)))
  530. goto error;
  531. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  532. goto error;
  533. if (!(name = tor_x509_name_new(cname)))
  534. goto error;
  535. if (!(X509_set_subject_name(x509, name)))
  536. goto error;
  537. if (!(name_issuer = tor_x509_name_new(cname_sign)))
  538. goto error;
  539. if (!(X509_set_issuer_name(x509, name_issuer)))
  540. goto error;
  541. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  542. goto error;
  543. end_time = start_time + cert_lifetime;
  544. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  545. goto error;
  546. if (!X509_set_pubkey(x509, pkey))
  547. goto error;
  548. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  549. goto error;
  550. goto done;
  551. error:
  552. if (x509) {
  553. X509_free(x509);
  554. x509 = NULL;
  555. }
  556. done:
  557. tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
  558. if (sign_pkey)
  559. EVP_PKEY_free(sign_pkey);
  560. if (pkey)
  561. EVP_PKEY_free(pkey);
  562. if (name)
  563. X509_NAME_free(name);
  564. if (name_issuer)
  565. X509_NAME_free(name_issuer);
  566. return x509;
  567. }
  568. /** List of ciphers that servers should select from.*/
  569. #define SERVER_CIPHER_LIST \
  570. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  571. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  572. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  573. /* Note: to set up your own private testing network with link crypto
  574. * disabled, set your Tors' cipher list to
  575. * (SSL3_TXT_RSA_NULL_SHA). If you do this, you won't be able to communicate
  576. * with any of the "real" Tors, though. */
  577. #ifdef V2_HANDSHAKE_CLIENT
  578. #define CIPHER(id, name) name ":"
  579. #define XCIPHER(id, name)
  580. /** List of ciphers that clients should advertise, omitting items that
  581. * our OpenSSL doesn't know about. */
  582. static const char CLIENT_CIPHER_LIST[] =
  583. #include "./ciphers.inc"
  584. ;
  585. #undef CIPHER
  586. #undef XCIPHER
  587. /** Holds a cipher that we want to advertise, and its 2-byte ID. */
  588. typedef struct cipher_info_t { unsigned id; const char *name; } cipher_info_t;
  589. /** A list of all the ciphers that clients should advertise, including items
  590. * that OpenSSL might not know about. */
  591. static const cipher_info_t CLIENT_CIPHER_INFO_LIST[] = {
  592. #define CIPHER(id, name) { id, name },
  593. #define XCIPHER(id, name) { id, #name },
  594. #include "./ciphers.inc"
  595. #undef CIPHER
  596. #undef XCIPHER
  597. };
  598. /** The length of CLIENT_CIPHER_INFO_LIST and CLIENT_CIPHER_DUMMIES. */
  599. static const int N_CLIENT_CIPHERS =
  600. sizeof(CLIENT_CIPHER_INFO_LIST)/sizeof(CLIENT_CIPHER_INFO_LIST[0]);
  601. #endif
  602. #ifndef V2_HANDSHAKE_CLIENT
  603. #undef CLIENT_CIPHER_LIST
  604. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  605. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  606. #endif
  607. /** Remove a reference to <b>ctx</b>, and free it if it has no more
  608. * references. */
  609. static void
  610. tor_tls_context_decref(tor_tls_context_t *ctx)
  611. {
  612. tor_assert(ctx);
  613. if (--ctx->refcnt == 0) {
  614. SSL_CTX_free(ctx->ctx);
  615. X509_free(ctx->my_cert);
  616. X509_free(ctx->my_id_cert);
  617. crypto_free_pk_env(ctx->key);
  618. tor_free(ctx);
  619. }
  620. }
  621. /** Increase the reference count of <b>ctx</b>. */
  622. static void
  623. tor_tls_context_incref(tor_tls_context_t *ctx)
  624. {
  625. ++ctx->refcnt;
  626. }
  627. /** Create new global client and server TLS contexts.
  628. *
  629. * If <b>server_identity</b> is NULL, this will not generate a server
  630. * TLS context. If <b>is_public_server</b> is non-zero, this will use
  631. * the same TLS context for incoming and outgoing connections, and
  632. * ignore <b>client_identity</b>. */
  633. int
  634. tor_tls_context_init(int is_public_server,
  635. crypto_pk_env_t *client_identity,
  636. crypto_pk_env_t *server_identity,
  637. unsigned int key_lifetime)
  638. {
  639. int rv1 = 0;
  640. int rv2 = 0;
  641. if (is_public_server) {
  642. tor_tls_context_t *new_ctx;
  643. tor_tls_context_t *old_ctx;
  644. tor_assert(server_identity != NULL);
  645. rv1 = tor_tls_context_init_one(&server_tls_context,
  646. server_identity,
  647. key_lifetime);
  648. if (rv1 >= 0) {
  649. new_ctx = server_tls_context;
  650. tor_tls_context_incref(new_ctx);
  651. old_ctx = client_tls_context;
  652. client_tls_context = new_ctx;
  653. if (old_ctx != NULL) {
  654. tor_tls_context_decref(old_ctx);
  655. }
  656. }
  657. } else {
  658. if (server_identity != NULL) {
  659. rv1 = tor_tls_context_init_one(&server_tls_context,
  660. server_identity,
  661. key_lifetime);
  662. } else {
  663. tor_tls_context_t *old_ctx = server_tls_context;
  664. server_tls_context = NULL;
  665. if (old_ctx != NULL) {
  666. tor_tls_context_decref(old_ctx);
  667. }
  668. }
  669. rv2 = tor_tls_context_init_one(&client_tls_context,
  670. client_identity,
  671. key_lifetime);
  672. }
  673. return MIN(rv1, rv2);
  674. }
  675. /** Create a new global TLS context.
  676. *
  677. * You can call this function multiple times. Each time you call it,
  678. * it generates new certificates; all new connections will use
  679. * the new SSL context.
  680. */
  681. static int
  682. tor_tls_context_init_one(tor_tls_context_t **ppcontext,
  683. crypto_pk_env_t *identity,
  684. unsigned int key_lifetime)
  685. {
  686. tor_tls_context_t *new_ctx = tor_tls_context_new(identity,
  687. key_lifetime);
  688. tor_tls_context_t *old_ctx = *ppcontext;
  689. if (new_ctx != NULL) {
  690. *ppcontext = new_ctx;
  691. /* Free the old context if one existed. */
  692. if (old_ctx != NULL) {
  693. /* This is safe even if there are open connections: we reference-
  694. * count tor_tls_context_t objects. */
  695. tor_tls_context_decref(old_ctx);
  696. }
  697. }
  698. return ((new_ctx != NULL) ? 0 : -1);
  699. }
  700. /** Create a new TLS context for use with Tor TLS handshakes.
  701. * <b>identity</b> should be set to the identity key used to sign the
  702. * certificate.
  703. */
  704. static tor_tls_context_t *
  705. tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
  706. {
  707. crypto_pk_env_t *rsa = NULL;
  708. EVP_PKEY *pkey = NULL;
  709. tor_tls_context_t *result = NULL;
  710. X509 *cert = NULL, *idcert = NULL;
  711. char *nickname = NULL, *nn2 = NULL;
  712. tor_tls_init();
  713. nickname = crypto_random_hostname(8, 20, "www.", ".net");
  714. nn2 = crypto_random_hostname(8, 20, "www.", ".net");
  715. /* Generate short-term RSA key. */
  716. if (!(rsa = crypto_new_pk_env()))
  717. goto error;
  718. if (crypto_pk_generate_key(rsa)<0)
  719. goto error;
  720. /* Create certificate signed by identity key. */
  721. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  722. key_lifetime);
  723. /* Create self-signed certificate for identity key. */
  724. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  725. IDENTITY_CERT_LIFETIME);
  726. if (!cert || !idcert) {
  727. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  728. goto error;
  729. }
  730. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  731. result->refcnt = 1;
  732. result->my_cert = X509_dup(cert);
  733. result->my_id_cert = X509_dup(idcert);
  734. result->key = crypto_pk_dup_key(rsa);
  735. #ifdef EVERYONE_HAS_AES
  736. /* Tell OpenSSL to only use TLS1 */
  737. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  738. goto error;
  739. #else
  740. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  741. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  742. goto error;
  743. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  744. #endif
  745. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  746. #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  747. SSL_CTX_set_options(result->ctx,
  748. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  749. #endif
  750. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  751. * as authenticating any earlier-received data.
  752. */
  753. if (use_unsafe_renegotiation_op) {
  754. SSL_CTX_set_options(result->ctx,
  755. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  756. }
  757. /* Don't actually allow compression; it uses ram and time, but the data
  758. * we transmit is all encrypted anyway. */
  759. if (result->ctx->comp_methods)
  760. result->ctx->comp_methods = NULL;
  761. #ifdef SSL_MODE_RELEASE_BUFFERS
  762. SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS);
  763. #endif
  764. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  765. goto error;
  766. X509_free(cert); /* We just added a reference to cert. */
  767. cert=NULL;
  768. if (idcert) {
  769. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  770. tor_assert(s);
  771. X509_STORE_add_cert(s, idcert);
  772. X509_free(idcert); /* The context now owns the reference to idcert */
  773. idcert = NULL;
  774. }
  775. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  776. tor_assert(rsa);
  777. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  778. goto error;
  779. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  780. goto error;
  781. EVP_PKEY_free(pkey);
  782. pkey = NULL;
  783. if (!SSL_CTX_check_private_key(result->ctx))
  784. goto error;
  785. {
  786. crypto_dh_env_t *dh = crypto_dh_new(DH_TYPE_TLS);
  787. tor_assert(dh);
  788. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  789. crypto_dh_free(dh);
  790. }
  791. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  792. always_accept_verify_cb);
  793. /* let us realloc bufs that we're writing from */
  794. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  795. if (rsa)
  796. crypto_free_pk_env(rsa);
  797. tor_free(nickname);
  798. tor_free(nn2);
  799. return result;
  800. error:
  801. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating TLS context");
  802. tor_free(nickname);
  803. tor_free(nn2);
  804. if (pkey)
  805. EVP_PKEY_free(pkey);
  806. if (rsa)
  807. crypto_free_pk_env(rsa);
  808. if (result)
  809. tor_tls_context_decref(result);
  810. if (cert)
  811. X509_free(cert);
  812. if (idcert)
  813. X509_free(idcert);
  814. return NULL;
  815. }
  816. #ifdef V2_HANDSHAKE_SERVER
  817. /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
  818. * a list that indicates that the client knows how to do the v2 TLS connection
  819. * handshake. */
  820. static int
  821. tor_tls_client_is_using_v2_ciphers(const SSL *ssl, const char *address)
  822. {
  823. int i;
  824. SSL_SESSION *session;
  825. /* If we reached this point, we just got a client hello. See if there is
  826. * a cipher list. */
  827. if (!(session = SSL_get_session((SSL *)ssl))) {
  828. log_info(LD_NET, "No session on TLS?");
  829. return 0;
  830. }
  831. if (!session->ciphers) {
  832. log_info(LD_NET, "No ciphers on session");
  833. return 0;
  834. }
  835. /* Now we need to see if there are any ciphers whose presence means we're
  836. * dealing with an updated Tor. */
  837. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  838. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  839. const char *ciphername = SSL_CIPHER_get_name(cipher);
  840. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  841. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  842. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  843. strcmp(ciphername, "(NONE)")) {
  844. log_debug(LD_NET, "Got a non-version-1 cipher called '%s'", ciphername);
  845. // return 1;
  846. goto dump_list;
  847. }
  848. }
  849. return 0;
  850. dump_list:
  851. {
  852. smartlist_t *elts = smartlist_create();
  853. char *s;
  854. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  855. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  856. const char *ciphername = SSL_CIPHER_get_name(cipher);
  857. smartlist_add(elts, (char*)ciphername);
  858. }
  859. s = smartlist_join_strings(elts, ":", 0, NULL);
  860. log_debug(LD_NET, "Got a non-version-1 cipher list from %s. It is: '%s'",
  861. address, s);
  862. tor_free(s);
  863. smartlist_free(elts);
  864. }
  865. return 1;
  866. }
  867. static void
  868. tor_tls_debug_state_callback(const SSL *ssl, int type, int val)
  869. {
  870. log_debug(LD_HANDSHAKE, "SSL %p is now in state %s [type=%d,val=%d].",
  871. ssl, ssl_state_to_string(ssl->state), type, val);
  872. }
  873. /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
  874. * changes state. We use this:
  875. * <ul><li>To alter the state of the handshake partway through, so we
  876. * do not send or request extra certificates in v2 handshakes.</li>
  877. * <li>To detect renegotiation</li></ul>
  878. */
  879. static void
  880. tor_tls_server_info_callback(const SSL *ssl, int type, int val)
  881. {
  882. tor_tls_t *tls;
  883. (void) val;
  884. tor_tls_debug_state_callback(ssl, type, val);
  885. if (type != SSL_CB_ACCEPT_LOOP)
  886. return;
  887. if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
  888. return;
  889. tls = tor_tls_get_by_ssl(ssl);
  890. if (tls) {
  891. /* Check whether we're watching for renegotiates. If so, this is one! */
  892. if (tls->negotiated_callback)
  893. tls->got_renegotiate = 1;
  894. if (tls->server_handshake_count < 127) /*avoid any overflow possibility*/
  895. ++tls->server_handshake_count;
  896. } else {
  897. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  898. return;
  899. }
  900. /* Now check the cipher list. */
  901. if (tor_tls_client_is_using_v2_ciphers(ssl, ADDR(tls))) {
  902. /*XXXX_TLS keep this from happening more than once! */
  903. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  904. * Let's hope openssl doesn't notice! */
  905. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  906. SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
  907. /* Don't send a hello request. */
  908. SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
  909. if (tls) {
  910. tls->wasV2Handshake = 1;
  911. #ifdef USE_BUFFEREVENTS
  912. if (use_unsafe_renegotiation_flag)
  913. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  914. #endif
  915. } else {
  916. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  917. }
  918. }
  919. }
  920. #endif
  921. /** Replace *<b>ciphers</b> with a new list of SSL ciphersuites: specifically,
  922. * a list designed to mimic a common web browser. Some of the ciphers in the
  923. * list won't actually be implemented by OpenSSL: that's okay so long as the
  924. * server doesn't select them, and the server won't select anything besides
  925. * what's in SERVER_CIPHER_LIST.
  926. *
  927. * [If the server <b>does</b> select a bogus cipher, we won't crash or
  928. * anything; we'll just fail later when we try to look up the cipher in
  929. * ssl->cipher_list_by_id.]
  930. */
  931. static void
  932. rectify_client_ciphers(STACK_OF(SSL_CIPHER) **ciphers)
  933. {
  934. #ifdef V2_HANDSHAKE_CLIENT
  935. if (PREDICT_UNLIKELY(!CLIENT_CIPHER_STACK)) {
  936. /* We need to set CLIENT_CIPHER_STACK to an array of the ciphers
  937. * we want.*/
  938. int i = 0, j = 0;
  939. /* First, create a dummy SSL_CIPHER for every cipher. */
  940. CLIENT_CIPHER_DUMMIES =
  941. tor_malloc_zero(sizeof(SSL_CIPHER)*N_CLIENT_CIPHERS);
  942. for (i=0; i < N_CLIENT_CIPHERS; ++i) {
  943. CLIENT_CIPHER_DUMMIES[i].valid = 1;
  944. CLIENT_CIPHER_DUMMIES[i].id = CLIENT_CIPHER_INFO_LIST[i].id | (3<<24);
  945. CLIENT_CIPHER_DUMMIES[i].name = CLIENT_CIPHER_INFO_LIST[i].name;
  946. }
  947. CLIENT_CIPHER_STACK = sk_SSL_CIPHER_new_null();
  948. tor_assert(CLIENT_CIPHER_STACK);
  949. log_debug(LD_NET, "List was: %s", CLIENT_CIPHER_LIST);
  950. for (j = 0; j < sk_SSL_CIPHER_num(*ciphers); ++j) {
  951. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(*ciphers, j);
  952. log_debug(LD_NET, "Cipher %d: %lx %s", j, cipher->id, cipher->name);
  953. }
  954. /* Then copy as many ciphers as we can from the good list, inserting
  955. * dummies as needed. */
  956. j=0;
  957. for (i = 0; i < N_CLIENT_CIPHERS; ) {
  958. SSL_CIPHER *cipher = NULL;
  959. if (j < sk_SSL_CIPHER_num(*ciphers))
  960. cipher = sk_SSL_CIPHER_value(*ciphers, j);
  961. if (cipher && ((cipher->id >> 24) & 0xff) != 3) {
  962. log_debug(LD_NET, "Skipping v2 cipher %s", cipher->name);
  963. ++j;
  964. } else if (cipher &&
  965. (cipher->id & 0xffff) == CLIENT_CIPHER_INFO_LIST[i].id) {
  966. log_debug(LD_NET, "Found cipher %s", cipher->name);
  967. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, cipher);
  968. ++j;
  969. ++i;
  970. } else {
  971. log_debug(LD_NET, "Inserting fake %s", CLIENT_CIPHER_DUMMIES[i].name);
  972. sk_SSL_CIPHER_push(CLIENT_CIPHER_STACK, &CLIENT_CIPHER_DUMMIES[i]);
  973. ++i;
  974. }
  975. }
  976. }
  977. sk_SSL_CIPHER_free(*ciphers);
  978. *ciphers = sk_SSL_CIPHER_dup(CLIENT_CIPHER_STACK);
  979. tor_assert(*ciphers);
  980. #else
  981. (void)ciphers;
  982. #endif
  983. }
  984. /** Create a new TLS object from a file descriptor, and a flag to
  985. * determine whether it is functioning as a server.
  986. */
  987. tor_tls_t *
  988. tor_tls_new(int sock, int isServer)
  989. {
  990. BIO *bio = NULL;
  991. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  992. tor_tls_context_t *context = isServer ? server_tls_context :
  993. client_tls_context;
  994. result->magic = TOR_TLS_MAGIC;
  995. tor_assert(context); /* make sure somebody made it first */
  996. if (!(result->ssl = SSL_new(context->ctx))) {
  997. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating SSL object");
  998. tor_free(result);
  999. return NULL;
  1000. }
  1001. #ifdef SSL_set_tlsext_host_name
  1002. /* Browsers use the TLS hostname extension, so we should too. */
  1003. if (!isServer) {
  1004. char *fake_hostname = crypto_random_hostname(4,25, "www.",".com");
  1005. SSL_set_tlsext_host_name(result->ssl, fake_hostname);
  1006. tor_free(fake_hostname);
  1007. }
  1008. #endif
  1009. if (!SSL_set_cipher_list(result->ssl,
  1010. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  1011. tls_log_errors(NULL, LOG_WARN, LD_NET, "setting ciphers");
  1012. #ifdef SSL_set_tlsext_host_name
  1013. SSL_set_tlsext_host_name(result->ssl, NULL);
  1014. #endif
  1015. SSL_free(result->ssl);
  1016. tor_free(result);
  1017. return NULL;
  1018. }
  1019. if (!isServer)
  1020. rectify_client_ciphers(&result->ssl->cipher_list);
  1021. result->socket = sock;
  1022. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1023. if (! bio) {
  1024. tls_log_errors(NULL, LOG_WARN, LD_NET, "opening BIO");
  1025. #ifdef SSL_set_tlsext_host_name
  1026. SSL_set_tlsext_host_name(result->ssl, NULL);
  1027. #endif
  1028. SSL_free(result->ssl);
  1029. tor_free(result);
  1030. return NULL;
  1031. }
  1032. {
  1033. int set_worked =
  1034. SSL_set_ex_data(result->ssl, tor_tls_object_ex_data_index, result);
  1035. if (!set_worked) {
  1036. log_warn(LD_BUG,
  1037. "Couldn't set the tls for an SSL*; connection will fail");
  1038. }
  1039. }
  1040. SSL_set_bio(result->ssl, bio, bio);
  1041. tor_tls_context_incref(context);
  1042. result->context = context;
  1043. result->state = TOR_TLS_ST_HANDSHAKE;
  1044. result->isServer = isServer;
  1045. result->wantwrite_n = 0;
  1046. result->last_write_count = BIO_number_written(bio);
  1047. result->last_read_count = BIO_number_read(bio);
  1048. if (result->last_write_count || result->last_read_count) {
  1049. log_warn(LD_NET, "Newly created BIO has read count %lu, write count %lu",
  1050. result->last_read_count, result->last_write_count);
  1051. }
  1052. #ifdef V2_HANDSHAKE_SERVER
  1053. if (isServer) {
  1054. SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
  1055. } else
  1056. #endif
  1057. {
  1058. SSL_set_info_callback(result->ssl, tor_tls_debug_state_callback);
  1059. }
  1060. /* Not expected to get called. */
  1061. tls_log_errors(NULL, LOG_WARN, LD_NET, "creating tor_tls_t object");
  1062. return result;
  1063. }
  1064. /** Make future log messages about <b>tls</b> display the address
  1065. * <b>address</b>.
  1066. */
  1067. void
  1068. tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
  1069. {
  1070. tor_assert(tls);
  1071. tor_free(tls->address);
  1072. tls->address = tor_strdup(address);
  1073. }
  1074. /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
  1075. * next gets a client-side renegotiate in the middle of a read. Do not
  1076. * invoke this function until <em>after</em> initial handshaking is done!
  1077. */
  1078. void
  1079. tor_tls_set_renegotiate_callback(tor_tls_t *tls,
  1080. void (*cb)(tor_tls_t *, void *arg),
  1081. void *arg)
  1082. {
  1083. tls->negotiated_callback = cb;
  1084. tls->callback_arg = arg;
  1085. tls->got_renegotiate = 0;
  1086. #ifdef V2_HANDSHAKE_SERVER
  1087. if (cb) {
  1088. SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
  1089. } else {
  1090. SSL_set_info_callback(tls->ssl, tor_tls_debug_state_callback);
  1091. }
  1092. #endif
  1093. }
  1094. /** If this version of openssl requires it, turn on renegotiation on
  1095. * <b>tls</b>.
  1096. */
  1097. void
  1098. tor_tls_unblock_renegotiation(tor_tls_t *tls)
  1099. {
  1100. /* Yes, we know what we are doing here. No, we do not treat a renegotiation
  1101. * as authenticating any earlier-received data. */
  1102. if (use_unsafe_renegotiation_flag) {
  1103. tls->ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1104. }
  1105. if (use_unsafe_renegotiation_op) {
  1106. SSL_set_options(tls->ssl,
  1107. SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
  1108. }
  1109. }
  1110. /** If this version of openssl supports it, turn off renegotiation on
  1111. * <b>tls</b>. (Our protocol never requires this for security, but it's nice
  1112. * to use belt-and-suspenders here.)
  1113. */
  1114. void
  1115. tor_tls_block_renegotiation(tor_tls_t *tls)
  1116. {
  1117. tls->ssl->s3->flags &= ~SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
  1118. }
  1119. void
  1120. tor_tls_assert_renegotiation_unblocked(tor_tls_t *tls)
  1121. {
  1122. if (use_unsafe_renegotiation_flag) {
  1123. tor_assert(0 != (tls->ssl->s3->flags &
  1124. SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1125. }
  1126. if (use_unsafe_renegotiation_op) {
  1127. long options = SSL_get_options(tls->ssl);
  1128. tor_assert(0 != (options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION));
  1129. }
  1130. }
  1131. /** Return whether this tls initiated the connect (client) or
  1132. * received it (server). */
  1133. int
  1134. tor_tls_is_server(tor_tls_t *tls)
  1135. {
  1136. tor_assert(tls);
  1137. return tls->isServer;
  1138. }
  1139. /** Release resources associated with a TLS object. Does not close the
  1140. * underlying file descriptor.
  1141. */
  1142. void
  1143. tor_tls_free(tor_tls_t *tls)
  1144. {
  1145. if (!tls)
  1146. return;
  1147. tor_assert(tls->ssl);
  1148. #ifdef SSL_set_tlsext_host_name
  1149. SSL_set_tlsext_host_name(tls->ssl, NULL);
  1150. #endif
  1151. SSL_free(tls->ssl);
  1152. tls->ssl = NULL;
  1153. tls->negotiated_callback = NULL;
  1154. if (tls->context)
  1155. tor_tls_context_decref(tls->context);
  1156. tor_free(tls->address);
  1157. tls->magic = 0x99999999;
  1158. tor_free(tls);
  1159. }
  1160. /** Underlying function for TLS reading. Reads up to <b>len</b>
  1161. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  1162. * number of characters read. On failure, returns TOR_TLS_ERROR,
  1163. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1164. */
  1165. int
  1166. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  1167. {
  1168. int r, err;
  1169. tor_assert(tls);
  1170. tor_assert(tls->ssl);
  1171. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1172. tor_assert(len<INT_MAX);
  1173. r = SSL_read(tls->ssl, cp, (int)len);
  1174. if (r > 0) {
  1175. #ifdef V2_HANDSHAKE_SERVER
  1176. if (tls->got_renegotiate) {
  1177. /* Renegotiation happened! */
  1178. log_info(LD_NET, "Got a TLS renegotiation from %s", ADDR(tls));
  1179. if (tls->negotiated_callback)
  1180. tls->negotiated_callback(tls, tls->callback_arg);
  1181. tls->got_renegotiate = 0;
  1182. }
  1183. #endif
  1184. return r;
  1185. }
  1186. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG, LD_NET);
  1187. if (err == _TOR_TLS_ZERORETURN || err == TOR_TLS_CLOSE) {
  1188. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  1189. tls->state = TOR_TLS_ST_CLOSED;
  1190. return TOR_TLS_CLOSE;
  1191. } else {
  1192. tor_assert(err != TOR_TLS_DONE);
  1193. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  1194. return err;
  1195. }
  1196. }
  1197. /** Underlying function for TLS writing. Write up to <b>n</b>
  1198. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  1199. * number of characters written. On failure, returns TOR_TLS_ERROR,
  1200. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  1201. */
  1202. int
  1203. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  1204. {
  1205. int r, err;
  1206. tor_assert(tls);
  1207. tor_assert(tls->ssl);
  1208. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  1209. tor_assert(n < INT_MAX);
  1210. if (n == 0)
  1211. return 0;
  1212. if (tls->wantwrite_n) {
  1213. /* if WANTWRITE last time, we must use the _same_ n as before */
  1214. tor_assert(n >= tls->wantwrite_n);
  1215. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  1216. (int)n, (int)tls->wantwrite_n);
  1217. n = tls->wantwrite_n;
  1218. tls->wantwrite_n = 0;
  1219. }
  1220. r = SSL_write(tls->ssl, cp, (int)n);
  1221. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO, LD_NET);
  1222. if (err == TOR_TLS_DONE) {
  1223. return r;
  1224. }
  1225. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  1226. tls->wantwrite_n = n;
  1227. }
  1228. return err;
  1229. }
  1230. /** Perform initial handshake on <b>tls</b>. When finished, returns
  1231. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1232. * or TOR_TLS_WANTWRITE.
  1233. */
  1234. int
  1235. tor_tls_handshake(tor_tls_t *tls)
  1236. {
  1237. int r;
  1238. int oldstate;
  1239. tor_assert(tls);
  1240. tor_assert(tls->ssl);
  1241. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  1242. check_no_tls_errors();
  1243. oldstate = tls->ssl->state;
  1244. if (tls->isServer) {
  1245. log_debug(LD_HANDSHAKE, "About to call SSL_accept on %p (%s)", tls,
  1246. ssl_state_to_string(tls->ssl->state));
  1247. r = SSL_accept(tls->ssl);
  1248. } else {
  1249. log_debug(LD_HANDSHAKE, "About to call SSL_connect on %p (%s)", tls,
  1250. ssl_state_to_string(tls->ssl->state));
  1251. r = SSL_connect(tls->ssl);
  1252. }
  1253. if (oldstate != tls->ssl->state)
  1254. log_debug(LD_HANDSHAKE, "After call, %p was in state %s",
  1255. tls, ssl_state_to_string(tls->ssl->state));
  1256. /* We need to call this here and not earlier, since OpenSSL has a penchant
  1257. * for clearing its flags when you say accept or connect. */
  1258. tor_tls_unblock_renegotiation(tls);
  1259. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO, LD_HANDSHAKE);
  1260. if (ERR_peek_error() != 0) {
  1261. tls_log_errors(tls, tls->isServer ? LOG_INFO : LOG_WARN, LD_HANDSHAKE,
  1262. "handshaking");
  1263. return TOR_TLS_ERROR_MISC;
  1264. }
  1265. if (r == TOR_TLS_DONE) {
  1266. tls->state = TOR_TLS_ST_OPEN;
  1267. return tor_tls_finish_handshake(tls);
  1268. }
  1269. return r;
  1270. }
  1271. /** Perform the final part of the intial TLS handshake on <b>tls</b>. This
  1272. * should be called for the first handshake only: it determines whether the v1
  1273. * or the v2 handshake was used, and adjusts things for the renegotiation
  1274. * handshake as appropriate.
  1275. *
  1276. * tor_tls_handshake() calls this on its own; you only need to call this if
  1277. * bufferevent is doing the handshake for you.
  1278. */
  1279. int
  1280. tor_tls_finish_handshake(tor_tls_t *tls)
  1281. {
  1282. int r = TOR_TLS_DONE;
  1283. if (tls->isServer) {
  1284. SSL_set_info_callback(tls->ssl, NULL);
  1285. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, always_accept_verify_cb);
  1286. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  1287. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  1288. #ifdef V2_HANDSHAKE_SERVER
  1289. if (tor_tls_client_is_using_v2_ciphers(tls->ssl, ADDR(tls))) {
  1290. /* This check is redundant, but back when we did it in the callback,
  1291. * we might have not been able to look up the tor_tls_t if the code
  1292. * was buggy. Fixing that. */
  1293. if (!tls->wasV2Handshake) {
  1294. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  1295. " get set. Fixing that.");
  1296. }
  1297. tls->wasV2Handshake = 1;
  1298. log_debug(LD_HANDSHAKE, "Completed V2 TLS handshake with client; waiting"
  1299. " for renegotiation.");
  1300. } else {
  1301. tls->wasV2Handshake = 0;
  1302. }
  1303. #endif
  1304. } else {
  1305. #ifdef V2_HANDSHAKE_CLIENT
  1306. /* If we got no ID cert, we're a v2 handshake. */
  1307. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  1308. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  1309. int n_certs = sk_X509_num(chain);
  1310. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0))) {
  1311. log_debug(LD_HANDSHAKE, "Server sent back multiple certificates; it "
  1312. "looks like a v1 handshake on %p", tls);
  1313. tls->wasV2Handshake = 0;
  1314. } else {
  1315. log_debug(LD_HANDSHAKE,
  1316. "Server sent back a single certificate; looks like "
  1317. "a v2 handshake on %p.", tls);
  1318. tls->wasV2Handshake = 1;
  1319. }
  1320. if (cert)
  1321. X509_free(cert);
  1322. #endif
  1323. if (SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST) == 0) {
  1324. tls_log_errors(NULL, LOG_WARN, LD_HANDSHAKE, "re-setting ciphers");
  1325. r = TOR_TLS_ERROR_MISC;
  1326. }
  1327. }
  1328. return r;
  1329. }
  1330. #ifdef USE_BUFFEREVENTS
  1331. /** Put <b>tls</b>, which must be a client connection, into renegotiation
  1332. * mode. */
  1333. int
  1334. tor_tls_start_renegotiating(tor_tls_t *tls)
  1335. {
  1336. int r = SSL_renegotiate(tls->ssl);
  1337. if (r <= 0) {
  1338. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1339. LD_HANDSHAKE);
  1340. }
  1341. return 0;
  1342. }
  1343. #endif
  1344. /** Client only: Renegotiate a TLS session. When finished, returns
  1345. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  1346. * TOR_TLS_WANTWRITE.
  1347. */
  1348. int
  1349. tor_tls_renegotiate(tor_tls_t *tls)
  1350. {
  1351. int r;
  1352. tor_assert(tls);
  1353. /* We could do server-initiated renegotiation too, but that would be tricky.
  1354. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  1355. tor_assert(!tls->isServer);
  1356. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  1357. int r = SSL_renegotiate(tls->ssl);
  1358. if (r <= 0) {
  1359. return tor_tls_get_error(tls, r, 0, "renegotiating", LOG_WARN,
  1360. LD_HANDSHAKE);
  1361. }
  1362. tls->state = TOR_TLS_ST_RENEGOTIATE;
  1363. }
  1364. r = SSL_do_handshake(tls->ssl);
  1365. if (r == 1) {
  1366. tls->state = TOR_TLS_ST_OPEN;
  1367. return TOR_TLS_DONE;
  1368. } else
  1369. return tor_tls_get_error(tls, r, 0, "renegotiating handshake", LOG_INFO,
  1370. LD_HANDSHAKE);
  1371. }
  1372. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  1373. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  1374. * or TOR_TLS_WANTWRITE.
  1375. */
  1376. int
  1377. tor_tls_shutdown(tor_tls_t *tls)
  1378. {
  1379. int r, err;
  1380. char buf[128];
  1381. tor_assert(tls);
  1382. tor_assert(tls->ssl);
  1383. while (1) {
  1384. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  1385. /* If we've already called shutdown once to send a close message,
  1386. * we read until the other side has closed too.
  1387. */
  1388. do {
  1389. r = SSL_read(tls->ssl, buf, 128);
  1390. } while (r>0);
  1391. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  1392. LOG_INFO, LD_NET);
  1393. if (err == _TOR_TLS_ZERORETURN) {
  1394. tls->state = TOR_TLS_ST_GOTCLOSE;
  1395. /* fall through... */
  1396. } else {
  1397. return err;
  1398. }
  1399. }
  1400. r = SSL_shutdown(tls->ssl);
  1401. if (r == 1) {
  1402. /* If shutdown returns 1, the connection is entirely closed. */
  1403. tls->state = TOR_TLS_ST_CLOSED;
  1404. return TOR_TLS_DONE;
  1405. }
  1406. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  1407. LOG_INFO, LD_NET);
  1408. if (err == _TOR_TLS_SYSCALL) {
  1409. /* The underlying TCP connection closed while we were shutting down. */
  1410. tls->state = TOR_TLS_ST_CLOSED;
  1411. return TOR_TLS_DONE;
  1412. } else if (err == _TOR_TLS_ZERORETURN) {
  1413. /* The TLS connection says that it sent a shutdown record, but
  1414. * isn't done shutting down yet. Make sure that this hasn't
  1415. * happened before, then go back to the start of the function
  1416. * and try to read.
  1417. */
  1418. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  1419. tls->state == TOR_TLS_ST_SENTCLOSE) {
  1420. log(LOG_WARN, LD_NET,
  1421. "TLS returned \"half-closed\" value while already half-closed");
  1422. return TOR_TLS_ERROR_MISC;
  1423. }
  1424. tls->state = TOR_TLS_ST_SENTCLOSE;
  1425. /* fall through ... */
  1426. } else {
  1427. return err;
  1428. }
  1429. } /* end loop */
  1430. }
  1431. /** Return true iff this TLS connection is authenticated.
  1432. */
  1433. int
  1434. tor_tls_peer_has_cert(tor_tls_t *tls)
  1435. {
  1436. X509 *cert;
  1437. cert = SSL_get_peer_certificate(tls->ssl);
  1438. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "getting peer certificate");
  1439. if (!cert)
  1440. return 0;
  1441. X509_free(cert);
  1442. return 1;
  1443. }
  1444. /** Warn that a certificate lifetime extends through a certain range. */
  1445. static void
  1446. log_cert_lifetime(X509 *cert, const char *problem)
  1447. {
  1448. BIO *bio = NULL;
  1449. BUF_MEM *buf;
  1450. char *s1=NULL, *s2=NULL;
  1451. char mytime[33];
  1452. time_t now = time(NULL);
  1453. struct tm tm;
  1454. if (problem)
  1455. log_warn(LD_GENERAL,
  1456. "Certificate %s: is your system clock set incorrectly?",
  1457. problem);
  1458. if (!(bio = BIO_new(BIO_s_mem()))) {
  1459. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1460. }
  1461. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1462. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1463. goto end;
  1464. }
  1465. BIO_get_mem_ptr(bio, &buf);
  1466. s1 = tor_strndup(buf->data, buf->length);
  1467. (void)BIO_reset(bio);
  1468. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1469. tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
  1470. goto end;
  1471. }
  1472. BIO_get_mem_ptr(bio, &buf);
  1473. s2 = tor_strndup(buf->data, buf->length);
  1474. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1475. log_warn(LD_GENERAL,
  1476. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1477. s1,s2,mytime);
  1478. end:
  1479. /* Not expected to get invoked */
  1480. tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
  1481. if (bio)
  1482. BIO_free(bio);
  1483. tor_free(s1);
  1484. tor_free(s2);
  1485. }
  1486. /** Helper function: try to extract a link certificate and an identity
  1487. * certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
  1488. * *<b>id_cert_out</b> respectively. Log all messages at level
  1489. * <b>severity</b>.
  1490. *
  1491. * Note that a reference is added to cert_out, so it needs to be
  1492. * freed. id_cert_out doesn't. */
  1493. static void
  1494. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1495. X509 **cert_out, X509 **id_cert_out)
  1496. {
  1497. X509 *cert = NULL, *id_cert = NULL;
  1498. STACK_OF(X509) *chain = NULL;
  1499. int num_in_chain, i;
  1500. *cert_out = *id_cert_out = NULL;
  1501. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1502. return;
  1503. *cert_out = cert;
  1504. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1505. return;
  1506. num_in_chain = sk_X509_num(chain);
  1507. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1508. * 2 means we're connecting (client-side), and it's both the link
  1509. * cert and the id_cert.
  1510. */
  1511. if (num_in_chain < 1) {
  1512. log_fn(severity,LD_PROTOCOL,
  1513. "Unexpected number of certificates in chain (%d)",
  1514. num_in_chain);
  1515. return;
  1516. }
  1517. for (i=0; i<num_in_chain; ++i) {
  1518. id_cert = sk_X509_value(chain, i);
  1519. if (X509_cmp(id_cert, cert) != 0)
  1520. break;
  1521. }
  1522. *id_cert_out = id_cert;
  1523. }
  1524. /** If the provided tls connection is authenticated and has a
  1525. * certificate chain that is currently valid and signed, then set
  1526. * *<b>identity_key</b> to the identity certificate's key and return
  1527. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1528. */
  1529. int
  1530. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1531. {
  1532. X509 *cert = NULL, *id_cert = NULL;
  1533. EVP_PKEY *id_pkey = NULL;
  1534. RSA *rsa;
  1535. int r = -1;
  1536. *identity_key = NULL;
  1537. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1538. if (!cert)
  1539. goto done;
  1540. if (!id_cert) {
  1541. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1542. goto done;
  1543. }
  1544. tls_log_errors(tls, severity, LD_HANDSHAKE, "before verifying certificate");
  1545. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1546. X509_verify(cert, id_pkey) <= 0) {
  1547. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1548. tls_log_errors(tls, severity, LD_HANDSHAKE, "verifying certificate");
  1549. goto done;
  1550. }
  1551. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1552. if (!rsa)
  1553. goto done;
  1554. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1555. r = 0;
  1556. done:
  1557. if (cert)
  1558. X509_free(cert);
  1559. if (id_pkey)
  1560. EVP_PKEY_free(id_pkey);
  1561. /* This should never get invoked, but let's make sure in case OpenSSL
  1562. * acts unexpectedly. */
  1563. tls_log_errors(tls, LOG_WARN, LD_HANDSHAKE, "finishing tor_tls_verify");
  1564. return r;
  1565. }
  1566. /** Check whether the certificate set on the connection <b>tls</b> is
  1567. * expired or not-yet-valid, give or take <b>tolerance</b>
  1568. * seconds. Return 0 for valid, -1 for failure.
  1569. *
  1570. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1571. */
  1572. int
  1573. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  1574. {
  1575. time_t now, t;
  1576. X509 *cert;
  1577. int r = -1;
  1578. now = time(NULL);
  1579. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1580. goto done;
  1581. t = now + tolerance;
  1582. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1583. log_cert_lifetime(cert, "not yet valid");
  1584. goto done;
  1585. }
  1586. t = now - tolerance;
  1587. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1588. log_cert_lifetime(cert, "already expired");
  1589. goto done;
  1590. }
  1591. r = 0;
  1592. done:
  1593. if (cert)
  1594. X509_free(cert);
  1595. /* Not expected to get invoked */
  1596. tls_log_errors(tls, LOG_WARN, LD_NET, "checking certificate lifetime");
  1597. return r;
  1598. }
  1599. /** Return the number of bytes available for reading from <b>tls</b>.
  1600. */
  1601. int
  1602. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1603. {
  1604. tor_assert(tls);
  1605. return SSL_pending(tls->ssl);
  1606. }
  1607. /** If <b>tls</b> requires that the next write be of a particular size,
  1608. * return that size. Otherwise, return 0. */
  1609. size_t
  1610. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1611. {
  1612. return tls->wantwrite_n;
  1613. }
  1614. /** Sets n_read and n_written to the number of bytes read and written,
  1615. * respectively, on the raw socket used by <b>tls</b> since the last time this
  1616. * function was called on <b>tls</b>. */
  1617. void
  1618. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1619. {
  1620. BIO *wbio, *tmpbio;
  1621. unsigned long r, w;
  1622. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1623. /* We want the number of bytes actually for real written. Unfortunately,
  1624. * sometimes OpenSSL replaces the wbio on tls->ssl with a buffering bio,
  1625. * which makes the answer turn out wrong. Let's cope with that. Note
  1626. * that this approach will fail if we ever replace tls->ssl's BIOs with
  1627. * buffering bios for reasons of our own. As an alternative, we could
  1628. * save the original BIO for tls->ssl in the tor_tls_t structure, but
  1629. * that would be tempting fate. */
  1630. wbio = SSL_get_wbio(tls->ssl);
  1631. if (wbio->method == BIO_f_buffer() && (tmpbio = BIO_next(wbio)) != NULL)
  1632. wbio = tmpbio;
  1633. w = BIO_number_written(wbio);
  1634. /* We are ok with letting these unsigned ints go "negative" here:
  1635. * If we wrapped around, this should still give us the right answer, unless
  1636. * we wrapped around by more than ULONG_MAX since the last time we called
  1637. * this function.
  1638. */
  1639. *n_read = (size_t)(r - tls->last_read_count);
  1640. *n_written = (size_t)(w - tls->last_write_count);
  1641. if (*n_read > INT_MAX || *n_written > INT_MAX) {
  1642. log_warn(LD_BUG, "Preposterously large value in tor_tls_get_n_raw_bytes. "
  1643. "r=%lu, last_read=%lu, w=%lu, last_written=%lu",
  1644. r, tls->last_read_count, w, tls->last_write_count);
  1645. }
  1646. tls->last_read_count = r;
  1647. tls->last_write_count = w;
  1648. }
  1649. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1650. * errors, log an error message. */
  1651. void
  1652. _check_no_tls_errors(const char *fname, int line)
  1653. {
  1654. if (ERR_peek_error() == 0)
  1655. return;
  1656. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1657. tor_fix_source_file(fname), line);
  1658. tls_log_errors(NULL, LOG_WARN, LD_NET, NULL);
  1659. }
  1660. /** Return true iff the initial TLS connection at <b>tls</b> did not use a v2
  1661. * TLS handshake. Output is undefined if the handshake isn't finished. */
  1662. int
  1663. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1664. {
  1665. if (tls->isServer) {
  1666. #ifdef V2_HANDSHAKE_SERVER
  1667. return ! tls->wasV2Handshake;
  1668. #endif
  1669. } else {
  1670. #ifdef V2_HANDSHAKE_CLIENT
  1671. return ! tls->wasV2Handshake;
  1672. #endif
  1673. }
  1674. return 1;
  1675. }
  1676. /** Return the number of server handshakes that we've noticed doing on
  1677. * <b>tls</b>. */
  1678. int
  1679. tor_tls_get_num_server_handshakes(tor_tls_t *tls)
  1680. {
  1681. return tls->server_handshake_count;
  1682. }
  1683. /** Return true iff the server TLS connection <b>tls</b> got the renegotiation
  1684. * request it was waiting for. */
  1685. int
  1686. tor_tls_server_got_renegotiate(tor_tls_t *tls)
  1687. {
  1688. return tls->got_renegotiate;
  1689. }
  1690. /** Examine the amount of memory used and available for buffers in <b>tls</b>.
  1691. * Set *<b>rbuf_capacity</b> to the amount of storage allocated for the read
  1692. * buffer and *<b>rbuf_bytes</b> to the amount actually used.
  1693. * Set *<b>wbuf_capacity</b> to the amount of storage allocated for the write
  1694. * buffer and *<b>wbuf_bytes</b> to the amount actually used. */
  1695. void
  1696. tor_tls_get_buffer_sizes(tor_tls_t *tls,
  1697. size_t *rbuf_capacity, size_t *rbuf_bytes,
  1698. size_t *wbuf_capacity, size_t *wbuf_bytes)
  1699. {
  1700. if (tls->ssl->s3->rbuf.buf)
  1701. *rbuf_capacity = tls->ssl->s3->rbuf.len;
  1702. else
  1703. *rbuf_capacity = 0;
  1704. if (tls->ssl->s3->wbuf.buf)
  1705. *wbuf_capacity = tls->ssl->s3->wbuf.len;
  1706. else
  1707. *wbuf_capacity = 0;
  1708. *rbuf_bytes = tls->ssl->s3->rbuf.left;
  1709. *wbuf_bytes = tls->ssl->s3->wbuf.left;
  1710. }
  1711. #ifdef USE_BUFFEREVENTS
  1712. /** Construct and return an TLS-encrypting bufferevent to send data over
  1713. * <b>socket</b>, which must match the socket of the underlying bufferevent
  1714. * <b>bufev_in</b>. The TLS object <b>tls</b> is used for encryption.
  1715. *
  1716. * This function will either create a filtering bufferevent that wraps around
  1717. * <b>bufev_in</b>, or it will free bufev_in and return a new bufferevent that
  1718. * uses the <b>tls</b> to talk to the network directly. Do not use
  1719. * <b>bufev_in</b> after calling this function.
  1720. *
  1721. * The connection will start out doing a server handshake if <b>receiving</b>
  1722. * is strue, and a client handshake otherwise.
  1723. *
  1724. * Returns NULL on failure.
  1725. */
  1726. struct bufferevent *
  1727. tor_tls_init_bufferevent(tor_tls_t *tls, struct bufferevent *bufev_in,
  1728. evutil_socket_t socket, int receiving,
  1729. int filter)
  1730. {
  1731. struct bufferevent *out;
  1732. const enum bufferevent_ssl_state state = receiving ?
  1733. BUFFEREVENT_SSL_ACCEPTING : BUFFEREVENT_SSL_CONNECTING;
  1734. if (filter || tor_libevent_using_iocp_bufferevents()) {
  1735. /* Grab an extra reference to the SSL, since BEV_OPT_CLOSE_ON_FREE
  1736. means that the SSL will get freed too.
  1737. This increment makes our SSL usage not-threadsafe, BTW. We should
  1738. see if we're allowed to use CRYPTO_add from outside openssl. */
  1739. tls->ssl->references += 1;
  1740. out = bufferevent_openssl_filter_new(tor_libevent_get_base(),
  1741. bufev_in,
  1742. tls->ssl,
  1743. state,
  1744. BEV_OPT_DEFER_CALLBACKS|
  1745. BEV_OPT_CLOSE_ON_FREE);
  1746. } else {
  1747. if (bufev_in) {
  1748. evutil_socket_t s = bufferevent_getfd(bufev_in);
  1749. tor_assert(s == -1 || s == socket);
  1750. tor_assert(evbuffer_get_length(bufferevent_get_input(bufev_in)) == 0);
  1751. tor_assert(evbuffer_get_length(bufferevent_get_output(bufev_in)) == 0);
  1752. tor_assert(BIO_number_read(SSL_get_rbio(tls->ssl)) == 0);
  1753. tor_assert(BIO_number_written(SSL_get_rbio(tls->ssl)) == 0);
  1754. bufferevent_free(bufev_in);
  1755. }
  1756. /* Current versions (as of 2.0.x) of Libevent need to defer
  1757. * bufferevent_openssl callbacks, or else our callback functions will
  1758. * get called reentrantly, which is bad for us.
  1759. */
  1760. out = bufferevent_openssl_socket_new(tor_libevent_get_base(),
  1761. socket,
  1762. tls->ssl,
  1763. state,
  1764. BEV_OPT_DEFER_CALLBACKS);
  1765. }
  1766. tls->state = TOR_TLS_ST_BUFFEREVENT;
  1767. /* Unblock _after_ creating the bufferevent, since accept/connect tend to
  1768. * clear flags. */
  1769. tor_tls_unblock_renegotiation(tls);
  1770. return out;
  1771. }
  1772. #endif