circpathbias.c 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  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-2017, 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 "or.h"
  23. #include "channel.h"
  24. #include "circpathbias.h"
  25. #include "circuitbuild.h"
  26. #include "circuitlist.h"
  27. #include "circuituse.h"
  28. #include "circuitstats.h"
  29. #include "connection_edge.h"
  30. #include "config.h"
  31. #include "crypto_rand.h"
  32. #include "entrynodes.h"
  33. #include "networkstatus.h"
  34. #include "relay.h"
  35. static void pathbias_count_successful_close(origin_circuit_t *circ);
  36. static void pathbias_count_collapse(origin_circuit_t *circ);
  37. static void pathbias_count_use_failed(origin_circuit_t *circ);
  38. static void pathbias_measure_use_rate(entry_guard_t *guard);
  39. static void pathbias_measure_close_rate(entry_guard_t *guard);
  40. static void pathbias_scale_use_rates(entry_guard_t *guard);
  41. static void pathbias_scale_close_rates(entry_guard_t *guard);
  42. static int entry_guard_inc_circ_attempt_count(entry_guard_t *guard);
  43. /** Increment the number of times we successfully extended a circuit to
  44. * <b>guard</b>, first checking if the failure rate is high enough that
  45. * we should eliminate the guard. Return -1 if the guard looks no good;
  46. * return 0 if the guard looks fine.
  47. */
  48. static int
  49. entry_guard_inc_circ_attempt_count(entry_guard_t *guard)
  50. {
  51. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  52. entry_guards_changed();
  53. pathbias_measure_close_rate(guard);
  54. if (pb->path_bias_disabled)
  55. return -1;
  56. pathbias_scale_close_rates(guard);
  57. pb->circ_attempts++;
  58. log_info(LD_CIRC, "Got success count %f/%f for guard %s",
  59. pb->circ_successes, pb->circ_attempts,
  60. entry_guard_describe(guard));
  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 /* !(defined(N2N_TAGGING_IS_POSSIBLE)) */
  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 /* defined(N2N_TAGGING_IS_POSSIBLE) */
  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. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  478. if (circ->path_state == PATH_STATE_BUILD_ATTEMPTED) {
  479. circ->path_state = PATH_STATE_BUILD_SUCCEEDED;
  480. pb->circ_successes++;
  481. entry_guards_changed();
  482. log_info(LD_CIRC, "Got success count %f/%f for guard %s",
  483. pb->circ_successes, pb->circ_attempts,
  484. entry_guard_describe(guard));
  485. } else {
  486. if ((rate_msg = rate_limit_log(&success_notice_limit,
  487. approx_time()))) {
  488. log_info(LD_BUG,
  489. "Succeeded circuit is in strange path state %s. "
  490. "Circuit is a %s currently %s.%s",
  491. pathbias_state_to_string(circ->path_state),
  492. circuit_purpose_to_string(circ->base_.purpose),
  493. circuit_state_to_string(circ->base_.state),
  494. rate_msg);
  495. tor_free(rate_msg);
  496. }
  497. }
  498. if (pb->circ_attempts < pb->circ_successes) {
  499. log_notice(LD_BUG, "Unexpectedly high successes counts (%f/%f) "
  500. "for guard %s",
  501. pb->circ_successes, pb->circ_attempts,
  502. entry_guard_describe(guard));
  503. }
  504. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  505. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  506. * No need to log that case. */
  507. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  508. if ((rate_msg = rate_limit_log(&success_notice_limit,
  509. approx_time()))) {
  510. log_info(LD_CIRC,
  511. "Completed circuit has no known guard. "
  512. "Circuit is a %s currently %s.%s",
  513. circuit_purpose_to_string(circ->base_.purpose),
  514. circuit_state_to_string(circ->base_.state),
  515. rate_msg);
  516. tor_free(rate_msg);
  517. }
  518. }
  519. } else {
  520. if (circ->path_state < PATH_STATE_BUILD_SUCCEEDED) {
  521. if ((rate_msg = rate_limit_log(&success_notice_limit,
  522. approx_time()))) {
  523. log_info(LD_BUG,
  524. "Opened circuit is in strange path state %s. "
  525. "Circuit is a %s currently %s.%s",
  526. pathbias_state_to_string(circ->path_state),
  527. circuit_purpose_to_string(circ->base_.purpose),
  528. circuit_state_to_string(circ->base_.state),
  529. rate_msg);
  530. tor_free(rate_msg);
  531. }
  532. }
  533. }
  534. }
  535. /**
  536. * Record an attempt to use a circuit. Changes the circuit's
  537. * path state and update its guard's usage counter.
  538. *
  539. * Used for path bias usage accounting.
  540. */
  541. void
  542. pathbias_count_use_attempt(origin_circuit_t *circ)
  543. {
  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. entry_guard_t *guard = entry_guard_get_by_id_digest(
  556. circ->cpath->extend_info->identity_digest);
  557. if (guard) {
  558. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  559. pathbias_measure_use_rate(guard);
  560. pathbias_scale_use_rates(guard);
  561. pb->use_attempts++;
  562. entry_guards_changed();
  563. log_debug(LD_CIRC,
  564. "Marked circuit %d (%f/%f) as used for guard %s.",
  565. circ->global_identifier,
  566. pb->use_successes, pb->use_attempts,
  567. entry_guard_describe(guard));
  568. }
  569. circ->path_state = PATH_STATE_USE_ATTEMPTED;
  570. } else {
  571. /* Harmless but educational log message */
  572. log_info(LD_CIRC,
  573. "Used circuit %d is already in path state %s. "
  574. "Circuit is a %s currently %s.",
  575. circ->global_identifier,
  576. pathbias_state_to_string(circ->path_state),
  577. circuit_purpose_to_string(circ->base_.purpose),
  578. circuit_state_to_string(circ->base_.state));
  579. }
  580. return;
  581. }
  582. /**
  583. * Check the circuit's path state is appropriate and mark it as
  584. * successfully used. Used for path bias usage accounting.
  585. *
  586. * We don't actually increment the guard's counters until
  587. * pathbias_check_close(), because the circuit can still transition
  588. * back to PATH_STATE_USE_ATTEMPTED if a stream fails later (this
  589. * is done so we can probe the circuit for liveness at close).
  590. */
  591. void
  592. pathbias_mark_use_success(origin_circuit_t *circ)
  593. {
  594. if (!pathbias_should_count(circ)) {
  595. return;
  596. }
  597. if (circ->path_state < PATH_STATE_USE_ATTEMPTED) {
  598. log_notice(LD_BUG,
  599. "Used circuit %d is in strange path state %s. "
  600. "Circuit is a %s currently %s.",
  601. circ->global_identifier,
  602. pathbias_state_to_string(circ->path_state),
  603. circuit_purpose_to_string(circ->base_.purpose),
  604. circuit_state_to_string(circ->base_.state));
  605. pathbias_count_use_attempt(circ);
  606. }
  607. /* We don't do any accounting at the guard until actual circuit close */
  608. circ->path_state = PATH_STATE_USE_SUCCEEDED;
  609. return;
  610. }
  611. /**
  612. * If a stream ever detatches from a circuit in a retriable way,
  613. * we need to mark this circuit as still needing either another
  614. * successful stream, or in need of a probe.
  615. *
  616. * An adversary could let the first stream request succeed (ie the
  617. * resolve), but then tag and timeout the remainder (via cell
  618. * dropping), forcing them on new circuits.
  619. *
  620. * Rolling back the state will cause us to probe such circuits, which
  621. * should lead to probe failures in the event of such tagging due to
  622. * either unrecognized cells coming in while we wait for the probe,
  623. * or the cipher state getting out of sync in the case of dropped cells.
  624. */
  625. void
  626. pathbias_mark_use_rollback(origin_circuit_t *circ)
  627. {
  628. if (circ->path_state == PATH_STATE_USE_SUCCEEDED) {
  629. log_info(LD_CIRC,
  630. "Rolling back pathbias use state to 'attempted' for detached "
  631. "circuit %d", circ->global_identifier);
  632. circ->path_state = PATH_STATE_USE_ATTEMPTED;
  633. }
  634. }
  635. /**
  636. * Actually count a circuit success towards a guard's usage counters
  637. * if the path state is appropriate.
  638. */
  639. static void
  640. pathbias_count_use_success(origin_circuit_t *circ)
  641. {
  642. entry_guard_t *guard;
  643. if (!pathbias_should_count(circ)) {
  644. return;
  645. }
  646. if (circ->path_state != PATH_STATE_USE_SUCCEEDED) {
  647. log_notice(LD_BUG,
  648. "Successfully used circuit %d is in strange path state %s. "
  649. "Circuit is a %s currently %s.",
  650. circ->global_identifier,
  651. pathbias_state_to_string(circ->path_state),
  652. circuit_purpose_to_string(circ->base_.purpose),
  653. circuit_state_to_string(circ->base_.state));
  654. } else {
  655. guard = entry_guard_get_by_id_digest(
  656. circ->cpath->extend_info->identity_digest);
  657. if (guard) {
  658. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  659. pb->use_successes++;
  660. entry_guards_changed();
  661. if (pb->use_attempts < pb->use_successes) {
  662. log_notice(LD_BUG, "Unexpectedly high use successes counts (%f/%f) "
  663. "for guard %s",
  664. pb->use_successes, pb->use_attempts,
  665. entry_guard_describe(guard));
  666. }
  667. log_debug(LD_CIRC,
  668. "Marked circuit %d (%f/%f) as used successfully for guard %s",
  669. circ->global_identifier, pb->use_successes,
  670. pb->use_attempts,
  671. entry_guard_describe(guard));
  672. }
  673. }
  674. return;
  675. }
  676. /**
  677. * Send a probe down a circuit that the client attempted to use,
  678. * but for which the stream timed out/failed. The probe is a
  679. * RELAY_BEGIN cell with a 0.a.b.c destination address, which
  680. * the exit will reject and reply back, echoing that address.
  681. *
  682. * The reason for such probes is because it is possible to bias
  683. * a user's paths simply by causing timeouts, and these timeouts
  684. * are not possible to differentiate from unresponsive servers.
  685. *
  686. * The probe is sent at the end of the circuit lifetime for two
  687. * reasons: to prevent cryptographic taggers from being able to
  688. * drop cells to cause timeouts, and to prevent easy recognition
  689. * of probes before any real client traffic happens.
  690. *
  691. * Returns -1 if we couldn't probe, 0 otherwise.
  692. */
  693. static int
  694. pathbias_send_usable_probe(circuit_t *circ)
  695. {
  696. /* Based on connection_ap_handshake_send_begin() */
  697. char payload[CELL_PAYLOAD_SIZE];
  698. int payload_len;
  699. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  700. crypt_path_t *cpath_layer = NULL;
  701. char *probe_nonce = NULL;
  702. tor_assert(ocirc);
  703. cpath_layer = ocirc->cpath->prev;
  704. if (cpath_layer->state != CPATH_STATE_OPEN) {
  705. /* This can happen for cannibalized circuits. Their
  706. * last hop isn't yet open */
  707. log_info(LD_CIRC,
  708. "Got pathbias probe request for unopened circuit %d. "
  709. "Opened %d, len %d", ocirc->global_identifier,
  710. ocirc->has_opened, ocirc->build_state->desired_path_len);
  711. return -1;
  712. }
  713. /* We already went down this road. */
  714. if (circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING &&
  715. ocirc->pathbias_probe_id) {
  716. log_info(LD_CIRC,
  717. "Got pathbias probe request for circuit %d with "
  718. "outstanding probe", ocirc->global_identifier);
  719. return -1;
  720. }
  721. /* Can't probe if the channel isn't open */
  722. if (circ->n_chan == NULL ||
  723. (!CHANNEL_IS_OPEN(circ->n_chan)
  724. && !CHANNEL_IS_MAINT(circ->n_chan))) {
  725. log_info(LD_CIRC,
  726. "Skipping pathbias probe for circuit %d: Channel is not open.",
  727. ocirc->global_identifier);
  728. return -1;
  729. }
  730. circuit_change_purpose(circ, CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  731. /* Update timestamp for when circuit_expire_building() should kill us */
  732. tor_gettimeofday(&circ->timestamp_began);
  733. /* Generate a random address for the nonce */
  734. crypto_rand((char*)&ocirc->pathbias_probe_nonce,
  735. sizeof(ocirc->pathbias_probe_nonce));
  736. ocirc->pathbias_probe_nonce &= 0x00ffffff;
  737. probe_nonce = tor_dup_ip(ocirc->pathbias_probe_nonce);
  738. tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:25", probe_nonce);
  739. payload_len = (int)strlen(payload)+1;
  740. // XXX: need this? Can we assume ipv4 will always be supported?
  741. // If not, how do we tell?
  742. //if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
  743. // set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
  744. // payload_len += 4;
  745. //}
  746. /* Generate+Store stream id, make sure it's non-zero */
  747. ocirc->pathbias_probe_id = get_unique_stream_id_by_circ(ocirc);
  748. if (ocirc->pathbias_probe_id==0) {
  749. log_warn(LD_CIRC,
  750. "Ran out of stream IDs on circuit %u during "
  751. "pathbias probe attempt.", ocirc->global_identifier);
  752. tor_free(probe_nonce);
  753. return -1;
  754. }
  755. log_info(LD_CIRC,
  756. "Sending pathbias testing cell to %s:25 on stream %d for circ %d.",
  757. probe_nonce, ocirc->pathbias_probe_id, ocirc->global_identifier);
  758. tor_free(probe_nonce);
  759. /* Send a test relay cell */
  760. if (relay_send_command_from_edge(ocirc->pathbias_probe_id, circ,
  761. RELAY_COMMAND_BEGIN, payload,
  762. payload_len, cpath_layer) < 0) {
  763. log_notice(LD_CIRC,
  764. "Failed to send pathbias probe cell on circuit %d.",
  765. ocirc->global_identifier);
  766. return -1;
  767. }
  768. /* Mark it freshly dirty so it doesn't get expired in the meantime */
  769. circ->timestamp_dirty = time(NULL);
  770. return 0;
  771. }
  772. /**
  773. * Check the response to a pathbias probe, to ensure the
  774. * cell is recognized and the nonce and other probe
  775. * characteristics are as expected.
  776. *
  777. * If the response is valid, return 0. Otherwise return < 0.
  778. */
  779. int
  780. pathbias_check_probe_response(circuit_t *circ, const cell_t *cell)
  781. {
  782. /* Based on connection_edge_process_relay_cell() */
  783. relay_header_t rh;
  784. int reason;
  785. uint32_t ipv4_host;
  786. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  787. tor_assert(cell);
  788. tor_assert(ocirc);
  789. tor_assert(circ->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING);
  790. relay_header_unpack(&rh, cell->payload);
  791. reason = rh.length > 0 ?
  792. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  793. if (rh.command == RELAY_COMMAND_END &&
  794. reason == END_STREAM_REASON_EXITPOLICY &&
  795. ocirc->pathbias_probe_id == rh.stream_id) {
  796. /* Check length+extract host: It is in network order after the reason code.
  797. * See connection_edge_end(). */
  798. if (rh.length < 9) { /* reason+ipv4+dns_ttl */
  799. log_notice(LD_PROTOCOL,
  800. "Short path bias probe response length field (%d).", rh.length);
  801. return - END_CIRC_REASON_TORPROTOCOL;
  802. }
  803. ipv4_host = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  804. /* Check nonce */
  805. if (ipv4_host == ocirc->pathbias_probe_nonce) {
  806. pathbias_mark_use_success(ocirc);
  807. circuit_read_valid_data(ocirc, rh.length);
  808. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  809. log_info(LD_CIRC,
  810. "Got valid path bias probe back for circ %d, stream %d.",
  811. ocirc->global_identifier, ocirc->pathbias_probe_id);
  812. return 0;
  813. } else {
  814. log_notice(LD_CIRC,
  815. "Got strange probe value 0x%x vs 0x%x back for circ %d, "
  816. "stream %d.", ipv4_host, ocirc->pathbias_probe_nonce,
  817. ocirc->global_identifier, ocirc->pathbias_probe_id);
  818. return -1;
  819. }
  820. }
  821. log_info(LD_CIRC,
  822. "Got another cell back back on pathbias probe circuit %d: "
  823. "Command: %d, Reason: %d, Stream-id: %d",
  824. ocirc->global_identifier, rh.command, reason, rh.stream_id);
  825. return -1;
  826. }
  827. /**
  828. * Check if a cell is counts as valid data for a circuit,
  829. * and if so, count it as valid.
  830. */
  831. void
  832. pathbias_count_valid_cells(circuit_t *circ, const cell_t *cell)
  833. {
  834. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  835. relay_header_t rh;
  836. relay_header_unpack(&rh, cell->payload);
  837. /* Check to see if this is a cell from a previous connection,
  838. * or is a request to close the circuit. */
  839. switch (rh.command) {
  840. case RELAY_COMMAND_TRUNCATED:
  841. /* Truncated cells can arrive on path bias circs. When they do,
  842. * just process them. This closes the circ, but it was junk anyway.
  843. * No reason to wait for the probe. */
  844. circuit_read_valid_data(ocirc, rh.length);
  845. circuit_truncated(TO_ORIGIN_CIRCUIT(circ),
  846. get_uint8(cell->payload + RELAY_HEADER_SIZE));
  847. break;
  848. case RELAY_COMMAND_END:
  849. if (connection_half_edge_is_valid_end(ocirc->half_streams,
  850. rh.stream_id)) {
  851. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  852. }
  853. break;
  854. case RELAY_COMMAND_DATA:
  855. if (connection_half_edge_is_valid_data(ocirc->half_streams,
  856. rh.stream_id)) {
  857. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  858. }
  859. break;
  860. case RELAY_COMMAND_SENDME:
  861. if (connection_half_edge_is_valid_sendme(ocirc->half_streams,
  862. rh.stream_id)) {
  863. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  864. }
  865. break;
  866. case RELAY_COMMAND_CONNECTED:
  867. if (connection_half_edge_is_valid_connected(ocirc->half_streams,
  868. rh.stream_id)) {
  869. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  870. }
  871. break;
  872. case RELAY_COMMAND_RESOLVED:
  873. if (connection_half_edge_is_valid_resolved(ocirc->half_streams,
  874. rh.stream_id)) {
  875. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), rh.length);
  876. }
  877. break;
  878. }
  879. }
  880. /**
  881. * Check if a circuit was used and/or closed successfully.
  882. *
  883. * If we attempted to use the circuit to carry a stream but failed
  884. * for whatever reason, or if the circuit mysteriously died before
  885. * we could attach any streams, record these two cases.
  886. *
  887. * If we *have* successfully used the circuit, or it appears to
  888. * have been closed by us locally, count it as a success.
  889. *
  890. * Returns 0 if we're done making decisions with the circ,
  891. * or -1 if we want to probe it first.
  892. */
  893. int
  894. pathbias_check_close(origin_circuit_t *ocirc, int reason)
  895. {
  896. circuit_t *circ = &ocirc->base_;
  897. if (!pathbias_should_count(ocirc)) {
  898. return 0;
  899. }
  900. switch (ocirc->path_state) {
  901. /* If the circuit was closed after building, but before use, we need
  902. * to ensure we were the ones who tried to close it (and not a remote
  903. * actor). */
  904. case PATH_STATE_BUILD_SUCCEEDED:
  905. if (reason & END_CIRC_REASON_FLAG_REMOTE) {
  906. /* Remote circ close reasons on an unused circuit all could be bias */
  907. log_info(LD_CIRC,
  908. "Circuit %d remote-closed without successful use for reason %d. "
  909. "Circuit purpose %d currently %d,%s. Len %d.",
  910. ocirc->global_identifier,
  911. reason, circ->purpose, ocirc->has_opened,
  912. circuit_state_to_string(circ->state),
  913. ocirc->build_state->desired_path_len);
  914. pathbias_count_collapse(ocirc);
  915. } else if ((reason & ~END_CIRC_REASON_FLAG_REMOTE)
  916. == END_CIRC_REASON_CHANNEL_CLOSED &&
  917. circ->n_chan &&
  918. circ->n_chan->reason_for_closing
  919. != CHANNEL_CLOSE_REQUESTED) {
  920. /* If we didn't close the channel ourselves, it could be bias */
  921. /* XXX: Only count bias if the network is live?
  922. * What about clock jumps/suspends? */
  923. log_info(LD_CIRC,
  924. "Circuit %d's channel closed without successful use for reason "
  925. "%d, channel reason %d. Circuit purpose %d currently %d,%s. Len "
  926. "%d.", ocirc->global_identifier,
  927. reason, circ->n_chan->reason_for_closing,
  928. circ->purpose, ocirc->has_opened,
  929. circuit_state_to_string(circ->state),
  930. ocirc->build_state->desired_path_len);
  931. pathbias_count_collapse(ocirc);
  932. } else {
  933. pathbias_count_successful_close(ocirc);
  934. }
  935. break;
  936. /* If we tried to use a circuit but failed, we should probe it to ensure
  937. * it has not been tampered with. */
  938. case PATH_STATE_USE_ATTEMPTED:
  939. /* XXX: Only probe and/or count failure if the network is live?
  940. * What about clock jumps/suspends? */
  941. if (pathbias_send_usable_probe(circ) == 0)
  942. return -1;
  943. else
  944. pathbias_count_use_failed(ocirc);
  945. /* Any circuit where there were attempted streams but no successful
  946. * streams could be bias */
  947. log_info(LD_CIRC,
  948. "Circuit %d closed without successful use for reason %d. "
  949. "Circuit purpose %d currently %d,%s. Len %d.",
  950. ocirc->global_identifier,
  951. reason, circ->purpose, ocirc->has_opened,
  952. circuit_state_to_string(circ->state),
  953. ocirc->build_state->desired_path_len);
  954. break;
  955. case PATH_STATE_USE_SUCCEEDED:
  956. pathbias_count_successful_close(ocirc);
  957. pathbias_count_use_success(ocirc);
  958. break;
  959. case PATH_STATE_USE_FAILED:
  960. pathbias_count_use_failed(ocirc);
  961. break;
  962. case PATH_STATE_NEW_CIRC:
  963. case PATH_STATE_BUILD_ATTEMPTED:
  964. case PATH_STATE_ALREADY_COUNTED:
  965. default:
  966. // Other states are uninteresting. No stats to count.
  967. break;
  968. }
  969. ocirc->path_state = PATH_STATE_ALREADY_COUNTED;
  970. return 0;
  971. }
  972. /**
  973. * Count a successfully closed circuit.
  974. */
  975. static void
  976. pathbias_count_successful_close(origin_circuit_t *circ)
  977. {
  978. entry_guard_t *guard = NULL;
  979. if (!pathbias_should_count(circ)) {
  980. return;
  981. }
  982. if (circ->cpath && circ->cpath->extend_info) {
  983. guard = entry_guard_get_by_id_digest(
  984. circ->cpath->extend_info->identity_digest);
  985. }
  986. if (guard) {
  987. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  988. /* In the long run: circuit_success ~= successful_circuit_close +
  989. * circ_failure + stream_failure */
  990. pb->successful_circuits_closed++;
  991. entry_guards_changed();
  992. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  993. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  994. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  995. * No need to log that case. */
  996. log_info(LD_CIRC,
  997. "Successfully closed circuit has no known guard. "
  998. "Circuit is a %s currently %s",
  999. circuit_purpose_to_string(circ->base_.purpose),
  1000. circuit_state_to_string(circ->base_.state));
  1001. }
  1002. }
  1003. /**
  1004. * Count a circuit that fails after it is built, but before it can
  1005. * carry any traffic.
  1006. *
  1007. * This is needed because there are ways to destroy a
  1008. * circuit after it has successfully completed. Right now, this is
  1009. * used for purely informational/debugging purposes.
  1010. */
  1011. static void
  1012. pathbias_count_collapse(origin_circuit_t *circ)
  1013. {
  1014. entry_guard_t *guard = NULL;
  1015. if (!pathbias_should_count(circ)) {
  1016. return;
  1017. }
  1018. if (circ->cpath && circ->cpath->extend_info) {
  1019. guard = entry_guard_get_by_id_digest(
  1020. circ->cpath->extend_info->identity_digest);
  1021. }
  1022. if (guard) {
  1023. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1024. pb->collapsed_circuits++;
  1025. entry_guards_changed();
  1026. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1027. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1028. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1029. * No need to log that case. */
  1030. log_info(LD_CIRC,
  1031. "Destroyed circuit has no known guard. "
  1032. "Circuit is a %s currently %s",
  1033. circuit_purpose_to_string(circ->base_.purpose),
  1034. circuit_state_to_string(circ->base_.state));
  1035. }
  1036. }
  1037. /**
  1038. * Count a known failed circuit (because we could not probe it).
  1039. *
  1040. * This counter is informational.
  1041. */
  1042. static void
  1043. pathbias_count_use_failed(origin_circuit_t *circ)
  1044. {
  1045. entry_guard_t *guard = NULL;
  1046. if (!pathbias_should_count(circ)) {
  1047. return;
  1048. }
  1049. if (circ->cpath && circ->cpath->extend_info) {
  1050. guard = entry_guard_get_by_id_digest(
  1051. circ->cpath->extend_info->identity_digest);
  1052. }
  1053. if (guard) {
  1054. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1055. pb->unusable_circuits++;
  1056. entry_guards_changed();
  1057. } else if (circ->base_.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
  1058. /* In rare cases, CIRCUIT_PURPOSE_TESTING can get converted to
  1059. * CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT and have no guards here.
  1060. * No need to log that case. */
  1061. /* XXX note cut-and-paste code in this function compared to nearby
  1062. * functions. Would be nice to refactor. -RD */
  1063. log_info(LD_CIRC,
  1064. "Stream-failing circuit has no known guard. "
  1065. "Circuit is a %s currently %s",
  1066. circuit_purpose_to_string(circ->base_.purpose),
  1067. circuit_state_to_string(circ->base_.state));
  1068. }
  1069. }
  1070. /**
  1071. * Count timeouts for path bias log messages.
  1072. *
  1073. * These counts are purely informational.
  1074. */
  1075. void
  1076. pathbias_count_timeout(origin_circuit_t *circ)
  1077. {
  1078. entry_guard_t *guard = NULL;
  1079. if (!pathbias_should_count(circ)) {
  1080. return;
  1081. }
  1082. /* For hidden service circs, they can actually be used
  1083. * successfully and then time out later (because
  1084. * the other side declines to use them). */
  1085. if (circ->path_state == PATH_STATE_USE_SUCCEEDED) {
  1086. return;
  1087. }
  1088. if (circ->cpath && circ->cpath->extend_info) {
  1089. guard = entry_guard_get_by_id_digest(
  1090. circ->cpath->extend_info->identity_digest);
  1091. }
  1092. if (guard) {
  1093. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1094. pb->timeouts++;
  1095. entry_guards_changed();
  1096. }
  1097. }
  1098. /**
  1099. * Helper function to count all of the currently opened circuits
  1100. * for a guard that are in a given path state range. The state
  1101. * range is inclusive on both ends.
  1102. */
  1103. static int
  1104. pathbias_count_circs_in_states(entry_guard_t *guard,
  1105. path_state_t from,
  1106. path_state_t to)
  1107. {
  1108. int open_circuits = 0;
  1109. /* Count currently open circuits. Give them the benefit of the doubt. */
  1110. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1111. origin_circuit_t *ocirc = NULL;
  1112. if (!CIRCUIT_IS_ORIGIN(circ) || /* didn't originate here */
  1113. circ->marked_for_close) /* already counted */
  1114. continue;
  1115. ocirc = TO_ORIGIN_CIRCUIT(circ);
  1116. if (!ocirc->cpath || !ocirc->cpath->extend_info)
  1117. continue;
  1118. if (ocirc->path_state >= from &&
  1119. ocirc->path_state <= to &&
  1120. pathbias_should_count(ocirc) &&
  1121. fast_memeq(entry_guard_get_rsa_id_digest(guard),
  1122. ocirc->cpath->extend_info->identity_digest,
  1123. DIGEST_LEN)) {
  1124. log_debug(LD_CIRC, "Found opened circuit %d in path_state %s",
  1125. ocirc->global_identifier,
  1126. pathbias_state_to_string(ocirc->path_state));
  1127. open_circuits++;
  1128. }
  1129. }
  1130. SMARTLIST_FOREACH_END(circ);
  1131. return open_circuits;
  1132. }
  1133. /**
  1134. * Return the number of circuits counted as successfully closed for
  1135. * this guard.
  1136. *
  1137. * Also add in the currently open circuits to give them the benefit
  1138. * of the doubt.
  1139. */
  1140. double
  1141. pathbias_get_close_success_count(entry_guard_t *guard)
  1142. {
  1143. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1144. return pb->successful_circuits_closed +
  1145. pathbias_count_circs_in_states(guard,
  1146. PATH_STATE_BUILD_SUCCEEDED,
  1147. PATH_STATE_USE_SUCCEEDED);
  1148. }
  1149. /**
  1150. * Return the number of circuits counted as successfully used
  1151. * this guard.
  1152. *
  1153. * Also add in the currently open circuits that we are attempting
  1154. * to use to give them the benefit of the doubt.
  1155. */
  1156. double
  1157. pathbias_get_use_success_count(entry_guard_t *guard)
  1158. {
  1159. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1160. return pb->use_successes +
  1161. pathbias_count_circs_in_states(guard,
  1162. PATH_STATE_USE_ATTEMPTED,
  1163. PATH_STATE_USE_SUCCEEDED);
  1164. }
  1165. /**
  1166. * Check the path bias use rate against our consensus parameter limits.
  1167. *
  1168. * Emits a log message if the use success rates are too low.
  1169. *
  1170. * If pathbias_get_dropguards() is set, we also disable the use of
  1171. * very failure prone guards.
  1172. */
  1173. static void
  1174. pathbias_measure_use_rate(entry_guard_t *guard)
  1175. {
  1176. const or_options_t *options = get_options();
  1177. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1178. if (pb->use_attempts > pathbias_get_min_use(options)) {
  1179. /* Note: We rely on the < comparison here to allow us to set a 0
  1180. * rate and disable the feature entirely. If refactoring, don't
  1181. * change to <= */
  1182. if (pathbias_get_use_success_count(guard)/pb->use_attempts
  1183. < pathbias_get_extreme_use_rate(options)) {
  1184. /* Dropping is currently disabled by default. */
  1185. if (pathbias_get_dropguards(options)) {
  1186. if (!pb->path_bias_disabled) {
  1187. log_warn(LD_CIRC,
  1188. "Your Guard %s is failing to carry an extremely large "
  1189. "amount of stream on its circuits. "
  1190. "To avoid potential route manipulation attacks, Tor has "
  1191. "disabled use of this guard. "
  1192. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  1193. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1194. "and %ld timed out. "
  1195. "For reference, your timeout cutoff is %ld seconds.",
  1196. entry_guard_describe(guard),
  1197. tor_lround(pathbias_get_use_success_count(guard)),
  1198. tor_lround(pb->use_attempts),
  1199. tor_lround(pathbias_get_close_success_count(guard)),
  1200. tor_lround(pb->circ_attempts),
  1201. tor_lround(pb->circ_successes),
  1202. tor_lround(pb->unusable_circuits),
  1203. tor_lround(pb->collapsed_circuits),
  1204. tor_lround(pb->timeouts),
  1205. tor_lround(get_circuit_build_close_time_ms()/1000));
  1206. pb->path_bias_disabled = 1;
  1207. return;
  1208. }
  1209. } else if (!pb->path_bias_use_extreme) {
  1210. pb->path_bias_use_extreme = 1;
  1211. log_warn(LD_CIRC,
  1212. "Your Guard %s is failing to carry an extremely large "
  1213. "amount of streams on its circuits. "
  1214. "This could indicate a route manipulation attack, network "
  1215. "overload, bad local network connectivity, or a bug. "
  1216. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  1217. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1218. "and %ld timed out. "
  1219. "For reference, your timeout cutoff is %ld seconds.",
  1220. entry_guard_describe(guard),
  1221. tor_lround(pathbias_get_use_success_count(guard)),
  1222. tor_lround(pb->use_attempts),
  1223. tor_lround(pathbias_get_close_success_count(guard)),
  1224. tor_lround(pb->circ_attempts),
  1225. tor_lround(pb->circ_successes),
  1226. tor_lround(pb->unusable_circuits),
  1227. tor_lround(pb->collapsed_circuits),
  1228. tor_lround(pb->timeouts),
  1229. tor_lround(get_circuit_build_close_time_ms()/1000));
  1230. }
  1231. } else if (pathbias_get_use_success_count(guard)/pb->use_attempts
  1232. < pathbias_get_notice_use_rate(options)) {
  1233. if (!pb->path_bias_use_noticed) {
  1234. pb->path_bias_use_noticed = 1;
  1235. log_notice(LD_CIRC,
  1236. "Your Guard %s is failing to carry more streams on its "
  1237. "circuits than usual. "
  1238. "Most likely this means the Tor network is overloaded "
  1239. "or your network connection is poor. "
  1240. "Use counts are %ld/%ld. Success counts are %ld/%ld. "
  1241. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1242. "and %ld timed out. "
  1243. "For reference, your timeout cutoff is %ld seconds.",
  1244. entry_guard_describe(guard),
  1245. tor_lround(pathbias_get_use_success_count(guard)),
  1246. tor_lround(pb->use_attempts),
  1247. tor_lround(pathbias_get_close_success_count(guard)),
  1248. tor_lround(pb->circ_attempts),
  1249. tor_lround(pb->circ_successes),
  1250. tor_lround(pb->unusable_circuits),
  1251. tor_lround(pb->collapsed_circuits),
  1252. tor_lround(pb->timeouts),
  1253. tor_lround(get_circuit_build_close_time_ms()/1000));
  1254. }
  1255. }
  1256. }
  1257. }
  1258. /**
  1259. * Check the path bias circuit close status rates against our consensus
  1260. * parameter limits.
  1261. *
  1262. * Emits a log message if the use success rates are too low.
  1263. *
  1264. * If pathbias_get_dropguards() is set, we also disable the use of
  1265. * very failure prone guards.
  1266. *
  1267. * XXX: This function shares similar log messages and checks to
  1268. * pathbias_measure_use_rate(). It may be possible to combine them
  1269. * eventually, especially if we can ever remove the need for 3
  1270. * levels of closure warns (if the overall circuit failure rate
  1271. * goes down with ntor). One way to do so would be to multiply
  1272. * the build rate with the use rate to get an idea of the total
  1273. * fraction of the total network paths the user is able to use.
  1274. * See ticket #8159.
  1275. */
  1276. static void
  1277. pathbias_measure_close_rate(entry_guard_t *guard)
  1278. {
  1279. const or_options_t *options = get_options();
  1280. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1281. if (pb->circ_attempts > pathbias_get_min_circs(options)) {
  1282. /* Note: We rely on the < comparison here to allow us to set a 0
  1283. * rate and disable the feature entirely. If refactoring, don't
  1284. * change to <= */
  1285. if (pathbias_get_close_success_count(guard)/pb->circ_attempts
  1286. < pathbias_get_extreme_rate(options)) {
  1287. /* Dropping is currently disabled by default. */
  1288. if (pathbias_get_dropguards(options)) {
  1289. if (!pb->path_bias_disabled) {
  1290. log_warn(LD_CIRC,
  1291. "Your Guard %s is failing an extremely large "
  1292. "amount of circuits. "
  1293. "To avoid potential route manipulation attacks, Tor has "
  1294. "disabled use of this guard. "
  1295. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  1296. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1297. "and %ld timed out. "
  1298. "For reference, your timeout cutoff is %ld seconds.",
  1299. entry_guard_describe(guard),
  1300. tor_lround(pathbias_get_close_success_count(guard)),
  1301. tor_lround(pb->circ_attempts),
  1302. tor_lround(pathbias_get_use_success_count(guard)),
  1303. tor_lround(pb->use_attempts),
  1304. tor_lround(pb->circ_successes),
  1305. tor_lround(pb->unusable_circuits),
  1306. tor_lround(pb->collapsed_circuits),
  1307. tor_lround(pb->timeouts),
  1308. tor_lround(get_circuit_build_close_time_ms()/1000));
  1309. pb->path_bias_disabled = 1;
  1310. return;
  1311. }
  1312. } else if (!pb->path_bias_extreme) {
  1313. pb->path_bias_extreme = 1;
  1314. log_warn(LD_CIRC,
  1315. "Your Guard %s is failing an extremely large "
  1316. "amount of circuits. "
  1317. "This could indicate a route manipulation attack, "
  1318. "extreme network overload, or a bug. "
  1319. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  1320. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1321. "and %ld timed out. "
  1322. "For reference, your timeout cutoff is %ld seconds.",
  1323. entry_guard_describe(guard),
  1324. tor_lround(pathbias_get_close_success_count(guard)),
  1325. tor_lround(pb->circ_attempts),
  1326. tor_lround(pathbias_get_use_success_count(guard)),
  1327. tor_lround(pb->use_attempts),
  1328. tor_lround(pb->circ_successes),
  1329. tor_lround(pb->unusable_circuits),
  1330. tor_lround(pb->collapsed_circuits),
  1331. tor_lround(pb->timeouts),
  1332. tor_lround(get_circuit_build_close_time_ms()/1000));
  1333. }
  1334. } else if (pathbias_get_close_success_count(guard)/pb->circ_attempts
  1335. < pathbias_get_warn_rate(options)) {
  1336. if (!pb->path_bias_warned) {
  1337. pb->path_bias_warned = 1;
  1338. log_warn(LD_CIRC,
  1339. "Your Guard %s is failing a very large "
  1340. "amount of circuits. "
  1341. "Most likely this means the Tor network is "
  1342. "overloaded, but it could also mean an attack against "
  1343. "you or potentially the guard itself. "
  1344. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  1345. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1346. "and %ld timed out. "
  1347. "For reference, your timeout cutoff is %ld seconds.",
  1348. entry_guard_describe(guard),
  1349. tor_lround(pathbias_get_close_success_count(guard)),
  1350. tor_lround(pb->circ_attempts),
  1351. tor_lround(pathbias_get_use_success_count(guard)),
  1352. tor_lround(pb->use_attempts),
  1353. tor_lround(pb->circ_successes),
  1354. tor_lround(pb->unusable_circuits),
  1355. tor_lround(pb->collapsed_circuits),
  1356. tor_lround(pb->timeouts),
  1357. tor_lround(get_circuit_build_close_time_ms()/1000));
  1358. }
  1359. } else if (pathbias_get_close_success_count(guard)/pb->circ_attempts
  1360. < pathbias_get_notice_rate(options)) {
  1361. if (!pb->path_bias_noticed) {
  1362. pb->path_bias_noticed = 1;
  1363. log_notice(LD_CIRC,
  1364. "Your Guard %s is failing more circuits than "
  1365. "usual. "
  1366. "Most likely this means the Tor network is overloaded. "
  1367. "Success counts are %ld/%ld. Use counts are %ld/%ld. "
  1368. "%ld circuits completed, %ld were unusable, %ld collapsed, "
  1369. "and %ld timed out. "
  1370. "For reference, your timeout cutoff is %ld seconds.",
  1371. entry_guard_describe(guard),
  1372. tor_lround(pathbias_get_close_success_count(guard)),
  1373. tor_lround(pb->circ_attempts),
  1374. tor_lround(pathbias_get_use_success_count(guard)),
  1375. tor_lround(pb->use_attempts),
  1376. tor_lround(pb->circ_successes),
  1377. tor_lround(pb->unusable_circuits),
  1378. tor_lround(pb->collapsed_circuits),
  1379. tor_lround(pb->timeouts),
  1380. tor_lround(get_circuit_build_close_time_ms()/1000));
  1381. }
  1382. }
  1383. }
  1384. }
  1385. /**
  1386. * This function scales the path bias use rates if we have
  1387. * more data than the scaling threshold. This allows us to
  1388. * be more sensitive to recent measurements.
  1389. *
  1390. * XXX: The attempt count transfer stuff here might be done
  1391. * better by keeping separate pending counters that get
  1392. * transferred at circuit close. See ticket #8160.
  1393. */
  1394. static void
  1395. pathbias_scale_close_rates(entry_guard_t *guard)
  1396. {
  1397. const or_options_t *options = get_options();
  1398. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1399. /* If we get a ton of circuits, just scale everything down */
  1400. if (pb->circ_attempts > pathbias_get_scale_threshold(options)) {
  1401. double scale_ratio = pathbias_get_scale_ratio(options);
  1402. int opened_attempts = pathbias_count_circs_in_states(guard,
  1403. PATH_STATE_BUILD_ATTEMPTED, PATH_STATE_BUILD_ATTEMPTED);
  1404. int opened_built = pathbias_count_circs_in_states(guard,
  1405. PATH_STATE_BUILD_SUCCEEDED,
  1406. PATH_STATE_USE_FAILED);
  1407. /* Verify that the counts are sane before and after scaling */
  1408. int counts_are_sane = (pb->circ_attempts >= pb->circ_successes);
  1409. pb->circ_attempts -= (opened_attempts+opened_built);
  1410. pb->circ_successes -= opened_built;
  1411. pb->circ_attempts *= scale_ratio;
  1412. pb->circ_successes *= scale_ratio;
  1413. pb->timeouts *= scale_ratio;
  1414. pb->successful_circuits_closed *= scale_ratio;
  1415. pb->collapsed_circuits *= scale_ratio;
  1416. pb->unusable_circuits *= scale_ratio;
  1417. pb->circ_attempts += (opened_attempts+opened_built);
  1418. pb->circ_successes += opened_built;
  1419. entry_guards_changed();
  1420. log_info(LD_CIRC,
  1421. "Scaled pathbias counts to (%f,%f)/%f (%d/%d open) for guard "
  1422. "%s",
  1423. pb->circ_successes, pb->successful_circuits_closed,
  1424. pb->circ_attempts, opened_built, opened_attempts,
  1425. entry_guard_describe(guard));
  1426. /* Have the counts just become invalid by this scaling attempt? */
  1427. if (counts_are_sane && pb->circ_attempts < pb->circ_successes) {
  1428. log_notice(LD_BUG,
  1429. "Scaling has mangled pathbias counts to %f/%f (%d/%d open) "
  1430. "for guard %s",
  1431. pb->circ_successes, pb->circ_attempts, opened_built,
  1432. opened_attempts,
  1433. entry_guard_describe(guard));
  1434. }
  1435. }
  1436. }
  1437. /**
  1438. * This function scales the path bias circuit close rates if we have
  1439. * more data than the scaling threshold. This allows us to be more
  1440. * sensitive to recent measurements.
  1441. *
  1442. * XXX: The attempt count transfer stuff here might be done
  1443. * better by keeping separate pending counters that get
  1444. * transferred at circuit close. See ticket #8160.
  1445. */
  1446. void
  1447. pathbias_scale_use_rates(entry_guard_t *guard)
  1448. {
  1449. const or_options_t *options = get_options();
  1450. guard_pathbias_t *pb = entry_guard_get_pathbias_state(guard);
  1451. /* If we get a ton of circuits, just scale everything down */
  1452. if (pb->use_attempts > pathbias_get_scale_use_threshold(options)) {
  1453. double scale_ratio = pathbias_get_scale_ratio(options);
  1454. int opened_attempts = pathbias_count_circs_in_states(guard,
  1455. PATH_STATE_USE_ATTEMPTED, PATH_STATE_USE_SUCCEEDED);
  1456. /* Verify that the counts are sane before and after scaling */
  1457. int counts_are_sane = (pb->use_attempts >= pb->use_successes);
  1458. pb->use_attempts -= opened_attempts;
  1459. pb->use_attempts *= scale_ratio;
  1460. pb->use_successes *= scale_ratio;
  1461. pb->use_attempts += opened_attempts;
  1462. log_info(LD_CIRC,
  1463. "Scaled pathbias use counts to %f/%f (%d open) for guard %s",
  1464. pb->use_successes, pb->use_attempts, opened_attempts,
  1465. entry_guard_describe(guard));
  1466. /* Have the counts just become invalid by this scaling attempt? */
  1467. if (counts_are_sane && pb->use_attempts < pb->use_successes) {
  1468. log_notice(LD_BUG,
  1469. "Scaling has mangled pathbias usage counts to %f/%f "
  1470. "(%d open) for guard %s",
  1471. pb->circ_successes, pb->circ_attempts,
  1472. opened_attempts, entry_guard_describe(guard));
  1473. }
  1474. entry_guards_changed();
  1475. }
  1476. }