tortls.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. /* Copyright 2003 Roger Dingledine. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /* TLS wrappers for The Onion Router. (Unlike other tor functions, these
  5. * are prefixed with tor_ in order to avoid conflicting with OpenSSL
  6. * functions and variables.)
  7. */
  8. #include "./crypto.h"
  9. #include "./tortls.h"
  10. #include "./util.h"
  11. #include "./log.h"
  12. #include <string.h>
  13. /* Copied from or.h */
  14. #define LEGAL_NICKNAME_CHARACTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  15. #include <assert.h>
  16. #include <openssl/ssl.h>
  17. #include <openssl/err.h>
  18. #include <openssl/tls1.h>
  19. #include <openssl/asn1.h>
  20. #include <openssl/bio.h>
  21. /* How long do certificates live? (sec) */
  22. #define CERT_LIFETIME (365*24*60*60)
  23. /* How much clock skew do we tolerate when checking certificates? (sec) */
  24. #define CERT_ALLOW_SKEW (90*60)
  25. struct tor_tls_context_st {
  26. SSL_CTX *ctx;
  27. };
  28. struct tor_tls_st {
  29. SSL *ssl;
  30. int socket;
  31. enum {
  32. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  33. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
  34. } state;
  35. int isServer;
  36. int wantwrite_n; /* 0 normally, >0 if we returned wantwrite last time */
  37. };
  38. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  39. const char *nickname);
  40. /* global tls context, keep it here because nobody else needs to touch it */
  41. static tor_tls_context *global_tls_context = NULL;
  42. static int tls_library_is_initialized = 0;
  43. #define _TOR_TLS_SYSCALL -6
  44. #define _TOR_TLS_ZERORETURN -5
  45. /* These functions are declared in crypto.c but not exported. */
  46. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env);
  47. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
  48. DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
  49. static void
  50. tls_log_errors(int severity, const char *doing)
  51. {
  52. int err;
  53. const char *msg, *lib, *func;
  54. while ((err = ERR_get_error()) != 0) {
  55. msg = (const char*)ERR_reason_error_string(err);
  56. lib = (const char*)ERR_lib_error_string(err);
  57. func = (const char*)ERR_func_error_string(err);
  58. if (!msg) msg = "(null)";
  59. if (doing) {
  60. log(severity, "TLS error while %s: %s (in %s:%s)", doing, msg, lib,func);
  61. } else {
  62. log(severity, "TLS error: %s (in %s:%s)", msg, lib, func);
  63. }
  64. }
  65. }
  66. #define CATCH_SYSCALL 1
  67. #define CATCH_ZERO 2
  68. static int
  69. tor_tls_get_error(tor_tls *tls, int r, int extra,
  70. const char *doing, int severity)
  71. {
  72. int err = SSL_get_error(tls->ssl, r);
  73. switch (err) {
  74. case SSL_ERROR_NONE:
  75. return TOR_TLS_DONE;
  76. case SSL_ERROR_WANT_READ:
  77. return TOR_TLS_WANTREAD;
  78. case SSL_ERROR_WANT_WRITE:
  79. return TOR_TLS_WANTWRITE;
  80. case SSL_ERROR_SYSCALL:
  81. if (extra&CATCH_SYSCALL)
  82. return _TOR_TLS_SYSCALL;
  83. log(severity, "TLS error: <syscall error> (errno=%d)",errno);
  84. tls_log_errors(severity, doing);
  85. return TOR_TLS_ERROR;
  86. case SSL_ERROR_ZERO_RETURN:
  87. if (extra&CATCH_ZERO)
  88. return _TOR_TLS_ZERORETURN;
  89. log(severity, "TLS error: Zero return");
  90. tls_log_errors(severity, doing);
  91. return TOR_TLS_ERROR;
  92. default:
  93. tls_log_errors(severity, doing);
  94. return TOR_TLS_ERROR;
  95. }
  96. }
  97. static void
  98. tor_tls_init() {
  99. if (!tls_library_is_initialized) {
  100. SSL_library_init();
  101. SSL_load_error_strings();
  102. crypto_global_init();
  103. OpenSSL_add_all_algorithms();
  104. tls_library_is_initialized = 1;
  105. }
  106. }
  107. static int always_accept_verify_cb(int preverify_ok,
  108. X509_STORE_CTX *x509_ctx)
  109. {
  110. /* We always accept peer certs and complete the handshake. We don't validate
  111. * them until later. */
  112. return 1;
  113. }
  114. /* Generate a self-signed certificate with the private key 'rsa' and
  115. * commonName 'nickname', and write it, PEM-encoded, to the file named
  116. * by 'certfile'. Return 0 on success, -1 for failure.
  117. */
  118. X509 *
  119. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  120. const char *nickname)
  121. {
  122. time_t start_time, end_time;
  123. EVP_PKEY *pkey = NULL;
  124. X509 *x509 = NULL;
  125. X509_NAME *name = NULL;
  126. int nid;
  127. tor_tls_init();
  128. start_time = time(NULL);
  129. assert(rsa && nickname);
  130. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa)))
  131. return NULL;
  132. if (!(x509 = X509_new()))
  133. goto error;
  134. if (!(X509_set_version(x509, 2)))
  135. goto error;
  136. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  137. goto error;
  138. if (!(name = X509_NAME_new()))
  139. goto error;
  140. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
  141. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  142. "TOR", -1, -1, 0))) goto error;
  143. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  144. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  145. (char*)nickname, -1, -1, 0))) goto error;
  146. if (!(X509_set_issuer_name(x509, name)))
  147. goto error;
  148. if (!(X509_set_subject_name(x509, name)))
  149. goto error;
  150. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  151. goto error;
  152. end_time = start_time + CERT_LIFETIME;
  153. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  154. goto error;
  155. if (!X509_set_pubkey(x509, pkey))
  156. goto error;
  157. if (!X509_sign(x509, pkey, EVP_sha1()))
  158. goto error;
  159. goto done;
  160. error:
  161. if (x509) {
  162. X509_free(x509);
  163. x509 = NULL;
  164. }
  165. done:
  166. if (pkey)
  167. EVP_PKEY_free(pkey);
  168. if (name)
  169. X509_NAME_free(name);
  170. return x509;
  171. }
  172. #ifdef EVERYONE_HAS_AES
  173. /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
  174. * is needed. */
  175. #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
  176. #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
  177. /* Some people are running OpenSSL before 0.9.7, but we aren't.
  178. * We can support AES and 3DES.
  179. */
  180. #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  181. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  182. #else
  183. /* We're running OpenSSL before 0.9.7. We only support 3DES. */
  184. #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
  185. #endif
  186. /* Create a new TLS context. If we are going to be using it as a
  187. * server, it must have isServer set to true, certfile set to a
  188. * filename for a certificate file, and RSA set to the private key
  189. * used for that certificate. Return -1 if failure, else 0.
  190. */
  191. int
  192. tor_tls_context_new(crypto_pk_env_t *rsa,
  193. int isServer, const char *nickname)
  194. {
  195. crypto_dh_env_t *dh = NULL;
  196. EVP_PKEY *pkey = NULL;
  197. tor_tls_context *result;
  198. X509 *cert = NULL;
  199. tor_tls_init();
  200. if (rsa) {
  201. cert = tor_tls_create_certificate(rsa, nickname);
  202. if (!cert) {
  203. log(LOG_WARN, "Error creating certificate");
  204. return -1;
  205. }
  206. }
  207. result = tor_malloc(sizeof(tor_tls_context));
  208. result->ctx = NULL;
  209. #ifdef EVERYONE_HAS_AES
  210. /* Tell OpenSSL to only use TLS1 */
  211. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  212. goto error;
  213. #else
  214. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  215. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  216. goto error;
  217. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  218. #endif
  219. if (!SSL_CTX_set_cipher_list(result->ctx, CIPHER_LIST))
  220. goto error;
  221. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  222. goto error;
  223. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  224. if (rsa) {
  225. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa)))
  226. goto error;
  227. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  228. goto error;
  229. EVP_PKEY_free(pkey);
  230. pkey = NULL;
  231. if (cert) {
  232. if (!SSL_CTX_check_private_key(result->ctx))
  233. goto error;
  234. }
  235. }
  236. dh = crypto_dh_new();
  237. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  238. crypto_dh_free(dh);
  239. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  240. always_accept_verify_cb);
  241. /* let us realloc bufs that we're writing from */
  242. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  243. /* Free the old context if one exists. */
  244. if (global_tls_context) {
  245. /* This is safe even if there are open connections: OpenSSL does
  246. * reference counting with SSL and SSL_CTX objects. */
  247. SSL_CTX_free(global_tls_context->ctx);
  248. free(global_tls_context);
  249. }
  250. global_tls_context = result;
  251. return 0;
  252. error:
  253. if (pkey)
  254. EVP_PKEY_free(pkey);
  255. if (dh)
  256. crypto_dh_free(dh);
  257. if (result && result->ctx)
  258. SSL_CTX_free(result->ctx);
  259. if (result)
  260. free(result);
  261. return -1;
  262. }
  263. /* Create a new TLS object from a TLS context, a filedescriptor, and
  264. * a flag to determine whether it is functioning as a server.
  265. */
  266. tor_tls *
  267. tor_tls_new(int sock, int isServer)
  268. {
  269. tor_tls *result = tor_malloc(sizeof(tor_tls));
  270. assert(global_tls_context); /* make sure somebody made it first */
  271. if (!(result->ssl = SSL_new(global_tls_context->ctx)))
  272. return NULL;
  273. result->socket = sock;
  274. SSL_set_fd(result->ssl, sock);
  275. result->state = TOR_TLS_ST_HANDSHAKE;
  276. result->isServer = isServer;
  277. result->wantwrite_n = 0;
  278. return result;
  279. }
  280. /* Release resources associated with a TLS object. Does not close the
  281. * underlying file descriptor.
  282. */
  283. void
  284. tor_tls_free(tor_tls *tls)
  285. {
  286. SSL_free(tls->ssl);
  287. free(tls);
  288. }
  289. /* Underlying function for TLS reading. Reads up to 'len' characters
  290. * from 'tls' into 'cp'. On success, returns the number of characters
  291. * read. On failure, returns TOR_TLS_ERROR, TOR_TLS_CLOSE,
  292. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  293. */
  294. int
  295. tor_tls_read(tor_tls *tls, char *cp, int len)
  296. {
  297. int r, err;
  298. assert(tls && tls->ssl);
  299. assert(tls->state == TOR_TLS_ST_OPEN);
  300. r = SSL_read(tls->ssl, cp, len);
  301. if (r > 0)
  302. return r;
  303. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
  304. if (err == _TOR_TLS_ZERORETURN) {
  305. tls->state = TOR_TLS_ST_CLOSED;
  306. return TOR_TLS_CLOSE;
  307. } else {
  308. assert(err != TOR_TLS_DONE);
  309. return err;
  310. }
  311. }
  312. /* Underlying function for TLS writing. Write up to 'n' characters
  313. * from 'cp' onto 'tls'. On success, returns the number of characters
  314. * written. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  315. * or TOR_TLS_WANTWRITE.
  316. */
  317. int
  318. tor_tls_write(tor_tls *tls, char *cp, int n)
  319. {
  320. int r, err;
  321. assert(tls && tls->ssl);
  322. assert(tls->state == TOR_TLS_ST_OPEN);
  323. if (n == 0)
  324. return 0;
  325. if(tls->wantwrite_n) {
  326. /* if WANTWRITE last time, we must use the _same_ n as before */
  327. assert(n >= tls->wantwrite_n);
  328. log_fn(LOG_INFO,"resuming pending-write, (%d to flush, reusing %d)",
  329. n, tls->wantwrite_n);
  330. n = tls->wantwrite_n;
  331. tls->wantwrite_n = 0;
  332. }
  333. r = SSL_write(tls->ssl, cp, n);
  334. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  335. if (err == TOR_TLS_DONE) {
  336. return r;
  337. }
  338. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  339. // log_fn(LOG_INFO,"wantwrite or wantread. remembering the number %d.",n);
  340. tls->wantwrite_n = n;
  341. }
  342. return err;
  343. }
  344. /* Perform initial handshake on 'tls'. When finished, returns
  345. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  346. * or TOR_TLS_WANTWRITE.
  347. */
  348. int
  349. tor_tls_handshake(tor_tls *tls)
  350. {
  351. int r;
  352. assert(tls && tls->ssl);
  353. assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  354. if (tls->isServer) {
  355. r = SSL_accept(tls->ssl);
  356. } else {
  357. r = SSL_connect(tls->ssl);
  358. }
  359. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  360. if (r == TOR_TLS_DONE) {
  361. tls->state = TOR_TLS_ST_OPEN;
  362. }
  363. return r;
  364. }
  365. /* Shut down an open tls connection 'tls'. When finished, returns
  366. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  367. * or TOR_TLS_WANTWRITE.
  368. */
  369. int
  370. tor_tls_shutdown(tor_tls *tls)
  371. {
  372. int r, err;
  373. char buf[128];
  374. assert(tls && tls->ssl);
  375. while (1) {
  376. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  377. /* If we've already called shutdown once to send a close message,
  378. * we read until the other side has closed too.
  379. */
  380. do {
  381. r = SSL_read(tls->ssl, buf, 128);
  382. } while (r>0);
  383. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  384. LOG_INFO);
  385. if (err == _TOR_TLS_ZERORETURN) {
  386. tls->state = TOR_TLS_ST_GOTCLOSE;
  387. /* fall through... */
  388. } else {
  389. return err;
  390. }
  391. }
  392. r = SSL_shutdown(tls->ssl);
  393. if (r == 1) {
  394. /* If shutdown returns 1, the connection is entirely closed. */
  395. tls->state = TOR_TLS_ST_CLOSED;
  396. return TOR_TLS_DONE;
  397. }
  398. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  399. LOG_INFO);
  400. if (err == _TOR_TLS_SYSCALL) {
  401. /* The underlying TCP connection closed while we were shutting down. */
  402. tls->state = TOR_TLS_ST_CLOSED;
  403. return TOR_TLS_DONE;
  404. } else if (err == _TOR_TLS_ZERORETURN) {
  405. /* The TLS connection says that it sent a shutdown record, but
  406. * isn't done shutting down yet. Make sure that this hasn't
  407. * happened before, then go back to the start of the function
  408. * and try to read.
  409. */
  410. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  411. tls->state == TOR_TLS_ST_SENTCLOSE) {
  412. log(LOG_WARN,
  413. "TLS returned \"half-closed\" value while already half-closed");
  414. return TOR_TLS_ERROR;
  415. }
  416. tls->state = TOR_TLS_ST_SENTCLOSE;
  417. /* fall through ... */
  418. } else {
  419. return err;
  420. }
  421. } /* end loop */
  422. }
  423. /* Return true iff this TLS connection is authenticated.
  424. */
  425. int
  426. tor_tls_peer_has_cert(tor_tls *tls)
  427. {
  428. X509 *cert;
  429. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  430. return 0;
  431. X509_free(cert);
  432. return 1;
  433. }
  434. int
  435. tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, int buflen)
  436. {
  437. X509 *cert = NULL;
  438. X509_NAME *name = NULL;
  439. int nid;
  440. int lenout;
  441. if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
  442. log_fn(LOG_WARN, "Peer has no certificate");
  443. goto error;
  444. }
  445. if (!(name = X509_get_subject_name(cert))) {
  446. log_fn(LOG_WARN, "Peer certificate has no subject name");
  447. goto error;
  448. }
  449. if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
  450. goto error;
  451. lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
  452. if (lenout == -1)
  453. goto error;
  454. if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
  455. log_fn(LOG_WARN, "Peer certificate nickname has illegal characters.");
  456. goto error;
  457. }
  458. return 0;
  459. error:
  460. if (cert)
  461. X509_free(cert);
  462. if (name)
  463. X509_NAME_free(name);
  464. return -1;
  465. }
  466. /* If the provided tls connection is authenticated and has a
  467. * certificate that is currently valid and is correctly self-signed,
  468. * return its public key. Otherwise return NULL.
  469. */
  470. crypto_pk_env_t *
  471. tor_tls_verify(tor_tls *tls)
  472. {
  473. X509 *cert = NULL;
  474. EVP_PKEY *pkey = NULL;
  475. RSA *rsa = NULL;
  476. time_t now, t;
  477. crypto_pk_env_t *r = NULL;
  478. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  479. return NULL;
  480. now = time(NULL);
  481. t = now + CERT_ALLOW_SKEW;
  482. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  483. log_fn(LOG_WARN,"Certificate becomes valid in the future: possible clock skew.");
  484. goto done;
  485. }
  486. t = now - CERT_ALLOW_SKEW;
  487. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  488. log_fn(LOG_WARN,"Certificate already expired; possible clock skew.");
  489. goto done;
  490. }
  491. /* Get the public key. */
  492. if (!(pkey = X509_get_pubkey(cert))) {
  493. log_fn(LOG_WARN,"X509_get_pubkey returned null");
  494. goto done;
  495. }
  496. if (X509_verify(cert, pkey) <= 0) {
  497. log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
  498. goto done;
  499. }
  500. rsa = EVP_PKEY_get1_RSA(pkey);
  501. EVP_PKEY_free(pkey);
  502. pkey = NULL;
  503. if (!rsa) {
  504. log_fn(LOG_WARN,"EVP_PKEY_get1_RSA(pkey) returned null");
  505. goto done;
  506. }
  507. r = _crypto_new_pk_env_rsa(rsa);
  508. rsa = NULL;
  509. done:
  510. if (cert)
  511. X509_free(cert);
  512. if (pkey)
  513. EVP_PKEY_free(pkey);
  514. if (rsa)
  515. RSA_free(rsa);
  516. return r;
  517. }
  518. int
  519. tor_tls_get_pending_bytes(tor_tls *tls)
  520. {
  521. assert(tls);
  522. return SSL_pending(tls->ssl);
  523. }
  524. /* Return the number of bytes read across the underlying socket. */
  525. unsigned long tor_tls_get_n_bytes_read(tor_tls *tls)
  526. {
  527. assert(tls);
  528. return BIO_number_read(SSL_get_rbio(tls->ssl));
  529. }
  530. unsigned long tor_tls_get_n_bytes_written(tor_tls *tls)
  531. {
  532. assert(tls);
  533. return BIO_number_written(SSL_get_wbio(tls->ssl));
  534. }
  535. /*
  536. Local Variables:
  537. mode:c
  538. indent-tabs-mode:nil
  539. c-basic-offset:2
  540. End:
  541. */