tortls.c 14 KB

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