trafficRules.go 22 KB

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