circuitpadding.c 87 KB

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