Update copyrights to 2021, using "make update-copyright"
[tor.git] / src / core / or / channeltls.c
blob21850d0fb60d628f4c96f03880dcd2d2251916e8
1 /* * Copyright (c) 2012-2021, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file channeltls.c
7 * \brief A concrete subclass of channel_t using or_connection_t to transfer
8 * cells between Tor instances.
10 * This module fills in the various function pointers in channel_t, to
11 * implement the channel_tls_t channels as used in Tor today. These channels
12 * are created from channel_tls_connect() and
13 * channel_tls_handle_incoming(). Each corresponds 1:1 to or_connection_t
14 * object, as implemented in connection_or.c. These channels transmit cells
15 * to the underlying or_connection_t by calling
16 * connection_or_write_*_cell_to_buf(), and receive cells from the underlying
17 * or_connection_t when connection_or_process_cells_from_inbuf() calls
18 * channel_tls_handle_*_cell().
20 * Here we also implement the server (responder) side of the v3+ Tor link
21 * handshake, which uses CERTS and AUTHENTICATE cell to negotiate versions,
22 * exchange expected and observed IP and time information, and bootstrap a
23 * level of authentication higher than we have gotten on the raw TLS
24 * handshake.
26 * NOTE: Since there is currently only one type of channel, there are probably
27 * more than a few cases where functionality that is currently in
28 * channeltls.c, connection_or.c, and channel.c ought to be divided up
29 * differently. The right time to do this is probably whenever we introduce
30 * our next channel type.
31 **/
34 * Define this so channel.h gives us things only channel_t subclasses
35 * should touch.
37 #define CHANNEL_OBJECT_PRIVATE
39 #define CHANNELTLS_PRIVATE
41 #include "core/or/or.h"
42 #include "core/or/channel.h"
43 #include "core/or/channeltls.h"
44 #include "core/or/circuitmux.h"
45 #include "core/or/circuitmux_ewma.h"
46 #include "core/or/command.h"
47 #include "app/config/config.h"
48 #include "app/config/resolve_addr.h"
49 #include "core/mainloop/connection.h"
50 #include "core/or/connection_or.h"
51 #include "feature/relay/relay_handshake.h"
52 #include "feature/control/control.h"
53 #include "feature/client/entrynodes.h"
54 #include "trunnel/link_handshake.h"
55 #include "core/or/relay.h"
56 #include "feature/stats/rephist.h"
57 #include "feature/relay/router.h"
58 #include "feature/relay/routermode.h"
59 #include "feature/nodelist/dirlist.h"
60 #include "core/or/scheduler.h"
61 #include "feature/nodelist/torcert.h"
62 #include "feature/nodelist/networkstatus.h"
63 #include "trunnel/channelpadding_negotiation.h"
64 #include "trunnel/netinfo.h"
65 #include "core/or/channelpadding.h"
66 #include "core/or/extendinfo.h"
68 #include "core/or/cell_st.h"
69 #include "core/or/cell_queue_st.h"
70 #include "core/or/or_connection_st.h"
71 #include "core/or/or_handshake_certs_st.h"
72 #include "core/or/or_handshake_state_st.h"
73 #include "feature/nodelist/routerinfo_st.h"
74 #include "core/or/var_cell_st.h"
75 #include "src/feature/relay/relay_find_addr.h"
77 #include "lib/tls/tortls.h"
78 #include "lib/tls/x509.h"
80 /** How many CELL_PADDING cells have we received, ever? */
81 uint64_t stats_n_padding_cells_processed = 0;
82 /** How many CELL_VERSIONS cells have we received, ever? */
83 uint64_t stats_n_versions_cells_processed = 0;
84 /** How many CELL_NETINFO cells have we received, ever? */
85 uint64_t stats_n_netinfo_cells_processed = 0;
86 /** How many CELL_VPADDING cells have we received, ever? */
87 uint64_t stats_n_vpadding_cells_processed = 0;
88 /** How many CELL_CERTS cells have we received, ever? */
89 uint64_t stats_n_certs_cells_processed = 0;
90 /** How many CELL_AUTH_CHALLENGE cells have we received, ever? */
91 uint64_t stats_n_auth_challenge_cells_processed = 0;
92 /** How many CELL_AUTHENTICATE cells have we received, ever? */
93 uint64_t stats_n_authenticate_cells_processed = 0;
94 /** How many CELL_AUTHORIZE cells have we received, ever? */
95 uint64_t stats_n_authorize_cells_processed = 0;
97 /** Active listener, if any */
98 static channel_listener_t *channel_tls_listener = NULL;
100 /* channel_tls_t method declarations */
102 static void channel_tls_close_method(channel_t *chan);
103 static const char * channel_tls_describe_transport_method(channel_t *chan);
104 static void channel_tls_free_method(channel_t *chan);
105 static double channel_tls_get_overhead_estimate_method(channel_t *chan);
106 static int channel_tls_get_remote_addr_method(const channel_t *chan,
107 tor_addr_t *addr_out);
108 static int
109 channel_tls_get_transport_name_method(channel_t *chan, char **transport_out);
110 static const char *channel_tls_describe_peer_method(const channel_t *chan);
111 static int channel_tls_has_queued_writes_method(channel_t *chan);
112 static int channel_tls_is_canonical_method(channel_t *chan);
113 static int
114 channel_tls_matches_extend_info_method(channel_t *chan,
115 extend_info_t *extend_info);
116 static int channel_tls_matches_target_method(channel_t *chan,
117 const tor_addr_t *target);
118 static int channel_tls_num_cells_writeable_method(channel_t *chan);
119 static size_t channel_tls_num_bytes_queued_method(channel_t *chan);
120 static int channel_tls_write_cell_method(channel_t *chan,
121 cell_t *cell);
122 static int channel_tls_write_packed_cell_method(channel_t *chan,
123 packed_cell_t *packed_cell);
124 static int channel_tls_write_var_cell_method(channel_t *chan,
125 var_cell_t *var_cell);
127 /* channel_listener_tls_t method declarations */
129 static void channel_tls_listener_close_method(channel_listener_t *chan_l);
130 static const char *
131 channel_tls_listener_describe_transport_method(channel_listener_t *chan_l);
133 /** Handle incoming cells for the handshake stuff here rather than
134 * passing them on up. */
136 static void channel_tls_process_versions_cell(var_cell_t *cell,
137 channel_tls_t *tlschan);
138 static void channel_tls_process_netinfo_cell(cell_t *cell,
139 channel_tls_t *tlschan);
140 static int command_allowed_before_handshake(uint8_t command);
141 static int enter_v3_handshake_with_cell(var_cell_t *cell,
142 channel_tls_t *tlschan);
143 static void channel_tls_process_padding_negotiate_cell(cell_t *cell,
144 channel_tls_t *chan);
147 * Do parts of channel_tls_t initialization common to channel_tls_connect()
148 * and channel_tls_handle_incoming().
150 STATIC void
151 channel_tls_common_init(channel_tls_t *tlschan)
153 channel_t *chan;
155 tor_assert(tlschan);
157 chan = &(tlschan->base_);
158 channel_init(chan);
159 chan->magic = TLS_CHAN_MAGIC;
160 chan->state = CHANNEL_STATE_OPENING;
161 chan->close = channel_tls_close_method;
162 chan->describe_transport = channel_tls_describe_transport_method;
163 chan->free_fn = channel_tls_free_method;
164 chan->get_overhead_estimate = channel_tls_get_overhead_estimate_method;
165 chan->get_remote_addr = channel_tls_get_remote_addr_method;
166 chan->describe_peer = channel_tls_describe_peer_method;
167 chan->get_transport_name = channel_tls_get_transport_name_method;
168 chan->has_queued_writes = channel_tls_has_queued_writes_method;
169 chan->is_canonical = channel_tls_is_canonical_method;
170 chan->matches_extend_info = channel_tls_matches_extend_info_method;
171 chan->matches_target = channel_tls_matches_target_method;
172 chan->num_bytes_queued = channel_tls_num_bytes_queued_method;
173 chan->num_cells_writeable = channel_tls_num_cells_writeable_method;
174 chan->write_cell = channel_tls_write_cell_method;
175 chan->write_packed_cell = channel_tls_write_packed_cell_method;
176 chan->write_var_cell = channel_tls_write_var_cell_method;
178 chan->cmux = circuitmux_alloc();
179 /* We only have one policy for now so always set it to EWMA. */
180 circuitmux_set_policy(chan->cmux, &ewma_policy);
184 * Start a new TLS channel.
186 * Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
187 * handshake with an OR with identity digest <b>id_digest</b>, and wrap
188 * it in a channel_tls_t.
190 channel_t *
191 channel_tls_connect(const tor_addr_t *addr, uint16_t port,
192 const char *id_digest,
193 const ed25519_public_key_t *ed_id)
195 channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
196 channel_t *chan = &(tlschan->base_);
198 channel_tls_common_init(tlschan);
200 log_debug(LD_CHANNEL,
201 "In channel_tls_connect() for channel %p "
202 "(global id %"PRIu64 ")",
203 tlschan,
204 (chan->global_identifier));
206 if (is_local_to_resolve_addr(addr)) {
207 log_debug(LD_CHANNEL,
208 "Marking new outgoing channel %"PRIu64 " at %p as local",
209 (chan->global_identifier), chan);
210 channel_mark_local(chan);
211 } else {
212 log_debug(LD_CHANNEL,
213 "Marking new outgoing channel %"PRIu64 " at %p as remote",
214 (chan->global_identifier), chan);
215 channel_mark_remote(chan);
218 channel_mark_outgoing(chan);
220 /* Set up or_connection stuff */
221 tlschan->conn = connection_or_connect(addr, port, id_digest, ed_id, tlschan);
222 /* connection_or_connect() will fill in tlschan->conn */
223 if (!(tlschan->conn)) {
224 chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
225 channel_change_state(chan, CHANNEL_STATE_ERROR);
226 goto err;
229 log_debug(LD_CHANNEL,
230 "Got orconn %p for channel with global id %"PRIu64,
231 tlschan->conn, (chan->global_identifier));
233 goto done;
235 err:
236 circuitmux_free(chan->cmux);
237 tor_free(tlschan);
238 chan = NULL;
240 done:
241 /* If we got one, we should register it */
242 if (chan) channel_register(chan);
244 return chan;
248 * Return the current channel_tls_t listener.
250 * Returns the current channel listener for incoming TLS connections, or
251 * NULL if none has been established
253 channel_listener_t *
254 channel_tls_get_listener(void)
256 return channel_tls_listener;
260 * Start a channel_tls_t listener if necessary.
262 * Return the current channel_tls_t listener, or start one if we haven't yet,
263 * and return that.
265 channel_listener_t *
266 channel_tls_start_listener(void)
268 channel_listener_t *listener;
270 if (!channel_tls_listener) {
271 listener = tor_malloc_zero(sizeof(*listener));
272 channel_init_listener(listener);
273 listener->state = CHANNEL_LISTENER_STATE_LISTENING;
274 listener->close = channel_tls_listener_close_method;
275 listener->describe_transport =
276 channel_tls_listener_describe_transport_method;
278 channel_tls_listener = listener;
280 log_debug(LD_CHANNEL,
281 "Starting TLS channel listener %p with global id %"PRIu64,
282 listener, (listener->global_identifier));
284 channel_listener_register(listener);
285 } else listener = channel_tls_listener;
287 return listener;
291 * Free everything on shutdown.
293 * Not much to do here, since channel_free_all() takes care of a lot, but let's
294 * get rid of the listener.
296 void
297 channel_tls_free_all(void)
299 channel_listener_t *old_listener = NULL;
301 log_debug(LD_CHANNEL,
302 "Shutting down TLS channels...");
304 if (channel_tls_listener) {
306 * When we close it, channel_tls_listener will get nulled out, so save
307 * a pointer so we can free it.
309 old_listener = channel_tls_listener;
310 log_debug(LD_CHANNEL,
311 "Closing channel_tls_listener with ID %"PRIu64
312 " at %p.",
313 (old_listener->global_identifier),
314 old_listener);
315 channel_listener_unregister(old_listener);
316 channel_listener_mark_for_close(old_listener);
317 channel_listener_free(old_listener);
318 tor_assert(channel_tls_listener == NULL);
321 log_debug(LD_CHANNEL,
322 "Done shutting down TLS channels");
326 * Create a new channel around an incoming or_connection_t.
328 channel_t *
329 channel_tls_handle_incoming(or_connection_t *orconn)
331 channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
332 channel_t *chan = &(tlschan->base_);
334 tor_assert(orconn);
335 tor_assert(!(orconn->chan));
337 channel_tls_common_init(tlschan);
339 /* Link the channel and orconn to each other */
340 tlschan->conn = orconn;
341 orconn->chan = tlschan;
343 if (is_local_to_resolve_addr(&(TO_CONN(orconn)->addr))) {
344 log_debug(LD_CHANNEL,
345 "Marking new incoming channel %"PRIu64 " at %p as local",
346 (chan->global_identifier), chan);
347 channel_mark_local(chan);
348 } else {
349 log_debug(LD_CHANNEL,
350 "Marking new incoming channel %"PRIu64 " at %p as remote",
351 (chan->global_identifier), chan);
352 channel_mark_remote(chan);
355 channel_mark_incoming(chan);
357 /* Register it */
358 channel_register(chan);
360 return chan;
364 * Set the `potentially_used_for_bootstrapping` flag on the or_connection_t
365 * corresponding to the provided channel.
367 * This flag indicates that if the connection fails, it might be interesting
368 * to the bootstrapping subsystem. (The bootstrapping system only cares about
369 * channels that we have tried to use for our own circuits. Other channels
370 * may have been launched in response to EXTEND cells from somebody else, and
371 * if they fail, it won't necessarily indicate a bootstrapping problem.)
373 void
374 channel_mark_as_used_for_origin_circuit(channel_t *chan)
376 if (BUG(!chan))
377 return;
378 if (chan->magic != TLS_CHAN_MAGIC)
379 return;
380 channel_tls_t *tlschan = channel_tls_from_base(chan);
381 if (BUG(!tlschan))
382 return;
384 if (tlschan->conn)
385 tlschan->conn->potentially_used_for_bootstrapping = 1;
388 /*********
389 * Casts *
390 ********/
393 * Cast a channel_tls_t to a channel_t.
395 channel_t *
396 channel_tls_to_base(channel_tls_t *tlschan)
398 if (!tlschan) return NULL;
400 return &(tlschan->base_);
404 * Cast a channel_t to a channel_tls_t, with appropriate type-checking
405 * asserts.
407 channel_tls_t *
408 channel_tls_from_base(channel_t *chan)
410 if (!chan) return NULL;
412 tor_assert(chan->magic == TLS_CHAN_MAGIC);
414 return (channel_tls_t *)(chan);
418 * Cast a const channel_tls_t to a const channel_t.
420 const channel_t *
421 channel_tls_to_base_const(const channel_tls_t *tlschan)
423 return channel_tls_to_base((channel_tls_t*) tlschan);
427 * Cast a const channel_t to a const channel_tls_t, with appropriate
428 * type-checking asserts.
430 const channel_tls_t *
431 channel_tls_from_base_const(const channel_t *chan)
433 return channel_tls_from_base((channel_t *)chan);
436 /********************************************
437 * Method implementations for channel_tls_t *
438 *******************************************/
441 * Close a channel_tls_t.
443 * This implements the close method for channel_tls_t.
445 static void
446 channel_tls_close_method(channel_t *chan)
448 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
450 tor_assert(tlschan);
452 if (tlschan->conn) connection_or_close_normally(tlschan->conn, 1);
453 else {
454 /* Weird - we'll have to change the state ourselves, I guess */
455 log_info(LD_CHANNEL,
456 "Tried to close channel_tls_t %p with NULL conn",
457 tlschan);
458 channel_change_state(chan, CHANNEL_STATE_ERROR);
463 * Describe the transport for a channel_tls_t.
465 * This returns the string "TLS channel on connection <id>" to the upper
466 * layer.
468 static const char *
469 channel_tls_describe_transport_method(channel_t *chan)
471 static char *buf = NULL;
472 uint64_t id;
473 channel_tls_t *tlschan;
474 const char *rv = NULL;
476 tor_assert(chan);
478 tlschan = BASE_CHAN_TO_TLS(chan);
480 if (tlschan->conn) {
481 id = TO_CONN(tlschan->conn)->global_identifier;
483 if (buf) tor_free(buf);
484 tor_asprintf(&buf,
485 "TLS channel (connection %"PRIu64 ")",
486 (id));
488 rv = buf;
489 } else {
490 rv = "TLS channel (no connection)";
493 return rv;
497 * Free a channel_tls_t.
499 * This is called by the generic channel layer when freeing a channel_tls_t;
500 * this happens either on a channel which has already reached
501 * CHANNEL_STATE_CLOSED or CHANNEL_STATE_ERROR from channel_run_cleanup() or
502 * on shutdown from channel_free_all(). In the latter case we might still
503 * have an orconn active (which connection_free_all() will get to later),
504 * so we should null out its channel pointer now.
506 static void
507 channel_tls_free_method(channel_t *chan)
509 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
511 tor_assert(tlschan);
513 if (tlschan->conn) {
514 tlschan->conn->chan = NULL;
515 tlschan->conn = NULL;
520 * Get an estimate of the average TLS overhead for the upper layer.
522 static double
523 channel_tls_get_overhead_estimate_method(channel_t *chan)
525 double overhead = 1.0;
526 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
528 tor_assert(tlschan);
529 tor_assert(tlschan->conn);
531 /* Just return 1.0f if we don't have sensible data */
532 if (tlschan->conn->bytes_xmitted > 0 &&
533 tlschan->conn->bytes_xmitted_by_tls >=
534 tlschan->conn->bytes_xmitted) {
535 overhead = ((double)(tlschan->conn->bytes_xmitted_by_tls)) /
536 ((double)(tlschan->conn->bytes_xmitted));
539 * Never estimate more than 2.0; otherwise we get silly large estimates
540 * at the very start of a new TLS connection.
542 if (overhead > 2.0)
543 overhead = 2.0;
546 log_debug(LD_CHANNEL,
547 "Estimated overhead ratio for TLS chan %"PRIu64 " is %f",
548 (chan->global_identifier), overhead);
550 return overhead;
554 * Get the remote address of a channel_tls_t.
556 * This implements the get_remote_addr method for channel_tls_t; copy the
557 * remote endpoint of the channel to addr_out and return 1. (Always
558 * succeeds if this channel is attached to an OR connection.)
560 * Always returns the real address of the peer, not the canonical address.
562 static int
563 channel_tls_get_remote_addr_method(const channel_t *chan,
564 tor_addr_t *addr_out)
566 const channel_tls_t *tlschan = CONST_BASE_CHAN_TO_TLS(chan);
568 tor_assert(tlschan);
569 tor_assert(addr_out);
571 if (tlschan->conn == NULL) {
572 tor_addr_make_unspec(addr_out);
573 return 0;
576 /* They want the real address, so give it to them. */
577 tor_addr_copy(addr_out, &TO_CONN(tlschan->conn)->addr);
579 return 1;
583 * Get the name of the pluggable transport used by a channel_tls_t.
585 * This implements the get_transport_name for channel_tls_t. If the
586 * channel uses a pluggable transport, copy its name to
587 * <b>transport_out</b> and return 0. If the channel did not use a
588 * pluggable transport, return -1.
590 static int
591 channel_tls_get_transport_name_method(channel_t *chan, char **transport_out)
593 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
595 tor_assert(tlschan);
596 tor_assert(transport_out);
597 tor_assert(tlschan->conn);
599 if (!tlschan->conn->ext_or_transport)
600 return -1;
602 *transport_out = tor_strdup(tlschan->conn->ext_or_transport);
603 return 0;
607 * Get a human-readable endpoint description of a channel_tls_t.
609 * This format is intended for logging, and may change in the future;
610 * nothing should parse or rely on its particular details.
612 static const char *
613 channel_tls_describe_peer_method(const channel_t *chan)
615 const channel_tls_t *tlschan = CONST_BASE_CHAN_TO_TLS(chan);
616 tor_assert(tlschan);
618 if (tlschan->conn) {
619 return connection_describe_peer(TO_CONN(tlschan->conn));
620 } else {
621 return "(No connection)";
626 * Tell the upper layer if we have queued writes.
628 * This implements the has_queued_writes method for channel_tls t_; it returns
629 * 1 iff we have queued writes on the outbuf of the underlying or_connection_t.
631 static int
632 channel_tls_has_queued_writes_method(channel_t *chan)
634 size_t outbuf_len;
635 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
637 tor_assert(tlschan);
638 if (!(tlschan->conn)) {
639 log_info(LD_CHANNEL,
640 "something called has_queued_writes on a tlschan "
641 "(%p with ID %"PRIu64 " but no conn",
642 chan, (chan->global_identifier));
645 outbuf_len = (tlschan->conn != NULL) ?
646 connection_get_outbuf_len(TO_CONN(tlschan->conn)) :
649 return (outbuf_len > 0);
653 * Tell the upper layer if we're canonical.
655 * This implements the is_canonical method for channel_tls_t:
656 * it returns whether this is a canonical channel.
658 static int
659 channel_tls_is_canonical_method(channel_t *chan)
661 int answer = 0;
662 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
664 tor_assert(tlschan);
666 if (tlschan->conn) {
667 /* If this bit is set to 0, and link_proto is sufficiently old, then we
668 * can't actually _rely_ on this being a non-canonical channel.
669 * Nonetheless, we're going to believe that this is a non-canonical
670 * channel in this case, since nobody should be using these link protocols
671 * any more. */
672 answer = tlschan->conn->is_canonical;
675 return answer;
679 * Check if we match an extend_info_t.
681 * This implements the matches_extend_info method for channel_tls_t; the upper
682 * layer wants to know if this channel matches an extend_info_t.
684 * NOTE that this function only checks for an address/port match, and should
685 * be used only when no identify is available.
687 static int
688 channel_tls_matches_extend_info_method(channel_t *chan,
689 extend_info_t *extend_info)
691 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
693 tor_assert(tlschan);
694 tor_assert(extend_info);
696 /* Never match if we have no conn */
697 if (!(tlschan->conn)) {
698 log_info(LD_CHANNEL,
699 "something called matches_extend_info on a tlschan "
700 "(%p with ID %"PRIu64 " but no conn",
701 chan, (chan->global_identifier));
702 return 0;
705 const tor_addr_port_t *orport = &tlschan->conn->canonical_orport;
706 // If the canonical address is set, then we'll allow matches based on that.
707 if (! tor_addr_is_unspec(&orport->addr)) {
708 if (extend_info_has_orport(extend_info, &orport->addr, orport->port)) {
709 return 1;
713 // We also want to match if the true address and port are listed in the
714 // extend info.
715 return extend_info_has_orport(extend_info,
716 &TO_CONN(tlschan->conn)->addr,
717 TO_CONN(tlschan->conn)->port);
721 * Check if we match a target address; return true iff we do.
723 * This implements the matches_target method for channel_tls t_; the upper
724 * layer wants to know if this channel matches a target address when extending
725 * a circuit.
727 static int
728 channel_tls_matches_target_method(channel_t *chan,
729 const tor_addr_t *target)
731 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
733 tor_assert(tlschan);
734 tor_assert(target);
736 /* Never match if we have no conn */
737 if (!(tlschan->conn)) {
738 log_info(LD_CHANNEL,
739 "something called matches_target on a tlschan "
740 "(%p with ID %"PRIu64 " but no conn",
741 chan, (chan->global_identifier));
742 return 0;
745 /* addr is the address this connection came from.
746 * canonical_orport is updated by connection_or_init_conn_from_address()
747 * to be the address in the descriptor. It may be tempting to
748 * allow either address to be allowed, but if we did so, it would
749 * enable someone who steals a relay's keys to covertly impersonate/MITM it
750 * from anywhere on the Internet! (Because they could make long-lived
751 * TLS connections from anywhere to all relays, and wait for them to
752 * be used for extends).
754 * An adversary who has stolen a relay's keys could also post a fake relay
755 * descriptor, but that attack is easier to detect.
757 return tor_addr_eq(&TO_CONN(tlschan->conn)->addr, target);
761 * Tell the upper layer how many bytes we have queued and not yet
762 * sent.
764 static size_t
765 channel_tls_num_bytes_queued_method(channel_t *chan)
767 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
769 tor_assert(tlschan);
770 tor_assert(tlschan->conn);
772 return connection_get_outbuf_len(TO_CONN(tlschan->conn));
776 * Tell the upper layer how many cells we can accept to write.
778 * This implements the num_cells_writeable method for channel_tls_t; it
779 * returns an estimate of the number of cells we can accept with
780 * channel_tls_write_*_cell().
782 static int
783 channel_tls_num_cells_writeable_method(channel_t *chan)
785 size_t outbuf_len;
786 ssize_t n;
787 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
788 size_t cell_network_size;
790 tor_assert(tlschan);
791 tor_assert(tlschan->conn);
793 cell_network_size = get_cell_network_size(tlschan->conn->wide_circ_ids);
794 outbuf_len = connection_get_outbuf_len(TO_CONN(tlschan->conn));
795 /* Get the number of cells */
796 n = CEIL_DIV(OR_CONN_HIGHWATER - outbuf_len, cell_network_size);
797 if (n < 0) n = 0;
798 #if SIZEOF_SIZE_T > SIZEOF_INT
799 if (n > INT_MAX) n = INT_MAX;
800 #endif
802 return (int)n;
806 * Write a cell to a channel_tls_t.
808 * This implements the write_cell method for channel_tls_t; given a
809 * channel_tls_t and a cell_t, transmit the cell_t.
811 static int
812 channel_tls_write_cell_method(channel_t *chan, cell_t *cell)
814 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
815 int written = 0;
817 tor_assert(tlschan);
818 tor_assert(cell);
820 if (tlschan->conn) {
821 connection_or_write_cell_to_buf(cell, tlschan->conn);
822 ++written;
823 } else {
824 log_info(LD_CHANNEL,
825 "something called write_cell on a tlschan "
826 "(%p with ID %"PRIu64 " but no conn",
827 chan, (chan->global_identifier));
830 return written;
834 * Write a packed cell to a channel_tls_t.
836 * This implements the write_packed_cell method for channel_tls_t; given a
837 * channel_tls_t and a packed_cell_t, transmit the packed_cell_t.
839 * Return 0 on success or negative value on error. The caller must free the
840 * packed cell.
842 static int
843 channel_tls_write_packed_cell_method(channel_t *chan,
844 packed_cell_t *packed_cell)
846 tor_assert(chan);
847 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
848 size_t cell_network_size = get_cell_network_size(chan->wide_circ_ids);
850 tor_assert(tlschan);
851 tor_assert(packed_cell);
853 if (tlschan->conn) {
854 connection_buf_add(packed_cell->body, cell_network_size,
855 TO_CONN(tlschan->conn));
856 } else {
857 log_info(LD_CHANNEL,
858 "something called write_packed_cell on a tlschan "
859 "(%p with ID %"PRIu64 " but no conn",
860 chan, (chan->global_identifier));
861 return -1;
864 return 0;
868 * Write a variable-length cell to a channel_tls_t.
870 * This implements the write_var_cell method for channel_tls_t; given a
871 * channel_tls_t and a var_cell_t, transmit the var_cell_t.
873 static int
874 channel_tls_write_var_cell_method(channel_t *chan, var_cell_t *var_cell)
876 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
877 int written = 0;
879 tor_assert(tlschan);
880 tor_assert(var_cell);
882 if (tlschan->conn) {
883 connection_or_write_var_cell_to_buf(var_cell, tlschan->conn);
884 ++written;
885 } else {
886 log_info(LD_CHANNEL,
887 "something called write_var_cell on a tlschan "
888 "(%p with ID %"PRIu64 " but no conn",
889 chan, (chan->global_identifier));
892 return written;
895 /*************************************************
896 * Method implementations for channel_listener_t *
897 ************************************************/
900 * Close a channel_listener_t.
902 * This implements the close method for channel_listener_t.
904 static void
905 channel_tls_listener_close_method(channel_listener_t *chan_l)
907 tor_assert(chan_l);
910 * Listeners we just go ahead and change state through to CLOSED, but
911 * make sure to check if they're channel_tls_listener to NULL it out.
913 if (chan_l == channel_tls_listener)
914 channel_tls_listener = NULL;
916 if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
917 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
918 chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
919 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
922 if (chan_l->incoming_list) {
923 SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
924 channel_t *, ichan) {
925 channel_mark_for_close(ichan);
926 } SMARTLIST_FOREACH_END(ichan);
928 smartlist_free(chan_l->incoming_list);
929 chan_l->incoming_list = NULL;
932 if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
933 chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
934 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
939 * Describe the transport for a channel_listener_t.
941 * This returns the string "TLS channel (listening)" to the upper
942 * layer.
944 static const char *
945 channel_tls_listener_describe_transport_method(channel_listener_t *chan_l)
947 tor_assert(chan_l);
949 return "TLS channel (listening)";
952 /*******************************************************
953 * Functions for handling events on an or_connection_t *
954 ******************************************************/
957 * Handle an orconn state change.
959 * This function will be called by connection_or.c when the or_connection_t
960 * associated with this channel_tls_t changes state.
962 void
963 channel_tls_handle_state_change_on_orconn(channel_tls_t *chan,
964 or_connection_t *conn,
965 uint8_t state)
967 channel_t *base_chan;
969 tor_assert(chan);
970 tor_assert(conn);
971 tor_assert(conn->chan == chan);
972 tor_assert(chan->conn == conn);
974 base_chan = TLS_CHAN_TO_BASE(chan);
976 /* Make sure the base connection state makes sense - shouldn't be error
977 * or closed. */
979 tor_assert(CHANNEL_IS_OPENING(base_chan) ||
980 CHANNEL_IS_OPEN(base_chan) ||
981 CHANNEL_IS_MAINT(base_chan) ||
982 CHANNEL_IS_CLOSING(base_chan));
984 /* Did we just go to state open? */
985 if (state == OR_CONN_STATE_OPEN) {
987 * We can go to CHANNEL_STATE_OPEN from CHANNEL_STATE_OPENING or
988 * CHANNEL_STATE_MAINT on this.
990 channel_change_state_open(base_chan);
991 /* We might have just become writeable; check and tell the scheduler */
992 if (connection_or_num_cells_writeable(conn) > 0) {
993 scheduler_channel_wants_writes(base_chan);
995 } else {
997 * Not open, so from CHANNEL_STATE_OPEN we go to CHANNEL_STATE_MAINT,
998 * otherwise no change.
1000 if (CHANNEL_IS_OPEN(base_chan)) {
1001 channel_change_state(base_chan, CHANNEL_STATE_MAINT);
1006 #ifdef KEEP_TIMING_STATS
1009 * Timing states wrapper.
1011 * This is a wrapper function around the actual function that processes the
1012 * <b>cell</b> that just arrived on <b>chan</b>. Increment <b>*time</b>
1013 * by the number of microseconds used by the call to <b>*func(cell, chan)</b>.
1015 static void
1016 channel_tls_time_process_cell(cell_t *cell, channel_tls_t *chan, int *time,
1017 void (*func)(cell_t *, channel_tls_t *))
1019 struct timeval start, end;
1020 long time_passed;
1022 tor_gettimeofday(&start);
1024 (*func)(cell, chan);
1026 tor_gettimeofday(&end);
1027 time_passed = tv_udiff(&start, &end) ;
1029 if (time_passed > 10000) { /* more than 10ms */
1030 log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
1033 if (time_passed < 0) {
1034 log_info(LD_GENERAL,"That call took us back in time!");
1035 time_passed = 0;
1038 *time += time_passed;
1040 #endif /* defined(KEEP_TIMING_STATS) */
1042 #ifdef KEEP_TIMING_STATS
1043 #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
1044 ++num ## tp; \
1045 channel_tls_time_process_cell(cl, cn, & tp ## time , \
1046 channel_tls_process_ ## tp ## _cell); \
1047 } STMT_END
1048 #else /* !defined(KEEP_TIMING_STATS) */
1049 #define PROCESS_CELL(tp, cl, cn) channel_tls_process_ ## tp ## _cell(cl, cn)
1050 #endif /* defined(KEEP_TIMING_STATS) */
1053 * Handle an incoming cell on a channel_tls_t.
1055 * This is called from connection_or.c to handle an arriving cell; it checks
1056 * for cell types specific to the handshake for this transport protocol and
1057 * handles them, and queues all other cells to the channel_t layer, which
1058 * eventually will hand them off to command.c.
1060 * The channel layer itself decides whether the cell should be queued or
1061 * can be handed off immediately to the upper-layer code. It is responsible
1062 * for copying in the case that it queues; we merely pass pointers through
1063 * which we get from connection_or_process_cells_from_inbuf().
1065 void
1066 channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
1068 channel_tls_t *chan;
1069 int handshaking;
1071 tor_assert(cell);
1072 tor_assert(conn);
1074 chan = conn->chan;
1076 if (!chan) {
1077 log_warn(LD_CHANNEL,
1078 "Got a cell_t on an OR connection with no channel");
1079 return;
1082 handshaking = (TO_CONN(conn)->state != OR_CONN_STATE_OPEN);
1084 if (conn->base_.marked_for_close)
1085 return;
1087 /* Reject all but VERSIONS and NETINFO when handshaking. */
1088 /* (VERSIONS actually indicates a protocol warning: it's variable-length,
1089 * so if it reaches this function, we're on a v1 connection.) */
1090 if (handshaking && cell->command != CELL_VERSIONS &&
1091 cell->command != CELL_NETINFO) {
1092 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1093 "Received unexpected cell command %d in chan state %s / "
1094 "conn state %s; closing the connection.",
1095 (int)cell->command,
1096 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1097 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state));
1098 connection_or_close_for_error(conn, 0);
1099 return;
1102 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
1103 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 1);
1105 /* We note that we're on the internet whenever we read a cell. This is
1106 * a fast operation. */
1107 entry_guards_note_internet_connectivity(get_guard_selection_info());
1108 rep_hist_padding_count_read(PADDING_TYPE_TOTAL);
1110 if (TLS_CHAN_TO_BASE(chan)->padding_enabled)
1111 rep_hist_padding_count_read(PADDING_TYPE_ENABLED_TOTAL);
1113 switch (cell->command) {
1114 case CELL_PADDING:
1115 rep_hist_padding_count_read(PADDING_TYPE_CELL);
1116 if (TLS_CHAN_TO_BASE(chan)->padding_enabled)
1117 rep_hist_padding_count_read(PADDING_TYPE_ENABLED_CELL);
1118 ++stats_n_padding_cells_processed;
1119 /* do nothing */
1120 break;
1121 case CELL_VERSIONS:
1122 /* A VERSIONS cell should always be a variable-length cell, and
1123 * so should never reach this function (which handles constant-sized
1124 * cells). But if the connection is using the (obsolete) v1 link
1125 * protocol, all cells will be treated as constant-sized, and so
1126 * it's possible we'll reach this code.
1128 log_fn(LOG_PROTOCOL_WARN, LD_CHANNEL,
1129 "Received unexpected VERSIONS cell on a channel using link "
1130 "protocol %d; ignoring.", conn->link_proto);
1131 break;
1132 case CELL_NETINFO:
1133 ++stats_n_netinfo_cells_processed;
1134 PROCESS_CELL(netinfo, cell, chan);
1135 break;
1136 case CELL_PADDING_NEGOTIATE:
1137 ++stats_n_netinfo_cells_processed;
1138 PROCESS_CELL(padding_negotiate, cell, chan);
1139 break;
1140 case CELL_CREATE:
1141 case CELL_CREATE_FAST:
1142 case CELL_CREATED:
1143 case CELL_CREATED_FAST:
1144 case CELL_RELAY:
1145 case CELL_RELAY_EARLY:
1146 case CELL_DESTROY:
1147 case CELL_CREATE2:
1148 case CELL_CREATED2:
1150 * These are all transport independent and we pass them up through the
1151 * channel_t mechanism. They are ultimately handled in command.c.
1153 channel_process_cell(TLS_CHAN_TO_BASE(chan), cell);
1154 break;
1155 default:
1156 log_fn(LOG_INFO, LD_PROTOCOL,
1157 "Cell of unknown type (%d) received in channeltls.c. "
1158 "Dropping.",
1159 cell->command);
1160 break;
1165 * Handle an incoming variable-length cell on a channel_tls_t.
1167 * Process a <b>var_cell</b> that was just received on <b>conn</b>. Keep
1168 * internal statistics about how many of each cell we've processed so far
1169 * this second, and the total number of microseconds it took to
1170 * process each type of cell. All the var_cell commands are handshake-
1171 * related and live below the channel_t layer, so no variable-length
1172 * cells ever get delivered in the current implementation, but I've left
1173 * the mechanism in place for future use.
1175 * If we were handing them off to the upper layer, the channel_t queueing
1176 * code would be responsible for memory management, and we'd just be passing
1177 * pointers through from connection_or_process_cells_from_inbuf(). That
1178 * caller always frees them after this function returns, so this function
1179 * should never free var_cell.
1181 void
1182 channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
1184 channel_tls_t *chan;
1186 #ifdef KEEP_TIMING_STATS
1187 /* how many of each cell have we seen so far this second? needs better
1188 * name. */
1189 static int num_versions = 0, num_certs = 0;
1190 static time_t current_second = 0; /* from previous calls to time */
1191 time_t now = time(NULL);
1193 if (current_second == 0) current_second = now;
1194 if (now > current_second) { /* the second has rolled over */
1195 /* print stats */
1196 log_info(LD_OR,
1197 "At end of second: %d versions (%d ms), %d certs (%d ms)",
1198 num_versions, versions_time / ((now - current_second) * 1000),
1199 num_certs, certs_time / ((now - current_second) * 1000));
1201 num_versions = num_certs = 0;
1202 versions_time = certs_time = 0;
1204 /* remember which second it is, for next time */
1205 current_second = now;
1207 #endif /* defined(KEEP_TIMING_STATS) */
1209 tor_assert(var_cell);
1210 tor_assert(conn);
1212 chan = conn->chan;
1214 if (!chan) {
1215 log_warn(LD_CHANNEL,
1216 "Got a var_cell_t on an OR connection with no channel");
1217 return;
1220 if (TO_CONN(conn)->marked_for_close)
1221 return;
1223 switch (TO_CONN(conn)->state) {
1224 case OR_CONN_STATE_OR_HANDSHAKING_V2:
1225 if (var_cell->command != CELL_VERSIONS) {
1226 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1227 "Received a cell with command %d in unexpected "
1228 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1229 "closing the connection.",
1230 (int)(var_cell->command),
1231 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1232 TO_CONN(conn)->state,
1233 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1234 (int)(TLS_CHAN_TO_BASE(chan)->state));
1236 * The code in connection_or.c will tell channel_t to close for
1237 * error; it will go to CHANNEL_STATE_CLOSING, and then to
1238 * CHANNEL_STATE_ERROR when conn is closed.
1240 connection_or_close_for_error(conn, 0);
1241 return;
1243 break;
1244 case OR_CONN_STATE_TLS_HANDSHAKING:
1245 /* If we're using bufferevents, it's entirely possible for us to
1246 * notice "hey, data arrived!" before we notice "hey, the handshake
1247 * finished!" And we need to be accepting both at once to handle both
1248 * the v2 and v3 handshakes. */
1249 /* But that should be happening any longer've disabled bufferevents. */
1250 tor_assert_nonfatal_unreached_once();
1251 FALLTHROUGH_UNLESS_ALL_BUGS_ARE_FATAL;
1252 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
1253 if (!(command_allowed_before_handshake(var_cell->command))) {
1254 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1255 "Received a cell with command %d in unexpected "
1256 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1257 "closing the connection.",
1258 (int)(var_cell->command),
1259 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1260 (int)(TO_CONN(conn)->state),
1261 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1262 (int)(TLS_CHAN_TO_BASE(chan)->state));
1263 /* see above comment about CHANNEL_STATE_ERROR */
1264 connection_or_close_for_error(conn, 0);
1265 return;
1266 } else {
1267 if (enter_v3_handshake_with_cell(var_cell, chan) < 0)
1268 return;
1270 break;
1271 case OR_CONN_STATE_OR_HANDSHAKING_V3:
1272 if (var_cell->command != CELL_AUTHENTICATE)
1273 or_handshake_state_record_var_cell(conn, conn->handshake_state,
1274 var_cell, 1);
1275 break; /* Everything is allowed */
1276 case OR_CONN_STATE_OPEN:
1277 if (conn->link_proto < 3) {
1278 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1279 "Received a variable-length cell with command %d in orconn "
1280 "state %s [%d], channel state %s [%d] with link protocol %d; "
1281 "ignoring it.",
1282 (int)(var_cell->command),
1283 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1284 (int)(TO_CONN(conn)->state),
1285 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1286 (int)(TLS_CHAN_TO_BASE(chan)->state),
1287 (int)(conn->link_proto));
1288 return;
1290 break;
1291 default:
1292 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1293 "Received var-length cell with command %d in unexpected "
1294 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1295 "ignoring it.",
1296 (int)(var_cell->command),
1297 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1298 (int)(TO_CONN(conn)->state),
1299 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1300 (int)(TLS_CHAN_TO_BASE(chan)->state));
1301 return;
1304 /* We note that we're on the internet whenever we read a cell. This is
1305 * a fast operation. */
1306 entry_guards_note_internet_connectivity(get_guard_selection_info());
1308 /* Now handle the cell */
1310 switch (var_cell->command) {
1311 case CELL_VERSIONS:
1312 ++stats_n_versions_cells_processed;
1313 PROCESS_CELL(versions, var_cell, chan);
1314 break;
1315 case CELL_VPADDING:
1316 ++stats_n_vpadding_cells_processed;
1317 /* Do nothing */
1318 break;
1319 case CELL_CERTS:
1320 ++stats_n_certs_cells_processed;
1321 PROCESS_CELL(certs, var_cell, chan);
1322 break;
1323 case CELL_AUTH_CHALLENGE:
1324 ++stats_n_auth_challenge_cells_processed;
1325 PROCESS_CELL(auth_challenge, var_cell, chan);
1326 break;
1327 case CELL_AUTHENTICATE:
1328 ++stats_n_authenticate_cells_processed;
1329 PROCESS_CELL(authenticate, var_cell, chan);
1330 break;
1331 case CELL_AUTHORIZE:
1332 ++stats_n_authorize_cells_processed;
1333 /* Ignored so far. */
1334 break;
1335 default:
1336 log_fn(LOG_INFO, LD_PROTOCOL,
1337 "Variable-length cell of unknown type (%d) received.",
1338 (int)(var_cell->command));
1339 break;
1343 #undef PROCESS_CELL
1346 * Update channel marks after connection_or.c has changed an address.
1348 * This is called from connection_or_init_conn_from_address() after the
1349 * connection's _base.addr or real_addr fields have potentially been changed
1350 * so we can recalculate the local mark. Notably, this happens when incoming
1351 * connections are reverse-proxied and we only learn the real address of the
1352 * remote router by looking it up in the consensus after we finish the
1353 * handshake and know an authenticated identity digest.
1355 void
1356 channel_tls_update_marks(or_connection_t *conn)
1358 channel_t *chan = NULL;
1360 tor_assert(conn);
1361 tor_assert(conn->chan);
1363 chan = TLS_CHAN_TO_BASE(conn->chan);
1365 if (is_local_to_resolve_addr(&(TO_CONN(conn)->addr))) {
1366 if (!channel_is_local(chan)) {
1367 log_debug(LD_CHANNEL,
1368 "Marking channel %"PRIu64 " at %p as local",
1369 (chan->global_identifier), chan);
1370 channel_mark_local(chan);
1372 } else {
1373 if (channel_is_local(chan)) {
1374 log_debug(LD_CHANNEL,
1375 "Marking channel %"PRIu64 " at %p as remote",
1376 (chan->global_identifier), chan);
1377 channel_mark_remote(chan);
1383 * Check if this cell type is allowed before the handshake is finished.
1385 * Return true if <b>command</b> is a cell command that's allowed to start a
1386 * V3 handshake.
1388 static int
1389 command_allowed_before_handshake(uint8_t command)
1391 switch (command) {
1392 case CELL_VERSIONS:
1393 case CELL_VPADDING:
1394 case CELL_AUTHORIZE:
1395 return 1;
1396 default:
1397 return 0;
1402 * Start a V3 handshake on an incoming connection.
1404 * Called when we as a server receive an appropriate cell while waiting
1405 * either for a cell or a TLS handshake. Set the connection's state to
1406 * "handshaking_v3', initializes the or_handshake_state field as needed,
1407 * and add the cell to the hash of incoming cells.)
1409 static int
1410 enter_v3_handshake_with_cell(var_cell_t *cell, channel_tls_t *chan)
1412 int started_here = 0;
1414 tor_assert(cell);
1415 tor_assert(chan);
1416 tor_assert(chan->conn);
1418 started_here = connection_or_nonopen_was_started_here(chan->conn);
1420 tor_assert(TO_CONN(chan->conn)->state == OR_CONN_STATE_TLS_HANDSHAKING ||
1421 TO_CONN(chan->conn)->state ==
1422 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1424 if (started_here) {
1425 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1426 "Received a cell while TLS-handshaking, not in "
1427 "OR_HANDSHAKING_V3, on a connection we originated.");
1429 connection_or_block_renegotiation(chan->conn);
1430 connection_or_change_state(chan->conn, OR_CONN_STATE_OR_HANDSHAKING_V3);
1431 if (connection_init_or_handshake_state(chan->conn, started_here) < 0) {
1432 connection_or_close_for_error(chan->conn, 0);
1433 return -1;
1435 or_handshake_state_record_var_cell(chan->conn,
1436 chan->conn->handshake_state, cell, 1);
1437 return 0;
1441 * Process a 'versions' cell.
1443 * This function is called to handle an incoming VERSIONS cell; the current
1444 * link protocol version must be 0 to indicate that no version has yet been
1445 * negotiated. We compare the versions in the cell to the list of versions
1446 * we support, pick the highest version we have in common, and continue the
1447 * negotiation from there.
1449 static void
1450 channel_tls_process_versions_cell(var_cell_t *cell, channel_tls_t *chan)
1452 int highest_supported_version = 0;
1453 int started_here = 0;
1455 tor_assert(cell);
1456 tor_assert(chan);
1457 tor_assert(chan->conn);
1459 if ((cell->payload_len % 2) == 1) {
1460 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1461 "Received a VERSION cell with odd payload length %d; "
1462 "closing connection.",cell->payload_len);
1463 connection_or_close_for_error(chan->conn, 0);
1464 return;
1467 started_here = connection_or_nonopen_was_started_here(chan->conn);
1469 if (chan->conn->link_proto != 0 ||
1470 (chan->conn->handshake_state &&
1471 chan->conn->handshake_state->received_versions)) {
1472 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1473 "Received a VERSIONS cell on a connection with its version "
1474 "already set to %d; dropping",
1475 (int)(chan->conn->link_proto));
1476 return;
1478 switch (chan->conn->base_.state)
1480 case OR_CONN_STATE_OR_HANDSHAKING_V2:
1481 case OR_CONN_STATE_OR_HANDSHAKING_V3:
1482 break;
1483 case OR_CONN_STATE_TLS_HANDSHAKING:
1484 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
1485 default:
1486 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1487 "VERSIONS cell while in unexpected state");
1488 return;
1491 tor_assert(chan->conn->handshake_state);
1494 int i;
1495 const uint8_t *cp = cell->payload;
1496 for (i = 0; i < cell->payload_len / 2; ++i, cp += 2) {
1497 uint16_t v = ntohs(get_uint16(cp));
1498 if (is_or_protocol_version_known(v) && v > highest_supported_version)
1499 highest_supported_version = v;
1502 if (!highest_supported_version) {
1503 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1504 "Couldn't find a version in common between my version list and the "
1505 "list in the VERSIONS cell; closing connection.");
1506 connection_or_close_for_error(chan->conn, 0);
1507 return;
1508 } else if (highest_supported_version == 1) {
1509 /* Negotiating version 1 makes no sense, since version 1 has no VERSIONS
1510 * cells. */
1511 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1512 "Used version negotiation protocol to negotiate a v1 connection. "
1513 "That's crazily non-compliant. Closing connection.");
1514 connection_or_close_for_error(chan->conn, 0);
1515 return;
1516 } else if (highest_supported_version < 3 &&
1517 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1518 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1519 "Negotiated link protocol 2 or lower after doing a v3 TLS "
1520 "handshake. Closing connection.");
1521 connection_or_close_for_error(chan->conn, 0);
1522 return;
1523 } else if (highest_supported_version != 2 &&
1524 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V2) {
1525 /* XXXX This should eventually be a log_protocol_warn */
1526 log_fn(LOG_WARN, LD_OR,
1527 "Negotiated link with non-2 protocol after doing a v2 TLS "
1528 "handshake with %s. Closing connection.",
1529 connection_describe_peer(TO_CONN(chan->conn)));
1530 connection_or_close_for_error(chan->conn, 0);
1531 return;
1534 rep_hist_note_negotiated_link_proto(highest_supported_version, started_here);
1536 chan->conn->link_proto = highest_supported_version;
1537 chan->conn->handshake_state->received_versions = 1;
1539 if (chan->conn->link_proto == 2) {
1540 log_info(LD_OR,
1541 "Negotiated version %d on %s; sending NETINFO.",
1542 highest_supported_version,
1543 connection_describe(TO_CONN(chan->conn)));
1545 if (connection_or_send_netinfo(chan->conn) < 0) {
1546 connection_or_close_for_error(chan->conn, 0);
1547 return;
1549 } else {
1550 const int send_versions = !started_here;
1551 /* If we want to authenticate, send a CERTS cell */
1552 const int send_certs = !started_here || public_server_mode(get_options());
1553 /* If we're a host that got a connection, ask for authentication. */
1554 const int send_chall = !started_here;
1555 /* If our certs cell will authenticate us, we can send a netinfo cell
1556 * right now. */
1557 const int send_netinfo = !started_here;
1558 const int send_any =
1559 send_versions || send_certs || send_chall || send_netinfo;
1560 tor_assert(chan->conn->link_proto >= 3);
1562 log_info(LD_OR,
1563 "Negotiated version %d with on %s; %s%s%s%s%s",
1564 highest_supported_version,
1565 connection_describe(TO_CONN(chan->conn)),
1566 send_any ? "Sending cells:" : "Waiting for CERTS cell",
1567 send_versions ? " VERSIONS" : "",
1568 send_certs ? " CERTS" : "",
1569 send_chall ? " AUTH_CHALLENGE" : "",
1570 send_netinfo ? " NETINFO" : "");
1572 #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
1573 if (1) {
1574 connection_or_close_normally(chan->conn, 1);
1575 return;
1577 #endif /* defined(DISABLE_V3_LINKPROTO_SERVERSIDE) */
1579 if (send_versions) {
1580 if (connection_or_send_versions(chan->conn, 1) < 0) {
1581 log_warn(LD_OR, "Couldn't send versions cell");
1582 connection_or_close_for_error(chan->conn, 0);
1583 return;
1587 /* We set this after sending the versions cell. */
1588 /*XXXXX symbolic const.*/
1589 TLS_CHAN_TO_BASE(chan)->wide_circ_ids =
1590 chan->conn->link_proto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
1591 chan->conn->wide_circ_ids = TLS_CHAN_TO_BASE(chan)->wide_circ_ids;
1593 TLS_CHAN_TO_BASE(chan)->padding_enabled =
1594 chan->conn->link_proto >= MIN_LINK_PROTO_FOR_CHANNEL_PADDING;
1596 if (send_certs) {
1597 if (connection_or_send_certs_cell(chan->conn) < 0) {
1598 log_warn(LD_OR, "Couldn't send certs cell");
1599 connection_or_close_for_error(chan->conn, 0);
1600 return;
1603 if (send_chall) {
1604 if (connection_or_send_auth_challenge_cell(chan->conn) < 0) {
1605 log_warn(LD_OR, "Couldn't send auth_challenge cell");
1606 connection_or_close_for_error(chan->conn, 0);
1607 return;
1610 if (send_netinfo) {
1611 if (connection_or_send_netinfo(chan->conn) < 0) {
1612 log_warn(LD_OR, "Couldn't send netinfo cell");
1613 connection_or_close_for_error(chan->conn, 0);
1614 return;
1621 * Process a 'padding_negotiate' cell.
1623 * This function is called to handle an incoming PADDING_NEGOTIATE cell;
1624 * enable or disable padding accordingly, and read and act on its timeout
1625 * value contents.
1627 static void
1628 channel_tls_process_padding_negotiate_cell(cell_t *cell, channel_tls_t *chan)
1630 channelpadding_negotiate_t *negotiation;
1631 tor_assert(cell);
1632 tor_assert(chan);
1633 tor_assert(chan->conn);
1635 if (chan->conn->link_proto < MIN_LINK_PROTO_FOR_CHANNEL_PADDING) {
1636 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1637 "Received a PADDING_NEGOTIATE cell on v%d connection; dropping.",
1638 chan->conn->link_proto);
1639 return;
1642 if (channelpadding_negotiate_parse(&negotiation, cell->payload,
1643 CELL_PAYLOAD_SIZE) < 0) {
1644 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1645 "Received malformed PADDING_NEGOTIATE cell on v%d connection; "
1646 "dropping.", chan->conn->link_proto);
1648 return;
1651 channelpadding_update_padding_for_channel(TLS_CHAN_TO_BASE(chan),
1652 negotiation);
1654 channelpadding_negotiate_free(negotiation);
1658 * Convert <b>netinfo_addr</b> into corresponding <b>tor_addr</b>.
1659 * Return 0 on success; on failure, return -1 and log a warning.
1661 static int
1662 tor_addr_from_netinfo_addr(tor_addr_t *tor_addr,
1663 const netinfo_addr_t *netinfo_addr) {
1664 tor_assert(tor_addr);
1665 tor_assert(netinfo_addr);
1667 uint8_t type = netinfo_addr_get_addr_type(netinfo_addr);
1668 uint8_t len = netinfo_addr_get_len(netinfo_addr);
1670 if (type == NETINFO_ADDR_TYPE_IPV4 && len == 4) {
1671 uint32_t ipv4 = netinfo_addr_get_addr_ipv4(netinfo_addr);
1672 tor_addr_from_ipv4h(tor_addr, ipv4);
1673 } else if (type == NETINFO_ADDR_TYPE_IPV6 && len == 16) {
1674 const uint8_t *ipv6_bytes = netinfo_addr_getconstarray_addr_ipv6(
1675 netinfo_addr);
1676 tor_addr_from_ipv6_bytes(tor_addr, ipv6_bytes);
1677 } else {
1678 log_fn(LOG_PROTOCOL_WARN, LD_OR, "Cannot read address from NETINFO "
1679 "- wrong type/length.");
1680 return -1;
1683 return 0;
1687 * Helper: compute the absolute value of a time_t.
1689 * (we need this because labs() doesn't always work for time_t, since
1690 * long can be shorter than time_t.)
1692 static inline time_t
1693 time_abs(time_t val)
1695 return (val < 0) ? -val : val;
1698 /** Return true iff the channel can process a NETINFO cell. For this to return
1699 * true, these channel conditions apply:
1701 * 1. Link protocol is version 2 or higher (tor-spec.txt, NETINFO cells
1702 * section).
1704 * 2. Underlying OR connection of the channel is either in v2 or v3
1705 * handshaking state.
1707 static bool
1708 can_process_netinfo_cell(const channel_tls_t *chan)
1710 /* NETINFO cells can only be negotiated on link protocol 2 or higher. */
1711 if (chan->conn->link_proto < 2) {
1712 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1713 "Received a NETINFO cell on %s connection; dropping.",
1714 chan->conn->link_proto == 0 ? "non-versioned" : "a v1");
1715 return false;
1718 /* Can't process a NETINFO cell if the connection is not handshaking. */
1719 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
1720 chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
1721 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1722 "Received a NETINFO cell on non-handshaking connection; dropping.");
1723 return false;
1726 /* Make sure we do have handshake state. */
1727 tor_assert(chan->conn->handshake_state);
1728 tor_assert(chan->conn->handshake_state->received_versions);
1730 return true;
1733 /** Mark the given channel endpoint as a client (which means either a tor
1734 * client or a tor bridge).
1736 * This MUST be done on an _unauthenticated_ channel. It is a mistake to mark
1737 * an authenticated channel as a client.
1739 * The following is done on the channel:
1741 * 1. Marked as a client.
1742 * 2. Type of circuit ID type is set.
1743 * 3. The underlying OR connection is initialized with the address of the
1744 * endpoint.
1746 static void
1747 mark_channel_tls_endpoint_as_client(channel_tls_t *chan)
1749 /* Ending up here for an authenticated link is a mistake. */
1750 if (BUG(chan->conn->handshake_state->authenticated)) {
1751 return;
1754 tor_assert(tor_digest_is_zero(
1755 (const char*)(chan->conn->handshake_state->
1756 authenticated_rsa_peer_id)));
1757 tor_assert(fast_mem_is_zero(
1758 (const char*)(chan->conn->handshake_state->
1759 authenticated_ed25519_peer_id.pubkey), 32));
1760 /* If the client never authenticated, it's a tor client or bridge
1761 * relay, and we must not use it for EXTEND requests (nor could we, as
1762 * there are no authenticated peer IDs) */
1763 channel_mark_client(TLS_CHAN_TO_BASE(chan));
1764 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), NULL,
1765 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
1767 connection_or_init_conn_from_address(chan->conn,
1768 &(chan->conn->base_.addr),
1769 chan->conn->base_.port,
1770 /* zero, checked above */
1771 (const char*)(chan->conn->handshake_state->
1772 authenticated_rsa_peer_id),
1773 NULL, /* Ed25519 ID: Also checked as zero */
1778 * Process a 'netinfo' cell
1780 * This function is called to handle an incoming NETINFO cell; read and act
1781 * on its contents, and set the connection state to "open".
1783 static void
1784 channel_tls_process_netinfo_cell(cell_t *cell, channel_tls_t *chan)
1786 time_t timestamp;
1787 uint8_t my_addr_type;
1788 uint8_t my_addr_len;
1789 uint8_t n_other_addrs;
1790 time_t now = time(NULL);
1791 const routerinfo_t *me = router_get_my_routerinfo();
1793 time_t apparent_skew = 0;
1794 tor_addr_t my_apparent_addr = TOR_ADDR_NULL;
1795 int started_here = 0;
1796 const char *identity_digest = NULL;
1798 tor_assert(cell);
1799 tor_assert(chan);
1800 tor_assert(chan->conn);
1802 /* Make sure we can process a NETINFO cell. Link protocol and state
1803 * validation is done to make sure of it. */
1804 if (!can_process_netinfo_cell(chan)) {
1805 return;
1808 started_here = connection_or_nonopen_was_started_here(chan->conn);
1809 identity_digest = chan->conn->identity_digest;
1811 if (chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1812 tor_assert(chan->conn->link_proto >= 3);
1813 if (started_here) {
1814 if (!(chan->conn->handshake_state->authenticated)) {
1815 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1816 "Got a NETINFO cell from server, "
1817 "but no authentication. Closing the connection.");
1818 connection_or_close_for_error(chan->conn, 0);
1819 return;
1821 } else {
1822 /* We're the server. If the client never authenticated, we have some
1823 * housekeeping to do.
1825 * It's a tor client or bridge relay, and we must not use it for EXTEND
1826 * requests (nor could we, as there are no authenticated peer IDs) */
1827 if (!(chan->conn->handshake_state->authenticated)) {
1828 mark_channel_tls_endpoint_as_client(chan);
1833 /* Decode the cell. */
1834 netinfo_cell_t *netinfo_cell = NULL;
1836 ssize_t parsed = netinfo_cell_parse(&netinfo_cell, cell->payload,
1837 CELL_PAYLOAD_SIZE);
1839 if (parsed < 0) {
1840 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1841 "Failed to parse NETINFO cell - closing connection.");
1842 connection_or_close_for_error(chan->conn, 0);
1843 return;
1846 timestamp = netinfo_cell_get_timestamp(netinfo_cell);
1848 const netinfo_addr_t *my_addr =
1849 netinfo_cell_getconst_other_addr(netinfo_cell);
1851 my_addr_type = netinfo_addr_get_addr_type(my_addr);
1852 my_addr_len = netinfo_addr_get_len(my_addr);
1854 if ((now - chan->conn->handshake_state->sent_versions_at) < 180) {
1855 apparent_skew = now - timestamp;
1857 /* We used to check:
1858 * if (my_addr_len >= CELL_PAYLOAD_SIZE - 6) {
1860 * This is actually never going to happen, since my_addr_len is at most 255,
1861 * and CELL_PAYLOAD_LEN - 6 is 503. So we know that cp is < end. */
1863 if (tor_addr_from_netinfo_addr(&my_apparent_addr, my_addr) == -1) {
1864 connection_or_close_for_error(chan->conn, 0);
1865 netinfo_cell_free(netinfo_cell);
1866 return;
1869 if (my_addr_type == NETINFO_ADDR_TYPE_IPV4 && my_addr_len == 4) {
1870 if (!get_options()->BridgeRelay && me &&
1871 tor_addr_eq(&my_apparent_addr, &me->ipv4_addr)) {
1872 TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
1874 } else if (my_addr_type == NETINFO_ADDR_TYPE_IPV6 &&
1875 my_addr_len == 16) {
1876 if (!get_options()->BridgeRelay && me &&
1877 !tor_addr_is_null(&me->ipv6_addr) &&
1878 tor_addr_eq(&my_apparent_addr, &me->ipv6_addr)) {
1879 TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
1883 if (me) {
1884 /* We have a descriptor, so we are a relay: record the address that the
1885 * other side said we had. */
1886 tor_addr_copy(&TLS_CHAN_TO_BASE(chan)->addr_according_to_peer,
1887 &my_apparent_addr);
1890 n_other_addrs = netinfo_cell_get_n_my_addrs(netinfo_cell);
1891 for (uint8_t i = 0; i < n_other_addrs; i++) {
1892 /* Consider all the other addresses; if any matches, this connection is
1893 * "canonical." */
1895 const netinfo_addr_t *netinfo_addr =
1896 netinfo_cell_getconst_my_addrs(netinfo_cell, i);
1898 tor_addr_t addr;
1900 if (tor_addr_from_netinfo_addr(&addr, netinfo_addr) == -1) {
1901 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1902 "Bad address in netinfo cell; Skipping.");
1903 continue;
1905 /* A relay can connect from anywhere and be canonical, so
1906 * long as it tells you from where it came. This may sound a bit
1907 * concerning... but that's what "canonical" means: that the
1908 * address is one that the relay itself has claimed. The relay
1909 * might be doing something funny, but nobody else is doing a MITM
1910 * on the relay's TCP.
1912 if (tor_addr_eq(&addr, &TO_CONN(chan->conn)->addr)) {
1913 connection_or_set_canonical(chan->conn, 1);
1914 break;
1918 netinfo_cell_free(netinfo_cell);
1920 if (me && !TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer &&
1921 channel_is_canonical(TLS_CHAN_TO_BASE(chan))) {
1922 const char *descr = channel_describe_peer(
1923 TLS_CHAN_TO_BASE(chan));
1924 log_info(LD_OR,
1925 "We made a connection to a relay at %s (fp=%s) but we think "
1926 "they will not consider this connection canonical. They "
1927 "think we are at %s, but we think its %s.",
1928 safe_str(descr),
1929 safe_str(hex_str(identity_digest, DIGEST_LEN)),
1930 safe_str(tor_addr_is_null(&my_apparent_addr) ?
1931 "<none>" : fmt_and_decorate_addr(&my_apparent_addr)),
1932 safe_str(fmt_addr(&me->ipv4_addr)));
1935 /* Act on apparent skew. */
1936 /** Warn when we get a netinfo skew with at least this value. */
1937 #define NETINFO_NOTICE_SKEW 3600
1938 if (time_abs(apparent_skew) > NETINFO_NOTICE_SKEW &&
1939 (started_here ||
1940 connection_or_digest_is_known_relay(chan->conn->identity_digest))) {
1941 int trusted = router_digest_is_trusted_dir(chan->conn->identity_digest);
1942 clock_skew_warning(TO_CONN(chan->conn), apparent_skew, trusted, LD_GENERAL,
1943 "NETINFO cell", "OR");
1946 /* Consider our apparent address as a possible suggestion for our address if
1947 * we were unable to resolve it previously. The endpoint address is passed
1948 * in order to make sure to never consider an address that is the same as
1949 * our endpoint. */
1950 relay_address_new_suggestion(&my_apparent_addr, &TO_CONN(chan->conn)->addr,
1951 identity_digest);
1953 if (! chan->conn->handshake_state->sent_netinfo) {
1954 /* If we were prepared to authenticate, but we never got an AUTH_CHALLENGE
1955 * cell, then we would not previously have sent a NETINFO cell. Do so
1956 * now. */
1957 if (connection_or_send_netinfo(chan->conn) < 0) {
1958 connection_or_close_for_error(chan->conn, 0);
1959 return;
1963 if (connection_or_set_state_open(chan->conn) < 0) {
1964 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1965 "Got good NETINFO cell on %s; but "
1966 "was unable to make the OR connection become open.",
1967 connection_describe(TO_CONN(chan->conn)));
1968 connection_or_close_for_error(chan->conn, 0);
1969 } else {
1970 log_info(LD_OR,
1971 "Got good NETINFO cell on %s; OR connection is now "
1972 "open, using protocol version %d. Its ID digest is %s. "
1973 "Our address is apparently %s.",
1974 connection_describe(TO_CONN(chan->conn)),
1975 (int)(chan->conn->link_proto),
1976 hex_str(identity_digest, DIGEST_LEN),
1977 tor_addr_is_null(&my_apparent_addr) ?
1978 "<none>" :
1979 safe_str_client(fmt_and_decorate_addr(&my_apparent_addr)));
1981 assert_connection_ok(TO_CONN(chan->conn),time(NULL));
1984 /** Types of certificates that we know how to parse from CERTS cells. Each
1985 * type corresponds to a different encoding format. */
1986 typedef enum cert_encoding_t {
1987 CERT_ENCODING_UNKNOWN, /**< We don't recognize this. */
1988 CERT_ENCODING_X509, /**< It's an RSA key, signed with RSA, encoded in x509.
1989 * (Actually, it might not be RSA. We test that later.) */
1990 CERT_ENCODING_ED25519, /**< It's something signed with an Ed25519 key,
1991 * encoded asa a tor_cert_t.*/
1992 CERT_ENCODING_RSA_CROSSCERT, /**< It's an Ed key signed with an RSA key. */
1993 } cert_encoding_t;
1996 * Given one of the certificate type codes used in a CERTS cell,
1997 * return the corresponding cert_encoding_t that we should use to parse
1998 * the certificate.
2000 static cert_encoding_t
2001 certs_cell_typenum_to_cert_type(int typenum)
2003 switch (typenum) {
2004 case CERTTYPE_RSA1024_ID_LINK:
2005 case CERTTYPE_RSA1024_ID_ID:
2006 case CERTTYPE_RSA1024_ID_AUTH:
2007 return CERT_ENCODING_X509;
2008 case CERTTYPE_ED_ID_SIGN:
2009 case CERTTYPE_ED_SIGN_LINK:
2010 case CERTTYPE_ED_SIGN_AUTH:
2011 return CERT_ENCODING_ED25519;
2012 case CERTTYPE_RSA1024_ID_EDID:
2013 return CERT_ENCODING_RSA_CROSSCERT;
2014 default:
2015 return CERT_ENCODING_UNKNOWN;
2020 * Process a CERTS cell from a channel.
2022 * This function is called to process an incoming CERTS cell on a
2023 * channel_tls_t:
2025 * If the other side should not have sent us a CERTS cell, or the cell is
2026 * malformed, or it is supposed to authenticate the TLS key but it doesn't,
2027 * then mark the connection.
2029 * If the cell has a good cert chain and we're doing a v3 handshake, then
2030 * store the certificates in or_handshake_state. If this is the client side
2031 * of the connection, we then authenticate the server or mark the connection.
2032 * If it's the server side, wait for an AUTHENTICATE cell.
2034 STATIC void
2035 channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
2037 #define MAX_CERT_TYPE_WANTED CERTTYPE_RSA1024_ID_EDID
2038 /* These arrays will be sparse, since a cert type can be at most one
2039 * of ed/x509 */
2040 tor_x509_cert_t *x509_certs[MAX_CERT_TYPE_WANTED + 1];
2041 tor_cert_t *ed_certs[MAX_CERT_TYPE_WANTED + 1];
2042 uint8_t *rsa_ed_cc_cert = NULL;
2043 size_t rsa_ed_cc_cert_len = 0;
2045 int n_certs, i;
2046 certs_cell_t *cc = NULL;
2048 int send_netinfo = 0, started_here = 0;
2050 memset(x509_certs, 0, sizeof(x509_certs));
2051 memset(ed_certs, 0, sizeof(ed_certs));
2052 tor_assert(cell);
2053 tor_assert(chan);
2054 tor_assert(chan->conn);
2056 #define ERR(s) \
2057 do { \
2058 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
2059 "Received a bad CERTS cell on %s: %s", \
2060 connection_describe(TO_CONN(chan->conn)), \
2061 (s)); \
2062 connection_or_close_for_error(chan->conn, 0); \
2063 goto err; \
2064 } while (0)
2066 /* Can't use connection_or_nonopen_was_started_here(); its conn->tls
2067 * check looks like it breaks
2068 * test_link_handshake_recv_certs_ok_server(). */
2069 started_here = chan->conn->handshake_state->started_here;
2071 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
2072 ERR("We're not doing a v3 handshake!");
2073 if (chan->conn->link_proto < 3)
2074 ERR("We're not using link protocol >= 3");
2075 if (chan->conn->handshake_state->received_certs_cell)
2076 ERR("We already got one");
2077 if (chan->conn->handshake_state->authenticated) {
2078 /* Should be unreachable, but let's make sure. */
2079 ERR("We're already authenticated!");
2081 if (cell->payload_len < 1)
2082 ERR("It had no body");
2083 if (cell->circ_id)
2084 ERR("It had a nonzero circuit ID");
2086 if (certs_cell_parse(&cc, cell->payload, cell->payload_len) < 0)
2087 ERR("It couldn't be parsed.");
2089 n_certs = cc->n_certs;
2091 for (i = 0; i < n_certs; ++i) {
2092 certs_cell_cert_t *c = certs_cell_get_certs(cc, i);
2094 uint16_t cert_type = c->cert_type;
2095 uint16_t cert_len = c->cert_len;
2096 uint8_t *cert_body = certs_cell_cert_getarray_body(c);
2098 if (cert_type > MAX_CERT_TYPE_WANTED)
2099 continue;
2100 const cert_encoding_t ct = certs_cell_typenum_to_cert_type(cert_type);
2101 switch (ct) {
2102 default:
2103 case CERT_ENCODING_UNKNOWN:
2104 break;
2105 case CERT_ENCODING_X509: {
2106 tor_x509_cert_t *x509_cert = tor_x509_cert_decode(cert_body, cert_len);
2107 if (!x509_cert) {
2108 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2109 "Received undecodable certificate in CERTS cell on %s",
2110 connection_describe(TO_CONN(chan->conn)));
2111 } else {
2112 if (x509_certs[cert_type]) {
2113 tor_x509_cert_free(x509_cert);
2114 ERR("Duplicate x509 certificate");
2115 } else {
2116 x509_certs[cert_type] = x509_cert;
2119 break;
2121 case CERT_ENCODING_ED25519: {
2122 tor_cert_t *ed_cert = tor_cert_parse(cert_body, cert_len);
2123 if (!ed_cert) {
2124 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2125 "Received undecodable Ed certificate "
2126 "in CERTS cell on %s",
2127 connection_describe(TO_CONN(chan->conn)));
2128 } else {
2129 if (ed_certs[cert_type]) {
2130 tor_cert_free(ed_cert);
2131 ERR("Duplicate Ed25519 certificate");
2132 } else {
2133 ed_certs[cert_type] = ed_cert;
2136 break;
2139 case CERT_ENCODING_RSA_CROSSCERT: {
2140 if (rsa_ed_cc_cert) {
2141 ERR("Duplicate RSA->Ed25519 crosscert");
2142 } else {
2143 rsa_ed_cc_cert = tor_memdup(cert_body, cert_len);
2144 rsa_ed_cc_cert_len = cert_len;
2146 break;
2151 /* Move the certificates we (might) want into the handshake_state->certs
2152 * structure. */
2153 tor_x509_cert_t *id_cert = x509_certs[CERTTYPE_RSA1024_ID_ID];
2154 tor_x509_cert_t *auth_cert = x509_certs[CERTTYPE_RSA1024_ID_AUTH];
2155 tor_x509_cert_t *link_cert = x509_certs[CERTTYPE_RSA1024_ID_LINK];
2156 chan->conn->handshake_state->certs->auth_cert = auth_cert;
2157 chan->conn->handshake_state->certs->link_cert = link_cert;
2158 chan->conn->handshake_state->certs->id_cert = id_cert;
2159 x509_certs[CERTTYPE_RSA1024_ID_ID] =
2160 x509_certs[CERTTYPE_RSA1024_ID_AUTH] =
2161 x509_certs[CERTTYPE_RSA1024_ID_LINK] = NULL;
2163 tor_cert_t *ed_id_sign = ed_certs[CERTTYPE_ED_ID_SIGN];
2164 tor_cert_t *ed_sign_link = ed_certs[CERTTYPE_ED_SIGN_LINK];
2165 tor_cert_t *ed_sign_auth = ed_certs[CERTTYPE_ED_SIGN_AUTH];
2166 chan->conn->handshake_state->certs->ed_id_sign = ed_id_sign;
2167 chan->conn->handshake_state->certs->ed_sign_link = ed_sign_link;
2168 chan->conn->handshake_state->certs->ed_sign_auth = ed_sign_auth;
2169 ed_certs[CERTTYPE_ED_ID_SIGN] =
2170 ed_certs[CERTTYPE_ED_SIGN_LINK] =
2171 ed_certs[CERTTYPE_ED_SIGN_AUTH] = NULL;
2173 chan->conn->handshake_state->certs->ed_rsa_crosscert = rsa_ed_cc_cert;
2174 chan->conn->handshake_state->certs->ed_rsa_crosscert_len =
2175 rsa_ed_cc_cert_len;
2176 rsa_ed_cc_cert = NULL;
2178 int severity;
2179 /* Note that this warns more loudly about time and validity if we were
2180 * _trying_ to connect to an authority, not necessarily if we _did_ connect
2181 * to one. */
2182 if (started_here &&
2183 router_digest_is_trusted_dir(TLS_CHAN_TO_BASE(chan)->identity_digest))
2184 severity = LOG_WARN;
2185 else
2186 severity = LOG_PROTOCOL_WARN;
2188 const ed25519_public_key_t *checked_ed_id = NULL;
2189 const common_digests_t *checked_rsa_id = NULL;
2190 or_handshake_certs_check_both(severity,
2191 chan->conn->handshake_state->certs,
2192 chan->conn->tls,
2193 time(NULL),
2194 &checked_ed_id,
2195 &checked_rsa_id);
2197 if (!checked_rsa_id)
2198 ERR("Invalid certificate chain!");
2200 if (started_here) {
2201 /* No more information is needed. */
2203 chan->conn->handshake_state->authenticated = 1;
2204 chan->conn->handshake_state->authenticated_rsa = 1;
2206 const common_digests_t *id_digests = checked_rsa_id;
2207 crypto_pk_t *identity_rcvd;
2208 if (!id_digests)
2209 ERR("Couldn't compute digests for key in ID cert");
2211 identity_rcvd = tor_tls_cert_get_key(id_cert);
2212 if (!identity_rcvd) {
2213 ERR("Couldn't get RSA key from ID cert.");
2215 memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
2216 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
2217 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
2218 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
2219 crypto_pk_free(identity_rcvd);
2222 if (checked_ed_id) {
2223 chan->conn->handshake_state->authenticated_ed25519 = 1;
2224 memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
2225 checked_ed_id, sizeof(ed25519_public_key_t));
2228 log_debug(LD_HANDSHAKE, "calling client_learned_peer_id from "
2229 "process_certs_cell");
2231 if (connection_or_client_learned_peer_id(chan->conn,
2232 chan->conn->handshake_state->authenticated_rsa_peer_id,
2233 checked_ed_id) < 0)
2234 ERR("Problem setting or checking peer id");
2236 log_info(LD_HANDSHAKE,
2237 "Got some good certificates on %s: Authenticated it with "
2238 "RSA%s",
2239 connection_describe(TO_CONN(chan->conn)),
2240 checked_ed_id ? " and Ed25519" : "");
2242 if (!public_server_mode(get_options())) {
2243 /* If we initiated the connection and we are not a public server, we
2244 * aren't planning to authenticate at all. At this point we know who we
2245 * are talking to, so we can just send a netinfo now. */
2246 send_netinfo = 1;
2248 } else {
2249 /* We can't call it authenticated till we see an AUTHENTICATE cell. */
2250 log_info(LD_OR,
2251 "Got some good RSA%s certificates on %s. "
2252 "Waiting for AUTHENTICATE.",
2253 checked_ed_id ? " and Ed25519" : "",
2254 connection_describe(TO_CONN(chan->conn)));
2255 /* XXXX check more stuff? */
2258 chan->conn->handshake_state->received_certs_cell = 1;
2260 if (send_netinfo) {
2261 if (connection_or_send_netinfo(chan->conn) < 0) {
2262 log_warn(LD_OR, "Couldn't send netinfo cell");
2263 connection_or_close_for_error(chan->conn, 0);
2264 goto err;
2268 err:
2269 for (unsigned u = 0; u < ARRAY_LENGTH(x509_certs); ++u) {
2270 tor_x509_cert_free(x509_certs[u]);
2272 for (unsigned u = 0; u < ARRAY_LENGTH(ed_certs); ++u) {
2273 tor_cert_free(ed_certs[u]);
2275 tor_free(rsa_ed_cc_cert);
2276 certs_cell_free(cc);
2277 #undef ERR
2281 * Process an AUTH_CHALLENGE cell from a channel_tls_t.
2283 * This function is called to handle an incoming AUTH_CHALLENGE cell on a
2284 * channel_tls_t; if we weren't supposed to get one (for example, because we're
2285 * not the originator of the channel), or it's ill-formed, or we aren't doing
2286 * a v3 handshake, mark the channel. If the cell is well-formed but we don't
2287 * want to authenticate, just drop it. If the cell is well-formed *and* we
2288 * want to authenticate, send an AUTHENTICATE cell and then a NETINFO cell.
2290 STATIC void
2291 channel_tls_process_auth_challenge_cell(var_cell_t *cell, channel_tls_t *chan)
2293 int n_types, i, use_type = -1;
2294 auth_challenge_cell_t *ac = NULL;
2296 tor_assert(cell);
2297 tor_assert(chan);
2298 tor_assert(chan->conn);
2300 #define ERR(s) \
2301 do { \
2302 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
2303 "Received a bad AUTH_CHALLENGE cell on %s: %s", \
2304 connection_describe(TO_CONN(chan->conn)), \
2305 (s)); \
2306 connection_or_close_for_error(chan->conn, 0); \
2307 goto done; \
2308 } while (0)
2310 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
2311 ERR("We're not currently doing a v3 handshake");
2312 if (chan->conn->link_proto < 3)
2313 ERR("We're not using link protocol >= 3");
2314 if (!(chan->conn->handshake_state->started_here))
2315 ERR("We didn't originate this connection");
2316 if (chan->conn->handshake_state->received_auth_challenge)
2317 ERR("We already received one");
2318 if (!(chan->conn->handshake_state->received_certs_cell))
2319 ERR("We haven't gotten a CERTS cell yet");
2320 if (cell->circ_id)
2321 ERR("It had a nonzero circuit ID");
2323 if (auth_challenge_cell_parse(&ac, cell->payload, cell->payload_len) < 0)
2324 ERR("It was not well-formed.");
2326 n_types = ac->n_methods;
2328 /* Now see if there is an authentication type we can use */
2329 for (i = 0; i < n_types; ++i) {
2330 uint16_t authtype = auth_challenge_cell_get_methods(ac, i);
2331 if (authchallenge_type_is_supported(authtype)) {
2332 if (use_type == -1 ||
2333 authchallenge_type_is_better(authtype, use_type)) {
2334 use_type = authtype;
2339 chan->conn->handshake_state->received_auth_challenge = 1;
2341 if (! public_server_mode(get_options())) {
2342 /* If we're not a public server then we don't want to authenticate on a
2343 connection we originated, and we already sent a NETINFO cell when we
2344 got the CERTS cell. We have nothing more to do. */
2345 goto done;
2348 if (use_type >= 0) {
2349 log_info(LD_OR,
2350 "Got an AUTH_CHALLENGE cell on %s: Sending "
2351 "authentication type %d",
2352 connection_describe(TO_CONN(chan->conn)),
2353 use_type);
2355 if (connection_or_send_authenticate_cell(chan->conn, use_type) < 0) {
2356 log_warn(LD_OR,
2357 "Couldn't send authenticate cell");
2358 connection_or_close_for_error(chan->conn, 0);
2359 goto done;
2361 } else {
2362 log_info(LD_OR,
2363 "Got an AUTH_CHALLENGE cell on %s, but we don't "
2364 "know any of its authentication types. Not authenticating.",
2365 connection_describe(TO_CONN(chan->conn)));
2368 if (connection_or_send_netinfo(chan->conn) < 0) {
2369 log_warn(LD_OR, "Couldn't send netinfo cell");
2370 connection_or_close_for_error(chan->conn, 0);
2371 goto done;
2374 done:
2375 auth_challenge_cell_free(ac);
2377 #undef ERR
2381 * Process an AUTHENTICATE cell from a channel_tls_t.
2383 * If it's ill-formed or we weren't supposed to get one or we're not doing a
2384 * v3 handshake, then mark the connection. If it does not authenticate the
2385 * other side of the connection successfully (because it isn't signed right,
2386 * we didn't get a CERTS cell, etc) mark the connection. Otherwise, accept
2387 * the identity of the router on the other side of the connection.
2389 STATIC void
2390 channel_tls_process_authenticate_cell(var_cell_t *cell, channel_tls_t *chan)
2392 var_cell_t *expected_cell = NULL;
2393 const uint8_t *auth;
2394 int authlen;
2395 int authtype;
2396 int bodylen;
2398 tor_assert(cell);
2399 tor_assert(chan);
2400 tor_assert(chan->conn);
2402 #define ERR(s) \
2403 do { \
2404 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
2405 "Received a bad AUTHENTICATE cell on %s: %s", \
2406 connection_describe(TO_CONN(chan->conn)), \
2407 (s)); \
2408 connection_or_close_for_error(chan->conn, 0); \
2409 var_cell_free(expected_cell); \
2410 return; \
2411 } while (0)
2413 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
2414 ERR("We're not doing a v3 handshake");
2415 if (chan->conn->link_proto < 3)
2416 ERR("We're not using link protocol >= 3");
2417 if (chan->conn->handshake_state->started_here)
2418 ERR("We originated this connection");
2419 if (chan->conn->handshake_state->received_authenticate)
2420 ERR("We already got one!");
2421 if (chan->conn->handshake_state->authenticated) {
2422 /* Should be impossible given other checks */
2423 ERR("The peer is already authenticated");
2425 if (!(chan->conn->handshake_state->received_certs_cell))
2426 ERR("We never got a certs cell");
2427 if (chan->conn->handshake_state->certs->id_cert == NULL)
2428 ERR("We never got an identity certificate");
2429 if (cell->payload_len < 4)
2430 ERR("Cell was way too short");
2432 auth = cell->payload;
2434 uint16_t type = ntohs(get_uint16(auth));
2435 uint16_t len = ntohs(get_uint16(auth+2));
2436 if (4 + len > cell->payload_len)
2437 ERR("Authenticator was truncated");
2439 if (! authchallenge_type_is_supported(type))
2440 ERR("Authenticator type was not recognized");
2441 authtype = type;
2443 auth += 4;
2444 authlen = len;
2447 if (authlen < V3_AUTH_BODY_LEN + 1)
2448 ERR("Authenticator was too short");
2450 expected_cell = connection_or_compute_authenticate_cell_body(
2451 chan->conn, authtype, NULL, NULL, 1);
2452 if (! expected_cell)
2453 ERR("Couldn't compute expected AUTHENTICATE cell body");
2455 int sig_is_rsa;
2456 if (authtype == AUTHTYPE_RSA_SHA256_TLSSECRET ||
2457 authtype == AUTHTYPE_RSA_SHA256_RFC5705) {
2458 bodylen = V3_AUTH_BODY_LEN;
2459 sig_is_rsa = 1;
2460 } else {
2461 tor_assert(authtype == AUTHTYPE_ED25519_SHA256_RFC5705);
2462 /* Our earlier check had better have made sure we had room
2463 * for an ed25519 sig (inadvertently) */
2464 tor_assert(V3_AUTH_BODY_LEN > ED25519_SIG_LEN);
2465 bodylen = authlen - ED25519_SIG_LEN;
2466 sig_is_rsa = 0;
2468 if (expected_cell->payload_len != bodylen+4) {
2469 ERR("Expected AUTHENTICATE cell body len not as expected.");
2472 /* Length of random part. */
2473 if (BUG(bodylen < 24)) {
2474 // LCOV_EXCL_START
2475 ERR("Bodylen is somehow less than 24, which should really be impossible");
2476 // LCOV_EXCL_STOP
2479 if (tor_memneq(expected_cell->payload+4, auth, bodylen-24))
2480 ERR("Some field in the AUTHENTICATE cell body was not as expected");
2482 if (sig_is_rsa) {
2483 if (chan->conn->handshake_state->certs->ed_id_sign != NULL)
2484 ERR("RSA-signed AUTHENTICATE response provided with an ED25519 cert");
2486 if (chan->conn->handshake_state->certs->auth_cert == NULL)
2487 ERR("We never got an RSA authentication certificate");
2489 crypto_pk_t *pk = tor_tls_cert_get_key(
2490 chan->conn->handshake_state->certs->auth_cert);
2491 char d[DIGEST256_LEN];
2492 char *signed_data;
2493 size_t keysize;
2494 int signed_len;
2496 if (! pk) {
2497 ERR("Couldn't get RSA key from AUTH cert.");
2499 crypto_digest256(d, (char*)auth, V3_AUTH_BODY_LEN, DIGEST_SHA256);
2501 keysize = crypto_pk_keysize(pk);
2502 signed_data = tor_malloc(keysize);
2503 signed_len = crypto_pk_public_checksig(pk, signed_data, keysize,
2504 (char*)auth + V3_AUTH_BODY_LEN,
2505 authlen - V3_AUTH_BODY_LEN);
2506 crypto_pk_free(pk);
2507 if (signed_len < 0) {
2508 tor_free(signed_data);
2509 ERR("RSA signature wasn't valid");
2511 if (signed_len < DIGEST256_LEN) {
2512 tor_free(signed_data);
2513 ERR("Not enough data was signed");
2515 /* Note that we deliberately allow *more* than DIGEST256_LEN bytes here,
2516 * in case they're later used to hold a SHA3 digest or something. */
2517 if (tor_memneq(signed_data, d, DIGEST256_LEN)) {
2518 tor_free(signed_data);
2519 ERR("Signature did not match data to be signed.");
2521 tor_free(signed_data);
2522 } else {
2523 if (chan->conn->handshake_state->certs->ed_id_sign == NULL)
2524 ERR("We never got an Ed25519 identity certificate.");
2525 if (chan->conn->handshake_state->certs->ed_sign_auth == NULL)
2526 ERR("We never got an Ed25519 authentication certificate.");
2528 const ed25519_public_key_t *authkey =
2529 &chan->conn->handshake_state->certs->ed_sign_auth->signed_key;
2530 ed25519_signature_t sig;
2531 tor_assert(authlen > ED25519_SIG_LEN);
2532 memcpy(&sig.sig, auth + authlen - ED25519_SIG_LEN, ED25519_SIG_LEN);
2533 if (ed25519_checksig(&sig, auth, authlen - ED25519_SIG_LEN, authkey)<0) {
2534 ERR("Ed25519 signature wasn't valid.");
2538 /* Okay, we are authenticated. */
2539 chan->conn->handshake_state->received_authenticate = 1;
2540 chan->conn->handshake_state->authenticated = 1;
2541 chan->conn->handshake_state->authenticated_rsa = 1;
2542 chan->conn->handshake_state->digest_received_data = 0;
2544 tor_x509_cert_t *id_cert = chan->conn->handshake_state->certs->id_cert;
2545 crypto_pk_t *identity_rcvd = tor_tls_cert_get_key(id_cert);
2546 const common_digests_t *id_digests = tor_x509_cert_get_id_digests(id_cert);
2547 const ed25519_public_key_t *ed_identity_received = NULL;
2549 if (! sig_is_rsa) {
2550 chan->conn->handshake_state->authenticated_ed25519 = 1;
2551 ed_identity_received =
2552 &chan->conn->handshake_state->certs->ed_id_sign->signing_key;
2553 memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
2554 ed_identity_received, sizeof(ed25519_public_key_t));
2557 /* This must exist; we checked key type when reading the cert. */
2558 tor_assert(id_digests);
2560 memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
2561 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
2563 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
2564 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
2565 crypto_pk_free(identity_rcvd);
2567 log_debug(LD_HANDSHAKE,
2568 "Calling connection_or_init_conn_from_address on %s "
2569 " from %s, with%s ed25519 id.",
2570 connection_describe(TO_CONN(chan->conn)),
2571 __func__,
2572 ed_identity_received ? "" : "out");
2574 connection_or_init_conn_from_address(chan->conn,
2575 &(chan->conn->base_.addr),
2576 chan->conn->base_.port,
2577 (const char*)(chan->conn->handshake_state->
2578 authenticated_rsa_peer_id),
2579 ed_identity_received,
2582 log_debug(LD_HANDSHAKE,
2583 "Got an AUTHENTICATE cell on %s, type %d: Looks good.",
2584 connection_describe(TO_CONN(chan->conn)),
2585 authtype);
2588 var_cell_free(expected_cell);
2590 #undef ERR