tortls.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  297. * signed by the private key <b>rsa_sign</b>. The commonName of the
  298. * certificate will be <b>cname</b>; the commonName of the issuer will be
  299. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  300. * starting from now. Return a certificate on success, NULL on
  301. * failure.
  302. */
  303. static X509 *
  304. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  305. crypto_pk_env_t *rsa_sign,
  306. const char *cname,
  307. const char *cname_sign,
  308. unsigned int cert_lifetime)
  309. {
  310. time_t start_time, end_time;
  311. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  312. X509 *x509 = NULL;
  313. X509_NAME *name = NULL, *name_issuer=NULL;
  314. int nid;
  315. tor_tls_init();
  316. start_time = time(NULL);
  317. tor_assert(rsa);
  318. tor_assert(cname);
  319. tor_assert(rsa_sign);
  320. tor_assert(cname_sign);
  321. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  322. goto error;
  323. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  324. goto error;
  325. if (!(x509 = X509_new()))
  326. goto error;
  327. if (!(X509_set_version(x509, 2)))
  328. goto error;
  329. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  330. goto error;
  331. if (!(name = X509_NAME_new()))
  332. goto error;
  333. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
  334. goto error;
  335. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  336. (unsigned char*)"t o r", -1, -1, 0)))
  337. goto error;
  338. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  339. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  340. (unsigned char*)cname, -1, -1, 0)))
  341. goto error;
  342. if (!(X509_set_subject_name(x509, name)))
  343. goto error;
  344. if (!(name_issuer = X509_NAME_new()))
  345. goto error;
  346. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
  347. goto error;
  348. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  349. (unsigned char*)"t o r", -1, -1, 0)))
  350. goto error;
  351. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  352. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  353. (unsigned char*)cname_sign, -1, -1, 0)))
  354. goto error;
  355. if (!(X509_set_issuer_name(x509, name_issuer)))
  356. goto error;
  357. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  358. goto error;
  359. end_time = start_time + cert_lifetime;
  360. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  361. goto error;
  362. if (!X509_set_pubkey(x509, pkey))
  363. goto error;
  364. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  365. goto error;
  366. goto done;
  367. error:
  368. if (x509) {
  369. X509_free(x509);
  370. x509 = NULL;
  371. }
  372. done:
  373. tls_log_errors(LOG_WARN, "generating certificate");
  374. if (sign_pkey)
  375. EVP_PKEY_free(sign_pkey);
  376. if (pkey)
  377. EVP_PKEY_free(pkey);
  378. if (name)
  379. X509_NAME_free(name);
  380. if (name_issuer)
  381. X509_NAME_free(name_issuer);
  382. return x509;
  383. }
  384. #define SERVER_CIPHER_LIST \
  385. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  386. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  387. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  388. /* Note: for setting up your own private testing network with link crypto
  389. * disabled, set the cipher lists to your cipher list to
  390. * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
  391. * with any of the "real" Tors, though. */
  392. #if OPENSSL_VERSION_NUMBER >= 0x00908000l
  393. #define CLIENT_CIPHER_LIST \
  394. (TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ":" \
  395. TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":" \
  396. TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  397. TLS1_TXT_DHE_DSS_WITH_AES_256_SHA ":" \
  398. TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA ":" \
  399. TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA ":" \
  400. TLS1_TXT_RSA_WITH_AES_256_SHA ":" \
  401. TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA ":" \
  402. TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA ":" \
  403. TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA ":" \
  404. TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":" \
  405. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  406. TLS1_TXT_DHE_DSS_WITH_AES_128_SHA ":" \
  407. TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA":" \
  408. TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA":" \
  409. TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA ":" \
  410. TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA ":" \
  411. SSL3_TXT_RSA_RC4_128_MD5 ":" \
  412. SSL3_TXT_RSA_RC4_128_SHA ":" \
  413. TLS1_TXT_RSA_WITH_AES_128_SHA ":" \
  414. TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA ":" \
  415. TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA ":" \
  416. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
  417. SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA ":" \
  418. TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA ":" \
  419. TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA ":" \
  420. /*SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA ":"*/ \
  421. SSL3_TXT_RSA_DES_192_CBC3_SHA)
  422. /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA is commented out because it doesn't
  423. * really exist; if I understand correctly, it's a bit of silliness that
  424. * netscape did on its own before any standard for what they wanted was
  425. * formally approved. Nonetheless, Firefox still uses it, so we need to
  426. * fake it at some point soon. XXXX020 -NM */
  427. #else
  428. /* Ug. We don't have as many ciphers with openssl 0.9.7 as we'd like. Fix
  429. * this list into something that sucks less. */
  430. #define CLIENT_CIPHER_LIST \
  431. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  432. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  433. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
  434. SSL3_TXT_RSA_RC4_128_SHA)
  435. #endif
  436. #ifndef V2_HANDSHAKE_CLIENT
  437. #undef CLIENT_CIPHER_LIST
  438. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  439. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  440. #endif
  441. /** Remove a reference to <b>ctx</b>, and free it if it has no more
  442. * references. */
  443. static void
  444. tor_tls_context_decref(tor_tls_context_t *ctx)
  445. {
  446. tor_assert(ctx);
  447. if (--ctx->refcnt == 0) {
  448. SSL_CTX_free(ctx->ctx);
  449. X509_free(ctx->my_cert);
  450. X509_free(ctx->my_id_cert);
  451. crypto_free_pk_env(ctx->key);
  452. tor_free(ctx);
  453. }
  454. }
  455. /** Increase the reference count of <b>ctx</b>. */
  456. static void
  457. tor_tls_context_incref(tor_tls_context_t *ctx)
  458. {
  459. ++ctx->refcnt;
  460. }
  461. /** Create a new TLS context for use with Tor TLS handshakes.
  462. * <b>identity</b> should be set to the identity key used to sign the
  463. * certificate, and <b>nickname</b> set to the nickname to use.
  464. *
  465. * You can call this function multiple times. Each time you call it,
  466. * it generates new certificates; all new connections will use
  467. * the new SSL context.
  468. */
  469. int
  470. tor_tls_context_new(crypto_pk_env_t *identity, const char *nickname,
  471. unsigned int key_lifetime)
  472. {
  473. crypto_pk_env_t *rsa = NULL;
  474. crypto_dh_env_t *dh = NULL;
  475. EVP_PKEY *pkey = NULL;
  476. tor_tls_context_t *result = NULL;
  477. X509 *cert = NULL, *idcert = NULL;
  478. char nn2[128];
  479. if (!nickname)
  480. nickname = "null";
  481. tor_snprintf(nn2, sizeof(nn2), "%s <signing>", nickname);
  482. tor_tls_init();
  483. /* Generate short-term RSA key. */
  484. if (!(rsa = crypto_new_pk_env()))
  485. goto error;
  486. if (crypto_pk_generate_key(rsa)<0)
  487. goto error;
  488. /* Create certificate signed by identity key. */
  489. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  490. key_lifetime);
  491. /* Create self-signed certificate for identity key. */
  492. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  493. IDENTITY_CERT_LIFETIME);
  494. if (!cert || !idcert) {
  495. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  496. goto error;
  497. }
  498. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  499. result->refcnt = 1;
  500. result->my_cert = X509_dup(cert);
  501. result->my_id_cert = X509_dup(idcert);
  502. result->key = crypto_pk_dup_key(rsa);
  503. #ifdef EVERYONE_HAS_AES
  504. /* Tell OpenSSL to only use TLS1 */
  505. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  506. goto error;
  507. #else
  508. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  509. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  510. goto error;
  511. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  512. #endif
  513. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  514. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  515. goto error;
  516. X509_free(cert); /* We just added a reference to cert. */
  517. cert=NULL;
  518. if (idcert) {
  519. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  520. tor_assert(s);
  521. X509_STORE_add_cert(s, idcert);
  522. X509_free(idcert); /* The context now owns the reference to idcert */
  523. idcert = NULL;
  524. }
  525. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  526. tor_assert(rsa);
  527. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  528. goto error;
  529. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  530. goto error;
  531. EVP_PKEY_free(pkey);
  532. pkey = NULL;
  533. if (!SSL_CTX_check_private_key(result->ctx))
  534. goto error;
  535. dh = crypto_dh_new();
  536. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  537. crypto_dh_free(dh);
  538. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  539. always_accept_verify_cb);
  540. /* let us realloc bufs that we're writing from */
  541. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  542. /* Free the old context if one exists. */
  543. if (global_tls_context) {
  544. /* This is safe even if there are open connections: OpenSSL does
  545. * reference counting with SSL and SSL_CTX objects. */
  546. tor_tls_context_decref(global_tls_context);
  547. }
  548. global_tls_context = result;
  549. if (rsa)
  550. crypto_free_pk_env(rsa);
  551. return 0;
  552. error:
  553. tls_log_errors(LOG_WARN, "creating TLS context");
  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_notice(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. } else {
  863. tls->wasV2Handshake = 0;
  864. }
  865. #endif
  866. } else {
  867. #ifdef V2_HANDSHAKE_CLIENT
  868. /* If we got no ID cert, we're a v2 handshake. */
  869. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  870. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  871. int n_certs = sk_X509_num(chain);
  872. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
  873. tls->wasV2Handshake = 0;
  874. else {
  875. log_notice(LD_NET, "I think I got a v2 handshake on %p!", tls);
  876. tls->wasV2Handshake = 1;
  877. }
  878. if (cert)
  879. X509_free(cert);
  880. #endif
  881. SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST);
  882. }
  883. }
  884. return r;
  885. }
  886. /** Client only: Renegotiate a TLS session. When finished, returns
  887. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  888. * TOR_TLS_WANTWRITE.
  889. */
  890. int
  891. tor_tls_renegotiate(tor_tls_t *tls)
  892. {
  893. int r;
  894. tor_assert(tls);
  895. /* We could do server-initiated renegotiation too, but that would be tricky.
  896. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  897. tor_assert(!tls->isServer);
  898. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  899. int r = SSL_renegotiate(tls->ssl);
  900. if (r <= 0) {
  901. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  902. "renegotiating", LOG_WARN);
  903. }
  904. tls->state = TOR_TLS_ST_RENEGOTIATE;
  905. }
  906. r = SSL_do_handshake(tls->ssl);
  907. if (r == 1) {
  908. tls->state = TOR_TLS_ST_OPEN;
  909. return TOR_TLS_DONE;
  910. } else
  911. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  912. "renegotiating handshake", LOG_WARN);
  913. }
  914. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  915. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  916. * or TOR_TLS_WANTWRITE.
  917. */
  918. int
  919. tor_tls_shutdown(tor_tls_t *tls)
  920. {
  921. int r, err;
  922. char buf[128];
  923. tor_assert(tls);
  924. tor_assert(tls->ssl);
  925. while (1) {
  926. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  927. /* If we've already called shutdown once to send a close message,
  928. * we read until the other side has closed too.
  929. */
  930. do {
  931. r = SSL_read(tls->ssl, buf, 128);
  932. } while (r>0);
  933. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  934. LOG_INFO);
  935. if (err == _TOR_TLS_ZERORETURN) {
  936. tls->state = TOR_TLS_ST_GOTCLOSE;
  937. /* fall through... */
  938. } else {
  939. return err;
  940. }
  941. }
  942. r = SSL_shutdown(tls->ssl);
  943. if (r == 1) {
  944. /* If shutdown returns 1, the connection is entirely closed. */
  945. tls->state = TOR_TLS_ST_CLOSED;
  946. return TOR_TLS_DONE;
  947. }
  948. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  949. LOG_INFO);
  950. if (err == _TOR_TLS_SYSCALL) {
  951. /* The underlying TCP connection closed while we were shutting down. */
  952. tls->state = TOR_TLS_ST_CLOSED;
  953. return TOR_TLS_DONE;
  954. } else if (err == _TOR_TLS_ZERORETURN) {
  955. /* The TLS connection says that it sent a shutdown record, but
  956. * isn't done shutting down yet. Make sure that this hasn't
  957. * happened before, then go back to the start of the function
  958. * and try to read.
  959. */
  960. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  961. tls->state == TOR_TLS_ST_SENTCLOSE) {
  962. log(LOG_WARN, LD_NET,
  963. "TLS returned \"half-closed\" value while already half-closed");
  964. return TOR_TLS_ERROR_MISC;
  965. }
  966. tls->state = TOR_TLS_ST_SENTCLOSE;
  967. /* fall through ... */
  968. } else {
  969. return err;
  970. }
  971. } /* end loop */
  972. }
  973. /** Return true iff this TLS connection is authenticated.
  974. */
  975. int
  976. tor_tls_peer_has_cert(tor_tls_t *tls)
  977. {
  978. X509 *cert;
  979. cert = SSL_get_peer_certificate(tls->ssl);
  980. tls_log_errors(LOG_WARN, "getting peer certificate");
  981. if (!cert)
  982. return 0;
  983. X509_free(cert);
  984. return 1;
  985. }
  986. /** Warn that a certificate lifetime extends through a certain range. */
  987. static void
  988. log_cert_lifetime(X509 *cert, const char *problem)
  989. {
  990. BIO *bio = NULL;
  991. BUF_MEM *buf;
  992. char *s1=NULL, *s2=NULL;
  993. char mytime[33];
  994. time_t now = time(NULL);
  995. struct tm tm;
  996. if (problem)
  997. log_warn(LD_GENERAL,
  998. "Certificate %s: is your system clock set incorrectly?",
  999. problem);
  1000. if (!(bio = BIO_new(BIO_s_mem()))) {
  1001. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1002. }
  1003. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1004. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  1005. goto end;
  1006. }
  1007. BIO_get_mem_ptr(bio, &buf);
  1008. s1 = tor_strndup(buf->data, buf->length);
  1009. (void)BIO_reset(bio);
  1010. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1011. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  1012. goto end;
  1013. }
  1014. BIO_get_mem_ptr(bio, &buf);
  1015. s2 = tor_strndup(buf->data, buf->length);
  1016. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1017. log_warn(LD_GENERAL,
  1018. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1019. s1,s2,mytime);
  1020. end:
  1021. /* Not expected to get invoked */
  1022. tls_log_errors(LOG_WARN, "getting certificate lifetime");
  1023. if (bio)
  1024. BIO_free(bio);
  1025. if (s1)
  1026. tor_free(s1);
  1027. if (s2)
  1028. tor_free(s2);
  1029. }
  1030. /** DOCDOC helper.
  1031. * cert_out needs to be freed. id_cert_out doesn't. */
  1032. static void
  1033. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1034. X509 **cert_out, X509 **id_cert_out)
  1035. {
  1036. X509 *cert = NULL, *id_cert = NULL;
  1037. STACK_OF(X509) *chain = NULL;
  1038. int num_in_chain, i;
  1039. *cert_out = *id_cert_out = NULL;
  1040. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1041. return;
  1042. *cert_out = cert;
  1043. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1044. return;
  1045. num_in_chain = sk_X509_num(chain);
  1046. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1047. * 2 means we're connecting (client-side), and it's both the link
  1048. * cert and the id_cert.
  1049. */
  1050. if (num_in_chain < 1) {
  1051. log_fn(severity,LD_PROTOCOL,
  1052. "Unexpected number of certificates in chain (%d)",
  1053. num_in_chain);
  1054. return;
  1055. }
  1056. for (i=0; i<num_in_chain; ++i) {
  1057. id_cert = sk_X509_value(chain, i);
  1058. if (X509_cmp(id_cert, cert) != 0)
  1059. break;
  1060. }
  1061. *id_cert_out = id_cert;
  1062. }
  1063. /** If the provided tls connection is authenticated and has a
  1064. * certificate that is currently valid and signed, then set
  1065. * *<b>identity_key</b> to the identity certificate's key and return
  1066. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1067. */
  1068. int
  1069. tor_tls_verify_v1(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1070. {
  1071. X509 *cert = NULL, *id_cert = NULL;
  1072. EVP_PKEY *id_pkey = NULL;
  1073. RSA *rsa;
  1074. int r = -1;
  1075. *identity_key = NULL;
  1076. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1077. if (!cert)
  1078. goto done;
  1079. if (!id_cert) {
  1080. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1081. goto done;
  1082. }
  1083. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1084. X509_verify(cert, id_pkey) <= 0) {
  1085. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1086. tls_log_errors(severity,"verifying certificate");
  1087. goto done;
  1088. }
  1089. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1090. if (!rsa)
  1091. goto done;
  1092. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1093. r = 0;
  1094. done:
  1095. if (cert)
  1096. X509_free(cert);
  1097. if (id_pkey)
  1098. EVP_PKEY_free(id_pkey);
  1099. /* This should never get invoked, but let's make sure in case OpenSSL
  1100. * acts unexpectedly. */
  1101. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  1102. return r;
  1103. }
  1104. /** Check whether the certificate set on the connection <b>tls</b> is
  1105. * expired or not-yet-valid, give or take <b>tolerance</b>
  1106. * seconds. Return 0 for valid, -1 for failure.
  1107. *
  1108. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1109. */
  1110. int
  1111. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  1112. {
  1113. time_t now, t;
  1114. X509 *cert;
  1115. int r = -1;
  1116. now = time(NULL);
  1117. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1118. goto done;
  1119. t = now + tolerance;
  1120. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1121. log_cert_lifetime(cert, "not yet valid");
  1122. goto done;
  1123. }
  1124. t = now - tolerance;
  1125. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1126. log_cert_lifetime(cert, "already expired");
  1127. goto done;
  1128. }
  1129. r = 0;
  1130. done:
  1131. if (cert)
  1132. X509_free(cert);
  1133. /* Not expected to get invoked */
  1134. tls_log_errors(LOG_WARN, "checking certificate lifetime");
  1135. return r;
  1136. }
  1137. /** Return the number of bytes available for reading from <b>tls</b>.
  1138. */
  1139. int
  1140. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1141. {
  1142. tor_assert(tls);
  1143. return SSL_pending(tls->ssl);
  1144. }
  1145. /** If <b>tls</b> requires that the next write be of a particular size,
  1146. * return that size. Otherwise, return 0. */
  1147. size_t
  1148. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1149. {
  1150. return tls->wantwrite_n;
  1151. }
  1152. /** Sets n_read and n_written to the number of bytes read and written,
  1153. * respectivey, on the raw socket used by <b>tls</b> since the last time this
  1154. * function was called on <b>tls</b>. */
  1155. void
  1156. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1157. {
  1158. unsigned long r, w;
  1159. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1160. w = BIO_number_written(SSL_get_wbio(tls->ssl));
  1161. /* We are ok with letting these unsigned ints go "negative" here:
  1162. * If we wrapped around, this should still give us the right answer, unless
  1163. * we wrapped around by more than ULONG_MAX since the last time we called
  1164. * this function.
  1165. */
  1166. *n_read = (size_t)(r - tls->last_read_count);
  1167. *n_written = (size_t)(w - tls->last_write_count);
  1168. tls->last_read_count = r;
  1169. tls->last_write_count = w;
  1170. }
  1171. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1172. * errors, log an error message. */
  1173. void
  1174. _check_no_tls_errors(const char *fname, int line)
  1175. {
  1176. if (ERR_peek_error() == 0)
  1177. return;
  1178. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1179. tor_fix_source_file(fname), line);
  1180. tls_log_errors(LOG_WARN, NULL);
  1181. }
  1182. /**DOCDOC */
  1183. int
  1184. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1185. {
  1186. if (tls->isServer) {
  1187. #ifdef V2_HANDSHAKE_SERVER
  1188. return ! tls->wasV2Handshake;
  1189. #endif
  1190. } else {
  1191. #ifdef V2_HANDSHAKE_CLIENT
  1192. return ! tls->wasV2Handshake;
  1193. #endif
  1194. }
  1195. return 1;
  1196. }