trafficRules.go 30 KB

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