tortls.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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. /* DOCDOC */
  32. typedef struct tor_tls_context_t {
  33. SSL_CTX *ctx;
  34. SSL_CTX *client_only_ctx;
  35. } tor_tls_context_t;
  36. /** Holds a SSL object and its associated data. Members are only
  37. * accessed from within tortls.c.
  38. */
  39. struct tor_tls_t {
  40. SSL *ssl; /**< An OpenSSL SSL object. */
  41. int socket; /**< The underlying file descriptor for this TLS connection. */
  42. enum {
  43. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  44. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
  45. } state; /**< The current SSL state, depending on which operations have
  46. * completed successfully. */
  47. int isServer;
  48. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last time. */
  49. };
  50. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  51. crypto_pk_env_t *rsa_sign,
  52. const char *cname,
  53. const char *cname_sign,
  54. unsigned int lifetime);
  55. /** Global tls context. We keep it here because nobody else needs to
  56. * touch it. */
  57. static tor_tls_context_t *global_tls_context = NULL;
  58. /** True iff tor_tls_init() has been called. */
  59. static int tls_library_is_initialized = 0;
  60. /* Module-internal error codes. */
  61. #define _TOR_TLS_SYSCALL -6
  62. #define _TOR_TLS_ZERORETURN -5
  63. /* These functions are declared in crypto.c but not exported. */
  64. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
  65. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
  66. DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
  67. /** Log all pending tls errors at level <b>severity</b>. Use
  68. * <b>doing</b> to describe our current activities.
  69. */
  70. static void
  71. tls_log_errors(int severity, const char *doing)
  72. {
  73. int err;
  74. const char *msg, *lib, *func;
  75. while ((err = ERR_get_error()) != 0) {
  76. msg = (const char*)ERR_reason_error_string(err);
  77. lib = (const char*)ERR_lib_error_string(err);
  78. func = (const char*)ERR_func_error_string(err);
  79. if (!msg) msg = "(null)";
  80. if (doing) {
  81. log(severity, LD_NET, "TLS error while %s: %s (in %s:%s)", doing, msg, lib,func);
  82. } else {
  83. log(severity, LD_NET, "TLS error: %s (in %s:%s)", msg, lib, func);
  84. }
  85. }
  86. }
  87. #define CATCH_SYSCALL 1
  88. #define CATCH_ZERO 2
  89. /** Given a TLS object and the result of an SSL_* call, use
  90. * SSL_get_error to determine whether an error has occurred, and if so
  91. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  92. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  93. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  94. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  95. *
  96. * If an error has occurred, log it at level <b>severity</b> and describe the
  97. * current action as <b>doing</b>.
  98. */
  99. static int
  100. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  101. const char *doing, int severity)
  102. {
  103. int err = SSL_get_error(tls->ssl, r);
  104. switch (err) {
  105. case SSL_ERROR_NONE:
  106. return TOR_TLS_DONE;
  107. case SSL_ERROR_WANT_READ:
  108. return TOR_TLS_WANTREAD;
  109. case SSL_ERROR_WANT_WRITE:
  110. return TOR_TLS_WANTWRITE;
  111. case SSL_ERROR_SYSCALL:
  112. if (extra&CATCH_SYSCALL)
  113. return _TOR_TLS_SYSCALL;
  114. if (r == 0)
  115. log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
  116. else {
  117. int e = tor_socket_errno(tls->socket);
  118. log(severity, LD_NET, "TLS error: <syscall error while %s> (errno=%d: %s)",
  119. doing, e, tor_socket_strerror(e));
  120. }
  121. tls_log_errors(severity, doing);
  122. return TOR_TLS_ERROR;
  123. case SSL_ERROR_ZERO_RETURN:
  124. if (extra&CATCH_ZERO)
  125. return _TOR_TLS_ZERORETURN;
  126. log(severity, LD_NET, "TLS error: Zero return");
  127. tls_log_errors(severity, doing);
  128. return TOR_TLS_ERROR;
  129. default:
  130. tls_log_errors(severity, doing);
  131. return TOR_TLS_ERROR;
  132. }
  133. }
  134. /** Initialize OpenSSL, unless it has already been initialized.
  135. */
  136. static void
  137. tor_tls_init(void)
  138. {
  139. if (!tls_library_is_initialized) {
  140. SSL_library_init();
  141. SSL_load_error_strings();
  142. crypto_global_init(-1);
  143. tls_library_is_initialized = 1;
  144. }
  145. }
  146. void
  147. tor_tls_free_all(void)
  148. {
  149. if (global_tls_context) {
  150. SSL_CTX_free(global_tls_context->ctx);
  151. SSL_CTX_free(global_tls_context->client_only_ctx);
  152. tor_free(global_tls_context);
  153. global_tls_context = NULL;
  154. }
  155. }
  156. /** We need to give OpenSSL a callback to verify certificates. This is
  157. * it: We always accept peer certs and complete the handshake. We
  158. * don't validate them until later.
  159. */
  160. static int
  161. always_accept_verify_cb(int preverify_ok,
  162. X509_STORE_CTX *x509_ctx)
  163. {
  164. /* avoid "unused parameter" warning. */
  165. preverify_ok = 0;
  166. x509_ctx = NULL;
  167. return 1;
  168. }
  169. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  170. * signed by the private key <b>rsa_sign</b>. The commonName of the
  171. * certificate will be <b>cname</b>; the commonName of the issuer will be
  172. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  173. * starting from now. Return a certificate on success, NULL on
  174. * failure.
  175. */
  176. static X509 *
  177. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  178. crypto_pk_env_t *rsa_sign,
  179. const char *cname,
  180. const char *cname_sign,
  181. unsigned int cert_lifetime)
  182. {
  183. time_t start_time, end_time;
  184. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  185. X509 *x509 = NULL;
  186. X509_NAME *name = NULL, *name_issuer=NULL;
  187. int nid;
  188. tor_tls_init();
  189. start_time = time(NULL);
  190. tor_assert(rsa);
  191. tor_assert(cname);
  192. tor_assert(rsa_sign);
  193. tor_assert(cname_sign);
  194. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  195. goto error;
  196. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  197. goto error;
  198. if (!(x509 = X509_new()))
  199. goto error;
  200. if (!(X509_set_version(x509, 2)))
  201. goto error;
  202. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  203. goto error;
  204. if (!(name = X509_NAME_new()))
  205. goto error;
  206. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
  207. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  208. (unsigned char*)"TOR", -1, -1, 0))) goto error;
  209. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  210. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  211. (unsigned char*)cname, -1, -1, 0))) goto error;
  212. if (!(X509_set_subject_name(x509, name)))
  213. goto error;
  214. if (!(name_issuer = X509_NAME_new()))
  215. goto error;
  216. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
  217. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  218. (unsigned char*)"TOR", -1, -1, 0))) goto error;
  219. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  220. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  221. (unsigned char*)cname_sign, -1, -1, 0))) goto error;
  222. if (!(X509_set_issuer_name(x509, name_issuer)))
  223. goto error;
  224. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  225. goto error;
  226. end_time = start_time + cert_lifetime;
  227. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  228. goto error;
  229. if (!X509_set_pubkey(x509, pkey))
  230. goto error;
  231. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  232. goto error;
  233. goto done;
  234. error:
  235. if (x509) {
  236. X509_free(x509);
  237. x509 = NULL;
  238. }
  239. done:
  240. tls_log_errors(LOG_WARN, "generating certificate");
  241. if (sign_pkey)
  242. EVP_PKEY_free(sign_pkey);
  243. if (pkey)
  244. EVP_PKEY_free(pkey);
  245. if (name)
  246. X509_NAME_free(name);
  247. if (name_issuer)
  248. X509_NAME_free(name_issuer);
  249. return x509;
  250. }
  251. #ifdef EVERYONE_HAS_AES
  252. /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
  253. * is needed. */
  254. #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
  255. #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
  256. /* Some people are running OpenSSL before 0.9.7, but we aren't.
  257. * We can support AES and 3DES.
  258. */
  259. #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  260. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  261. #else
  262. /* We're running OpenSSL before 0.9.7. We only support 3DES. */
  263. #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
  264. #endif
  265. static DH *
  266. dh_callback(SSL *ssl, int is_export, int keylength)
  267. {
  268. DH *dh;
  269. crypto_dh_env_t *env = crypto_dh_new();
  270. crypto_dh_generate_public(env);
  271. dh = _crypto_dh_env_get_dh(env);
  272. notice(LD_CRYPTO, "%d references to the DH key?", dh->references);
  273. ++dh->references;
  274. crypto_dh_free(env);
  275. --dh->references;
  276. notice(LD_CRYPTO, "%d references to the DH key!", dh->references);
  277. return dh;
  278. }
  279. /** Create a new TLS context. If we are going to be using it as a
  280. * server, it must have isServer set to true, <b>identity</b> set to the
  281. * identity key used to sign that certificate, and <b>nickname</b> set to
  282. * the server's nickname. If we're only going to be a client,
  283. * isServer should be false, identity should be NULL, and nickname
  284. * should be NULL. Return -1 if failure, else 0.
  285. *
  286. * You can call this function multiple times. Each time you call it,
  287. * it generates new certificates; all new connections will use
  288. * the new SSL context.
  289. */
  290. int
  291. tor_tls_context_new(crypto_pk_env_t *identity,
  292. int isServer, const char *nickname,
  293. unsigned int key_lifetime)
  294. {
  295. crypto_pk_env_t *rsa = NULL;
  296. crypto_dh_env_t *dh = NULL;
  297. EVP_PKEY *pkey = NULL;
  298. tor_tls_context_t *result = NULL;
  299. X509 *cert = NULL, *idcert = NULL;
  300. char nn2[128];
  301. int client_only;
  302. SSL_CTX **ctx;
  303. if (!nickname)
  304. nickname = "null";
  305. tor_snprintf(nn2, sizeof(nn2), "%s <identity>", nickname);
  306. tor_tls_init();
  307. if (isServer) {
  308. /* Generate short-term RSA key. */
  309. if (!(rsa = crypto_new_pk_env()))
  310. goto error;
  311. if (crypto_pk_generate_key(rsa)<0)
  312. goto error;
  313. /* Create certificate signed by identity key. */
  314. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  315. key_lifetime);
  316. /* Create self-signed certificate for identity key. */
  317. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  318. IDENTITY_CERT_LIFETIME);
  319. if (!cert || !idcert) {
  320. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  321. goto error;
  322. }
  323. }
  324. result = tor_malloc(sizeof(tor_tls_context_t));
  325. result->ctx = result->client_only_ctx = NULL;
  326. for (client_only=0; client_only <= 1; ++client_only) {
  327. ctx = client_only ? &result->client_only_ctx : &result->ctx;
  328. #ifdef EVERYONE_HAS_AES
  329. /* Tell OpenSSL to only use TLS1 */
  330. if (!(*ctx = SSL_CTX_new(TLSv1_method())))
  331. goto error;
  332. #else
  333. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  334. if (!(*ctx = SSL_CTX_new(SSLv23_method())))
  335. goto error;
  336. SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
  337. #endif
  338. SSL_CTX_set_options(*ctx, SSL_OP_SINGLE_DH_USE);
  339. if (!SSL_CTX_set_cipher_list(*ctx, CIPHER_LIST))
  340. goto error;
  341. if (!client_only) {
  342. if (cert && !SSL_CTX_use_certificate(*ctx,cert))
  343. goto error;
  344. X509_free(cert); /* We just added a reference to cert. */
  345. cert=NULL;
  346. if (idcert && !SSL_CTX_add_extra_chain_cert(*ctx,idcert))
  347. goto error;
  348. idcert=NULL; /* The context now owns the reference to idcert */
  349. }
  350. SSL_CTX_set_session_cache_mode(*ctx, SSL_SESS_CACHE_OFF);
  351. if (isServer && !client_only) {
  352. tor_assert(rsa);
  353. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  354. goto error;
  355. if (!SSL_CTX_use_PrivateKey(*ctx, pkey))
  356. goto error;
  357. EVP_PKEY_free(pkey);
  358. pkey = NULL;
  359. if (!SSL_CTX_check_private_key(*ctx))
  360. goto error;
  361. }
  362. SSL_CTX_set_tmp_dh_callback(*ctx, dh_callback);
  363. SSL_CTX_set_verify(*ctx, SSL_VERIFY_PEER,
  364. always_accept_verify_cb);
  365. /* let us realloc bufs that we're writing from */
  366. SSL_CTX_set_mode(*ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  367. }
  368. /* Free the old context if one exists. */
  369. if (global_tls_context) {
  370. /* This is safe even if there are open connections: OpenSSL does
  371. * reference counting with SSL and SSL_CTX objects. */
  372. SSL_CTX_free(global_tls_context->ctx);
  373. SSL_CTX_free(global_tls_context->client_only_ctx);
  374. tor_free(global_tls_context);
  375. }
  376. global_tls_context = result;
  377. if (rsa)
  378. crypto_free_pk_env(rsa);
  379. return 0;
  380. error:
  381. tls_log_errors(LOG_WARN, "creating TLS context");
  382. if (pkey)
  383. EVP_PKEY_free(pkey);
  384. if (rsa)
  385. crypto_free_pk_env(rsa);
  386. if (dh)
  387. crypto_dh_free(dh);
  388. if (result && result->ctx)
  389. SSL_CTX_free(result->ctx);
  390. if (result && result->client_only_ctx)
  391. SSL_CTX_free(result->client_only_ctx);
  392. if (result)
  393. tor_free(result);
  394. if (cert)
  395. X509_free(cert);
  396. if (idcert)
  397. X509_free(idcert);
  398. return -1;
  399. }
  400. /** Create a new TLS object from a file descriptor, and a flag to
  401. * determine whether it is functioning as a server.
  402. */
  403. tor_tls_t *
  404. tor_tls_new(int sock, int isServer, int use_no_cert)
  405. {
  406. tor_tls_t *result = tor_malloc(sizeof(tor_tls_t));
  407. SSL_CTX *ctx;
  408. tor_assert(global_tls_context); /* make sure somebody made it first */
  409. ctx = use_no_cert ? global_tls_context->client_only_ctx
  410. : global_tls_context->ctx;
  411. if (!(result->ssl = SSL_new(ctx))) {
  412. tls_log_errors(LOG_WARN, "generating TLS context");
  413. tor_free(result);
  414. return NULL;
  415. }
  416. result->socket = sock;
  417. SSL_set_fd(result->ssl, sock);
  418. result->state = TOR_TLS_ST_HANDSHAKE;
  419. result->isServer = isServer;
  420. result->wantwrite_n = 0;
  421. SSL_set_tmp_dh_callback(result->ssl,dh_callback);
  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, "Peer certificate nickname \"%s\" has illegal characters.",
  630. buf);
  631. if (strchr(buf, '.'))
  632. warn(LD_PROTOCOL, " (Maybe it is not really running Tor at its advertised OR port.)");
  633. goto error;
  634. }
  635. r = 0;
  636. error:
  637. if (cert)
  638. X509_free(cert);
  639. tls_log_errors(LOG_WARN, "getting peer certificate nickname");
  640. return r;
  641. }
  642. static void
  643. log_cert_lifetime(X509 *cert, const char *problem)
  644. {
  645. BIO *bio = NULL;
  646. BUF_MEM *buf;
  647. char *s1=NULL, *s2=NULL;
  648. char mytime[33];
  649. time_t now = time(NULL);
  650. struct tm tm;
  651. if (problem)
  652. warn(LD_GENERAL,"Certificate %s: is your system clock set incorrectly?",
  653. problem);
  654. if (!(bio = BIO_new(BIO_s_mem()))) {
  655. warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  656. }
  657. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  658. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  659. goto end;
  660. }
  661. BIO_get_mem_ptr(bio, &buf);
  662. s1 = tor_strndup(buf->data, buf->length);
  663. BIO_reset(bio);
  664. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  665. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  666. goto end;
  667. }
  668. BIO_get_mem_ptr(bio, &buf);
  669. s2 = tor_strndup(buf->data, buf->length);
  670. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  671. warn(LD_GENERAL, "(certificate lifetime runs from %s through %s. Your time is %s.)",s1,s2,mytime);
  672. end:
  673. /* Not expected to get invoked */
  674. tls_log_errors(LOG_WARN, "getting certificate lifetime");
  675. if (bio)
  676. BIO_free(bio);
  677. if (s1)
  678. tor_free(s1);
  679. if (s2)
  680. tor_free(s2);
  681. }
  682. /** If the provided tls connection is authenticated and has a
  683. * certificate that is currently valid and signed, then set
  684. * *<b>identity_key</b> to the identity certificate's key and return
  685. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  686. */
  687. int
  688. tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  689. {
  690. X509 *cert = NULL, *id_cert = NULL;
  691. STACK_OF(X509) *chain = NULL;
  692. EVP_PKEY *id_pkey = NULL;
  693. RSA *rsa;
  694. int num_in_chain;
  695. int r = -1, i;
  696. *identity_key = NULL;
  697. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  698. goto done;
  699. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  700. goto done;
  701. num_in_chain = sk_X509_num(chain);
  702. /* 1 means we're receiving (server-side), and it's just the id_cert.
  703. * 2 means we're connecting (client-side), and it's both the link
  704. * cert and the id_cert.
  705. */
  706. if (num_in_chain < 1) {
  707. log_fn(severity,LD_PROTOCOL,"Unexpected number of certificates in chain (%d)",
  708. num_in_chain);
  709. goto done;
  710. }
  711. for (i=0; i<num_in_chain; ++i) {
  712. id_cert = sk_X509_value(chain, i);
  713. if (X509_cmp(id_cert, cert) != 0)
  714. break;
  715. }
  716. if (!id_cert) {
  717. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  718. goto done;
  719. }
  720. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  721. X509_verify(cert, id_pkey) <= 0) {
  722. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  723. tls_log_errors(severity,"verifying certificate");
  724. goto done;
  725. }
  726. rsa = EVP_PKEY_get1_RSA(id_pkey);
  727. if (!rsa)
  728. goto done;
  729. *identity_key = _crypto_new_pk_env_rsa(rsa);
  730. r = 0;
  731. done:
  732. if (cert)
  733. X509_free(cert);
  734. if (id_pkey)
  735. EVP_PKEY_free(id_pkey);
  736. /* This should never get invoked, but let's make sure in case OpenSSL
  737. * acts unexpectedly. */
  738. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  739. return r;
  740. }
  741. /** Check whether the certificate set on the connection <b>tls</b> is
  742. * expired or not-yet-valid, give or take <b>tolerance</b>
  743. * seconds. Return 0 for valid, -1 for failure.
  744. *
  745. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  746. */
  747. int
  748. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  749. {
  750. time_t now, t;
  751. X509 *cert;
  752. int r = -1;
  753. now = time(NULL);
  754. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  755. goto done;
  756. t = now + tolerance;
  757. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  758. log_cert_lifetime(cert, "not yet valid");
  759. goto done;
  760. }
  761. t = now - tolerance;
  762. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  763. log_cert_lifetime(cert, "already expired");
  764. goto done;
  765. }
  766. r = 0;
  767. done:
  768. if (cert)
  769. X509_free(cert);
  770. /* Not expected to get invoked */
  771. tls_log_errors(LOG_WARN, "checking certificate lifetime");
  772. return r;
  773. }
  774. /** Return the number of bytes available for reading from <b>tls</b>.
  775. */
  776. int
  777. tor_tls_get_pending_bytes(tor_tls_t *tls)
  778. {
  779. tor_assert(tls);
  780. #if OPENSSL_VERSION_NUMBER < 0x0090700fl
  781. if (tls->ssl->rstate == SSL_ST_READ_BODY)
  782. return 0;
  783. if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
  784. return 0;
  785. #endif
  786. return SSL_pending(tls->ssl);
  787. }
  788. /** Return the number of bytes read across the underlying socket. */
  789. unsigned long
  790. tor_tls_get_n_bytes_read(tor_tls_t *tls)
  791. {
  792. tor_assert(tls);
  793. return BIO_number_read(SSL_get_rbio(tls->ssl));
  794. }
  795. /** Return the number of bytes written across the underlying socket. */
  796. unsigned long
  797. tor_tls_get_n_bytes_written(tor_tls_t *tls)
  798. {
  799. tor_assert(tls);
  800. return BIO_number_written(SSL_get_wbio(tls->ssl));
  801. }
  802. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  803. * errors, log an error message and assert(0). */
  804. void
  805. _check_no_tls_errors(const char *fname, int line)
  806. {
  807. if (ERR_peek_error() == 0)
  808. return;
  809. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  810. tor_fix_source_file(fname), line);
  811. tls_log_errors(LOG_WARN, NULL);
  812. }