circpathbias.c 58 KB

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