Avoid using labs() on time_t in channeltls.c
[tor.git] / src / or / channeltls.c
blobea69792f1205657bcdb428954583f38adea4b49f
1 /* * Copyright (c) 2012-2016, 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 "link_handshake.h"
53 #include "relay.h"
54 #include "rephist.h"
55 #include "router.h"
56 #include "routerlist.h"
57 #include "scheduler.h"
59 /** How many CELL_PADDING cells have we received, ever? */
60 uint64_t stats_n_padding_cells_processed = 0;
61 /** How many CELL_VERSIONS cells have we received, ever? */
62 uint64_t stats_n_versions_cells_processed = 0;
63 /** How many CELL_NETINFO cells have we received, ever? */
64 uint64_t stats_n_netinfo_cells_processed = 0;
65 /** How many CELL_VPADDING cells have we received, ever? */
66 uint64_t stats_n_vpadding_cells_processed = 0;
67 /** How many CELL_CERTS cells have we received, ever? */
68 uint64_t stats_n_certs_cells_processed = 0;
69 /** How many CELL_AUTH_CHALLENGE cells have we received, ever? */
70 uint64_t stats_n_auth_challenge_cells_processed = 0;
71 /** How many CELL_AUTHENTICATE cells have we received, ever? */
72 uint64_t stats_n_authenticate_cells_processed = 0;
73 /** How many CELL_AUTHORIZE cells have we received, ever? */
74 uint64_t stats_n_authorize_cells_processed = 0;
76 /** Active listener, if any */
77 static channel_listener_t *channel_tls_listener = NULL;
79 /* channel_tls_t method declarations */
81 static void channel_tls_close_method(channel_t *chan);
82 static const char * channel_tls_describe_transport_method(channel_t *chan);
83 static void channel_tls_free_method(channel_t *chan);
84 static double channel_tls_get_overhead_estimate_method(channel_t *chan);
85 static int
86 channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out);
87 static int
88 channel_tls_get_transport_name_method(channel_t *chan, char **transport_out);
89 static const char *
90 channel_tls_get_remote_descr_method(channel_t *chan, int flags);
91 static int channel_tls_has_queued_writes_method(channel_t *chan);
92 static int channel_tls_is_canonical_method(channel_t *chan, int req);
93 static int
94 channel_tls_matches_extend_info_method(channel_t *chan,
95 extend_info_t *extend_info);
96 static int channel_tls_matches_target_method(channel_t *chan,
97 const tor_addr_t *target);
98 static int channel_tls_num_cells_writeable_method(channel_t *chan);
99 static size_t channel_tls_num_bytes_queued_method(channel_t *chan);
100 static int channel_tls_write_cell_method(channel_t *chan,
101 cell_t *cell);
102 static int channel_tls_write_packed_cell_method(channel_t *chan,
103 packed_cell_t *packed_cell);
104 static int channel_tls_write_var_cell_method(channel_t *chan,
105 var_cell_t *var_cell);
107 /* channel_listener_tls_t method declarations */
109 static void channel_tls_listener_close_method(channel_listener_t *chan_l);
110 static const char *
111 channel_tls_listener_describe_transport_method(channel_listener_t *chan_l);
113 /** Handle incoming cells for the handshake stuff here rather than
114 * passing them on up. */
116 static void channel_tls_process_versions_cell(var_cell_t *cell,
117 channel_tls_t *tlschan);
118 static void channel_tls_process_netinfo_cell(cell_t *cell,
119 channel_tls_t *tlschan);
120 static int command_allowed_before_handshake(uint8_t command);
121 static int enter_v3_handshake_with_cell(var_cell_t *cell,
122 channel_tls_t *tlschan);
125 * Do parts of channel_tls_t initialization common to channel_tls_connect()
126 * and channel_tls_handle_incoming().
129 STATIC void
130 channel_tls_common_init(channel_tls_t *tlschan)
132 channel_t *chan;
134 tor_assert(tlschan);
136 chan = &(tlschan->base_);
137 channel_init(chan);
138 chan->magic = TLS_CHAN_MAGIC;
139 chan->state = CHANNEL_STATE_OPENING;
140 chan->close = channel_tls_close_method;
141 chan->describe_transport = channel_tls_describe_transport_method;
142 chan->free_fn = channel_tls_free_method;
143 chan->get_overhead_estimate = channel_tls_get_overhead_estimate_method;
144 chan->get_remote_addr = channel_tls_get_remote_addr_method;
145 chan->get_remote_descr = channel_tls_get_remote_descr_method;
146 chan->get_transport_name = channel_tls_get_transport_name_method;
147 chan->has_queued_writes = channel_tls_has_queued_writes_method;
148 chan->is_canonical = channel_tls_is_canonical_method;
149 chan->matches_extend_info = channel_tls_matches_extend_info_method;
150 chan->matches_target = channel_tls_matches_target_method;
151 chan->num_bytes_queued = channel_tls_num_bytes_queued_method;
152 chan->num_cells_writeable = channel_tls_num_cells_writeable_method;
153 chan->write_cell = channel_tls_write_cell_method;
154 chan->write_packed_cell = channel_tls_write_packed_cell_method;
155 chan->write_var_cell = channel_tls_write_var_cell_method;
157 chan->cmux = circuitmux_alloc();
158 if (cell_ewma_enabled()) {
159 circuitmux_set_policy(chan->cmux, &ewma_policy);
164 * Start a new TLS channel
166 * Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
167 * handshake with an OR with identity digest <b>id_digest</b>, and wrap
168 * it in a channel_tls_t.
171 channel_t *
172 channel_tls_connect(const tor_addr_t *addr, uint16_t port,
173 const char *id_digest)
175 channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
176 channel_t *chan = &(tlschan->base_);
178 channel_tls_common_init(tlschan);
180 log_debug(LD_CHANNEL,
181 "In channel_tls_connect() for channel %p "
182 "(global id " U64_FORMAT ")",
183 tlschan,
184 U64_PRINTF_ARG(chan->global_identifier));
186 if (is_local_addr(addr)) {
187 log_debug(LD_CHANNEL,
188 "Marking new outgoing channel " U64_FORMAT " at %p as local",
189 U64_PRINTF_ARG(chan->global_identifier), chan);
190 channel_mark_local(chan);
191 } else {
192 log_debug(LD_CHANNEL,
193 "Marking new outgoing channel " U64_FORMAT " at %p as remote",
194 U64_PRINTF_ARG(chan->global_identifier), chan);
195 channel_mark_remote(chan);
198 channel_mark_outgoing(chan);
200 /* Set up or_connection stuff */
201 tlschan->conn = connection_or_connect(addr, port, id_digest, tlschan);
202 /* connection_or_connect() will fill in tlschan->conn */
203 if (!(tlschan->conn)) {
204 chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
205 channel_change_state(chan, CHANNEL_STATE_ERROR);
206 goto err;
209 log_debug(LD_CHANNEL,
210 "Got orconn %p for channel with global id " U64_FORMAT,
211 tlschan->conn, U64_PRINTF_ARG(chan->global_identifier));
213 goto done;
215 err:
216 circuitmux_free(chan->cmux);
217 tor_free(tlschan);
218 chan = NULL;
220 done:
221 /* If we got one, we should register it */
222 if (chan) channel_register(chan);
224 return chan;
228 * Return the current channel_tls_t listener
230 * Returns the current channel listener for incoming TLS connections, or
231 * NULL if none has been established
234 channel_listener_t *
235 channel_tls_get_listener(void)
237 return channel_tls_listener;
241 * Start a channel_tls_t listener if necessary
243 * Return the current channel_tls_t listener, or start one if we haven't yet,
244 * and return that.
247 channel_listener_t *
248 channel_tls_start_listener(void)
250 channel_listener_t *listener;
252 if (!channel_tls_listener) {
253 listener = tor_malloc_zero(sizeof(*listener));
254 channel_init_listener(listener);
255 listener->state = CHANNEL_LISTENER_STATE_LISTENING;
256 listener->close = channel_tls_listener_close_method;
257 listener->describe_transport =
258 channel_tls_listener_describe_transport_method;
260 channel_tls_listener = listener;
262 log_debug(LD_CHANNEL,
263 "Starting TLS channel listener %p with global id " U64_FORMAT,
264 listener, U64_PRINTF_ARG(listener->global_identifier));
266 channel_listener_register(listener);
267 } else listener = channel_tls_listener;
269 return listener;
273 * Free everything on shutdown
275 * Not much to do here, since channel_free_all() takes care of a lot, but let's
276 * get rid of the listener.
279 void
280 channel_tls_free_all(void)
282 channel_listener_t *old_listener = NULL;
284 log_debug(LD_CHANNEL,
285 "Shutting down TLS channels...");
287 if (channel_tls_listener) {
289 * When we close it, channel_tls_listener will get nulled out, so save
290 * a pointer so we can free it.
292 old_listener = channel_tls_listener;
293 log_debug(LD_CHANNEL,
294 "Closing channel_tls_listener with ID " U64_FORMAT
295 " at %p.",
296 U64_PRINTF_ARG(old_listener->global_identifier),
297 old_listener);
298 channel_listener_unregister(old_listener);
299 channel_listener_mark_for_close(old_listener);
300 channel_listener_free(old_listener);
301 tor_assert(channel_tls_listener == NULL);
304 log_debug(LD_CHANNEL,
305 "Done shutting down TLS channels");
309 * Create a new channel around an incoming or_connection_t
312 channel_t *
313 channel_tls_handle_incoming(or_connection_t *orconn)
315 channel_tls_t *tlschan = tor_malloc_zero(sizeof(*tlschan));
316 channel_t *chan = &(tlschan->base_);
318 tor_assert(orconn);
319 tor_assert(!(orconn->chan));
321 channel_tls_common_init(tlschan);
323 /* Link the channel and orconn to each other */
324 tlschan->conn = orconn;
325 orconn->chan = tlschan;
327 if (is_local_addr(&(TO_CONN(orconn)->addr))) {
328 log_debug(LD_CHANNEL,
329 "Marking new incoming channel " U64_FORMAT " at %p as local",
330 U64_PRINTF_ARG(chan->global_identifier), chan);
331 channel_mark_local(chan);
332 } else {
333 log_debug(LD_CHANNEL,
334 "Marking new incoming channel " U64_FORMAT " at %p as remote",
335 U64_PRINTF_ARG(chan->global_identifier), chan);
336 channel_mark_remote(chan);
339 channel_mark_incoming(chan);
341 /* Register it */
342 channel_register(chan);
344 return chan;
347 /*********
348 * Casts *
349 ********/
352 * Cast a channel_tls_t to a channel_t.
355 channel_t *
356 channel_tls_to_base(channel_tls_t *tlschan)
358 if (!tlschan) return NULL;
360 return &(tlschan->base_);
364 * Cast a channel_t to a channel_tls_t, with appropriate type-checking
365 * asserts.
368 channel_tls_t *
369 channel_tls_from_base(channel_t *chan)
371 if (!chan) return NULL;
373 tor_assert(chan->magic == TLS_CHAN_MAGIC);
375 return (channel_tls_t *)(chan);
378 /********************************************
379 * Method implementations for channel_tls_t *
380 *******************************************/
383 * Close a channel_tls_t
385 * This implements the close method for channel_tls_t
388 static void
389 channel_tls_close_method(channel_t *chan)
391 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
393 tor_assert(tlschan);
395 if (tlschan->conn) connection_or_close_normally(tlschan->conn, 1);
396 else {
397 /* Weird - we'll have to change the state ourselves, I guess */
398 log_info(LD_CHANNEL,
399 "Tried to close channel_tls_t %p with NULL conn",
400 tlschan);
401 channel_change_state(chan, CHANNEL_STATE_ERROR);
406 * Describe the transport for a channel_tls_t
408 * This returns the string "TLS channel on connection <id>" to the upper
409 * layer.
412 static const char *
413 channel_tls_describe_transport_method(channel_t *chan)
415 static char *buf = NULL;
416 uint64_t id;
417 channel_tls_t *tlschan;
418 const char *rv = NULL;
420 tor_assert(chan);
422 tlschan = BASE_CHAN_TO_TLS(chan);
424 if (tlschan->conn) {
425 id = TO_CONN(tlschan->conn)->global_identifier;
427 if (buf) tor_free(buf);
428 tor_asprintf(&buf,
429 "TLS channel (connection " U64_FORMAT ")",
430 U64_PRINTF_ARG(id));
432 rv = buf;
433 } else {
434 rv = "TLS channel (no connection)";
437 return rv;
441 * Free a channel_tls_t
443 * This is called by the generic channel layer when freeing a channel_tls_t;
444 * this happens either on a channel which has already reached
445 * CHANNEL_STATE_CLOSED or CHANNEL_STATE_ERROR from channel_run_cleanup() or
446 * on shutdown from channel_free_all(). In the latter case we might still
447 * have an orconn active (which connection_free_all() will get to later),
448 * so we should null out its channel pointer now.
451 static void
452 channel_tls_free_method(channel_t *chan)
454 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
456 tor_assert(tlschan);
458 if (tlschan->conn) {
459 tlschan->conn->chan = NULL;
460 tlschan->conn = NULL;
465 * Get an estimate of the average TLS overhead for the upper layer
468 static double
469 channel_tls_get_overhead_estimate_method(channel_t *chan)
471 double overhead = 1.0;
472 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
474 tor_assert(tlschan);
475 tor_assert(tlschan->conn);
477 /* Just return 1.0f if we don't have sensible data */
478 if (tlschan->conn->bytes_xmitted > 0 &&
479 tlschan->conn->bytes_xmitted_by_tls >=
480 tlschan->conn->bytes_xmitted) {
481 overhead = ((double)(tlschan->conn->bytes_xmitted_by_tls)) /
482 ((double)(tlschan->conn->bytes_xmitted));
485 * Never estimate more than 2.0; otherwise we get silly large estimates
486 * at the very start of a new TLS connection.
488 if (overhead > 2.0)
489 overhead = 2.0;
492 log_debug(LD_CHANNEL,
493 "Estimated overhead ratio for TLS chan " U64_FORMAT " is %f",
494 U64_PRINTF_ARG(chan->global_identifier), overhead);
496 return overhead;
500 * Get the remote address of a channel_tls_t
502 * This implements the get_remote_addr method for channel_tls_t; copy the
503 * remote endpoint of the channel to addr_out and return 1 (always
504 * succeeds for this transport).
507 static int
508 channel_tls_get_remote_addr_method(channel_t *chan, tor_addr_t *addr_out)
510 int rv = 0;
511 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
513 tor_assert(tlschan);
514 tor_assert(addr_out);
516 if (tlschan->conn) {
517 tor_addr_copy(addr_out, &(tlschan->conn->real_addr));
518 rv = 1;
519 } else tor_addr_make_unspec(addr_out);
521 return rv;
525 * Get the name of the pluggable transport used by a channel_tls_t.
527 * This implements the get_transport_name for channel_tls_t. If the
528 * channel uses a pluggable transport, copy its name to
529 * <b>transport_out</b> and return 0. If the channel did not use a
530 * pluggable transport, return -1. */
532 static int
533 channel_tls_get_transport_name_method(channel_t *chan, char **transport_out)
535 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
537 tor_assert(tlschan);
538 tor_assert(transport_out);
539 tor_assert(tlschan->conn);
541 if (!tlschan->conn->ext_or_transport)
542 return -1;
544 *transport_out = tor_strdup(tlschan->conn->ext_or_transport);
545 return 0;
549 * Get endpoint description of a channel_tls_t
551 * This implements the get_remote_descr method for channel_tls_t; it returns
552 * a text description of the remote endpoint of the channel suitable for use
553 * in log messages. The req parameter is 0 for the canonical address or 1 for
554 * the actual address seen.
557 static const char *
558 channel_tls_get_remote_descr_method(channel_t *chan, int flags)
560 #define MAX_DESCR_LEN 32
562 static char buf[MAX_DESCR_LEN + 1];
563 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
564 connection_t *conn;
565 const char *answer = NULL;
566 char *addr_str;
568 tor_assert(tlschan);
570 if (tlschan->conn) {
571 conn = TO_CONN(tlschan->conn);
572 switch (flags) {
573 case 0:
574 /* Canonical address with port*/
575 tor_snprintf(buf, MAX_DESCR_LEN + 1,
576 "%s:%u", conn->address, conn->port);
577 answer = buf;
578 break;
579 case GRD_FLAG_ORIGINAL:
580 /* Actual address with port */
581 addr_str = tor_addr_to_str_dup(&(tlschan->conn->real_addr));
582 tor_snprintf(buf, MAX_DESCR_LEN + 1,
583 "%s:%u", addr_str, conn->port);
584 tor_free(addr_str);
585 answer = buf;
586 break;
587 case GRD_FLAG_ADDR_ONLY:
588 /* Canonical address, no port */
589 strlcpy(buf, conn->address, sizeof(buf));
590 answer = buf;
591 break;
592 case GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY:
593 /* Actual address, no port */
594 addr_str = tor_addr_to_str_dup(&(tlschan->conn->real_addr));
595 strlcpy(buf, addr_str, sizeof(buf));
596 tor_free(addr_str);
597 answer = buf;
598 break;
599 default:
600 /* Something's broken in channel.c */
601 tor_assert(1);
603 } else {
604 strlcpy(buf, "(No connection)", sizeof(buf));
605 answer = buf;
608 return answer;
612 * Tell the upper layer if we have queued writes
614 * This implements the has_queued_writes method for channel_tls t_; it returns
615 * 1 iff we have queued writes on the outbuf of the underlying or_connection_t.
618 static int
619 channel_tls_has_queued_writes_method(channel_t *chan)
621 size_t outbuf_len;
622 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
624 tor_assert(tlschan);
625 if (!(tlschan->conn)) {
626 log_info(LD_CHANNEL,
627 "something called has_queued_writes on a tlschan "
628 "(%p with ID " U64_FORMAT " but no conn",
629 chan, U64_PRINTF_ARG(chan->global_identifier));
632 outbuf_len = (tlschan->conn != NULL) ?
633 connection_get_outbuf_len(TO_CONN(tlschan->conn)) :
636 return (outbuf_len > 0);
640 * Tell the upper layer if we're canonical
642 * This implements the is_canonical method for channel_tls_t; if req is zero,
643 * it returns whether this is a canonical channel, and if it is one it returns
644 * whether that can be relied upon.
647 static int
648 channel_tls_is_canonical_method(channel_t *chan, int req)
650 int answer = 0;
651 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
653 tor_assert(tlschan);
655 if (tlschan->conn) {
656 switch (req) {
657 case 0:
658 answer = tlschan->conn->is_canonical;
659 break;
660 case 1:
662 * Is the is_canonical bit reliable? In protocols version 2 and up
663 * we get the canonical address from a NETINFO cell, but in older
664 * versions it might be based on an obsolete descriptor.
666 answer = (tlschan->conn->link_proto >= 2);
667 break;
668 default:
669 /* This shouldn't happen; channel.c is broken if it does */
670 tor_assert(1);
673 /* else return 0 for tlschan->conn == NULL */
675 return answer;
679 * Check if we match an extend_info_t
681 * This implements the matches_extend_info method for channel_tls_t; the upper
682 * layer wants to know if this channel matches an extend_info_t.
685 static int
686 channel_tls_matches_extend_info_method(channel_t *chan,
687 extend_info_t *extend_info)
689 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
691 tor_assert(tlschan);
692 tor_assert(extend_info);
694 /* Never match if we have no conn */
695 if (!(tlschan->conn)) {
696 log_info(LD_CHANNEL,
697 "something called matches_extend_info on a tlschan "
698 "(%p with ID " U64_FORMAT " but no conn",
699 chan, U64_PRINTF_ARG(chan->global_identifier));
700 return 0;
703 return (tor_addr_eq(&(extend_info->addr),
704 &(TO_CONN(tlschan->conn)->addr)) &&
705 (extend_info->port == TO_CONN(tlschan->conn)->port));
709 * Check if we match a target address; return true iff we do.
711 * This implements the matches_target method for channel_tls t_; the upper
712 * layer wants to know if this channel matches a target address when extending
713 * a circuit.
716 static int
717 channel_tls_matches_target_method(channel_t *chan,
718 const tor_addr_t *target)
720 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
722 tor_assert(tlschan);
723 tor_assert(target);
725 /* Never match if we have no conn */
726 if (!(tlschan->conn)) {
727 log_info(LD_CHANNEL,
728 "something called matches_target on a tlschan "
729 "(%p with ID " U64_FORMAT " but no conn",
730 chan, U64_PRINTF_ARG(chan->global_identifier));
731 return 0;
734 return tor_addr_eq(&(tlschan->conn->real_addr), target);
738 * Tell the upper layer how many bytes we have queued and not yet
739 * sent.
742 static size_t
743 channel_tls_num_bytes_queued_method(channel_t *chan)
745 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
747 tor_assert(tlschan);
748 tor_assert(tlschan->conn);
750 return connection_get_outbuf_len(TO_CONN(tlschan->conn));
754 * Tell the upper layer how many cells we can accept to write
756 * This implements the num_cells_writeable method for channel_tls_t; it
757 * returns an estimate of the number of cells we can accept with
758 * channel_tls_write_*_cell().
761 static int
762 channel_tls_num_cells_writeable_method(channel_t *chan)
764 size_t outbuf_len;
765 ssize_t n;
766 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
767 size_t cell_network_size;
769 tor_assert(tlschan);
770 tor_assert(tlschan->conn);
772 cell_network_size = get_cell_network_size(tlschan->conn->wide_circ_ids);
773 outbuf_len = connection_get_outbuf_len(TO_CONN(tlschan->conn));
774 /* Get the number of cells */
775 n = CEIL_DIV(OR_CONN_HIGHWATER - outbuf_len, cell_network_size);
776 if (n < 0) n = 0;
777 #if SIZEOF_SIZE_T > SIZEOF_INT
778 if (n > INT_MAX) n = INT_MAX;
779 #endif
781 return (int)n;
785 * Write a cell to a channel_tls_t
787 * This implements the write_cell method for channel_tls_t; given a
788 * channel_tls_t and a cell_t, transmit the cell_t.
791 static int
792 channel_tls_write_cell_method(channel_t *chan, cell_t *cell)
794 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
795 int written = 0;
797 tor_assert(tlschan);
798 tor_assert(cell);
800 if (tlschan->conn) {
801 connection_or_write_cell_to_buf(cell, tlschan->conn);
802 ++written;
803 } else {
804 log_info(LD_CHANNEL,
805 "something called write_cell on a tlschan "
806 "(%p with ID " U64_FORMAT " but no conn",
807 chan, U64_PRINTF_ARG(chan->global_identifier));
810 return written;
814 * Write a packed cell to a channel_tls_t
816 * This implements the write_packed_cell method for channel_tls_t; given a
817 * channel_tls_t and a packed_cell_t, transmit the packed_cell_t.
820 static int
821 channel_tls_write_packed_cell_method(channel_t *chan,
822 packed_cell_t *packed_cell)
824 tor_assert(chan);
825 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
826 size_t cell_network_size = get_cell_network_size(chan->wide_circ_ids);
827 int written = 0;
829 tor_assert(tlschan);
830 tor_assert(packed_cell);
832 if (tlschan->conn) {
833 connection_write_to_buf(packed_cell->body, cell_network_size,
834 TO_CONN(tlschan->conn));
836 /* This is where the cell is finished; used to be done from relay.c */
837 packed_cell_free(packed_cell);
838 ++written;
839 } else {
840 log_info(LD_CHANNEL,
841 "something called write_packed_cell on a tlschan "
842 "(%p with ID " U64_FORMAT " but no conn",
843 chan, U64_PRINTF_ARG(chan->global_identifier));
846 return written;
850 * Write a variable-length cell to a channel_tls_t
852 * This implements the write_var_cell method for channel_tls_t; given a
853 * channel_tls_t and a var_cell_t, transmit the var_cell_t.
856 static int
857 channel_tls_write_var_cell_method(channel_t *chan, var_cell_t *var_cell)
859 channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
860 int written = 0;
862 tor_assert(tlschan);
863 tor_assert(var_cell);
865 if (tlschan->conn) {
866 connection_or_write_var_cell_to_buf(var_cell, tlschan->conn);
867 ++written;
868 } else {
869 log_info(LD_CHANNEL,
870 "something called write_var_cell on a tlschan "
871 "(%p with ID " U64_FORMAT " but no conn",
872 chan, U64_PRINTF_ARG(chan->global_identifier));
875 return written;
878 /*************************************************
879 * Method implementations for channel_listener_t *
880 ************************************************/
883 * Close a channel_listener_t
885 * This implements the close method for channel_listener_t
888 static void
889 channel_tls_listener_close_method(channel_listener_t *chan_l)
891 tor_assert(chan_l);
894 * Listeners we just go ahead and change state through to CLOSED, but
895 * make sure to check if they're channel_tls_listener to NULL it out.
897 if (chan_l == channel_tls_listener)
898 channel_tls_listener = NULL;
900 if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
901 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
902 chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
903 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
906 if (chan_l->incoming_list) {
907 SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
908 channel_t *, ichan) {
909 channel_mark_for_close(ichan);
910 } SMARTLIST_FOREACH_END(ichan);
912 smartlist_free(chan_l->incoming_list);
913 chan_l->incoming_list = NULL;
916 if (!(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
917 chan_l->state == CHANNEL_LISTENER_STATE_ERROR)) {
918 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
923 * Describe the transport for a channel_listener_t
925 * This returns the string "TLS channel (listening)" to the upper
926 * layer.
929 static const char *
930 channel_tls_listener_describe_transport_method(channel_listener_t *chan_l)
932 tor_assert(chan_l);
934 return "TLS channel (listening)";
937 /*******************************************************
938 * Functions for handling events on an or_connection_t *
939 ******************************************************/
942 * Handle an orconn state change
944 * This function will be called by connection_or.c when the or_connection_t
945 * associated with this channel_tls_t changes state.
948 void
949 channel_tls_handle_state_change_on_orconn(channel_tls_t *chan,
950 or_connection_t *conn,
951 uint8_t old_state,
952 uint8_t state)
954 channel_t *base_chan;
956 tor_assert(chan);
957 tor_assert(conn);
958 tor_assert(conn->chan == chan);
959 tor_assert(chan->conn == conn);
960 /* Shut the compiler up without triggering -Wtautological-compare */
961 (void)old_state;
963 base_chan = TLS_CHAN_TO_BASE(chan);
965 /* Make sure the base connection state makes sense - shouldn't be error
966 * or closed. */
968 tor_assert(CHANNEL_IS_OPENING(base_chan) ||
969 CHANNEL_IS_OPEN(base_chan) ||
970 CHANNEL_IS_MAINT(base_chan) ||
971 CHANNEL_IS_CLOSING(base_chan));
973 /* Did we just go to state open? */
974 if (state == OR_CONN_STATE_OPEN) {
976 * We can go to CHANNEL_STATE_OPEN from CHANNEL_STATE_OPENING or
977 * CHANNEL_STATE_MAINT on this.
979 channel_change_state(base_chan, CHANNEL_STATE_OPEN);
980 /* We might have just become writeable; check and tell the scheduler */
981 if (connection_or_num_cells_writeable(conn) > 0) {
982 scheduler_channel_wants_writes(base_chan);
984 } else {
986 * Not open, so from CHANNEL_STATE_OPEN we go to CHANNEL_STATE_MAINT,
987 * otherwise no change.
989 if (CHANNEL_IS_OPEN(base_chan)) {
990 channel_change_state(base_chan, CHANNEL_STATE_MAINT);
995 #ifdef KEEP_TIMING_STATS
998 * Timing states wrapper
1000 * This is a wrapper function around the actual function that processes the
1001 * <b>cell</b> that just arrived on <b>chan</b>. Increment <b>*time</b>
1002 * by the number of microseconds used by the call to <b>*func(cell, chan)</b>.
1005 static void
1006 channel_tls_time_process_cell(cell_t *cell, channel_tls_t *chan, int *time,
1007 void (*func)(cell_t *, channel_tls_t *))
1009 struct timeval start, end;
1010 long time_passed;
1012 tor_gettimeofday(&start);
1014 (*func)(cell, chan);
1016 tor_gettimeofday(&end);
1017 time_passed = tv_udiff(&start, &end) ;
1019 if (time_passed > 10000) { /* more than 10ms */
1020 log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
1023 if (time_passed < 0) {
1024 log_info(LD_GENERAL,"That call took us back in time!");
1025 time_passed = 0;
1028 *time += time_passed;
1030 #endif
1033 * Handle an incoming cell on a channel_tls_t
1035 * This is called from connection_or.c to handle an arriving cell; it checks
1036 * for cell types specific to the handshake for this transport protocol and
1037 * handles them, and queues all other cells to the channel_t layer, which
1038 * eventually will hand them off to command.c.
1040 * The channel layer itself decides whether the cell should be queued or
1041 * can be handed off immediately to the upper-layer code. It is responsible
1042 * for copying in the case that it queues; we merely pass pointers through
1043 * which we get from connection_or_process_cells_from_inbuf().
1046 void
1047 channel_tls_handle_cell(cell_t *cell, or_connection_t *conn)
1049 channel_tls_t *chan;
1050 int handshaking;
1052 #ifdef KEEP_TIMING_STATS
1053 #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
1054 ++num ## tp; \
1055 channel_tls_time_process_cell(cl, cn, & tp ## time , \
1056 channel_tls_process_ ## tp ## _cell); \
1057 } STMT_END
1058 #else
1059 #define PROCESS_CELL(tp, cl, cn) channel_tls_process_ ## tp ## _cell(cl, cn)
1060 #endif
1062 tor_assert(cell);
1063 tor_assert(conn);
1065 chan = conn->chan;
1067 if (!chan) {
1068 log_warn(LD_CHANNEL,
1069 "Got a cell_t on an OR connection with no channel");
1070 return;
1073 handshaking = (TO_CONN(conn)->state != OR_CONN_STATE_OPEN);
1075 if (conn->base_.marked_for_close)
1076 return;
1078 /* Reject all but VERSIONS and NETINFO when handshaking. */
1079 /* (VERSIONS should actually be impossible; it's variable-length.) */
1080 if (handshaking && cell->command != CELL_VERSIONS &&
1081 cell->command != CELL_NETINFO) {
1082 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1083 "Received unexpected cell command %d in chan state %s / "
1084 "conn state %s; closing the connection.",
1085 (int)cell->command,
1086 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1087 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state));
1088 connection_or_close_for_error(conn, 0);
1089 return;
1092 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
1093 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 1);
1095 switch (cell->command) {
1096 case CELL_PADDING:
1097 ++stats_n_padding_cells_processed;
1098 /* do nothing */
1099 break;
1100 case CELL_VERSIONS:
1101 tor_fragile_assert();
1102 break;
1103 case CELL_NETINFO:
1104 ++stats_n_netinfo_cells_processed;
1105 PROCESS_CELL(netinfo, cell, chan);
1106 break;
1107 case CELL_CREATE:
1108 case CELL_CREATE_FAST:
1109 case CELL_CREATED:
1110 case CELL_CREATED_FAST:
1111 case CELL_RELAY:
1112 case CELL_RELAY_EARLY:
1113 case CELL_DESTROY:
1114 case CELL_CREATE2:
1115 case CELL_CREATED2:
1117 * These are all transport independent and we pass them up through the
1118 * channel_t mechanism. They are ultimately handled in command.c.
1120 channel_queue_cell(TLS_CHAN_TO_BASE(chan), cell);
1121 break;
1122 default:
1123 log_fn(LOG_INFO, LD_PROTOCOL,
1124 "Cell of unknown type (%d) received in channeltls.c. "
1125 "Dropping.",
1126 cell->command);
1127 break;
1132 * Handle an incoming variable-length cell on a channel_tls_t
1134 * Process a <b>var_cell</b> that was just received on <b>conn</b>. Keep
1135 * internal statistics about how many of each cell we've processed so far
1136 * this second, and the total number of microseconds it took to
1137 * process each type of cell. All the var_cell commands are handshake-
1138 * related and live below the channel_t layer, so no variable-length
1139 * cells ever get delivered in the current implementation, but I've left
1140 * the mechanism in place for future use.
1142 * If we were handing them off to the upper layer, the channel_t queueing
1143 * code would be responsible for memory management, and we'd just be passing
1144 * pointers through from connection_or_process_cells_from_inbuf(). That
1145 * caller always frees them after this function returns, so this function
1146 * should never free var_cell.
1149 void
1150 channel_tls_handle_var_cell(var_cell_t *var_cell, or_connection_t *conn)
1152 channel_tls_t *chan;
1154 #ifdef KEEP_TIMING_STATS
1155 /* how many of each cell have we seen so far this second? needs better
1156 * name. */
1157 static int num_versions = 0, num_certs = 0;
1158 static time_t current_second = 0; /* from previous calls to time */
1159 time_t now = time(NULL);
1161 if (current_second == 0) current_second = now;
1162 if (now > current_second) { /* the second has rolled over */
1163 /* print stats */
1164 log_info(LD_OR,
1165 "At end of second: %d versions (%d ms), %d certs (%d ms)",
1166 num_versions, versions_time / ((now - current_second) * 1000),
1167 num_certs, certs_time / ((now - current_second) * 1000));
1169 num_versions = num_certs = 0;
1170 versions_time = certs_time = 0;
1172 /* remember which second it is, for next time */
1173 current_second = now;
1175 #endif
1177 tor_assert(var_cell);
1178 tor_assert(conn);
1180 chan = conn->chan;
1182 if (!chan) {
1183 log_warn(LD_CHANNEL,
1184 "Got a var_cell_t on an OR connection with no channel");
1185 return;
1188 if (TO_CONN(conn)->marked_for_close)
1189 return;
1191 switch (TO_CONN(conn)->state) {
1192 case OR_CONN_STATE_OR_HANDSHAKING_V2:
1193 if (var_cell->command != CELL_VERSIONS) {
1194 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1195 "Received a cell with command %d in unexpected "
1196 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1197 "closing the connection.",
1198 (int)(var_cell->command),
1199 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1200 TO_CONN(conn)->state,
1201 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1202 (int)(TLS_CHAN_TO_BASE(chan)->state));
1204 * The code in connection_or.c will tell channel_t to close for
1205 * error; it will go to CHANNEL_STATE_CLOSING, and then to
1206 * CHANNEL_STATE_ERROR when conn is closed.
1208 connection_or_close_for_error(conn, 0);
1209 return;
1211 break;
1212 case OR_CONN_STATE_TLS_HANDSHAKING:
1213 /* If we're using bufferevents, it's entirely possible for us to
1214 * notice "hey, data arrived!" before we notice "hey, the handshake
1215 * finished!" And we need to be accepting both at once to handle both
1216 * the v2 and v3 handshakes. */
1217 /* But that should be happening any longer've disabled bufferevents. */
1218 tor_assert_nonfatal_unreached_once();
1220 /* fall through */
1221 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
1222 if (!(command_allowed_before_handshake(var_cell->command))) {
1223 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1224 "Received a cell with command %d in unexpected "
1225 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1226 "closing the connection.",
1227 (int)(var_cell->command),
1228 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1229 (int)(TO_CONN(conn)->state),
1230 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1231 (int)(TLS_CHAN_TO_BASE(chan)->state));
1232 /* see above comment about CHANNEL_STATE_ERROR */
1233 connection_or_close_for_error(conn, 0);
1234 return;
1235 } else {
1236 if (enter_v3_handshake_with_cell(var_cell, chan) < 0)
1237 return;
1239 break;
1240 case OR_CONN_STATE_OR_HANDSHAKING_V3:
1241 if (var_cell->command != CELL_AUTHENTICATE)
1242 or_handshake_state_record_var_cell(conn, conn->handshake_state,
1243 var_cell, 1);
1244 break; /* Everything is allowed */
1245 case OR_CONN_STATE_OPEN:
1246 if (conn->link_proto < 3) {
1247 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1248 "Received a variable-length cell with command %d in orconn "
1249 "state %s [%d], channel state %s [%d] with link protocol %d; "
1250 "ignoring it.",
1251 (int)(var_cell->command),
1252 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1253 (int)(TO_CONN(conn)->state),
1254 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1255 (int)(TLS_CHAN_TO_BASE(chan)->state),
1256 (int)(conn->link_proto));
1257 return;
1259 break;
1260 default:
1261 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1262 "Received var-length cell with command %d in unexpected "
1263 "orconn state \"%s\" [%d], channel state \"%s\" [%d]; "
1264 "ignoring it.",
1265 (int)(var_cell->command),
1266 conn_state_to_string(CONN_TYPE_OR, TO_CONN(conn)->state),
1267 (int)(TO_CONN(conn)->state),
1268 channel_state_to_string(TLS_CHAN_TO_BASE(chan)->state),
1269 (int)(TLS_CHAN_TO_BASE(chan)->state));
1270 return;
1273 /* Now handle the cell */
1275 switch (var_cell->command) {
1276 case CELL_VERSIONS:
1277 ++stats_n_versions_cells_processed;
1278 PROCESS_CELL(versions, var_cell, chan);
1279 break;
1280 case CELL_VPADDING:
1281 ++stats_n_vpadding_cells_processed;
1282 /* Do nothing */
1283 break;
1284 case CELL_CERTS:
1285 ++stats_n_certs_cells_processed;
1286 PROCESS_CELL(certs, var_cell, chan);
1287 break;
1288 case CELL_AUTH_CHALLENGE:
1289 ++stats_n_auth_challenge_cells_processed;
1290 PROCESS_CELL(auth_challenge, var_cell, chan);
1291 break;
1292 case CELL_AUTHENTICATE:
1293 ++stats_n_authenticate_cells_processed;
1294 PROCESS_CELL(authenticate, var_cell, chan);
1295 break;
1296 case CELL_AUTHORIZE:
1297 ++stats_n_authorize_cells_processed;
1298 /* Ignored so far. */
1299 break;
1300 default:
1301 log_fn(LOG_INFO, LD_PROTOCOL,
1302 "Variable-length cell of unknown type (%d) received.",
1303 (int)(var_cell->command));
1304 break;
1309 * Update channel marks after connection_or.c has changed an address
1311 * This is called from connection_or_init_conn_from_address() after the
1312 * connection's _base.addr or real_addr fields have potentially been changed
1313 * so we can recalculate the local mark. Notably, this happens when incoming
1314 * connections are reverse-proxied and we only learn the real address of the
1315 * remote router by looking it up in the consensus after we finish the
1316 * handshake and know an authenticated identity digest.
1319 void
1320 channel_tls_update_marks(or_connection_t *conn)
1322 channel_t *chan = NULL;
1324 tor_assert(conn);
1325 tor_assert(conn->chan);
1327 chan = TLS_CHAN_TO_BASE(conn->chan);
1329 if (is_local_addr(&(TO_CONN(conn)->addr))) {
1330 if (!channel_is_local(chan)) {
1331 log_debug(LD_CHANNEL,
1332 "Marking channel " U64_FORMAT " at %p as local",
1333 U64_PRINTF_ARG(chan->global_identifier), chan);
1334 channel_mark_local(chan);
1336 } else {
1337 if (channel_is_local(chan)) {
1338 log_debug(LD_CHANNEL,
1339 "Marking channel " U64_FORMAT " at %p as remote",
1340 U64_PRINTF_ARG(chan->global_identifier), chan);
1341 channel_mark_remote(chan);
1347 * Check if this cell type is allowed before the handshake is finished
1349 * Return true if <b>command</b> is a cell command that's allowed to start a
1350 * V3 handshake.
1353 static int
1354 command_allowed_before_handshake(uint8_t command)
1356 switch (command) {
1357 case CELL_VERSIONS:
1358 case CELL_VPADDING:
1359 case CELL_AUTHORIZE:
1360 return 1;
1361 default:
1362 return 0;
1367 * Start a V3 handshake on an incoming connection
1369 * Called when we as a server receive an appropriate cell while waiting
1370 * either for a cell or a TLS handshake. Set the connection's state to
1371 * "handshaking_v3', initializes the or_handshake_state field as needed,
1372 * and add the cell to the hash of incoming cells.)
1375 static int
1376 enter_v3_handshake_with_cell(var_cell_t *cell, channel_tls_t *chan)
1378 int started_here = 0;
1380 tor_assert(cell);
1381 tor_assert(chan);
1382 tor_assert(chan->conn);
1384 started_here = connection_or_nonopen_was_started_here(chan->conn);
1386 tor_assert(TO_CONN(chan->conn)->state == OR_CONN_STATE_TLS_HANDSHAKING ||
1387 TO_CONN(chan->conn)->state ==
1388 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1390 if (started_here) {
1391 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1392 "Received a cell while TLS-handshaking, not in "
1393 "OR_HANDSHAKING_V3, on a connection we originated.");
1395 connection_or_block_renegotiation(chan->conn);
1396 chan->conn->base_.state = OR_CONN_STATE_OR_HANDSHAKING_V3;
1397 if (connection_init_or_handshake_state(chan->conn, started_here) < 0) {
1398 connection_or_close_for_error(chan->conn, 0);
1399 return -1;
1401 or_handshake_state_record_var_cell(chan->conn,
1402 chan->conn->handshake_state, cell, 1);
1403 return 0;
1407 * Process a 'versions' cell.
1409 * This function is called to handle an incoming VERSIONS cell; the current
1410 * link protocol version must be 0 to indicate that no version has yet been
1411 * negotiated. We compare the versions in the cell to the list of versions
1412 * we support, pick the highest version we have in common, and continue the
1413 * negotiation from there.
1416 static void
1417 channel_tls_process_versions_cell(var_cell_t *cell, channel_tls_t *chan)
1419 int highest_supported_version = 0;
1420 int started_here = 0;
1422 tor_assert(cell);
1423 tor_assert(chan);
1424 tor_assert(chan->conn);
1426 if ((cell->payload_len % 2) == 1) {
1427 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1428 "Received a VERSION cell with odd payload length %d; "
1429 "closing connection.",cell->payload_len);
1430 connection_or_close_for_error(chan->conn, 0);
1431 return;
1434 started_here = connection_or_nonopen_was_started_here(chan->conn);
1436 if (chan->conn->link_proto != 0 ||
1437 (chan->conn->handshake_state &&
1438 chan->conn->handshake_state->received_versions)) {
1439 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1440 "Received a VERSIONS cell on a connection with its version "
1441 "already set to %d; dropping",
1442 (int)(chan->conn->link_proto));
1443 return;
1445 switch (chan->conn->base_.state)
1447 case OR_CONN_STATE_OR_HANDSHAKING_V2:
1448 case OR_CONN_STATE_OR_HANDSHAKING_V3:
1449 break;
1450 case OR_CONN_STATE_TLS_HANDSHAKING:
1451 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
1452 default:
1453 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1454 "VERSIONS cell while in unexpected state");
1455 return;
1458 tor_assert(chan->conn->handshake_state);
1461 int i;
1462 const uint8_t *cp = cell->payload;
1463 for (i = 0; i < cell->payload_len / 2; ++i, cp += 2) {
1464 uint16_t v = ntohs(get_uint16(cp));
1465 if (is_or_protocol_version_known(v) && v > highest_supported_version)
1466 highest_supported_version = v;
1469 if (!highest_supported_version) {
1470 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1471 "Couldn't find a version in common between my version list and the "
1472 "list in the VERSIONS cell; closing connection.");
1473 connection_or_close_for_error(chan->conn, 0);
1474 return;
1475 } else if (highest_supported_version == 1) {
1476 /* Negotiating version 1 makes no sense, since version 1 has no VERSIONS
1477 * cells. */
1478 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1479 "Used version negotiation protocol to negotiate a v1 connection. "
1480 "That's crazily non-compliant. Closing connection.");
1481 connection_or_close_for_error(chan->conn, 0);
1482 return;
1483 } else if (highest_supported_version < 3 &&
1484 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1485 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1486 "Negotiated link protocol 2 or lower after doing a v3 TLS "
1487 "handshake. Closing connection.");
1488 connection_or_close_for_error(chan->conn, 0);
1489 return;
1490 } else if (highest_supported_version != 2 &&
1491 chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V2) {
1492 /* XXXX This should eventually be a log_protocol_warn */
1493 log_fn(LOG_WARN, LD_OR,
1494 "Negotiated link with non-2 protocol after doing a v2 TLS "
1495 "handshake with %s. Closing connection.",
1496 fmt_addr(&chan->conn->base_.addr));
1497 connection_or_close_for_error(chan->conn, 0);
1498 return;
1501 rep_hist_note_negotiated_link_proto(highest_supported_version, started_here);
1503 chan->conn->link_proto = highest_supported_version;
1504 chan->conn->handshake_state->received_versions = 1;
1506 if (chan->conn->link_proto == 2) {
1507 log_info(LD_OR,
1508 "Negotiated version %d with %s:%d; sending NETINFO.",
1509 highest_supported_version,
1510 safe_str_client(chan->conn->base_.address),
1511 chan->conn->base_.port);
1513 if (connection_or_send_netinfo(chan->conn) < 0) {
1514 connection_or_close_for_error(chan->conn, 0);
1515 return;
1517 } else {
1518 const int send_versions = !started_here;
1519 /* If we want to authenticate, send a CERTS cell */
1520 const int send_certs = !started_here || public_server_mode(get_options());
1521 /* If we're a host that got a connection, ask for authentication. */
1522 const int send_chall = !started_here;
1523 /* If our certs cell will authenticate us, we can send a netinfo cell
1524 * right now. */
1525 const int send_netinfo = !started_here;
1526 const int send_any =
1527 send_versions || send_certs || send_chall || send_netinfo;
1528 tor_assert(chan->conn->link_proto >= 3);
1530 log_info(LD_OR,
1531 "Negotiated version %d with %s:%d; %s%s%s%s%s",
1532 highest_supported_version,
1533 safe_str_client(chan->conn->base_.address),
1534 chan->conn->base_.port,
1535 send_any ? "Sending cells:" : "Waiting for CERTS cell",
1536 send_versions ? " VERSIONS" : "",
1537 send_certs ? " CERTS" : "",
1538 send_chall ? " AUTH_CHALLENGE" : "",
1539 send_netinfo ? " NETINFO" : "");
1541 #ifdef DISABLE_V3_LINKPROTO_SERVERSIDE
1542 if (1) {
1543 connection_or_close_normally(chan->conn, 1);
1544 return;
1546 #endif
1548 if (send_versions) {
1549 if (connection_or_send_versions(chan->conn, 1) < 0) {
1550 log_warn(LD_OR, "Couldn't send versions cell");
1551 connection_or_close_for_error(chan->conn, 0);
1552 return;
1556 /* We set this after sending the verions cell. */
1557 /*XXXXX symbolic const.*/
1558 chan->base_.wide_circ_ids =
1559 chan->conn->link_proto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
1560 chan->conn->wide_circ_ids = chan->base_.wide_circ_ids;
1562 if (send_certs) {
1563 if (connection_or_send_certs_cell(chan->conn) < 0) {
1564 log_warn(LD_OR, "Couldn't send certs cell");
1565 connection_or_close_for_error(chan->conn, 0);
1566 return;
1569 if (send_chall) {
1570 if (connection_or_send_auth_challenge_cell(chan->conn) < 0) {
1571 log_warn(LD_OR, "Couldn't send auth_challenge cell");
1572 connection_or_close_for_error(chan->conn, 0);
1573 return;
1576 if (send_netinfo) {
1577 if (connection_or_send_netinfo(chan->conn) < 0) {
1578 log_warn(LD_OR, "Couldn't send netinfo cell");
1579 connection_or_close_for_error(chan->conn, 0);
1580 return;
1587 * Helper: compute the absolute value of a time_t.
1589 * (we need this because labs() doesn't always work for time_t, since
1590 * long can be shorter than time_t.)
1592 static inline time_t
1593 time_abs(time_t val)
1595 return (val < 0) ? -val : val;
1599 * Process a 'netinfo' cell
1601 * This function is called to handle an incoming NETINFO cell; read and act
1602 * on its contents, and set the connection state to "open".
1605 static void
1606 channel_tls_process_netinfo_cell(cell_t *cell, channel_tls_t *chan)
1608 time_t timestamp;
1609 uint8_t my_addr_type;
1610 uint8_t my_addr_len;
1611 const uint8_t *my_addr_ptr;
1612 const uint8_t *cp, *end;
1613 uint8_t n_other_addrs;
1614 time_t now = time(NULL);
1616 time_t apparent_skew = 0;
1617 tor_addr_t my_apparent_addr = TOR_ADDR_NULL;
1619 tor_assert(cell);
1620 tor_assert(chan);
1621 tor_assert(chan->conn);
1623 if (chan->conn->link_proto < 2) {
1624 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1625 "Received a NETINFO cell on %s connection; dropping.",
1626 chan->conn->link_proto == 0 ? "non-versioned" : "a v1");
1627 return;
1629 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
1630 chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
1631 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1632 "Received a NETINFO cell on non-handshaking connection; dropping.");
1633 return;
1635 tor_assert(chan->conn->handshake_state &&
1636 chan->conn->handshake_state->received_versions);
1638 if (chan->conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
1639 tor_assert(chan->conn->link_proto >= 3);
1640 if (chan->conn->handshake_state->started_here) {
1641 if (!(chan->conn->handshake_state->authenticated)) {
1642 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1643 "Got a NETINFO cell from server, "
1644 "but no authentication. Closing the connection.");
1645 connection_or_close_for_error(chan->conn, 0);
1646 return;
1648 } else {
1649 /* we're the server. If the client never authenticated, we have
1650 some housekeeping to do.*/
1651 if (!(chan->conn->handshake_state->authenticated)) {
1652 tor_assert(tor_digest_is_zero(
1653 (const char*)(chan->conn->handshake_state->
1654 authenticated_peer_id)));
1655 /* If the client never authenticated, it's a tor client or bridge
1656 * relay, and we must not use it for EXTEND requests (nor could we, as
1657 * there are no authenticated peer IDs) */
1658 channel_mark_client(TLS_CHAN_TO_BASE(chan));
1659 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), NULL,
1660 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
1662 connection_or_init_conn_from_address(chan->conn,
1663 &(chan->conn->base_.addr),
1664 chan->conn->base_.port,
1665 (const char*)(chan->conn->handshake_state->
1666 authenticated_peer_id),
1672 /* Decode the cell. */
1673 timestamp = ntohl(get_uint32(cell->payload));
1674 const time_t sent_versions_at =
1675 chan->conn->handshake_state->sent_versions_at;
1676 if (now > sent_versions_at && (now - sent_versions_at) < 180) {
1677 /* If we have gotten the NETINFO cell reasonably soon after having
1678 * sent our VERSIONS cell, maybe we can learn skew information from it. */
1679 apparent_skew = now - timestamp;
1682 my_addr_type = (uint8_t) cell->payload[4];
1683 my_addr_len = (uint8_t) cell->payload[5];
1684 my_addr_ptr = (uint8_t*) cell->payload + 6;
1685 end = cell->payload + CELL_PAYLOAD_SIZE;
1686 cp = cell->payload + 6 + my_addr_len;
1688 /* We used to check:
1689 * if (my_addr_len >= CELL_PAYLOAD_SIZE - 6) {
1691 * This is actually never going to happen, since my_addr_len is at most 255,
1692 * and CELL_PAYLOAD_LEN - 6 is 503. So we know that cp is < end. */
1694 if (my_addr_type == RESOLVED_TYPE_IPV4 && my_addr_len == 4) {
1695 tor_addr_from_ipv4n(&my_apparent_addr, get_uint32(my_addr_ptr));
1696 } else if (my_addr_type == RESOLVED_TYPE_IPV6 && my_addr_len == 16) {
1697 tor_addr_from_ipv6_bytes(&my_apparent_addr, (const char *) my_addr_ptr);
1700 n_other_addrs = (uint8_t) *cp++;
1701 while (n_other_addrs && cp < end-2) {
1702 /* Consider all the other addresses; if any matches, this connection is
1703 * "canonical." */
1704 tor_addr_t addr;
1705 const uint8_t *next =
1706 decode_address_from_payload(&addr, cp, (int)(end-cp));
1707 if (next == NULL) {
1708 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1709 "Bad address in netinfo cell; closing connection.");
1710 connection_or_close_for_error(chan->conn, 0);
1711 return;
1713 if (tor_addr_eq(&addr, &(chan->conn->real_addr))) {
1714 connection_or_set_canonical(chan->conn, 1);
1715 break;
1717 cp = next;
1718 --n_other_addrs;
1721 /* Act on apparent skew. */
1722 /** Warn when we get a netinfo skew with at least this value. */
1723 #define NETINFO_NOTICE_SKEW 3600
1724 if (time_abs(apparent_skew) &&
1725 router_get_by_id_digest(chan->conn->identity_digest)) {
1726 int trusted = router_digest_is_trusted_dir(chan->conn->identity_digest);
1727 clock_skew_warning(TO_CONN(chan->conn), apparent_skew, trusted, LD_GENERAL,
1728 "NETINFO cell", "OR");
1731 /* XXX maybe act on my_apparent_addr, if the source is sufficiently
1732 * trustworthy. */
1734 if (! chan->conn->handshake_state->sent_netinfo) {
1735 /* If we were prepared to authenticate, but we never got an AUTH_CHALLENGE
1736 * cell, then we would not previously have sent a NETINFO cell. Do so
1737 * now. */
1738 if (connection_or_send_netinfo(chan->conn) < 0) {
1739 connection_or_close_for_error(chan->conn, 0);
1740 return;
1744 if (connection_or_set_state_open(chan->conn) < 0) {
1745 log_fn(LOG_PROTOCOL_WARN, LD_OR,
1746 "Got good NETINFO cell from %s:%d; but "
1747 "was unable to make the OR connection become open.",
1748 safe_str_client(chan->conn->base_.address),
1749 chan->conn->base_.port);
1750 connection_or_close_for_error(chan->conn, 0);
1751 } else {
1752 log_info(LD_OR,
1753 "Got good NETINFO cell from %s:%d; OR connection is now "
1754 "open, using protocol version %d. Its ID digest is %s. "
1755 "Our address is apparently %s.",
1756 safe_str_client(chan->conn->base_.address),
1757 chan->conn->base_.port,
1758 (int)(chan->conn->link_proto),
1759 hex_str(TLS_CHAN_TO_BASE(chan)->identity_digest,
1760 DIGEST_LEN),
1761 tor_addr_is_null(&my_apparent_addr) ?
1762 "<none>" : fmt_and_decorate_addr(&my_apparent_addr));
1764 assert_connection_ok(TO_CONN(chan->conn),time(NULL));
1768 * Process a CERTS cell from a channel.
1770 * This function is called to process an incoming CERTS cell on a
1771 * channel_tls_t:
1773 * If the other side should not have sent us a CERTS cell, or the cell is
1774 * malformed, or it is supposed to authenticate the TLS key but it doesn't,
1775 * then mark the connection.
1777 * If the cell has a good cert chain and we're doing a v3 handshake, then
1778 * store the certificates in or_handshake_state. If this is the client side
1779 * of the connection, we then authenticate the server or mark the connection.
1780 * If it's the server side, wait for an AUTHENTICATE cell.
1783 STATIC void
1784 channel_tls_process_certs_cell(var_cell_t *cell, channel_tls_t *chan)
1786 #define MAX_CERT_TYPE_WANTED OR_CERT_TYPE_AUTH_1024
1787 tor_x509_cert_t *certs[MAX_CERT_TYPE_WANTED + 1];
1788 int n_certs, i;
1789 certs_cell_t *cc = NULL;
1791 int send_netinfo = 0;
1793 memset(certs, 0, sizeof(certs));
1794 tor_assert(cell);
1795 tor_assert(chan);
1796 tor_assert(chan->conn);
1798 #define ERR(s) \
1799 do { \
1800 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
1801 "Received a bad CERTS cell from %s:%d: %s", \
1802 safe_str(chan->conn->base_.address), \
1803 chan->conn->base_.port, (s)); \
1804 connection_or_close_for_error(chan->conn, 0); \
1805 goto err; \
1806 } while (0)
1808 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
1809 ERR("We're not doing a v3 handshake!");
1810 if (chan->conn->link_proto < 3)
1811 ERR("We're not using link protocol >= 3");
1812 if (chan->conn->handshake_state->received_certs_cell)
1813 ERR("We already got one");
1814 if (chan->conn->handshake_state->authenticated) {
1815 /* Should be unreachable, but let's make sure. */
1816 ERR("We're already authenticated!");
1818 if (cell->payload_len < 1)
1819 ERR("It had no body");
1820 if (cell->circ_id)
1821 ERR("It had a nonzero circuit ID");
1823 if (certs_cell_parse(&cc, cell->payload, cell->payload_len) < 0)
1824 ERR("It couldn't be parsed.");
1826 n_certs = cc->n_certs;
1828 for (i = 0; i < n_certs; ++i) {
1829 certs_cell_cert_t *c = certs_cell_get_certs(cc, i);
1831 uint16_t cert_type = c->cert_type;
1832 uint16_t cert_len = c->cert_len;
1833 uint8_t *cert_body = certs_cell_cert_getarray_body(c);
1835 if (cert_type > MAX_CERT_TYPE_WANTED)
1836 continue;
1838 tor_x509_cert_t *cert = tor_x509_cert_decode(cert_body, cert_len);
1839 if (!cert) {
1840 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
1841 "Received undecodable certificate in CERTS cell from %s:%d",
1842 safe_str(chan->conn->base_.address),
1843 chan->conn->base_.port);
1844 } else {
1845 if (certs[cert_type]) {
1846 tor_x509_cert_free(cert);
1847 ERR("Duplicate x509 certificate");
1848 } else {
1849 certs[cert_type] = cert;
1854 tor_x509_cert_t *id_cert = certs[OR_CERT_TYPE_ID_1024];
1855 tor_x509_cert_t *auth_cert = certs[OR_CERT_TYPE_AUTH_1024];
1856 tor_x509_cert_t *link_cert = certs[OR_CERT_TYPE_TLS_LINK];
1858 if (chan->conn->handshake_state->started_here) {
1859 int severity;
1860 if (! (id_cert && link_cert))
1861 ERR("The certs we wanted were missing");
1862 /* Okay. We should be able to check the certificates now. */
1863 if (! tor_tls_cert_matches_key(chan->conn->tls, link_cert)) {
1864 ERR("The link certificate didn't match the TLS public key");
1866 /* Note that this warns more loudly about time and validity if we were
1867 * _trying_ to connect to an authority, not necessarily if we _did_ connect
1868 * to one. */
1869 if (router_digest_is_trusted_dir(
1870 TLS_CHAN_TO_BASE(chan)->identity_digest))
1871 severity = LOG_WARN;
1872 else
1873 severity = LOG_PROTOCOL_WARN;
1875 if (! tor_tls_cert_is_valid(severity, link_cert, id_cert, 0))
1876 ERR("The link certificate was not valid");
1877 if (! tor_tls_cert_is_valid(severity, id_cert, id_cert, 1))
1878 ERR("The ID certificate was not valid");
1880 chan->conn->handshake_state->authenticated = 1;
1882 const common_digests_t *id_digests =
1883 tor_x509_cert_get_id_digests(id_cert);
1884 crypto_pk_t *identity_rcvd;
1885 if (!id_digests)
1886 ERR("Couldn't compute digests for key in ID cert");
1888 identity_rcvd = tor_tls_cert_get_key(id_cert);
1889 if (!identity_rcvd)
1890 ERR("Internal error: Couldn't get RSA key from ID cert.");
1891 memcpy(chan->conn->handshake_state->authenticated_peer_id,
1892 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
1893 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
1894 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
1895 crypto_pk_free(identity_rcvd);
1898 if (connection_or_client_learned_peer_id(chan->conn,
1899 chan->conn->handshake_state->authenticated_peer_id) < 0)
1900 ERR("Problem setting or checking peer id");
1902 log_info(LD_OR,
1903 "Got some good certificates from %s:%d: Authenticated it.",
1904 safe_str(chan->conn->base_.address), chan->conn->base_.port);
1906 chan->conn->handshake_state->id_cert = id_cert;
1907 certs[OR_CERT_TYPE_ID_1024] = NULL;
1909 if (!public_server_mode(get_options())) {
1910 /* If we initiated the connection and we are not a public server, we
1911 * aren't planning to authenticate at all. At this point we know who we
1912 * are talking to, so we can just send a netinfo now. */
1913 send_netinfo = 1;
1915 } else {
1916 if (! (id_cert && auth_cert))
1917 ERR("The certs we wanted were missing");
1919 /* Remember these certificates so we can check an AUTHENTICATE cell */
1920 if (! tor_tls_cert_is_valid(LOG_PROTOCOL_WARN, auth_cert, id_cert, 1))
1921 ERR("The authentication certificate was not valid");
1922 if (! tor_tls_cert_is_valid(LOG_PROTOCOL_WARN, id_cert, id_cert, 1))
1923 ERR("The ID certificate was not valid");
1925 log_info(LD_OR,
1926 "Got some good certificates from %s:%d: "
1927 "Waiting for AUTHENTICATE.",
1928 safe_str(chan->conn->base_.address),
1929 chan->conn->base_.port);
1930 /* XXXX check more stuff? */
1932 chan->conn->handshake_state->id_cert = id_cert;
1933 chan->conn->handshake_state->auth_cert = auth_cert;
1934 certs[OR_CERT_TYPE_ID_1024] = certs[OR_CERT_TYPE_AUTH_1024] = NULL;
1937 chan->conn->handshake_state->received_certs_cell = 1;
1939 if (send_netinfo) {
1940 if (connection_or_send_netinfo(chan->conn) < 0) {
1941 log_warn(LD_OR, "Couldn't send netinfo cell");
1942 connection_or_close_for_error(chan->conn, 0);
1943 goto err;
1947 err:
1948 for (unsigned u = 0; u < ARRAY_LENGTH(certs); ++u) {
1949 tor_x509_cert_free(certs[u]);
1951 certs_cell_free(cc);
1952 #undef ERR
1956 * Process an AUTH_CHALLENGE cell from a channel_tls_t
1958 * This function is called to handle an incoming AUTH_CHALLENGE cell on a
1959 * channel_tls_t; if we weren't supposed to get one (for example, because we're
1960 * not the originator of the channel), or it's ill-formed, or we aren't doing
1961 * a v3 handshake, mark the channel. If the cell is well-formed but we don't
1962 * want to authenticate, just drop it. If the cell is well-formed *and* we
1963 * want to authenticate, send an AUTHENTICATE cell and then a NETINFO cell.
1966 STATIC void
1967 channel_tls_process_auth_challenge_cell(var_cell_t *cell, channel_tls_t *chan)
1969 int n_types, i, use_type = -1;
1970 auth_challenge_cell_t *ac = NULL;
1972 tor_assert(cell);
1973 tor_assert(chan);
1974 tor_assert(chan->conn);
1976 #define ERR(s) \
1977 do { \
1978 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
1979 "Received a bad AUTH_CHALLENGE cell from %s:%d: %s", \
1980 safe_str(chan->conn->base_.address), \
1981 chan->conn->base_.port, (s)); \
1982 connection_or_close_for_error(chan->conn, 0); \
1983 goto done; \
1984 } while (0)
1986 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
1987 ERR("We're not currently doing a v3 handshake");
1988 if (chan->conn->link_proto < 3)
1989 ERR("We're not using link protocol >= 3");
1990 if (!(chan->conn->handshake_state->started_here))
1991 ERR("We didn't originate this connection");
1992 if (chan->conn->handshake_state->received_auth_challenge)
1993 ERR("We already received one");
1994 if (!(chan->conn->handshake_state->received_certs_cell))
1995 ERR("We haven't gotten a CERTS cell yet");
1996 if (cell->circ_id)
1997 ERR("It had a nonzero circuit ID");
1999 if (auth_challenge_cell_parse(&ac, cell->payload, cell->payload_len) < 0)
2000 ERR("It was not well-formed.");
2002 n_types = ac->n_methods;
2004 /* Now see if there is an authentication type we can use */
2005 for (i = 0; i < n_types; ++i) {
2006 uint16_t authtype = auth_challenge_cell_get_methods(ac, i);
2007 if (authtype == AUTHTYPE_RSA_SHA256_TLSSECRET)
2008 use_type = authtype;
2011 chan->conn->handshake_state->received_auth_challenge = 1;
2013 if (! public_server_mode(get_options())) {
2014 /* If we're not a public server then we don't want to authenticate on a
2015 connection we originated, and we already sent a NETINFO cell when we
2016 got the CERTS cell. We have nothing more to do. */
2017 goto done;
2020 if (use_type >= 0) {
2021 log_info(LD_OR,
2022 "Got an AUTH_CHALLENGE cell from %s:%d: Sending "
2023 "authentication",
2024 safe_str(chan->conn->base_.address),
2025 chan->conn->base_.port);
2027 if (connection_or_send_authenticate_cell(chan->conn, use_type) < 0) {
2028 log_warn(LD_OR,
2029 "Couldn't send authenticate cell");
2030 connection_or_close_for_error(chan->conn, 0);
2031 goto done;
2033 } else {
2034 log_info(LD_OR,
2035 "Got an AUTH_CHALLENGE cell from %s:%d, but we don't "
2036 "know any of its authentication types. Not authenticating.",
2037 safe_str(chan->conn->base_.address),
2038 chan->conn->base_.port);
2041 if (connection_or_send_netinfo(chan->conn) < 0) {
2042 log_warn(LD_OR, "Couldn't send netinfo cell");
2043 connection_or_close_for_error(chan->conn, 0);
2044 goto done;
2047 done:
2048 auth_challenge_cell_free(ac);
2050 #undef ERR
2054 * Process an AUTHENTICATE cell from a channel_tls_t
2056 * If it's ill-formed or we weren't supposed to get one or we're not doing a
2057 * v3 handshake, then mark the connection. If it does not authenticate the
2058 * other side of the connection successfully (because it isn't signed right,
2059 * we didn't get a CERTS cell, etc) mark the connection. Otherwise, accept
2060 * the identity of the router on the other side of the connection.
2063 STATIC void
2064 channel_tls_process_authenticate_cell(var_cell_t *cell, channel_tls_t *chan)
2066 uint8_t expected[V3_AUTH_FIXED_PART_LEN+256];
2067 const uint8_t *auth;
2068 int authlen;
2070 tor_assert(cell);
2071 tor_assert(chan);
2072 tor_assert(chan->conn);
2074 #define ERR(s) \
2075 do { \
2076 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, \
2077 "Received a bad AUTHENTICATE cell from %s:%d: %s", \
2078 safe_str(chan->conn->base_.address), \
2079 chan->conn->base_.port, (s)); \
2080 connection_or_close_for_error(chan->conn, 0); \
2081 return; \
2082 } while (0)
2084 if (chan->conn->base_.state != OR_CONN_STATE_OR_HANDSHAKING_V3)
2085 ERR("We're not doing a v3 handshake");
2086 if (chan->conn->link_proto < 3)
2087 ERR("We're not using link protocol >= 3");
2088 if (chan->conn->handshake_state->started_here)
2089 ERR("We originated this connection");
2090 if (chan->conn->handshake_state->received_authenticate)
2091 ERR("We already got one!");
2092 if (chan->conn->handshake_state->authenticated) {
2093 /* Should be impossible given other checks */
2094 ERR("The peer is already authenticated");
2096 if (!(chan->conn->handshake_state->received_certs_cell))
2097 ERR("We never got a certs cell");
2098 if (chan->conn->handshake_state->auth_cert == NULL)
2099 ERR("We never got an authentication certificate");
2100 if (chan->conn->handshake_state->id_cert == NULL)
2101 ERR("We never got an identity certificate");
2102 if (cell->payload_len < 4)
2103 ERR("Cell was way too short");
2105 auth = cell->payload;
2107 uint16_t type = ntohs(get_uint16(auth));
2108 uint16_t len = ntohs(get_uint16(auth+2));
2109 if (4 + len > cell->payload_len)
2110 ERR("Authenticator was truncated");
2112 if (type != AUTHTYPE_RSA_SHA256_TLSSECRET)
2113 ERR("Authenticator type was not recognized");
2115 auth += 4;
2116 authlen = len;
2119 if (authlen < V3_AUTH_BODY_LEN + 1)
2120 ERR("Authenticator was too short");
2122 ssize_t bodylen =
2123 connection_or_compute_authenticate_cell_body(
2124 chan->conn, expected, sizeof(expected), NULL, 1);
2125 if (bodylen < 0 || bodylen != V3_AUTH_FIXED_PART_LEN)
2126 ERR("Couldn't compute expected AUTHENTICATE cell body");
2128 if (tor_memneq(expected, auth, bodylen))
2129 ERR("Some field in the AUTHENTICATE cell body was not as expected");
2132 crypto_pk_t *pk = tor_tls_cert_get_key(
2133 chan->conn->handshake_state->auth_cert);
2134 char d[DIGEST256_LEN];
2135 char *signed_data;
2136 size_t keysize;
2137 int signed_len;
2139 if (!pk)
2140 ERR("Internal error: couldn't get RSA key from AUTH cert.");
2141 crypto_digest256(d, (char*)auth, V3_AUTH_BODY_LEN, DIGEST_SHA256);
2143 keysize = crypto_pk_keysize(pk);
2144 signed_data = tor_malloc(keysize);
2145 signed_len = crypto_pk_public_checksig(pk, signed_data, keysize,
2146 (char*)auth + V3_AUTH_BODY_LEN,
2147 authlen - V3_AUTH_BODY_LEN);
2148 crypto_pk_free(pk);
2149 if (signed_len < 0) {
2150 tor_free(signed_data);
2151 ERR("Signature wasn't valid");
2153 if (signed_len < DIGEST256_LEN) {
2154 tor_free(signed_data);
2155 ERR("Not enough data was signed");
2157 /* Note that we deliberately allow *more* than DIGEST256_LEN bytes here,
2158 * in case they're later used to hold a SHA3 digest or something. */
2159 if (tor_memneq(signed_data, d, DIGEST256_LEN)) {
2160 tor_free(signed_data);
2161 ERR("Signature did not match data to be signed.");
2163 tor_free(signed_data);
2166 /* Okay, we are authenticated. */
2167 chan->conn->handshake_state->received_authenticate = 1;
2168 chan->conn->handshake_state->authenticated = 1;
2169 chan->conn->handshake_state->digest_received_data = 0;
2171 crypto_pk_t *identity_rcvd =
2172 tor_tls_cert_get_key(chan->conn->handshake_state->id_cert);
2173 const common_digests_t *id_digests =
2174 tor_x509_cert_get_id_digests(chan->conn->handshake_state->id_cert);
2176 /* This must exist; we checked key type when reading the cert. */
2177 tor_assert(id_digests);
2179 memcpy(chan->conn->handshake_state->authenticated_peer_id,
2180 id_digests->d[DIGEST_SHA1], DIGEST_LEN);
2182 channel_set_circid_type(TLS_CHAN_TO_BASE(chan), identity_rcvd,
2183 chan->conn->link_proto < MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS);
2184 crypto_pk_free(identity_rcvd);
2186 connection_or_init_conn_from_address(chan->conn,
2187 &(chan->conn->base_.addr),
2188 chan->conn->base_.port,
2189 (const char*)(chan->conn->handshake_state->
2190 authenticated_peer_id),
2193 log_info(LD_OR,
2194 "Got an AUTHENTICATE cell from %s:%d: Looks good.",
2195 safe_str(chan->conn->base_.address),
2196 chan->conn->base_.port);
2199 #undef ERR