tortls.c 26 KB

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