trafficRules.go 32 KB

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