fallbackdir: Update list generated on August 30, 2023
[tor.git] / src / core / or / channelpadding.c
blob1f559f6c420d6cce246082bafef9451a65c93483
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 */
7 /**
8 * @file channelpadding.c
9 * @brief Link-level padding code.
10 **/
12 /* CHANNEL_OBJECT_PRIVATE define needed for an O(1) implementation of
13 * channelpadding_channel_to_channelinfo() */
14 #define CHANNEL_OBJECT_PRIVATE
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"
33 #include "core/or/cell_st.h"
34 #include "core/or/or_connection_st.h"
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 *);
41 /** The total number of pending channelpadding timers */
42 static uint64_t total_timers_pending;
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;
64 #define TOR_MSEC_PER_SEC 1000
65 #define TOR_USEC_PER_MSEC 1000
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
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).
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))
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.
92 void
93 channelpadding_new_consensus_params(const networkstatus_t *ns)
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 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 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);
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 consensus_nf_ito_low_reduced =
113 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);
118 consensus_nf_ito_high_reduced =
119 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);
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 consensus_nf_conntimeout_relays =
128 networkstatus_get_param(ns, "nf_conntimeout_relays",
129 CONNTIMEOUT_RELAYS_DFLT,
130 CONNTIMEOUT_RELAYS_MIN,
131 CONNTIMEOUT_RELAYS_MAX);
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 consensus_nf_conntimeout_clients =
137 networkstatus_get_param(ns, "nf_conntimeout_clients",
138 CIRCTIMEOUT_CLIENTS_DFLT,
139 CIRCTIMEOUT_CLIENTS_MIN,
140 CIRCTIMEOUT_CLIENTS_MAX);
142 consensus_nf_pad_before_usage =
143 networkstatus_get_param(ns, "nf_pad_before_usage", 1, 0, 1);
145 consensus_nf_pad_relays =
146 networkstatus_get_param(ns, "nf_pad_relays", 0, 0, 1);
148 consensus_nf_pad_single_onion =
149 networkstatus_get_param(ns,
150 CHANNELPADDING_SOS_PARAM,
151 CHANNELPADDING_SOS_DEFAULT, 0, 1);
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.
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.
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.
169 * Returns the next timeout period (in milliseconds) after which we should
170 * send a padding packet, or 0 if padding is disabled.
172 STATIC int32_t
173 channelpadding_get_netflow_inactive_timeout_ms(const channel_t *chan)
175 int low_timeout = consensus_nf_ito_low;
176 int high_timeout = consensus_nf_ito_high;
177 int X1, X2;
179 if (low_timeout == 0 && low_timeout == high_timeout)
180 return 0; // No padding
182 /* If we have negotiated different timeout values, use those, but
183 * don't allow them to be lower than the consensus ones */
184 if (chan->padding_timeout_low_ms && chan->padding_timeout_high_ms) {
185 low_timeout = MAX(low_timeout, chan->padding_timeout_low_ms);
186 high_timeout = MAX(high_timeout, chan->padding_timeout_high_ms);
189 if (low_timeout >= high_timeout)
190 return low_timeout; // No randomization
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).
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).
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:
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
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).
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.
233 X1 = crypto_rand_int(high_timeout - low_timeout);
234 X2 = crypto_rand_int(high_timeout - low_timeout);
235 return low_timeout + MAX(X1, X2);
239 * Update this channel's padding settings based on the PADDING_NEGOTIATE
240 * contents.
242 * Returns -1 on error; 1 on success.
245 channelpadding_update_padding_for_channel(channel_t *chan,
246 const channelpadding_negotiate_t *pad_vars)
248 if (pad_vars->version != 0) {
249 static ratelim_t version_limit = RATELIM_INIT(600);
251 log_fn_ratelim(&version_limit,LOG_PROTOCOL_WARN,LD_PROTOCOL,
252 "Got a PADDING_NEGOTIATE cell with an unknown version. Ignoring.");
253 return -1;
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 if ((get_options()->BridgeRelay &&
261 connection_or_digest_is_known_relay(chan->identity_digest)) ||
262 !get_options()->ORPort_set) {
263 static ratelim_t relay_limit = RATELIM_INIT(600);
265 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 return -1;
273 chan->padding_enabled = (pad_vars->command == CHANNELPADDING_COMMAND_START);
275 /* Min must not be lower than the current consensus parameter
276 nf_ito_low. */
277 chan->padding_timeout_low_ms = MAX(consensus_nf_ito_low,
278 pad_vars->ito_low_ms);
280 /* Max must not be lower than ito_low_ms */
281 chan->padding_timeout_high_ms = MAX(chan->padding_timeout_low_ms,
282 pad_vars->ito_high_ms);
284 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));
290 return 1;
294 * Sends a CELL_PADDING_NEGOTIATE on the channel to tell the other side not
295 * to send padding.
297 * Returns -1 on error, 0 on success.
299 STATIC int
300 channelpadding_send_disable_command(channel_t *chan)
302 channelpadding_negotiate_t disable;
303 cell_t cell;
305 tor_assert(chan);
306 tor_assert(BASE_CHAN_TO_TLS(chan)->conn->link_proto >=
307 MIN_LINK_PROTO_FOR_CHANNEL_PADDING);
309 memset(&cell, 0, sizeof(cell_t));
310 memset(&disable, 0, sizeof(channelpadding_negotiate_t));
311 cell.command = CELL_PADDING_NEGOTIATE;
313 channelpadding_negotiate_set_command(&disable, CHANNELPADDING_COMMAND_STOP);
315 if (channelpadding_negotiate_encode(cell.payload, CELL_PAYLOAD_SIZE,
316 &disable) < 0)
317 return -1;
319 if (chan->write_cell(chan, &cell) == 1)
320 return 0;
321 else
322 return -1;
326 * Sends a CELL_PADDING_NEGOTIATE on the channel to tell the other side to
327 * resume sending padding at some rate.
329 * Returns -1 on error, 0 on success.
332 channelpadding_send_enable_command(channel_t *chan, uint16_t low_timeout,
333 uint16_t high_timeout)
335 channelpadding_negotiate_t enable;
336 cell_t cell;
338 tor_assert(chan);
339 tor_assert(BASE_CHAN_TO_TLS(chan)->conn->link_proto >=
340 MIN_LINK_PROTO_FOR_CHANNEL_PADDING);
342 memset(&cell, 0, sizeof(cell_t));
343 memset(&enable, 0, sizeof(channelpadding_negotiate_t));
344 cell.command = CELL_PADDING_NEGOTIATE;
346 channelpadding_negotiate_set_command(&enable, CHANNELPADDING_COMMAND_START);
347 channelpadding_negotiate_set_ito_low_ms(&enable, low_timeout);
348 channelpadding_negotiate_set_ito_high_ms(&enable, high_timeout);
350 if (channelpadding_negotiate_encode(cell.payload, CELL_PAYLOAD_SIZE,
351 &enable) < 0)
352 return -1;
354 if (chan->write_cell(chan, &cell) == 1)
355 return 0;
356 else
357 return -1;
361 * Sends a CELL_PADDING cell on a channel if it has been idle since
362 * our callback was scheduled.
364 * This function also clears the pending padding timer and the callback
365 * flags.
367 static void
368 channelpadding_send_padding_cell_for_callback(channel_t *chan)
370 cell_t cell;
372 /* Check that the channel is still valid and open */
373 if (!chan || chan->state != CHANNEL_STATE_OPEN) {
374 if (chan) chan->pending_padding_callback = 0;
375 log_fn(LOG_INFO,LD_OR,
376 "Scheduled a netflow padding cell, but connection already closed.");
377 return;
380 /* We should have a pending callback flag set. */
381 if (BUG(chan->pending_padding_callback == 0))
382 return;
384 chan->pending_padding_callback = 0;
386 if (monotime_coarse_is_zero(&chan->next_padding_time) ||
387 chan->has_queued_writes(chan) ||
388 (chan->cmux && circuitmux_num_cells(chan->cmux))) {
389 /* We must have been active before the timer fired */
390 monotime_coarse_zero(&chan->next_padding_time);
391 return;
395 monotime_coarse_t now;
396 monotime_coarse_get(&now);
398 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)),
406 monotime_coarse_diff_msec(&chan->next_padding_time,&now)));
409 /* Clear the timer */
410 monotime_coarse_zero(&chan->next_padding_time);
412 /* Send the padding cell. This will cause the channel to get a
413 * fresh timestamp_active */
414 memset(&cell, 0, sizeof(cell));
415 cell.command = CELL_PADDING;
416 chan->write_cell(chan, &cell);
420 * tor_timer callback function for us to send padding on an idle channel.
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.
427 static void
428 channelpadding_send_padding_callback(tor_timer_t *timer, void *args,
429 const struct monotime_t *when)
431 channel_t *chan = channel_handle_get((struct channel_handle_t*)args);
432 (void)timer; (void)when;
434 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 tor_assert(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn)->magic ==
438 OR_CONNECTION_MAGIC);
439 assert_connection_ok(TO_CONN(BASE_CHAN_TO_TLS(chan)->conn), approx_time());
441 channelpadding_send_padding_cell_for_callback(chan);
442 } else {
443 log_fn(LOG_INFO,LD_OR,
444 "Channel closed while waiting for timer.");
447 total_timers_pending--;
451 * Schedules a callback to send padding on a channel in_ms milliseconds from
452 * now.
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.
458 static channelpadding_decision_t
459 channelpadding_schedule_padding(channel_t *chan, int in_ms)
461 struct timeval timeout;
462 tor_assert(!chan->pending_padding_callback);
464 if (in_ms <= 0) {
465 chan->pending_padding_callback = 1;
466 channelpadding_send_padding_cell_for_callback(chan);
467 return CHANNELPADDING_PADDING_SENT;
470 timeout.tv_sec = in_ms/TOR_MSEC_PER_SEC;
471 timeout.tv_usec = (in_ms%TOR_USEC_PER_MSEC)*TOR_USEC_PER_MSEC;
473 if (!chan->timer_handle) {
474 chan->timer_handle = channel_handle_new(chan);
477 if (chan->padding_timer) {
478 timer_set_cb(chan->padding_timer,
479 channelpadding_send_padding_callback,
480 chan->timer_handle);
481 } else {
482 chan->padding_timer = timer_new(channelpadding_send_padding_callback,
483 chan->timer_handle);
485 timer_schedule(chan->padding_timer, &timeout);
487 rep_hist_padding_count_timers(++total_timers_pending);
489 chan->pending_padding_callback = 1;
490 return CHANNELPADDING_PADDING_SCHEDULED;
494 * Calculates the number of milliseconds from now to schedule a padding cell.
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.
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.
507 #define CHANNELPADDING_TIME_LATER -1
508 #define CHANNELPADDING_TIME_DISABLED -2
509 STATIC int64_t
510 channelpadding_compute_time_until_pad_for_netflow(channel_t *chan)
512 monotime_coarse_t now;
513 monotime_coarse_get(&now);
515 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 int32_t padding_timeout =
523 channelpadding_get_netflow_inactive_timeout_ms(chan);
525 if (!padding_timeout)
526 return CHANNELPADDING_TIME_DISABLED;
528 monotime_coarse_add_msec(&chan->next_padding_time,
529 &chan->timestamp_xfer,
530 padding_timeout);
533 const int64_t ms_till_pad =
534 monotime_coarse_diff_msec(&now, &chan->next_padding_time);
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.
542 if (ms_till_pad > DFLT_NETFLOW_INACTIVE_KEEPALIVE_MAX) {
543 tor_fragile_assert();
544 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 return 0; /* Clock jumped: Send padding now */
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.
556 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 if (ms_till_pad < 0) {
568 int severity = (ms_till_pad < -NETFLOW_MISSED_WINDOW)
569 ? LOG_NOTICE : LOG_INFO;
570 log_fn(severity, LD_OR,
571 "Channel padding timeout scheduled %"PRId64"ms in the past. ",
572 (-ms_till_pad));
573 return 0; /* Clock jumped: Send padding now */
576 return ms_till_pad;
578 return CHANNELPADDING_TIME_LATER;
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.
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.
591 * Also allows the default relay-to-relay value to be controlled by the
592 * consensus.
594 unsigned int
595 channelpadding_get_channel_idle_timeout(const channel_t *chan,
596 int is_canonical)
598 const or_options_t *options = get_options();
599 unsigned int timeout;
601 /* Non-canonical and client channels only last for 3-4.5 min when idle */
602 if (!is_canonical || CHANNEL_IS_CLIENT(chan, options)) {
603 #define CONNTIMEOUT_CLIENTS_BASE 180 // 3 to 4.5 min
604 timeout = CONNTIMEOUT_CLIENTS_BASE
605 + crypto_rand_int(CONNTIMEOUT_CLIENTS_BASE/2);
606 } else { // Canonical relay-to-relay channels
607 // 45..75min or consensus +/- 25%
608 timeout = consensus_nf_conntimeout_relays;
609 timeout = 3*timeout/4 + crypto_rand_int(timeout/2);
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.
618 * We also don't reduce any values for timeout that the user explicitly
619 * set.
621 if (options->ReducedConnectionPadding
622 && !options->CircuitsAvailableTimeout) {
623 timeout /= 2;
626 return timeout;
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.
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.
642 channelpadding_get_circuits_available_timeout(void)
644 const or_options_t *options = get_options();
645 int timeout = options->CircuitsAvailableTimeout;
647 if (!timeout) {
648 timeout = consensus_nf_conntimeout_clients;
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.
656 * We also don't reduce any values for timeout that the user explicitly
657 * set.
659 if (options->ReducedConnectionPadding) {
660 // half the value to 15..30min by default
661 timeout /= 2;
665 // 30..60min by default
666 timeout = timeout + crypto_rand_int(timeout);
668 tor_assert(timeout >= 0);
670 return timeout;
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.
677 void
678 channelpadding_disable_padding_on_channel(channel_t *chan)
680 chan->padding_enabled = 0;
682 // Send cell to disable padding on the other end
683 channelpadding_send_disable_command(chan);
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.
691 void
692 channelpadding_reduce_padding_on_channel(channel_t *chan)
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 if (chan->padding_enabled) {
698 channelpadding_send_disable_command(chan);
701 chan->padding_timeout_low_ms = consensus_nf_ito_low_reduced;
702 chan->padding_timeout_high_ms = consensus_nf_ito_high_reduced;
704 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);
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.
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.
717 * Returns an enum that represents the current padding decision state.
718 * Return value is currently used only by unit tests.
720 channelpadding_decision_t
721 channelpadding_decide_to_pad_channel(channel_t *chan)
723 const or_options_t *options = get_options();
725 /* Only pad open channels */
726 if (chan->state != CHANNEL_STATE_OPEN)
727 return CHANNELPADDING_WONTPAD;
729 if (chan->channel_usage == CHANNEL_USED_FOR_FULL_CIRCS) {
730 if (!consensus_nf_pad_before_usage)
731 return CHANNELPADDING_WONTPAD;
732 } else if (chan->channel_usage != CHANNEL_USED_FOR_USER_TRAFFIC) {
733 return CHANNELPADDING_WONTPAD;
736 if (chan->pending_padding_callback)
737 return CHANNELPADDING_PADDING_ALREADY_SCHEDULED;
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.
743 if (!chan->padding_enabled && options->ConnectionPadding != 1) {
744 return CHANNELPADDING_WONTPAD;
747 if (hs_service_allow_non_anonymous_connection(options) &&
748 !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 if (chan->padding_enabled)
752 channelpadding_disable_padding_on_channel(chan);
754 return CHANNELPADDING_WONTPAD;
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 if (chan->cmux && !chan->has_queued_writes(chan) &&
761 !circuitmux_num_cells(chan->cmux)) {
762 int is_client_channel = 0;
764 if (CHANNEL_IS_CLIENT(chan, options)) {
765 is_client_channel = 1;
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 if (is_client_channel || consensus_nf_pad_relays) {
772 int64_t pad_time_ms =
773 channelpadding_compute_time_until_pad_for_netflow(chan);
775 if (pad_time_ms == CHANNELPADDING_TIME_DISABLED) {
776 return CHANNELPADDING_WONTPAD;
777 } else if (pad_time_ms == CHANNELPADDING_TIME_LATER) {
778 chan->currently_padding = 1;
779 return CHANNELPADDING_PADLATER;
780 } else {
781 if (BUG(pad_time_ms > INT_MAX)) {
782 pad_time_ms = INT_MAX;
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.
789 chan->currently_padding = 1;
790 return channelpadding_schedule_padding(chan, (int)pad_time_ms);
792 } else {
793 chan->currently_padding = 0;
794 return CHANNELPADDING_WONTPAD;
796 } else {
797 return CHANNELPADDING_PADLATER;