dirvote: Handling adding vote and signature if module is disabled
[tor.git] / src / or / connection_or.c
blob7723d9d2bd65724bfd3ced751f04ed0cc4910b84
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-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection_or.c
9 * \brief Functions to handle OR connections, TLS handshaking, and
10 * cells on the network.
12 * An or_connection_t is a subtype of connection_t (as implemented in
13 * connection.c) that uses a TLS connection to send and receive cells on the
14 * Tor network. (By sending and receiving cells connection_or.c, it cooperates
15 * with channeltls.c to implement a the channel interface of channel.c.)
17 * Every OR connection has an underlying tortls_t object (as implemented in
18 * tortls.c) which it uses as its TLS stream. It is responsible for
19 * sending and receiving cells over that TLS.
21 * This module also implements the client side of the v3 Tor link handshake,
22 **/
23 #include "or.h"
24 #include "bridges.h"
25 #include "buffers.h"
27 * Define this so we get channel internal functions, since we're implementing
28 * part of a subclass (channel_tls_t).
30 #define TOR_CHANNEL_INTERNAL_
31 #define CONNECTION_OR_PRIVATE
32 #include "channel.h"
33 #include "channeltls.h"
34 #include "circuitbuild.h"
35 #include "circuitlist.h"
36 #include "circuitstats.h"
37 #include "command.h"
38 #include "config.h"
39 #include "connection.h"
40 #include "connection_or.h"
41 #include "control.h"
42 #include "dirserv.h"
43 #include "entrynodes.h"
44 #include "geoip.h"
45 #include "main.h"
46 #include "link_handshake.h"
47 #include "microdesc.h"
48 #include "networkstatus.h"
49 #include "nodelist.h"
50 #include "proto_cell.h"
51 #include "reasons.h"
52 #include "relay.h"
53 #include "rephist.h"
54 #include "router.h"
55 #include "routerkeys.h"
56 #include "routerlist.h"
57 #include "ext_orport.h"
58 #include "scheduler.h"
59 #include "torcert.h"
60 #include "channelpadding.h"
62 static int connection_tls_finish_handshake(or_connection_t *conn);
63 static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
64 static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
65 static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
66 int started_here,
67 char *digest_rcvd_out);
69 static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
71 static unsigned int
72 connection_or_is_bad_for_new_circs(or_connection_t *or_conn);
73 static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
76 * Call this when changing connection state, so notifications to the owning
77 * channel can be handled.
80 static void connection_or_change_state(or_connection_t *conn, uint8_t state);
82 static void connection_or_check_canonicity(or_connection_t *conn,
83 int started_here);
85 /**************************************************************/
87 /** Global map between Extended ORPort identifiers and OR
88 * connections. */
89 static digestmap_t *orconn_ext_or_id_map = NULL;
91 /** Clear clear conn->identity_digest and update other data
92 * structures as appropriate.*/
93 void
94 connection_or_clear_identity(or_connection_t *conn)
96 tor_assert(conn);
97 memset(conn->identity_digest, 0, DIGEST_LEN);
100 /** Clear all identities in OR conns.*/
101 void
102 connection_or_clear_identity_map(void)
104 smartlist_t *conns = get_connection_array();
105 SMARTLIST_FOREACH(conns, connection_t *, conn,
107 if (conn->type == CONN_TYPE_OR) {
108 connection_or_clear_identity(TO_OR_CONN(conn));
113 /** Change conn->identity_digest to digest, and add conn into
114 * the appropriate digest maps.
116 * NOTE that this function only allows two kinds of transitions: from
117 * unset identity to set identity, and from idempotent re-settings
118 * of the same identity. It's not allowed to clear an identity or to
119 * change an identity. Return 0 on success, and -1 if the transition
120 * is not allowed.
122 static void
123 connection_or_set_identity_digest(or_connection_t *conn,
124 const char *rsa_digest,
125 const ed25519_public_key_t *ed_id)
127 channel_t *chan = NULL;
128 tor_assert(conn);
129 tor_assert(rsa_digest);
131 if (conn->chan)
132 chan = TLS_CHAN_TO_BASE(conn->chan);
134 log_info(LD_HANDSHAKE, "Set identity digest for %p (%s): %s %s.",
135 conn,
136 escaped_safe_str(conn->base_.address),
137 hex_str(rsa_digest, DIGEST_LEN),
138 ed25519_fmt(ed_id));
139 log_info(LD_HANDSHAKE, " (Previously: %s %s)",
140 hex_str(conn->identity_digest, DIGEST_LEN),
141 chan ? ed25519_fmt(&chan->ed25519_identity) : "<null>");
143 const int rsa_id_was_set = ! tor_digest_is_zero(conn->identity_digest);
144 const int ed_id_was_set =
145 chan && !ed25519_public_key_is_zero(&chan->ed25519_identity);
146 const int rsa_changed =
147 tor_memneq(conn->identity_digest, rsa_digest, DIGEST_LEN);
148 const int ed_changed = ed_id_was_set &&
149 (!ed_id || !ed25519_pubkey_eq(ed_id, &chan->ed25519_identity));
151 tor_assert(!rsa_changed || !rsa_id_was_set);
152 tor_assert(!ed_changed || !ed_id_was_set);
154 if (!rsa_changed && !ed_changed)
155 return;
157 /* If the identity was set previously, remove the old mapping. */
158 if (rsa_id_was_set) {
159 connection_or_clear_identity(conn);
160 if (chan)
161 channel_clear_identity_digest(chan);
164 memcpy(conn->identity_digest, rsa_digest, DIGEST_LEN);
166 /* If we're initializing the IDs to zero, don't add a mapping yet. */
167 if (tor_digest_is_zero(rsa_digest) &&
168 (!ed_id || ed25519_public_key_is_zero(ed_id)))
169 return;
171 /* Deal with channels */
172 if (chan)
173 channel_set_identity_digest(chan, rsa_digest, ed_id);
176 /** Remove the Extended ORPort identifier of <b>conn</b> from the
177 * global identifier list. Also, clear the identifier from the
178 * connection itself. */
179 void
180 connection_or_remove_from_ext_or_id_map(or_connection_t *conn)
182 or_connection_t *tmp;
183 if (!orconn_ext_or_id_map)
184 return;
185 if (!conn->ext_or_conn_id)
186 return;
188 tmp = digestmap_remove(orconn_ext_or_id_map, conn->ext_or_conn_id);
189 if (!tor_digest_is_zero(conn->ext_or_conn_id))
190 tor_assert(tmp == conn);
192 memset(conn->ext_or_conn_id, 0, EXT_OR_CONN_ID_LEN);
195 /** Return the connection whose ext_or_id is <b>id</b>. Return NULL if no such
196 * connection is found. */
197 or_connection_t *
198 connection_or_get_by_ext_or_id(const char *id)
200 if (!orconn_ext_or_id_map)
201 return NULL;
202 return digestmap_get(orconn_ext_or_id_map, id);
205 /** Deallocate the global Extended ORPort identifier list */
206 void
207 connection_or_clear_ext_or_id_map(void)
209 digestmap_free(orconn_ext_or_id_map, NULL);
210 orconn_ext_or_id_map = NULL;
213 /** Creates an Extended ORPort identifier for <b>conn</b> and deposits
214 * it into the global list of identifiers. */
215 void
216 connection_or_set_ext_or_identifier(or_connection_t *conn)
218 char random_id[EXT_OR_CONN_ID_LEN];
219 or_connection_t *tmp;
221 if (!orconn_ext_or_id_map)
222 orconn_ext_or_id_map = digestmap_new();
224 /* Remove any previous identifiers: */
225 if (conn->ext_or_conn_id && !tor_digest_is_zero(conn->ext_or_conn_id))
226 connection_or_remove_from_ext_or_id_map(conn);
228 do {
229 crypto_rand(random_id, sizeof(random_id));
230 } while (digestmap_get(orconn_ext_or_id_map, random_id));
232 if (!conn->ext_or_conn_id)
233 conn->ext_or_conn_id = tor_malloc_zero(EXT_OR_CONN_ID_LEN);
235 memcpy(conn->ext_or_conn_id, random_id, EXT_OR_CONN_ID_LEN);
237 tmp = digestmap_set(orconn_ext_or_id_map, random_id, conn);
238 tor_assert(!tmp);
241 /**************************************************************/
243 /** Map from a string describing what a non-open OR connection was doing when
244 * failed, to an intptr_t describing the count of connections that failed that
245 * way. Note that the count is stored _as_ the pointer.
247 static strmap_t *broken_connection_counts;
249 /** If true, do not record information in <b>broken_connection_counts</b>. */
250 static int disable_broken_connection_counts = 0;
252 /** Record that an OR connection failed in <b>state</b>. */
253 static void
254 note_broken_connection(const char *state)
256 void *ptr;
257 intptr_t val;
258 if (disable_broken_connection_counts)
259 return;
261 if (!broken_connection_counts)
262 broken_connection_counts = strmap_new();
264 ptr = strmap_get(broken_connection_counts, state);
265 val = (intptr_t)ptr;
266 val++;
267 ptr = (void*)val;
268 strmap_set(broken_connection_counts, state, ptr);
271 /** Forget all recorded states for failed connections. If
272 * <b>stop_recording</b> is true, don't record any more. */
273 void
274 clear_broken_connection_map(int stop_recording)
276 if (broken_connection_counts)
277 strmap_free(broken_connection_counts, NULL);
278 broken_connection_counts = NULL;
279 if (stop_recording)
280 disable_broken_connection_counts = 1;
283 /** Write a detailed description the state of <b>orconn</b> into the
284 * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
285 * only the OR-conn level state but also the TLS state. It's useful for
286 * diagnosing broken handshakes. */
287 static void
288 connection_or_get_state_description(or_connection_t *orconn,
289 char *buf, size_t buflen)
291 connection_t *conn = TO_CONN(orconn);
292 const char *conn_state;
293 char tls_state[256];
295 tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
297 conn_state = conn_state_to_string(conn->type, conn->state);
298 tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
300 tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
303 /** Record the current state of <b>orconn</b> as the state of a broken
304 * connection. */
305 static void
306 connection_or_note_state_when_broken(or_connection_t *orconn)
308 char buf[256];
309 if (disable_broken_connection_counts)
310 return;
311 connection_or_get_state_description(orconn, buf, sizeof(buf));
312 log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
313 note_broken_connection(buf);
316 /** Helper type used to sort connection states and find the most frequent. */
317 typedef struct broken_state_count_t {
318 intptr_t count;
319 const char *state;
320 } broken_state_count_t;
322 /** Helper function used to sort broken_state_count_t by frequency. */
323 static int
324 broken_state_count_compare(const void **a_ptr, const void **b_ptr)
326 const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
327 if (b->count < a->count)
328 return -1;
329 else if (b->count == a->count)
330 return 0;
331 else
332 return 1;
335 /** Upper limit on the number of different states to report for connection
336 * failure. */
337 #define MAX_REASONS_TO_REPORT 10
339 /** Report a list of the top states for failed OR connections at log level
340 * <b>severity</b>, in log domain <b>domain</b>. */
341 void
342 connection_or_report_broken_states(int severity, int domain)
344 int total = 0;
345 smartlist_t *items;
347 if (!broken_connection_counts || disable_broken_connection_counts)
348 return;
350 items = smartlist_new();
351 STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
352 broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
353 c->count = (intptr_t)countptr;
354 total += (int)c->count;
355 c->state = state;
356 smartlist_add(items, c);
357 } STRMAP_FOREACH_END;
359 smartlist_sort(items, broken_state_count_compare);
361 tor_log(severity, domain, "%d connections have failed%s", total,
362 smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
364 SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
365 if (c_sl_idx > MAX_REASONS_TO_REPORT)
366 break;
367 tor_log(severity, domain,
368 " %d connections died in state %s", (int)c->count, c->state);
369 } SMARTLIST_FOREACH_END(c);
371 SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
372 smartlist_free(items);
375 /** Call this to change or_connection_t states, so the owning channel_tls_t can
376 * be notified.
379 static void
380 connection_or_change_state(or_connection_t *conn, uint8_t state)
382 uint8_t old_state;
384 tor_assert(conn);
386 old_state = conn->base_.state;
387 conn->base_.state = state;
389 if (conn->chan)
390 channel_tls_handle_state_change_on_orconn(conn->chan, conn,
391 old_state, state);
394 /** Return the number of circuits using an or_connection_t; this used to
395 * be an or_connection_t field, but it got moved to channel_t and we
396 * shouldn't maintain two copies. */
398 MOCK_IMPL(int,
399 connection_or_get_num_circuits, (or_connection_t *conn))
401 tor_assert(conn);
403 if (conn->chan) {
404 return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
405 } else return 0;
408 /**************************************************************/
410 /** Pack the cell_t host-order structure <b>src</b> into network-order
411 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
412 * wire format.
414 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
415 * should set it or clear it as appropriate.
417 void
418 cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
420 char *dest = dst->body;
421 if (wide_circ_ids) {
422 set_uint32(dest, htonl(src->circ_id));
423 dest += 4;
424 } else {
425 /* Clear the last two bytes of dest, in case we can accidentally
426 * send them to the network somehow. */
427 memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2);
428 set_uint16(dest, htons(src->circ_id));
429 dest += 2;
431 set_uint8(dest, src->command);
432 memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
435 /** Unpack the network-order buffer <b>src</b> into a host-order
436 * cell_t structure <b>dest</b>.
438 static void
439 cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
441 if (wide_circ_ids) {
442 dest->circ_id = ntohl(get_uint32(src));
443 src += 4;
444 } else {
445 dest->circ_id = ntohs(get_uint16(src));
446 src += 2;
448 dest->command = get_uint8(src);
449 memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
452 /** Write the header of <b>cell</b> into the first VAR_CELL_MAX_HEADER_SIZE
453 * bytes of <b>hdr_out</b>. Returns number of bytes used. */
455 var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
457 int r;
458 if (wide_circ_ids) {
459 set_uint32(hdr_out, htonl(cell->circ_id));
460 hdr_out += 4;
461 r = VAR_CELL_MAX_HEADER_SIZE;
462 } else {
463 set_uint16(hdr_out, htons(cell->circ_id));
464 hdr_out += 2;
465 r = VAR_CELL_MAX_HEADER_SIZE - 2;
467 set_uint8(hdr_out, cell->command);
468 set_uint16(hdr_out+1, htons(cell->payload_len));
469 return r;
472 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
473 * payload space. */
474 var_cell_t *
475 var_cell_new(uint16_t payload_len)
477 size_t size = offsetof(var_cell_t, payload) + payload_len;
478 var_cell_t *cell = tor_malloc_zero(size);
479 cell->payload_len = payload_len;
480 cell->command = 0;
481 cell->circ_id = 0;
482 return cell;
486 * Copy a var_cell_t
489 var_cell_t *
490 var_cell_copy(const var_cell_t *src)
492 var_cell_t *copy = NULL;
493 size_t size = 0;
495 if (src != NULL) {
496 size = offsetof(var_cell_t, payload) + src->payload_len;
497 copy = tor_malloc_zero(size);
498 copy->payload_len = src->payload_len;
499 copy->command = src->command;
500 copy->circ_id = src->circ_id;
501 memcpy(copy->payload, src->payload, copy->payload_len);
504 return copy;
507 /** Release all space held by <b>cell</b>. */
508 void
509 var_cell_free_(var_cell_t *cell)
511 tor_free(cell);
514 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
516 connection_or_reached_eof(or_connection_t *conn)
518 tor_assert(conn);
520 log_info(LD_OR,"OR connection reached EOF. Closing.");
521 connection_or_close_normally(conn, 1);
523 return 0;
526 /** Handle any new bytes that have come in on connection <b>conn</b>.
527 * If conn is in 'open' state, hand it to
528 * connection_or_process_cells_from_inbuf()
529 * (else do nothing).
532 connection_or_process_inbuf(or_connection_t *conn)
534 /** Don't let the inbuf of a nonopen OR connection grow beyond this many
535 * bytes: it's either a broken client, a non-Tor client, or a DOS
536 * attempt. */
537 #define MAX_OR_INBUF_WHEN_NONOPEN 0
539 int ret = 0;
540 tor_assert(conn);
542 switch (conn->base_.state) {
543 case OR_CONN_STATE_PROXY_HANDSHAKING:
544 ret = connection_read_proxy_handshake(TO_CONN(conn));
546 /* start TLS after handshake completion, or deal with error */
547 if (ret == 1) {
548 tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
549 if (connection_tls_start_handshake(conn, 0) < 0)
550 ret = -1;
551 /* Touch the channel's active timestamp if there is one */
552 if (conn->chan)
553 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
555 if (ret < 0) {
556 connection_or_close_for_error(conn, 0);
559 return ret;
560 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
561 case OR_CONN_STATE_OPEN:
562 case OR_CONN_STATE_OR_HANDSHAKING_V2:
563 case OR_CONN_STATE_OR_HANDSHAKING_V3:
564 return connection_or_process_cells_from_inbuf(conn);
565 default:
566 break; /* don't do anything */
569 /* This check was necessary with 0.2.2, when the TLS_SERVER_RENEGOTIATING
570 * check would otherwise just let data accumulate. It serves no purpose
571 * in 0.2.3.
573 * XXXX Remove this check once we verify that the above paragraph is
574 * 100% true. */
575 if (buf_datalen(conn->base_.inbuf) > MAX_OR_INBUF_WHEN_NONOPEN) {
576 log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated too much data (%d bytes) "
577 "on nonopen OR connection %s %s:%u in state %s; closing.",
578 (int)buf_datalen(conn->base_.inbuf),
579 connection_or_nonopen_was_started_here(conn) ? "to" : "from",
580 conn->base_.address, conn->base_.port,
581 conn_state_to_string(conn->base_.type, conn->base_.state));
582 connection_or_close_for_error(conn, 0);
583 ret = -1;
586 return ret;
589 /** Called whenever we have flushed some data on an or_conn: add more data
590 * from active circuits. */
592 connection_or_flushed_some(or_connection_t *conn)
594 size_t datalen;
596 /* Update the channel's active timestamp if there is one */
597 if (conn->chan)
598 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
600 /* If we're under the low water mark, add cells until we're just over the
601 * high water mark. */
602 datalen = connection_get_outbuf_len(TO_CONN(conn));
603 if (datalen < OR_CONN_LOWWATER) {
604 /* Let the scheduler know */
605 scheduler_channel_wants_writes(TLS_CHAN_TO_BASE(conn->chan));
608 return 0;
611 /** This is for channeltls.c to ask how many cells we could accept if
612 * they were available. */
613 ssize_t
614 connection_or_num_cells_writeable(or_connection_t *conn)
616 size_t datalen, cell_network_size;
617 ssize_t n = 0;
619 tor_assert(conn);
622 * If we're under the high water mark, we're potentially
623 * writeable; note this is different from the calculation above
624 * used to trigger when to start writing after we've stopped.
626 datalen = connection_get_outbuf_len(TO_CONN(conn));
627 if (datalen < OR_CONN_HIGHWATER) {
628 cell_network_size = get_cell_network_size(conn->wide_circ_ids);
629 n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, cell_network_size);
632 return n;
635 /** Connection <b>conn</b> has finished writing and has no bytes left on
636 * its outbuf.
638 * Otherwise it's in state "open": stop writing and return.
640 * If <b>conn</b> is broken, mark it for close and return -1, else
641 * return 0.
644 connection_or_finished_flushing(or_connection_t *conn)
646 tor_assert(conn);
647 assert_connection_ok(TO_CONN(conn),0);
649 switch (conn->base_.state) {
650 case OR_CONN_STATE_PROXY_HANDSHAKING:
651 case OR_CONN_STATE_OPEN:
652 case OR_CONN_STATE_OR_HANDSHAKING_V2:
653 case OR_CONN_STATE_OR_HANDSHAKING_V3:
654 break;
655 default:
656 log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
657 tor_fragile_assert();
658 return -1;
661 /* Update the channel's active timestamp if there is one */
662 if (conn->chan)
663 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
665 return 0;
668 /** Connected handler for OR connections: begin the TLS handshake.
671 connection_or_finished_connecting(or_connection_t *or_conn)
673 const int proxy_type = or_conn->proxy_type;
674 connection_t *conn;
676 tor_assert(or_conn);
677 conn = TO_CONN(or_conn);
678 tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
680 log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
681 conn->address,conn->port);
682 control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
684 if (proxy_type != PROXY_NONE) {
685 /* start proxy handshake */
686 if (connection_proxy_connect(conn, proxy_type) < 0) {
687 connection_or_close_for_error(or_conn, 0);
688 return -1;
691 connection_start_reading(conn);
692 connection_or_change_state(or_conn, OR_CONN_STATE_PROXY_HANDSHAKING);
693 return 0;
696 if (connection_tls_start_handshake(or_conn, 0) < 0) {
697 /* TLS handshaking error of some kind. */
698 connection_or_close_for_error(or_conn, 0);
699 return -1;
701 return 0;
704 /** Called when we're about to finally unlink and free an OR connection:
705 * perform necessary accounting and cleanup */
706 void
707 connection_or_about_to_close(or_connection_t *or_conn)
709 connection_t *conn = TO_CONN(or_conn);
711 /* Tell the controlling channel we're closed */
712 if (or_conn->chan) {
713 channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
715 * NULL this out because the channel might hang around a little
716 * longer before channel_run_cleanup() gets it.
718 or_conn->chan->conn = NULL;
719 or_conn->chan = NULL;
722 /* Remember why we're closing this connection. */
723 if (conn->state != OR_CONN_STATE_OPEN) {
724 /* now mark things down as needed */
725 if (connection_or_nonopen_was_started_here(or_conn)) {
726 const or_options_t *options = get_options();
727 connection_or_note_state_when_broken(or_conn);
728 /* Tell the new guard API about the channel failure */
729 entry_guard_chan_failed(TLS_CHAN_TO_BASE(or_conn->chan));
730 if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
731 int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
732 control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
733 reason);
734 if (!authdir_mode_tests_reachability(options))
735 control_event_bootstrap_prob_or(
736 orconn_end_reason_to_control_string(reason),
737 reason, or_conn);
740 } else if (conn->hold_open_until_flushed) {
741 /* We only set hold_open_until_flushed when we're intentionally
742 * closing a connection. */
743 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
744 tls_error_to_orconn_end_reason(or_conn->tls_error));
745 } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
746 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
747 tls_error_to_orconn_end_reason(or_conn->tls_error));
751 /** Return 1 if identity digest <b>id_digest</b> is known to be a
752 * currently or recently running relay. Otherwise return 0. */
754 connection_or_digest_is_known_relay(const char *id_digest)
756 if (router_get_consensus_status_by_id(id_digest))
757 return 1; /* It's in the consensus: "yes" */
758 if (router_get_by_id_digest(id_digest))
759 return 1; /* Not in the consensus, but we have a descriptor for
760 * it. Probably it was in a recent consensus. "Yes". */
761 return 0;
764 /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
765 * relay, we will rely on the global read and write buckets, so give it
766 * per-conn limits that are big enough they'll never matter. But if it's
767 * not a known relay, first check if we set PerConnBwRate/Burst, then
768 * check if the consensus sets them, else default to 'big enough'.
770 * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
771 * clip the bucket if it happens to be <em>too</em> full.
773 static void
774 connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
775 const or_options_t *options)
777 int rate, burst; /* per-connection rate limiting params */
778 if (connection_or_digest_is_known_relay(conn->identity_digest)) {
779 /* It's in the consensus, or we have a descriptor for it meaning it
780 * was probably in a recent consensus. It's a recognized relay:
781 * give it full bandwidth. */
782 rate = (int)options->BandwidthRate;
783 burst = (int)options->BandwidthBurst;
784 } else {
785 /* Not a recognized relay. Squeeze it down based on the suggested
786 * bandwidth parameters in the consensus, but allow local config
787 * options to override. */
788 rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
789 networkstatus_get_param(NULL, "perconnbwrate",
790 (int)options->BandwidthRate, 1, INT32_MAX);
791 burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
792 networkstatus_get_param(NULL, "perconnbwburst",
793 (int)options->BandwidthBurst, 1, INT32_MAX);
796 token_bucket_rw_adjust(&conn->bucket, rate, burst);
797 if (reset) {
798 token_bucket_rw_reset(&conn->bucket, monotime_coarse_get_stamp());
802 /** Either our set of relays or our per-conn rate limits have changed.
803 * Go through all the OR connections and update their token buckets to make
804 * sure they don't exceed their maximum values. */
805 void
806 connection_or_update_token_buckets(smartlist_t *conns,
807 const or_options_t *options)
809 SMARTLIST_FOREACH(conns, connection_t *, conn,
811 if (connection_speaks_cells(conn))
812 connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
816 /* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
817 * non-canonical otherwise. Adjust idle_timeout accordingly.
819 void
820 connection_or_set_canonical(or_connection_t *or_conn,
821 int is_canonical)
823 if (bool_eq(is_canonical, or_conn->is_canonical) &&
824 or_conn->idle_timeout != 0) {
825 /* Don't recalculate an existing idle_timeout unless the canonical
826 * status changed. */
827 return;
830 or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
831 or_conn->idle_timeout = channelpadding_get_channel_idle_timeout(
832 TLS_CHAN_TO_BASE(or_conn->chan), is_canonical);
834 log_info(LD_CIRC,
835 "Channel " U64_FORMAT " chose an idle timeout of %d.",
836 or_conn->chan ?
837 U64_PRINTF_ARG(TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier):0,
838 or_conn->idle_timeout);
841 /** If we don't necessarily know the router we're connecting to, but we
842 * have an addr/port/id_digest, then fill in as much as we can. Start
843 * by checking to see if this describes a router we know.
844 * <b>started_here</b> is 1 if we are the initiator of <b>conn</b> and
845 * 0 if it's an incoming connection. */
846 void
847 connection_or_init_conn_from_address(or_connection_t *conn,
848 const tor_addr_t *addr, uint16_t port,
849 const char *id_digest,
850 const ed25519_public_key_t *ed_id,
851 int started_here)
853 log_debug(LD_HANDSHAKE, "init conn from address %s: %s, %s (%d)",
854 fmt_addr(addr),
855 hex_str((const char*)id_digest, DIGEST_LEN),
856 ed25519_fmt(ed_id),
857 started_here);
859 connection_or_set_identity_digest(conn, id_digest, ed_id);
860 connection_or_update_token_buckets_helper(conn, 1, get_options());
862 conn->base_.port = port;
863 tor_addr_copy(&conn->base_.addr, addr);
864 tor_addr_copy(&conn->real_addr, addr);
866 connection_or_check_canonicity(conn, started_here);
869 /** Check whether the identity of <b>conn</b> matches a known node. If it
870 * does, check whether the address of conn matches the expected address, and
871 * update the connection's is_canonical flag, nickname, and address fields as
872 * appropriate. */
873 static void
874 connection_or_check_canonicity(or_connection_t *conn, int started_here)
876 const char *id_digest = conn->identity_digest;
877 const ed25519_public_key_t *ed_id = NULL;
878 const tor_addr_t *addr = &conn->real_addr;
879 if (conn->chan)
880 ed_id = & TLS_CHAN_TO_BASE(conn->chan)->ed25519_identity;
882 const node_t *r = node_get_by_id(id_digest);
883 if (r &&
884 node_supports_ed25519_link_authentication(r, 1) &&
885 ! node_ed25519_id_matches(r, ed_id)) {
886 /* If this node is capable of proving an ed25519 ID,
887 * we can't call this a canonical connection unless both IDs match. */
888 r = NULL;
891 if (r) {
892 tor_addr_port_t node_ap;
893 node_get_pref_orport(r, &node_ap);
894 /* XXXX proposal 186 is making this more complex. For now, a conn
895 is canonical when it uses the _preferred_ address. */
896 if (tor_addr_eq(&conn->base_.addr, &node_ap.addr))
897 connection_or_set_canonical(conn, 1);
898 if (!started_here) {
899 /* Override the addr/port, so our log messages will make sense.
900 * This is dangerous, since if we ever try looking up a conn by
901 * its actual addr/port, we won't remember. Careful! */
902 /* XXXX arma: this is stupid, and it's the reason we need real_addr
903 * to track is_canonical properly. What requires it? */
904 /* XXXX <arma> i believe the reason we did this, originally, is because
905 * we wanted to log what OR a connection was to, and if we logged the
906 * right IP address and port 56244, that wouldn't be as helpful. now we
907 * log the "right" port too, so we know if it's moria1 or moria2.
909 tor_addr_copy(&conn->base_.addr, &node_ap.addr);
910 conn->base_.port = node_ap.port;
912 tor_free(conn->nickname);
913 conn->nickname = tor_strdup(node_get_nickname(r));
914 tor_free(conn->base_.address);
915 conn->base_.address = tor_addr_to_str_dup(&node_ap.addr);
916 } else {
917 tor_free(conn->nickname);
918 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
919 conn->nickname[0] = '$';
920 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
921 conn->identity_digest, DIGEST_LEN);
923 tor_free(conn->base_.address);
924 conn->base_.address = tor_addr_to_str_dup(addr);
928 * We have to tell channeltls.c to update the channel marks (local, in
929 * particular), since we may have changed the address.
932 if (conn->chan) {
933 channel_tls_update_marks(conn);
937 /** These just pass all the is_bad_for_new_circs manipulation on to
938 * channel_t */
940 static unsigned int
941 connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
943 tor_assert(or_conn);
945 if (or_conn->chan)
946 return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
947 else return 0;
950 static void
951 connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
953 tor_assert(or_conn);
955 if (or_conn->chan)
956 channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
959 /** How old do we let a connection to an OR get before deciding it's
960 * too old for new circuits? */
961 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
963 /** Expire an or_connection if it is too old. Helper for
964 * connection_or_group_set_badness_ and fast path for
965 * channel_rsa_id_group_set_badness.
967 * Returns 1 if the connection was already expired, else 0.
970 connection_or_single_set_badness_(time_t now,
971 or_connection_t *or_conn,
972 int force)
974 /* XXXX this function should also be about channels? */
975 if (or_conn->base_.marked_for_close ||
976 connection_or_is_bad_for_new_circs(or_conn))
977 return 1;
979 if (force ||
980 or_conn->base_.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
981 < now) {
982 log_info(LD_OR,
983 "Marking OR conn to %s:%d as too old for new circuits "
984 "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
985 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
986 (int)(now - or_conn->base_.timestamp_created));
987 connection_or_mark_bad_for_new_circs(or_conn);
990 return 0;
993 /** Given a list of all the or_connections with a given
994 * identity, set elements of that list as is_bad_for_new_circs as
995 * appropriate. Helper for connection_or_set_bad_connections().
997 * Specifically, we set the is_bad_for_new_circs flag on:
998 * - all connections if <b>force</b> is true.
999 * - all connections that are too old.
1000 * - all open non-canonical connections for which a canonical connection
1001 * exists to the same router.
1002 * - all open canonical connections for which a 'better' canonical
1003 * connection exists to the same router.
1004 * - all open non-canonical connections for which a 'better' non-canonical
1005 * connection exists to the same router at the same address.
1007 * See channel_is_better() in channel.c for our idea of what makes one OR
1008 * connection better than another.
1010 void
1011 connection_or_group_set_badness_(smartlist_t *group, int force)
1013 /* XXXX this function should be entirely about channels, not OR
1014 * XXXX connections. */
1016 or_connection_t *best = NULL;
1017 int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
1018 time_t now = time(NULL);
1020 /* Pass 1: expire everything that's old, and see what the status of
1021 * everything else is. */
1022 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1023 if (connection_or_single_set_badness_(now, or_conn, force))
1024 continue;
1026 if (connection_or_is_bad_for_new_circs(or_conn)) {
1027 ++n_old;
1028 } else if (or_conn->base_.state != OR_CONN_STATE_OPEN) {
1029 ++n_inprogress;
1030 } else if (or_conn->is_canonical) {
1031 ++n_canonical;
1032 } else {
1033 ++n_other;
1035 } SMARTLIST_FOREACH_END(or_conn);
1037 /* Pass 2: We know how about how good the best connection is.
1038 * expire everything that's worse, and find the very best if we can. */
1039 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1040 if (or_conn->base_.marked_for_close ||
1041 connection_or_is_bad_for_new_circs(or_conn))
1042 continue; /* This one doesn't need to be marked bad. */
1043 if (or_conn->base_.state != OR_CONN_STATE_OPEN)
1044 continue; /* Don't mark anything bad until we have seen what happens
1045 * when the connection finishes. */
1046 if (n_canonical && !or_conn->is_canonical) {
1047 /* We have at least one open canonical connection to this router,
1048 * and this one is open but not canonical. Mark it bad. */
1049 log_info(LD_OR,
1050 "Marking OR conn to %s:%d as unsuitable for new circuits: "
1051 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). It is not "
1052 "canonical, and we have another connection to that OR that is.",
1053 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1054 (int)(now - or_conn->base_.timestamp_created));
1055 connection_or_mark_bad_for_new_circs(or_conn);
1056 continue;
1059 if (!best ||
1060 channel_is_better(TLS_CHAN_TO_BASE(or_conn->chan),
1061 TLS_CHAN_TO_BASE(best->chan))) {
1062 best = or_conn;
1064 } SMARTLIST_FOREACH_END(or_conn);
1066 if (!best)
1067 return;
1069 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
1070 * every other open connection. If it's non-canonical, mark as bad
1071 * every other open connection to the same address.
1073 * XXXX This isn't optimal; if we have connections to an OR at multiple
1074 * addresses, we'd like to pick the best _for each address_, and mark as
1075 * bad every open connection that isn't best for its address. But this
1076 * can only occur in cases where the other OR is old (so we have no
1077 * canonical connection to it), or where all the connections to the OR are
1078 * at noncanonical addresses and we have no good direct connection (which
1079 * means we aren't at risk of attaching circuits to it anyway). As
1080 * 0.1.2.x dies out, the first case will go away, and the second one is
1081 * "mostly harmless", so a fix can wait until somebody is bored.
1083 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1084 if (or_conn->base_.marked_for_close ||
1085 connection_or_is_bad_for_new_circs(or_conn) ||
1086 or_conn->base_.state != OR_CONN_STATE_OPEN)
1087 continue;
1088 if (or_conn != best &&
1089 channel_is_better(TLS_CHAN_TO_BASE(best->chan),
1090 TLS_CHAN_TO_BASE(or_conn->chan))) {
1091 /* This isn't the best conn, _and_ the best conn is better than it */
1092 if (best->is_canonical) {
1093 log_info(LD_OR,
1094 "Marking OR conn to %s:%d as unsuitable for new circuits: "
1095 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
1096 "We have a better canonical one "
1097 "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1098 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1099 (int)(now - or_conn->base_.timestamp_created),
1100 best->base_.s, (int)(now - best->base_.timestamp_created));
1101 connection_or_mark_bad_for_new_circs(or_conn);
1102 } else if (!tor_addr_compare(&or_conn->real_addr,
1103 &best->real_addr, CMP_EXACT)) {
1104 log_info(LD_OR,
1105 "Marking OR conn to %s:%d as unsuitable for new circuits: "
1106 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). We have a better "
1107 "one with the "
1108 "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1109 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1110 (int)(now - or_conn->base_.timestamp_created),
1111 best->base_.s, (int)(now - best->base_.timestamp_created));
1112 connection_or_mark_bad_for_new_circs(or_conn);
1115 } SMARTLIST_FOREACH_END(or_conn);
1118 /* Lifetime of a connection failure. After that, we'll retry. This is in
1119 * seconds. */
1120 #define OR_CONNECT_FAILURE_LIFETIME 60
1121 /* The interval to use with when to clean up the failure cache. */
1122 #define OR_CONNECT_FAILURE_CLEANUP_INTERVAL 60
1124 /* When is the next time we have to cleanup the failure map. We keep this
1125 * because we clean it opportunistically. */
1126 static time_t or_connect_failure_map_next_cleanup_ts = 0;
1128 /* OR connection failure entry data structure. It is kept in the connection
1129 * failure map defined below and indexed by OR identity digest, address and
1130 * port.
1132 * We need to identify a connection failure with these three values because we
1133 * want to avoid to wrongfully blacklist a relay if someone is trying to
1134 * extend to a known identity digest but with the wrong IP/port. For instance,
1135 * it can happen if a relay changed its port but the client still has an old
1136 * descriptor with the old port. We want to stop connecting to that
1137 * IP/port/identity all together, not only the relay identity. */
1138 typedef struct or_connect_failure_entry_t {
1139 HT_ENTRY(or_connect_failure_entry_t) node;
1140 /* Identity digest of the connection where it is connecting to. */
1141 uint8_t identity_digest[DIGEST_LEN];
1142 /* This is the connection address from the base connection_t. After the
1143 * connection is checked for canonicity, the base address should represent
1144 * what we know instead of where we are connecting to. This is what we need
1145 * so we can correlate known relays within the consensus. */
1146 tor_addr_t addr;
1147 uint16_t port;
1148 /* Last time we were unable to connect. */
1149 time_t last_failed_connect_ts;
1150 } or_connect_failure_entry_t;
1152 /* Map where we keep connection failure entries. They are indexed by addr,
1153 * port and identity digest. */
1154 static HT_HEAD(or_connect_failure_ht, or_connect_failure_entry_t)
1155 or_connect_failures_map = HT_INITIALIZER();
1157 /* Helper: Hashtable equal function. Return 1 if equal else 0. */
1158 static int
1159 or_connect_failure_ht_eq(const or_connect_failure_entry_t *a,
1160 const or_connect_failure_entry_t *b)
1162 return fast_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN) &&
1163 tor_addr_eq(&a->addr, &b->addr) &&
1164 a->port == b->port;
1167 /* Helper: Return the hash for the hashtable of the given entry. For this
1168 * table, it is a combination of address, port and identity digest. */
1169 static unsigned int
1170 or_connect_failure_ht_hash(const or_connect_failure_entry_t *entry)
1172 size_t offset = 0, addr_size;
1173 const void *addr_ptr;
1174 /* Largest size is IPv6 and IPv4 is smaller so it is fine. */
1175 uint8_t data[16 + sizeof(uint16_t) + DIGEST_LEN];
1177 /* Get the right address bytes depending on the family. */
1178 switch (tor_addr_family(&entry->addr)) {
1179 case AF_INET:
1180 addr_size = 4;
1181 addr_ptr = &entry->addr.addr.in_addr.s_addr;
1182 break;
1183 case AF_INET6:
1184 addr_size = 16;
1185 addr_ptr = &entry->addr.addr.in6_addr.s6_addr;
1186 break;
1187 default:
1188 tor_assert_nonfatal_unreached();
1189 return 0;
1192 memcpy(data, addr_ptr, addr_size);
1193 offset += addr_size;
1194 memcpy(data + offset, entry->identity_digest, DIGEST_LEN);
1195 offset += DIGEST_LEN;
1196 set_uint16(data + offset, entry->port);
1197 offset += sizeof(uint16_t);
1199 return (unsigned int) siphash24g(data, offset);
1202 HT_PROTOTYPE(or_connect_failure_ht, or_connect_failure_entry_t, node,
1203 or_connect_failure_ht_hash, or_connect_failure_ht_eq)
1205 HT_GENERATE2(or_connect_failure_ht, or_connect_failure_entry_t, node,
1206 or_connect_failure_ht_hash, or_connect_failure_ht_eq,
1207 0.6, tor_reallocarray_, tor_free_)
1209 /* Initialize a given connect failure entry with the given identity_digest,
1210 * addr and port. All field are optional except ocf. */
1211 static void
1212 or_connect_failure_init(const char *identity_digest, const tor_addr_t *addr,
1213 uint16_t port, or_connect_failure_entry_t *ocf)
1215 tor_assert(ocf);
1216 if (identity_digest) {
1217 memcpy(ocf->identity_digest, identity_digest,
1218 sizeof(ocf->identity_digest));
1220 if (addr) {
1221 tor_addr_copy(&ocf->addr, addr);
1223 ocf->port = port;
1226 /* Return a newly allocated connection failure entry. It is initialized with
1227 * the given or_conn data. This can't fail. */
1228 static or_connect_failure_entry_t *
1229 or_connect_failure_new(const or_connection_t *or_conn)
1231 or_connect_failure_entry_t *ocf = tor_malloc_zero(sizeof(*ocf));
1232 or_connect_failure_init(or_conn->identity_digest, &or_conn->real_addr,
1233 TO_CONN(or_conn)->port, ocf);
1234 return ocf;
1237 /* Return a connection failure entry matching the given or_conn. NULL is
1238 * returned if not found. */
1239 static or_connect_failure_entry_t *
1240 or_connect_failure_find(const or_connection_t *or_conn)
1242 or_connect_failure_entry_t lookup;
1243 tor_assert(or_conn);
1244 or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
1245 TO_CONN(or_conn)->port, &lookup);
1246 return HT_FIND(or_connect_failure_ht, &or_connect_failures_map, &lookup);
1249 /* Note down in the connection failure cache that a failure occurred on the
1250 * given or_conn. */
1251 STATIC void
1252 note_or_connect_failed(const or_connection_t *or_conn)
1254 or_connect_failure_entry_t *ocf = NULL;
1256 tor_assert(or_conn);
1258 ocf = or_connect_failure_find(or_conn);
1259 if (ocf == NULL) {
1260 ocf = or_connect_failure_new(or_conn);
1261 HT_INSERT(or_connect_failure_ht, &or_connect_failures_map, ocf);
1263 ocf->last_failed_connect_ts = approx_time();
1266 /* Cleanup the connection failure cache and remove all entries below the
1267 * given cutoff. */
1268 static void
1269 or_connect_failure_map_cleanup(time_t cutoff)
1271 or_connect_failure_entry_t **ptr, **next, *entry;
1273 for (ptr = HT_START(or_connect_failure_ht, &or_connect_failures_map);
1274 ptr != NULL; ptr = next) {
1275 entry = *ptr;
1276 if (entry->last_failed_connect_ts <= cutoff) {
1277 next = HT_NEXT_RMV(or_connect_failure_ht, &or_connect_failures_map, ptr);
1278 tor_free(entry);
1279 } else {
1280 next = HT_NEXT(or_connect_failure_ht, &or_connect_failures_map, ptr);
1285 /* Return true iff the given OR connection can connect to its destination that
1286 * is the triplet identity_digest, address and port.
1288 * The or_conn MUST have gone through connection_or_check_canonicity() so the
1289 * base address is properly set to what we know or doesn't know. */
1290 STATIC int
1291 should_connect_to_relay(const or_connection_t *or_conn)
1293 time_t now, cutoff;
1294 time_t connect_failed_since_ts = 0;
1295 or_connect_failure_entry_t *ocf;
1297 tor_assert(or_conn);
1299 now = approx_time();
1300 cutoff = now - OR_CONNECT_FAILURE_LIFETIME;
1302 /* Opportunistically try to cleanup the failure cache. We do that at regular
1303 * interval so it doesn't grow too big. */
1304 if (or_connect_failure_map_next_cleanup_ts <= now) {
1305 or_connect_failure_map_cleanup(cutoff);
1306 or_connect_failure_map_next_cleanup_ts =
1307 now + OR_CONNECT_FAILURE_CLEANUP_INTERVAL;
1310 /* Look if we have failed previously to the same destination as this
1311 * OR connection. */
1312 ocf = or_connect_failure_find(or_conn);
1313 if (ocf) {
1314 connect_failed_since_ts = ocf->last_failed_connect_ts;
1316 /* If we do have an unable to connect timestamp and it is below cutoff, we
1317 * can connect. Or we have never failed before so let it connect. */
1318 if (connect_failed_since_ts > cutoff) {
1319 goto no_connect;
1322 /* Ok we can connect! */
1323 return 1;
1324 no_connect:
1325 return 0;
1328 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
1329 * a TCP connection. Send notifications appropriately.
1331 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1332 * <b>msg</b> specifies the strerror-style error message.
1334 void
1335 connection_or_connect_failed(or_connection_t *conn,
1336 int reason, const char *msg)
1338 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
1339 if (!authdir_mode_tests_reachability(get_options()))
1340 control_event_bootstrap_prob_or(msg, reason, conn);
1341 note_or_connect_failed(conn);
1344 /** <b>conn</b> got an error in connection_handle_read_impl() or
1345 * connection_handle_write_impl() and is going to die soon.
1347 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1348 * <b>msg</b> specifies the strerror-style error message.
1350 void
1351 connection_or_notify_error(or_connection_t *conn,
1352 int reason, const char *msg)
1354 channel_t *chan;
1356 tor_assert(conn);
1358 /* If we're connecting, call connect_failed() too */
1359 if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
1360 connection_or_connect_failed(conn, reason, msg);
1362 /* Tell the controlling channel if we have one */
1363 if (conn->chan) {
1364 chan = TLS_CHAN_TO_BASE(conn->chan);
1365 /* Don't transition if we're already in closing, closed or error */
1366 if (!CHANNEL_CONDEMNED(chan)) {
1367 channel_close_for_error(chan);
1371 /* No need to mark for error because connection.c is about to do that */
1374 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
1375 * handshake with an OR with identity digest <b>id_digest</b>. Optionally,
1376 * pass in a pointer to a channel using this connection.
1378 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
1379 * return that connection. If the connect() is in progress, set the
1380 * new conn's state to 'connecting' and return it. If connect() succeeds,
1381 * call connection_tls_start_handshake() on it.
1383 * This function is called from router_retry_connections(), for
1384 * ORs connecting to ORs, and circuit_establish_circuit(), for
1385 * OPs connecting to ORs.
1387 * Return the launched conn, or NULL if it failed.
1390 MOCK_IMPL(or_connection_t *,
1391 connection_or_connect, (const tor_addr_t *_addr, uint16_t port,
1392 const char *id_digest,
1393 const ed25519_public_key_t *ed_id,
1394 channel_tls_t *chan))
1396 or_connection_t *conn;
1397 const or_options_t *options = get_options();
1398 int socket_error = 0;
1399 tor_addr_t addr;
1401 int r;
1402 tor_addr_t proxy_addr;
1403 uint16_t proxy_port;
1404 int proxy_type;
1406 tor_assert(_addr);
1407 tor_assert(id_digest);
1408 tor_addr_copy(&addr, _addr);
1410 if (server_mode(options) && router_digest_is_me(id_digest)) {
1411 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
1412 return NULL;
1414 if (server_mode(options) && router_ed25519_id_is_me(ed_id)) {
1415 log_info(LD_PROTOCOL,"Client asked me to connect to myself by Ed25519 "
1416 "identity. Refusing.");
1417 return NULL;
1420 conn = or_connection_new(CONN_TYPE_OR, tor_addr_family(&addr));
1423 * Set up conn so it's got all the data we need to remember for channels
1425 * This stuff needs to happen before connection_or_init_conn_from_address()
1426 * so connection_or_set_identity_digest() and such know where to look to
1427 * keep the channel up to date.
1429 conn->chan = chan;
1430 chan->conn = conn;
1431 connection_or_init_conn_from_address(conn, &addr, port, id_digest, ed_id, 1);
1433 /* We have a proper OR connection setup, now check if we can connect to it
1434 * that is we haven't had a failure earlier. This is to avoid to try to
1435 * constantly connect to relays that we think are not reachable. */
1436 if (!should_connect_to_relay(conn)) {
1437 log_info(LD_GENERAL, "Can't connect to identity %s at %s:%u because we "
1438 "failed earlier. Refusing.",
1439 hex_str(id_digest, DIGEST_LEN), fmt_addr(&TO_CONN(conn)->addr),
1440 TO_CONN(conn)->port);
1441 connection_free_(TO_CONN(conn));
1442 return NULL;
1445 connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
1446 control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1448 conn->is_outgoing = 1;
1450 /* If we are using a proxy server, find it and use it. */
1451 r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, TO_CONN(conn));
1452 if (r == 0) {
1453 conn->proxy_type = proxy_type;
1454 if (proxy_type != PROXY_NONE) {
1455 tor_addr_copy(&addr, &proxy_addr);
1456 port = proxy_port;
1457 conn->base_.proxy_state = PROXY_INFANT;
1459 } else {
1460 /* get_proxy_addrport() might fail if we have a Bridge line that
1461 references a transport, but no ClientTransportPlugin lines
1462 defining its transport proxy. If this is the case, let's try to
1463 output a useful log message to the user. */
1464 const char *transport_name =
1465 find_transport_name_by_bridge_addrport(&TO_CONN(conn)->addr,
1466 TO_CONN(conn)->port);
1468 if (transport_name) {
1469 log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
1470 "using pluggable transport '%s', but we can't find a pluggable "
1471 "transport proxy supporting '%s'. This can happen if you "
1472 "haven't provided a ClientTransportPlugin line, or if "
1473 "your pluggable transport proxy stopped running.",
1474 fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port),
1475 transport_name, transport_name);
1477 control_event_bootstrap_prob_or(
1478 "Can't connect to bridge",
1479 END_OR_CONN_REASON_PT_MISSING,
1480 conn);
1482 } else {
1483 log_warn(LD_GENERAL, "Tried to connect to '%s' through a proxy, but "
1484 "the proxy address could not be found.",
1485 fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port));
1488 connection_free_(TO_CONN(conn));
1489 return NULL;
1492 switch (connection_connect(TO_CONN(conn), conn->base_.address,
1493 &addr, port, &socket_error)) {
1494 case -1:
1495 /* We failed to establish a connection probably because of a local
1496 * error. No need to blame the guard in this case. Notify the networking
1497 * system of this failure. */
1498 connection_or_connect_failed(conn,
1499 errno_to_orconn_end_reason(socket_error),
1500 tor_socket_strerror(socket_error));
1501 connection_free_(TO_CONN(conn));
1502 return NULL;
1503 case 0:
1504 connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
1505 /* writable indicates finish, readable indicates broken link,
1506 error indicates broken link on windows */
1507 return conn;
1508 /* case 1: fall through */
1511 if (connection_or_finished_connecting(conn) < 0) {
1512 /* already marked for close */
1513 return NULL;
1515 return conn;
1518 /** Mark orconn for close and transition the associated channel, if any, to
1519 * the closing state.
1521 * It's safe to call this and connection_or_close_for_error() any time, and
1522 * channel layer will treat it as a connection closing for reasons outside
1523 * its control, like the remote end closing it. It can also be a local
1524 * reason that's specific to connection_t/or_connection_t rather than
1525 * the channel mechanism, such as expiration of old connections in
1526 * run_connection_housekeeping(). If you want to close a channel_t
1527 * from somewhere that logically works in terms of generic channels
1528 * rather than connections, use channel_mark_for_close(); see also
1529 * the comment on that function in channel.c.
1532 void
1533 connection_or_close_normally(or_connection_t *orconn, int flush)
1535 channel_t *chan = NULL;
1537 tor_assert(orconn);
1538 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1539 else connection_mark_for_close_internal(TO_CONN(orconn));
1540 if (orconn->chan) {
1541 chan = TLS_CHAN_TO_BASE(orconn->chan);
1542 /* Don't transition if we're already in closing, closed or error */
1543 if (!CHANNEL_CONDEMNED(chan)) {
1544 channel_close_from_lower_layer(chan);
1549 /** Mark orconn for close and transition the associated channel, if any, to
1550 * the error state.
1553 MOCK_IMPL(void,
1554 connection_or_close_for_error,(or_connection_t *orconn, int flush))
1556 channel_t *chan = NULL;
1558 tor_assert(orconn);
1559 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1560 else connection_mark_for_close_internal(TO_CONN(orconn));
1561 if (orconn->chan) {
1562 chan = TLS_CHAN_TO_BASE(orconn->chan);
1563 /* Don't transition if we're already in closing, closed or error */
1564 if (!CHANNEL_CONDEMNED(chan)) {
1565 channel_close_for_error(chan);
1570 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
1571 * we initiated the connection, else it's 1.
1573 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
1574 * pass <b>conn</b> to connection_tls_continue_handshake().
1576 * Return -1 if <b>conn</b> is broken, else return 0.
1578 MOCK_IMPL(int,
1579 connection_tls_start_handshake,(or_connection_t *conn, int receiving))
1581 channel_listener_t *chan_listener;
1582 channel_t *chan;
1584 /* Incoming connections will need a new channel passed to the
1585 * channel_tls_listener */
1586 if (receiving) {
1587 /* It shouldn't already be set */
1588 tor_assert(!(conn->chan));
1589 chan_listener = channel_tls_get_listener();
1590 if (!chan_listener) {
1591 chan_listener = channel_tls_start_listener();
1592 command_setup_listener(chan_listener);
1594 chan = channel_tls_handle_incoming(conn);
1595 channel_listener_queue_incoming(chan_listener, chan);
1598 connection_or_change_state(conn, OR_CONN_STATE_TLS_HANDSHAKING);
1599 tor_assert(!conn->tls);
1600 conn->tls = tor_tls_new(conn->base_.s, receiving);
1601 if (!conn->tls) {
1602 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
1603 return -1;
1605 tor_tls_set_logged_address(conn->tls, // XXX client and relay?
1606 escaped_safe_str(conn->base_.address));
1608 connection_start_reading(TO_CONN(conn));
1609 log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
1610 conn->base_.s);
1612 if (connection_tls_continue_handshake(conn) < 0)
1613 return -1;
1615 return 0;
1618 /** Block all future attempts to renegotiate on 'conn' */
1619 void
1620 connection_or_block_renegotiation(or_connection_t *conn)
1622 tor_tls_t *tls = conn->tls;
1623 if (!tls)
1624 return;
1625 tor_tls_set_renegotiate_callback(tls, NULL, NULL);
1626 tor_tls_block_renegotiation(tls);
1629 /** Invoked on the server side from inside tor_tls_read() when the server
1630 * gets a successful TLS renegotiation from the client. */
1631 static void
1632 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
1634 or_connection_t *conn = _conn;
1635 (void)tls;
1637 /* Don't invoke this again. */
1638 connection_or_block_renegotiation(conn);
1640 if (connection_tls_finish_handshake(conn) < 0) {
1641 /* XXXX_TLS double-check that it's ok to do this from inside read. */
1642 /* XXXX_TLS double-check that this verifies certificates. */
1643 connection_or_close_for_error(conn, 0);
1647 /** Move forward with the tls handshake. If it finishes, hand
1648 * <b>conn</b> to connection_tls_finish_handshake().
1650 * Return -1 if <b>conn</b> is broken, else return 0.
1653 connection_tls_continue_handshake(or_connection_t *conn)
1655 int result;
1656 check_no_tls_errors();
1658 tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
1659 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
1660 result = tor_tls_handshake(conn->tls);
1661 // log_notice(LD_OR, "Result: %d", result);
1663 switch (result) {
1664 CASE_TOR_TLS_ERROR_ANY:
1665 log_info(LD_OR,"tls error [%s]. breaking connection.",
1666 tor_tls_err_to_string(result));
1667 return -1;
1668 case TOR_TLS_DONE:
1669 if (! tor_tls_used_v1_handshake(conn->tls)) {
1670 if (!tor_tls_is_server(conn->tls)) {
1671 tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
1672 return connection_or_launch_v3_or_handshake(conn);
1673 } else {
1674 /* v2/v3 handshake, but we are not a client. */
1675 log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
1676 "Expecting renegotiation or VERSIONS cell");
1677 tor_tls_set_renegotiate_callback(conn->tls,
1678 connection_or_tls_renegotiated_cb,
1679 conn);
1680 connection_or_change_state(conn,
1681 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1682 connection_stop_writing(TO_CONN(conn));
1683 connection_start_reading(TO_CONN(conn));
1684 return 0;
1687 tor_assert(tor_tls_is_server(conn->tls));
1688 return connection_tls_finish_handshake(conn);
1689 case TOR_TLS_WANTWRITE:
1690 connection_start_writing(TO_CONN(conn));
1691 log_debug(LD_OR,"wanted write");
1692 return 0;
1693 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
1694 log_debug(LD_OR,"wanted read");
1695 return 0;
1696 case TOR_TLS_CLOSE:
1697 log_info(LD_OR,"tls closed. breaking connection.");
1698 return -1;
1700 return 0;
1703 /** Return 1 if we initiated this connection, or 0 if it started
1704 * out as an incoming connection.
1707 connection_or_nonopen_was_started_here(or_connection_t *conn)
1709 tor_assert(conn->base_.type == CONN_TYPE_OR ||
1710 conn->base_.type == CONN_TYPE_EXT_OR);
1711 if (!conn->tls)
1712 return 1; /* it's still in proxy states or something */
1713 if (conn->handshake_state)
1714 return conn->handshake_state->started_here;
1715 return !tor_tls_is_server(conn->tls);
1718 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
1719 * return -1 if they are lying, broken, or otherwise something is wrong.
1721 * If we initiated this connection (<b>started_here</b> is true), make sure
1722 * the other side sent a correctly formed certificate. If I initiated the
1723 * connection, make sure it's the right relay by checking the certificate.
1725 * Otherwise (if we _didn't_ initiate this connection), it's okay for
1726 * the certificate to be weird or absent.
1728 * If we return 0, and the certificate is as expected, write a hash of the
1729 * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
1730 * space in it.
1731 * If the certificate is invalid or missing on an incoming connection,
1732 * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
1733 * (If we return -1, the contents of this buffer are undefined.)
1735 * As side effects,
1736 * 1) Set conn->circ_id_type according to tor-spec.txt.
1737 * 2) If we're an authdirserver and we initiated the connection: drop all
1738 * descriptors that claim to be on that IP/port but that aren't
1739 * this relay; and note that this relay is reachable.
1740 * 3) If this is a bridge and we didn't configure its identity
1741 * fingerprint, remember the keyid we just learned.
1743 static int
1744 connection_or_check_valid_tls_handshake(or_connection_t *conn,
1745 int started_here,
1746 char *digest_rcvd_out)
1748 crypto_pk_t *identity_rcvd=NULL;
1749 const or_options_t *options = get_options();
1750 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1751 const char *safe_address =
1752 started_here ? conn->base_.address :
1753 safe_str_client(conn->base_.address);
1754 const char *conn_type = started_here ? "outgoing" : "incoming";
1755 int has_cert = 0;
1757 check_no_tls_errors();
1758 has_cert = tor_tls_peer_has_cert(conn->tls);
1759 if (started_here && !has_cert) {
1760 log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
1761 "send a cert! Closing.",
1762 safe_address, conn->base_.port);
1763 return -1;
1764 } else if (!has_cert) {
1765 log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
1766 "That's ok.");
1768 check_no_tls_errors();
1770 if (has_cert) {
1771 int v = tor_tls_verify(started_here?severity:LOG_INFO,
1772 conn->tls, &identity_rcvd);
1773 if (started_here && v<0) {
1774 log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
1775 " has a cert but it's invalid. Closing.",
1776 safe_address, conn->base_.port);
1777 return -1;
1778 } else if (v<0) {
1779 log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
1780 "chain; ignoring.");
1781 } else {
1782 log_debug(LD_HANDSHAKE,
1783 "The certificate seems to be valid on %s connection "
1784 "with %s:%d", conn_type, safe_address, conn->base_.port);
1786 check_no_tls_errors();
1789 if (identity_rcvd) {
1790 if (crypto_pk_get_digest(identity_rcvd, digest_rcvd_out) < 0) {
1791 crypto_pk_free(identity_rcvd);
1792 return -1;
1794 } else {
1795 memset(digest_rcvd_out, 0, DIGEST_LEN);
1798 tor_assert(conn->chan);
1799 channel_set_circid_type(TLS_CHAN_TO_BASE(conn->chan), identity_rcvd, 1);
1801 crypto_pk_free(identity_rcvd);
1803 if (started_here) {
1804 /* A TLS handshake can't teach us an Ed25519 ID, so we set it to NULL
1805 * here. */
1806 log_debug(LD_HANDSHAKE, "Calling client_learned_peer_id from "
1807 "check_valid_tls_handshake");
1808 return connection_or_client_learned_peer_id(conn,
1809 (const uint8_t*)digest_rcvd_out,
1810 NULL);
1813 return 0;
1816 /** Called when we (as a connection initiator) have definitively,
1817 * authenticatedly, learned that ID of the Tor instance on the other
1818 * side of <b>conn</b> is <b>rsa_peer_id</b> and optionally <b>ed_peer_id</b>.
1819 * For v1 and v2 handshakes,
1820 * this is right after we get a certificate chain in a TLS handshake
1821 * or renegotiation. For v3+ handshakes, this is right after we get a
1822 * certificate chain in a CERTS cell.
1824 * If we did not know the ID before, record the one we got.
1826 * If we wanted an ID, but we didn't get the one we expected, log a message
1827 * and return -1.
1828 * On relays:
1829 * - log a protocol warning whenever the fingerprints don't match;
1830 * On clients:
1831 * - if a relay's fingerprint doesn't match, log a warning;
1832 * - if we don't have updated relay fingerprints from a recent consensus, and
1833 * a fallback directory mirror's hard-coded fingerprint has changed, log an
1834 * info explaining that we will try another fallback.
1836 * If we're testing reachability, remember what we learned.
1838 * Return 0 on success, -1 on failure.
1841 connection_or_client_learned_peer_id(or_connection_t *conn,
1842 const uint8_t *rsa_peer_id,
1843 const ed25519_public_key_t *ed_peer_id)
1845 const or_options_t *options = get_options();
1846 channel_tls_t *chan_tls = conn->chan;
1847 channel_t *chan = channel_tls_to_base(chan_tls);
1848 int changed_identity = 0;
1849 tor_assert(chan);
1851 const int expected_rsa_key =
1852 ! tor_digest_is_zero(conn->identity_digest);
1853 const int expected_ed_key =
1854 ! ed25519_public_key_is_zero(&chan->ed25519_identity);
1856 log_info(LD_HANDSHAKE, "learned peer id for %p (%s): %s, %s",
1857 conn,
1858 safe_str_client(conn->base_.address),
1859 hex_str((const char*)rsa_peer_id, DIGEST_LEN),
1860 ed25519_fmt(ed_peer_id));
1862 if (! expected_rsa_key && ! expected_ed_key) {
1863 log_info(LD_HANDSHAKE, "(we had no ID in mind when we made this "
1864 "connection.");
1865 connection_or_set_identity_digest(conn,
1866 (const char*)rsa_peer_id, ed_peer_id);
1867 tor_free(conn->nickname);
1868 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1869 conn->nickname[0] = '$';
1870 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
1871 conn->identity_digest, DIGEST_LEN);
1872 log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
1873 "its key. Hoping for the best.",
1874 conn->nickname, conn->base_.address, conn->base_.port);
1875 /* if it's a bridge and we didn't know its identity fingerprint, now
1876 * we do -- remember it for future attempts. */
1877 learned_router_identity(&conn->base_.addr, conn->base_.port,
1878 (const char*)rsa_peer_id, ed_peer_id);
1879 changed_identity = 1;
1882 const int rsa_mismatch = expected_rsa_key &&
1883 tor_memneq(rsa_peer_id, conn->identity_digest, DIGEST_LEN);
1884 /* It only counts as an ed25519 mismatch if we wanted an ed25519 identity
1885 * and didn't get it. It's okay if we get one that we didn't ask for. */
1886 const int ed25519_mismatch =
1887 expected_ed_key &&
1888 (ed_peer_id == NULL ||
1889 ! ed25519_pubkey_eq(&chan->ed25519_identity, ed_peer_id));
1891 if (rsa_mismatch || ed25519_mismatch) {
1892 /* I was aiming for a particular digest. I didn't get it! */
1893 char seen_rsa[HEX_DIGEST_LEN+1];
1894 char expected_rsa[HEX_DIGEST_LEN+1];
1895 char seen_ed[ED25519_BASE64_LEN+1];
1896 char expected_ed[ED25519_BASE64_LEN+1];
1897 base16_encode(seen_rsa, sizeof(seen_rsa),
1898 (const char*)rsa_peer_id, DIGEST_LEN);
1899 base16_encode(expected_rsa, sizeof(expected_rsa), conn->identity_digest,
1900 DIGEST_LEN);
1901 if (ed_peer_id) {
1902 ed25519_public_to_base64(seen_ed, ed_peer_id);
1903 } else {
1904 strlcpy(seen_ed, "no ed25519 key", sizeof(seen_ed));
1906 if (! ed25519_public_key_is_zero(&chan->ed25519_identity)) {
1907 ed25519_public_to_base64(expected_ed, &chan->ed25519_identity);
1908 } else {
1909 strlcpy(expected_ed, "no ed25519 key", sizeof(expected_ed));
1911 const int using_hardcoded_fingerprints =
1912 !networkstatus_get_reasonably_live_consensus(time(NULL),
1913 usable_consensus_flavor());
1914 const int is_fallback_fingerprint = router_digest_is_fallback_dir(
1915 conn->identity_digest);
1916 const int is_authority_fingerprint = router_digest_is_trusted_dir(
1917 conn->identity_digest);
1918 int severity;
1919 const char *extra_log = "";
1921 if (server_mode(options)) {
1922 severity = LOG_PROTOCOL_WARN;
1923 } else {
1924 if (using_hardcoded_fingerprints) {
1925 /* We need to do the checks in this order, because the list of
1926 * fallbacks includes the list of authorities */
1927 if (is_authority_fingerprint) {
1928 severity = LOG_WARN;
1929 } else if (is_fallback_fingerprint) {
1930 /* we expect a small number of fallbacks to change from their
1931 * hard-coded fingerprints over the life of a release */
1932 severity = LOG_INFO;
1933 extra_log = " Tor will try a different fallback.";
1934 } else {
1935 /* it's a bridge, it's either a misconfiguration, or unexpected */
1936 severity = LOG_WARN;
1938 } else {
1939 /* a relay has changed its fingerprint from the one in the consensus */
1940 severity = LOG_WARN;
1944 log_fn(severity, LD_HANDSHAKE,
1945 "Tried connecting to router at %s:%d, but RSA identity key was not "
1946 "as expected: wanted %s + %s but got %s + %s.%s",
1947 conn->base_.address, conn->base_.port,
1948 expected_rsa, expected_ed, seen_rsa, seen_ed, extra_log);
1950 /* Tell the new guard API about the channel failure */
1951 entry_guard_chan_failed(TLS_CHAN_TO_BASE(conn->chan));
1952 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
1953 END_OR_CONN_REASON_OR_IDENTITY);
1954 if (!authdir_mode_tests_reachability(options))
1955 control_event_bootstrap_prob_or(
1956 "Unexpected identity in router certificate",
1957 END_OR_CONN_REASON_OR_IDENTITY,
1958 conn);
1959 return -1;
1962 if (!expected_ed_key && ed_peer_id) {
1963 log_info(LD_HANDSHAKE, "(we had no Ed25519 ID in mind when we made this "
1964 "connection.");
1965 connection_or_set_identity_digest(conn,
1966 (const char*)rsa_peer_id, ed_peer_id);
1967 changed_identity = 1;
1970 if (changed_identity) {
1971 /* If we learned an identity for this connection, then we might have
1972 * just discovered it to be canonical. */
1973 connection_or_check_canonicity(conn, conn->handshake_state->started_here);
1976 if (authdir_mode_tests_reachability(options)) {
1977 dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
1978 (const char*)rsa_peer_id, ed_peer_id);
1981 return 0;
1984 /** Return when we last used this channel for client activity (origin
1985 * circuits). This is called from connection.c, since client_used is now one
1986 * of the timestamps in channel_t */
1988 time_t
1989 connection_or_client_used(or_connection_t *conn)
1991 tor_assert(conn);
1993 if (conn->chan) {
1994 return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
1995 } else return 0;
1998 /** The v1/v2 TLS handshake is finished.
2000 * Make sure we are happy with the peer we just handshaked with.
2002 * If they initiated the connection, make sure they're not already connected,
2003 * then initialize conn from the information in router.
2005 * If all is successful, call circuit_n_conn_done() to handle events
2006 * that have been pending on the <tls handshake completion. Also set the
2007 * directory to be dirty (only matters if I'm an authdirserver).
2009 * If this is a v2 TLS handshake, send a versions cell.
2011 static int
2012 connection_tls_finish_handshake(or_connection_t *conn)
2014 char digest_rcvd[DIGEST_LEN];
2015 int started_here = connection_or_nonopen_was_started_here(conn);
2017 tor_assert(!started_here);
2019 log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done, using "
2020 "ciphersuite %s. verifying.",
2021 started_here?"outgoing":"incoming",
2022 conn,
2023 safe_str_client(conn->base_.address),
2024 tor_tls_get_ciphersuite_name(conn->tls));
2026 if (connection_or_check_valid_tls_handshake(conn, started_here,
2027 digest_rcvd) < 0)
2028 return -1;
2030 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2032 if (tor_tls_used_v1_handshake(conn->tls)) {
2033 conn->link_proto = 1;
2034 connection_or_init_conn_from_address(conn, &conn->base_.addr,
2035 conn->base_.port, digest_rcvd,
2036 NULL, 0);
2037 tor_tls_block_renegotiation(conn->tls);
2038 rep_hist_note_negotiated_link_proto(1, started_here);
2039 return connection_or_set_state_open(conn);
2040 } else {
2041 connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V2);
2042 if (connection_init_or_handshake_state(conn, started_here) < 0)
2043 return -1;
2044 connection_or_init_conn_from_address(conn, &conn->base_.addr,
2045 conn->base_.port, digest_rcvd,
2046 NULL, 0);
2047 return connection_or_send_versions(conn, 0);
2052 * Called as client when initial TLS handshake is done, and we notice
2053 * that we got a v3-handshake signalling certificate from the server.
2054 * Set up structures, do bookkeeping, and send the versions cell.
2055 * Return 0 on success and -1 on failure.
2057 static int
2058 connection_or_launch_v3_or_handshake(or_connection_t *conn)
2060 tor_assert(connection_or_nonopen_was_started_here(conn));
2062 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2064 connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V3);
2065 if (connection_init_or_handshake_state(conn, 1) < 0)
2066 return -1;
2068 return connection_or_send_versions(conn, 1);
2071 /** Allocate a new connection handshake state for the connection
2072 * <b>conn</b>. Return 0 on success, -1 on failure. */
2074 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
2076 or_handshake_state_t *s;
2077 if (conn->handshake_state) {
2078 log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
2079 return 0;
2081 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
2082 s->started_here = started_here ? 1 : 0;
2083 s->digest_sent_data = 1;
2084 s->digest_received_data = 1;
2085 if (! started_here && get_current_link_cert_cert()) {
2086 s->own_link_cert = tor_cert_dup(get_current_link_cert_cert());
2088 s->certs = or_handshake_certs_new();
2089 s->certs->started_here = s->started_here;
2090 return 0;
2093 /** Free all storage held by <b>state</b>. */
2094 void
2095 or_handshake_state_free_(or_handshake_state_t *state)
2097 if (!state)
2098 return;
2099 crypto_digest_free(state->digest_sent);
2100 crypto_digest_free(state->digest_received);
2101 or_handshake_certs_free(state->certs);
2102 tor_cert_free(state->own_link_cert);
2103 memwipe(state, 0xBE, sizeof(or_handshake_state_t));
2104 tor_free(state);
2108 * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
2109 * false) or received (if <b>incoming</b> is true) during a V3 handshake using
2110 * <b>state</b>.
2112 * (We don't record the cell, but we keep a digest of everything sent or
2113 * received during the v3 handshake, and the client signs it in an
2114 * authenticate cell.)
2116 void
2117 or_handshake_state_record_cell(or_connection_t *conn,
2118 or_handshake_state_t *state,
2119 const cell_t *cell,
2120 int incoming)
2122 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2123 crypto_digest_t *d, **dptr;
2124 packed_cell_t packed;
2125 if (incoming) {
2126 if (!state->digest_received_data)
2127 return;
2128 } else {
2129 if (!state->digest_sent_data)
2130 return;
2132 if (!incoming) {
2133 log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
2134 "while making a handshake digest. But we think we are sending "
2135 "one with type %d.", (int)cell->command);
2137 dptr = incoming ? &state->digest_received : &state->digest_sent;
2138 if (! *dptr)
2139 *dptr = crypto_digest256_new(DIGEST_SHA256);
2141 d = *dptr;
2142 /* Re-packing like this is a little inefficient, but we don't have to do
2143 this very often at all. */
2144 cell_pack(&packed, cell, conn->wide_circ_ids);
2145 crypto_digest_add_bytes(d, packed.body, cell_network_size);
2146 memwipe(&packed, 0, sizeof(packed));
2149 /** Remember that a variable-length <b>cell</b> has been transmitted (if
2150 * <b>incoming</b> is false) or received (if <b>incoming</b> is true) during a
2151 * V3 handshake using <b>state</b>.
2153 * (We don't record the cell, but we keep a digest of everything sent or
2154 * received during the v3 handshake, and the client signs it in an
2155 * authenticate cell.)
2157 void
2158 or_handshake_state_record_var_cell(or_connection_t *conn,
2159 or_handshake_state_t *state,
2160 const var_cell_t *cell,
2161 int incoming)
2163 crypto_digest_t *d, **dptr;
2164 int n;
2165 char buf[VAR_CELL_MAX_HEADER_SIZE];
2166 if (incoming) {
2167 if (!state->digest_received_data)
2168 return;
2169 } else {
2170 if (!state->digest_sent_data)
2171 return;
2173 dptr = incoming ? &state->digest_received : &state->digest_sent;
2174 if (! *dptr)
2175 *dptr = crypto_digest256_new(DIGEST_SHA256);
2177 d = *dptr;
2179 n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
2180 crypto_digest_add_bytes(d, buf, n);
2181 crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
2183 memwipe(buf, 0, sizeof(buf));
2186 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
2187 * as appropriate. Called when we are done with all TLS and OR handshaking.
2190 connection_or_set_state_open(or_connection_t *conn)
2192 connection_or_change_state(conn, OR_CONN_STATE_OPEN);
2193 control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
2195 /* Link protocol 3 appeared in Tor 0.2.3.6-alpha, so any connection
2196 * that uses an earlier link protocol should not be treated as a relay. */
2197 if (conn->link_proto < 3) {
2198 channel_mark_client(TLS_CHAN_TO_BASE(conn->chan));
2201 or_handshake_state_free(conn->handshake_state);
2202 conn->handshake_state = NULL;
2203 connection_start_reading(TO_CONN(conn));
2205 return 0;
2208 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
2209 * For cells that use or affect a circuit, this should only be called by
2210 * connection_or_flush_from_first_active_circuit().
2212 void
2213 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
2215 packed_cell_t networkcell;
2216 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2218 tor_assert(cell);
2219 tor_assert(conn);
2221 cell_pack(&networkcell, cell, conn->wide_circ_ids);
2223 rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
2224 if (cell->command == CELL_PADDING)
2225 rep_hist_padding_count_write(PADDING_TYPE_CELL);
2227 connection_buf_add(networkcell.body, cell_network_size, TO_CONN(conn));
2229 /* Touch the channel's active timestamp if there is one */
2230 if (conn->chan) {
2231 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2233 if (TLS_CHAN_TO_BASE(conn->chan)->currently_padding) {
2234 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_TOTAL);
2235 if (cell->command == CELL_PADDING)
2236 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_CELL);
2240 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2241 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
2244 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
2245 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
2246 * affect a circuit.
2248 MOCK_IMPL(void,
2249 connection_or_write_var_cell_to_buf,(const var_cell_t *cell,
2250 or_connection_t *conn))
2252 int n;
2253 char hdr[VAR_CELL_MAX_HEADER_SIZE];
2254 tor_assert(cell);
2255 tor_assert(conn);
2256 n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
2257 connection_buf_add(hdr, n, TO_CONN(conn));
2258 connection_buf_add((char*)cell->payload,
2259 cell->payload_len, TO_CONN(conn));
2260 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2261 or_handshake_state_record_var_cell(conn, conn->handshake_state, cell, 0);
2263 /* Touch the channel's active timestamp if there is one */
2264 if (conn->chan)
2265 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2268 /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
2269 * inbuf. Return values as for fetch_var_cell_from_buf(). */
2270 static int
2271 connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
2273 connection_t *conn = TO_CONN(or_conn);
2274 return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
2277 /** Process cells from <b>conn</b>'s inbuf.
2279 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
2280 * and hand it to command_process_cell().
2282 * Always return 0.
2284 static int
2285 connection_or_process_cells_from_inbuf(or_connection_t *conn)
2287 var_cell_t *var_cell;
2290 * Note on memory management for incoming cells: below the channel layer,
2291 * we shouldn't need to consider its internal queueing/copying logic. It
2292 * is safe to pass cells to it on the stack or on the heap, but in the
2293 * latter case we must be sure we free them later.
2295 * The incoming cell queue code in channel.c will (in the common case)
2296 * decide it can pass them to the upper layer immediately, in which case
2297 * those functions may run directly on the cell pointers we pass here, or
2298 * it may decide to queue them, in which case it will allocate its own
2299 * buffer and copy the cell.
2302 while (1) {
2303 log_debug(LD_OR,
2304 TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
2305 "(%d pending in tls object).",
2306 conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
2307 tor_tls_get_pending_bytes(conn->tls));
2308 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
2309 if (!var_cell)
2310 return 0; /* not yet. */
2312 /* Touch the channel's active timestamp if there is one */
2313 if (conn->chan)
2314 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2316 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2317 channel_tls_handle_var_cell(var_cell, conn);
2318 var_cell_free(var_cell);
2319 } else {
2320 const int wide_circ_ids = conn->wide_circ_ids;
2321 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2322 char buf[CELL_MAX_NETWORK_SIZE];
2323 cell_t cell;
2324 if (connection_get_inbuf_len(TO_CONN(conn))
2325 < cell_network_size) /* whole response available? */
2326 return 0; /* not yet */
2328 /* Touch the channel's active timestamp if there is one */
2329 if (conn->chan)
2330 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2332 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2333 connection_buf_get_bytes(buf, cell_network_size, TO_CONN(conn));
2335 /* retrieve cell info from buf (create the host-order struct from the
2336 * network-order string) */
2337 cell_unpack(&cell, buf, wide_circ_ids);
2339 channel_tls_handle_cell(&cell, conn);
2344 /** Array of recognized link protocol versions. */
2345 static const uint16_t or_protocol_versions[] = { 1, 2, 3, 4, 5 };
2346 /** Number of versions in <b>or_protocol_versions</b>. */
2347 static const int n_or_protocol_versions =
2348 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
2350 /** Return true iff <b>v</b> is a link protocol version that this Tor
2351 * implementation believes it can support. */
2353 is_or_protocol_version_known(uint16_t v)
2355 int i;
2356 for (i = 0; i < n_or_protocol_versions; ++i) {
2357 if (or_protocol_versions[i] == v)
2358 return 1;
2360 return 0;
2363 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
2364 * link protocol versions that this Tor can support.
2366 * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
2367 * allow protocol version v3 or later. If not <b>v3_plus</b>, this is
2368 * not part of a v3 protocol handshake, so don't allow protocol v3 or
2369 * later.
2372 connection_or_send_versions(or_connection_t *conn, int v3_plus)
2374 var_cell_t *cell;
2375 int i;
2376 int n_versions = 0;
2377 const int min_version = v3_plus ? 3 : 0;
2378 const int max_version = v3_plus ? UINT16_MAX : 2;
2379 tor_assert(conn->handshake_state &&
2380 !conn->handshake_state->sent_versions_at);
2381 cell = var_cell_new(n_or_protocol_versions * 2);
2382 cell->command = CELL_VERSIONS;
2383 for (i = 0; i < n_or_protocol_versions; ++i) {
2384 uint16_t v = or_protocol_versions[i];
2385 if (v < min_version || v > max_version)
2386 continue;
2387 set_uint16(cell->payload+(2*n_versions), htons(v));
2388 ++n_versions;
2390 cell->payload_len = n_versions * 2;
2392 connection_or_write_var_cell_to_buf(cell, conn);
2393 conn->handshake_state->sent_versions_at = time(NULL);
2395 var_cell_free(cell);
2396 return 0;
2399 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
2400 * about their address, our address, and the current time. */
2401 MOCK_IMPL(int,
2402 connection_or_send_netinfo,(or_connection_t *conn))
2404 cell_t cell;
2405 time_t now = time(NULL);
2406 const routerinfo_t *me;
2407 int len;
2408 uint8_t *out;
2410 tor_assert(conn->handshake_state);
2412 if (conn->handshake_state->sent_netinfo) {
2413 log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
2414 "where we already sent one.");
2415 return 0;
2418 memset(&cell, 0, sizeof(cell_t));
2419 cell.command = CELL_NETINFO;
2421 /* Timestamp, if we're a relay. */
2422 if (public_server_mode(get_options()) || ! conn->is_outgoing)
2423 set_uint32(cell.payload, htonl((uint32_t)now));
2425 /* Their address. */
2426 out = cell.payload + 4;
2427 /* We use &conn->real_addr below, unless it hasn't yet been set. If it
2428 * hasn't yet been set, we know that base_.addr hasn't been tampered with
2429 * yet either. */
2430 len = append_address_to_payload(out, !tor_addr_is_null(&conn->real_addr)
2431 ? &conn->real_addr : &conn->base_.addr);
2432 if (len<0)
2433 return -1;
2434 out += len;
2436 /* My address -- only include it if I'm a public relay, or if I'm a
2437 * bridge and this is an incoming connection. If I'm a bridge and this
2438 * is an outgoing connection, act like a normal client and omit it. */
2439 if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
2440 (me = router_get_my_routerinfo())) {
2441 tor_addr_t my_addr;
2442 *out++ = 1 + !tor_addr_is_null(&me->ipv6_addr);
2444 tor_addr_from_ipv4h(&my_addr, me->addr);
2445 len = append_address_to_payload(out, &my_addr);
2446 if (len < 0)
2447 return -1;
2448 out += len;
2450 if (!tor_addr_is_null(&me->ipv6_addr)) {
2451 len = append_address_to_payload(out, &me->ipv6_addr);
2452 if (len < 0)
2453 return -1;
2455 } else {
2456 *out = 0;
2459 conn->handshake_state->digest_sent_data = 0;
2460 conn->handshake_state->sent_netinfo = 1;
2461 connection_or_write_cell_to_buf(&cell, conn);
2463 return 0;
2466 /** Helper used to add an encoded certs to a cert cell */
2467 static void
2468 add_certs_cell_cert_helper(certs_cell_t *certs_cell,
2469 uint8_t cert_type,
2470 const uint8_t *cert_encoded,
2471 size_t cert_len)
2473 tor_assert(cert_len <= UINT16_MAX);
2474 certs_cell_cert_t *ccc = certs_cell_cert_new();
2475 ccc->cert_type = cert_type;
2476 ccc->cert_len = cert_len;
2477 certs_cell_cert_setlen_body(ccc, cert_len);
2478 memcpy(certs_cell_cert_getarray_body(ccc), cert_encoded, cert_len);
2480 certs_cell_add_certs(certs_cell, ccc);
2483 /** Add an encoded X509 cert (stored as <b>cert_len</b> bytes at
2484 * <b>cert_encoded</b>) to the trunnel certs_cell_t object that we are
2485 * building in <b>certs_cell</b>. Set its type field to <b>cert_type</b>.
2486 * (If <b>cert</b> is NULL, take no action.) */
2487 static void
2488 add_x509_cert(certs_cell_t *certs_cell,
2489 uint8_t cert_type,
2490 const tor_x509_cert_t *cert)
2492 if (NULL == cert)
2493 return;
2495 const uint8_t *cert_encoded = NULL;
2496 size_t cert_len;
2497 tor_x509_cert_get_der(cert, &cert_encoded, &cert_len);
2499 add_certs_cell_cert_helper(certs_cell, cert_type, cert_encoded, cert_len);
2502 /** Add an Ed25519 cert from <b>cert</b> to the trunnel certs_cell_t object
2503 * that we are building in <b>certs_cell</b>. Set its type field to
2504 * <b>cert_type</b>. (If <b>cert</b> is NULL, take no action.) */
2505 static void
2506 add_ed25519_cert(certs_cell_t *certs_cell,
2507 uint8_t cert_type,
2508 const tor_cert_t *cert)
2510 if (NULL == cert)
2511 return;
2513 add_certs_cell_cert_helper(certs_cell, cert_type,
2514 cert->encoded, cert->encoded_len);
2517 #ifdef TOR_UNIT_TESTS
2518 int certs_cell_ed25519_disabled_for_testing = 0;
2519 #else
2520 #define certs_cell_ed25519_disabled_for_testing 0
2521 #endif
2523 /** Send a CERTS cell on the connection <b>conn</b>. Return 0 on success, -1
2524 * on failure. */
2526 connection_or_send_certs_cell(or_connection_t *conn)
2528 const tor_x509_cert_t *global_link_cert = NULL, *id_cert = NULL;
2529 tor_x509_cert_t *own_link_cert = NULL;
2530 var_cell_t *cell;
2532 certs_cell_t *certs_cell = NULL;
2534 tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
2536 if (! conn->handshake_state)
2537 return -1;
2539 const int conn_in_server_mode = ! conn->handshake_state->started_here;
2541 /* Get the encoded values of the X509 certificates */
2542 if (tor_tls_get_my_certs(conn_in_server_mode,
2543 &global_link_cert, &id_cert) < 0)
2544 return -1;
2546 if (conn_in_server_mode) {
2547 own_link_cert = tor_tls_get_own_cert(conn->tls);
2549 tor_assert(id_cert);
2551 certs_cell = certs_cell_new();
2553 /* Start adding certs. First the link cert or auth1024 cert. */
2554 if (conn_in_server_mode) {
2555 tor_assert_nonfatal(own_link_cert);
2556 add_x509_cert(certs_cell,
2557 OR_CERT_TYPE_TLS_LINK, own_link_cert);
2558 } else {
2559 tor_assert(global_link_cert);
2560 add_x509_cert(certs_cell,
2561 OR_CERT_TYPE_AUTH_1024, global_link_cert);
2564 /* Next the RSA->RSA ID cert */
2565 add_x509_cert(certs_cell,
2566 OR_CERT_TYPE_ID_1024, id_cert);
2568 /* Next the Ed25519 certs */
2569 add_ed25519_cert(certs_cell,
2570 CERTTYPE_ED_ID_SIGN,
2571 get_master_signing_key_cert());
2572 if (conn_in_server_mode) {
2573 tor_assert_nonfatal(conn->handshake_state->own_link_cert ||
2574 certs_cell_ed25519_disabled_for_testing);
2575 add_ed25519_cert(certs_cell,
2576 CERTTYPE_ED_SIGN_LINK,
2577 conn->handshake_state->own_link_cert);
2578 } else {
2579 add_ed25519_cert(certs_cell,
2580 CERTTYPE_ED_SIGN_AUTH,
2581 get_current_auth_key_cert());
2584 /* And finally the crosscert. */
2586 const uint8_t *crosscert=NULL;
2587 size_t crosscert_len;
2588 get_master_rsa_crosscert(&crosscert, &crosscert_len);
2589 if (crosscert) {
2590 add_certs_cell_cert_helper(certs_cell,
2591 CERTTYPE_RSA1024_ID_EDID,
2592 crosscert, crosscert_len);
2596 /* We've added all the certs; make the cell. */
2597 certs_cell->n_certs = certs_cell_getlen_certs(certs_cell);
2599 ssize_t alloc_len = certs_cell_encoded_len(certs_cell);
2600 tor_assert(alloc_len >= 0 && alloc_len <= UINT16_MAX);
2601 cell = var_cell_new(alloc_len);
2602 cell->command = CELL_CERTS;
2603 ssize_t enc_len = certs_cell_encode(cell->payload, alloc_len, certs_cell);
2604 tor_assert(enc_len > 0 && enc_len <= alloc_len);
2605 cell->payload_len = enc_len;
2607 connection_or_write_var_cell_to_buf(cell, conn);
2608 var_cell_free(cell);
2609 certs_cell_free(certs_cell);
2610 tor_x509_cert_free(own_link_cert);
2612 return 0;
2615 /** Return true iff <b>challenge_type</b> is an AUTHCHALLENGE type that
2616 * we can send and receive. */
2618 authchallenge_type_is_supported(uint16_t challenge_type)
2620 switch (challenge_type) {
2621 case AUTHTYPE_RSA_SHA256_TLSSECRET:
2622 case AUTHTYPE_ED25519_SHA256_RFC5705:
2623 return 1;
2624 case AUTHTYPE_RSA_SHA256_RFC5705:
2625 default:
2626 return 0;
2630 /** Return true iff <b>challenge_type_a</b> is one that we would rather
2631 * use than <b>challenge_type_b</b>. */
2633 authchallenge_type_is_better(uint16_t challenge_type_a,
2634 uint16_t challenge_type_b)
2636 /* Any supported type is better than an unsupported one;
2637 * all unsupported types are equally bad. */
2638 if (!authchallenge_type_is_supported(challenge_type_a))
2639 return 0;
2640 if (!authchallenge_type_is_supported(challenge_type_b))
2641 return 1;
2642 /* It happens that types are superior in numerically ascending order.
2643 * If that ever changes, this must change too. */
2644 return (challenge_type_a > challenge_type_b);
2647 /** Send an AUTH_CHALLENGE cell on the connection <b>conn</b>. Return 0
2648 * on success, -1 on failure. */
2650 connection_or_send_auth_challenge_cell(or_connection_t *conn)
2652 var_cell_t *cell = NULL;
2653 int r = -1;
2654 tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
2656 if (! conn->handshake_state)
2657 return -1;
2659 auth_challenge_cell_t *ac = auth_challenge_cell_new();
2661 tor_assert(sizeof(ac->challenge) == 32);
2662 crypto_rand((char*)ac->challenge, sizeof(ac->challenge));
2664 auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_TLSSECRET);
2665 /* Disabled, because everything that supports this method also supports
2666 * the much-superior ED25519_SHA256_RFC5705 */
2667 /* auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_RFC5705); */
2668 auth_challenge_cell_add_methods(ac, AUTHTYPE_ED25519_SHA256_RFC5705);
2669 auth_challenge_cell_set_n_methods(ac,
2670 auth_challenge_cell_getlen_methods(ac));
2672 cell = var_cell_new(auth_challenge_cell_encoded_len(ac));
2673 ssize_t len = auth_challenge_cell_encode(cell->payload, cell->payload_len,
2674 ac);
2675 if (len != cell->payload_len) {
2676 /* LCOV_EXCL_START */
2677 log_warn(LD_BUG, "Encoded auth challenge cell length not as expected");
2678 goto done;
2679 /* LCOV_EXCL_STOP */
2681 cell->command = CELL_AUTH_CHALLENGE;
2683 connection_or_write_var_cell_to_buf(cell, conn);
2684 r = 0;
2686 done:
2687 var_cell_free(cell);
2688 auth_challenge_cell_free(ac);
2690 return r;
2693 /** Compute the main body of an AUTHENTICATE cell that a client can use
2694 * to authenticate itself on a v3 handshake for <b>conn</b>. Return it
2695 * in a var_cell_t.
2697 * If <b>server</b> is true, only calculate the first
2698 * V3_AUTH_FIXED_PART_LEN bytes -- the part of the authenticator that's
2699 * determined by the rest of the handshake, and which match the provided value
2700 * exactly.
2702 * If <b>server</b> is false and <b>signing_key</b> is NULL, calculate the
2703 * first V3_AUTH_BODY_LEN bytes of the authenticator (that is, everything
2704 * that should be signed), but don't actually sign it.
2706 * If <b>server</b> is false and <b>signing_key</b> is provided, calculate the
2707 * entire authenticator, signed with <b>signing_key</b>.
2709 * Return the length of the cell body on success, and -1 on failure.
2711 var_cell_t *
2712 connection_or_compute_authenticate_cell_body(or_connection_t *conn,
2713 const int authtype,
2714 crypto_pk_t *signing_key,
2715 const ed25519_keypair_t *ed_signing_key,
2716 int server)
2718 auth1_t *auth = NULL;
2719 auth_ctx_t *ctx = auth_ctx_new();
2720 var_cell_t *result = NULL;
2721 int old_tlssecrets_algorithm = 0;
2722 const char *authtype_str = NULL;
2724 int is_ed = 0;
2726 /* assert state is reasonable XXXX */
2727 switch (authtype) {
2728 case AUTHTYPE_RSA_SHA256_TLSSECRET:
2729 authtype_str = "AUTH0001";
2730 old_tlssecrets_algorithm = 1;
2731 break;
2732 case AUTHTYPE_RSA_SHA256_RFC5705:
2733 authtype_str = "AUTH0002";
2734 break;
2735 case AUTHTYPE_ED25519_SHA256_RFC5705:
2736 authtype_str = "AUTH0003";
2737 is_ed = 1;
2738 break;
2739 default:
2740 tor_assert(0);
2741 break;
2744 auth = auth1_new();
2745 ctx->is_ed = is_ed;
2747 /* Type: 8 bytes. */
2748 memcpy(auth1_getarray_type(auth), authtype_str, 8);
2751 const tor_x509_cert_t *id_cert=NULL;
2752 const common_digests_t *my_digests, *their_digests;
2753 const uint8_t *my_id, *their_id, *client_id, *server_id;
2754 if (tor_tls_get_my_certs(server, NULL, &id_cert))
2755 goto err;
2756 my_digests = tor_x509_cert_get_id_digests(id_cert);
2757 their_digests =
2758 tor_x509_cert_get_id_digests(conn->handshake_state->certs->id_cert);
2759 tor_assert(my_digests);
2760 tor_assert(their_digests);
2761 my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
2762 their_id = (uint8_t*)their_digests->d[DIGEST_SHA256];
2764 client_id = server ? their_id : my_id;
2765 server_id = server ? my_id : their_id;
2767 /* Client ID digest: 32 octets. */
2768 memcpy(auth->cid, client_id, 32);
2770 /* Server ID digest: 32 octets. */
2771 memcpy(auth->sid, server_id, 32);
2774 if (is_ed) {
2775 const ed25519_public_key_t *my_ed_id, *their_ed_id;
2776 if (!conn->handshake_state->certs->ed_id_sign) {
2777 log_warn(LD_OR, "Ed authenticate without Ed ID cert from peer.");
2778 goto err;
2780 my_ed_id = get_master_identity_key();
2781 their_ed_id = &conn->handshake_state->certs->ed_id_sign->signing_key;
2783 const uint8_t *cid_ed = (server ? their_ed_id : my_ed_id)->pubkey;
2784 const uint8_t *sid_ed = (server ? my_ed_id : their_ed_id)->pubkey;
2786 memcpy(auth->u1_cid_ed, cid_ed, ED25519_PUBKEY_LEN);
2787 memcpy(auth->u1_sid_ed, sid_ed, ED25519_PUBKEY_LEN);
2791 crypto_digest_t *server_d, *client_d;
2792 if (server) {
2793 server_d = conn->handshake_state->digest_sent;
2794 client_d = conn->handshake_state->digest_received;
2795 } else {
2796 client_d = conn->handshake_state->digest_sent;
2797 server_d = conn->handshake_state->digest_received;
2800 /* Server log digest : 32 octets */
2801 crypto_digest_get_digest(server_d, (char*)auth->slog, 32);
2803 /* Client log digest : 32 octets */
2804 crypto_digest_get_digest(client_d, (char*)auth->clog, 32);
2808 /* Digest of cert used on TLS link : 32 octets. */
2809 tor_x509_cert_t *cert = NULL;
2810 if (server) {
2811 cert = tor_tls_get_own_cert(conn->tls);
2812 } else {
2813 cert = tor_tls_get_peer_cert(conn->tls);
2815 if (!cert) {
2816 log_warn(LD_OR, "Unable to find cert when making %s data.",
2817 authtype_str);
2818 goto err;
2821 memcpy(auth->scert,
2822 tor_x509_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
2824 tor_x509_cert_free(cert);
2827 /* HMAC of clientrandom and serverrandom using master key : 32 octets */
2828 if (old_tlssecrets_algorithm) {
2829 tor_tls_get_tlssecrets(conn->tls, auth->tlssecrets);
2830 } else {
2831 char label[128];
2832 tor_snprintf(label, sizeof(label),
2833 "EXPORTER FOR TOR TLS CLIENT BINDING %s", authtype_str);
2834 tor_tls_export_key_material(conn->tls, auth->tlssecrets,
2835 auth->cid, sizeof(auth->cid),
2836 label);
2839 /* 8 octets were reserved for the current time, but we're trying to get out
2840 * of the habit of sending time around willynilly. Fortunately, nothing
2841 * checks it. That's followed by 16 bytes of nonce. */
2842 crypto_rand((char*)auth->rand, 24);
2844 ssize_t maxlen = auth1_encoded_len(auth, ctx);
2845 if (ed_signing_key && is_ed) {
2846 maxlen += ED25519_SIG_LEN;
2847 } else if (signing_key && !is_ed) {
2848 maxlen += crypto_pk_keysize(signing_key);
2851 const int AUTH_CELL_HEADER_LEN = 4; /* 2 bytes of type, 2 bytes of length */
2852 result = var_cell_new(AUTH_CELL_HEADER_LEN + maxlen);
2853 uint8_t *const out = result->payload + AUTH_CELL_HEADER_LEN;
2854 const size_t outlen = maxlen;
2855 ssize_t len;
2857 result->command = CELL_AUTHENTICATE;
2858 set_uint16(result->payload, htons(authtype));
2860 if ((len = auth1_encode(out, outlen, auth, ctx)) < 0) {
2861 /* LCOV_EXCL_START */
2862 log_warn(LD_BUG, "Unable to encode signed part of AUTH1 data.");
2863 goto err;
2864 /* LCOV_EXCL_STOP */
2867 if (server) {
2868 auth1_t *tmp = NULL;
2869 ssize_t len2 = auth1_parse(&tmp, out, len, ctx);
2870 if (!tmp) {
2871 /* LCOV_EXCL_START */
2872 log_warn(LD_BUG, "Unable to parse signed part of AUTH1 data that "
2873 "we just encoded");
2874 goto err;
2875 /* LCOV_EXCL_STOP */
2877 result->payload_len = (tmp->end_of_signed - result->payload);
2879 auth1_free(tmp);
2880 if (len2 != len) {
2881 /* LCOV_EXCL_START */
2882 log_warn(LD_BUG, "Mismatched length when re-parsing AUTH1 data.");
2883 goto err;
2884 /* LCOV_EXCL_STOP */
2886 goto done;
2889 if (ed_signing_key && is_ed) {
2890 ed25519_signature_t sig;
2891 if (ed25519_sign(&sig, out, len, ed_signing_key) < 0) {
2892 /* LCOV_EXCL_START */
2893 log_warn(LD_BUG, "Unable to sign ed25519 authentication data");
2894 goto err;
2895 /* LCOV_EXCL_STOP */
2897 auth1_setlen_sig(auth, ED25519_SIG_LEN);
2898 memcpy(auth1_getarray_sig(auth), sig.sig, ED25519_SIG_LEN);
2900 } else if (signing_key && !is_ed) {
2901 auth1_setlen_sig(auth, crypto_pk_keysize(signing_key));
2903 char d[32];
2904 crypto_digest256(d, (char*)out, len, DIGEST_SHA256);
2905 int siglen = crypto_pk_private_sign(signing_key,
2906 (char*)auth1_getarray_sig(auth),
2907 auth1_getlen_sig(auth),
2908 d, 32);
2909 if (siglen < 0) {
2910 log_warn(LD_OR, "Unable to sign AUTH1 data.");
2911 goto err;
2914 auth1_setlen_sig(auth, siglen);
2917 len = auth1_encode(out, outlen, auth, ctx);
2918 if (len < 0) {
2919 /* LCOV_EXCL_START */
2920 log_warn(LD_BUG, "Unable to encode signed AUTH1 data.");
2921 goto err;
2922 /* LCOV_EXCL_STOP */
2924 tor_assert(len + AUTH_CELL_HEADER_LEN <= result->payload_len);
2925 result->payload_len = len + AUTH_CELL_HEADER_LEN;
2926 set_uint16(result->payload+2, htons(len));
2928 goto done;
2930 err:
2931 var_cell_free(result);
2932 result = NULL;
2933 done:
2934 auth1_free(auth);
2935 auth_ctx_free(ctx);
2936 return result;
2939 /** Send an AUTHENTICATE cell on the connection <b>conn</b>. Return 0 on
2940 * success, -1 on failure */
2941 MOCK_IMPL(int,
2942 connection_or_send_authenticate_cell,(or_connection_t *conn, int authtype))
2944 var_cell_t *cell;
2945 crypto_pk_t *pk = tor_tls_get_my_client_auth_key();
2946 /* XXXX make sure we're actually supposed to send this! */
2948 if (!pk) {
2949 log_warn(LD_BUG, "Can't compute authenticate cell: no client auth key");
2950 return -1;
2952 if (! authchallenge_type_is_supported(authtype)) {
2953 log_warn(LD_BUG, "Tried to send authenticate cell with unknown "
2954 "authentication type %d", authtype);
2955 return -1;
2958 cell = connection_or_compute_authenticate_cell_body(conn,
2959 authtype,
2961 get_current_auth_keypair(),
2962 0 /* not server */);
2963 if (! cell) {
2964 /* LCOV_EXCL_START */
2965 log_warn(LD_BUG, "Unable to compute authenticate cell!");
2966 return -1;
2967 /* LCOV_EXCL_STOP */
2969 connection_or_write_var_cell_to_buf(cell, conn);
2970 var_cell_free(cell);
2972 return 0;