tortls.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. int err;
  126. tor_tls_init();
  127. start_time = time(NULL);
  128. assert(rsa && nickname);
  129. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa)))
  130. return NULL;
  131. if (!(x509 = X509_new()))
  132. goto error;
  133. if (!(X509_set_version(x509, 2)))
  134. goto error;
  135. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  136. goto error;
  137. if (!(name = X509_NAME_new()))
  138. goto error;
  139. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
  140. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  141. "TOR", -1, -1, 0))) goto error;
  142. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  143. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  144. (char*)nickname, -1, -1, 0))) goto error;
  145. if (!(X509_set_issuer_name(x509, name)))
  146. goto error;
  147. if (!(X509_set_subject_name(x509, name)))
  148. goto error;
  149. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  150. goto error;
  151. end_time = start_time + CERT_LIFETIME;
  152. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  153. goto error;
  154. if (!X509_set_pubkey(x509, pkey))
  155. goto error;
  156. if (!X509_sign(x509, pkey, EVP_sha1()))
  157. goto error;
  158. err = 0;
  159. goto done;
  160. error:
  161. err = 1;
  162. done:
  163. if (x509 && err)
  164. X509_free(x509);
  165. if (pkey)
  166. EVP_PKEY_free(pkey);
  167. if (name)
  168. X509_NAME_free(name);
  169. return x509;
  170. }
  171. #ifdef EVERYONE_HAS_AES
  172. /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibiliy
  173. * is needed. */
  174. #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
  175. #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
  176. /* Some people are running OpenSSL before 0.9.7, but we aren't.
  177. * We can support AES and 3DES.
  178. */
  179. #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  180. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  181. #else
  182. /* We're running OpenSSL before 0.9.7. We only support 3DES. */
  183. #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
  184. #endif
  185. /* Create a new TLS context. If we are going to be using it as a
  186. * server, it must have isServer set to true, certfile set to a
  187. * filename for a certificate file, and RSA set to the private key
  188. * used for that certificate. Return -1 if failure, else 0.
  189. */
  190. int
  191. tor_tls_context_new(crypto_pk_env_t *rsa,
  192. int isServer, const char *nickname)
  193. {
  194. crypto_dh_env_t *dh = NULL;
  195. EVP_PKEY *pkey = NULL;
  196. tor_tls_context *result;
  197. X509 *cert = NULL;
  198. tor_tls_init();
  199. if (rsa) {
  200. cert = tor_tls_create_certificate(rsa, nickname);
  201. if (!cert) {
  202. log(LOG_WARN, "Error creating certificate");
  203. return -1;
  204. }
  205. }
  206. result = tor_malloc(sizeof(tor_tls_context));
  207. result->ctx = NULL;
  208. #ifdef EVERYONE_HAS_AES
  209. /* Tell OpenSSL to only use TLS1 */
  210. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  211. goto error;
  212. #else
  213. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  214. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  215. goto error;
  216. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  217. #endif
  218. if (!SSL_CTX_set_cipher_list(result->ctx, CIPHER_LIST))
  219. goto error;
  220. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  221. goto error;
  222. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  223. if (rsa) {
  224. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa)))
  225. goto error;
  226. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  227. goto error;
  228. EVP_PKEY_free(pkey);
  229. pkey = NULL;
  230. if (cert) {
  231. if (!SSL_CTX_check_private_key(result->ctx))
  232. goto error;
  233. }
  234. }
  235. dh = crypto_dh_new();
  236. SSL_CTX_set_tmp_dh(result->ctx, dh->dh);
  237. crypto_dh_free(dh);
  238. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  239. always_accept_verify_cb);
  240. /* let us realloc bufs that we're writing from */
  241. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  242. /* Free the old context if one exists. */
  243. if (global_tls_context) {
  244. /* This is safe even if there are open connections: OpenSSL does
  245. * reference counting with SSL and SSL_CTX objects. */
  246. SSL_CTX_free(global_tls_context->ctx);
  247. free(global_tls_context);
  248. }
  249. global_tls_context = result;
  250. return 0;
  251. error:
  252. if (pkey)
  253. EVP_PKEY_free(pkey);
  254. if (dh)
  255. crypto_dh_free(dh);
  256. if (result && result->ctx)
  257. SSL_CTX_free(result->ctx);
  258. if (result)
  259. free(result);
  260. return -1;
  261. }
  262. /* Create a new TLS object from a TLS context, a filedescriptor, and
  263. * a flag to determine whether it is functioning as a server.
  264. */
  265. tor_tls *
  266. tor_tls_new(int sock, int isServer)
  267. {
  268. tor_tls *result = tor_malloc(sizeof(tor_tls));
  269. assert(global_tls_context); /* make sure somebody made it first */
  270. if (!(result->ssl = SSL_new(global_tls_context->ctx)))
  271. return NULL;
  272. result->socket = sock;
  273. SSL_set_fd(result->ssl, sock);
  274. result->state = TOR_TLS_ST_HANDSHAKE;
  275. result->isServer = isServer;
  276. result->wantwrite_n = 0;
  277. return result;
  278. }
  279. /* Release resources associated with a TLS object. Does not close the
  280. * underlying file descriptor.
  281. */
  282. void
  283. tor_tls_free(tor_tls *tls)
  284. {
  285. SSL_free(tls->ssl);
  286. free(tls);
  287. }
  288. /* Underlying function for TLS reading. Reads up to 'len' characters
  289. * from 'tls' into 'cp'. On success, returns the number of characters
  290. * read. On failure, returns TOR_TLS_ERROR, TOR_TLS_CLOSE,
  291. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  292. */
  293. int
  294. tor_tls_read(tor_tls *tls, char *cp, int len)
  295. {
  296. int r, err;
  297. assert(tls && tls->ssl);
  298. assert(tls->state == TOR_TLS_ST_OPEN);
  299. r = SSL_read(tls->ssl, cp, len);
  300. if (r > 0)
  301. return r;
  302. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
  303. if (err == _TOR_TLS_ZERORETURN) {
  304. tls->state = TOR_TLS_ST_CLOSED;
  305. return TOR_TLS_CLOSE;
  306. } else {
  307. assert(err != TOR_TLS_DONE);
  308. return err;
  309. }
  310. }
  311. /* Underlying function for TLS writing. Write up to 'n' characters
  312. * from 'cp' onto 'tls'. On success, returns the number of characters
  313. * written. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  314. * or TOR_TLS_WANTWRITE.
  315. */
  316. int
  317. tor_tls_write(tor_tls *tls, char *cp, int n)
  318. {
  319. int r, err;
  320. assert(tls && tls->ssl);
  321. assert(tls->state == TOR_TLS_ST_OPEN);
  322. if (n == 0)
  323. return 0;
  324. if(tls->wantwrite_n) {
  325. /* if WANTWRITE last time, we must use the _same_ n as before */
  326. assert(n >= tls->wantwrite_n);
  327. log_fn(LOG_INFO,"resuming pending-write, (%d to flush, reusing %d)",
  328. n, tls->wantwrite_n);
  329. n = tls->wantwrite_n;
  330. tls->wantwrite_n = 0;
  331. }
  332. r = SSL_write(tls->ssl, cp, n);
  333. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  334. if (err == TOR_TLS_DONE) {
  335. return r;
  336. }
  337. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  338. log_fn(LOG_INFO,"wantwrite or wantread. remembering the number %d.",n);
  339. tls->wantwrite_n = n;
  340. }
  341. return err;
  342. }
  343. /* Perform initial handshake on 'tls'. When finished, returns
  344. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  345. * or TOR_TLS_WANTWRITE.
  346. */
  347. int
  348. tor_tls_handshake(tor_tls *tls)
  349. {
  350. int r;
  351. assert(tls && tls->ssl);
  352. assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  353. if (tls->isServer) {
  354. r = SSL_accept(tls->ssl);
  355. } else {
  356. r = SSL_connect(tls->ssl);
  357. }
  358. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  359. if (r == TOR_TLS_DONE) {
  360. tls->state = TOR_TLS_ST_OPEN;
  361. }
  362. return r;
  363. }
  364. /* Shut down an open tls connection 'tls'. When finished, returns
  365. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  366. * or TOR_TLS_WANTWRITE.
  367. */
  368. int
  369. tor_tls_shutdown(tor_tls *tls)
  370. {
  371. int r, err;
  372. char buf[128];
  373. assert(tls && tls->ssl);
  374. while (1) {
  375. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  376. /* If we've already called shutdown once to send a close message,
  377. * we read until the other side has closed too.
  378. */
  379. do {
  380. r = SSL_read(tls->ssl, buf, 128);
  381. } while (r>0);
  382. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  383. LOG_INFO);
  384. if (err == _TOR_TLS_ZERORETURN) {
  385. tls->state = TOR_TLS_ST_GOTCLOSE;
  386. /* fall through... */
  387. } else {
  388. return err;
  389. }
  390. }
  391. r = SSL_shutdown(tls->ssl);
  392. if (r == 1) {
  393. /* If shutdown returns 1, the connection is entirely closed. */
  394. tls->state = TOR_TLS_ST_CLOSED;
  395. return TOR_TLS_DONE;
  396. }
  397. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  398. LOG_INFO);
  399. if (err == _TOR_TLS_SYSCALL) {
  400. /* The underlying TCP connection closed while we were shutting down. */
  401. tls->state = TOR_TLS_ST_CLOSED;
  402. return TOR_TLS_DONE;
  403. } else if (err == _TOR_TLS_ZERORETURN) {
  404. /* The TLS connection says that it sent a shutdown record, but
  405. * isn't done shutting down yet. Make sure that this hasn't
  406. * happened before, then go back to the start of the function
  407. * and try to read.
  408. */
  409. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  410. tls->state == TOR_TLS_ST_SENTCLOSE) {
  411. log(LOG_WARN,
  412. "TLS returned \"half-closed\" value while already half-closed");
  413. return TOR_TLS_ERROR;
  414. }
  415. tls->state = TOR_TLS_ST_SENTCLOSE;
  416. /* fall through ... */
  417. } else {
  418. return err;
  419. }
  420. } /* end loop */
  421. }
  422. /* Return true iff this TLS connection is authenticated.
  423. */
  424. int
  425. tor_tls_peer_has_cert(tor_tls *tls)
  426. {
  427. X509 *cert;
  428. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  429. return 0;
  430. X509_free(cert);
  431. return 1;
  432. }
  433. int
  434. tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, int buflen)
  435. {
  436. X509 *cert = NULL;
  437. X509_NAME *name = NULL;
  438. int nid;
  439. int lenout;
  440. if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
  441. log_fn(LOG_WARN, "Peer has no certificate");
  442. return -1;
  443. }
  444. if (!(name = X509_get_subject_name(cert))) {
  445. log_fn(LOG_WARN, "Peer certificate has no subject name");
  446. return -1;
  447. }
  448. if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
  449. return -1;
  450. lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
  451. if (lenout == -1)
  452. return -1;
  453. if (strspn(buf, LEGAL_NICKNAME_CHARACTERS) != lenout) {
  454. log_fn(LOG_WARN, "Peer certificate nickname has illegal characters.");
  455. return -1;
  456. }
  457. return 0;
  458. }
  459. /* If the provided tls connection is authenticated and has a
  460. * certificate that is currently valid and is correctly self-signed,
  461. * return its public key. Otherwise return NULL.
  462. */
  463. crypto_pk_env_t *
  464. tor_tls_verify(tor_tls *tls)
  465. {
  466. X509 *cert = NULL;
  467. EVP_PKEY *pkey = NULL;
  468. RSA *rsa = NULL;
  469. time_t now, t;
  470. crypto_pk_env_t *r = NULL;
  471. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  472. return NULL;
  473. now = time(NULL);
  474. t = now - CERT_ALLOW_SKEW;
  475. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  476. log_fn(LOG_WARN,"Certificate becomes valid in the future: possible clock skew.");
  477. goto done;
  478. }
  479. t = now + CERT_ALLOW_SKEW;
  480. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  481. log_fn(LOG_WARN,"Certificate already expired; possible clock skew.");
  482. goto done;
  483. }
  484. /* Get the public key. */
  485. if (!(pkey = X509_get_pubkey(cert))) {
  486. log_fn(LOG_WARN,"X509_get_pubkey returned null");
  487. goto done;
  488. }
  489. if (X509_verify(cert, pkey) <= 0) {
  490. log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
  491. goto done;
  492. }
  493. rsa = EVP_PKEY_get1_RSA(pkey);
  494. EVP_PKEY_free(pkey);
  495. pkey = NULL;
  496. if (!rsa) {
  497. log_fn(LOG_WARN,"EVP_PKEY_get1_RSA(pkey) returned null");
  498. goto done;
  499. }
  500. r = _crypto_new_pk_env_rsa(rsa);
  501. rsa = NULL;
  502. done:
  503. if (cert)
  504. X509_free(cert);
  505. if (pkey)
  506. EVP_PKEY_free(pkey);
  507. if (rsa)
  508. RSA_free(rsa);
  509. return r;
  510. }
  511. int
  512. tor_tls_get_pending_bytes(tor_tls *tls)
  513. {
  514. assert(tls);
  515. return SSL_pending(tls->ssl);
  516. }