circuitpadding.c 85 KB

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