channelpadding.c 29 KB

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