circuitpadding.c 102 KB

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