tortls.c 15 KB

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