tortls.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. /* Copyright (c) 2003, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char tortls_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file tortls.c
  10. * \brief Wrapper functions to present a consistent interface to
  11. * TLS, SSL, and X.509 functions from OpenSSL.
  12. **/
  13. /* (Unlike other tor functions, these
  14. * are prefixed with tor_ in order to avoid conflicting with OpenSSL
  15. * functions and variables.)
  16. */
  17. #include "orconfig.h"
  18. #include <assert.h>
  19. #include <openssl/ssl.h>
  20. #include <openssl/ssl3.h>
  21. #include <openssl/err.h>
  22. #include <openssl/tls1.h>
  23. #include <openssl/asn1.h>
  24. #include <openssl/bio.h>
  25. #include <openssl/opensslv.h>
  26. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  27. #error "We require openssl >= 0.9.7"
  28. #endif
  29. #define CRYPTO_PRIVATE /* to import prototypes from crypto.h */
  30. #include "crypto.h"
  31. #include "tortls.h"
  32. #include "util.h"
  33. #include "log.h"
  34. #include "container.h"
  35. #include "ht.h"
  36. #include <string.h>
  37. // #define V2_HANDSHAKE_SERVER
  38. // #define V2_HANDSHAKE_CLIENT
  39. /* Copied from or.h */
  40. #define LEGAL_NICKNAME_CHARACTERS \
  41. "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  42. /** How long do identity certificates live? (sec) */
  43. #define IDENTITY_CERT_LIFETIME (365*24*60*60)
  44. /** Structure holding the TLS state for a single connection. */
  45. typedef struct tor_tls_context_t {
  46. int refcnt;
  47. SSL_CTX *ctx;
  48. X509 *my_cert;
  49. X509 *my_id_cert;
  50. crypto_pk_env_t *key;
  51. } tor_tls_context_t;
  52. /** Holds a SSL object and its associated data. Members are only
  53. * accessed from within tortls.c.
  54. */
  55. struct tor_tls_t {
  56. HT_ENTRY(tor_tls_t) node;
  57. tor_tls_context_t *context; /** A link to the context object for this tls */
  58. SSL *ssl; /**< An OpenSSL SSL object. */
  59. int socket; /**< The underlying file descriptor for this TLS connection. */
  60. enum {
  61. TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
  62. TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
  63. } state : 3; /**< The current SSL state, depending on which operations have
  64. * completed successfully. */
  65. unsigned int isServer:1; /**< True iff this is a server-side connection */
  66. unsigned int wasV2Handshake:1; /**< True iff the original handshake for
  67. * this connection used the updated version
  68. * of the connection protocol (client sends
  69. * different cipher list, server sends only
  70. * one certificate). */
  71. int got_renegotiate:1; /**< True iff we should call negotiated_callback
  72. * when we're done reading. */
  73. size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
  74. * time. */
  75. /** Last values retrieved from BIO_number_read()/write(); see
  76. * tor_tls_get_n_raw_bytes() for usage.
  77. */
  78. unsigned long last_write_count;
  79. unsigned long last_read_count;
  80. /** If set, a callback to invoke whenever the client tries to renegotiate
  81. * the handshake. */
  82. void (*negotiated_callback)(tor_tls_t *tls, void *arg);
  83. /** Argument to pass to negotiated_callback. */
  84. void *callback_arg;
  85. };
  86. /** Helper: compare tor_tls_t objects by its SSL. */
  87. static INLINE int
  88. tor_tls_entries_eq(const tor_tls_t *a, const tor_tls_t *b)
  89. {
  90. return a->ssl == b->ssl;
  91. }
  92. /** Helper: return a hash value for a tor_tls_t by its SSL. */
  93. static INLINE unsigned int
  94. tor_tls_entry_hash(const tor_tls_t *a)
  95. {
  96. #if SIZEOF_INT == SIZEOF_VOID_P
  97. return ((unsigned int)a->ssl);
  98. #else
  99. return (unsigned int) ((((uint64_t)a->ssl)>>2) & UINT_MAX);
  100. #endif
  101. }
  102. /** Map from SSL* pointers to tor_tls_t objects using those pointers.
  103. */
  104. static HT_HEAD(tlsmap, tor_tls_t) tlsmap_root = HT_INITIALIZER();
  105. HT_PROTOTYPE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
  106. tor_tls_entries_eq)
  107. HT_GENERATE(tlsmap, tor_tls_t, node, tor_tls_entry_hash,
  108. tor_tls_entries_eq, 0.6, malloc, realloc, free)
  109. /** Helper: given a SSL* pointer, return the tor_tls_t object using that
  110. * pointer. */
  111. static INLINE tor_tls_t *
  112. tor_tls_get_by_ssl(const SSL *ssl)
  113. {
  114. tor_tls_t search, *result;
  115. memset(&search, 0, sizeof(search));
  116. search.ssl = (SSL*)ssl;
  117. result = HT_FIND(tlsmap, &tlsmap_root, &search);
  118. return result;
  119. }
  120. static void tor_tls_context_decref(tor_tls_context_t *ctx);
  121. static void tor_tls_context_incref(tor_tls_context_t *ctx);
  122. static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
  123. crypto_pk_env_t *rsa_sign,
  124. const char *cname,
  125. const char *cname_sign,
  126. unsigned int lifetime);
  127. /** Global tls context. We keep it here because nobody else needs to
  128. * touch it. */
  129. static tor_tls_context_t *global_tls_context = NULL;
  130. /** True iff tor_tls_init() has been called. */
  131. static int tls_library_is_initialized = 0;
  132. /* Module-internal error codes. */
  133. #define _TOR_TLS_SYSCALL (_MIN_TOR_TLS_ERROR_VAL - 2)
  134. #define _TOR_TLS_ZERORETURN (_MIN_TOR_TLS_ERROR_VAL - 1)
  135. /** Log all pending tls errors at level <b>severity</b>. Use
  136. * <b>doing</b> to describe our current activities.
  137. */
  138. static void
  139. tls_log_errors(int severity, const char *doing)
  140. {
  141. int err;
  142. const char *msg, *lib, *func;
  143. while ((err = ERR_get_error()) != 0) {
  144. msg = (const char*)ERR_reason_error_string(err);
  145. lib = (const char*)ERR_lib_error_string(err);
  146. func = (const char*)ERR_func_error_string(err);
  147. if (!msg) msg = "(null)";
  148. if (doing) {
  149. log(severity, LD_NET, "TLS error while %s: %s (in %s:%s)",
  150. doing, msg, lib,func);
  151. } else {
  152. log(severity, LD_NET, "TLS error: %s (in %s:%s)", msg, lib, func);
  153. }
  154. }
  155. }
  156. /** Convert an errno (or a WSAerrno on windows) into a TOR_TLS_* error
  157. * code. */
  158. static int
  159. tor_errno_to_tls_error(int e)
  160. {
  161. #if defined(MS_WINDOWS) && !defined(USE_BSOCKETS)
  162. switch (e) {
  163. case WSAECONNRESET: // most common
  164. return TOR_TLS_ERROR_CONNRESET;
  165. case WSAETIMEDOUT:
  166. return TOR_TLS_ERROR_TIMEOUT;
  167. case WSAENETUNREACH:
  168. case WSAEHOSTUNREACH:
  169. return TOR_TLS_ERROR_NO_ROUTE;
  170. case WSAECONNREFUSED:
  171. return TOR_TLS_ERROR_CONNREFUSED; // least common
  172. default:
  173. return TOR_TLS_ERROR_MISC;
  174. }
  175. #else
  176. switch (e) {
  177. case ECONNRESET: // most common
  178. return TOR_TLS_ERROR_CONNRESET;
  179. case ETIMEDOUT:
  180. return TOR_TLS_ERROR_TIMEOUT;
  181. case EHOSTUNREACH:
  182. case ENETUNREACH:
  183. return TOR_TLS_ERROR_NO_ROUTE;
  184. case ECONNREFUSED:
  185. return TOR_TLS_ERROR_CONNREFUSED; // least common
  186. default:
  187. return TOR_TLS_ERROR_MISC;
  188. }
  189. #endif
  190. }
  191. /** Given a TOR_TLS_* error code, return a string equivalent. */
  192. const char *
  193. tor_tls_err_to_string(int err)
  194. {
  195. if (err >= 0)
  196. return "[Not an error.]";
  197. switch (err) {
  198. case TOR_TLS_ERROR_MISC: return "misc error";
  199. case TOR_TLS_ERROR_IO: return "unexpected close";
  200. case TOR_TLS_ERROR_CONNREFUSED: return "connection refused";
  201. case TOR_TLS_ERROR_CONNRESET: return "connection reset";
  202. case TOR_TLS_ERROR_NO_ROUTE: return "host unreachable";
  203. case TOR_TLS_ERROR_TIMEOUT: return "connection timed out";
  204. case TOR_TLS_CLOSE: return "closed";
  205. case TOR_TLS_WANTREAD: return "want to read";
  206. case TOR_TLS_WANTWRITE: return "want to write";
  207. default: return "(unknown error code)";
  208. }
  209. }
  210. #define CATCH_SYSCALL 1
  211. #define CATCH_ZERO 2
  212. /** Given a TLS object and the result of an SSL_* call, use
  213. * SSL_get_error to determine whether an error has occurred, and if so
  214. * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
  215. * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
  216. * reporting syscall errors. If extra&CATCH_ZERO is true, return
  217. * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
  218. *
  219. * If an error has occurred, log it at level <b>severity</b> and describe the
  220. * current action as <b>doing</b>.
  221. */
  222. static int
  223. tor_tls_get_error(tor_tls_t *tls, int r, int extra,
  224. const char *doing, int severity)
  225. {
  226. int err = SSL_get_error(tls->ssl, r);
  227. int tor_error = TOR_TLS_ERROR_MISC;
  228. switch (err) {
  229. case SSL_ERROR_NONE:
  230. return TOR_TLS_DONE;
  231. case SSL_ERROR_WANT_READ:
  232. return TOR_TLS_WANTREAD;
  233. case SSL_ERROR_WANT_WRITE:
  234. return TOR_TLS_WANTWRITE;
  235. case SSL_ERROR_SYSCALL:
  236. if (extra&CATCH_SYSCALL)
  237. return _TOR_TLS_SYSCALL;
  238. if (r == 0) {
  239. log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
  240. tor_error = TOR_TLS_ERROR_IO;
  241. } else {
  242. int e = tor_socket_errno(tls->socket);
  243. log(severity, LD_NET,
  244. "TLS error: <syscall error while %s> (errno=%d: %s)",
  245. doing, e, tor_socket_strerror(e));
  246. tor_error = tor_errno_to_tls_error(e);
  247. }
  248. tls_log_errors(severity, doing);
  249. return tor_error;
  250. case SSL_ERROR_ZERO_RETURN:
  251. if (extra&CATCH_ZERO)
  252. return _TOR_TLS_ZERORETURN;
  253. log(severity, LD_NET, "TLS error: Zero return");
  254. tls_log_errors(severity, doing);
  255. /* XXXX020 Actually, a 'zero return' error has a pretty specific meaning:
  256. * the connection has been closed cleanly. */
  257. return TOR_TLS_ERROR_MISC;
  258. default:
  259. tls_log_errors(severity, doing);
  260. return TOR_TLS_ERROR_MISC;
  261. }
  262. }
  263. /** Initialize OpenSSL, unless it has already been initialized.
  264. */
  265. static void
  266. tor_tls_init(void)
  267. {
  268. if (!tls_library_is_initialized) {
  269. SSL_library_init();
  270. SSL_load_error_strings();
  271. crypto_global_init(-1);
  272. tls_library_is_initialized = 1;
  273. }
  274. }
  275. /** Free all global TLS structures. */
  276. void
  277. tor_tls_free_all(void)
  278. {
  279. if (global_tls_context) {
  280. tor_tls_context_decref(global_tls_context);
  281. global_tls_context = NULL;
  282. }
  283. }
  284. /** We need to give OpenSSL a callback to verify certificates. This is
  285. * it: We always accept peer certs and complete the handshake. We
  286. * don't validate them until later.
  287. */
  288. static int
  289. always_accept_verify_cb(int preverify_ok,
  290. X509_STORE_CTX *x509_ctx)
  291. {
  292. (void) preverify_ok;
  293. (void) x509_ctx;
  294. return 1;
  295. }
  296. /** Return a newly allocated X509 name with commonName <b>cname</b> */
  297. static X509_NAME *
  298. tor_x509_name_new(const char *cname)
  299. {
  300. int nid;
  301. X509_NAME *name;
  302. if (!(name = X509_NAME_new()))
  303. return NULL;
  304. if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  305. if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
  306. (unsigned char*)cname, -1, -1, 0)))
  307. goto error;
  308. return name;
  309. error:
  310. X509_NAME_free(name);
  311. return NULL;
  312. }
  313. /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
  314. * signed by the private key <b>rsa_sign</b>. The commonName of the
  315. * certificate will be <b>cname</b>; the commonName of the issuer will be
  316. * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
  317. * starting from now. Return a certificate on success, NULL on
  318. * failure.
  319. */
  320. static X509 *
  321. tor_tls_create_certificate(crypto_pk_env_t *rsa,
  322. crypto_pk_env_t *rsa_sign,
  323. const char *cname,
  324. const char *cname_sign,
  325. unsigned int cert_lifetime)
  326. {
  327. time_t start_time, end_time;
  328. EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
  329. X509 *x509 = NULL;
  330. X509_NAME *name = NULL, *name_issuer=NULL;
  331. tor_tls_init();
  332. start_time = time(NULL);
  333. tor_assert(rsa);
  334. tor_assert(cname);
  335. tor_assert(rsa_sign);
  336. tor_assert(cname_sign);
  337. if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
  338. goto error;
  339. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
  340. goto error;
  341. if (!(x509 = X509_new()))
  342. goto error;
  343. if (!(X509_set_version(x509, 2)))
  344. goto error;
  345. if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
  346. goto error;
  347. if (!(name = tor_x509_name_new(cname)))
  348. goto error;
  349. if (!(X509_set_subject_name(x509, name)))
  350. goto error;
  351. if (!(name_issuer = tor_x509_name_new(cname_sign)))
  352. goto error;
  353. if (!(X509_set_issuer_name(x509, name_issuer)))
  354. goto error;
  355. if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
  356. goto error;
  357. end_time = start_time + cert_lifetime;
  358. if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
  359. goto error;
  360. if (!X509_set_pubkey(x509, pkey))
  361. goto error;
  362. if (!X509_sign(x509, sign_pkey, EVP_sha1()))
  363. goto error;
  364. goto done;
  365. error:
  366. if (x509) {
  367. X509_free(x509);
  368. x509 = NULL;
  369. }
  370. done:
  371. tls_log_errors(LOG_WARN, "generating certificate");
  372. if (sign_pkey)
  373. EVP_PKEY_free(sign_pkey);
  374. if (pkey)
  375. EVP_PKEY_free(pkey);
  376. if (name)
  377. X509_NAME_free(name);
  378. if (name_issuer)
  379. X509_NAME_free(name_issuer);
  380. return x509;
  381. }
  382. #define SERVER_CIPHER_LIST \
  383. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  384. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  385. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  386. /* Note: for setting up your own private testing network with link crypto
  387. * disabled, set the cipher lists to your cipher list to
  388. * SSL3_TXT_RSA_NULL_SHA. If you do this, you won't be able to communicate
  389. * with any of the "real" Tors, though. */
  390. #if OPENSSL_VERSION_NUMBER >= 0x00908000l
  391. #define CLIENT_CIPHER_LIST \
  392. (TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ":" \
  393. TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA ":" \
  394. TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  395. TLS1_TXT_DHE_DSS_WITH_AES_256_SHA ":" \
  396. TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA ":" \
  397. TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA ":" \
  398. TLS1_TXT_RSA_WITH_AES_256_SHA ":" \
  399. TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA ":" \
  400. TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA ":" \
  401. TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA ":" \
  402. TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA ":" \
  403. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  404. TLS1_TXT_DHE_DSS_WITH_AES_128_SHA ":" \
  405. TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA":" \
  406. TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA":" \
  407. TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA ":" \
  408. TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA ":" \
  409. SSL3_TXT_RSA_RC4_128_MD5 ":" \
  410. SSL3_TXT_RSA_RC4_128_SHA ":" \
  411. TLS1_TXT_RSA_WITH_AES_128_SHA ":" \
  412. TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA ":" \
  413. TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA ":" \
  414. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
  415. SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA ":" \
  416. TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA ":" \
  417. TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA ":" \
  418. /*SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA ":"*/ \
  419. SSL3_TXT_RSA_DES_192_CBC3_SHA)
  420. /* SSL3_TXT_RSA_FIPS_WITH_3DES_EDE_CBC_SHA is commented out because it doesn't
  421. * really exist; if I understand correctly, it's a bit of silliness that
  422. * netscape did on its own before any standard for what they wanted was
  423. * formally approved. Nonetheless, Firefox still uses it, so we need to
  424. * fake it at some point soon. XXXX020 -NM */
  425. #else
  426. /* Ug. We don't have as many ciphers with openssl 0.9.7 as we'd like. Fix
  427. * this list into something that sucks less. */
  428. #define CLIENT_CIPHER_LIST \
  429. (TLS1_TXT_DHE_RSA_WITH_AES_256_SHA ":" \
  430. TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  431. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA ":" \
  432. SSL3_TXT_RSA_RC4_128_SHA)
  433. #endif
  434. #ifndef V2_HANDSHAKE_CLIENT
  435. #undef CLIENT_CIPHER_LIST
  436. #define CLIENT_CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
  437. SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
  438. #endif
  439. /** Remove a reference to <b>ctx</b>, and free it if it has no more
  440. * references. */
  441. static void
  442. tor_tls_context_decref(tor_tls_context_t *ctx)
  443. {
  444. tor_assert(ctx);
  445. if (--ctx->refcnt == 0) {
  446. SSL_CTX_free(ctx->ctx);
  447. X509_free(ctx->my_cert);
  448. X509_free(ctx->my_id_cert);
  449. crypto_free_pk_env(ctx->key);
  450. tor_free(ctx);
  451. }
  452. }
  453. /** Increase the reference count of <b>ctx</b>. */
  454. static void
  455. tor_tls_context_incref(tor_tls_context_t *ctx)
  456. {
  457. ++ctx->refcnt;
  458. }
  459. /** Create a new TLS context for use with Tor TLS handshakes.
  460. * <b>identity</b> should be set to the identity key used to sign the
  461. * certificate, and <b>nickname</b> set to the nickname to use.
  462. *
  463. * You can call this function multiple times. Each time you call it,
  464. * it generates new certificates; all new connections will use
  465. * the new SSL context.
  466. */
  467. int
  468. tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime)
  469. {
  470. crypto_pk_env_t *rsa = NULL;
  471. crypto_dh_env_t *dh = NULL;
  472. EVP_PKEY *pkey = NULL;
  473. tor_tls_context_t *result = NULL;
  474. X509 *cert = NULL, *idcert = NULL;
  475. char *nickname = NULL, *nn2 = NULL;
  476. tor_tls_init();
  477. nickname = crypto_random_hostname(8, 20, "www.", ".net");
  478. nn2 = crypto_random_hostname(8, 20, "www.", ".net");
  479. log_notice(LD_NET, "<%s> <%s>", nickname, nn2);
  480. /* Generate short-term RSA key. */
  481. if (!(rsa = crypto_new_pk_env()))
  482. goto error;
  483. if (crypto_pk_generate_key(rsa)<0)
  484. goto error;
  485. /* Create certificate signed by identity key. */
  486. cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
  487. key_lifetime);
  488. /* Create self-signed certificate for identity key. */
  489. idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
  490. IDENTITY_CERT_LIFETIME);
  491. if (!cert || !idcert) {
  492. log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
  493. goto error;
  494. }
  495. result = tor_malloc_zero(sizeof(tor_tls_context_t));
  496. result->refcnt = 1;
  497. result->my_cert = X509_dup(cert);
  498. result->my_id_cert = X509_dup(idcert);
  499. result->key = crypto_pk_dup_key(rsa);
  500. #ifdef EVERYONE_HAS_AES
  501. /* Tell OpenSSL to only use TLS1 */
  502. if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
  503. goto error;
  504. #else
  505. /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
  506. if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
  507. goto error;
  508. SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
  509. #endif
  510. SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
  511. if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
  512. goto error;
  513. X509_free(cert); /* We just added a reference to cert. */
  514. cert=NULL;
  515. if (idcert) {
  516. X509_STORE *s = SSL_CTX_get_cert_store(result->ctx);
  517. tor_assert(s);
  518. X509_STORE_add_cert(s, idcert);
  519. X509_free(idcert); /* The context now owns the reference to idcert */
  520. idcert = NULL;
  521. }
  522. SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
  523. tor_assert(rsa);
  524. if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
  525. goto error;
  526. if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
  527. goto error;
  528. EVP_PKEY_free(pkey);
  529. pkey = NULL;
  530. if (!SSL_CTX_check_private_key(result->ctx))
  531. goto error;
  532. dh = crypto_dh_new();
  533. SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
  534. crypto_dh_free(dh);
  535. SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
  536. always_accept_verify_cb);
  537. /* let us realloc bufs that we're writing from */
  538. SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  539. /* Free the old context if one exists. */
  540. if (global_tls_context) {
  541. /* This is safe even if there are open connections: OpenSSL does
  542. * reference counting with SSL and SSL_CTX objects. */
  543. tor_tls_context_decref(global_tls_context);
  544. }
  545. global_tls_context = result;
  546. if (rsa)
  547. crypto_free_pk_env(rsa);
  548. tor_free(nickname);
  549. tor_free(nn2);
  550. return 0;
  551. error:
  552. tls_log_errors(LOG_WARN, "creating TLS context");
  553. tor_free(nickname);
  554. tor_free(nn2);
  555. if (pkey)
  556. EVP_PKEY_free(pkey);
  557. if (rsa)
  558. crypto_free_pk_env(rsa);
  559. if (dh)
  560. crypto_dh_free(dh);
  561. if (result)
  562. tor_tls_context_decref(result);
  563. if (cert)
  564. X509_free(cert);
  565. if (idcert)
  566. X509_free(idcert);
  567. return -1;
  568. }
  569. #ifdef V2_HANDSHAKE_SERVER
  570. /** Return true iff the cipher list suggested by the client for <b>ssl</b> is
  571. * a list that indicates that the client know how to do the v2 TLS connection
  572. * handshake. */
  573. static int
  574. tor_tls_client_is_using_v2_ciphers(const SSL *ssl)
  575. {
  576. int i;
  577. SSL_SESSION *session;
  578. /* If we reached this point, we just got a client hello. See if there is
  579. * a cipher list. */
  580. if (!(session = SSL_get_session(ssl))) {
  581. log_warn(LD_NET, "No session on TLS?");
  582. return 0;
  583. }
  584. if (!session->ciphers) {
  585. log_warn(LD_NET, "No ciphers on session");
  586. return 0;
  587. }
  588. /* Now we need to see if there are any ciphers whose presence means we're
  589. * dealing with an updated Tor. */
  590. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  591. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  592. const char *ciphername = SSL_CIPHER_get_name(cipher);
  593. if (strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_128_SHA) &&
  594. strcmp(ciphername, TLS1_TXT_DHE_RSA_WITH_AES_256_SHA) &&
  595. strcmp(ciphername, SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA) &&
  596. strcmp(ciphername, "(NONE)")) {
  597. /* XXXX should be ld_debug */
  598. log_info(LD_NET, "Got a non-version-1 cipher called '%s'",ciphername);
  599. // return 1;
  600. goto dump_list;
  601. }
  602. }
  603. return 0;
  604. dump_list:
  605. {
  606. smartlist_t *elts = smartlist_create();
  607. char *s;
  608. for (i = 0; i < sk_SSL_CIPHER_num(session->ciphers); ++i) {
  609. SSL_CIPHER *cipher = sk_SSL_CIPHER_value(session->ciphers, i);
  610. const char *ciphername = SSL_CIPHER_get_name(cipher);
  611. smartlist_add(elts, (char*)ciphername);
  612. }
  613. s = smartlist_join_strings(elts, ":", 0, NULL);
  614. log_info(LD_NET, "Got a non-version-1 cipher list. It is: '%s'", s);
  615. tor_free(s);
  616. smartlist_free(elts);
  617. }
  618. return 1;
  619. }
  620. /** Invoked when we're accepting a connection on <b>ssl</b>, and the connection
  621. * changes state. We use this:
  622. * <ul><li>To alter the state of the handshake partway through, so we
  623. * do not send or request extra certificates in v2 handshakes.</li>
  624. * <li>To detect renegotiation</li></ul>
  625. */
  626. static void
  627. tor_tls_server_info_callback(const SSL *ssl, int type, int val)
  628. {
  629. tor_tls_t *tls;
  630. (void) val;
  631. if (type != SSL_CB_ACCEPT_LOOP)
  632. return;
  633. if (ssl->state != SSL3_ST_SW_SRVR_HELLO_A)
  634. return;
  635. tls = tor_tls_get_by_ssl(ssl);
  636. if (tls) {
  637. /* Check whether we're watching for renegotiates. If so, this is one! */
  638. if (tls->negotiated_callback)
  639. tls->got_renegotiate = 1;
  640. } else {
  641. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  642. }
  643. /* Now check the cipher list. */
  644. if (tor_tls_client_is_using_v2_ciphers(ssl)) {
  645. /*XXXX_TLS keep this from happening more than once! */
  646. /* Yes, we're casting away the const from ssl. This is very naughty of us.
  647. * Let's hope openssl doesn't notice! */
  648. /* Set SSL_MODE_NO_AUTO_CHAIN to keep from sending back any extra certs. */
  649. SSL_set_mode((SSL*) ssl, SSL_MODE_NO_AUTO_CHAIN);
  650. /* Don't send a hello request. */
  651. SSL_set_verify((SSL*) ssl, SSL_VERIFY_NONE, NULL);
  652. if (tls) {
  653. tls->wasV2Handshake = 1;
  654. } else {
  655. log_warn(LD_BUG, "Couldn't look up the tls for an SSL*. How odd!");
  656. }
  657. }
  658. }
  659. #endif
  660. /** Create a new TLS object from a file descriptor, and a flag to
  661. * determine whether it is functioning as a server.
  662. */
  663. tor_tls_t *
  664. tor_tls_new(int sock, int isServer)
  665. {
  666. BIO *bio = NULL;
  667. tor_tls_t *result = tor_malloc_zero(sizeof(tor_tls_t));
  668. tor_assert(global_tls_context); /* make sure somebody made it first */
  669. if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
  670. tls_log_errors(LOG_WARN, "generating TLS context");
  671. tor_free(result);
  672. return NULL;
  673. }
  674. if (!SSL_set_cipher_list(result->ssl,
  675. isServer ? SERVER_CIPHER_LIST : CLIENT_CIPHER_LIST)) {
  676. SSL_free(result->ssl);
  677. tor_free(result);
  678. return NULL;
  679. }
  680. result->socket = sock;
  681. #ifdef USE_BSOCKETS
  682. bio = BIO_new_bsocket(sock, BIO_NOCLOSE);
  683. #else
  684. bio = BIO_new_socket(sock, BIO_NOCLOSE);
  685. #endif
  686. if (! bio) {
  687. tls_log_errors(LOG_WARN, "opening BIO");
  688. SSL_free(result->ssl);
  689. tor_free(result);
  690. return NULL;
  691. }
  692. HT_INSERT(tlsmap, &tlsmap_root, result);
  693. SSL_set_bio(result->ssl, bio, bio);
  694. tor_tls_context_incref(global_tls_context);
  695. result->context = global_tls_context;
  696. result->state = TOR_TLS_ST_HANDSHAKE;
  697. result->isServer = isServer;
  698. result->wantwrite_n = 0;
  699. #ifdef V2_HANDSHAKE_SERVER
  700. if (isServer) {
  701. SSL_set_info_callback(result->ssl, tor_tls_server_info_callback);
  702. }
  703. #endif
  704. /* Not expected to get called. */
  705. tls_log_errors(LOG_WARN, "generating TLS context");
  706. return result;
  707. }
  708. /** Set <b>cb</b> to be called with argument <b>arg</b> whenever <b>tls</b>
  709. * next gets a client-side renegotiate in the middle of a read. Do not
  710. * invoke this function untile <em>after</em> initial handshaking is done!
  711. */
  712. void
  713. tor_tls_set_renegotiate_callback(tor_tls_t *tls,
  714. void (*cb)(tor_tls_t *, void *arg),
  715. void *arg)
  716. {
  717. tls->negotiated_callback = cb;
  718. tls->callback_arg = arg;
  719. tls->got_renegotiate = 0;
  720. #ifdef V2_HANDSHAKE_SERVER
  721. if (cb) {
  722. SSL_set_info_callback(tls->ssl, tor_tls_server_info_callback);
  723. } else {
  724. SSL_set_info_callback(tls->ssl, NULL);
  725. }
  726. #endif
  727. }
  728. /** Return whether this tls initiated the connect (client) or
  729. * received it (server). */
  730. int
  731. tor_tls_is_server(tor_tls_t *tls)
  732. {
  733. tor_assert(tls);
  734. return tls->isServer;
  735. }
  736. /** Release resources associated with a TLS object. Does not close the
  737. * underlying file descriptor.
  738. */
  739. void
  740. tor_tls_free(tor_tls_t *tls)
  741. {
  742. tor_tls_t *removed;
  743. tor_assert(tls && tls->ssl);
  744. removed = HT_REMOVE(tlsmap, &tlsmap_root, tls);
  745. if (!removed) {
  746. log_warn(LD_BUG, "Freeing a TLS that was not in the ssl->tls map.");
  747. }
  748. SSL_free(tls->ssl);
  749. tls->ssl = NULL;
  750. tls->negotiated_callback = NULL;
  751. if (tls->context)
  752. tor_tls_context_decref(tls->context);
  753. tor_free(tls);
  754. }
  755. /** Underlying function for TLS reading. Reads up to <b>len</b>
  756. * characters from <b>tls</b> into <b>cp</b>. On success, returns the
  757. * number of characters read. On failure, returns TOR_TLS_ERROR,
  758. * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  759. */
  760. int
  761. tor_tls_read(tor_tls_t *tls, char *cp, size_t len)
  762. {
  763. int r, err;
  764. tor_assert(tls);
  765. tor_assert(tls->ssl);
  766. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  767. r = SSL_read(tls->ssl, cp, len);
  768. if (r > 0) {
  769. #ifdef V2_HANDSHAKE_SERVER
  770. if (tls->got_renegotiate) {
  771. /* Renegotiation happened! */
  772. log_notice(LD_NET, "Got a TLS renegotiation from %p", tls);
  773. if (tls->negotiated_callback)
  774. tls->negotiated_callback(tls, tls->callback_arg);
  775. tls->got_renegotiate = 0;
  776. }
  777. #endif
  778. return r;
  779. }
  780. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
  781. if (err == _TOR_TLS_ZERORETURN) {
  782. log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
  783. tls->state = TOR_TLS_ST_CLOSED;
  784. return TOR_TLS_CLOSE;
  785. } else {
  786. tor_assert(err != TOR_TLS_DONE);
  787. log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
  788. return err;
  789. }
  790. }
  791. /** Underlying function for TLS writing. Write up to <b>n</b>
  792. * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
  793. * number of characters written. On failure, returns TOR_TLS_ERROR,
  794. * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
  795. */
  796. int
  797. tor_tls_write(tor_tls_t *tls, const char *cp, size_t n)
  798. {
  799. int r, err;
  800. tor_assert(tls);
  801. tor_assert(tls->ssl);
  802. tor_assert(tls->state == TOR_TLS_ST_OPEN);
  803. if (n == 0)
  804. return 0;
  805. if (tls->wantwrite_n) {
  806. /* if WANTWRITE last time, we must use the _same_ n as before */
  807. tor_assert(n >= tls->wantwrite_n);
  808. log_debug(LD_NET,"resuming pending-write, (%d to flush, reusing %d)",
  809. (int)n, (int)tls->wantwrite_n);
  810. n = tls->wantwrite_n;
  811. tls->wantwrite_n = 0;
  812. }
  813. r = SSL_write(tls->ssl, cp, n);
  814. err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
  815. if (err == TOR_TLS_DONE) {
  816. return r;
  817. }
  818. if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
  819. tls->wantwrite_n = n;
  820. }
  821. return err;
  822. }
  823. /** Perform initial handshake on <b>tls</b>. When finished, returns
  824. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  825. * or TOR_TLS_WANTWRITE.
  826. */
  827. int
  828. tor_tls_handshake(tor_tls_t *tls)
  829. {
  830. int r;
  831. tor_assert(tls);
  832. tor_assert(tls->ssl);
  833. tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
  834. check_no_tls_errors();
  835. if (tls->isServer) {
  836. r = SSL_accept(tls->ssl);
  837. } else {
  838. r = SSL_connect(tls->ssl);
  839. }
  840. r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
  841. if (ERR_peek_error() != 0) {
  842. tls_log_errors(tls->isServer ? LOG_INFO : LOG_WARN,
  843. "handshaking");
  844. return TOR_TLS_ERROR_MISC;
  845. }
  846. if (r == TOR_TLS_DONE) {
  847. tls->state = TOR_TLS_ST_OPEN;
  848. if (tls->isServer) {
  849. SSL_set_info_callback(tls->ssl, NULL);
  850. SSL_set_verify(tls->ssl, SSL_VERIFY_NONE, always_accept_verify_cb);
  851. /* There doesn't seem to be a clear OpenSSL API to clear mode flags. */
  852. tls->ssl->mode &= ~SSL_MODE_NO_AUTO_CHAIN;
  853. #ifdef V2_HANDSHAKE_SERVER
  854. if (tor_tls_client_is_using_v2_ciphers(tls->ssl)) {
  855. /* This check is redundant, but back when we did it in the callback,
  856. * we might have not been able to look up the tor_tls_t if the code
  857. * was buggy. Fixing that. */
  858. if (!tls->wasV2Handshake) {
  859. log_warn(LD_BUG, "For some reason, wasV2Handshake didn't"
  860. " get set. Fixing that.");
  861. }
  862. tls->wasV2Handshake = 1;
  863. } else {
  864. tls->wasV2Handshake = 0;
  865. }
  866. #endif
  867. } else {
  868. #ifdef V2_HANDSHAKE_CLIENT
  869. /* If we got no ID cert, we're a v2 handshake. */
  870. X509 *cert = SSL_get_peer_certificate(tls->ssl);
  871. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(tls->ssl);
  872. int n_certs = sk_X509_num(chain);
  873. if (n_certs > 1 || (n_certs == 1 && cert != sk_X509_value(chain, 0)))
  874. tls->wasV2Handshake = 0;
  875. else {
  876. log_notice(LD_NET, "I think I got a v2 handshake on %p!", tls);
  877. tls->wasV2Handshake = 1;
  878. }
  879. if (cert)
  880. X509_free(cert);
  881. #endif
  882. SSL_set_cipher_list(tls->ssl, SERVER_CIPHER_LIST);
  883. }
  884. }
  885. return r;
  886. }
  887. /** Client only: Renegotiate a TLS session. When finished, returns
  888. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD, or
  889. * TOR_TLS_WANTWRITE.
  890. */
  891. int
  892. tor_tls_renegotiate(tor_tls_t *tls)
  893. {
  894. int r;
  895. tor_assert(tls);
  896. /* We could do server-initiated renegotiation too, but that would be tricky.
  897. * Instead of "SSL_renegotiate, then SSL_do_handshake until done" */
  898. tor_assert(!tls->isServer);
  899. if (tls->state != TOR_TLS_ST_RENEGOTIATE) {
  900. int r = SSL_renegotiate(tls->ssl);
  901. if (r <= 0) {
  902. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  903. "renegotiating", LOG_WARN);
  904. }
  905. tls->state = TOR_TLS_ST_RENEGOTIATE;
  906. }
  907. r = SSL_do_handshake(tls->ssl);
  908. if (r == 1) {
  909. tls->state = TOR_TLS_ST_OPEN;
  910. return TOR_TLS_DONE;
  911. } else
  912. return tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO,
  913. "renegotiating handshake", LOG_WARN);
  914. }
  915. /** Shut down an open tls connection <b>tls</b>. When finished, returns
  916. * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
  917. * or TOR_TLS_WANTWRITE.
  918. */
  919. int
  920. tor_tls_shutdown(tor_tls_t *tls)
  921. {
  922. int r, err;
  923. char buf[128];
  924. tor_assert(tls);
  925. tor_assert(tls->ssl);
  926. while (1) {
  927. if (tls->state == TOR_TLS_ST_SENTCLOSE) {
  928. /* If we've already called shutdown once to send a close message,
  929. * we read until the other side has closed too.
  930. */
  931. do {
  932. r = SSL_read(tls->ssl, buf, 128);
  933. } while (r>0);
  934. err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
  935. LOG_INFO);
  936. if (err == _TOR_TLS_ZERORETURN) {
  937. tls->state = TOR_TLS_ST_GOTCLOSE;
  938. /* fall through... */
  939. } else {
  940. return err;
  941. }
  942. }
  943. r = SSL_shutdown(tls->ssl);
  944. if (r == 1) {
  945. /* If shutdown returns 1, the connection is entirely closed. */
  946. tls->state = TOR_TLS_ST_CLOSED;
  947. return TOR_TLS_DONE;
  948. }
  949. err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
  950. LOG_INFO);
  951. if (err == _TOR_TLS_SYSCALL) {
  952. /* The underlying TCP connection closed while we were shutting down. */
  953. tls->state = TOR_TLS_ST_CLOSED;
  954. return TOR_TLS_DONE;
  955. } else if (err == _TOR_TLS_ZERORETURN) {
  956. /* The TLS connection says that it sent a shutdown record, but
  957. * isn't done shutting down yet. Make sure that this hasn't
  958. * happened before, then go back to the start of the function
  959. * and try to read.
  960. */
  961. if (tls->state == TOR_TLS_ST_GOTCLOSE ||
  962. tls->state == TOR_TLS_ST_SENTCLOSE) {
  963. log(LOG_WARN, LD_NET,
  964. "TLS returned \"half-closed\" value while already half-closed");
  965. return TOR_TLS_ERROR_MISC;
  966. }
  967. tls->state = TOR_TLS_ST_SENTCLOSE;
  968. /* fall through ... */
  969. } else {
  970. return err;
  971. }
  972. } /* end loop */
  973. }
  974. /** Return true iff this TLS connection is authenticated.
  975. */
  976. int
  977. tor_tls_peer_has_cert(tor_tls_t *tls)
  978. {
  979. X509 *cert;
  980. cert = SSL_get_peer_certificate(tls->ssl);
  981. tls_log_errors(LOG_WARN, "getting peer certificate");
  982. if (!cert)
  983. return 0;
  984. X509_free(cert);
  985. return 1;
  986. }
  987. /** Warn that a certificate lifetime extends through a certain range. */
  988. static void
  989. log_cert_lifetime(X509 *cert, const char *problem)
  990. {
  991. BIO *bio = NULL;
  992. BUF_MEM *buf;
  993. char *s1=NULL, *s2=NULL;
  994. char mytime[33];
  995. time_t now = time(NULL);
  996. struct tm tm;
  997. if (problem)
  998. log_warn(LD_GENERAL,
  999. "Certificate %s: is your system clock set incorrectly?",
  1000. problem);
  1001. if (!(bio = BIO_new(BIO_s_mem()))) {
  1002. log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
  1003. }
  1004. if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
  1005. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  1006. goto end;
  1007. }
  1008. BIO_get_mem_ptr(bio, &buf);
  1009. s1 = tor_strndup(buf->data, buf->length);
  1010. (void)BIO_reset(bio);
  1011. if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
  1012. tls_log_errors(LOG_WARN, "printing certificate lifetime");
  1013. goto end;
  1014. }
  1015. BIO_get_mem_ptr(bio, &buf);
  1016. s2 = tor_strndup(buf->data, buf->length);
  1017. strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
  1018. log_warn(LD_GENERAL,
  1019. "(certificate lifetime runs from %s through %s. Your time is %s.)",
  1020. s1,s2,mytime);
  1021. end:
  1022. /* Not expected to get invoked */
  1023. tls_log_errors(LOG_WARN, "getting certificate lifetime");
  1024. if (bio)
  1025. BIO_free(bio);
  1026. if (s1)
  1027. tor_free(s1);
  1028. if (s2)
  1029. tor_free(s2);
  1030. }
  1031. /** DOCDOC helper.
  1032. * cert_out needs to be freed. id_cert_out doesn't. */
  1033. static void
  1034. try_to_extract_certs_from_tls(int severity, tor_tls_t *tls,
  1035. X509 **cert_out, X509 **id_cert_out)
  1036. {
  1037. X509 *cert = NULL, *id_cert = NULL;
  1038. STACK_OF(X509) *chain = NULL;
  1039. int num_in_chain, i;
  1040. *cert_out = *id_cert_out = NULL;
  1041. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1042. return;
  1043. *cert_out = cert;
  1044. if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
  1045. return;
  1046. num_in_chain = sk_X509_num(chain);
  1047. /* 1 means we're receiving (server-side), and it's just the id_cert.
  1048. * 2 means we're connecting (client-side), and it's both the link
  1049. * cert and the id_cert.
  1050. */
  1051. if (num_in_chain < 1) {
  1052. log_fn(severity,LD_PROTOCOL,
  1053. "Unexpected number of certificates in chain (%d)",
  1054. num_in_chain);
  1055. return;
  1056. }
  1057. for (i=0; i<num_in_chain; ++i) {
  1058. id_cert = sk_X509_value(chain, i);
  1059. if (X509_cmp(id_cert, cert) != 0)
  1060. break;
  1061. }
  1062. *id_cert_out = id_cert;
  1063. }
  1064. /** If the provided tls connection is authenticated and has a
  1065. * certificate that is currently valid and signed, then set
  1066. * *<b>identity_key</b> to the identity certificate's key and return
  1067. * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
  1068. */
  1069. int
  1070. tor_tls_verify_v1(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
  1071. {
  1072. X509 *cert = NULL, *id_cert = NULL;
  1073. EVP_PKEY *id_pkey = NULL;
  1074. RSA *rsa;
  1075. int r = -1;
  1076. *identity_key = NULL;
  1077. try_to_extract_certs_from_tls(severity, tls, &cert, &id_cert);
  1078. if (!cert)
  1079. goto done;
  1080. if (!id_cert) {
  1081. log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
  1082. goto done;
  1083. }
  1084. if (!(id_pkey = X509_get_pubkey(id_cert)) ||
  1085. X509_verify(cert, id_pkey) <= 0) {
  1086. log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
  1087. tls_log_errors(severity,"verifying certificate");
  1088. goto done;
  1089. }
  1090. rsa = EVP_PKEY_get1_RSA(id_pkey);
  1091. if (!rsa)
  1092. goto done;
  1093. *identity_key = _crypto_new_pk_env_rsa(rsa);
  1094. r = 0;
  1095. done:
  1096. if (cert)
  1097. X509_free(cert);
  1098. if (id_pkey)
  1099. EVP_PKEY_free(id_pkey);
  1100. /* This should never get invoked, but let's make sure in case OpenSSL
  1101. * acts unexpectedly. */
  1102. tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
  1103. return r;
  1104. }
  1105. /** Check whether the certificate set on the connection <b>tls</b> is
  1106. * expired or not-yet-valid, give or take <b>tolerance</b>
  1107. * seconds. Return 0 for valid, -1 for failure.
  1108. *
  1109. * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
  1110. */
  1111. int
  1112. tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
  1113. {
  1114. time_t now, t;
  1115. X509 *cert;
  1116. int r = -1;
  1117. now = time(NULL);
  1118. if (!(cert = SSL_get_peer_certificate(tls->ssl)))
  1119. goto done;
  1120. t = now + tolerance;
  1121. if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
  1122. log_cert_lifetime(cert, "not yet valid");
  1123. goto done;
  1124. }
  1125. t = now - tolerance;
  1126. if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
  1127. log_cert_lifetime(cert, "already expired");
  1128. goto done;
  1129. }
  1130. r = 0;
  1131. done:
  1132. if (cert)
  1133. X509_free(cert);
  1134. /* Not expected to get invoked */
  1135. tls_log_errors(LOG_WARN, "checking certificate lifetime");
  1136. return r;
  1137. }
  1138. /** Return the number of bytes available for reading from <b>tls</b>.
  1139. */
  1140. int
  1141. tor_tls_get_pending_bytes(tor_tls_t *tls)
  1142. {
  1143. tor_assert(tls);
  1144. return SSL_pending(tls->ssl);
  1145. }
  1146. /** If <b>tls</b> requires that the next write be of a particular size,
  1147. * return that size. Otherwise, return 0. */
  1148. size_t
  1149. tor_tls_get_forced_write_size(tor_tls_t *tls)
  1150. {
  1151. return tls->wantwrite_n;
  1152. }
  1153. /** Sets n_read and n_written to the number of bytes read and written,
  1154. * respectivey, on the raw socket used by <b>tls</b> since the last time this
  1155. * function was called on <b>tls</b>. */
  1156. void
  1157. tor_tls_get_n_raw_bytes(tor_tls_t *tls, size_t *n_read, size_t *n_written)
  1158. {
  1159. unsigned long r, w;
  1160. r = BIO_number_read(SSL_get_rbio(tls->ssl));
  1161. w = BIO_number_written(SSL_get_wbio(tls->ssl));
  1162. /* We are ok with letting these unsigned ints go "negative" here:
  1163. * If we wrapped around, this should still give us the right answer, unless
  1164. * we wrapped around by more than ULONG_MAX since the last time we called
  1165. * this function.
  1166. */
  1167. *n_read = (size_t)(r - tls->last_read_count);
  1168. *n_written = (size_t)(w - tls->last_write_count);
  1169. tls->last_read_count = r;
  1170. tls->last_write_count = w;
  1171. }
  1172. /** Implement check_no_tls_errors: If there are any pending OpenSSL
  1173. * errors, log an error message. */
  1174. void
  1175. _check_no_tls_errors(const char *fname, int line)
  1176. {
  1177. if (ERR_peek_error() == 0)
  1178. return;
  1179. log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
  1180. tor_fix_source_file(fname), line);
  1181. tls_log_errors(LOG_WARN, NULL);
  1182. }
  1183. /**DOCDOC */
  1184. int
  1185. tor_tls_used_v1_handshake(tor_tls_t *tls)
  1186. {
  1187. if (tls->isServer) {
  1188. #ifdef V2_HANDSHAKE_SERVER
  1189. return ! tls->wasV2Handshake;
  1190. #endif
  1191. } else {
  1192. #ifdef V2_HANDSHAKE_CLIENT
  1193. return ! tls->wasV2Handshake;
  1194. #endif
  1195. }
  1196. return 1;
  1197. }