tortls.c 12 KB

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