LCOV - code coverage report
Current view: top level - core/or - channeltls.c (source / functions) Hit Total Coverage
Test: lcov.info Lines: 421 947 44.5 %
Date: 2021-11-24 03:28:48 Functions: 18 46 39.1 %

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

Generated by: LCOV version 1.14