tortls.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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. SSL_free(tls->ssl);
  407. free(tls);
  408. }
  409. /** Underlying function for TLS reading. Reads up to <b>len</b>
  410. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  411. * number of characters read. On failure, returns TOR_TLS_ERROR,
  412. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  413. */
  414. int
  415. tor_tls_read(tor_tls *tls, char *cp, size_t len)
  416. {
  417. int r, err;
  418. tor_assert(tls);
  419. tor_assert(tls->ssl);
  420. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  421. r = SSL_read(tls->ssl, cp, len);
  422. if (r > 0)
  423. return r;
  424. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
  425. if (err == _TOR_TLS_ZERORETURN) {
  426. log_fn(LOG_DEBUG,"read returned r=%d; TLS is closed",r);
  427. tls->state = TOR_TLS_ST_CLOSED;
  428. return TOR_TLS_CLOSE;
  429. } else {
  430. tor_assert(err != TOR_TLS_DONE);
  431. log_fn(LOG_DEBUG,"read returned r=%d, err=%d",r,err);
  432. return err;
  433. }
  434. }
  435. /** Underlying function for TLS writing. Write up to <b>n</b>
  436. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  437. * number of characters written. On failure, returns TOR_TLS_ERROR,
  438. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  439. */
  440. int
  441. tor_tls_write(tor_tls *tls, char *cp, size_t n)
  442. {
  443. int r, err;
  444. tor_assert(tls);
  445. tor_assert(tls->ssl);
  446. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  447. if (n == 0)
  448. return 0;
  449. if (tls->wantwrite_n) {
  450. /* if WANTWRITE last time, we must use the _same_ n as before */
  451. tor_assert(n >= tls->wantwrite_n);
  452. log_fn(LOG_DEBUG,"resuming pending-write, (%d to flush, reusing %d)",
  453. (int)n, (int)tls->wantwrite_n);
  454. n = tls->wantwrite_n;
  455. tls->wantwrite_n = 0;
  456. }
  457. r = SSL_write(tls->ssl, cp, n);
  458. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  459. if (err == TOR_TLS_DONE) {
  460. return r;
  461. }
  462. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  463. tls->wantwrite_n = n;
  464. }
  465. return err;
  466. }
  467. /** Perform initial handshake on <b>tls</b>. When finished, returns
  468. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  469. * or TOR_TLS_WANTWRITE.
  470. */
  471. int
  472. tor_tls_handshake(tor_tls *tls)
  473. {
  474. int r;
  475. tor_assert(tls);
  476. tor_assert(tls->ssl);
  477. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  478. if (tls->isServer) {
  479. r = SSL_accept(tls->ssl);
  480. } else {
  481. r = SSL_connect(tls->ssl);
  482. }
  483. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  484. if (r == TOR_TLS_DONE) {
  485. tls->state = TOR_TLS_ST_OPEN;
  486. }
  487. return r;
  488. }
  489. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  490. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  491. * or TOR_TLS_WANTWRITE.
  492. */
  493. int
  494. tor_tls_shutdown(tor_tls *tls)
  495. {
  496. int r, err;
  497. char buf[128];
  498. tor_assert(tls);
  499. tor_assert(tls->ssl);
  500. while (1) {
  501. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  502. /* If we've already called shutdown once to send a close message,
  503. * we read until the other side has closed too.
  504. */
  505. do {
  506. r = SSL_read(tls->ssl, buf, 128);
  507. } while (r>0);
  508. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  509. LOG_INFO);
  510. if (err == _TOR_TLS_ZERORETURN) {
  511. tls->state = TOR_TLS_ST_GOTCLOSE;
  512. /* fall through... */
  513. } else {
  514. return err;
  515. }
  516. }
  517. r = SSL_shutdown(tls->ssl);
  518. if (r == 1) {
  519. /* If shutdown returns 1, the connection is entirely closed. */
  520. tls->state = TOR_TLS_ST_CLOSED;
  521. return TOR_TLS_DONE;
  522. }
  523. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  524. LOG_INFO);
  525. if (err == _TOR_TLS_SYSCALL) {
  526. /* The underlying TCP connection closed while we were shutting down. */
  527. tls->state = TOR_TLS_ST_CLOSED;
  528. return TOR_TLS_DONE;
  529. } else if (err == _TOR_TLS_ZERORETURN) {
  530. /* The TLS connection says that it sent a shutdown record, but
  531. * isn't done shutting down yet. Make sure that this hasn't
  532. * happened before, then go back to the start of the function
  533. * and try to read.
  534. */
  535. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  536. tls->state == TOR_TLS_ST_SENTCLOSE) {
  537. log(LOG_WARN,
  538. "TLS returned \"half-closed\" value while already half-closed");
  539. return TOR_TLS_ERROR;
  540. }
  541. tls->state = TOR_TLS_ST_SENTCLOSE;
  542. /* fall through ... */
  543. } else {
  544. return err;
  545. }
  546. } /* end loop */
  547. }
  548. /** Return true iff this TLS connection is authenticated.
  549. */
  550. int
  551. tor_tls_peer_has_cert(tor_tls *tls)
  552. {
  553. X509 *cert;
  554. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  555. return 0;
  556. X509_free(cert);
  557. return 1;
  558. }
  559. /** Write the nickname (if any) that the peer connected on <b>tls</b>
  560. * claims to have into the first <b>buflen</b> characters of <b>buf</b>.
  561. * Truncate the nickname if it is longer than buflen-1 characters. Always
  562. * NUL-terminate. Return 0 on success, -1 on failure.
  563. */
  564. int
  565. tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, size_t buflen)
  566. {
  567. X509 *cert = NULL;
  568. X509_NAME *name = NULL;
  569. int nid;
  570. int lenout;
  571. if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
  572. log_fn(LOG_WARN, "Peer has no certificate");
  573. goto error;
  574. }
  575. if (!(name = X509_get_subject_name(cert))) {
  576. log_fn(LOG_WARN, "Peer certificate has no subject name");
  577. goto error;
  578. }
  579. if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
  580. goto error;
  581. lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
  582. if (lenout == -1)
  583. goto error;
  584. if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
  585. log_fn(LOG_WARN, "Peer certificate nickname '%s' has illegal characters.",
  586. buf);
  587. if (strchr(buf, '.'))
  588. log_fn(LOG_WARN, " (Maybe it is not really running Tor at its advertised OR port.)");
  589. goto error;
  590. }
  591. X509_free(cert);
  592. return 0;
  593. error:
  594. if (cert)
  595. X509_free(cert);
  596. return -1;
  597. }
  598. static void log_cert_lifetime(X509 *cert, const char *problem)
  599. {
  600. BIO *bio = NULL;
  601. BUF_MEM *buf;
  602. char *s1=NULL, *s2=NULL;
  603. char mytime[33];
  604. time_t now = time(NULL);
  605. struct tm tm;
  606. if (problem)
  607. log_fn(LOG_WARN,"Certificate %s: is your system clock set incorrectly?",
  608. problem);
  609. if (!(bio = BIO_new(BIO_s_mem()))) {
  610. log_fn(LOG_WARN, "Couldn't allocate BIO!"); goto end;
  611. }
  612. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  613. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  614. goto end;
  615. }
  616. BIO_get_mem_ptr(bio, &buf);
  617. s1 = tor_strndup(buf->data, buf->length);
  618. BIO_reset(bio);
  619. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  620. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  621. goto end;
  622. }
  623. BIO_get_mem_ptr(bio, &buf);
  624. s2 = tor_strndup(buf->data, buf->length);
  625. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  626. log_fn(LOG_WARN, "(certificate lifetime runs from %s through %s. Your time is %s.)",s1,s2,mytime);
  627. end:
  628. if (bio)
  629. BIO_free(bio);
  630. if (s1)
  631. tor_free(s1);
  632. if (s2)
  633. tor_free(s2);
  634. }
  635. /** If the provided tls connection is authenticated and has a
  636. * certificate that is currently valid and signed, then set
  637. * *<b>identity_key</b> to the identity certificate's key and return
  638. * 0. Else, return -1.
  639. */
  640. int
  641. tor_tls_verify(tor_tls *tls, crypto_pk_env_t **identity_key)
  642. {
  643. X509 *cert = NULL, *id_cert = NULL;
  644. STACK_OF(X509) *chain = NULL;
  645. EVP_PKEY *id_pkey = NULL;
  646. RSA *rsa;
  647. int num_in_chain;
  648. int r = -1, i;
  649. *identity_key = NULL;
  650. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  651. goto done;
  652. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  653. goto done;
  654. num_in_chain = sk_X509_num(chain);
  655. /* 1 means we're receiving (server-side), and it's just the id_cert.
  656. * 2 means we're connecting (client-side), and it's both the link
  657. * cert and the id_cert.
  658. */
  659. if (num_in_chain < 1) {
  660. log_fn(LOG_WARN,"Unexpected number of certificates in chain (%d)",
  661. num_in_chain);
  662. goto done;
  663. }
  664. for (i=0; i<num_in_chain; ++i) {
  665. id_cert = sk_X509_value(chain, i);
  666. if (X509_cmp(id_cert, cert) != 0)
  667. break;
  668. }
  669. if (!id_cert) {
  670. log_fn(LOG_WARN,"No distinct identity certificate found");
  671. goto done;
  672. }
  673. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  674. X509_verify(cert, id_pkey) <= 0) {
  675. log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
  676. tls_log_errors(LOG_WARN,"verifying certificate");
  677. goto done;
  678. }
  679. rsa = EVP_PKEY_get1_RSA(id_pkey);
  680. if (!rsa)
  681. goto done;
  682. *identity_key = _crypto_new_pk_env_rsa(rsa);
  683. r = 0;
  684. done:
  685. if (cert)
  686. X509_free(cert);
  687. if (id_pkey)
  688. EVP_PKEY_free(id_pkey);
  689. /* This should never get invoked, but let's make sure in case OpenSSL
  690. * acts unexpectedly. */
  691. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  692. return r;
  693. }
  694. /** Check whether the certificate set on the connection <b>tls</b> is
  695. * expired or not-yet-valid, give or take <b>tolerance</b>
  696. * seconds. Return 0 for valid, -1 for failure.
  697. *
  698. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  699. */
  700. int
  701. tor_tls_check_lifetime(tor_tls *tls, int tolerance)
  702. {
  703. time_t now, t;
  704. X509 *cert;
  705. int r = -1;
  706. now = time(NULL);
  707. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  708. goto done;
  709. t = now + tolerance;
  710. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  711. log_cert_lifetime(cert, "not yet valid");
  712. goto done;
  713. }
  714. t = now - tolerance;
  715. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  716. log_cert_lifetime(cert, "already expired");
  717. goto done;
  718. }
  719. r = 0;
  720. done:
  721. if (cert)
  722. X509_free(cert);
  723. return r;
  724. }
  725. /** Return the number of bytes available for reading from <b>tls</b>.
  726. */
  727. int
  728. tor_tls_get_pending_bytes(tor_tls *tls)
  729. {
  730. tor_assert(tls);
  731. #if OPENSSL_VERSION_NUMBER < 0x0090700fl
  732. if (tls->ssl->rstate == SSL_ST_READ_BODY)
  733. return 0;
  734. if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
  735. return 0;
  736. #endif
  737. return SSL_pending(tls->ssl);
  738. }
  739. /** Return the number of bytes read across the underlying socket. */
  740. unsigned long tor_tls_get_n_bytes_read(tor_tls *tls)
  741. {
  742. tor_assert(tls);
  743. return BIO_number_read(SSL_get_rbio(tls->ssl));
  744. }
  745. /** Return the number of bytes written across the underlying socket. */
  746. unsigned long tor_tls_get_n_bytes_written(tor_tls *tls)
  747. {
  748. tor_assert(tls);
  749. return BIO_number_written(SSL_get_wbio(tls->ssl));
  750. }
  751. /** Implement assert_no_tls_errors: If there are any pending OpenSSL
  752. * errors, log an error message and assert(0). */
  753. void _assert_no_tls_errors(const char *fname, int line)
  754. {
  755. if (ERR_peek_error() == 0)
  756. return;
  757. log_fn(LOG_ERR, "Unhandled OpenSSL errors found at %s:%d: ",
  758. fname, line);
  759. tls_log_errors(LOG_ERR, NULL);
  760. tor_assert(0);
  761. }