tortls.c 48 KB

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