tortls.c 27 KB

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