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