channelpadding.c 28 KB

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