tortls.c 26 KB

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