Merge branch 'maint-0.2.5' into maint-0.2.6
[tor.git] / src / or / channeltls.c
blob1cf697ccc5f265ea25c03cd0acc1a9ed109df410
1 /* * Copyright (c) 2012-2015, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file channeltls.c
6 * \brief channel_t concrete subclass using or_connection_t
7 **/
9 /*
10 * Define this so channel.h gives us things only channel_t subclasses
11 * should touch.
14 #define TOR_CHANNEL_INTERNAL_
16 #include "or.h"
17 #include "channel.h"
18 #include "channeltls.h"
19 #include "circuitmux.h"
20 #include "circuitmux_ewma.h"
21 #include "config.h"
22 #include "connection.h"
23 #include "connection_or.h"
24 #include "control.h"
25 #include "relay.h"
26 #include "rephist.h"
27 #include "router.h"
28 #include "routerlist.h"
29 #include "scheduler.h"
31 /** How many CELL_PADDING cells have we received, ever? */
32 uint64_t stats_n_padding_cells_processed = 0;
33 /** How many CELL_VERSIONS cells have we received, ever? */
34 uint64_t stats_n_versions_cells_processed = 0;
35 /** How many CELL_NETINFO cells have we received, ever? */
36 uint64_t stats_n_netinfo_cells_processed = 0;
37 /** How many CELL_VPADDING cells have we received, ever? */
38 uint64_t stats_n_vpadding_cells_processed = 0;
39 /** How many CELL_CERTS cells have we received, ever? */
40 uint64_t stats_n_certs_cells_processed = 0;
41 /** How many CELL_AUTH_CHALLENGE cells have we received, ever? */
42 uint64_t stats_n_auth_challenge_cells_processed = 0;
43 /** How many CELL_AUTHENTICATE cells have we received, ever? */
44 uint64_t stats_n_authenticate_cells_processed = 0;
45 /** How many CELL_AUTHORIZE cells have we received, ever? */
46 uint64_t stats_n_authorize_cells_processed = 0;
48 /** Active listener, if any */
49 channel_listener_t *channel_tls_listener = NULL;
51 /* Utility function declarations */
52 static void channel_tls_common_init(channel_tls_t *tlschan);
54 /* channel_tls_t method declarations */
56 static void channel_tls_close_method(channel_t *chan);
57 static const char * channel_tls_describe_transport_method(channel_t *chan);
58 static void channel_tls_free_method(channel_t *chan);
59 static double channel_tls_get_overhead_estimate_method(channel_t *chan);
60 static int
61 channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out);
62 static int
63 channel_tls_get_transport_name_method(channel_t *chan, char **transport_out);
64 static const char *
65 channel_tls_get_remote_descr_method(channel_t *chan, int flags);
66 static int channel_tls_has_queued_writes_method(channel_t *chan);
67 static int channel_tls_is_canonical_method(channel_t *chan, int req);
68 static int
69 channel_tls_matches_extend_info_method(channel_t *chan,
70 extend_info_t *extend_info);
71 static int channel_tls_matches_target_method(channel_t *chan,
72 const tor_addr_t *target);
73 static int channel_tls_num_cells_writeable_method(channel_t *chan);
74 static size_t channel_tls_num_bytes_queued_method(channel_t *chan);
75 static int channel_tls_write_cell_method(channel_t *chan,
76 cell_t *cell);
77 static int channel_tls_write_packed_cell_method(channel_t *chan,
78 packed_cell_t *packed_cell);
79 static int channel_tls_write_var_cell_method(channel_t *chan,
80 var_cell_t *var_cell);
82 /* channel_listener_tls_t method declarations */
84 static void channel_tls_listener_close_method(channel_listener_t *chan_l);
85 static const char *
86 channel_tls_listener_describe_transport_method(channel_listener_t *chan_l);
88 /** Handle incoming cells for the handshake stuff here rather than
89 * passing them on up. */
91 static void channel_tls_process_versions_cell(var_cell_t *cell,
92 channel_tls_t *tlschan);
93 static void channel_tls_process_netinfo_cell(cell_t *cell,
94 channel_tls_t *tlschan);
95 static void channel_tls_process_certs_cell(var_cell_t *cell,
96 channel_tls_t *tlschan);
97 static void channel_tls_process_auth_challenge_cell(var_cell_t *cell,
98 channel_tls_t *tlschan);
99 static void channel_tls_process_authenticate_cell(var_cell_t *cell,
100 channel_tls_t *tlschan);
101 static int command_allowed_before_handshake(uint8_t command);
102 static int enter_v3_handshake_with_cell(var_cell_t *cell,
103 channel_tls_t *tlschan);
106 * Do parts of channel_tls_t initialization common to channel_tls_connect()
107 * and channel_tls_handle_incoming().
110 static void
111 channel_tls_common_init(channel_tls_t *tlschan)
113 channel_t *chan;
115 tor_assert(tlschan);
117 chan = &(tlschan->base_);
118 channel_init(chan);
119 chan->magic = TLS_CHAN_MAGIC;
120 chan->state = CHANNEL_STATE_OPENING;
121 chan->close = channel_tls_close_method;
122 chan->describe_transport = channel_tls_describe_transport_method;
123 chan->free = channel_tls_free_method;
124 chan->get_overhead_estimate = channel_tls_get_overhead_estimate_method;
125 chan->get_remote_addr = channel_tls_get_remote_addr_method;
126 chan->get_remote_descr = channel_tls_get_remote_descr_method;
127 chan->get_transport_name = channel_tls_get_transport_name_method;
128 chan->has_queued_writes = channel_tls_has_queued_writes_method;
129 chan->is_canonical = channel_tls_is_canonical_method;
130 chan->matches_extend_info = channel_tls_matches_extend_info_method;
131 chan->matches_target = channel_tls_matches_target_method;
132 chan->num_bytes_queued = channel_tls_num_bytes_queued_method;
133 chan->num_cells_writeable = channel_tls_num_cells_writeable_method;
134 chan->write_cell = channel_tls_write_cell_method;
135 chan->write_packed_cell = channel_tls_write_packed_cell_method;
136 chan->write_var_cell = channel_tls_write_var_cell_method;
138 chan->cmux = circuitmux_alloc();
139 if (cell_ewma_enabled()) {
140 circuitmux_set_policy(chan->cmux, &ewma_policy);
145 * Start a new TLS channel
147 * Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
148 * handshake with an OR with identity digest <b>id_digest</b>, and wrap
149 * it in a channel_tls_t.
152 channel_t *
153 channel_tls_connect(const tor_addr_t *addr, uint16_t port,
154 const char *id_digest)
156 channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
157 channel_t *chan = &(tlschan->base_);
159 channel_tls_common_init(tlschan);
161 log_debug(LD_CHANNEL,
162 "In channel_tls_connect() for channel %p "
163 "(global id " U64_FORMAT ")",
164 tlschan,
165 U64_PRINTF_ARG(chan->global_identifier));
167 if (is_local_addr(addr)) {
168 log_debug(LD_CHANNEL,
169 "Marking new outgoing channel " U64_FORMAT " at %p as local",
170 U64_PRINTF_ARG(chan->global_identifier), chan);
171 channel_mark_local(chan);
172 } else {
173 log_debug(LD_CHANNEL,
174 "Marking new outgoing channel " U64_FORMAT " at %p as remote",
175 U64_PRINTF_ARG(chan->global_identifier), chan);
176 channel_mark_remote(chan);
179 channel_mark_outgoing(chan);
181 /* Set up or_connection stuff */
182 tlschan->conn = connection_or_connect(addr, port, id_digest, tlschan);
183 /* connection_or_connect() will fill in tlschan->conn */
184 if (!(tlschan->conn)) {
185 chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
186 channel_change_state(chan, CHANNEL_STATE_ERROR);
187 goto err;
190 log_debug(LD_CHANNEL,
191 "Got orconn %p for channel with global id " U64_FORMAT,
192 tlschan->conn, U64_PRINTF_ARG(chan->global_identifier));
194 goto done;
196 err:
197 circuitmux_free(chan->cmux);
198 tor_free(tlschan);
199 chan = NULL;
201 done:
202 /* If we got one, we should register it */
203 if (chan) channel_register(chan);
205 return chan;
209 * Return the current channel_tls_t listener
211 * Returns the current channel listener for incoming TLS connections, or
212 * NULL if none has been established
215 channel_listener_t *
216 channel_tls_get_listener(void)
218 return channel_tls_listener;
222 * Start a channel_tls_t listener if necessary
224 * Return the current channel_tls_t listener, or start one if we haven't yet,
225 * and return that.
228 channel_listener_t *
229 channel_tls_start_listener(void)
231 channel_listener_t *listener;
233 if (!channel_tls_listener) {
234 listener = tor_malloc_zero(sizeof(*listener));
235 channel_init_listener(listener);
236 listener->state = CHANNEL_LISTENER_STATE_LISTENING;
237 listener->close = channel_tls_listener_close_method;
238 listener->describe_transport =
239 channel_tls_listener_describe_transport_method;
241 channel_tls_listener = listener;
243 log_debug(LD_CHANNEL,
244 "Starting TLS channel listener %p with global id " U64_FORMAT,
245 listener, U64_PRINTF_ARG(listener->global_identifier));
247 channel_listener_register(listener);
248 } else listener = channel_tls_listener;
250 return listener;
254 * Free everything on shutdown
256 * Not much to do here, since channel_free_all() takes care of a lot, but let's
257 * get rid of the listener.
260 void
261 channel_tls_free_all(void)
263 channel_listener_t *old_listener = NULL;
265 log_debug(LD_CHANNEL,
266 "Shutting down TLS channels...");
268 if (channel_tls_listener) {
270 * When we close it, channel_tls_listener will get nulled out, so save
271 * a pointer so we can free it.
273 old_listener = channel_tls_listener;
274 log_debug(LD_CHANNEL,
275 "Closing channel_tls_listener with ID " U64_FORMAT
276 " at %p.",
277 U64_PRINTF_ARG(old_listener->global_identifier),
278 old_listener);
279 channel_listener_unregister(old_listener);
280 channel_listener_mark_for_close(old_listener);
281 channel_listener_free(old_listener);
282 tor_assert(channel_tls_listener == NULL);
285 log_debug(LD_CHANNEL,
286 "Done shutting down TLS channels");
290 * Create a new channel around an incoming or_connection_t
293 channel_t *
294 channel_tls_handle_incoming(or_connection_t *orconn)
296 channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
297 channel_t *chan = &(tlschan->base_);
299 tor_assert(orconn);
300 tor_assert(!(orconn->chan));
302 channel_tls_common_init(tlschan);
304 /* Link the channel and orconn to each other */
305 tlschan->conn = orconn;
306 orconn->chan = tlschan;
308 if (is_local_addr(&(TO_CONN(orconn)->addr))) {
309 log_debug(LD_CHANNEL,
310 "Marking new incoming channel " U64_FORMAT " at %p as local",
311 U64_PRINTF_ARG(chan->global_identifier), chan);
312 channel_mark_local(chan);
313 } else {
314 log_debug(LD_CHANNEL,
315 "Marking new incoming channel " U64_FORMAT " at %p as remote",
316 U64_PRINTF_ARG(chan->global_identifier), chan);
317 channel_mark_remote(chan);
320 channel_mark_incoming(chan);
322 /* Register it */
323 channel_register(chan);
325 return chan;
328 /*********
329 * Casts *
330 ********/
333 * Cast a channel_tls_t to a channel_t.
336 channel_t *
337 channel_tls_to_base(channel_tls_t *tlschan)
339 if (!tlschan) return NULL;
341 return &(tlschan->base_);
345 * Cast a channel_t to a channel_tls_t, with appropriate type-checking
346 * asserts.
349 channel_tls_t *
350 channel_tls_from_base(channel_t *chan)
352 if (!chan) return NULL;
354 tor_assert(chan->magic == TLS_CHAN_MAGIC);
356 return (channel_tls_t *)(chan);
359 /********************************************
360 * Method implementations for channel_tls_t *
361 *******************************************/
364 * Close a channel_tls_t
366 * This implements the close method for channel_tls_t
369 static void
370 channel_tls_close_method(channel_t *chan)
372 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
374 tor_assert(tlschan);
376 if (tlschan->conn) connection_or_close_normally(tlschan->conn, 1);
377 else {
378 /* Weird - we'll have to change the state ourselves, I guess */
379 log_info(LD_CHANNEL,
380 "Tried to close channel_tls_t %p with NULL conn",
381 tlschan);
382 channel_change_state(chan, CHANNEL_STATE_ERROR);
387 * Describe the transport for a channel_tls_t
389 * This returns the string "TLS channel on connection <id>" to the upper
390 * layer.
393 static const char *
394 channel_tls_describe_transport_method(channel_t *chan)
396 static char *buf = NULL;
397 uint64_t id;
398 channel_tls_t *tlschan;
399 const char *rv = NULL;
401 tor_assert(chan);
403 tlschan = BASE_CHAN_TO_TLS(chan);
405 if (tlschan->conn) {
406 id = TO_CONN(tlschan->conn)->global_identifier;
408 if (buf) tor_free(buf);
409 tor_asprintf(&buf,
410 "TLS channel (connection " U64_FORMAT ")",
411 U64_PRINTF_ARG(id));
413 rv = buf;
414 } else {
415 rv = "TLS channel (no connection)";
418 return rv;
422 * Free a channel_tls_t
424 * This is called by the generic channel layer when freeing a channel_tls_t;
425 * this happens either on a channel which has already reached
426 * CHANNEL_STATE_CLOSED or CHANNEL_STATE_ERROR from channel_run_cleanup() or
427 * on shutdown from channel_free_all(). In the latter case we might still
428 * have an orconn active (which connection_free_all() will get to later),
429 * so we should null out its channel pointer now.
432 static void
433 channel_tls_free_method(channel_t *chan)
435 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
437 tor_assert(tlschan);
439 if (tlschan->conn) {
440 tlschan->conn->chan = NULL;
441 tlschan->conn = NULL;
446 * Get an estimate of the average TLS overhead for the upper layer
449 static double
450 channel_tls_get_overhead_estimate_method(channel_t *chan)
452 double overhead = 1.0f;
453 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
455 tor_assert(tlschan);
456 tor_assert(tlschan->conn);
458 /* Just return 1.0f if we don't have sensible data */
459 if (tlschan->conn->bytes_xmitted > 0 &&
460 tlschan->conn->bytes_xmitted_by_tls >=
461 tlschan->conn->bytes_xmitted) {
462 overhead = ((double)(tlschan->conn->bytes_xmitted_by_tls)) /
463 ((double)(tlschan->conn->bytes_xmitted));
466 * Never estimate more than 2.0; otherwise we get silly large estimates
467 * at the very start of a new TLS connection.
469 if (overhead > 2.0f) overhead = 2.0f;
472 log_debug(LD_CHANNEL,
473 "Estimated overhead ratio for TLS chan " U64_FORMAT " is %f",
474 U64_PRINTF_ARG(chan->global_identifier), overhead);
476 return overhead;
480 * Get the remote address of a channel_tls_t
482 * This implements the get_remote_addr method for channel_tls_t; copy the
483 * remote endpoint of the channel to addr_out and return 1 (always
484 * succeeds for this transport).
487 static int
488 channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out)
490 int rv = 0;
491 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
493 tor_assert(tlschan);
494 tor_assert(addr_out);
496 if (tlschan->conn) {
497 tor_addr_copy(addr_out, &(TO_CONN(tlschan->conn)->addr));
498 rv = 1;
499 } else tor_addr_make_unspec(addr_out);
501 return rv;
505 * Get the name of the pluggable transport used by a channel_tls_t.
507 * This implements the get_transport_name for channel_tls_t. If the
508 * channel uses a pluggable transport, copy its name to
509 * <b>transport_out</b> and return 0. If the channel did not use a
510 * pluggable transport, return -1. */
512 static int
513 channel_tls_get_transport_name_method(channel_t *chan, char **transport_out)
515 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
517 tor_assert(tlschan);
518 tor_assert(transport_out);
519 tor_assert(tlschan->conn);
521 if (!tlschan->conn->ext_or_transport)
522 return -1;
524 *transport_out = tor_strdup(tlschan->conn->ext_or_transport);
525 return 0;
529 * Get endpoint description of a channel_tls_t
531 * This implements the get_remote_descr method for channel_tls_t; it returns
532 * a text description of the remote endpoint of the channel suitable for use
533 * in log messages. The req parameter is 0 for the canonical address or 1 for
534 * the actual address seen.
537 static const char *
538 channel_tls_get_remote_descr_method(channel_t *chan, int flags)
540 #define MAX_DESCR_LEN 32
542 static char buf[MAX_DESCR_LEN + 1];
543 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
544 connection_t *conn;
545 const char *answer = NULL;
546 char *addr_str;
548 tor_assert(tlschan);
550 if (tlschan->conn) {
551 conn = TO_CONN(tlschan->conn);
552 switch (flags) {
553 case 0:
554 /* Canonical address with port*/
555 tor_snprintf(buf, MAX_DESCR_LEN + 1,
556 "%s:%u", conn->address, conn->port);
557 answer = buf;
558 break;
559 case GRD_FLAG_ORIGINAL:
560 /* Actual address with port */
561 addr_str = tor_dup_addr(&(tlschan->conn->real_addr));
562 tor_snprintf(buf, MAX_DESCR_LEN + 1,
563 "%s:%u", addr_str, conn->port);
564 tor_free(addr_str);
565 answer = buf;
566 break;
567 case GRD_FLAG_ADDR_ONLY:
568 /* Canonical address, no port */
569 strlcpy(buf, conn->address, sizeof(buf));
570 answer = buf;
571 break;
572 case GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY:
573 /* Actual address, no port */
574 addr_str = tor_dup_addr(&(tlschan->conn->real_addr));
575 strlcpy(buf, addr_str, sizeof(buf));
576 tor_free(addr_str);
577 answer = buf;
578 break;
579 default:
580 /* Something's broken in channel.c */
581 tor_assert(1);
583 } else {
584 strlcpy(buf, "(No connection)", sizeof(buf));
585 answer = buf;
588 return answer;
592 * Tell the upper layer if we have queued writes
594 * This implements the has_queued_writes method for channel_tls t_; it returns
595 * 1 iff we have queued writes on the outbuf of the underlying or_connection_t.
598 static int
599 channel_tls_has_queued_writes_method(channel_t *chan)
601 size_t outbuf_len;
602 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
604 tor_assert(tlschan);
605 if (!(tlschan->conn)) {
606 log_info(LD_CHANNEL,
607 "something called has_queued_writes on a tlschan "
608 "(%p with ID " U64_FORMAT " but no conn",
609 chan, U64_PRINTF_ARG(chan->global_identifier));
612 outbuf_len = (tlschan->conn != NULL) ?
613 connection_get_outbuf_len(TO_CONN(tlschan->conn)) :
616 return (outbuf_len > 0);
620 * Tell the upper layer if we're canonical
622 * This implements the is_canonical method for channel_tls_t; if req is zero,
623 * it returns whether this is a canonical channel, and if it is one it returns
624 * whether that can be relied upon.
627 static int
628 channel_tls_is_canonical_method(channel_t *chan, int req)
630 int answer = 0;
631 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
633 tor_assert(tlschan);
635 if (tlschan->conn) {
636 switch (req) {
637 case 0:
638 answer = tlschan->conn->is_canonical;
639 break;
640 case 1:
642 * Is the is_canonical bit reliable? In protocols version 2 and up
643 * we get the canonical address from a NETINFO cell, but in older
644 * versions it might be based on an obsolete descriptor.
646 answer = (tlschan->conn->link_proto >= 2);
647 break;
648 default:
649 /* This shouldn't happen; channel.c is broken if it does */
650 tor_assert(1);
653 /* else return 0 for tlschan->conn == NULL */
655 return answer;
659 * Check if we match an extend_info_t
661 * This implements the matches_extend_info method for channel_tls_t; the upper
662 * layer wants to know if this channel matches an extend_info_t.
665 static int
666 channel_tls_matches_extend_info_method(channel_t *chan,
667 extend_info_t *extend_info)
669 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
671 tor_assert(tlschan);
672 tor_assert(extend_info);
674 /* Never match if we have no conn */
675 if (!(tlschan->conn)) {
676 log_info(LD_CHANNEL,
677 "something called matches_extend_info on a tlschan "
678 "(%p with ID " U64_FORMAT " but no conn",
679 chan, U64_PRINTF_ARG(chan->global_identifier));
680 return 0;
683 return (tor_addr_eq(&(extend_info->addr),
684 &(TO_CONN(tlschan->conn)->addr)) &&
685 (extend_info->port == TO_CONN(tlschan->conn)->port));
689 * Check if we match a target address; return true iff we do.
691 * This implements the matches_target method for channel_tls t_; the upper
692 * layer wants to know if this channel matches a target address when extending
693 * a circuit.
696 static int
697 channel_tls_matches_target_method(channel_t *chan,
698 const tor_addr_t *target)
700 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
702 tor_assert(tlschan);
703 tor_assert(target);
705 /* Never match if we have no conn */
706 if (!(tlschan->conn)) {
707 log_info(LD_CHANNEL,
708 "something called matches_target on a tlschan "
709 "(%p with ID " U64_FORMAT " but no conn",
710 chan, U64_PRINTF_ARG(chan->global_identifier));
711 return 0;
714 return tor_addr_eq(&(tlschan->conn->real_addr), target);
718 * Tell the upper layer how many bytes we have queued and not yet
719 * sent.
722 static size_t
723 channel_tls_num_bytes_queued_method(channel_t *chan)
725 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
727 tor_assert(tlschan);
728 tor_assert(tlschan->conn);
730 return connection_get_outbuf_len(TO_CONN(tlschan->conn));
734 * Tell the upper layer how many cells we can accept to write
736 * This implements the num_cells_writeable method for channel_tls_t; it
737 * returns an estimate of the number of cells we can accept with
738 * channel_tls_write_*_cell().
741 static int
742 channel_tls_num_cells_writeable_method(channel_t *chan)
744 size_t outbuf_len;
745 ssize_t n;
746 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
747 size_t cell_network_size;
749 tor_assert(tlschan);
750 tor_assert(tlschan->conn);
752 cell_network_size = get_cell_network_size(tlschan->conn->wide_circ_ids);
753 outbuf_len = connection_get_outbuf_len(TO_CONN(tlschan->conn));
754 /* Get the number of cells */
755 n = CEIL_DIV(OR_CONN_HIGHWATER - outbuf_len, cell_network_size);
756 if (n < 0) n = 0;
757 #if SIZEOF_SIZE_T > SIZEOF_INT
758 if (n > INT_MAX) n = INT_MAX;
759 #endif
761 return (int)n;
765 * Write a cell to a channel_tls_t
767 * This implements the write_cell method for channel_tls_t; given a
768 * channel_tls_t and a cell_t, transmit the cell_t.
771 static int
772 channel_tls_write_cell_method(channel_t *chan, cell_t *cell)
774 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
775 int written = 0;
777 tor_assert(tlschan);
778 tor_assert(cell);
780 if (tlschan->conn) {
781 connection_or_write_cell_to_buf(cell, tlschan->conn);
782 ++written;
783 } else {
784 log_info(LD_CHANNEL,
785 "something called write_cell on a tlschan "
786 "(%p with ID " U64_FORMAT " but no conn",
787 chan, U64_PRINTF_ARG(chan->global_identifier));
790 return written;
794 * Write a packed cell to a channel_tls_t
796 * This implements the write_packed_cell method for channel_tls_t; given a
797 * channel_tls_t and a packed_cell_t, transmit the packed_cell_t.
800 static int
801 channel_tls_write_packed_cell_method(channel_t *chan,
802 packed_cell_t *packed_cell)
804 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
805 size_t cell_network_size = get_cell_network_size(chan->wide_circ_ids);
806 int written = 0;
808 tor_assert(tlschan);
809 tor_assert(packed_cell);
811 if (tlschan->conn) {
812 connection_write_to_buf(packed_cell->body, cell_network_size,
813 TO_CONN(tlschan->conn));
815 /* This is where the cell is finished; used to be done from relay.c */
816 packed_cell_free(packed_cell);
817 ++written;
818 } else {
819 log_info(LD_CHANNEL,
820 "something called write_packed_cell on a tlschan "
821 "(%p with ID " U64_FORMAT " but no conn",
822 chan, U64_PRINTF_ARG(chan->global_identifier));
825 return written;
829 * Write a variable-length cell to a channel_tls_t
831 * This implements the write_var_cell method for channel_tls_t; given a
832 * channel_tls_t and a var_cell_t, transmit the var_cell_t.
835 static int
836 channel_tls_write_var_cell_method(channel_t *chan, var_cell_t *var_cell)
838 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
839 int written = 0;
841 tor_assert(tlschan);
842 tor_assert(var_cell);
844 if (tlschan->conn) {
845 connection_or_write_var_cell_to_buf(var_cell, tlschan->conn);
846 ++written;
847 } else {
848 log_info(LD_CHANNEL,
849 "something called write_var_cell on a tlschan "
850 "(%p with ID " U64_FORMAT " but no conn",
851 chan, U64_PRINTF_ARG(chan->global_identifier));
854 return written;
857 /*************************************************
858 * Method implementations for channel_listener_t *
859 ************************************************/
862 * Close a channel_listener_t
864 * This implements the close method for channel_listener_t
867 static void
868 channel_tls_listener_close_method(channel_listener_t *chan_l)
870 tor_assert(chan_l);
873 * Listeners we just go ahead and change state through to CLOSED, but
874 * make sure to check if they're channel_tls_listener to NULL it out.
876 if (chan_l == channel_tls_listener)
877 channel_tls_listener = NULL;
879 if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
880 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
881 chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
882 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
885 if (chan_l->incoming_list) {
886 SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
887 channel_t *, ichan) {
888 channel_mark_for_close(ichan);
889 } SMARTLIST_FOREACH_END(ichan);
891 smartlist_free(chan_l->incoming_list);
892 chan_l->incoming_list = NULL;
895 if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
896 chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
897 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
902 * Describe the transport for a channel_listener_t
904 * This returns the string "TLS channel (listening)" to the upper
905 * layer.
908 static const char *
909 channel_tls_listener_describe_transport_method(channel_listener_t *chan_l)
911 tor_assert(chan_l);
913 return "TLS channel (listening)";
916 /*******************************************************
917 * Functions for handling events on an or_connection_t *
918 ******************************************************/
921 * Handle an orconn state change
923 * This function will be called by connection_or.c when the or_connection_t
924 * associated with this channel_tls_t changes state.
927 void
928 channel_tls_handle_state_change_on_orconn(channel_tls_t *chan,
929 or_connection_t *conn,
930 uint8_t old_state,
931 uint8_t state)
933 channel_t *base_chan;
935 tor_assert(chan);
936 tor_assert(conn);
937 tor_assert(conn->chan == chan);
938 tor_assert(chan->conn == conn);
939 /* Shut the compiler up without triggering -Wtautological-compare */
940 (void)old_state;
942 base_chan = TLS_CHAN_TO_BASE(chan);
944 /* Make sure the base connection state makes sense - shouldn't be error
945 * or closed. */
947 tor_assert(CHANNEL_IS_OPENING(base_chan) ||
948 CHANNEL_IS_OPEN(base_chan) ||
949 CHANNEL_IS_MAINT(base_chan) ||
950 CHANNEL_IS_CLOSING(base_chan));
952 /* Did we just go to state open? */
953 if (state == OR_CONN_STATE_OPEN) {
955 * We can go to CHANNEL_STATE_OPEN from CHANNEL_STATE_OPENING or
956 * CHANNEL_STATE_MAINT on this.
958 channel_change_state(base_chan, CHANNEL_STATE_OPEN);
959 /* We might have just become writeable; check and tell the scheduler */
960 if (connection_or_num_cells_writeable(conn) > 0) {
961 scheduler_channel_wants_writes(base_chan);
963 } else {
965 * Not open, so from CHANNEL_STATE_OPEN we go to CHANNEL_STATE_MAINT,
966 * otherwise no change.
968 if (CHANNEL_IS_OPEN(base_chan)) {
969 channel_change_state(base_chan, CHANNEL_STATE_MAINT);
974 #ifdef KEEP_TIMING_STATS
977 * Timing states wrapper
979 * This is a wrapper function around the actual function that processes the
980 * <b>cell</b> that just arrived on <b>chan</b>. Increment <b>*time</b>
981 * by the number of microseconds used by the call to <b>*func(cell, chan)</b>.
984 static void
985 channel_tls_time_process_cell(cell_t *cell, channel_tls_t *chan, int *time,
986 void (*func)(cell_t *, channel_tls_t *))
988 struct timeval start, end;
989 long time_passed;
991 tor_gettimeofday(&start);
993 (*func)(cell, chan);
995 tor_gettimeofday(&end);
996 time_passed = tv_udiff(&start, &end) ;
998 if (time_passed > 10000) { /* more than 10ms */
999 log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
1002 if (time_passed < 0) {
1003 log_info(LD_GENERAL,"That call took us back in time!");
1004 time_passed = 0;
1007 *time += time_passed;
1009 #endif
1012 * Handle an incoming cell on a channel_tls_t
1014 * This is called from connection_or.c to handle an arriving cell; it checks
1015 * for cell types specific to the handshake for this transport protocol and
1016 * handles them, and queues all other cells to the channel_t layer, which
1017 * eventually will hand them off to command.c.
1020 void
1021 channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
1023 channel_tls_t *chan;
1024 int handshaking;
1026 #ifdef KEEP_TIMING_STATS
1027 #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
1028 ++num ## tp; \
1029 channel_tls_time_process_cell(cl, cn, & tp ## time , \
1030 channel_tls_process_ ## tp ## _cell); \
1031 } STMT_END
1032 #else
1033 #define PROCESS_CELL(tp, cl, cn) channel_tls_process_ ## tp ## _cell(cl, cn)
1034 #endif
1036 tor_assert(cell);
1037 tor_assert(conn);
1039 chan = conn->chan;
1041 if (!chan) {
1042 log_warn(LD_CHANNEL,
1043 "Got a cell_t on an OR connection with no channel");
1044 return;
1047 handshaking = (TO_CONN(conn)->state != OR_CONN_STATE_OPEN);
1049 if (conn->base_.marked_for_close)
1050 return;
1052 /* Reject all but VERSIONS and NETINFO when handshaking. */
1053 /* (VERSIONS should actually be impossible; it's variable-length.) */
1054 if (handshaking && cell->command != CELL_VERSIONS &&
1055 cell->command != CELL_NETINFO) {
1056 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1057 "Received unexpected cell command %d in chan state %s / "
1058 "conn state %s; closing the connection.",
1059 (int)cell->command,
1060 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1061 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state));
1062 connection_or_close_for_error(conn, 0);
1063 return;
1066 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
1067 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 1);
1069 switch (cell->command) {
1070 case CELL_PADDING:
1071 ++stats_n_padding_cells_processed;
1072 /* do nothing */
1073 break;
1074 case CELL_VERSIONS:
1075 tor_fragile_assert();
1076 break;
1077 case CELL_NETINFO:
1078 ++stats_n_netinfo_cells_processed;
1079 PROCESS_CELL(netinfo, cell, chan);
1080 break;
1081 case CELL_CREATE:
1082 case CELL_CREATE_FAST:
1083 case CELL_CREATED:
1084 case CELL_CREATED_FAST:
1085 case CELL_RELAY:
1086 case CELL_RELAY_EARLY:
1087 case CELL_DESTROY:
1088 case CELL_CREATE2:
1089 case CELL_CREATED2:
1091 * These are all transport independent and we pass them up through the
1092 * channel_t mechanism. They are ultimately handled in command.c.
1094 channel_queue_cell(TLS_CHAN_TO_BASE(chan), cell);
1095 break;
1096 default:
1097 log_fn(LOG_INFO, LD_PROTOCOL,
1098 "Cell of unknown type (%d) received in channeltls.c. "
1099 "Dropping.",
1100 cell->command);
1101 break;
1106 * Handle an incoming variable-length cell on a channel_tls_t
1108 * Process a <b>var_cell</b> that was just received on <b>conn</b>. Keep
1109 * internal statistics about how many of each cell we've processed so far
1110 * this second, and the total number of microseconds it took to
1111 * process each type of cell. All the var_cell commands are handshake-
1112 * related and live below the channel_t layer, so no variable-length
1113 * cells ever get delivered in the current implementation, but I've left
1114 * the mechanism in place for future use.
1117 void
1118 channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
1120 channel_tls_t *chan;
1122 #ifdef KEEP_TIMING_STATS
1123 /* how many of each cell have we seen so far this second? needs better
1124 * name. */
1125 static int num_versions = 0, num_certs = 0;
1126 static time_t current_second = 0; /* from previous calls to time */
1127 time_t now = time(NULL);
1129 if (current_second == 0) current_second = now;
1130 if (now > current_second) { /* the second has rolled over */
1131 /* print stats */
1132 log_info(LD_OR,
1133 "At end of second: %d versions (%d ms), %d certs (%d ms)",
1134 num_versions, versions_time / ((now - current_second) * 1000),
1135 num_certs, certs_time / ((now - current_second) * 1000));
1137 num_versions = num_certs = 0;
1138 versions_time = certs_time = 0;
1140 /* remember which second it is, for next time */
1141 current_second = now;
1143 #endif
1145 tor_assert(var_cell);
1146 tor_assert(conn);
1148 chan = conn->chan;
1150 if (!chan) {
1151 log_warn(LD_CHANNEL,
1152 "Got a var_cell_t on an OR connection with no channel");
1153 return;
1156 if (TO_CONN(conn)->marked_for_close)
1157 return;
1159 switch (TO_CONN(conn)->state) {
1160 case OR_CONN_STATE_OR_HANDSHAKING_V2:
1161 if (var_cell->command != CELL_VERSIONS) {
1162 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1163 "Received a cell with command %d in unexpected "
1164 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1165 "closing the connection.",
1166 (int)(var_cell->command),
1167 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1168 TO_CONN(conn)->state,
1169 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1170 (int)(TLS_CHAN_TO_BASE(chan)->state));
1172 * The code in connection_or.c will tell channel_t to close for
1173 * error; it will go to CHANNEL_STATE_CLOSING, and then to
1174 * CHANNEL_STATE_ERROR when conn is closed.
1176 connection_or_close_for_error(conn, 0);
1177 return;
1179 break;
1180 case OR_CONN_STATE_TLS_HANDSHAKING:
1181 /* If we're using bufferevents, it's entirely possible for us to
1182 * notice "hey, data arrived!" before we notice "hey, the handshake
1183 * finished!" And we need to be accepting both at once to handle both
1184 * the v2 and v3 handshakes. */
1186 /* fall through */
1187 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
1188 if (!(command_allowed_before_handshake(var_cell->command))) {
1189 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1190 "Received a cell with command %d in unexpected "
1191 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1192 "closing the connection.",
1193 (int)(var_cell->command),
1194 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1195 (int)(TO_CONN(conn)->state),
1196 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1197 (int)(TLS_CHAN_TO_BASE(chan)->state));
1198 /* see above comment about CHANNEL_STATE_ERROR */
1199 connection_or_close_for_error(conn, 0);
1200 return;
1201 } else {
1202 if (enter_v3_handshake_with_cell(var_cell, chan) < 0)
1203 return;
1205 break;
1206 case OR_CONN_STATE_OR_HANDSHAKING_V3:
1207 if (var_cell->command != CELL_AUTHENTICATE)
1208 or_handshake_state_record_var_cell(conn, conn->handshake_state,
1209 var_cell, 1);
1210 break; /* Everything is allowed */
1211 case OR_CONN_STATE_OPEN:
1212 if (conn->link_proto < 3) {
1213 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1214 "Received a variable-length cell with command %d in orconn "
1215 "state %s [%d], channel state %s [%d] with link protocol %d; "
1216 "ignoring it.",
1217 (int)(var_cell->command),
1218 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1219 (int)(TO_CONN(conn)->state),
1220 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1221 (int)(TLS_CHAN_TO_BASE(chan)->state),
1222 (int)(conn->link_proto));
1223 return;
1225 break;
1226 default:
1227 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1228 "Received var-length cell with command %d in unexpected "
1229 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1230 "ignoring it.",
1231 (int)(var_cell->command),
1232 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1233 (int)(TO_CONN(conn)->state),
1234 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1235 (int)(TLS_CHAN_TO_BASE(chan)->state));
1236 return;
1239 /* Now handle the cell */
1241 switch (var_cell->command) {
1242 case CELL_VERSIONS:
1243 ++stats_n_versions_cells_processed;
1244 PROCESS_CELL(versions, var_cell, chan);
1245 break;
1246 case CELL_VPADDING:
1247 ++stats_n_vpadding_cells_processed;
1248 /* Do nothing */
1249 break;
1250 case CELL_CERTS:
1251 ++stats_n_certs_cells_processed;
1252 PROCESS_CELL(certs, var_cell, chan);
1253 break;
1254 case CELL_AUTH_CHALLENGE:
1255 ++stats_n_auth_challenge_cells_processed;
1256 PROCESS_CELL(auth_challenge, var_cell, chan);
1257 break;
1258 case CELL_AUTHENTICATE:
1259 ++stats_n_authenticate_cells_processed;
1260 PROCESS_CELL(authenticate, var_cell, chan);
1261 break;
1262 case CELL_AUTHORIZE:
1263 ++stats_n_authorize_cells_processed;
1264 /* Ignored so far. */
1265 break;
1266 default:
1267 log_fn(LOG_INFO, LD_PROTOCOL,
1268 "Variable-length cell of unknown type (%d) received.",
1269 (int)(var_cell->command));
1270 break;
1275 * Update channel marks after connection_or.c has changed an address
1277 * This is called from connection_or_init_conn_from_address() after the
1278 * connection's _base.addr or real_addr fields have potentially been changed
1279 * so we can recalculate the local mark. Notably, this happens when incoming
1280 * connections are reverse-proxied and we only learn the real address of the
1281 * remote router by looking it up in the consensus after we finish the
1282 * handshake and know an authenticated identity digest.
1285 void
1286 channel_tls_update_marks(or_connection_t *conn)
1288 channel_t *chan = NULL;
1290 tor_assert(conn);
1291 tor_assert(conn->chan);
1293 chan = TLS_CHAN_TO_BASE(conn->chan);
1295 if (is_local_addr(&(TO_CONN(conn)->addr))) {
1296 if (!channel_is_local(chan)) {
1297 log_debug(LD_CHANNEL,
1298 "Marking channel " U64_FORMAT " at %p as local",
1299 U64_PRINTF_ARG(chan->global_identifier), chan);
1300 channel_mark_local(chan);
1302 } else {
1303 if (channel_is_local(chan)) {
1304 log_debug(LD_CHANNEL,
1305 "Marking channel " U64_FORMAT " at %p as remote",
1306 U64_PRINTF_ARG(chan->global_identifier), chan);
1307 channel_mark_remote(chan);
1313 * Check if this cell type is allowed before the handshake is finished
1315 * Return true if <b>command</b> is a cell command that's allowed to start a
1316 * V3 handshake.
1319 static int
1320 command_allowed_before_handshake(uint8_t command)
1322 switch (command) {
1323 case CELL_VERSIONS:
1324 case CELL_VPADDING:
1325 case CELL_AUTHORIZE:
1326 return 1;
1327 default:
1328 return 0;
1333 * Start a V3 handshake on an incoming connection
1335 * Called when we as a server receive an appropriate cell while waiting
1336 * either for a cell or a TLS handshake. Set the connection's state to
1337 * "handshaking_v3', initializes the or_handshake_state field as needed,
1338 * and add the cell to the hash of incoming cells.)
1341 static int
1342 enter_v3_handshake_with_cell(var_cell_t *cell, channel_tls_t *chan)
1344 int started_here = 0;
1346 tor_assert(cell);
1347 tor_assert(chan);
1348 tor_assert(chan->conn);
1350 started_here = connection_or_nonopen_was_started_here(chan->conn);
1352 tor_assert(TO_CONN(chan->conn)->state == OR_CONN_STATE_TLS_HANDSHAKING ||
1353 TO_CONN(chan->conn)->state ==
1354 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1356 if (started_here) {
1357 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1358 "Received a cell while TLS-handshaking, not in "
1359 "OR_HANDSHAKING_V3, on a connection we originated.");
1361 connection_or_block_renegotiation(chan->conn);
1362 chan->conn->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
1363 if (connection_init_or_handshake_state(chan->conn, started_here) < 0) {
1364 connection_or_close_for_error(chan->conn, 0);
1365 return -1;
1367 or_handshake_state_record_var_cell(chan->conn,
1368 chan->conn->handshake_state, cell, 1);
1369 return 0;
1373 * Process a 'versions' cell.
1375 * This function is called to handle an incoming VERSIONS cell; the current
1376 * link protocol version must be 0 to indicate that no version has yet been
1377 * negotiated. We compare the versions in the cell to the list of versions
1378 * we support, pick the highest version we have in common, and continue the
1379 * negotiation from there.
1382 static void
1383 channel_tls_process_versions_cell(var_cell_t *cell, channel_tls_t *chan)
1385 int highest_supported_version = 0;
1386 int started_here = 0;
1388 tor_assert(cell);
1389 tor_assert(chan);
1390 tor_assert(chan->conn);
1392 if ((cell->payload_len % 2) == 1) {
1393 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1394 "Received a VERSION cell with odd payload length %d; "
1395 "closing connection.",cell->payload_len);
1396 connection_or_close_for_error(chan->conn, 0);
1397 return;
1400 started_here = connection_or_nonopen_was_started_here(chan->conn);
1402 if (chan->conn->link_proto != 0 ||
1403 (chan->conn->handshake_state &&
1404 chan->conn->handshake_state->received_versions)) {
1405 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1406 "Received a VERSIONS cell on a connection with its version "
1407 "already set to %d; dropping",
1408 (int)(chan->conn->link_proto));
1409 return;
1411 switch (chan->conn->base_.state)
1413 case OR_CONN_STATE_OR_HANDSHAKING_V2:
1414 case OR_CONN_STATE_OR_HANDSHAKING_V3:
1415 break;
1416 case OR_CONN_STATE_TLS_HANDSHAKING:
1417 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
1418 default:
1419 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1420 "VERSIONS cell while in unexpected state");
1421 return;
1424 tor_assert(chan->conn->handshake_state);
1427 int i;
1428 const uint8_t *cp = cell->payload;
1429 for (i = 0; i < cell->payload_len / 2; ++i, cp += 2) {
1430 uint16_t v = ntohs(get_uint16(cp));
1431 if (is_or_protocol_version_known(v) && v > highest_supported_version)
1432 highest_supported_version = v;
1435 if (!highest_supported_version) {
1436 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1437 "Couldn't find a version in common between my version list and the "
1438 "list in the VERSIONS cell; closing connection.");
1439 connection_or_close_for_error(chan->conn, 0);
1440 return;
1441 } else if (highest_supported_version == 1) {
1442 /* Negotiating version 1 makes no sense, since version 1 has no VERSIONS
1443 * cells. */
1444 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1445 "Used version negotiation protocol to negotiate a v1 connection. "
1446 "That's crazily non-compliant. Closing connection.");
1447 connection_or_close_for_error(chan->conn, 0);
1448 return;
1449 } else if (highest_supported_version < 3 &&
1450 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1451 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1452 "Negotiated link protocol 2 or lower after doing a v3 TLS "
1453 "handshake. Closing connection.");
1454 connection_or_close_for_error(chan->conn, 0);
1455 return;
1456 } else if (highest_supported_version != 2 &&
1457 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V2) {
1458 /* XXXX This should eventually be a log_protocol_warn */
1459 log_fn(LOG_WARN, LD_OR,
1460 "Negotiated link with non-2 protocol after doing a v2 TLS "
1461 "handshake with %s. Closing connection.",
1462 fmt_addr(&chan->conn->base_.addr));
1463 connection_or_close_for_error(chan->conn, 0);
1464 return;
1467 rep_hist_note_negotiated_link_proto(highest_supported_version, started_here);
1469 chan->conn->link_proto = highest_supported_version;
1470 chan->conn->handshake_state->received_versions = 1;
1472 if (chan->conn->link_proto == 2) {
1473 log_info(LD_OR,
1474 "Negotiated version %d with %s:%d; sending NETINFO.",
1475 highest_supported_version,
1476 safe_str_client(chan->conn->base_.address),
1477 chan->conn->base_.port);
1479 if (connection_or_send_netinfo(chan->conn) < 0) {
1480 connection_or_close_for_error(chan->conn, 0);
1481 return;
1483 } else {
1484 const int send_versions = !started_here;
1485 /* If we want to authenticate, send a CERTS cell */
1486 const int send_certs = !started_here || public_server_mode(get_options());
1487 /* If we're a host that got a connection, ask for authentication. */
1488 const int send_chall = !started_here;
1489 /* If our certs cell will authenticate us, we can send a netinfo cell
1490 * right now. */
1491 const int send_netinfo = !started_here;
1492 const int send_any =
1493 send_versions || send_certs || send_chall || send_netinfo;
1494 tor_assert(chan->conn->link_proto >= 3);
1496 log_info(LD_OR,
1497 "Negotiated version %d with %s:%d; %s%s%s%s%s",
1498 highest_supported_version,
1499 safe_str_client(chan->conn->base_.address),
1500 chan->conn->base_.port,
1501 send_any ? "Sending cells:" : "Waiting for CERTS cell",
1502 send_versions ? " VERSIONS" : "",
1503 send_certs ? " CERTS" : "",
1504 send_chall ? " AUTH_CHALLENGE" : "",
1505 send_netinfo ? " NETINFO" : "");
1507 #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
1508 if (1) {
1509 connection_or_close_normally(chan->conn, 1);
1510 return;
1512 #endif
1514 if (send_versions) {
1515 if (connection_or_send_versions(chan->conn, 1) < 0) {
1516 log_warn(LD_OR, "Couldn't send versions cell");
1517 connection_or_close_for_error(chan->conn, 0);
1518 return;
1522 /* We set this after sending the verions cell. */
1523 /*XXXXX symbolic const.*/
1524 chan->base_.wide_circ_ids =
1525 chan->conn->link_proto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
1526 chan->conn->wide_circ_ids = chan->base_.wide_circ_ids;
1528 if (send_certs) {
1529 if (connection_or_send_certs_cell(chan->conn) < 0) {
1530 log_warn(LD_OR, "Couldn't send certs cell");
1531 connection_or_close_for_error(chan->conn, 0);
1532 return;
1535 if (send_chall) {
1536 if (connection_or_send_auth_challenge_cell(chan->conn) < 0) {
1537 log_warn(LD_OR, "Couldn't send auth_challenge cell");
1538 connection_or_close_for_error(chan->conn, 0);
1539 return;
1542 if (send_netinfo) {
1543 if (connection_or_send_netinfo(chan->conn) < 0) {
1544 log_warn(LD_OR, "Couldn't send netinfo cell");
1545 connection_or_close_for_error(chan->conn, 0);
1546 return;
1553 * Process a 'netinfo' cell
1555 * This function is called to handle an incoming NETINFO cell; read and act
1556 * on its contents, and set the connection state to "open".
1559 static void
1560 channel_tls_process_netinfo_cell(cell_t *cell, channel_tls_t *chan)
1562 time_t timestamp;
1563 uint8_t my_addr_type;
1564 uint8_t my_addr_len;
1565 const uint8_t *my_addr_ptr;
1566 const uint8_t *cp, *end;
1567 uint8_t n_other_addrs;
1568 time_t now = time(NULL);
1570 long apparent_skew = 0;
1571 tor_addr_t my_apparent_addr = TOR_ADDR_NULL;
1573 tor_assert(cell);
1574 tor_assert(chan);
1575 tor_assert(chan->conn);
1577 if (chan->conn->link_proto < 2) {
1578 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1579 "Received a NETINFO cell on %s connection; dropping.",
1580 chan->conn->link_proto == 0 ? "non-versioned" : "a v1");
1581 return;
1583 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
1584 chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
1585 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1586 "Received a NETINFO cell on non-handshaking connection; dropping.");
1587 return;
1589 tor_assert(chan->conn->handshake_state &&
1590 chan->conn->handshake_state->received_versions);
1592 if (chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1593 tor_assert(chan->conn->link_proto >= 3);
1594 if (chan->conn->handshake_state->started_here) {
1595 if (!(chan->conn->handshake_state->authenticated)) {
1596 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1597 "Got a NETINFO cell from server, "
1598 "but no authentication. Closing the connection.");
1599 connection_or_close_for_error(chan->conn, 0);
1600 return;
1602 } else {
1603 /* we're the server. If the client never authenticated, we have
1604 some housekeeping to do.*/
1605 if (!(chan->conn->handshake_state->authenticated)) {
1606 tor_assert(tor_digest_is_zero(
1607 (const char*)(chan->conn->handshake_state->
1608 authenticated_peer_id)));
1609 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), NULL,
1610 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
1612 connection_or_init_conn_from_address(chan->conn,
1613 &(chan->conn->base_.addr),
1614 chan->conn->base_.port,
1615 (const char*)(chan->conn->handshake_state->
1616 authenticated_peer_id),
1622 /* Decode the cell. */
1623 timestamp = ntohl(get_uint32(cell->payload));
1624 if (labs(now - chan->conn->handshake_state->sent_versions_at) < 180) {
1625 apparent_skew = now - timestamp;
1628 my_addr_type = (uint8_t) cell->payload[4];
1629 my_addr_len = (uint8_t) cell->payload[5];
1630 my_addr_ptr = (uint8_t*) cell->payload + 6;
1631 end = cell->payload + CELL_PAYLOAD_SIZE;
1632 cp = cell->payload + 6 + my_addr_len;
1634 /* We used to check:
1635 * if (my_addr_len >= CELL_PAYLOAD_SIZE - 6) {
1637 * This is actually never going to happen, since my_addr_len is at most 255,
1638 * and CELL_PAYLOAD_LEN - 6 is 503. So we know that cp is < end. */
1640 if (my_addr_type == RESOLVED_TYPE_IPV4 && my_addr_len == 4) {
1641 tor_addr_from_ipv4n(&my_apparent_addr, get_uint32(my_addr_ptr));
1642 } else if (my_addr_type == RESOLVED_TYPE_IPV6 && my_addr_len == 16) {
1643 tor_addr_from_ipv6_bytes(&my_apparent_addr, (const char *) my_addr_ptr);
1646 n_other_addrs = (uint8_t) *cp++;
1647 while (n_other_addrs && cp < end-2) {
1648 /* Consider all the other addresses; if any matches, this connection is
1649 * "canonical." */
1650 tor_addr_t addr;
1651 const uint8_t *next =
1652 decode_address_from_payload(&addr, cp, (int)(end-cp));
1653 if (next == NULL) {
1654 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1655 "Bad address in netinfo cell; closing connection.");
1656 connection_or_close_for_error(chan->conn, 0);
1657 return;
1659 if (tor_addr_eq(&addr, &(chan->conn->real_addr))) {
1660 connection_or_set_canonical(chan->conn, 1);
1661 break;
1663 cp = next;
1664 --n_other_addrs;
1667 /* Act on apparent skew. */
1668 /** Warn when we get a netinfo skew with at least this value. */
1669 #define NETINFO_NOTICE_SKEW 3600
1670 if (labs(apparent_skew) > NETINFO_NOTICE_SKEW &&
1671 router_get_by_id_digest(chan->conn->identity_digest)) {
1672 char dbuf[64];
1673 int severity;
1674 /*XXXX be smarter about when everybody says we are skewed. */
1675 if (router_digest_is_trusted_dir(chan->conn->identity_digest))
1676 severity = LOG_WARN;
1677 else
1678 severity = LOG_INFO;
1679 format_time_interval(dbuf, sizeof(dbuf), apparent_skew);
1680 log_fn(severity, LD_GENERAL,
1681 "Received NETINFO cell with skewed time from "
1682 "server at %s:%d. It seems that our clock is %s by %s, or "
1683 "that theirs is %s. Tor requires an accurate clock to work: "
1684 "please check your time and date settings.",
1685 chan->conn->base_.address,
1686 (int)(chan->conn->base_.port),
1687 apparent_skew > 0 ? "ahead" : "behind",
1688 dbuf,
1689 apparent_skew > 0 ? "behind" : "ahead");
1690 if (severity == LOG_WARN) /* only tell the controller if an authority */
1691 control_event_general_status(LOG_WARN,
1692 "CLOCK_SKEW SKEW=%ld SOURCE=OR:%s:%d",
1693 apparent_skew,
1694 chan->conn->base_.address,
1695 chan->conn->base_.port);
1698 /* XXX maybe act on my_apparent_addr, if the source is sufficiently
1699 * trustworthy. */
1701 if (! chan->conn->handshake_state->sent_netinfo) {
1702 /* If we were prepared to authenticate, but we never got an AUTH_CHALLENGE
1703 * cell, then we would not previously have sent a NETINFO cell. Do so
1704 * now. */
1705 if (connection_or_send_netinfo(chan->conn) < 0) {
1706 connection_or_close_for_error(chan->conn, 0);
1707 return;
1711 if (connection_or_set_state_open(chan->conn) < 0) {
1712 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1713 "Got good NETINFO cell from %s:%d; but "
1714 "was unable to make the OR connection become open.",
1715 safe_str_client(chan->conn->base_.address),
1716 chan->conn->base_.port);
1717 connection_or_close_for_error(chan->conn, 0);
1718 } else {
1719 log_info(LD_OR,
1720 "Got good NETINFO cell from %s:%d; OR connection is now "
1721 "open, using protocol version %d. Its ID digest is %s. "
1722 "Our address is apparently %s.",
1723 safe_str_client(chan->conn->base_.address),
1724 chan->conn->base_.port,
1725 (int)(chan->conn->link_proto),
1726 hex_str(TLS_CHAN_TO_BASE(chan)->identity_digest,
1727 DIGEST_LEN),
1728 tor_addr_is_null(&my_apparent_addr) ?
1729 "<none>" : fmt_and_decorate_addr(&my_apparent_addr));
1731 assert_connection_ok(TO_CONN(chan->conn),time(NULL));
1735 * Process a CERTS cell from a channel.
1737 * This function is called to process an incoming CERTS cell on a
1738 * channel_tls_t:
1740 * If the other side should not have sent us a CERTS cell, or the cell is
1741 * malformed, or it is supposed to authenticate the TLS key but it doesn't,
1742 * then mark the connection.
1744 * If the cell has a good cert chain and we're doing a v3 handshake, then
1745 * store the certificates in or_handshake_state. If this is the client side
1746 * of the connection, we then authenticate the server or mark the connection.
1747 * If it's the server side, wait for an AUTHENTICATE cell.
1750 static void
1751 channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
1753 tor_cert_t *link_cert = NULL;
1754 tor_cert_t *id_cert = NULL;
1755 tor_cert_t *auth_cert = NULL;
1756 uint8_t *ptr;
1757 int n_certs, i;
1758 int send_netinfo = 0;
1760 tor_assert(cell);
1761 tor_assert(chan);
1762 tor_assert(chan->conn);
1764 #define ERR(s) \
1765 do { \
1766 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
1767 "Received a bad CERTS cell from %s:%d: %s", \
1768 safe_str(chan->conn->base_.address), \
1769 chan->conn->base_.port, (s)); \
1770 connection_or_close_for_error(chan->conn, 0); \
1771 goto err; \
1772 } while (0)
1774 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
1775 ERR("We're not doing a v3 handshake!");
1776 if (chan->conn->link_proto < 3)
1777 ERR("We're not using link protocol >= 3");
1778 if (chan->conn->handshake_state->received_certs_cell)
1779 ERR("We already got one");
1780 if (chan->conn->handshake_state->authenticated) {
1781 /* Should be unreachable, but let's make sure. */
1782 ERR("We're already authenticated!");
1784 if (cell->payload_len < 1)
1785 ERR("It had no body");
1786 if (cell->circ_id)
1787 ERR("It had a nonzero circuit ID");
1789 n_certs = cell->payload[0];
1790 ptr = cell->payload + 1;
1791 for (i = 0; i < n_certs; ++i) {
1792 uint8_t cert_type;
1793 uint16_t cert_len;
1794 if (cell->payload_len < 3)
1795 goto truncated;
1796 if (ptr > cell->payload + cell->payload_len - 3) {
1797 goto truncated;
1799 cert_type = *ptr;
1800 cert_len = ntohs(get_uint16(ptr+1));
1801 if (cell->payload_len < 3 + cert_len)
1802 goto truncated;
1803 if (ptr > cell->payload + cell->payload_len - cert_len - 3) {
1804 goto truncated;
1806 if (cert_type == OR_CERT_TYPE_TLS_LINK ||
1807 cert_type == OR_CERT_TYPE_ID_1024 ||
1808 cert_type == OR_CERT_TYPE_AUTH_1024) {
1809 tor_cert_t *cert = tor_cert_decode(ptr + 3, cert_len);
1810 if (!cert) {
1811 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1812 "Received undecodable certificate in CERTS cell from %s:%d",
1813 safe_str(chan->conn->base_.address),
1814 chan->conn->base_.port);
1815 } else {
1816 if (cert_type == OR_CERT_TYPE_TLS_LINK) {
1817 if (link_cert) {
1818 tor_cert_free(cert);
1819 ERR("Too many TLS_LINK certificates");
1821 link_cert = cert;
1822 } else if (cert_type == OR_CERT_TYPE_ID_1024) {
1823 if (id_cert) {
1824 tor_cert_free(cert);
1825 ERR("Too many ID_1024 certificates");
1827 id_cert = cert;
1828 } else if (cert_type == OR_CERT_TYPE_AUTH_1024) {
1829 if (auth_cert) {
1830 tor_cert_free(cert);
1831 ERR("Too many AUTH_1024 certificates");
1833 auth_cert = cert;
1834 } else {
1835 tor_cert_free(cert);
1839 ptr += 3 + cert_len;
1840 continue;
1842 truncated:
1843 ERR("It ends in the middle of a certificate");
1846 if (chan->conn->handshake_state->started_here) {
1847 int severity;
1848 if (! (id_cert && link_cert))
1849 ERR("The certs we wanted were missing");
1850 /* Okay. We should be able to check the certificates now. */
1851 if (! tor_tls_cert_matches_key(chan->conn->tls, link_cert)) {
1852 ERR("The link certificate didn't match the TLS public key");
1854 /* Note that this warns more loudly about time and validity if we were
1855 * _trying_ to connect to an authority, not necessarily if we _did_ connect
1856 * to one. */
1857 if (router_digest_is_trusted_dir(
1858 TLS_CHAN_TO_BASE(chan)->identity_digest))
1859 severity = LOG_WARN;
1860 else
1861 severity = LOG_PROTOCOL_WARN;
1863 if (! tor_tls_cert_is_valid(severity, link_cert, id_cert, 0))
1864 ERR("The link certificate was not valid");
1865 if (! tor_tls_cert_is_valid(severity, id_cert, id_cert, 1))
1866 ERR("The ID certificate was not valid");
1868 chan->conn->handshake_state->authenticated = 1;
1870 const digests_t *id_digests = tor_cert_get_id_digests(id_cert);
1871 crypto_pk_t *identity_rcvd;
1872 if (!id_digests)
1873 ERR("Couldn't compute digests for key in ID cert");
1875 identity_rcvd = tor_tls_cert_get_key(id_cert);
1876 if (!identity_rcvd)
1877 ERR("Internal error: Couldn't get RSA key from ID cert.");
1878 memcpy(chan->conn->handshake_state->authenticated_peer_id,
1879 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
1880 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
1881 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
1882 crypto_pk_free(identity_rcvd);
1885 if (connection_or_client_learned_peer_id(chan->conn,
1886 chan->conn->handshake_state->authenticated_peer_id) < 0)
1887 ERR("Problem setting or checking peer id");
1889 log_info(LD_OR,
1890 "Got some good certificates from %s:%d: Authenticated it.",
1891 safe_str(chan->conn->base_.address), chan->conn->base_.port);
1893 chan->conn->handshake_state->id_cert = id_cert;
1894 id_cert = NULL;
1896 if (!public_server_mode(get_options())) {
1897 /* If we initiated the connection and we are not a public server, we
1898 * aren't planning to authenticate at all. At this point we know who we
1899 * are talking to, so we can just send a netinfo now. */
1900 send_netinfo = 1;
1902 } else {
1903 if (! (id_cert && auth_cert))
1904 ERR("The certs we wanted were missing");
1906 /* Remember these certificates so we can check an AUTHENTICATE cell */
1907 if (! tor_tls_cert_is_valid(LOG_PROTOCOL_WARN, auth_cert, id_cert, 1))
1908 ERR("The authentication certificate was not valid");
1909 if (! tor_tls_cert_is_valid(LOG_PROTOCOL_WARN, id_cert, id_cert, 1))
1910 ERR("The ID certificate was not valid");
1912 log_info(LD_OR,
1913 "Got some good certificates from %s:%d: "
1914 "Waiting for AUTHENTICATE.",
1915 safe_str(chan->conn->base_.address),
1916 chan->conn->base_.port);
1917 /* XXXX check more stuff? */
1919 chan->conn->handshake_state->id_cert = id_cert;
1920 chan->conn->handshake_state->auth_cert = auth_cert;
1921 id_cert = auth_cert = NULL;
1924 chan->conn->handshake_state->received_certs_cell = 1;
1926 if (send_netinfo) {
1927 if (connection_or_send_netinfo(chan->conn) < 0) {
1928 log_warn(LD_OR, "Couldn't send netinfo cell");
1929 connection_or_close_for_error(chan->conn, 0);
1930 goto err;
1934 err:
1935 tor_cert_free(id_cert);
1936 tor_cert_free(link_cert);
1937 tor_cert_free(auth_cert);
1938 #undef ERR
1942 * Process an AUTH_CHALLENGE cell from a channel_tls_t
1944 * This function is called to handle an incoming AUTH_CHALLENGE cell on a
1945 * channel_tls_t; if we weren't supposed to get one (for example, because we're
1946 * not the originator of the channel), or it's ill-formed, or we aren't doing
1947 * a v3 handshake, mark the channel. If the cell is well-formed but we don't
1948 * want to authenticate, just drop it. If the cell is well-formed *and* we
1949 * want to authenticate, send an AUTHENTICATE cell and then a NETINFO cell.
1952 static void
1953 channel_tls_process_auth_challenge_cell(var_cell_t *cell, channel_tls_t *chan)
1955 int n_types, i, use_type = -1;
1956 uint8_t *cp;
1958 tor_assert(cell);
1959 tor_assert(chan);
1960 tor_assert(chan->conn);
1962 #define ERR(s) \
1963 do { \
1964 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
1965 "Received a bad AUTH_CHALLENGE cell from %s:%d: %s", \
1966 safe_str(chan->conn->base_.address), \
1967 chan->conn->base_.port, (s)); \
1968 connection_or_close_for_error(chan->conn, 0); \
1969 return; \
1970 } while (0)
1972 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
1973 ERR("We're not currently doing a v3 handshake");
1974 if (chan->conn->link_proto < 3)
1975 ERR("We're not using link protocol >= 3");
1976 if (!(chan->conn->handshake_state->started_here))
1977 ERR("We didn't originate this connection");
1978 if (chan->conn->handshake_state->received_auth_challenge)
1979 ERR("We already received one");
1980 if (!(chan->conn->handshake_state->received_certs_cell))
1981 ERR("We haven't gotten a CERTS cell yet");
1982 if (cell->payload_len < OR_AUTH_CHALLENGE_LEN + 2)
1983 ERR("It was too short");
1984 if (cell->circ_id)
1985 ERR("It had a nonzero circuit ID");
1987 n_types = ntohs(get_uint16(cell->payload + OR_AUTH_CHALLENGE_LEN));
1988 if (cell->payload_len < OR_AUTH_CHALLENGE_LEN + 2 + 2*n_types)
1989 ERR("It looks truncated");
1991 /* Now see if there is an authentication type we can use */
1992 cp = cell->payload+OR_AUTH_CHALLENGE_LEN + 2;
1993 for (i = 0; i < n_types; ++i, cp += 2) {
1994 uint16_t authtype = ntohs(get_uint16(cp));
1995 if (authtype == AUTHTYPE_RSA_SHA256_TLSSECRET)
1996 use_type = authtype;
1999 chan->conn->handshake_state->received_auth_challenge = 1;
2001 if (! public_server_mode(get_options())) {
2002 /* If we're not a public server then we don't want to authenticate on a
2003 connection we originated, and we already sent a NETINFO cell when we
2004 got the CERTS cell. We have nothing more to do. */
2005 return;
2008 if (use_type >= 0) {
2009 log_info(LD_OR,
2010 "Got an AUTH_CHALLENGE cell from %s:%d: Sending "
2011 "authentication",
2012 safe_str(chan->conn->base_.address),
2013 chan->conn->base_.port);
2015 if (connection_or_send_authenticate_cell(chan->conn, use_type) < 0) {
2016 log_warn(LD_OR,
2017 "Couldn't send authenticate cell");
2018 connection_or_close_for_error(chan->conn, 0);
2019 return;
2021 } else {
2022 log_info(LD_OR,
2023 "Got an AUTH_CHALLENGE cell from %s:%d, but we don't "
2024 "know any of its authentication types. Not authenticating.",
2025 safe_str(chan->conn->base_.address),
2026 chan->conn->base_.port);
2029 if (connection_or_send_netinfo(chan->conn) < 0) {
2030 log_warn(LD_OR, "Couldn't send netinfo cell");
2031 connection_or_close_for_error(chan->conn, 0);
2032 return;
2035 #undef ERR
2039 * Process an AUTHENTICATE cell from a channel_tls_t
2041 * If it's ill-formed or we weren't supposed to get one or we're not doing a
2042 * v3 handshake, then mark the connection. If it does not authenticate the
2043 * other side of the connection successfully (because it isn't signed right,
2044 * we didn't get a CERTS cell, etc) mark the connection. Otherwise, accept
2045 * the identity of the router on the other side of the connection.
2048 static void
2049 channel_tls_process_authenticate_cell(var_cell_t *cell, channel_tls_t *chan)
2051 uint8_t expected[V3_AUTH_FIXED_PART_LEN];
2052 const uint8_t *auth;
2053 int authlen;
2055 tor_assert(cell);
2056 tor_assert(chan);
2057 tor_assert(chan->conn);
2059 #define ERR(s) \
2060 do { \
2061 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
2062 "Received a bad AUTHENTICATE cell from %s:%d: %s", \
2063 safe_str(chan->conn->base_.address), \
2064 chan->conn->base_.port, (s)); \
2065 connection_or_close_for_error(chan->conn, 0); \
2066 return; \
2067 } while (0)
2069 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
2070 ERR("We're not doing a v3 handshake");
2071 if (chan->conn->link_proto < 3)
2072 ERR("We're not using link protocol >= 3");
2073 if (chan->conn->handshake_state->started_here)
2074 ERR("We originated this connection");
2075 if (chan->conn->handshake_state->received_authenticate)
2076 ERR("We already got one!");
2077 if (chan->conn->handshake_state->authenticated) {
2078 /* Should be impossible given other checks */
2079 ERR("The peer is already authenticated");
2081 if (!(chan->conn->handshake_state->received_certs_cell))
2082 ERR("We never got a certs cell");
2083 if (chan->conn->handshake_state->auth_cert == NULL)
2084 ERR("We never got an authentication certificate");
2085 if (chan->conn->handshake_state->id_cert == NULL)
2086 ERR("We never got an identity certificate");
2087 if (cell->payload_len < 4)
2088 ERR("Cell was way too short");
2090 auth = cell->payload;
2092 uint16_t type = ntohs(get_uint16(auth));
2093 uint16_t len = ntohs(get_uint16(auth+2));
2094 if (4 + len > cell->payload_len)
2095 ERR("Authenticator was truncated");
2097 if (type != AUTHTYPE_RSA_SHA256_TLSSECRET)
2098 ERR("Authenticator type was not recognized");
2100 auth += 4;
2101 authlen = len;
2104 if (authlen < V3_AUTH_BODY_LEN + 1)
2105 ERR("Authenticator was too short");
2107 if (connection_or_compute_authenticate_cell_body(
2108 chan->conn, expected, sizeof(expected), NULL, 1) < 0)
2109 ERR("Couldn't compute expected AUTHENTICATE cell body");
2111 if (tor_memneq(expected, auth, sizeof(expected)))
2112 ERR("Some field in the AUTHENTICATE cell body was not as expected");
2115 crypto_pk_t *pk = tor_tls_cert_get_key(
2116 chan->conn->handshake_state->auth_cert);
2117 char d[DIGEST256_LEN];
2118 char *signed_data;
2119 size_t keysize;
2120 int signed_len;
2122 if (!pk)
2123 ERR("Internal error: couldn't get RSA key from AUTH cert.");
2124 crypto_digest256(d, (char*)auth, V3_AUTH_BODY_LEN, DIGEST_SHA256);
2126 keysize = crypto_pk_keysize(pk);
2127 signed_data = tor_malloc(keysize);
2128 signed_len = crypto_pk_public_checksig(pk, signed_data, keysize,
2129 (char*)auth + V3_AUTH_BODY_LEN,
2130 authlen - V3_AUTH_BODY_LEN);
2131 crypto_pk_free(pk);
2132 if (signed_len < 0) {
2133 tor_free(signed_data);
2134 ERR("Signature wasn't valid");
2136 if (signed_len < DIGEST256_LEN) {
2137 tor_free(signed_data);
2138 ERR("Not enough data was signed");
2140 /* Note that we deliberately allow *more* than DIGEST256_LEN bytes here,
2141 * in case they're later used to hold a SHA3 digest or something. */
2142 if (tor_memneq(signed_data, d, DIGEST256_LEN)) {
2143 tor_free(signed_data);
2144 ERR("Signature did not match data to be signed.");
2146 tor_free(signed_data);
2149 /* Okay, we are authenticated. */
2150 chan->conn->handshake_state->received_authenticate = 1;
2151 chan->conn->handshake_state->authenticated = 1;
2152 chan->conn->handshake_state->digest_received_data = 0;
2154 crypto_pk_t *identity_rcvd =
2155 tor_tls_cert_get_key(chan->conn->handshake_state->id_cert);
2156 const digests_t *id_digests =
2157 tor_cert_get_id_digests(chan->conn->handshake_state->id_cert);
2159 /* This must exist; we checked key type when reading the cert. */
2160 tor_assert(id_digests);
2162 memcpy(chan->conn->handshake_state->authenticated_peer_id,
2163 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
2165 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
2166 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
2167 crypto_pk_free(identity_rcvd);
2169 connection_or_init_conn_from_address(chan->conn,
2170 &(chan->conn->base_.addr),
2171 chan->conn->base_.port,
2172 (const char*)(chan->conn->handshake_state->
2173 authenticated_peer_id),
2176 log_info(LD_OR,
2177 "Got an AUTHENTICATE cell from %s:%d: Looks good.",
2178 safe_str(chan->conn->base_.address),
2179 chan->conn->base_.port);
2182 #undef ERR