trafficRules.go 22 KB

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