tortls.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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. /** How much clock skew do we tolerate when checking certificates? (sec) */
  29. #define CERT_ALLOW_SKEW (90*60)
  30. typedef struct tor_tls_context_st {
  31. SSL_CTX *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. int 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() {
  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 && cname && rsa_sign && cname_sign);
  174. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  175. goto error;
  176. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  177. goto error;
  178. if (!(x509 = X509_new()))
  179. goto error;
  180. if (!(X509_set_version(x509, 2)))
  181. goto error;
  182. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  183. goto error;
  184. if (!(name = X509_NAME_new()))
  185. goto error;
  186. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
  187. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  188. "TOR", -1, -1, 0))) goto error;
  189. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  190. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  191. (char*)cname, -1, -1, 0))) goto error;
  192. if (!(X509_set_subject_name(x509, name)))
  193. goto error;
  194. if (!(name_issuer = X509_NAME_new()))
  195. goto error;
  196. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
  197. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  198. "TOR", -1, -1, 0))) goto error;
  199. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  200. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  201. (char*)cname_sign, -1, -1, 0))) goto error;
  202. if (!(X509_set_issuer_name(x509, name_issuer)))
  203. goto error;
  204. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  205. goto error;
  206. end_time = start_time + cert_lifetime;
  207. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  208. goto error;
  209. if (!X509_set_pubkey(x509, pkey))
  210. goto error;
  211. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  212. goto error;
  213. goto done;
  214. error:
  215. tls_log_errors(LOG_WARN, "generating certificate");
  216. if (x509) {
  217. X509_free(x509);
  218. x509 = NULL;
  219. }
  220. done:
  221. if (sign_pkey)
  222. EVP_PKEY_free(sign_pkey);
  223. if (pkey)
  224. EVP_PKEY_free(pkey);
  225. if (name)
  226. X509_NAME_free(name);
  227. if (name_issuer)
  228. X509_NAME_free(name_issuer);
  229. return x509;
  230. }
  231. #ifdef EVERYONE_HAS_AES
  232. /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
  233. * is needed. */
  234. #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
  235. #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
  236. /* Some people are running OpenSSL before 0.9.7, but we aren't.
  237. * We can support AES and 3DES.
  238. */
  239. #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  240. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  241. #else
  242. /* We're running OpenSSL before 0.9.7. We only support 3DES. */
  243. #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
  244. #endif
  245. /** Create a new TLS context. If we are going to be using it as a
  246. * server, it must have isServer set to true, <b>identity</b> set to the
  247. * identity key used to sign that certificate, and <b>nickname</b> set to
  248. * the server's nickname. If we're only going to be a client,
  249. * isServer should be false, identity should be NULL, and nickname
  250. * should be NULL. Return -1 if failure, else 0.
  251. *
  252. * You can call this function multiple times. Each time you call it,
  253. * it generates new certificates; all new connections will be begin
  254. * with the new SSL context.
  255. */
  256. int
  257. tor_tls_context_new(crypto_pk_env_t *identity,
  258. int isServer, const char *nickname,
  259. unsigned int key_lifetime)
  260. {
  261. crypto_pk_env_t *rsa = NULL;
  262. crypto_dh_env_t *dh = NULL;
  263. EVP_PKEY *pkey = NULL;
  264. tor_tls_context *result = NULL;
  265. X509 *cert = NULL, *idcert = NULL;
  266. char nn2[1024];
  267. sprintf(nn2, "%s <identity>", nickname);
  268. tor_tls_init();
  269. if (isServer) {
  270. /* Generate short-term RSA key. */
  271. if (!(rsa = crypto_new_pk_env()))
  272. goto error;
  273. if (crypto_pk_generate_key(rsa)<0)
  274. goto error;
  275. /* Create certificate signed by identity key. */
  276. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  277. key_lifetime);
  278. /* Create self-signed certificate for identity key. */
  279. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  280. IDENTITY_CERT_LIFETIME);
  281. if (!cert || !idcert) {
  282. log(LOG_WARN, "Error creating certificate");
  283. goto error;
  284. }
  285. }
  286. result = tor_malloc(sizeof(tor_tls_context));
  287. result->ctx = NULL;
  288. #ifdef EVERYONE_HAS_AES
  289. /* Tell OpenSSL to only use TLS1 */
  290. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  291. goto error;
  292. #else
  293. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  294. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  295. goto error;
  296. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  297. #endif
  298. if (!SSL_CTX_set_cipher_list(result->ctx, CIPHER_LIST))
  299. goto error;
  300. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  301. goto error;
  302. if (idcert && !SSL_CTX_add_extra_chain_cert(result->ctx,idcert))
  303. goto error;
  304. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  305. if (isServer) {
  306. tor_assert(rsa);
  307. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  308. goto error;
  309. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  310. goto error;
  311. EVP_PKEY_free(pkey);
  312. pkey = NULL;
  313. if (cert) {
  314. if (!SSL_CTX_check_private_key(result->ctx))
  315. goto error;
  316. }
  317. }
  318. dh = crypto_dh_new();
  319. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  320. crypto_dh_free(dh);
  321. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  322. always_accept_verify_cb);
  323. /* let us realloc bufs that we're writing from */
  324. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  325. /* Free the old context if one exists. */
  326. if (global_tls_context) {
  327. /* This is safe even if there are open connections: OpenSSL does
  328. * reference counting with SSL and SSL_CTX objects. */
  329. SSL_CTX_free(global_tls_context->ctx);
  330. free(global_tls_context);
  331. }
  332. global_tls_context = result;
  333. return 0;
  334. error:
  335. tls_log_errors(LOG_WARN, "creating TLS context");
  336. if (pkey)
  337. EVP_PKEY_free(pkey);
  338. if (rsa)
  339. crypto_free_pk_env(rsa);
  340. if (dh)
  341. crypto_dh_free(dh);
  342. if (result && result->ctx)
  343. SSL_CTX_free(result->ctx);
  344. if (result)
  345. free(result);
  346. if (cert)
  347. X509_free(cert);
  348. if (idcert)
  349. X509_free(cert);
  350. return -1;
  351. }
  352. /** Create a new TLS object from a file descriptor, and a flag to
  353. * determine whether it is functioning as a server.
  354. */
  355. tor_tls *
  356. tor_tls_new(int sock, int isServer)
  357. {
  358. tor_tls *result = tor_malloc(sizeof(tor_tls));
  359. tor_assert(global_tls_context); /* make sure somebody made it first */
  360. if (!(result->ssl = SSL_new(global_tls_context->ctx)))
  361. return NULL;
  362. result->socket = sock;
  363. SSL_set_fd(result->ssl, sock);
  364. result->state = TOR_TLS_ST_HANDSHAKE;
  365. result->isServer = isServer;
  366. result->wantwrite_n = 0;
  367. return result;
  368. }
  369. /** Release resources associated with a TLS object. Does not close the
  370. * underlying file descriptor.
  371. */
  372. void
  373. tor_tls_free(tor_tls *tls)
  374. {
  375. SSL_free(tls->ssl);
  376. free(tls);
  377. }
  378. /** Underlying function for TLS reading. Reads up to <b>len</b>
  379. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  380. * number of characters read. On failure, returns TOR_TLS_ERROR,
  381. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  382. */
  383. int
  384. tor_tls_read(tor_tls *tls, char *cp, int len)
  385. {
  386. int r, err;
  387. tor_assert(tls && tls->ssl);
  388. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  389. r = SSL_read(tls->ssl, cp, len);
  390. if (r > 0)
  391. return r;
  392. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
  393. log_fn(LOG_DEBUG,"returned r=%d, err=%d",r,err);
  394. if (err == _TOR_TLS_ZERORETURN) {
  395. tls->state = TOR_TLS_ST_CLOSED;
  396. return TOR_TLS_CLOSE;
  397. } else {
  398. tor_assert(err != TOR_TLS_DONE);
  399. return err;
  400. }
  401. }
  402. /** Underlying function for TLS writing. Write up to <b>n</b>
  403. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  404. * number of characters written. On failure, returns TOR_TLS_ERROR,
  405. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  406. */
  407. int
  408. tor_tls_write(tor_tls *tls, char *cp, int n)
  409. {
  410. int r, err;
  411. tor_assert(tls && tls->ssl);
  412. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  413. if (n == 0)
  414. return 0;
  415. if(tls->wantwrite_n) {
  416. /* if WANTWRITE last time, we must use the _same_ n as before */
  417. tor_assert(n >= tls->wantwrite_n);
  418. log_fn(LOG_DEBUG,"resuming pending-write, (%d to flush, reusing %d)",
  419. n, tls->wantwrite_n);
  420. n = tls->wantwrite_n;
  421. tls->wantwrite_n = 0;
  422. }
  423. r = SSL_write(tls->ssl, cp, n);
  424. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  425. if (err == TOR_TLS_DONE) {
  426. return r;
  427. }
  428. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  429. // log_fn(LOG_INFO,"wantwrite or wantread. remembering the number %d.",n);
  430. tls->wantwrite_n = n;
  431. }
  432. return err;
  433. }
  434. /** Perform initial handshake on <b>tls</b>. When finished, returns
  435. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  436. * or TOR_TLS_WANTWRITE.
  437. */
  438. int
  439. tor_tls_handshake(tor_tls *tls)
  440. {
  441. int r;
  442. tor_assert(tls && tls->ssl);
  443. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  444. if (tls->isServer) {
  445. r = SSL_accept(tls->ssl);
  446. } else {
  447. r = SSL_connect(tls->ssl);
  448. }
  449. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  450. if (r == TOR_TLS_DONE) {
  451. tls->state = TOR_TLS_ST_OPEN;
  452. }
  453. return r;
  454. }
  455. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  456. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  457. * or TOR_TLS_WANTWRITE.
  458. */
  459. int
  460. tor_tls_shutdown(tor_tls *tls)
  461. {
  462. int r, err;
  463. char buf[128];
  464. tor_assert(tls && tls->ssl);
  465. while (1) {
  466. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  467. /* If we've already called shutdown once to send a close message,
  468. * we read until the other side has closed too.
  469. */
  470. do {
  471. r = SSL_read(tls->ssl, buf, 128);
  472. } while (r>0);
  473. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  474. LOG_INFO);
  475. if (err == _TOR_TLS_ZERORETURN) {
  476. tls->state = TOR_TLS_ST_GOTCLOSE;
  477. /* fall through... */
  478. } else {
  479. return err;
  480. }
  481. }
  482. r = SSL_shutdown(tls->ssl);
  483. if (r == 1) {
  484. /* If shutdown returns 1, the connection is entirely closed. */
  485. tls->state = TOR_TLS_ST_CLOSED;
  486. return TOR_TLS_DONE;
  487. }
  488. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  489. LOG_INFO);
  490. if (err == _TOR_TLS_SYSCALL) {
  491. /* The underlying TCP connection closed while we were shutting down. */
  492. tls->state = TOR_TLS_ST_CLOSED;
  493. return TOR_TLS_DONE;
  494. } else if (err == _TOR_TLS_ZERORETURN) {
  495. /* The TLS connection says that it sent a shutdown record, but
  496. * isn't done shutting down yet. Make sure that this hasn't
  497. * happened before, then go back to the start of the function
  498. * and try to read.
  499. */
  500. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  501. tls->state == TOR_TLS_ST_SENTCLOSE) {
  502. log(LOG_WARN,
  503. "TLS returned \"half-closed\" value while already half-closed");
  504. return TOR_TLS_ERROR;
  505. }
  506. tls->state = TOR_TLS_ST_SENTCLOSE;
  507. /* fall through ... */
  508. } else {
  509. return err;
  510. }
  511. } /* end loop */
  512. }
  513. /** Return true iff this TLS connection is authenticated.
  514. */
  515. int
  516. tor_tls_peer_has_cert(tor_tls *tls)
  517. {
  518. X509 *cert;
  519. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  520. return 0;
  521. X509_free(cert);
  522. return 1;
  523. }
  524. /** Return the nickname (if any) that the peer connected on <b>tls</b>
  525. * claims to have.
  526. */
  527. int
  528. tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, int buflen)
  529. {
  530. X509 *cert = NULL;
  531. X509_NAME *name = NULL;
  532. int nid;
  533. int lenout;
  534. if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
  535. log_fn(LOG_WARN, "Peer has no certificate");
  536. goto error;
  537. }
  538. if (!(name = X509_get_subject_name(cert))) {
  539. log_fn(LOG_WARN, "Peer certificate has no subject name");
  540. goto error;
  541. }
  542. if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
  543. goto error;
  544. lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
  545. if (lenout == -1)
  546. goto error;
  547. if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
  548. log_fn(LOG_WARN, "Peer certificate nickname has illegal characters.");
  549. goto error;
  550. }
  551. return 0;
  552. error:
  553. if (cert)
  554. X509_free(cert);
  555. if (name)
  556. X509_NAME_free(name);
  557. return -1;
  558. }
  559. /** If the provided tls connection is authenticated and has a
  560. * certificate that is currently valid and is correctly signed by
  561. * <b>identity_key</b>, return 0. Else, return -1.
  562. */
  563. int
  564. tor_tls_verify(tor_tls *tls, crypto_pk_env_t *identity_key)
  565. {
  566. X509 *cert = NULL;
  567. EVP_PKEY *id_pkey = NULL;
  568. time_t now, t;
  569. int r = -1;
  570. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  571. return -1;
  572. now = time(NULL);
  573. t = now + CERT_ALLOW_SKEW;
  574. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  575. log_fn(LOG_WARN,"Certificate becomes valid in the future: is your system clock set incorrectly?");
  576. goto done;
  577. }
  578. t = now - CERT_ALLOW_SKEW;
  579. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  580. log_fn(LOG_WARN,"Certificate already expired; is your system clock set incorrectly?");
  581. goto done;
  582. }
  583. /* Get the public key. */
  584. if (!(id_pkey = _crypto_pk_env_get_evp_pkey(identity_key,0)) ||
  585. X509_verify(cert, id_pkey) <= 0) {
  586. log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
  587. tls_log_errors(LOG_WARN,"verifying certificate");
  588. goto done;
  589. }
  590. r = 0;
  591. done:
  592. if (cert)
  593. X509_free(cert);
  594. if (id_pkey)
  595. EVP_PKEY_free(id_pkey);
  596. /* This should never get invoked, but let's make sure in case OpenSSL
  597. * acts unexpectedly. */
  598. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  599. return r;
  600. }
  601. /** Return the number of bytes available for reading from <b>tls</b>.
  602. */
  603. int
  604. tor_tls_get_pending_bytes(tor_tls *tls)
  605. {
  606. tor_assert(tls);
  607. #if OPENSSL_VERSION_NUMBER < 0x0090700fl
  608. if (tls->ssl->rstate == SSL_ST_READ_BODY)
  609. return 0;
  610. if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
  611. return 0;
  612. #endif
  613. return SSL_pending(tls->ssl);
  614. }
  615. /** Return the number of bytes read across the underlying socket. */
  616. unsigned long tor_tls_get_n_bytes_read(tor_tls *tls)
  617. {
  618. tor_assert(tls);
  619. return BIO_number_read(SSL_get_rbio(tls->ssl));
  620. }
  621. /** Return the number of bytes written across the underlying socket. */
  622. unsigned long tor_tls_get_n_bytes_written(tor_tls *tls)
  623. {
  624. tor_assert(tls);
  625. return BIO_number_written(SSL_get_wbio(tls->ssl));
  626. }
  627. /** Implement assert_no_tls_errors: If there are any pending OpenSSL
  628. * errors, log an error message and assert(0). */
  629. void _assert_no_tls_errors(const char *fname, int line)
  630. {
  631. if (ERR_peek_error() == 0)
  632. return;
  633. log_fn(LOG_ERR, "Unhandled OpenSSL errors found at %s:%d: ",
  634. fname, line);
  635. tls_log_errors(LOG_ERR, NULL);
  636. tor_assert(0);
  637. }
  638. /*
  639. Local Variables:
  640. mode:c
  641. indent-tabs-mode:nil
  642. c-basic-offset:2
  643. End:
  644. */