trafficRules.go 29 KB

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