tortls.c 25 KB

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