trafficRules.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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. "net"
  23. "time"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  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/ISPs/Cities.
  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. // MeekRateLimiterCities, if set, limits application of the meek
  85. // late-stage rate limiter to clients in the specified list of GeoIP
  86. // cities. When omitted or empty, meek rate limiting, if configured,
  87. // is applied to all client cities.
  88. MeekRateLimiterCities []string
  89. // MeekRateLimiterGarbageCollectionTriggerCount specifies the number of
  90. // rate limit events after which garbage collection is manually triggered
  91. // in order to reclaim memory used by rate limited and other rejected
  92. // requests.
  93. // A default of 5000 is used when
  94. // MeekRateLimiterGarbageCollectionTriggerCount is 0.
  95. MeekRateLimiterGarbageCollectionTriggerCount int
  96. // MeekRateLimiterReapHistoryFrequencySeconds specifies a schedule for
  97. // reaping old records from the rate limit history.
  98. // A default of 600 is used when
  99. // MeekRateLimiterReapHistoryFrequencySeconds is 0.
  100. MeekRateLimiterReapHistoryFrequencySeconds int
  101. }
  102. // TrafficRulesFilter defines a filter to match against client attributes.
  103. type TrafficRulesFilter struct {
  104. // TunnelProtocols is a list of client tunnel protocols that must be
  105. // in use to match this filter. When omitted or empty, any protocol
  106. // matches.
  107. TunnelProtocols []string
  108. // Regions is a list of countries that the client must geolocate to in
  109. // order to match this filter. When omitted or empty, any client country
  110. // matches.
  111. Regions []string
  112. // ISPs is a list of ISPs that the client must geolocate to in order to
  113. // match this filter. When omitted or empty, any client ISP matches.
  114. ISPs []string
  115. // Cities is a list of cities that the client must geolocate to in order to
  116. // match this filter. When omitted or empty, any client city matches.
  117. Cities []string
  118. // APIProtocol specifies whether the client must use the SSH
  119. // API protocol (when "ssh") or the web API protocol (when "web").
  120. // When omitted or blank, any API protocol matches.
  121. APIProtocol string
  122. // HandshakeParameters specifies handshake API parameter names and
  123. // a list of values, one of which must be specified to match this
  124. // filter. Only scalar string API parameters may be filtered.
  125. // Values may be patterns containing the '*' wildcard.
  126. HandshakeParameters map[string][]string
  127. // AuthorizedAccessTypes specifies a list of access types, at least
  128. // one of which the client must have presented an active authorization
  129. // for and which must not be revoked.
  130. // AuthorizedAccessTypes is ignored when AuthorizationsRevoked is true.
  131. AuthorizedAccessTypes []string
  132. // AuthorizationsRevoked indicates whether the client's authorizations
  133. // must have been revoked. When true, authorizations must have been
  134. // revoked. When omitted or false, this field is ignored.
  135. AuthorizationsRevoked bool
  136. regionLookup map[string]bool
  137. ispLookup map[string]bool
  138. cityLookup map[string]bool
  139. }
  140. // TrafficRules specify the limits placed on client traffic.
  141. type TrafficRules struct {
  142. // RateLimits specifies data transfer rate limits for the
  143. // client traffic.
  144. RateLimits RateLimits
  145. // DialTCPPortForwardTimeoutMilliseconds is the timeout period
  146. // for dialing TCP port forwards. A value of 0 specifies no timeout.
  147. // When omitted in DefaultRules,
  148. // DEFAULT_TCP_PORT_FORWARD_DIAL_TIMEOUT_MILLISECONDS is used.
  149. DialTCPPortForwardTimeoutMilliseconds *int
  150. // IdleTCPPortForwardTimeoutMilliseconds is the timeout period
  151. // after which idle (no bytes flowing in either direction)
  152. // client TCP port forwards are preemptively closed.
  153. // A value of 0 specifies no idle timeout. When omitted in
  154. // DefaultRules, DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  155. // is used.
  156. IdleTCPPortForwardTimeoutMilliseconds *int
  157. // IdleUDPPortForwardTimeoutMilliseconds is the timeout period
  158. // after which idle (no bytes flowing in either direction)
  159. // client UDP port forwards are preemptively closed.
  160. // A value of 0 specifies no idle timeout. When omitted in
  161. // DefaultRules, DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  162. // is used.
  163. IdleUDPPortForwardTimeoutMilliseconds *int
  164. // MaxTCPDialingPortForwardCount is the maximum number of dialing
  165. // TCP port forwards each client may have open concurrently. When
  166. // persistently at the limit, new TCP port forwards are rejected.
  167. // A value of 0 specifies no maximum. When omitted in
  168. // DefaultRules, DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT is used.
  169. MaxTCPDialingPortForwardCount *int
  170. // MaxTCPPortForwardCount is the maximum number of established TCP
  171. // port forwards each client may have open concurrently. If at the
  172. // limit when a new TCP port forward is established, the LRU
  173. // established TCP port forward is closed.
  174. // A value of 0 specifies no maximum. When omitted in
  175. // DefaultRules, DEFAULT_MAX_TCP_PORT_FORWARD_COUNT is used.
  176. MaxTCPPortForwardCount *int
  177. // MaxUDPPortForwardCount is the maximum number of UDP port
  178. // forwards each client may have open concurrently. If at the
  179. // limit when a new UDP port forward is created, the LRU
  180. // UDP port forward is closed.
  181. // A value of 0 specifies no maximum. When omitted in
  182. // DefaultRules, DEFAULT_MAX_UDP_PORT_FORWARD_COUNT is used.
  183. MaxUDPPortForwardCount *int
  184. // AllowTCPPorts specifies a list of TCP ports that are permitted for port
  185. // forwarding. When set, only ports in the list are accessible to clients.
  186. AllowTCPPorts []int
  187. // AllowUDPPorts specifies a list of UDP ports that are permitted for port
  188. // forwarding. When set, only ports in the list are accessible to clients.
  189. AllowUDPPorts []int
  190. // DisallowTCPPorts specifies a list of TCP ports that are not permitted for
  191. // port forwarding. DisallowTCPPorts takes priority over AllowTCPPorts and
  192. // AllowSubnets.
  193. DisallowTCPPorts []int
  194. // DisallowUDPPorts specifies a list of UDP ports that are not permitted for
  195. // port forwarding. DisallowUDPPorts takes priority over AllowUDPPorts and
  196. // AllowSubnets.
  197. DisallowUDPPorts []int
  198. // AllowSubnets specifies a list of IP address subnets for which all TCP and
  199. // UDP ports are allowed. This list is consulted if a port is disallowed by
  200. // the AllowTCPPorts or AllowUDPPorts configuration. Each entry is a IP
  201. // subnet in CIDR notation.
  202. //
  203. // Limitation: currently, AllowSubnets only matches port forwards where the
  204. // client sends an IP address. Domain names are not resolved before checking
  205. // AllowSubnets.
  206. AllowSubnets []string
  207. allowTCPPortsLookup map[int]bool
  208. allowUDPPortsLookup map[int]bool
  209. disallowTCPPortsLookup map[int]bool
  210. disallowUDPPortsLookup map[int]bool
  211. }
  212. // RateLimits is a clone of common.RateLimits with pointers
  213. // to fields to enable distinguishing between zero values and
  214. // omitted values in JSON serialized traffic rules.
  215. // See common.RateLimits for field descriptions.
  216. type RateLimits struct {
  217. ReadUnthrottledBytes *int64
  218. ReadBytesPerSecond *int64
  219. WriteUnthrottledBytes *int64
  220. WriteBytesPerSecond *int64
  221. CloseAfterExhausted *bool
  222. // UnthrottleFirstTunnelOnly specifies whether any
  223. // ReadUnthrottledBytes/WriteUnthrottledBytes apply
  224. // only to the first tunnel in a session.
  225. UnthrottleFirstTunnelOnly *bool
  226. }
  227. // CommonRateLimits converts a RateLimits to a common.RateLimits.
  228. func (rateLimits *RateLimits) CommonRateLimits() common.RateLimits {
  229. return common.RateLimits{
  230. ReadUnthrottledBytes: *rateLimits.ReadUnthrottledBytes,
  231. ReadBytesPerSecond: *rateLimits.ReadBytesPerSecond,
  232. WriteUnthrottledBytes: *rateLimits.WriteUnthrottledBytes,
  233. WriteBytesPerSecond: *rateLimits.WriteBytesPerSecond,
  234. CloseAfterExhausted: *rateLimits.CloseAfterExhausted,
  235. }
  236. }
  237. // NewTrafficRulesSet initializes a TrafficRulesSet with
  238. // the rules data in the specified config file.
  239. func NewTrafficRulesSet(filename string) (*TrafficRulesSet, error) {
  240. set := &TrafficRulesSet{}
  241. set.ReloadableFile = common.NewReloadableFile(
  242. filename,
  243. true,
  244. func(fileContent []byte, _ time.Time) error {
  245. var newSet TrafficRulesSet
  246. err := json.Unmarshal(fileContent, &newSet)
  247. if err != nil {
  248. return errors.Trace(err)
  249. }
  250. err = newSet.Validate()
  251. if err != nil {
  252. return errors.Trace(err)
  253. }
  254. // Modify actual traffic rules only after validation
  255. set.MeekRateLimiterHistorySize = newSet.MeekRateLimiterHistorySize
  256. set.MeekRateLimiterThresholdSeconds = newSet.MeekRateLimiterThresholdSeconds
  257. set.MeekRateLimiterRegions = newSet.MeekRateLimiterRegions
  258. set.MeekRateLimiterISPs = newSet.MeekRateLimiterISPs
  259. set.MeekRateLimiterCities = newSet.MeekRateLimiterCities
  260. set.MeekRateLimiterGarbageCollectionTriggerCount = newSet.MeekRateLimiterGarbageCollectionTriggerCount
  261. set.MeekRateLimiterReapHistoryFrequencySeconds = newSet.MeekRateLimiterReapHistoryFrequencySeconds
  262. set.DefaultRules = newSet.DefaultRules
  263. set.FilteredRules = newSet.FilteredRules
  264. set.initLookups()
  265. return nil
  266. })
  267. _, err := set.Reload()
  268. if err != nil {
  269. return nil, errors.Trace(err)
  270. }
  271. return set, nil
  272. }
  273. // Validate checks for correct input formats in a TrafficRulesSet.
  274. func (set *TrafficRulesSet) Validate() error {
  275. if set.MeekRateLimiterHistorySize < 0 ||
  276. set.MeekRateLimiterThresholdSeconds < 0 ||
  277. set.MeekRateLimiterGarbageCollectionTriggerCount < 0 ||
  278. set.MeekRateLimiterReapHistoryFrequencySeconds < 0 {
  279. return errors.TraceNew("MeekRateLimiter values must be >= 0")
  280. }
  281. if set.MeekRateLimiterHistorySize > 0 {
  282. if set.MeekRateLimiterThresholdSeconds <= 0 {
  283. return errors.TraceNew("MeekRateLimiterThresholdSeconds must be > 0")
  284. }
  285. }
  286. validateTrafficRules := func(rules *TrafficRules) error {
  287. if (rules.RateLimits.ReadUnthrottledBytes != nil && *rules.RateLimits.ReadUnthrottledBytes < 0) ||
  288. (rules.RateLimits.ReadBytesPerSecond != nil && *rules.RateLimits.ReadBytesPerSecond < 0) ||
  289. (rules.RateLimits.WriteUnthrottledBytes != nil && *rules.RateLimits.WriteUnthrottledBytes < 0) ||
  290. (rules.RateLimits.WriteBytesPerSecond != nil && *rules.RateLimits.WriteBytesPerSecond < 0) ||
  291. (rules.DialTCPPortForwardTimeoutMilliseconds != nil && *rules.DialTCPPortForwardTimeoutMilliseconds < 0) ||
  292. (rules.IdleTCPPortForwardTimeoutMilliseconds != nil && *rules.IdleTCPPortForwardTimeoutMilliseconds < 0) ||
  293. (rules.IdleUDPPortForwardTimeoutMilliseconds != nil && *rules.IdleUDPPortForwardTimeoutMilliseconds < 0) ||
  294. (rules.MaxTCPDialingPortForwardCount != nil && *rules.MaxTCPDialingPortForwardCount < 0) ||
  295. (rules.MaxTCPPortForwardCount != nil && *rules.MaxTCPPortForwardCount < 0) ||
  296. (rules.MaxUDPPortForwardCount != nil && *rules.MaxUDPPortForwardCount < 0) {
  297. return errors.TraceNew("TrafficRules values must be >= 0")
  298. }
  299. for _, subnet := range rules.AllowSubnets {
  300. _, _, err := net.ParseCIDR(subnet)
  301. if err != nil {
  302. return errors.Tracef("invalid subnet: %s %s", subnet, err)
  303. }
  304. }
  305. return nil
  306. }
  307. err := validateTrafficRules(&set.DefaultRules)
  308. if err != nil {
  309. return errors.Trace(err)
  310. }
  311. for _, filteredRule := range set.FilteredRules {
  312. for paramName := range filteredRule.Filter.HandshakeParameters {
  313. validParamName := false
  314. for _, paramSpec := range baseRequestParams {
  315. if paramSpec.name == paramName {
  316. validParamName = true
  317. break
  318. }
  319. }
  320. if !validParamName {
  321. return errors.Tracef("invalid parameter name: %s", paramName)
  322. }
  323. }
  324. err := validateTrafficRules(&filteredRule.Rules)
  325. if err != nil {
  326. return errors.Trace(err)
  327. }
  328. }
  329. return nil
  330. }
  331. const stringLookupThreshold = 5
  332. const intLookupThreshold = 10
  333. // initLookups creates map lookups for filters where the number of string/int
  334. // values to compare against exceeds a threshold where benchmarks show maps
  335. // are faster than looping through a string/int slice.
  336. func (set *TrafficRulesSet) initLookups() {
  337. initTrafficRulesLookups := func(rules *TrafficRules) {
  338. if len(rules.AllowTCPPorts) >= intLookupThreshold {
  339. rules.allowTCPPortsLookup = make(map[int]bool)
  340. for _, port := range rules.AllowTCPPorts {
  341. rules.allowTCPPortsLookup[port] = true
  342. }
  343. }
  344. if len(rules.AllowUDPPorts) >= intLookupThreshold {
  345. rules.allowUDPPortsLookup = make(map[int]bool)
  346. for _, port := range rules.AllowUDPPorts {
  347. rules.allowUDPPortsLookup[port] = true
  348. }
  349. }
  350. if len(rules.DisallowTCPPorts) >= intLookupThreshold {
  351. rules.disallowTCPPortsLookup = make(map[int]bool)
  352. for _, port := range rules.DisallowTCPPorts {
  353. rules.disallowTCPPortsLookup[port] = true
  354. }
  355. }
  356. if len(rules.DisallowUDPPorts) >= intLookupThreshold {
  357. rules.disallowUDPPortsLookup = make(map[int]bool)
  358. for _, port := range rules.DisallowUDPPorts {
  359. rules.disallowUDPPortsLookup[port] = true
  360. }
  361. }
  362. }
  363. initTrafficRulesFilterLookups := func(filter *TrafficRulesFilter) {
  364. if len(filter.Regions) >= stringLookupThreshold {
  365. filter.regionLookup = make(map[string]bool)
  366. for _, region := range filter.Regions {
  367. filter.regionLookup[region] = true
  368. }
  369. }
  370. if len(filter.ISPs) >= stringLookupThreshold {
  371. filter.ispLookup = make(map[string]bool)
  372. for _, ISP := range filter.ISPs {
  373. filter.ispLookup[ISP] = true
  374. }
  375. }
  376. if len(filter.Cities) >= stringLookupThreshold {
  377. filter.cityLookup = make(map[string]bool)
  378. for _, city := range filter.Cities {
  379. filter.cityLookup[city] = true
  380. }
  381. }
  382. }
  383. initTrafficRulesLookups(&set.DefaultRules)
  384. for i := range set.FilteredRules {
  385. initTrafficRulesFilterLookups(&set.FilteredRules[i].Filter)
  386. initTrafficRulesLookups(&set.FilteredRules[i].Rules)
  387. }
  388. // TODO: add lookups for MeekRateLimiter?
  389. }
  390. // GetTrafficRules determines the traffic rules for a client based on its attributes.
  391. // For the return value TrafficRules, all pointer and slice fields are initialized,
  392. // so nil checks are not required. The caller must not modify the returned TrafficRules.
  393. func (set *TrafficRulesSet) GetTrafficRules(
  394. isFirstTunnelInSession bool,
  395. tunnelProtocol string,
  396. geoIPData GeoIPData,
  397. state handshakeState) TrafficRules {
  398. set.ReloadableFile.RLock()
  399. defer set.ReloadableFile.RUnlock()
  400. // Start with a copy of the DefaultRules, and then select the first
  401. // matching Rules from FilteredTrafficRules, taking only the explicitly
  402. // specified fields from that Rules.
  403. //
  404. // Notes:
  405. // - Scalar pointers are used in TrafficRules and RateLimits to distinguish between
  406. // omitted fields (in serialized JSON) and default values. For example, if a filtered
  407. // Rules specifies a field value of 0, this will override the default; but if the
  408. // serialized filtered rule omits the field, the default is to be retained.
  409. // - We use shallow copies and slices and scalar pointers are shared between the
  410. // return value TrafficRules, so callers must treat the return value as immutable.
  411. // This also means that these slices and pointers can remain referenced in memory even
  412. // after a hot reload.
  413. trafficRules := set.DefaultRules
  414. // Populate defaults for omitted DefaultRules fields
  415. if trafficRules.RateLimits.ReadUnthrottledBytes == nil {
  416. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  417. }
  418. if trafficRules.RateLimits.ReadBytesPerSecond == nil {
  419. trafficRules.RateLimits.ReadBytesPerSecond = new(int64)
  420. }
  421. if trafficRules.RateLimits.WriteUnthrottledBytes == nil {
  422. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  423. }
  424. if trafficRules.RateLimits.WriteBytesPerSecond == nil {
  425. trafficRules.RateLimits.WriteBytesPerSecond = new(int64)
  426. }
  427. if trafficRules.RateLimits.CloseAfterExhausted == nil {
  428. trafficRules.RateLimits.CloseAfterExhausted = new(bool)
  429. }
  430. if trafficRules.RateLimits.UnthrottleFirstTunnelOnly == nil {
  431. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = new(bool)
  432. }
  433. intPtr := func(i int) *int {
  434. return &i
  435. }
  436. if trafficRules.DialTCPPortForwardTimeoutMilliseconds == nil {
  437. trafficRules.DialTCPPortForwardTimeoutMilliseconds =
  438. intPtr(DEFAULT_DIAL_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  439. }
  440. if trafficRules.IdleTCPPortForwardTimeoutMilliseconds == nil {
  441. trafficRules.IdleTCPPortForwardTimeoutMilliseconds =
  442. intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  443. }
  444. if trafficRules.IdleUDPPortForwardTimeoutMilliseconds == nil {
  445. trafficRules.IdleUDPPortForwardTimeoutMilliseconds =
  446. intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  447. }
  448. if trafficRules.MaxTCPDialingPortForwardCount == nil {
  449. trafficRules.MaxTCPDialingPortForwardCount =
  450. intPtr(DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT)
  451. }
  452. if trafficRules.MaxTCPPortForwardCount == nil {
  453. trafficRules.MaxTCPPortForwardCount =
  454. intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT)
  455. }
  456. if trafficRules.MaxUDPPortForwardCount == nil {
  457. trafficRules.MaxUDPPortForwardCount =
  458. intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT)
  459. }
  460. if trafficRules.AllowTCPPorts == nil {
  461. trafficRules.AllowTCPPorts = make([]int, 0)
  462. }
  463. if trafficRules.AllowUDPPorts == nil {
  464. trafficRules.AllowUDPPorts = make([]int, 0)
  465. }
  466. if trafficRules.AllowSubnets == nil {
  467. trafficRules.AllowSubnets = make([]string, 0)
  468. }
  469. // TODO: faster lookup?
  470. for _, filteredRules := range set.FilteredRules {
  471. log.WithTraceFields(LogFields{"filter": filteredRules.Filter}).Debug("filter check")
  472. if len(filteredRules.Filter.TunnelProtocols) > 0 {
  473. if !common.Contains(filteredRules.Filter.TunnelProtocols, tunnelProtocol) {
  474. continue
  475. }
  476. }
  477. if len(filteredRules.Filter.Regions) > 0 {
  478. if filteredRules.Filter.regionLookup != nil {
  479. if !filteredRules.Filter.regionLookup[geoIPData.Country] {
  480. continue
  481. }
  482. } else {
  483. if !common.Contains(filteredRules.Filter.Regions, geoIPData.Country) {
  484. continue
  485. }
  486. }
  487. }
  488. if len(filteredRules.Filter.ISPs) > 0 {
  489. if filteredRules.Filter.ispLookup != nil {
  490. if !filteredRules.Filter.ispLookup[geoIPData.ISP] {
  491. continue
  492. }
  493. } else {
  494. if !common.Contains(filteredRules.Filter.ISPs, geoIPData.ISP) {
  495. continue
  496. }
  497. }
  498. }
  499. if len(filteredRules.Filter.Cities) > 0 {
  500. if filteredRules.Filter.cityLookup != nil {
  501. if !filteredRules.Filter.cityLookup[geoIPData.City] {
  502. continue
  503. }
  504. } else {
  505. if !common.Contains(filteredRules.Filter.Cities, geoIPData.City) {
  506. continue
  507. }
  508. }
  509. }
  510. if filteredRules.Filter.APIProtocol != "" {
  511. if !state.completed {
  512. continue
  513. }
  514. if state.apiProtocol != filteredRules.Filter.APIProtocol {
  515. continue
  516. }
  517. }
  518. if filteredRules.Filter.HandshakeParameters != nil {
  519. if !state.completed {
  520. continue
  521. }
  522. mismatch := false
  523. for name, values := range filteredRules.Filter.HandshakeParameters {
  524. clientValue, err := getStringRequestParam(state.apiParams, name)
  525. if err != nil || !common.ContainsWildcard(values, clientValue) {
  526. mismatch = true
  527. break
  528. }
  529. }
  530. if mismatch {
  531. continue
  532. }
  533. }
  534. if filteredRules.Filter.AuthorizationsRevoked {
  535. if !state.completed {
  536. continue
  537. }
  538. if !state.authorizationsRevoked {
  539. continue
  540. }
  541. } else if len(filteredRules.Filter.AuthorizedAccessTypes) > 0 {
  542. if !state.completed {
  543. continue
  544. }
  545. if state.authorizationsRevoked {
  546. continue
  547. }
  548. if !common.ContainsAny(filteredRules.Filter.AuthorizedAccessTypes, state.authorizedAccessTypes) {
  549. continue
  550. }
  551. }
  552. log.WithTraceFields(LogFields{"filter": filteredRules.Filter}).Debug("filter match")
  553. // This is the first match. Override defaults using provided fields from selected rules, and return result.
  554. if filteredRules.Rules.RateLimits.ReadUnthrottledBytes != nil {
  555. trafficRules.RateLimits.ReadUnthrottledBytes = filteredRules.Rules.RateLimits.ReadUnthrottledBytes
  556. }
  557. if filteredRules.Rules.RateLimits.ReadBytesPerSecond != nil {
  558. trafficRules.RateLimits.ReadBytesPerSecond = filteredRules.Rules.RateLimits.ReadBytesPerSecond
  559. }
  560. if filteredRules.Rules.RateLimits.WriteUnthrottledBytes != nil {
  561. trafficRules.RateLimits.WriteUnthrottledBytes = filteredRules.Rules.RateLimits.WriteUnthrottledBytes
  562. }
  563. if filteredRules.Rules.RateLimits.WriteBytesPerSecond != nil {
  564. trafficRules.RateLimits.WriteBytesPerSecond = filteredRules.Rules.RateLimits.WriteBytesPerSecond
  565. }
  566. if filteredRules.Rules.RateLimits.CloseAfterExhausted != nil {
  567. trafficRules.RateLimits.CloseAfterExhausted = filteredRules.Rules.RateLimits.CloseAfterExhausted
  568. }
  569. if filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly != nil {
  570. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly
  571. }
  572. if filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds != nil {
  573. trafficRules.DialTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds
  574. }
  575. if filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds != nil {
  576. trafficRules.IdleTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds
  577. }
  578. if filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds != nil {
  579. trafficRules.IdleUDPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds
  580. }
  581. if filteredRules.Rules.MaxTCPDialingPortForwardCount != nil {
  582. trafficRules.MaxTCPDialingPortForwardCount = filteredRules.Rules.MaxTCPDialingPortForwardCount
  583. }
  584. if filteredRules.Rules.MaxTCPPortForwardCount != nil {
  585. trafficRules.MaxTCPPortForwardCount = filteredRules.Rules.MaxTCPPortForwardCount
  586. }
  587. if filteredRules.Rules.MaxUDPPortForwardCount != nil {
  588. trafficRules.MaxUDPPortForwardCount = filteredRules.Rules.MaxUDPPortForwardCount
  589. }
  590. if filteredRules.Rules.AllowTCPPorts != nil {
  591. trafficRules.AllowTCPPorts = filteredRules.Rules.AllowTCPPorts
  592. trafficRules.allowTCPPortsLookup = filteredRules.Rules.allowTCPPortsLookup
  593. }
  594. if filteredRules.Rules.AllowUDPPorts != nil {
  595. trafficRules.AllowUDPPorts = filteredRules.Rules.AllowUDPPorts
  596. trafficRules.allowUDPPortsLookup = filteredRules.Rules.allowUDPPortsLookup
  597. }
  598. if filteredRules.Rules.DisallowTCPPorts != nil {
  599. trafficRules.DisallowTCPPorts = filteredRules.Rules.DisallowTCPPorts
  600. trafficRules.disallowTCPPortsLookup = filteredRules.Rules.disallowTCPPortsLookup
  601. }
  602. if filteredRules.Rules.DisallowUDPPorts != nil {
  603. trafficRules.DisallowUDPPorts = filteredRules.Rules.DisallowUDPPorts
  604. trafficRules.disallowUDPPortsLookup = filteredRules.Rules.disallowUDPPortsLookup
  605. }
  606. if filteredRules.Rules.AllowSubnets != nil {
  607. trafficRules.AllowSubnets = filteredRules.Rules.AllowSubnets
  608. }
  609. break
  610. }
  611. if *trafficRules.RateLimits.UnthrottleFirstTunnelOnly && !isFirstTunnelInSession {
  612. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  613. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  614. }
  615. log.WithTraceFields(LogFields{"trafficRules": trafficRules}).Debug("selected traffic rules")
  616. return trafficRules
  617. }
  618. func (rules *TrafficRules) AllowTCPPort(remoteIP net.IP, port int) bool {
  619. if len(rules.DisallowTCPPorts) > 0 {
  620. if rules.disallowTCPPortsLookup != nil {
  621. if rules.disallowTCPPortsLookup[port] {
  622. return false
  623. }
  624. } else {
  625. for _, disallowPort := range rules.DisallowTCPPorts {
  626. if port == disallowPort {
  627. return false
  628. }
  629. }
  630. }
  631. }
  632. if len(rules.AllowTCPPorts) == 0 {
  633. return true
  634. }
  635. if rules.allowTCPPortsLookup != nil {
  636. if rules.allowTCPPortsLookup[port] {
  637. return true
  638. }
  639. } else {
  640. for _, allowPort := range rules.AllowTCPPorts {
  641. if port == allowPort {
  642. return true
  643. }
  644. }
  645. }
  646. return rules.allowSubnet(remoteIP)
  647. }
  648. func (rules *TrafficRules) AllowUDPPort(remoteIP net.IP, port int) bool {
  649. if len(rules.DisallowUDPPorts) > 0 {
  650. if rules.disallowUDPPortsLookup != nil {
  651. if rules.disallowUDPPortsLookup[port] {
  652. return false
  653. }
  654. } else {
  655. for _, disallowPort := range rules.DisallowUDPPorts {
  656. if port == disallowPort {
  657. return false
  658. }
  659. }
  660. }
  661. }
  662. if len(rules.AllowUDPPorts) == 0 {
  663. return true
  664. }
  665. if rules.allowUDPPortsLookup != nil {
  666. if rules.allowUDPPortsLookup[port] {
  667. return true
  668. }
  669. } else {
  670. for _, allowPort := range rules.AllowUDPPorts {
  671. if port == allowPort {
  672. return true
  673. }
  674. }
  675. }
  676. return rules.allowSubnet(remoteIP)
  677. }
  678. func (rules *TrafficRules) allowSubnet(remoteIP net.IP) bool {
  679. for _, subnet := range rules.AllowSubnets {
  680. // Note: ignoring error as config has been validated
  681. _, network, _ := net.ParseCIDR(subnet)
  682. if network.Contains(remoteIP) {
  683. return true
  684. }
  685. }
  686. return false
  687. }
  688. // GetMeekRateLimiterConfig gets a snapshot of the meek rate limiter
  689. // configuration values.
  690. func (set *TrafficRulesSet) GetMeekRateLimiterConfig() (int, int, []string, []string, []string, int, int) {
  691. set.ReloadableFile.RLock()
  692. defer set.ReloadableFile.RUnlock()
  693. GCTriggerCount := set.MeekRateLimiterGarbageCollectionTriggerCount
  694. if GCTriggerCount <= 0 {
  695. GCTriggerCount = DEFAULT_MEEK_RATE_LIMITER_GARBAGE_COLLECTOR_TRIGGER_COUNT
  696. }
  697. reapFrequencySeconds := set.MeekRateLimiterReapHistoryFrequencySeconds
  698. if reapFrequencySeconds <= 0 {
  699. reapFrequencySeconds = DEFAULT_MEEK_RATE_LIMITER_REAP_HISTORY_FREQUENCY_SECONDS
  700. }
  701. return set.MeekRateLimiterHistorySize,
  702. set.MeekRateLimiterThresholdSeconds,
  703. set.MeekRateLimiterRegions,
  704. set.MeekRateLimiterISPs,
  705. set.MeekRateLimiterCities,
  706. GCTriggerCount,
  707. reapFrequencySeconds
  708. }