tortls.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. struct tor_tls_context_st {
  21. SSL_CTX *ctx;
  22. };
  23. struct tor_tls_st {
  24. SSL *ssl;
  25. int socket;
  26. enum {
  27. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  28. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
  29. } state;
  30. int isServer;
  31. int wantwrite_n; /* 0 normally, >0 if we returned wantwrite last time */
  32. };
  33. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  34. const char *nickname);
  35. /* global tls context, keep it here because nobody else needs to touch it */
  36. static tor_tls_context *global_tls_context=NULL;
  37. static int tls_library_is_initialized = 0;
  38. #define _TOR_TLS_SYSCALL -6
  39. #define _TOR_TLS_ZERORETURN -5
  40. /* These functions are declared in crypto.c but not exported. */
  41. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env);
  42. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
  43. static void
  44. tls_log_errors(int severity, const char *doing)
  45. {
  46. int err;
  47. const char *msg, *lib, *func;
  48. while ((err = ERR_get_error()) != 0) {
  49. msg = (const char*)ERR_reason_error_string(err);
  50. lib = (const char*)ERR_lib_error_string(err);
  51. func = (const char*)ERR_func_error_string(err);
  52. if (!msg) msg = "(null)";
  53. if (doing) {
  54. log(severity, "TLS error while %s: %s (in %s:%s)", doing, msg, lib,func);
  55. } else {
  56. log(severity, "TLS error: %s (in %s:%s)", msg, lib, func);
  57. }
  58. }
  59. }
  60. #define CATCH_SYSCALL 1
  61. #define CATCH_ZERO 2
  62. static int
  63. tor_tls_get_error(tor_tls *tls, int r, int extra,
  64. const char *doing, int severity)
  65. {
  66. int err = SSL_get_error(tls->ssl, r);
  67. switch (err) {
  68. case SSL_ERROR_NONE:
  69. return TOR_TLS_DONE;
  70. case SSL_ERROR_WANT_READ:
  71. return TOR_TLS_WANTREAD;
  72. case SSL_ERROR_WANT_WRITE:
  73. return TOR_TLS_WANTWRITE;
  74. case SSL_ERROR_SYSCALL:
  75. if (extra&CATCH_SYSCALL)
  76. return _TOR_TLS_SYSCALL;
  77. log(severity, "TLS error: <syscall error> (errno=%d)",errno);
  78. tls_log_errors(severity, doing);
  79. return TOR_TLS_ERROR;
  80. case SSL_ERROR_ZERO_RETURN:
  81. if (extra&CATCH_ZERO)
  82. return _TOR_TLS_ZERORETURN;
  83. log(severity, "TLS error: Zero return");
  84. tls_log_errors(severity, doing);
  85. return TOR_TLS_ERROR;
  86. default:
  87. tls_log_errors(severity, doing);
  88. return TOR_TLS_ERROR;
  89. }
  90. }
  91. static void
  92. tor_tls_init() {
  93. if (!tls_library_is_initialized) {
  94. SSL_library_init();
  95. SSL_load_error_strings();
  96. crypto_global_init();
  97. OpenSSL_add_all_algorithms();
  98. tls_library_is_initialized = 1;
  99. }
  100. }
  101. static int always_accept_verify_cb(int preverify_ok,
  102. X509_STORE_CTX *x509_ctx)
  103. {
  104. /* We always accept peer certs and complete the handshake. We don't validate
  105. * them until later. */
  106. return 1;
  107. }
  108. /* Generate a self-signed certificate with the private key 'rsa' and
  109. * commonName 'nickname', and write it, PEM-encoded, to the file named
  110. * by 'certfile'. Return 0 on success, -1 for failure.
  111. */
  112. X509 *
  113. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  114. const char *nickname)
  115. {
  116. time_t start_time, end_time;
  117. EVP_PKEY *pkey = NULL;
  118. X509 *x509 = NULL;
  119. X509_NAME *name = 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 (x509 && err)
  160. X509_free(x509);
  161. if (pkey)
  162. EVP_PKEY_free(pkey);
  163. if (name)
  164. X509_NAME_free(name);
  165. return x509;
  166. }
  167. #ifdef EVERYONE_HAS_AES
  168. /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibiliy
  169. * is needed. */
  170. #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
  171. #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
  172. /* Some people are running OpenSSL before 0.9.7, but we aren't.
  173. * We can support AES and 3DES.
  174. */
  175. #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  176. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  177. #else
  178. /* We're running OpenSSL before 0.9.7. We only support 3DES. */
  179. #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
  180. #endif
  181. /* Create a new TLS context. If we are going to be using it as a
  182. * server, it must have isServer set to true, certfile set to a
  183. * filename for a certificate file, and RSA set to the private key
  184. * used for that certificate. Return -1 if failure, else 0.
  185. */
  186. int
  187. tor_tls_context_new(crypto_pk_env_t *rsa,
  188. int isServer, const char *nickname)
  189. {
  190. crypto_dh_env_t *dh = NULL;
  191. EVP_PKEY *pkey = NULL;
  192. tor_tls_context *result;
  193. X509 *cert = NULL;
  194. tor_tls_init();
  195. if (rsa) {
  196. cert = tor_tls_create_certificate(rsa, nickname);
  197. if (!cert) {
  198. log(LOG_WARN, "Error creating certificate");
  199. return -1;
  200. }
  201. }
  202. result = tor_malloc(sizeof(tor_tls_context));
  203. result->ctx = NULL;
  204. #ifdef EVERYONE_HAS_AES
  205. /* Tell OpenSSL to only use TLS1 */
  206. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  207. goto error;
  208. #else
  209. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  210. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  211. goto error;
  212. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  213. #endif
  214. if (!SSL_CTX_set_cipher_list(result->ctx, CIPHER_LIST))
  215. goto error;
  216. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  217. goto error;
  218. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  219. if (rsa) {
  220. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa)))
  221. goto error;
  222. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  223. goto error;
  224. EVP_PKEY_free(pkey);
  225. pkey = NULL;
  226. if (cert) {
  227. if (!SSL_CTX_check_private_key(result->ctx))
  228. goto error;
  229. }
  230. }
  231. dh = crypto_dh_new();
  232. SSL_CTX_set_tmp_dh(result->ctx, dh->dh);
  233. crypto_dh_free(dh);
  234. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  235. always_accept_verify_cb);
  236. /* let us realloc bufs that we're writing from */
  237. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  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 || err == TOR_TLS_WANTREAD) {
  327. log_fn(LOG_INFO,"wantwrite or wantread. 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. int
  423. tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, int buflen)
  424. {
  425. X509 *cert = NULL;
  426. X509_NAME *name = NULL;
  427. int nid;
  428. int lenout;
  429. int i;
  430. if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
  431. log_fn(LOG_WARN, "Peer has no certificate");
  432. return -1;
  433. }
  434. if (!(name = X509_get_subject_name(cert))) {
  435. log_fn(LOG_WARN, "Peer certificate has no subject name");
  436. return -1;
  437. }
  438. if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
  439. return -1;
  440. lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
  441. if (lenout == -1)
  442. return -1;
  443. if (strspn(buf, LEGAL_NICKNAME_CHARACTERS) != lenout) {
  444. log_fn(LOG_WARN, "Peer certificate nickname has illegal characters.");
  445. return -1;
  446. }
  447. return 0;
  448. }
  449. /* If the provided tls connection is authenticated and has a
  450. * certificate that is currently valid and is correctly self-signed,
  451. * return its public key. Otherwise return NULL.
  452. */
  453. crypto_pk_env_t *
  454. tor_tls_verify(tor_tls *tls)
  455. {
  456. X509 *cert = NULL;
  457. EVP_PKEY *pkey = NULL;
  458. RSA *rsa = NULL;
  459. time_t now;
  460. crypto_pk_env_t *r = NULL;
  461. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  462. return NULL;
  463. now = time(NULL);
  464. if (X509_cmp_time(X509_get_notBefore(cert), &now) > 0) {
  465. log_fn(LOG_WARN,"X509_get_notBefore(cert) is in the future");
  466. goto done;
  467. }
  468. if (X509_cmp_time(X509_get_notAfter(cert), &now) < 0) {
  469. log_fn(LOG_WARN,"X509_get_notAfter(cert) is in the past");
  470. goto done;
  471. }
  472. /* Get the public key. */
  473. if (!(pkey = X509_get_pubkey(cert))) {
  474. log_fn(LOG_WARN,"X509_get_pubkey returned null");
  475. goto done;
  476. }
  477. if (X509_verify(cert, pkey) <= 0) {
  478. log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
  479. goto done;
  480. }
  481. rsa = EVP_PKEY_get1_RSA(pkey);
  482. EVP_PKEY_free(pkey);
  483. pkey = NULL;
  484. if (!rsa) {
  485. log_fn(LOG_WARN,"EVP_PKEY_get1_RSA(pkey) returned null");
  486. goto done;
  487. }
  488. r = _crypto_new_pk_env_rsa(rsa);
  489. rsa = NULL;
  490. done:
  491. if (cert)
  492. X509_free(cert);
  493. if (pkey)
  494. EVP_PKEY_free(pkey);
  495. if (rsa)
  496. RSA_free(rsa);
  497. return r;
  498. }
  499. int
  500. tor_tls_get_pending_bytes(tor_tls *tls)
  501. {
  502. assert(tls);
  503. return SSL_pending(tls->ssl);
  504. }