circuitpadding.c 84 KB

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