tortls.c 23 KB

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