trafficRules.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "encoding/json"
  22. "errors"
  23. "fmt"
  24. "net"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  26. )
  27. const (
  28. DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS = 30000
  29. DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS = 30000
  30. DEFAULT_DIAL_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS = 10000
  31. DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT = 64
  32. DEFAULT_MAX_TCP_PORT_FORWARD_COUNT = 512
  33. DEFAULT_MAX_UDP_PORT_FORWARD_COUNT = 32
  34. DEFAULT_MEEK_RATE_LIMITER_GARBAGE_COLLECTOR_TRIGGER_COUNT = 5000
  35. DEFAULT_MEEK_RATE_LIMITER_REAP_HISTORY_FREQUENCY_SECONDS = 600
  36. )
  37. // TrafficRulesSet represents the various traffic rules to
  38. // apply to Psiphon client tunnels. The Reload function supports
  39. // hot reloading of rules data while the server is running.
  40. //
  41. // For a given client, the traffic rules are determined by starting
  42. // with DefaultRules, then finding the first (if any)
  43. // FilteredTrafficRules match and overriding the defaults with fields
  44. // set in the selected FilteredTrafficRules.
  45. type TrafficRulesSet struct {
  46. common.ReloadableFile
  47. // DefaultRules are the base values to use as defaults for all
  48. // clients.
  49. DefaultRules TrafficRules
  50. // FilteredTrafficRules is an ordered list of filter/rules pairs.
  51. // For each client, the first matching Filter in FilteredTrafficRules
  52. // determines the additional Rules that are selected and applied
  53. // on top of DefaultRules.
  54. FilteredRules []struct {
  55. Filter TrafficRulesFilter
  56. Rules TrafficRules
  57. }
  58. // MeekRateLimiterHistorySize enables the late-stage meek rate limiter and
  59. // sets its history size. The late-stage meek rate limiter acts on client
  60. // IPs relayed in MeekProxyForwardedForHeaders, and so it must wait for
  61. // the HTTP headers to be read. This rate limiter immediately terminates
  62. // any client endpoint request or any request to create a new session, but
  63. // not any meek request for an existing session, if the
  64. // MeekRateLimiterHistorySize requests occur in
  65. // MeekRateLimiterThresholdSeconds. The scope of rate limiting may be
  66. // limited using LimitMeekRateLimiterRegions.
  67. //
  68. // Hot reloading a new history size will result in existing history being
  69. // truncated.
  70. MeekRateLimiterHistorySize int
  71. // MeekRateLimiterThresholdSeconds is part of the meek rate limiter
  72. // specification and must be set when MeekRateLimiterHistorySize is set.
  73. MeekRateLimiterThresholdSeconds int
  74. // MeekRateLimiterRegions, if set, limits application of the meek
  75. // late-stage rate limiter to clients in the specified list of GeoIP
  76. // countries. When omitted or empty, meek rate limiting, if configured,
  77. // is applied to all clients.
  78. MeekRateLimiterRegions []string
  79. // MeekRateLimiterGarbageCollectionTriggerCount specifies the number of
  80. // rate limit events after which garbage collection is manually triggered
  81. // in order to reclaim memory used by rate limited and other rejected
  82. // requests.
  83. // A default of 5000 is used when
  84. // MeekRateLimiterGarbageCollectionTriggerCount is 0.
  85. MeekRateLimiterGarbageCollectionTriggerCount int
  86. // MeekRateLimiterReapHistoryFrequencySeconds specifies a schedule for
  87. // reaping old records from the rate limit history.
  88. // A default of 600 is used when
  89. // MeekRateLimiterReapHistoryFrequencySeconds is 0.
  90. MeekRateLimiterReapHistoryFrequencySeconds int
  91. }
  92. // TrafficRulesFilter defines a filter to match against client attributes.
  93. type TrafficRulesFilter struct {
  94. // TunnelProtocols is a list of client tunnel protocols that must be
  95. // in use to match this filter. When omitted or empty, any protocol
  96. // matches.
  97. TunnelProtocols []string
  98. // Regions is a list of client GeoIP countries that the client must
  99. // reolve to to match this filter. When omitted or empty, any client
  100. // region matches.
  101. Regions []string
  102. // APIProtocol specifies whether the client must use the SSH
  103. // API protocol (when "ssh") or the web API protocol (when "web").
  104. // When omitted or blank, any API protocol matches.
  105. APIProtocol string
  106. // HandshakeParameters specifies handshake API parameter names and
  107. // a list of values, one of which must be specified to match this
  108. // filter. Only scalar string API parameters may be filtered.
  109. // Values may be patterns containing the '*' wildcard.
  110. HandshakeParameters map[string][]string
  111. // AuthorizedAccessTypes specifies a list of access types, at least
  112. // one of which the client must have presented an active authorization
  113. // for and which must not be revoked.
  114. // AuthorizedAccessTypes is ignored when AuthorizationsRevoked is true.
  115. AuthorizedAccessTypes []string
  116. // AuthorizationsRevoked indicates whether the client's authorizations
  117. // must have been revoked. When true, authorizations must have been
  118. // revoked. When omitted or false, this field is ignored.
  119. AuthorizationsRevoked bool
  120. }
  121. // TrafficRules specify the limits placed on client traffic.
  122. type TrafficRules struct {
  123. // RateLimits specifies data transfer rate limits for the
  124. // client traffic.
  125. RateLimits RateLimits
  126. // DialTCPPortForwardTimeoutMilliseconds is the timeout period
  127. // for dialing TCP port forwards. A value of 0 specifies no timeout.
  128. // When omitted in DefaultRules,
  129. // DEFAULT_TCP_PORT_FORWARD_DIAL_TIMEOUT_MILLISECONDS is used.
  130. DialTCPPortForwardTimeoutMilliseconds *int
  131. // IdleTCPPortForwardTimeoutMilliseconds is the timeout period
  132. // after which idle (no bytes flowing in either direction)
  133. // client TCP port forwards are preemptively closed.
  134. // A value of 0 specifies no idle timeout. When omitted in
  135. // DefaultRules, DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  136. // is used.
  137. IdleTCPPortForwardTimeoutMilliseconds *int
  138. // IdleUDPPortForwardTimeoutMilliseconds is the timeout period
  139. // after which idle (no bytes flowing in either direction)
  140. // client UDP port forwards are preemptively closed.
  141. // A value of 0 specifies no idle timeout. When omitted in
  142. // DefaultRules, DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  143. // is used.
  144. IdleUDPPortForwardTimeoutMilliseconds *int
  145. // MaxTCPDialingPortForwardCount is the maximum number of dialing
  146. // TCP port forwards each client may have open concurrently. When
  147. // persistently at the limit, new TCP port forwards are rejected.
  148. // A value of 0 specifies no maximum. When omitted in
  149. // DefaultRules, DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT is used.
  150. MaxTCPDialingPortForwardCount *int
  151. // MaxTCPPortForwardCount is the maximum number of established TCP
  152. // port forwards each client may have open concurrently. If at the
  153. // limit when a new TCP port forward is established, the LRU
  154. // established TCP port forward is closed.
  155. // A value of 0 specifies no maximum. When omitted in
  156. // DefaultRules, DEFAULT_MAX_TCP_PORT_FORWARD_COUNT is used.
  157. MaxTCPPortForwardCount *int
  158. // MaxUDPPortForwardCount is the maximum number of UDP port
  159. // forwards each client may have open concurrently. If at the
  160. // limit when a new UDP port forward is created, the LRU
  161. // UDP port forward is closed.
  162. // A value of 0 specifies no maximum. When omitted in
  163. // DefaultRules, DEFAULT_MAX_UDP_PORT_FORWARD_COUNT is used.
  164. MaxUDPPortForwardCount *int
  165. // AllowTCPPorts specifies a whitelist of TCP ports that
  166. // are permitted for port forwarding. When set, only ports
  167. // in the list are accessible to clients.
  168. AllowTCPPorts []int
  169. // AllowUDPPorts specifies a whitelist of UDP ports that
  170. // are permitted for port forwarding. When set, only ports
  171. // in the list are accessible to clients.
  172. AllowUDPPorts []int
  173. // AllowSubnets specifies a list of IP address subnets for
  174. // which all TCP and UDP ports are allowed. This list is
  175. // consulted if a port is disallowed by the AllowTCPPorts
  176. // or AllowUDPPorts configuration. Each entry is a IP subnet
  177. // in CIDR notation.
  178. // Limitation: currently, AllowSubnets only matches port
  179. // forwards where the client sends an IP address. Domain
  180. // names aren not resolved before checking AllowSubnets.
  181. AllowSubnets []string
  182. }
  183. // RateLimits is a clone of common.RateLimits with pointers
  184. // to fields to enable distinguishing between zero values and
  185. // omitted values in JSON serialized traffic rules.
  186. // See common.RateLimits for field descriptions.
  187. type RateLimits struct {
  188. ReadUnthrottledBytes *int64
  189. ReadBytesPerSecond *int64
  190. WriteUnthrottledBytes *int64
  191. WriteBytesPerSecond *int64
  192. CloseAfterExhausted *bool
  193. // UnthrottleFirstTunnelOnly specifies whether any
  194. // ReadUnthrottledBytes/WriteUnthrottledBytes apply
  195. // only to the first tunnel in a session.
  196. UnthrottleFirstTunnelOnly *bool
  197. }
  198. // CommonRateLimits converts a RateLimits to a common.RateLimits.
  199. func (rateLimits *RateLimits) CommonRateLimits() common.RateLimits {
  200. return common.RateLimits{
  201. ReadUnthrottledBytes: *rateLimits.ReadUnthrottledBytes,
  202. ReadBytesPerSecond: *rateLimits.ReadBytesPerSecond,
  203. WriteUnthrottledBytes: *rateLimits.WriteUnthrottledBytes,
  204. WriteBytesPerSecond: *rateLimits.WriteBytesPerSecond,
  205. CloseAfterExhausted: *rateLimits.CloseAfterExhausted,
  206. }
  207. }
  208. // NewTrafficRulesSet initializes a TrafficRulesSet with
  209. // the rules data in the specified config file.
  210. func NewTrafficRulesSet(filename string) (*TrafficRulesSet, error) {
  211. set := &TrafficRulesSet{}
  212. set.ReloadableFile = common.NewReloadableFile(
  213. filename,
  214. func(fileContent []byte) error {
  215. var newSet TrafficRulesSet
  216. err := json.Unmarshal(fileContent, &newSet)
  217. if err != nil {
  218. return common.ContextError(err)
  219. }
  220. err = newSet.Validate()
  221. if err != nil {
  222. return common.ContextError(err)
  223. }
  224. // Modify actual traffic rules only after validation
  225. set.DefaultRules = newSet.DefaultRules
  226. set.FilteredRules = newSet.FilteredRules
  227. return nil
  228. })
  229. _, err := set.Reload()
  230. if err != nil {
  231. return nil, common.ContextError(err)
  232. }
  233. return set, nil
  234. }
  235. // Validate checks for correct input formats in a TrafficRulesSet.
  236. func (set *TrafficRulesSet) Validate() error {
  237. if set.MeekRateLimiterHistorySize < 0 ||
  238. set.MeekRateLimiterThresholdSeconds < 0 ||
  239. set.MeekRateLimiterGarbageCollectionTriggerCount < 0 ||
  240. set.MeekRateLimiterReapHistoryFrequencySeconds < 0 {
  241. return common.ContextError(
  242. errors.New("MeekRateLimiter values must be >= 0"))
  243. }
  244. if set.MeekRateLimiterHistorySize > 0 {
  245. if set.MeekRateLimiterThresholdSeconds <= 0 {
  246. return common.ContextError(
  247. errors.New("MeekRateLimiterThresholdSeconds must be > 0"))
  248. }
  249. }
  250. validateTrafficRules := func(rules *TrafficRules) error {
  251. if (rules.RateLimits.ReadUnthrottledBytes != nil && *rules.RateLimits.ReadUnthrottledBytes < 0) ||
  252. (rules.RateLimits.ReadBytesPerSecond != nil && *rules.RateLimits.ReadBytesPerSecond < 0) ||
  253. (rules.RateLimits.WriteUnthrottledBytes != nil && *rules.RateLimits.WriteUnthrottledBytes < 0) ||
  254. (rules.RateLimits.WriteBytesPerSecond != nil && *rules.RateLimits.WriteBytesPerSecond < 0) ||
  255. (rules.DialTCPPortForwardTimeoutMilliseconds != nil && *rules.DialTCPPortForwardTimeoutMilliseconds < 0) ||
  256. (rules.IdleTCPPortForwardTimeoutMilliseconds != nil && *rules.IdleTCPPortForwardTimeoutMilliseconds < 0) ||
  257. (rules.IdleUDPPortForwardTimeoutMilliseconds != nil && *rules.IdleUDPPortForwardTimeoutMilliseconds < 0) ||
  258. (rules.MaxTCPDialingPortForwardCount != nil && *rules.MaxTCPDialingPortForwardCount < 0) ||
  259. (rules.MaxTCPPortForwardCount != nil && *rules.MaxTCPPortForwardCount < 0) ||
  260. (rules.MaxUDPPortForwardCount != nil && *rules.MaxUDPPortForwardCount < 0) {
  261. return common.ContextError(
  262. errors.New("TrafficRules values must be >= 0"))
  263. }
  264. for _, subnet := range rules.AllowSubnets {
  265. _, _, err := net.ParseCIDR(subnet)
  266. if err != nil {
  267. return common.ContextError(
  268. fmt.Errorf("invalid subnet: %s %s", subnet, err))
  269. }
  270. }
  271. return nil
  272. }
  273. err := validateTrafficRules(&set.DefaultRules)
  274. if err != nil {
  275. return common.ContextError(err)
  276. }
  277. for _, filteredRule := range set.FilteredRules {
  278. for paramName := range filteredRule.Filter.HandshakeParameters {
  279. validParamName := false
  280. for _, paramSpec := range baseRequestParams {
  281. if paramSpec.name == paramName {
  282. validParamName = true
  283. break
  284. }
  285. }
  286. if !validParamName {
  287. return common.ContextError(
  288. fmt.Errorf("invalid parameter name: %s", paramName))
  289. }
  290. }
  291. err := validateTrafficRules(&filteredRule.Rules)
  292. if err != nil {
  293. return common.ContextError(err)
  294. }
  295. }
  296. return nil
  297. }
  298. // GetTrafficRules determines the traffic rules for a client based on its attributes.
  299. // For the return value TrafficRules, all pointer and slice fields are initialized,
  300. // so nil checks are not required. The caller must not modify the returned TrafficRules.
  301. func (set *TrafficRulesSet) GetTrafficRules(
  302. isFirstTunnelInSession bool,
  303. tunnelProtocol string,
  304. geoIPData GeoIPData,
  305. state handshakeState) TrafficRules {
  306. set.ReloadableFile.RLock()
  307. defer set.ReloadableFile.RUnlock()
  308. // Start with a copy of the DefaultRules, and then select the first
  309. // matching Rules from FilteredTrafficRules, taking only the explicitly
  310. // specified fields from that Rules.
  311. //
  312. // Notes:
  313. // - Scalar pointers are used in TrafficRules and RateLimits to distinguish between
  314. // omitted fields (in serialized JSON) and default values. For example, if a filtered
  315. // Rules specifies a field value of 0, this will override the default; but if the
  316. // serialized filtered rule omits the field, the default is to be retained.
  317. // - We use shallow copies and slices and scalar pointers are shared between the
  318. // return value TrafficRules, so callers must treat the return value as immutable.
  319. // This also means that these slices and pointers can remain referenced in memory even
  320. // after a hot reload.
  321. trafficRules := set.DefaultRules
  322. // Populate defaults for omitted DefaultRules fields
  323. if trafficRules.RateLimits.ReadUnthrottledBytes == nil {
  324. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  325. }
  326. if trafficRules.RateLimits.ReadBytesPerSecond == nil {
  327. trafficRules.RateLimits.ReadBytesPerSecond = new(int64)
  328. }
  329. if trafficRules.RateLimits.WriteUnthrottledBytes == nil {
  330. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  331. }
  332. if trafficRules.RateLimits.WriteBytesPerSecond == nil {
  333. trafficRules.RateLimits.WriteBytesPerSecond = new(int64)
  334. }
  335. if trafficRules.RateLimits.CloseAfterExhausted == nil {
  336. trafficRules.RateLimits.CloseAfterExhausted = new(bool)
  337. }
  338. if trafficRules.RateLimits.UnthrottleFirstTunnelOnly == nil {
  339. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = new(bool)
  340. }
  341. intPtr := func(i int) *int {
  342. return &i
  343. }
  344. if trafficRules.DialTCPPortForwardTimeoutMilliseconds == nil {
  345. trafficRules.DialTCPPortForwardTimeoutMilliseconds =
  346. intPtr(DEFAULT_DIAL_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  347. }
  348. if trafficRules.IdleTCPPortForwardTimeoutMilliseconds == nil {
  349. trafficRules.IdleTCPPortForwardTimeoutMilliseconds =
  350. intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  351. }
  352. if trafficRules.IdleUDPPortForwardTimeoutMilliseconds == nil {
  353. trafficRules.IdleUDPPortForwardTimeoutMilliseconds =
  354. intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  355. }
  356. if trafficRules.MaxTCPDialingPortForwardCount == nil {
  357. trafficRules.MaxTCPDialingPortForwardCount =
  358. intPtr(DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT)
  359. }
  360. if trafficRules.MaxTCPPortForwardCount == nil {
  361. trafficRules.MaxTCPPortForwardCount =
  362. intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT)
  363. }
  364. if trafficRules.MaxUDPPortForwardCount == nil {
  365. trafficRules.MaxUDPPortForwardCount =
  366. intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT)
  367. }
  368. if trafficRules.AllowTCPPorts == nil {
  369. trafficRules.AllowTCPPorts = make([]int, 0)
  370. }
  371. if trafficRules.AllowUDPPorts == nil {
  372. trafficRules.AllowUDPPorts = make([]int, 0)
  373. }
  374. if trafficRules.AllowSubnets == nil {
  375. trafficRules.AllowSubnets = make([]string, 0)
  376. }
  377. // TODO: faster lookup?
  378. for _, filteredRules := range set.FilteredRules {
  379. log.WithContextFields(LogFields{"filter": filteredRules.Filter}).Debug("filter check")
  380. if len(filteredRules.Filter.TunnelProtocols) > 0 {
  381. if !common.Contains(filteredRules.Filter.TunnelProtocols, tunnelProtocol) {
  382. continue
  383. }
  384. }
  385. if len(filteredRules.Filter.Regions) > 0 {
  386. if !common.Contains(filteredRules.Filter.Regions, geoIPData.Country) {
  387. continue
  388. }
  389. }
  390. if filteredRules.Filter.APIProtocol != "" {
  391. if !state.completed {
  392. continue
  393. }
  394. if state.apiProtocol != filteredRules.Filter.APIProtocol {
  395. continue
  396. }
  397. }
  398. if filteredRules.Filter.HandshakeParameters != nil {
  399. if !state.completed {
  400. continue
  401. }
  402. mismatch := false
  403. for name, values := range filteredRules.Filter.HandshakeParameters {
  404. clientValue, err := getStringRequestParam(state.apiParams, name)
  405. if err != nil || !common.ContainsWildcard(values, clientValue) {
  406. mismatch = true
  407. break
  408. }
  409. }
  410. if mismatch {
  411. continue
  412. }
  413. }
  414. if filteredRules.Filter.AuthorizationsRevoked {
  415. if !state.completed {
  416. continue
  417. }
  418. if !state.authorizationsRevoked {
  419. continue
  420. }
  421. } else if len(filteredRules.Filter.AuthorizedAccessTypes) > 0 {
  422. if !state.completed {
  423. continue
  424. }
  425. if state.authorizationsRevoked {
  426. continue
  427. }
  428. if !common.ContainsAny(filteredRules.Filter.AuthorizedAccessTypes, state.authorizedAccessTypes) {
  429. continue
  430. }
  431. }
  432. log.WithContextFields(LogFields{"filter": filteredRules.Filter}).Debug("filter match")
  433. // This is the first match. Override defaults using provided fields from selected rules, and return result.
  434. if filteredRules.Rules.RateLimits.ReadUnthrottledBytes != nil {
  435. trafficRules.RateLimits.ReadUnthrottledBytes = filteredRules.Rules.RateLimits.ReadUnthrottledBytes
  436. }
  437. if filteredRules.Rules.RateLimits.ReadBytesPerSecond != nil {
  438. trafficRules.RateLimits.ReadBytesPerSecond = filteredRules.Rules.RateLimits.ReadBytesPerSecond
  439. }
  440. if filteredRules.Rules.RateLimits.WriteUnthrottledBytes != nil {
  441. trafficRules.RateLimits.WriteUnthrottledBytes = filteredRules.Rules.RateLimits.WriteUnthrottledBytes
  442. }
  443. if filteredRules.Rules.RateLimits.WriteBytesPerSecond != nil {
  444. trafficRules.RateLimits.WriteBytesPerSecond = filteredRules.Rules.RateLimits.WriteBytesPerSecond
  445. }
  446. if filteredRules.Rules.RateLimits.CloseAfterExhausted != nil {
  447. trafficRules.RateLimits.CloseAfterExhausted = filteredRules.Rules.RateLimits.CloseAfterExhausted
  448. }
  449. if filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly != nil {
  450. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly
  451. }
  452. if filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds != nil {
  453. trafficRules.DialTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds
  454. }
  455. if filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds != nil {
  456. trafficRules.IdleTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds
  457. }
  458. if filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds != nil {
  459. trafficRules.IdleUDPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds
  460. }
  461. if filteredRules.Rules.MaxTCPDialingPortForwardCount != nil {
  462. trafficRules.MaxTCPDialingPortForwardCount = filteredRules.Rules.MaxTCPDialingPortForwardCount
  463. }
  464. if filteredRules.Rules.MaxTCPPortForwardCount != nil {
  465. trafficRules.MaxTCPPortForwardCount = filteredRules.Rules.MaxTCPPortForwardCount
  466. }
  467. if filteredRules.Rules.MaxUDPPortForwardCount != nil {
  468. trafficRules.MaxUDPPortForwardCount = filteredRules.Rules.MaxUDPPortForwardCount
  469. }
  470. if filteredRules.Rules.AllowTCPPorts != nil {
  471. trafficRules.AllowTCPPorts = filteredRules.Rules.AllowTCPPorts
  472. }
  473. if filteredRules.Rules.AllowUDPPorts != nil {
  474. trafficRules.AllowUDPPorts = filteredRules.Rules.AllowUDPPorts
  475. }
  476. if filteredRules.Rules.AllowSubnets != nil {
  477. trafficRules.AllowSubnets = filteredRules.Rules.AllowSubnets
  478. }
  479. break
  480. }
  481. if *trafficRules.RateLimits.UnthrottleFirstTunnelOnly && !isFirstTunnelInSession {
  482. *trafficRules.RateLimits.ReadUnthrottledBytes = 0
  483. *trafficRules.RateLimits.WriteUnthrottledBytes = 0
  484. }
  485. log.WithContextFields(LogFields{"trafficRules": trafficRules}).Debug("selected traffic rules")
  486. return trafficRules
  487. }
  488. // GetMeekRateLimiterConfig gets a snapshot of the meek rate limiter
  489. // configuration values.
  490. func (set *TrafficRulesSet) GetMeekRateLimiterConfig() (int, int, []string, int, int) {
  491. set.ReloadableFile.RLock()
  492. defer set.ReloadableFile.RUnlock()
  493. GCTriggerCount := set.MeekRateLimiterGarbageCollectionTriggerCount
  494. if GCTriggerCount <= 0 {
  495. GCTriggerCount = DEFAULT_MEEK_RATE_LIMITER_GARBAGE_COLLECTOR_TRIGGER_COUNT
  496. }
  497. reapFrequencySeconds := set.MeekRateLimiterReapHistoryFrequencySeconds
  498. if reapFrequencySeconds <= 0 {
  499. reapFrequencySeconds = DEFAULT_MEEK_RATE_LIMITER_REAP_HISTORY_FREQUENCY_SECONDS
  500. }
  501. return set.MeekRateLimiterHistorySize,
  502. set.MeekRateLimiterThresholdSeconds,
  503. set.MeekRateLimiterRegions,
  504. GCTriggerCount,
  505. reapFrequencySeconds
  506. }