tortls.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 (2*24*60*60)
  22. /* How much clock skew do we tolerate when checking certificates? (sec) */
  23. #define CERT_ALLOW_SKEW (3*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. global_tls_context = result;
  243. return 0;
  244. error:
  245. if (pkey)
  246. EVP_PKEY_free(pkey);
  247. if (dh)
  248. crypto_dh_free(dh);
  249. if (result && result->ctx)
  250. SSL_CTX_free(result->ctx);
  251. if (result)
  252. free(result);
  253. return -1;
  254. }
  255. /* Create a new TLS object from a TLS context, a filedescriptor, and
  256. * a flag to determine whether it is functioning as a server.
  257. */
  258. tor_tls *
  259. tor_tls_new(int sock, int isServer)
  260. {
  261. tor_tls *result = tor_malloc(sizeof(tor_tls));
  262. assert(global_tls_context); /* make sure somebody made it first */
  263. if (!(result->ssl = SSL_new(global_tls_context->ctx)))
  264. return NULL;
  265. result->socket = sock;
  266. SSL_set_fd(result->ssl, sock);
  267. result->state = TOR_TLS_ST_HANDSHAKE;
  268. result->isServer = isServer;
  269. result->wantwrite_n = 0;
  270. return result;
  271. }
  272. /* Release resources associated with a TLS object. Does not close the
  273. * underlying file descriptor.
  274. */
  275. void
  276. tor_tls_free(tor_tls *tls)
  277. {
  278. SSL_free(tls->ssl);
  279. free(tls);
  280. }
  281. /* Underlying function for TLS reading. Reads up to 'len' characters
  282. * from 'tls' into 'cp'. On success, returns the number of characters
  283. * read. On failure, returns TOR_TLS_ERROR, TOR_TLS_CLOSE,
  284. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  285. */
  286. int
  287. tor_tls_read(tor_tls *tls, char *cp, int len)
  288. {
  289. int r, err;
  290. assert(tls && tls->ssl);
  291. assert(tls->state == TOR_TLS_ST_OPEN);
  292. r = SSL_read(tls->ssl, cp, len);
  293. if (r > 0)
  294. return r;
  295. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
  296. if (err == _TOR_TLS_ZERORETURN) {
  297. tls->state = TOR_TLS_ST_CLOSED;
  298. return TOR_TLS_CLOSE;
  299. } else {
  300. assert(err != TOR_TLS_DONE);
  301. return err;
  302. }
  303. }
  304. /* Underlying function for TLS writing. Write up to 'n' characters
  305. * from 'cp' onto 'tls'. On success, returns the number of characters
  306. * written. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  307. * or TOR_TLS_WANTWRITE.
  308. */
  309. int
  310. tor_tls_write(tor_tls *tls, char *cp, int n)
  311. {
  312. int r, err;
  313. assert(tls && tls->ssl);
  314. assert(tls->state == TOR_TLS_ST_OPEN);
  315. if (n == 0)
  316. return 0;
  317. if(tls->wantwrite_n) {
  318. /* if WANTWRITE last time, we must use the _same_ n as before */
  319. assert(n >= tls->wantwrite_n);
  320. log_fn(LOG_INFO,"resuming pending-write, (%d to flush, reusing %d)",
  321. n, tls->wantwrite_n);
  322. n = tls->wantwrite_n;
  323. tls->wantwrite_n = 0;
  324. }
  325. r = SSL_write(tls->ssl, cp, n);
  326. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  327. if (err == TOR_TLS_DONE) {
  328. return r;
  329. }
  330. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  331. log_fn(LOG_INFO,"wantwrite or wantread. remembering the number %d.",n);
  332. tls->wantwrite_n = n;
  333. }
  334. return err;
  335. }
  336. /* Perform initial handshake on 'tls'. When finished, returns
  337. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  338. * or TOR_TLS_WANTWRITE.
  339. */
  340. int
  341. tor_tls_handshake(tor_tls *tls)
  342. {
  343. int r;
  344. assert(tls && tls->ssl);
  345. assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  346. if (tls->isServer) {
  347. r = SSL_accept(tls->ssl);
  348. } else {
  349. r = SSL_connect(tls->ssl);
  350. }
  351. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  352. if (r == TOR_TLS_DONE) {
  353. tls->state = TOR_TLS_ST_OPEN;
  354. }
  355. return r;
  356. }
  357. /* Shut down an open tls connection 'tls'. When finished, returns
  358. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  359. * or TOR_TLS_WANTWRITE.
  360. */
  361. int
  362. tor_tls_shutdown(tor_tls *tls)
  363. {
  364. int r, err;
  365. char buf[128];
  366. assert(tls && tls->ssl);
  367. while (1) {
  368. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  369. /* If we've already called shutdown once to send a close message,
  370. * we read until the other side has closed too.
  371. */
  372. do {
  373. r = SSL_read(tls->ssl, buf, 128);
  374. } while (r>0);
  375. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  376. LOG_INFO);
  377. if (err == _TOR_TLS_ZERORETURN) {
  378. tls->state = TOR_TLS_ST_GOTCLOSE;
  379. /* fall through... */
  380. } else {
  381. return err;
  382. }
  383. }
  384. r = SSL_shutdown(tls->ssl);
  385. if (r == 1) {
  386. /* If shutdown returns 1, the connection is entirely closed. */
  387. tls->state = TOR_TLS_ST_CLOSED;
  388. return TOR_TLS_DONE;
  389. }
  390. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  391. LOG_INFO);
  392. if (err == _TOR_TLS_SYSCALL) {
  393. /* The underlying TCP connection closed while we were shutting down. */
  394. tls->state = TOR_TLS_ST_CLOSED;
  395. return TOR_TLS_DONE;
  396. } else if (err == _TOR_TLS_ZERORETURN) {
  397. /* The TLS connection says that it sent a shutdown record, but
  398. * isn't done shutting down yet. Make sure that this hasn't
  399. * happened before, then go back to the start of the function
  400. * and try to read.
  401. */
  402. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  403. tls->state == TOR_TLS_ST_SENTCLOSE) {
  404. log(LOG_WARN,
  405. "TLS returned \"half-closed\" value while already half-closed");
  406. return TOR_TLS_ERROR;
  407. }
  408. tls->state = TOR_TLS_ST_SENTCLOSE;
  409. /* fall through ... */
  410. } else {
  411. return err;
  412. }
  413. } /* end loop */
  414. }
  415. /* Return true iff this TLS connection is authenticated.
  416. */
  417. int
  418. tor_tls_peer_has_cert(tor_tls *tls)
  419. {
  420. X509 *cert;
  421. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  422. return 0;
  423. X509_free(cert);
  424. return 1;
  425. }
  426. int
  427. tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, int buflen)
  428. {
  429. X509 *cert = NULL;
  430. X509_NAME *name = NULL;
  431. int nid;
  432. int lenout;
  433. if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
  434. log_fn(LOG_WARN, "Peer has no certificate");
  435. return -1;
  436. }
  437. if (!(name = X509_get_subject_name(cert))) {
  438. log_fn(LOG_WARN, "Peer certificate has no subject name");
  439. return -1;
  440. }
  441. if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
  442. return -1;
  443. lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
  444. if (lenout == -1)
  445. return -1;
  446. if (strspn(buf, LEGAL_NICKNAME_CHARACTERS) != lenout) {
  447. log_fn(LOG_WARN, "Peer certificate nickname has illegal characters.");
  448. return -1;
  449. }
  450. return 0;
  451. }
  452. /* If the provided tls connection is authenticated and has a
  453. * certificate that is currently valid and is correctly self-signed,
  454. * return its public key. Otherwise return NULL.
  455. */
  456. crypto_pk_env_t *
  457. tor_tls_verify(tor_tls *tls)
  458. {
  459. X509 *cert = NULL;
  460. EVP_PKEY *pkey = NULL;
  461. RSA *rsa = NULL;
  462. time_t now, t;
  463. crypto_pk_env_t *r = NULL;
  464. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  465. return NULL;
  466. now = time(NULL);
  467. t = now - CERT_ALLOW_SKEW;
  468. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  469. log_fn(LOG_WARN,"Certificate becomes valid in the future: possible clock skew.");
  470. goto done;
  471. }
  472. t = now + CERT_ALLOW_SKEW;
  473. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  474. log_fn(LOG_WARN,"Certificate already expired; possible clock skew.");
  475. goto done;
  476. }
  477. /* Get the public key. */
  478. if (!(pkey = X509_get_pubkey(cert))) {
  479. log_fn(LOG_WARN,"X509_get_pubkey returned null");
  480. goto done;
  481. }
  482. if (X509_verify(cert, pkey) <= 0) {
  483. log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
  484. goto done;
  485. }
  486. rsa = EVP_PKEY_get1_RSA(pkey);
  487. EVP_PKEY_free(pkey);
  488. pkey = NULL;
  489. if (!rsa) {
  490. log_fn(LOG_WARN,"EVP_PKEY_get1_RSA(pkey) returned null");
  491. goto done;
  492. }
  493. r = _crypto_new_pk_env_rsa(rsa);
  494. rsa = NULL;
  495. done:
  496. if (cert)
  497. X509_free(cert);
  498. if (pkey)
  499. EVP_PKEY_free(pkey);
  500. if (rsa)
  501. RSA_free(rsa);
  502. return r;
  503. }
  504. int
  505. tor_tls_get_pending_bytes(tor_tls *tls)
  506. {
  507. assert(tls);
  508. return SSL_pending(tls->ssl);
  509. }