tortls.c 12 KB

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