tortls.c 48 KB

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