circpathbias.c 56 KB

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