tortls.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. /* Copyright 2003 Roger Dingledine. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. const char tortls_c_id[] = "$Id$";
  5. /**
  6. * \file tortls.c
  7. *
  8. * \brief TLS wrappers for Tor.
  9. **/
  10. /* (Unlike other tor functions, these
  11. * are prefixed with tor_ in order to avoid conflicting with OpenSSL
  12. * functions and variables.)
  13. */
  14. #include "./crypto.h"
  15. #include "./tortls.h"
  16. #include "./util.h"
  17. #include "./log.h"
  18. #include <string.h>
  19. /* Copied from or.h */
  20. #define LEGAL_NICKNAME_CHARACTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  21. #include <assert.h>
  22. #include <openssl/ssl.h>
  23. #include <openssl/err.h>
  24. #include <openssl/tls1.h>
  25. #include <openssl/asn1.h>
  26. #include <openssl/bio.h>
  27. /** How long do identity certificates live? (sec) */
  28. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  29. typedef struct tor_tls_context_st {
  30. SSL_CTX *ctx;
  31. SSL_CTX *client_only_ctx;
  32. } tor_tls_context;
  33. /** Holds a SSL object and its associated data. Members are only
  34. * accessed from within tortls.c.
  35. */
  36. struct tor_tls_st {
  37. SSL *ssl; /**< An OpenSSL SSL object. */
  38. int socket; /**< The underlying file descriptor for this TLS connection. */
  39. enum {
  40. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  41. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
  42. } state; /**< The current SSL state, depending on which operations have
  43. * completed successfully. */
  44. int isServer;
  45. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last time. */
  46. };
  47. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  48. crypto_pk_env_t *rsa_sign,
  49. const char *cname,
  50. const char *cname_sign,
  51. unsigned int lifetime);
  52. /** Global tls context. We keep it here because nobody else needs to
  53. * touch it. */
  54. static tor_tls_context *global_tls_context = NULL;
  55. /** True iff tor_tls_init() has been called. */
  56. static int tls_library_is_initialized = 0;
  57. /* Module-internal error codes. */
  58. #define _TOR_TLS_SYSCALL -6
  59. #define _TOR_TLS_ZERORETURN -5
  60. /* These functions are declared in crypto.c but not exported. */
  61. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
  62. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
  63. DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
  64. /** Log all pending tls errors at level <b>severity</b>. Use
  65. * <b>doing</b> to describe our current activities.
  66. */
  67. static void
  68. tls_log_errors(int severity, const char *doing)
  69. {
  70. int err;
  71. const char *msg, *lib, *func;
  72. while ((err = ERR_get_error()) != 0) {
  73. msg = (const char*)ERR_reason_error_string(err);
  74. lib = (const char*)ERR_lib_error_string(err);
  75. func = (const char*)ERR_func_error_string(err);
  76. if (!msg) msg = "(null)";
  77. if (doing) {
  78. log(severity, "TLS error while %s: %s (in %s:%s)", doing, msg, lib,func);
  79. } else {
  80. log(severity, "TLS error: %s (in %s:%s)", msg, lib, func);
  81. }
  82. }
  83. }
  84. #define CATCH_SYSCALL 1
  85. #define CATCH_ZERO 2
  86. /** Given a TLS object and the result of an SSL_* call, use
  87. * SSL_get_error to determine whether an error has occurred, and if so
  88. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  89. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  90. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  91. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  92. *
  93. * If an error has occurred, log it at level <b>severity</b> and describe the
  94. * current action as <b>doing</b>.
  95. */
  96. static int
  97. tor_tls_get_error(tor_tls *tls, int r, int extra,
  98. const char *doing, int severity)
  99. {
  100. int err = SSL_get_error(tls->ssl, r);
  101. switch (err) {
  102. case SSL_ERROR_NONE:
  103. return TOR_TLS_DONE;
  104. case SSL_ERROR_WANT_READ:
  105. return TOR_TLS_WANTREAD;
  106. case SSL_ERROR_WANT_WRITE:
  107. return TOR_TLS_WANTWRITE;
  108. case SSL_ERROR_SYSCALL:
  109. if (extra&CATCH_SYSCALL)
  110. return _TOR_TLS_SYSCALL;
  111. if (r == 0)
  112. log(severity, "TLS error: unexpected close while %s", doing);
  113. else {
  114. int e = tor_socket_errno(tls->socket);
  115. log(severity, "TLS error: <syscall error while %s> (errno=%d: %s)",
  116. doing, e, tor_socket_strerror(e));
  117. }
  118. tls_log_errors(severity, doing);
  119. return TOR_TLS_ERROR;
  120. case SSL_ERROR_ZERO_RETURN:
  121. if (extra&CATCH_ZERO)
  122. return _TOR_TLS_ZERORETURN;
  123. log(severity, "TLS error: Zero return");
  124. tls_log_errors(severity, doing);
  125. return TOR_TLS_ERROR;
  126. default:
  127. tls_log_errors(severity, doing);
  128. return TOR_TLS_ERROR;
  129. }
  130. }
  131. /** Initialize OpenSSL, unless it has already been initialized.
  132. */
  133. static void
  134. tor_tls_init(void) {
  135. if (!tls_library_is_initialized) {
  136. SSL_library_init();
  137. SSL_load_error_strings();
  138. crypto_global_init();
  139. OpenSSL_add_all_algorithms();
  140. tls_library_is_initialized = 1;
  141. }
  142. }
  143. /** We need to give OpenSSL a callback to verify certificates. This is
  144. * it: We always accept peer certs and complete the handshake. We
  145. * don't validate them until later.
  146. */
  147. static int always_accept_verify_cb(int preverify_ok,
  148. X509_STORE_CTX *x509_ctx)
  149. {
  150. return 1;
  151. }
  152. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  153. * signed by the private key <b>rsa_sign</b>. The commonName of the
  154. * certificate will be <b>cname</b>; the commonName of the issuer will be
  155. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  156. * starting from now. Return a certificate on success, NULL on
  157. * failure.
  158. */
  159. static X509 *
  160. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  161. crypto_pk_env_t *rsa_sign,
  162. const char *cname,
  163. const char *cname_sign,
  164. unsigned int cert_lifetime)
  165. {
  166. time_t start_time, end_time;
  167. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  168. X509 *x509 = NULL;
  169. X509_NAME *name = NULL, *name_issuer=NULL;
  170. int nid;
  171. tor_tls_init();
  172. start_time = time(NULL);
  173. tor_assert(rsa);
  174. tor_assert(cname);
  175. tor_assert(rsa_sign);
  176. tor_assert(cname_sign);
  177. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  178. goto error;
  179. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  180. goto error;
  181. if (!(x509 = X509_new()))
  182. goto error;
  183. if (!(X509_set_version(x509, 2)))
  184. goto error;
  185. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  186. goto error;
  187. if (!(name = X509_NAME_new()))
  188. goto error;
  189. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
  190. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  191. (char*)"TOR", -1, -1, 0))) goto error;
  192. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  193. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  194. (char*)cname, -1, -1, 0))) goto error;
  195. if (!(X509_set_subject_name(x509, name)))
  196. goto error;
  197. if (!(name_issuer = X509_NAME_new()))
  198. goto error;
  199. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
  200. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  201. (char*)"TOR", -1, -1, 0))) goto error;
  202. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  203. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  204. (char*)cname_sign, -1, -1, 0))) goto error;
  205. if (!(X509_set_issuer_name(x509, name_issuer)))
  206. goto error;
  207. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  208. goto error;
  209. end_time = start_time + cert_lifetime;
  210. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  211. goto error;
  212. if (!X509_set_pubkey(x509, pkey))
  213. goto error;
  214. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  215. goto error;
  216. goto done;
  217. error:
  218. tls_log_errors(LOG_WARN, "generating certificate");
  219. if (x509) {
  220. X509_free(x509);
  221. x509 = NULL;
  222. }
  223. done:
  224. if (sign_pkey)
  225. EVP_PKEY_free(sign_pkey);
  226. if (pkey)
  227. EVP_PKEY_free(pkey);
  228. if (name)
  229. X509_NAME_free(name);
  230. if (name_issuer)
  231. X509_NAME_free(name_issuer);
  232. return x509;
  233. }
  234. #ifdef EVERYONE_HAS_AES
  235. /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
  236. * is needed. */
  237. #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
  238. #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
  239. /* Some people are running OpenSSL before 0.9.7, but we aren't.
  240. * We can support AES and 3DES.
  241. */
  242. #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  243. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  244. #else
  245. /* We're running OpenSSL before 0.9.7. We only support 3DES. */
  246. #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
  247. #endif
  248. /** Create a new TLS context. If we are going to be using it as a
  249. * server, it must have isServer set to true, <b>identity</b> set to the
  250. * identity key used to sign that certificate, and <b>nickname</b> set to
  251. * the server's nickname. If we're only going to be a client,
  252. * isServer should be false, identity should be NULL, and nickname
  253. * should be NULL. Return -1 if failure, else 0.
  254. *
  255. * You can call this function multiple times. Each time you call it,
  256. * it generates new certificates; all new connections will use
  257. * the new SSL context.
  258. */
  259. int
  260. tor_tls_context_new(crypto_pk_env_t *identity,
  261. int isServer, const char *nickname,
  262. unsigned int key_lifetime)
  263. {
  264. crypto_pk_env_t *rsa = NULL;
  265. crypto_dh_env_t *dh = NULL;
  266. EVP_PKEY *pkey = NULL;
  267. tor_tls_context *result = NULL;
  268. X509 *cert = NULL, *idcert = NULL;
  269. char nn2[128];
  270. int client_only;
  271. SSL_CTX **ctx;
  272. if (!nickname)
  273. nickname = "null";
  274. tor_snprintf(nn2, sizeof(nn2), "%s <identity>", nickname);
  275. tor_tls_init();
  276. if (isServer) {
  277. /* Generate short-term RSA key. */
  278. if (!(rsa = crypto_new_pk_env()))
  279. goto error;
  280. if (crypto_pk_generate_key(rsa)<0)
  281. goto error;
  282. /* Create certificate signed by identity key. */
  283. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  284. key_lifetime);
  285. /* Create self-signed certificate for identity key. */
  286. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  287. IDENTITY_CERT_LIFETIME);
  288. if (!cert || !idcert) {
  289. log(LOG_WARN, "Error creating certificate");
  290. goto error;
  291. }
  292. }
  293. result = tor_malloc(sizeof(tor_tls_context));
  294. result->ctx = result->client_only_ctx = NULL;
  295. for (client_only=0; client_only <= 1; ++client_only) {
  296. ctx = client_only ? &result->client_only_ctx : &result->ctx;
  297. #ifdef EVERYONE_HAS_AES
  298. /* Tell OpenSSL to only use TLS1 */
  299. if (!(*ctx = SSL_CTX_new(TLSv1_method())))
  300. goto error;
  301. #else
  302. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  303. if (!(*ctx = SSL_CTX_new(SSLv23_method())))
  304. goto error;
  305. SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
  306. #endif
  307. if (!SSL_CTX_set_cipher_list(*ctx, CIPHER_LIST))
  308. goto error;
  309. if (!client_only) {
  310. if (cert && !SSL_CTX_use_certificate(*ctx,cert))
  311. goto error;
  312. if (idcert && !SSL_CTX_add_extra_chain_cert(*ctx,idcert))
  313. goto error;
  314. }
  315. SSL_CTX_set_session_cache_mode(*ctx, SSL_SESS_CACHE_OFF);
  316. if (isServer && !client_only) {
  317. tor_assert(rsa);
  318. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  319. goto error;
  320. if (!SSL_CTX_use_PrivateKey(*ctx, pkey))
  321. goto error;
  322. EVP_PKEY_free(pkey);
  323. pkey = NULL;
  324. if (cert) {
  325. if (!SSL_CTX_check_private_key(*ctx))
  326. goto error;
  327. }
  328. }
  329. dh = crypto_dh_new();
  330. SSL_CTX_set_tmp_dh(*ctx, _crypto_dh_env_get_dh(dh));
  331. crypto_dh_free(dh);
  332. SSL_CTX_set_verify(*ctx, SSL_VERIFY_PEER,
  333. always_accept_verify_cb);
  334. /* let us realloc bufs that we're writing from */
  335. SSL_CTX_set_mode(*ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  336. }
  337. /* Free the old context if one exists. */
  338. if (global_tls_context) {
  339. /* This is safe even if there are open connections: OpenSSL does
  340. * reference counting with SSL and SSL_CTX objects. */
  341. SSL_CTX_free(global_tls_context->ctx);
  342. SSL_CTX_free(global_tls_context->client_only_ctx);
  343. tor_free(global_tls_context);
  344. }
  345. global_tls_context = result;
  346. return 0;
  347. error:
  348. tls_log_errors(LOG_WARN, "creating TLS context");
  349. if (pkey)
  350. EVP_PKEY_free(pkey);
  351. if (rsa)
  352. crypto_free_pk_env(rsa);
  353. if (dh)
  354. crypto_dh_free(dh);
  355. if (result && result->ctx)
  356. SSL_CTX_free(result->ctx);
  357. if (result && result->client_only_ctx)
  358. SSL_CTX_free(result->client_only_ctx);
  359. if (result)
  360. free(result);
  361. if (cert)
  362. X509_free(cert);
  363. if (idcert)
  364. X509_free(cert);
  365. return -1;
  366. }
  367. /** Create a new TLS object from a file descriptor, and a flag to
  368. * determine whether it is functioning as a server.
  369. */
  370. tor_tls *
  371. tor_tls_new(int sock, int isServer, int use_no_cert)
  372. {
  373. tor_tls *result = tor_malloc(sizeof(tor_tls));
  374. SSL_CTX *ctx;
  375. tor_assert(global_tls_context); /* make sure somebody made it first */
  376. ctx = use_no_cert ? global_tls_context->client_only_ctx
  377. : global_tls_context->ctx;
  378. if (!(result->ssl = SSL_new(ctx)))
  379. return NULL;
  380. result->socket = sock;
  381. SSL_set_fd(result->ssl, sock);
  382. result->state = TOR_TLS_ST_HANDSHAKE;
  383. result->isServer = isServer;
  384. result->wantwrite_n = 0;
  385. return result;
  386. }
  387. /** Release resources associated with a TLS object. Does not close the
  388. * underlying file descriptor.
  389. */
  390. void
  391. tor_tls_free(tor_tls *tls)
  392. {
  393. SSL_free(tls->ssl);
  394. free(tls);
  395. }
  396. /** Underlying function for TLS reading. Reads up to <b>len</b>
  397. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  398. * number of characters read. On failure, returns TOR_TLS_ERROR,
  399. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  400. */
  401. int
  402. tor_tls_read(tor_tls *tls, char *cp, size_t len)
  403. {
  404. int r, err;
  405. tor_assert(tls);
  406. tor_assert(tls->ssl);
  407. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  408. r = SSL_read(tls->ssl, cp, len);
  409. if (r > 0)
  410. return r;
  411. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
  412. if (err == _TOR_TLS_ZERORETURN) {
  413. log_fn(LOG_DEBUG,"read returned r=%d; TLS is closed",r);
  414. tls->state = TOR_TLS_ST_CLOSED;
  415. return TOR_TLS_CLOSE;
  416. } else {
  417. tor_assert(err != TOR_TLS_DONE);
  418. log_fn(LOG_DEBUG,"read returned r=%d, err=%d",r,err);
  419. return err;
  420. }
  421. }
  422. /** Underlying function for TLS writing. Write up to <b>n</b>
  423. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  424. * number of characters written. On failure, returns TOR_TLS_ERROR,
  425. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  426. */
  427. int
  428. tor_tls_write(tor_tls *tls, char *cp, size_t n)
  429. {
  430. int r, err;
  431. tor_assert(tls);
  432. tor_assert(tls->ssl);
  433. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  434. if (n == 0)
  435. return 0;
  436. if (tls->wantwrite_n) {
  437. /* if WANTWRITE last time, we must use the _same_ n as before */
  438. tor_assert(n >= tls->wantwrite_n);
  439. log_fn(LOG_DEBUG,"resuming pending-write, (%d to flush, reusing %d)",
  440. (int)n, (int)tls->wantwrite_n);
  441. n = tls->wantwrite_n;
  442. tls->wantwrite_n = 0;
  443. }
  444. r = SSL_write(tls->ssl, cp, n);
  445. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  446. if (err == TOR_TLS_DONE) {
  447. return r;
  448. }
  449. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  450. tls->wantwrite_n = n;
  451. }
  452. return err;
  453. }
  454. /** Perform initial handshake on <b>tls</b>. When finished, returns
  455. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  456. * or TOR_TLS_WANTWRITE.
  457. */
  458. int
  459. tor_tls_handshake(tor_tls *tls)
  460. {
  461. int r;
  462. tor_assert(tls);
  463. tor_assert(tls->ssl);
  464. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  465. if (tls->isServer) {
  466. r = SSL_accept(tls->ssl);
  467. } else {
  468. r = SSL_connect(tls->ssl);
  469. }
  470. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  471. if (r == TOR_TLS_DONE) {
  472. tls->state = TOR_TLS_ST_OPEN;
  473. }
  474. return r;
  475. }
  476. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  477. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  478. * or TOR_TLS_WANTWRITE.
  479. */
  480. int
  481. tor_tls_shutdown(tor_tls *tls)
  482. {
  483. int r, err;
  484. char buf[128];
  485. tor_assert(tls);
  486. tor_assert(tls->ssl);
  487. while (1) {
  488. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  489. /* If we've already called shutdown once to send a close message,
  490. * we read until the other side has closed too.
  491. */
  492. do {
  493. r = SSL_read(tls->ssl, buf, 128);
  494. } while (r>0);
  495. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  496. LOG_INFO);
  497. if (err == _TOR_TLS_ZERORETURN) {
  498. tls->state = TOR_TLS_ST_GOTCLOSE;
  499. /* fall through... */
  500. } else {
  501. return err;
  502. }
  503. }
  504. r = SSL_shutdown(tls->ssl);
  505. if (r == 1) {
  506. /* If shutdown returns 1, the connection is entirely closed. */
  507. tls->state = TOR_TLS_ST_CLOSED;
  508. return TOR_TLS_DONE;
  509. }
  510. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  511. LOG_INFO);
  512. if (err == _TOR_TLS_SYSCALL) {
  513. /* The underlying TCP connection closed while we were shutting down. */
  514. tls->state = TOR_TLS_ST_CLOSED;
  515. return TOR_TLS_DONE;
  516. } else if (err == _TOR_TLS_ZERORETURN) {
  517. /* The TLS connection says that it sent a shutdown record, but
  518. * isn't done shutting down yet. Make sure that this hasn't
  519. * happened before, then go back to the start of the function
  520. * and try to read.
  521. */
  522. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  523. tls->state == TOR_TLS_ST_SENTCLOSE) {
  524. log(LOG_WARN,
  525. "TLS returned \"half-closed\" value while already half-closed");
  526. return TOR_TLS_ERROR;
  527. }
  528. tls->state = TOR_TLS_ST_SENTCLOSE;
  529. /* fall through ... */
  530. } else {
  531. return err;
  532. }
  533. } /* end loop */
  534. }
  535. /** Return true iff this TLS connection is authenticated.
  536. */
  537. int
  538. tor_tls_peer_has_cert(tor_tls *tls)
  539. {
  540. X509 *cert;
  541. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  542. return 0;
  543. X509_free(cert);
  544. return 1;
  545. }
  546. /** Return the nickname (if any) that the peer connected on <b>tls</b>
  547. * claims to have.
  548. */
  549. int
  550. tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, size_t buflen)
  551. {
  552. X509 *cert = NULL;
  553. X509_NAME *name = NULL;
  554. int nid;
  555. int lenout;
  556. if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
  557. log_fn(LOG_WARN, "Peer has no certificate");
  558. goto error;
  559. }
  560. if (!(name = X509_get_subject_name(cert))) {
  561. log_fn(LOG_WARN, "Peer certificate has no subject name");
  562. goto error;
  563. }
  564. if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
  565. goto error;
  566. lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
  567. if (lenout == -1)
  568. goto error;
  569. if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
  570. log_fn(LOG_WARN, "Peer certificate nickname has illegal characters.");
  571. goto error;
  572. }
  573. return 0;
  574. error:
  575. if (cert)
  576. X509_free(cert);
  577. if (name)
  578. X509_NAME_free(name);
  579. return -1;
  580. }
  581. static void log_cert_lifetime(X509 *cert, const char *problem)
  582. {
  583. BIO *bio = NULL;
  584. BUF_MEM *buf;
  585. char *s1=NULL, *s2=NULL;
  586. char mytime[33];
  587. time_t now = time(NULL);
  588. if (problem)
  589. log_fn(LOG_WARN,"Certificate %s: is your system clock set incorrectly?",
  590. problem);
  591. if (!(bio = BIO_new(BIO_s_mem()))) {
  592. log_fn(LOG_WARN, "Couldn't allocate BIO!"); goto end;
  593. }
  594. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  595. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  596. goto end;
  597. }
  598. BIO_get_mem_ptr(bio, &buf);
  599. s1 = tor_strndup(buf->data, buf->length);
  600. BIO_reset(bio);
  601. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  602. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  603. goto end;
  604. }
  605. BIO_get_mem_ptr(bio, &buf);
  606. s2 = tor_strndup(buf->data, buf->length);
  607. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", gmtime(&now));
  608. log_fn(LOG_WARN, "(certificate lifetime runs from %s through %s. Your time is %s.)",s1,s2,mytime);
  609. end:
  610. if (bio)
  611. BIO_free(bio);
  612. if (s1)
  613. tor_free(s1);
  614. if (s2)
  615. tor_free(s2);
  616. }
  617. /** If the provided tls connection is authenticated and has a
  618. * certificate that is currently valid and signed, then set
  619. * *<b>identity_key</b> to the identity certificate's key and return
  620. * 0. Else, return -1.
  621. */
  622. int
  623. tor_tls_verify(tor_tls *tls, crypto_pk_env_t **identity_key)
  624. {
  625. X509 *cert = NULL, *id_cert = NULL;
  626. STACK_OF(X509) *chain = NULL;
  627. EVP_PKEY *id_pkey = NULL;
  628. RSA *rsa;
  629. int num_in_chain;
  630. int r = -1, i;
  631. *identity_key = NULL;
  632. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  633. goto done;
  634. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  635. goto done;
  636. num_in_chain = sk_X509_num(chain);
  637. /* 1 means we're receiving (server-side), and it's just the id_cert.
  638. * 2 means we're connecting (client-side), and it's both the link
  639. * cert and the id_cert.
  640. */
  641. if (num_in_chain < 1) {
  642. log_fn(LOG_WARN,"Unexpected number of certificates in chain (%d)",
  643. num_in_chain);
  644. goto done;
  645. }
  646. for (i=0; i<num_in_chain; ++i) {
  647. id_cert = sk_X509_value(chain, i);
  648. if (X509_cmp(id_cert, cert) != 0)
  649. break;
  650. }
  651. if (!id_cert) {
  652. log_fn(LOG_WARN,"No distinct identity certificate found");
  653. goto done;
  654. }
  655. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  656. X509_verify(cert, id_pkey) <= 0) {
  657. log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
  658. tls_log_errors(LOG_WARN,"verifying certificate");
  659. goto done;
  660. }
  661. rsa = EVP_PKEY_get1_RSA(id_pkey);
  662. if (!rsa)
  663. goto done;
  664. *identity_key = _crypto_new_pk_env_rsa(rsa);
  665. r = 0;
  666. done:
  667. if (cert)
  668. X509_free(cert);
  669. if (id_pkey)
  670. EVP_PKEY_free(id_pkey);
  671. /* This should never get invoked, but let's make sure in case OpenSSL
  672. * acts unexpectedly. */
  673. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  674. return r;
  675. }
  676. /** Check whether the certificate set on the connection <b>tls</b> is
  677. * expired or not-yet-valid, give or take <b>tolerance</b>
  678. * seconds. Return 0 for valid, -1 for failure.
  679. *
  680. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  681. */
  682. int
  683. tor_tls_check_lifetime(tor_tls *tls, int tolerance)
  684. {
  685. time_t now, t;
  686. X509 *cert;
  687. int r = -1;
  688. now = time(NULL);
  689. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  690. goto done;
  691. t = now + tolerance;
  692. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  693. log_cert_lifetime(cert, "not yet valid");
  694. goto done;
  695. }
  696. t = now - tolerance;
  697. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  698. log_cert_lifetime(cert, "already expired");
  699. goto done;
  700. }
  701. r = 0;
  702. done:
  703. if (cert)
  704. X509_free(cert);
  705. return r;
  706. }
  707. /** Return the number of bytes available for reading from <b>tls</b>.
  708. */
  709. int
  710. tor_tls_get_pending_bytes(tor_tls *tls)
  711. {
  712. tor_assert(tls);
  713. #if OPENSSL_VERSION_NUMBER < 0x0090700fl
  714. if (tls->ssl->rstate == SSL_ST_READ_BODY)
  715. return 0;
  716. if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
  717. return 0;
  718. #endif
  719. return SSL_pending(tls->ssl);
  720. }
  721. /** Return the number of bytes read across the underlying socket. */
  722. unsigned long tor_tls_get_n_bytes_read(tor_tls *tls)
  723. {
  724. tor_assert(tls);
  725. return BIO_number_read(SSL_get_rbio(tls->ssl));
  726. }
  727. /** Return the number of bytes written across the underlying socket. */
  728. unsigned long tor_tls_get_n_bytes_written(tor_tls *tls)
  729. {
  730. tor_assert(tls);
  731. return BIO_number_written(SSL_get_wbio(tls->ssl));
  732. }
  733. /** Implement assert_no_tls_errors: If there are any pending OpenSSL
  734. * errors, log an error message and assert(0). */
  735. void _assert_no_tls_errors(const char *fname, int line)
  736. {
  737. if (ERR_peek_error() == 0)
  738. return;
  739. log_fn(LOG_ERR, "Unhandled OpenSSL errors found at %s:%d: ",
  740. fname, line);
  741. tls_log_errors(LOG_ERR, NULL);
  742. tor_assert(0);
  743. }