Tor  0.4.3.0-alpha-dev
connection_or.c
Go to the documentation of this file.
1 /* Copyright (c) 2001 Matej Pfajfar.
2  * Copyright (c) 2001-2004, Roger Dingledine.
3  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4  * Copyright (c) 2007-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
7 /**
8  * \file connection_or.c
9  * \brief Functions to handle OR connections, TLS handshaking, and
10  * cells on the network.
11  *
12  * An or_connection_t is a subtype of connection_t (as implemented in
13  * connection.c) that uses a TLS connection to send and receive cells on the
14  * Tor network. (By sending and receiving cells connection_or.c, it cooperates
15  * with channeltls.c to implement a the channel interface of channel.c.)
16  *
17  * Every OR connection has an underlying tortls_t object (as implemented in
18  * tortls.c) which it uses as its TLS stream. It is responsible for
19  * sending and receiving cells over that TLS.
20  *
21  * This module also implements the client side of the v3 Tor link handshake,
22  **/
23 #include "core/or/or.h"
24 #include "feature/client/bridges.h"
25 #include "lib/buf/buffers.h"
26 /*
27  * Define this so we get channel internal functions, since we're implementing
28  * part of a subclass (channel_tls_t).
29  */
30 #define TOR_CHANNEL_INTERNAL_
31 #define CONNECTION_OR_PRIVATE
32 #define ORCONN_EVENT_PRIVATE
33 #include "core/or/channel.h"
34 #include "core/or/channeltls.h"
35 #include "core/or/circuitbuild.h"
36 #include "core/or/circuitlist.h"
37 #include "core/or/circuitstats.h"
38 #include "core/or/command.h"
39 #include "app/config/config.h"
41 #include "core/or/connection_or.h"
47 #include "lib/geoip/geoip.h"
48 #include "core/mainloop/mainloop.h"
49 #include "trunnel/link_handshake.h"
50 #include "trunnel/netinfo.h"
54 #include "core/proto/proto_cell.h"
55 #include "core/or/reasons.h"
56 #include "core/or/relay.h"
58 #include "feature/stats/rephist.h"
59 #include "feature/relay/router.h"
65 #include "core/or/scheduler.h"
67 #include "core/or/channelpadding.h"
69 
70 #include "core/or/cell_st.h"
71 #include "core/or/cell_queue_st.h"
75 #include "app/config/or_state_st.h"
77 #include "core/or/var_cell_st.h"
79 
80 #include "lib/tls/tortls.h"
81 #include "lib/tls/x509.h"
82 
83 #include "core/or/orconn_event.h"
84 
89  int started_here,
90  char *digest_rcvd_out);
91 
92 static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
93 
94 static unsigned int
96 static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
97 
98 /*
99  * Call this when changing connection state, so notifications to the owning
100  * channel can be handled.
101  */
102 
103 static void connection_or_change_state(or_connection_t *conn, uint8_t state);
104 
106  int started_here);
107 
108 /**************************************************************/
109 
110 /** Convert a connection_t* to an or_connection_t*; assert if the cast is
111  * invalid. */
114 {
115  tor_assert(c->magic == OR_CONNECTION_MAGIC);
116  return DOWNCAST(or_connection_t, c);
117 }
118 
119 /** Global map between Extended ORPort identifiers and OR
120  * connections. */
121 static digestmap_t *orconn_ext_or_id_map = NULL;
122 
123 /** Clear clear conn->identity_digest and update other data
124  * structures as appropriate.*/
125 void
127 {
128  tor_assert(conn);
129  memset(conn->identity_digest, 0, DIGEST_LEN);
130 }
131 
132 /** Clear all identities in OR conns.*/
133 void
135 {
137  SMARTLIST_FOREACH(conns, connection_t *, conn,
138  {
139  if (conn->type == CONN_TYPE_OR) {
140  connection_or_clear_identity(TO_OR_CONN(conn));
141  }
142  });
143 }
144 
145 /** Change conn->identity_digest to digest, and add conn into
146  * the appropriate digest maps.
147  *
148  * NOTE that this function only allows two kinds of transitions: from
149  * unset identity to set identity, and from idempotent re-settings
150  * of the same identity. It's not allowed to clear an identity or to
151  * change an identity. Return 0 on success, and -1 if the transition
152  * is not allowed.
153  **/
154 static void
156  const char *rsa_digest,
157  const ed25519_public_key_t *ed_id)
158 {
159  channel_t *chan = NULL;
160  tor_assert(conn);
161  tor_assert(rsa_digest);
162 
163  if (conn->chan)
164  chan = TLS_CHAN_TO_BASE(conn->chan);
165 
166  log_info(LD_HANDSHAKE, "Set identity digest for %p (%s): %s %s.",
167  conn,
168  escaped_safe_str(conn->base_.address),
169  hex_str(rsa_digest, DIGEST_LEN),
170  ed25519_fmt(ed_id));
171  log_info(LD_HANDSHAKE, " (Previously: %s %s)",
173  chan ? ed25519_fmt(&chan->ed25519_identity) : "<null>");
174 
175  const int rsa_id_was_set = ! tor_digest_is_zero(conn->identity_digest);
176  const int ed_id_was_set =
177  chan && !ed25519_public_key_is_zero(&chan->ed25519_identity);
178  const int rsa_changed =
179  tor_memneq(conn->identity_digest, rsa_digest, DIGEST_LEN);
180  const int ed_changed = ed_id_was_set &&
181  (!ed_id || !ed25519_pubkey_eq(ed_id, &chan->ed25519_identity));
182 
183  tor_assert(!rsa_changed || !rsa_id_was_set);
184  tor_assert(!ed_changed || !ed_id_was_set);
185 
186  if (!rsa_changed && !ed_changed)
187  return;
188 
189  /* If the identity was set previously, remove the old mapping. */
190  if (rsa_id_was_set) {
192  if (chan)
194  }
195 
196  memcpy(conn->identity_digest, rsa_digest, DIGEST_LEN);
197 
198  /* If we're initializing the IDs to zero, don't add a mapping yet. */
199  if (tor_digest_is_zero(rsa_digest) &&
200  (!ed_id || ed25519_public_key_is_zero(ed_id)))
201  return;
202 
203  /* Deal with channels */
204  if (chan)
205  channel_set_identity_digest(chan, rsa_digest, ed_id);
206 }
207 
208 /** Remove the Extended ORPort identifier of <b>conn</b> from the
209  * global identifier list. Also, clear the identifier from the
210  * connection itself. */
211 void
213 {
214  or_connection_t *tmp;
216  return;
217  if (!conn->ext_or_conn_id)
218  return;
219 
220  tmp = digestmap_remove(orconn_ext_or_id_map, conn->ext_or_conn_id);
222  tor_assert(tmp == conn);
223 
224  memset(conn->ext_or_conn_id, 0, EXT_OR_CONN_ID_LEN);
225 }
226 
227 /** Return the connection whose ext_or_id is <b>id</b>. Return NULL if no such
228  * connection is found. */
231 {
233  return NULL;
234  return digestmap_get(orconn_ext_or_id_map, id);
235 }
236 
237 /** Deallocate the global Extended ORPort identifier list */
238 void
240 {
241  digestmap_free(orconn_ext_or_id_map, NULL);
242  orconn_ext_or_id_map = NULL;
243 }
244 
245 /** Creates an Extended ORPort identifier for <b>conn</b> and deposits
246  * it into the global list of identifiers. */
247 void
249 {
250  char random_id[EXT_OR_CONN_ID_LEN];
251  or_connection_t *tmp;
252 
254  orconn_ext_or_id_map = digestmap_new();
255 
256  /* Remove any previous identifiers: */
257  if (conn->ext_or_conn_id && !tor_digest_is_zero(conn->ext_or_conn_id))
259 
260  do {
261  crypto_rand(random_id, sizeof(random_id));
262  } while (digestmap_get(orconn_ext_or_id_map, random_id));
263 
264  if (!conn->ext_or_conn_id)
265  conn->ext_or_conn_id = tor_malloc_zero(EXT_OR_CONN_ID_LEN);
266 
267  memcpy(conn->ext_or_conn_id, random_id, EXT_OR_CONN_ID_LEN);
268 
269  tmp = digestmap_set(orconn_ext_or_id_map, random_id, conn);
270  tor_assert(!tmp);
271 }
272 
273 /**************************************************************/
274 
275 /** Map from a string describing what a non-open OR connection was doing when
276  * failed, to an intptr_t describing the count of connections that failed that
277  * way. Note that the count is stored _as_ the pointer.
278  */
279 static strmap_t *broken_connection_counts;
280 
281 /** If true, do not record information in <b>broken_connection_counts</b>. */
283 
284 /** Record that an OR connection failed in <b>state</b>. */
285 static void
286 note_broken_connection(const char *state)
287 {
288  void *ptr;
289  intptr_t val;
291  return;
292 
294  broken_connection_counts = strmap_new();
295 
296  ptr = strmap_get(broken_connection_counts, state);
297  val = (intptr_t)ptr;
298  val++;
299  ptr = (void*)val;
300  strmap_set(broken_connection_counts, state, ptr);
301 }
302 
303 /** Forget all recorded states for failed connections. If
304  * <b>stop_recording</b> is true, don't record any more. */
305 void
306 clear_broken_connection_map(int stop_recording)
307 {
309  strmap_free(broken_connection_counts, NULL);
311  if (stop_recording)
313 }
314 
315 /** Write a detailed description the state of <b>orconn</b> into the
316  * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
317  * only the OR-conn level state but also the TLS state. It's useful for
318  * diagnosing broken handshakes. */
319 static void
321  char *buf, size_t buflen)
322 {
323  connection_t *conn = TO_CONN(orconn);
324  const char *conn_state;
325  char tls_state[256];
326 
327  tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
328 
329  conn_state = conn_state_to_string(conn->type, conn->state);
330  tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
331 
332  tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
333 }
334 
335 /** Record the current state of <b>orconn</b> as the state of a broken
336  * connection. */
337 static void
339 {
340  char buf[256];
342  return;
343  connection_or_get_state_description(orconn, buf, sizeof(buf));
344  log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
346 }
347 
348 /** Helper type used to sort connection states and find the most frequent. */
349 typedef struct broken_state_count_t {
350  intptr_t count;
351  const char *state;
353 
354 /** Helper function used to sort broken_state_count_t by frequency. */
355 static int
356 broken_state_count_compare(const void **a_ptr, const void **b_ptr)
357 {
358  const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
359  if (b->count < a->count)
360  return -1;
361  else if (b->count == a->count)
362  return 0;
363  else
364  return 1;
365 }
366 
367 /** Upper limit on the number of different states to report for connection
368  * failure. */
369 #define MAX_REASONS_TO_REPORT 10
370 
371 /** Report a list of the top states for failed OR connections at log level
372  * <b>severity</b>, in log domain <b>domain</b>. */
373 void
374 connection_or_report_broken_states(int severity, int domain)
375 {
376  int total = 0;
377  smartlist_t *items;
378 
380  return;
381 
382  items = smartlist_new();
383  STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
384  broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
385  c->count = (intptr_t)countptr;
386  total += (int)c->count;
387  c->state = state;
388  smartlist_add(items, c);
389  } STRMAP_FOREACH_END;
390 
392 
393  tor_log(severity, domain, "%d connections have failed%s", total,
394  smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
395 
396  SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
397  if (c_sl_idx > MAX_REASONS_TO_REPORT)
398  break;
399  tor_log(severity, domain,
400  " %d connections died in state %s", (int)c->count, c->state);
401  } SMARTLIST_FOREACH_END(c);
402 
404  smartlist_free(items);
405 }
406 
407 /**
408  * Helper function to publish an OR connection status event
409  *
410  * Publishes a messages to subscribers of ORCONN messages, and sends
411  * the control event.
412  **/
413 void
415  int reason)
416 {
417  orconn_status_msg_t *msg = tor_malloc(sizeof(*msg));
418 
419  msg->gid = conn->base_.global_identifier;
420  msg->status = tp;
421  msg->reason = reason;
422  orconn_status_publish(msg);
423  control_event_or_conn_status(conn, tp, reason);
424 }
425 
426 /**
427  * Helper function to publish a state change message
428  *
429  * connection_or_change_state() calls this to notify subscribers about
430  * a change of an OR connection state.
431  **/
432 static void
433 connection_or_state_publish(const or_connection_t *conn, uint8_t state)
434 {
435  orconn_state_msg_t *msg = tor_malloc(sizeof(*msg));
436 
437  msg->gid = conn->base_.global_identifier;
438  if (conn->is_pt) {
439  /* Do extra decoding because conn->proxy_type indicates the proxy
440  * protocol that tor uses to talk with the transport plugin,
441  * instead of PROXY_PLUGGABLE. */
442  tor_assert_nonfatal(conn->proxy_type != PROXY_NONE);
443  msg->proxy_type = PROXY_PLUGGABLE;
444  } else {
445  msg->proxy_type = conn->proxy_type;
446  }
447  msg->state = state;
448  if (conn->chan) {
449  msg->chan = TLS_CHAN_TO_BASE(conn->chan)->global_identifier;
450  } else {
451  msg->chan = 0;
452  }
453  orconn_state_publish(msg);
454 }
455 
456 /** Call this to change or_connection_t states, so the owning channel_tls_t can
457  * be notified.
458  */
459 
460 static void
462 {
463  tor_assert(conn);
464 
465  conn->base_.state = state;
466 
467  connection_or_state_publish(conn, state);
468  if (conn->chan)
470 }
471 
472 /** Return the number of circuits using an or_connection_t; this used to
473  * be an or_connection_t field, but it got moved to channel_t and we
474  * shouldn't maintain two copies. */
475 
476 MOCK_IMPL(int,
478 {
479  tor_assert(conn);
480 
481  if (conn->chan) {
482  return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
483  } else return 0;
484 }
485 
486 /**************************************************************/
487 
488 /** Pack the cell_t host-order structure <b>src</b> into network-order
489  * in the buffer <b>dest</b>. See tor-spec.txt for details about the
490  * wire format.
491  *
492  * Note that this function doesn't touch <b>dst</b>->next: the caller
493  * should set it or clear it as appropriate.
494  */
495 void
496 cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
497 {
498  char *dest = dst->body;
499  if (wide_circ_ids) {
500  set_uint32(dest, htonl(src->circ_id));
501  dest += 4;
502  } else {
503  /* Clear the last two bytes of dest, in case we can accidentally
504  * send them to the network somehow. */
505  memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2);
506  set_uint16(dest, htons(src->circ_id));
507  dest += 2;
508  }
509  set_uint8(dest, src->command);
510  memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
511 }
512 
513 /** Unpack the network-order buffer <b>src</b> into a host-order
514  * cell_t structure <b>dest</b>.
515  */
516 static void
517 cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
518 {
519  if (wide_circ_ids) {
520  dest->circ_id = ntohl(get_uint32(src));
521  src += 4;
522  } else {
523  dest->circ_id = ntohs(get_uint16(src));
524  src += 2;
525  }
526  dest->command = get_uint8(src);
527  memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
528 }
529 
530 /** Write the header of <b>cell</b> into the first VAR_CELL_MAX_HEADER_SIZE
531  * bytes of <b>hdr_out</b>. Returns number of bytes used. */
532 int
533 var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
534 {
535  int r;
536  if (wide_circ_ids) {
537  set_uint32(hdr_out, htonl(cell->circ_id));
538  hdr_out += 4;
540  } else {
541  set_uint16(hdr_out, htons(cell->circ_id));
542  hdr_out += 2;
543  r = VAR_CELL_MAX_HEADER_SIZE - 2;
544  }
545  set_uint8(hdr_out, cell->command);
546  set_uint16(hdr_out+1, htons(cell->payload_len));
547  return r;
548 }
549 
550 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
551  * payload space. */
552 var_cell_t *
553 var_cell_new(uint16_t payload_len)
554 {
555  size_t size = offsetof(var_cell_t, payload) + payload_len;
556  var_cell_t *cell = tor_malloc_zero(size);
557  cell->payload_len = payload_len;
558  cell->command = 0;
559  cell->circ_id = 0;
560  return cell;
561 }
562 
563 /**
564  * Copy a var_cell_t
565  */
566 
567 var_cell_t *
569 {
570  var_cell_t *copy = NULL;
571  size_t size = 0;
572 
573  if (src != NULL) {
574  size = offsetof(var_cell_t, payload) + src->payload_len;
575  copy = tor_malloc_zero(size);
576  copy->payload_len = src->payload_len;
577  copy->command = src->command;
578  copy->circ_id = src->circ_id;
579  memcpy(copy->payload, src->payload, copy->payload_len);
580  }
581 
582  return copy;
583 }
584 
585 /** Release all space held by <b>cell</b>. */
586 void
588 {
589  tor_free(cell);
590 }
591 
592 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
593 int
595 {
596  tor_assert(conn);
597 
598  log_info(LD_OR,"OR connection reached EOF. Closing.");
600 
601  return 0;
602 }
603 
604 /** Handle any new bytes that have come in on connection <b>conn</b>.
605  * If conn is in 'open' state, hand it to
606  * connection_or_process_cells_from_inbuf()
607  * (else do nothing).
608  */
609 int
611 {
612  /** Don't let the inbuf of a nonopen OR connection grow beyond this many
613  * bytes: it's either a broken client, a non-Tor client, or a DOS
614  * attempt. */
615 #define MAX_OR_INBUF_WHEN_NONOPEN 0
616 
617  int ret = 0;
618  tor_assert(conn);
619 
620  switch (conn->base_.state) {
623 
624  /* start TLS after handshake completion, or deal with error */
625  if (ret == 1) {
626  tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
627  if (connection_tls_start_handshake(conn, 0) < 0)
628  ret = -1;
629  /* Touch the channel's active timestamp if there is one */
630  if (conn->chan)
631  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
632  }
633  if (ret < 0) {
635  }
636 
637  return ret;
639  case OR_CONN_STATE_OPEN:
643  default:
644  break; /* don't do anything */
645  }
646 
647  /* This check was necessary with 0.2.2, when the TLS_SERVER_RENEGOTIATING
648  * check would otherwise just let data accumulate. It serves no purpose
649  * in 0.2.3.
650  *
651  * XXXX Remove this check once we verify that the above paragraph is
652  * 100% true. */
653  if (buf_datalen(conn->base_.inbuf) > MAX_OR_INBUF_WHEN_NONOPEN) {
654  log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated too much data (%d bytes) "
655  "on nonopen OR connection %s %s:%u in state %s; closing.",
656  (int)buf_datalen(conn->base_.inbuf),
657  connection_or_nonopen_was_started_here(conn) ? "to" : "from",
658  conn->base_.address, conn->base_.port,
659  conn_state_to_string(conn->base_.type, conn->base_.state));
661  ret = -1;
662  }
663 
664  return ret;
665 }
666 
667 /** Called whenever we have flushed some data on an or_conn: add more data
668  * from active circuits. */
669 int
671 {
672  size_t datalen;
673 
674  /* Update the channel's active timestamp if there is one */
675  if (conn->chan)
676  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
677 
678  /* If we're under the low water mark, add cells until we're just over the
679  * high water mark. */
680  datalen = connection_get_outbuf_len(TO_CONN(conn));
681  if (datalen < OR_CONN_LOWWATER) {
682  /* Let the scheduler know */
683  scheduler_channel_wants_writes(TLS_CHAN_TO_BASE(conn->chan));
684  }
685 
686  return 0;
687 }
688 
689 /** This is for channeltls.c to ask how many cells we could accept if
690  * they were available. */
691 ssize_t
693 {
694  size_t datalen, cell_network_size;
695  ssize_t n = 0;
696 
697  tor_assert(conn);
698 
699  /*
700  * If we're under the high water mark, we're potentially
701  * writeable; note this is different from the calculation above
702  * used to trigger when to start writing after we've stopped.
703  */
704  datalen = connection_get_outbuf_len(TO_CONN(conn));
705  if (datalen < OR_CONN_HIGHWATER) {
706  cell_network_size = get_cell_network_size(conn->wide_circ_ids);
707  n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, cell_network_size);
708  }
709 
710  return n;
711 }
712 
713 /** Connection <b>conn</b> has finished writing and has no bytes left on
714  * its outbuf.
715  *
716  * Otherwise it's in state "open": stop writing and return.
717  *
718  * If <b>conn</b> is broken, mark it for close and return -1, else
719  * return 0.
720  */
721 int
723 {
724  tor_assert(conn);
725  assert_connection_ok(TO_CONN(conn),0);
726 
727  switch (conn->base_.state) {
729  case OR_CONN_STATE_OPEN:
732  break;
733  default:
734  log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
736  return -1;
737  }
738 
739  /* Update the channel's active timestamp if there is one */
740  if (conn->chan)
741  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
742 
743  return 0;
744 }
745 
746 /** Connected handler for OR connections: begin the TLS handshake.
747  */
748 int
750 {
751  const int proxy_type = or_conn->proxy_type;
752  connection_t *conn;
753 
754  tor_assert(or_conn);
755  conn = TO_CONN(or_conn);
757 
758  log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
759  conn->address,conn->port);
760 
761  if (proxy_type != PROXY_NONE) {
762  /* start proxy handshake */
763  if (connection_proxy_connect(conn, proxy_type) < 0) {
764  connection_or_close_for_error(or_conn, 0);
765  return -1;
766  }
767 
770  return 0;
771  }
772 
773  if (connection_tls_start_handshake(or_conn, 0) < 0) {
774  /* TLS handshaking error of some kind. */
775  connection_or_close_for_error(or_conn, 0);
776  return -1;
777  }
778  return 0;
779 }
780 
781 /** Called when we're about to finally unlink and free an OR connection:
782  * perform necessary accounting and cleanup */
783 void
785 {
786  connection_t *conn = TO_CONN(or_conn);
787 
788  /* Tell the controlling channel we're closed */
789  if (or_conn->chan) {
790  channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
791  /*
792  * NULL this out because the channel might hang around a little
793  * longer before channel_run_cleanup() gets it.
794  */
795  or_conn->chan->conn = NULL;
796  or_conn->chan = NULL;
797  }
798 
799  /* Remember why we're closing this connection. */
800  if (conn->state != OR_CONN_STATE_OPEN) {
801  /* now mark things down as needed */
803  const or_options_t *options = get_options();
805  /* Tell the new guard API about the channel failure */
806  entry_guard_chan_failed(TLS_CHAN_TO_BASE(or_conn->chan));
807  if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
808  int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
809  connection_or_event_status(or_conn, OR_CONN_EVENT_FAILED,
810  reason);
811  if (!authdir_mode_tests_reachability(options))
814  reason, or_conn);
815  }
816  }
817  } else if (conn->hold_open_until_flushed) {
818  /* We only set hold_open_until_flushed when we're intentionally
819  * closing a connection. */
820  connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
822  } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
823  connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
825  }
826 }
827 
828 /** Return 1 if identity digest <b>id_digest</b> is known to be a
829  * currently or recently running relay. Otherwise return 0. */
830 int
832 {
833  if (router_get_consensus_status_by_id(id_digest))
834  return 1; /* It's in the consensus: "yes" */
835  if (router_get_by_id_digest(id_digest))
836  return 1; /* Not in the consensus, but we have a descriptor for
837  * it. Probably it was in a recent consensus. "Yes". */
838  return 0;
839 }
840 
841 /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
842  * relay, we will rely on the global read and write buckets, so give it
843  * per-conn limits that are big enough they'll never matter. But if it's
844  * not a known relay, first check if we set PerConnBwRate/Burst, then
845  * check if the consensus sets them, else default to 'big enough'.
846  *
847  * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
848  * clip the bucket if it happens to be <em>too</em> full.
849  */
850 static void
852  const or_options_t *options)
853 {
854  int rate, burst; /* per-connection rate limiting params */
856  /* It's in the consensus, or we have a descriptor for it meaning it
857  * was probably in a recent consensus. It's a recognized relay:
858  * give it full bandwidth. */
859  rate = (int)options->BandwidthRate;
860  burst = (int)options->BandwidthBurst;
861  } else {
862  /* Not a recognized relay. Squeeze it down based on the suggested
863  * bandwidth parameters in the consensus, but allow local config
864  * options to override. */
865  rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
866  networkstatus_get_param(NULL, "perconnbwrate",
867  (int)options->BandwidthRate, 1, INT32_MAX);
868  burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
869  networkstatus_get_param(NULL, "perconnbwburst",
870  (int)options->BandwidthBurst, 1, INT32_MAX);
871  }
872 
873  token_bucket_rw_adjust(&conn->bucket, rate, burst);
874  if (reset) {
876  }
877 }
878 
879 /** Either our set of relays or our per-conn rate limits have changed.
880  * Go through all the OR connections and update their token buckets to make
881  * sure they don't exceed their maximum values. */
882 void
884  const or_options_t *options)
885 {
886  SMARTLIST_FOREACH(conns, connection_t *, conn,
887  {
888  if (connection_speaks_cells(conn))
890  });
891 }
892 
893 /* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
894  * non-canonical otherwise. Adjust idle_timeout accordingly.
895  */
896 void
897 connection_or_set_canonical(or_connection_t *or_conn,
898  int is_canonical)
899 {
900  if (bool_eq(is_canonical, or_conn->is_canonical) &&
901  or_conn->idle_timeout != 0) {
902  /* Don't recalculate an existing idle_timeout unless the canonical
903  * status changed. */
904  return;
905  }
906 
907  or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
909  TLS_CHAN_TO_BASE(or_conn->chan), is_canonical);
910 
911  log_info(LD_CIRC,
912  "Channel %"PRIu64 " chose an idle timeout of %d.",
913  or_conn->chan ?
914  (TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier):0,
915  or_conn->idle_timeout);
916 }
917 
918 /** If we don't necessarily know the router we're connecting to, but we
919  * have an addr/port/id_digest, then fill in as much as we can. Start
920  * by checking to see if this describes a router we know.
921  * <b>started_here</b> is 1 if we are the initiator of <b>conn</b> and
922  * 0 if it's an incoming connection. */
923 void
925  const tor_addr_t *addr, uint16_t port,
926  const char *id_digest,
927  const ed25519_public_key_t *ed_id,
928  int started_here)
929 {
930  log_debug(LD_HANDSHAKE, "init conn from address %s: %s, %s (%d)",
931  fmt_addr(addr),
932  hex_str((const char*)id_digest, DIGEST_LEN),
933  ed25519_fmt(ed_id),
934  started_here);
935 
936  connection_or_set_identity_digest(conn, id_digest, ed_id);
938 
939  conn->base_.port = port;
940  tor_addr_copy(&conn->base_.addr, addr);
941  tor_addr_copy(&conn->real_addr, addr);
942 
943  connection_or_check_canonicity(conn, started_here);
944 }
945 
946 /** Check whether the identity of <b>conn</b> matches a known node. If it
947  * does, check whether the address of conn matches the expected address, and
948  * update the connection's is_canonical flag, nickname, and address fields as
949  * appropriate. */
950 static void
952 {
953  const char *id_digest = conn->identity_digest;
954  const ed25519_public_key_t *ed_id = NULL;
955  const tor_addr_t *addr = &conn->real_addr;
956  if (conn->chan)
957  ed_id = & TLS_CHAN_TO_BASE(conn->chan)->ed25519_identity;
958 
959  const node_t *r = node_get_by_id(id_digest);
960  if (r &&
962  ! node_ed25519_id_matches(r, ed_id)) {
963  /* If this node is capable of proving an ed25519 ID,
964  * we can't call this a canonical connection unless both IDs match. */
965  r = NULL;
966  }
967 
968  if (r) {
969  tor_addr_port_t node_ap;
970  node_get_pref_orport(r, &node_ap);
971  /* XXXX proposal 186 is making this more complex. For now, a conn
972  is canonical when it uses the _preferred_ address. */
973  if (tor_addr_eq(&conn->base_.addr, &node_ap.addr))
974  connection_or_set_canonical(conn, 1);
975  if (!started_here) {
976  /* Override the addr/port, so our log messages will make sense.
977  * This is dangerous, since if we ever try looking up a conn by
978  * its actual addr/port, we won't remember. Careful! */
979  /* XXXX arma: this is stupid, and it's the reason we need real_addr
980  * to track is_canonical properly. What requires it? */
981  /* XXXX <arma> i believe the reason we did this, originally, is because
982  * we wanted to log what OR a connection was to, and if we logged the
983  * right IP address and port 56244, that wouldn't be as helpful. now we
984  * log the "right" port too, so we know if it's moria1 or moria2.
985  */
986  tor_addr_copy(&conn->base_.addr, &node_ap.addr);
987  conn->base_.port = node_ap.port;
988  }
989  tor_free(conn->nickname);
990  conn->nickname = tor_strdup(node_get_nickname(r));
991  tor_free(conn->base_.address);
992  conn->base_.address = tor_addr_to_str_dup(&node_ap.addr);
993  } else {
994  tor_free(conn->nickname);
995  conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
996  conn->nickname[0] = '$';
998  conn->identity_digest, DIGEST_LEN);
999 
1000  tor_free(conn->base_.address);
1001  conn->base_.address = tor_addr_to_str_dup(addr);
1002  }
1003 
1004  /*
1005  * We have to tell channeltls.c to update the channel marks (local, in
1006  * particular), since we may have changed the address.
1007  */
1008 
1009  if (conn->chan) {
1011  }
1012 }
1013 
1014 /** These just pass all the is_bad_for_new_circs manipulation on to
1015  * channel_t */
1016 
1017 static unsigned int
1019 {
1020  tor_assert(or_conn);
1021 
1022  if (or_conn->chan)
1023  return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
1024  else return 0;
1025 }
1026 
1027 static void
1028 connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
1029 {
1030  tor_assert(or_conn);
1031 
1032  if (or_conn->chan)
1033  channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
1034 }
1035 
1036 /** How old do we let a connection to an OR get before deciding it's
1037  * too old for new circuits? */
1038 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
1039 
1040 /** Expire an or_connection if it is too old. Helper for
1041  * connection_or_group_set_badness_ and fast path for
1042  * channel_rsa_id_group_set_badness.
1043  *
1044  * Returns 1 if the connection was already expired, else 0.
1045  */
1046 int
1048  or_connection_t *or_conn,
1049  int force)
1050 {
1051  /* XXXX this function should also be about channels? */
1052  if (or_conn->base_.marked_for_close ||
1054  return 1;
1055 
1056  if (force ||
1058  < now) {
1059  log_info(LD_OR,
1060  "Marking OR conn to %s:%d as too old for new circuits "
1061  "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
1062  or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1063  (int)(now - or_conn->base_.timestamp_created));
1064  connection_or_mark_bad_for_new_circs(or_conn);
1065  }
1066 
1067  return 0;
1068 }
1069 
1070 /** Given a list of all the or_connections with a given
1071  * identity, set elements of that list as is_bad_for_new_circs as
1072  * appropriate. Helper for connection_or_set_bad_connections().
1073  *
1074  * Specifically, we set the is_bad_for_new_circs flag on:
1075  * - all connections if <b>force</b> is true.
1076  * - all connections that are too old.
1077  * - all open non-canonical connections for which a canonical connection
1078  * exists to the same router.
1079  * - all open canonical connections for which a 'better' canonical
1080  * connection exists to the same router.
1081  * - all open non-canonical connections for which a 'better' non-canonical
1082  * connection exists to the same router at the same address.
1083  *
1084  * See channel_is_better() in channel.c for our idea of what makes one OR
1085  * connection better than another.
1086  */
1087 void
1089 {
1090  /* XXXX this function should be entirely about channels, not OR
1091  * XXXX connections. */
1092 
1093  or_connection_t *best = NULL;
1094  int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
1095  time_t now = time(NULL);
1096 
1097  /* Pass 1: expire everything that's old, and see what the status of
1098  * everything else is. */
1099  SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1100  if (connection_or_single_set_badness_(now, or_conn, force))
1101  continue;
1102 
1103  if (connection_or_is_bad_for_new_circs(or_conn)) {
1104  ++n_old;
1105  } else if (or_conn->base_.state != OR_CONN_STATE_OPEN) {
1106  ++n_inprogress;
1107  } else if (or_conn->is_canonical) {
1108  ++n_canonical;
1109  } else {
1110  ++n_other;
1111  }
1112  } SMARTLIST_FOREACH_END(or_conn);
1113 
1114  /* Pass 2: We know how about how good the best connection is.
1115  * expire everything that's worse, and find the very best if we can. */
1116  SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1117  if (or_conn->base_.marked_for_close ||
1119  continue; /* This one doesn't need to be marked bad. */
1120  if (or_conn->base_.state != OR_CONN_STATE_OPEN)
1121  continue; /* Don't mark anything bad until we have seen what happens
1122  * when the connection finishes. */
1123  if (n_canonical && !or_conn->is_canonical) {
1124  /* We have at least one open canonical connection to this router,
1125  * and this one is open but not canonical. Mark it bad. */
1126  log_info(LD_OR,
1127  "Marking OR conn to %s:%d as unsuitable for new circuits: "
1128  "(fd "TOR_SOCKET_T_FORMAT", %d secs old). It is not "
1129  "canonical, and we have another connection to that OR that is.",
1130  or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1131  (int)(now - or_conn->base_.timestamp_created));
1132  connection_or_mark_bad_for_new_circs(or_conn);
1133  continue;
1134  }
1135 
1136  if (!best ||
1137  channel_is_better(TLS_CHAN_TO_BASE(or_conn->chan),
1138  TLS_CHAN_TO_BASE(best->chan))) {
1139  best = or_conn;
1140  }
1141  } SMARTLIST_FOREACH_END(or_conn);
1142 
1143  if (!best)
1144  return;
1145 
1146  /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
1147  * every other open connection. If it's non-canonical, mark as bad
1148  * every other open connection to the same address.
1149  *
1150  * XXXX This isn't optimal; if we have connections to an OR at multiple
1151  * addresses, we'd like to pick the best _for each address_, and mark as
1152  * bad every open connection that isn't best for its address. But this
1153  * can only occur in cases where the other OR is old (so we have no
1154  * canonical connection to it), or where all the connections to the OR are
1155  * at noncanonical addresses and we have no good direct connection (which
1156  * means we aren't at risk of attaching circuits to it anyway). As
1157  * 0.1.2.x dies out, the first case will go away, and the second one is
1158  * "mostly harmless", so a fix can wait until somebody is bored.
1159  */
1160  SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1161  if (or_conn->base_.marked_for_close ||
1163  or_conn->base_.state != OR_CONN_STATE_OPEN)
1164  continue;
1165  if (or_conn != best &&
1166  channel_is_better(TLS_CHAN_TO_BASE(best->chan),
1167  TLS_CHAN_TO_BASE(or_conn->chan))) {
1168  /* This isn't the best conn, _and_ the best conn is better than it */
1169  if (best->is_canonical) {
1170  log_info(LD_OR,
1171  "Marking OR conn to %s:%d as unsuitable for new circuits: "
1172  "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
1173  "We have a better canonical one "
1174  "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1175  or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1176  (int)(now - or_conn->base_.timestamp_created),
1177  best->base_.s, (int)(now - best->base_.timestamp_created));
1178  connection_or_mark_bad_for_new_circs(or_conn);
1179  } else if (!tor_addr_compare(&or_conn->real_addr,
1180  &best->real_addr, CMP_EXACT)) {
1181  log_info(LD_OR,
1182  "Marking OR conn to %s:%d as unsuitable for new circuits: "
1183  "(fd "TOR_SOCKET_T_FORMAT", %d secs old). We have a better "
1184  "one with the "
1185  "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1186  or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1187  (int)(now - or_conn->base_.timestamp_created),
1188  best->base_.s, (int)(now - best->base_.timestamp_created));
1189  connection_or_mark_bad_for_new_circs(or_conn);
1190  }
1191  }
1192  } SMARTLIST_FOREACH_END(or_conn);
1193 }
1194 
1195 /* Lifetime of a connection failure. After that, we'll retry. This is in
1196  * seconds. */
1197 #define OR_CONNECT_FAILURE_LIFETIME 60
1198 /* The interval to use with when to clean up the failure cache. */
1199 #define OR_CONNECT_FAILURE_CLEANUP_INTERVAL 60
1200 
1201 /* When is the next time we have to cleanup the failure map. We keep this
1202  * because we clean it opportunistically. */
1203 static time_t or_connect_failure_map_next_cleanup_ts = 0;
1204 
1205 /* OR connection failure entry data structure. It is kept in the connection
1206  * failure map defined below and indexed by OR identity digest, address and
1207  * port.
1208  *
1209  * We need to identify a connection failure with these three values because we
1210  * want to avoid to wrongfully blacklist a relay if someone is trying to
1211  * extend to a known identity digest but with the wrong IP/port. For instance,
1212  * it can happen if a relay changed its port but the client still has an old
1213  * descriptor with the old port. We want to stop connecting to that
1214  * IP/port/identity all together, not only the relay identity. */
1216  HT_ENTRY(or_connect_failure_entry_t) node;
1217  /* Identity digest of the connection where it is connecting to. */
1218  uint8_t identity_digest[DIGEST_LEN];
1219  /* This is the connection address from the base connection_t. After the
1220  * connection is checked for canonicity, the base address should represent
1221  * what we know instead of where we are connecting to. This is what we need
1222  * so we can correlate known relays within the consensus. */
1223  tor_addr_t addr;
1224  uint16_t port;
1225  /* Last time we were unable to connect. */
1226  time_t last_failed_connect_ts;
1228 
1229 /* Map where we keep connection failure entries. They are indexed by addr,
1230  * port and identity digest. */
1231 static HT_HEAD(or_connect_failure_ht, or_connect_failure_entry_t)
1232  or_connect_failures_map = HT_INITIALIZER();
1233 
1234 /* Helper: Hashtable equal function. Return 1 if equal else 0. */
1235 static int
1236 or_connect_failure_ht_eq(const or_connect_failure_entry_t *a,
1237  const or_connect_failure_entry_t *b)
1238 {
1239  return fast_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN) &&
1240  tor_addr_eq(&a->addr, &b->addr) &&
1241  a->port == b->port;
1242 }
1243 
1244 /* Helper: Return the hash for the hashtable of the given entry. For this
1245  * table, it is a combination of address, port and identity digest. */
1246 static unsigned int
1247 or_connect_failure_ht_hash(const or_connect_failure_entry_t *entry)
1248 {
1249  size_t offset = 0, addr_size;
1250  const void *addr_ptr;
1251  /* Largest size is IPv6 and IPv4 is smaller so it is fine. */
1252  uint8_t data[16 + sizeof(uint16_t) + DIGEST_LEN];
1253 
1254  /* Get the right address bytes depending on the family. */
1255  switch (tor_addr_family(&entry->addr)) {
1256  case AF_INET:
1257  addr_size = 4;
1258  addr_ptr = &entry->addr.addr.in_addr.s_addr;
1259  break;
1260  case AF_INET6:
1261  addr_size = 16;
1262  addr_ptr = &entry->addr.addr.in6_addr.s6_addr;
1263  break;
1264  default:
1265  tor_assert_nonfatal_unreached();
1266  return 0;
1267  }
1268 
1269  memcpy(data, addr_ptr, addr_size);
1270  offset += addr_size;
1271  memcpy(data + offset, entry->identity_digest, DIGEST_LEN);
1272  offset += DIGEST_LEN;
1273  set_uint16(data + offset, entry->port);
1274  offset += sizeof(uint16_t);
1275 
1276  return (unsigned int) siphash24g(data, offset);
1277 }
1278 
1279 HT_PROTOTYPE(or_connect_failure_ht, or_connect_failure_entry_t, node,
1280  or_connect_failure_ht_hash, or_connect_failure_ht_eq)
1281 
1282 HT_GENERATE2(or_connect_failure_ht, or_connect_failure_entry_t, node,
1283  or_connect_failure_ht_hash, or_connect_failure_ht_eq,
1285 
1286 /* Initialize a given connect failure entry with the given identity_digest,
1287  * addr and port. All field are optional except ocf. */
1288 static void
1289 or_connect_failure_init(const char *identity_digest, const tor_addr_t *addr,
1290  uint16_t port, or_connect_failure_entry_t *ocf)
1291 {
1292  tor_assert(ocf);
1293  if (identity_digest) {
1294  memcpy(ocf->identity_digest, identity_digest,
1295  sizeof(ocf->identity_digest));
1296  }
1297  if (addr) {
1298  tor_addr_copy(&ocf->addr, addr);
1299  }
1300  ocf->port = port;
1301 }
1302 
1303 /* Return a newly allocated connection failure entry. It is initialized with
1304  * the given or_conn data. This can't fail. */
1306 or_connect_failure_new(const or_connection_t *or_conn)
1307 {
1308  or_connect_failure_entry_t *ocf = tor_malloc_zero(sizeof(*ocf));
1309  or_connect_failure_init(or_conn->identity_digest, &or_conn->real_addr,
1310  TO_CONN(or_conn)->port, ocf);
1311  return ocf;
1312 }
1313 
1314 /* Return a connection failure entry matching the given or_conn. NULL is
1315  * returned if not found. */
1317 or_connect_failure_find(const or_connection_t *or_conn)
1318 {
1320  tor_assert(or_conn);
1321  or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
1322  TO_CONN(or_conn)->port, &lookup);
1323  return HT_FIND(or_connect_failure_ht, &or_connect_failures_map, &lookup);
1324 }
1325 
1326 /* Note down in the connection failure cache that a failure occurred on the
1327  * given or_conn. */
1328 STATIC void
1329 note_or_connect_failed(const or_connection_t *or_conn)
1330 {
1331  or_connect_failure_entry_t *ocf = NULL;
1332 
1333  tor_assert(or_conn);
1334 
1335  ocf = or_connect_failure_find(or_conn);
1336  if (ocf == NULL) {
1337  ocf = or_connect_failure_new(or_conn);
1338  HT_INSERT(or_connect_failure_ht, &or_connect_failures_map, ocf);
1339  }
1340  ocf->last_failed_connect_ts = approx_time();
1341 }
1342 
1343 /* Cleanup the connection failure cache and remove all entries below the
1344  * given cutoff. */
1345 static void
1346 or_connect_failure_map_cleanup(time_t cutoff)
1347 {
1348  or_connect_failure_entry_t **ptr, **next, *entry;
1349 
1350  for (ptr = HT_START(or_connect_failure_ht, &or_connect_failures_map);
1351  ptr != NULL; ptr = next) {
1352  entry = *ptr;
1353  if (entry->last_failed_connect_ts <= cutoff) {
1354  next = HT_NEXT_RMV(or_connect_failure_ht, &or_connect_failures_map, ptr);
1355  tor_free(entry);
1356  } else {
1357  next = HT_NEXT(or_connect_failure_ht, &or_connect_failures_map, ptr);
1358  }
1359  }
1360 }
1361 
1362 /* Return true iff the given OR connection can connect to its destination that
1363  * is the triplet identity_digest, address and port.
1364  *
1365  * The or_conn MUST have gone through connection_or_check_canonicity() so the
1366  * base address is properly set to what we know or doesn't know. */
1367 STATIC int
1368 should_connect_to_relay(const or_connection_t *or_conn)
1369 {
1370  time_t now, cutoff;
1371  time_t connect_failed_since_ts = 0;
1373 
1374  tor_assert(or_conn);
1375 
1376  now = approx_time();
1377  cutoff = now - OR_CONNECT_FAILURE_LIFETIME;
1378 
1379  /* Opportunistically try to cleanup the failure cache. We do that at regular
1380  * interval so it doesn't grow too big. */
1381  if (or_connect_failure_map_next_cleanup_ts <= now) {
1382  or_connect_failure_map_cleanup(cutoff);
1383  or_connect_failure_map_next_cleanup_ts =
1384  now + OR_CONNECT_FAILURE_CLEANUP_INTERVAL;
1385  }
1386 
1387  /* Look if we have failed previously to the same destination as this
1388  * OR connection. */
1389  ocf = or_connect_failure_find(or_conn);
1390  if (ocf) {
1391  connect_failed_since_ts = ocf->last_failed_connect_ts;
1392  }
1393  /* If we do have an unable to connect timestamp and it is below cutoff, we
1394  * can connect. Or we have never failed before so let it connect. */
1395  if (connect_failed_since_ts > cutoff) {
1396  goto no_connect;
1397  }
1398 
1399  /* Ok we can connect! */
1400  return 1;
1401  no_connect:
1402  return 0;
1403 }
1404 
1405 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
1406  * a TCP connection. Send notifications appropriately.
1407  *
1408  * <b>reason</b> specifies the or_conn_end_reason for the failure;
1409  * <b>msg</b> specifies the strerror-style error message.
1410  */
1411 void
1413  int reason, const char *msg)
1414 {
1415  connection_or_event_status(conn, OR_CONN_EVENT_FAILED, reason);
1417  control_event_bootstrap_prob_or(msg, reason, conn);
1418  note_or_connect_failed(conn);
1419 }
1420 
1421 /** <b>conn</b> got an error in connection_handle_read_impl() or
1422  * connection_handle_write_impl() and is going to die soon.
1423  *
1424  * <b>reason</b> specifies the or_conn_end_reason for the failure;
1425  * <b>msg</b> specifies the strerror-style error message.
1426  */
1427 void
1429  int reason, const char *msg)
1430 {
1431  channel_t *chan;
1432 
1433  tor_assert(conn);
1434 
1435  /* If we're connecting, call connect_failed() too */
1436  if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
1437  connection_or_connect_failed(conn, reason, msg);
1438 
1439  /* Tell the controlling channel if we have one */
1440  if (conn->chan) {
1441  chan = TLS_CHAN_TO_BASE(conn->chan);
1442  /* Don't transition if we're already in closing, closed or error */
1443  if (!CHANNEL_CONDEMNED(chan)) {
1445  }
1446  }
1447 
1448  /* No need to mark for error because connection.c is about to do that */
1449 }
1450 
1451 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
1452  * handshake with an OR with identity digest <b>id_digest</b>. Optionally,
1453  * pass in a pointer to a channel using this connection.
1454  *
1455  * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
1456  * return that connection. If the connect() is in progress, set the
1457  * new conn's state to 'connecting' and return it. If connect() succeeds,
1458  * call connection_tls_start_handshake() on it.
1459  *
1460  * This function is called from router_retry_connections(), for
1461  * ORs connecting to ORs, and circuit_establish_circuit(), for
1462  * OPs connecting to ORs.
1463  *
1464  * Return the launched conn, or NULL if it failed.
1465  */
1466 
1468 connection_or_connect, (const tor_addr_t *_addr, uint16_t port,
1469  const char *id_digest,
1470  const ed25519_public_key_t *ed_id,
1471  channel_tls_t *chan))
1472 {
1473  or_connection_t *conn;
1474  const or_options_t *options = get_options();
1475  int socket_error = 0;
1476  tor_addr_t addr;
1477 
1478  int r;
1479  tor_addr_t proxy_addr;
1480  uint16_t proxy_port;
1481  int proxy_type, is_pt = 0;
1482 
1483  tor_assert(_addr);
1484  tor_assert(id_digest);
1485  tor_addr_copy(&addr, _addr);
1486 
1487  if (server_mode(options) && router_digest_is_me(id_digest)) {
1488  log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
1489  return NULL;
1490  }
1491  if (server_mode(options) && router_ed25519_id_is_me(ed_id)) {
1492  log_info(LD_PROTOCOL,"Client asked me to connect to myself by Ed25519 "
1493  "identity. Refusing.");
1494  return NULL;
1495  }
1496 
1498 
1499  /*
1500  * Set up conn so it's got all the data we need to remember for channels
1501  *
1502  * This stuff needs to happen before connection_or_init_conn_from_address()
1503  * so connection_or_set_identity_digest() and such know where to look to
1504  * keep the channel up to date.
1505  */
1506  conn->chan = chan;
1507  chan->conn = conn;
1508  connection_or_init_conn_from_address(conn, &addr, port, id_digest, ed_id, 1);
1509 
1510  /* We have a proper OR connection setup, now check if we can connect to it
1511  * that is we haven't had a failure earlier. This is to avoid to try to
1512  * constantly connect to relays that we think are not reachable. */
1513  if (!should_connect_to_relay(conn)) {
1514  log_info(LD_GENERAL, "Can't connect to identity %s at %s:%u because we "
1515  "failed earlier. Refusing.",
1516  hex_str(id_digest, DIGEST_LEN), fmt_addr(&TO_CONN(conn)->addr),
1517  TO_CONN(conn)->port);
1518  connection_free_(TO_CONN(conn));
1519  return NULL;
1520  }
1521 
1522  conn->is_outgoing = 1;
1523 
1524  /* If we are using a proxy server, find it and use it. */
1525  r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, &is_pt,
1526  TO_CONN(conn));
1527  if (r == 0) {
1528  conn->proxy_type = proxy_type;
1529  if (proxy_type != PROXY_NONE) {
1530  tor_addr_copy(&addr, &proxy_addr);
1531  port = proxy_port;
1532  conn->base_.proxy_state = PROXY_INFANT;
1533  conn->is_pt = is_pt;
1534  }
1536  connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1537  } else {
1538  /* This duplication of state change calls is necessary in case we
1539  * run into an error condition below */
1541  connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1542 
1543  /* get_proxy_addrport() might fail if we have a Bridge line that
1544  references a transport, but no ClientTransportPlugin lines
1545  defining its transport proxy. If this is the case, let's try to
1546  output a useful log message to the user. */
1547  const char *transport_name =
1549  TO_CONN(conn)->port);
1550 
1551  if (transport_name) {
1552  log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
1553  "using pluggable transport '%s', but we can't find a pluggable "
1554  "transport proxy supporting '%s'. This can happen if you "
1555  "haven't provided a ClientTransportPlugin line, or if "
1556  "your pluggable transport proxy stopped running.",
1557  fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port),
1558  transport_name, transport_name);
1559 
1561  "Can't connect to bridge",
1562  END_OR_CONN_REASON_PT_MISSING,
1563  conn);
1564 
1565  } else {
1566  log_warn(LD_GENERAL, "Tried to connect to '%s' through a proxy, but "
1567  "the proxy address could not be found.",
1568  fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port));
1569  }
1570 
1571  connection_free_(TO_CONN(conn));
1572  return NULL;
1573  }
1574 
1575  switch (connection_connect(TO_CONN(conn), conn->base_.address,
1576  &addr, port, &socket_error)) {
1577  case -1:
1578  /* We failed to establish a connection probably because of a local
1579  * error. No need to blame the guard in this case. Notify the networking
1580  * system of this failure. */
1582  errno_to_orconn_end_reason(socket_error),
1583  tor_socket_strerror(socket_error));
1584  connection_free_(TO_CONN(conn));
1585  return NULL;
1586  case 0:
1588  /* writable indicates finish, readable indicates broken link,
1589  error indicates broken link on windows */
1590  return conn;
1591  /* case 1: fall through */
1592  }
1593 
1594  if (connection_or_finished_connecting(conn) < 0) {
1595  /* already marked for close */
1596  return NULL;
1597  }
1598  return conn;
1599 }
1600 
1601 /** Mark orconn for close and transition the associated channel, if any, to
1602  * the closing state.
1603  *
1604  * It's safe to call this and connection_or_close_for_error() any time, and
1605  * channel layer will treat it as a connection closing for reasons outside
1606  * its control, like the remote end closing it. It can also be a local
1607  * reason that's specific to connection_t/or_connection_t rather than
1608  * the channel mechanism, such as expiration of old connections in
1609  * run_connection_housekeeping(). If you want to close a channel_t
1610  * from somewhere that logically works in terms of generic channels
1611  * rather than connections, use channel_mark_for_close(); see also
1612  * the comment on that function in channel.c.
1613  */
1614 
1615 void
1617 {
1618  channel_t *chan = NULL;
1619 
1620  tor_assert(orconn);
1621  if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1622  else connection_mark_for_close_internal(TO_CONN(orconn));
1623  if (orconn->chan) {
1624  chan = TLS_CHAN_TO_BASE(orconn->chan);
1625  /* Don't transition if we're already in closing, closed or error */
1626  if (!CHANNEL_CONDEMNED(chan)) {
1628  }
1629  }
1630 }
1631 
1632 /** Mark orconn for close and transition the associated channel, if any, to
1633  * the error state.
1634  */
1635 
1636 MOCK_IMPL(void,
1638 {
1639  channel_t *chan = NULL;
1640 
1641  tor_assert(orconn);
1642  if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1643  else connection_mark_for_close_internal(TO_CONN(orconn));
1644  if (orconn->chan) {
1645  chan = TLS_CHAN_TO_BASE(orconn->chan);
1646  /* Don't transition if we're already in closing, closed or error */
1647  if (!CHANNEL_CONDEMNED(chan)) {
1649  }
1650  }
1651 }
1652 
1653 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
1654  * we initiated the connection, else it's 1.
1655  *
1656  * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
1657  * pass <b>conn</b> to connection_tls_continue_handshake().
1658  *
1659  * Return -1 if <b>conn</b> is broken, else return 0.
1660  */
1661 MOCK_IMPL(int,
1663 {
1664  channel_listener_t *chan_listener;
1665  channel_t *chan;
1666 
1667  /* Incoming connections will need a new channel passed to the
1668  * channel_tls_listener */
1669  if (receiving) {
1670  /* It shouldn't already be set */
1671  tor_assert(!(conn->chan));
1672  chan_listener = channel_tls_get_listener();
1673  if (!chan_listener) {
1674  chan_listener = channel_tls_start_listener();
1675  command_setup_listener(chan_listener);
1676  }
1677  chan = channel_tls_handle_incoming(conn);
1678  channel_listener_queue_incoming(chan_listener, chan);
1679  }
1680 
1682  tor_assert(!conn->tls);
1683  conn->tls = tor_tls_new(conn->base_.s, receiving);
1684  if (!conn->tls) {
1685  log_warn(LD_BUG,"tor_tls_new failed. Closing.");
1686  return -1;
1687  }
1688  tor_tls_set_logged_address(conn->tls, // XXX client and relay?
1689  escaped_safe_str(conn->base_.address));
1690 
1692  log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
1693  conn->base_.s);
1694 
1695  if (connection_tls_continue_handshake(conn) < 0)
1696  return -1;
1697 
1698  return 0;
1699 }
1700 
1701 /** Block all future attempts to renegotiate on 'conn' */
1702 void
1704 {
1705  tor_tls_t *tls = conn->tls;
1706  if (!tls)
1707  return;
1708  tor_tls_set_renegotiate_callback(tls, NULL, NULL);
1710 }
1711 
1712 /** Invoked on the server side from inside tor_tls_read() when the server
1713  * gets a successful TLS renegotiation from the client. */
1714 static void
1716 {
1717  or_connection_t *conn = _conn;
1718  (void)tls;
1719 
1720  /* Don't invoke this again. */
1722 
1723  if (connection_tls_finish_handshake(conn) < 0) {
1724  /* XXXX_TLS double-check that it's ok to do this from inside read. */
1725  /* XXXX_TLS double-check that this verifies certificates. */
1727  }
1728 }
1729 
1730 /** Move forward with the tls handshake. If it finishes, hand
1731  * <b>conn</b> to connection_tls_finish_handshake().
1732  *
1733  * Return -1 if <b>conn</b> is broken, else return 0.
1734  */
1735 int
1737 {
1738  int result;
1739  check_no_tls_errors();
1740 
1742  // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
1743  result = tor_tls_handshake(conn->tls);
1744  // log_notice(LD_OR, "Result: %d", result);
1745 
1746  switch (result) {
1748  log_info(LD_OR,"tls error [%s]. breaking connection.",
1749  tor_tls_err_to_string(result));
1750  return -1;
1751  case TOR_TLS_DONE:
1752  if (! tor_tls_used_v1_handshake(conn->tls)) {
1753  if (!tor_tls_is_server(conn->tls)) {
1756  } else {
1757  /* v2/v3 handshake, but we are not a client. */
1758  log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
1759  "Expecting renegotiation or VERSIONS cell");
1762  conn);
1767  return 0;
1768  }
1769  }
1771  return connection_tls_finish_handshake(conn);
1772  case TOR_TLS_WANTWRITE:
1774  log_debug(LD_OR,"wanted write");
1775  return 0;
1776  case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
1777  log_debug(LD_OR,"wanted read");
1778  return 0;
1779  case TOR_TLS_CLOSE:
1780  log_info(LD_OR,"tls closed. breaking connection.");
1781  return -1;
1782  }
1783  return 0;
1784 }
1785 
1786 /** Return 1 if we initiated this connection, or 0 if it started
1787  * out as an incoming connection.
1788  */
1789 int
1791 {
1792  tor_assert(conn->base_.type == CONN_TYPE_OR ||
1793  conn->base_.type == CONN_TYPE_EXT_OR);
1794  if (!conn->tls)
1795  return 1; /* it's still in proxy states or something */
1796  if (conn->handshake_state)
1797  return conn->handshake_state->started_here;
1798  return !tor_tls_is_server(conn->tls);
1799 }
1800 
1801 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
1802  * return -1 if they are lying, broken, or otherwise something is wrong.
1803  *
1804  * If we initiated this connection (<b>started_here</b> is true), make sure
1805  * the other side sent a correctly formed certificate. If I initiated the
1806  * connection, make sure it's the right relay by checking the certificate.
1807  *
1808  * Otherwise (if we _didn't_ initiate this connection), it's okay for
1809  * the certificate to be weird or absent.
1810  *
1811  * If we return 0, and the certificate is as expected, write a hash of the
1812  * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
1813  * space in it.
1814  * If the certificate is invalid or missing on an incoming connection,
1815  * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
1816  * (If we return -1, the contents of this buffer are undefined.)
1817  *
1818  * As side effects,
1819  * 1) Set conn->circ_id_type according to tor-spec.txt.
1820  * 2) If we're an authdirserver and we initiated the connection: drop all
1821  * descriptors that claim to be on that IP/port but that aren't
1822  * this relay; and note that this relay is reachable.
1823  * 3) If this is a bridge and we didn't configure its identity
1824  * fingerprint, remember the keyid we just learned.
1825  */
1826 static int
1828  int started_here,
1829  char *digest_rcvd_out)
1830 {
1831  crypto_pk_t *identity_rcvd=NULL;
1832  const or_options_t *options = get_options();
1833  int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1834  const char *safe_address =
1835  started_here ? conn->base_.address :
1836  safe_str_client(conn->base_.address);
1837  const char *conn_type = started_here ? "outgoing" : "incoming";
1838  int has_cert = 0;
1839 
1840  check_no_tls_errors();
1841  has_cert = tor_tls_peer_has_cert(conn->tls);
1842  if (started_here && !has_cert) {
1843  log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
1844  "send a cert! Closing.",
1845  safe_address, conn->base_.port);
1846  return -1;
1847  } else if (!has_cert) {
1848  log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
1849  "That's ok.");
1850  }
1851  check_no_tls_errors();
1852 
1853  if (has_cert) {
1854  int v = tor_tls_verify(started_here?severity:LOG_INFO,
1855  conn->tls, &identity_rcvd);
1856  if (started_here && v<0) {
1857  log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
1858  " has a cert but it's invalid. Closing.",
1859  safe_address, conn->base_.port);
1860  return -1;
1861  } else if (v<0) {
1862  log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
1863  "chain; ignoring.");
1864  } else {
1865  log_debug(LD_HANDSHAKE,
1866  "The certificate seems to be valid on %s connection "
1867  "with %s:%d", conn_type, safe_address, conn->base_.port);
1868  }
1869  check_no_tls_errors();
1870  }
1871 
1872  if (identity_rcvd) {
1873  if (crypto_pk_get_digest(identity_rcvd, digest_rcvd_out) < 0) {
1874  crypto_pk_free(identity_rcvd);
1875  return -1;
1876  }
1877  } else {
1878  memset(digest_rcvd_out, 0, DIGEST_LEN);
1879  }
1880 
1881  tor_assert(conn->chan);
1882  channel_set_circid_type(TLS_CHAN_TO_BASE(conn->chan), identity_rcvd, 1);
1883 
1884  crypto_pk_free(identity_rcvd);
1885 
1886  if (started_here) {
1887  /* A TLS handshake can't teach us an Ed25519 ID, so we set it to NULL
1888  * here. */
1889  log_debug(LD_HANDSHAKE, "Calling client_learned_peer_id from "
1890  "check_valid_tls_handshake");
1892  (const uint8_t*)digest_rcvd_out,
1893  NULL);
1894  }
1895 
1896  return 0;
1897 }
1898 
1899 /** Called when we (as a connection initiator) have definitively,
1900  * authenticatedly, learned that ID of the Tor instance on the other
1901  * side of <b>conn</b> is <b>rsa_peer_id</b> and optionally <b>ed_peer_id</b>.
1902  * For v1 and v2 handshakes,
1903  * this is right after we get a certificate chain in a TLS handshake
1904  * or renegotiation. For v3+ handshakes, this is right after we get a
1905  * certificate chain in a CERTS cell.
1906  *
1907  * If we did not know the ID before, record the one we got.
1908  *
1909  * If we wanted an ID, but we didn't get the one we expected, log a message
1910  * and return -1.
1911  * On relays:
1912  * - log a protocol warning whenever the fingerprints don't match;
1913  * On clients:
1914  * - if a relay's fingerprint doesn't match, log a warning;
1915  * - if we don't have updated relay fingerprints from a recent consensus, and
1916  * a fallback directory mirror's hard-coded fingerprint has changed, log an
1917  * info explaining that we will try another fallback.
1918  *
1919  * If we're testing reachability, remember what we learned.
1920  *
1921  * Return 0 on success, -1 on failure.
1922  */
1923 int
1925  const uint8_t *rsa_peer_id,
1926  const ed25519_public_key_t *ed_peer_id)
1927 {
1928  const or_options_t *options = get_options();
1929  channel_tls_t *chan_tls = conn->chan;
1930  channel_t *chan = channel_tls_to_base(chan_tls);
1931  int changed_identity = 0;
1932  tor_assert(chan);
1933 
1934  const int expected_rsa_key =
1936  const int expected_ed_key =
1937  ! ed25519_public_key_is_zero(&chan->ed25519_identity);
1938 
1939  log_info(LD_HANDSHAKE, "learned peer id for %p (%s): %s, %s",
1940  conn,
1941  safe_str_client(conn->base_.address),
1942  hex_str((const char*)rsa_peer_id, DIGEST_LEN),
1943  ed25519_fmt(ed_peer_id));
1944 
1945  if (! expected_rsa_key && ! expected_ed_key) {
1946  log_info(LD_HANDSHAKE, "(we had no ID in mind when we made this "
1947  "connection.");
1949  (const char*)rsa_peer_id, ed_peer_id);
1950  tor_free(conn->nickname);
1951  conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1952  conn->nickname[0] = '$';
1954  conn->identity_digest, DIGEST_LEN);
1955  log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
1956  "its key. Hoping for the best.",
1957  conn->nickname, conn->base_.address, conn->base_.port);
1958  /* if it's a bridge and we didn't know its identity fingerprint, now
1959  * we do -- remember it for future attempts. */
1960  learned_router_identity(&conn->base_.addr, conn->base_.port,
1961  (const char*)rsa_peer_id, ed_peer_id);
1962  changed_identity = 1;
1963  }
1964 
1965  const int rsa_mismatch = expected_rsa_key &&
1966  tor_memneq(rsa_peer_id, conn->identity_digest, DIGEST_LEN);
1967  /* It only counts as an ed25519 mismatch if we wanted an ed25519 identity
1968  * and didn't get it. It's okay if we get one that we didn't ask for. */
1969  const int ed25519_mismatch =
1970  expected_ed_key &&
1971  (ed_peer_id == NULL ||
1972  ! ed25519_pubkey_eq(&chan->ed25519_identity, ed_peer_id));
1973 
1974  if (rsa_mismatch || ed25519_mismatch) {
1975  /* I was aiming for a particular digest. I didn't get it! */
1976  char seen_rsa[HEX_DIGEST_LEN+1];
1977  char expected_rsa[HEX_DIGEST_LEN+1];
1978  char seen_ed[ED25519_BASE64_LEN+1];
1979  char expected_ed[ED25519_BASE64_LEN+1];
1980  base16_encode(seen_rsa, sizeof(seen_rsa),
1981  (const char*)rsa_peer_id, DIGEST_LEN);
1982  base16_encode(expected_rsa, sizeof(expected_rsa), conn->identity_digest,
1983  DIGEST_LEN);
1984  if (ed_peer_id) {
1985  ed25519_public_to_base64(seen_ed, ed_peer_id);
1986  } else {
1987  strlcpy(seen_ed, "no ed25519 key", sizeof(seen_ed));
1988  }
1989  if (! ed25519_public_key_is_zero(&chan->ed25519_identity)) {
1990  ed25519_public_to_base64(expected_ed, &chan->ed25519_identity);
1991  } else {
1992  strlcpy(expected_ed, "no ed25519 key", sizeof(expected_ed));
1993  }
1994  const int using_hardcoded_fingerprints =
1997  const int is_fallback_fingerprint = router_digest_is_fallback_dir(
1998  conn->identity_digest);
1999  const int is_authority_fingerprint = router_digest_is_trusted_dir(
2000  conn->identity_digest);
2001  const int non_anonymous_mode = rend_non_anonymous_mode_enabled(options);
2002  int severity;
2003  const char *extra_log = "";
2004 
2005  /* Relays and Single Onion Services make direct connections using
2006  * untrusted authentication keys. */
2007  if (server_mode(options) || non_anonymous_mode) {
2008  severity = LOG_PROTOCOL_WARN;
2009  } else {
2010  if (using_hardcoded_fingerprints) {
2011  /* We need to do the checks in this order, because the list of
2012  * fallbacks includes the list of authorities */
2013  if (is_authority_fingerprint) {
2014  severity = LOG_WARN;
2015  } else if (is_fallback_fingerprint) {
2016  /* we expect a small number of fallbacks to change from their
2017  * hard-coded fingerprints over the life of a release */
2018  severity = LOG_INFO;
2019  extra_log = " Tor will try a different fallback.";
2020  } else {
2021  /* it's a bridge, it's either a misconfiguration, or unexpected */
2022  severity = LOG_WARN;
2023  }
2024  } else {
2025  /* a relay has changed its fingerprint from the one in the consensus */
2026  severity = LOG_WARN;
2027  }
2028  }
2029 
2030  log_fn(severity, LD_HANDSHAKE,
2031  "Tried connecting to router at %s:%d, but RSA + ed25519 identity "
2032  "keys were not as expected: wanted %s + %s but got %s + %s.%s",
2033  conn->base_.address, conn->base_.port,
2034  expected_rsa, expected_ed, seen_rsa, seen_ed, extra_log);
2035 
2036  /* Tell the new guard API about the channel failure */
2037  entry_guard_chan_failed(TLS_CHAN_TO_BASE(conn->chan));
2038  connection_or_event_status(conn, OR_CONN_EVENT_FAILED,
2039  END_OR_CONN_REASON_OR_IDENTITY);
2040  if (!authdir_mode_tests_reachability(options))
2042  "Unexpected identity in router certificate",
2043  END_OR_CONN_REASON_OR_IDENTITY,
2044  conn);
2045  return -1;
2046  }
2047 
2048  if (!expected_ed_key && ed_peer_id) {
2049  log_info(LD_HANDSHAKE, "(We had no Ed25519 ID in mind when we made this "
2050  "connection.)");
2052  (const char*)rsa_peer_id, ed_peer_id);
2053  changed_identity = 1;
2054  }
2055 
2056  if (changed_identity) {
2057  /* If we learned an identity for this connection, then we might have
2058  * just discovered it to be canonical. */
2060  }
2061 
2062  if (authdir_mode_tests_reachability(options)) {
2063  dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
2064  (const char*)rsa_peer_id, ed_peer_id);
2065  }
2066 
2067  return 0;
2068 }
2069 
2070 /** Return when we last used this channel for client activity (origin
2071  * circuits). This is called from connection.c, since client_used is now one
2072  * of the timestamps in channel_t */
2073 
2074 time_t
2076 {
2077  tor_assert(conn);
2078 
2079  if (conn->chan) {
2080  return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
2081  } else return 0;
2082 }
2083 
2084 /** The v1/v2 TLS handshake is finished.
2085  *
2086  * Make sure we are happy with the peer we just handshaked with.
2087  *
2088  * If they initiated the connection, make sure they're not already connected,
2089  * then initialize conn from the information in router.
2090  *
2091  * If all is successful, call circuit_n_conn_done() to handle events
2092  * that have been pending on the <tls handshake completion. Also set the
2093  * directory to be dirty (only matters if I'm an authdirserver).
2094  *
2095  * If this is a v2 TLS handshake, send a versions cell.
2096  */
2097 static int
2099 {
2100  char digest_rcvd[DIGEST_LEN];
2101  int started_here = connection_or_nonopen_was_started_here(conn);
2102 
2103  tor_assert(!started_here);
2104 
2105  log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done, using "
2106  "ciphersuite %s. verifying.",
2107  started_here?"outgoing":"incoming",
2108  conn,
2109  safe_str_client(conn->base_.address),
2110  tor_tls_get_ciphersuite_name(conn->tls));
2111 
2112  if (connection_or_check_valid_tls_handshake(conn, started_here,
2113  digest_rcvd) < 0)
2114  return -1;
2115 
2117 
2118  if (tor_tls_used_v1_handshake(conn->tls)) {
2119  conn->link_proto = 1;
2120  connection_or_init_conn_from_address(conn, &conn->base_.addr,
2121  conn->base_.port, digest_rcvd,
2122  NULL, 0);
2124  rep_hist_note_negotiated_link_proto(1, started_here);
2125  return connection_or_set_state_open(conn);
2126  } else {
2128  if (connection_init_or_handshake_state(conn, started_here) < 0)
2129  return -1;
2130  connection_or_init_conn_from_address(conn, &conn->base_.addr,
2131  conn->base_.port, digest_rcvd,
2132  NULL, 0);
2133  return connection_or_send_versions(conn, 0);
2134  }
2135 }
2136 
2137 /**
2138  * Called as client when initial TLS handshake is done, and we notice
2139  * that we got a v3-handshake signalling certificate from the server.
2140  * Set up structures, do bookkeeping, and send the versions cell.
2141  * Return 0 on success and -1 on failure.
2142  */
2143 static int
2145 {
2147 
2149 
2151  if (connection_init_or_handshake_state(conn, 1) < 0)
2152  return -1;
2153 
2154  return connection_or_send_versions(conn, 1);
2155 }
2156 
2157 /** Allocate a new connection handshake state for the connection
2158  * <b>conn</b>. Return 0 on success, -1 on failure. */
2159 int
2161 {
2163  if (conn->handshake_state) {
2164  log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
2165  return 0;
2166  }
2167  s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
2168  s->started_here = started_here ? 1 : 0;
2169  s->digest_sent_data = 1;
2170  s->digest_received_data = 1;
2171  if (! started_here && get_current_link_cert_cert()) {
2172  s->own_link_cert = tor_cert_dup(get_current_link_cert_cert());
2173  }
2175  s->certs->started_here = s->started_here;
2176  return 0;
2177 }
2178 
2179 /** Free all storage held by <b>state</b>. */
2180 void
2182 {
2183  if (!state)
2184  return;
2186  crypto_digest_free(state->digest_received);
2187  or_handshake_certs_free(state->certs);
2188  tor_cert_free(state->own_link_cert);
2189  memwipe(state, 0xBE, sizeof(or_handshake_state_t));
2190  tor_free(state);
2191 }
2192 
2193 /**
2194  * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
2195  * false) or received (if <b>incoming</b> is true) during a V3 handshake using
2196  * <b>state</b>.
2197  *
2198  * (We don't record the cell, but we keep a digest of everything sent or
2199  * received during the v3 handshake, and the client signs it in an
2200  * authenticate cell.)
2201  */
2202 void
2204  or_handshake_state_t *state,
2205  const cell_t *cell,
2206  int incoming)
2207 {
2208  size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2209  crypto_digest_t *d, **dptr;
2210  packed_cell_t packed;
2211  if (incoming) {
2212  if (!state->digest_received_data)
2213  return;
2214  } else {
2215  if (!state->digest_sent_data)
2216  return;
2217  }
2218  if (!incoming) {
2219  log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
2220  "while making a handshake digest. But we think we are sending "
2221  "one with type %d.", (int)cell->command);
2222  }
2223  dptr = incoming ? &state->digest_received : &state->digest_sent;
2224  if (! *dptr)
2225  *dptr = crypto_digest256_new(DIGEST_SHA256);
2226 
2227  d = *dptr;
2228  /* Re-packing like this is a little inefficient, but we don't have to do
2229  this very often at all. */
2230  cell_pack(&packed, cell, conn->wide_circ_ids);
2231  crypto_digest_add_bytes(d, packed.body, cell_network_size);
2232  memwipe(&packed, 0, sizeof(packed));
2233 }
2234 
2235 /** Remember that a variable-length <b>cell</b> has been transmitted (if
2236  * <b>incoming</b> is false) or received (if <b>incoming</b> is true) during a
2237  * V3 handshake using <b>state</b>.
2238  *
2239  * (We don't record the cell, but we keep a digest of everything sent or
2240  * received during the v3 handshake, and the client signs it in an
2241  * authenticate cell.)
2242  */
2243 void
2245  or_handshake_state_t *state,
2246  const var_cell_t *cell,
2247  int incoming)
2248 {
2249  crypto_digest_t *d, **dptr;
2250  int n;
2251  char buf[VAR_CELL_MAX_HEADER_SIZE];
2252  if (incoming) {
2253  if (!state->digest_received_data)
2254  return;
2255  } else {
2256  if (!state->digest_sent_data)
2257  return;
2258  }
2259  dptr = incoming ? &state->digest_received : &state->digest_sent;
2260  if (! *dptr)
2261  *dptr = crypto_digest256_new(DIGEST_SHA256);
2262 
2263  d = *dptr;
2264 
2265  n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
2266  crypto_digest_add_bytes(d, buf, n);
2267  crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
2268 
2269  memwipe(buf, 0, sizeof(buf));
2270 }
2271 
2272 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
2273  * as appropriate. Called when we are done with all TLS and OR handshaking.
2274  */
2275 int
2277 {
2279  connection_or_event_status(conn, OR_CONN_EVENT_CONNECTED, 0);
2280 
2281  /* Link protocol 3 appeared in Tor 0.2.3.6-alpha, so any connection
2282  * that uses an earlier link protocol should not be treated as a relay. */
2283  if (conn->link_proto < 3) {
2284  channel_mark_client(TLS_CHAN_TO_BASE(conn->chan));
2285  }
2286 
2287  or_handshake_state_free(conn->handshake_state);
2288  conn->handshake_state = NULL;
2290 
2291  return 0;
2292 }
2293 
2294 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
2295  * For cells that use or affect a circuit, this should only be called by
2296  * connection_or_flush_from_first_active_circuit().
2297  */
2298 void
2300 {
2301  packed_cell_t networkcell;
2302  size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2303 
2304  tor_assert(cell);
2305  tor_assert(conn);
2306 
2307  cell_pack(&networkcell, cell, conn->wide_circ_ids);
2308 
2309  /* We need to count padding cells from this non-packed code path
2310  * since they are sent via chan->write_cell() (which is not packed) */
2312  if (cell->command == CELL_PADDING)
2314 
2315  connection_buf_add(networkcell.body, cell_network_size, TO_CONN(conn));
2316 
2317  /* Touch the channel's active timestamp if there is one */
2318  if (conn->chan) {
2319  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2320 
2321  if (TLS_CHAN_TO_BASE(conn->chan)->padding_enabled) {
2323  if (cell->command == CELL_PADDING)
2325  }
2326  }
2327 
2328  if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2329  or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
2330 }
2331 
2332 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
2333  * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
2334  * affect a circuit.
2335  */
2336 MOCK_IMPL(void,
2339 {
2340  int n;
2341  char hdr[VAR_CELL_MAX_HEADER_SIZE];
2342  tor_assert(cell);
2343  tor_assert(conn);
2344  n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
2345  connection_buf_add(hdr, n, TO_CONN(conn));
2346  connection_buf_add((char*)cell->payload,
2347  cell->payload_len, TO_CONN(conn));
2348  if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2350 
2352  /* Touch the channel's active timestamp if there is one */
2353  if (conn->chan)
2354  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2355 }
2356 
2357 /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
2358  * inbuf. Return values as for fetch_var_cell_from_buf(). */
2359 static int
2361 {
2362  connection_t *conn = TO_CONN(or_conn);
2363  return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
2364 }
2365 
2366 /** Process cells from <b>conn</b>'s inbuf.
2367  *
2368  * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
2369  * and hand it to command_process_cell().
2370  *
2371  * Always return 0.
2372  */
2373 static int
2375 {
2376  var_cell_t *var_cell;
2377 
2378  /*
2379  * Note on memory management for incoming cells: below the channel layer,
2380  * we shouldn't need to consider its internal queueing/copying logic. It
2381  * is safe to pass cells to it on the stack or on the heap, but in the
2382  * latter case we must be sure we free them later.
2383  *
2384  * The incoming cell queue code in channel.c will (in the common case)
2385  * decide it can pass them to the upper layer immediately, in which case
2386  * those functions may run directly on the cell pointers we pass here, or
2387  * it may decide to queue them, in which case it will allocate its own
2388  * buffer and copy the cell.
2389  */
2390 
2391  while (1) {
2392  log_debug(LD_OR,
2393  TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
2394  "(%d pending in tls object).",
2395  conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
2397  if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
2398  if (!var_cell)
2399  return 0; /* not yet. */
2400 
2401  /* Touch the channel's active timestamp if there is one */
2402  if (conn->chan)
2403  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2404 
2406  channel_tls_handle_var_cell(var_cell, conn);
2407  var_cell_free(var_cell);
2408  } else {
2409  const int wide_circ_ids = conn->wide_circ_ids;
2410  size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2411  char buf[CELL_MAX_NETWORK_SIZE];
2412  cell_t cell;
2413  if (connection_get_inbuf_len(TO_CONN(conn))
2414  < cell_network_size) /* whole response available? */
2415  return 0; /* not yet */
2416 
2417  /* Touch the channel's active timestamp if there is one */
2418  if (conn->chan)
2419  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2420 
2422  connection_buf_get_bytes(buf, cell_network_size, TO_CONN(conn));
2423 
2424  /* retrieve cell info from buf (create the host-order struct from the
2425  * network-order string) */
2426  cell_unpack(&cell, buf, wide_circ_ids);
2427 
2428  channel_tls_handle_cell(&cell, conn);
2429  }
2430  }
2431 }
2432 
2433 /** Array of recognized link protocol versions. */
2434 static const uint16_t or_protocol_versions[] = { 1, 2, 3, 4, 5 };
2435 /** Number of versions in <b>or_protocol_versions</b>. */
2436 static const int n_or_protocol_versions =
2437  (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
2438 
2439 /** Return true iff <b>v</b> is a link protocol version that this Tor
2440  * implementation believes it can support. */
2441 int
2443 {
2444  int i;
2445  for (i = 0; i < n_or_protocol_versions; ++i) {
2446  if (or_protocol_versions[i] == v)
2447  return 1;
2448  }
2449  return 0;
2450 }
2451 
2452 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
2453  * link protocol versions that this Tor can support.
2454  *
2455  * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
2456  * allow protocol version v3 or later. If not <b>v3_plus</b>, this is
2457  * not part of a v3 protocol handshake, so don't allow protocol v3 or
2458  * later.
2459  **/
2460 int
2462 {
2463  var_cell_t *cell;
2464  int i;
2465  int n_versions = 0;
2466  const int min_version = v3_plus ? 3 : 0;
2467  const int max_version = v3_plus ? UINT16_MAX : 2;
2468  tor_assert(conn->handshake_state &&
2471  cell->command = CELL_VERSIONS;
2472  for (i = 0; i < n_or_protocol_versions; ++i) {
2473  uint16_t v = or_protocol_versions[i];
2474  if (v < min_version || v > max_version)
2475  continue;
2476  set_uint16(cell->payload+(2*n_versions), htons(v));
2477  ++n_versions;
2478  }
2479  cell->payload_len = n_versions * 2;
2480 
2482  conn->handshake_state->sent_versions_at = time(NULL);
2483 
2484  var_cell_free(cell);
2485  return 0;
2486 }
2487 
2488 static netinfo_addr_t *
2489 netinfo_addr_from_tor_addr(const tor_addr_t *tor_addr)
2490 {
2491  sa_family_t addr_family = tor_addr_family(tor_addr);
2492 
2493  if (BUG(addr_family != AF_INET && addr_family != AF_INET6))
2494  return NULL;
2495 
2496  netinfo_addr_t *netinfo_addr = netinfo_addr_new();
2497 
2498  if (addr_family == AF_INET) {
2499  netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV4);
2500  netinfo_addr_set_len(netinfo_addr, 4);
2501  netinfo_addr_set_addr_ipv4(netinfo_addr, tor_addr_to_ipv4h(tor_addr));
2502  } else if (addr_family == AF_INET6) {
2503  netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV6);
2504  netinfo_addr_set_len(netinfo_addr, 16);
2505  uint8_t *ipv6_buf = netinfo_addr_getarray_addr_ipv6(netinfo_addr);
2506  const uint8_t *in6_addr = tor_addr_to_in6_addr8(tor_addr);
2507  memcpy(ipv6_buf, in6_addr, 16);
2508  }
2509 
2510  return netinfo_addr;
2511 }
2512 
2513 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
2514  * about their address, our address, and the current time. */
2515 MOCK_IMPL(int,
2517 {
2518  cell_t cell;
2519  time_t now = time(NULL);
2520  const routerinfo_t *me;
2521  int r = -1;
2522 
2523  tor_assert(conn->handshake_state);
2524 
2525  if (conn->handshake_state->sent_netinfo) {
2526  log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
2527  "where we already sent one.");
2528  return 0;
2529  }
2530 
2531  memset(&cell, 0, sizeof(cell_t));
2532  cell.command = CELL_NETINFO;
2533 
2534  netinfo_cell_t *netinfo_cell = netinfo_cell_new();
2535 
2536  /* Timestamp, if we're a relay. */
2537  if (public_server_mode(get_options()) || ! conn->is_outgoing)
2538  netinfo_cell_set_timestamp(netinfo_cell, (uint32_t)now);
2539 
2540  /* Their address. */
2541  const tor_addr_t *remote_tor_addr =
2542  !tor_addr_is_null(&conn->real_addr) ? &conn->real_addr : &conn->base_.addr;
2543  /* We use &conn->real_addr below, unless it hasn't yet been set. If it
2544  * hasn't yet been set, we know that base_.addr hasn't been tampered with
2545  * yet either. */
2546  netinfo_addr_t *their_addr = netinfo_addr_from_tor_addr(remote_tor_addr);
2547 
2548  netinfo_cell_set_other_addr(netinfo_cell, their_addr);
2549 
2550  /* My address -- only include it if I'm a public relay, or if I'm a
2551  * bridge and this is an incoming connection. If I'm a bridge and this
2552  * is an outgoing connection, act like a normal client and omit it. */
2553  if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
2554  (me = router_get_my_routerinfo())) {
2555  tor_addr_t my_addr;
2556  tor_addr_from_ipv4h(&my_addr, me->addr);
2557 
2558  uint8_t n_my_addrs = 1 + !tor_addr_is_null(&me->ipv6_addr);
2559  netinfo_cell_set_n_my_addrs(netinfo_cell, n_my_addrs);
2560 
2561  netinfo_cell_add_my_addrs(netinfo_cell,
2562  netinfo_addr_from_tor_addr(&my_addr));
2563 
2564  if (!tor_addr_is_null(&me->ipv6_addr)) {
2565  netinfo_cell_add_my_addrs(netinfo_cell,
2566  netinfo_addr_from_tor_addr(&me->ipv6_addr));
2567  }
2568  }
2569 
2570  const char *errmsg = NULL;
2571  if ((errmsg = netinfo_cell_check(netinfo_cell))) {
2572  log_warn(LD_OR, "Failed to validate NETINFO cell with error: %s",
2573  errmsg);
2574  goto cleanup;
2575  }
2576 
2577  if (netinfo_cell_encode(cell.payload, CELL_PAYLOAD_SIZE,
2578  netinfo_cell) < 0) {
2579  log_warn(LD_OR, "Failed generating NETINFO cell");
2580  goto cleanup;
2581  }
2582 
2583  conn->handshake_state->digest_sent_data = 0;
2584  conn->handshake_state->sent_netinfo = 1;
2585  connection_or_write_cell_to_buf(&cell, conn);
2586 
2587  r = 0;
2588  cleanup:
2589  netinfo_cell_free(netinfo_cell);
2590 
2591  return r;
2592 }
2593 
2594 /** Helper used to add an encoded certs to a cert cell */
2595 static void
2596 add_certs_cell_cert_helper(certs_cell_t *certs_cell,
2597  uint8_t cert_type,
2598  const uint8_t *cert_encoded,
2599  size_t cert_len)
2600 {
2601  tor_assert(cert_len <= UINT16_MAX);
2602  certs_cell_cert_t *ccc = certs_cell_cert_new();
2603  ccc->cert_type = cert_type;
2604  ccc->cert_len = cert_len;
2605  certs_cell_cert_setlen_body(ccc, cert_len);
2606  memcpy(certs_cell_cert_getarray_body(ccc), cert_encoded, cert_len);
2607 
2608  certs_cell_add_certs(certs_cell, ccc);
2609 }
2610 
2611 /** Add an encoded X509 cert (stored as <b>cert_len</b> bytes at
2612  * <b>cert_encoded</b>) to the trunnel certs_cell_t object that we are
2613  * building in <b>certs_cell</b>. Set its type field to <b>cert_type</b>.
2614  * (If <b>cert</b> is NULL, take no action.) */
2615 static void
2616 add_x509_cert(certs_cell_t *certs_cell,
2617  uint8_t cert_type,
2618  const tor_x509_cert_t *cert)
2619 {
2620  if (NULL == cert)
2621  return;
2622 
2623  const uint8_t *cert_encoded = NULL;
2624  size_t cert_len;
2625  tor_x509_cert_get_der(cert, &cert_encoded, &cert_len);
2626 
2627  add_certs_cell_cert_helper(certs_cell, cert_type, cert_encoded, cert_len);
2628 }
2629 
2630 /** Add an Ed25519 cert from <b>cert</b> to the trunnel certs_cell_t object
2631  * that we are building in <b>certs_cell</b>. Set its type field to
2632  * <b>cert_type</b>. (If <b>cert</b> is NULL, take no action.) */
2633 static void
2634 add_ed25519_cert(certs_cell_t *certs_cell,
2635  uint8_t cert_type,
2636  const tor_cert_t *cert)
2637 {
2638  if (NULL == cert)
2639  return;
2640 
2641  add_certs_cell_cert_helper(certs_cell, cert_type,
2642  cert->encoded, cert->encoded_len);
2643 }
2644 
2645 #ifdef TOR_UNIT_TESTS
2646 int certs_cell_ed25519_disabled_for_testing = 0;
2647 #else
2648 #define certs_cell_ed25519_disabled_for_testing 0
2649 #endif
2650 
2651 /** Send a CERTS cell on the connection <b>conn</b>. Return 0 on success, -1
2652  * on failure. */
2653 int
2655 {
2656  const tor_x509_cert_t *global_link_cert = NULL, *id_cert = NULL;
2657  tor_x509_cert_t *own_link_cert = NULL;
2658  var_cell_t *cell;
2659 
2660  certs_cell_t *certs_cell = NULL;
2661 
2663 
2664  if (! conn->handshake_state)
2665  return -1;
2666 
2667  const int conn_in_server_mode = ! conn->handshake_state->started_here;
2668 
2669  /* Get the encoded values of the X509 certificates */
2670  if (tor_tls_get_my_certs(conn_in_server_mode,
2671  &global_link_cert, &id_cert) < 0)
2672  return -1;
2673 
2674  if (conn_in_server_mode) {
2675  own_link_cert = tor_tls_get_own_cert(conn->tls);
2676  }
2677  tor_assert(id_cert);
2678 
2679  certs_cell = certs_cell_new();
2680 
2681  /* Start adding certs. First the link cert or auth1024 cert. */
2682  if (conn_in_server_mode) {
2683  tor_assert_nonfatal(own_link_cert);
2684  add_x509_cert(certs_cell,
2685  OR_CERT_TYPE_TLS_LINK, own_link_cert);
2686  } else {
2687  tor_assert(global_link_cert);
2688  add_x509_cert(certs_cell,
2689  OR_CERT_TYPE_AUTH_1024, global_link_cert);
2690  }
2691 
2692  /* Next the RSA->RSA ID cert */
2693  add_x509_cert(certs_cell,
2694  OR_CERT_TYPE_ID_1024, id_cert);
2695 
2696  /* Next the Ed25519 certs */
2697  add_ed25519_cert(certs_cell,
2698  CERTTYPE_ED_ID_SIGN,
2699  get_master_signing_key_cert());
2700  if (conn_in_server_mode) {
2701  tor_assert_nonfatal(conn->handshake_state->own_link_cert ||
2702  certs_cell_ed25519_disabled_for_testing);
2703  add_ed25519_cert(certs_cell,
2704  CERTTYPE_ED_SIGN_LINK,
2706  } else {
2707  add_ed25519_cert(certs_cell,
2708  CERTTYPE_ED_SIGN_AUTH,
2709  get_current_auth_key_cert());
2710  }
2711 
2712  /* And finally the crosscert. */
2713  {
2714  const uint8_t *crosscert=NULL;
2715  size_t crosscert_len;
2716  get_master_rsa_crosscert(&crosscert, &crosscert_len);
2717  if (crosscert) {
2718  add_certs_cell_cert_helper(certs_cell,
2719  CERTTYPE_RSA1024_ID_EDID,
2720  crosscert, crosscert_len);
2721  }
2722  }
2723 
2724  /* We've added all the certs; make the cell. */
2725  certs_cell->n_certs = certs_cell_getlen_certs(certs_cell);
2726 
2727  ssize_t alloc_len = certs_cell_encoded_len(certs_cell);
2728  tor_assert(alloc_len >= 0 && alloc_len <= UINT16_MAX);
2729  cell = var_cell_new(alloc_len);
2730  cell->command = CELL_CERTS;
2731  ssize_t enc_len = certs_cell_encode(cell->payload, alloc_len, certs_cell);
2732  tor_assert(enc_len > 0 && enc_len <= alloc_len);
2733  cell->payload_len = enc_len;
2734 
2736  var_cell_free(cell);
2737  certs_cell_free(certs_cell);
2738  tor_x509_cert_free(own_link_cert);
2739 
2740  return 0;
2741 }
2742 
2743 #ifdef TOR_UNIT_TESTS
2744 int testing__connection_or_pretend_TLSSECRET_is_supported = 0;
2745 #else
2746 #define testing__connection_or_pretend_TLSSECRET_is_supported 0
2747 #endif
2748 
2749 /** Return true iff <b>challenge_type</b> is an AUTHCHALLENGE type that
2750  * we can send and receive. */
2751 int
2752 authchallenge_type_is_supported(uint16_t challenge_type)
2753 {
2754  switch (challenge_type) {
2756 #ifdef HAVE_WORKING_TOR_TLS_GET_TLSSECRETS
2757  return 1;
2758 #else
2759  return testing__connection_or_pretend_TLSSECRET_is_supported;
2760 #endif
2762  return 1;
2764  default:
2765  return 0;
2766  }
2767 }
2768 
2769 /** Return true iff <b>challenge_type_a</b> is one that we would rather
2770  * use than <b>challenge_type_b</b>. */
2771 int
2772 authchallenge_type_is_better(uint16_t challenge_type_a,
2773  uint16_t challenge_type_b)
2774 {
2775  /* Any supported type is better than an unsupported one;
2776  * all unsupported types are equally bad. */
2777  if (!authchallenge_type_is_supported(challenge_type_a))
2778  return 0;
2779  if (!authchallenge_type_is_supported(challenge_type_b))
2780  return 1;
2781  /* It happens that types are superior in numerically ascending order.
2782  * If that ever changes, this must change too. */
2783  return (challenge_type_a > challenge_type_b);
2784 }
2785 
2786 /** Send an AUTH_CHALLENGE cell on the connection <b>conn</b>. Return 0
2787  * on success, -1 on failure. */
2788 int
2790 {
2791  var_cell_t *cell = NULL;
2792  int r = -1;
2794 
2795  if (! conn->handshake_state)
2796  return -1;
2797 
2798  auth_challenge_cell_t *ac = auth_challenge_cell_new();
2799 
2800  tor_assert(sizeof(ac->challenge) == 32);
2801  crypto_rand((char*)ac->challenge, sizeof(ac->challenge));
2802 
2804  auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_TLSSECRET);
2805  /* Disabled, because everything that supports this method also supports
2806  * the much-superior ED25519_SHA256_RFC5705 */
2807  /* auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_RFC5705); */
2809  auth_challenge_cell_add_methods(ac, AUTHTYPE_ED25519_SHA256_RFC5705);
2810  auth_challenge_cell_set_n_methods(ac,
2811  auth_challenge_cell_getlen_methods(ac));
2812 
2813  cell = var_cell_new(auth_challenge_cell_encoded_len(ac));
2814  ssize_t len = auth_challenge_cell_encode(cell->payload, cell->payload_len,
2815  ac);
2816  if (len != cell->payload_len) {
2817  /* LCOV_EXCL_START */
2818  log_warn(LD_BUG, "Encoded auth challenge cell length not as expected");
2819  goto done;
2820  /* LCOV_EXCL_STOP */
2821  }
2822  cell->command = CELL_AUTH_CHALLENGE;
2823 
2825  r = 0;
2826 
2827  done:
2828  var_cell_free(cell);
2829  auth_challenge_cell_free(ac);
2830 
2831  return r;
2832 }
2833 
2834 /** Compute the main body of an AUTHENTICATE cell that a client can use
2835  * to authenticate itself on a v3 handshake for <b>conn</b>. Return it
2836  * in a var_cell_t.
2837  *
2838  * If <b>server</b> is true, only calculate the first
2839  * V3_AUTH_FIXED_PART_LEN bytes -- the part of the authenticator that's
2840  * determined by the rest of the handshake, and which match the provided value
2841  * exactly.
2842  *
2843  * If <b>server</b> is false and <b>signing_key</b> is NULL, calculate the
2844  * first V3_AUTH_BODY_LEN bytes of the authenticator (that is, everything
2845  * that should be signed), but don't actually sign it.
2846  *
2847  * If <b>server</b> is false and <b>signing_key</b> is provided, calculate the
2848  * entire authenticator, signed with <b>signing_key</b>.
2849  *
2850  * Return the length of the cell body on success, and -1 on failure.
2851  */
2852 var_cell_t *
2854  const int authtype,
2855  crypto_pk_t *signing_key,
2856  const ed25519_keypair_t *ed_signing_key,
2857  int server)
2858 {
2859  auth1_t *auth = NULL;
2860  auth_ctx_t *ctx = auth_ctx_new();
2861  var_cell_t *result = NULL;
2862  int old_tlssecrets_algorithm = 0;
2863  const char *authtype_str = NULL;
2864 
2865  int is_ed = 0;
2866 
2867  /* assert state is reasonable XXXX */
2868  switch (authtype) {
2870  authtype_str = "AUTH0001";
2871  old_tlssecrets_algorithm = 1;
2872  break;
2874  authtype_str = "AUTH0002";
2875  break;
2877  authtype_str = "AUTH0003";
2878  is_ed = 1;
2879  break;
2880  default:
2881  tor_assert(0);
2882  break;
2883  }
2884 
2885  auth = auth1_new();
2886  ctx->is_ed = is_ed;
2887 
2888  /* Type: 8 bytes. */
2889  memcpy(auth1_getarray_type(auth), authtype_str, 8);
2890 
2891  {
2892  const tor_x509_cert_t *id_cert=NULL;
2893  const common_digests_t *my_digests, *their_digests;
2894  const uint8_t *my_id, *their_id, *client_id, *server_id;
2895  if (tor_tls_get_my_certs(server, NULL, &id_cert))
2896  goto err;
2897  my_digests = tor_x509_cert_get_id_digests(id_cert);
2898  their_digests =
2900  tor_assert(my_digests);
2901  tor_assert(their_digests);
2902  my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
2903  their_id = (uint8_t*)their_digests->d[DIGEST_SHA256];
2904 
2905  client_id = server ? their_id : my_id;
2906  server_id = server ? my_id : their_id;
2907 
2908  /* Client ID digest: 32 octets. */
2909  memcpy(auth->cid, client_id, 32);
2910 
2911  /* Server ID digest: 32 octets. */
2912  memcpy(auth->sid, server_id, 32);
2913  }
2914 
2915  if (is_ed) {
2916  const ed25519_public_key_t *my_ed_id, *their_ed_id;
2917  if (!conn->handshake_state->certs->ed_id_sign) {
2918  log_warn(LD_OR, "Ed authenticate without Ed ID cert from peer.");
2919  goto err;
2920  }
2921  my_ed_id = get_master_identity_key();
2922  their_ed_id = &conn->handshake_state->certs->ed_id_sign->signing_key;
2923 
2924  const uint8_t *cid_ed = (server ? their_ed_id : my_ed_id)->pubkey;
2925  const uint8_t *sid_ed = (server ? my_ed_id : their_ed_id)->pubkey;
2926 
2927  memcpy(auth->u1_cid_ed, cid_ed, ED25519_PUBKEY_LEN);
2928  memcpy(auth->u1_sid_ed, sid_ed, ED25519_PUBKEY_LEN);
2929  }
2930 
2931  {
2932  crypto_digest_t *server_d, *client_d;
2933  if (server) {
2934  server_d = conn->handshake_state->digest_sent;
2935  client_d = conn->handshake_state->digest_received;
2936  } else {
2937  client_d = conn->handshake_state->digest_sent;
2938  server_d = conn->handshake_state->digest_received;
2939  }
2940 
2941  /* Server log digest : 32 octets */
2942  crypto_digest_get_digest(server_d, (char*)auth->slog, 32);
2943 
2944  /* Client log digest : 32 octets */
2945  crypto_digest_get_digest(client_d, (char*)auth->clog, 32);
2946  }
2947 
2948  {
2949  /* Digest of cert used on TLS link : 32 octets. */
2950  tor_x509_cert_t *cert = NULL;
2951  if (server) {
2952  cert = tor_tls_get_own_cert(conn->tls);
2953  } else {
2954  cert = tor_tls_get_peer_cert(conn->tls);
2955  }
2956  if (!cert) {
2957  log_warn(LD_OR, "Unable to find cert when making %s data.",
2958  authtype_str);
2959  goto err;
2960  }
2961 
2962  memcpy(auth->scert,
2963  tor_x509_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
2964 
2965  tor_x509_cert_free(cert);
2966  }
2967 
2968  /* HMAC of clientrandom and serverrandom using master key : 32 octets */
2969  if (old_tlssecrets_algorithm) {
2970  if (tor_tls_get_tlssecrets(conn->tls, auth->tlssecrets) < 0) {
2971  log_fn(LOG_PROTOCOL_WARN, LD_OR, "Somebody asked us for an older TLS "
2972  "authentication method (AUTHTYPE_RSA_SHA256_TLSSECRET) "
2973  "which we don't support.");
2974  }
2975  } else {
2976  char label[128];
2977  tor_snprintf(label, sizeof(label),
2978  "EXPORTER FOR TOR TLS CLIENT BINDING %s", authtype_str);
2979  int r = tor_tls_export_key_material(conn->tls, auth->tlssecrets,
2980  auth->cid, sizeof(auth->cid),
2981  label);
2982  if (r < 0) {
2983  if (r != -2)
2984  log_warn(LD_BUG, "TLS key export failed for unknown reason.");
2985  // If r == -2, this was openssl bug 7712.
2986  goto err;
2987  }
2988  }
2989 
2990  /* 8 octets were reserved for the current time, but we're trying to get out
2991  * of the habit of sending time around willynilly. Fortunately, nothing
2992  * checks it. That's followed by 16 bytes of nonce. */
2993  crypto_rand((char*)auth->rand, 24);
2994 
2995  ssize_t maxlen = auth1_encoded_len(auth, ctx);
2996  if (ed_signing_key && is_ed) {
2997  maxlen += ED25519_SIG_LEN;
2998  } else if (signing_key && !is_ed) {
2999  maxlen += crypto_pk_keysize(signing_key);
3000  }
3001 
3002  const int AUTH_CELL_HEADER_LEN = 4; /* 2 bytes of type, 2 bytes of length */
3003  result = var_cell_new(AUTH_CELL_HEADER_LEN + maxlen);
3004  uint8_t *const out = result->payload + AUTH_CELL_HEADER_LEN;
3005  const size_t outlen = maxlen;
3006  ssize_t len;
3007 
3008  result->command = CELL_AUTHENTICATE;
3009  set_uint16(result->payload, htons(authtype));
3010 
3011  if ((len = auth1_encode(out, outlen, auth, ctx)) < 0) {
3012  /* LCOV_EXCL_START */
3013  log_warn(LD_BUG, "Unable to encode signed part of AUTH1 data.");
3014  goto err;
3015  /* LCOV_EXCL_STOP */
3016  }
3017 
3018  if (server) {
3019  auth1_t *tmp = NULL;
3020  ssize_t len2 = auth1_parse(&tmp, out, len, ctx);
3021  if (!tmp) {
3022  /* LCOV_EXCL_START */
3023  log_warn(LD_BUG, "Unable to parse signed part of AUTH1 data that "
3024  "we just encoded");
3025  goto err;
3026  /* LCOV_EXCL_STOP */
3027  }
3028  result->payload_len = (tmp->end_of_signed - result->payload);
3029 
3030  auth1_free(tmp);
3031  if (len2 != len) {
3032  /* LCOV_EXCL_START */
3033  log_warn(LD_BUG, "Mismatched length when re-parsing AUTH1 data.");
3034  goto err;
3035  /* LCOV_EXCL_STOP */
3036  }
3037  goto done;
3038  }
3039 
3040  if (ed_signing_key && is_ed) {
3041  ed25519_signature_t sig;
3042  if (ed25519_sign(&sig, out, len, ed_signing_key) < 0) {
3043  /* LCOV_EXCL_START */
3044  log_warn(LD_BUG, "Unable to sign ed25519 authentication data");
3045  goto err;
3046  /* LCOV_EXCL_STOP */
3047  }
3048  auth1_setlen_sig(auth, ED25519_SIG_LEN);
3049  memcpy(auth1_getarray_sig(auth), sig.sig, ED25519_SIG_LEN);
3050 
3051  } else if (signing_key && !is_ed) {
3052  auth1_setlen_sig(auth, crypto_pk_keysize(signing_key));
3053 
3054  char d[32];
3055  crypto_digest256(d, (char*)out, len, DIGEST_SHA256);
3056  int siglen = crypto_pk_private_sign(signing_key,
3057  (char*)auth1_getarray_sig(auth),
3058  auth1_getlen_sig(auth),
3059  d, 32);
3060  if (siglen < 0) {
3061  log_warn(LD_OR, "Unable to sign AUTH1 data.");
3062  goto err;
3063  }
3064 
3065  auth1_setlen_sig(auth, siglen);
3066  }
3067 
3068  len = auth1_encode(out, outlen, auth, ctx);
3069  if (len < 0) {
3070  /* LCOV_EXCL_START */
3071  log_warn(LD_BUG, "Unable to encode signed AUTH1 data.");
3072  goto err;
3073  /* LCOV_EXCL_STOP */
3074  }
3075  tor_assert(len + AUTH_CELL_HEADER_LEN <= result->payload_len);
3076  result->payload_len = len + AUTH_CELL_HEADER_LEN;
3077  set_uint16(result->payload+2, htons(len));
3078 
3079  goto done;
3080 
3081  err:
3082  var_cell_free(result);
3083  result = NULL;
3084  done:
3085  auth1_free(auth);
3086  auth_ctx_free(ctx);
3087  return result;
3088 }
3089 
3090 /** Send an AUTHENTICATE cell on the connection <b>conn</b>. Return 0 on
3091  * success, -1 on failure */
3092 MOCK_IMPL(int,
3094 {
3095  var_cell_t *cell;
3097  /* XXXX make sure we're actually supposed to send this! */
3098 
3099  if (!pk) {
3100  log_warn(LD_BUG, "Can't compute authenticate cell: no client auth key");
3101  return -1;
3102  }
3103  if (! authchallenge_type_is_supported(authtype)) {
3104  log_warn(LD_BUG, "Tried to send authenticate cell with unknown "
3105  "authentication type %d", authtype);
3106  return -1;
3107  }
3108 
3110  authtype,
3111  pk,
3112  get_current_auth_keypair(),
3113  0 /* not server */);
3114  if (! cell) {
3115  log_fn(LOG_PROTOCOL_WARN, LD_NET, "Unable to compute authenticate cell!");
3116  return -1;
3117  }
3119  var_cell_free(cell);
3120 
3121  return 0;
3122 }
void connection_or_close_for_error(or_connection_t *orconn, int flush)
var_cell_t * var_cell_new(uint16_t payload_len)
unsigned int is_pt
static int connection_or_launch_v3_or_handshake(or_connection_t *conn)
Header file for circuitstats.c.
#define ED25519_SIG_LEN
Definition: x25519_sizes.h:34
void tor_tls_block_renegotiation(tor_tls_t *tls)
Definition: tortls_nss.c:620
smartlist_t * get_connection_array(void)
Definition: mainloop.c:452
Header file for rendcommon.c.
Cell queue structures.
HT_PROTOTYPE(HT_GENERATE2(channel_gid_map, HT_GENERATE2(channel_s, HT_GENERATE2(gidmap_node, HT_GENERATE2(channel_id_hash, HT_GENERATE2(channel_id_eq)
Definition: channel.c:121
void crypto_rand(char *to, size_t n)
Definition: crypto_rand.c:477
int tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity)
Definition: tortls.c:416
int authdir_mode_tests_reachability(const or_options_t *options)
Definition: authmode.c:59
Header file for channeltls.c.
unsigned int channel_num_circuits(channel_t *chan)
Definition: channel.c:3346
char body[CELL_MAX_NETWORK_SIZE]
Definition: cell_queue_st.h:21
void connection_or_close_normally(or_connection_t *orconn, int flush)
Router descriptor structure.
int tor_tls_get_tlssecrets(tor_tls_t *tls, uint8_t *secrets_out)
Definition: tortls_nss.c:737
Header for proto_cell.c.
static const int n_or_protocol_versions
void channel_mark_bad_for_new_circs(channel_t *chan)
Definition: channel.c:2909
crypto_pk_t * tor_tls_get_my_client_auth_key(void)
Definition: tortls.c:101
int connection_or_send_authenticate_cell(or_connection_t *conn, int authtype)
void connection_start_writing(connection_t *conn)
Definition: mainloop.c:688
Header file for circuitbuild.c.
Common functions for using (pseudo-)random number generators.
int get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type, int *is_pt_out, const connection_t *conn)
Definition: connection.c:5411
Definition: node_st.h:33
static const uint16_t or_protocol_versions[]
int node_supports_ed25519_link_authentication(const node_t *node, int compatible_with_us)
Definition: nodelist.c:1135
struct tor_x509_cert_t * tor_tls_get_own_cert(tor_tls_t *tls)
Definition: tortls_nss.c:528
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
uint16_t sa_family_t
Definition: inaddr_st.h:77
#define TO_CONN(c)
Definition: or.h:735
#define AUTHTYPE_ED25519_SHA256_RFC5705
Definition: or.h:691
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
int crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen)
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
Header file for command.c.
time_t channel_when_last_client(channel_t *chan)
Definition: channel.c:3288
void crypto_digest_get_digest(crypto_digest_t *digest, char *out, size_t out_len)
const char * escaped_safe_str(const char *address)
Definition: config.c:1150
void channel_timestamp_active(channel_t *chan)
Definition: channel.c:3168
uint64_t PerConnBWRate
void channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
Definition: channeltls.c:1054
static int disable_broken_connection_counts
void channel_close_for_error(channel_t *chan)
Definition: channel.c:1241
Header file for connection.c.
void connection_or_connect_failed(or_connection_t *conn, int reason, const char *msg)
#define OR_CONN_HIGHWATER
Definition: or.h:720
channel_listener_t * channel_tls_get_listener(void)
Definition: channeltls.c:252
static int connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
circid_t circ_id
Definition: var_cell_st.h:20
static void set_uint16(void *cp, uint16_t v)
Definition: bytes.h:78
const char * tor_tls_err_to_string(int err)
Definition: tortls.c:155
void channel_tls_handle_state_change_on_orconn(channel_tls_t *chan, or_connection_t *conn, uint8_t state)
Definition: channeltls.c:951
Definition: cell_st.h:17
#define LD_GENERAL
Definition: log.h:62
void connection_free_(connection_t *conn)
Definition: connection.c:761
void connection_or_block_renegotiation(or_connection_t *conn)
static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
tor_cert_t * tor_cert_dup(const tor_cert_t *cert)
Definition: torcert.c:294
#define DOWNCAST(to, ptr)
Definition: or.h:110
void rep_hist_note_negotiated_link_proto(unsigned link_proto, int started_here)
Definition: rephist.c:2701
int tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2, tor_addr_comparison_t how)
Definition: address.c:954
time_t connection_or_client_used(or_connection_t *conn)
#define TIME_BEFORE_OR_CONN_IS_TOO_OLD
#define LOG_INFO
Definition: log.h:45
#define OR_CERT_TYPE_ID_1024
Definition: or.h:665
Header file for nodelist.c.
const common_digests_t * tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert)
Definition: x509.c:58
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:628
void var_cell_free_(var_cell_t *cell)
void smartlist_add(smartlist_t *sl, void *element)
#define OR_CONN_STATE_TLS_HANDSHAKING
Definition: orconn_event.h:36
void learned_router_identity(const tor_addr_t *addr, uint16_t port, const char *digest, const ed25519_public_key_t *ed_id)
Definition: bridges.c:397
int channel_is_better(channel_t *a, channel_t *b)
Definition: channel.c:2334
void connection_or_notify_error(or_connection_t *conn, int reason, const char *msg)
void connection_or_clear_identity_map(void)
void channel_tls_update_marks(or_connection_t *conn)
Definition: channeltls.c:1345
static strmap_t * broken_connection_counts
OR connection structure.
int authchallenge_type_is_supported(uint16_t challenge_type)
crypto_digest_t * crypto_digest256_new(digest_algorithm_t algorithm)
#define ED25519_BASE64_LEN
Definition: x25519_sizes.h:40
void channel_close_from_lower_layer(channel_t *chan)
Definition: channel.c:1213
int connection_or_digest_is_known_relay(const char *id_digest)
#define MAX_REASONS_TO_REPORT
#define OR_CONN_STATE_TLS_SERVER_RENEGOTIATING
Definition: orconn_event.h:43
Header file for config.c.
int router_digest_is_fallback_dir(const char *digest)
Definition: dirlist.c:157
#define CONN_TYPE_OR
Definition: connection.h:24
int fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
Definition: proto_cell.c:57
void crypto_digest_add_bytes(crypto_digest_t *digest, const char *data, size_t len)
const or_options_t * get_options(void)
Definition: config.c:941
#define tor_assert(expr)
Definition: util_bug.h:102
struct tor_tls_t * tls
Header file for microdesc.c.
static uint32_t tor_addr_to_ipv4h(const tor_addr_t *a)
Definition: address.h:152
void ed25519_public_to_base64(char *output, const ed25519_public_key_t *pkey)
Header file for reachability.c.
tor_tls_t * tor_tls_new(tor_socket_t sock, int is_server)
Definition: tortls_nss.c:396
size_t buf_datalen(const buf_t *buf)
Definition: buffers.c:394
#define tor_free(p)
Definition: malloc.h:52
unsigned int channelpadding_get_channel_idle_timeout(const channel_t *chan, int is_canonical)
uint8_t command
Definition: var_cell_st.h:18
unsigned int proxy_state
Definition: connection_st.h:89
#define ED25519_PUBKEY_LEN
Definition: x25519_sizes.h:27
#define tor_fragile_assert()
Definition: util_bug.h:246
struct tor_cert_st * own_link_cert
void control_event_bootstrap_prob_or(const char *warn, int reason, or_connection_t *or_conn)
or_handshake_certs_t * certs
const char * conn_state_to_string(int type, int state)
Definition: connection.c:275
Header file for mainloop.c.
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:57
void circuit_build_times_network_is_live(circuit_build_times_t *cbt)
void node_get_pref_orport(const node_t *node, tor_addr_port_t *ap_out)
Definition: nodelist.c:1715
void connection_or_about_to_close(or_connection_t *or_conn)
smartlist_t * smartlist_new(void)
int tor_tls_export_key_material(tor_tls_t *tls, uint8_t *secrets_out, const uint8_t *context, size_t context_len, const char *label)
Definition: tortls_nss.c:751
#define bool_eq(a, b)
Definition: logic.h:16
void connection_or_init_conn_from_address(or_connection_t *conn, const tor_addr_t *addr, uint16_t port, const char *id_digest, const ed25519_public_key_t *ed_id, int started_here)
Header file for geoip.c.
void * tor_reallocarray_(void *ptr, size_t sz1, size_t sz2)
Definition: malloc.c:146
int connection_tls_start_handshake(or_connection_t *conn, int receiving)
Header for ext_orport.c.
Header file for scheduler*.c.
or_connection_t * or_connection_new(int type, int socket_family)
Definition: connection.c:375
var_cell_t * var_cell_copy(const var_cell_t *src)
void connection_or_clear_identity(or_connection_t *conn)
uint8_t payload[CELL_PAYLOAD_SIZE]
Definition: cell_st.h:21
#define AUTHTYPE_RSA_SHA256_TLSSECRET
Definition: or.h:680
#define STATIC
Definition: testsupport.h:32
Header file for orconn_event.c.
static void set_uint32(void *cp, uint32_t v)
Definition: bytes.h:87
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:54
or_connection_t * TO_OR_CONN(connection_t *c)
void connection_or_report_broken_states(int severity, int domain)
Header file for directory authority mode.
static uint8_t get_uint8(const void *cp)
Definition: bytes.h:23
#define EXT_OR_CONN_ID_LEN
Definition: or.h:712
void connection_or_event_status(or_connection_t *conn, or_conn_status_event_t tp, int reason)
#define CONN_TYPE_EXT_OR
Definition: connection.h:51
void connection_or_remove_from_ext_or_id_map(or_connection_t *conn)
int ed25519_pubkey_eq(const ed25519_public_key_t *key1, const ed25519_public_key_t *key2)
static void set_uint8(void *cp, uint8_t v)
Definition: bytes.h:31
const char * ed25519_fmt(const ed25519_public_key_t *pkey)
int errno_to_orconn_end_reason(int e)
Definition: reasons.c:287
Common functions for cryptographic routines.
Header file for channel.c.
#define AUTHTYPE_RSA_SHA256_RFC5705
Definition: or.h:688
const char * node_get_nickname(const node_t *node)
Definition: nodelist.c:1301
static int broken_state_count_compare(const void **a_ptr, const void **b_ptr)
OR handshake certs structure.
static int connection_or_check_valid_tls_handshake(or_connection_t *conn, int started_here, char *digest_rcvd_out)
uint64_t BandwidthRate
networkstatus_t * networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
unsigned int is_outgoing
int connection_or_set_state_open(or_connection_t *conn)
#define tor_addr_from_ipv4h(dest, v4addr)
Definition: address.h:287
static void connection_or_check_canonicity(or_connection_t *conn, int started_here)
void connection_or_group_set_badness_(smartlist_t *group, int force)
void tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz)
Definition: tortls_nss.c:346
#define LD_CIRC
Definition: log.h:82
Header for crypto_format.c.
Header file for routermode.c.
token_bucket_rw_t bucket
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1169
void clear_broken_connection_map(int stop_recording)
#define OR_CERT_TYPE_AUTH_1024
Definition: or.h:669
or_handshake_certs_t * or_handshake_certs_new(void)
Definition: torcert.c:471
const routerinfo_t * router_get_by_id_digest(const char *digest)
Definition: routerlist.c:690
#define DIGEST_LEN
Definition: digest_sizes.h:20
void channel_listener_queue_incoming(channel_listener_t *listener, channel_t *incoming)
Definition: channel.c:1922
int connection_or_reached_eof(or_connection_t *conn)
uint8_t payload[FLEXIBLE_ARRAY_MEMBER]
Definition: var_cell_st.h:24
tor_socket_t s
Definition: connection_st.h:93
int tor_tls_used_v1_handshake(tor_tls_t *tls)
Definition: tortls_nss.c:697
int ed25519_public_key_is_zero(const ed25519_public_key_t *pubkey)
channel_tls_t * chan
Header file for circuitbuild.c.
#define OR_CONN_LOWWATER
Definition: or.h:724
var_cell_t * connection_or_compute_authenticate_cell_body(or_connection_t *conn, const int authtype, crypto_pk_t *signing_key, const ed25519_keypair_t *ed_signing_key, int server)
int usable_consensus_flavor(void)
Definition: microdesc.c:1084
Master header file for Tor-specific functionality.
const char * find_transport_name_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
Definition: bridges.c:591
void entry_guard_chan_failed(channel_t *chan)
Definition: entrynodes.c:2500
int connection_or_get_num_circuits(or_connection_t *conn)
static void add_x509_cert(certs_cell_t *certs_cell, uint8_t cert_type, const tor_x509_cert_t *cert)
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
int connection_or_nonopen_was_started_here(or_connection_t *conn)
HT_GENERATE2(cdm_diff_ht, cdm_diff_t, node, cdm_diff_hash, cdm_diff_eq, 0.6, tor_reallocarray, tor_free_) static void cdm_diff_free_(cdm_diff_t *diff)
Definition: consdiffmgr.c:222
struct buf_t * inbuf
Definition: connection_st.h:98
circid_t circ_id
Definition: cell_st.h:18
Header file for circuitbuild.c.
int control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp, int reason)
#define OR_CONN_STATE_OPEN
Definition: orconn_event.h:53
const node_t * node_get_by_id(const char *identity_digest)
Definition: nodelist.c:223
void tor_x509_cert_get_der(const tor_x509_cert_t *cert, const uint8_t **encoded_out, size_t *size_out)
Definition: x509_nss.c:216
#define LD_HANDSHAKE
Definition: log.h:101
int connection_buf_get_bytes(char *string, size_t len, connection_t *conn)
Definition: connection.c:3891
Header file for rephist.c.
static uint16_t get_uint16(const void *cp)
Definition: bytes.h:42
#define OR_CONN_STATE_PROXY_HANDSHAKING
Definition: orconn_event.h:33
uint16_t payload_len
Definition: var_cell_st.h:22
#define LOG_WARN
Definition: log.h:53
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:770
Header for routerkeys.c.
void connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
int connection_read_proxy_handshake(connection_t *conn)
Definition: connection.c:2605
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
void tor_free_(void *mem)
Definition: malloc.c:227
#define CELL_MAX_NETWORK_SIZE
Definition: or.h:579
time_t timestamp_created
#define crypto_digest_free(d)
int connection_connect(connection_t *conn, const char *address, const tor_addr_t *addr, uint16_t port, int *socket_error)
Definition: connection.c:2185
Header file for circuitlist.c.
uint16_t marked_for_close
int connection_or_send_netinfo(or_connection_t *conn)
struct tor_cert_st * ed_id_sign
#define VAR_CELL_MAX_HEADER_SIZE
Definition: or.h:582
size_t encoded_len
Definition: torcert.h:40
tor_addr_t real_addr
const routerstatus_t * router_get_consensus_status_by_id(const char *digest)
void token_bucket_rw_reset(token_bucket_rw_t *bucket, uint32_t now_ts)
Definition: token_bucket.c:167
#define LD_OR
Definition: log.h:92
int router_ed25519_id_is_me(const ed25519_public_key_t *id)
Definition: routerkeys.c:618
void channel_clear_identity_digest(channel_t *chan)
Definition: channel.c:1299
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
static digestmap_t * orconn_ext_or_id_map
Headers for tortls.c.
Fixed-size cell structure.
int channel_is_bad_for_new_circs(channel_t *chan)
Definition: channel.c:2896
#define OR_CERT_TYPE_TLS_LINK
Definition: or.h:662
void tor_tls_set_renegotiate_callback(tor_tls_t *tls, void(*cb)(tor_tls_t *, void *arg), void *arg)
Definition: tortls_nss.c:445
#define OR_CONN_STATE_OR_HANDSHAKING_V2
Definition: orconn_event.h:47
static void note_broken_connection(const char *state)
uint8_t command
Definition: cell_st.h:19
int tor_tls_handshake(tor_tls_t *tls)
Definition: tortls_nss.c:586
unsigned int type
Definition: connection_st.h:50
void connection_or_set_ext_or_identifier(or_connection_t *conn)
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
int connection_or_client_learned_peer_id(or_connection_t *conn, const uint8_t *rsa_peer_id, const ed25519_public_key_t *ed_peer_id)
const common_digests_t * tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
Definition: x509.c:68
void or_handshake_state_record_cell(or_connection_t *conn, or_handshake_state_t *state, const cell_t *cell, int incoming)
static void connection_or_change_state(or_connection_t *conn, uint8_t state)
uint64_t global_identifier
void connection_or_clear_ext_or_id_map(void)
struct tor_x509_cert_t * tor_tls_get_peer_cert(tor_tls_t *tls)
Definition: tortls_nss.c:518
void connection_or_write_var_cell_to_buf(const var_cell_t *cell, or_connection_t *conn)
uint64_t PerConnBWBurst
void assert_connection_ok(connection_t *conn, time_t now)
Definition: connection.c:5257
channel_listener_t * channel_tls_start_listener(void)
Definition: channeltls.c:264
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition: address.c:1134
const routerinfo_t * router_get_my_routerinfo(void)
Definition: router.c:1623
#define CELL_PAYLOAD_SIZE
Definition: or.h:576
uint32_t magic
Definition: connection_st.h:46
int crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
Definition: crypto_rsa.c:356
int connection_or_send_certs_cell(or_connection_t *conn)
ssize_t connection_or_num_cells_writeable(or_connection_t *conn)
void or_handshake_state_record_var_cell(or_connection_t *conn, or_handshake_state_t *state, const var_cell_t *cell, int incoming)
void rep_hist_padding_count_write(padding_type_t type)
Definition: rephist.c:2731
static void connection_or_set_identity_digest(or_connection_t *conn, const char *rsa_digest, const ed25519_public_key_t *ed_id)
Header file for relay.c.
#define SMARTLIST_FOREACH(sl, type, var, cmd)
int connection_or_send_auth_challenge_cell(or_connection_t *conn)
int connection_or_flushed_some(or_connection_t *conn)
The or_state_t structure, which represents Tor's state file.
void connection_start_reading(connection_t *conn)
Definition: mainloop.c:632
Header file for router.c.
static int connection_or_process_cells_from_inbuf(or_connection_t *conn)
uint16_t port
or_connection_t * connection_or_connect(const tor_addr_t *_addr, uint16_t port, const char *id_digest, const ed25519_public_key_t *ed_id, channel_tls_t *chan)
int connection_or_finished_flushing(or_connection_t *conn)
static void connection_or_update_token_buckets_helper(or_connection_t *conn, int reset, const or_options_t *options)
typedef HT_HEAD(hs_service_ht, hs_service_t) hs_service_ht
static int connection_tls_finish_handshake(or_connection_t *conn)
#define fmt_addr(a)
Definition: address.h:211
circuit_build_times_t * get_circuit_build_times_mutable(void)
Definition: circuitstats.c:89
int tor_tls_peer_has_cert(tor_tls_t *tls)
Definition: tortls_nss.c:509
void connection_stop_writing(connection_t *conn)
Definition: mainloop.c:665
static void cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
int connection_init_or_handshake_state(or_connection_t *conn, int started_here)
void token_bucket_rw_adjust(token_bucket_rw_t *bucket, uint32_t rate, uint32_t burst)
Definition: token_bucket.c:152
#define log_fn(severity, domain, args,...)
Definition: log.h:287
unsigned int proxy_type
static void connection_or_note_state_when_broken(or_connection_t *orconn)
uint64_t BandwidthBurst
int router_digest_is_me(const char *digest)
Definition: router.c:1586
Variable-length cell structure.
int var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
size_t crypto_pk_keysize(const crypto_pk_t *env)
#define CASE_TOR_TLS_ERROR_ANY
Definition: tortls.h:62
Headers for tortls.c.
channel_t * channel_tls_handle_incoming(or_connection_t *orconn)
Definition: channeltls.c:327
unsigned int hold_open_until_flushed
Definition: connection_st.h:61
void channel_set_circid_type(channel_t *chan, crypto_pk_t *identity_rcvd, int consider_identity)
Definition: channel.c:3363
static void add_certs_cell_cert_helper(certs_cell_t *certs_cell, uint8_t cert_type, const uint8_t *cert_encoded, size_t cert_len)
#define tor_addr_eq(a, b)
Definition: address.h:244
void tor_tls_set_logged_address(tor_tls_t *tls, const char *address)
Definition: tortls.c:369
#define OR_CONN_STATE_OR_HANDSHAKING_V3
Definition: orconn_event.h:51
tor_addr_t ipv6_addr
Definition: routerinfo_st.h:32
time_t approx_time(void)
Definition: approx_time.c:32
int ed25519_sign(ed25519_signature_t *signature_out, const uint8_t *msg, size_t len, const ed25519_keypair_t *keypair)
void scheduler_channel_wants_writes(channel_t *chan)
Definition: scheduler.c:669
int authchallenge_type_is_better(uint16_t challenge_type_a, uint16_t challenge_type_b)
struct tor_x509_cert_t * id_cert
static void connection_or_state_publish(const or_connection_t *conn, uint8_t state)
Header for torcert.c.
static void add_ed25519_cert(certs_cell_t *certs_cell, uint8_t cert_type, const tor_cert_t *cert)
Header file for dirlist.c.
int connection_or_send_versions(or_connection_t *conn, int v3_plus)
static unsigned int connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
int public_server_mode(const or_options_t *options)
Definition: routermode.c:43
uint8_t * encoded
Definition: torcert.h:38
void connection_or_update_token_buckets(smartlist_t *conns, const or_options_t *options)
int node_ed25519_id_matches(const node_t *node, const ed25519_public_key_t *id)
Definition: nodelist.c:1096
Header file for buffers.c.
char d[N_COMMON_DIGEST_ALGORITHMS][DIGEST256_LEN]
Definition: crypto_digest.h:89
Header file for reasons.c.
int tls_error_to_orconn_end_reason(int e)
Definition: reasons.c:261
OR handshake state structure.
tor_addr_t addr
uint32_t addr
Definition: routerinfo_st.h:24
Header file for connection_or.c.
void cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
int connection_or_process_inbuf(or_connection_t *conn)
#define LD_NET
Definition: log.h:66
int crypto_digest256(char *digest, const char *m, size_t len, digest_algorithm_t algorithm)
#define OR_CONN_STATE_CONNECTING
Definition: orconn_event.h:31
#define tor_addr_to_in6_addr8(x)
Definition: address.h:129
void connection_watch_events(connection_t *conn, watchable_events_t events)
Definition: mainloop.c:494
int is_or_protocol_version_known(uint16_t v)
static void connection_or_get_state_description(or_connection_t *orconn, char *buf, size_t buflen)
channel_t * channel_tls_to_base(channel_tls_t *tlschan)
Definition: channeltls.c:369
void channel_set_identity_digest(channel_t *chan, const char *identity_digest, const ed25519_public_key_t *ed_identity)
Definition: channel.c:1328
int tor_tls_get_pending_bytes(tor_tls_t *tls)
Definition: tortls_nss.c:634
void channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
Definition: channeltls.c:1170
int server_mode(const or_options_t *options)
Definition: routermode.c:34
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:904
or_conn_status_event_t
Definition: orconn_event.h:59
int connection_proxy_connect(connection_t *conn, int type)
Definition: connection.c:2340
int tor_tls_is_server(tor_tls_t *tls)
Definition: tortls.c:379
Header file for control_events.c.
#define LD_PROTOCOL
Definition: log.h:72
int connection_or_single_set_badness_(time_t now, or_connection_t *or_conn, int force)
or_handshake_state_t * handshake_state
int connection_tls_continue_handshake(or_connection_t *conn)
void smartlist_sort(smartlist_t *sl, int(*compare)(const void **a, const void **b))
Definition: smartlist.c:334
crypto_digest_t * digest_sent
void channel_closed(channel_t *chan)
Definition: channel.c:1268
const char * orconn_end_reason_to_control_string(int r)
Definition: reasons.c:225
void channel_mark_client(channel_t *chan)
Definition: channel.c:2937
void dirserv_orconn_tls_done(const tor_addr_t *addr, uint16_t or_port, const char *digest_rcvd, const ed25519_public_key_t *ed_id_rcvd)
Definition: reachability.c:38
int tor_tls_get_my_certs(int server, const tor_x509_cert_t **link_cert_out, const tor_x509_cert_t **id_cert_out)
Definition: tortls.c:76
uint8_t state
Definition: connection_st.h:49
int connection_or_finished_connecting(or_connection_t *or_conn)
void or_handshake_state_free_(or_handshake_state_t *state)
Header file for networkstatus.c.
#define LD_BUG
Definition: log.h:86
uint32_t monotime_coarse_get_stamp(void)
Definition: compat_time.c:844
char identity_digest[DIGEST_LEN]
Header file for routerlist.c.
void command_setup_listener(channel_listener_t *listener)
Definition: command.c:697
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:179
or_connection_t * connection_or_get_by_ext_or_id(const char *id)
unsigned int is_canonical
#define fast_memeq(a, b, c)
Definition: di_ops.h:35