tortls.c 25 KB

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