tortls.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. /* Copyright 2003 Roger Dingledine.
  2. * Copyright 2004-2006 Roger Dingledine, Nick Mathewson */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char tortls_c_id[] =
  6. "$Id$";
  7. /**
  8. * \file tortls.c
  9. * \brief Wrapper functions to present a consistent interface to
  10. * TLS, SSL, and X.509 functions from OpenSSL.
  11. **/
  12. /* (Unlike other tor functions, these
  13. * are prefixed with tor_ in order to avoid conflicting with OpenSSL
  14. * functions and variables.)
  15. */
  16. #include "orconfig.h"
  17. #include "./crypto.h"
  18. #include "./tortls.h"
  19. #include "./util.h"
  20. #include "./log.h"
  21. #include <string.h>
  22. /* Copied from or.h */
  23. #define LEGAL_NICKNAME_CHARACTERS \
  24. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  25. #include <assert.h>
  26. #include <openssl/ssl.h>
  27. #include <openssl/err.h>
  28. #include <openssl/tls1.h>
  29. #include <openssl/asn1.h>
  30. #include <openssl/bio.h>
  31. /** How long do identity certificates live? (sec) */
  32. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  33. /** Structure holding the TLS state for a single connection. */
  34. typedef struct tor_tls_context_t {
  35. SSL_CTX *ctx;
  36. } tor_tls_context_t;
  37. /** Holds a SSL object and its associated data. Members are only
  38. * accessed from within tortls.c.
  39. */
  40. struct tor_tls_t {
  41. SSL *ssl; /**< An OpenSSL SSL object. */
  42. int socket; /**< The underlying file descriptor for this TLS connection. */
  43. enum {
  44. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  45. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
  46. } state; /**< The current SSL state, depending on which operations have
  47. * completed successfully. */
  48. int isServer;
  49. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
  50. * time. */
  51. };
  52. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  53. crypto_pk_env_t *rsa_sign,
  54. const char *cname,
  55. const char *cname_sign,
  56. unsigned int lifetime);
  57. /** Global tls context. We keep it here because nobody else needs to
  58. * touch it. */
  59. static tor_tls_context_t *global_tls_context = NULL;
  60. /** True iff tor_tls_init() has been called. */
  61. static int tls_library_is_initialized = 0;
  62. /* Module-internal error codes. */
  63. #define _TOR_TLS_SYSCALL -6
  64. #define _TOR_TLS_ZERORETURN -5
  65. /* These functions are declared in crypto.c but not exported. */
  66. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
  67. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
  68. DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
  69. /** Log all pending tls errors at level <b>severity</b>. Use
  70. * <b>doing</b> to describe our current activities.
  71. */
  72. static void
  73. tls_log_errors(int severity, const char *doing)
  74. {
  75. int err;
  76. const char *msg, *lib, *func;
  77. while ((err = ERR_get_error()) != 0) {
  78. msg = (const char*)ERR_reason_error_string(err);
  79. lib = (const char*)ERR_lib_error_string(err);
  80. func = (const char*)ERR_func_error_string(err);
  81. if (!msg) msg = "(null)";
  82. if (doing) {
  83. log(severity, LD_NET, "TLS error while %s: %s (in %s:%s)",
  84. doing, msg, lib,func);
  85. } else {
  86. log(severity, LD_NET, "TLS error: %s (in %s:%s)", msg, lib, func);
  87. }
  88. }
  89. }
  90. #define CATCH_SYSCALL 1
  91. #define CATCH_ZERO 2
  92. /** Given a TLS object and the result of an SSL_* call, use
  93. * SSL_get_error to determine whether an error has occurred, and if so
  94. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  95. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  96. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  97. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  98. *
  99. * If an error has occurred, log it at level <b>severity</b> and describe the
  100. * current action as <b>doing</b>.
  101. */
  102. static int
  103. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  104. const char *doing, int severity)
  105. {
  106. int err = SSL_get_error(tls->ssl, r);
  107. switch (err) {
  108. case SSL_ERROR_NONE:
  109. return TOR_TLS_DONE;
  110. case SSL_ERROR_WANT_READ:
  111. return TOR_TLS_WANTREAD;
  112. case SSL_ERROR_WANT_WRITE:
  113. return TOR_TLS_WANTWRITE;
  114. case SSL_ERROR_SYSCALL:
  115. if (extra&CATCH_SYSCALL)
  116. return _TOR_TLS_SYSCALL;
  117. if (r == 0)
  118. log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
  119. else {
  120. int e = tor_socket_errno(tls->socket);
  121. log(severity, LD_NET,
  122. "TLS error: <syscall error while %s> (errno=%d: %s)",
  123. doing, e, tor_socket_strerror(e));
  124. }
  125. tls_log_errors(severity, doing);
  126. return TOR_TLS_ERROR;
  127. case SSL_ERROR_ZERO_RETURN:
  128. if (extra&CATCH_ZERO)
  129. return _TOR_TLS_ZERORETURN;
  130. log(severity, LD_NET, "TLS error: Zero return");
  131. tls_log_errors(severity, doing);
  132. return TOR_TLS_ERROR;
  133. default:
  134. tls_log_errors(severity, doing);
  135. return TOR_TLS_ERROR;
  136. }
  137. }
  138. /** Initialize OpenSSL, unless it has already been initialized.
  139. */
  140. static void
  141. tor_tls_init(void)
  142. {
  143. if (!tls_library_is_initialized) {
  144. SSL_library_init();
  145. SSL_load_error_strings();
  146. crypto_global_init(-1);
  147. tls_library_is_initialized = 1;
  148. }
  149. }
  150. void
  151. tor_tls_free_all(void)
  152. {
  153. if (global_tls_context) {
  154. SSL_CTX_free(global_tls_context->ctx);
  155. tor_free(global_tls_context);
  156. global_tls_context = NULL;
  157. }
  158. }
  159. /** We need to give OpenSSL a callback to verify certificates. This is
  160. * it: We always accept peer certs and complete the handshake. We
  161. * don't validate them until later.
  162. */
  163. static int
  164. always_accept_verify_cb(int preverify_ok,
  165. X509_STORE_CTX *x509_ctx)
  166. {
  167. /* avoid "unused parameter" warning. */
  168. preverify_ok = 0;
  169. x509_ctx = NULL;
  170. return 1;
  171. }
  172. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  173. * signed by the private key <b>rsa_sign</b>. The commonName of the
  174. * certificate will be <b>cname</b>; the commonName of the issuer will be
  175. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  176. * starting from now. Return a certificate on success, NULL on
  177. * failure.
  178. */
  179. static X509 *
  180. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  181. crypto_pk_env_t *rsa_sign,
  182. const char *cname,
  183. const char *cname_sign,
  184. unsigned int cert_lifetime)
  185. {
  186. time_t start_time, end_time;
  187. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  188. X509 *x509 = NULL;
  189. X509_NAME *name = NULL, *name_issuer=NULL;
  190. int nid;
  191. tor_tls_init();
  192. start_time = time(NULL);
  193. tor_assert(rsa);
  194. tor_assert(cname);
  195. tor_assert(rsa_sign);
  196. tor_assert(cname_sign);
  197. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  198. goto error;
  199. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  200. goto error;
  201. if (!(x509 = X509_new()))
  202. goto error;
  203. if (!(X509_set_version(x509, 2)))
  204. goto error;
  205. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  206. goto error;
  207. if (!(name = X509_NAME_new()))
  208. goto error;
  209. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
  210. goto error;
  211. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  212. (unsigned char*)"Tor", -1, -1, 0)))
  213. goto error;
  214. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  215. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  216. (unsigned char*)cname, -1, -1, 0)))
  217. goto error;
  218. if (!(X509_set_subject_name(x509, name)))
  219. goto error;
  220. if (!(name_issuer = X509_NAME_new()))
  221. goto error;
  222. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
  223. goto error;
  224. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  225. (unsigned char*)"Tor", -1, -1, 0)))
  226. goto error;
  227. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  228. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  229. (unsigned char*)cname_sign, -1, -1, 0)))
  230. goto error;
  231. if (!(X509_set_issuer_name(x509, name_issuer)))
  232. goto error;
  233. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  234. goto error;
  235. end_time = start_time + cert_lifetime;
  236. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  237. goto error;
  238. if (!X509_set_pubkey(x509, pkey))
  239. goto error;
  240. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  241. goto error;
  242. goto done;
  243. error:
  244. if (x509) {
  245. X509_free(x509);
  246. x509 = NULL;
  247. }
  248. done:
  249. tls_log_errors(LOG_WARN, "generating certificate");
  250. if (sign_pkey)
  251. EVP_PKEY_free(sign_pkey);
  252. if (pkey)
  253. EVP_PKEY_free(pkey);
  254. if (name)
  255. X509_NAME_free(name);
  256. if (name_issuer)
  257. X509_NAME_free(name_issuer);
  258. return x509;
  259. }
  260. #ifdef EVERYONE_HAS_AES
  261. /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
  262. * is needed. */
  263. #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
  264. #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
  265. /* Some people are running OpenSSL before 0.9.7, but we aren't.
  266. * We can support AES and 3DES.
  267. */
  268. #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  269. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  270. #else
  271. /* We're running OpenSSL before 0.9.7. We only support 3DES. */
  272. #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
  273. #endif
  274. /** Create a new TLS context for use with Tor TLS handshakes.
  275. * <b>identity</b> should be set to the identity key used to sign the
  276. * certificate, and <b>nickname</b> set to the nickname to use.
  277. *
  278. * You can call this function multiple times. Each time you call it,
  279. * it generates new certificates; all new connections will use
  280. * the new SSL context.
  281. */
  282. int
  283. tor_tls_context_new(crypto_pk_env_t *identity, const char *nickname,
  284. unsigned int key_lifetime)
  285. {
  286. crypto_pk_env_t *rsa = NULL;
  287. crypto_dh_env_t *dh = NULL;
  288. EVP_PKEY *pkey = NULL;
  289. tor_tls_context_t *result = NULL;
  290. X509 *cert = NULL, *idcert = NULL;
  291. char nn2[128];
  292. if (!nickname)
  293. nickname = "null";
  294. tor_snprintf(nn2, sizeof(nn2), "%s <identity>", nickname);
  295. tor_tls_init();
  296. /* Generate short-term RSA key. */
  297. if (!(rsa = crypto_new_pk_env()))
  298. goto error;
  299. if (crypto_pk_generate_key(rsa)<0)
  300. goto error;
  301. /* Create certificate signed by identity key. */
  302. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  303. key_lifetime);
  304. /* Create self-signed certificate for identity key. */
  305. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  306. IDENTITY_CERT_LIFETIME);
  307. if (!cert || !idcert) {
  308. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  309. goto error;
  310. }
  311. result = tor_malloc(sizeof(tor_tls_context_t));
  312. #ifdef EVERYONE_HAS_AES
  313. /* Tell OpenSSL to only use TLS1 */
  314. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  315. goto error;
  316. #else
  317. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  318. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  319. goto error;
  320. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  321. #endif
  322. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  323. if (!SSL_CTX_set_cipher_list(result->ctx, CIPHER_LIST))
  324. goto error;
  325. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  326. goto error;
  327. X509_free(cert); /* We just added a reference to cert. */
  328. cert=NULL;
  329. if (idcert && !SSL_CTX_add_extra_chain_cert(result->ctx,idcert))
  330. goto error;
  331. idcert=NULL; /* The context now owns the reference to idcert */
  332. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  333. tor_assert(rsa);
  334. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  335. goto error;
  336. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  337. goto error;
  338. EVP_PKEY_free(pkey);
  339. pkey = NULL;
  340. if (!SSL_CTX_check_private_key(result->ctx))
  341. goto error;
  342. dh = crypto_dh_new();
  343. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  344. crypto_dh_free(dh);
  345. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  346. always_accept_verify_cb);
  347. /* let us realloc bufs that we're writing from */
  348. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  349. /* Free the old context if one exists. */
  350. if (global_tls_context) {
  351. /* This is safe even if there are open connections: OpenSSL does
  352. * reference counting with SSL and SSL_CTX objects. */
  353. SSL_CTX_free(global_tls_context->ctx);
  354. tor_free(global_tls_context);
  355. }
  356. global_tls_context = result;
  357. if (rsa)
  358. crypto_free_pk_env(rsa);
  359. return 0;
  360. error:
  361. tls_log_errors(LOG_WARN, "creating TLS context");
  362. if (pkey)
  363. EVP_PKEY_free(pkey);
  364. if (rsa)
  365. crypto_free_pk_env(rsa);
  366. if (dh)
  367. crypto_dh_free(dh);
  368. if (result && result->ctx)
  369. SSL_CTX_free(result->ctx);
  370. if (result)
  371. tor_free(result);
  372. if (cert)
  373. X509_free(cert);
  374. if (idcert)
  375. X509_free(idcert);
  376. return -1;
  377. }
  378. /** Create a new TLS object from a file descriptor, and a flag to
  379. * determine whether it is functioning as a server.
  380. */
  381. tor_tls_t *
  382. tor_tls_new(int sock, int isServer)
  383. {
  384. BIO *bio = NULL;
  385. tor_tls_t *result = tor_malloc(sizeof(tor_tls_t));
  386. tor_assert(global_tls_context); /* make sure somebody made it first */
  387. if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
  388. tls_log_errors(LOG_WARN, "generating TLS context");
  389. tor_free(result);
  390. return NULL;
  391. }
  392. result->socket = sock;
  393. #ifdef USE_BSOCKETS
  394. bio = BIO_new_bsocket(sock, BIO_NOCLOSE);
  395. #else
  396. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  397. #endif
  398. if (! bio) {
  399. tls_log_errors(LOG_WARN, "opening BIO");
  400. tor_free(result);
  401. return NULL;
  402. }
  403. SSL_set_bio(result->ssl, bio, bio);
  404. result->state = TOR_TLS_ST_HANDSHAKE;
  405. result->isServer = isServer;
  406. result->wantwrite_n = 0;
  407. /* Not expected to get called. */
  408. tls_log_errors(LOG_WARN, "generating TLS context");
  409. return result;
  410. }
  411. /** Return whether this tls initiated the connect (client) or
  412. * received it (server). */
  413. int
  414. tor_tls_is_server(tor_tls_t *tls)
  415. {
  416. tor_assert(tls);
  417. return tls->isServer;
  418. }
  419. /** Release resources associated with a TLS object. Does not close the
  420. * underlying file descriptor.
  421. */
  422. void
  423. tor_tls_free(tor_tls_t *tls)
  424. {
  425. tor_assert(tls && tls->ssl);
  426. SSL_free(tls->ssl);
  427. tls->ssl = NULL;
  428. tor_free(tls);
  429. }
  430. /** Underlying function for TLS reading. Reads up to <b>len</b>
  431. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  432. * number of characters read. On failure, returns TOR_TLS_ERROR,
  433. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  434. */
  435. int
  436. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  437. {
  438. int r, err;
  439. tor_assert(tls);
  440. tor_assert(tls->ssl);
  441. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  442. r = SSL_read(tls->ssl, cp, len);
  443. if (r > 0)
  444. return r;
  445. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
  446. if (err == _TOR_TLS_ZERORETURN) {
  447. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  448. tls->state = TOR_TLS_ST_CLOSED;
  449. return TOR_TLS_CLOSE;
  450. } else {
  451. tor_assert(err != TOR_TLS_DONE);
  452. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  453. return err;
  454. }
  455. }
  456. /** Underlying function for TLS writing. Write up to <b>n</b>
  457. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  458. * number of characters written. On failure, returns TOR_TLS_ERROR,
  459. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  460. */
  461. int
  462. tor_tls_write(tor_tls_t *tls, char *cp, size_t n)
  463. {
  464. int r, err;
  465. tor_assert(tls);
  466. tor_assert(tls->ssl);
  467. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  468. if (n == 0)
  469. return 0;
  470. if (tls->wantwrite_n) {
  471. /* if WANTWRITE last time, we must use the _same_ n as before */
  472. tor_assert(n >= tls->wantwrite_n);
  473. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  474. (int)n, (int)tls->wantwrite_n);
  475. n = tls->wantwrite_n;
  476. tls->wantwrite_n = 0;
  477. }
  478. r = SSL_write(tls->ssl, cp, n);
  479. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  480. if (err == TOR_TLS_DONE) {
  481. return r;
  482. }
  483. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  484. tls->wantwrite_n = n;
  485. }
  486. return err;
  487. }
  488. /** Perform initial handshake on <b>tls</b>. When finished, returns
  489. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  490. * or TOR_TLS_WANTWRITE.
  491. */
  492. int
  493. tor_tls_handshake(tor_tls_t *tls)
  494. {
  495. int r;
  496. tor_assert(tls);
  497. tor_assert(tls->ssl);
  498. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  499. check_no_tls_errors();
  500. if (tls->isServer) {
  501. r = SSL_accept(tls->ssl);
  502. } else {
  503. r = SSL_connect(tls->ssl);
  504. }
  505. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  506. if (ERR_peek_error() != 0) {
  507. tls_log_errors(tls->isServer ? LOG_INFO : LOG_WARN,
  508. "handshaking");
  509. return TOR_TLS_ERROR;
  510. }
  511. if (r == TOR_TLS_DONE) {
  512. tls->state = TOR_TLS_ST_OPEN;
  513. }
  514. return r;
  515. }
  516. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  517. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  518. * or TOR_TLS_WANTWRITE.
  519. */
  520. int
  521. tor_tls_shutdown(tor_tls_t *tls)
  522. {
  523. int r, err;
  524. char buf[128];
  525. tor_assert(tls);
  526. tor_assert(tls->ssl);
  527. while (1) {
  528. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  529. /* If we've already called shutdown once to send a close message,
  530. * we read until the other side has closed too.
  531. */
  532. do {
  533. r = SSL_read(tls->ssl, buf, 128);
  534. } while (r>0);
  535. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  536. LOG_INFO);
  537. if (err == _TOR_TLS_ZERORETURN) {
  538. tls->state = TOR_TLS_ST_GOTCLOSE;
  539. /* fall through... */
  540. } else {
  541. return err;
  542. }
  543. }
  544. r = SSL_shutdown(tls->ssl);
  545. if (r == 1) {
  546. /* If shutdown returns 1, the connection is entirely closed. */
  547. tls->state = TOR_TLS_ST_CLOSED;
  548. return TOR_TLS_DONE;
  549. }
  550. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  551. LOG_INFO);
  552. if (err == _TOR_TLS_SYSCALL) {
  553. /* The underlying TCP connection closed while we were shutting down. */
  554. tls->state = TOR_TLS_ST_CLOSED;
  555. return TOR_TLS_DONE;
  556. } else if (err == _TOR_TLS_ZERORETURN) {
  557. /* The TLS connection says that it sent a shutdown record, but
  558. * isn't done shutting down yet. Make sure that this hasn't
  559. * happened before, then go back to the start of the function
  560. * and try to read.
  561. */
  562. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  563. tls->state == TOR_TLS_ST_SENTCLOSE) {
  564. log(LOG_WARN, LD_NET,
  565. "TLS returned \"half-closed\" value while already half-closed");
  566. return TOR_TLS_ERROR;
  567. }
  568. tls->state = TOR_TLS_ST_SENTCLOSE;
  569. /* fall through ... */
  570. } else {
  571. return err;
  572. }
  573. } /* end loop */
  574. }
  575. /** Return true iff this TLS connection is authenticated.
  576. */
  577. int
  578. tor_tls_peer_has_cert(tor_tls_t *tls)
  579. {
  580. X509 *cert;
  581. cert = SSL_get_peer_certificate(tls->ssl);
  582. tls_log_errors(LOG_WARN, "getting peer certificate");
  583. if (!cert)
  584. return 0;
  585. X509_free(cert);
  586. return 1;
  587. }
  588. /** Write the nickname (if any) that the peer connected on <b>tls</b>
  589. * claims to have into the first <b>buflen</b> characters of <b>buf</b>.
  590. * Truncate the nickname if it is longer than buflen-1 characters. Always
  591. * NUL-terminate. Return 0 on success, -1 on failure.
  592. */
  593. int
  594. tor_tls_get_peer_cert_nickname(int severity, tor_tls_t *tls,
  595. char *buf, size_t buflen)
  596. {
  597. X509 *cert = NULL;
  598. X509_NAME *name = NULL;
  599. int nid;
  600. int lenout;
  601. int r = -1;
  602. if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
  603. log_fn(severity, LD_PROTOCOL, "Peer has no certificate");
  604. goto error;
  605. }
  606. if (!(name = X509_get_subject_name(cert))) {
  607. log_fn(severity, LD_PROTOCOL, "Peer certificate has no subject name");
  608. goto error;
  609. }
  610. if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
  611. goto error;
  612. lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
  613. if (lenout == -1)
  614. goto error;
  615. if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
  616. log_fn(severity, LD_PROTOCOL,
  617. "Peer certificate nickname %s has illegal characters.",
  618. escaped(buf));
  619. if (strchr(buf, '.'))
  620. log_fn(severity, LD_PROTOCOL,
  621. " (Maybe it is not really running Tor at its "
  622. "advertised OR port.)");
  623. goto error;
  624. }
  625. r = 0;
  626. error:
  627. if (cert)
  628. X509_free(cert);
  629. tls_log_errors(severity, "getting peer certificate nickname");
  630. return r;
  631. }
  632. static void
  633. log_cert_lifetime(X509 *cert, const char *problem)
  634. {
  635. BIO *bio = NULL;
  636. BUF_MEM *buf;
  637. char *s1=NULL, *s2=NULL;
  638. char mytime[33];
  639. time_t now = time(NULL);
  640. struct tm tm;
  641. if (problem)
  642. log_warn(LD_GENERAL,
  643. "Certificate %s: is your system clock set incorrectly?",
  644. problem);
  645. if (!(bio = BIO_new(BIO_s_mem()))) {
  646. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  647. }
  648. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  649. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  650. goto end;
  651. }
  652. BIO_get_mem_ptr(bio, &buf);
  653. s1 = tor_strndup(buf->data, buf->length);
  654. (void)BIO_reset(bio);
  655. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  656. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  657. goto end;
  658. }
  659. BIO_get_mem_ptr(bio, &buf);
  660. s2 = tor_strndup(buf->data, buf->length);
  661. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  662. log_warn(LD_GENERAL,
  663. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  664. s1,s2,mytime);
  665. end:
  666. /* Not expected to get invoked */
  667. tls_log_errors(LOG_WARN, "getting certificate lifetime");
  668. if (bio)
  669. BIO_free(bio);
  670. if (s1)
  671. tor_free(s1);
  672. if (s2)
  673. tor_free(s2);
  674. }
  675. /** If the provided tls connection is authenticated and has a
  676. * certificate that is currently valid and signed, then set
  677. * *<b>identity_key</b> to the identity certificate's key and return
  678. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  679. */
  680. int
  681. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  682. {
  683. X509 *cert = NULL, *id_cert = NULL;
  684. STACK_OF(X509) *chain = NULL;
  685. EVP_PKEY *id_pkey = NULL;
  686. RSA *rsa;
  687. int num_in_chain;
  688. int r = -1, i;
  689. *identity_key = NULL;
  690. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  691. goto done;
  692. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  693. goto done;
  694. num_in_chain = sk_X509_num(chain);
  695. /* 1 means we're receiving (server-side), and it's just the id_cert.
  696. * 2 means we're connecting (client-side), and it's both the link
  697. * cert and the id_cert.
  698. */
  699. if (num_in_chain < 1) {
  700. log_fn(severity,LD_PROTOCOL,
  701. "Unexpected number of certificates in chain (%d)",
  702. num_in_chain);
  703. goto done;
  704. }
  705. for (i=0; i<num_in_chain; ++i) {
  706. id_cert = sk_X509_value(chain, i);
  707. if (X509_cmp(id_cert, cert) != 0)
  708. break;
  709. }
  710. if (!id_cert) {
  711. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  712. goto done;
  713. }
  714. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  715. X509_verify(cert, id_pkey) <= 0) {
  716. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  717. tls_log_errors(severity,"verifying certificate");
  718. goto done;
  719. }
  720. rsa = EVP_PKEY_get1_RSA(id_pkey);
  721. if (!rsa)
  722. goto done;
  723. *identity_key = _crypto_new_pk_env_rsa(rsa);
  724. r = 0;
  725. done:
  726. if (cert)
  727. X509_free(cert);
  728. if (id_pkey)
  729. EVP_PKEY_free(id_pkey);
  730. /* This should never get invoked, but let's make sure in case OpenSSL
  731. * acts unexpectedly. */
  732. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  733. return r;
  734. }
  735. /** Check whether the certificate set on the connection <b>tls</b> is
  736. * expired or not-yet-valid, give or take <b>tolerance</b>
  737. * seconds. Return 0 for valid, -1 for failure.
  738. *
  739. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  740. */
  741. int
  742. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  743. {
  744. time_t now, t;
  745. X509 *cert;
  746. int r = -1;
  747. now = time(NULL);
  748. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  749. goto done;
  750. t = now + tolerance;
  751. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  752. log_cert_lifetime(cert, "not yet valid");
  753. goto done;
  754. }
  755. t = now - tolerance;
  756. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  757. log_cert_lifetime(cert, "already expired");
  758. goto done;
  759. }
  760. r = 0;
  761. done:
  762. if (cert)
  763. X509_free(cert);
  764. /* Not expected to get invoked */
  765. tls_log_errors(LOG_WARN, "checking certificate lifetime");
  766. return r;
  767. }
  768. /** Return the number of bytes available for reading from <b>tls</b>.
  769. */
  770. int
  771. tor_tls_get_pending_bytes(tor_tls_t *tls)
  772. {
  773. tor_assert(tls);
  774. #if OPENSSL_VERSION_NUMBER < 0x0090700fl
  775. if (tls->ssl->rstate == SSL_ST_READ_BODY)
  776. return 0;
  777. if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
  778. return 0;
  779. #endif
  780. return SSL_pending(tls->ssl);
  781. }
  782. /** Return the number of bytes read across the underlying socket. */
  783. unsigned long
  784. tor_tls_get_n_bytes_read(tor_tls_t *tls)
  785. {
  786. tor_assert(tls);
  787. return BIO_number_read(SSL_get_rbio(tls->ssl));
  788. }
  789. /** Return the number of bytes written across the underlying socket. */
  790. unsigned long
  791. tor_tls_get_n_bytes_written(tor_tls_t *tls)
  792. {
  793. tor_assert(tls);
  794. return BIO_number_written(SSL_get_wbio(tls->ssl));
  795. }
  796. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  797. * errors, log an error message. */
  798. void
  799. _check_no_tls_errors(const char *fname, int line)
  800. {
  801. if (ERR_peek_error() == 0)
  802. return;
  803. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  804. tor_fix_source_file(fname), line);
  805. tls_log_errors(LOG_WARN, NULL);
  806. }