tortls.c 60 KB

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