circpathbias.c 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  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-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circpathbias.c
  8. *
  9. * \brief Code to track success/failure rates of circuits built through
  10. * different tor nodes, in an attempt to detect attacks where
  11. * an attacker deliberately causes circuits to fail until the client
  12. * choses a path they like.
  13. *
  14. * This code is currently configured in a warning-only mode, though false
  15. * positives appear to be rare in practice. There is also support for
  16. * disabling really bad guards, but it's quite experimental and may have bad
  17. * anonymity effects.
  18. *
  19. * The information here is associated with the entry_guard_t object for
  20. * each guard, and stored persistently in the state file.
  21. */
  22. #include "core/or/or.h"
  23. #include "core/or/channel.h"
  24. #include "feature/client/circpathbias.h"
  25. #include "core/or/circuitbuild.h"
  26. #include "core/or/circuitlist.h"
  27. #include "core/or/circuituse.h"
  28. #include "core/or/circuitstats.h"
  29. #include "core/or/connection_edge.h"
  30. #include "app/config/config.h"
  31. #include "lib/crypt_ops/crypto_rand.h"
  32. #include "feature/client/entrynodes.h"
  33. #include "feature/nodelist/networkstatus.h"
  34. #include "core/or/relay.h"
  35. #include "lib/math/fp.h"
  36. #include "lib/math/laplace.h"
  37. #include "core/or/cell_st.h"
  38. #include "core/or/cpath_build_state_st.h"
  39. #include "core/or/crypt_path_st.h"
  40. #include "core/or/extend_info_st.h"
  41. #include "core/or/origin_circuit_st.h"
  42. static void pathbias_count_successful_close(origin_circuit_t *circ);
  43. static void pathbias_count_collapse(origin_circuit_t *circ);
  44. static void pathbias_count_use_failed(origin_circuit_t *circ);
  45. static void pathbias_measure_use_rate(entry_guard_t *guard);
  46. static void pathbias_measure_close_rate(entry_guard_t *guard);
  47. static void pathbias_scale_use_rates(entry_guard_t *guard);
  48. static void pathbias_scale_close_rates(entry_guard_t *guard);
  49. static int entry_guard_inc_circ_attempt_count(entry_guard_t *guard);
  50. /** Increment the number of times we successfully extended a circuit to
  51. * <b>guard</b>, first checking if the failure rate is high enough that
  52. * we should eliminate the guard. Return -1 if the guard looks no good;
  53. * return 0 if the guard looks fine.
  54. */
  55. static int
  56. entry_guard_inc_circ_attempt_count(entry_guard_t *guard)
  57. {
  58. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  59. entry_guards_changed();
  60. pathbias_measure_close_rate(guard);
  61. if (pb->path_bias_disabled)
  62. return -1;
  63. pathbias_scale_close_rates(guard);
  64. pb->circ_attempts++;
  65. log_info(LD_CIRC, "Got success count %f/%f for guard %s",
  66. pb->circ_successes, pb->circ_attempts,
  67. entry_guard_describe(guard));
  68. return 0;
  69. }
  70. /** The minimum number of circuit attempts before we start
  71. * thinking about warning about path bias and dropping guards */
  72. static int
  73. pathbias_get_min_circs(const or_options_t *options)
  74. {
  75. #define DFLT_PATH_BIAS_MIN_CIRC 150
  76. if (options->PathBiasCircThreshold >= 5)
  77. return options->PathBiasCircThreshold;
  78. else
  79. return networkstatus_get_param(NULL, "pb_mincircs",
  80. DFLT_PATH_BIAS_MIN_CIRC,
  81. 5, INT32_MAX);
  82. }
  83. /** The circuit success rate below which we issue a notice */
  84. static double
  85. pathbias_get_notice_rate(const or_options_t *options)
  86. {
  87. #define DFLT_PATH_BIAS_NOTICE_PCT 70
  88. if (options->PathBiasNoticeRate >= 0.0)
  89. return options->PathBiasNoticeRate;
  90. else
  91. return networkstatus_get_param(NULL, "pb_noticepct",
  92. DFLT_PATH_BIAS_NOTICE_PCT, 0, 100)/100.0;
  93. }
  94. /** The circuit success rate below which we issue a warn */
  95. static double
  96. pathbias_get_warn_rate(const or_options_t *options)
  97. {
  98. #define DFLT_PATH_BIAS_WARN_PCT 50
  99. if (options->PathBiasWarnRate >= 0.0)
  100. return options->PathBiasWarnRate;
  101. else
  102. return networkstatus_get_param(NULL, "pb_warnpct",
  103. DFLT_PATH_BIAS_WARN_PCT, 0, 100)/100.0;
  104. }
  105. /* XXXX I'd like to have this be static again, but entrynodes.c needs it. */
  106. /**
  107. * The extreme rate is the rate at which we would drop the guard,
  108. * if pb_dropguard is also set. Otherwise we just warn.
  109. */
  110. double
  111. pathbias_get_extreme_rate(const or_options_t *options)
  112. {
  113. #define DFLT_PATH_BIAS_EXTREME_PCT 30
  114. if (options->PathBiasExtremeRate >= 0.0)
  115. return options->PathBiasExtremeRate;
  116. else
  117. return networkstatus_get_param(NULL, "pb_extremepct",
  118. DFLT_PATH_BIAS_EXTREME_PCT, 0, 100)/100.0;
  119. }
  120. /* XXXX I'd like to have this be static again, but entrynodes.c needs it. */
  121. /**
  122. * If 1, we actually disable use of guards that fall below
  123. * the extreme_pct.
  124. */
  125. int
  126. pathbias_get_dropguards(const or_options_t *options)
  127. {
  128. #define DFLT_PATH_BIAS_DROP_GUARDS 0
  129. if (options->PathBiasDropGuards >= 0)
  130. return options->PathBiasDropGuards;
  131. else
  132. return networkstatus_get_param(NULL, "pb_dropguards",
  133. DFLT_PATH_BIAS_DROP_GUARDS, 0, 1);
  134. }
  135. /**
  136. * This is the number of circuits at which we scale our
  137. * counts by mult_factor/scale_factor. Note, this count is
  138. * not exact, as we only perform the scaling in the event
  139. * of no integer truncation.
  140. */
  141. static int
  142. pathbias_get_scale_threshold(const or_options_t *options)
  143. {
  144. #define DFLT_PATH_BIAS_SCALE_THRESHOLD 300
  145. if (options->PathBiasScaleThreshold >= 10)
  146. return options->PathBiasScaleThreshold;
  147. else
  148. return networkstatus_get_param(NULL, "pb_scalecircs",
  149. DFLT_PATH_BIAS_SCALE_THRESHOLD, 10,
  150. INT32_MAX);
  151. }
  152. /**
  153. * Compute the path bias scaling ratio from the consensus
  154. * parameters pb_multfactor/pb_scalefactor.
  155. *
  156. * Returns a value in (0, 1.0] which we multiply our pathbias
  157. * counts with to scale them down.
  158. */
  159. static double
  160. pathbias_get_scale_ratio(const or_options_t *options)
  161. {
  162. (void) options;
  163. /*
  164. * The scale factor is the denominator for our scaling
  165. * of circuit counts for our path bias window.
  166. *
  167. * Note that our use of doubles for the path bias state
  168. * file means that powers of 2 work best here.
  169. */
  170. int denominator = networkstatus_get_param(NULL, "pb_scalefactor",
  171. 2, 2, INT32_MAX);
  172. tor_assert(denominator > 0);
  173. /**
  174. * The mult factor is the numerator for our scaling
  175. * of circuit counts for our path bias window. It
  176. * allows us to scale by fractions.
  177. */
  178. return networkstatus_get_param(NULL, "pb_multfactor",
  179. 1, 1, denominator)/((double)denominator);
  180. }
  181. /** The minimum number of circuit usage attempts before we start
  182. * thinking about warning about path use bias and dropping guards */
  183. static int
  184. pathbias_get_min_use(const or_options_t *options)
  185. {
  186. #define DFLT_PATH_BIAS_MIN_USE 20
  187. if (options->PathBiasUseThreshold >= 3)
  188. return options->PathBiasUseThreshold;
  189. else
  190. return networkstatus_get_param(NULL, "pb_minuse",
  191. DFLT_PATH_BIAS_MIN_USE,
  192. 3, INT32_MAX);
  193. }
  194. /** The circuit use success rate below which we issue a notice */
  195. static double
  196. pathbias_get_notice_use_rate(const or_options_t *options)
  197. {
  198. #define DFLT_PATH_BIAS_NOTICE_USE_PCT 80
  199. if (options->PathBiasNoticeUseRate >= 0.0)
  200. return options->PathBiasNoticeUseRate;
  201. else
  202. return networkstatus_get_param(NULL, "pb_noticeusepct",
  203. DFLT_PATH_BIAS_NOTICE_USE_PCT,
  204. 0, 100)/100.0;
  205. }
  206. /**
  207. * The extreme use rate is the rate at which we would drop the guard,
  208. * if pb_dropguard is also set. Otherwise we just warn.
  209. */
  210. double
  211. pathbias_get_extreme_use_rate(const or_options_t *options)
  212. {
  213. #define DFLT_PATH_BIAS_EXTREME_USE_PCT 60
  214. if (options->PathBiasExtremeUseRate >= 0.0)
  215. return options->PathBiasExtremeUseRate;
  216. else
  217. return networkstatus_get_param(NULL, "pb_extremeusepct",
  218. DFLT_PATH_BIAS_EXTREME_USE_PCT,
  219. 0, 100)/100.0;
  220. }
  221. /**
  222. * This is the number of circuits at which we scale our
  223. * use counts by mult_factor/scale_factor. Note, this count is
  224. * not exact, as we only perform the scaling in the event
  225. * of no integer truncation.
  226. */
  227. static int
  228. pathbias_get_scale_use_threshold(const or_options_t *options)
  229. {
  230. #define DFLT_PATH_BIAS_SCALE_USE_THRESHOLD 100
  231. if (options->PathBiasScaleUseThreshold >= 10)
  232. return options->PathBiasScaleUseThreshold;
  233. else
  234. return networkstatus_get_param(NULL, "pb_scaleuse",
  235. DFLT_PATH_BIAS_SCALE_USE_THRESHOLD,
  236. 10, INT32_MAX);
  237. }
  238. /**
  239. * Convert a Guard's path state to string.
  240. */
  241. const char *
  242. pathbias_state_to_string(path_state_t state)
  243. {
  244. switch (state) {
  245. case PATH_STATE_NEW_CIRC:
  246. return "new";
  247. case PATH_STATE_BUILD_ATTEMPTED:
  248. return "build attempted";
  249. case PATH_STATE_BUILD_SUCCEEDED:
  250. return "build succeeded";
  251. case PATH_STATE_USE_ATTEMPTED:
  252. return "use attempted";
  253. case PATH_STATE_USE_SUCCEEDED:
  254. return "use succeeded";
  255. case PATH_STATE_USE_FAILED:
  256. return "use failed";
  257. case PATH_STATE_ALREADY_COUNTED:
  258. return "already counted";
  259. }
  260. return "unknown";
  261. }
  262. /**
  263. * This function decides if a circuit has progressed far enough to count
  264. * as a circuit "attempt". As long as end-to-end tagging is possible,
  265. * we assume the adversary will use it over hop-to-hop failure. Therefore,
  266. * we only need to account bias for the last hop. This should make us
  267. * much more resilient to ambient circuit failure, and also make that
  268. * failure easier to measure (we only need to measure Exit failure rates).
  269. */
  270. static int
  271. pathbias_is_new_circ_attempt(origin_circuit_t *circ)
  272. {
  273. #define N2N_TAGGING_IS_POSSIBLE
  274. #ifdef N2N_TAGGING_IS_POSSIBLE
  275. /* cpath is a circular list. We want circs with more than one hop,
  276. * and the second hop must be waiting for keys still (it's just
  277. * about to get them). */
  278. return circ->cpath &&
  279. circ->cpath->next != circ->cpath &&
  280. circ->cpath->next->state == CPATH_STATE_AWAITING_KEYS;
  281. #else /* !defined(N2N_TAGGING_IS_POSSIBLE) */
  282. /* If tagging attacks are no longer possible, we probably want to
  283. * count bias from the first hop. However, one could argue that
  284. * timing-based tagging is still more useful than per-hop failure.
  285. * In which case, we'd never want to use this.
  286. */
  287. return circ->cpath &&
  288. circ->cpath->state == CPATH_STATE_AWAITING_KEYS;
  289. #endif /* defined(N2N_TAGGING_IS_POSSIBLE) */
  290. }
  291. /**
  292. * Decide if the path bias code should count a circuit.
  293. *
  294. * @returns 1 if we should count it, 0 otherwise.
  295. */
  296. static int
  297. pathbias_should_count(origin_circuit_t *circ)
  298. {
  299. #define PATHBIAS_COUNT_INTERVAL (600)
  300. static ratelim_t count_limit =
  301. RATELIM_INIT(PATHBIAS_COUNT_INTERVAL);
  302. char *rate_msg = NULL;
  303. /* We can't do path bias accounting without entry guards.
  304. * Testing and controller circuits also have no guards.
  305. *
  306. * We also don't count server-side rends, because their
  307. * endpoint could be chosen maliciously.
  308. * Similarly, we can't count client-side intro attempts,
  309. * because clients can be manipulated into connecting to
  310. * malicious intro points. */
  311. if (get_options()->UseEntryGuards == 0 ||
  312. circ->base_.purpose == CIRCUIT_PURPOSE_TESTING ||
  313. circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER ||
  314. circ->base_.purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
  315. circ->base_.purpose == CIRCUIT_PURPOSE_S_REND_JOINED ||
  316. (circ->base_.purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
  317. circ->base_.purpose <= CIRCUIT_PURPOSE_C_INTRODUCE_ACKED)) {
  318. /* Check to see if the shouldcount result has changed due to a
  319. * unexpected purpose change that would affect our results.
  320. *
  321. * The reason we check the path state too here is because for the
  322. * cannibalized versions of these purposes, we count them as successful
  323. * before their purpose change.
  324. */
  325. if (circ->pathbias_shouldcount == PATHBIAS_SHOULDCOUNT_COUNTED
  326. && circ->path_state != PATH_STATE_ALREADY_COUNTED) {
  327. log_info(LD_BUG,
  328. "Circuit %d is now being ignored despite being counted "
  329. "in the past. Purpose is %s, path state is %s",
  330. circ->global_identifier,
  331. circuit_purpose_to_string(circ->base_.purpose),
  332. pathbias_state_to_string(circ->path_state));
  333. }
  334. circ->pathbias_shouldcount = PATHBIAS_SHOULDCOUNT_IGNORED;
  335. return 0;
  336. }
  337. /* Completely ignore one hop circuits */
  338. if (circ->build_state->onehop_tunnel ||
  339. circ->build_state->desired_path_len == 1) {
  340. /* Check for inconsistency */
  341. if (circ->build_state->desired_path_len != 1 ||
  342. !circ->build_state->onehop_tunnel) {
  343. if ((rate_msg = rate_limit_log(&count_limit, approx_time()))) {
  344. log_info(LD_BUG,
  345. "One-hop circuit %d has length %d. Path state is %s. "
  346. "Circuit is a %s currently %s.%s",
  347. circ->global_identifier,
  348. circ->build_state->desired_path_len,
  349. pathbias_state_to_string(circ->path_state),
  350. circuit_purpose_to_string(circ->base_.purpose),
  351. circuit_state_to_string(circ->base_.state),
  352. rate_msg);
  353. tor_free(rate_msg);
  354. }
  355. tor_fragile_assert();
  356. }
  357. /* Check to see if the shouldcount result has changed due to a
  358. * unexpected change that would affect our results */
  359. if (circ->pathbias_shouldcount == PATHBIAS_SHOULDCOUNT_COUNTED) {
  360. log_info(LD_BUG,
  361. "One-hop circuit %d is now being ignored despite being counted "
  362. "in the past. Purpose is %s, path state is %s",
  363. circ->global_identifier,
  364. circuit_purpose_to_string(circ->base_.purpose),
  365. pathbias_state_to_string(circ->path_state));
  366. }
  367. circ->pathbias_shouldcount = PATHBIAS_SHOULDCOUNT_IGNORED;
  368. return 0;
  369. }
  370. /* Check to see if the shouldcount result has changed due to a
  371. * unexpected purpose change that would affect our results */
  372. if (circ->pathbias_shouldcount == PATHBIAS_SHOULDCOUNT_IGNORED) {
  373. log_info(LD_CIRC,
  374. "Circuit %d is not being counted by pathbias because it was "
  375. "ignored in the past. Purpose is %s, path state is %s",
  376. circ->global_identifier,
  377. circuit_purpose_to_string(circ->base_.purpose),
  378. pathbias_state_to_string(circ->path_state));
  379. return 0;
  380. }
  381. circ->pathbias_shouldcount = PATHBIAS_SHOULDCOUNT_COUNTED;
  382. return 1;
  383. }
  384. /**
  385. * Check our circuit state to see if this is a successful circuit attempt.
  386. * If so, record it in the current guard's path bias circ_attempt count.
  387. *
  388. * Also check for several potential error cases for bug #6475.
  389. */
  390. int
  391. pathbias_count_build_attempt(origin_circuit_t *circ)
  392. {
  393. #define CIRC_ATTEMPT_NOTICE_INTERVAL (600)
  394. static ratelim_t circ_attempt_notice_limit =
  395. RATELIM_INIT(CIRC_ATTEMPT_NOTICE_INTERVAL);
  396. char *rate_msg = NULL;
  397. if (!pathbias_should_count(circ)) {
  398. return 0;
  399. }
  400. if (pathbias_is_new_circ_attempt(circ)) {
  401. /* Help track down the real cause of bug #6475: */
  402. if (circ->has_opened && circ->path_state != PATH_STATE_BUILD_ATTEMPTED) {
  403. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  404. approx_time()))) {
  405. log_info(LD_BUG,
  406. "Opened circuit %d is in strange path state %s. "
  407. "Circuit is a %s currently %s.%s",
  408. circ->global_identifier,
  409. pathbias_state_to_string(circ->path_state),
  410. circuit_purpose_to_string(circ->base_.purpose),
  411. circuit_state_to_string(circ->base_.state),
  412. rate_msg);
  413. tor_free(rate_msg);
  414. }
  415. }
  416. /* Don't re-count cannibalized circs.. */
  417. if (!circ->has_opened) {
  418. entry_guard_t *guard = NULL;
  419. if (circ->cpath && circ->cpath->extend_info) {
  420. guard = entry_guard_get_by_id_digest(
  421. circ->cpath->extend_info->identity_digest);
  422. } else if (circ->base_.n_chan) {
  423. guard =
  424. entry_guard_get_by_id_digest(circ->base_.n_chan->identity_digest);
  425. }
  426. if (guard) {
  427. if (circ->path_state == PATH_STATE_NEW_CIRC) {
  428. circ->path_state = PATH_STATE_BUILD_ATTEMPTED;
  429. if (entry_guard_inc_circ_attempt_count(guard) < 0) {
  430. /* Bogus guard; we already warned. */
  431. return -END_CIRC_REASON_TORPROTOCOL;
  432. }
  433. } else {
  434. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  435. approx_time()))) {
  436. log_info(LD_BUG,
  437. "Unopened circuit %d has strange path state %s. "
  438. "Circuit is a %s currently %s.%s",
  439. circ->global_identifier,
  440. pathbias_state_to_string(circ->path_state),
  441. circuit_purpose_to_string(circ->base_.purpose),
  442. circuit_state_to_string(circ->base_.state),
  443. rate_msg);
  444. tor_free(rate_msg);
  445. }
  446. }
  447. } else {
  448. if ((rate_msg = rate_limit_log(&circ_attempt_notice_limit,
  449. approx_time()))) {
  450. log_info(LD_CIRC,
  451. "Unopened circuit has no known guard. "
  452. "Circuit is a %s currently %s.%s",
  453. circuit_purpose_to_string(circ->base_.purpose),
  454. circuit_state_to_string(circ->base_.state),
  455. rate_msg);
  456. tor_free(rate_msg);
  457. }
  458. }
  459. }
  460. }
  461. return 0;
  462. }
  463. /**
  464. * Check our circuit state to see if this is a successful circuit
  465. * completion. If so, record it in the current guard's path bias
  466. * success count.
  467. *
  468. * Also check for several potential error cases for bug #6475.
  469. */
  470. void
  471. pathbias_count_build_success(origin_circuit_t *circ)
  472. {
  473. #define SUCCESS_NOTICE_INTERVAL (600)
  474. static ratelim_t success_notice_limit =
  475. RATELIM_INIT(SUCCESS_NOTICE_INTERVAL);
  476. char *rate_msg = NULL;
  477. entry_guard_t *guard = NULL;
  478. if (!pathbias_should_count(circ)) {
  479. return;
  480. }
  481. /* Don't count cannibalized/reused circs for path bias
  482. * "build" success, since they get counted under "use" success. */
  483. if (!circ->has_opened) {
  484. if (circ->cpath && circ->cpath->extend_info) {
  485. guard = entry_guard_get_by_id_digest(
  486. circ->cpath->extend_info->identity_digest);
  487. }
  488. if (guard) {
  489. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  490. if (circ->path_state == PATH_STATE_BUILD_ATTEMPTED) {
  491. circ->path_state = PATH_STATE_BUILD_SUCCEEDED;
  492. pb->circ_successes++;
  493. entry_guards_changed();
  494. log_info(LD_CIRC, "Got success count %f/%f for guard %s",
  495. pb->circ_successes, pb->circ_attempts,
  496. entry_guard_describe(guard));
  497. } else {
  498. if ((rate_msg = rate_limit_log(&success_notice_limit,
  499. approx_time()))) {
  500. log_info(LD_BUG,
  501. "Succeeded circuit %d is in strange path state %s. "
  502. "Circuit is a %s currently %s.%s",
  503. circ->global_identifier,
  504. pathbias_state_to_string(circ->path_state),
  505. circuit_purpose_to_string(circ->base_.purpose),
  506. circuit_state_to_string(circ->base_.state),
  507. rate_msg);
  508. tor_free(rate_msg);
  509. }
  510. }
  511. if (pb->circ_attempts < pb->circ_successes) {
  512. log_notice(LD_BUG, "Unexpectedly high successes counts (%f/%f) "
  513. "for guard %s",
  514. pb->circ_successes, pb->circ_attempts,
  515. entry_guard_describe(guard));
  516. }
  517. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  518. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  519. * No need to log that case. */
  520. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  521. if ((rate_msg = rate_limit_log(&success_notice_limit,
  522. approx_time()))) {
  523. log_info(LD_CIRC,
  524. "Completed circuit has no known guard. "
  525. "Circuit is a %s currently %s.%s",
  526. circuit_purpose_to_string(circ->base_.purpose),
  527. circuit_state_to_string(circ->base_.state),
  528. rate_msg);
  529. tor_free(rate_msg);
  530. }
  531. }
  532. } else {
  533. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  534. if ((rate_msg = rate_limit_log(&success_notice_limit,
  535. approx_time()))) {
  536. log_info(LD_BUG,
  537. "Opened circuit %d is in strange path state %s. "
  538. "Circuit is a %s currently %s.%s",
  539. circ->global_identifier,
  540. pathbias_state_to_string(circ->path_state),
  541. circuit_purpose_to_string(circ->base_.purpose),
  542. circuit_state_to_string(circ->base_.state),
  543. rate_msg);
  544. tor_free(rate_msg);
  545. }
  546. }
  547. }
  548. }
  549. /**
  550. * Record an attempt to use a circuit. Changes the circuit's
  551. * path state and update its guard's usage counter.
  552. *
  553. * Used for path bias usage accounting.
  554. */
  555. void
  556. pathbias_count_use_attempt(origin_circuit_t *circ)
  557. {
  558. if (!pathbias_should_count(circ)) {
  559. return;
  560. }
  561. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  562. log_notice(LD_BUG,
  563. "Used circuit %d is in strange path state %s. "
  564. "Circuit is a %s currently %s.",
  565. circ->global_identifier,
  566. pathbias_state_to_string(circ->path_state),
  567. circuit_purpose_to_string(circ->base_.purpose),
  568. circuit_state_to_string(circ->base_.state));
  569. } else if (circ->path_state < PATH_STATE_USE_ATTEMPTED) {
  570. entry_guard_t *guard = entry_guard_get_by_id_digest(
  571. circ->cpath->extend_info->identity_digest);
  572. if (guard) {
  573. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  574. pathbias_measure_use_rate(guard);
  575. pathbias_scale_use_rates(guard);
  576. pb->use_attempts++;
  577. entry_guards_changed();
  578. log_debug(LD_CIRC,
  579. "Marked circuit %d (%f/%f) as used for guard %s.",
  580. circ->global_identifier,
  581. pb->use_successes, pb->use_attempts,
  582. entry_guard_describe(guard));
  583. }
  584. circ->path_state = PATH_STATE_USE_ATTEMPTED;
  585. } else {
  586. /* Harmless but educational log message */
  587. log_info(LD_CIRC,
  588. "Used circuit %d is already in path state %s. "
  589. "Circuit is a %s currently %s.",
  590. circ->global_identifier,
  591. pathbias_state_to_string(circ->path_state),
  592. circuit_purpose_to_string(circ->base_.purpose),
  593. circuit_state_to_string(circ->base_.state));
  594. }
  595. return;
  596. }
  597. /**
  598. * Check the circuit's path state is appropriate and mark it as
  599. * successfully used. Used for path bias usage accounting.
  600. *
  601. * We don't actually increment the guard's counters until
  602. * pathbias_check_close(), because the circuit can still transition
  603. * back to PATH_STATE_USE_ATTEMPTED if a stream fails later (this
  604. * is done so we can probe the circuit for liveness at close).
  605. */
  606. void
  607. pathbias_mark_use_success(origin_circuit_t *circ)
  608. {
  609. if (!pathbias_should_count(circ)) {
  610. return;
  611. }
  612. if (circ->path_state < PATH_STATE_USE_ATTEMPTED) {
  613. log_notice(LD_BUG,
  614. "Used circuit %d is in strange path state %s. "
  615. "Circuit is a %s currently %s.",
  616. circ->global_identifier,
  617. pathbias_state_to_string(circ->path_state),
  618. circuit_purpose_to_string(circ->base_.purpose),
  619. circuit_state_to_string(circ->base_.state));
  620. pathbias_count_use_attempt(circ);
  621. }
  622. /* We don't do any accounting at the guard until actual circuit close */
  623. circ->path_state = PATH_STATE_USE_SUCCEEDED;
  624. return;
  625. }
  626. /**
  627. * If a stream ever detatches from a circuit in a retriable way,
  628. * we need to mark this circuit as still needing either another
  629. * successful stream, or in need of a probe.
  630. *
  631. * An adversary could let the first stream request succeed (ie the
  632. * resolve), but then tag and timeout the remainder (via cell
  633. * dropping), forcing them on new circuits.
  634. *
  635. * Rolling back the state will cause us to probe such circuits, which
  636. * should lead to probe failures in the event of such tagging due to
  637. * either unrecognized cells coming in while we wait for the probe,
  638. * or the cipher state getting out of sync in the case of dropped cells.
  639. */
  640. void
  641. pathbias_mark_use_rollback(origin_circuit_t *circ)
  642. {
  643. if (circ->path_state == PATH_STATE_USE_SUCCEEDED) {
  644. log_info(LD_CIRC,
  645. "Rolling back pathbias use state to 'attempted' for detached "
  646. "circuit %d", circ->global_identifier);
  647. circ->path_state = PATH_STATE_USE_ATTEMPTED;
  648. }
  649. }
  650. /**
  651. * Actually count a circuit success towards a guard's usage counters
  652. * if the path state is appropriate.
  653. */
  654. static void
  655. pathbias_count_use_success(origin_circuit_t *circ)
  656. {
  657. entry_guard_t *guard;
  658. if (!pathbias_should_count(circ)) {
  659. return;
  660. }
  661. if (circ->path_state != PATH_STATE_USE_SUCCEEDED) {
  662. log_notice(LD_BUG,
  663. "Successfully used circuit %d is in strange path state %s. "
  664. "Circuit is a %s currently %s.",
  665. circ->global_identifier,
  666. pathbias_state_to_string(circ->path_state),
  667. circuit_purpose_to_string(circ->base_.purpose),
  668. circuit_state_to_string(circ->base_.state));
  669. } else {
  670. guard = entry_guard_get_by_id_digest(
  671. circ->cpath->extend_info->identity_digest);
  672. if (guard) {
  673. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  674. pb->use_successes++;
  675. entry_guards_changed();
  676. if (pb->use_attempts < pb->use_successes) {
  677. log_notice(LD_BUG, "Unexpectedly high use successes counts (%f/%f) "
  678. "for guard %s",
  679. pb->use_successes, pb->use_attempts,
  680. entry_guard_describe(guard));
  681. }
  682. log_debug(LD_CIRC,
  683. "Marked circuit %d (%f/%f) as used successfully for guard %s",
  684. circ->global_identifier, pb->use_successes,
  685. pb->use_attempts,
  686. entry_guard_describe(guard));
  687. }
  688. }
  689. return;
  690. }
  691. /**
  692. * Send a probe down a circuit that the client attempted to use,
  693. * but for which the stream timed out/failed. The probe is a
  694. * RELAY_BEGIN cell with a 0.a.b.c destination address, which
  695. * the exit will reject and reply back, echoing that address.
  696. *
  697. * The reason for such probes is because it is possible to bias
  698. * a user's paths simply by causing timeouts, and these timeouts
  699. * are not possible to differentiate from unresponsive servers.
  700. *
  701. * The probe is sent at the end of the circuit lifetime for two
  702. * reasons: to prevent cryptographic taggers from being able to
  703. * drop cells to cause timeouts, and to prevent easy recognition
  704. * of probes before any real client traffic happens.
  705. *
  706. * Returns -1 if we couldn't probe, 0 otherwise.
  707. */
  708. static int
  709. pathbias_send_usable_probe(circuit_t *circ)
  710. {
  711. /* Based on connection_ap_handshake_send_begin() */
  712. char payload[CELL_PAYLOAD_SIZE];
  713. int payload_len;
  714. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  715. crypt_path_t *cpath_layer = NULL;
  716. char *probe_nonce = NULL;
  717. tor_assert(ocirc);
  718. cpath_layer = ocirc->cpath->prev;
  719. if (cpath_layer->state != CPATH_STATE_OPEN) {
  720. /* This can happen for cannibalized circuits. Their
  721. * last hop isn't yet open */
  722. log_info(LD_CIRC,
  723. "Got pathbias probe request for unopened circuit %d. "
  724. "Opened %d, len %d", ocirc->global_identifier,
  725. ocirc->has_opened, ocirc->build_state->desired_path_len);
  726. return -1;
  727. }
  728. /* We already went down this road. */
  729. if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING &&
  730. ocirc->pathbias_probe_id) {
  731. log_info(LD_CIRC,
  732. "Got pathbias probe request for circuit %d with "
  733. "outstanding probe", ocirc->global_identifier);
  734. return -1;
  735. }
  736. /* Can't probe if the channel isn't open */
  737. if (circ->n_chan == NULL ||
  738. (!CHANNEL_IS_OPEN(circ->n_chan)
  739. && !CHANNEL_IS_MAINT(circ->n_chan))) {
  740. log_info(LD_CIRC,
  741. "Skipping pathbias probe for circuit %d: Channel is not open.",
  742. ocirc->global_identifier);
  743. return -1;
  744. }
  745. circuit_change_purpose(circ, CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  746. /* Update timestamp for when circuit_expire_building() should kill us */
  747. tor_gettimeofday(&circ->timestamp_began);
  748. /* Generate a random address for the nonce */
  749. crypto_rand((char*)&ocirc->pathbias_probe_nonce,
  750. sizeof(ocirc->pathbias_probe_nonce));
  751. ocirc->pathbias_probe_nonce &= 0x00ffffff;
  752. probe_nonce = tor_dup_ip(ocirc->pathbias_probe_nonce);
  753. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:25", probe_nonce);
  754. payload_len = (int)strlen(payload)+1;
  755. // XXX: need this? Can we assume ipv4 will always be supported?
  756. // If not, how do we tell?
  757. //if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  758. // set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  759. // payload_len += 4;
  760. //}
  761. /* Generate+Store stream id, make sure it's non-zero */
  762. ocirc->pathbias_probe_id = get_unique_stream_id_by_circ(ocirc);
  763. if (ocirc->pathbias_probe_id==0) {
  764. log_warn(LD_CIRC,
  765. "Ran out of stream IDs on circuit %u during "
  766. "pathbias probe attempt.", ocirc->global_identifier);
  767. tor_free(probe_nonce);
  768. return -1;
  769. }
  770. log_info(LD_CIRC,
  771. "Sending pathbias testing cell to %s:25 on stream %d for circ %d.",
  772. probe_nonce, ocirc->pathbias_probe_id, ocirc->global_identifier);
  773. tor_free(probe_nonce);
  774. /* Send a test relay cell */
  775. if (relay_send_command_from_edge(ocirc->pathbias_probe_id, circ,
  776. RELAY_COMMAND_BEGIN, payload,
  777. payload_len, cpath_layer) < 0) {
  778. log_notice(LD_CIRC,
  779. "Failed to send pathbias probe cell on circuit %d.",
  780. ocirc->global_identifier);
  781. return -1;
  782. }
  783. /* Mark it freshly dirty so it doesn't get expired in the meantime */
  784. circ->timestamp_dirty = time(NULL);
  785. return 0;
  786. }
  787. /**
  788. * Check the response to a pathbias probe, to ensure the
  789. * cell is recognized and the nonce and other probe
  790. * characteristics are as expected.
  791. *
  792. * If the response is valid, return 0. Otherwise return < 0.
  793. */
  794. int
  795. pathbias_check_probe_response(circuit_t *circ, const cell_t *cell)
  796. {
  797. /* Based on connection_edge_process_relay_cell() */
  798. relay_header_t rh;
  799. int reason;
  800. uint32_t ipv4_host;
  801. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  802. tor_assert(cell);
  803. tor_assert(ocirc);
  804. tor_assert(circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  805. relay_header_unpack(&rh, cell->payload);
  806. reason = rh.length > 0 ?
  807. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  808. if (rh.command == RELAY_COMMAND_END &&
  809. reason == END_STREAM_REASON_EXITPOLICY &&
  810. ocirc->pathbias_probe_id == rh.stream_id) {
  811. /* Check length+extract host: It is in network order after the reason code.
  812. * See connection_edge_end(). */
  813. if (rh.length < 9) { /* reason+ipv4+dns_ttl */
  814. log_notice(LD_PROTOCOL,
  815. "Short path bias probe response length field (%d).", rh.length);
  816. return - END_CIRC_REASON_TORPROTOCOL;
  817. }
  818. ipv4_host = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  819. /* Check nonce */
  820. if (ipv4_host == ocirc->pathbias_probe_nonce) {
  821. pathbias_mark_use_success(ocirc);
  822. circuit_read_valid_data(ocirc, rh.length);
  823. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  824. log_info(LD_CIRC,
  825. "Got valid path bias probe back for circ %d, stream %d.",
  826. ocirc->global_identifier, ocirc->pathbias_probe_id);
  827. return 0;
  828. } else {
  829. log_notice(LD_CIRC,
  830. "Got strange probe value 0x%x vs 0x%x back for circ %d, "
  831. "stream %d.", ipv4_host, ocirc->pathbias_probe_nonce,
  832. ocirc->global_identifier, ocirc->pathbias_probe_id);
  833. return -1;
  834. }
  835. }
  836. log_info(LD_CIRC,
  837. "Got another cell back back on pathbias probe circuit %d: "
  838. "Command: %d, Reason: %d, Stream-id: %d",
  839. ocirc->global_identifier, rh.command, reason, rh.stream_id);
  840. return -1;
  841. }
  842. /**
  843. * Check if a cell is counts as valid data for a circuit,
  844. * and if so, count it as valid.
  845. */
  846. void
  847. pathbias_count_valid_cells(circuit_t *circ, const cell_t *cell)
  848. {
  849. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  850. relay_header_t rh;
  851. relay_header_unpack(&rh, cell->payload);
  852. /* Check to see if this is a cell from a previous connection,
  853. * or is a request to close the circuit. */
  854. switch (rh.command) {
  855. case RELAY_COMMAND_TRUNCATED:
  856. /* Truncated cells can arrive on path bias circs. When they do,
  857. * just process them. This closes the circ, but it was junk anyway.
  858. * No reason to wait for the probe. */
  859. circuit_read_valid_data(ocirc, rh.length);
  860. circuit_truncated(TO_ORIGIN_CIRCUIT(circ),
  861. get_uint8(cell->payload + RELAY_HEADER_SIZE));
  862. break;
  863. case RELAY_COMMAND_END:
  864. if (connection_half_edge_is_valid_end(ocirc->half_streams,
  865. rh.stream_id)) {
  866. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  867. }
  868. break;
  869. case RELAY_COMMAND_DATA:
  870. if (connection_half_edge_is_valid_data(ocirc->half_streams,
  871. rh.stream_id)) {
  872. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  873. }
  874. break;
  875. case RELAY_COMMAND_SENDME:
  876. if (connection_half_edge_is_valid_sendme(ocirc->half_streams,
  877. rh.stream_id)) {
  878. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  879. }
  880. break;
  881. case RELAY_COMMAND_CONNECTED:
  882. if (connection_half_edge_is_valid_connected(ocirc->half_streams,
  883. rh.stream_id)) {
  884. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  885. }
  886. break;
  887. case RELAY_COMMAND_RESOLVED:
  888. if (connection_half_edge_is_valid_resolved(ocirc->half_streams,
  889. rh.stream_id)) {
  890. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  891. }
  892. break;
  893. }
  894. }
  895. /**
  896. * Check if a circuit was used and/or closed successfully.
  897. *
  898. * If we attempted to use the circuit to carry a stream but failed
  899. * for whatever reason, or if the circuit mysteriously died before
  900. * we could attach any streams, record these two cases.
  901. *
  902. * If we *have* successfully used the circuit, or it appears to
  903. * have been closed by us locally, count it as a success.
  904. *
  905. * Returns 0 if we're done making decisions with the circ,
  906. * or -1 if we want to probe it first.
  907. */
  908. int
  909. pathbias_check_close(origin_circuit_t *ocirc, int reason)
  910. {
  911. circuit_t *circ = &ocirc->base_;
  912. if (!pathbias_should_count(ocirc)) {
  913. return 0;
  914. }
  915. switch (ocirc->path_state) {
  916. /* If the circuit was closed after building, but before use, we need
  917. * to ensure we were the ones who tried to close it (and not a remote
  918. * actor). */
  919. case PATH_STATE_BUILD_SUCCEEDED:
  920. if (reason & END_CIRC_REASON_FLAG_REMOTE) {
  921. /* Remote circ close reasons on an unused circuit all could be bias */
  922. log_info(LD_CIRC,
  923. "Circuit %d remote-closed without successful use for reason %d. "
  924. "Circuit purpose %d currently %d,%s. Len %d.",
  925. ocirc->global_identifier,
  926. reason, circ->purpose, ocirc->has_opened,
  927. circuit_state_to_string(circ->state),
  928. ocirc->build_state->desired_path_len);
  929. pathbias_count_collapse(ocirc);
  930. } else if ((reason & ~END_CIRC_REASON_FLAG_REMOTE)
  931. == END_CIRC_REASON_CHANNEL_CLOSED &&
  932. circ->n_chan &&
  933. circ->n_chan->reason_for_closing
  934. != CHANNEL_CLOSE_REQUESTED) {
  935. /* If we didn't close the channel ourselves, it could be bias */
  936. /* XXX: Only count bias if the network is live?
  937. * What about clock jumps/suspends? */
  938. log_info(LD_CIRC,
  939. "Circuit %d's channel closed without successful use for reason "
  940. "%d, channel reason %d. Circuit purpose %d currently %d,%s. Len "
  941. "%d.", ocirc->global_identifier,
  942. reason, circ->n_chan->reason_for_closing,
  943. circ->purpose, ocirc->has_opened,
  944. circuit_state_to_string(circ->state),
  945. ocirc->build_state->desired_path_len);
  946. pathbias_count_collapse(ocirc);
  947. } else {
  948. pathbias_count_successful_close(ocirc);
  949. }
  950. break;
  951. /* If we tried to use a circuit but failed, we should probe it to ensure
  952. * it has not been tampered with. */
  953. case PATH_STATE_USE_ATTEMPTED:
  954. /* XXX: Only probe and/or count failure if the network is live?
  955. * What about clock jumps/suspends? */
  956. if (pathbias_send_usable_probe(circ) == 0)
  957. return -1;
  958. else
  959. pathbias_count_use_failed(ocirc);
  960. /* Any circuit where there were attempted streams but no successful
  961. * streams could be bias */
  962. log_info(LD_CIRC,
  963. "Circuit %d closed without successful use for reason %d. "
  964. "Circuit purpose %d currently %d,%s. Len %d.",
  965. ocirc->global_identifier,
  966. reason, circ->purpose, ocirc->has_opened,
  967. circuit_state_to_string(circ->state),
  968. ocirc->build_state->desired_path_len);
  969. break;
  970. case PATH_STATE_USE_SUCCEEDED:
  971. pathbias_count_successful_close(ocirc);
  972. pathbias_count_use_success(ocirc);
  973. break;
  974. case PATH_STATE_USE_FAILED:
  975. pathbias_count_use_failed(ocirc);
  976. break;
  977. case PATH_STATE_NEW_CIRC:
  978. case PATH_STATE_BUILD_ATTEMPTED:
  979. case PATH_STATE_ALREADY_COUNTED:
  980. default:
  981. // Other states are uninteresting. No stats to count.
  982. break;
  983. }
  984. ocirc->path_state = PATH_STATE_ALREADY_COUNTED;
  985. return 0;
  986. }
  987. /**
  988. * Count a successfully closed circuit.
  989. */
  990. static void
  991. pathbias_count_successful_close(origin_circuit_t *circ)
  992. {
  993. entry_guard_t *guard = NULL;
  994. if (!pathbias_should_count(circ)) {
  995. return;
  996. }
  997. if (circ->cpath && circ->cpath->extend_info) {
  998. guard = entry_guard_get_by_id_digest(
  999. circ->cpath->extend_info->identity_digest);
  1000. }
  1001. if (guard) {
  1002. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1003. /* In the long run: circuit_success ~= successful_circuit_close +
  1004. * circ_failure + stream_failure */
  1005. pb->successful_circuits_closed++;
  1006. entry_guards_changed();
  1007. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1008. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1009. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1010. * No need to log that case. */
  1011. log_info(LD_CIRC,
  1012. "Successfully closed circuit has no known guard. "
  1013. "Circuit is a %s currently %s",
  1014. circuit_purpose_to_string(circ->base_.purpose),
  1015. circuit_state_to_string(circ->base_.state));
  1016. }
  1017. }
  1018. /**
  1019. * Count a circuit that fails after it is built, but before it can
  1020. * carry any traffic.
  1021. *
  1022. * This is needed because there are ways to destroy a
  1023. * circuit after it has successfully completed. Right now, this is
  1024. * used for purely informational/debugging purposes.
  1025. */
  1026. static void
  1027. pathbias_count_collapse(origin_circuit_t *circ)
  1028. {
  1029. entry_guard_t *guard = NULL;
  1030. if (!pathbias_should_count(circ)) {
  1031. return;
  1032. }
  1033. if (circ->cpath && circ->cpath->extend_info) {
  1034. guard = entry_guard_get_by_id_digest(
  1035. circ->cpath->extend_info->identity_digest);
  1036. }
  1037. if (guard) {
  1038. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1039. pb->collapsed_circuits++;
  1040. entry_guards_changed();
  1041. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1042. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1043. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1044. * No need to log that case. */
  1045. log_info(LD_CIRC,
  1046. "Destroyed circuit has no known guard. "
  1047. "Circuit is a %s currently %s",
  1048. circuit_purpose_to_string(circ->base_.purpose),
  1049. circuit_state_to_string(circ->base_.state));
  1050. }
  1051. }
  1052. /**
  1053. * Count a known failed circuit (because we could not probe it).
  1054. *
  1055. * This counter is informational.
  1056. */
  1057. static void
  1058. pathbias_count_use_failed(origin_circuit_t *circ)
  1059. {
  1060. entry_guard_t *guard = NULL;
  1061. if (!pathbias_should_count(circ)) {
  1062. return;
  1063. }
  1064. if (circ->cpath && circ->cpath->extend_info) {
  1065. guard = entry_guard_get_by_id_digest(
  1066. circ->cpath->extend_info->identity_digest);
  1067. }
  1068. if (guard) {
  1069. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1070. pb->unusable_circuits++;
  1071. entry_guards_changed();
  1072. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1073. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1074. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1075. * No need to log that case. */
  1076. /* XXX note cut-and-paste code in this function compared to nearby
  1077. * functions. Would be nice to refactor. -RD */
  1078. log_info(LD_CIRC,
  1079. "Stream-failing circuit has no known guard. "
  1080. "Circuit is a %s currently %s",
  1081. circuit_purpose_to_string(circ->base_.purpose),
  1082. circuit_state_to_string(circ->base_.state));
  1083. }
  1084. }
  1085. /**
  1086. * Count timeouts for path bias log messages.
  1087. *
  1088. * These counts are purely informational.
  1089. */
  1090. void
  1091. pathbias_count_timeout(origin_circuit_t *circ)
  1092. {
  1093. entry_guard_t *guard = NULL;
  1094. if (!pathbias_should_count(circ)) {
  1095. return;
  1096. }
  1097. /* For hidden service circs, they can actually be used
  1098. * successfully and then time out later (because
  1099. * the other side declines to use them). */
  1100. if (circ->path_state == PATH_STATE_USE_SUCCEEDED) {
  1101. return;
  1102. }
  1103. if (circ->cpath && circ->cpath->extend_info) {
  1104. guard = entry_guard_get_by_id_digest(
  1105. circ->cpath->extend_info->identity_digest);
  1106. }
  1107. if (guard) {
  1108. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1109. pb->timeouts++;
  1110. entry_guards_changed();
  1111. }
  1112. }
  1113. /**
  1114. * Helper function to count all of the currently opened circuits
  1115. * for a guard that are in a given path state range. The state
  1116. * range is inclusive on both ends.
  1117. */
  1118. static int
  1119. pathbias_count_circs_in_states(entry_guard_t *guard,
  1120. path_state_t from,
  1121. path_state_t to)
  1122. {
  1123. int open_circuits = 0;
  1124. /* Count currently open circuits. Give them the benefit of the doubt. */
  1125. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1126. origin_circuit_t *ocirc = NULL;
  1127. if (!CIRCUIT_IS_ORIGIN(circ) || /* didn't originate here */
  1128. circ->marked_for_close) /* already counted */
  1129. continue;
  1130. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1131. if (!ocirc->cpath || !ocirc->cpath->extend_info)
  1132. continue;
  1133. if (ocirc->path_state >= from &&
  1134. ocirc->path_state <= to &&
  1135. pathbias_should_count(ocirc) &&
  1136. fast_memeq(entry_guard_get_rsa_id_digest(guard),
  1137. ocirc->cpath->extend_info->identity_digest,
  1138. DIGEST_LEN)) {
  1139. log_debug(LD_CIRC, "Found opened circuit %d in path_state %s",
  1140. ocirc->global_identifier,
  1141. pathbias_state_to_string(ocirc->path_state));
  1142. open_circuits++;
  1143. }
  1144. }
  1145. SMARTLIST_FOREACH_END(circ);
  1146. return open_circuits;
  1147. }
  1148. /**
  1149. * Return the number of circuits counted as successfully closed for
  1150. * this guard.
  1151. *
  1152. * Also add in the currently open circuits to give them the benefit
  1153. * of the doubt.
  1154. */
  1155. double
  1156. pathbias_get_close_success_count(entry_guard_t *guard)
  1157. {
  1158. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1159. return pb->successful_circuits_closed +
  1160. pathbias_count_circs_in_states(guard,
  1161. PATH_STATE_BUILD_SUCCEEDED,
  1162. PATH_STATE_USE_SUCCEEDED);
  1163. }
  1164. /**
  1165. * Return the number of circuits counted as successfully used
  1166. * this guard.
  1167. *
  1168. * Also add in the currently open circuits that we are attempting
  1169. * to use to give them the benefit of the doubt.
  1170. */
  1171. double
  1172. pathbias_get_use_success_count(entry_guard_t *guard)
  1173. {
  1174. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1175. return pb->use_successes +
  1176. pathbias_count_circs_in_states(guard,
  1177. PATH_STATE_USE_ATTEMPTED,
  1178. PATH_STATE_USE_SUCCEEDED);
  1179. }
  1180. /**
  1181. * Check the path bias use rate against our consensus parameter limits.
  1182. *
  1183. * Emits a log message if the use success rates are too low.
  1184. *
  1185. * If pathbias_get_dropguards() is set, we also disable the use of
  1186. * very failure prone guards.
  1187. */
  1188. static void
  1189. pathbias_measure_use_rate(entry_guard_t *guard)
  1190. {
  1191. const or_options_t *options = get_options();
  1192. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1193. if (pb->use_attempts > pathbias_get_min_use(options)) {
  1194. /* Note: We rely on the < comparison here to allow us to set a 0
  1195. * rate and disable the feature entirely. If refactoring, don't
  1196. * change to <= */
  1197. if (pathbias_get_use_success_count(guard)/pb->use_attempts
  1198. < pathbias_get_extreme_use_rate(options)) {
  1199. /* Dropping is currently disabled by default. */
  1200. if (pathbias_get_dropguards(options)) {
  1201. if (!pb->path_bias_disabled) {
  1202. log_warn(LD_CIRC,
  1203. "Guard %s is failing to carry an extremely large "
  1204. "amount of stream on its circuits. "
  1205. "To avoid potential route manipulation attacks, Tor has "
  1206. "disabled use of this guard. "
  1207. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  1208. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1209. "and %ld timed out. "
  1210. "For reference, your timeout cutoff is %ld seconds.",
  1211. entry_guard_describe(guard),
  1212. tor_lround(pathbias_get_use_success_count(guard)),
  1213. tor_lround(pb->use_attempts),
  1214. tor_lround(pathbias_get_close_success_count(guard)),
  1215. tor_lround(pb->circ_attempts),
  1216. tor_lround(pb->circ_successes),
  1217. tor_lround(pb->unusable_circuits),
  1218. tor_lround(pb->collapsed_circuits),
  1219. tor_lround(pb->timeouts),
  1220. tor_lround(get_circuit_build_close_time_ms()/1000));
  1221. pb->path_bias_disabled = 1;
  1222. return;
  1223. }
  1224. } else if (!pb->path_bias_use_extreme) {
  1225. pb->path_bias_use_extreme = 1;
  1226. log_warn(LD_CIRC,
  1227. "Guard %s is failing to carry an extremely large "
  1228. "amount of streams on its circuits. "
  1229. "This could indicate a route manipulation attack, network "
  1230. "overload, bad local network connectivity, or a bug. "
  1231. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  1232. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1233. "and %ld timed out. "
  1234. "For reference, your timeout cutoff is %ld seconds.",
  1235. entry_guard_describe(guard),
  1236. tor_lround(pathbias_get_use_success_count(guard)),
  1237. tor_lround(pb->use_attempts),
  1238. tor_lround(pathbias_get_close_success_count(guard)),
  1239. tor_lround(pb->circ_attempts),
  1240. tor_lround(pb->circ_successes),
  1241. tor_lround(pb->unusable_circuits),
  1242. tor_lround(pb->collapsed_circuits),
  1243. tor_lround(pb->timeouts),
  1244. tor_lround(get_circuit_build_close_time_ms()/1000));
  1245. }
  1246. } else if (pathbias_get_use_success_count(guard)/pb->use_attempts
  1247. < pathbias_get_notice_use_rate(options)) {
  1248. if (!pb->path_bias_use_noticed) {
  1249. pb->path_bias_use_noticed = 1;
  1250. log_notice(LD_CIRC,
  1251. "Guard %s is failing to carry more streams on its "
  1252. "circuits than usual. "
  1253. "Most likely this means the Tor network is overloaded "
  1254. "or your network connection is poor. "
  1255. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  1256. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1257. "and %ld timed out. "
  1258. "For reference, your timeout cutoff is %ld seconds.",
  1259. entry_guard_describe(guard),
  1260. tor_lround(pathbias_get_use_success_count(guard)),
  1261. tor_lround(pb->use_attempts),
  1262. tor_lround(pathbias_get_close_success_count(guard)),
  1263. tor_lround(pb->circ_attempts),
  1264. tor_lround(pb->circ_successes),
  1265. tor_lround(pb->unusable_circuits),
  1266. tor_lround(pb->collapsed_circuits),
  1267. tor_lround(pb->timeouts),
  1268. tor_lround(get_circuit_build_close_time_ms()/1000));
  1269. }
  1270. }
  1271. }
  1272. }
  1273. /**
  1274. * Check the path bias circuit close status rates against our consensus
  1275. * parameter limits.
  1276. *
  1277. * Emits a log message if the use success rates are too low.
  1278. *
  1279. * If pathbias_get_dropguards() is set, we also disable the use of
  1280. * very failure prone guards.
  1281. *
  1282. * XXX: This function shares similar log messages and checks to
  1283. * pathbias_measure_use_rate(). It may be possible to combine them
  1284. * eventually, especially if we can ever remove the need for 3
  1285. * levels of closure warns (if the overall circuit failure rate
  1286. * goes down with ntor). One way to do so would be to multiply
  1287. * the build rate with the use rate to get an idea of the total
  1288. * fraction of the total network paths the user is able to use.
  1289. * See ticket #8159.
  1290. */
  1291. static void
  1292. pathbias_measure_close_rate(entry_guard_t *guard)
  1293. {
  1294. const or_options_t *options = get_options();
  1295. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1296. if (pb->circ_attempts > pathbias_get_min_circs(options)) {
  1297. /* Note: We rely on the < comparison here to allow us to set a 0
  1298. * rate and disable the feature entirely. If refactoring, don't
  1299. * change to <= */
  1300. if (pathbias_get_close_success_count(guard)/pb->circ_attempts
  1301. < pathbias_get_extreme_rate(options)) {
  1302. /* Dropping is currently disabled by default. */
  1303. if (pathbias_get_dropguards(options)) {
  1304. if (!pb->path_bias_disabled) {
  1305. log_warn(LD_CIRC,
  1306. "Guard %s is failing an extremely large "
  1307. "amount of circuits. "
  1308. "To avoid potential route manipulation attacks, Tor has "
  1309. "disabled use of this guard. "
  1310. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  1311. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1312. "and %ld timed out. "
  1313. "For reference, your timeout cutoff is %ld seconds.",
  1314. entry_guard_describe(guard),
  1315. tor_lround(pathbias_get_close_success_count(guard)),
  1316. tor_lround(pb->circ_attempts),
  1317. tor_lround(pathbias_get_use_success_count(guard)),
  1318. tor_lround(pb->use_attempts),
  1319. tor_lround(pb->circ_successes),
  1320. tor_lround(pb->unusable_circuits),
  1321. tor_lround(pb->collapsed_circuits),
  1322. tor_lround(pb->timeouts),
  1323. tor_lround(get_circuit_build_close_time_ms()/1000));
  1324. pb->path_bias_disabled = 1;
  1325. return;
  1326. }
  1327. } else if (!pb->path_bias_extreme) {
  1328. pb->path_bias_extreme = 1;
  1329. log_warn(LD_CIRC,
  1330. "Guard %s is failing an extremely large "
  1331. "amount of circuits. "
  1332. "This could indicate a route manipulation attack, "
  1333. "extreme network overload, or a bug. "
  1334. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  1335. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1336. "and %ld timed out. "
  1337. "For reference, your timeout cutoff is %ld seconds.",
  1338. entry_guard_describe(guard),
  1339. tor_lround(pathbias_get_close_success_count(guard)),
  1340. tor_lround(pb->circ_attempts),
  1341. tor_lround(pathbias_get_use_success_count(guard)),
  1342. tor_lround(pb->use_attempts),
  1343. tor_lround(pb->circ_successes),
  1344. tor_lround(pb->unusable_circuits),
  1345. tor_lround(pb->collapsed_circuits),
  1346. tor_lround(pb->timeouts),
  1347. tor_lround(get_circuit_build_close_time_ms()/1000));
  1348. }
  1349. } else if (pathbias_get_close_success_count(guard)/pb->circ_attempts
  1350. < pathbias_get_warn_rate(options)) {
  1351. if (!pb->path_bias_warned) {
  1352. pb->path_bias_warned = 1;
  1353. log_warn(LD_CIRC,
  1354. "Guard %s is failing a very large "
  1355. "amount of circuits. "
  1356. "Most likely this means the Tor network is "
  1357. "overloaded, but it could also mean an attack against "
  1358. "you or potentially the guard itself. "
  1359. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  1360. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1361. "and %ld timed out. "
  1362. "For reference, your timeout cutoff is %ld seconds.",
  1363. entry_guard_describe(guard),
  1364. tor_lround(pathbias_get_close_success_count(guard)),
  1365. tor_lround(pb->circ_attempts),
  1366. tor_lround(pathbias_get_use_success_count(guard)),
  1367. tor_lround(pb->use_attempts),
  1368. tor_lround(pb->circ_successes),
  1369. tor_lround(pb->unusable_circuits),
  1370. tor_lround(pb->collapsed_circuits),
  1371. tor_lround(pb->timeouts),
  1372. tor_lround(get_circuit_build_close_time_ms()/1000));
  1373. }
  1374. } else if (pathbias_get_close_success_count(guard)/pb->circ_attempts
  1375. < pathbias_get_notice_rate(options)) {
  1376. if (!pb->path_bias_noticed) {
  1377. pb->path_bias_noticed = 1;
  1378. log_notice(LD_CIRC,
  1379. "Guard %s is failing more circuits than "
  1380. "usual. "
  1381. "Most likely this means the Tor network is overloaded. "
  1382. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  1383. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1384. "and %ld timed out. "
  1385. "For reference, your timeout cutoff is %ld seconds.",
  1386. entry_guard_describe(guard),
  1387. tor_lround(pathbias_get_close_success_count(guard)),
  1388. tor_lround(pb->circ_attempts),
  1389. tor_lround(pathbias_get_use_success_count(guard)),
  1390. tor_lround(pb->use_attempts),
  1391. tor_lround(pb->circ_successes),
  1392. tor_lround(pb->unusable_circuits),
  1393. tor_lround(pb->collapsed_circuits),
  1394. tor_lround(pb->timeouts),
  1395. tor_lround(get_circuit_build_close_time_ms()/1000));
  1396. }
  1397. }
  1398. }
  1399. }
  1400. /**
  1401. * This function scales the path bias use rates if we have
  1402. * more data than the scaling threshold. This allows us to
  1403. * be more sensitive to recent measurements.
  1404. *
  1405. * XXX: The attempt count transfer stuff here might be done
  1406. * better by keeping separate pending counters that get
  1407. * transferred at circuit close. See ticket #8160.
  1408. */
  1409. static void
  1410. pathbias_scale_close_rates(entry_guard_t *guard)
  1411. {
  1412. const or_options_t *options = get_options();
  1413. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1414. /* If we get a ton of circuits, just scale everything down */
  1415. if (pb->circ_attempts > pathbias_get_scale_threshold(options)) {
  1416. double scale_ratio = pathbias_get_scale_ratio(options);
  1417. int opened_attempts = pathbias_count_circs_in_states(guard,
  1418. PATH_STATE_BUILD_ATTEMPTED, PATH_STATE_BUILD_ATTEMPTED);
  1419. int opened_built = pathbias_count_circs_in_states(guard,
  1420. PATH_STATE_BUILD_SUCCEEDED,
  1421. PATH_STATE_USE_FAILED);
  1422. /* Verify that the counts are sane before and after scaling */
  1423. int counts_are_sane = (pb->circ_attempts >= pb->circ_successes);
  1424. pb->circ_attempts -= (opened_attempts+opened_built);
  1425. pb->circ_successes -= opened_built;
  1426. pb->circ_attempts *= scale_ratio;
  1427. pb->circ_successes *= scale_ratio;
  1428. pb->timeouts *= scale_ratio;
  1429. pb->successful_circuits_closed *= scale_ratio;
  1430. pb->collapsed_circuits *= scale_ratio;
  1431. pb->unusable_circuits *= scale_ratio;
  1432. pb->circ_attempts += (opened_attempts+opened_built);
  1433. pb->circ_successes += opened_built;
  1434. entry_guards_changed();
  1435. log_info(LD_CIRC,
  1436. "Scaled pathbias counts to (%f,%f)/%f (%d/%d open) for guard "
  1437. "%s",
  1438. pb->circ_successes, pb->successful_circuits_closed,
  1439. pb->circ_attempts, opened_built, opened_attempts,
  1440. entry_guard_describe(guard));
  1441. /* Have the counts just become invalid by this scaling attempt? */
  1442. if (counts_are_sane && pb->circ_attempts < pb->circ_successes) {
  1443. log_notice(LD_BUG,
  1444. "Scaling has mangled pathbias counts to %f/%f (%d/%d open) "
  1445. "for guard %s",
  1446. pb->circ_successes, pb->circ_attempts, opened_built,
  1447. opened_attempts,
  1448. entry_guard_describe(guard));
  1449. }
  1450. }
  1451. }
  1452. /**
  1453. * This function scales the path bias circuit close rates if we have
  1454. * more data than the scaling threshold. This allows us to be more
  1455. * sensitive to recent measurements.
  1456. *
  1457. * XXX: The attempt count transfer stuff here might be done
  1458. * better by keeping separate pending counters that get
  1459. * transferred at circuit close. See ticket #8160.
  1460. */
  1461. void
  1462. pathbias_scale_use_rates(entry_guard_t *guard)
  1463. {
  1464. const or_options_t *options = get_options();
  1465. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1466. /* If we get a ton of circuits, just scale everything down */
  1467. if (pb->use_attempts > pathbias_get_scale_use_threshold(options)) {
  1468. double scale_ratio = pathbias_get_scale_ratio(options);
  1469. int opened_attempts = pathbias_count_circs_in_states(guard,
  1470. PATH_STATE_USE_ATTEMPTED, PATH_STATE_USE_SUCCEEDED);
  1471. /* Verify that the counts are sane before and after scaling */
  1472. int counts_are_sane = (pb->use_attempts >= pb->use_successes);
  1473. pb->use_attempts -= opened_attempts;
  1474. pb->use_attempts *= scale_ratio;
  1475. pb->use_successes *= scale_ratio;
  1476. pb->use_attempts += opened_attempts;
  1477. log_info(LD_CIRC,
  1478. "Scaled pathbias use counts to %f/%f (%d open) for guard %s",
  1479. pb->use_successes, pb->use_attempts, opened_attempts,
  1480. entry_guard_describe(guard));
  1481. /* Have the counts just become invalid by this scaling attempt? */
  1482. if (counts_are_sane && pb->use_attempts < pb->use_successes) {
  1483. log_notice(LD_BUG,
  1484. "Scaling has mangled pathbias usage counts to %f/%f "
  1485. "(%d open) for guard %s",
  1486. pb->circ_successes, pb->circ_attempts,
  1487. opened_attempts, entry_guard_describe(guard));
  1488. }
  1489. entry_guards_changed();
  1490. }
  1491. }