tortls.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. /* Copyright 2003 Roger Dingledine.
  2. * Copyright 2004-2007 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 <assert.h>
  18. #include <openssl/ssl.h>
  19. #include <openssl/ssl3.h>
  20. #include <openssl/err.h>
  21. #include <openssl/tls1.h>
  22. #include <openssl/asn1.h>
  23. #include <openssl/bio.h>
  24. #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
  25. #include "./crypto.h"
  26. #include "./tortls.h"
  27. #include "./util.h"
  28. #include "./log.h"
  29. #include <string.h>
  30. /* Copied from or.h */
  31. #define LEGAL_NICKNAME_CHARACTERS \
  32. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  33. /** How long do identity certificates live? (sec) */
  34. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  35. /** Structure holding the TLS state for a single connection. */
  36. typedef struct tor_tls_context_t {
  37. int refcnt;
  38. SSL_CTX *ctx;
  39. X509 *my_cert;
  40. X509 *my_id_cert;
  41. crypto_pk_env_t *key;
  42. } tor_tls_context_t;
  43. /** Holds a SSL object and its associated data. Members are only
  44. * accessed from within tortls.c.
  45. */
  46. struct tor_tls_t {
  47. tor_tls_context_t *context; /**DOCDOC */
  48. SSL *ssl; /**< An OpenSSL SSL object. */
  49. int socket; /**< The underlying file descriptor for this TLS connection. */
  50. enum {
  51. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  52. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
  53. } state : 7; /**< The current SSL state, depending on which operations have
  54. * completed successfully. */
  55. unsigned int isServer:1; /**< True iff this is a server-side connection */
  56. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
  57. * time. */
  58. unsigned long last_write_count;
  59. unsigned long last_read_count;
  60. };
  61. static void tor_tls_context_decref(tor_tls_context_t *ctx);
  62. static void tor_tls_context_incref(tor_tls_context_t *ctx);
  63. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  64. crypto_pk_env_t *rsa_sign,
  65. const char *cname,
  66. const char *cname_sign,
  67. unsigned int lifetime);
  68. /** Global tls context. We keep it here because nobody else needs to
  69. * touch it. */
  70. static tor_tls_context_t *global_tls_context = NULL;
  71. /** True iff tor_tls_init() has been called. */
  72. static int tls_library_is_initialized = 0;
  73. /* Module-internal error codes. */
  74. #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
  75. #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
  76. /** Log all pending tls errors at level <b>severity</b>. Use
  77. * <b>doing</b> to describe our current activities.
  78. */
  79. static void
  80. tls_log_errors(int severity, const char *doing)
  81. {
  82. int err;
  83. const char *msg, *lib, *func;
  84. while ((err = ERR_get_error()) != 0) {
  85. msg = (const char*)ERR_reason_error_string(err);
  86. lib = (const char*)ERR_lib_error_string(err);
  87. func = (const char*)ERR_func_error_string(err);
  88. if (!msg) msg = "(null)";
  89. if (doing) {
  90. log(severity, LD_NET, "TLS error while %s: %s (in %s:%s)",
  91. doing, msg, lib,func);
  92. } else {
  93. log(severity, LD_NET, "TLS error: %s (in %s:%s)", msg, lib, func);
  94. }
  95. }
  96. }
  97. /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
  98. * code. */
  99. static int
  100. tor_errno_to_tls_error(int e)
  101. {
  102. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  103. switch (e) {
  104. case WSAECONNRESET: // most common
  105. return TOR_TLS_ERROR_CONNRESET;
  106. case WSAETIMEDOUT:
  107. return TOR_TLS_ERROR_TIMEOUT;
  108. case WSAENETUNREACH:
  109. case WSAEHOSTUNREACH:
  110. return TOR_TLS_ERROR_NO_ROUTE;
  111. case WSAECONNREFUSED:
  112. return TOR_TLS_ERROR_CONNREFUSED; // least common
  113. default:
  114. return TOR_TLS_ERROR_MISC;
  115. }
  116. #else
  117. switch (e) {
  118. case ECONNRESET: // most common
  119. return TOR_TLS_ERROR_CONNRESET;
  120. case ETIMEDOUT:
  121. return TOR_TLS_ERROR_TIMEOUT;
  122. case EHOSTUNREACH:
  123. case ENETUNREACH:
  124. return TOR_TLS_ERROR_NO_ROUTE;
  125. case ECONNREFUSED:
  126. return TOR_TLS_ERROR_CONNREFUSED; // least common
  127. default:
  128. return TOR_TLS_ERROR_MISC;
  129. }
  130. #endif
  131. }
  132. /** DOCDOC */
  133. const char *
  134. tor_tls_err_to_string(int err)
  135. {
  136. if (err >= 0)
  137. return "[Not an error.]";
  138. switch (err) {
  139. case TOR_TLS_ERROR_MISC: return "misc error";
  140. case TOR_TLS_ERROR_IO: return "unexpected close";
  141. case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
  142. case TOR_TLS_ERROR_CONNRESET: return "connection reset";
  143. case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
  144. case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
  145. case TOR_TLS_CLOSE: return "closed";
  146. case TOR_TLS_WANTREAD: return "want to read";
  147. case TOR_TLS_WANTWRITE: return "want to write";
  148. default: return "(unknown error code)";
  149. }
  150. }
  151. #define CATCH_SYSCALL 1
  152. #define CATCH_ZERO 2
  153. /** Given a TLS object and the result of an SSL_* call, use
  154. * SSL_get_error to determine whether an error has occurred, and if so
  155. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  156. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  157. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  158. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  159. *
  160. * If an error has occurred, log it at level <b>severity</b> and describe the
  161. * current action as <b>doing</b>.
  162. */
  163. static int
  164. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  165. const char *doing, int severity)
  166. {
  167. int err = SSL_get_error(tls->ssl, r);
  168. int tor_error = TOR_TLS_ERROR_MISC;
  169. switch (err) {
  170. case SSL_ERROR_NONE:
  171. return TOR_TLS_DONE;
  172. case SSL_ERROR_WANT_READ:
  173. return TOR_TLS_WANTREAD;
  174. case SSL_ERROR_WANT_WRITE:
  175. return TOR_TLS_WANTWRITE;
  176. case SSL_ERROR_SYSCALL:
  177. if (extra&CATCH_SYSCALL)
  178. return _TOR_TLS_SYSCALL;
  179. if (r == 0) {
  180. log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
  181. tor_error = TOR_TLS_ERROR_IO;
  182. } else {
  183. int e = tor_socket_errno(tls->socket);
  184. log(severity, LD_NET,
  185. "TLS error: <syscall error while %s> (errno=%d: %s)",
  186. doing, e, tor_socket_strerror(e));
  187. tor_error = tor_errno_to_tls_error(e);
  188. }
  189. tls_log_errors(severity, doing);
  190. return tor_error;
  191. case SSL_ERROR_ZERO_RETURN:
  192. if (extra&CATCH_ZERO)
  193. return _TOR_TLS_ZERORETURN;
  194. log(severity, LD_NET, "TLS error: Zero return");
  195. tls_log_errors(severity, doing);
  196. /* XXXX020 Actually, a 'zero return' error has a pretty specific meaning:
  197. * the connection has been closed cleanly. */
  198. return TOR_TLS_ERROR_MISC;
  199. default:
  200. tls_log_errors(severity, doing);
  201. return TOR_TLS_ERROR_MISC;
  202. }
  203. }
  204. /** Initialize OpenSSL, unless it has already been initialized.
  205. */
  206. static void
  207. tor_tls_init(void)
  208. {
  209. if (!tls_library_is_initialized) {
  210. SSL_library_init();
  211. SSL_load_error_strings();
  212. crypto_global_init(-1);
  213. tls_library_is_initialized = 1;
  214. }
  215. }
  216. /** Free all global TLS structures. */
  217. void
  218. tor_tls_free_all(void)
  219. {
  220. if (global_tls_context) {
  221. tor_tls_context_decref(global_tls_context);
  222. global_tls_context = NULL;
  223. }
  224. }
  225. /** We need to give OpenSSL a callback to verify certificates. This is
  226. * it: We always accept peer certs and complete the handshake. We
  227. * don't validate them until later.
  228. */
  229. static int
  230. always_accept_verify_cb(int preverify_ok,
  231. X509_STORE_CTX *x509_ctx)
  232. {
  233. /* avoid "unused parameter" warning. */
  234. preverify_ok = 0;
  235. x509_ctx = NULL;
  236. return 1;
  237. }
  238. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  239. * signed by the private key <b>rsa_sign</b>. The commonName of the
  240. * certificate will be <b>cname</b>; the commonName of the issuer will be
  241. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  242. * starting from now. Return a certificate on success, NULL on
  243. * failure.
  244. */
  245. static X509 *
  246. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  247. crypto_pk_env_t *rsa_sign,
  248. const char *cname,
  249. const char *cname_sign,
  250. unsigned int cert_lifetime)
  251. {
  252. time_t start_time, end_time;
  253. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  254. X509 *x509 = NULL;
  255. X509_NAME *name = NULL, *name_issuer=NULL;
  256. int nid;
  257. tor_tls_init();
  258. start_time = time(NULL);
  259. tor_assert(rsa);
  260. tor_assert(cname);
  261. tor_assert(rsa_sign);
  262. tor_assert(cname_sign);
  263. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  264. goto error;
  265. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  266. goto error;
  267. if (!(x509 = X509_new()))
  268. goto error;
  269. if (!(X509_set_version(x509, 2)))
  270. goto error;
  271. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  272. goto error;
  273. if (!(name = X509_NAME_new()))
  274. goto error;
  275. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
  276. goto error;
  277. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  278. (unsigned char*)"t o r", -1, -1, 0)))
  279. goto error;
  280. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  281. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  282. (unsigned char*)cname, -1, -1, 0)))
  283. goto error;
  284. if (!(X509_set_subject_name(x509, name)))
  285. goto error;
  286. if (!(name_issuer = X509_NAME_new()))
  287. goto error;
  288. if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
  289. goto error;
  290. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  291. (unsigned char*)"t o r", -1, -1, 0)))
  292. goto error;
  293. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  294. if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
  295. (unsigned char*)cname_sign, -1, -1, 0)))
  296. goto error;
  297. if (!(X509_set_issuer_name(x509, name_issuer)))
  298. goto error;
  299. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  300. goto error;
  301. end_time = start_time + cert_lifetime;
  302. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  303. goto error;
  304. if (!X509_set_pubkey(x509, pkey))
  305. goto error;
  306. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  307. goto error;
  308. goto done;
  309. error:
  310. if (x509) {
  311. X509_free(x509);
  312. x509 = NULL;
  313. }
  314. done:
  315. tls_log_errors(LOG_WARN, "generating certificate");
  316. if (sign_pkey)
  317. EVP_PKEY_free(sign_pkey);
  318. if (pkey)
  319. EVP_PKEY_free(pkey);
  320. if (name)
  321. X509_NAME_free(name);
  322. if (name_issuer)
  323. X509_NAME_free(name_issuer);
  324. return x509;
  325. }
  326. #ifdef EVERYONE_HAS_AES
  327. /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
  328. * is needed. */
  329. #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
  330. #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
  331. /* Some people are running OpenSSL before 0.9.7, but we aren't.
  332. * We can support AES and 3DES.
  333. */
  334. #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  335. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  336. /* Note: for setting up your own private testing network with link
  337. * crypto disabled, set your cipher list to SSL3_TXT_RSA_NULL_SHA.
  338. * If you do this, you won't be able to communicate with any of the
  339. * "real" Tors, though. */
  340. #else
  341. #error "Tor requires OpenSSL version 0.9.7 or later, for AES support."
  342. #endif
  343. /** DOCDOC */
  344. static void
  345. tor_tls_context_decref(tor_tls_context_t *ctx)
  346. {
  347. tor_assert(ctx);
  348. if (--ctx->refcnt == 0) {
  349. SSL_CTX_free(ctx->ctx);
  350. X509_free(ctx->my_cert);
  351. X509_free(ctx->my_id_cert);
  352. crypto_free_pk_env(ctx->key);
  353. tor_free(ctx);
  354. }
  355. }
  356. /** DOCDOC */
  357. static void
  358. tor_tls_context_incref(tor_tls_context_t *ctx)
  359. {
  360. ++ctx->refcnt;
  361. }
  362. /** Create a new TLS context for use with Tor TLS handshakes.
  363. * <b>identity</b> should be set to the identity key used to sign the
  364. * certificate, and <b>nickname</b> set to the nickname to use.
  365. *
  366. * You can call this function multiple times. Each time you call it,
  367. * it generates new certificates; all new connections will use
  368. * the new SSL context.
  369. */
  370. int
  371. tor_tls_context_new(crypto_pk_env_t *identity, const char *nickname,
  372. unsigned int key_lifetime)
  373. {
  374. crypto_pk_env_t *rsa = NULL;
  375. crypto_dh_env_t *dh = NULL;
  376. EVP_PKEY *pkey = NULL;
  377. tor_tls_context_t *result = NULL;
  378. X509 *cert = NULL, *idcert = NULL;
  379. char nn2[128];
  380. if (!nickname)
  381. nickname = "null";
  382. tor_snprintf(nn2, sizeof(nn2), "%s <signing>", nickname);
  383. tor_tls_init();
  384. /* Generate short-term RSA key. */
  385. if (!(rsa = crypto_new_pk_env()))
  386. goto error;
  387. if (crypto_pk_generate_key(rsa)<0)
  388. goto error;
  389. /* Create certificate signed by identity key. */
  390. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  391. key_lifetime);
  392. /* Create self-signed certificate for identity key. */
  393. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  394. IDENTITY_CERT_LIFETIME);
  395. if (!cert || !idcert) {
  396. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  397. goto error;
  398. }
  399. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  400. result->refcnt = 1;
  401. result->my_cert = X509_dup(cert);
  402. result->my_id_cert = X509_dup(idcert);
  403. result->key = crypto_pk_dup_key(rsa);
  404. #ifdef EVERYONE_HAS_AES
  405. /* Tell OpenSSL to only use TLS1 */
  406. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  407. goto error;
  408. #else
  409. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  410. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  411. goto error;
  412. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  413. #endif
  414. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  415. if (!SSL_CTX_set_cipher_list(result->ctx, CIPHER_LIST))
  416. goto error;
  417. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  418. goto error;
  419. X509_free(cert); /* We just added a reference to cert. */
  420. cert=NULL;
  421. #if 1
  422. if (idcert && !SSL_CTX_add_extra_chain_cert(result->ctx,idcert))
  423. goto error;
  424. #else
  425. if (idcert) {
  426. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  427. tor_assert(s);
  428. X509_STORE_add_cert(s, idcert);
  429. }
  430. #endif
  431. idcert=NULL; /* The context now owns the reference to idcert */
  432. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  433. tor_assert(rsa);
  434. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  435. goto error;
  436. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  437. goto error;
  438. EVP_PKEY_free(pkey);
  439. pkey = NULL;
  440. if (!SSL_CTX_check_private_key(result->ctx))
  441. goto error;
  442. dh = crypto_dh_new();
  443. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  444. crypto_dh_free(dh);
  445. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  446. always_accept_verify_cb);
  447. /* let us realloc bufs that we're writing from */
  448. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  449. /* Free the old context if one exists. */
  450. if (global_tls_context) {
  451. /* This is safe even if there are open connections: OpenSSL does
  452. * reference counting with SSL and SSL_CTX objects. */
  453. tor_tls_context_decref(global_tls_context);
  454. }
  455. global_tls_context = result;
  456. if (rsa)
  457. crypto_free_pk_env(rsa);
  458. return 0;
  459. error:
  460. tls_log_errors(LOG_WARN, "creating TLS context");
  461. if (pkey)
  462. EVP_PKEY_free(pkey);
  463. if (rsa)
  464. crypto_free_pk_env(rsa);
  465. if (dh)
  466. crypto_dh_free(dh);
  467. if (result)
  468. tor_tls_context_decref(result);
  469. if (cert)
  470. X509_free(cert);
  471. if (idcert)
  472. X509_free(idcert);
  473. return -1;
  474. }
  475. /** Create a new TLS object from a file descriptor, and a flag to
  476. * determine whether it is functioning as a server.
  477. */
  478. tor_tls_t *
  479. tor_tls_new(int sock, int isServer)
  480. {
  481. BIO *bio = NULL;
  482. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  483. tor_assert(global_tls_context); /* make sure somebody made it first */
  484. if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
  485. tls_log_errors(LOG_WARN, "generating TLS context");
  486. tor_free(result);
  487. return NULL;
  488. }
  489. result->socket = sock;
  490. #ifdef USE_BSOCKETS
  491. bio = BIO_new_bsocket(sock, BIO_NOCLOSE);
  492. #else
  493. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  494. #endif
  495. if (! bio) {
  496. tls_log_errors(LOG_WARN, "opening BIO");
  497. SSL_free(result->ssl);
  498. tor_free(result);
  499. return NULL;
  500. }
  501. SSL_set_bio(result->ssl, bio, bio);
  502. tor_tls_context_incref(global_tls_context);
  503. result->context = global_tls_context;
  504. result->state = TOR_TLS_ST_HANDSHAKE;
  505. result->isServer = isServer;
  506. result->wantwrite_n = 0;
  507. /* Not expected to get called. */
  508. tls_log_errors(LOG_WARN, "generating TLS context");
  509. return result;
  510. }
  511. /** Return whether this tls initiated the connect (client) or
  512. * received it (server). */
  513. int
  514. tor_tls_is_server(tor_tls_t *tls)
  515. {
  516. tor_assert(tls);
  517. return tls->isServer;
  518. }
  519. /** Release resources associated with a TLS object. Does not close the
  520. * underlying file descriptor.
  521. */
  522. void
  523. tor_tls_free(tor_tls_t *tls)
  524. {
  525. tor_assert(tls && tls->ssl);
  526. SSL_free(tls->ssl);
  527. tls->ssl = NULL;
  528. if (tls->context)
  529. tor_tls_context_decref(tls->context);
  530. tor_free(tls);
  531. }
  532. /** Underlying function for TLS reading. Reads up to <b>len</b>
  533. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  534. * number of characters read. On failure, returns TOR_TLS_ERROR,
  535. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  536. */
  537. int
  538. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  539. {
  540. int r, err;
  541. tor_assert(tls);
  542. tor_assert(tls->ssl);
  543. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  544. r = SSL_read(tls->ssl, cp, len);
  545. if (r > 0)
  546. return r;
  547. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
  548. if (err == _TOR_TLS_ZERORETURN) {
  549. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  550. tls->state = TOR_TLS_ST_CLOSED;
  551. return TOR_TLS_CLOSE;
  552. } else {
  553. tor_assert(err != TOR_TLS_DONE);
  554. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  555. return err;
  556. }
  557. }
  558. /** Underlying function for TLS writing. Write up to <b>n</b>
  559. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  560. * number of characters written. On failure, returns TOR_TLS_ERROR,
  561. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  562. */
  563. int
  564. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  565. {
  566. int r, err;
  567. tor_assert(tls);
  568. tor_assert(tls->ssl);
  569. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  570. if (n == 0)
  571. return 0;
  572. if (tls->wantwrite_n) {
  573. /* if WANTWRITE last time, we must use the _same_ n as before */
  574. tor_assert(n >= tls->wantwrite_n);
  575. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  576. (int)n, (int)tls->wantwrite_n);
  577. n = tls->wantwrite_n;
  578. tls->wantwrite_n = 0;
  579. }
  580. r = SSL_write(tls->ssl, cp, n);
  581. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  582. if (err == TOR_TLS_DONE) {
  583. return r;
  584. }
  585. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  586. tls->wantwrite_n = n;
  587. }
  588. return err;
  589. }
  590. /** Perform initial handshake on <b>tls</b>. When finished, returns
  591. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  592. * or TOR_TLS_WANTWRITE.
  593. */
  594. int
  595. tor_tls_handshake(tor_tls_t *tls)
  596. {
  597. int r;
  598. tor_assert(tls);
  599. tor_assert(tls->ssl);
  600. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  601. check_no_tls_errors();
  602. if (tls->isServer) {
  603. r = SSL_accept(tls->ssl);
  604. } else {
  605. r = SSL_connect(tls->ssl);
  606. }
  607. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  608. if (ERR_peek_error() != 0) {
  609. tls_log_errors(tls->isServer ? LOG_INFO : LOG_WARN,
  610. "handshaking");
  611. return TOR_TLS_ERROR_MISC;
  612. }
  613. if (r == TOR_TLS_DONE) {
  614. tls->state = TOR_TLS_ST_OPEN;
  615. }
  616. return r;
  617. }
  618. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  619. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  620. * or TOR_TLS_WANTWRITE.
  621. */
  622. int
  623. tor_tls_shutdown(tor_tls_t *tls)
  624. {
  625. int r, err;
  626. char buf[128];
  627. tor_assert(tls);
  628. tor_assert(tls->ssl);
  629. while (1) {
  630. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  631. /* If we've already called shutdown once to send a close message,
  632. * we read until the other side has closed too.
  633. */
  634. do {
  635. r = SSL_read(tls->ssl, buf, 128);
  636. } while (r>0);
  637. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  638. LOG_INFO);
  639. if (err == _TOR_TLS_ZERORETURN) {
  640. tls->state = TOR_TLS_ST_GOTCLOSE;
  641. /* fall through... */
  642. } else {
  643. return err;
  644. }
  645. }
  646. r = SSL_shutdown(tls->ssl);
  647. if (r == 1) {
  648. /* If shutdown returns 1, the connection is entirely closed. */
  649. tls->state = TOR_TLS_ST_CLOSED;
  650. return TOR_TLS_DONE;
  651. }
  652. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  653. LOG_INFO);
  654. if (err == _TOR_TLS_SYSCALL) {
  655. /* The underlying TCP connection closed while we were shutting down. */
  656. tls->state = TOR_TLS_ST_CLOSED;
  657. return TOR_TLS_DONE;
  658. } else if (err == _TOR_TLS_ZERORETURN) {
  659. /* The TLS connection says that it sent a shutdown record, but
  660. * isn't done shutting down yet. Make sure that this hasn't
  661. * happened before, then go back to the start of the function
  662. * and try to read.
  663. */
  664. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  665. tls->state == TOR_TLS_ST_SENTCLOSE) {
  666. log(LOG_WARN, LD_NET,
  667. "TLS returned \"half-closed\" value while already half-closed");
  668. return TOR_TLS_ERROR_MISC;
  669. }
  670. tls->state = TOR_TLS_ST_SENTCLOSE;
  671. /* fall through ... */
  672. } else {
  673. return err;
  674. }
  675. } /* end loop */
  676. }
  677. /** Return true iff this TLS connection is authenticated.
  678. */
  679. int
  680. tor_tls_peer_has_cert(tor_tls_t *tls)
  681. {
  682. X509 *cert;
  683. cert = SSL_get_peer_certificate(tls->ssl);
  684. tls_log_errors(LOG_WARN, "getting peer certificate");
  685. if (!cert)
  686. return 0;
  687. X509_free(cert);
  688. return 1;
  689. }
  690. /** DOCDOC */
  691. int
  692. tor_tls_get_cert_digests(tor_tls_t *tls,
  693. char *my_digest_out,
  694. char *peer_digest_out)
  695. {
  696. X509 *cert;
  697. unsigned int len;
  698. tor_assert(tls && tls->context);
  699. cert = tls->context->my_cert;
  700. if (cert) {
  701. X509_digest(cert, EVP_sha1(), (unsigned char*)my_digest_out, &len);
  702. if (len != DIGEST_LEN)
  703. return -1;
  704. }
  705. cert = SSL_get_peer_certificate(tls->ssl);
  706. if (cert) {
  707. X509_digest(cert, EVP_sha1(), (unsigned char*)peer_digest_out, &len);
  708. if (len != DIGEST_LEN)
  709. return -1;
  710. }
  711. return 0;
  712. }
  713. /** DOCDOC */
  714. crypto_pk_env_t *
  715. tor_tls_dup_private_key(tor_tls_t *tls)
  716. {
  717. return crypto_pk_dup_key(tls->context->key);
  718. }
  719. /** DOCDOC */
  720. char *
  721. tor_tls_encode_my_certificate(tor_tls_t *tls, size_t *size_out,
  722. int conn_cert)
  723. {
  724. unsigned char *result, *cp;
  725. int certlen;
  726. X509 *cert;
  727. tor_assert(tls && tls->context);
  728. cert = conn_cert ? tls->context->my_cert : tls->context->my_id_cert;
  729. tor_assert(cert);
  730. certlen = i2d_X509(cert, NULL);
  731. tor_assert(certlen >= 0);
  732. cp = result = tor_malloc(certlen);
  733. i2d_X509(cert, &cp);
  734. tor_assert(cp-result == certlen);
  735. *size_out = (size_t)certlen;
  736. return (char*) result;
  737. }
  738. /** Warn that a certificate lifetime extends through a certain range. */
  739. static void
  740. log_cert_lifetime(X509 *cert, const char *problem)
  741. {
  742. BIO *bio = NULL;
  743. BUF_MEM *buf;
  744. char *s1=NULL, *s2=NULL;
  745. char mytime[33];
  746. time_t now = time(NULL);
  747. struct tm tm;
  748. if (problem)
  749. log_warn(LD_GENERAL,
  750. "Certificate %s: is your system clock set incorrectly?",
  751. problem);
  752. if (!(bio = BIO_new(BIO_s_mem()))) {
  753. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  754. }
  755. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  756. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  757. goto end;
  758. }
  759. BIO_get_mem_ptr(bio, &buf);
  760. s1 = tor_strndup(buf->data, buf->length);
  761. (void)BIO_reset(bio);
  762. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  763. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  764. goto end;
  765. }
  766. BIO_get_mem_ptr(bio, &buf);
  767. s2 = tor_strndup(buf->data, buf->length);
  768. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  769. log_warn(LD_GENERAL,
  770. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  771. s1,s2,mytime);
  772. end:
  773. /* Not expected to get invoked */
  774. tls_log_errors(LOG_WARN, "getting certificate lifetime");
  775. if (bio)
  776. BIO_free(bio);
  777. if (s1)
  778. tor_free(s1);
  779. if (s2)
  780. tor_free(s2);
  781. }
  782. /** DOCDOC helper.
  783. * cert_out needs to be freed. id_cert_out doesn't. */
  784. static void
  785. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  786. X509 **cert_out, X509 **id_cert_out)
  787. {
  788. X509 *cert = NULL, *id_cert = NULL;
  789. STACK_OF(X509) *chain = NULL;
  790. int num_in_chain, i;
  791. *cert_out = *id_cert_out = NULL;
  792. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  793. return;
  794. *cert_out = cert;
  795. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  796. return;
  797. num_in_chain = sk_X509_num(chain);
  798. /* 1 means we're receiving (server-side), and it's just the id_cert.
  799. * 2 means we're connecting (client-side), and it's both the link
  800. * cert and the id_cert.
  801. */
  802. if (num_in_chain < 1) {
  803. log_fn(severity,LD_PROTOCOL,
  804. "Unexpected number of certificates in chain (%d)",
  805. num_in_chain);
  806. return;
  807. }
  808. for (i=0; i<num_in_chain; ++i) {
  809. id_cert = sk_X509_value(chain, i);
  810. if (X509_cmp(id_cert, cert) != 0)
  811. break;
  812. }
  813. *id_cert_out = id_cert;
  814. }
  815. /** If the provided tls connection is authenticated and has a
  816. * certificate that is currently valid and signed, then set
  817. * *<b>identity_key</b> to the identity certificate's key and return
  818. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  819. */
  820. int
  821. tor_tls_verify_v1(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  822. {
  823. X509 *cert = NULL, *id_cert = NULL;
  824. EVP_PKEY *id_pkey = NULL;
  825. RSA *rsa;
  826. int r = -1;
  827. *identity_key = NULL;
  828. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  829. if (!cert)
  830. goto done;
  831. if (!id_cert) {
  832. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  833. goto done;
  834. }
  835. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  836. X509_verify(cert, id_pkey) <= 0) {
  837. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  838. tls_log_errors(severity,"verifying certificate");
  839. goto done;
  840. }
  841. rsa = EVP_PKEY_get1_RSA(id_pkey);
  842. if (!rsa)
  843. goto done;
  844. *identity_key = _crypto_new_pk_env_rsa(rsa);
  845. r = 0;
  846. done:
  847. if (cert)
  848. X509_free(cert);
  849. if (id_pkey)
  850. EVP_PKEY_free(id_pkey);
  851. /* This should never get invoked, but let's make sure in case OpenSSL
  852. * acts unexpectedly. */
  853. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  854. return r;
  855. }
  856. /** DOCDOC
  857. *
  858. * Returns 1 on "verification is done", 0 on "still need LINK_AUTH."
  859. */
  860. int
  861. tor_tls_verify_certs_v2(int severity, tor_tls_t *tls,
  862. const char *cert_str, size_t cert_len,
  863. const char *id_cert_str, size_t id_cert_len,
  864. crypto_pk_env_t **cert_key_out,
  865. char *conn_cert_digest_out,
  866. crypto_pk_env_t **id_key_out,
  867. char *id_digest_out)
  868. {
  869. X509 *cert = NULL, *id_cert = NULL;
  870. EVP_PKEY *id_pkey = NULL, *cert_pkey = NULL;
  871. int free_id_cert = 0, peer_used_tls_cert = 0;
  872. int r = -1;
  873. tor_assert(cert_key_out);
  874. tor_assert(conn_cert_digest_out);
  875. tor_assert(id_key_out);
  876. tor_assert(id_digest_out);
  877. *cert_key_out = NULL;
  878. if (cert_str && cert_len) {
  879. /*XXXX020 warn on error. */
  880. const unsigned char *cp = (const unsigned char*) cert_str;
  881. cert = d2i_X509(NULL, &cp, cert_len);
  882. }
  883. if (id_cert_str && id_cert_len) {
  884. /*XXXX020 warn on error. */
  885. const unsigned char *cp = (const unsigned char*) id_cert_str;
  886. id_cert = d2i_X509(NULL, &cp, id_cert_len);
  887. if (id_cert)
  888. free_id_cert = 1;
  889. }
  890. if (cert) {
  891. int cmp = 0;
  892. X509 *cert_tmp = SSL_get_peer_certificate(tls->ssl);
  893. if (cert_tmp) {
  894. peer_used_tls_cert = 1;
  895. cmp = X509_cmp(cert, cert_tmp);
  896. X509_free(cert_tmp);
  897. }
  898. if (cmp != 0) {
  899. log_fn(severity, LD_PROTOCOL,
  900. "Certificate in CERT cell didn't match TLS cert.");
  901. goto done;
  902. }
  903. }
  904. if (!cert || !id_cert) {
  905. X509 *c=NULL, *id=NULL;
  906. try_to_extract_certs_from_tls(severity, tls, &c, &id);
  907. if (c) {
  908. if (!cert)
  909. cert = c;
  910. else
  911. X509_free(c);
  912. }
  913. if (id && !id_cert)
  914. id_cert = id;
  915. }
  916. if (!id_cert || !cert)
  917. goto done;
  918. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  919. X509_verify(cert, id_pkey) <= 0) {
  920. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  921. tls_log_errors(severity,"verifying certificate");
  922. goto done;
  923. }
  924. if (!(*id_key_out = _crypto_new_pk_env_evp_pkey(id_pkey)))
  925. goto done;
  926. crypto_pk_get_digest(*id_key_out, id_digest_out);
  927. if (!(cert_pkey = X509_get_pubkey(cert)))
  928. goto done;
  929. if (!(*cert_key_out = _crypto_new_pk_env_evp_pkey(cert_pkey)))
  930. goto done;
  931. {
  932. unsigned int len = 0;
  933. X509_digest(cert, EVP_sha1(), (unsigned char*)conn_cert_digest_out, &len);
  934. tor_assert(len == DIGEST_LEN);
  935. }
  936. r = peer_used_tls_cert ? 1 : 0;
  937. done:
  938. if (cert)
  939. X509_free(cert);
  940. if (id_cert && free_id_cert)
  941. X509_free(id_cert);
  942. if (id_pkey)
  943. EVP_PKEY_free(id_pkey);
  944. if (cert_pkey)
  945. EVP_PKEY_free(cert_pkey);
  946. return r;
  947. }
  948. /** Check whether the certificate set on the connection <b>tls</b> is
  949. * expired or not-yet-valid, give or take <b>tolerance</b>
  950. * seconds. Return 0 for valid, -1 for failure.
  951. *
  952. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  953. */
  954. int
  955. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  956. {
  957. time_t now, t;
  958. X509 *cert;
  959. int r = -1;
  960. now = time(NULL);
  961. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  962. goto done;
  963. t = now + tolerance;
  964. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  965. log_cert_lifetime(cert, "not yet valid");
  966. goto done;
  967. }
  968. t = now - tolerance;
  969. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  970. log_cert_lifetime(cert, "already expired");
  971. goto done;
  972. }
  973. r = 0;
  974. done:
  975. if (cert)
  976. X509_free(cert);
  977. /* Not expected to get invoked */
  978. tls_log_errors(LOG_WARN, "checking certificate lifetime");
  979. return r;
  980. }
  981. /** Return the number of bytes available for reading from <b>tls</b>.
  982. */
  983. int
  984. tor_tls_get_pending_bytes(tor_tls_t *tls)
  985. {
  986. tor_assert(tls);
  987. return SSL_pending(tls->ssl);
  988. }
  989. /** If <b>tls</b> requires that the next write be of a particular size,
  990. * return that size. Otherwise, return 0. */
  991. size_t
  992. tor_tls_get_forced_write_size(tor_tls_t *tls)
  993. {
  994. return tls->wantwrite_n;
  995. }
  996. /** Sets n_read and n_written to the number of bytes read and written,
  997. * respectivey, on the raw socket used by <b>tls</b> since the last time this
  998. * function was called on <b>tls</b>. */
  999. void
  1000. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1001. {
  1002. unsigned long r, w;
  1003. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1004. w = BIO_number_written(SSL_get_wbio(tls->ssl));
  1005. /* We are ok with letting these unsigned ints go "negative" here:
  1006. * If we wrapped around, this should still give us the right answer, unless
  1007. * we wrapped around by more than ULONG_MAX since the last time we called
  1008. * this function.
  1009. */
  1010. *n_read = (size_t)(r - tls->last_read_count);
  1011. *n_written = (size_t)(w - tls->last_write_count);
  1012. tls->last_read_count = r;
  1013. tls->last_write_count = w;
  1014. }
  1015. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1016. * errors, log an error message. */
  1017. void
  1018. _check_no_tls_errors(const char *fname, int line)
  1019. {
  1020. if (ERR_peek_error() == 0)
  1021. return;
  1022. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1023. tor_fix_source_file(fname), line);
  1024. tls_log_errors(LOG_WARN, NULL);
  1025. }
  1026. /**DOCDOC */
  1027. int
  1028. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1029. {
  1030. (void)tls;
  1031. return 1;
  1032. }
  1033. #if SSL3_RANDOM_SIZE != TOR_TLS_RANDOM_LEN
  1034. #error "The TOR_TLS_RANDOM_LEN macro is defined incorrectly. That's a bug."
  1035. #endif
  1036. /** DOCDOC */
  1037. int
  1038. tor_tls_get_random_values(tor_tls_t *tls, char *client_random_out,
  1039. char *server_random_out)
  1040. {
  1041. tor_assert(tls && tls->ssl);
  1042. if (!tls->ssl->s3)
  1043. return -1;
  1044. memcpy(client_random_out, tls->ssl->s3->client_random, SSL3_RANDOM_SIZE);
  1045. memcpy(server_random_out, tls->ssl->s3->server_random, SSL3_RANDOM_SIZE);
  1046. return 0;
  1047. }
  1048. /** DOCDOC */
  1049. int
  1050. tor_tls_hmac_with_master_secret(tor_tls_t *tls, char *hmac_out,
  1051. const char *data, size_t data_len)
  1052. {
  1053. SSL_SESSION *s;
  1054. tor_assert(tls && tls->ssl);
  1055. if (!(s = SSL_get_session(tls->ssl)))
  1056. return -1;
  1057. if (s->master_key_length < 0)
  1058. return -1;
  1059. crypto_hmac_sha1(hmac_out,
  1060. (const char*)s->master_key,
  1061. (size_t)s->master_key_length,
  1062. data, data_len);
  1063. return 0;
  1064. }