circuitpadding.c 84 KB

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