tortls.c 25 KB

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