more fixes for typos, grammar, whitespace, etc
[tor.git] / src / or / channeltls.c
blob2302c194b6798427b5b3979c4c3eeee6f7424b25
1 /* * Copyright (c) 2012-2017, 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.
38 #define TOR_CHANNEL_INTERNAL_
40 #define CHANNELTLS_PRIVATE
42 #include "or.h"
43 #include "channel.h"
44 #include "channeltls.h"
45 #include "circuitmux.h"
46 #include "circuitmux_ewma.h"
47 #include "command.h"
48 #include "config.h"
49 #include "connection.h"
50 #include "connection_or.h"
51 #include "control.h"
52 #include "entrynodes.h"
53 #include "link_handshake.h"
54 #include "relay.h"
55 #include "rephist.h"
56 #include "router.h"
57 #include "routerlist.h"
58 #include "scheduler.h"
59 #include "torcert.h"
60 #include "networkstatus.h"
61 #include "channelpadding_negotiation.h"
62 #include "channelpadding.h"
64 /** How many CELL_PADDING cells have we received, ever? */
65 uint64_t stats_n_padding_cells_processed = 0;
66 /** How many CELL_VERSIONS cells have we received, ever? */
67 uint64_t stats_n_versions_cells_processed = 0;
68 /** How many CELL_NETINFO cells have we received, ever? */
69 uint64_t stats_n_netinfo_cells_processed = 0;
70 /** How many CELL_VPADDING cells have we received, ever? */
71 uint64_t stats_n_vpadding_cells_processed = 0;
72 /** How many CELL_CERTS cells have we received, ever? */
73 uint64_t stats_n_certs_cells_processed = 0;
74 /** How many CELL_AUTH_CHALLENGE cells have we received, ever? */
75 uint64_t stats_n_auth_challenge_cells_processed = 0;
76 /** How many CELL_AUTHENTICATE cells have we received, ever? */
77 uint64_t stats_n_authenticate_cells_processed = 0;
78 /** How many CELL_AUTHORIZE cells have we received, ever? */
79 uint64_t stats_n_authorize_cells_processed = 0;
81 /** Active listener, if any */
82 static channel_listener_t *channel_tls_listener = NULL;
84 /* channel_tls_t method declarations */
86 static void channel_tls_close_method(channel_t *chan);
87 static const char * channel_tls_describe_transport_method(channel_t *chan);
88 static void channel_tls_free_method(channel_t *chan);
89 static double channel_tls_get_overhead_estimate_method(channel_t *chan);
90 static int
91 channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out);
92 static int
93 channel_tls_get_transport_name_method(channel_t *chan, char **transport_out);
94 static const char *
95 channel_tls_get_remote_descr_method(channel_t *chan, int flags);
96 static int channel_tls_has_queued_writes_method(channel_t *chan);
97 static int channel_tls_is_canonical_method(channel_t *chan, int req);
98 static int
99 channel_tls_matches_extend_info_method(channel_t *chan,
100 extend_info_t *extend_info);
101 static int channel_tls_matches_target_method(channel_t *chan,
102 const tor_addr_t *target);
103 static int channel_tls_num_cells_writeable_method(channel_t *chan);
104 static size_t channel_tls_num_bytes_queued_method(channel_t *chan);
105 static int channel_tls_write_cell_method(channel_t *chan,
106 cell_t *cell);
107 static int channel_tls_write_packed_cell_method(channel_t *chan,
108 packed_cell_t *packed_cell);
109 static int channel_tls_write_var_cell_method(channel_t *chan,
110 var_cell_t *var_cell);
112 /* channel_listener_tls_t method declarations */
114 static void channel_tls_listener_close_method(channel_listener_t *chan_l);
115 static const char *
116 channel_tls_listener_describe_transport_method(channel_listener_t *chan_l);
118 /** Handle incoming cells for the handshake stuff here rather than
119 * passing them on up. */
121 static void channel_tls_process_versions_cell(var_cell_t *cell,
122 channel_tls_t *tlschan);
123 static void channel_tls_process_netinfo_cell(cell_t *cell,
124 channel_tls_t *tlschan);
125 static int command_allowed_before_handshake(uint8_t command);
126 static int enter_v3_handshake_with_cell(var_cell_t *cell,
127 channel_tls_t *tlschan);
128 static void channel_tls_process_padding_negotiate_cell(cell_t *cell,
129 channel_tls_t *chan);
132 * Do parts of channel_tls_t initialization common to channel_tls_connect()
133 * and channel_tls_handle_incoming().
136 STATIC void
137 channel_tls_common_init(channel_tls_t *tlschan)
139 channel_t *chan;
141 tor_assert(tlschan);
143 chan = &(tlschan->base_);
144 channel_init(chan);
145 chan->magic = TLS_CHAN_MAGIC;
146 chan->state = CHANNEL_STATE_OPENING;
147 chan->close = channel_tls_close_method;
148 chan->describe_transport = channel_tls_describe_transport_method;
149 chan->free_fn = channel_tls_free_method;
150 chan->get_overhead_estimate = channel_tls_get_overhead_estimate_method;
151 chan->get_remote_addr = channel_tls_get_remote_addr_method;
152 chan->get_remote_descr = channel_tls_get_remote_descr_method;
153 chan->get_transport_name = channel_tls_get_transport_name_method;
154 chan->has_queued_writes = channel_tls_has_queued_writes_method;
155 chan->is_canonical = channel_tls_is_canonical_method;
156 chan->matches_extend_info = channel_tls_matches_extend_info_method;
157 chan->matches_target = channel_tls_matches_target_method;
158 chan->num_bytes_queued = channel_tls_num_bytes_queued_method;
159 chan->num_cells_writeable = channel_tls_num_cells_writeable_method;
160 chan->write_cell = channel_tls_write_cell_method;
161 chan->write_packed_cell = channel_tls_write_packed_cell_method;
162 chan->write_var_cell = channel_tls_write_var_cell_method;
164 chan->cmux = circuitmux_alloc();
165 if (cell_ewma_enabled()) {
166 circuitmux_set_policy(chan->cmux, &ewma_policy);
171 * Start a new TLS channel
173 * Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
174 * handshake with an OR with identity digest <b>id_digest</b>, and wrap
175 * it in a channel_tls_t.
178 channel_t *
179 channel_tls_connect(const tor_addr_t *addr, uint16_t port,
180 const char *id_digest,
181 const ed25519_public_key_t *ed_id)
183 channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
184 channel_t *chan = &(tlschan->base_);
186 channel_tls_common_init(tlschan);
188 log_debug(LD_CHANNEL,
189 "In channel_tls_connect() for channel %p "
190 "(global id " U64_FORMAT ")",
191 tlschan,
192 U64_PRINTF_ARG(chan->global_identifier));
194 if (is_local_addr(addr)) {
195 log_debug(LD_CHANNEL,
196 "Marking new outgoing channel " U64_FORMAT " at %p as local",
197 U64_PRINTF_ARG(chan->global_identifier), chan);
198 channel_mark_local(chan);
199 } else {
200 log_debug(LD_CHANNEL,
201 "Marking new outgoing channel " U64_FORMAT " at %p as remote",
202 U64_PRINTF_ARG(chan->global_identifier), chan);
203 channel_mark_remote(chan);
206 channel_mark_outgoing(chan);
208 /* Set up or_connection stuff */
209 tlschan->conn = connection_or_connect(addr, port, id_digest, ed_id, tlschan);
210 /* connection_or_connect() will fill in tlschan->conn */
211 if (!(tlschan->conn)) {
212 chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
213 channel_change_state(chan, CHANNEL_STATE_ERROR);
214 goto err;
217 log_debug(LD_CHANNEL,
218 "Got orconn %p for channel with global id " U64_FORMAT,
219 tlschan->conn, U64_PRINTF_ARG(chan->global_identifier));
221 goto done;
223 err:
224 circuitmux_free(chan->cmux);
225 tor_free(tlschan);
226 chan = NULL;
228 done:
229 /* If we got one, we should register it */
230 if (chan) channel_register(chan);
232 return chan;
236 * Return the current channel_tls_t listener
238 * Returns the current channel listener for incoming TLS connections, or
239 * NULL if none has been established
242 channel_listener_t *
243 channel_tls_get_listener(void)
245 return channel_tls_listener;
249 * Start a channel_tls_t listener if necessary
251 * Return the current channel_tls_t listener, or start one if we haven't yet,
252 * and return that.
255 channel_listener_t *
256 channel_tls_start_listener(void)
258 channel_listener_t *listener;
260 if (!channel_tls_listener) {
261 listener = tor_malloc_zero(sizeof(*listener));
262 channel_init_listener(listener);
263 listener->state = CHANNEL_LISTENER_STATE_LISTENING;
264 listener->close = channel_tls_listener_close_method;
265 listener->describe_transport =
266 channel_tls_listener_describe_transport_method;
268 channel_tls_listener = listener;
270 log_debug(LD_CHANNEL,
271 "Starting TLS channel listener %p with global id " U64_FORMAT,
272 listener, U64_PRINTF_ARG(listener->global_identifier));
274 channel_listener_register(listener);
275 } else listener = channel_tls_listener;
277 return listener;
281 * Free everything on shutdown
283 * Not much to do here, since channel_free_all() takes care of a lot, but let's
284 * get rid of the listener.
287 void
288 channel_tls_free_all(void)
290 channel_listener_t *old_listener = NULL;
292 log_debug(LD_CHANNEL,
293 "Shutting down TLS channels...");
295 if (channel_tls_listener) {
297 * When we close it, channel_tls_listener will get nulled out, so save
298 * a pointer so we can free it.
300 old_listener = channel_tls_listener;
301 log_debug(LD_CHANNEL,
302 "Closing channel_tls_listener with ID " U64_FORMAT
303 " at %p.",
304 U64_PRINTF_ARG(old_listener->global_identifier),
305 old_listener);
306 channel_listener_unregister(old_listener);
307 channel_listener_mark_for_close(old_listener);
308 channel_listener_free(old_listener);
309 tor_assert(channel_tls_listener == NULL);
312 log_debug(LD_CHANNEL,
313 "Done shutting down TLS channels");
317 * Create a new channel around an incoming or_connection_t
320 channel_t *
321 channel_tls_handle_incoming(or_connection_t *orconn)
323 channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
324 channel_t *chan = &(tlschan->base_);
326 tor_assert(orconn);
327 tor_assert(!(orconn->chan));
329 channel_tls_common_init(tlschan);
331 /* Link the channel and orconn to each other */
332 tlschan->conn = orconn;
333 orconn->chan = tlschan;
335 if (is_local_addr(&(TO_CONN(orconn)->addr))) {
336 log_debug(LD_CHANNEL,
337 "Marking new incoming channel " U64_FORMAT " at %p as local",
338 U64_PRINTF_ARG(chan->global_identifier), chan);
339 channel_mark_local(chan);
340 } else {
341 log_debug(LD_CHANNEL,
342 "Marking new incoming channel " U64_FORMAT " at %p as remote",
343 U64_PRINTF_ARG(chan->global_identifier), chan);
344 channel_mark_remote(chan);
347 channel_mark_incoming(chan);
349 /* Register it */
350 channel_register(chan);
352 return chan;
355 /*********
356 * Casts *
357 ********/
360 * Cast a channel_tls_t to a channel_t.
363 channel_t *
364 channel_tls_to_base(channel_tls_t *tlschan)
366 if (!tlschan) return NULL;
368 return &(tlschan->base_);
372 * Cast a channel_t to a channel_tls_t, with appropriate type-checking
373 * asserts.
376 channel_tls_t *
377 channel_tls_from_base(channel_t *chan)
379 if (!chan) return NULL;
381 tor_assert(chan->magic == TLS_CHAN_MAGIC);
383 return (channel_tls_t *)(chan);
386 /********************************************
387 * Method implementations for channel_tls_t *
388 *******************************************/
391 * Close a channel_tls_t
393 * This implements the close method for channel_tls_t
396 static void
397 channel_tls_close_method(channel_t *chan)
399 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
401 tor_assert(tlschan);
403 if (tlschan->conn) connection_or_close_normally(tlschan->conn, 1);
404 else {
405 /* Weird - we'll have to change the state ourselves, I guess */
406 log_info(LD_CHANNEL,
407 "Tried to close channel_tls_t %p with NULL conn",
408 tlschan);
409 channel_change_state(chan, CHANNEL_STATE_ERROR);
414 * Describe the transport for a channel_tls_t
416 * This returns the string "TLS channel on connection <id>" to the upper
417 * layer.
420 static const char *
421 channel_tls_describe_transport_method(channel_t *chan)
423 static char *buf = NULL;
424 uint64_t id;
425 channel_tls_t *tlschan;
426 const char *rv = NULL;
428 tor_assert(chan);
430 tlschan = BASE_CHAN_TO_TLS(chan);
432 if (tlschan->conn) {
433 id = TO_CONN(tlschan->conn)->global_identifier;
435 if (buf) tor_free(buf);
436 tor_asprintf(&buf,
437 "TLS channel (connection " U64_FORMAT ")",
438 U64_PRINTF_ARG(id));
440 rv = buf;
441 } else {
442 rv = "TLS channel (no connection)";
445 return rv;
449 * Free a channel_tls_t
451 * This is called by the generic channel layer when freeing a channel_tls_t;
452 * this happens either on a channel which has already reached
453 * CHANNEL_STATE_CLOSED or CHANNEL_STATE_ERROR from channel_run_cleanup() or
454 * on shutdown from channel_free_all(). In the latter case we might still
455 * have an orconn active (which connection_free_all() will get to later),
456 * so we should null out its channel pointer now.
459 static void
460 channel_tls_free_method(channel_t *chan)
462 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
464 tor_assert(tlschan);
466 if (tlschan->conn) {
467 tlschan->conn->chan = NULL;
468 tlschan->conn = NULL;
473 * Get an estimate of the average TLS overhead for the upper layer
476 static double
477 channel_tls_get_overhead_estimate_method(channel_t *chan)
479 double overhead = 1.0;
480 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
482 tor_assert(tlschan);
483 tor_assert(tlschan->conn);
485 /* Just return 1.0f if we don't have sensible data */
486 if (tlschan->conn->bytes_xmitted > 0 &&
487 tlschan->conn->bytes_xmitted_by_tls >=
488 tlschan->conn->bytes_xmitted) {
489 overhead = ((double)(tlschan->conn->bytes_xmitted_by_tls)) /
490 ((double)(tlschan->conn->bytes_xmitted));
493 * Never estimate more than 2.0; otherwise we get silly large estimates
494 * at the very start of a new TLS connection.
496 if (overhead > 2.0)
497 overhead = 2.0;
500 log_debug(LD_CHANNEL,
501 "Estimated overhead ratio for TLS chan " U64_FORMAT " is %f",
502 U64_PRINTF_ARG(chan->global_identifier), overhead);
504 return overhead;
508 * Get the remote address of a channel_tls_t
510 * This implements the get_remote_addr method for channel_tls_t; copy the
511 * remote endpoint of the channel to addr_out and return 1 (always
512 * succeeds for this transport).
515 static int
516 channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out)
518 int rv = 0;
519 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
521 tor_assert(tlschan);
522 tor_assert(addr_out);
524 if (tlschan->conn) {
525 tor_addr_copy(addr_out, &(tlschan->conn->real_addr));
526 rv = 1;
527 } else tor_addr_make_unspec(addr_out);
529 return rv;
533 * Get the name of the pluggable transport used by a channel_tls_t.
535 * This implements the get_transport_name for channel_tls_t. If the
536 * channel uses a pluggable transport, copy its name to
537 * <b>transport_out</b> and return 0. If the channel did not use a
538 * pluggable transport, return -1. */
540 static int
541 channel_tls_get_transport_name_method(channel_t *chan, char **transport_out)
543 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
545 tor_assert(tlschan);
546 tor_assert(transport_out);
547 tor_assert(tlschan->conn);
549 if (!tlschan->conn->ext_or_transport)
550 return -1;
552 *transport_out = tor_strdup(tlschan->conn->ext_or_transport);
553 return 0;
557 * Get endpoint description of a channel_tls_t
559 * This implements the get_remote_descr method for channel_tls_t; it returns
560 * a text description of the remote endpoint of the channel suitable for use
561 * in log messages. The req parameter is 0 for the canonical address or 1 for
562 * the actual address seen.
565 static const char *
566 channel_tls_get_remote_descr_method(channel_t *chan, int flags)
568 #define MAX_DESCR_LEN 32
570 static char buf[MAX_DESCR_LEN + 1];
571 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
572 connection_t *conn;
573 const char *answer = NULL;
574 char *addr_str;
576 tor_assert(tlschan);
578 if (tlschan->conn) {
579 conn = TO_CONN(tlschan->conn);
580 switch (flags) {
581 case 0:
582 /* Canonical address with port*/
583 tor_snprintf(buf, MAX_DESCR_LEN + 1,
584 "%s:%u", conn->address, conn->port);
585 answer = buf;
586 break;
587 case GRD_FLAG_ORIGINAL:
588 /* Actual address with port */
589 addr_str = tor_addr_to_str_dup(&(tlschan->conn->real_addr));
590 tor_snprintf(buf, MAX_DESCR_LEN + 1,
591 "%s:%u", addr_str, conn->port);
592 tor_free(addr_str);
593 answer = buf;
594 break;
595 case GRD_FLAG_ADDR_ONLY:
596 /* Canonical address, no port */
597 strlcpy(buf, conn->address, sizeof(buf));
598 answer = buf;
599 break;
600 case GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY:
601 /* Actual address, no port */
602 addr_str = tor_addr_to_str_dup(&(tlschan->conn->real_addr));
603 strlcpy(buf, addr_str, sizeof(buf));
604 tor_free(addr_str);
605 answer = buf;
606 break;
607 default:
608 /* Something's broken in channel.c */
609 tor_assert_nonfatal_unreached_once();
611 } else {
612 strlcpy(buf, "(No connection)", sizeof(buf));
613 answer = buf;
616 return answer;
620 * Tell the upper layer if we have queued writes
622 * This implements the has_queued_writes method for channel_tls t_; it returns
623 * 1 iff we have queued writes on the outbuf of the underlying or_connection_t.
626 static int
627 channel_tls_has_queued_writes_method(channel_t *chan)
629 size_t outbuf_len;
630 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
632 tor_assert(tlschan);
633 if (!(tlschan->conn)) {
634 log_info(LD_CHANNEL,
635 "something called has_queued_writes on a tlschan "
636 "(%p with ID " U64_FORMAT " but no conn",
637 chan, U64_PRINTF_ARG(chan->global_identifier));
640 outbuf_len = (tlschan->conn != NULL) ?
641 connection_get_outbuf_len(TO_CONN(tlschan->conn)) :
644 return (outbuf_len > 0);
648 * Tell the upper layer if we're canonical
650 * This implements the is_canonical method for channel_tls_t; if req is zero,
651 * it returns whether this is a canonical channel, and if it is one it returns
652 * whether that can be relied upon.
655 static int
656 channel_tls_is_canonical_method(channel_t *chan, int req)
658 int answer = 0;
659 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
661 tor_assert(tlschan);
663 if (tlschan->conn) {
664 switch (req) {
665 case 0:
666 answer = tlschan->conn->is_canonical;
667 break;
668 case 1:
670 * Is the is_canonical bit reliable? In protocols version 2 and up
671 * we get the canonical address from a NETINFO cell, but in older
672 * versions it might be based on an obsolete descriptor.
674 answer = (tlschan->conn->link_proto >= 2);
675 break;
676 default:
677 /* This shouldn't happen; channel.c is broken if it does */
678 tor_assert_nonfatal_unreached_once();
681 /* else return 0 for tlschan->conn == NULL */
683 return answer;
687 * Check if we match an extend_info_t
689 * This implements the matches_extend_info method for channel_tls_t; the upper
690 * layer wants to know if this channel matches an extend_info_t.
693 static int
694 channel_tls_matches_extend_info_method(channel_t *chan,
695 extend_info_t *extend_info)
697 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
699 tor_assert(tlschan);
700 tor_assert(extend_info);
702 /* Never match if we have no conn */
703 if (!(tlschan->conn)) {
704 log_info(LD_CHANNEL,
705 "something called matches_extend_info on a tlschan "
706 "(%p with ID " U64_FORMAT " but no conn",
707 chan, U64_PRINTF_ARG(chan->global_identifier));
708 return 0;
711 return (tor_addr_eq(&(extend_info->addr),
712 &(TO_CONN(tlschan->conn)->addr)) &&
713 (extend_info->port == TO_CONN(tlschan->conn)->port));
717 * Check if we match a target address; return true iff we do.
719 * This implements the matches_target method for channel_tls t_; the upper
720 * layer wants to know if this channel matches a target address when extending
721 * a circuit.
724 static int
725 channel_tls_matches_target_method(channel_t *chan,
726 const tor_addr_t *target)
728 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
730 tor_assert(tlschan);
731 tor_assert(target);
733 /* Never match if we have no conn */
734 if (!(tlschan->conn)) {
735 log_info(LD_CHANNEL,
736 "something called matches_target on a tlschan "
737 "(%p with ID " U64_FORMAT " but no conn",
738 chan, U64_PRINTF_ARG(chan->global_identifier));
739 return 0;
742 /* real_addr is the address this connection came from.
743 * base_.addr is updated by connection_or_init_conn_from_address()
744 * to be the address in the descriptor. It may be tempting to
745 * allow either address to be allowed, but if we did so, it would
746 * enable someone who steals a relay's keys to impersonate/MITM it
747 * from anywhere on the Internet! (Because they could make long-lived
748 * TLS connections from anywhere to all relays, and wait for them to
749 * be used for extends).
751 return tor_addr_eq(&(tlschan->conn->real_addr), target);
755 * Tell the upper layer how many bytes we have queued and not yet
756 * sent.
759 static size_t
760 channel_tls_num_bytes_queued_method(channel_t *chan)
762 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
764 tor_assert(tlschan);
765 tor_assert(tlschan->conn);
767 return connection_get_outbuf_len(TO_CONN(tlschan->conn));
771 * Tell the upper layer how many cells we can accept to write
773 * This implements the num_cells_writeable method for channel_tls_t; it
774 * returns an estimate of the number of cells we can accept with
775 * channel_tls_write_*_cell().
778 static int
779 channel_tls_num_cells_writeable_method(channel_t *chan)
781 size_t outbuf_len;
782 ssize_t n;
783 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
784 size_t cell_network_size;
786 tor_assert(tlschan);
787 tor_assert(tlschan->conn);
789 cell_network_size = get_cell_network_size(tlschan->conn->wide_circ_ids);
790 outbuf_len = connection_get_outbuf_len(TO_CONN(tlschan->conn));
791 /* Get the number of cells */
792 n = CEIL_DIV(OR_CONN_HIGHWATER - outbuf_len, cell_network_size);
793 if (n < 0) n = 0;
794 #if SIZEOF_SIZE_T > SIZEOF_INT
795 if (n > INT_MAX) n = INT_MAX;
796 #endif
798 return (int)n;
802 * Write a cell to a channel_tls_t
804 * This implements the write_cell method for channel_tls_t; given a
805 * channel_tls_t and a cell_t, transmit the cell_t.
808 static int
809 channel_tls_write_cell_method(channel_t *chan, cell_t *cell)
811 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
812 int written = 0;
814 tor_assert(tlschan);
815 tor_assert(cell);
817 if (tlschan->conn) {
818 connection_or_write_cell_to_buf(cell, tlschan->conn);
819 ++written;
820 } else {
821 log_info(LD_CHANNEL,
822 "something called write_cell on a tlschan "
823 "(%p with ID " U64_FORMAT " but no conn",
824 chan, U64_PRINTF_ARG(chan->global_identifier));
827 return written;
831 * Write a packed cell to a channel_tls_t
833 * This implements the write_packed_cell method for channel_tls_t; given a
834 * channel_tls_t and a packed_cell_t, transmit the packed_cell_t.
836 * Return 0 on success or negative value on error. The caller must free the
837 * packed cell.
840 static int
841 channel_tls_write_packed_cell_method(channel_t *chan,
842 packed_cell_t *packed_cell)
844 tor_assert(chan);
845 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
846 size_t cell_network_size = get_cell_network_size(chan->wide_circ_ids);
848 tor_assert(tlschan);
849 tor_assert(packed_cell);
851 if (tlschan->conn) {
852 connection_buf_add(packed_cell->body, cell_network_size,
853 TO_CONN(tlschan->conn));
854 } else {
855 log_info(LD_CHANNEL,
856 "something called write_packed_cell on a tlschan "
857 "(%p with ID " U64_FORMAT " but no conn",
858 chan, U64_PRINTF_ARG(chan->global_identifier));
859 return -1;
862 return 0;
866 * Write a variable-length cell to a channel_tls_t
868 * This implements the write_var_cell method for channel_tls_t; given a
869 * channel_tls_t and a var_cell_t, transmit the var_cell_t.
872 static int
873 channel_tls_write_var_cell_method(channel_t *chan, var_cell_t *var_cell)
875 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
876 int written = 0;
878 tor_assert(tlschan);
879 tor_assert(var_cell);
881 if (tlschan->conn) {
882 connection_or_write_var_cell_to_buf(var_cell, tlschan->conn);
883 ++written;
884 } else {
885 log_info(LD_CHANNEL,
886 "something called write_var_cell on a tlschan "
887 "(%p with ID " U64_FORMAT " but no conn",
888 chan, U64_PRINTF_ARG(chan->global_identifier));
891 return written;
894 /*************************************************
895 * Method implementations for channel_listener_t *
896 ************************************************/
899 * Close a channel_listener_t
901 * 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.
945 static const char *
946 channel_tls_listener_describe_transport_method(channel_listener_t *chan_l)
948 tor_assert(chan_l);
950 return "TLS channel (listening)";
953 /*******************************************************
954 * Functions for handling events on an or_connection_t *
955 ******************************************************/
958 * Handle an orconn state change
960 * This function will be called by connection_or.c when the or_connection_t
961 * associated with this channel_tls_t changes state.
964 void
965 channel_tls_handle_state_change_on_orconn(channel_tls_t *chan,
966 or_connection_t *conn,
967 uint8_t old_state,
968 uint8_t state)
970 channel_t *base_chan;
972 tor_assert(chan);
973 tor_assert(conn);
974 tor_assert(conn->chan == chan);
975 tor_assert(chan->conn == conn);
976 /* Shut the compiler up without triggering -Wtautological-compare */
977 (void)old_state;
979 base_chan = TLS_CHAN_TO_BASE(chan);
981 /* Make sure the base connection state makes sense - shouldn't be error
982 * or closed. */
984 tor_assert(CHANNEL_IS_OPENING(base_chan) ||
985 CHANNEL_IS_OPEN(base_chan) ||
986 CHANNEL_IS_MAINT(base_chan) ||
987 CHANNEL_IS_CLOSING(base_chan));
989 /* Did we just go to state open? */
990 if (state == OR_CONN_STATE_OPEN) {
992 * We can go to CHANNEL_STATE_OPEN from CHANNEL_STATE_OPENING or
993 * CHANNEL_STATE_MAINT on this.
995 channel_change_state_open(base_chan);
996 /* We might have just become writeable; check and tell the scheduler */
997 if (connection_or_num_cells_writeable(conn) > 0) {
998 scheduler_channel_wants_writes(base_chan);
1000 } else {
1002 * Not open, so from CHANNEL_STATE_OPEN we go to CHANNEL_STATE_MAINT,
1003 * otherwise no change.
1005 if (CHANNEL_IS_OPEN(base_chan)) {
1006 channel_change_state(base_chan, CHANNEL_STATE_MAINT);
1011 #ifdef KEEP_TIMING_STATS
1014 * Timing states wrapper
1016 * This is a wrapper function around the actual function that processes the
1017 * <b>cell</b> that just arrived on <b>chan</b>. Increment <b>*time</b>
1018 * by the number of microseconds used by the call to <b>*func(cell, chan)</b>.
1021 static void
1022 channel_tls_time_process_cell(cell_t *cell, channel_tls_t *chan, int *time,
1023 void (*func)(cell_t *, channel_tls_t *))
1025 struct timeval start, end;
1026 long time_passed;
1028 tor_gettimeofday(&start);
1030 (*func)(cell, chan);
1032 tor_gettimeofday(&end);
1033 time_passed = tv_udiff(&start, &end) ;
1035 if (time_passed > 10000) { /* more than 10ms */
1036 log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
1039 if (time_passed < 0) {
1040 log_info(LD_GENERAL,"That call took us back in time!");
1041 time_passed = 0;
1044 *time += time_passed;
1046 #endif /* defined(KEEP_TIMING_STATS) */
1049 * Handle an incoming cell on a channel_tls_t
1051 * This is called from connection_or.c to handle an arriving cell; it checks
1052 * for cell types specific to the handshake for this transport protocol and
1053 * handles them, and queues all other cells to the channel_t layer, which
1054 * eventually will hand them off to command.c.
1056 * The channel layer itself decides whether the cell should be queued or
1057 * can be handed off immediately to the upper-layer code. It is responsible
1058 * for copying in the case that it queues; we merely pass pointers through
1059 * which we get from connection_or_process_cells_from_inbuf().
1062 void
1063 channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
1065 channel_tls_t *chan;
1066 int handshaking;
1068 #ifdef KEEP_TIMING_STATS
1069 #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
1070 ++num ## tp; \
1071 channel_tls_time_process_cell(cl, cn, & tp ## time , \
1072 channel_tls_process_ ## tp ## _cell); \
1073 } STMT_END
1074 #else /* !(defined(KEEP_TIMING_STATS)) */
1075 #define PROCESS_CELL(tp, cl, cn) channel_tls_process_ ## tp ## _cell(cl, cn)
1076 #endif /* defined(KEEP_TIMING_STATS) */
1078 tor_assert(cell);
1079 tor_assert(conn);
1081 chan = conn->chan;
1083 if (!chan) {
1084 log_warn(LD_CHANNEL,
1085 "Got a cell_t on an OR connection with no channel");
1086 return;
1089 handshaking = (TO_CONN(conn)->state != OR_CONN_STATE_OPEN);
1091 if (conn->base_.marked_for_close)
1092 return;
1094 /* Reject all but VERSIONS and NETINFO when handshaking. */
1095 /* (VERSIONS should actually be impossible; it's variable-length.) */
1096 if (handshaking && cell->command != CELL_VERSIONS &&
1097 cell->command != CELL_NETINFO) {
1098 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1099 "Received unexpected cell command %d in chan state %s / "
1100 "conn state %s; closing the connection.",
1101 (int)cell->command,
1102 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1103 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state));
1104 connection_or_close_for_error(conn, 0);
1105 return;
1108 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
1109 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 1);
1111 /* We note that we're on the internet whenever we read a cell. This is
1112 * a fast operation. */
1113 entry_guards_note_internet_connectivity(get_guard_selection_info());
1114 rep_hist_padding_count_read(PADDING_TYPE_TOTAL);
1116 if (TLS_CHAN_TO_BASE(chan)->currently_padding)
1117 rep_hist_padding_count_read(PADDING_TYPE_ENABLED_TOTAL);
1119 switch (cell->command) {
1120 case CELL_PADDING:
1121 rep_hist_padding_count_read(PADDING_TYPE_CELL);
1122 if (TLS_CHAN_TO_BASE(chan)->currently_padding)
1123 rep_hist_padding_count_read(PADDING_TYPE_ENABLED_CELL);
1124 ++stats_n_padding_cells_processed;
1125 /* do nothing */
1126 break;
1127 case CELL_VERSIONS:
1128 tor_fragile_assert();
1129 break;
1130 case CELL_NETINFO:
1131 ++stats_n_netinfo_cells_processed;
1132 PROCESS_CELL(netinfo, cell, chan);
1133 break;
1134 case CELL_PADDING_NEGOTIATE:
1135 ++stats_n_netinfo_cells_processed;
1136 PROCESS_CELL(padding_negotiate, cell, chan);
1137 break;
1138 case CELL_CREATE:
1139 case CELL_CREATE_FAST:
1140 case CELL_CREATED:
1141 case CELL_CREATED_FAST:
1142 case CELL_RELAY:
1143 case CELL_RELAY_EARLY:
1144 case CELL_DESTROY:
1145 case CELL_CREATE2:
1146 case CELL_CREATED2:
1148 * These are all transport independent and we pass them up through the
1149 * channel_t mechanism. They are ultimately handled in command.c.
1151 channel_process_cell(TLS_CHAN_TO_BASE(chan), cell);
1152 break;
1153 default:
1154 log_fn(LOG_INFO, LD_PROTOCOL,
1155 "Cell of unknown type (%d) received in channeltls.c. "
1156 "Dropping.",
1157 cell->command);
1158 break;
1163 * Handle an incoming variable-length cell on a channel_tls_t
1165 * Process a <b>var_cell</b> that was just received on <b>conn</b>. Keep
1166 * internal statistics about how many of each cell we've processed so far
1167 * this second, and the total number of microseconds it took to
1168 * process each type of cell. All the var_cell commands are handshake-
1169 * related and live below the channel_t layer, so no variable-length
1170 * cells ever get delivered in the current implementation, but I've left
1171 * the mechanism in place for future use.
1173 * If we were handing them off to the upper layer, the channel_t queueing
1174 * code would be responsible for memory management, and we'd just be passing
1175 * pointers through from connection_or_process_cells_from_inbuf(). That
1176 * caller always frees them after this function returns, so this function
1177 * should never free var_cell.
1180 void
1181 channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
1183 channel_tls_t *chan;
1185 #ifdef KEEP_TIMING_STATS
1186 /* how many of each cell have we seen so far this second? needs better
1187 * name. */
1188 static int num_versions = 0, num_certs = 0;
1189 static time_t current_second = 0; /* from previous calls to time */
1190 time_t now = time(NULL);
1192 if (current_second == 0) current_second = now;
1193 if (now > current_second) { /* the second has rolled over */
1194 /* print stats */
1195 log_info(LD_OR,
1196 "At end of second: %d versions (%d ms), %d certs (%d ms)",
1197 num_versions, versions_time / ((now - current_second) * 1000),
1198 num_certs, certs_time / ((now - current_second) * 1000));
1200 num_versions = num_certs = 0;
1201 versions_time = certs_time = 0;
1203 /* remember which second it is, for next time */
1204 current_second = now;
1206 #endif /* defined(KEEP_TIMING_STATS) */
1208 tor_assert(var_cell);
1209 tor_assert(conn);
1211 chan = conn->chan;
1213 if (!chan) {
1214 log_warn(LD_CHANNEL,
1215 "Got a var_cell_t on an OR connection with no channel");
1216 return;
1219 if (TO_CONN(conn)->marked_for_close)
1220 return;
1222 switch (TO_CONN(conn)->state) {
1223 case OR_CONN_STATE_OR_HANDSHAKING_V2:
1224 if (var_cell->command != CELL_VERSIONS) {
1225 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1226 "Received a cell with command %d in unexpected "
1227 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1228 "closing the connection.",
1229 (int)(var_cell->command),
1230 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1231 TO_CONN(conn)->state,
1232 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1233 (int)(TLS_CHAN_TO_BASE(chan)->state));
1235 * The code in connection_or.c will tell channel_t to close for
1236 * error; it will go to CHANNEL_STATE_CLOSING, and then to
1237 * CHANNEL_STATE_ERROR when conn is closed.
1239 connection_or_close_for_error(conn, 0);
1240 return;
1242 break;
1243 case OR_CONN_STATE_TLS_HANDSHAKING:
1244 /* If we're using bufferevents, it's entirely possible for us to
1245 * notice "hey, data arrived!" before we notice "hey, the handshake
1246 * finished!" And we need to be accepting both at once to handle both
1247 * the v2 and v3 handshakes. */
1248 /* But that should be happening any longer've disabled bufferevents. */
1249 tor_assert_nonfatal_unreached_once();
1251 /* fall through */
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;
1344 * Update channel marks after connection_or.c has changed an address
1346 * This is called from connection_or_init_conn_from_address() after the
1347 * connection's _base.addr or real_addr fields have potentially been changed
1348 * so we can recalculate the local mark. Notably, this happens when incoming
1349 * connections are reverse-proxied and we only learn the real address of the
1350 * remote router by looking it up in the consensus after we finish the
1351 * handshake and know an authenticated identity digest.
1354 void
1355 channel_tls_update_marks(or_connection_t *conn)
1357 channel_t *chan = NULL;
1359 tor_assert(conn);
1360 tor_assert(conn->chan);
1362 chan = TLS_CHAN_TO_BASE(conn->chan);
1364 if (is_local_addr(&(TO_CONN(conn)->addr))) {
1365 if (!channel_is_local(chan)) {
1366 log_debug(LD_CHANNEL,
1367 "Marking channel " U64_FORMAT " at %p as local",
1368 U64_PRINTF_ARG(chan->global_identifier), chan);
1369 channel_mark_local(chan);
1371 } else {
1372 if (channel_is_local(chan)) {
1373 log_debug(LD_CHANNEL,
1374 "Marking channel " U64_FORMAT " at %p as remote",
1375 U64_PRINTF_ARG(chan->global_identifier), chan);
1376 channel_mark_remote(chan);
1382 * Check if this cell type is allowed before the handshake is finished
1384 * Return true if <b>command</b> is a cell command that's allowed to start a
1385 * 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.)
1410 static int
1411 enter_v3_handshake_with_cell(var_cell_t *cell, channel_tls_t *chan)
1413 int started_here = 0;
1415 tor_assert(cell);
1416 tor_assert(chan);
1417 tor_assert(chan->conn);
1419 started_here = connection_or_nonopen_was_started_here(chan->conn);
1421 tor_assert(TO_CONN(chan->conn)->state == OR_CONN_STATE_TLS_HANDSHAKING ||
1422 TO_CONN(chan->conn)->state ==
1423 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1425 if (started_here) {
1426 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1427 "Received a cell while TLS-handshaking, not in "
1428 "OR_HANDSHAKING_V3, on a connection we originated.");
1430 connection_or_block_renegotiation(chan->conn);
1431 chan->conn->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
1432 if (connection_init_or_handshake_state(chan->conn, started_here) < 0) {
1433 connection_or_close_for_error(chan->conn, 0);
1434 return -1;
1436 or_handshake_state_record_var_cell(chan->conn,
1437 chan->conn->handshake_state, cell, 1);
1438 return 0;
1442 * Process a 'versions' cell.
1444 * This function is called to handle an incoming VERSIONS cell; the current
1445 * link protocol version must be 0 to indicate that no version has yet been
1446 * negotiated. We compare the versions in the cell to the list of versions
1447 * we support, pick the highest version we have in common, and continue the
1448 * negotiation from there.
1451 static void
1452 channel_tls_process_versions_cell(var_cell_t *cell, channel_tls_t *chan)
1454 int highest_supported_version = 0;
1455 int started_here = 0;
1457 tor_assert(cell);
1458 tor_assert(chan);
1459 tor_assert(chan->conn);
1461 if ((cell->payload_len % 2) == 1) {
1462 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1463 "Received a VERSION cell with odd payload length %d; "
1464 "closing connection.",cell->payload_len);
1465 connection_or_close_for_error(chan->conn, 0);
1466 return;
1469 started_here = connection_or_nonopen_was_started_here(chan->conn);
1471 if (chan->conn->link_proto != 0 ||
1472 (chan->conn->handshake_state &&
1473 chan->conn->handshake_state->received_versions)) {
1474 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1475 "Received a VERSIONS cell on a connection with its version "
1476 "already set to %d; dropping",
1477 (int)(chan->conn->link_proto));
1478 return;
1480 switch (chan->conn->base_.state)
1482 case OR_CONN_STATE_OR_HANDSHAKING_V2:
1483 case OR_CONN_STATE_OR_HANDSHAKING_V3:
1484 break;
1485 case OR_CONN_STATE_TLS_HANDSHAKING:
1486 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
1487 default:
1488 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1489 "VERSIONS cell while in unexpected state");
1490 return;
1493 tor_assert(chan->conn->handshake_state);
1496 int i;
1497 const uint8_t *cp = cell->payload;
1498 for (i = 0; i < cell->payload_len / 2; ++i, cp += 2) {
1499 uint16_t v = ntohs(get_uint16(cp));
1500 if (is_or_protocol_version_known(v) && v > highest_supported_version)
1501 highest_supported_version = v;
1504 if (!highest_supported_version) {
1505 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1506 "Couldn't find a version in common between my version list and the "
1507 "list in the VERSIONS cell; closing connection.");
1508 connection_or_close_for_error(chan->conn, 0);
1509 return;
1510 } else if (highest_supported_version == 1) {
1511 /* Negotiating version 1 makes no sense, since version 1 has no VERSIONS
1512 * cells. */
1513 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1514 "Used version negotiation protocol to negotiate a v1 connection. "
1515 "That's crazily non-compliant. Closing connection.");
1516 connection_or_close_for_error(chan->conn, 0);
1517 return;
1518 } else if (highest_supported_version < 3 &&
1519 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1520 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1521 "Negotiated link protocol 2 or lower after doing a v3 TLS "
1522 "handshake. Closing connection.");
1523 connection_or_close_for_error(chan->conn, 0);
1524 return;
1525 } else if (highest_supported_version != 2 &&
1526 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V2) {
1527 /* XXXX This should eventually be a log_protocol_warn */
1528 log_fn(LOG_WARN, LD_OR,
1529 "Negotiated link with non-2 protocol after doing a v2 TLS "
1530 "handshake with %s. Closing connection.",
1531 fmt_addr(&chan->conn->base_.addr));
1532 connection_or_close_for_error(chan->conn, 0);
1533 return;
1536 rep_hist_note_negotiated_link_proto(highest_supported_version, started_here);
1538 chan->conn->link_proto = highest_supported_version;
1539 chan->conn->handshake_state->received_versions = 1;
1541 if (chan->conn->link_proto == 2) {
1542 log_info(LD_OR,
1543 "Negotiated version %d with %s:%d; sending NETINFO.",
1544 highest_supported_version,
1545 safe_str_client(chan->conn->base_.address),
1546 chan->conn->base_.port);
1548 if (connection_or_send_netinfo(chan->conn) < 0) {
1549 connection_or_close_for_error(chan->conn, 0);
1550 return;
1552 } else {
1553 const int send_versions = !started_here;
1554 /* If we want to authenticate, send a CERTS cell */
1555 const int send_certs = !started_here || public_server_mode(get_options());
1556 /* If we're a host that got a connection, ask for authentication. */
1557 const int send_chall = !started_here;
1558 /* If our certs cell will authenticate us, we can send a netinfo cell
1559 * right now. */
1560 const int send_netinfo = !started_here;
1561 const int send_any =
1562 send_versions || send_certs || send_chall || send_netinfo;
1563 tor_assert(chan->conn->link_proto >= 3);
1565 log_info(LD_OR,
1566 "Negotiated version %d with %s:%d; %s%s%s%s%s",
1567 highest_supported_version,
1568 safe_str_client(chan->conn->base_.address),
1569 chan->conn->base_.port,
1570 send_any ? "Sending cells:" : "Waiting for CERTS cell",
1571 send_versions ? " VERSIONS" : "",
1572 send_certs ? " CERTS" : "",
1573 send_chall ? " AUTH_CHALLENGE" : "",
1574 send_netinfo ? " NETINFO" : "");
1576 #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
1577 if (1) {
1578 connection_or_close_normally(chan->conn, 1);
1579 return;
1581 #endif /* defined(DISABLE_V3_LINKPROTO_SERVERSIDE) */
1583 if (send_versions) {
1584 if (connection_or_send_versions(chan->conn, 1) < 0) {
1585 log_warn(LD_OR, "Couldn't send versions cell");
1586 connection_or_close_for_error(chan->conn, 0);
1587 return;
1591 /* We set this after sending the versions cell. */
1592 /*XXXXX symbolic const.*/
1593 TLS_CHAN_TO_BASE(chan)->wide_circ_ids =
1594 chan->conn->link_proto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
1595 chan->conn->wide_circ_ids = TLS_CHAN_TO_BASE(chan)->wide_circ_ids;
1597 TLS_CHAN_TO_BASE(chan)->padding_enabled =
1598 chan->conn->link_proto >= MIN_LINK_PROTO_FOR_CHANNEL_PADDING;
1600 if (send_certs) {
1601 if (connection_or_send_certs_cell(chan->conn) < 0) {
1602 log_warn(LD_OR, "Couldn't send certs cell");
1603 connection_or_close_for_error(chan->conn, 0);
1604 return;
1607 if (send_chall) {
1608 if (connection_or_send_auth_challenge_cell(chan->conn) < 0) {
1609 log_warn(LD_OR, "Couldn't send auth_challenge cell");
1610 connection_or_close_for_error(chan->conn, 0);
1611 return;
1614 if (send_netinfo) {
1615 if (connection_or_send_netinfo(chan->conn) < 0) {
1616 log_warn(LD_OR, "Couldn't send netinfo cell");
1617 connection_or_close_for_error(chan->conn, 0);
1618 return;
1625 * Process a 'padding_negotiate' cell
1627 * This function is called to handle an incoming PADDING_NEGOTIATE cell;
1628 * enable or disable padding accordingly, and read and act on its timeout
1629 * value contents.
1631 static void
1632 channel_tls_process_padding_negotiate_cell(cell_t *cell, channel_tls_t *chan)
1634 channelpadding_negotiate_t *negotiation;
1635 tor_assert(cell);
1636 tor_assert(chan);
1637 tor_assert(chan->conn);
1639 if (chan->conn->link_proto < MIN_LINK_PROTO_FOR_CHANNEL_PADDING) {
1640 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1641 "Received a PADDING_NEGOTIATE cell on v%d connection; dropping.",
1642 chan->conn->link_proto);
1643 return;
1646 if (channelpadding_negotiate_parse(&negotiation, cell->payload,
1647 CELL_PAYLOAD_SIZE) < 0) {
1648 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1649 "Received malformed PADDING_NEGOTIATE cell on v%d connection; "
1650 "dropping.", chan->conn->link_proto);
1652 return;
1655 channelpadding_update_padding_for_channel(TLS_CHAN_TO_BASE(chan),
1656 negotiation);
1658 channelpadding_negotiate_free(negotiation);
1662 * Process a 'netinfo' cell
1664 * This function is called to handle an incoming NETINFO cell; read and act
1665 * on its contents, and set the connection state to "open".
1668 static void
1669 channel_tls_process_netinfo_cell(cell_t *cell, channel_tls_t *chan)
1671 time_t timestamp;
1672 uint8_t my_addr_type;
1673 uint8_t my_addr_len;
1674 const uint8_t *my_addr_ptr;
1675 const uint8_t *cp, *end;
1676 uint8_t n_other_addrs;
1677 time_t now = time(NULL);
1678 const routerinfo_t *me = router_get_my_routerinfo();
1680 long apparent_skew = 0;
1681 tor_addr_t my_apparent_addr = TOR_ADDR_NULL;
1682 int started_here = 0;
1683 const char *identity_digest = NULL;
1685 tor_assert(cell);
1686 tor_assert(chan);
1687 tor_assert(chan->conn);
1689 if (chan->conn->link_proto < 2) {
1690 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1691 "Received a NETINFO cell on %s connection; dropping.",
1692 chan->conn->link_proto == 0 ? "non-versioned" : "a v1");
1693 return;
1695 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
1696 chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
1697 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1698 "Received a NETINFO cell on non-handshaking connection; dropping.");
1699 return;
1701 tor_assert(chan->conn->handshake_state &&
1702 chan->conn->handshake_state->received_versions);
1703 started_here = connection_or_nonopen_was_started_here(chan->conn);
1704 identity_digest = chan->conn->identity_digest;
1706 if (chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1707 tor_assert(chan->conn->link_proto >= 3);
1708 if (started_here) {
1709 if (!(chan->conn->handshake_state->authenticated)) {
1710 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1711 "Got a NETINFO cell from server, "
1712 "but no authentication. Closing the connection.");
1713 connection_or_close_for_error(chan->conn, 0);
1714 return;
1716 } else {
1717 /* we're the server. If the client never authenticated, we have
1718 some housekeeping to do.*/
1719 if (!(chan->conn->handshake_state->authenticated)) {
1720 tor_assert(tor_digest_is_zero(
1721 (const char*)(chan->conn->handshake_state->
1722 authenticated_rsa_peer_id)));
1723 tor_assert(tor_mem_is_zero(
1724 (const char*)(chan->conn->handshake_state->
1725 authenticated_ed25519_peer_id.pubkey), 32));
1726 /* If the client never authenticated, it's a tor client or bridge
1727 * relay, and we must not use it for EXTEND requests (nor could we, as
1728 * there are no authenticated peer IDs) */
1729 channel_mark_client(TLS_CHAN_TO_BASE(chan));
1730 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), NULL,
1731 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
1733 connection_or_init_conn_from_address(chan->conn,
1734 &(chan->conn->base_.addr),
1735 chan->conn->base_.port,
1736 /* zero, checked above */
1737 (const char*)(chan->conn->handshake_state->
1738 authenticated_rsa_peer_id),
1739 NULL, /* Ed25519 ID: Also checked as zero */
1745 /* Decode the cell. */
1746 timestamp = ntohl(get_uint32(cell->payload));
1747 if (labs(now - chan->conn->handshake_state->sent_versions_at) < 180) {
1748 apparent_skew = now - timestamp;
1751 my_addr_type = (uint8_t) cell->payload[4];
1752 my_addr_len = (uint8_t) cell->payload[5];
1753 my_addr_ptr = (uint8_t*) cell->payload + 6;
1754 end = cell->payload + CELL_PAYLOAD_SIZE;
1755 cp = cell->payload + 6 + my_addr_len;
1757 /* We used to check:
1758 * if (my_addr_len >= CELL_PAYLOAD_SIZE - 6) {
1760 * This is actually never going to happen, since my_addr_len is at most 255,
1761 * and CELL_PAYLOAD_LEN - 6 is 503. So we know that cp is < end. */
1763 if (my_addr_type == RESOLVED_TYPE_IPV4 && my_addr_len == 4) {
1764 tor_addr_from_ipv4n(&my_apparent_addr, get_uint32(my_addr_ptr));
1766 if (!get_options()->BridgeRelay && me &&
1767 get_uint32(my_addr_ptr) == htonl(me->addr)) {
1768 TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
1771 } else if (my_addr_type == RESOLVED_TYPE_IPV6 && my_addr_len == 16) {
1772 tor_addr_from_ipv6_bytes(&my_apparent_addr, (const char *) my_addr_ptr);
1774 if (!get_options()->BridgeRelay && me &&
1775 !tor_addr_is_null(&me->ipv6_addr) &&
1776 tor_addr_eq(&my_apparent_addr, &me->ipv6_addr)) {
1777 TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
1781 n_other_addrs = (uint8_t) *cp++;
1782 while (n_other_addrs && cp < end-2) {
1783 /* Consider all the other addresses; if any matches, this connection is
1784 * "canonical." */
1785 tor_addr_t addr;
1786 const uint8_t *next =
1787 decode_address_from_payload(&addr, cp, (int)(end-cp));
1788 if (next == NULL) {
1789 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1790 "Bad address in netinfo cell; closing connection.");
1791 connection_or_close_for_error(chan->conn, 0);
1792 return;
1794 /* A relay can connect from anywhere and be canonical, so
1795 * long as it tells you from where it came. This may sound a bit
1796 * concerning... but that's what "canonical" means: that the
1797 * address is one that the relay itself has claimed. The relay
1798 * might be doing something funny, but nobody else is doing a MITM
1799 * on the relay's TCP.
1801 if (tor_addr_eq(&addr, &(chan->conn->real_addr))) {
1802 connection_or_set_canonical(chan->conn, 1);
1803 break;
1805 cp = next;
1806 --n_other_addrs;
1809 if (me && !TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer &&
1810 channel_is_canonical(TLS_CHAN_TO_BASE(chan))) {
1811 const char *descr =
1812 TLS_CHAN_TO_BASE(chan)->get_remote_descr(TLS_CHAN_TO_BASE(chan), 0);
1813 log_info(LD_OR,
1814 "We made a connection to a relay at %s (fp=%s) but we think "
1815 "they will not consider this connection canonical. They "
1816 "think we are at %s, but we think its %s.",
1817 safe_str(descr),
1818 safe_str(hex_str(identity_digest, DIGEST_LEN)),
1819 safe_str(tor_addr_is_null(&my_apparent_addr) ?
1820 "<none>" : fmt_and_decorate_addr(&my_apparent_addr)),
1821 safe_str(fmt_addr32(me->addr)));
1824 /* Act on apparent skew. */
1825 /** Warn when we get a netinfo skew with at least this value. */
1826 #define NETINFO_NOTICE_SKEW 3600
1827 if (labs(apparent_skew) > NETINFO_NOTICE_SKEW &&
1828 (started_here ||
1829 connection_or_digest_is_known_relay(chan->conn->identity_digest))) {
1830 int trusted = router_digest_is_trusted_dir(chan->conn->identity_digest);
1831 clock_skew_warning(TO_CONN(chan->conn), apparent_skew, trusted, LD_GENERAL,
1832 "NETINFO cell", "OR");
1835 /* XXX maybe act on my_apparent_addr, if the source is sufficiently
1836 * trustworthy. */
1838 if (! chan->conn->handshake_state->sent_netinfo) {
1839 /* If we were prepared to authenticate, but we never got an AUTH_CHALLENGE
1840 * cell, then we would not previously have sent a NETINFO cell. Do so
1841 * now. */
1842 if (connection_or_send_netinfo(chan->conn) < 0) {
1843 connection_or_close_for_error(chan->conn, 0);
1844 return;
1848 if (connection_or_set_state_open(chan->conn) < 0) {
1849 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1850 "Got good NETINFO cell from %s:%d; but "
1851 "was unable to make the OR connection become open.",
1852 safe_str_client(chan->conn->base_.address),
1853 chan->conn->base_.port);
1854 connection_or_close_for_error(chan->conn, 0);
1855 } else {
1856 log_info(LD_OR,
1857 "Got good NETINFO cell from %s:%d; OR connection is now "
1858 "open, using protocol version %d. Its ID digest is %s. "
1859 "Our address is apparently %s.",
1860 safe_str_client(chan->conn->base_.address),
1861 chan->conn->base_.port,
1862 (int)(chan->conn->link_proto),
1863 hex_str(identity_digest, DIGEST_LEN),
1864 tor_addr_is_null(&my_apparent_addr) ?
1865 "<none>" : fmt_and_decorate_addr(&my_apparent_addr));
1867 assert_connection_ok(TO_CONN(chan->conn),time(NULL));
1870 /** Types of certificates that we know how to parse from CERTS cells. Each
1871 * type corresponds to a different encoding format. */
1872 typedef enum cert_encoding_t {
1873 CERT_ENCODING_UNKNOWN, /**< We don't recognize this. */
1874 CERT_ENCODING_X509, /**< It's an RSA key, signed with RSA, encoded in x509.
1875 * (Actually, it might not be RSA. We test that later.) */
1876 CERT_ENCODING_ED25519, /**< It's something signed with an Ed25519 key,
1877 * encoded asa a tor_cert_t.*/
1878 CERT_ENCODING_RSA_CROSSCERT, /**< It's an Ed key signed with an RSA key. */
1879 } cert_encoding_t;
1882 * Given one of the certificate type codes used in a CERTS cell,
1883 * return the corresponding cert_encoding_t that we should use to parse
1884 * the certificate.
1886 static cert_encoding_t
1887 certs_cell_typenum_to_cert_type(int typenum)
1889 switch (typenum) {
1890 case CERTTYPE_RSA1024_ID_LINK:
1891 case CERTTYPE_RSA1024_ID_ID:
1892 case CERTTYPE_RSA1024_ID_AUTH:
1893 return CERT_ENCODING_X509;
1894 case CERTTYPE_ED_ID_SIGN:
1895 case CERTTYPE_ED_SIGN_LINK:
1896 case CERTTYPE_ED_SIGN_AUTH:
1897 return CERT_ENCODING_ED25519;
1898 case CERTTYPE_RSA1024_ID_EDID:
1899 return CERT_ENCODING_RSA_CROSSCERT;
1900 default:
1901 return CERT_ENCODING_UNKNOWN;
1906 * Process a CERTS cell from a channel.
1908 * This function is called to process an incoming CERTS cell on a
1909 * channel_tls_t:
1911 * If the other side should not have sent us a CERTS cell, or the cell is
1912 * malformed, or it is supposed to authenticate the TLS key but it doesn't,
1913 * then mark the connection.
1915 * If the cell has a good cert chain and we're doing a v3 handshake, then
1916 * store the certificates in or_handshake_state. If this is the client side
1917 * of the connection, we then authenticate the server or mark the connection.
1918 * If it's the server side, wait for an AUTHENTICATE cell.
1920 STATIC void
1921 channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
1923 #define MAX_CERT_TYPE_WANTED CERTTYPE_RSA1024_ID_EDID
1924 /* These arrays will be sparse, since a cert type can be at most one
1925 * of ed/x509 */
1926 tor_x509_cert_t *x509_certs[MAX_CERT_TYPE_WANTED + 1];
1927 tor_cert_t *ed_certs[MAX_CERT_TYPE_WANTED + 1];
1928 uint8_t *rsa_ed_cc_cert = NULL;
1929 size_t rsa_ed_cc_cert_len = 0;
1931 int n_certs, i;
1932 certs_cell_t *cc = NULL;
1934 int send_netinfo = 0, started_here = 0;
1936 memset(x509_certs, 0, sizeof(x509_certs));
1937 memset(ed_certs, 0, sizeof(ed_certs));
1938 tor_assert(cell);
1939 tor_assert(chan);
1940 tor_assert(chan->conn);
1942 #define ERR(s) \
1943 do { \
1944 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
1945 "Received a bad CERTS cell from %s:%d: %s", \
1946 safe_str(chan->conn->base_.address), \
1947 chan->conn->base_.port, (s)); \
1948 connection_or_close_for_error(chan->conn, 0); \
1949 goto err; \
1950 } while (0)
1952 /* Can't use connection_or_nonopen_was_started_here(); its conn->tls
1953 * check looks like it breaks
1954 * test_link_handshake_recv_certs_ok_server(). */
1955 started_here = chan->conn->handshake_state->started_here;
1957 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
1958 ERR("We're not doing a v3 handshake!");
1959 if (chan->conn->link_proto < 3)
1960 ERR("We're not using link protocol >= 3");
1961 if (chan->conn->handshake_state->received_certs_cell)
1962 ERR("We already got one");
1963 if (chan->conn->handshake_state->authenticated) {
1964 /* Should be unreachable, but let's make sure. */
1965 ERR("We're already authenticated!");
1967 if (cell->payload_len < 1)
1968 ERR("It had no body");
1969 if (cell->circ_id)
1970 ERR("It had a nonzero circuit ID");
1972 if (certs_cell_parse(&cc, cell->payload, cell->payload_len) < 0)
1973 ERR("It couldn't be parsed.");
1975 n_certs = cc->n_certs;
1977 for (i = 0; i < n_certs; ++i) {
1978 certs_cell_cert_t *c = certs_cell_get_certs(cc, i);
1980 uint16_t cert_type = c->cert_type;
1981 uint16_t cert_len = c->cert_len;
1982 uint8_t *cert_body = certs_cell_cert_getarray_body(c);
1984 if (cert_type > MAX_CERT_TYPE_WANTED)
1985 continue;
1986 const cert_encoding_t ct = certs_cell_typenum_to_cert_type(cert_type);
1987 switch (ct) {
1988 default:
1989 case CERT_ENCODING_UNKNOWN:
1990 break;
1991 case CERT_ENCODING_X509: {
1992 tor_x509_cert_t *x509_cert = tor_x509_cert_decode(cert_body, cert_len);
1993 if (!x509_cert) {
1994 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1995 "Received undecodable certificate in CERTS cell from %s:%d",
1996 safe_str(chan->conn->base_.address),
1997 chan->conn->base_.port);
1998 } else {
1999 if (x509_certs[cert_type]) {
2000 tor_x509_cert_free(x509_cert);
2001 ERR("Duplicate x509 certificate");
2002 } else {
2003 x509_certs[cert_type] = x509_cert;
2006 break;
2008 case CERT_ENCODING_ED25519: {
2009 tor_cert_t *ed_cert = tor_cert_parse(cert_body, cert_len);
2010 if (!ed_cert) {
2011 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2012 "Received undecodable Ed certificate "
2013 "in CERTS cell from %s:%d",
2014 safe_str(chan->conn->base_.address),
2015 chan->conn->base_.port);
2016 } else {
2017 if (ed_certs[cert_type]) {
2018 tor_cert_free(ed_cert);
2019 ERR("Duplicate Ed25519 certificate");
2020 } else {
2021 ed_certs[cert_type] = ed_cert;
2024 break;
2027 case CERT_ENCODING_RSA_CROSSCERT: {
2028 if (rsa_ed_cc_cert) {
2029 ERR("Duplicate RSA->Ed25519 crosscert");
2030 } else {
2031 rsa_ed_cc_cert = tor_memdup(cert_body, cert_len);
2032 rsa_ed_cc_cert_len = cert_len;
2034 break;
2039 /* Move the certificates we (might) want into the handshake_state->certs
2040 * structure. */
2041 tor_x509_cert_t *id_cert = x509_certs[CERTTYPE_RSA1024_ID_ID];
2042 tor_x509_cert_t *auth_cert = x509_certs[CERTTYPE_RSA1024_ID_AUTH];
2043 tor_x509_cert_t *link_cert = x509_certs[CERTTYPE_RSA1024_ID_LINK];
2044 chan->conn->handshake_state->certs->auth_cert = auth_cert;
2045 chan->conn->handshake_state->certs->link_cert = link_cert;
2046 chan->conn->handshake_state->certs->id_cert = id_cert;
2047 x509_certs[CERTTYPE_RSA1024_ID_ID] =
2048 x509_certs[CERTTYPE_RSA1024_ID_AUTH] =
2049 x509_certs[CERTTYPE_RSA1024_ID_LINK] = NULL;
2051 tor_cert_t *ed_id_sign = ed_certs[CERTTYPE_ED_ID_SIGN];
2052 tor_cert_t *ed_sign_link = ed_certs[CERTTYPE_ED_SIGN_LINK];
2053 tor_cert_t *ed_sign_auth = ed_certs[CERTTYPE_ED_SIGN_AUTH];
2054 chan->conn->handshake_state->certs->ed_id_sign = ed_id_sign;
2055 chan->conn->handshake_state->certs->ed_sign_link = ed_sign_link;
2056 chan->conn->handshake_state->certs->ed_sign_auth = ed_sign_auth;
2057 ed_certs[CERTTYPE_ED_ID_SIGN] =
2058 ed_certs[CERTTYPE_ED_SIGN_LINK] =
2059 ed_certs[CERTTYPE_ED_SIGN_AUTH] = NULL;
2061 chan->conn->handshake_state->certs->ed_rsa_crosscert = rsa_ed_cc_cert;
2062 chan->conn->handshake_state->certs->ed_rsa_crosscert_len =
2063 rsa_ed_cc_cert_len;
2064 rsa_ed_cc_cert = NULL;
2066 int severity;
2067 /* Note that this warns more loudly about time and validity if we were
2068 * _trying_ to connect to an authority, not necessarily if we _did_ connect
2069 * to one. */
2070 if (started_here &&
2071 router_digest_is_trusted_dir(TLS_CHAN_TO_BASE(chan)->identity_digest))
2072 severity = LOG_WARN;
2073 else
2074 severity = LOG_PROTOCOL_WARN;
2076 const ed25519_public_key_t *checked_ed_id = NULL;
2077 const common_digests_t *checked_rsa_id = NULL;
2078 or_handshake_certs_check_both(severity,
2079 chan->conn->handshake_state->certs,
2080 chan->conn->tls,
2081 time(NULL),
2082 &checked_ed_id,
2083 &checked_rsa_id);
2085 if (!checked_rsa_id)
2086 ERR("Invalid certificate chain!");
2088 if (started_here) {
2089 /* No more information is needed. */
2091 chan->conn->handshake_state->authenticated = 1;
2092 chan->conn->handshake_state->authenticated_rsa = 1;
2094 const common_digests_t *id_digests = checked_rsa_id;
2095 crypto_pk_t *identity_rcvd;
2096 if (!id_digests)
2097 ERR("Couldn't compute digests for key in ID cert");
2099 identity_rcvd = tor_tls_cert_get_key(id_cert);
2100 if (!identity_rcvd) {
2101 ERR("Couldn't get RSA key from ID cert.");
2103 memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
2104 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
2105 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
2106 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
2107 crypto_pk_free(identity_rcvd);
2110 if (checked_ed_id) {
2111 chan->conn->handshake_state->authenticated_ed25519 = 1;
2112 memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
2113 checked_ed_id, sizeof(ed25519_public_key_t));
2116 log_debug(LD_HANDSHAKE, "calling client_learned_peer_id from "
2117 "process_certs_cell");
2119 if (connection_or_client_learned_peer_id(chan->conn,
2120 chan->conn->handshake_state->authenticated_rsa_peer_id,
2121 checked_ed_id) < 0)
2122 ERR("Problem setting or checking peer id");
2124 log_info(LD_HANDSHAKE,
2125 "Got some good certificates from %s:%d: Authenticated it with "
2126 "RSA%s",
2127 safe_str(chan->conn->base_.address), chan->conn->base_.port,
2128 checked_ed_id ? " and Ed25519" : "");
2130 if (!public_server_mode(get_options())) {
2131 /* If we initiated the connection and we are not a public server, we
2132 * aren't planning to authenticate at all. At this point we know who we
2133 * are talking to, so we can just send a netinfo now. */
2134 send_netinfo = 1;
2136 } else {
2137 /* We can't call it authenticated till we see an AUTHENTICATE cell. */
2138 log_info(LD_OR,
2139 "Got some good RSA%s certificates from %s:%d. "
2140 "Waiting for AUTHENTICATE.",
2141 checked_ed_id ? " and Ed25519" : "",
2142 safe_str(chan->conn->base_.address),
2143 chan->conn->base_.port);
2144 /* XXXX check more stuff? */
2147 chan->conn->handshake_state->received_certs_cell = 1;
2149 if (send_netinfo) {
2150 if (connection_or_send_netinfo(chan->conn) < 0) {
2151 log_warn(LD_OR, "Couldn't send netinfo cell");
2152 connection_or_close_for_error(chan->conn, 0);
2153 goto err;
2157 err:
2158 for (unsigned u = 0; u < ARRAY_LENGTH(x509_certs); ++u) {
2159 tor_x509_cert_free(x509_certs[u]);
2161 for (unsigned u = 0; u < ARRAY_LENGTH(ed_certs); ++u) {
2162 tor_cert_free(ed_certs[u]);
2164 tor_free(rsa_ed_cc_cert);
2165 certs_cell_free(cc);
2166 #undef ERR
2170 * Process an AUTH_CHALLENGE cell from a channel_tls_t
2172 * This function is called to handle an incoming AUTH_CHALLENGE cell on a
2173 * channel_tls_t; if we weren't supposed to get one (for example, because we're
2174 * not the originator of the channel), or it's ill-formed, or we aren't doing
2175 * a v3 handshake, mark the channel. If the cell is well-formed but we don't
2176 * want to authenticate, just drop it. If the cell is well-formed *and* we
2177 * want to authenticate, send an AUTHENTICATE cell and then a NETINFO cell.
2180 STATIC void
2181 channel_tls_process_auth_challenge_cell(var_cell_t *cell, channel_tls_t *chan)
2183 int n_types, i, use_type = -1;
2184 auth_challenge_cell_t *ac = NULL;
2186 tor_assert(cell);
2187 tor_assert(chan);
2188 tor_assert(chan->conn);
2190 #define ERR(s) \
2191 do { \
2192 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
2193 "Received a bad AUTH_CHALLENGE cell from %s:%d: %s", \
2194 safe_str(chan->conn->base_.address), \
2195 chan->conn->base_.port, (s)); \
2196 connection_or_close_for_error(chan->conn, 0); \
2197 goto done; \
2198 } while (0)
2200 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
2201 ERR("We're not currently doing a v3 handshake");
2202 if (chan->conn->link_proto < 3)
2203 ERR("We're not using link protocol >= 3");
2204 if (!(chan->conn->handshake_state->started_here))
2205 ERR("We didn't originate this connection");
2206 if (chan->conn->handshake_state->received_auth_challenge)
2207 ERR("We already received one");
2208 if (!(chan->conn->handshake_state->received_certs_cell))
2209 ERR("We haven't gotten a CERTS cell yet");
2210 if (cell->circ_id)
2211 ERR("It had a nonzero circuit ID");
2213 if (auth_challenge_cell_parse(&ac, cell->payload, cell->payload_len) < 0)
2214 ERR("It was not well-formed.");
2216 n_types = ac->n_methods;
2218 /* Now see if there is an authentication type we can use */
2219 for (i = 0; i < n_types; ++i) {
2220 uint16_t authtype = auth_challenge_cell_get_methods(ac, i);
2221 if (authchallenge_type_is_supported(authtype)) {
2222 if (use_type == -1 ||
2223 authchallenge_type_is_better(authtype, use_type)) {
2224 use_type = authtype;
2229 chan->conn->handshake_state->received_auth_challenge = 1;
2231 if (! public_server_mode(get_options())) {
2232 /* If we're not a public server then we don't want to authenticate on a
2233 connection we originated, and we already sent a NETINFO cell when we
2234 got the CERTS cell. We have nothing more to do. */
2235 goto done;
2238 if (use_type >= 0) {
2239 log_info(LD_OR,
2240 "Got an AUTH_CHALLENGE cell from %s:%d: Sending "
2241 "authentication type %d",
2242 safe_str(chan->conn->base_.address),
2243 chan->conn->base_.port,
2244 use_type);
2246 if (connection_or_send_authenticate_cell(chan->conn, use_type) < 0) {
2247 log_warn(LD_OR,
2248 "Couldn't send authenticate cell");
2249 connection_or_close_for_error(chan->conn, 0);
2250 goto done;
2252 } else {
2253 log_info(LD_OR,
2254 "Got an AUTH_CHALLENGE cell from %s:%d, but we don't "
2255 "know any of its authentication types. Not authenticating.",
2256 safe_str(chan->conn->base_.address),
2257 chan->conn->base_.port);
2260 if (connection_or_send_netinfo(chan->conn) < 0) {
2261 log_warn(LD_OR, "Couldn't send netinfo cell");
2262 connection_or_close_for_error(chan->conn, 0);
2263 goto done;
2266 done:
2267 auth_challenge_cell_free(ac);
2269 #undef ERR
2273 * Process an AUTHENTICATE cell from a channel_tls_t
2275 * If it's ill-formed or we weren't supposed to get one or we're not doing a
2276 * v3 handshake, then mark the connection. If it does not authenticate the
2277 * other side of the connection successfully (because it isn't signed right,
2278 * we didn't get a CERTS cell, etc) mark the connection. Otherwise, accept
2279 * the identity of the router on the other side of the connection.
2282 STATIC void
2283 channel_tls_process_authenticate_cell(var_cell_t *cell, channel_tls_t *chan)
2285 var_cell_t *expected_cell = NULL;
2286 const uint8_t *auth;
2287 int authlen;
2288 int authtype;
2289 int bodylen;
2291 tor_assert(cell);
2292 tor_assert(chan);
2293 tor_assert(chan->conn);
2295 #define ERR(s) \
2296 do { \
2297 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
2298 "Received a bad AUTHENTICATE cell from %s:%d: %s", \
2299 safe_str(chan->conn->base_.address), \
2300 chan->conn->base_.port, (s)); \
2301 connection_or_close_for_error(chan->conn, 0); \
2302 var_cell_free(expected_cell); \
2303 return; \
2304 } while (0)
2306 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
2307 ERR("We're not doing a v3 handshake");
2308 if (chan->conn->link_proto < 3)
2309 ERR("We're not using link protocol >= 3");
2310 if (chan->conn->handshake_state->started_here)
2311 ERR("We originated this connection");
2312 if (chan->conn->handshake_state->received_authenticate)
2313 ERR("We already got one!");
2314 if (chan->conn->handshake_state->authenticated) {
2315 /* Should be impossible given other checks */
2316 ERR("The peer is already authenticated");
2318 if (!(chan->conn->handshake_state->received_certs_cell))
2319 ERR("We never got a certs cell");
2320 if (chan->conn->handshake_state->certs->id_cert == NULL)
2321 ERR("We never got an identity certificate");
2322 if (cell->payload_len < 4)
2323 ERR("Cell was way too short");
2325 auth = cell->payload;
2327 uint16_t type = ntohs(get_uint16(auth));
2328 uint16_t len = ntohs(get_uint16(auth+2));
2329 if (4 + len > cell->payload_len)
2330 ERR("Authenticator was truncated");
2332 if (! authchallenge_type_is_supported(type))
2333 ERR("Authenticator type was not recognized");
2334 authtype = type;
2336 auth += 4;
2337 authlen = len;
2340 if (authlen < V3_AUTH_BODY_LEN + 1)
2341 ERR("Authenticator was too short");
2343 expected_cell = connection_or_compute_authenticate_cell_body(
2344 chan->conn, authtype, NULL, NULL, 1);
2345 if (! expected_cell)
2346 ERR("Couldn't compute expected AUTHENTICATE cell body");
2348 int sig_is_rsa;
2349 if (authtype == AUTHTYPE_RSA_SHA256_TLSSECRET ||
2350 authtype == AUTHTYPE_RSA_SHA256_RFC5705) {
2351 bodylen = V3_AUTH_BODY_LEN;
2352 sig_is_rsa = 1;
2353 } else {
2354 tor_assert(authtype == AUTHTYPE_ED25519_SHA256_RFC5705);
2355 /* Our earlier check had better have made sure we had room
2356 * for an ed25519 sig (inadvertently) */
2357 tor_assert(V3_AUTH_BODY_LEN > ED25519_SIG_LEN);
2358 bodylen = authlen - ED25519_SIG_LEN;
2359 sig_is_rsa = 0;
2361 if (expected_cell->payload_len != bodylen+4) {
2362 ERR("Expected AUTHENTICATE cell body len not as expected.");
2365 /* Length of random part. */
2366 if (BUG(bodylen < 24)) {
2367 // LCOV_EXCL_START
2368 ERR("Bodylen is somehow less than 24, which should really be impossible");
2369 // LCOV_EXCL_STOP
2372 if (tor_memneq(expected_cell->payload+4, auth, bodylen-24))
2373 ERR("Some field in the AUTHENTICATE cell body was not as expected");
2375 if (sig_is_rsa) {
2376 if (chan->conn->handshake_state->certs->ed_id_sign != NULL)
2377 ERR("RSA-signed AUTHENTICATE response provided with an ED25519 cert");
2379 if (chan->conn->handshake_state->certs->auth_cert == NULL)
2380 ERR("We never got an RSA authentication certificate");
2382 crypto_pk_t *pk = tor_tls_cert_get_key(
2383 chan->conn->handshake_state->certs->auth_cert);
2384 char d[DIGEST256_LEN];
2385 char *signed_data;
2386 size_t keysize;
2387 int signed_len;
2389 if (! pk) {
2390 ERR("Couldn't get RSA key from AUTH cert.");
2392 crypto_digest256(d, (char*)auth, V3_AUTH_BODY_LEN, DIGEST_SHA256);
2394 keysize = crypto_pk_keysize(pk);
2395 signed_data = tor_malloc(keysize);
2396 signed_len = crypto_pk_public_checksig(pk, signed_data, keysize,
2397 (char*)auth + V3_AUTH_BODY_LEN,
2398 authlen - V3_AUTH_BODY_LEN);
2399 crypto_pk_free(pk);
2400 if (signed_len < 0) {
2401 tor_free(signed_data);
2402 ERR("RSA signature wasn't valid");
2404 if (signed_len < DIGEST256_LEN) {
2405 tor_free(signed_data);
2406 ERR("Not enough data was signed");
2408 /* Note that we deliberately allow *more* than DIGEST256_LEN bytes here,
2409 * in case they're later used to hold a SHA3 digest or something. */
2410 if (tor_memneq(signed_data, d, DIGEST256_LEN)) {
2411 tor_free(signed_data);
2412 ERR("Signature did not match data to be signed.");
2414 tor_free(signed_data);
2415 } else {
2416 if (chan->conn->handshake_state->certs->ed_id_sign == NULL)
2417 ERR("We never got an Ed25519 identity certificate.");
2418 if (chan->conn->handshake_state->certs->ed_sign_auth == NULL)
2419 ERR("We never got an Ed25519 authentication certificate.");
2421 const ed25519_public_key_t *authkey =
2422 &chan->conn->handshake_state->certs->ed_sign_auth->signed_key;
2423 ed25519_signature_t sig;
2424 tor_assert(authlen > ED25519_SIG_LEN);
2425 memcpy(&sig.sig, auth + authlen - ED25519_SIG_LEN, ED25519_SIG_LEN);
2426 if (ed25519_checksig(&sig, auth, authlen - ED25519_SIG_LEN, authkey)<0) {
2427 ERR("Ed25519 signature wasn't valid.");
2431 /* Okay, we are authenticated. */
2432 chan->conn->handshake_state->received_authenticate = 1;
2433 chan->conn->handshake_state->authenticated = 1;
2434 chan->conn->handshake_state->authenticated_rsa = 1;
2435 chan->conn->handshake_state->digest_received_data = 0;
2437 tor_x509_cert_t *id_cert = chan->conn->handshake_state->certs->id_cert;
2438 crypto_pk_t *identity_rcvd = tor_tls_cert_get_key(id_cert);
2439 const common_digests_t *id_digests = tor_x509_cert_get_id_digests(id_cert);
2440 const ed25519_public_key_t *ed_identity_received = NULL;
2442 if (! sig_is_rsa) {
2443 chan->conn->handshake_state->authenticated_ed25519 = 1;
2444 ed_identity_received =
2445 &chan->conn->handshake_state->certs->ed_id_sign->signing_key;
2446 memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
2447 ed_identity_received, sizeof(ed25519_public_key_t));
2450 /* This must exist; we checked key type when reading the cert. */
2451 tor_assert(id_digests);
2453 memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
2454 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
2456 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
2457 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
2458 crypto_pk_free(identity_rcvd);
2460 log_debug(LD_HANDSHAKE,
2461 "Calling connection_or_init_conn_from_address for %s "
2462 " from %s, with%s ed25519 id.",
2463 safe_str(chan->conn->base_.address),
2464 __func__,
2465 ed_identity_received ? "" : "out");
2467 connection_or_init_conn_from_address(chan->conn,
2468 &(chan->conn->base_.addr),
2469 chan->conn->base_.port,
2470 (const char*)(chan->conn->handshake_state->
2471 authenticated_rsa_peer_id),
2472 ed_identity_received,
2475 log_debug(LD_HANDSHAKE,
2476 "Got an AUTHENTICATE cell from %s:%d, type %d: Looks good.",
2477 safe_str(chan->conn->base_.address),
2478 chan->conn->base_.port,
2479 authtype);
2482 var_cell_free(expected_cell);
2484 #undef ERR