tor  0.4.0.1-alpha
connection_or.c
Go to the documentation of this file.
1 /* Copyright (c) 2001 Matej Pfajfar.
2  * Copyright (c) 2001-2004, Roger Dingledine.
3  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4  * Copyright (c) 2007-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
23 #include "core/or/or.h"
24 #include "feature/client/bridges.h"
25 #include "lib/buf/buffers.h"
26 /*
27  * Define this so we get channel internal functions, since we're implementing
28  * part of a subclass (channel_tls_t).
29  */
30 #define TOR_CHANNEL_INTERNAL_
31 #define CONNECTION_OR_PRIVATE
32 #define ORCONN_EVENT_PRIVATE
33 #include "core/or/channel.h"
34 #include "core/or/channeltls.h"
35 #include "core/or/circuitbuild.h"
36 #include "core/or/circuitlist.h"
37 #include "core/or/circuitstats.h"
38 #include "core/or/command.h"
39 #include "app/config/config.h"
41 #include "core/or/connection_or.h"
47 #include "lib/geoip/geoip.h"
48 #include "core/mainloop/mainloop.h"
49 #include "trunnel/link_handshake.h"
50 #include "trunnel/netinfo.h"
54 #include "core/proto/proto_cell.h"
55 #include "core/or/reasons.h"
56 #include "core/or/relay.h"
58 #include "feature/stats/rephist.h"
59 #include "feature/relay/router.h"
60 #include "feature/relay/routerkeys.h"
64 #include "feature/relay/ext_orport.h"
65 #include "core/or/scheduler.h"
66 #include "feature/nodelist/torcert.h"
67 #include "core/or/channelpadding.h"
69 
70 #include "core/or/cell_st.h"
71 #include "core/or/cell_queue_st.h"
72 #include "core/or/or_connection_st.h"
73 #include "core/or/or_handshake_certs_st.h"
74 #include "core/or/or_handshake_state_st.h"
75 #include "app/config/or_state_st.h"
76 #include "feature/nodelist/routerinfo_st.h"
77 #include "core/or/var_cell_st.h"
79 
80 #include "lib/tls/tortls.h"
81 #include "lib/tls/x509.h"
82 
83 #include "core/or/orconn_event.h"
84 
89  int started_here,
90  char *digest_rcvd_out);
91 
92 static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
93 
94 static unsigned int
96 static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
97 
98 /*
99  * Call this when changing connection state, so notifications to the owning
100  * channel can be handled.
101  */
102 
103 static void connection_or_change_state(or_connection_t *conn, uint8_t state);
104 
106  int started_here);
107 
108 /**************************************************************/
109 
114 {
115  tor_assert(c->magic == OR_CONNECTION_MAGIC);
116  return DOWNCAST(or_connection_t, c);
117 }
118 
121 static digestmap_t *orconn_ext_or_id_map = NULL;
122 
125 void
127 {
128  tor_assert(conn);
129  memset(conn->identity_digest, 0, DIGEST_LEN);
130 }
131 
133 void
135 {
136  smartlist_t *conns = get_connection_array();
137  SMARTLIST_FOREACH(conns, connection_t *, conn,
138  {
139  if (conn->type == CONN_TYPE_OR) {
140  connection_or_clear_identity(TO_OR_CONN(conn));
141  }
142  });
143 }
144 
154 static void
156  const char *rsa_digest,
157  const ed25519_public_key_t *ed_id)
158 {
159  channel_t *chan = NULL;
160  tor_assert(conn);
161  tor_assert(rsa_digest);
162 
163  if (conn->chan)
164  chan = TLS_CHAN_TO_BASE(conn->chan);
165 
166  log_info(LD_HANDSHAKE, "Set identity digest for %p (%s): %s %s.",
167  conn,
168  escaped_safe_str(conn->base_.address),
169  hex_str(rsa_digest, DIGEST_LEN),
170  ed25519_fmt(ed_id));
171  log_info(LD_HANDSHAKE, " (Previously: %s %s)",
173  chan ? ed25519_fmt(&chan->ed25519_identity) : "<null>");
174 
175  const int rsa_id_was_set = ! tor_digest_is_zero(conn->identity_digest);
176  const int ed_id_was_set =
178  const int rsa_changed =
179  tor_memneq(conn->identity_digest, rsa_digest, DIGEST_LEN);
180  const int ed_changed = ed_id_was_set &&
181  (!ed_id || !ed25519_pubkey_eq(ed_id, &chan->ed25519_identity));
182 
183  tor_assert(!rsa_changed || !rsa_id_was_set);
184  tor_assert(!ed_changed || !ed_id_was_set);
185 
186  if (!rsa_changed && !ed_changed)
187  return;
188 
189  /* If the identity was set previously, remove the old mapping. */
190  if (rsa_id_was_set) {
192  if (chan)
194  }
195 
196  memcpy(conn->identity_digest, rsa_digest, DIGEST_LEN);
197 
198  /* If we're initializing the IDs to zero, don't add a mapping yet. */
199  if (tor_digest_is_zero(rsa_digest) &&
200  (!ed_id || ed25519_public_key_is_zero(ed_id)))
201  return;
202 
203  /* Deal with channels */
204  if (chan)
205  channel_set_identity_digest(chan, rsa_digest, ed_id);
206 }
207 
211 void
213 {
214  or_connection_t *tmp;
216  return;
217  if (!conn->ext_or_conn_id)
218  return;
219 
220  tmp = digestmap_remove(orconn_ext_or_id_map, conn->ext_or_conn_id);
222  tor_assert(tmp == conn);
223 
224  memset(conn->ext_or_conn_id, 0, EXT_OR_CONN_ID_LEN);
225 }
226 
231 {
233  return NULL;
234  return digestmap_get(orconn_ext_or_id_map, id);
235 }
236 
238 void
240 {
241  digestmap_free(orconn_ext_or_id_map, NULL);
242  orconn_ext_or_id_map = NULL;
243 }
244 
247 void
249 {
250  char random_id[EXT_OR_CONN_ID_LEN];
251  or_connection_t *tmp;
252 
254  orconn_ext_or_id_map = digestmap_new();
255 
256  /* Remove any previous identifiers: */
257  if (conn->ext_or_conn_id && !tor_digest_is_zero(conn->ext_or_conn_id))
259 
260  do {
261  crypto_rand(random_id, sizeof(random_id));
262  } while (digestmap_get(orconn_ext_or_id_map, random_id));
263 
264  if (!conn->ext_or_conn_id)
265  conn->ext_or_conn_id = tor_malloc_zero(EXT_OR_CONN_ID_LEN);
266 
267  memcpy(conn->ext_or_conn_id, random_id, EXT_OR_CONN_ID_LEN);
268 
269  tmp = digestmap_set(orconn_ext_or_id_map, random_id, conn);
270  tor_assert(!tmp);
271 }
272 
273 /**************************************************************/
274 
279 static strmap_t *broken_connection_counts;
280 
283 
285 static void
286 note_broken_connection(const char *state)
287 {
288  void *ptr;
289  intptr_t val;
291  return;
292 
294  broken_connection_counts = strmap_new();
295 
296  ptr = strmap_get(broken_connection_counts, state);
297  val = (intptr_t)ptr;
298  val++;
299  ptr = (void*)val;
300  strmap_set(broken_connection_counts, state, ptr);
301 }
302 
305 void
306 clear_broken_connection_map(int stop_recording)
307 {
309  strmap_free(broken_connection_counts, NULL);
311  if (stop_recording)
313 }
314 
319 static void
321  char *buf, size_t buflen)
322 {
323  connection_t *conn = TO_CONN(orconn);
324  const char *conn_state;
325  char tls_state[256];
326 
327  tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
328 
329  conn_state = conn_state_to_string(conn->type, conn->state);
330  tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
331 
332  tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
333 }
334 
337 static void
339 {
340  char buf[256];
342  return;
343  connection_or_get_state_description(orconn, buf, sizeof(buf));
344  log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
346 }
347 
349 typedef struct broken_state_count_t {
350  intptr_t count;
351  const char *state;
353 
355 static int
356 broken_state_count_compare(const void **a_ptr, const void **b_ptr)
357 {
358  const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
359  if (b->count < a->count)
360  return -1;
361  else if (b->count == a->count)
362  return 0;
363  else
364  return 1;
365 }
366 
369 #define MAX_REASONS_TO_REPORT 10
370 
373 void
374 connection_or_report_broken_states(int severity, int domain)
375 {
376  int total = 0;
377  smartlist_t *items;
378 
380  return;
381 
382  items = smartlist_new();
383  STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
384  broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
385  c->count = (intptr_t)countptr;
386  total += (int)c->count;
387  c->state = state;
388  smartlist_add(items, c);
389  } STRMAP_FOREACH_END;
390 
392 
393  tor_log(severity, domain, "%d connections have failed%s", total,
394  smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
395 
396  SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
397  if (c_sl_idx > MAX_REASONS_TO_REPORT)
398  break;
399  tor_log(severity, domain,
400  " %d connections died in state %s", (int)c->count, c->state);
401  } SMARTLIST_FOREACH_END(c);
402 
404  smartlist_free(items);
405 }
406 
413 void
415  int reason)
416 {
417  orconn_event_msg_t msg;
418 
419  msg.type = ORCONN_MSGTYPE_STATUS;
420  msg.u.status.gid = conn->base_.global_identifier;
421  msg.u.status.status = tp;
422  msg.u.status.reason = reason;
423  orconn_event_publish(&msg);
424  control_event_or_conn_status(conn, tp, reason);
425 }
426 
433 static void
434 connection_or_state_publish(const or_connection_t *conn, uint8_t state)
435 {
436  orconn_event_msg_t msg;
437 
438  msg.type = ORCONN_MSGTYPE_STATE;
439  msg.u.state.gid = conn->base_.global_identifier;
440  msg.u.state.proxy_type = conn->proxy_type;
441  msg.u.state.state = state;
442  if (conn->chan) {
443  msg.u.state.chan = TLS_CHAN_TO_BASE(conn->chan)->global_identifier;
444  } else {
445  msg.u.state.chan = 0;
446  }
447  orconn_event_publish(&msg);
448 }
449 
454 static void
456 {
457  tor_assert(conn);
458 
459  conn->base_.state = state;
460 
461  connection_or_state_publish(conn, state);
462  if (conn->chan)
464 }
465 
471 connection_or_get_num_circuits, (or_connection_t *conn))
472 {
473  tor_assert(conn);
474 
475  if (conn->chan) {
476  return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
477  } else return 0;
478 }
479 
480 /**************************************************************/
481 
489 void
490 cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
491 {
492  char *dest = dst->body;
493  if (wide_circ_ids) {
494  set_uint32(dest, htonl(src->circ_id));
495  dest += 4;
496  } else {
497  /* Clear the last two bytes of dest, in case we can accidentally
498  * send them to the network somehow. */
499  memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2);
500  set_uint16(dest, htons(src->circ_id));
501  dest += 2;
502  }
503  set_uint8(dest, src->command);
504  memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
505 }
506 
510 static void
511 cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
512 {
513  if (wide_circ_ids) {
514  dest->circ_id = ntohl(get_uint32(src));
515  src += 4;
516  } else {
517  dest->circ_id = ntohs(get_uint16(src));
518  src += 2;
519  }
520  dest->command = get_uint8(src);
521  memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
522 }
523 
526 int
527 var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
528 {
529  int r;
530  if (wide_circ_ids) {
531  set_uint32(hdr_out, htonl(cell->circ_id));
532  hdr_out += 4;
534  } else {
535  set_uint16(hdr_out, htons(cell->circ_id));
536  hdr_out += 2;
537  r = VAR_CELL_MAX_HEADER_SIZE - 2;
538  }
539  set_uint8(hdr_out, cell->command);
540  set_uint16(hdr_out+1, htons(cell->payload_len));
541  return r;
542 }
543 
546 var_cell_t *
547 var_cell_new(uint16_t payload_len)
548 {
549  size_t size = offsetof(var_cell_t, payload) + payload_len;
550  var_cell_t *cell = tor_malloc_zero(size);
551  cell->payload_len = payload_len;
552  cell->command = 0;
553  cell->circ_id = 0;
554  return cell;
555 }
556 
561 var_cell_t *
563 {
564  var_cell_t *copy = NULL;
565  size_t size = 0;
566 
567  if (src != NULL) {
568  size = offsetof(var_cell_t, payload) + src->payload_len;
569  copy = tor_malloc_zero(size);
570  copy->payload_len = src->payload_len;
571  copy->command = src->command;
572  copy->circ_id = src->circ_id;
573  memcpy(copy->payload, src->payload, copy->payload_len);
574  }
575 
576  return copy;
577 }
578 
580 void
582 {
583  tor_free(cell);
584 }
585 
587 int
589 {
590  tor_assert(conn);
591 
592  log_info(LD_OR,"OR connection reached EOF. Closing.");
594 
595  return 0;
596 }
597 
603 int
605 {
609 #define MAX_OR_INBUF_WHEN_NONOPEN 0
610 
611  int ret = 0;
612  tor_assert(conn);
613 
614  switch (conn->base_.state) {
617 
618  /* start TLS after handshake completion, or deal with error */
619  if (ret == 1) {
620  tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
621  if (connection_tls_start_handshake(conn, 0) < 0)
622  ret = -1;
623  /* Touch the channel's active timestamp if there is one */
624  if (conn->chan)
625  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
626  }
627  if (ret < 0) {
628  connection_or_close_for_error(conn, 0);
629  }
630 
631  return ret;
633  case OR_CONN_STATE_OPEN:
637  default:
638  break; /* don't do anything */
639  }
640 
641  /* This check was necessary with 0.2.2, when the TLS_SERVER_RENEGOTIATING
642  * check would otherwise just let data accumulate. It serves no purpose
643  * in 0.2.3.
644  *
645  * XXXX Remove this check once we verify that the above paragraph is
646  * 100% true. */
647  if (buf_datalen(conn->base_.inbuf) > MAX_OR_INBUF_WHEN_NONOPEN) {
648  log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated too much data (%d bytes) "
649  "on nonopen OR connection %s %s:%u in state %s; closing.",
650  (int)buf_datalen(conn->base_.inbuf),
651  connection_or_nonopen_was_started_here(conn) ? "to" : "from",
652  conn->base_.address, conn->base_.port,
653  conn_state_to_string(conn->base_.type, conn->base_.state));
654  connection_or_close_for_error(conn, 0);
655  ret = -1;
656  }
657 
658  return ret;
659 }
660 
663 int
665 {
666  size_t datalen;
667 
668  /* Update the channel's active timestamp if there is one */
669  if (conn->chan)
670  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
671 
672  /* If we're under the low water mark, add cells until we're just over the
673  * high water mark. */
674  datalen = connection_get_outbuf_len(TO_CONN(conn));
675  if (datalen < OR_CONN_LOWWATER) {
676  /* Let the scheduler know */
677  scheduler_channel_wants_writes(TLS_CHAN_TO_BASE(conn->chan));
678  }
679 
680  return 0;
681 }
682 
685 ssize_t
687 {
688  size_t datalen, cell_network_size;
689  ssize_t n = 0;
690 
691  tor_assert(conn);
692 
693  /*
694  * If we're under the high water mark, we're potentially
695  * writeable; note this is different from the calculation above
696  * used to trigger when to start writing after we've stopped.
697  */
698  datalen = connection_get_outbuf_len(TO_CONN(conn));
699  if (datalen < OR_CONN_HIGHWATER) {
700  cell_network_size = get_cell_network_size(conn->wide_circ_ids);
701  n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, cell_network_size);
702  }
703 
704  return n;
705 }
706 
715 int
717 {
718  tor_assert(conn);
719  assert_connection_ok(TO_CONN(conn),0);
720 
721  switch (conn->base_.state) {
723  case OR_CONN_STATE_OPEN:
726  break;
727  default:
728  log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
730  return -1;
731  }
732 
733  /* Update the channel's active timestamp if there is one */
734  if (conn->chan)
735  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
736 
737  return 0;
738 }
739 
742 int
744 {
745  const int proxy_type = or_conn->proxy_type;
746  connection_t *conn;
747 
748  tor_assert(or_conn);
749  conn = TO_CONN(or_conn);
751 
752  log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
753  conn->address,conn->port);
754 
755  if (proxy_type != PROXY_NONE) {
756  /* start proxy handshake */
757  if (connection_proxy_connect(conn, proxy_type) < 0) {
758  connection_or_close_for_error(or_conn, 0);
759  return -1;
760  }
761 
762  connection_start_reading(conn);
764  return 0;
765  }
766 
767  if (connection_tls_start_handshake(or_conn, 0) < 0) {
768  /* TLS handshaking error of some kind. */
769  connection_or_close_for_error(or_conn, 0);
770  return -1;
771  }
772  return 0;
773 }
774 
777 void
779 {
780  connection_t *conn = TO_CONN(or_conn);
781 
782  /* Tell the controlling channel we're closed */
783  if (or_conn->chan) {
784  channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
785  /*
786  * NULL this out because the channel might hang around a little
787  * longer before channel_run_cleanup() gets it.
788  */
789  or_conn->chan->conn = NULL;
790  or_conn->chan = NULL;
791  }
792 
793  /* Remember why we're closing this connection. */
794  if (conn->state != OR_CONN_STATE_OPEN) {
795  /* now mark things down as needed */
797  const or_options_t *options = get_options();
799  /* Tell the new guard API about the channel failure */
800  entry_guard_chan_failed(TLS_CHAN_TO_BASE(or_conn->chan));
801  if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
802  int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
803  connection_or_event_status(or_conn, OR_CONN_EVENT_FAILED,
804  reason);
805  if (!authdir_mode_tests_reachability(options))
806  control_event_bootstrap_prob_or(
808  reason, or_conn);
809  }
810  }
811  } else if (conn->hold_open_until_flushed) {
812  /* We only set hold_open_until_flushed when we're intentionally
813  * closing a connection. */
814  connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
816  } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
817  connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
819  }
820 }
821 
824 int
826 {
827  if (router_get_consensus_status_by_id(id_digest))
828  return 1; /* It's in the consensus: "yes" */
829  if (router_get_by_id_digest(id_digest))
830  return 1; /* Not in the consensus, but we have a descriptor for
831  * it. Probably it was in a recent consensus. "Yes". */
832  return 0;
833 }
834 
844 static void
846  const or_options_t *options)
847 {
848  int rate, burst; /* per-connection rate limiting params */
850  /* It's in the consensus, or we have a descriptor for it meaning it
851  * was probably in a recent consensus. It's a recognized relay:
852  * give it full bandwidth. */
853  rate = (int)options->BandwidthRate;
854  burst = (int)options->BandwidthBurst;
855  } else {
856  /* Not a recognized relay. Squeeze it down based on the suggested
857  * bandwidth parameters in the consensus, but allow local config
858  * options to override. */
859  rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
860  networkstatus_get_param(NULL, "perconnbwrate",
861  (int)options->BandwidthRate, 1, INT32_MAX);
862  burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
863  networkstatus_get_param(NULL, "perconnbwburst",
864  (int)options->BandwidthBurst, 1, INT32_MAX);
865  }
866 
867  token_bucket_rw_adjust(&conn->bucket, rate, burst);
868  if (reset) {
870  }
871 }
872 
876 void
878  const or_options_t *options)
879 {
880  SMARTLIST_FOREACH(conns, connection_t *, conn,
881  {
882  if (connection_speaks_cells(conn))
884  });
885 }
886 
887 /* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
888  * non-canonical otherwise. Adjust idle_timeout accordingly.
889  */
890 void
891 connection_or_set_canonical(or_connection_t *or_conn,
892  int is_canonical)
893 {
894  if (bool_eq(is_canonical, or_conn->is_canonical) &&
895  or_conn->idle_timeout != 0) {
896  /* Don't recalculate an existing idle_timeout unless the canonical
897  * status changed. */
898  return;
899  }
900 
901  or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
902  or_conn->idle_timeout = channelpadding_get_channel_idle_timeout(
903  TLS_CHAN_TO_BASE(or_conn->chan), is_canonical);
904 
905  log_info(LD_CIRC,
906  "Channel %"PRIu64 " chose an idle timeout of %d.",
907  or_conn->chan ?
908  (TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier):0,
909  or_conn->idle_timeout);
910 }
911 
917 void
919  const tor_addr_t *addr, uint16_t port,
920  const char *id_digest,
921  const ed25519_public_key_t *ed_id,
922  int started_here)
923 {
924  log_debug(LD_HANDSHAKE, "init conn from address %s: %s, %s (%d)",
925  fmt_addr(addr),
926  hex_str((const char*)id_digest, DIGEST_LEN),
927  ed25519_fmt(ed_id),
928  started_here);
929 
930  connection_or_set_identity_digest(conn, id_digest, ed_id);
931  connection_or_update_token_buckets_helper(conn, 1, get_options());
932 
933  conn->base_.port = port;
934  tor_addr_copy(&conn->base_.addr, addr);
935  tor_addr_copy(&conn->real_addr, addr);
936 
937  connection_or_check_canonicity(conn, started_here);
938 }
939 
944 static void
946 {
947  const char *id_digest = conn->identity_digest;
948  const ed25519_public_key_t *ed_id = NULL;
949  const tor_addr_t *addr = &conn->real_addr;
950  if (conn->chan)
951  ed_id = & TLS_CHAN_TO_BASE(conn->chan)->ed25519_identity;
952 
953  const node_t *r = node_get_by_id(id_digest);
954  if (r &&
956  ! node_ed25519_id_matches(r, ed_id)) {
957  /* If this node is capable of proving an ed25519 ID,
958  * we can't call this a canonical connection unless both IDs match. */
959  r = NULL;
960  }
961 
962  if (r) {
963  tor_addr_port_t node_ap;
964  node_get_pref_orport(r, &node_ap);
965  /* XXXX proposal 186 is making this more complex. For now, a conn
966  is canonical when it uses the _preferred_ address. */
967  if (tor_addr_eq(&conn->base_.addr, &node_ap.addr))
968  connection_or_set_canonical(conn, 1);
969  if (!started_here) {
970  /* Override the addr/port, so our log messages will make sense.
971  * This is dangerous, since if we ever try looking up a conn by
972  * its actual addr/port, we won't remember. Careful! */
973  /* XXXX arma: this is stupid, and it's the reason we need real_addr
974  * to track is_canonical properly. What requires it? */
975  /* XXXX <arma> i believe the reason we did this, originally, is because
976  * we wanted to log what OR a connection was to, and if we logged the
977  * right IP address and port 56244, that wouldn't be as helpful. now we
978  * log the "right" port too, so we know if it's moria1 or moria2.
979  */
980  tor_addr_copy(&conn->base_.addr, &node_ap.addr);
981  conn->base_.port = node_ap.port;
982  }
983  tor_free(conn->nickname);
984  conn->nickname = tor_strdup(node_get_nickname(r));
985  tor_free(conn->base_.address);
986  conn->base_.address = tor_addr_to_str_dup(&node_ap.addr);
987  } else {
988  tor_free(conn->nickname);
989  conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
990  conn->nickname[0] = '$';
992  conn->identity_digest, DIGEST_LEN);
993 
994  tor_free(conn->base_.address);
995  conn->base_.address = tor_addr_to_str_dup(addr);
996  }
997 
998  /*
999  * We have to tell channeltls.c to update the channel marks (local, in
1000  * particular), since we may have changed the address.
1001  */
1002 
1003  if (conn->chan) {
1005  }
1006 }
1007 
1011 static unsigned int
1013 {
1014  tor_assert(or_conn);
1015 
1016  if (or_conn->chan)
1017  return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
1018  else return 0;
1019 }
1020 
1021 static void
1022 connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
1023 {
1024  tor_assert(or_conn);
1025 
1026  if (or_conn->chan)
1027  channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
1028 }
1029 
1032 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
1033 
1040 int
1042  or_connection_t *or_conn,
1043  int force)
1044 {
1045  /* XXXX this function should also be about channels? */
1046  if (or_conn->base_.marked_for_close ||
1048  return 1;
1049 
1050  if (force ||
1052  < now) {
1053  log_info(LD_OR,
1054  "Marking OR conn to %s:%d as too old for new circuits "
1055  "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
1056  or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1057  (int)(now - or_conn->base_.timestamp_created));
1058  connection_or_mark_bad_for_new_circs(or_conn);
1059  }
1060 
1061  return 0;
1062 }
1063 
1081 void
1083 {
1084  /* XXXX this function should be entirely about channels, not OR
1085  * XXXX connections. */
1086 
1087  or_connection_t *best = NULL;
1088  int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
1089  time_t now = time(NULL);
1090 
1091  /* Pass 1: expire everything that's old, and see what the status of
1092  * everything else is. */
1093  SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1094  if (connection_or_single_set_badness_(now, or_conn, force))
1095  continue;
1096 
1097  if (connection_or_is_bad_for_new_circs(or_conn)) {
1098  ++n_old;
1099  } else if (or_conn->base_.state != OR_CONN_STATE_OPEN) {
1100  ++n_inprogress;
1101  } else if (or_conn->is_canonical) {
1102  ++n_canonical;
1103  } else {
1104  ++n_other;
1105  }
1106  } SMARTLIST_FOREACH_END(or_conn);
1107 
1108  /* Pass 2: We know how about how good the best connection is.
1109  * expire everything that's worse, and find the very best if we can. */
1110  SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1111  if (or_conn->base_.marked_for_close ||
1113  continue; /* This one doesn't need to be marked bad. */
1114  if (or_conn->base_.state != OR_CONN_STATE_OPEN)
1115  continue; /* Don't mark anything bad until we have seen what happens
1116  * when the connection finishes. */
1117  if (n_canonical && !or_conn->is_canonical) {
1118  /* We have at least one open canonical connection to this router,
1119  * and this one is open but not canonical. Mark it bad. */
1120  log_info(LD_OR,
1121  "Marking OR conn to %s:%d as unsuitable for new circuits: "
1122  "(fd "TOR_SOCKET_T_FORMAT", %d secs old). It is not "
1123  "canonical, and we have another connection to that OR that is.",
1124  or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1125  (int)(now - or_conn->base_.timestamp_created));
1126  connection_or_mark_bad_for_new_circs(or_conn);
1127  continue;
1128  }
1129 
1130  if (!best ||
1131  channel_is_better(TLS_CHAN_TO_BASE(or_conn->chan),
1132  TLS_CHAN_TO_BASE(best->chan))) {
1133  best = or_conn;
1134  }
1135  } SMARTLIST_FOREACH_END(or_conn);
1136 
1137  if (!best)
1138  return;
1139 
1140  /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
1141  * every other open connection. If it's non-canonical, mark as bad
1142  * every other open connection to the same address.
1143  *
1144  * XXXX This isn't optimal; if we have connections to an OR at multiple
1145  * addresses, we'd like to pick the best _for each address_, and mark as
1146  * bad every open connection that isn't best for its address. But this
1147  * can only occur in cases where the other OR is old (so we have no
1148  * canonical connection to it), or where all the connections to the OR are
1149  * at noncanonical addresses and we have no good direct connection (which
1150  * means we aren't at risk of attaching circuits to it anyway). As
1151  * 0.1.2.x dies out, the first case will go away, and the second one is
1152  * "mostly harmless", so a fix can wait until somebody is bored.
1153  */
1154  SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1155  if (or_conn->base_.marked_for_close ||
1157  or_conn->base_.state != OR_CONN_STATE_OPEN)
1158  continue;
1159  if (or_conn != best &&
1160  channel_is_better(TLS_CHAN_TO_BASE(best->chan),
1161  TLS_CHAN_TO_BASE(or_conn->chan))) {
1162  /* This isn't the best conn, _and_ the best conn is better than it */
1163  if (best->is_canonical) {
1164  log_info(LD_OR,
1165  "Marking OR conn to %s:%d as unsuitable for new circuits: "
1166  "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
1167  "We have a better canonical one "
1168  "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1169  or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1170  (int)(now - or_conn->base_.timestamp_created),
1171  best->base_.s, (int)(now - best->base_.timestamp_created));
1172  connection_or_mark_bad_for_new_circs(or_conn);
1173  } else if (!tor_addr_compare(&or_conn->real_addr,
1174  &best->real_addr, CMP_EXACT)) {
1175  log_info(LD_OR,
1176  "Marking OR conn to %s:%d as unsuitable for new circuits: "
1177  "(fd "TOR_SOCKET_T_FORMAT", %d secs old). We have a better "
1178  "one with the "
1179  "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1180  or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1181  (int)(now - or_conn->base_.timestamp_created),
1182  best->base_.s, (int)(now - best->base_.timestamp_created));
1183  connection_or_mark_bad_for_new_circs(or_conn);
1184  }
1185  }
1186  } SMARTLIST_FOREACH_END(or_conn);
1187 }
1188 
1189 /* Lifetime of a connection failure. After that, we'll retry. This is in
1190  * seconds. */
1191 #define OR_CONNECT_FAILURE_LIFETIME 60
1192 /* The interval to use with when to clean up the failure cache. */
1193 #define OR_CONNECT_FAILURE_CLEANUP_INTERVAL 60
1194 
1195 /* When is the next time we have to cleanup the failure map. We keep this
1196  * because we clean it opportunistically. */
1197 static time_t or_connect_failure_map_next_cleanup_ts = 0;
1198 
1199 /* OR connection failure entry data structure. It is kept in the connection
1200  * failure map defined below and indexed by OR identity digest, address and
1201  * port.
1202  *
1203  * We need to identify a connection failure with these three values because we
1204  * want to avoid to wrongfully blacklist a relay if someone is trying to
1205  * extend to a known identity digest but with the wrong IP/port. For instance,
1206  * it can happen if a relay changed its port but the client still has an old
1207  * descriptor with the old port. We want to stop connecting to that
1208  * IP/port/identity all together, not only the relay identity. */
1210  HT_ENTRY(or_connect_failure_entry_t) node;
1211  /* Identity digest of the connection where it is connecting to. */
1212  uint8_t identity_digest[DIGEST_LEN];
1213  /* This is the connection address from the base connection_t. After the
1214  * connection is checked for canonicity, the base address should represent
1215  * what we know instead of where we are connecting to. This is what we need
1216  * so we can correlate known relays within the consensus. */
1217  tor_addr_t addr;
1218  uint16_t port;
1219  /* Last time we were unable to connect. */
1220  time_t last_failed_connect_ts;
1222 
1223 /* Map where we keep connection failure entries. They are indexed by addr,
1224  * port and identity digest. */
1225 static HT_HEAD(or_connect_failure_ht, or_connect_failure_entry_t)
1226  or_connect_failures_map = HT_INITIALIZER();
1227 
1228 /* Helper: Hashtable equal function. Return 1 if equal else 0. */
1229 static int
1230 or_connect_failure_ht_eq(const or_connect_failure_entry_t *a,
1231  const or_connect_failure_entry_t *b)
1232 {
1233  return fast_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN) &&
1234  tor_addr_eq(&a->addr, &b->addr) &&
1235  a->port == b->port;
1236 }
1237 
1238 /* Helper: Return the hash for the hashtable of the given entry. For this
1239  * table, it is a combination of address, port and identity digest. */
1240 static unsigned int
1241 or_connect_failure_ht_hash(const or_connect_failure_entry_t *entry)
1242 {
1243  size_t offset = 0, addr_size;
1244  const void *addr_ptr;
1245  /* Largest size is IPv6 and IPv4 is smaller so it is fine. */
1246  uint8_t data[16 + sizeof(uint16_t) + DIGEST_LEN];
1247 
1248  /* Get the right address bytes depending on the family. */
1249  switch (tor_addr_family(&entry->addr)) {
1250  case AF_INET:
1251  addr_size = 4;
1252  addr_ptr = &entry->addr.addr.in_addr.s_addr;
1253  break;
1254  case AF_INET6:
1255  addr_size = 16;
1256  addr_ptr = &entry->addr.addr.in6_addr.s6_addr;
1257  break;
1258  default:
1259  tor_assert_nonfatal_unreached();
1260  return 0;
1261  }
1262 
1263  memcpy(data, addr_ptr, addr_size);
1264  offset += addr_size;
1265  memcpy(data + offset, entry->identity_digest, DIGEST_LEN);
1266  offset += DIGEST_LEN;
1267  set_uint16(data + offset, entry->port);
1268  offset += sizeof(uint16_t);
1269 
1270  return (unsigned int) siphash24g(data, offset);
1271 }
1272 
1273 HT_PROTOTYPE(or_connect_failure_ht, or_connect_failure_entry_t, node,
1274  or_connect_failure_ht_hash, or_connect_failure_ht_eq)
1275 
1276 HT_GENERATE2(or_connect_failure_ht, or_connect_failure_entry_t, node,
1277  or_connect_failure_ht_hash, or_connect_failure_ht_eq,
1279 
1280 /* Initialize a given connect failure entry with the given identity_digest,
1281  * addr and port. All field are optional except ocf. */
1282 static void
1283 or_connect_failure_init(const char *identity_digest, const tor_addr_t *addr,
1284  uint16_t port, or_connect_failure_entry_t *ocf)
1285 {
1286  tor_assert(ocf);
1287  if (identity_digest) {
1288  memcpy(ocf->identity_digest, identity_digest,
1289  sizeof(ocf->identity_digest));
1290  }
1291  if (addr) {
1292  tor_addr_copy(&ocf->addr, addr);
1293  }
1294  ocf->port = port;
1295 }
1296 
1297 /* Return a newly allocated connection failure entry. It is initialized with
1298  * the given or_conn data. This can't fail. */
1300 or_connect_failure_new(const or_connection_t *or_conn)
1301 {
1302  or_connect_failure_entry_t *ocf = tor_malloc_zero(sizeof(*ocf));
1303  or_connect_failure_init(or_conn->identity_digest, &or_conn->real_addr,
1304  TO_CONN(or_conn)->port, ocf);
1305  return ocf;
1306 }
1307 
1308 /* Return a connection failure entry matching the given or_conn. NULL is
1309  * returned if not found. */
1311 or_connect_failure_find(const or_connection_t *or_conn)
1312 {
1314  tor_assert(or_conn);
1315  or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
1316  TO_CONN(or_conn)->port, &lookup);
1317  return HT_FIND(or_connect_failure_ht, &or_connect_failures_map, &lookup);
1318 }
1319 
1320 /* Note down in the connection failure cache that a failure occurred on the
1321  * given or_conn. */
1322 STATIC void
1323 note_or_connect_failed(const or_connection_t *or_conn)
1324 {
1325  or_connect_failure_entry_t *ocf = NULL;
1326 
1327  tor_assert(or_conn);
1328 
1329  ocf = or_connect_failure_find(or_conn);
1330  if (ocf == NULL) {
1331  ocf = or_connect_failure_new(or_conn);
1332  HT_INSERT(or_connect_failure_ht, &or_connect_failures_map, ocf);
1333  }
1334  ocf->last_failed_connect_ts = approx_time();
1335 }
1336 
1337 /* Cleanup the connection failure cache and remove all entries below the
1338  * given cutoff. */
1339 static void
1340 or_connect_failure_map_cleanup(time_t cutoff)
1341 {
1342  or_connect_failure_entry_t **ptr, **next, *entry;
1343 
1344  for (ptr = HT_START(or_connect_failure_ht, &or_connect_failures_map);
1345  ptr != NULL; ptr = next) {
1346  entry = *ptr;
1347  if (entry->last_failed_connect_ts <= cutoff) {
1348  next = HT_NEXT_RMV(or_connect_failure_ht, &or_connect_failures_map, ptr);
1349  tor_free(entry);
1350  } else {
1351  next = HT_NEXT(or_connect_failure_ht, &or_connect_failures_map, ptr);
1352  }
1353  }
1354 }
1355 
1356 /* Return true iff the given OR connection can connect to its destination that
1357  * is the triplet identity_digest, address and port.
1358  *
1359  * The or_conn MUST have gone through connection_or_check_canonicity() so the
1360  * base address is properly set to what we know or doesn't know. */
1361 STATIC int
1362 should_connect_to_relay(const or_connection_t *or_conn)
1363 {
1364  time_t now, cutoff;
1365  time_t connect_failed_since_ts = 0;
1367 
1368  tor_assert(or_conn);
1369 
1370  now = approx_time();
1371  cutoff = now - OR_CONNECT_FAILURE_LIFETIME;
1372 
1373  /* Opportunistically try to cleanup the failure cache. We do that at regular
1374  * interval so it doesn't grow too big. */
1375  if (or_connect_failure_map_next_cleanup_ts <= now) {
1376  or_connect_failure_map_cleanup(cutoff);
1377  or_connect_failure_map_next_cleanup_ts =
1378  now + OR_CONNECT_FAILURE_CLEANUP_INTERVAL;
1379  }
1380 
1381  /* Look if we have failed previously to the same destination as this
1382  * OR connection. */
1383  ocf = or_connect_failure_find(or_conn);
1384  if (ocf) {
1385  connect_failed_since_ts = ocf->last_failed_connect_ts;
1386  }
1387  /* If we do have an unable to connect timestamp and it is below cutoff, we
1388  * can connect. Or we have never failed before so let it connect. */
1389  if (connect_failed_since_ts > cutoff) {
1390  goto no_connect;
1391  }
1392 
1393  /* Ok we can connect! */
1394  return 1;
1395  no_connect:
1396  return 0;
1397 }
1398 
1405 void
1407  int reason, const char *msg)
1408 {
1409  connection_or_event_status(conn, OR_CONN_EVENT_FAILED, reason);
1410  if (!authdir_mode_tests_reachability(get_options()))
1411  control_event_bootstrap_prob_or(msg, reason, conn);
1412  note_or_connect_failed(conn);
1413 }
1414 
1421 void
1423  int reason, const char *msg)
1424 {
1425  channel_t *chan;
1426 
1427  tor_assert(conn);
1428 
1429  /* If we're connecting, call connect_failed() too */
1430  if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
1431  connection_or_connect_failed(conn, reason, msg);
1432 
1433  /* Tell the controlling channel if we have one */
1434  if (conn->chan) {
1435  chan = TLS_CHAN_TO_BASE(conn->chan);
1436  /* Don't transition if we're already in closing, closed or error */
1437  if (!CHANNEL_CONDEMNED(chan)) {
1439  }
1440  }
1441 
1442  /* No need to mark for error because connection.c is about to do that */
1443 }
1444 
1462 connection_or_connect, (const tor_addr_t *_addr, uint16_t port,
1463  const char *id_digest,
1464  const ed25519_public_key_t *ed_id,
1465  channel_tls_t *chan))
1466 {
1467  or_connection_t *conn;
1468  const or_options_t *options = get_options();
1469  int socket_error = 0;
1470  tor_addr_t addr;
1471 
1472  int r;
1473  tor_addr_t proxy_addr;
1474  uint16_t proxy_port;
1475  int proxy_type;
1476 
1477  tor_assert(_addr);
1478  tor_assert(id_digest);
1479  tor_addr_copy(&addr, _addr);
1480 
1481  if (server_mode(options) && router_digest_is_me(id_digest)) {
1482  log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
1483  return NULL;
1484  }
1485  if (server_mode(options) && router_ed25519_id_is_me(ed_id)) {
1486  log_info(LD_PROTOCOL,"Client asked me to connect to myself by Ed25519 "
1487  "identity. Refusing.");
1488  return NULL;
1489  }
1490 
1492 
1493  /*
1494  * Set up conn so it's got all the data we need to remember for channels
1495  *
1496  * This stuff needs to happen before connection_or_init_conn_from_address()
1497  * so connection_or_set_identity_digest() and such know where to look to
1498  * keep the channel up to date.
1499  */
1500  conn->chan = chan;
1501  chan->conn = conn;
1502  connection_or_init_conn_from_address(conn, &addr, port, id_digest, ed_id, 1);
1503 
1504  /* We have a proper OR connection setup, now check if we can connect to it
1505  * that is we haven't had a failure earlier. This is to avoid to try to
1506  * constantly connect to relays that we think are not reachable. */
1507  if (!should_connect_to_relay(conn)) {
1508  log_info(LD_GENERAL, "Can't connect to identity %s at %s:%u because we "
1509  "failed earlier. Refusing.",
1510  hex_str(id_digest, DIGEST_LEN), fmt_addr(&TO_CONN(conn)->addr),
1511  TO_CONN(conn)->port);
1512  connection_free_(TO_CONN(conn));
1513  return NULL;
1514  }
1515 
1516  conn->is_outgoing = 1;
1517 
1518  /* If we are using a proxy server, find it and use it. */
1519  r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, TO_CONN(conn));
1520  if (r == 0) {
1521  conn->proxy_type = proxy_type;
1522  if (proxy_type != PROXY_NONE) {
1523  tor_addr_copy(&addr, &proxy_addr);
1524  port = proxy_port;
1525  conn->base_.proxy_state = PROXY_INFANT;
1526  }
1528  connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1529  } else {
1530  /* This duplication of state change calls is necessary in case we
1531  * run into an error condition below */
1533  connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1534 
1535  /* get_proxy_addrport() might fail if we have a Bridge line that
1536  references a transport, but no ClientTransportPlugin lines
1537  defining its transport proxy. If this is the case, let's try to
1538  output a useful log message to the user. */
1539  const char *transport_name =
1541  TO_CONN(conn)->port);
1542 
1543  if (transport_name) {
1544  log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
1545  "using pluggable transport '%s', but we can't find a pluggable "
1546  "transport proxy supporting '%s'. This can happen if you "
1547  "haven't provided a ClientTransportPlugin line, or if "
1548  "your pluggable transport proxy stopped running.",
1549  fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port),
1550  transport_name, transport_name);
1551 
1552  control_event_bootstrap_prob_or(
1553  "Can't connect to bridge",
1554  END_OR_CONN_REASON_PT_MISSING,
1555  conn);
1556 
1557  } else {
1558  log_warn(LD_GENERAL, "Tried to connect to '%s' through a proxy, but "
1559  "the proxy address could not be found.",
1560  fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port));
1561  }
1562 
1563  connection_free_(TO_CONN(conn));
1564  return NULL;
1565  }
1566 
1567  switch (connection_connect(TO_CONN(conn), conn->base_.address,
1568  &addr, port, &socket_error)) {
1569  case -1:
1570  /* We failed to establish a connection probably because of a local
1571  * error. No need to blame the guard in this case. Notify the networking
1572  * system of this failure. */
1574  errno_to_orconn_end_reason(socket_error),
1575  tor_socket_strerror(socket_error));
1576  connection_free_(TO_CONN(conn));
1577  return NULL;
1578  case 0:
1580  /* writable indicates finish, readable indicates broken link,
1581  error indicates broken link on windows */
1582  return conn;
1583  /* case 1: fall through */
1584  }
1585 
1586  if (connection_or_finished_connecting(conn) < 0) {
1587  /* already marked for close */
1588  return NULL;
1589  }
1590  return conn;
1591 }
1592 
1607 void
1609 {
1610  channel_t *chan = NULL;
1611 
1612  tor_assert(orconn);
1613  if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1614  else connection_mark_for_close_internal(TO_CONN(orconn));
1615  if (orconn->chan) {
1616  chan = TLS_CHAN_TO_BASE(orconn->chan);
1617  /* Don't transition if we're already in closing, closed or error */
1618  if (!CHANNEL_CONDEMNED(chan)) {
1620  }
1621  }
1622 }
1623 
1629 connection_or_close_for_error,(or_connection_t *orconn, int flush))
1630 {
1631  channel_t *chan = NULL;
1632 
1633  tor_assert(orconn);
1634  if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1635  else connection_mark_for_close_internal(TO_CONN(orconn));
1636  if (orconn->chan) {
1637  chan = TLS_CHAN_TO_BASE(orconn->chan);
1638  /* Don't transition if we're already in closing, closed or error */
1639  if (!CHANNEL_CONDEMNED(chan)) {
1641  }
1642  }
1643 }
1644 
1654 connection_tls_start_handshake,(or_connection_t *conn, int receiving))
1655 {
1656  channel_listener_t *chan_listener;
1657  channel_t *chan;
1658 
1659  /* Incoming connections will need a new channel passed to the
1660  * channel_tls_listener */
1661  if (receiving) {
1662  /* It shouldn't already be set */
1663  tor_assert(!(conn->chan));
1664  chan_listener = channel_tls_get_listener();
1665  if (!chan_listener) {
1666  chan_listener = channel_tls_start_listener();
1667  command_setup_listener(chan_listener);
1668  }
1669  chan = channel_tls_handle_incoming(conn);
1670  channel_listener_queue_incoming(chan_listener, chan);
1671  }
1672 
1674  tor_assert(!conn->tls);
1675  conn->tls = tor_tls_new(conn->base_.s, receiving);
1676  if (!conn->tls) {
1677  log_warn(LD_BUG,"tor_tls_new failed. Closing.");
1678  return -1;
1679  }
1680  tor_tls_set_logged_address(conn->tls, // XXX client and relay?
1681  escaped_safe_str(conn->base_.address));
1682 
1683  connection_start_reading(TO_CONN(conn));
1684  log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
1685  conn->base_.s);
1686 
1687  if (connection_tls_continue_handshake(conn) < 0)
1688  return -1;
1689 
1690  return 0;
1691 }
1692 
1694 void
1696 {
1697  tor_tls_t *tls = conn->tls;
1698  if (!tls)
1699  return;
1700  tor_tls_set_renegotiate_callback(tls, NULL, NULL);
1702 }
1703 
1706 static void
1708 {
1709  or_connection_t *conn = _conn;
1710  (void)tls;
1711 
1712  /* Don't invoke this again. */
1714 
1715  if (connection_tls_finish_handshake(conn) < 0) {
1716  /* XXXX_TLS double-check that it's ok to do this from inside read. */
1717  /* XXXX_TLS double-check that this verifies certificates. */
1718  connection_or_close_for_error(conn, 0);
1719  }
1720 }
1721 
1727 int
1729 {
1730  int result;
1731  check_no_tls_errors();
1732 
1734  // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
1735  result = tor_tls_handshake(conn->tls);
1736  // log_notice(LD_OR, "Result: %d", result);
1737 
1738  switch (result) {
1740  log_info(LD_OR,"tls error [%s]. breaking connection.",
1741  tor_tls_err_to_string(result));
1742  return -1;
1743  case TOR_TLS_DONE:
1744  if (! tor_tls_used_v1_handshake(conn->tls)) {
1745  if (!tor_tls_is_server(conn->tls)) {
1748  } else {
1749  /* v2/v3 handshake, but we are not a client. */
1750  log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
1751  "Expecting renegotiation or VERSIONS cell");
1754  conn);
1757  connection_stop_writing(TO_CONN(conn));
1758  connection_start_reading(TO_CONN(conn));
1759  return 0;
1760  }
1761  }
1763  return connection_tls_finish_handshake(conn);
1764  case TOR_TLS_WANTWRITE:
1765  connection_start_writing(TO_CONN(conn));
1766  log_debug(LD_OR,"wanted write");
1767  return 0;
1768  case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
1769  log_debug(LD_OR,"wanted read");
1770  return 0;
1771  case TOR_TLS_CLOSE:
1772  log_info(LD_OR,"tls closed. breaking connection.");
1773  return -1;
1774  }
1775  return 0;
1776 }
1777 
1781 int
1783 {
1784  tor_assert(conn->base_.type == CONN_TYPE_OR ||
1785  conn->base_.type == CONN_TYPE_EXT_OR);
1786  if (!conn->tls)
1787  return 1; /* it's still in proxy states or something */
1788  if (conn->handshake_state)
1789  return conn->handshake_state->started_here;
1790  return !tor_tls_is_server(conn->tls);
1791 }
1792 
1818 static int
1820  int started_here,
1821  char *digest_rcvd_out)
1822 {
1823  crypto_pk_t *identity_rcvd=NULL;
1824  const or_options_t *options = get_options();
1825  int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1826  const char *safe_address =
1827  started_here ? conn->base_.address :
1828  safe_str_client(conn->base_.address);
1829  const char *conn_type = started_here ? "outgoing" : "incoming";
1830  int has_cert = 0;
1831 
1832  check_no_tls_errors();
1833  has_cert = tor_tls_peer_has_cert(conn->tls);
1834  if (started_here && !has_cert) {
1835  log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
1836  "send a cert! Closing.",
1837  safe_address, conn->base_.port);
1838  return -1;
1839  } else if (!has_cert) {
1840  log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
1841  "That's ok.");
1842  }
1843  check_no_tls_errors();
1844 
1845  if (has_cert) {
1846  int v = tor_tls_verify(started_here?severity:LOG_INFO,
1847  conn->tls, &identity_rcvd);
1848  if (started_here && v<0) {
1849  log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
1850  " has a cert but it's invalid. Closing.",
1851  safe_address, conn->base_.port);
1852  return -1;
1853  } else if (v<0) {
1854  log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
1855  "chain; ignoring.");
1856  } else {
1857  log_debug(LD_HANDSHAKE,
1858  "The certificate seems to be valid on %s connection "
1859  "with %s:%d", conn_type, safe_address, conn->base_.port);
1860  }
1861  check_no_tls_errors();
1862  }
1863 
1864  if (identity_rcvd) {
1865  if (crypto_pk_get_digest(identity_rcvd, digest_rcvd_out) < 0) {
1866  crypto_pk_free(identity_rcvd);
1867  return -1;
1868  }
1869  } else {
1870  memset(digest_rcvd_out, 0, DIGEST_LEN);
1871  }
1872 
1873  tor_assert(conn->chan);
1874  channel_set_circid_type(TLS_CHAN_TO_BASE(conn->chan), identity_rcvd, 1);
1875 
1876  crypto_pk_free(identity_rcvd);
1877 
1878  if (started_here) {
1879  /* A TLS handshake can't teach us an Ed25519 ID, so we set it to NULL
1880  * here. */
1881  log_debug(LD_HANDSHAKE, "Calling client_learned_peer_id from "
1882  "check_valid_tls_handshake");
1884  (const uint8_t*)digest_rcvd_out,
1885  NULL);
1886  }
1887 
1888  return 0;
1889 }
1890 
1915 int
1917  const uint8_t *rsa_peer_id,
1918  const ed25519_public_key_t *ed_peer_id)
1919 {
1920  const or_options_t *options = get_options();
1921  channel_tls_t *chan_tls = conn->chan;
1922  channel_t *chan = channel_tls_to_base(chan_tls);
1923  int changed_identity = 0;
1924  tor_assert(chan);
1925 
1926  const int expected_rsa_key =
1928  const int expected_ed_key =
1930 
1931  log_info(LD_HANDSHAKE, "learned peer id for %p (%s): %s, %s",
1932  conn,
1933  safe_str_client(conn->base_.address),
1934  hex_str((const char*)rsa_peer_id, DIGEST_LEN),
1935  ed25519_fmt(ed_peer_id));
1936 
1937  if (! expected_rsa_key && ! expected_ed_key) {
1938  log_info(LD_HANDSHAKE, "(we had no ID in mind when we made this "
1939  "connection.");
1941  (const char*)rsa_peer_id, ed_peer_id);
1942  tor_free(conn->nickname);
1943  conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1944  conn->nickname[0] = '$';
1946  conn->identity_digest, DIGEST_LEN);
1947  log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
1948  "its key. Hoping for the best.",
1949  conn->nickname, conn->base_.address, conn->base_.port);
1950  /* if it's a bridge and we didn't know its identity fingerprint, now
1951  * we do -- remember it for future attempts. */
1952  learned_router_identity(&conn->base_.addr, conn->base_.port,
1953  (const char*)rsa_peer_id, ed_peer_id);
1954  changed_identity = 1;
1955  }
1956 
1957  const int rsa_mismatch = expected_rsa_key &&
1958  tor_memneq(rsa_peer_id, conn->identity_digest, DIGEST_LEN);
1959  /* It only counts as an ed25519 mismatch if we wanted an ed25519 identity
1960  * and didn't get it. It's okay if we get one that we didn't ask for. */
1961  const int ed25519_mismatch =
1962  expected_ed_key &&
1963  (ed_peer_id == NULL ||
1964  ! ed25519_pubkey_eq(&chan->ed25519_identity, ed_peer_id));
1965 
1966  if (rsa_mismatch || ed25519_mismatch) {
1967  /* I was aiming for a particular digest. I didn't get it! */
1968  char seen_rsa[HEX_DIGEST_LEN+1];
1969  char expected_rsa[HEX_DIGEST_LEN+1];
1970  char seen_ed[ED25519_BASE64_LEN+1];
1971  char expected_ed[ED25519_BASE64_LEN+1];
1972  base16_encode(seen_rsa, sizeof(seen_rsa),
1973  (const char*)rsa_peer_id, DIGEST_LEN);
1974  base16_encode(expected_rsa, sizeof(expected_rsa), conn->identity_digest,
1975  DIGEST_LEN);
1976  if (ed_peer_id) {
1977  ed25519_public_to_base64(seen_ed, ed_peer_id);
1978  } else {
1979  strlcpy(seen_ed, "no ed25519 key", sizeof(seen_ed));
1980  }
1982  ed25519_public_to_base64(expected_ed, &chan->ed25519_identity);
1983  } else {
1984  strlcpy(expected_ed, "no ed25519 key", sizeof(expected_ed));
1985  }
1986  const int using_hardcoded_fingerprints =
1987  !networkstatus_get_reasonably_live_consensus(time(NULL),
1988  usable_consensus_flavor());
1989  const int is_fallback_fingerprint = router_digest_is_fallback_dir(
1990  conn->identity_digest);
1991  const int is_authority_fingerprint = router_digest_is_trusted_dir(
1992  conn->identity_digest);
1993  const int non_anonymous_mode = rend_non_anonymous_mode_enabled(options);
1994  int severity;
1995  const char *extra_log = "";
1996 
1997  /* Relays and Single Onion Services make direct connections using
1998  * untrusted authentication keys. */
1999  if (server_mode(options) || non_anonymous_mode) {
2000  severity = LOG_PROTOCOL_WARN;
2001  } else {
2002  if (using_hardcoded_fingerprints) {
2003  /* We need to do the checks in this order, because the list of
2004  * fallbacks includes the list of authorities */
2005  if (is_authority_fingerprint) {
2006  severity = LOG_WARN;
2007  } else if (is_fallback_fingerprint) {
2008  /* we expect a small number of fallbacks to change from their
2009  * hard-coded fingerprints over the life of a release */
2010  severity = LOG_INFO;
2011  extra_log = " Tor will try a different fallback.";
2012  } else {
2013  /* it's a bridge, it's either a misconfiguration, or unexpected */
2014  severity = LOG_WARN;
2015  }
2016  } else {
2017  /* a relay has changed its fingerprint from the one in the consensus */
2018  severity = LOG_WARN;
2019  }
2020  }
2021 
2022  log_fn(severity, LD_HANDSHAKE,
2023  "Tried connecting to router at %s:%d, but RSA + ed25519 identity "
2024  "keys were not as expected: wanted %s + %s but got %s + %s.%s",
2025  conn->base_.address, conn->base_.port,
2026  expected_rsa, expected_ed, seen_rsa, seen_ed, extra_log);
2027 
2028  /* Tell the new guard API about the channel failure */
2029  entry_guard_chan_failed(TLS_CHAN_TO_BASE(conn->chan));
2030  connection_or_event_status(conn, OR_CONN_EVENT_FAILED,
2031  END_OR_CONN_REASON_OR_IDENTITY);
2032  if (!authdir_mode_tests_reachability(options))
2033  control_event_bootstrap_prob_or(
2034  "Unexpected identity in router certificate",
2035  END_OR_CONN_REASON_OR_IDENTITY,
2036  conn);
2037  return -1;
2038  }
2039 
2040  if (!expected_ed_key && ed_peer_id) {
2041  log_info(LD_HANDSHAKE, "(We had no Ed25519 ID in mind when we made this "
2042  "connection.)");
2044  (const char*)rsa_peer_id, ed_peer_id);
2045  changed_identity = 1;
2046  }
2047 
2048  if (changed_identity) {
2049  /* If we learned an identity for this connection, then we might have
2050  * just discovered it to be canonical. */
2052  }
2053 
2054  if (authdir_mode_tests_reachability(options)) {
2055  dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
2056  (const char*)rsa_peer_id, ed_peer_id);
2057  }
2058 
2059  return 0;
2060 }
2061 
2066 time_t
2068 {
2069  tor_assert(conn);
2070 
2071  if (conn->chan) {
2072  return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
2073  } else return 0;
2074 }
2075 
2089 static int
2091 {
2092  char digest_rcvd[DIGEST_LEN];
2093  int started_here = connection_or_nonopen_was_started_here(conn);
2094 
2095  tor_assert(!started_here);
2096 
2097  log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done, using "
2098  "ciphersuite %s. verifying.",
2099  started_here?"outgoing":"incoming",
2100  conn,
2101  safe_str_client(conn->base_.address),
2102  tor_tls_get_ciphersuite_name(conn->tls));
2103 
2104  if (connection_or_check_valid_tls_handshake(conn, started_here,
2105  digest_rcvd) < 0)
2106  return -1;
2107 
2109 
2110  if (tor_tls_used_v1_handshake(conn->tls)) {
2111  conn->link_proto = 1;
2112  connection_or_init_conn_from_address(conn, &conn->base_.addr,
2113  conn->base_.port, digest_rcvd,
2114  NULL, 0);
2116  rep_hist_note_negotiated_link_proto(1, started_here);
2117  return connection_or_set_state_open(conn);
2118  } else {
2120  if (connection_init_or_handshake_state(conn, started_here) < 0)
2121  return -1;
2122  connection_or_init_conn_from_address(conn, &conn->base_.addr,
2123  conn->base_.port, digest_rcvd,
2124  NULL, 0);
2125  return connection_or_send_versions(conn, 0);
2126  }
2127 }
2128 
2135 static int
2137 {
2139 
2141 
2143  if (connection_init_or_handshake_state(conn, 1) < 0)
2144  return -1;
2145 
2146  return connection_or_send_versions(conn, 1);
2147 }
2148 
2151 int
2153 {
2155  if (conn->handshake_state) {
2156  log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
2157  return 0;
2158  }
2159  s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
2160  s->started_here = started_here ? 1 : 0;
2161  s->digest_sent_data = 1;
2162  s->digest_received_data = 1;
2163  if (! started_here && get_current_link_cert_cert()) {
2164  s->own_link_cert = tor_cert_dup(get_current_link_cert_cert());
2165  }
2167  s->certs->started_here = s->started_here;
2168  return 0;
2169 }
2170 
2172 void
2174 {
2175  if (!state)
2176  return;
2177  crypto_digest_free(state->digest_sent);
2178  crypto_digest_free(state->digest_received);
2179  or_handshake_certs_free(state->certs);
2180  tor_cert_free(state->own_link_cert);
2181  memwipe(state, 0xBE, sizeof(or_handshake_state_t));
2182  tor_free(state);
2183 }
2184 
2194 void
2196  or_handshake_state_t *state,
2197  const cell_t *cell,
2198  int incoming)
2199 {
2200  size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2201  crypto_digest_t *d, **dptr;
2202  packed_cell_t packed;
2203  if (incoming) {
2204  if (!state->digest_received_data)
2205  return;
2206  } else {
2207  if (!state->digest_sent_data)
2208  return;
2209  }
2210  if (!incoming) {
2211  log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
2212  "while making a handshake digest. But we think we are sending "
2213  "one with type %d.", (int)cell->command);
2214  }
2215  dptr = incoming ? &state->digest_received : &state->digest_sent;
2216  if (! *dptr)
2217  *dptr = crypto_digest256_new(DIGEST_SHA256);
2218 
2219  d = *dptr;
2220  /* Re-packing like this is a little inefficient, but we don't have to do
2221  this very often at all. */
2222  cell_pack(&packed, cell, conn->wide_circ_ids);
2223  crypto_digest_add_bytes(d, packed.body, cell_network_size);
2224  memwipe(&packed, 0, sizeof(packed));
2225 }
2226 
2235 void
2237  or_handshake_state_t *state,
2238  const var_cell_t *cell,
2239  int incoming)
2240 {
2241  crypto_digest_t *d, **dptr;
2242  int n;
2243  char buf[VAR_CELL_MAX_HEADER_SIZE];
2244  if (incoming) {
2245  if (!state->digest_received_data)
2246  return;
2247  } else {
2248  if (!state->digest_sent_data)
2249  return;
2250  }
2251  dptr = incoming ? &state->digest_received : &state->digest_sent;
2252  if (! *dptr)
2253  *dptr = crypto_digest256_new(DIGEST_SHA256);
2254 
2255  d = *dptr;
2256 
2257  n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
2258  crypto_digest_add_bytes(d, buf, n);
2259  crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
2260 
2261  memwipe(buf, 0, sizeof(buf));
2262 }
2263 
2267 int
2269 {
2271  connection_or_event_status(conn, OR_CONN_EVENT_CONNECTED, 0);
2272 
2273  /* Link protocol 3 appeared in Tor 0.2.3.6-alpha, so any connection
2274  * that uses an earlier link protocol should not be treated as a relay. */
2275  if (conn->link_proto < 3) {
2276  channel_mark_client(TLS_CHAN_TO_BASE(conn->chan));
2277  }
2278 
2279  or_handshake_state_free(conn->handshake_state);
2280  conn->handshake_state = NULL;
2281  connection_start_reading(TO_CONN(conn));
2282 
2283  return 0;
2284 }
2285 
2290 void
2292 {
2293  packed_cell_t networkcell;
2294  size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2295 
2296  tor_assert(cell);
2297  tor_assert(conn);
2298 
2299  cell_pack(&networkcell, cell, conn->wide_circ_ids);
2300 
2302  if (cell->command == CELL_PADDING)
2304 
2305  connection_buf_add(networkcell.body, cell_network_size, TO_CONN(conn));
2306 
2307  /* Touch the channel's active timestamp if there is one */
2308  if (conn->chan) {
2309  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2310 
2311  if (TLS_CHAN_TO_BASE(conn->chan)->currently_padding) {
2313  if (cell->command == CELL_PADDING)
2315  }
2316  }
2317 
2318  if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2319  or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
2320 }
2321 
2327 connection_or_write_var_cell_to_buf,(const var_cell_t *cell,
2328  or_connection_t *conn))
2329 {
2330  int n;
2331  char hdr[VAR_CELL_MAX_HEADER_SIZE];
2332  tor_assert(cell);
2333  tor_assert(conn);
2334  n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
2335  connection_buf_add(hdr, n, TO_CONN(conn));
2336  connection_buf_add((char*)cell->payload,
2337  cell->payload_len, TO_CONN(conn));
2338  if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2340 
2341  /* Touch the channel's active timestamp if there is one */
2342  if (conn->chan)
2343  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2344 }
2345 
2348 static int
2350 {
2351  connection_t *conn = TO_CONN(or_conn);
2352  return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
2353 }
2354 
2362 static int
2364 {
2365  var_cell_t *var_cell;
2366 
2367  /*
2368  * Note on memory management for incoming cells: below the channel layer,
2369  * we shouldn't need to consider its internal queueing/copying logic. It
2370  * is safe to pass cells to it on the stack or on the heap, but in the
2371  * latter case we must be sure we free them later.
2372  *
2373  * The incoming cell queue code in channel.c will (in the common case)
2374  * decide it can pass them to the upper layer immediately, in which case
2375  * those functions may run directly on the cell pointers we pass here, or
2376  * it may decide to queue them, in which case it will allocate its own
2377  * buffer and copy the cell.
2378  */
2379 
2380  while (1) {
2381  log_debug(LD_OR,
2382  TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
2383  "(%d pending in tls object).",
2384  conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
2386  if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
2387  if (!var_cell)
2388  return 0; /* not yet. */
2389 
2390  /* Touch the channel's active timestamp if there is one */
2391  if (conn->chan)
2392  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2393 
2395  channel_tls_handle_var_cell(var_cell, conn);
2396  var_cell_free(var_cell);
2397  } else {
2398  const int wide_circ_ids = conn->wide_circ_ids;
2399  size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2400  char buf[CELL_MAX_NETWORK_SIZE];
2401  cell_t cell;
2402  if (connection_get_inbuf_len(TO_CONN(conn))
2403  < cell_network_size) /* whole response available? */
2404  return 0; /* not yet */
2405 
2406  /* Touch the channel's active timestamp if there is one */
2407  if (conn->chan)
2408  channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2409 
2411  connection_buf_get_bytes(buf, cell_network_size, TO_CONN(conn));
2412 
2413  /* retrieve cell info from buf (create the host-order struct from the
2414  * network-order string) */
2415  cell_unpack(&cell, buf, wide_circ_ids);
2416 
2417  channel_tls_handle_cell(&cell, conn);
2418  }
2419  }
2420 }
2421 
2423 static const uint16_t or_protocol_versions[] = { 1, 2, 3, 4, 5 };
2425 static const int n_or_protocol_versions =
2426  (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
2427 
2430 int
2432 {
2433  int i;
2434  for (i = 0; i < n_or_protocol_versions; ++i) {
2435  if (or_protocol_versions[i] == v)
2436  return 1;
2437  }
2438  return 0;
2439 }
2440 
2449 int
2451 {
2452  var_cell_t *cell;
2453  int i;
2454  int n_versions = 0;
2455  const int min_version = v3_plus ? 3 : 0;
2456  const int max_version = v3_plus ? UINT16_MAX : 2;
2457  tor_assert(conn->handshake_state &&
2460  cell->command = CELL_VERSIONS;
2461  for (i = 0; i < n_or_protocol_versions; ++i) {
2462  uint16_t v = or_protocol_versions[i];
2463  if (v < min_version || v > max_version)
2464  continue;
2465  set_uint16(cell->payload+(2*n_versions), htons(v));
2466  ++n_versions;
2467  }
2468  cell->payload_len = n_versions * 2;
2469 
2470  connection_or_write_var_cell_to_buf(cell, conn);
2471  conn->handshake_state->sent_versions_at = time(NULL);
2472 
2473  var_cell_free(cell);
2474  return 0;
2475 }
2476 
2477 static netinfo_addr_t *
2478 netinfo_addr_from_tor_addr(const tor_addr_t *tor_addr)
2479 {
2480  sa_family_t addr_family = tor_addr_family(tor_addr);
2481 
2482  if (BUG(addr_family != AF_INET && addr_family != AF_INET6))
2483  return NULL;
2484 
2485  netinfo_addr_t *netinfo_addr = netinfo_addr_new();
2486 
2487  if (addr_family == AF_INET) {
2488  netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV4);
2489  netinfo_addr_set_len(netinfo_addr, 4);
2490  netinfo_addr_set_addr_ipv4(netinfo_addr, tor_addr_to_ipv4h(tor_addr));
2491  } else if (addr_family == AF_INET6) {
2492  netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV6);
2493  netinfo_addr_set_len(netinfo_addr, 16);
2494  uint8_t *ipv6_buf = netinfo_addr_getarray_addr_ipv6(netinfo_addr);
2495  const uint8_t *in6_addr = tor_addr_to_in6_addr8(tor_addr);
2496  memcpy(ipv6_buf, in6_addr, 16);
2497  }
2498 
2499  return netinfo_addr;
2500 }
2501 
2505 connection_or_send_netinfo,(or_connection_t *conn))
2506 {
2507  cell_t cell;
2508  time_t now = time(NULL);
2509  const routerinfo_t *me;
2510  int r = -1;
2511 
2512  tor_assert(conn->handshake_state);
2513 
2514  if (conn->handshake_state->sent_netinfo) {
2515  log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
2516  "where we already sent one.");
2517  return 0;
2518  }
2519 
2520  memset(&cell, 0, sizeof(cell_t));
2521  cell.command = CELL_NETINFO;
2522 
2523  netinfo_cell_t *netinfo_cell = netinfo_cell_new();
2524 
2525  /* Timestamp, if we're a relay. */
2526  if (public_server_mode(get_options()) || ! conn->is_outgoing)
2527  netinfo_cell_set_timestamp(netinfo_cell, (uint32_t)now);
2528 
2529  /* Their address. */
2530  const tor_addr_t *remote_tor_addr =
2531  !tor_addr_is_null(&conn->real_addr) ? &conn->real_addr : &conn->base_.addr;
2532  /* We use &conn->real_addr below, unless it hasn't yet been set. If it
2533  * hasn't yet been set, we know that base_.addr hasn't been tampered with
2534  * yet either. */
2535  netinfo_addr_t *their_addr = netinfo_addr_from_tor_addr(remote_tor_addr);
2536 
2537  netinfo_cell_set_other_addr(netinfo_cell, their_addr);
2538 
2539  /* My address -- only include it if I'm a public relay, or if I'm a
2540  * bridge and this is an incoming connection. If I'm a bridge and this
2541  * is an outgoing connection, act like a normal client and omit it. */
2542  if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
2543  (me = router_get_my_routerinfo())) {
2544  tor_addr_t my_addr;
2545  tor_addr_from_ipv4h(&my_addr, me->addr);
2546 
2547  uint8_t n_my_addrs = 1 + !tor_addr_is_null(&me->ipv6_addr);
2548  netinfo_cell_set_n_my_addrs(netinfo_cell, n_my_addrs);
2549 
2550  netinfo_cell_add_my_addrs(netinfo_cell,
2551  netinfo_addr_from_tor_addr(&my_addr));
2552 
2553  if (!tor_addr_is_null(&me->ipv6_addr)) {
2554  netinfo_cell_add_my_addrs(netinfo_cell,
2555  netinfo_addr_from_tor_addr(&me->ipv6_addr));
2556  }
2557  }
2558 
2559  const char *errmsg = NULL;
2560  if ((errmsg = netinfo_cell_check(netinfo_cell))) {
2561  log_warn(LD_OR, "Failed to validate NETINFO cell with error: %s",
2562  errmsg);
2563  goto cleanup;
2564  }
2565 
2566  if (netinfo_cell_encode(cell.payload, CELL_PAYLOAD_SIZE,
2567  netinfo_cell) < 0) {
2568  log_warn(LD_OR, "Failed generating NETINFO cell");
2569  goto cleanup;
2570  }
2571 
2572  conn->handshake_state->digest_sent_data = 0;
2573  conn->handshake_state->sent_netinfo = 1;
2574  connection_or_write_cell_to_buf(&cell, conn);
2575 
2576  r = 0;
2577  cleanup:
2578  netinfo_cell_free(netinfo_cell);
2579 
2580  return r;
2581 }
2582 
2584 static void
2585 add_certs_cell_cert_helper(certs_cell_t *certs_cell,
2586  uint8_t cert_type,
2587  const uint8_t *cert_encoded,
2588  size_t cert_len)
2589 {
2590  tor_assert(cert_len <= UINT16_MAX);
2591  certs_cell_cert_t *ccc = certs_cell_cert_new();
2592  ccc->cert_type = cert_type;
2593  ccc->cert_len = cert_len;
2594  certs_cell_cert_setlen_body(ccc, cert_len);
2595  memcpy(certs_cell_cert_getarray_body(ccc), cert_encoded, cert_len);
2596 
2597  certs_cell_add_certs(certs_cell, ccc);
2598 }
2599 
2604 static void
2605 add_x509_cert(certs_cell_t *certs_cell,
2606  uint8_t cert_type,
2607  const tor_x509_cert_t *cert)
2608 {
2609  if (NULL == cert)
2610  return;
2611 
2612  const uint8_t *cert_encoded = NULL;
2613  size_t cert_len;
2614  tor_x509_cert_get_der(cert, &cert_encoded, &cert_len);
2615 
2616  add_certs_cell_cert_helper(certs_cell, cert_type, cert_encoded, cert_len);
2617 }
2618 
2622 static void
2623 add_ed25519_cert(certs_cell_t *certs_cell,
2624  uint8_t cert_type,
2625  const tor_cert_t *cert)
2626 {
2627  if (NULL == cert)
2628  return;
2629 
2630  add_certs_cell_cert_helper(certs_cell, cert_type,
2631  cert->encoded, cert->encoded_len);
2632 }
2633 
2634 #ifdef TOR_UNIT_TESTS
2635 int certs_cell_ed25519_disabled_for_testing = 0;
2636 #else
2637 #define certs_cell_ed25519_disabled_for_testing 0
2638 #endif
2639 
2642 int
2644 {
2645  const tor_x509_cert_t *global_link_cert = NULL, *id_cert = NULL;
2646  tor_x509_cert_t *own_link_cert = NULL;
2647  var_cell_t *cell;
2648 
2649  certs_cell_t *certs_cell = NULL;
2650 
2652 
2653  if (! conn->handshake_state)
2654  return -1;
2655 
2656  const int conn_in_server_mode = ! conn->handshake_state->started_here;
2657 
2658  /* Get the encoded values of the X509 certificates */
2659  if (tor_tls_get_my_certs(conn_in_server_mode,
2660  &global_link_cert, &id_cert) < 0)
2661  return -1;
2662 
2663  if (conn_in_server_mode) {
2664  own_link_cert = tor_tls_get_own_cert(conn->tls);
2665  }
2666  tor_assert(id_cert);
2667 
2668  certs_cell = certs_cell_new();
2669 
2670  /* Start adding certs. First the link cert or auth1024 cert. */
2671  if (conn_in_server_mode) {
2672  tor_assert_nonfatal(own_link_cert);
2673  add_x509_cert(certs_cell,
2674  OR_CERT_TYPE_TLS_LINK, own_link_cert);
2675  } else {
2676  tor_assert(global_link_cert);
2677  add_x509_cert(certs_cell,
2678  OR_CERT_TYPE_AUTH_1024, global_link_cert);
2679  }
2680 
2681  /* Next the RSA->RSA ID cert */
2682  add_x509_cert(certs_cell,
2683  OR_CERT_TYPE_ID_1024, id_cert);
2684 
2685  /* Next the Ed25519 certs */
2686  add_ed25519_cert(certs_cell,
2687  CERTTYPE_ED_ID_SIGN,
2688  get_master_signing_key_cert());
2689  if (conn_in_server_mode) {
2690  tor_assert_nonfatal(conn->handshake_state->own_link_cert ||
2691  certs_cell_ed25519_disabled_for_testing);
2692  add_ed25519_cert(certs_cell,
2693  CERTTYPE_ED_SIGN_LINK,
2695  } else {
2696  add_ed25519_cert(certs_cell,
2697  CERTTYPE_ED_SIGN_AUTH,
2698  get_current_auth_key_cert());
2699  }
2700 
2701  /* And finally the crosscert. */
2702  {
2703  const uint8_t *crosscert=NULL;
2704  size_t crosscert_len;
2705  get_master_rsa_crosscert(&crosscert, &crosscert_len);
2706  if (crosscert) {
2707  add_certs_cell_cert_helper(certs_cell,
2708  CERTTYPE_RSA1024_ID_EDID,
2709  crosscert, crosscert_len);
2710  }
2711  }
2712 
2713  /* We've added all the certs; make the cell. */
2714  certs_cell->n_certs = certs_cell_getlen_certs(certs_cell);
2715 
2716  ssize_t alloc_len = certs_cell_encoded_len(certs_cell);
2717  tor_assert(alloc_len >= 0 && alloc_len <= UINT16_MAX);
2718  cell = var_cell_new(alloc_len);
2719  cell->command = CELL_CERTS;
2720  ssize_t enc_len = certs_cell_encode(cell->payload, alloc_len, certs_cell);
2721  tor_assert(enc_len > 0 && enc_len <= alloc_len);
2722  cell->payload_len = enc_len;
2723 
2724  connection_or_write_var_cell_to_buf(cell, conn);
2725  var_cell_free(cell);
2726  certs_cell_free(certs_cell);
2727  tor_x509_cert_free(own_link_cert);
2728 
2729  return 0;
2730 }
2731 
2732 #ifdef TOR_UNIT_TESTS
2733 int testing__connection_or_pretend_TLSSECRET_is_supported = 0;
2734 #else
2735 #define testing__connection_or_pretend_TLSSECRET_is_supported 0
2736 #endif
2737 
2740 int
2741 authchallenge_type_is_supported(uint16_t challenge_type)
2742 {
2743  switch (challenge_type) {
2745 #ifdef HAVE_WORKING_TOR_TLS_GET_TLSSECRETS
2746  return 1;
2747 #else
2748  return testing__connection_or_pretend_TLSSECRET_is_supported;
2749 #endif
2751  return 1;
2753  default:
2754  return 0;
2755  }
2756 }
2757 
2760 int
2761 authchallenge_type_is_better(uint16_t challenge_type_a,
2762  uint16_t challenge_type_b)
2763 {
2764  /* Any supported type is better than an unsupported one;
2765  * all unsupported types are equally bad. */
2766  if (!authchallenge_type_is_supported(challenge_type_a))
2767  return 0;
2768  if (!authchallenge_type_is_supported(challenge_type_b))
2769  return 1;
2770  /* It happens that types are superior in numerically ascending order.
2771  * If that ever changes, this must change too. */
2772  return (challenge_type_a > challenge_type_b);
2773 }
2774 
2777 int
2779 {
2780  var_cell_t *cell = NULL;
2781  int r = -1;
2783 
2784  if (! conn->handshake_state)
2785  return -1;
2786 
2787  auth_challenge_cell_t *ac = auth_challenge_cell_new();
2788 
2789  tor_assert(sizeof(ac->challenge) == 32);
2790  crypto_rand((char*)ac->challenge, sizeof(ac->challenge));
2791 
2793  auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_TLSSECRET);
2794  /* Disabled, because everything that supports this method also supports
2795  * the much-superior ED25519_SHA256_RFC5705 */
2796  /* auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_RFC5705); */
2798  auth_challenge_cell_add_methods(ac, AUTHTYPE_ED25519_SHA256_RFC5705);
2799  auth_challenge_cell_set_n_methods(ac,
2800  auth_challenge_cell_getlen_methods(ac));
2801 
2802  cell = var_cell_new(auth_challenge_cell_encoded_len(ac));
2803  ssize_t len = auth_challenge_cell_encode(cell->payload, cell->payload_len,
2804  ac);
2805  if (len != cell->payload_len) {
2806  /* LCOV_EXCL_START */
2807  log_warn(LD_BUG, "Encoded auth challenge cell length not as expected");
2808  goto done;
2809  /* LCOV_EXCL_STOP */
2810  }
2811  cell->command = CELL_AUTH_CHALLENGE;
2812 
2813  connection_or_write_var_cell_to_buf(cell, conn);
2814  r = 0;
2815 
2816  done:
2817  var_cell_free(cell);
2818  auth_challenge_cell_free(ac);
2819 
2820  return r;
2821 }
2822 
2841 var_cell_t *
2843  const int authtype,
2844  crypto_pk_t *signing_key,
2845  const ed25519_keypair_t *ed_signing_key,
2846  int server)
2847 {
2848  auth1_t *auth = NULL;
2849  auth_ctx_t *ctx = auth_ctx_new();
2850  var_cell_t *result = NULL;
2851  int old_tlssecrets_algorithm = 0;
2852  const char *authtype_str = NULL;
2853 
2854  int is_ed = 0;
2855 
2856  /* assert state is reasonable XXXX */
2857  switch (authtype) {
2859  authtype_str = "AUTH0001";
2860  old_tlssecrets_algorithm = 1;
2861  break;
2863  authtype_str = "AUTH0002";
2864  break;
2866  authtype_str = "AUTH0003";
2867  is_ed = 1;
2868  break;
2869  default:
2870  tor_assert(0);
2871  break;
2872  }
2873 
2874  auth = auth1_new();
2875  ctx->is_ed = is_ed;
2876 
2877  /* Type: 8 bytes. */
2878  memcpy(auth1_getarray_type(auth), authtype_str, 8);
2879 
2880  {
2881  const tor_x509_cert_t *id_cert=NULL;
2882  const common_digests_t *my_digests, *their_digests;
2883  const uint8_t *my_id, *their_id, *client_id, *server_id;
2884  if (tor_tls_get_my_certs(server, NULL, &id_cert))
2885  goto err;
2886  my_digests = tor_x509_cert_get_id_digests(id_cert);
2887  their_digests =
2889  tor_assert(my_digests);
2890  tor_assert(their_digests);
2891  my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
2892  their_id = (uint8_t*)their_digests->d[DIGEST_SHA256];
2893 
2894  client_id = server ? their_id : my_id;
2895  server_id = server ? my_id : their_id;
2896 
2897  /* Client ID digest: 32 octets. */
2898  memcpy(auth->cid, client_id, 32);
2899 
2900  /* Server ID digest: 32 octets. */
2901  memcpy(auth->sid, server_id, 32);
2902  }
2903 
2904  if (is_ed) {
2905  const ed25519_public_key_t *my_ed_id, *their_ed_id;
2906  if (!conn->handshake_state->certs->ed_id_sign) {
2907  log_warn(LD_OR, "Ed authenticate without Ed ID cert from peer.");
2908  goto err;
2909  }
2910  my_ed_id = get_master_identity_key();
2911  their_ed_id = &conn->handshake_state->certs->ed_id_sign->signing_key;
2912 
2913  const uint8_t *cid_ed = (server ? their_ed_id : my_ed_id)->pubkey;
2914  const uint8_t *sid_ed = (server ? my_ed_id : their_ed_id)->pubkey;
2915 
2916  memcpy(auth->u1_cid_ed, cid_ed, ED25519_PUBKEY_LEN);
2917  memcpy(auth->u1_sid_ed, sid_ed, ED25519_PUBKEY_LEN);
2918  }
2919 
2920  {
2921  crypto_digest_t *server_d, *client_d;
2922  if (server) {
2923  server_d = conn->handshake_state->digest_sent;
2924  client_d = conn->handshake_state->digest_received;
2925  } else {
2926  client_d = conn->handshake_state->digest_sent;
2927  server_d = conn->handshake_state->digest_received;
2928  }
2929 
2930  /* Server log digest : 32 octets */
2931  crypto_digest_get_digest(server_d, (char*)auth->slog, 32);
2932 
2933  /* Client log digest : 32 octets */
2934  crypto_digest_get_digest(client_d, (char*)auth->clog, 32);
2935  }
2936 
2937  {
2938  /* Digest of cert used on TLS link : 32 octets. */
2939  tor_x509_cert_t *cert = NULL;
2940  if (server) {
2941  cert = tor_tls_get_own_cert(conn->tls);
2942  } else {
2943  cert = tor_tls_get_peer_cert(conn->tls);
2944  }
2945  if (!cert) {
2946  log_warn(LD_OR, "Unable to find cert when making %s data.",
2947  authtype_str);
2948  goto err;
2949  }
2950 
2951  memcpy(auth->scert,
2952  tor_x509_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
2953 
2954  tor_x509_cert_free(cert);
2955  }
2956 
2957  /* HMAC of clientrandom and serverrandom using master key : 32 octets */
2958  if (old_tlssecrets_algorithm) {
2959  if (tor_tls_get_tlssecrets(conn->tls, auth->tlssecrets) < 0) {
2960  log_fn(LOG_PROTOCOL_WARN, LD_OR, "Somebody asked us for an older TLS "
2961  "authentication method (AUTHTYPE_RSA_SHA256_TLSSECRET) "
2962  "which we don't support.");
2963  }
2964  } else {
2965  char label[128];
2966  tor_snprintf(label, sizeof(label),
2967  "EXPORTER FOR TOR TLS CLIENT BINDING %s", authtype_str);
2968  int r = tor_tls_export_key_material(conn->tls, auth->tlssecrets,
2969  auth->cid, sizeof(auth->cid),
2970  label);
2971  if (r < 0) {
2972  if (r != -2)
2973  log_warn(LD_BUG, "TLS key export failed for unknown reason.");
2974  // If r == -2, this was openssl bug 7712.
2975  goto err;
2976  }
2977  }
2978 
2979  /* 8 octets were reserved for the current time, but we're trying to get out
2980  * of the habit of sending time around willynilly. Fortunately, nothing
2981  * checks it. That's followed by 16 bytes of nonce. */
2982  crypto_rand((char*)auth->rand, 24);
2983 
2984  ssize_t maxlen = auth1_encoded_len(auth, ctx);
2985  if (ed_signing_key && is_ed) {
2986  maxlen += ED25519_SIG_LEN;
2987  } else if (signing_key && !is_ed) {
2988  maxlen += crypto_pk_keysize(signing_key);
2989  }
2990 
2991  const int AUTH_CELL_HEADER_LEN = 4; /* 2 bytes of type, 2 bytes of length */
2992  result = var_cell_new(AUTH_CELL_HEADER_LEN + maxlen);
2993  uint8_t *const out = result->payload + AUTH_CELL_HEADER_LEN;
2994  const size_t outlen = maxlen;
2995  ssize_t len;
2996 
2997  result->command = CELL_AUTHENTICATE;
2998  set_uint16(result->payload, htons(authtype));
2999 
3000  if ((len = auth1_encode(out, outlen, auth, ctx)) < 0) {
3001  /* LCOV_EXCL_START */
3002  log_warn(LD_BUG, "Unable to encode signed part of AUTH1 data.");
3003  goto err;
3004  /* LCOV_EXCL_STOP */
3005  }
3006 
3007  if (server) {
3008  auth1_t *tmp = NULL;
3009  ssize_t len2 = auth1_parse(&tmp, out, len, ctx);
3010  if (!tmp) {
3011  /* LCOV_EXCL_START */
3012  log_warn(LD_BUG, "Unable to parse signed part of AUTH1 data that "
3013  "we just encoded");
3014  goto err;
3015  /* LCOV_EXCL_STOP */
3016  }
3017  result->payload_len = (tmp->end_of_signed - result->payload);
3018 
3019  auth1_free(tmp);
3020  if (len2 != len) {
3021  /* LCOV_EXCL_START */
3022  log_warn(LD_BUG, "Mismatched length when re-parsing AUTH1 data.");
3023  goto err;
3024  /* LCOV_EXCL_STOP */
3025  }
3026  goto done;
3027  }
3028 
3029  if (ed_signing_key && is_ed) {
3030  ed25519_signature_t sig;
3031  if (ed25519_sign(&sig, out, len, ed_signing_key) < 0) {
3032  /* LCOV_EXCL_START */
3033  log_warn(LD_BUG, "Unable to sign ed25519 authentication data");
3034  goto err;
3035  /* LCOV_EXCL_STOP */
3036  }
3037  auth1_setlen_sig(auth, ED25519_SIG_LEN);
3038  memcpy(auth1_getarray_sig(auth), sig.sig, ED25519_SIG_LEN);
3039 
3040  } else if (signing_key && !is_ed) {
3041  auth1_setlen_sig(auth, crypto_pk_keysize(signing_key));
3042 
3043  char d[32];
3044  crypto_digest256(d, (char*)out, len, DIGEST_SHA256);
3045  int siglen = crypto_pk_private_sign(signing_key,
3046  (char*)auth1_getarray_sig(auth),
3047  auth1_getlen_sig(auth),
3048  d, 32);
3049  if (siglen < 0) {
3050  log_warn(LD_OR, "Unable to sign AUTH1 data.");
3051  goto err;
3052  }
3053 
3054  auth1_setlen_sig(auth, siglen);
3055  }
3056 
3057  len = auth1_encode(out, outlen, auth, ctx);
3058  if (len < 0) {
3059  /* LCOV_EXCL_START */
3060  log_warn(LD_BUG, "Unable to encode signed AUTH1 data.");
3061  goto err;
3062  /* LCOV_EXCL_STOP */
3063  }
3064  tor_assert(len + AUTH_CELL_HEADER_LEN <= result->payload_len);
3065  result->payload_len = len + AUTH_CELL_HEADER_LEN;
3066  set_uint16(result->payload+2, htons(len));
3067 
3068  goto done;
3069 
3070  err:
3071  var_cell_free(result);
3072  result = NULL;
3073  done:
3074  auth1_free(auth);
3075  auth_ctx_free(ctx);
3076  return result;
3077 }
3078 
3082 connection_or_send_authenticate_cell,(or_connection_t *conn, int authtype))
3083 {
3084  var_cell_t *cell;
3086  /* XXXX make sure we're actually supposed to send this! */
3087 
3088  if (!pk) {
3089  log_warn(LD_BUG, "Can't compute authenticate cell: no client auth key");
3090  return -1;
3091  }
3092  if (! authchallenge_type_is_supported(authtype)) {
3093  log_warn(LD_BUG, "Tried to send authenticate cell with unknown "
3094  "authentication type %d", authtype);
3095  return -1;
3096  }
3097 
3099  authtype,
3100  pk,
3101  get_current_auth_keypair(),
3102  0 /* not server */);
3103  if (! cell) {
3104  log_fn(LOG_PROTOCOL_WARN, LD_NET, "Unable to compute authenticate cell!");
3105  return -1;
3106  }
3107  connection_or_write_var_cell_to_buf(cell, conn);
3108  var_cell_free(cell);
3109 
3110  return 0;
3111 }
tor_socket_t s
Definition: connection_st.h:88
var_cell_t * var_cell_new(uint16_t payload_len)
static int connection_or_launch_v3_or_handshake(or_connection_t *conn)
Header file for circuitstats.c.
void tor_tls_block_renegotiation(tor_tls_t *tls)
Definition: tortls_nss.c:588
Header file for rendcommon.c.
void crypto_digest_add_bytes(crypto_digest_t *digest, const char *data, size_t len)
int tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity)
Definition: tortls.c:411
int authdir_mode_tests_reachability(const or_options_t *options)
Definition: authmode.c:59
Header file for channeltls.c.
unsigned int channel_num_circuits(channel_t *chan)
Definition: channel.c:3335
void connection_or_close_normally(or_connection_t *orconn, int flush)
uint64_t global_identifier
static const int n_or_protocol_versions
void channel_mark_bad_for_new_circs(channel_t *chan)
Definition: channel.c:2898
token_bucket_rw_t bucket
crypto_pk_t * tor_tls_get_my_client_auth_key(void)
Definition: tortls.c:96
uint8_t * encoded
Definition: torcert.h:33
Header file for circuitbuild.c.
uint8_t payload[CELL_PAYLOAD_SIZE]
Definition: cell_st.h:16
Common functions for using (pseudo-)random number generators.
uint8_t payload[FLEXIBLE_ARRAY_MEMBER]
Definition: var_cell_st.h:19
Definition: node_st.h:28
tor_addr_t real_addr
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
char identity_digest[DIGEST_LEN]
#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
int crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen)
struct tor_cert_st * ed_id_sign
Header file for command.c.
time_t channel_when_last_client(channel_t *chan)
Definition: channel.c:3277
const char * escaped_safe_str(const char *address)
Definition: config.c:1101
void channel_timestamp_active(channel_t *chan)
Definition: channel.c:3157
or_handshake_state_t * handshake_state
void channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
Definition: channeltls.c:1044
tor_addr_t addr
static int disable_broken_connection_counts
void channel_close_for_error(channel_t *chan)
Definition: channel.c:1241
Header file for connection.c.
void connection_or_connect_failed(or_connection_t *conn, int reason, const char *msg)
#define OR_CONN_HIGHWATER
Definition: or.h:720
channel_listener_t * channel_tls_get_listener(void)
Definition: channeltls.c:252
static int connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
static void set_uint16(void *cp, uint16_t v)
Definition: bytes.h:73
uint64_t PerConnBWBurst
const char * tor_tls_err_to_string(int err)
Definition: tortls.c:150
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:12
#define LD_GENERAL
Definition: log.h:58
void connection_or_block_renegotiation(or_connection_t *conn)
static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
tor_cert_t * tor_cert_dup(const tor_cert_t *cert)
Definition: torcert.c:294
#define DOWNCAST(to, ptr)
Definition: or.h:110
void rep_hist_note_negotiated_link_proto(unsigned link_proto, int started_here)
Definition: rephist.c:2701
unsigned int proxy_state
Definition: connection_st.h:84
uint64_t BandwidthRate
uint8_t state
Definition: connection_st.h:44
int tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2, tor_addr_comparison_t how)
Definition: address.c:942
time_t connection_or_client_used(or_connection_t *conn)
#define TIME_BEFORE_OR_CONN_IS_TOO_OLD
#define LOG_INFO
Definition: log.h:41
#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
HT_PROTOTYPE(HT_GENERATE2(strmap_impl, HT_GENERATE2(strmap_entry_t, HT_GENERATE2(node, HT_GENERATE2(strmap_entry_hash, HT_GENERATE2(strmap_entries_eq)
Definition: map.c:87
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:631
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:34
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:2323
int ed25519_public_to_base64(char *output, const ed25519_public_key_t *pkey)
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:1334
static strmap_t * broken_connection_counts
int authchallenge_type_is_supported(uint16_t challenge_type)
void channel_close_from_lower_layer(channel_t *chan)
Definition: channel.c:1213
const char * safe_str_client(const char *address)
Definition: config.c:1059
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:41
Header file for config.c.
int router_digest_is_fallback_dir(const char *digest)
Definition: dirlist.c:157
#define CONN_TYPE_OR
Definition: connection.h:24
ed25519_public_key_t signing_key
Definition: torcert.h:28
Header file for microdesc.c.
static uint32_t tor_addr_to_ipv4h(const tor_addr_t *a)
Definition: address.h:152
uint16_t port
Header file for reachability.c.
tor_tls_t * tor_tls_new(tor_socket_t sock, int is_server)
Definition: tortls_nss.c:364
#define tor_free(p)
Definition: malloc.h:52
#define tor_fragile_assert()
Definition: util_bug.h:221
int crypto_digest256(char *digest, const char *m, size_t len, digest_algorithm_t algorithm)
struct broken_state_count_t broken_state_count_t
const char * conn_state_to_string(int type, int state)
Definition: connection.c:273
Header file for mainloop.c.
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:57
void circuit_build_times_network_is_live(circuit_build_times_t *cbt)
void node_get_pref_orport(const node_t *node, tor_addr_port_t *ap_out)
Definition: nodelist.c:1609
void connection_or_about_to_close(or_connection_t *or_conn)
char body[CELL_MAX_NETWORK_SIZE]
Definition: cell_queue_st.h:16
#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
Header file for scheduler*.c.
struct tor_tls_t * tls
or_connection_t * or_connection_new(int type, int socket_family)
Definition: connection.c:373
var_cell_t * var_cell_copy(const var_cell_t *src)
void connection_or_clear_identity(or_connection_t *conn)
#define AUTHTYPE_RSA_SHA256_TLSSECRET
Definition: or.h:680
Header file for orconn_event.c.
int control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp, int reason)
Definition: control.c:5966
static void set_uint32(void *cp, uint32_t v)
Definition: bytes.h:82
struct ed25519_public_key_t ed25519_identity
Definition: channel.h:394
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:49
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.
size_t encoded_len
Definition: torcert.h:35
#define EXT_OR_CONN_ID_LEN
Definition: or.h:712
void connection_or_event_status(or_connection_t *conn, or_conn_status_event_t tp, int reason)
#define CONN_TYPE_EXT_OR
Definition: connection.h:51
void connection_or_remove_from_ext_or_id_map(or_connection_t *conn)
uint64_t PerConnBWRate
int ed25519_pubkey_eq(const ed25519_public_key_t *key1, const ed25519_public_key_t *key2)
const char * ed25519_fmt(const ed25519_public_key_t *pkey)
struct buf_t * inbuf
Definition: connection_st.h:93
int errno_to_orconn_end_reason(int e)
Definition: reasons.c:287
Common functions for cryptographic routines.
Header file for channel.c.
tor_assert(buffer)
#define AUTHTYPE_RSA_SHA256_RFC5705
Definition: or.h:688
int get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type, const connection_t *conn)
Definition: connection.c:5370
const char * node_get_nickname(const node_t *node)
Definition: nodelist.c:1194
static int broken_state_count_compare(const void **a_ptr, const void **b_ptr)
static int connection_or_check_valid_tls_handshake(or_connection_t *conn, int started_here, char *digest_rcvd_out)
int connection_or_set_state_open(or_connection_t *conn)
MOCK_IMPL(int, connection_or_get_num_circuits,(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:314
#define LD_CIRC
Definition: log.h:78
Header for crypto_format.c.
Header file for routermode.c.
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1157
void clear_broken_connection_map(int stop_recording)
#define OR_CERT_TYPE_AUTH_1024
Definition: or.h:669
or_handshake_certs_t * or_handshake_certs_new(void)
Definition: torcert.c:471
const routerinfo_t * router_get_by_id_digest(const char *digest)
Definition: routerlist.c:690
#define DIGEST_LEN
Definition: digest_sizes.h:20
void channel_listener_queue_incoming(channel_listener_t *listener, channel_t *incoming)
Definition: channel.c:1911
int connection_or_reached_eof(or_connection_t *conn)
int tor_tls_used_v1_handshake(tor_tls_t *tls)
Definition: tortls_nss.c:665
int ed25519_public_key_is_zero(const ed25519_public_key_t *pubkey)
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)
void crypto_digest_get_digest(crypto_digest_t *digest, char *out, size_t out_len)
Master header file for Tor-specific functionality.
const char * find_transport_name_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
Definition: bridges.c:591
void entry_guard_chan_failed(channel_t *chan)
Definition: entrynodes.c:2500
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)
Header file for circuitbuild.c.
#define OR_CONN_STATE_OPEN
Definition: orconn_event.h:51
uint16_t marked_for_close
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:97
int connection_buf_get_bytes(char *string, size_t len, connection_t *conn)
Definition: connection.c:3869
Header file for rephist.c.
static uint16_t get_uint16(const void *cp)
Definition: bytes.h:37
circid_t circ_id
Definition: cell_st.h:13
#define OR_CONN_STATE_PROXY_HANDSHAKING
Definition: orconn_event.h:31
#define LOG_WARN
Definition: log.h:49
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:758
unsigned int type
Definition: connection_st.h:45
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:2587
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:476
struct tor_cert_st * own_link_cert
void tor_free_(void *mem)
Definition: malloc.c:227
#define CELL_MAX_NETWORK_SIZE
Definition: or.h:579
int connection_connect(connection_t *conn, const char *address, const tor_addr_t *addr, uint16_t port, int *socket_error)
Definition: connection.c:2176
Header file for circuitlist.c.
#define VAR_CELL_MAX_HEADER_SIZE
Definition: or.h:582
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:88
int router_ed25519_id_is_me(const ed25519_public_key_t *id)
Definition: routerkeys.c:618
void channel_clear_identity_digest(channel_t *chan)
Definition: channel.c:1299
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
static digestmap_t * orconn_ext_or_id_map
Headers for tortls.c.
int channel_is_bad_for_new_circs(channel_t *chan)
Definition: channel.c:2885
#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:413
#define OR_CONN_STATE_OR_HANDSHAKING_V2
Definition: orconn_event.h:45
static void note_broken_connection(const char *state)
int tor_tls_handshake(tor_tls_t *tls)
Definition: tortls_nss.c:554
void connection_or_set_ext_or_identifier(or_connection_t *conn)
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
int connection_or_client_learned_peer_id(or_connection_t *conn, const uint8_t *rsa_peer_id, const ed25519_public_key_t *ed_peer_id)
const common_digests_t * tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
Definition: x509.c:68
void or_handshake_state_record_cell(or_connection_t *conn, or_handshake_state_t *state, const cell_t *cell, int incoming)
static void connection_or_change_state(or_connection_t *conn, uint8_t state)
void connection_or_clear_ext_or_id_map(void)
void assert_connection_ok(connection_t *conn, time_t now)
Definition: connection.c:5218
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:1122
#define CELL_PAYLOAD_SIZE
Definition: or.h:576
int crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
Definition: crypto_rsa.c:351
int connection_or_send_certs_cell(or_connection_t *conn)
ssize_t connection_or_num_cells_writeable(or_connection_t *conn)
uint64_t BandwidthBurst
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)
Header file for router.c.
static int connection_or_process_cells_from_inbuf(or_connection_t *conn)
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)
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:88
int tor_tls_peer_has_cert(tor_tls_t *tls)
Definition: tortls_nss.c:477
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:255
static void connection_or_note_state_when_broken(or_connection_t *orconn)
channel_tls_t * chan
int router_digest_is_me(const char *digest)
Definition: router.c:1589
struct tor_x509_cert_t * id_cert
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
Header file for control.c.
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:364
circid_t circ_id
Definition: var_cell_st.h:15
unsigned int hold_open_until_flushed
Definition: connection_st.h:56
or_handshake_certs_t * certs
#define OR_CONN_STATE_OR_HANDSHAKING_V3
Definition: orconn_event.h:49
time_t approx_time(void)
Definition: approx_time.c:32
int ed25519_sign(ed25519_signature_t *signature_out, const uint8_t *msg, size_t len, const ed25519_keypair_t *keypair)
void scheduler_channel_wants_writes(channel_t *chan)
Definition: scheduler.c:669
int authchallenge_type_is_better(uint16_t challenge_type_a, uint16_t challenge_type_b)
uint32_t magic
Definition: connection_st.h:41
static void connection_or_state_publish(const or_connection_t *conn, uint8_t state)
static void add_ed25519_cert(certs_cell_t *certs_cell, uint8_t cert_type, const tor_cert_t *cert)
Header file for dirlist.c.
time_t timestamp_created
int connection_or_send_versions(or_connection_t *conn, int v3_plus)
uint32_t addr
Definition: routerinfo_st.h:19
static unsigned int connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
unsigned int is_outgoing
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.
Header file for reasons.c.
int tls_error_to_orconn_end_reason(int e)
Definition: reasons.c:261
uint8_t command
Definition: var_cell_st.h:13
uint8_t command
Definition: cell_st.h:14
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:62
#define OR_CONN_STATE_CONNECTING
Definition: orconn_event.h:29
#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:496
int is_or_protocol_version_known(uint16_t v)
uint16_t payload_len
Definition: var_cell_st.h:17
static void connection_or_get_state_description(or_connection_t *orconn, char *buf, size_t buflen)
channel_t * channel_tls_to_base(channel_tls_t *tlschan)
Definition: channeltls.c:369
void channel_set_identity_digest(channel_t *chan, const char *identity_digest, const ed25519_public_key_t *ed_identity)
Definition: channel.c:1328
int tor_tls_get_pending_bytes(tor_tls_t *tls)
Definition: tortls_nss.c:602
void channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
Definition: channeltls.c:1161
tor_addr_t ipv6_addr
Definition: routerinfo_st.h:27
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:892
or_conn_status_event_t
Definition: orconn_event.h:57
int connection_proxy_connect(connection_t *conn, int type)
Definition: connection.c:2322
int tor_tls_is_server(tor_tls_t *tls)
Definition: tortls.c:374
#define LD_PROTOCOL
Definition: log.h:68
int connection_or_single_set_badness_(time_t now, or_connection_t *or_conn, int force)
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
void channel_closed(channel_t *chan)
Definition: channel.c:1268
const char * orconn_end_reason_to_control_string(int r)
Definition: reasons.c:225
unsigned int proxy_type
void channel_mark_client(channel_t *chan)
Definition: channel.c:2926
void dirserv_orconn_tls_done(const tor_addr_t *addr, uint16_t or_port, const char *digest_rcvd, const ed25519_public_key_t *ed_id_rcvd)
Definition: reachability.c:38
unsigned int is_canonical
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:71
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:82
uint32_t monotime_coarse_get_stamp(void)
Definition: compat_time.c:834
Header file for routerlist.c.
void command_setup_listener(channel_listener_t *listener)
Definition: command.c:697
crypto_digest_t * digest_sent
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:179
void orconn_event_publish(const orconn_event_msg_t *msg)
Definition: orconn_event.c:67
or_connection_t * connection_or_get_by_ext_or_id(const char *id)
crypto_digest_t * crypto_digest256_new(digest_algorithm_t algorithm)