minor updates on upcoming changelog
[tor.git] / src / or / channeltls.c
blob82778131863b1679decf018e545aee5e19b355a7
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, &(TO_CONN(tlschan->conn)->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.
837 static int
838 channel_tls_write_packed_cell_method(channel_t *chan,
839 packed_cell_t *packed_cell)
841 tor_assert(chan);
842 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
843 size_t cell_network_size = get_cell_network_size(chan->wide_circ_ids);
844 int written = 0;
846 tor_assert(tlschan);
847 tor_assert(packed_cell);
849 if (tlschan->conn) {
850 connection_buf_add(packed_cell->body, cell_network_size,
851 TO_CONN(tlschan->conn));
853 /* This is where the cell is finished; used to be done from relay.c */
854 packed_cell_free(packed_cell);
855 ++written;
856 } else {
857 log_info(LD_CHANNEL,
858 "something called write_packed_cell on a tlschan "
859 "(%p with ID " U64_FORMAT " but no conn",
860 chan, U64_PRINTF_ARG(chan->global_identifier));
863 return written;
867 * Write a variable-length cell to a channel_tls_t
869 * This implements the write_var_cell method for channel_tls_t; given a
870 * 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 " U64_FORMAT " but no conn",
889 chan, U64_PRINTF_ARG(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
905 static void
906 channel_tls_listener_close_method(channel_listener_t *chan_l)
908 tor_assert(chan_l);
911 * Listeners we just go ahead and change state through to CLOSED, but
912 * make sure to check if they're channel_tls_listener to NULL it out.
914 if (chan_l == channel_tls_listener)
915 channel_tls_listener = NULL;
917 if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
918 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
919 chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
920 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
923 if (chan_l->incoming_list) {
924 SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
925 channel_t *, ichan) {
926 channel_mark_for_close(ichan);
927 } SMARTLIST_FOREACH_END(ichan);
929 smartlist_free(chan_l->incoming_list);
930 chan_l->incoming_list = NULL;
933 if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
934 chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
935 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
940 * Describe the transport for a channel_listener_t
942 * This returns the string "TLS channel (listening)" to the upper
943 * layer.
946 static const char *
947 channel_tls_listener_describe_transport_method(channel_listener_t *chan_l)
949 tor_assert(chan_l);
951 return "TLS channel (listening)";
954 /*******************************************************
955 * Functions for handling events on an or_connection_t *
956 ******************************************************/
959 * Handle an orconn state change
961 * This function will be called by connection_or.c when the or_connection_t
962 * associated with this channel_tls_t changes state.
965 void
966 channel_tls_handle_state_change_on_orconn(channel_tls_t *chan,
967 or_connection_t *conn,
968 uint8_t old_state,
969 uint8_t state)
971 channel_t *base_chan;
973 tor_assert(chan);
974 tor_assert(conn);
975 tor_assert(conn->chan == chan);
976 tor_assert(chan->conn == conn);
977 /* Shut the compiler up without triggering -Wtautological-compare */
978 (void)old_state;
980 base_chan = TLS_CHAN_TO_BASE(chan);
982 /* Make sure the base connection state makes sense - shouldn't be error
983 * or closed. */
985 tor_assert(CHANNEL_IS_OPENING(base_chan) ||
986 CHANNEL_IS_OPEN(base_chan) ||
987 CHANNEL_IS_MAINT(base_chan) ||
988 CHANNEL_IS_CLOSING(base_chan));
990 /* Did we just go to state open? */
991 if (state == OR_CONN_STATE_OPEN) {
993 * We can go to CHANNEL_STATE_OPEN from CHANNEL_STATE_OPENING or
994 * CHANNEL_STATE_MAINT on this.
996 channel_change_state_open(base_chan);
997 /* We might have just become writeable; check and tell the scheduler */
998 if (connection_or_num_cells_writeable(conn) > 0) {
999 scheduler_channel_wants_writes(base_chan);
1001 } else {
1003 * Not open, so from CHANNEL_STATE_OPEN we go to CHANNEL_STATE_MAINT,
1004 * otherwise no change.
1006 if (CHANNEL_IS_OPEN(base_chan)) {
1007 channel_change_state(base_chan, CHANNEL_STATE_MAINT);
1012 #ifdef KEEP_TIMING_STATS
1015 * Timing states wrapper
1017 * This is a wrapper function around the actual function that processes the
1018 * <b>cell</b> that just arrived on <b>chan</b>. Increment <b>*time</b>
1019 * by the number of microseconds used by the call to <b>*func(cell, chan)</b>.
1022 static void
1023 channel_tls_time_process_cell(cell_t *cell, channel_tls_t *chan, int *time,
1024 void (*func)(cell_t *, channel_tls_t *))
1026 struct timeval start, end;
1027 long time_passed;
1029 tor_gettimeofday(&start);
1031 (*func)(cell, chan);
1033 tor_gettimeofday(&end);
1034 time_passed = tv_udiff(&start, &end) ;
1036 if (time_passed > 10000) { /* more than 10ms */
1037 log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
1040 if (time_passed < 0) {
1041 log_info(LD_GENERAL,"That call took us back in time!");
1042 time_passed = 0;
1045 *time += time_passed;
1047 #endif /* defined(KEEP_TIMING_STATS) */
1050 * Handle an incoming cell on a channel_tls_t
1052 * This is called from connection_or.c to handle an arriving cell; it checks
1053 * for cell types specific to the handshake for this transport protocol and
1054 * handles them, and queues all other cells to the channel_t layer, which
1055 * eventually will hand them off to command.c.
1057 * The channel layer itself decides whether the cell should be queued or
1058 * can be handed off immediately to the upper-layer code. It is responsible
1059 * for copying in the case that it queues; we merely pass pointers through
1060 * which we get from connection_or_process_cells_from_inbuf().
1063 void
1064 channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
1066 channel_tls_t *chan;
1067 int handshaking;
1069 #ifdef KEEP_TIMING_STATS
1070 #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
1071 ++num ## tp; \
1072 channel_tls_time_process_cell(cl, cn, & tp ## time , \
1073 channel_tls_process_ ## tp ## _cell); \
1074 } STMT_END
1075 #else /* !(defined(KEEP_TIMING_STATS)) */
1076 #define PROCESS_CELL(tp, cl, cn) channel_tls_process_ ## tp ## _cell(cl, cn)
1077 #endif /* defined(KEEP_TIMING_STATS) */
1079 tor_assert(cell);
1080 tor_assert(conn);
1082 chan = conn->chan;
1084 if (!chan) {
1085 log_warn(LD_CHANNEL,
1086 "Got a cell_t on an OR connection with no channel");
1087 return;
1090 handshaking = (TO_CONN(conn)->state != OR_CONN_STATE_OPEN);
1092 if (conn->base_.marked_for_close)
1093 return;
1095 /* Reject all but VERSIONS and NETINFO when handshaking. */
1096 /* (VERSIONS should actually be impossible; it's variable-length.) */
1097 if (handshaking && cell->command != CELL_VERSIONS &&
1098 cell->command != CELL_NETINFO) {
1099 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1100 "Received unexpected cell command %d in chan state %s / "
1101 "conn state %s; closing the connection.",
1102 (int)cell->command,
1103 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1104 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state));
1105 connection_or_close_for_error(conn, 0);
1106 return;
1109 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
1110 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 1);
1112 /* We note that we're on the internet whenever we read a cell. This is
1113 * a fast operation. */
1114 entry_guards_note_internet_connectivity(get_guard_selection_info());
1115 rep_hist_padding_count_read(PADDING_TYPE_TOTAL);
1117 if (TLS_CHAN_TO_BASE(chan)->currently_padding)
1118 rep_hist_padding_count_read(PADDING_TYPE_ENABLED_TOTAL);
1120 switch (cell->command) {
1121 case CELL_PADDING:
1122 rep_hist_padding_count_read(PADDING_TYPE_CELL);
1123 if (TLS_CHAN_TO_BASE(chan)->currently_padding)
1124 rep_hist_padding_count_read(PADDING_TYPE_ENABLED_CELL);
1125 ++stats_n_padding_cells_processed;
1126 /* do nothing */
1127 break;
1128 case CELL_VERSIONS:
1129 tor_fragile_assert();
1130 break;
1131 case CELL_NETINFO:
1132 ++stats_n_netinfo_cells_processed;
1133 PROCESS_CELL(netinfo, cell, chan);
1134 break;
1135 case CELL_PADDING_NEGOTIATE:
1136 ++stats_n_netinfo_cells_processed;
1137 PROCESS_CELL(padding_negotiate, cell, chan);
1138 break;
1139 case CELL_CREATE:
1140 case CELL_CREATE_FAST:
1141 case CELL_CREATED:
1142 case CELL_CREATED_FAST:
1143 case CELL_RELAY:
1144 case CELL_RELAY_EARLY:
1145 case CELL_DESTROY:
1146 case CELL_CREATE2:
1147 case CELL_CREATED2:
1149 * These are all transport independent and we pass them up through the
1150 * channel_t mechanism. They are ultimately handled in command.c.
1152 channel_queue_cell(TLS_CHAN_TO_BASE(chan), cell);
1153 break;
1154 default:
1155 log_fn(LOG_INFO, LD_PROTOCOL,
1156 "Cell of unknown type (%d) received in channeltls.c. "
1157 "Dropping.",
1158 cell->command);
1159 break;
1164 * Handle an incoming variable-length cell on a channel_tls_t
1166 * Process a <b>var_cell</b> that was just received on <b>conn</b>. Keep
1167 * internal statistics about how many of each cell we've processed so far
1168 * this second, and the total number of microseconds it took to
1169 * process each type of cell. All the var_cell commands are handshake-
1170 * related and live below the channel_t layer, so no variable-length
1171 * cells ever get delivered in the current implementation, but I've left
1172 * the mechanism in place for future use.
1174 * If we were handing them off to the upper layer, the channel_t queueing
1175 * code would be responsible for memory management, and we'd just be passing
1176 * pointers through from connection_or_process_cells_from_inbuf(). That
1177 * caller always frees them after this function returns, so this function
1178 * 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();
1252 /* fall through */
1253 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
1254 if (!(command_allowed_before_handshake(var_cell->command))) {
1255 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1256 "Received a cell with command %d in unexpected "
1257 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1258 "closing the connection.",
1259 (int)(var_cell->command),
1260 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1261 (int)(TO_CONN(conn)->state),
1262 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1263 (int)(TLS_CHAN_TO_BASE(chan)->state));
1264 /* see above comment about CHANNEL_STATE_ERROR */
1265 connection_or_close_for_error(conn, 0);
1266 return;
1267 } else {
1268 if (enter_v3_handshake_with_cell(var_cell, chan) < 0)
1269 return;
1271 break;
1272 case OR_CONN_STATE_OR_HANDSHAKING_V3:
1273 if (var_cell->command != CELL_AUTHENTICATE)
1274 or_handshake_state_record_var_cell(conn, conn->handshake_state,
1275 var_cell, 1);
1276 break; /* Everything is allowed */
1277 case OR_CONN_STATE_OPEN:
1278 if (conn->link_proto < 3) {
1279 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1280 "Received a variable-length cell with command %d in orconn "
1281 "state %s [%d], channel state %s [%d] with link protocol %d; "
1282 "ignoring it.",
1283 (int)(var_cell->command),
1284 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1285 (int)(TO_CONN(conn)->state),
1286 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1287 (int)(TLS_CHAN_TO_BASE(chan)->state),
1288 (int)(conn->link_proto));
1289 return;
1291 break;
1292 default:
1293 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1294 "Received var-length cell with command %d in unexpected "
1295 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1296 "ignoring it.",
1297 (int)(var_cell->command),
1298 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1299 (int)(TO_CONN(conn)->state),
1300 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1301 (int)(TLS_CHAN_TO_BASE(chan)->state));
1302 return;
1305 /* We note that we're on the internet whenever we read a cell. This is
1306 * a fast operation. */
1307 entry_guards_note_internet_connectivity(get_guard_selection_info());
1309 /* Now handle the cell */
1311 switch (var_cell->command) {
1312 case CELL_VERSIONS:
1313 ++stats_n_versions_cells_processed;
1314 PROCESS_CELL(versions, var_cell, chan);
1315 break;
1316 case CELL_VPADDING:
1317 ++stats_n_vpadding_cells_processed;
1318 /* Do nothing */
1319 break;
1320 case CELL_CERTS:
1321 ++stats_n_certs_cells_processed;
1322 PROCESS_CELL(certs, var_cell, chan);
1323 break;
1324 case CELL_AUTH_CHALLENGE:
1325 ++stats_n_auth_challenge_cells_processed;
1326 PROCESS_CELL(auth_challenge, var_cell, chan);
1327 break;
1328 case CELL_AUTHENTICATE:
1329 ++stats_n_authenticate_cells_processed;
1330 PROCESS_CELL(authenticate, var_cell, chan);
1331 break;
1332 case CELL_AUTHORIZE:
1333 ++stats_n_authorize_cells_processed;
1334 /* Ignored so far. */
1335 break;
1336 default:
1337 log_fn(LOG_INFO, LD_PROTOCOL,
1338 "Variable-length cell of unknown type (%d) received.",
1339 (int)(var_cell->command));
1340 break;
1345 * Update channel marks after connection_or.c has changed an address
1347 * This is called from connection_or_init_conn_from_address() after the
1348 * connection's _base.addr or real_addr fields have potentially been changed
1349 * so we can recalculate the local mark. Notably, this happens when incoming
1350 * connections are reverse-proxied and we only learn the real address of the
1351 * remote router by looking it up in the consensus after we finish the
1352 * 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_addr(&(TO_CONN(conn)->addr))) {
1366 if (!channel_is_local(chan)) {
1367 log_debug(LD_CHANNEL,
1368 "Marking channel " U64_FORMAT " at %p as local",
1369 U64_PRINTF_ARG(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 " U64_FORMAT " at %p as remote",
1376 U64_PRINTF_ARG(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.
1389 static int
1390 command_allowed_before_handshake(uint8_t command)
1392 switch (command) {
1393 case CELL_VERSIONS:
1394 case CELL_VPADDING:
1395 case CELL_AUTHORIZE:
1396 return 1;
1397 default:
1398 return 0;
1403 * Start a V3 handshake on an incoming connection
1405 * Called when we as a server receive an appropriate cell while waiting
1406 * either for a cell or a TLS handshake. Set the connection's state to
1407 * "handshaking_v3', initializes the or_handshake_state field as needed,
1408 * and add the cell to the hash of incoming cells.)
1411 static int
1412 enter_v3_handshake_with_cell(var_cell_t *cell, channel_tls_t *chan)
1414 int started_here = 0;
1416 tor_assert(cell);
1417 tor_assert(chan);
1418 tor_assert(chan->conn);
1420 started_here = connection_or_nonopen_was_started_here(chan->conn);
1422 tor_assert(TO_CONN(chan->conn)->state == OR_CONN_STATE_TLS_HANDSHAKING ||
1423 TO_CONN(chan->conn)->state ==
1424 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1426 if (started_here) {
1427 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1428 "Received a cell while TLS-handshaking, not in "
1429 "OR_HANDSHAKING_V3, on a connection we originated.");
1431 connection_or_block_renegotiation(chan->conn);
1432 chan->conn->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
1433 if (connection_init_or_handshake_state(chan->conn, started_here) < 0) {
1434 connection_or_close_for_error(chan->conn, 0);
1435 return -1;
1437 or_handshake_state_record_var_cell(chan->conn,
1438 chan->conn->handshake_state, cell, 1);
1439 return 0;
1443 * Process a 'versions' cell.
1445 * This function is called to handle an incoming VERSIONS cell; the current
1446 * link protocol version must be 0 to indicate that no version has yet been
1447 * negotiated. We compare the versions in the cell to the list of versions
1448 * we support, pick the highest version we have in common, and continue the
1449 * negotiation from there.
1452 static void
1453 channel_tls_process_versions_cell(var_cell_t *cell, channel_tls_t *chan)
1455 int highest_supported_version = 0;
1456 int started_here = 0;
1458 tor_assert(cell);
1459 tor_assert(chan);
1460 tor_assert(chan->conn);
1462 if ((cell->payload_len % 2) == 1) {
1463 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1464 "Received a VERSION cell with odd payload length %d; "
1465 "closing connection.",cell->payload_len);
1466 connection_or_close_for_error(chan->conn, 0);
1467 return;
1470 started_here = connection_or_nonopen_was_started_here(chan->conn);
1472 if (chan->conn->link_proto != 0 ||
1473 (chan->conn->handshake_state &&
1474 chan->conn->handshake_state->received_versions)) {
1475 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1476 "Received a VERSIONS cell on a connection with its version "
1477 "already set to %d; dropping",
1478 (int)(chan->conn->link_proto));
1479 return;
1481 switch (chan->conn->base_.state)
1483 case OR_CONN_STATE_OR_HANDSHAKING_V2:
1484 case OR_CONN_STATE_OR_HANDSHAKING_V3:
1485 break;
1486 case OR_CONN_STATE_TLS_HANDSHAKING:
1487 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
1488 default:
1489 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1490 "VERSIONS cell while in unexpected state");
1491 return;
1494 tor_assert(chan->conn->handshake_state);
1497 int i;
1498 const uint8_t *cp = cell->payload;
1499 for (i = 0; i < cell->payload_len / 2; ++i, cp += 2) {
1500 uint16_t v = ntohs(get_uint16(cp));
1501 if (is_or_protocol_version_known(v) && v > highest_supported_version)
1502 highest_supported_version = v;
1505 if (!highest_supported_version) {
1506 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1507 "Couldn't find a version in common between my version list and the "
1508 "list in the VERSIONS cell; closing connection.");
1509 connection_or_close_for_error(chan->conn, 0);
1510 return;
1511 } else if (highest_supported_version == 1) {
1512 /* Negotiating version 1 makes no sense, since version 1 has no VERSIONS
1513 * cells. */
1514 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1515 "Used version negotiation protocol to negotiate a v1 connection. "
1516 "That's crazily non-compliant. Closing connection.");
1517 connection_or_close_for_error(chan->conn, 0);
1518 return;
1519 } else if (highest_supported_version < 3 &&
1520 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1521 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1522 "Negotiated link protocol 2 or lower after doing a v3 TLS "
1523 "handshake. Closing connection.");
1524 connection_or_close_for_error(chan->conn, 0);
1525 return;
1526 } else if (highest_supported_version != 2 &&
1527 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V2) {
1528 /* XXXX This should eventually be a log_protocol_warn */
1529 log_fn(LOG_WARN, LD_OR,
1530 "Negotiated link with non-2 protocol after doing a v2 TLS "
1531 "handshake with %s. Closing connection.",
1532 fmt_addr(&chan->conn->base_.addr));
1533 connection_or_close_for_error(chan->conn, 0);
1534 return;
1537 rep_hist_note_negotiated_link_proto(highest_supported_version, started_here);
1539 chan->conn->link_proto = highest_supported_version;
1540 chan->conn->handshake_state->received_versions = 1;
1542 if (chan->conn->link_proto == 2) {
1543 log_info(LD_OR,
1544 "Negotiated version %d with %s:%d; sending NETINFO.",
1545 highest_supported_version,
1546 safe_str_client(chan->conn->base_.address),
1547 chan->conn->base_.port);
1549 if (connection_or_send_netinfo(chan->conn) < 0) {
1550 connection_or_close_for_error(chan->conn, 0);
1551 return;
1553 } else {
1554 const int send_versions = !started_here;
1555 /* If we want to authenticate, send a CERTS cell */
1556 const int send_certs = !started_here || public_server_mode(get_options());
1557 /* If we're a host that got a connection, ask for authentication. */
1558 const int send_chall = !started_here;
1559 /* If our certs cell will authenticate us, we can send a netinfo cell
1560 * right now. */
1561 const int send_netinfo = !started_here;
1562 const int send_any =
1563 send_versions || send_certs || send_chall || send_netinfo;
1564 tor_assert(chan->conn->link_proto >= 3);
1566 log_info(LD_OR,
1567 "Negotiated version %d with %s:%d; %s%s%s%s%s",
1568 highest_supported_version,
1569 safe_str_client(chan->conn->base_.address),
1570 chan->conn->base_.port,
1571 send_any ? "Sending cells:" : "Waiting for CERTS cell",
1572 send_versions ? " VERSIONS" : "",
1573 send_certs ? " CERTS" : "",
1574 send_chall ? " AUTH_CHALLENGE" : "",
1575 send_netinfo ? " NETINFO" : "");
1577 #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
1578 if (1) {
1579 connection_or_close_normally(chan->conn, 1);
1580 return;
1582 #endif /* defined(DISABLE_V3_LINKPROTO_SERVERSIDE) */
1584 if (send_versions) {
1585 if (connection_or_send_versions(chan->conn, 1) < 0) {
1586 log_warn(LD_OR, "Couldn't send versions cell");
1587 connection_or_close_for_error(chan->conn, 0);
1588 return;
1592 /* We set this after sending the verions cell. */
1593 /*XXXXX symbolic const.*/
1594 TLS_CHAN_TO_BASE(chan)->wide_circ_ids =
1595 chan->conn->link_proto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
1596 chan->conn->wide_circ_ids = TLS_CHAN_TO_BASE(chan)->wide_circ_ids;
1598 TLS_CHAN_TO_BASE(chan)->padding_enabled =
1599 chan->conn->link_proto >= MIN_LINK_PROTO_FOR_CHANNEL_PADDING;
1601 if (send_certs) {
1602 if (connection_or_send_certs_cell(chan->conn) < 0) {
1603 log_warn(LD_OR, "Couldn't send certs cell");
1604 connection_or_close_for_error(chan->conn, 0);
1605 return;
1608 if (send_chall) {
1609 if (connection_or_send_auth_challenge_cell(chan->conn) < 0) {
1610 log_warn(LD_OR, "Couldn't send auth_challenge cell");
1611 connection_or_close_for_error(chan->conn, 0);
1612 return;
1615 if (send_netinfo) {
1616 if (connection_or_send_netinfo(chan->conn) < 0) {
1617 log_warn(LD_OR, "Couldn't send netinfo cell");
1618 connection_or_close_for_error(chan->conn, 0);
1619 return;
1626 * Process a 'padding_negotiate' cell
1628 * This function is called to handle an incoming PADDING_NEGOTIATE cell;
1629 * enable or disable padding accordingly, and read and act on its timeout
1630 * value contents.
1632 static void
1633 channel_tls_process_padding_negotiate_cell(cell_t *cell, channel_tls_t *chan)
1635 channelpadding_negotiate_t *negotiation;
1636 tor_assert(cell);
1637 tor_assert(chan);
1638 tor_assert(chan->conn);
1640 if (chan->conn->link_proto < MIN_LINK_PROTO_FOR_CHANNEL_PADDING) {
1641 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1642 "Received a PADDING_NEGOTIATE cell on v%d connection; dropping.",
1643 chan->conn->link_proto);
1644 return;
1647 if (channelpadding_negotiate_parse(&negotiation, cell->payload,
1648 CELL_PAYLOAD_SIZE) < 0) {
1649 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1650 "Received malformed PADDING_NEGOTIATE cell on v%d connection; "
1651 "dropping.", chan->conn->link_proto);
1653 return;
1656 channelpadding_update_padding_for_channel(TLS_CHAN_TO_BASE(chan),
1657 negotiation);
1659 channelpadding_negotiate_free(negotiation);
1663 * Process a 'netinfo' cell
1665 * This function is called to handle an incoming NETINFO cell; read and act
1666 * on its contents, and set the connection state to "open".
1669 static void
1670 channel_tls_process_netinfo_cell(cell_t *cell, channel_tls_t *chan)
1672 time_t timestamp;
1673 uint8_t my_addr_type;
1674 uint8_t my_addr_len;
1675 const uint8_t *my_addr_ptr;
1676 const uint8_t *cp, *end;
1677 uint8_t n_other_addrs;
1678 time_t now = time(NULL);
1679 const routerinfo_t *me = router_get_my_routerinfo();
1681 long apparent_skew = 0;
1682 tor_addr_t my_apparent_addr = TOR_ADDR_NULL;
1683 int started_here = 0;
1684 const char *identity_digest = NULL;
1686 tor_assert(cell);
1687 tor_assert(chan);
1688 tor_assert(chan->conn);
1690 if (chan->conn->link_proto < 2) {
1691 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1692 "Received a NETINFO cell on %s connection; dropping.",
1693 chan->conn->link_proto == 0 ? "non-versioned" : "a v1");
1694 return;
1696 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
1697 chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
1698 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1699 "Received a NETINFO cell on non-handshaking connection; dropping.");
1700 return;
1702 tor_assert(chan->conn->handshake_state &&
1703 chan->conn->handshake_state->received_versions);
1704 started_here = connection_or_nonopen_was_started_here(chan->conn);
1705 identity_digest = chan->conn->identity_digest;
1707 if (chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1708 tor_assert(chan->conn->link_proto >= 3);
1709 if (started_here) {
1710 if (!(chan->conn->handshake_state->authenticated)) {
1711 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1712 "Got a NETINFO cell from server, "
1713 "but no authentication. Closing the connection.");
1714 connection_or_close_for_error(chan->conn, 0);
1715 return;
1717 } else {
1718 /* we're the server. If the client never authenticated, we have
1719 some housekeeping to do.*/
1720 if (!(chan->conn->handshake_state->authenticated)) {
1721 tor_assert(tor_digest_is_zero(
1722 (const char*)(chan->conn->handshake_state->
1723 authenticated_rsa_peer_id)));
1724 tor_assert(tor_mem_is_zero(
1725 (const char*)(chan->conn->handshake_state->
1726 authenticated_ed25519_peer_id.pubkey), 32));
1727 /* If the client never authenticated, it's a tor client or bridge
1728 * relay, and we must not use it for EXTEND requests (nor could we, as
1729 * there are no authenticated peer IDs) */
1730 channel_mark_client(TLS_CHAN_TO_BASE(chan));
1731 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), NULL,
1732 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
1734 connection_or_init_conn_from_address(chan->conn,
1735 &(chan->conn->base_.addr),
1736 chan->conn->base_.port,
1737 /* zero, checked above */
1738 (const char*)(chan->conn->handshake_state->
1739 authenticated_rsa_peer_id),
1740 NULL, /* Ed25519 ID: Also checked as zero */
1746 /* Decode the cell. */
1747 timestamp = ntohl(get_uint32(cell->payload));
1748 if (labs(now - chan->conn->handshake_state->sent_versions_at) < 180) {
1749 apparent_skew = now - timestamp;
1752 my_addr_type = (uint8_t) cell->payload[4];
1753 my_addr_len = (uint8_t) cell->payload[5];
1754 my_addr_ptr = (uint8_t*) cell->payload + 6;
1755 end = cell->payload + CELL_PAYLOAD_SIZE;
1756 cp = cell->payload + 6 + my_addr_len;
1758 /* We used to check:
1759 * if (my_addr_len >= CELL_PAYLOAD_SIZE - 6) {
1761 * This is actually never going to happen, since my_addr_len is at most 255,
1762 * and CELL_PAYLOAD_LEN - 6 is 503. So we know that cp is < end. */
1764 if (my_addr_type == RESOLVED_TYPE_IPV4 && my_addr_len == 4) {
1765 tor_addr_from_ipv4n(&my_apparent_addr, get_uint32(my_addr_ptr));
1767 if (!get_options()->BridgeRelay && me &&
1768 get_uint32(my_addr_ptr) == htonl(me->addr)) {
1769 TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
1772 } else if (my_addr_type == RESOLVED_TYPE_IPV6 && my_addr_len == 16) {
1773 tor_addr_from_ipv6_bytes(&my_apparent_addr, (const char *) my_addr_ptr);
1775 if (!get_options()->BridgeRelay && me &&
1776 !tor_addr_is_null(&me->ipv6_addr) &&
1777 tor_addr_eq(&my_apparent_addr, &me->ipv6_addr)) {
1778 TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer = 1;
1782 n_other_addrs = (uint8_t) *cp++;
1783 while (n_other_addrs && cp < end-2) {
1784 /* Consider all the other addresses; if any matches, this connection is
1785 * "canonical." */
1786 tor_addr_t addr;
1787 const uint8_t *next =
1788 decode_address_from_payload(&addr, cp, (int)(end-cp));
1789 if (next == NULL) {
1790 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1791 "Bad address in netinfo cell; closing connection.");
1792 connection_or_close_for_error(chan->conn, 0);
1793 return;
1795 /* A relay can connect from anywhere and be canonical, so
1796 * long as it tells you from where it came. This may sound a bit
1797 * concerning... but that's what "canonical" means: that the
1798 * address is one that the relay itself has claimed. The relay
1799 * might be doing something funny, but nobody else is doing a MITM
1800 * on the relay's TCP.
1802 if (tor_addr_eq(&addr, &(chan->conn->real_addr))) {
1803 connection_or_set_canonical(chan->conn, 1);
1804 break;
1806 cp = next;
1807 --n_other_addrs;
1810 if (me && !TLS_CHAN_TO_BASE(chan)->is_canonical_to_peer &&
1811 channel_is_canonical(TLS_CHAN_TO_BASE(chan))) {
1812 const char *descr =
1813 TLS_CHAN_TO_BASE(chan)->get_remote_descr(TLS_CHAN_TO_BASE(chan), 0);
1814 log_info(LD_OR,
1815 "We made a connection to a relay at %s (fp=%s) but we think "
1816 "they will not consider this connection canonical. They "
1817 "think we are at %s, but we think its %s.",
1818 safe_str(descr),
1819 safe_str(hex_str(identity_digest, DIGEST_LEN)),
1820 safe_str(tor_addr_is_null(&my_apparent_addr) ?
1821 "<none>" : fmt_and_decorate_addr(&my_apparent_addr)),
1822 safe_str(fmt_addr32(me->addr)));
1825 /* Act on apparent skew. */
1826 /** Warn when we get a netinfo skew with at least this value. */
1827 #define NETINFO_NOTICE_SKEW 3600
1828 if (labs(apparent_skew) > NETINFO_NOTICE_SKEW &&
1829 (started_here ||
1830 connection_or_digest_is_known_relay(chan->conn->identity_digest))) {
1831 int trusted = router_digest_is_trusted_dir(chan->conn->identity_digest);
1832 clock_skew_warning(TO_CONN(chan->conn), apparent_skew, trusted, LD_GENERAL,
1833 "NETINFO cell", "OR");
1836 /* XXX maybe act on my_apparent_addr, if the source is sufficiently
1837 * trustworthy. */
1839 if (! chan->conn->handshake_state->sent_netinfo) {
1840 /* If we were prepared to authenticate, but we never got an AUTH_CHALLENGE
1841 * cell, then we would not previously have sent a NETINFO cell. Do so
1842 * now. */
1843 if (connection_or_send_netinfo(chan->conn) < 0) {
1844 connection_or_close_for_error(chan->conn, 0);
1845 return;
1849 if (connection_or_set_state_open(chan->conn) < 0) {
1850 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1851 "Got good NETINFO cell from %s:%d; but "
1852 "was unable to make the OR connection become open.",
1853 safe_str_client(chan->conn->base_.address),
1854 chan->conn->base_.port);
1855 connection_or_close_for_error(chan->conn, 0);
1856 } else {
1857 log_info(LD_OR,
1858 "Got good NETINFO cell from %s:%d; OR connection is now "
1859 "open, using protocol version %d. Its ID digest is %s. "
1860 "Our address is apparently %s.",
1861 safe_str_client(chan->conn->base_.address),
1862 chan->conn->base_.port,
1863 (int)(chan->conn->link_proto),
1864 hex_str(identity_digest, DIGEST_LEN),
1865 tor_addr_is_null(&my_apparent_addr) ?
1866 "<none>" : fmt_and_decorate_addr(&my_apparent_addr));
1868 assert_connection_ok(TO_CONN(chan->conn),time(NULL));
1871 /** Types of certificates that we know how to parse from CERTS cells. Each
1872 * type corresponds to a different encoding format. */
1873 typedef enum cert_encoding_t {
1874 CERT_ENCODING_UNKNOWN, /**< We don't recognize this. */
1875 CERT_ENCODING_X509, /**< It's an RSA key, signed with RSA, encoded in x509.
1876 * (Actually, it might not be RSA. We test that later.) */
1877 CERT_ENCODING_ED25519, /**< It's something signed with an Ed25519 key,
1878 * encoded asa a tor_cert_t.*/
1879 CERT_ENCODING_RSA_CROSSCERT, /**< It's an Ed key signed with an RSA key. */
1880 } cert_encoding_t;
1883 * Given one of the certificate type codes used in a CERTS cell,
1884 * return the corresponding cert_encoding_t that we should use to parse
1885 * the certificate.
1887 static cert_encoding_t
1888 certs_cell_typenum_to_cert_type(int typenum)
1890 switch (typenum) {
1891 case CERTTYPE_RSA1024_ID_LINK:
1892 case CERTTYPE_RSA1024_ID_ID:
1893 case CERTTYPE_RSA1024_ID_AUTH:
1894 return CERT_ENCODING_X509;
1895 case CERTTYPE_ED_ID_SIGN:
1896 case CERTTYPE_ED_SIGN_LINK:
1897 case CERTTYPE_ED_SIGN_AUTH:
1898 return CERT_ENCODING_ED25519;
1899 case CERTTYPE_RSA1024_ID_EDID:
1900 return CERT_ENCODING_RSA_CROSSCERT;
1901 default:
1902 return CERT_ENCODING_UNKNOWN;
1907 * Process a CERTS cell from a channel.
1909 * This function is called to process an incoming CERTS cell on a
1910 * channel_tls_t:
1912 * If the other side should not have sent us a CERTS cell, or the cell is
1913 * malformed, or it is supposed to authenticate the TLS key but it doesn't,
1914 * then mark the connection.
1916 * If the cell has a good cert chain and we're doing a v3 handshake, then
1917 * store the certificates in or_handshake_state. If this is the client side
1918 * of the connection, we then authenticate the server or mark the connection.
1919 * If it's the server side, wait for an AUTHENTICATE cell.
1921 STATIC void
1922 channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
1924 #define MAX_CERT_TYPE_WANTED CERTTYPE_RSA1024_ID_EDID
1925 /* These arrays will be sparse, since a cert type can be at most one
1926 * of ed/x509 */
1927 tor_x509_cert_t *x509_certs[MAX_CERT_TYPE_WANTED + 1];
1928 tor_cert_t *ed_certs[MAX_CERT_TYPE_WANTED + 1];
1929 uint8_t *rsa_ed_cc_cert = NULL;
1930 size_t rsa_ed_cc_cert_len = 0;
1932 int n_certs, i;
1933 certs_cell_t *cc = NULL;
1935 int send_netinfo = 0, started_here = 0;
1937 memset(x509_certs, 0, sizeof(x509_certs));
1938 memset(ed_certs, 0, sizeof(ed_certs));
1939 tor_assert(cell);
1940 tor_assert(chan);
1941 tor_assert(chan->conn);
1943 #define ERR(s) \
1944 do { \
1945 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
1946 "Received a bad CERTS cell from %s:%d: %s", \
1947 safe_str(chan->conn->base_.address), \
1948 chan->conn->base_.port, (s)); \
1949 connection_or_close_for_error(chan->conn, 0); \
1950 goto err; \
1951 } while (0)
1953 /* Can't use connection_or_nonopen_was_started_here(); its conn->tls
1954 * check looks like it breaks
1955 * test_link_handshake_recv_certs_ok_server(). */
1956 started_here = chan->conn->handshake_state->started_here;
1958 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
1959 ERR("We're not doing a v3 handshake!");
1960 if (chan->conn->link_proto < 3)
1961 ERR("We're not using link protocol >= 3");
1962 if (chan->conn->handshake_state->received_certs_cell)
1963 ERR("We already got one");
1964 if (chan->conn->handshake_state->authenticated) {
1965 /* Should be unreachable, but let's make sure. */
1966 ERR("We're already authenticated!");
1968 if (cell->payload_len < 1)
1969 ERR("It had no body");
1970 if (cell->circ_id)
1971 ERR("It had a nonzero circuit ID");
1973 if (certs_cell_parse(&cc, cell->payload, cell->payload_len) < 0)
1974 ERR("It couldn't be parsed.");
1976 n_certs = cc->n_certs;
1978 for (i = 0; i < n_certs; ++i) {
1979 certs_cell_cert_t *c = certs_cell_get_certs(cc, i);
1981 uint16_t cert_type = c->cert_type;
1982 uint16_t cert_len = c->cert_len;
1983 uint8_t *cert_body = certs_cell_cert_getarray_body(c);
1985 if (cert_type > MAX_CERT_TYPE_WANTED)
1986 continue;
1987 const cert_encoding_t ct = certs_cell_typenum_to_cert_type(cert_type);
1988 switch (ct) {
1989 default:
1990 case CERT_ENCODING_UNKNOWN:
1991 break;
1992 case CERT_ENCODING_X509: {
1993 tor_x509_cert_t *x509_cert = tor_x509_cert_decode(cert_body, cert_len);
1994 if (!x509_cert) {
1995 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1996 "Received undecodable certificate in CERTS cell from %s:%d",
1997 safe_str(chan->conn->base_.address),
1998 chan->conn->base_.port);
1999 } else {
2000 if (x509_certs[cert_type]) {
2001 tor_x509_cert_free(x509_cert);
2002 ERR("Duplicate x509 certificate");
2003 } else {
2004 x509_certs[cert_type] = x509_cert;
2007 break;
2009 case CERT_ENCODING_ED25519: {
2010 tor_cert_t *ed_cert = tor_cert_parse(cert_body, cert_len);
2011 if (!ed_cert) {
2012 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2013 "Received undecodable Ed certificate "
2014 "in CERTS cell from %s:%d",
2015 safe_str(chan->conn->base_.address),
2016 chan->conn->base_.port);
2017 } else {
2018 if (ed_certs[cert_type]) {
2019 tor_cert_free(ed_cert);
2020 ERR("Duplicate Ed25519 certificate");
2021 } else {
2022 ed_certs[cert_type] = ed_cert;
2025 break;
2028 case CERT_ENCODING_RSA_CROSSCERT: {
2029 if (rsa_ed_cc_cert) {
2030 ERR("Duplicate RSA->Ed25519 crosscert");
2031 } else {
2032 rsa_ed_cc_cert = tor_memdup(cert_body, cert_len);
2033 rsa_ed_cc_cert_len = cert_len;
2035 break;
2040 /* Move the certificates we (might) want into the handshake_state->certs
2041 * structure. */
2042 tor_x509_cert_t *id_cert = x509_certs[CERTTYPE_RSA1024_ID_ID];
2043 tor_x509_cert_t *auth_cert = x509_certs[CERTTYPE_RSA1024_ID_AUTH];
2044 tor_x509_cert_t *link_cert = x509_certs[CERTTYPE_RSA1024_ID_LINK];
2045 chan->conn->handshake_state->certs->auth_cert = auth_cert;
2046 chan->conn->handshake_state->certs->link_cert = link_cert;
2047 chan->conn->handshake_state->certs->id_cert = id_cert;
2048 x509_certs[CERTTYPE_RSA1024_ID_ID] =
2049 x509_certs[CERTTYPE_RSA1024_ID_AUTH] =
2050 x509_certs[CERTTYPE_RSA1024_ID_LINK] = NULL;
2052 tor_cert_t *ed_id_sign = ed_certs[CERTTYPE_ED_ID_SIGN];
2053 tor_cert_t *ed_sign_link = ed_certs[CERTTYPE_ED_SIGN_LINK];
2054 tor_cert_t *ed_sign_auth = ed_certs[CERTTYPE_ED_SIGN_AUTH];
2055 chan->conn->handshake_state->certs->ed_id_sign = ed_id_sign;
2056 chan->conn->handshake_state->certs->ed_sign_link = ed_sign_link;
2057 chan->conn->handshake_state->certs->ed_sign_auth = ed_sign_auth;
2058 ed_certs[CERTTYPE_ED_ID_SIGN] =
2059 ed_certs[CERTTYPE_ED_SIGN_LINK] =
2060 ed_certs[CERTTYPE_ED_SIGN_AUTH] = NULL;
2062 chan->conn->handshake_state->certs->ed_rsa_crosscert = rsa_ed_cc_cert;
2063 chan->conn->handshake_state->certs->ed_rsa_crosscert_len =
2064 rsa_ed_cc_cert_len;
2065 rsa_ed_cc_cert = NULL;
2067 int severity;
2068 /* Note that this warns more loudly about time and validity if we were
2069 * _trying_ to connect to an authority, not necessarily if we _did_ connect
2070 * to one. */
2071 if (started_here &&
2072 router_digest_is_trusted_dir(TLS_CHAN_TO_BASE(chan)->identity_digest))
2073 severity = LOG_WARN;
2074 else
2075 severity = LOG_PROTOCOL_WARN;
2077 const ed25519_public_key_t *checked_ed_id = NULL;
2078 const common_digests_t *checked_rsa_id = NULL;
2079 or_handshake_certs_check_both(severity,
2080 chan->conn->handshake_state->certs,
2081 chan->conn->tls,
2082 time(NULL),
2083 &checked_ed_id,
2084 &checked_rsa_id);
2086 if (!checked_rsa_id)
2087 ERR("Invalid certificate chain!");
2089 if (started_here) {
2090 /* No more information is needed. */
2092 chan->conn->handshake_state->authenticated = 1;
2093 chan->conn->handshake_state->authenticated_rsa = 1;
2095 const common_digests_t *id_digests = checked_rsa_id;
2096 crypto_pk_t *identity_rcvd;
2097 if (!id_digests)
2098 ERR("Couldn't compute digests for key in ID cert");
2100 identity_rcvd = tor_tls_cert_get_key(id_cert);
2101 if (!identity_rcvd) {
2102 ERR("Couldn't get RSA key from ID cert.");
2104 memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
2105 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
2106 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
2107 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
2108 crypto_pk_free(identity_rcvd);
2111 if (checked_ed_id) {
2112 chan->conn->handshake_state->authenticated_ed25519 = 1;
2113 memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
2114 checked_ed_id, sizeof(ed25519_public_key_t));
2117 log_debug(LD_HANDSHAKE, "calling client_learned_peer_id from "
2118 "process_certs_cell");
2120 if (connection_or_client_learned_peer_id(chan->conn,
2121 chan->conn->handshake_state->authenticated_rsa_peer_id,
2122 checked_ed_id) < 0)
2123 ERR("Problem setting or checking peer id");
2125 log_info(LD_HANDSHAKE,
2126 "Got some good certificates from %s:%d: Authenticated it with "
2127 "RSA%s",
2128 safe_str(chan->conn->base_.address), chan->conn->base_.port,
2129 checked_ed_id ? " and Ed25519" : "");
2131 if (!public_server_mode(get_options())) {
2132 /* If we initiated the connection and we are not a public server, we
2133 * aren't planning to authenticate at all. At this point we know who we
2134 * are talking to, so we can just send a netinfo now. */
2135 send_netinfo = 1;
2137 } else {
2138 /* We can't call it authenticated till we see an AUTHENTICATE cell. */
2139 log_info(LD_OR,
2140 "Got some good RSA%s certificates from %s:%d. "
2141 "Waiting for AUTHENTICATE.",
2142 checked_ed_id ? " and Ed25519" : "",
2143 safe_str(chan->conn->base_.address),
2144 chan->conn->base_.port);
2145 /* XXXX check more stuff? */
2148 chan->conn->handshake_state->received_certs_cell = 1;
2150 if (send_netinfo) {
2151 if (connection_or_send_netinfo(chan->conn) < 0) {
2152 log_warn(LD_OR, "Couldn't send netinfo cell");
2153 connection_or_close_for_error(chan->conn, 0);
2154 goto err;
2158 err:
2159 for (unsigned u = 0; u < ARRAY_LENGTH(x509_certs); ++u) {
2160 tor_x509_cert_free(x509_certs[u]);
2162 for (unsigned u = 0; u < ARRAY_LENGTH(ed_certs); ++u) {
2163 tor_cert_free(ed_certs[u]);
2165 tor_free(rsa_ed_cc_cert);
2166 certs_cell_free(cc);
2167 #undef ERR
2171 * Process an AUTH_CHALLENGE cell from a channel_tls_t
2173 * This function is called to handle an incoming AUTH_CHALLENGE cell on a
2174 * channel_tls_t; if we weren't supposed to get one (for example, because we're
2175 * not the originator of the channel), or it's ill-formed, or we aren't doing
2176 * a v3 handshake, mark the channel. If the cell is well-formed but we don't
2177 * want to authenticate, just drop it. If the cell is well-formed *and* we
2178 * want to authenticate, send an AUTHENTICATE cell and then a NETINFO cell.
2181 STATIC void
2182 channel_tls_process_auth_challenge_cell(var_cell_t *cell, channel_tls_t *chan)
2184 int n_types, i, use_type = -1;
2185 auth_challenge_cell_t *ac = NULL;
2187 tor_assert(cell);
2188 tor_assert(chan);
2189 tor_assert(chan->conn);
2191 #define ERR(s) \
2192 do { \
2193 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
2194 "Received a bad AUTH_CHALLENGE cell from %s:%d: %s", \
2195 safe_str(chan->conn->base_.address), \
2196 chan->conn->base_.port, (s)); \
2197 connection_or_close_for_error(chan->conn, 0); \
2198 goto done; \
2199 } while (0)
2201 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
2202 ERR("We're not currently doing a v3 handshake");
2203 if (chan->conn->link_proto < 3)
2204 ERR("We're not using link protocol >= 3");
2205 if (!(chan->conn->handshake_state->started_here))
2206 ERR("We didn't originate this connection");
2207 if (chan->conn->handshake_state->received_auth_challenge)
2208 ERR("We already received one");
2209 if (!(chan->conn->handshake_state->received_certs_cell))
2210 ERR("We haven't gotten a CERTS cell yet");
2211 if (cell->circ_id)
2212 ERR("It had a nonzero circuit ID");
2214 if (auth_challenge_cell_parse(&ac, cell->payload, cell->payload_len) < 0)
2215 ERR("It was not well-formed.");
2217 n_types = ac->n_methods;
2219 /* Now see if there is an authentication type we can use */
2220 for (i = 0; i < n_types; ++i) {
2221 uint16_t authtype = auth_challenge_cell_get_methods(ac, i);
2222 if (authchallenge_type_is_supported(authtype)) {
2223 if (use_type == -1 ||
2224 authchallenge_type_is_better(authtype, use_type)) {
2225 use_type = authtype;
2230 chan->conn->handshake_state->received_auth_challenge = 1;
2232 if (! public_server_mode(get_options())) {
2233 /* If we're not a public server then we don't want to authenticate on a
2234 connection we originated, and we already sent a NETINFO cell when we
2235 got the CERTS cell. We have nothing more to do. */
2236 goto done;
2239 if (use_type >= 0) {
2240 log_info(LD_OR,
2241 "Got an AUTH_CHALLENGE cell from %s:%d: Sending "
2242 "authentication type %d",
2243 safe_str(chan->conn->base_.address),
2244 chan->conn->base_.port,
2245 use_type);
2247 if (connection_or_send_authenticate_cell(chan->conn, use_type) < 0) {
2248 log_warn(LD_OR,
2249 "Couldn't send authenticate cell");
2250 connection_or_close_for_error(chan->conn, 0);
2251 goto done;
2253 } else {
2254 log_info(LD_OR,
2255 "Got an AUTH_CHALLENGE cell from %s:%d, but we don't "
2256 "know any of its authentication types. Not authenticating.",
2257 safe_str(chan->conn->base_.address),
2258 chan->conn->base_.port);
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 done;
2267 done:
2268 auth_challenge_cell_free(ac);
2270 #undef ERR
2274 * Process an AUTHENTICATE cell from a channel_tls_t
2276 * If it's ill-formed or we weren't supposed to get one or we're not doing a
2277 * v3 handshake, then mark the connection. If it does not authenticate the
2278 * other side of the connection successfully (because it isn't signed right,
2279 * we didn't get a CERTS cell, etc) mark the connection. Otherwise, accept
2280 * the identity of the router on the other side of the connection.
2283 STATIC void
2284 channel_tls_process_authenticate_cell(var_cell_t *cell, channel_tls_t *chan)
2286 var_cell_t *expected_cell = NULL;
2287 const uint8_t *auth;
2288 int authlen;
2289 int authtype;
2290 int bodylen;
2292 tor_assert(cell);
2293 tor_assert(chan);
2294 tor_assert(chan->conn);
2296 #define ERR(s) \
2297 do { \
2298 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
2299 "Received a bad AUTHENTICATE cell from %s:%d: %s", \
2300 safe_str(chan->conn->base_.address), \
2301 chan->conn->base_.port, (s)); \
2302 connection_or_close_for_error(chan->conn, 0); \
2303 var_cell_free(expected_cell); \
2304 return; \
2305 } while (0)
2307 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
2308 ERR("We're not doing a v3 handshake");
2309 if (chan->conn->link_proto < 3)
2310 ERR("We're not using link protocol >= 3");
2311 if (chan->conn->handshake_state->started_here)
2312 ERR("We originated this connection");
2313 if (chan->conn->handshake_state->received_authenticate)
2314 ERR("We already got one!");
2315 if (chan->conn->handshake_state->authenticated) {
2316 /* Should be impossible given other checks */
2317 ERR("The peer is already authenticated");
2319 if (!(chan->conn->handshake_state->received_certs_cell))
2320 ERR("We never got a certs cell");
2321 if (chan->conn->handshake_state->certs->id_cert == NULL)
2322 ERR("We never got an identity certificate");
2323 if (cell->payload_len < 4)
2324 ERR("Cell was way too short");
2326 auth = cell->payload;
2328 uint16_t type = ntohs(get_uint16(auth));
2329 uint16_t len = ntohs(get_uint16(auth+2));
2330 if (4 + len > cell->payload_len)
2331 ERR("Authenticator was truncated");
2333 if (! authchallenge_type_is_supported(type))
2334 ERR("Authenticator type was not recognized");
2335 authtype = type;
2337 auth += 4;
2338 authlen = len;
2341 if (authlen < V3_AUTH_BODY_LEN + 1)
2342 ERR("Authenticator was too short");
2344 expected_cell = connection_or_compute_authenticate_cell_body(
2345 chan->conn, authtype, NULL, NULL, 1);
2346 if (! expected_cell)
2347 ERR("Couldn't compute expected AUTHENTICATE cell body");
2349 int sig_is_rsa;
2350 if (authtype == AUTHTYPE_RSA_SHA256_TLSSECRET ||
2351 authtype == AUTHTYPE_RSA_SHA256_RFC5705) {
2352 bodylen = V3_AUTH_BODY_LEN;
2353 sig_is_rsa = 1;
2354 } else {
2355 tor_assert(authtype == AUTHTYPE_ED25519_SHA256_RFC5705);
2356 /* Our earlier check had better have made sure we had room
2357 * for an ed25519 sig (inadvertently) */
2358 tor_assert(V3_AUTH_BODY_LEN > ED25519_SIG_LEN);
2359 bodylen = authlen - ED25519_SIG_LEN;
2360 sig_is_rsa = 0;
2362 if (expected_cell->payload_len != bodylen+4) {
2363 ERR("Expected AUTHENTICATE cell body len not as expected.");
2366 /* Length of random part. */
2367 if (BUG(bodylen < 24)) {
2368 // LCOV_EXCL_START
2369 ERR("Bodylen is somehow less than 24, which should really be impossible");
2370 // LCOV_EXCL_STOP
2373 if (tor_memneq(expected_cell->payload+4, auth, bodylen-24))
2374 ERR("Some field in the AUTHENTICATE cell body was not as expected");
2376 if (sig_is_rsa) {
2377 if (chan->conn->handshake_state->certs->ed_id_sign != NULL)
2378 ERR("RSA-signed AUTHENTICATE response provided with an ED25519 cert");
2380 if (chan->conn->handshake_state->certs->auth_cert == NULL)
2381 ERR("We never got an RSA authentication certificate");
2383 crypto_pk_t *pk = tor_tls_cert_get_key(
2384 chan->conn->handshake_state->certs->auth_cert);
2385 char d[DIGEST256_LEN];
2386 char *signed_data;
2387 size_t keysize;
2388 int signed_len;
2390 if (! pk) {
2391 ERR("Couldn't get RSA key from AUTH cert.");
2393 crypto_digest256(d, (char*)auth, V3_AUTH_BODY_LEN, DIGEST_SHA256);
2395 keysize = crypto_pk_keysize(pk);
2396 signed_data = tor_malloc(keysize);
2397 signed_len = crypto_pk_public_checksig(pk, signed_data, keysize,
2398 (char*)auth + V3_AUTH_BODY_LEN,
2399 authlen - V3_AUTH_BODY_LEN);
2400 crypto_pk_free(pk);
2401 if (signed_len < 0) {
2402 tor_free(signed_data);
2403 ERR("RSA signature wasn't valid");
2405 if (signed_len < DIGEST256_LEN) {
2406 tor_free(signed_data);
2407 ERR("Not enough data was signed");
2409 /* Note that we deliberately allow *more* than DIGEST256_LEN bytes here,
2410 * in case they're later used to hold a SHA3 digest or something. */
2411 if (tor_memneq(signed_data, d, DIGEST256_LEN)) {
2412 tor_free(signed_data);
2413 ERR("Signature did not match data to be signed.");
2415 tor_free(signed_data);
2416 } else {
2417 if (chan->conn->handshake_state->certs->ed_id_sign == NULL)
2418 ERR("We never got an Ed25519 identity certificate.");
2419 if (chan->conn->handshake_state->certs->ed_sign_auth == NULL)
2420 ERR("We never got an Ed25519 authentication certificate.");
2422 const ed25519_public_key_t *authkey =
2423 &chan->conn->handshake_state->certs->ed_sign_auth->signed_key;
2424 ed25519_signature_t sig;
2425 tor_assert(authlen > ED25519_SIG_LEN);
2426 memcpy(&sig.sig, auth + authlen - ED25519_SIG_LEN, ED25519_SIG_LEN);
2427 if (ed25519_checksig(&sig, auth, authlen - ED25519_SIG_LEN, authkey)<0) {
2428 ERR("Ed25519 signature wasn't valid.");
2432 /* Okay, we are authenticated. */
2433 chan->conn->handshake_state->received_authenticate = 1;
2434 chan->conn->handshake_state->authenticated = 1;
2435 chan->conn->handshake_state->authenticated_rsa = 1;
2436 chan->conn->handshake_state->digest_received_data = 0;
2438 tor_x509_cert_t *id_cert = chan->conn->handshake_state->certs->id_cert;
2439 crypto_pk_t *identity_rcvd = tor_tls_cert_get_key(id_cert);
2440 const common_digests_t *id_digests = tor_x509_cert_get_id_digests(id_cert);
2441 const ed25519_public_key_t *ed_identity_received = NULL;
2443 if (! sig_is_rsa) {
2444 chan->conn->handshake_state->authenticated_ed25519 = 1;
2445 ed_identity_received =
2446 &chan->conn->handshake_state->certs->ed_id_sign->signing_key;
2447 memcpy(&chan->conn->handshake_state->authenticated_ed25519_peer_id,
2448 ed_identity_received, sizeof(ed25519_public_key_t));
2451 /* This must exist; we checked key type when reading the cert. */
2452 tor_assert(id_digests);
2454 memcpy(chan->conn->handshake_state->authenticated_rsa_peer_id,
2455 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
2457 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
2458 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
2459 crypto_pk_free(identity_rcvd);
2461 log_debug(LD_HANDSHAKE,
2462 "Calling connection_or_init_conn_from_address for %s "
2463 " from %s, with%s ed25519 id.",
2464 safe_str(chan->conn->base_.address),
2465 __func__,
2466 ed_identity_received ? "" : "out");
2468 connection_or_init_conn_from_address(chan->conn,
2469 &(chan->conn->base_.addr),
2470 chan->conn->base_.port,
2471 (const char*)(chan->conn->handshake_state->
2472 authenticated_rsa_peer_id),
2473 ed_identity_received,
2476 log_debug(LD_HANDSHAKE,
2477 "Got an AUTHENTICATE cell from %s:%d, type %d: Looks good.",
2478 safe_str(chan->conn->base_.address),
2479 chan->conn->base_.port,
2480 authtype);
2483 var_cell_free(expected_cell);
2485 #undef ERR