circuitpadding.c 83 KB

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