circuitpadding.c 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576
  1. /* Copyright (c) 2017 The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file circuitpadding.c
  5. * \brief Circuit-level padding implementation
  6. *
  7. * \details
  8. *
  9. * This file implements Tor proposal 254 "Padding Negotiation" which is heavily
  10. * inspired by the paper "Toward an Efficient Website Fingerprinting Defense"
  11. * by M. Juarez, M. Imani, M. Perry, C. Diaz, M. Wright.
  12. *
  13. * In particular the code in this file describes mechanisms for clients to
  14. * negotiate various types of circuit-level padding from relays.
  15. *
  16. * Each padding type is described by a state machine (circpad_machine_spec_t),
  17. * which is also referred as a "padding machine" in this file. Currently,
  18. * these state machines are hardcoded in the source code (e.g. see
  19. * circpad_circ_client_machine_init()), but in the future we will be able to
  20. * serialize them in the torrc or the consensus.
  21. *
  22. * As specified by prop#254, clients can negotiate padding with relays by using
  23. * PADDING_NEGOTIATE cells. After successful padding negotiation, padding
  24. * machines are assigned to the circuit in their mutable form as a
  25. * circpad_machine_state_t.
  26. *
  27. * Each state of a padding state machine can be either:
  28. * - A histogram that specifies inter-arrival padding delays.
  29. * - Or a parametrized probability distribution that specifies inter-arrival
  30. * delays (see circpad_distribution_type_t).
  31. *
  32. * Padding machines start from the START state and finish with the END
  33. * state. They can transition between states using the events in
  34. * circpad_event_t.
  35. *
  36. * When a padding machine reaches the END state, it gets wiped from the circuit
  37. * so that other padding machines can take over if needed (see
  38. * circpad_machine_spec_transitioned_to_end()).
  39. **/
  40. #define CIRCUITPADDING_PRIVATE
  41. #include <math.h>
  42. #include "lib/math/fp.h"
  43. #include "lib/math/prob_distr.h"
  44. #include "core/or/or.h"
  45. #include "core/or/circuitpadding.h"
  46. #include "core/or/circuitlist.h"
  47. #include "core/or/circuituse.h"
  48. #include "core/or/relay.h"
  49. #include "feature/stats/rephist.h"
  50. #include "feature/nodelist/networkstatus.h"
  51. #include "core/or/channel.h"
  52. #include "lib/time/compat_time.h"
  53. #include "lib/defs/time.h"
  54. #include "lib/crypt_ops/crypto_rand.h"
  55. #include "core/or/crypt_path_st.h"
  56. #include "core/or/circuit_st.h"
  57. #include "core/or/origin_circuit_st.h"
  58. #include "core/or/or_circuit_st.h"
  59. #include "feature/nodelist/routerstatus_st.h"
  60. #include "feature/nodelist/node_st.h"
  61. #include "core/or/cell_st.h"
  62. #include "core/or/extend_info_st.h"
  63. #include "core/crypto/relay_crypto.h"
  64. #include "feature/nodelist/nodelist.h"
  65. #include "app/config/config.h"
  66. static inline circpad_purpose_mask_t circpad_circ_purpose_to_mask(uint8_t
  67. circ_purpose);
  68. static inline circpad_circuit_state_t circpad_circuit_state(
  69. origin_circuit_t *circ);
  70. static void circpad_setup_machine_on_circ(circuit_t *on_circ,
  71. const circpad_machine_spec_t *machine);
  72. static double circpad_distribution_sample(circpad_distribution_t dist);
  73. /** Cached consensus params */
  74. static uint8_t circpad_global_max_padding_percent;
  75. static uint16_t circpad_global_allowed_cells;
  76. static uint16_t circpad_max_circ_queued_cells;
  77. /** Global cell counts, for rate limiting */
  78. static uint64_t circpad_global_padding_sent;
  79. static uint64_t circpad_global_nonpadding_sent;
  80. /** This is the list of circpad_machine_spec_t's parsed from consensus and
  81. * torrc that have origin_side == 1 (ie: are for client side).
  82. *
  83. * The machines in this smartlist are considered immutable and they are used
  84. * as-is by circuits so they should not change or get deallocated in Tor's
  85. * runtime and as long as circuits are alive. */
  86. STATIC smartlist_t *origin_padding_machines = NULL;
  87. /** This is the list of circpad_machine_spec_t's parsed from consensus and
  88. * torrc that have origin_side == 0 (ie: are for relay side).
  89. *
  90. * The machines in this smartlist are considered immutable and they are used
  91. * as-is by circuits so they should not change or get deallocated in Tor's
  92. * runtime and as long as circuits are alive. */
  93. STATIC smartlist_t *relay_padding_machines = NULL;
  94. /** Loop over the current padding state machines using <b>loop_var</b> as the
  95. * loop variable. */
  96. #define FOR_EACH_CIRCUIT_MACHINE_BEGIN(loop_var) \
  97. STMT_BEGIN \
  98. for (int loop_var = 0; loop_var < CIRCPAD_MAX_MACHINES; loop_var++) {
  99. #define FOR_EACH_CIRCUIT_MACHINE_END } STMT_END ;
  100. /** Loop over the current active padding state machines using <b>loop_var</b>
  101. * as the loop variable. If a machine is not active, skip it. */
  102. #define FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(loop_var, circ) \
  103. FOR_EACH_CIRCUIT_MACHINE_BEGIN(loop_var) \
  104. if (!(circ)->padding_info[loop_var]) \
  105. continue;
  106. #define FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END } STMT_END ;
  107. /**
  108. * Return a human-readable description for a circuit padding state.
  109. */
  110. static const char *
  111. circpad_state_to_string(circpad_statenum_t state)
  112. {
  113. const char *descr;
  114. switch (state) {
  115. case CIRCPAD_STATE_START:
  116. descr = "START";
  117. break;
  118. case CIRCPAD_STATE_BURST:
  119. descr = "BURST";
  120. break;
  121. case CIRCPAD_STATE_GAP:
  122. descr = "GAP";
  123. break;
  124. case CIRCPAD_STATE_END:
  125. descr = "END";
  126. break;
  127. default:
  128. descr = "CUSTOM"; // XXX: Just return # in static char buf?
  129. }
  130. return descr;
  131. }
  132. /**
  133. * Free the machineinfo at an index
  134. */
  135. static void
  136. circpad_circuit_machineinfo_free_idx(circuit_t *circ, int idx)
  137. {
  138. if (circ->padding_info[idx]) {
  139. tor_free(circ->padding_info[idx]->histogram);
  140. timer_free(circ->padding_info[idx]->padding_timer);
  141. tor_free(circ->padding_info[idx]);
  142. }
  143. }
  144. /** Free all the machineinfos in <b>circ</b> that match <b>machine_num</b>. */
  145. static void
  146. free_circ_machineinfos_with_machine_num(circuit_t *circ, int machine_num)
  147. {
  148. FOR_EACH_CIRCUIT_MACHINE_BEGIN(i) {
  149. if (circ->padding_machine[i] &&
  150. circ->padding_machine[i]->machine_num == machine_num) {
  151. circpad_circuit_machineinfo_free_idx(circ, i);
  152. circ->padding_machine[i] = NULL;
  153. }
  154. } FOR_EACH_CIRCUIT_MACHINE_END;
  155. }
  156. /**
  157. * Free all padding machines and mutable info associated with circuit
  158. */
  159. void
  160. circpad_circuit_free_all_machineinfos(circuit_t *circ)
  161. {
  162. FOR_EACH_CIRCUIT_MACHINE_BEGIN(i) {
  163. circpad_circuit_machineinfo_free_idx(circ, i);
  164. } FOR_EACH_CIRCUIT_MACHINE_END;
  165. }
  166. /**
  167. * Allocate a new mutable machineinfo structure.
  168. */
  169. STATIC circpad_machine_state_t *
  170. circpad_circuit_machineinfo_new(circuit_t *on_circ, int machine_index)
  171. {
  172. circpad_machine_state_t *mi =
  173. tor_malloc_zero(sizeof(circpad_machine_state_t));
  174. mi->machine_index = machine_index;
  175. mi->on_circ = on_circ;
  176. return mi;
  177. }
  178. /**
  179. * Return the circpad_state_t for the current state based on the
  180. * mutable info.
  181. *
  182. * This function returns NULL when the machine is in the end state or in an
  183. * invalid state.
  184. */
  185. STATIC const circpad_state_t *
  186. circpad_machine_current_state(const circpad_machine_state_t *mi)
  187. {
  188. const circpad_machine_spec_t *machine = CIRCPAD_GET_MACHINE(mi);
  189. if (mi->current_state == CIRCPAD_STATE_END) {
  190. return NULL;
  191. } else if (BUG(mi->current_state >= machine->num_states)) {
  192. log_fn(LOG_WARN,LD_CIRC,
  193. "Invalid circuit padding state %d",
  194. mi->current_state);
  195. return NULL;
  196. }
  197. return &machine->states[mi->current_state];
  198. }
  199. /**
  200. * Calculate the lower bound of a histogram bin. The upper bound
  201. * is obtained by calling this function with bin+1, and subtracting 1.
  202. *
  203. * The 0th bin has a special value -- it only represents start_usec.
  204. * This is so we can specify a probability on 0-delay values.
  205. *
  206. * After bin 0, bins are exponentially spaced, so that each subsequent
  207. * bin is twice as large as the previous. This is done so that higher
  208. * time resolution is given to lower time values.
  209. *
  210. * The infinity bin is a the last bin in the array (histogram_len-1).
  211. * It has a usec value of CIRCPAD_DELAY_INFINITE (UINT32_MAX).
  212. */
  213. STATIC circpad_delay_t
  214. circpad_histogram_bin_to_usec(const circpad_machine_state_t *mi,
  215. circpad_hist_index_t bin)
  216. {
  217. const circpad_state_t *state = circpad_machine_current_state(mi);
  218. circpad_delay_t start_usec;
  219. /* Our state should have been checked to be non-null by the caller
  220. * (circpad_machine_remove_token()) */
  221. if (BUG(state == NULL)) {
  222. return CIRCPAD_DELAY_INFINITE;
  223. }
  224. if (state->use_rtt_estimate)
  225. start_usec = mi->rtt_estimate_usec+state->start_usec;
  226. else
  227. start_usec = state->start_usec;
  228. if (bin >= CIRCPAD_INFINITY_BIN(state))
  229. return CIRCPAD_DELAY_INFINITE;
  230. if (bin == 0)
  231. return start_usec;
  232. if (bin == 1)
  233. return start_usec+1;
  234. /* The bin widths double every index, so that we can have more resolution
  235. * for lower time values in the histogram. */
  236. const circpad_time_t bin_width_exponent =
  237. 1 << (CIRCPAD_INFINITY_BIN(state) - bin);
  238. return (circpad_delay_t)MIN(start_usec +
  239. state->range_usec/bin_width_exponent,
  240. CIRCPAD_DELAY_INFINITE);
  241. }
  242. /** Return the midpoint of the histogram bin <b>bin_index</b>. */
  243. static circpad_delay_t
  244. circpad_get_histogram_bin_midpoint(const circpad_machine_state_t *mi,
  245. int bin_index)
  246. {
  247. circpad_delay_t left_bound = circpad_histogram_bin_to_usec(mi, bin_index);
  248. circpad_delay_t right_bound =
  249. circpad_histogram_bin_to_usec(mi, bin_index+1)-1;
  250. return left_bound + (right_bound - left_bound)/2;
  251. }
  252. /**
  253. * Return the bin that contains the usec argument.
  254. * "Contains" is defined as us in [lower, upper).
  255. *
  256. * This function will never return the infinity bin (histogram_len-1),
  257. * in order to simplify the rest of the code.
  258. *
  259. * This means that technically the last bin (histogram_len-2)
  260. * has range [start_usec+range_usec, CIRCPAD_DELAY_INFINITE].
  261. */
  262. STATIC circpad_hist_index_t
  263. circpad_histogram_usec_to_bin(const circpad_machine_state_t *mi,
  264. circpad_delay_t usec)
  265. {
  266. const circpad_state_t *state = circpad_machine_current_state(mi);
  267. circpad_delay_t start_usec;
  268. int32_t bin; /* Larger than return type to properly clamp overflow */
  269. /* Our state should have been checked to be non-null by the caller
  270. * (circpad_machine_remove_token()) */
  271. if (BUG(state == NULL)) {
  272. return 0;
  273. }
  274. if (state->use_rtt_estimate)
  275. start_usec = mi->rtt_estimate_usec+state->start_usec;
  276. else
  277. start_usec = state->start_usec;
  278. /* The first bin (#0) has zero width and starts (and ends) at start_usec. */
  279. if (usec <= start_usec)
  280. return 0;
  281. if (usec == start_usec+1)
  282. return 1;
  283. const circpad_time_t histogram_range_usec = state->range_usec;
  284. /* We need to find the bin corresponding to our position in the range.
  285. * Since bins are exponentially spaced in powers of two, we need to
  286. * take the log2 of our position in histogram_range_usec. However,
  287. * since tor_log2() returns the floor(log2(u64)), we have to adjust
  288. * it to behave like ceil(log2(u64)). This is verified in our tests
  289. * to properly invert the operation done in
  290. * circpad_histogram_bin_to_usec(). */
  291. bin = CIRCPAD_INFINITY_BIN(state) -
  292. tor_log2(2*histogram_range_usec/(usec-start_usec+1));
  293. /* Clamp the return value to account for timevals before the start
  294. * of bin 0, or after the last bin. Don't return the infinity bin
  295. * index. */
  296. bin = MIN(MAX(bin, 1), CIRCPAD_INFINITY_BIN(state)-1);
  297. return bin;
  298. }
  299. /**
  300. * This function frees any token bins allocated from a previous state
  301. *
  302. * Called after a state transition, or if the bins are empty.
  303. */
  304. STATIC void
  305. circpad_machine_setup_tokens(circpad_machine_state_t *mi)
  306. {
  307. const circpad_state_t *state = circpad_machine_current_state(mi);
  308. /* If this state doesn't exist, or doesn't have token removal,
  309. * free any previous state's histogram, and bail */
  310. if (!state || state->token_removal == CIRCPAD_TOKEN_REMOVAL_NONE) {
  311. if (mi->histogram) {
  312. tor_free(mi->histogram);
  313. mi->histogram = NULL;
  314. mi->histogram_len = 0;
  315. }
  316. return;
  317. }
  318. /* Try to avoid re-mallocing if we don't really need to */
  319. if (!mi->histogram || (mi->histogram
  320. && mi->histogram_len != state->histogram_len)) {
  321. tor_free(mi->histogram); // null ok
  322. mi->histogram = tor_malloc_zero(sizeof(circpad_hist_token_t)
  323. *state->histogram_len);
  324. }
  325. mi->histogram_len = state->histogram_len;
  326. memcpy(mi->histogram, state->histogram,
  327. sizeof(circpad_hist_token_t)*state->histogram_len);
  328. }
  329. /**
  330. * Choose a length for this state (in cells), if specified.
  331. */
  332. static void
  333. circpad_choose_state_length(circpad_machine_state_t *mi)
  334. {
  335. const circpad_state_t *state = circpad_machine_current_state(mi);
  336. double length;
  337. if (!state || state->length_dist.type == CIRCPAD_DIST_NONE) {
  338. mi->state_length = CIRCPAD_STATE_LENGTH_INFINITE;
  339. return;
  340. }
  341. length = circpad_distribution_sample(state->length_dist);
  342. length = MAX(0, length);
  343. length += state->start_length;
  344. length = MIN(length, state->max_length);
  345. mi->state_length = clamp_double_to_int64(length);
  346. }
  347. /**
  348. * Sample a value from our iat_dist, and clamp it safely
  349. * to circpad_delay_t.
  350. */
  351. static circpad_delay_t
  352. circpad_distribution_sample_iat_delay(const circpad_state_t *state,
  353. circpad_delay_t start_usec)
  354. {
  355. double val = circpad_distribution_sample(state->iat_dist);
  356. /* These comparisons are safe, because the output is in the range
  357. * [0, 2**32), and double has a precision of 53 bits. */
  358. val = MAX(0, val);
  359. val = MIN(val, state->range_usec);
  360. /* This addition is exact: val is at most 2**32-1, start_usec
  361. * is at most 2**32-1, and doubles have a precision of 53 bits. */
  362. val += start_usec;
  363. /* Clamp the distribution at infinite delay val */
  364. return (circpad_delay_t)MIN(tor_llround(val), CIRCPAD_DELAY_INFINITE);
  365. }
  366. /**
  367. * Sample an expected time-until-next-packet delay from the histogram.
  368. *
  369. * The bin is chosen with probability proportional to the number
  370. * of tokens in each bin, and then a time value is chosen uniformly from
  371. * that bin's [start,end) time range.
  372. */
  373. STATIC circpad_delay_t
  374. circpad_machine_sample_delay(circpad_machine_state_t *mi)
  375. {
  376. const circpad_state_t *state = circpad_machine_current_state(mi);
  377. const circpad_hist_token_t *histogram = NULL;
  378. circpad_hist_index_t curr_bin = 0;
  379. circpad_delay_t bin_start, bin_end;
  380. circpad_delay_t start_usec;
  381. /* These three must all be larger than circpad_hist_token_t, because
  382. * we sum several circpad_hist_token_t values across the histogram */
  383. uint64_t curr_weight = 0;
  384. uint64_t histogram_total_tokens = 0;
  385. uint64_t bin_choice;
  386. tor_assert(state);
  387. if (state->use_rtt_estimate)
  388. start_usec = mi->rtt_estimate_usec+state->start_usec;
  389. else
  390. start_usec = state->start_usec;
  391. if (state->iat_dist.type != CIRCPAD_DIST_NONE) {
  392. /* Sample from a fixed IAT distribution and return */
  393. return circpad_distribution_sample_iat_delay(state, start_usec);
  394. } else if (state->token_removal != CIRCPAD_TOKEN_REMOVAL_NONE) {
  395. /* We have a mutable histogram. Do basic sanity check and apply: */
  396. if (BUG(!mi->histogram) ||
  397. BUG(mi->histogram_len != state->histogram_len)) {
  398. return CIRCPAD_DELAY_INFINITE;
  399. }
  400. histogram = mi->histogram;
  401. for (circpad_hist_index_t b = 0; b < state->histogram_len; b++)
  402. histogram_total_tokens += histogram[b];
  403. } else {
  404. /* We have a histogram, but it's immutable */
  405. histogram = state->histogram;
  406. histogram_total_tokens = state->histogram_total_tokens;
  407. }
  408. bin_choice = crypto_rand_uint64(histogram_total_tokens);
  409. /* Skip all the initial zero bins */
  410. while (!histogram[curr_bin]) {
  411. curr_bin++;
  412. }
  413. curr_weight = histogram[curr_bin];
  414. // TODO: This is not constant-time. Pretty sure we don't
  415. // really need it to be, though.
  416. while (curr_weight < bin_choice) {
  417. curr_bin++;
  418. /* It should be impossible to run past the end of the histogram */
  419. if (BUG(curr_bin >= state->histogram_len)) {
  420. return CIRCPAD_DELAY_INFINITE;
  421. }
  422. curr_weight += histogram[curr_bin];
  423. }
  424. /* Do some basic checking of the current bin we are in */
  425. if (BUG(curr_bin >= state->histogram_len) ||
  426. BUG(histogram[curr_bin] == 0)) {
  427. return CIRCPAD_DELAY_INFINITE;
  428. }
  429. // Store this index to remove the token upon callback.
  430. if (state->token_removal != CIRCPAD_TOKEN_REMOVAL_NONE) {
  431. mi->chosen_bin = curr_bin;
  432. }
  433. if (curr_bin >= CIRCPAD_INFINITY_BIN(state)) {
  434. if (state->token_removal != CIRCPAD_TOKEN_REMOVAL_NONE &&
  435. mi->histogram[curr_bin] > 0) {
  436. mi->histogram[curr_bin]--;
  437. }
  438. // Infinity: Don't send a padding packet. Wait for a real packet
  439. // and then see if our bins are empty or what else we should do.
  440. return CIRCPAD_DELAY_INFINITE;
  441. }
  442. tor_assert(curr_bin < CIRCPAD_INFINITY_BIN(state));
  443. bin_start = circpad_histogram_bin_to_usec(mi, curr_bin);
  444. /* We don't need to reduct 1 from the upper bound because the random range
  445. * function below samples from [bin_start, bin_end) */
  446. bin_end = circpad_histogram_bin_to_usec(mi, curr_bin+1);
  447. /* Truncate the high bin in case it's the infinity bin:
  448. * Don't actually schedule an "infinite"-1 delay */
  449. bin_end = MIN(bin_end, start_usec+state->range_usec);
  450. // Sample uniformly between histogram[i] to histogram[i+1]-1,
  451. // but no need to sample if they are the same timeval (aka bin 0 or bin 1).
  452. if (bin_end <= bin_start+1)
  453. return bin_start;
  454. else
  455. return (circpad_delay_t)crypto_rand_uint64_range(bin_start, bin_end);
  456. }
  457. /**
  458. * Sample a value from the specified probability distribution.
  459. *
  460. * This performs inverse transform sampling
  461. * (https://en.wikipedia.org/wiki/Inverse_transform_sampling).
  462. *
  463. * XXX: These formulas were taken verbatim. Need a floating wizard
  464. * to check them for catastropic cancellation and other issues (teor?).
  465. * Also: is 32bits of double from [0.0,1.0) enough?
  466. */
  467. static double
  468. circpad_distribution_sample(circpad_distribution_t dist)
  469. {
  470. log_fn(LOG_DEBUG,LD_CIRC, "Sampling delay with distribution %d",
  471. dist.type);
  472. switch (dist.type) {
  473. case CIRCPAD_DIST_NONE:
  474. {
  475. /* We should not get in here like this */
  476. tor_assert_nonfatal_unreached();
  477. return 0;
  478. }
  479. case CIRCPAD_DIST_UNIFORM:
  480. {
  481. // param2 is upper bound, param1 is lower
  482. const struct uniform my_uniform = {
  483. .base = UNIFORM(my_uniform),
  484. .a = dist.param1,
  485. .b = dist.param2,
  486. };
  487. return dist_sample(&my_uniform.base);
  488. }
  489. case CIRCPAD_DIST_LOGISTIC:
  490. {
  491. /* param1 is Mu, param2 is sigma. */
  492. const struct logistic my_logistic = {
  493. .base = LOGISTIC(my_logistic),
  494. .mu = dist.param1,
  495. .sigma = dist.param2,
  496. };
  497. return dist_sample(&my_logistic.base);
  498. }
  499. case CIRCPAD_DIST_LOG_LOGISTIC:
  500. {
  501. /* param1 is Alpha, param2 is 1.0/Beta */
  502. const struct log_logistic my_log_logistic = {
  503. .base = LOG_LOGISTIC(my_log_logistic),
  504. .alpha = dist.param1,
  505. .beta = dist.param2,
  506. };
  507. return dist_sample(&my_log_logistic.base);
  508. }
  509. case CIRCPAD_DIST_GEOMETRIC:
  510. {
  511. /* param1 is 'p' (success probability) */
  512. const struct geometric my_geometric = {
  513. .base = GEOMETRIC(my_geometric),
  514. .p = dist.param1,
  515. };
  516. return dist_sample(&my_geometric.base);
  517. }
  518. case CIRCPAD_DIST_WEIBULL:
  519. {
  520. /* param1 is k, param2 is Lambda */
  521. const struct weibull my_weibull = {
  522. .base = WEIBULL(my_weibull),
  523. .k = dist.param1,
  524. .lambda = dist.param2,
  525. };
  526. return dist_sample(&my_weibull.base);
  527. }
  528. case CIRCPAD_DIST_PARETO:
  529. {
  530. /* param1 is sigma, param2 is xi, no more params for mu so we use 0 */
  531. const struct genpareto my_genpareto = {
  532. .base = GENPARETO(my_genpareto),
  533. .mu = 0,
  534. .sigma = dist.param1,
  535. .xi = dist.param2,
  536. };
  537. return dist_sample(&my_genpareto.base);
  538. }
  539. }
  540. tor_assert_nonfatal_unreached();
  541. return 0;
  542. }
  543. /**
  544. * Find the index of the first bin whose upper bound is
  545. * greater than the target, and that has tokens remaining.
  546. */
  547. static circpad_hist_index_t
  548. circpad_machine_first_higher_index(const circpad_machine_state_t *mi,
  549. circpad_delay_t target_bin_usec)
  550. {
  551. circpad_hist_index_t bin = circpad_histogram_usec_to_bin(mi,
  552. target_bin_usec);
  553. /* Don't remove from the infinity bin */
  554. for (; bin < CIRCPAD_INFINITY_BIN(mi); bin++) {
  555. if (mi->histogram[bin] &&
  556. circpad_histogram_bin_to_usec(mi, bin+1) > target_bin_usec) {
  557. return bin;
  558. }
  559. }
  560. return mi->histogram_len;
  561. }
  562. /**
  563. * Find the index of the first bin whose lower bound is lower or equal to
  564. * <b>target_bin_usec</b>, and that still has tokens remaining.
  565. */
  566. static circpad_hist_index_t
  567. circpad_machine_first_lower_index(const circpad_machine_state_t *mi,
  568. circpad_delay_t target_bin_usec)
  569. {
  570. circpad_hist_index_t bin = circpad_histogram_usec_to_bin(mi,
  571. target_bin_usec);
  572. for (; bin >= 0; bin--) {
  573. if (mi->histogram[bin] &&
  574. circpad_histogram_bin_to_usec(mi, bin) <= target_bin_usec) {
  575. return bin;
  576. }
  577. }
  578. return -1;
  579. }
  580. /**
  581. * Remove a token from the first non-empty bin whose upper bound is
  582. * greater than the target.
  583. */
  584. STATIC void
  585. circpad_machine_remove_higher_token(circpad_machine_state_t *mi,
  586. circpad_delay_t target_bin_usec)
  587. {
  588. /* We need to remove the token from the first bin
  589. * whose upper bound is greater than the target, and that
  590. * has tokens remaining. */
  591. circpad_hist_index_t bin = circpad_machine_first_higher_index(mi,
  592. target_bin_usec);
  593. if (bin >= 0 && bin < CIRCPAD_INFINITY_BIN(mi)) {
  594. if (!BUG(mi->histogram[bin] == 0)) {
  595. mi->histogram[bin]--;
  596. }
  597. }
  598. }
  599. /**
  600. * Remove a token from the first non-empty bin whose upper bound is
  601. * lower than the target.
  602. */
  603. STATIC void
  604. circpad_machine_remove_lower_token(circpad_machine_state_t *mi,
  605. circpad_delay_t target_bin_usec)
  606. {
  607. circpad_hist_index_t bin = circpad_machine_first_lower_index(mi,
  608. target_bin_usec);
  609. if (bin >= 0 && bin < CIRCPAD_INFINITY_BIN(mi)) {
  610. if (!BUG(mi->histogram[bin] == 0)) {
  611. mi->histogram[bin]--;
  612. }
  613. }
  614. }
  615. /* Helper macro: Ensure that the bin has tokens available, and BUG out of the
  616. * function if it's not the case. */
  617. #define ENSURE_BIN_CAPACITY(bin_index) \
  618. if (BUG(mi->histogram[bin_index] == 0)) { \
  619. return; \
  620. }
  621. /**
  622. * Remove a token from the closest non-empty bin to the target.
  623. *
  624. * If use_usec is true, measure "closest" in terms of the next closest bin
  625. * midpoint.
  626. *
  627. * If it is false, use bin index distance only.
  628. */
  629. STATIC void
  630. circpad_machine_remove_closest_token(circpad_machine_state_t *mi,
  631. circpad_delay_t target_bin_usec,
  632. bool use_usec)
  633. {
  634. circpad_hist_index_t lower, higher, current;
  635. circpad_hist_index_t bin_to_remove = -1;
  636. lower = circpad_machine_first_lower_index(mi, target_bin_usec);
  637. higher = circpad_machine_first_higher_index(mi, target_bin_usec);
  638. current = circpad_histogram_usec_to_bin(mi, target_bin_usec);
  639. /* Sanity check the results */
  640. if (BUG(lower > current) || BUG(higher < current)) {
  641. return;
  642. }
  643. /* Take care of edge cases first */
  644. if (higher == mi->histogram_len && lower == -1) {
  645. /* All bins are empty */
  646. return;
  647. } else if (higher == mi->histogram_len) {
  648. /* All higher bins are empty */
  649. ENSURE_BIN_CAPACITY(lower);
  650. mi->histogram[lower]--;
  651. return;
  652. } else if (lower == -1) {
  653. /* All lower bins are empty */
  654. ENSURE_BIN_CAPACITY(higher);
  655. mi->histogram[higher]--;
  656. return;
  657. }
  658. /* Now handle the intermediate cases */
  659. if (use_usec) {
  660. /* Find the closest bin midpoint to the target */
  661. circpad_delay_t lower_usec = circpad_get_histogram_bin_midpoint(mi, lower);
  662. circpad_delay_t higher_usec =
  663. circpad_get_histogram_bin_midpoint(mi, higher);
  664. if (target_bin_usec < lower_usec) {
  665. // Lower bin is closer
  666. ENSURE_BIN_CAPACITY(lower);
  667. bin_to_remove = lower;
  668. } else if (target_bin_usec > higher_usec) {
  669. // Higher bin is closer
  670. ENSURE_BIN_CAPACITY(higher);
  671. bin_to_remove = higher;
  672. } else if (target_bin_usec-lower_usec > higher_usec-target_bin_usec) {
  673. // Higher bin is closer
  674. ENSURE_BIN_CAPACITY(higher);
  675. bin_to_remove = higher;
  676. } else {
  677. // Lower bin is closer
  678. ENSURE_BIN_CAPACITY(lower);
  679. bin_to_remove = lower;
  680. }
  681. mi->histogram[bin_to_remove]--;
  682. log_debug(LD_GENERAL, "Removing token from bin %d", bin_to_remove);
  683. return;
  684. } else {
  685. if (current - lower > higher - current) {
  686. // Higher bin is closer
  687. ENSURE_BIN_CAPACITY(higher);
  688. mi->histogram[higher]--;
  689. return;
  690. } else {
  691. // Lower bin is closer
  692. ENSURE_BIN_CAPACITY(lower);
  693. mi->histogram[lower]--;
  694. return;
  695. }
  696. }
  697. }
  698. #undef ENSURE_BIN_CAPACITY
  699. /**
  700. * Remove a token from the exact bin corresponding to the target.
  701. *
  702. * If it is empty, do nothing.
  703. */
  704. static void
  705. circpad_machine_remove_exact(circpad_machine_state_t *mi,
  706. circpad_delay_t target_bin_usec)
  707. {
  708. circpad_hist_index_t bin = circpad_histogram_usec_to_bin(mi,
  709. target_bin_usec);
  710. if (mi->histogram[bin] > 0)
  711. mi->histogram[bin]--;
  712. }
  713. /**
  714. * Check our state's cell limit count and tokens.
  715. *
  716. * Returns 1 if either limits are hit and we decide to change states,
  717. * otherwise returns 0.
  718. */
  719. static circpad_decision_t
  720. check_machine_token_supply(circpad_machine_state_t *mi)
  721. {
  722. uint32_t histogram_total_tokens = 0;
  723. /* Check if bins empty. This requires summing up the current mutable
  724. * machineinfo histogram token total and checking if it is zero.
  725. * Machineinfo does not keep a running token count. We're assuming the
  726. * extra space is not worth this short loop iteration.
  727. *
  728. * We also do not count infinity bin in histogram totals.
  729. */
  730. if (mi->histogram_len && mi->histogram) {
  731. for (circpad_hist_index_t b = 0; b < CIRCPAD_INFINITY_BIN(mi); b++)
  732. histogram_total_tokens += mi->histogram[b];
  733. /* If we change state, we're done */
  734. if (histogram_total_tokens == 0) {
  735. if (circpad_internal_event_bins_empty(mi) == CIRCPAD_STATE_CHANGED)
  736. return CIRCPAD_STATE_CHANGED;
  737. }
  738. }
  739. if (mi->state_length == 0) {
  740. return circpad_internal_event_state_length_up(mi);
  741. }
  742. return CIRCPAD_STATE_UNCHANGED;
  743. }
  744. /**
  745. * Remove a token from the bin corresponding to the delta since
  746. * last packet. If that bin is empty, choose a token based on
  747. * the specified removal strategy in the state machine.
  748. *
  749. * This function also updates and checks rate limit and state
  750. * limit counters.
  751. *
  752. * Returns 1 if we transition states, 0 otherwise.
  753. */
  754. STATIC circpad_decision_t
  755. circpad_machine_remove_token(circpad_machine_state_t *mi)
  756. {
  757. const circpad_state_t *state = NULL;
  758. circpad_time_t current_time;
  759. circpad_delay_t target_bin_usec;
  760. /* Update non-padding counts for rate limiting: We scale at UINT16_MAX
  761. * because we only use this for a percentile limit of 2 sig figs, and
  762. * space is scare in the machineinfo struct. */
  763. mi->nonpadding_sent++;
  764. if (mi->nonpadding_sent == UINT16_MAX) {
  765. mi->padding_sent /= 2;
  766. mi->nonpadding_sent /= 2;
  767. }
  768. /* Dont remove any tokens if there was no padding scheduled */
  769. if (!mi->padding_scheduled_at_usec) {
  770. return CIRCPAD_STATE_UNCHANGED;
  771. }
  772. state = circpad_machine_current_state(mi);
  773. current_time = monotime_absolute_usec();
  774. /* If we have scheduled padding some time in the future, we want to see what
  775. bin we are in at the current time */
  776. target_bin_usec = (circpad_delay_t)
  777. MIN((current_time - mi->padding_scheduled_at_usec),
  778. CIRCPAD_DELAY_INFINITE-1);
  779. /* We are treating this non-padding cell as a padding cell, so we cancel
  780. padding timer, if present. */
  781. mi->padding_scheduled_at_usec = 0;
  782. if (mi->is_padding_timer_scheduled) {
  783. mi->is_padding_timer_scheduled = 0;
  784. timer_disable(mi->padding_timer);
  785. }
  786. /* If we are not in a padding state (like start or end), we're done */
  787. if (!state)
  788. return CIRCPAD_STATE_UNCHANGED;
  789. /* If we're enforcing a state length on non-padding packets,
  790. * decrement it */
  791. if (mi->state_length != CIRCPAD_STATE_LENGTH_INFINITE &&
  792. state->length_includes_nonpadding &&
  793. mi->state_length > 0) {
  794. mi->state_length--;
  795. }
  796. /* Perform the specified token removal strategy */
  797. switch (state->token_removal) {
  798. case CIRCPAD_TOKEN_REMOVAL_NONE:
  799. break;
  800. case CIRCPAD_TOKEN_REMOVAL_CLOSEST_USEC:
  801. circpad_machine_remove_closest_token(mi, target_bin_usec, 1);
  802. break;
  803. case CIRCPAD_TOKEN_REMOVAL_CLOSEST:
  804. circpad_machine_remove_closest_token(mi, target_bin_usec, 0);
  805. break;
  806. case CIRCPAD_TOKEN_REMOVAL_LOWER:
  807. circpad_machine_remove_lower_token(mi, target_bin_usec);
  808. break;
  809. case CIRCPAD_TOKEN_REMOVAL_HIGHER:
  810. circpad_machine_remove_higher_token(mi, target_bin_usec);
  811. break;
  812. case CIRCPAD_TOKEN_REMOVAL_EXACT:
  813. circpad_machine_remove_exact(mi, target_bin_usec);
  814. break;
  815. }
  816. /* Check our token and state length limits */
  817. return check_machine_token_supply(mi);
  818. }
  819. /**
  820. * Send a relay command with a relay cell payload on a circuit to
  821. * the particular hopnum.
  822. *
  823. * Hopnum starts at 1 (1=guard, 2=middle, 3=exit, etc).
  824. *
  825. * Payload may be null.
  826. *
  827. * Returns negative on error, 0 on success.
  828. */
  829. MOCK_IMPL(STATIC signed_error_t,
  830. circpad_send_command_to_hop,(origin_circuit_t *circ, uint8_t hopnum,
  831. uint8_t relay_command, const uint8_t *payload,
  832. ssize_t payload_len))
  833. {
  834. crypt_path_t *target_hop = circuit_get_cpath_hop(circ, hopnum);
  835. signed_error_t ret;
  836. /* Check that the cpath has the target hop */
  837. if (!target_hop) {
  838. log_fn(LOG_WARN, LD_BUG, "Padding circuit %u has %d hops, not %d",
  839. circ->global_identifier, circuit_get_cpath_len(circ), hopnum);
  840. return -1;
  841. }
  842. /* Check that the target hop is opened */
  843. if (target_hop->state != CPATH_STATE_OPEN) {
  844. log_fn(LOG_WARN,LD_CIRC,
  845. "Padding circuit %u has %d hops, not %d",
  846. circ->global_identifier,
  847. circuit_get_cpath_opened_len(circ), hopnum);
  848. return -1;
  849. }
  850. /* Send the drop command to the second hop */
  851. ret = relay_send_command_from_edge(0, TO_CIRCUIT(circ), relay_command,
  852. (const char*)payload, payload_len,
  853. target_hop);
  854. return ret;
  855. }
  856. /**
  857. * Callback helper to send a padding cell.
  858. *
  859. * This helper is called after our histogram-sampled delay period passes
  860. * without another packet being sent first. If a packet is sent before this
  861. * callback happens, it is canceled. So when we're called here, send padding
  862. * right away.
  863. *
  864. * If sending this padding cell forced us to transition states return
  865. * CIRCPAD_STATE_CHANGED. Otherwise return CIRCPAD_STATE_UNCHANGED.
  866. */
  867. circpad_decision_t
  868. circpad_send_padding_cell_for_callback(circpad_machine_state_t *mi)
  869. {
  870. circuit_t *circ = mi->on_circ;
  871. int machine_idx = mi->machine_index;
  872. mi->padding_scheduled_at_usec = 0;
  873. circpad_statenum_t state = mi->current_state;
  874. // Make sure circuit didn't close on us
  875. if (mi->on_circ->marked_for_close) {
  876. log_fn(LOG_INFO,LD_CIRC,
  877. "Padding callback on a circuit marked for close. Ignoring.");
  878. return CIRCPAD_STATE_CHANGED;
  879. }
  880. /* If it's a histogram, reduce the token count */
  881. if (mi->histogram && mi->histogram_len) {
  882. /* Basic sanity check on the histogram before removing anything */
  883. if (BUG(mi->chosen_bin >= mi->histogram_len) ||
  884. BUG(mi->histogram[mi->chosen_bin] == 0)) {
  885. return CIRCPAD_STATE_CHANGED;
  886. }
  887. mi->histogram[mi->chosen_bin]--;
  888. }
  889. /* If we have a valid state length bound, consider it */
  890. if (mi->state_length != CIRCPAD_STATE_LENGTH_INFINITE &&
  891. !BUG(mi->state_length <= 0)) {
  892. mi->state_length--;
  893. }
  894. /*
  895. * Update non-padding counts for rate limiting: We scale at UINT16_MAX
  896. * because we only use this for a percentile limit of 2 sig figs, and
  897. * space is scare in the machineinfo struct.
  898. */
  899. mi->padding_sent++;
  900. if (mi->padding_sent == UINT16_MAX) {
  901. mi->padding_sent /= 2;
  902. mi->nonpadding_sent /= 2;
  903. }
  904. circpad_global_padding_sent++;
  905. if (CIRCUIT_IS_ORIGIN(mi->on_circ)) {
  906. circpad_send_command_to_hop(TO_ORIGIN_CIRCUIT(mi->on_circ),
  907. CIRCPAD_GET_MACHINE(mi)->target_hopnum,
  908. RELAY_COMMAND_DROP, NULL, 0);
  909. log_fn(LOG_INFO,LD_CIRC, "Callback: Sending padding to origin circuit %u.",
  910. TO_ORIGIN_CIRCUIT(mi->on_circ)->global_identifier);
  911. } else {
  912. // If we're a non-origin circ, we can just send from here as if we're the
  913. // edge.
  914. if (TO_OR_CIRCUIT(circ)->p_chan_cells.n <= circpad_max_circ_queued_cells) {
  915. log_fn(LOG_INFO,LD_CIRC,
  916. "Callback: Sending padding to non-origin circuit.");
  917. relay_send_command_from_edge(0, mi->on_circ, RELAY_COMMAND_DROP, NULL,
  918. 0, NULL);
  919. } else {
  920. static ratelim_t cell_lim = RATELIM_INIT(600);
  921. log_fn_ratelim(&cell_lim,LOG_NOTICE,LD_CIRC,
  922. "Too many cells (%d) in circ queue to send padding.",
  923. TO_OR_CIRCUIT(circ)->p_chan_cells.n);
  924. }
  925. }
  926. rep_hist_padding_count_write(PADDING_TYPE_DROP);
  927. /* This is a padding cell sent from the client or from the middle node,
  928. * (because it's invoked from circuitpadding.c) */
  929. circpad_cell_event_padding_sent(circ);
  930. /* The circpad_cell_event_padding_sent() could cause us to transition.
  931. * Check that we still have a padding machineinfo, and then check our token
  932. * supply. */
  933. if (circ->padding_info[machine_idx] != NULL) {
  934. if (state != circ->padding_info[machine_idx]->current_state)
  935. return CIRCPAD_STATE_CHANGED;
  936. else
  937. return check_machine_token_supply(circ->padding_info[machine_idx]);
  938. } else {
  939. return CIRCPAD_STATE_CHANGED;
  940. }
  941. }
  942. /**
  943. * Tor-timer compatible callback that tells us to send a padding cell.
  944. *
  945. * Timers are associated with circpad_machine_state_t's. When the machineinfo
  946. * is freed on a circuit, the timers are cancelled. Since the lifetime
  947. * of machineinfo is always longer than the timers, handles are not
  948. * needed.
  949. */
  950. static void
  951. circpad_send_padding_callback(tor_timer_t *timer, void *args,
  952. const struct monotime_t *time)
  953. {
  954. circpad_machine_state_t *mi = ((circpad_machine_state_t*)args);
  955. (void)timer; (void)time;
  956. if (mi && mi->on_circ) {
  957. assert_circuit_ok(mi->on_circ);
  958. circpad_send_padding_cell_for_callback(mi);
  959. } else {
  960. // This shouldn't happen (represents a timer leak)
  961. log_fn(LOG_WARN,LD_CIRC,
  962. "Circuit closed while waiting for padding timer.");
  963. tor_fragile_assert();
  964. }
  965. // TODO-MP-AP: Unify this counter with channelpadding for rephist stats
  966. //total_timers_pending--;
  967. }
  968. /**
  969. * Cache our consensus parameters upon consensus update.
  970. */
  971. void
  972. circpad_new_consensus_params(const networkstatus_t *ns)
  973. {
  974. circpad_global_allowed_cells =
  975. networkstatus_get_param(ns, "circpad_global_allowed_cells",
  976. 0, 0, UINT16_MAX-1);
  977. circpad_global_max_padding_percent =
  978. networkstatus_get_param(ns, "circpad_global_max_padding_pct",
  979. 0, 0, 100);
  980. circpad_max_circ_queued_cells =
  981. networkstatus_get_param(ns, "circpad_max_circ_queued_cells",
  982. CIRCWINDOW_START_MAX, 0, 50*CIRCWINDOW_START_MAX);
  983. }
  984. /**
  985. * Check this machine against its padding limits, as well as global
  986. * consensus limits.
  987. *
  988. * We have two limits: a percent and a cell count. The cell count
  989. * limit must be reached before the percent is enforced (this is to
  990. * optionally allow very light padding of things like circuit setup
  991. * while there is no other traffic on the circuit).
  992. *
  993. * TODO: Don't apply limits to machines form torrc.
  994. *
  995. * Returns 1 if limits are set and we've hit them. Otherwise returns 0.
  996. */
  997. STATIC bool
  998. circpad_machine_reached_padding_limit(circpad_machine_state_t *mi)
  999. {
  1000. const circpad_machine_spec_t *machine = CIRCPAD_GET_MACHINE(mi);
  1001. /* If machine_padding_pct is non-zero, and we've sent more
  1002. * than the allowed count of padding cells, then check our
  1003. * percent limits for this machine. */
  1004. if (machine->max_padding_percent &&
  1005. mi->padding_sent >= machine->allowed_padding_count) {
  1006. uint32_t total_cells = mi->padding_sent + mi->nonpadding_sent;
  1007. /* Check the percent */
  1008. if ((100*(uint32_t)mi->padding_sent) / total_cells >
  1009. machine->max_padding_percent) {
  1010. return 1; // limit is reached. Stop.
  1011. }
  1012. }
  1013. /* If circpad_max_global_padding_pct is non-zero, and we've
  1014. * sent more than the global padding cell limit, then check our
  1015. * gloabl tor process percentage limit on padding. */
  1016. if (circpad_global_max_padding_percent &&
  1017. circpad_global_padding_sent >= circpad_global_allowed_cells) {
  1018. uint64_t total_cells = circpad_global_padding_sent +
  1019. circpad_global_nonpadding_sent;
  1020. /* Check the percent */
  1021. if ((100*circpad_global_padding_sent) / total_cells >
  1022. circpad_global_max_padding_percent) {
  1023. return 1; // global limit reached. Stop.
  1024. }
  1025. }
  1026. return 0; // All good!
  1027. }
  1028. /**
  1029. * Schedule the next padding time according to the machineinfo on a
  1030. * circuit.
  1031. *
  1032. * The histograms represent inter-packet-delay. Whenever you get an packet
  1033. * event you should be scheduling your next timer (after cancelling any old
  1034. * ones and updating tokens accordingly).
  1035. *
  1036. * Returns 1 if we decide to transition states (due to infinity bin),
  1037. * 0 otherwise.
  1038. */
  1039. MOCK_IMPL(circpad_decision_t,
  1040. circpad_machine_schedule_padding,(circpad_machine_state_t *mi))
  1041. {
  1042. circpad_delay_t in_usec = 0;
  1043. struct timeval timeout;
  1044. tor_assert(mi);
  1045. // Don't pad in end (but also don't cancel any previously
  1046. // scheduled padding either).
  1047. if (mi->current_state == CIRCPAD_STATE_END) {
  1048. log_fn(LOG_INFO, LD_CIRC, "Padding end state");
  1049. return CIRCPAD_STATE_UNCHANGED;
  1050. }
  1051. /* Check our padding limits */
  1052. if (circpad_machine_reached_padding_limit(mi)) {
  1053. if (CIRCUIT_IS_ORIGIN(mi->on_circ)) {
  1054. log_fn(LOG_INFO, LD_CIRC,
  1055. "Padding machine has reached padding limit on circuit %u",
  1056. TO_ORIGIN_CIRCUIT(mi->on_circ)->global_identifier);
  1057. } else {
  1058. log_fn(LOG_INFO, LD_CIRC,
  1059. "Padding machine has reached padding limit on circuit %"PRIu64
  1060. ", %d",
  1061. mi->on_circ->n_chan ? mi->on_circ->n_chan->global_identifier : 0,
  1062. mi->on_circ->n_circ_id);
  1063. }
  1064. return CIRCPAD_STATE_UNCHANGED;
  1065. }
  1066. if (mi->is_padding_timer_scheduled) {
  1067. /* Cancel current timer (if any) */
  1068. timer_disable(mi->padding_timer);
  1069. mi->is_padding_timer_scheduled = 0;
  1070. }
  1071. /* in_usec = in microseconds */
  1072. in_usec = circpad_machine_sample_delay(mi);
  1073. mi->padding_scheduled_at_usec = monotime_absolute_usec();
  1074. log_fn(LOG_INFO,LD_CIRC,"\tPadding in %u usec", in_usec);
  1075. // Don't schedule if we have infinite delay.
  1076. if (in_usec == CIRCPAD_DELAY_INFINITE) {
  1077. return circpad_internal_event_infinity(mi);
  1078. }
  1079. if (mi->state_length == 0) {
  1080. /* If we're at length 0, that means we hit 0 after sending
  1081. * a cell earlier, and emitted an event for it, but
  1082. * for whatever reason we did not decide to change states then.
  1083. * So maybe the machine is waiting for bins empty, or for an
  1084. * infinity event later? That would be a strange machine,
  1085. * but there's no reason to make it impossible. */
  1086. return CIRCPAD_STATE_UNCHANGED;
  1087. }
  1088. if (in_usec <= 0) {
  1089. return circpad_send_padding_cell_for_callback(mi);
  1090. }
  1091. timeout.tv_sec = in_usec/TOR_USEC_PER_SEC;
  1092. timeout.tv_usec = (in_usec%TOR_USEC_PER_SEC);
  1093. log_fn(LOG_INFO, LD_CIRC, "\tPadding in %u sec, %u usec",
  1094. (unsigned)timeout.tv_sec, (unsigned)timeout.tv_usec);
  1095. if (mi->padding_timer) {
  1096. timer_set_cb(mi->padding_timer, circpad_send_padding_callback, mi);
  1097. } else {
  1098. mi->padding_timer =
  1099. timer_new(circpad_send_padding_callback, mi);
  1100. }
  1101. timer_schedule(mi->padding_timer, &timeout);
  1102. mi->is_padding_timer_scheduled = 1;
  1103. // TODO-MP-AP: Unify with channelpadding counter
  1104. //rep_hist_padding_count_timers(++total_timers_pending);
  1105. return CIRCPAD_STATE_UNCHANGED;
  1106. }
  1107. /**
  1108. * If the machine transitioned to the END state, we need
  1109. * to check to see if it wants us to shut it down immediately.
  1110. * If it does, then we need to send the appropate negotation commands
  1111. * depending on which side it is.
  1112. *
  1113. * After this function is called, mi may point to freed memory. Do
  1114. * not access it.
  1115. */
  1116. static void
  1117. circpad_machine_spec_transitioned_to_end(circpad_machine_state_t *mi)
  1118. {
  1119. const circpad_machine_spec_t *machine = CIRCPAD_GET_MACHINE(mi);
  1120. /*
  1121. * We allow machines to shut down and delete themselves as opposed
  1122. * to just going back to START or waiting forever in END so that
  1123. * we can handle the case where this machine started while it was
  1124. * the only machine that matched conditions, but *since* then more
  1125. * "higher ranking" machines now match the conditions, and would
  1126. * be given a chance to take precidence over this one in
  1127. * circpad_add_matching_machines().
  1128. *
  1129. * Returning to START or waiting forever in END would not give those
  1130. * other machines a chance to be launched, where as shutting down
  1131. * here does.
  1132. */
  1133. if (machine->should_negotiate_end) {
  1134. circuit_t *on_circ = mi->on_circ;
  1135. if (machine->is_origin_side) {
  1136. /* We free the machine info here so that we can be replaced
  1137. * by a different machine. But we must leave the padding_machine
  1138. * in place to wait for the negotiated response */
  1139. circpad_circuit_machineinfo_free_idx(on_circ,
  1140. machine->machine_index);
  1141. circpad_negotiate_padding(TO_ORIGIN_CIRCUIT(on_circ),
  1142. machine->machine_num,
  1143. machine->target_hopnum,
  1144. CIRCPAD_COMMAND_STOP);
  1145. } else {
  1146. circpad_circuit_machineinfo_free_idx(on_circ,
  1147. machine->machine_index);
  1148. circpad_padding_negotiated(on_circ,
  1149. machine->machine_num,
  1150. CIRCPAD_COMMAND_STOP,
  1151. CIRCPAD_RESPONSE_OK);
  1152. on_circ->padding_machine[machine->machine_index] = NULL;
  1153. }
  1154. }
  1155. }
  1156. /**
  1157. * Generic state transition function for padding state machines.
  1158. *
  1159. * Given an event and our mutable machine info, decide if/how to
  1160. * transition to a different state, and perform actions accordingly.
  1161. *
  1162. * Returns 1 if we transition states, 0 otherwise.
  1163. */
  1164. MOCK_IMPL(circpad_decision_t,
  1165. circpad_machine_spec_transition,(circpad_machine_state_t *mi,
  1166. circpad_event_t event))
  1167. {
  1168. const circpad_state_t *state =
  1169. circpad_machine_current_state(mi);
  1170. /* If state is null we are in the end state. */
  1171. if (!state) {
  1172. /* If we in end state we don't pad no matter what. */
  1173. return CIRCPAD_STATE_UNCHANGED;
  1174. }
  1175. /* Check if this event is ignored or causes a cancel */
  1176. if (state->next_state[event] == CIRCPAD_STATE_IGNORE) {
  1177. return CIRCPAD_STATE_UNCHANGED;
  1178. } else if (state->next_state[event] == CIRCPAD_STATE_CANCEL) {
  1179. /* Check cancel events and cancel any pending padding */
  1180. mi->padding_scheduled_at_usec = 0;
  1181. if (mi->is_padding_timer_scheduled) {
  1182. mi->is_padding_timer_scheduled = 0;
  1183. /* Cancel current timer (if any) */
  1184. timer_disable(mi->padding_timer);
  1185. }
  1186. return CIRCPAD_STATE_UNCHANGED;
  1187. } else {
  1188. circpad_statenum_t s = state->next_state[event];
  1189. /* See if we need to transition to any other states based on this event.
  1190. * Whenever a transition happens, even to our own state, we schedule
  1191. * padding.
  1192. *
  1193. * So if a state only wants to schedule padding for an event, it specifies
  1194. * a transition to itself. All non-specified events are ignored.
  1195. */
  1196. log_fn(LOG_INFO, LD_CIRC,
  1197. "Circpad machine %d transitioning from %s to %s",
  1198. mi->machine_index, circpad_state_to_string(mi->current_state),
  1199. circpad_state_to_string(s));
  1200. /* If this is not the same state, switch and init tokens,
  1201. * otherwise just reschedule padding. */
  1202. if (mi->current_state != s) {
  1203. mi->current_state = s;
  1204. circpad_machine_setup_tokens(mi);
  1205. circpad_choose_state_length(mi);
  1206. /* If we transition to the end state, check to see
  1207. * if this machine wants to be shut down at end */
  1208. if (s == CIRCPAD_STATE_END) {
  1209. circpad_machine_spec_transitioned_to_end(mi);
  1210. /* We transitioned but we don't pad in end. Also, mi
  1211. * may be freed. Returning STATE_CHANGED prevents us
  1212. * from accessing it in any callers of this function. */
  1213. return CIRCPAD_STATE_CHANGED;
  1214. }
  1215. /* We transitioned to a new state, schedule padding */
  1216. circpad_machine_schedule_padding(mi);
  1217. return CIRCPAD_STATE_CHANGED;
  1218. }
  1219. /* We transitioned back to the same state. Schedule padding,
  1220. * and inform if that causes a state transition. */
  1221. return circpad_machine_schedule_padding(mi);
  1222. }
  1223. return CIRCPAD_STATE_UNCHANGED;
  1224. }
  1225. /**
  1226. * Estimate the circuit RTT from the current middle hop out to the
  1227. * end of the circuit.
  1228. *
  1229. * We estimate RTT by calculating the time between "receive" and
  1230. * "send" at a middle hop. This is because we "receive" a cell
  1231. * from the origin, and then relay it towards the exit before a
  1232. * response comes back. It is that response time from the exit side
  1233. * that we want to measure, so that we can make use of it for synthetic
  1234. * response delays.
  1235. */
  1236. static void
  1237. circpad_estimate_circ_rtt_on_received(circuit_t *circ,
  1238. circpad_machine_state_t *mi)
  1239. {
  1240. /* Origin circuits don't estimate RTT. They could do it easily enough,
  1241. * but they have no reason to use it in any delay calculations. */
  1242. if (CIRCUIT_IS_ORIGIN(circ) || mi->stop_rtt_update)
  1243. return;
  1244. /* If we already have a last receieved packet time, that means we
  1245. * did not get a response before this packet. The RTT estimate
  1246. * only makes sense if we do not have multiple packets on the
  1247. * wire, so stop estimating if this is the second packet
  1248. * back to back. However, for the first set of back-to-back
  1249. * packets, we can wait until the very first response comes back
  1250. * to us, to measure that RTT (for the response to optimistic
  1251. * data, for example). Hence stop_rtt_update is only checked
  1252. * in this received side function, and not in send side below.
  1253. */
  1254. if (mi->last_received_time_usec) {
  1255. /* We also allow multiple back-to-back packets if the circuit is not
  1256. * opened, to handle var cells.
  1257. * XXX: Will this work with out var cell plans? Maybe not,
  1258. * since we're opened at the middle hop as soon as we process
  1259. * one var extend2 :/ */
  1260. if (circ->state == CIRCUIT_STATE_OPEN) {
  1261. log_fn(LOG_INFO, LD_CIRC,
  1262. "Stopping padding RTT estimation on circuit (%"PRIu64
  1263. ", %d) after two back to back packets. Current RTT: %d",
  1264. circ->n_chan ? circ->n_chan->global_identifier : 0,
  1265. circ->n_circ_id, mi->rtt_estimate_usec);
  1266. mi->stop_rtt_update = 1;
  1267. }
  1268. } else {
  1269. mi->last_received_time_usec = monotime_absolute_usec();
  1270. }
  1271. }
  1272. /**
  1273. * Handles the "send" side of RTT calculation at middle nodes.
  1274. *
  1275. * This function calculates the RTT from the middle to the end
  1276. * of the circuit by subtracting the last received cell timestamp
  1277. * from the current time. It allows back-to-back cells until
  1278. * the circuit is opened, to allow for var cell handshakes.
  1279. * XXX: Check our var cell plans to make sure this will work.
  1280. */
  1281. static void
  1282. circpad_estimate_circ_rtt_on_send(circuit_t *circ,
  1283. circpad_machine_state_t *mi)
  1284. {
  1285. /* Origin circuits don't estimate RTT. They could do it easily enough,
  1286. * but they have no reason to use it in any delay calculations. */
  1287. if (CIRCUIT_IS_ORIGIN(circ))
  1288. return;
  1289. /* If last_received_time_usec is non-zero, we are waiting for a response
  1290. * from the exit side. Calculate the time delta and use it as RTT. */
  1291. if (mi->last_received_time_usec) {
  1292. circpad_time_t rtt_time = monotime_absolute_usec() -
  1293. mi->last_received_time_usec;
  1294. /* Reset the last RTT packet time, so we can tell if two cells
  1295. * arrive back to back */
  1296. mi->last_received_time_usec = 0;
  1297. /* Use INT32_MAX to ensure the addition doesn't overflow */
  1298. if (rtt_time >= INT32_MAX) {
  1299. log_fn(LOG_WARN,LD_CIRC,
  1300. "Circuit padding RTT estimate overflowed: %"PRIu64
  1301. " vs %"PRIu64, monotime_absolute_usec(),
  1302. mi->last_received_time_usec);
  1303. return;
  1304. }
  1305. /* If the old RTT estimate is lower than this one, use this one, because
  1306. * the circuit is getting longer. If this estimate is somehow
  1307. * faster than the previous, then maybe that was network jitter, or a
  1308. * bad monotonic clock source (so our ratchet returned a zero delta).
  1309. * In that case, average them. */
  1310. if (mi->rtt_estimate_usec < (circpad_delay_t)rtt_time) {
  1311. mi->rtt_estimate_usec = (circpad_delay_t)rtt_time;
  1312. } else {
  1313. mi->rtt_estimate_usec += (circpad_delay_t)rtt_time;
  1314. mi->rtt_estimate_usec /= 2;
  1315. }
  1316. } else if (circ->state == CIRCUIT_STATE_OPEN) {
  1317. /* If last_received_time_usec is zero, then we have gotten two cells back
  1318. * to back. Stop estimating RTT in this case. Note that we only
  1319. * stop RTT update if the circuit is opened, to allow for RTT estimates
  1320. * of var cells during circ setup. */
  1321. mi->stop_rtt_update = 1;
  1322. if (!mi->rtt_estimate_usec) {
  1323. log_fn(LOG_NOTICE, LD_CIRC,
  1324. "Got two cells back to back on a circuit before estimating RTT.");
  1325. }
  1326. }
  1327. }
  1328. /**
  1329. * A "non-padding" cell has been sent from this endpoint. React
  1330. * according to any padding state machines on the circuit.
  1331. *
  1332. * For origin circuits, this means we sent a cell into the network.
  1333. * For middle relay circuits, this means we sent a cell towards the
  1334. * origin.
  1335. */
  1336. void
  1337. circpad_cell_event_nonpadding_sent(circuit_t *on_circ)
  1338. {
  1339. /* Update global cell count */
  1340. circpad_global_nonpadding_sent++;
  1341. /* If there are no machines then this loop should not iterate */
  1342. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, on_circ) {
  1343. /* First, update any RTT estimate */
  1344. circpad_estimate_circ_rtt_on_send(on_circ, on_circ->padding_info[i]);
  1345. /* Remove a token: this is the idea of adaptive padding, since we have an
  1346. * ideal distribution that we want our distribution to look like. */
  1347. if (!circpad_machine_remove_token(on_circ->padding_info[i])) {
  1348. /* If removing a token did not cause a transition, check if
  1349. * non-padding sent event should */
  1350. circpad_machine_spec_transition(on_circ->padding_info[i],
  1351. CIRCPAD_EVENT_NONPADDING_SENT);
  1352. }
  1353. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1354. }
  1355. /**
  1356. * A "non-padding" cell has been received by this endpoint. React
  1357. * according to any padding state machines on the circuit.
  1358. *
  1359. * For origin circuits, this means we read a cell from the network.
  1360. * For middle relay circuits, this means we received a cell from the
  1361. * origin.
  1362. */
  1363. void
  1364. circpad_cell_event_nonpadding_received(circuit_t *on_circ)
  1365. {
  1366. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, on_circ) {
  1367. /* First, update any RTT estimate */
  1368. circpad_estimate_circ_rtt_on_received(on_circ, on_circ->padding_info[i]);
  1369. circpad_machine_spec_transition(on_circ->padding_info[i],
  1370. CIRCPAD_EVENT_NONPADDING_RECV);
  1371. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1372. }
  1373. /**
  1374. * A padding cell has been sent from this endpoint. React
  1375. * according to any padding state machines on the circuit.
  1376. *
  1377. * For origin circuits, this means we sent a cell into the network.
  1378. * For middle relay circuits, this means we sent a cell towards the
  1379. * origin.
  1380. */
  1381. void
  1382. circpad_cell_event_padding_sent(circuit_t *on_circ)
  1383. {
  1384. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, on_circ) {
  1385. circpad_machine_spec_transition(on_circ->padding_info[i],
  1386. CIRCPAD_EVENT_PADDING_SENT);
  1387. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1388. }
  1389. /**
  1390. * A padding cell has been received by this endpoint. React
  1391. * according to any padding state machines on the circuit.
  1392. *
  1393. * For origin circuits, this means we read a cell from the network.
  1394. * For middle relay circuits, this means we received a cell from the
  1395. * origin.
  1396. */
  1397. void
  1398. circpad_cell_event_padding_received(circuit_t *on_circ)
  1399. {
  1400. /* identical to padding sent */
  1401. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, on_circ) {
  1402. circpad_machine_spec_transition(on_circ->padding_info[i],
  1403. CIRCPAD_EVENT_PADDING_RECV);
  1404. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1405. }
  1406. /**
  1407. * An "infinite" delay has ben chosen from one of our histograms.
  1408. *
  1409. * "Infinite" delays mean don't send padding -- but they can also
  1410. * mean transition to another state depending on the state machine
  1411. * definitions. Check the rules and react accordingly.
  1412. *
  1413. * Return 1 if we decide to transition, 0 otherwise.
  1414. */
  1415. circpad_decision_t
  1416. circpad_internal_event_infinity(circpad_machine_state_t *mi)
  1417. {
  1418. return circpad_machine_spec_transition(mi, CIRCPAD_EVENT_INFINITY);
  1419. }
  1420. /**
  1421. * All of the bins of our current state's histogram's are empty.
  1422. *
  1423. * Check to see if this means transition to another state, and if
  1424. * not, refill the tokens.
  1425. *
  1426. * Return 1 if we decide to transition, 0 otherwise.
  1427. */
  1428. circpad_decision_t
  1429. circpad_internal_event_bins_empty(circpad_machine_state_t *mi)
  1430. {
  1431. if (circpad_machine_spec_transition(mi, CIRCPAD_EVENT_BINS_EMPTY)
  1432. == CIRCPAD_STATE_CHANGED) {
  1433. return CIRCPAD_STATE_CHANGED;
  1434. } else {
  1435. /* If we dont transition, then we refill the tokens */
  1436. circpad_machine_setup_tokens(mi);
  1437. return CIRCPAD_STATE_UNCHANGED;
  1438. }
  1439. }
  1440. /**
  1441. * This state has used up its cell count. Emit the event and
  1442. * see if we transition.
  1443. *
  1444. * Return 1 if we decide to transition, 0 otherwise.
  1445. */
  1446. circpad_decision_t
  1447. circpad_internal_event_state_length_up(circpad_machine_state_t *mi)
  1448. {
  1449. return circpad_machine_spec_transition(mi, CIRCPAD_EVENT_LENGTH_COUNT);
  1450. }
  1451. /**
  1452. * Returns true if the circuit matches the conditions.
  1453. */
  1454. static inline bool
  1455. circpad_machine_conditions_met(origin_circuit_t *circ,
  1456. const circpad_machine_spec_t *machine)
  1457. {
  1458. if (!(circpad_circ_purpose_to_mask(TO_CIRCUIT(circ)->purpose)
  1459. & machine->conditions.purpose_mask))
  1460. return 0;
  1461. if (machine->conditions.requires_vanguards) {
  1462. const or_options_t *options = get_options();
  1463. /* Pinned middles are effectively vanguards */
  1464. if (!(options->HSLayer2Nodes || options->HSLayer3Nodes))
  1465. return 0;
  1466. }
  1467. /* We check for any bits set in the circuit state mask so that machines
  1468. * can say any of the following through their state bitmask:
  1469. * "I want to apply to circuits with either streams or no streams"; OR
  1470. * "I only want to apply to circuits with streams"; OR
  1471. * "I only want to apply to circuits without streams". */
  1472. if (!(circpad_circuit_state(circ) & machine->conditions.state_mask))
  1473. return 0;
  1474. if (circuit_get_cpath_opened_len(circ) < machine->conditions.min_hops)
  1475. return 0;
  1476. return 1;
  1477. }
  1478. /**
  1479. * Returns a minimized representation of the circuit state.
  1480. *
  1481. * The padding code only cares if the circuit is building,
  1482. * opened, used for streams, and/or still has relay early cells.
  1483. * This returns a bitmask of all state properities that apply to
  1484. * this circuit.
  1485. */
  1486. static inline
  1487. circpad_circuit_state_t
  1488. circpad_circuit_state(origin_circuit_t *circ)
  1489. {
  1490. circpad_circuit_state_t retmask = 0;
  1491. if (circ->p_streams)
  1492. retmask |= CIRCPAD_CIRC_STREAMS;
  1493. else
  1494. retmask |= CIRCPAD_CIRC_NO_STREAMS;
  1495. /* We use has_opened to prevent cannibialized circs from flapping. */
  1496. if (circ->has_opened)
  1497. retmask |= CIRCPAD_CIRC_OPENED;
  1498. else
  1499. retmask |= CIRCPAD_CIRC_BUILDING;
  1500. if (circ->remaining_relay_early_cells > 0)
  1501. retmask |= CIRCPAD_CIRC_HAS_RELAY_EARLY;
  1502. else
  1503. retmask |= CIRCPAD_CIRC_HAS_NO_RELAY_EARLY;
  1504. return retmask;
  1505. }
  1506. /**
  1507. * Convert a normal circuit purpose into a bitmask that we can
  1508. * use for determining matching circuits.
  1509. */
  1510. static inline
  1511. circpad_purpose_mask_t
  1512. circpad_circ_purpose_to_mask(uint8_t circ_purpose)
  1513. {
  1514. /* Treat OR circ purposes as ignored. They should not be passed here*/
  1515. if (BUG(circ_purpose <= CIRCUIT_PURPOSE_OR_MAX_)) {
  1516. return 0;
  1517. }
  1518. /* Treat new client circuit purposes as "OMG ITS EVERYTHING".
  1519. * This also should not happen */
  1520. if (BUG(circ_purpose - CIRCUIT_PURPOSE_OR_MAX_ - 1 > 32)) {
  1521. return CIRCPAD_PURPOSE_ALL;
  1522. }
  1523. /* Convert the purpose to a bit position */
  1524. return 1 << (circ_purpose - CIRCUIT_PURPOSE_OR_MAX_ - 1);
  1525. }
  1526. /**
  1527. * Shut down any machines whose conditions no longer match
  1528. * the current circuit.
  1529. */
  1530. static void
  1531. circpad_shutdown_old_machines(origin_circuit_t *on_circ)
  1532. {
  1533. circuit_t *circ = TO_CIRCUIT(on_circ);
  1534. FOR_EACH_ACTIVE_CIRCUIT_MACHINE_BEGIN(i, circ) {
  1535. if (!circpad_machine_conditions_met(on_circ,
  1536. circ->padding_machine[i])) {
  1537. // Clear machineinfo (frees timers)
  1538. circpad_circuit_machineinfo_free_idx(circ, i);
  1539. // Send padding negotiate stop
  1540. circpad_negotiate_padding(on_circ,
  1541. circ->padding_machine[i]->machine_num,
  1542. circ->padding_machine[i]->target_hopnum,
  1543. CIRCPAD_COMMAND_STOP);
  1544. }
  1545. } FOR_EACH_ACTIVE_CIRCUIT_MACHINE_END;
  1546. }
  1547. /**
  1548. * Negotiate new machines that would apply to this circuit.
  1549. *
  1550. * This function checks to see if we have any free machine indexes,
  1551. * and for each free machine index, it initializes the most recently
  1552. * added origin-side padding machine that matches the target machine
  1553. * index and circuit conditions, and negotiates it with the appropriate
  1554. * middle relay.
  1555. */
  1556. static void
  1557. circpad_add_matching_machines(origin_circuit_t *on_circ)
  1558. {
  1559. circuit_t *circ = TO_CIRCUIT(on_circ);
  1560. #ifdef TOR_UNIT_TESTS
  1561. /* Tests don't have to init our padding machines */
  1562. if (!origin_padding_machines)
  1563. return;
  1564. #endif
  1565. /* If padding negotiation failed before, do not try again */
  1566. if (on_circ->padding_negotiation_failed)
  1567. return;
  1568. FOR_EACH_CIRCUIT_MACHINE_BEGIN(i) {
  1569. /* If there is a padding machine info, this index is occupied.
  1570. * No need to check conditions for this index. */
  1571. if (circ->padding_info[i])
  1572. continue;
  1573. /* We have a free machine index. Check the origin padding
  1574. * machines in reverse order, so that more recently added
  1575. * machines take priority over older ones. */
  1576. SMARTLIST_FOREACH_REVERSE_BEGIN(origin_padding_machines,
  1577. circpad_machine_spec_t *,
  1578. machine) {
  1579. /* Machine definitions have a specific target machine index.
  1580. * This is so event ordering is deterministic with respect
  1581. * to which machine gets events first when there are two
  1582. * machines installed on a circuit. Make sure we only
  1583. * add this machine if its target machine index is free. */
  1584. if (machine->machine_index == i &&
  1585. circpad_machine_conditions_met(on_circ, machine)) {
  1586. // We can only replace this machine if the target hopnum
  1587. // is the same, otherwise we'll get invalid data
  1588. if (circ->padding_machine[i]) {
  1589. if (circ->padding_machine[i]->target_hopnum !=
  1590. machine->target_hopnum)
  1591. continue;
  1592. /* Replace it. (Don't free - is global). */
  1593. circ->padding_machine[i] = NULL;
  1594. }
  1595. /* Set up the machine immediately so that the slot is occupied.
  1596. * We will tear it down on error return, or if there is an error
  1597. * response from the relay. */
  1598. circpad_setup_machine_on_circ(circ, machine);
  1599. if (circpad_negotiate_padding(on_circ, machine->machine_num,
  1600. machine->target_hopnum,
  1601. CIRCPAD_COMMAND_START) < 0) {
  1602. circpad_circuit_machineinfo_free_idx(circ, i);
  1603. circ->padding_machine[i] = NULL;
  1604. on_circ->padding_negotiation_failed = 1;
  1605. } else {
  1606. /* Success. Don't try any more machines */
  1607. return;
  1608. }
  1609. }
  1610. } SMARTLIST_FOREACH_END(machine);
  1611. } FOR_EACH_CIRCUIT_MACHINE_END;
  1612. }
  1613. /**
  1614. * Event that tells us we added a hop to an origin circuit.
  1615. *
  1616. * This event is used to decide if we should create a padding machine
  1617. * on a circuit.
  1618. */
  1619. void
  1620. circpad_machine_event_circ_added_hop(origin_circuit_t *on_circ)
  1621. {
  1622. /* Since our padding conditions do not specify a max_hops,
  1623. * all we can do is add machines here */
  1624. circpad_add_matching_machines(on_circ);
  1625. }
  1626. /**
  1627. * Event that tells us that an origin circuit is now built.
  1628. *
  1629. * Shut down any machines that only applied to un-built circuits.
  1630. * Activate any new ones.
  1631. */
  1632. void
  1633. circpad_machine_event_circ_built(origin_circuit_t *circ)
  1634. {
  1635. circpad_shutdown_old_machines(circ);
  1636. circpad_add_matching_machines(circ);
  1637. }
  1638. /**
  1639. * Circpad purpose changed event.
  1640. *
  1641. * Shut down any machines that don't apply to our circ purpose.
  1642. * Activate any new ones that do.
  1643. */
  1644. void
  1645. circpad_machine_event_circ_purpose_changed(origin_circuit_t *circ)
  1646. {
  1647. circpad_shutdown_old_machines(circ);
  1648. circpad_add_matching_machines(circ);
  1649. }
  1650. /**
  1651. * Event that tells us that an origin circuit is out of RELAY_EARLY
  1652. * cells.
  1653. *
  1654. * Shut down any machines that only applied to RELAY_EARLY circuits.
  1655. * Activate any new ones.
  1656. */
  1657. void
  1658. circpad_machine_event_circ_has_no_relay_early(origin_circuit_t *circ)
  1659. {
  1660. circpad_shutdown_old_machines(circ);
  1661. circpad_add_matching_machines(circ);
  1662. }
  1663. /**
  1664. * Streams attached event.
  1665. *
  1666. * Called from link_apconn_to_circ() and handle_hs_exit_conn()
  1667. *
  1668. * Shut down any machines that only applied to machines without
  1669. * streams. Activate any new ones.
  1670. */
  1671. void
  1672. circpad_machine_event_circ_has_streams(origin_circuit_t *circ)
  1673. {
  1674. circpad_shutdown_old_machines(circ);
  1675. circpad_add_matching_machines(circ);
  1676. }
  1677. /**
  1678. * Streams detached event.
  1679. *
  1680. * Called from circuit_detach_stream()
  1681. *
  1682. * Shut down any machines that only applied to machines without
  1683. * streams. Activate any new ones.
  1684. */
  1685. void
  1686. circpad_machine_event_circ_has_no_streams(origin_circuit_t *circ)
  1687. {
  1688. circpad_shutdown_old_machines(circ);
  1689. circpad_add_matching_machines(circ);
  1690. }
  1691. /**
  1692. * Verify that padding is coming from the expected hop.
  1693. *
  1694. * Returns true if from_hop matches the target hop from
  1695. * one of our padding machines.
  1696. *
  1697. * Returns false if we're not an origin circuit, or if from_hop
  1698. * does not match one of the padding machines.
  1699. */
  1700. bool
  1701. circpad_padding_is_from_expected_hop(circuit_t *circ,
  1702. crypt_path_t *from_hop)
  1703. {
  1704. crypt_path_t *target_hop = NULL;
  1705. if (!CIRCUIT_IS_ORIGIN(circ))
  1706. return 0;
  1707. FOR_EACH_CIRCUIT_MACHINE_BEGIN(i) {
  1708. /* We have to check padding_machine and not padding_info/active
  1709. * machines here because padding may arrive after we shut down a
  1710. * machine. The info is gone, but the padding_machine waits
  1711. * for the padding_negotiated response to come back. */
  1712. if (!circ->padding_machine[i])
  1713. continue;
  1714. target_hop = circuit_get_cpath_hop(TO_ORIGIN_CIRCUIT(circ),
  1715. circ->padding_machine[i]->target_hopnum);
  1716. if (target_hop == from_hop)
  1717. return 1;
  1718. } FOR_EACH_CIRCUIT_MACHINE_END;
  1719. return 0;
  1720. }
  1721. /**
  1722. * Deliver circpad events for an "unrecognized cell".
  1723. *
  1724. * Unrecognized cells are sent to relays and are forwarded
  1725. * onto the next hop of their circuits. Unrecognized cells
  1726. * are by definition not padding. We need to tell relay-side
  1727. * state machines that a non-padding cell was sent or received,
  1728. * depending on the direction, so they can update their histograms
  1729. * and decide to pad or not.
  1730. */
  1731. void
  1732. circpad_deliver_unrecognized_cell_events(circuit_t *circ,
  1733. cell_direction_t dir)
  1734. {
  1735. // We should never see unrecognized cells at origin.
  1736. // Our caller emits a warn when this happens.
  1737. if (CIRCUIT_IS_ORIGIN(circ)) {
  1738. return;
  1739. }
  1740. if (dir == CELL_DIRECTION_OUT) {
  1741. /* When direction is out (away from origin), then we received non-padding
  1742. cell coming from the origin to us. */
  1743. circpad_cell_event_nonpadding_received(circ);
  1744. } else if (dir == CELL_DIRECTION_IN) {
  1745. /* It's in and not origin, so the cell is going away from us.
  1746. * So we are relaying a non-padding cell towards the origin. */
  1747. circpad_cell_event_nonpadding_sent(circ);
  1748. }
  1749. }
  1750. /**
  1751. * Deliver circpad events for "recognized" relay cells.
  1752. *
  1753. * Recognized cells are destined for this hop, either client or middle.
  1754. * Check if this is a padding cell or not, and send the appropiate
  1755. * received event.
  1756. */
  1757. void
  1758. circpad_deliver_recognized_relay_cell_events(circuit_t *circ,
  1759. uint8_t relay_command,
  1760. crypt_path_t *layer_hint)
  1761. {
  1762. /* Padding negotiate cells are ignored by the state machines
  1763. * for simplicity. */
  1764. if (relay_command == RELAY_COMMAND_PADDING_NEGOTIATE ||
  1765. relay_command == RELAY_COMMAND_PADDING_NEGOTIATED) {
  1766. return;
  1767. }
  1768. if (relay_command == RELAY_COMMAND_DROP) {
  1769. rep_hist_padding_count_read(PADDING_TYPE_DROP);
  1770. if (CIRCUIT_IS_ORIGIN(circ)) {
  1771. if (circpad_padding_is_from_expected_hop(circ, layer_hint)) {
  1772. circuit_read_valid_data(TO_ORIGIN_CIRCUIT(circ), 0);
  1773. } else {
  1774. /* This is unexpected padding. Ignore it for now. */
  1775. return;
  1776. }
  1777. }
  1778. /* The cell should be recognized by now, which means that we are on the
  1779. destination, which means that we received a padding cell. We might be
  1780. the client or the Middle node, still, because leaky-pipe. */
  1781. circpad_cell_event_padding_received(circ);
  1782. log_fn(LOG_INFO, LD_CIRC, "Got padding cell on %s circuit %u.",
  1783. CIRCUIT_IS_ORIGIN(circ) ? "origin" : "non-origin",
  1784. CIRCUIT_IS_ORIGIN(circ) ?
  1785. TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0);
  1786. } else {
  1787. /* We received a non-padding cell on the edge */
  1788. circpad_cell_event_nonpadding_received(circ);
  1789. }
  1790. }
  1791. /**
  1792. * Deliver circpad events for relay cells sent from us.
  1793. *
  1794. * If this is a padding cell, update our padding stats
  1795. * and deliver the event. Otherwise just deliver the event.
  1796. */
  1797. void
  1798. circpad_deliver_sent_relay_cell_events(circuit_t *circ,
  1799. uint8_t relay_command)
  1800. {
  1801. /* Padding negotiate cells are ignored by the state machines
  1802. * for simplicity. */
  1803. if (relay_command == RELAY_COMMAND_PADDING_NEGOTIATE ||
  1804. relay_command == RELAY_COMMAND_PADDING_NEGOTIATED) {
  1805. return;
  1806. }
  1807. /* RELAY_COMMAND_DROP is the multi-hop (aka circuit-level) padding cell in
  1808. * tor. (CELL_PADDING is a channel-level padding cell, which is not relayed
  1809. * or processed here) */
  1810. if (relay_command == RELAY_COMMAND_DROP) {
  1811. /* Optimization: The event for RELAY_COMMAND_DROP is sent directly
  1812. * from circpad_send_padding_cell_for_callback(). This is to avoid
  1813. * putting a cell_t and a relay_header_t on the stack repeatedly
  1814. * if we decide to send a long train of padidng cells back-to-back
  1815. * with 0 delay. So we do nothing here. */
  1816. return;
  1817. } else {
  1818. /* This is a non-padding cell sent from the client or from
  1819. * this node. */
  1820. circpad_cell_event_nonpadding_sent(circ);
  1821. }
  1822. }
  1823. /**
  1824. * Initialize the states array for a circpad machine.
  1825. */
  1826. void
  1827. circpad_machine_states_init(circpad_machine_spec_t *machine,
  1828. circpad_statenum_t num_states)
  1829. {
  1830. if (BUG(num_states > CIRCPAD_MAX_MACHINE_STATES)) {
  1831. num_states = CIRCPAD_MAX_MACHINE_STATES;
  1832. }
  1833. machine->num_states = num_states;
  1834. machine->states = tor_malloc_zero(sizeof(circpad_state_t)*num_states);
  1835. /* Initialize the default next state for all events to
  1836. * "ignore" -- if events aren't specified, they are ignored. */
  1837. for (circpad_statenum_t s = 0; s < num_states; s++) {
  1838. for (int e = 0; e < CIRCPAD_NUM_EVENTS; e++) {
  1839. machine->states[s].next_state[e] = CIRCPAD_STATE_IGNORE;
  1840. }
  1841. }
  1842. }
  1843. static void
  1844. circpad_setup_machine_on_circ(circuit_t *on_circ,
  1845. const circpad_machine_spec_t *machine)
  1846. {
  1847. if (CIRCUIT_IS_ORIGIN(on_circ) && !machine->is_origin_side) {
  1848. log_fn(LOG_WARN, LD_BUG,
  1849. "Can't set up non-origin machine on origin circuit!");
  1850. return;
  1851. }
  1852. if (!CIRCUIT_IS_ORIGIN(on_circ) && machine->is_origin_side) {
  1853. log_fn(LOG_WARN, LD_BUG,
  1854. "Can't set up origin machine on non-origin circuit!");
  1855. return;
  1856. }
  1857. tor_assert_nonfatal(on_circ->padding_machine[machine->machine_index]
  1858. == NULL);
  1859. tor_assert_nonfatal(on_circ->padding_info[machine->machine_index] == NULL);
  1860. on_circ->padding_info[machine->machine_index] =
  1861. circpad_circuit_machineinfo_new(on_circ, machine->machine_index);
  1862. on_circ->padding_machine[machine->machine_index] = machine;
  1863. }
  1864. /* These padding machines are only used for tests pending #28634. */
  1865. #ifdef TOR_UNIT_TESTS
  1866. static void
  1867. circpad_circ_client_machine_init(void)
  1868. {
  1869. circpad_machine_spec_t *circ_client_machine
  1870. = tor_malloc_zero(sizeof(circpad_machine_spec_t));
  1871. // XXX: Better conditions for merge.. Or disable this machine in
  1872. // merge?
  1873. circ_client_machine->conditions.min_hops = 2;
  1874. circ_client_machine->conditions.state_mask =
  1875. CIRCPAD_CIRC_BUILDING|CIRCPAD_CIRC_OPENED|CIRCPAD_CIRC_HAS_RELAY_EARLY;
  1876. circ_client_machine->conditions.purpose_mask = CIRCPAD_PURPOSE_ALL;
  1877. circ_client_machine->target_hopnum = 2;
  1878. circ_client_machine->is_origin_side = 1;
  1879. /* Start, gap, burst */
  1880. circpad_machine_states_init(circ_client_machine, 3);
  1881. circ_client_machine->states[CIRCPAD_STATE_START].
  1882. next_state[CIRCPAD_EVENT_NONPADDING_RECV] = CIRCPAD_STATE_BURST;
  1883. circ_client_machine->states[CIRCPAD_STATE_BURST].
  1884. next_state[CIRCPAD_EVENT_NONPADDING_RECV] = CIRCPAD_STATE_BURST;
  1885. circ_client_machine->states[CIRCPAD_STATE_BURST].
  1886. next_state[CIRCPAD_EVENT_PADDING_RECV] = CIRCPAD_STATE_BURST;
  1887. /* If we are in burst state, and we send a non-padding cell, then we cancel
  1888. the timer for the next padding cell:
  1889. We dont want to send fake extends when actual extends are going on */
  1890. circ_client_machine->states[CIRCPAD_STATE_BURST].
  1891. next_state[CIRCPAD_EVENT_NONPADDING_SENT] = CIRCPAD_STATE_CANCEL;
  1892. circ_client_machine->states[CIRCPAD_STATE_BURST].
  1893. next_state[CIRCPAD_EVENT_BINS_EMPTY] = CIRCPAD_STATE_END;
  1894. circ_client_machine->states[CIRCPAD_STATE_BURST].token_removal =
  1895. CIRCPAD_TOKEN_REMOVAL_CLOSEST;
  1896. // FIXME: Tune this histogram
  1897. circ_client_machine->states[CIRCPAD_STATE_BURST].histogram_len = 2;
  1898. circ_client_machine->states[CIRCPAD_STATE_BURST].start_usec = 500;
  1899. circ_client_machine->states[CIRCPAD_STATE_BURST].range_usec = 1000000;
  1900. /* We have 5 tokens in the histogram, which means that all circuits will look
  1901. * like they have 7 hops (since we start this machine after the second hop,
  1902. * and tokens are decremented for any valid hops, and fake extends are
  1903. * used after that -- 2+5==7). */
  1904. circ_client_machine->states[CIRCPAD_STATE_BURST].histogram[0] = 5;
  1905. circ_client_machine->states[CIRCPAD_STATE_BURST].histogram_total_tokens = 5;
  1906. circ_client_machine->machine_num = smartlist_len(origin_padding_machines);
  1907. smartlist_add(origin_padding_machines, circ_client_machine);
  1908. }
  1909. static void
  1910. circpad_circ_responder_machine_init(void)
  1911. {
  1912. circpad_machine_spec_t *circ_responder_machine
  1913. = tor_malloc_zero(sizeof(circpad_machine_spec_t));
  1914. /* Shut down the machine after we've sent enough packets */
  1915. circ_responder_machine->should_negotiate_end = 1;
  1916. /* The relay-side doesn't care what hopnum it is, but for consistency,
  1917. * let's match the client */
  1918. circ_responder_machine->target_hopnum = 2;
  1919. circ_responder_machine->is_origin_side = 0;
  1920. /* Start, gap, burst */
  1921. circpad_machine_states_init(circ_responder_machine, 3);
  1922. /* This is the settings of the state machine. In the future we are gonna
  1923. serialize this into the consensus or the torrc */
  1924. /* We transition to the burst state on padding receive and on non-padding
  1925. * recieve */
  1926. circ_responder_machine->states[CIRCPAD_STATE_START].
  1927. next_state[CIRCPAD_EVENT_PADDING_RECV] = CIRCPAD_STATE_BURST;
  1928. circ_responder_machine->states[CIRCPAD_STATE_START].
  1929. next_state[CIRCPAD_EVENT_NONPADDING_RECV] = CIRCPAD_STATE_BURST;
  1930. /* Inside the burst state we _stay_ in the burst state when a non-padding
  1931. * is sent */
  1932. circ_responder_machine->states[CIRCPAD_STATE_BURST].
  1933. next_state[CIRCPAD_EVENT_NONPADDING_SENT] = CIRCPAD_STATE_BURST;
  1934. /* Inside the burst state we transition to the gap state when we receive a
  1935. * padding cell */
  1936. circ_responder_machine->states[CIRCPAD_STATE_BURST].
  1937. next_state[CIRCPAD_EVENT_PADDING_RECV] = CIRCPAD_STATE_GAP;
  1938. /* These describe the padding charasteristics when in burst state */
  1939. /* use_rtt_estimate tries to estimate how long padding cells take to go from
  1940. C->M, and uses that as what as the base of the histogram */
  1941. circ_responder_machine->states[CIRCPAD_STATE_BURST].use_rtt_estimate = 1;
  1942. /* The histogram is 2 bins: an empty one, and infinity */
  1943. circ_responder_machine->states[CIRCPAD_STATE_BURST].histogram_len = 2;
  1944. circ_responder_machine->states[CIRCPAD_STATE_BURST].start_usec = 5000;
  1945. circ_responder_machine->states[CIRCPAD_STATE_BURST].range_usec = 1000000;
  1946. /* During burst state we wait forever for padding to arrive.
  1947. We are waiting for a padding cell from the client to come in, so that we
  1948. respond, and we immitate how extend looks like */
  1949. circ_responder_machine->states[CIRCPAD_STATE_BURST].histogram[0] = 0;
  1950. // Only infinity bin:
  1951. circ_responder_machine->states[CIRCPAD_STATE_BURST].histogram[1] = 1;
  1952. circ_responder_machine->states[CIRCPAD_STATE_BURST].
  1953. histogram_total_tokens = 1;
  1954. /* From the gap state, we _stay_ in the gap state, when we receive padding
  1955. * or non padding */
  1956. circ_responder_machine->states[CIRCPAD_STATE_GAP].
  1957. next_state[CIRCPAD_EVENT_PADDING_RECV] = CIRCPAD_STATE_GAP;
  1958. circ_responder_machine->states[CIRCPAD_STATE_GAP].
  1959. next_state[CIRCPAD_EVENT_NONPADDING_RECV] = CIRCPAD_STATE_GAP;
  1960. /* And from the gap state, we go to the end, when the bins are empty or a
  1961. * non-padding cell is sent */
  1962. circ_responder_machine->states[CIRCPAD_STATE_GAP].
  1963. next_state[CIRCPAD_EVENT_BINS_EMPTY] = CIRCPAD_STATE_END;
  1964. circ_responder_machine->states[CIRCPAD_STATE_GAP].
  1965. next_state[CIRCPAD_EVENT_NONPADDING_SENT] = CIRCPAD_STATE_END;
  1966. // FIXME: Tune this histogram
  1967. /* The gap state is the delay you wait after you receive a padding cell
  1968. before you send a padding response */
  1969. circ_responder_machine->states[CIRCPAD_STATE_GAP].use_rtt_estimate = 1;
  1970. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram_len = 6;
  1971. circ_responder_machine->states[CIRCPAD_STATE_GAP].start_usec = 5000;
  1972. circ_responder_machine->states[CIRCPAD_STATE_GAP].range_usec = 1000000;
  1973. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[0] = 0;
  1974. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[1] = 1;
  1975. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[2] = 2;
  1976. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[3] = 2;
  1977. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram[4] = 1;
  1978. /* Total number of tokens */
  1979. circ_responder_machine->states[CIRCPAD_STATE_GAP].histogram_total_tokens = 6;
  1980. circ_responder_machine->states[CIRCPAD_STATE_GAP].token_removal =
  1981. CIRCPAD_TOKEN_REMOVAL_CLOSEST_USEC;
  1982. circ_responder_machine->machine_num = smartlist_len(relay_padding_machines);
  1983. smartlist_add(relay_padding_machines, circ_responder_machine);
  1984. }
  1985. #endif
  1986. /**
  1987. * Initialize all of our padding machines.
  1988. *
  1989. * This is called at startup. It sets up some global machines, and then
  1990. * loads some from torrc, and from the tor consensus.
  1991. */
  1992. void
  1993. circpad_machines_init(void)
  1994. {
  1995. tor_assert_nonfatal(origin_padding_machines == NULL);
  1996. tor_assert_nonfatal(relay_padding_machines == NULL);
  1997. origin_padding_machines = smartlist_new();
  1998. relay_padding_machines = smartlist_new();
  1999. // TODO: Parse machines from consensus and torrc
  2000. #ifdef TOR_UNIT_TESTS
  2001. circpad_circ_client_machine_init();
  2002. circpad_circ_responder_machine_init();
  2003. #endif
  2004. }
  2005. /**
  2006. * Free our padding machines
  2007. */
  2008. void
  2009. circpad_machines_free(void)
  2010. {
  2011. if (origin_padding_machines) {
  2012. SMARTLIST_FOREACH(origin_padding_machines,
  2013. circpad_machine_spec_t *,
  2014. m, tor_free(m->states); tor_free(m));
  2015. smartlist_free(origin_padding_machines);
  2016. }
  2017. if (relay_padding_machines) {
  2018. SMARTLIST_FOREACH(relay_padding_machines,
  2019. circpad_machine_spec_t *,
  2020. m, tor_free(m->states); tor_free(m));
  2021. smartlist_free(relay_padding_machines);
  2022. }
  2023. }
  2024. /**
  2025. * Check the Protover info to see if a node supports padding.
  2026. */
  2027. static bool
  2028. circpad_node_supports_padding(const node_t *node)
  2029. {
  2030. if (node->rs) {
  2031. log_fn(LOG_INFO, LD_CIRC, "Checking padding: %s",
  2032. node->rs->pv.supports_padding ? "supported" : "unsupported");
  2033. return node->rs->pv.supports_padding;
  2034. }
  2035. log_fn(LOG_INFO, LD_CIRC, "Empty routerstatus in padding check");
  2036. return 0;
  2037. }
  2038. /**
  2039. * Get a node_t for the nth hop in our circuit, starting from 1.
  2040. *
  2041. * Returns node_t from the consensus for that hop, if it is opened.
  2042. * Otherwise returns NULL.
  2043. */
  2044. static const node_t *
  2045. circuit_get_nth_node(origin_circuit_t *circ, int hop)
  2046. {
  2047. crypt_path_t *iter = circuit_get_cpath_hop(circ, hop);
  2048. if (!iter || iter->state != CPATH_STATE_OPEN)
  2049. return NULL;
  2050. return node_get_by_id(iter->extend_info->identity_digest);
  2051. }
  2052. /**
  2053. * Return true if a particular circuit supports padding
  2054. * at the desired hop.
  2055. */
  2056. static bool
  2057. circpad_circuit_supports_padding(origin_circuit_t *circ,
  2058. int target_hopnum)
  2059. {
  2060. const node_t *hop;
  2061. if (!(hop = circuit_get_nth_node(circ, target_hopnum))) {
  2062. return 0;
  2063. }
  2064. return circpad_node_supports_padding(hop);
  2065. }
  2066. /**
  2067. * Try to negotiate padding.
  2068. *
  2069. * Returns -1 on error, 0 on success.
  2070. */
  2071. signed_error_t
  2072. circpad_negotiate_padding(origin_circuit_t *circ,
  2073. circpad_machine_num_t machine,
  2074. uint8_t target_hopnum,
  2075. uint8_t command)
  2076. {
  2077. circpad_negotiate_t type;
  2078. cell_t cell;
  2079. ssize_t len;
  2080. /* Check that the target hop lists support for padding in
  2081. * its ProtoVer fields */
  2082. if (!circpad_circuit_supports_padding(circ, target_hopnum)) {
  2083. return -1;
  2084. }
  2085. memset(&cell, 0, sizeof(cell_t));
  2086. memset(&type, 0, sizeof(circpad_negotiate_t));
  2087. // This gets reset to RELAY_EARLY appropriately by
  2088. // relay_send_command_from_edge_. At least, it looks that way.
  2089. // QQQ-MP-AP: Verify that.
  2090. cell.command = CELL_RELAY;
  2091. circpad_negotiate_set_command(&type, command);
  2092. circpad_negotiate_set_version(&type, 0);
  2093. circpad_negotiate_set_machine_type(&type, machine);
  2094. if ((len = circpad_negotiate_encode(cell.payload, CELL_PAYLOAD_SIZE,
  2095. &type)) < 0)
  2096. return -1;
  2097. log_fn(LOG_INFO,LD_CIRC, "Negotiating padding on circuit %u",
  2098. circ->global_identifier);
  2099. return circpad_send_command_to_hop(circ, target_hopnum,
  2100. RELAY_COMMAND_PADDING_NEGOTIATE,
  2101. cell.payload, len);
  2102. }
  2103. /**
  2104. * Try to negotiate padding.
  2105. *
  2106. * Returns 1 if successful (or already set up), 0 otherwise.
  2107. */
  2108. bool
  2109. circpad_padding_negotiated(circuit_t *circ,
  2110. circpad_machine_num_t machine,
  2111. uint8_t command,
  2112. uint8_t response)
  2113. {
  2114. circpad_negotiated_t type;
  2115. cell_t cell;
  2116. ssize_t len;
  2117. memset(&cell, 0, sizeof(cell_t));
  2118. memset(&type, 0, sizeof(circpad_negotiated_t));
  2119. // This gets reset to RELAY_EARLY appropriately by
  2120. // relay_send_command_from_edge_. At least, it looks that way.
  2121. // QQQ-MP-AP: Verify that.
  2122. cell.command = CELL_RELAY;
  2123. circpad_negotiated_set_command(&type, command);
  2124. circpad_negotiated_set_response(&type, response);
  2125. circpad_negotiated_set_version(&type, 0);
  2126. circpad_negotiated_set_machine_type(&type, machine);
  2127. if ((len = circpad_negotiated_encode(cell.payload, CELL_PAYLOAD_SIZE,
  2128. &type)) < 0)
  2129. return 0;
  2130. /* Use relay_send because we're from the middle to the origin. We don't
  2131. * need to specify a target hop or layer_hint. */
  2132. return relay_send_command_from_edge(0, circ,
  2133. RELAY_COMMAND_PADDING_NEGOTIATED,
  2134. (void*)cell.payload,
  2135. (size_t)len, NULL) == 0;
  2136. }
  2137. /**
  2138. * Parse and react to a padding_negotiate cell.
  2139. *
  2140. * This is called at the middle node upon receipt of the client's choice of
  2141. * state machine, so that it can use the requested state machine index, if
  2142. * it is available.
  2143. *
  2144. * Returns -1 on error, 0 on success.
  2145. */
  2146. signed_error_t
  2147. circpad_handle_padding_negotiate(circuit_t *circ, cell_t *cell)
  2148. {
  2149. int retval = 0;
  2150. circpad_negotiate_t *negotiate;
  2151. if (CIRCUIT_IS_ORIGIN(circ)) {
  2152. log_fn(LOG_WARN, LD_PROTOCOL,
  2153. "Padding negotiate cell unsupported at origin.");
  2154. return -1;
  2155. }
  2156. if (circpad_negotiate_parse(&negotiate, cell->payload+RELAY_HEADER_SIZE,
  2157. CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE) < 0) {
  2158. log_fn(LOG_WARN, LD_CIRC,
  2159. "Received malformed PADDING_NEGOTIATE cell; dropping.");
  2160. return -1;
  2161. }
  2162. if (negotiate->command == CIRCPAD_COMMAND_STOP) {
  2163. /* Free the machine corresponding to this machine type */
  2164. free_circ_machineinfos_with_machine_num(circ, negotiate->machine_type);
  2165. log_fn(LOG_WARN, LD_CIRC,
  2166. "Received circuit padding stop command for unknown machine.");
  2167. goto err;
  2168. } else if (negotiate->command == CIRCPAD_COMMAND_START) {
  2169. SMARTLIST_FOREACH_BEGIN(relay_padding_machines,
  2170. const circpad_machine_spec_t *, m) {
  2171. if (m->machine_num == negotiate->machine_type) {
  2172. circpad_setup_machine_on_circ(circ, m);
  2173. goto done;
  2174. }
  2175. } SMARTLIST_FOREACH_END(m);
  2176. }
  2177. err:
  2178. retval = -1;
  2179. done:
  2180. circpad_padding_negotiated(circ, negotiate->machine_type,
  2181. negotiate->command,
  2182. (retval == 0) ? CIRCPAD_RESPONSE_OK : CIRCPAD_RESPONSE_ERR);
  2183. circpad_negotiate_free(negotiate);
  2184. return retval;
  2185. }
  2186. /**
  2187. * Parse and react to a padding_negotiated cell.
  2188. *
  2189. * This is called at the origin upon receipt of the middle's response
  2190. * to our choice of state machine.
  2191. *
  2192. * Returns -1 on error, 0 on success.
  2193. */
  2194. signed_error_t
  2195. circpad_handle_padding_negotiated(circuit_t *circ, cell_t *cell,
  2196. crypt_path_t *layer_hint)
  2197. {
  2198. circpad_negotiated_t *negotiated;
  2199. if (!CIRCUIT_IS_ORIGIN(circ)) {
  2200. log_fn(LOG_WARN, LD_PROTOCOL,
  2201. "Padding negotiated cell unsupported at non-origin.");
  2202. return -1;
  2203. }
  2204. /* Verify this came from the expected hop */
  2205. if (!circpad_padding_is_from_expected_hop(circ, layer_hint)) {
  2206. log_fn(LOG_WARN, LD_PROTOCOL,
  2207. "Padding negotiated cell from wrong hop!");
  2208. return -1;
  2209. }
  2210. if (circpad_negotiated_parse(&negotiated, cell->payload+RELAY_HEADER_SIZE,
  2211. CELL_PAYLOAD_SIZE-RELAY_HEADER_SIZE) < 0) {
  2212. log_fn(LOG_WARN, LD_CIRC,
  2213. "Received malformed PADDING_NEGOTIATED cell; "
  2214. "dropping.");
  2215. return -1;
  2216. }
  2217. if (negotiated->command == CIRCPAD_COMMAND_STOP) {
  2218. /* There may not be a padding_info here if we shut down the
  2219. * machine in circpad_shutdown_old_machines(). Or, if
  2220. * circpad_add_matching_matchines() added a new machine,
  2221. * there may be a padding_machine for a different machine num
  2222. * than this response. */
  2223. free_circ_machineinfos_with_machine_num(circ, negotiated->machine_type);
  2224. } else if (negotiated->command == CIRCPAD_COMMAND_START &&
  2225. negotiated->response == CIRCPAD_RESPONSE_ERR) {
  2226. // This can happen due to consensus drift.. free the machines
  2227. // and be sad
  2228. free_circ_machineinfos_with_machine_num(circ, negotiated->machine_type);
  2229. TO_ORIGIN_CIRCUIT(circ)->padding_negotiation_failed = 1;
  2230. log_fn(LOG_INFO, LD_CIRC,
  2231. "Middle node did not accept our padding request.");
  2232. }
  2233. circpad_negotiated_free(negotiated);
  2234. return 0;
  2235. }
  2236. /* Serialization */
  2237. // TODO: Should we use keyword=value here? Are there helpers for that?
  2238. #if 0
  2239. static void
  2240. circpad_state_serialize(const circpad_state_t *state,
  2241. smartlist_t *chunks)
  2242. {
  2243. smartlist_add_asprintf(chunks, " %u", state->histogram[0]);
  2244. for (int i = 1; i < state->histogram_len; i++) {
  2245. smartlist_add_asprintf(chunks, ",%u",
  2246. state->histogram[i]);
  2247. }
  2248. smartlist_add_asprintf(chunks, " 0x%x",
  2249. state->transition_cancel_events);
  2250. for (int i = 0; i < CIRCPAD_NUM_STATES; i++) {
  2251. smartlist_add_asprintf(chunks, ",0x%x",
  2252. state->transition_events[i]);
  2253. }
  2254. smartlist_add_asprintf(chunks, " %u %u",
  2255. state->use_rtt_estimate,
  2256. state->token_removal);
  2257. }
  2258. char *
  2259. circpad_machine_spec_to_string(const circpad_machine_spec_t *machine)
  2260. {
  2261. smartlist_t *chunks = smartlist_new();
  2262. char *out;
  2263. (void)machine;
  2264. circpad_state_serialize(&machine->start, chunks);
  2265. circpad_state_serialize(&machine->gap, chunks);
  2266. circpad_state_serialize(&machine->burst, chunks);
  2267. out = smartlist_join_strings(chunks, "", 0, NULL);
  2268. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  2269. smartlist_free(chunks);
  2270. return out;
  2271. }
  2272. // XXX: Writeme
  2273. const circpad_machine_spec_t *
  2274. circpad_string_to_machine(const char *str)
  2275. {
  2276. (void)str;
  2277. return NULL;
  2278. }
  2279. #endif