trafficRules.go 32 KB

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