tortls.c 25 KB

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