circuitpadding.c 104 KB

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