circuitpadding.c 100 KB

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