tortls.c 11 KB

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