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