LCOV - code coverage report
Current view: top level - core/or - channelpadding.c (source / functions) Hit Total Coverage
Test: lcov.info Lines: 201 207 97.1 %
Date: 2021-11-24 03:28:48 Functions: 14 14 100.0 %

          Line data    Source code
       1             : /* Copyright (c) 2001 Matej Pfajfar.
       2             :  * Copyright (c) 2001-2004, Roger Dingledine.
       3             :  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
       4             :  * Copyright (c) 2007-2021, The Tor Project, Inc. */
       5             : /* See LICENSE for licensing information */
       6             : 
       7             : /**
       8             :  * @file channelpadding.c
       9             :  * @brief Link-level padding code.
      10             :  **/
      11             : 
      12             : /* CHANNEL_OBJECT_PRIVATE define needed for an O(1) implementation of
      13             :  * channelpadding_channel_to_channelinfo() */
      14             : #define CHANNEL_OBJECT_PRIVATE
      15             : 
      16             : #include "core/or/or.h"
      17             : #include "core/or/channel.h"
      18             : #include "core/or/channelpadding.h"
      19             : #include "core/or/channeltls.h"
      20             : #include "app/config/config.h"
      21             : #include "feature/nodelist/networkstatus.h"
      22             : #include "core/mainloop/connection.h"
      23             : #include "core/or/connection_or.h"
      24             : #include "lib/crypt_ops/crypto_rand.h"
      25             : #include "core/mainloop/mainloop.h"
      26             : #include "feature/stats/rephist.h"
      27             : #include "feature/relay/router.h"
      28             : #include "feature/relay/routermode.h"
      29             : #include "lib/time/compat_time.h"
      30             : #include "lib/evloop/timers.h"
      31             : #include "feature/hs/hs_service.h"
      32             : 
      33             : #include "core/or/cell_st.h"
      34             : #include "core/or/or_connection_st.h"
      35             : 
      36             : STATIC int32_t channelpadding_get_netflow_inactive_timeout_ms(
      37             :                                                            const channel_t *);
      38             : STATIC int channelpadding_send_disable_command(channel_t *);
      39             : STATIC int64_t channelpadding_compute_time_until_pad_for_netflow(channel_t *);
      40             : 
      41             : /** The total number of pending channelpadding timers */
      42             : static uint64_t total_timers_pending;
      43             : 
      44             : /** These are cached consensus parameters for netflow */
      45             : /** The timeout lower bound that is allowed before sending padding */
      46             : static int consensus_nf_ito_low;
      47             : /** The timeout upper bound that is allowed before sending padding */
      48             : static int consensus_nf_ito_high;
      49             : /** The timeout lower bound that is allowed before sending reduced padding */
      50             : static int consensus_nf_ito_low_reduced;
      51             : /** The timeout upper bound that is allowed before sending reduced padding */
      52             : static int consensus_nf_ito_high_reduced;
      53             : /** The connection timeout between relays */
      54             : static int consensus_nf_conntimeout_relays;
      55             : /** The connection timeout for client connections */
      56             : static int consensus_nf_conntimeout_clients;
      57             : /** Should we pad before circuits are actually used for client data? */
      58             : static int consensus_nf_pad_before_usage;
      59             : /** Should we pad relay-to-relay connections? */
      60             : static int consensus_nf_pad_relays;
      61             : /** Should we pad rosos connections? */
      62             : static int consensus_nf_pad_single_onion;
      63             : 
      64             : #define TOR_MSEC_PER_SEC 1000
      65             : #define TOR_USEC_PER_MSEC 1000
      66             : 
      67             : /**
      68             :  * How often do we get called by the connection housekeeping (ie: once
      69             :  * per second) */
      70             : #define TOR_HOUSEKEEPING_CALLBACK_MSEC 1000
      71             : /**
      72             :  * Additional extra time buffer on the housekeeping callback, since
      73             :  * it can be delayed. This extra slack is used to decide if we should
      74             :  * schedule a timer or wait for the next callback. */
      75             : #define TOR_HOUSEKEEPING_CALLBACK_SLACK_MSEC 100
      76             : 
      77             : /**
      78             :  * This macro tells us if either end of the channel is connected to a client.
      79             :  * (If we're not a server, we're definitely a client. If the channel thinks
      80             :  *  it's a client, use that. Then finally verify in the consensus).
      81             :  */
      82             : #define CHANNEL_IS_CLIENT(chan, options) \
      83             :   (!public_server_mode((options)) || channel_is_client(chan) || \
      84             :       !connection_or_digest_is_known_relay((chan)->identity_digest))
      85             : 
      86             : /**
      87             :  * This function is called to update cached consensus parameters every time
      88             :  * there is a consensus update. This allows us to move the consensus param
      89             :  * search off of the critical path, so it does not need to be evaluated
      90             :  * for every single connection, every second.
      91             :  */
      92             : void
      93         222 : channelpadding_new_consensus_params(const networkstatus_t *ns)
      94             : {
      95             : #define DFLT_NETFLOW_INACTIVE_KEEPALIVE_LOW 1500
      96             : #define DFLT_NETFLOW_INACTIVE_KEEPALIVE_HIGH 9500
      97             : #define DFLT_NETFLOW_INACTIVE_KEEPALIVE_MIN 0
      98             : #define DFLT_NETFLOW_INACTIVE_KEEPALIVE_MAX 60000
      99         222 :   consensus_nf_ito_low = networkstatus_get_param(ns, "nf_ito_low",
     100             :       DFLT_NETFLOW_INACTIVE_KEEPALIVE_LOW,
     101             :       DFLT_NETFLOW_INACTIVE_KEEPALIVE_MIN,
     102             :       DFLT_NETFLOW_INACTIVE_KEEPALIVE_MAX);
     103         222 :   consensus_nf_ito_high = networkstatus_get_param(ns, "nf_ito_high",
     104             :       DFLT_NETFLOW_INACTIVE_KEEPALIVE_HIGH,
     105             :       consensus_nf_ito_low,
     106             :       DFLT_NETFLOW_INACTIVE_KEEPALIVE_MAX);
     107             : 
     108             : #define DFLT_NETFLOW_REDUCED_KEEPALIVE_LOW 9000
     109             : #define DFLT_NETFLOW_REDUCED_KEEPALIVE_HIGH 14000
     110             : #define DFLT_NETFLOW_REDUCED_KEEPALIVE_MIN 0
     111             : #define DFLT_NETFLOW_REDUCED_KEEPALIVE_MAX 60000
     112         444 :   consensus_nf_ito_low_reduced =
     113         222 :     networkstatus_get_param(ns, "nf_ito_low_reduced",
     114             :         DFLT_NETFLOW_REDUCED_KEEPALIVE_LOW,
     115             :         DFLT_NETFLOW_REDUCED_KEEPALIVE_MIN,
     116             :         DFLT_NETFLOW_REDUCED_KEEPALIVE_MAX);
     117             : 
     118         444 :   consensus_nf_ito_high_reduced =
     119         222 :     networkstatus_get_param(ns, "nf_ito_high_reduced",
     120             :         DFLT_NETFLOW_REDUCED_KEEPALIVE_HIGH,
     121             :         consensus_nf_ito_low_reduced,
     122             :         DFLT_NETFLOW_REDUCED_KEEPALIVE_MAX);
     123             : 
     124             : #define CONNTIMEOUT_RELAYS_DFLT (60*60) // 1 hour
     125             : #define CONNTIMEOUT_RELAYS_MIN 60
     126             : #define CONNTIMEOUT_RELAYS_MAX (7*24*60*60) // 1 week
     127         444 :   consensus_nf_conntimeout_relays =
     128         222 :     networkstatus_get_param(ns, "nf_conntimeout_relays",
     129             :         CONNTIMEOUT_RELAYS_DFLT,
     130             :         CONNTIMEOUT_RELAYS_MIN,
     131             :         CONNTIMEOUT_RELAYS_MAX);
     132             : 
     133             : #define CIRCTIMEOUT_CLIENTS_DFLT (30*60) // 30 minutes
     134             : #define CIRCTIMEOUT_CLIENTS_MIN 60
     135             : #define CIRCTIMEOUT_CLIENTS_MAX (24*60*60) // 24 hours
     136         444 :   consensus_nf_conntimeout_clients =
     137         222 :     networkstatus_get_param(ns, "nf_conntimeout_clients",
     138             :         CIRCTIMEOUT_CLIENTS_DFLT,
     139             :         CIRCTIMEOUT_CLIENTS_MIN,
     140             :         CIRCTIMEOUT_CLIENTS_MAX);
     141             : 
     142         444 :   consensus_nf_pad_before_usage =
     143         222 :     networkstatus_get_param(ns, "nf_pad_before_usage", 1, 0, 1);
     144             : 
     145         444 :   consensus_nf_pad_relays =
     146         222 :     networkstatus_get_param(ns, "nf_pad_relays", 0, 0, 1);
     147             : 
     148         444 :   consensus_nf_pad_single_onion =
     149         222 :     networkstatus_get_param(ns,
     150             :                             CHANNELPADDING_SOS_PARAM,
     151             :                             CHANNELPADDING_SOS_DEFAULT, 0, 1);
     152         222 : }
     153             : 
     154             : /**
     155             :  * Get a random netflow inactive timeout keepalive period in milliseconds,
     156             :  * the range for which is determined by consensus parameters, negotiation,
     157             :  * configuration, or default values. The consensus parameters enforce the
     158             :  * minimum possible value, to avoid excessively frequent padding.
     159             :  *
     160             :  * The ranges for this value were chosen to be low enough to ensure that
     161             :  * routers do not emit a new netflow record for a connection due to it
     162             :  * being idle.
     163             :  *
     164             :  * Specific timeout values for major routers are listed in Proposal 251.
     165             :  * No major router appeared capable of setting an inactive timeout below 10
     166             :  * seconds, so we set the defaults below that value, since we can always
     167             :  * scale back if it ends up being too much padding.
     168             :  *
     169             :  * Returns the next timeout period (in milliseconds) after which we should
     170             :  * send a padding packet, or 0 if padding is disabled.
     171             :  */
     172             : STATIC int32_t
     173          14 : channelpadding_get_netflow_inactive_timeout_ms(const channel_t *chan)
     174             : {
     175          14 :   int low_timeout = consensus_nf_ito_low;
     176          14 :   int high_timeout = consensus_nf_ito_high;
     177          14 :   int X1, X2;
     178             : 
     179          14 :   if (low_timeout == 0 && low_timeout == high_timeout)
     180             :     return 0; // No padding
     181             : 
     182             :   /* If we have negotiated different timeout values, use those, but
     183             :    * don't allow them to be lower than the consensus ones */
     184           8 :   if (chan->padding_timeout_low_ms && chan->padding_timeout_high_ms) {
     185           6 :     low_timeout = MAX(low_timeout, chan->padding_timeout_low_ms);
     186           6 :     high_timeout = MAX(high_timeout, chan->padding_timeout_high_ms);
     187             :   }
     188             : 
     189           8 :   if (low_timeout == high_timeout)
     190             :     return low_timeout; // No randomization
     191             : 
     192             :   /*
     193             :    * This MAX() hack is here because we apply the timeout on both the client
     194             :    * and the server. This creates the situation where the total time before
     195             :    * sending a packet in either direction is actually
     196             :    * min(client_timeout,server_timeout).
     197             :    *
     198             :    * If X is a random variable uniform from 0..R-1 (where R=high-low),
     199             :    * then Y=max(X,X) has Prob(Y == i) = (2.0*i + 1)/(R*R).
     200             :    *
     201             :    * If we create a third random variable Z=min(Y,Y), then it turns out that
     202             :    * Exp[Z] ~= Exp[X]. Here's a table:
     203             :    *
     204             :    *    R     Exp[X]    Exp[Z]    Exp[min(X,X)]   Exp[max(X,X)]
     205             :    *  2000     999.5    1066        666.2           1332.8
     206             :    *  3000    1499.5    1599.5      999.5           1999.5
     207             :    *  5000    2499.5    2666       1666.2           3332.8
     208             :    *  6000    2999.5    3199.5     1999.5           3999.5
     209             :    *  7000    3499.5    3732.8     2332.8           4666.2
     210             :    *  8000    3999.5    4266.2     2666.2           5332.8
     211             :    *  10000   4999.5    5328       3332.8           6666.2
     212             :    *  15000   7499.5    7995       4999.5           9999.5
     213             :    *  20000   9900.5    10661      6666.2           13332.8
     214             :    *
     215             :    * In other words, this hack makes it so that when both the client and
     216             :    * the guard are sending this padding, then the averages work out closer
     217             :    * to the midpoint of the range, making the overhead easier to tune.
     218             :    * If only one endpoint is padding (for example: if the relay does not
     219             :    * support padding, but the client has set ConnectionPadding 1; or
     220             :    * if the relay does support padding, but the client has set
     221             :    * ReducedConnectionPadding 1), then the defense will still prevent
     222             :    * record splitting, but with less overhead than the midpoint
     223             :    * (as seen by the Exp[max(X,X)] column).
     224             :    *
     225             :    * To calculate average padding packet frequency (and thus overhead),
     226             :    * index into the table by picking a row based on R = high-low. Then,
     227             :    * use the appropriate column (Exp[Z] for two-sided padding, and
     228             :    * Exp[max(X,X)] for one-sided padding). Finally, take this value
     229             :    * and add it to the low timeout value. This value is the average
     230             :    * frequency which padding packets will be sent.
     231             :    */
     232             : 
     233           8 :   X1 = crypto_rand_int(high_timeout - low_timeout);
     234           8 :   X2 = crypto_rand_int(high_timeout - low_timeout);
     235           8 :   return low_timeout + MAX(X1, X2);
     236             : }
     237             : 
     238             : /**
     239             :  * Update this channel's padding settings based on the PADDING_NEGOTIATE
     240             :  * contents.
     241             :  *
     242             :  * Returns -1 on error; 1 on success.
     243             :  */
     244             : int
     245          10 : channelpadding_update_padding_for_channel(channel_t *chan,
     246             :                 const channelpadding_negotiate_t *pad_vars)
     247             : {
     248          10 :   if (pad_vars->version != 0) {
     249           1 :     static ratelim_t version_limit = RATELIM_INIT(600);
     250             : 
     251           1 :     log_fn_ratelim(&version_limit,LOG_PROTOCOL_WARN,LD_PROTOCOL,
     252             :            "Got a PADDING_NEGOTIATE cell with an unknown version. Ignoring.");
     253           1 :     return -1;
     254             :   }
     255             : 
     256             :   // We should not allow malicious relays to disable or reduce padding for
     257             :   // us as clients. In fact, we should only accept this cell at all if we're
     258             :   // operating as a relay. Bridges should not accept it from relays, either
     259             :   // (only from their clients).
     260          11 :   if ((get_options()->BridgeRelay &&
     261           2 :        connection_or_digest_is_known_relay(chan->identity_digest)) ||
     262           8 :       !get_options()->ORPort_set) {
     263           2 :     static ratelim_t relay_limit = RATELIM_INIT(600);
     264             : 
     265           2 :     log_fn_ratelim(&relay_limit,LOG_PROTOCOL_WARN,LD_PROTOCOL,
     266             :            "Got a PADDING_NEGOTIATE from relay at %s (%s). "
     267             :            "This should not happen.",
     268             :            channel_describe_peer(chan),
     269             :            hex_str(chan->identity_digest, DIGEST_LEN));
     270           2 :     return -1;
     271             :   }
     272             : 
     273           7 :   chan->padding_enabled = (pad_vars->command == CHANNELPADDING_COMMAND_START);
     274             : 
     275             :   /* Min must not be lower than the current consensus parameter
     276             :      nf_ito_low. */
     277           7 :   chan->padding_timeout_low_ms = MAX(consensus_nf_ito_low,
     278             :                                      pad_vars->ito_low_ms);
     279             : 
     280             :   /* Max must not be lower than ito_low_ms */
     281           7 :   chan->padding_timeout_high_ms = MAX(chan->padding_timeout_low_ms,
     282             :                                       pad_vars->ito_high_ms);
     283             : 
     284           7 :   log_fn(LOG_INFO,LD_OR,
     285             :          "Negotiated padding=%d, lo=%d, hi=%d on %"PRIu64,
     286             :          chan->padding_enabled, chan->padding_timeout_low_ms,
     287             :          chan->padding_timeout_high_ms,
     288             :          (chan->global_identifier));
     289             : 
     290           7 :   return 1;
     291             : }
     292             : 
     293             : /**
     294             :  * Sends a CELL_PADDING_NEGOTIATE on the channel to tell the other side not
     295             :  * to send padding.
     296             :  *
     297             :  * Returns -1 on error, 0 on success.
     298             :  */
     299             : STATIC int
     300           6 : channelpadding_send_disable_command(channel_t *chan)
     301             : {
     302           6 :   channelpadding_negotiate_t disable;
     303           6 :   cell_t cell;
     304             : 
     305           6 :   tor_assert(chan);
     306           6 :   tor_assert(BASE_CHAN_TO_TLS(chan)->conn->link_proto >=
     307             :              MIN_LINK_PROTO_FOR_CHANNEL_PADDING);
     308             : 
     309           6 :   memset(&cell, 0, sizeof(cell_t));
     310           6 :   memset(&disable, 0, sizeof(channelpadding_negotiate_t));
     311           6 :   cell.command = CELL_PADDING_NEGOTIATE;
     312             : 
     313           6 :   channelpadding_negotiate_set_command(&disable, CHANNELPADDING_COMMAND_STOP);
     314             : 
     315           6 :   if (channelpadding_negotiate_encode(cell.payload, CELL_PAYLOAD_SIZE,
     316             :                                       &disable) < 0)
     317             :     return -1;
     318             : 
     319           6 :   if (chan->write_cell(chan, &cell) == 1)
     320             :     return 0;
     321             :   else
     322           6 :     return -1;
     323             : }
     324             : 
     325             : /**
     326             :  * Sends a CELL_PADDING_NEGOTIATE on the channel to tell the other side to
     327             :  * resume sending padding at some rate.
     328             :  *
     329             :  * Returns -1 on error, 0 on success.
     330             :  */
     331             : int
     332           2 : channelpadding_send_enable_command(channel_t *chan, uint16_t low_timeout,
     333             :                                    uint16_t high_timeout)
     334             : {
     335           2 :   channelpadding_negotiate_t enable;
     336           2 :   cell_t cell;
     337             : 
     338           2 :   tor_assert(chan);
     339           2 :   tor_assert(BASE_CHAN_TO_TLS(chan)->conn->link_proto >=
     340             :              MIN_LINK_PROTO_FOR_CHANNEL_PADDING);
     341             : 
     342           2 :   memset(&cell, 0, sizeof(cell_t));
     343           2 :   memset(&enable, 0, sizeof(channelpadding_negotiate_t));
     344           2 :   cell.command = CELL_PADDING_NEGOTIATE;
     345             : 
     346           2 :   channelpadding_negotiate_set_command(&enable, CHANNELPADDING_COMMAND_START);
     347           2 :   channelpadding_negotiate_set_ito_low_ms(&enable, low_timeout);
     348           2 :   channelpadding_negotiate_set_ito_high_ms(&enable, high_timeout);
     349             : 
     350           2 :   if (channelpadding_negotiate_encode(cell.payload, CELL_PAYLOAD_SIZE,
     351             :                                       &enable) < 0)
     352             :     return -1;
     353             : 
     354           2 :   if (chan->write_cell(chan, &cell) == 1)
     355             :     return 0;
     356             :   else
     357           2 :     return -1;
     358             : }
     359             : 
     360             : /**
     361             :  * Sends a CELL_PADDING cell on a channel if it has been idle since
     362             :  * our callback was scheduled.
     363             :  *
     364             :  * This function also clears the pending padding timer and the callback
     365             :  * flags.
     366             :  */
     367             : static void
     368         211 : channelpadding_send_padding_cell_for_callback(channel_t *chan)
     369             : {
     370         211 :   cell_t cell;
     371             : 
     372             :   /* Check that the channel is still valid and open */
     373         211 :   if (!chan || chan->state != CHANNEL_STATE_OPEN) {
     374           1 :     if (chan) chan->pending_padding_callback = 0;
     375           1 :     log_fn(LOG_INFO,LD_OR,
     376             :            "Scheduled a netflow padding cell, but connection already closed.");
     377           3 :     return;
     378             :   }
     379             : 
     380             :   /* We should have a pending callback flag set. */
     381         210 :   if (BUG(chan->pending_padding_callback == 0))
     382           0 :     return;
     383             : 
     384         210 :   chan->pending_padding_callback = 0;
     385             : 
     386         419 :   if (monotime_coarse_is_zero(&chan->next_padding_time) ||
     387         209 :       chan->has_queued_writes(chan) ||
     388         209 :       (chan->cmux && circuitmux_num_cells(chan->cmux))) {
     389             :     /* We must have been active before the timer fired */
     390           1 :     monotime_coarse_zero(&chan->next_padding_time);
     391           1 :     return;
     392             :   }
     393             : 
     394             :   {
     395         209 :     monotime_coarse_t now;
     396         209 :     monotime_coarse_get(&now);
     397             : 
     398         209 :     log_fn(LOG_INFO,LD_OR,
     399             :         "Sending netflow keepalive on %"PRIu64" to %s (%s) after "
     400             :         "%"PRId64" ms. Delta %"PRId64"ms",
     401             :         (chan->global_identifier),
     402             :         safe_str_client(channel_describe_peer(chan)),
     403             :         safe_str_client(hex_str(chan->identity_digest, DIGEST_LEN)),
     404             :         (monotime_coarse_diff_msec(&chan->timestamp_xfer,&now)),
     405             :         (
     406             :                    monotime_coarse_diff_msec(&chan->next_padding_time,&now)));
     407             :   }
     408             : 
     409             :   /* Clear the timer */
     410         209 :   monotime_coarse_zero(&chan->next_padding_time);
     411             : 
     412             :   /* Send the padding cell. This will cause the channel to get a
     413             :    * fresh timestamp_active */
     414         209 :   memset(&cell, 0, sizeof(cell));
     415         209 :   cell.command = CELL_PADDING;
     416         209 :   chan->write_cell(chan, &cell);
     417             : }
     418             : 
     419             : /**
     420             :  * tor_timer callback function for us to send padding on an idle channel.
     421             :  *
     422             :  * This function just obtains the channel from the callback handle, ensures
     423             :  * it is still valid, and then hands it off to
     424             :  * channelpadding_send_padding_cell_for_callback(), which checks if
     425             :  * the channel is still idle before sending padding.
     426             :  */
     427             : static void
     428         209 : channelpadding_send_padding_callback(tor_timer_t *timer, void *args,
     429             :                                      const struct monotime_t *when)
     430             : {
     431         209 :   channel_t *chan = channel_handle_get((struct channel_handle_t*)args);
     432         209 :   (void)timer; (void)when;
     433             : 
     434         209 :   if (chan && CHANNEL_CAN_HANDLE_CELLS(chan)) {
     435             :     /* Hrmm.. It might be nice to have an equivalent to assert_connection_ok
     436             :      * for channels. Then we could get rid of the channeltls dependency */
     437         209 :     tor_assert(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn)->magic ==
     438             :                OR_CONNECTION_MAGIC);
     439         209 :     assert_connection_ok(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn), approx_time());
     440             : 
     441         209 :     channelpadding_send_padding_cell_for_callback(chan);
     442             :   } else {
     443           0 :      log_fn(LOG_INFO,LD_OR,
     444             :             "Channel closed while waiting for timer.");
     445             :   }
     446             : 
     447         209 :   total_timers_pending--;
     448         209 : }
     449             : 
     450             : /**
     451             :  * Schedules a callback to send padding on a channel in_ms milliseconds from
     452             :  * now.
     453             :  *
     454             :  * Returns CHANNELPADDING_WONTPAD on error, CHANNELPADDING_PADDING_SENT if we
     455             :  * sent the packet immediately without a timer, and
     456             :  * CHANNELPADDING_PADDING_SCHEDULED if we decided to schedule a timer.
     457             :  */
     458             : static channelpadding_decision_t
     459         212 : channelpadding_schedule_padding(channel_t *chan, int in_ms)
     460             : {
     461         212 :   struct timeval timeout;
     462         212 :   tor_assert(!chan->pending_padding_callback);
     463             : 
     464         212 :   if (in_ms <= 0) {
     465           2 :     chan->pending_padding_callback = 1;
     466           2 :     channelpadding_send_padding_cell_for_callback(chan);
     467           2 :     return CHANNELPADDING_PADDING_SENT;
     468             :   }
     469             : 
     470         210 :   timeout.tv_sec = in_ms/TOR_MSEC_PER_SEC;
     471         210 :   timeout.tv_usec = (in_ms%TOR_USEC_PER_MSEC)*TOR_USEC_PER_MSEC;
     472             : 
     473         210 :   if (!chan->timer_handle) {
     474         104 :     chan->timer_handle = channel_handle_new(chan);
     475             :   }
     476             : 
     477         210 :   if (chan->padding_timer) {
     478         106 :     timer_set_cb(chan->padding_timer,
     479             :                  channelpadding_send_padding_callback,
     480         106 :                  chan->timer_handle);
     481             :   } else {
     482         104 :     chan->padding_timer = timer_new(channelpadding_send_padding_callback,
     483         104 :                                     chan->timer_handle);
     484             :   }
     485         210 :   timer_schedule(chan->padding_timer, &timeout);
     486             : 
     487         210 :   rep_hist_padding_count_timers(++total_timers_pending);
     488             : 
     489         210 :   chan->pending_padding_callback = 1;
     490         210 :   return CHANNELPADDING_PADDING_SCHEDULED;
     491             : }
     492             : 
     493             : /**
     494             :  * Calculates the number of milliseconds from now to schedule a padding cell.
     495             :  *
     496             :  * Returns the number of milliseconds from now (relative) to schedule the
     497             :  * padding callback. If the padding timer is more than 1.1 seconds in the
     498             :  * future, we return -1, to avoid scheduling excessive callbacks. If padding
     499             :  * is disabled in the consensus, we return -2.
     500             :  *
     501             :  * Side-effects: Updates chan->next_padding_time_ms, storing an (absolute, not
     502             :  * relative) millisecond representation of when we should send padding, unless
     503             :  * other activity happens first. This side-effect allows us to avoid
     504             :  * scheduling a libevent callback until we're within 1.1 seconds of the padding
     505             :  * time.
     506             :  */
     507             : #define CHANNELPADDING_TIME_LATER -1
     508             : #define CHANNELPADDING_TIME_DISABLED -2
     509             : STATIC int64_t
     510         227 : channelpadding_compute_time_until_pad_for_netflow(channel_t *chan)
     511             : {
     512         227 :   monotime_coarse_t now;
     513         227 :   monotime_coarse_get(&now);
     514             : 
     515         227 :   if (monotime_coarse_is_zero(&chan->next_padding_time)) {
     516             :     /* If the below line or crypto_rand_int() shows up on a profile,
     517             :      * we can avoid getting a timeout until we're at least nf_ito_lo
     518             :      * from a timeout window. That will prevent us from setting timers
     519             :      * on connections that were active up to 1.5 seconds ago.
     520             :      * Idle connections should only call this once every 5.5s on average
     521             :      * though, so that might be a micro-optimization for little gain. */
     522           8 :     int32_t padding_timeout =
     523           8 :         channelpadding_get_netflow_inactive_timeout_ms(chan);
     524             : 
     525           8 :     if (!padding_timeout)
     526             :       return CHANNELPADDING_TIME_DISABLED;
     527             : 
     528           4 :     monotime_coarse_add_msec(&chan->next_padding_time,
     529           4 :                              &chan->timestamp_xfer,
     530             :                              padding_timeout);
     531             :   }
     532             : 
     533         223 :   const int64_t ms_till_pad =
     534         223 :     monotime_coarse_diff_msec(&now, &chan->next_padding_time);
     535             : 
     536             :   /* If the next padding time is beyond the maximum possible consensus value,
     537             :    * then this indicates a clock jump, so just send padding now. This is
     538             :    * better than using monotonic time because we want to avoid the situation
     539             :    * where we wait around forever for monotonic time to move forward after
     540             :    * a clock jump far into the past.
     541             :    */
     542         223 :   if (ms_till_pad > DFLT_NETFLOW_INACTIVE_KEEPALIVE_MAX) {
     543           0 :     tor_fragile_assert();
     544           0 :     log_warn(LD_BUG,
     545             :         "Channel padding timeout scheduled %"PRId64"ms in the future. "
     546             :         "Did the monotonic clock just jump?",
     547             :         (ms_till_pad));
     548           0 :     return 0; /* Clock jumped: Send padding now */
     549             :   }
     550             : 
     551             :   /* If the timeout will expire before the next time we're called (1000ms
     552             :      from now, plus some slack), then calculate the number of milliseconds
     553             :      from now which we should send padding, so we can schedule a callback
     554             :      then.
     555             :    */
     556         223 :   if (ms_till_pad < (TOR_HOUSEKEEPING_CALLBACK_MSEC +
     557             :                        TOR_HOUSEKEEPING_CALLBACK_SLACK_MSEC)) {
     558             :     /* If the padding time is in the past, that means that libevent delayed
     559             :      * calling the once-per-second callback due to other work taking too long.
     560             :      * See https://bugs.torproject.org/22212 and
     561             :      * https://bugs.torproject.org/16585. This is a systemic problem
     562             :      * with being single-threaded, but let's emit a notice if this
     563             :      * is long enough in the past that we might have missed a netflow window,
     564             :      * and allowed a router to emit a netflow frame, just so we don't forget
     565             :      * about it entirely.. */
     566             : #define NETFLOW_MISSED_WINDOW (150000 - DFLT_NETFLOW_INACTIVE_KEEPALIVE_HIGH)
     567         213 :     if (ms_till_pad < 0) {
     568           2 :       int severity = (ms_till_pad < -NETFLOW_MISSED_WINDOW)
     569           1 :                       ? LOG_NOTICE : LOG_INFO;
     570           1 :       log_fn(severity, LD_OR,
     571             :               "Channel padding timeout scheduled %"PRId64"ms in the past. ",
     572             :              (-ms_till_pad));
     573           1 :       return 0; /* Clock jumped: Send padding now */
     574             :     }
     575             : 
     576             :     return ms_till_pad;
     577             :   }
     578             :   return CHANNELPADDING_TIME_LATER;
     579             : }
     580             : 
     581             : /**
     582             :  * Returns a randomized value for channel idle timeout in seconds.
     583             :  * The channel idle timeout governs how quickly we close a channel
     584             :  * after its last circuit has disappeared.
     585             :  *
     586             :  * There are three classes of channels:
     587             :  *  1. Client+non-canonical. These live for 3-4.5 minutes
     588             :  *  2. relay to relay. These live for 45-75 min by default
     589             :  *  3. Reduced padding clients. These live for 1.5-2.25 minutes.
     590             :  *
     591             :  * Also allows the default relay-to-relay value to be controlled by the
     592             :  * consensus.
     593             :  */
     594             : unsigned int
     595         335 : channelpadding_get_channel_idle_timeout(const channel_t *chan,
     596             :                                         int is_canonical)
     597             : {
     598         335 :   const or_options_t *options = get_options();
     599         335 :   unsigned int timeout;
     600             : 
     601             :   /* Non-canonical and client channels only last for 3-4.5 min when idle */
     602         335 :   if (!is_canonical || CHANNEL_IS_CLIENT(chan, options)) {
     603             : #define CONNTIMEOUT_CLIENTS_BASE 180 // 3 to 4.5 min
     604         668 :     timeout = CONNTIMEOUT_CLIENTS_BASE
     605         334 :         + crypto_rand_int(CONNTIMEOUT_CLIENTS_BASE/2);
     606             :   } else { // Canonical relay-to-relay channels
     607             :     // 45..75min or consensus +/- 25%
     608           1 :     timeout = consensus_nf_conntimeout_relays;
     609           1 :     timeout = 3*timeout/4 + crypto_rand_int(timeout/2);
     610             :   }
     611             : 
     612             :   /* If ReducedConnectionPadding is set, we want to halve the duration of
     613             :    * the channel idle timeout, since reducing the additional time that
     614             :    * a channel stays open will reduce the total overhead for making
     615             :    * new channels. This reduction in overhead/channel expense
     616             :    * is important for mobile users. The option cannot be set by relays.
     617             :    *
     618             :    * We also don't reduce any values for timeout that the user explicitly
     619             :    * set.
     620             :    */
     621         335 :   if (options->ReducedConnectionPadding
     622           1 :       && !options->CircuitsAvailableTimeout) {
     623           1 :     timeout /= 2;
     624             :   }
     625             : 
     626         335 :   return timeout;
     627             : }
     628             : 
     629             : /**
     630             :  * This function controls how long we keep idle circuits open,
     631             :  * and how long we build predicted circuits. This behavior is under
     632             :  * the control of channelpadding because circuit availability is the
     633             :  * dominant factor in channel lifespan, which influences total padding
     634             :  * overhead.
     635             :  *
     636             :  * Returns a randomized number of seconds in a range from
     637             :  * CircuitsAvailableTimeout to 2*CircuitsAvailableTimeout. This value is halved
     638             :  * if ReducedConnectionPadding is set. The default value of
     639             :  * CircuitsAvailableTimeout can be controlled by the consensus.
     640             :  */
     641             : int
     642         206 : channelpadding_get_circuits_available_timeout(void)
     643             : {
     644         206 :   const or_options_t *options = get_options();
     645         206 :   int timeout = options->CircuitsAvailableTimeout;
     646             : 
     647         206 :   if (!timeout) {
     648         202 :     timeout = consensus_nf_conntimeout_clients;
     649             : 
     650             :     /* If ReducedConnectionPadding is set, we want to halve the duration of
     651             :      * the channel idle timeout, since reducing the additional time that
     652             :      * a channel stays open will reduce the total overhead for making
     653             :      * new connections. This reduction in overhead/connection expense
     654             :      * is important for mobile users. The option cannot be set by relays.
     655             :      *
     656             :      * We also don't reduce any values for timeout that the user explicitly
     657             :      * set.
     658             :      */
     659         202 :     if (options->ReducedConnectionPadding) {
     660             :       // half the value to 15..30min by default
     661           1 :       timeout /= 2;
     662             :     }
     663             :   }
     664             : 
     665             :   // 30..60min by default
     666         206 :   timeout = timeout + crypto_rand_int(timeout);
     667             : 
     668         206 :   tor_assert(timeout >= 0);
     669             : 
     670         206 :   return timeout;
     671             : }
     672             : 
     673             : /**
     674             :  * Calling this function on a channel causes it to tell the other side
     675             :  * not to send padding, and disables sending padding from this side as well.
     676             :  */
     677             : void
     678           4 : channelpadding_disable_padding_on_channel(channel_t *chan)
     679             : {
     680           4 :   chan->padding_enabled = 0;
     681             : 
     682             :   // Send cell to disable padding on the other end
     683           4 :   channelpadding_send_disable_command(chan);
     684           4 : }
     685             : 
     686             : /**
     687             :  * Calling this function on a channel causes it to tell the other side
     688             :  * not to send padding, and reduces the rate that padding is sent from
     689             :  * this side.
     690             :  */
     691             : void
     692           1 : channelpadding_reduce_padding_on_channel(channel_t *chan)
     693             : {
     694             :   /* Padding can be forced and reduced by clients, regardless of if
     695             :    * the channel supports it. So we check for support here before
     696             :    * sending any commands. */
     697           1 :   if (chan->padding_enabled) {
     698           1 :     channelpadding_send_disable_command(chan);
     699             :   }
     700             : 
     701           1 :   chan->padding_timeout_low_ms = consensus_nf_ito_low_reduced;
     702           1 :   chan->padding_timeout_high_ms = consensus_nf_ito_high_reduced;
     703             : 
     704           1 :   log_fn(LOG_INFO,LD_OR,
     705             :          "Reduced padding on channel %"PRIu64": lo=%d, hi=%d",
     706             :          (chan->global_identifier),
     707             :          chan->padding_timeout_low_ms, chan->padding_timeout_high_ms);
     708           1 : }
     709             : 
     710             : /**
     711             :  * This function is called once per second by run_connection_housekeeping(),
     712             :  * but only if the channel is still open, valid, and non-wedged.
     713             :  *
     714             :  * It decides if and when we should send a padding cell, and if needed,
     715             :  * schedules a callback to send that cell at the appropriate time.
     716             :  *
     717             :  * Returns an enum that represents the current padding decision state.
     718             :  * Return value is currently used only by unit tests.
     719             :  */
     720             : channelpadding_decision_t
     721         233 : channelpadding_decide_to_pad_channel(channel_t *chan)
     722             : {
     723         233 :   const or_options_t *options = get_options();
     724             : 
     725             :   /* Only pad open channels */
     726         233 :   if (chan->state != CHANNEL_STATE_OPEN)
     727             :     return CHANNELPADDING_WONTPAD;
     728             : 
     729         233 :   if (chan->channel_usage == CHANNEL_USED_FOR_FULL_CIRCS) {
     730         232 :     if (!consensus_nf_pad_before_usage)
     731             :       return CHANNELPADDING_WONTPAD;
     732           1 :   } else if (chan->channel_usage != CHANNEL_USED_FOR_USER_TRAFFIC) {
     733             :     return CHANNELPADDING_WONTPAD;
     734             :   }
     735             : 
     736         231 :   if (chan->pending_padding_callback)
     737             :     return CHANNELPADDING_PADDING_ALREADY_SCHEDULED;
     738             : 
     739             :   /* Don't pad the channel if we didn't negotiate it, but still
     740             :    * allow clients to force padding if options->ChannelPadding is
     741             :    * explicitly set to 1.
     742             :    */
     743         228 :   if (!chan->padding_enabled && options->ConnectionPadding != 1) {
     744             :     return CHANNELPADDING_WONTPAD;
     745             :   }
     746             : 
     747         223 :   if (hs_service_allow_non_anonymous_connection(options) &&
     748           2 :       !consensus_nf_pad_single_onion) {
     749             :     /* If the consensus just changed values, this channel may still
     750             :      * think padding is enabled. Negotiate it off. */
     751           1 :     if (chan->padding_enabled)
     752           1 :       channelpadding_disable_padding_on_channel(chan);
     753             : 
     754           1 :     return CHANNELPADDING_WONTPAD;
     755             :   }
     756             : 
     757             :   /* There should always be a cmux on the circuit. After that,
     758             :    * only schedule padding if there are no queued writes and no
     759             :    * queued cells in circuitmux queues. */
     760         444 :   if (chan->cmux && !chan->has_queued_writes(chan) &&
     761         222 :       !circuitmux_num_cells(chan->cmux)) {
     762         222 :     int is_client_channel = 0;
     763             : 
     764         222 :     if (CHANNEL_IS_CLIENT(chan, options)) {
     765             :        is_client_channel = 1;
     766             :     }
     767             : 
     768             :     /* If nf_pad_relays=1 is set in the consensus, we pad
     769             :      * on *all* idle connections, relay-relay or relay-client.
     770             :      * Otherwise pad only for client+bridge cons */
     771           2 :     if (is_client_channel || consensus_nf_pad_relays) {
     772         221 :       int64_t pad_time_ms =
     773         221 :           channelpadding_compute_time_until_pad_for_netflow(chan);
     774             : 
     775         221 :       if (pad_time_ms == CHANNELPADDING_TIME_DISABLED) {
     776             :         return CHANNELPADDING_WONTPAD;
     777         219 :       } else if (pad_time_ms == CHANNELPADDING_TIME_LATER) {
     778           7 :         chan->currently_padding = 1;
     779           7 :         return CHANNELPADDING_PADLATER;
     780             :       } else {
     781         212 :         if (BUG(pad_time_ms > INT_MAX)) {
     782             :           pad_time_ms = INT_MAX;
     783             :         }
     784             :        /* We have to schedule a callback because we're called exactly once per
     785             :         * second, but we don't want padding packets to go out exactly on an
     786             :         * integer multiple of seconds. This callback will only be scheduled
     787             :         * if we're within 1.1 seconds of the padding time.
     788             :         */
     789         212 :         chan->currently_padding = 1;
     790         212 :         return channelpadding_schedule_padding(chan, (int)pad_time_ms);
     791             :       }
     792             :     } else {
     793           1 :       chan->currently_padding = 0;
     794           1 :       return CHANNELPADDING_WONTPAD;
     795             :     }
     796             :   } else {
     797           0 :     return CHANNELPADDING_PADLATER;
     798             :   }
     799             : }

Generated by: LCOV version 1.14