tortls.c 26 KB

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