tortls.c 12 KB

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