tortls.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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. char *id_digest_out)
  867. {
  868. X509 *cert = NULL, *id_cert = NULL;
  869. EVP_PKEY *id_pkey = NULL, *cert_pkey = NULL;
  870. int free_id_cert = 0, peer_used_tls_cert = 0;
  871. int r = -1;
  872. tor_assert(cert_key_out);
  873. tor_assert(conn_cert_digest_out);
  874. tor_assert(id_digest_out);
  875. *cert_key_out = NULL;
  876. if (cert_str && cert_len) {
  877. /*XXXX020 warn on error. */
  878. const unsigned char *cp = (const unsigned char*) cert_str;
  879. cert = d2i_X509(NULL, &cp, cert_len);
  880. }
  881. if (id_cert_str && id_cert_len) {
  882. /*XXXX020 warn on error. */
  883. const unsigned char *cp = (const unsigned char*) id_cert_str;
  884. id_cert = d2i_X509(NULL, &cp, id_cert_len);
  885. if (id_cert)
  886. free_id_cert = 1;
  887. }
  888. if (cert) {
  889. int cmp = 0;
  890. X509 *cert_tmp = SSL_get_peer_certificate(tls->ssl);
  891. if (cert_tmp) {
  892. peer_used_tls_cert = 1;
  893. cmp = X509_cmp(cert, cert_tmp);
  894. X509_free(cert_tmp);
  895. }
  896. if (cmp != 0) {
  897. log_fn(severity, LD_PROTOCOL,
  898. "Certificate in CERT cell didn't match TLS cert.");
  899. goto done;
  900. }
  901. }
  902. if (!cert || !id_cert) {
  903. X509 *c=NULL, *id=NULL;
  904. try_to_extract_certs_from_tls(severity, tls, &c, &id);
  905. if (c) {
  906. if (!cert)
  907. cert = c;
  908. else
  909. X509_free(c);
  910. }
  911. if (id && !id_cert)
  912. id_cert = id;
  913. }
  914. if (!id_cert || !cert)
  915. goto done;
  916. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  917. X509_verify(cert, id_pkey) <= 0) {
  918. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  919. tls_log_errors(severity,"verifying certificate");
  920. goto done;
  921. }
  922. {
  923. crypto_pk_env_t *i = _crypto_new_pk_env_evp_pkey(id_pkey);
  924. if (!i)
  925. goto done;
  926. crypto_pk_get_digest(i, id_digest_out);
  927. crypto_free_pk_env(i);
  928. }
  929. if (!(cert_pkey = X509_get_pubkey(cert)))
  930. goto done;
  931. if (!(*cert_key_out = _crypto_new_pk_env_evp_pkey(cert_pkey)))
  932. goto done;
  933. {
  934. unsigned int len = 0;
  935. X509_digest(cert, EVP_sha1(), (unsigned char*)conn_cert_digest_out, &len);
  936. tor_assert(len == DIGEST_LEN);
  937. }
  938. r = peer_used_tls_cert ? 1 : 0;
  939. done:
  940. if (cert)
  941. X509_free(cert);
  942. if (id_cert && free_id_cert)
  943. X509_free(id_cert);
  944. if (id_pkey)
  945. EVP_PKEY_free(id_pkey);
  946. if (cert_pkey)
  947. EVP_PKEY_free(cert_pkey);
  948. return r;
  949. }
  950. /** Check whether the certificate set on the connection <b>tls</b> is
  951. * expired or not-yet-valid, give or take <b>tolerance</b>
  952. * seconds. Return 0 for valid, -1 for failure.
  953. *
  954. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  955. */
  956. int
  957. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  958. {
  959. time_t now, t;
  960. X509 *cert;
  961. int r = -1;
  962. now = time(NULL);
  963. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  964. goto done;
  965. t = now + tolerance;
  966. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  967. log_cert_lifetime(cert, "not yet valid");
  968. goto done;
  969. }
  970. t = now - tolerance;
  971. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  972. log_cert_lifetime(cert, "already expired");
  973. goto done;
  974. }
  975. r = 0;
  976. done:
  977. if (cert)
  978. X509_free(cert);
  979. /* Not expected to get invoked */
  980. tls_log_errors(LOG_WARN, "checking certificate lifetime");
  981. return r;
  982. }
  983. /** Return the number of bytes available for reading from <b>tls</b>.
  984. */
  985. int
  986. tor_tls_get_pending_bytes(tor_tls_t *tls)
  987. {
  988. tor_assert(tls);
  989. return SSL_pending(tls->ssl);
  990. }
  991. /** If <b>tls</b> requires that the next write be of a particular size,
  992. * return that size. Otherwise, return 0. */
  993. size_t
  994. tor_tls_get_forced_write_size(tor_tls_t *tls)
  995. {
  996. return tls->wantwrite_n;
  997. }
  998. /** Sets n_read and n_written to the number of bytes read and written,
  999. * respectivey, on the raw socket used by <b>tls</b> since the last time this
  1000. * function was called on <b>tls</b>. */
  1001. void
  1002. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1003. {
  1004. unsigned long r, w;
  1005. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1006. w = BIO_number_written(SSL_get_wbio(tls->ssl));
  1007. /* We are ok with letting these unsigned ints go "negative" here:
  1008. * If we wrapped around, this should still give us the right answer, unless
  1009. * we wrapped around by more than ULONG_MAX since the last time we called
  1010. * this function.
  1011. */
  1012. *n_read = (size_t)(r - tls->last_read_count);
  1013. *n_written = (size_t)(w - tls->last_write_count);
  1014. tls->last_read_count = r;
  1015. tls->last_write_count = w;
  1016. }
  1017. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1018. * errors, log an error message. */
  1019. void
  1020. _check_no_tls_errors(const char *fname, int line)
  1021. {
  1022. if (ERR_peek_error() == 0)
  1023. return;
  1024. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1025. tor_fix_source_file(fname), line);
  1026. tls_log_errors(LOG_WARN, NULL);
  1027. }
  1028. /**DOCDOC */
  1029. int
  1030. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1031. {
  1032. (void)tls;
  1033. return 1;
  1034. }
  1035. #if SSL3_RANDOM_SIZE != TOR_TLS_RANDOM_LEN
  1036. #error "The TOR_TLS_RANDOM_LEN macro is defined incorrectly. That's a bug."
  1037. #endif
  1038. /** DOCDOC */
  1039. int
  1040. tor_tls_get_random_values(tor_tls_t *tls, char *client_random_out,
  1041. char *server_random_out)
  1042. {
  1043. tor_assert(tls && tls->ssl);
  1044. if (!tls->ssl->s3)
  1045. return -1;
  1046. memcpy(client_random_out, tls->ssl->s3->client_random, SSL3_RANDOM_SIZE);
  1047. memcpy(server_random_out, tls->ssl->s3->server_random, SSL3_RANDOM_SIZE);
  1048. return 0;
  1049. }
  1050. /** DOCDOC */
  1051. int
  1052. tor_tls_hmac_with_master_secret(tor_tls_t *tls, char *hmac_out,
  1053. const char *data, size_t data_len)
  1054. {
  1055. SSL_SESSION *s;
  1056. tor_assert(tls && tls->ssl);
  1057. if (!(s = SSL_get_session(tls->ssl)))
  1058. return -1;
  1059. if (s->master_key_length < 0)
  1060. return -1;
  1061. crypto_hmac_sha1(hmac_out,
  1062. (const char*)s->master_key,
  1063. (size_t)s->master_key_length,
  1064. data, data_len);
  1065. return 0;
  1066. }