tortls.c 44 KB

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