tortls.c 13 KB

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