tortls.c 39 KB

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