tortls.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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. void
  144. tor_tls_free_all(void)
  145. {
  146. if (global_tls_context) {
  147. SSL_CTX_free(global_tls_context->ctx);
  148. SSL_CTX_free(global_tls_context->client_only_ctx);
  149. tor_free(global_tls_context);
  150. global_tls_context = NULL;
  151. }
  152. }
  153. /** We need to give OpenSSL a callback to verify certificates. This is
  154. * it: We always accept peer certs and complete the handshake. We
  155. * don't validate them until later.
  156. */
  157. static int always_accept_verify_cb(int preverify_ok,
  158. X509_STORE_CTX *x509_ctx)
  159. {
  160. return 1;
  161. }
  162. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  163. * signed by the private key <b>rsa_sign</b>. The commonName of the
  164. * certificate will be <b>cname</b>; the commonName of the issuer will be
  165. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  166. * starting from now. Return a certificate on success, NULL on
  167. * failure.
  168. */
  169. static X509 *
  170. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  171. crypto_pk_env_t *rsa_sign,
  172. const char *cname,
  173. const char *cname_sign,
  174. unsigned int cert_lifetime)
  175. {
  176. time_t start_time, end_time;
  177. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  178. X509 *x509 = NULL;
  179. X509_NAME *name = NULL, *name_issuer=NULL;
  180. int nid;
  181. tor_tls_init();
  182. start_time = time(NULL);
  183. tor_assert(rsa);
  184. tor_assert(cname);
  185. tor_assert(rsa_sign);
  186. tor_assert(cname_sign);
  187. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  188. goto error;
  189. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  190. goto error;
  191. if (!(x509 = X509_new()))
  192. goto error;
  193. if (!(X509_set_version(x509, 2)))
  194. goto error;
  195. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  196. goto error;
  197. if (!(name = 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, 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, nid, MBSTRING_ASC,
  204. (char*)cname, -1, -1, 0))) goto error;
  205. if (!(X509_set_subject_name(x509, name)))
  206. goto error;
  207. if (!(name_issuer = X509_NAME_new()))
  208. goto error;
  209. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
  210. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  211. (char*)"TOR", -1, -1, 0))) goto error;
  212. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  213. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  214. (char*)cname_sign, -1, -1, 0))) goto error;
  215. if (!(X509_set_issuer_name(x509, name_issuer)))
  216. goto error;
  217. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  218. goto error;
  219. end_time = start_time + cert_lifetime;
  220. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  221. goto error;
  222. if (!X509_set_pubkey(x509, pkey))
  223. goto error;
  224. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  225. goto error;
  226. goto done;
  227. error:
  228. tls_log_errors(LOG_WARN, "generating certificate");
  229. if (x509) {
  230. X509_free(x509);
  231. x509 = NULL;
  232. }
  233. done:
  234. if (sign_pkey)
  235. EVP_PKEY_free(sign_pkey);
  236. if (pkey)
  237. EVP_PKEY_free(pkey);
  238. if (name)
  239. X509_NAME_free(name);
  240. if (name_issuer)
  241. X509_NAME_free(name_issuer);
  242. return x509;
  243. }
  244. #ifdef EVERYONE_HAS_AES
  245. /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
  246. * is needed. */
  247. #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
  248. #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
  249. /* Some people are running OpenSSL before 0.9.7, but we aren't.
  250. * We can support AES and 3DES.
  251. */
  252. #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  253. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  254. #else
  255. /* We're running OpenSSL before 0.9.7. We only support 3DES. */
  256. #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
  257. #endif
  258. /** Create a new TLS context. If we are going to be using it as a
  259. * server, it must have isServer set to true, <b>identity</b> set to the
  260. * identity key used to sign that certificate, and <b>nickname</b> set to
  261. * the server's nickname. If we're only going to be a client,
  262. * isServer should be false, identity should be NULL, and nickname
  263. * should be NULL. Return -1 if failure, else 0.
  264. *
  265. * You can call this function multiple times. Each time you call it,
  266. * it generates new certificates; all new connections will use
  267. * the new SSL context.
  268. */
  269. int
  270. tor_tls_context_new(crypto_pk_env_t *identity,
  271. int isServer, const char *nickname,
  272. unsigned int key_lifetime)
  273. {
  274. crypto_pk_env_t *rsa = NULL;
  275. crypto_dh_env_t *dh = NULL;
  276. EVP_PKEY *pkey = NULL;
  277. tor_tls_context *result = NULL;
  278. X509 *cert = NULL, *idcert = NULL;
  279. char nn2[128];
  280. int client_only;
  281. SSL_CTX **ctx;
  282. if (!nickname)
  283. nickname = "null";
  284. tor_snprintf(nn2, sizeof(nn2), "%s <identity>", nickname);
  285. tor_tls_init();
  286. if (isServer) {
  287. /* Generate short-term RSA key. */
  288. if (!(rsa = crypto_new_pk_env()))
  289. goto error;
  290. if (crypto_pk_generate_key(rsa)<0)
  291. goto error;
  292. /* Create certificate signed by identity key. */
  293. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  294. key_lifetime);
  295. /* Create self-signed certificate for identity key. */
  296. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  297. IDENTITY_CERT_LIFETIME);
  298. if (!cert || !idcert) {
  299. log(LOG_WARN, "Error creating certificate");
  300. goto error;
  301. }
  302. }
  303. result = tor_malloc(sizeof(tor_tls_context));
  304. result->ctx = result->client_only_ctx = NULL;
  305. for (client_only=0; client_only <= 1; ++client_only) {
  306. ctx = client_only ? &result->client_only_ctx : &result->ctx;
  307. #ifdef EVERYONE_HAS_AES
  308. /* Tell OpenSSL to only use TLS1 */
  309. if (!(*ctx = SSL_CTX_new(TLSv1_method())))
  310. goto error;
  311. #else
  312. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  313. if (!(*ctx = SSL_CTX_new(SSLv23_method())))
  314. goto error;
  315. SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
  316. #endif
  317. if (!SSL_CTX_set_cipher_list(*ctx, CIPHER_LIST))
  318. goto error;
  319. if (!client_only) {
  320. if (cert && !SSL_CTX_use_certificate(*ctx,cert))
  321. goto error;
  322. X509_free(cert); /* We just added a reference to cert. */
  323. cert=NULL;
  324. if (idcert && !SSL_CTX_add_extra_chain_cert(*ctx,idcert))
  325. goto error;
  326. idcert=NULL; /* The context now owns the reference to idcert */
  327. }
  328. SSL_CTX_set_session_cache_mode(*ctx, SSL_SESS_CACHE_OFF);
  329. if (isServer && !client_only) {
  330. tor_assert(rsa);
  331. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  332. goto error;
  333. if (!SSL_CTX_use_PrivateKey(*ctx, pkey))
  334. goto error;
  335. EVP_PKEY_free(pkey);
  336. pkey = NULL;
  337. if (!SSL_CTX_check_private_key(*ctx))
  338. goto error;
  339. }
  340. dh = crypto_dh_new();
  341. SSL_CTX_set_tmp_dh(*ctx, _crypto_dh_env_get_dh(dh));
  342. crypto_dh_free(dh);
  343. SSL_CTX_set_verify(*ctx, SSL_VERIFY_PEER,
  344. always_accept_verify_cb);
  345. /* let us realloc bufs that we're writing from */
  346. SSL_CTX_set_mode(*ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  347. }
  348. /* Free the old context if one exists. */
  349. if (global_tls_context) {
  350. /* This is safe even if there are open connections: OpenSSL does
  351. * reference counting with SSL and SSL_CTX objects. */
  352. SSL_CTX_free(global_tls_context->ctx);
  353. SSL_CTX_free(global_tls_context->client_only_ctx);
  354. tor_free(global_tls_context);
  355. }
  356. global_tls_context = result;
  357. if (rsa)
  358. crypto_free_pk_env(rsa);
  359. return 0;
  360. error:
  361. tls_log_errors(LOG_WARN, "creating TLS context");
  362. if (pkey)
  363. EVP_PKEY_free(pkey);
  364. if (rsa)
  365. crypto_free_pk_env(rsa);
  366. if (dh)
  367. crypto_dh_free(dh);
  368. if (result && result->ctx)
  369. SSL_CTX_free(result->ctx);
  370. if (result && result->client_only_ctx)
  371. SSL_CTX_free(result->client_only_ctx);
  372. if (result)
  373. free(result);
  374. if (cert)
  375. X509_free(cert);
  376. if (idcert)
  377. X509_free(idcert);
  378. return -1;
  379. }
  380. /** Create a new TLS object from a file descriptor, and a flag to
  381. * determine whether it is functioning as a server.
  382. */
  383. tor_tls *
  384. tor_tls_new(int sock, int isServer, int use_no_cert)
  385. {
  386. tor_tls *result = tor_malloc(sizeof(tor_tls));
  387. SSL_CTX *ctx;
  388. tor_assert(global_tls_context); /* make sure somebody made it first */
  389. ctx = use_no_cert ? global_tls_context->client_only_ctx
  390. : global_tls_context->ctx;
  391. if (!(result->ssl = SSL_new(ctx)))
  392. return NULL;
  393. result->socket = sock;
  394. SSL_set_fd(result->ssl, sock);
  395. result->state = TOR_TLS_ST_HANDSHAKE;
  396. result->isServer = isServer;
  397. result->wantwrite_n = 0;
  398. return result;
  399. }
  400. /** Release resources associated with a TLS object. Does not close the
  401. * underlying file descriptor.
  402. */
  403. void
  404. tor_tls_free(tor_tls *tls)
  405. {
  406. tor_assert(tls && tls->ssl);
  407. SSL_free(tls->ssl);
  408. tls->ssl = NULL;
  409. tor_free(tls);
  410. }
  411. /** Underlying function for TLS reading. Reads up to <b>len</b>
  412. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  413. * number of characters read. On failure, returns TOR_TLS_ERROR,
  414. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  415. */
  416. int
  417. tor_tls_read(tor_tls *tls, char *cp, size_t len)
  418. {
  419. int r, err;
  420. tor_assert(tls);
  421. tor_assert(tls->ssl);
  422. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  423. r = SSL_read(tls->ssl, cp, len);
  424. if (r > 0)
  425. return r;
  426. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
  427. if (err == _TOR_TLS_ZERORETURN) {
  428. log_fn(LOG_DEBUG,"read returned r=%d; TLS is closed",r);
  429. tls->state = TOR_TLS_ST_CLOSED;
  430. return TOR_TLS_CLOSE;
  431. } else {
  432. tor_assert(err != TOR_TLS_DONE);
  433. log_fn(LOG_DEBUG,"read returned r=%d, err=%d",r,err);
  434. return err;
  435. }
  436. }
  437. /** Underlying function for TLS writing. Write up to <b>n</b>
  438. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  439. * number of characters written. On failure, returns TOR_TLS_ERROR,
  440. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  441. */
  442. int
  443. tor_tls_write(tor_tls *tls, char *cp, size_t n)
  444. {
  445. int r, err;
  446. tor_assert(tls);
  447. tor_assert(tls->ssl);
  448. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  449. if (n == 0)
  450. return 0;
  451. if (tls->wantwrite_n) {
  452. /* if WANTWRITE last time, we must use the _same_ n as before */
  453. tor_assert(n >= tls->wantwrite_n);
  454. log_fn(LOG_DEBUG,"resuming pending-write, (%d to flush, reusing %d)",
  455. (int)n, (int)tls->wantwrite_n);
  456. n = tls->wantwrite_n;
  457. tls->wantwrite_n = 0;
  458. }
  459. r = SSL_write(tls->ssl, cp, n);
  460. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  461. if (err == TOR_TLS_DONE) {
  462. return r;
  463. }
  464. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  465. tls->wantwrite_n = n;
  466. }
  467. return err;
  468. }
  469. /** Perform initial handshake on <b>tls</b>. When finished, returns
  470. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  471. * or TOR_TLS_WANTWRITE.
  472. */
  473. int
  474. tor_tls_handshake(tor_tls *tls)
  475. {
  476. int r;
  477. tor_assert(tls);
  478. tor_assert(tls->ssl);
  479. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  480. if (tls->isServer) {
  481. r = SSL_accept(tls->ssl);
  482. } else {
  483. r = SSL_connect(tls->ssl);
  484. }
  485. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  486. if (r == TOR_TLS_DONE) {
  487. tls->state = TOR_TLS_ST_OPEN;
  488. }
  489. return r;
  490. }
  491. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  492. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  493. * or TOR_TLS_WANTWRITE.
  494. */
  495. int
  496. tor_tls_shutdown(tor_tls *tls)
  497. {
  498. int r, err;
  499. char buf[128];
  500. tor_assert(tls);
  501. tor_assert(tls->ssl);
  502. while (1) {
  503. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  504. /* If we've already called shutdown once to send a close message,
  505. * we read until the other side has closed too.
  506. */
  507. do {
  508. r = SSL_read(tls->ssl, buf, 128);
  509. } while (r>0);
  510. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  511. LOG_INFO);
  512. if (err == _TOR_TLS_ZERORETURN) {
  513. tls->state = TOR_TLS_ST_GOTCLOSE;
  514. /* fall through... */
  515. } else {
  516. return err;
  517. }
  518. }
  519. r = SSL_shutdown(tls->ssl);
  520. if (r == 1) {
  521. /* If shutdown returns 1, the connection is entirely closed. */
  522. tls->state = TOR_TLS_ST_CLOSED;
  523. return TOR_TLS_DONE;
  524. }
  525. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  526. LOG_INFO);
  527. if (err == _TOR_TLS_SYSCALL) {
  528. /* The underlying TCP connection closed while we were shutting down. */
  529. tls->state = TOR_TLS_ST_CLOSED;
  530. return TOR_TLS_DONE;
  531. } else if (err == _TOR_TLS_ZERORETURN) {
  532. /* The TLS connection says that it sent a shutdown record, but
  533. * isn't done shutting down yet. Make sure that this hasn't
  534. * happened before, then go back to the start of the function
  535. * and try to read.
  536. */
  537. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  538. tls->state == TOR_TLS_ST_SENTCLOSE) {
  539. log(LOG_WARN,
  540. "TLS returned \"half-closed\" value while already half-closed");
  541. return TOR_TLS_ERROR;
  542. }
  543. tls->state = TOR_TLS_ST_SENTCLOSE;
  544. /* fall through ... */
  545. } else {
  546. return err;
  547. }
  548. } /* end loop */
  549. }
  550. /** Return true iff this TLS connection is authenticated.
  551. */
  552. int
  553. tor_tls_peer_has_cert(tor_tls *tls)
  554. {
  555. X509 *cert;
  556. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  557. return 0;
  558. X509_free(cert);
  559. return 1;
  560. }
  561. /** Write the nickname (if any) that the peer connected on <b>tls</b>
  562. * claims to have into the first <b>buflen</b> characters of <b>buf</b>.
  563. * Truncate the nickname if it is longer than buflen-1 characters. Always
  564. * NUL-terminate. Return 0 on success, -1 on failure.
  565. */
  566. int
  567. tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, size_t buflen)
  568. {
  569. X509 *cert = NULL;
  570. X509_NAME *name = NULL;
  571. int nid;
  572. int lenout;
  573. if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
  574. log_fn(LOG_WARN, "Peer has no certificate");
  575. goto error;
  576. }
  577. if (!(name = X509_get_subject_name(cert))) {
  578. log_fn(LOG_WARN, "Peer certificate has no subject name");
  579. goto error;
  580. }
  581. if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
  582. goto error;
  583. lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
  584. if (lenout == -1)
  585. goto error;
  586. if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
  587. log_fn(LOG_WARN, "Peer certificate nickname '%s' has illegal characters.",
  588. buf);
  589. if (strchr(buf, '.'))
  590. log_fn(LOG_WARN, " (Maybe it is not really running Tor at its advertised OR port.)");
  591. goto error;
  592. }
  593. X509_free(cert);
  594. return 0;
  595. error:
  596. if (cert)
  597. X509_free(cert);
  598. return -1;
  599. }
  600. static void log_cert_lifetime(X509 *cert, const char *problem)
  601. {
  602. BIO *bio = NULL;
  603. BUF_MEM *buf;
  604. char *s1=NULL, *s2=NULL;
  605. char mytime[33];
  606. time_t now = time(NULL);
  607. struct tm tm;
  608. if (problem)
  609. log_fn(LOG_WARN,"Certificate %s: is your system clock set incorrectly?",
  610. problem);
  611. if (!(bio = BIO_new(BIO_s_mem()))) {
  612. log_fn(LOG_WARN, "Couldn't allocate BIO!"); goto end;
  613. }
  614. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  615. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  616. goto end;
  617. }
  618. BIO_get_mem_ptr(bio, &buf);
  619. s1 = tor_strndup(buf->data, buf->length);
  620. BIO_reset(bio);
  621. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  622. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  623. goto end;
  624. }
  625. BIO_get_mem_ptr(bio, &buf);
  626. s2 = tor_strndup(buf->data, buf->length);
  627. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  628. log_fn(LOG_WARN, "(certificate lifetime runs from %s through %s. Your time is %s.)",s1,s2,mytime);
  629. end:
  630. if (bio)
  631. BIO_free(bio);
  632. if (s1)
  633. tor_free(s1);
  634. if (s2)
  635. tor_free(s2);
  636. }
  637. /** If the provided tls connection is authenticated and has a
  638. * certificate that is currently valid and signed, then set
  639. * *<b>identity_key</b> to the identity certificate's key and return
  640. * 0. Else, return -1.
  641. */
  642. int
  643. tor_tls_verify(tor_tls *tls, crypto_pk_env_t **identity_key)
  644. {
  645. X509 *cert = NULL, *id_cert = NULL;
  646. STACK_OF(X509) *chain = NULL;
  647. EVP_PKEY *id_pkey = NULL;
  648. RSA *rsa;
  649. int num_in_chain;
  650. int r = -1, i;
  651. *identity_key = NULL;
  652. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  653. goto done;
  654. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  655. goto done;
  656. num_in_chain = sk_X509_num(chain);
  657. /* 1 means we're receiving (server-side), and it's just the id_cert.
  658. * 2 means we're connecting (client-side), and it's both the link
  659. * cert and the id_cert.
  660. */
  661. if (num_in_chain < 1) {
  662. log_fn(LOG_WARN,"Unexpected number of certificates in chain (%d)",
  663. num_in_chain);
  664. goto done;
  665. }
  666. for (i=0; i<num_in_chain; ++i) {
  667. id_cert = sk_X509_value(chain, i);
  668. if (X509_cmp(id_cert, cert) != 0)
  669. break;
  670. }
  671. if (!id_cert) {
  672. log_fn(LOG_WARN,"No distinct identity certificate found");
  673. goto done;
  674. }
  675. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  676. X509_verify(cert, id_pkey) <= 0) {
  677. log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
  678. tls_log_errors(LOG_WARN,"verifying certificate");
  679. goto done;
  680. }
  681. rsa = EVP_PKEY_get1_RSA(id_pkey);
  682. if (!rsa)
  683. goto done;
  684. *identity_key = _crypto_new_pk_env_rsa(rsa);
  685. r = 0;
  686. done:
  687. if (cert)
  688. X509_free(cert);
  689. if (id_pkey)
  690. EVP_PKEY_free(id_pkey);
  691. /* This should never get invoked, but let's make sure in case OpenSSL
  692. * acts unexpectedly. */
  693. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  694. return r;
  695. }
  696. /** Check whether the certificate set on the connection <b>tls</b> is
  697. * expired or not-yet-valid, give or take <b>tolerance</b>
  698. * seconds. Return 0 for valid, -1 for failure.
  699. *
  700. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  701. */
  702. int
  703. tor_tls_check_lifetime(tor_tls *tls, int tolerance)
  704. {
  705. time_t now, t;
  706. X509 *cert;
  707. int r = -1;
  708. now = time(NULL);
  709. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  710. goto done;
  711. t = now + tolerance;
  712. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  713. log_cert_lifetime(cert, "not yet valid");
  714. goto done;
  715. }
  716. t = now - tolerance;
  717. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  718. log_cert_lifetime(cert, "already expired");
  719. goto done;
  720. }
  721. r = 0;
  722. done:
  723. if (cert)
  724. X509_free(cert);
  725. return r;
  726. }
  727. /** Return the number of bytes available for reading from <b>tls</b>.
  728. */
  729. int
  730. tor_tls_get_pending_bytes(tor_tls *tls)
  731. {
  732. tor_assert(tls);
  733. #if OPENSSL_VERSION_NUMBER < 0x0090700fl
  734. if (tls->ssl->rstate == SSL_ST_READ_BODY)
  735. return 0;
  736. if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
  737. return 0;
  738. #endif
  739. return SSL_pending(tls->ssl);
  740. }
  741. /** Return the number of bytes read across the underlying socket. */
  742. unsigned long tor_tls_get_n_bytes_read(tor_tls *tls)
  743. {
  744. tor_assert(tls);
  745. return BIO_number_read(SSL_get_rbio(tls->ssl));
  746. }
  747. /** Return the number of bytes written across the underlying socket. */
  748. unsigned long tor_tls_get_n_bytes_written(tor_tls *tls)
  749. {
  750. tor_assert(tls);
  751. return BIO_number_written(SSL_get_wbio(tls->ssl));
  752. }
  753. /** Implement assert_no_tls_errors: If there are any pending OpenSSL
  754. * errors, log an error message and assert(0). */
  755. void _assert_no_tls_errors(const char *fname, int line)
  756. {
  757. if (ERR_peek_error() == 0)
  758. return;
  759. log_fn(LOG_ERR, "Unhandled OpenSSL errors found at %s:%d: ",
  760. fname, line);
  761. tls_log_errors(LOG_ERR, NULL);
  762. tor_assert(0);
  763. }