trafficRules.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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 []int
  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 []int
  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 []int
  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 []int
  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. allowTCPPortsLookup map[int]bool
  226. allowUDPPortsLookup map[int]bool
  227. disallowTCPPortsLookup map[int]bool
  228. disallowUDPPortsLookup map[int]bool
  229. }
  230. // RateLimits is a clone of common.RateLimits with pointers
  231. // to fields to enable distinguishing between zero values and
  232. // omitted values in JSON serialized traffic rules.
  233. // See common.RateLimits for field descriptions.
  234. type RateLimits struct {
  235. ReadUnthrottledBytes *int64
  236. ReadBytesPerSecond *int64
  237. WriteUnthrottledBytes *int64
  238. WriteBytesPerSecond *int64
  239. CloseAfterExhausted *bool
  240. // EstablishmentRead/WriteBytesPerSecond are used in place of
  241. // Read/WriteBytesPerSecond for tunnels in the establishment phase, from the
  242. // initial network connection up to the completion of the API handshake.
  243. EstablishmentReadBytesPerSecond *int64
  244. EstablishmentWriteBytesPerSecond *int64
  245. // UnthrottleFirstTunnelOnly specifies whether any
  246. // ReadUnthrottledBytes/WriteUnthrottledBytes apply
  247. // only to the first tunnel in a session.
  248. UnthrottleFirstTunnelOnly *bool
  249. }
  250. // CommonRateLimits converts a RateLimits to a common.RateLimits.
  251. func (rateLimits *RateLimits) CommonRateLimits(handshaked bool) common.RateLimits {
  252. r := common.RateLimits{
  253. ReadUnthrottledBytes: *rateLimits.ReadUnthrottledBytes,
  254. ReadBytesPerSecond: *rateLimits.ReadBytesPerSecond,
  255. WriteUnthrottledBytes: *rateLimits.WriteUnthrottledBytes,
  256. WriteBytesPerSecond: *rateLimits.WriteBytesPerSecond,
  257. CloseAfterExhausted: *rateLimits.CloseAfterExhausted,
  258. }
  259. if !handshaked {
  260. r.ReadBytesPerSecond = *rateLimits.EstablishmentReadBytesPerSecond
  261. r.WriteBytesPerSecond = *rateLimits.EstablishmentWriteBytesPerSecond
  262. }
  263. return r
  264. }
  265. // NewTrafficRulesSet initializes a TrafficRulesSet with
  266. // the rules data in the specified config file.
  267. func NewTrafficRulesSet(filename string) (*TrafficRulesSet, error) {
  268. set := &TrafficRulesSet{}
  269. set.ReloadableFile = common.NewReloadableFile(
  270. filename,
  271. true,
  272. func(fileContent []byte, _ time.Time) error {
  273. var newSet TrafficRulesSet
  274. err := json.Unmarshal(fileContent, &newSet)
  275. if err != nil {
  276. return errors.Trace(err)
  277. }
  278. err = newSet.Validate()
  279. if err != nil {
  280. return errors.Trace(err)
  281. }
  282. // Modify actual traffic rules only after validation
  283. set.MeekRateLimiterHistorySize = newSet.MeekRateLimiterHistorySize
  284. set.MeekRateLimiterThresholdSeconds = newSet.MeekRateLimiterThresholdSeconds
  285. set.MeekRateLimiterTunnelProtocols = newSet.MeekRateLimiterTunnelProtocols
  286. set.MeekRateLimiterRegions = newSet.MeekRateLimiterRegions
  287. set.MeekRateLimiterISPs = newSet.MeekRateLimiterISPs
  288. set.MeekRateLimiterCities = newSet.MeekRateLimiterCities
  289. set.MeekRateLimiterGarbageCollectionTriggerCount = newSet.MeekRateLimiterGarbageCollectionTriggerCount
  290. set.MeekRateLimiterReapHistoryFrequencySeconds = newSet.MeekRateLimiterReapHistoryFrequencySeconds
  291. set.DefaultRules = newSet.DefaultRules
  292. set.FilteredRules = newSet.FilteredRules
  293. set.initLookups()
  294. return nil
  295. })
  296. _, err := set.Reload()
  297. if err != nil {
  298. return nil, errors.Trace(err)
  299. }
  300. return set, nil
  301. }
  302. // Validate checks for correct input formats in a TrafficRulesSet.
  303. func (set *TrafficRulesSet) Validate() error {
  304. if set.MeekRateLimiterHistorySize < 0 ||
  305. set.MeekRateLimiterThresholdSeconds < 0 ||
  306. set.MeekRateLimiterGarbageCollectionTriggerCount < 0 ||
  307. set.MeekRateLimiterReapHistoryFrequencySeconds < 0 {
  308. return errors.TraceNew("MeekRateLimiter values must be >= 0")
  309. }
  310. if set.MeekRateLimiterHistorySize > 0 {
  311. if set.MeekRateLimiterThresholdSeconds <= 0 {
  312. return errors.TraceNew("MeekRateLimiterThresholdSeconds must be > 0")
  313. }
  314. }
  315. validateTrafficRules := func(rules *TrafficRules) error {
  316. if (rules.RateLimits.ReadUnthrottledBytes != nil && *rules.RateLimits.ReadUnthrottledBytes < 0) ||
  317. (rules.RateLimits.ReadBytesPerSecond != nil && *rules.RateLimits.ReadBytesPerSecond < 0) ||
  318. (rules.RateLimits.WriteUnthrottledBytes != nil && *rules.RateLimits.WriteUnthrottledBytes < 0) ||
  319. (rules.RateLimits.WriteBytesPerSecond != nil && *rules.RateLimits.WriteBytesPerSecond < 0) ||
  320. (rules.RateLimits.EstablishmentReadBytesPerSecond != nil && *rules.RateLimits.EstablishmentReadBytesPerSecond < 0) ||
  321. (rules.RateLimits.EstablishmentWriteBytesPerSecond != nil && *rules.RateLimits.EstablishmentWriteBytesPerSecond < 0) ||
  322. (rules.DialTCPPortForwardTimeoutMilliseconds != nil && *rules.DialTCPPortForwardTimeoutMilliseconds < 0) ||
  323. (rules.IdleTCPPortForwardTimeoutMilliseconds != nil && *rules.IdleTCPPortForwardTimeoutMilliseconds < 0) ||
  324. (rules.IdleUDPPortForwardTimeoutMilliseconds != nil && *rules.IdleUDPPortForwardTimeoutMilliseconds < 0) ||
  325. (rules.MaxTCPDialingPortForwardCount != nil && *rules.MaxTCPDialingPortForwardCount < 0) ||
  326. (rules.MaxTCPPortForwardCount != nil && *rules.MaxTCPPortForwardCount < 0) ||
  327. (rules.MaxUDPPortForwardCount != nil && *rules.MaxUDPPortForwardCount < 0) {
  328. return errors.TraceNew("TrafficRules values must be >= 0")
  329. }
  330. for _, subnet := range rules.AllowSubnets {
  331. _, _, err := net.ParseCIDR(subnet)
  332. if err != nil {
  333. return errors.Tracef("invalid subnet: %s %s", subnet, err)
  334. }
  335. }
  336. return nil
  337. }
  338. err := validateTrafficRules(&set.DefaultRules)
  339. if err != nil {
  340. return errors.Trace(err)
  341. }
  342. for _, filteredRule := range set.FilteredRules {
  343. for paramName := range filteredRule.Filter.HandshakeParameters {
  344. validParamName := false
  345. for _, paramSpec := range handshakeRequestParams {
  346. if paramSpec.name == paramName {
  347. validParamName = true
  348. break
  349. }
  350. }
  351. if !validParamName {
  352. return errors.Tracef("invalid parameter name: %s", paramName)
  353. }
  354. }
  355. err := validateTrafficRules(&filteredRule.Rules)
  356. if err != nil {
  357. return errors.Trace(err)
  358. }
  359. }
  360. return nil
  361. }
  362. const stringLookupThreshold = 5
  363. const intLookupThreshold = 10
  364. // initLookups creates map lookups for filters where the number of string/int
  365. // values to compare against exceeds a threshold where benchmarks show maps
  366. // are faster than looping through a string/int slice.
  367. func (set *TrafficRulesSet) initLookups() {
  368. initTrafficRulesLookups := func(rules *TrafficRules) {
  369. if len(rules.AllowTCPPorts) >= intLookupThreshold {
  370. rules.allowTCPPortsLookup = make(map[int]bool)
  371. for _, port := range rules.AllowTCPPorts {
  372. rules.allowTCPPortsLookup[port] = true
  373. }
  374. }
  375. if len(rules.AllowUDPPorts) >= intLookupThreshold {
  376. rules.allowUDPPortsLookup = make(map[int]bool)
  377. for _, port := range rules.AllowUDPPorts {
  378. rules.allowUDPPortsLookup[port] = true
  379. }
  380. }
  381. if len(rules.DisallowTCPPorts) >= intLookupThreshold {
  382. rules.disallowTCPPortsLookup = make(map[int]bool)
  383. for _, port := range rules.DisallowTCPPorts {
  384. rules.disallowTCPPortsLookup[port] = true
  385. }
  386. }
  387. if len(rules.DisallowUDPPorts) >= intLookupThreshold {
  388. rules.disallowUDPPortsLookup = make(map[int]bool)
  389. for _, port := range rules.DisallowUDPPorts {
  390. rules.disallowUDPPortsLookup[port] = true
  391. }
  392. }
  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.Cities) >= stringLookupThreshold {
  408. filter.cityLookup = make(map[string]bool)
  409. for _, city := range filter.Cities {
  410. filter.cityLookup[city] = true
  411. }
  412. }
  413. if len(filter.ActiveAuthorizationIDs) >= stringLookupThreshold {
  414. filter.activeAuthorizationIDLookup = make(map[string]bool)
  415. for _, ID := range filter.ActiveAuthorizationIDs {
  416. filter.activeAuthorizationIDLookup[ID] = true
  417. }
  418. }
  419. }
  420. initTrafficRulesLookups(&set.DefaultRules)
  421. for i := range set.FilteredRules {
  422. initTrafficRulesFilterLookups(&set.FilteredRules[i].Filter)
  423. initTrafficRulesLookups(&set.FilteredRules[i].Rules)
  424. }
  425. // TODO: add lookups for MeekRateLimiter?
  426. }
  427. // GetTrafficRules determines the traffic rules for a client based on its attributes.
  428. // For the return value TrafficRules, all pointer and slice fields are initialized,
  429. // so nil checks are not required. The caller must not modify the returned TrafficRules.
  430. func (set *TrafficRulesSet) GetTrafficRules(
  431. isFirstTunnelInSession bool,
  432. tunnelProtocol string,
  433. geoIPData GeoIPData,
  434. state handshakeState) TrafficRules {
  435. set.ReloadableFile.RLock()
  436. defer set.ReloadableFile.RUnlock()
  437. // Start with a copy of the DefaultRules, and then select the first
  438. // matching Rules from FilteredTrafficRules, taking only the explicitly
  439. // specified fields from that Rules.
  440. //
  441. // Notes:
  442. // - Scalar pointers are used in TrafficRules and RateLimits to distinguish between
  443. // omitted fields (in serialized JSON) and default values. For example, if a filtered
  444. // Rules specifies a field value of 0, this will override the default; but if the
  445. // serialized filtered rule omits the field, the default is to be retained.
  446. // - We use shallow copies and slices and scalar pointers are shared between the
  447. // return value TrafficRules, so callers must treat the return value as immutable.
  448. // This also means that these slices and pointers can remain referenced in memory even
  449. // after a hot reload.
  450. trafficRules := set.DefaultRules
  451. // Populate defaults for omitted DefaultRules fields
  452. if trafficRules.RateLimits.ReadUnthrottledBytes == nil {
  453. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  454. }
  455. if trafficRules.RateLimits.ReadBytesPerSecond == nil {
  456. trafficRules.RateLimits.ReadBytesPerSecond = new(int64)
  457. }
  458. if trafficRules.RateLimits.WriteUnthrottledBytes == nil {
  459. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  460. }
  461. if trafficRules.RateLimits.WriteBytesPerSecond == nil {
  462. trafficRules.RateLimits.WriteBytesPerSecond = new(int64)
  463. }
  464. if trafficRules.RateLimits.CloseAfterExhausted == nil {
  465. trafficRules.RateLimits.CloseAfterExhausted = new(bool)
  466. }
  467. if trafficRules.RateLimits.EstablishmentReadBytesPerSecond == nil {
  468. trafficRules.RateLimits.EstablishmentReadBytesPerSecond = new(int64)
  469. }
  470. if trafficRules.RateLimits.EstablishmentWriteBytesPerSecond == nil {
  471. trafficRules.RateLimits.EstablishmentWriteBytesPerSecond = new(int64)
  472. }
  473. if trafficRules.RateLimits.UnthrottleFirstTunnelOnly == nil {
  474. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = new(bool)
  475. }
  476. intPtr := func(i int) *int {
  477. return &i
  478. }
  479. if trafficRules.DialTCPPortForwardTimeoutMilliseconds == nil {
  480. trafficRules.DialTCPPortForwardTimeoutMilliseconds =
  481. intPtr(DEFAULT_DIAL_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  482. }
  483. if trafficRules.IdleTCPPortForwardTimeoutMilliseconds == nil {
  484. trafficRules.IdleTCPPortForwardTimeoutMilliseconds =
  485. intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  486. }
  487. if trafficRules.IdleUDPPortForwardTimeoutMilliseconds == nil {
  488. trafficRules.IdleUDPPortForwardTimeoutMilliseconds =
  489. intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  490. }
  491. if trafficRules.MaxTCPDialingPortForwardCount == nil {
  492. trafficRules.MaxTCPDialingPortForwardCount =
  493. intPtr(DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT)
  494. }
  495. if trafficRules.MaxTCPPortForwardCount == nil {
  496. trafficRules.MaxTCPPortForwardCount =
  497. intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT)
  498. }
  499. if trafficRules.MaxUDPPortForwardCount == nil {
  500. trafficRules.MaxUDPPortForwardCount =
  501. intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT)
  502. }
  503. if trafficRules.AllowTCPPorts == nil {
  504. trafficRules.AllowTCPPorts = make([]int, 0)
  505. }
  506. if trafficRules.AllowUDPPorts == nil {
  507. trafficRules.AllowUDPPorts = make([]int, 0)
  508. }
  509. if trafficRules.AllowSubnets == nil {
  510. trafficRules.AllowSubnets = make([]string, 0)
  511. }
  512. // TODO: faster lookup?
  513. for _, filteredRules := range set.FilteredRules {
  514. log.WithTraceFields(LogFields{"filter": filteredRules.Filter}).Debug("filter check")
  515. if len(filteredRules.Filter.TunnelProtocols) > 0 {
  516. if !common.Contains(filteredRules.Filter.TunnelProtocols, tunnelProtocol) {
  517. continue
  518. }
  519. }
  520. if len(filteredRules.Filter.Regions) > 0 {
  521. if filteredRules.Filter.regionLookup != nil {
  522. if !filteredRules.Filter.regionLookup[geoIPData.Country] {
  523. continue
  524. }
  525. } else {
  526. if !common.Contains(filteredRules.Filter.Regions, geoIPData.Country) {
  527. continue
  528. }
  529. }
  530. }
  531. if len(filteredRules.Filter.ISPs) > 0 {
  532. if filteredRules.Filter.ispLookup != nil {
  533. if !filteredRules.Filter.ispLookup[geoIPData.ISP] {
  534. continue
  535. }
  536. } else {
  537. if !common.Contains(filteredRules.Filter.ISPs, geoIPData.ISP) {
  538. continue
  539. }
  540. }
  541. }
  542. if len(filteredRules.Filter.Cities) > 0 {
  543. if filteredRules.Filter.cityLookup != nil {
  544. if !filteredRules.Filter.cityLookup[geoIPData.City] {
  545. continue
  546. }
  547. } else {
  548. if !common.Contains(filteredRules.Filter.Cities, geoIPData.City) {
  549. continue
  550. }
  551. }
  552. }
  553. if filteredRules.Filter.APIProtocol != "" {
  554. if !state.completed {
  555. continue
  556. }
  557. if state.apiProtocol != filteredRules.Filter.APIProtocol {
  558. continue
  559. }
  560. }
  561. if filteredRules.Filter.HandshakeParameters != nil {
  562. if !state.completed {
  563. continue
  564. }
  565. mismatch := false
  566. for name, values := range filteredRules.Filter.HandshakeParameters {
  567. clientValue, err := getStringRequestParam(state.apiParams, name)
  568. if err != nil || !common.ContainsWildcard(values, clientValue) {
  569. mismatch = true
  570. break
  571. }
  572. }
  573. if mismatch {
  574. continue
  575. }
  576. }
  577. if filteredRules.Filter.AuthorizationsRevoked {
  578. if !state.completed {
  579. continue
  580. }
  581. if !state.authorizationsRevoked {
  582. continue
  583. }
  584. } else {
  585. if len(filteredRules.Filter.ActiveAuthorizationIDs) > 0 {
  586. if !state.completed {
  587. continue
  588. }
  589. if state.authorizationsRevoked {
  590. continue
  591. }
  592. if filteredRules.Filter.activeAuthorizationIDLookup != nil {
  593. found := false
  594. for _, ID := range state.activeAuthorizationIDs {
  595. if filteredRules.Filter.activeAuthorizationIDLookup[ID] {
  596. found = true
  597. break
  598. }
  599. }
  600. if !found {
  601. continue
  602. }
  603. } else {
  604. if !common.ContainsAny(filteredRules.Filter.ActiveAuthorizationIDs, state.activeAuthorizationIDs) {
  605. continue
  606. }
  607. }
  608. }
  609. if len(filteredRules.Filter.AuthorizedAccessTypes) > 0 {
  610. if !state.completed {
  611. continue
  612. }
  613. if state.authorizationsRevoked {
  614. continue
  615. }
  616. if !common.ContainsAny(filteredRules.Filter.AuthorizedAccessTypes, state.authorizedAccessTypes) {
  617. continue
  618. }
  619. }
  620. }
  621. log.WithTraceFields(LogFields{"filter": filteredRules.Filter}).Debug("filter match")
  622. // This is the first match. Override defaults using provided fields from selected rules, and return result.
  623. if filteredRules.Rules.RateLimits.ReadUnthrottledBytes != nil {
  624. trafficRules.RateLimits.ReadUnthrottledBytes = filteredRules.Rules.RateLimits.ReadUnthrottledBytes
  625. }
  626. if filteredRules.Rules.RateLimits.ReadBytesPerSecond != nil {
  627. trafficRules.RateLimits.ReadBytesPerSecond = filteredRules.Rules.RateLimits.ReadBytesPerSecond
  628. }
  629. if filteredRules.Rules.RateLimits.WriteUnthrottledBytes != nil {
  630. trafficRules.RateLimits.WriteUnthrottledBytes = filteredRules.Rules.RateLimits.WriteUnthrottledBytes
  631. }
  632. if filteredRules.Rules.RateLimits.WriteBytesPerSecond != nil {
  633. trafficRules.RateLimits.WriteBytesPerSecond = filteredRules.Rules.RateLimits.WriteBytesPerSecond
  634. }
  635. if filteredRules.Rules.RateLimits.CloseAfterExhausted != nil {
  636. trafficRules.RateLimits.CloseAfterExhausted = filteredRules.Rules.RateLimits.CloseAfterExhausted
  637. }
  638. if filteredRules.Rules.RateLimits.EstablishmentReadBytesPerSecond != nil {
  639. trafficRules.RateLimits.EstablishmentReadBytesPerSecond = filteredRules.Rules.RateLimits.EstablishmentReadBytesPerSecond
  640. }
  641. if filteredRules.Rules.RateLimits.EstablishmentWriteBytesPerSecond != nil {
  642. trafficRules.RateLimits.EstablishmentWriteBytesPerSecond = filteredRules.Rules.RateLimits.EstablishmentWriteBytesPerSecond
  643. }
  644. if filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly != nil {
  645. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly
  646. }
  647. if filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds != nil {
  648. trafficRules.DialTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds
  649. }
  650. if filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds != nil {
  651. trafficRules.IdleTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds
  652. }
  653. if filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds != nil {
  654. trafficRules.IdleUDPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds
  655. }
  656. if filteredRules.Rules.MaxTCPDialingPortForwardCount != nil {
  657. trafficRules.MaxTCPDialingPortForwardCount = filteredRules.Rules.MaxTCPDialingPortForwardCount
  658. }
  659. if filteredRules.Rules.MaxTCPPortForwardCount != nil {
  660. trafficRules.MaxTCPPortForwardCount = filteredRules.Rules.MaxTCPPortForwardCount
  661. }
  662. if filteredRules.Rules.MaxUDPPortForwardCount != nil {
  663. trafficRules.MaxUDPPortForwardCount = filteredRules.Rules.MaxUDPPortForwardCount
  664. }
  665. if filteredRules.Rules.AllowTCPPorts != nil {
  666. trafficRules.AllowTCPPorts = filteredRules.Rules.AllowTCPPorts
  667. trafficRules.allowTCPPortsLookup = filteredRules.Rules.allowTCPPortsLookup
  668. }
  669. if filteredRules.Rules.AllowUDPPorts != nil {
  670. trafficRules.AllowUDPPorts = filteredRules.Rules.AllowUDPPorts
  671. trafficRules.allowUDPPortsLookup = filteredRules.Rules.allowUDPPortsLookup
  672. }
  673. if filteredRules.Rules.DisallowTCPPorts != nil {
  674. trafficRules.DisallowTCPPorts = filteredRules.Rules.DisallowTCPPorts
  675. trafficRules.disallowTCPPortsLookup = filteredRules.Rules.disallowTCPPortsLookup
  676. }
  677. if filteredRules.Rules.DisallowUDPPorts != nil {
  678. trafficRules.DisallowUDPPorts = filteredRules.Rules.DisallowUDPPorts
  679. trafficRules.disallowUDPPortsLookup = filteredRules.Rules.disallowUDPPortsLookup
  680. }
  681. if filteredRules.Rules.AllowSubnets != nil {
  682. trafficRules.AllowSubnets = filteredRules.Rules.AllowSubnets
  683. }
  684. break
  685. }
  686. if *trafficRules.RateLimits.UnthrottleFirstTunnelOnly && !isFirstTunnelInSession {
  687. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  688. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  689. }
  690. log.WithTraceFields(LogFields{"trafficRules": trafficRules}).Debug("selected traffic rules")
  691. return trafficRules
  692. }
  693. func (rules *TrafficRules) AllowTCPPort(remoteIP net.IP, port int) bool {
  694. if len(rules.DisallowTCPPorts) > 0 {
  695. if rules.disallowTCPPortsLookup != nil {
  696. if rules.disallowTCPPortsLookup[port] {
  697. return false
  698. }
  699. } else {
  700. for _, disallowPort := range rules.DisallowTCPPorts {
  701. if port == disallowPort {
  702. return false
  703. }
  704. }
  705. }
  706. }
  707. if len(rules.AllowTCPPorts) == 0 {
  708. return true
  709. }
  710. if rules.allowTCPPortsLookup != nil {
  711. if rules.allowTCPPortsLookup[port] {
  712. return true
  713. }
  714. } else {
  715. for _, allowPort := range rules.AllowTCPPorts {
  716. if port == allowPort {
  717. return true
  718. }
  719. }
  720. }
  721. return rules.allowSubnet(remoteIP)
  722. }
  723. func (rules *TrafficRules) AllowUDPPort(remoteIP net.IP, port int) bool {
  724. if len(rules.DisallowUDPPorts) > 0 {
  725. if rules.disallowUDPPortsLookup != nil {
  726. if rules.disallowUDPPortsLookup[port] {
  727. return false
  728. }
  729. } else {
  730. for _, disallowPort := range rules.DisallowUDPPorts {
  731. if port == disallowPort {
  732. return false
  733. }
  734. }
  735. }
  736. }
  737. if len(rules.AllowUDPPorts) == 0 {
  738. return true
  739. }
  740. if rules.allowUDPPortsLookup != nil {
  741. if rules.allowUDPPortsLookup[port] {
  742. return true
  743. }
  744. } else {
  745. for _, allowPort := range rules.AllowUDPPorts {
  746. if port == allowPort {
  747. return true
  748. }
  749. }
  750. }
  751. return rules.allowSubnet(remoteIP)
  752. }
  753. func (rules *TrafficRules) allowSubnet(remoteIP net.IP) bool {
  754. for _, subnet := range rules.AllowSubnets {
  755. // Note: ignoring error as config has been validated
  756. _, network, _ := net.ParseCIDR(subnet)
  757. if network.Contains(remoteIP) {
  758. return true
  759. }
  760. }
  761. return false
  762. }
  763. // GetMeekRateLimiterConfig gets a snapshot of the meek rate limiter
  764. // configuration values.
  765. func (set *TrafficRulesSet) GetMeekRateLimiterConfig() (
  766. int, int, []string, []string, []string, []string, int, int) {
  767. set.ReloadableFile.RLock()
  768. defer set.ReloadableFile.RUnlock()
  769. GCTriggerCount := set.MeekRateLimiterGarbageCollectionTriggerCount
  770. if GCTriggerCount <= 0 {
  771. GCTriggerCount = DEFAULT_MEEK_RATE_LIMITER_GARBAGE_COLLECTOR_TRIGGER_COUNT
  772. }
  773. reapFrequencySeconds := set.MeekRateLimiterReapHistoryFrequencySeconds
  774. if reapFrequencySeconds <= 0 {
  775. reapFrequencySeconds = DEFAULT_MEEK_RATE_LIMITER_REAP_HISTORY_FREQUENCY_SECONDS
  776. }
  777. return set.MeekRateLimiterHistorySize,
  778. set.MeekRateLimiterThresholdSeconds,
  779. set.MeekRateLimiterTunnelProtocols,
  780. set.MeekRateLimiterRegions,
  781. set.MeekRateLimiterISPs,
  782. set.MeekRateLimiterCities,
  783. GCTriggerCount,
  784. reapFrequencySeconds
  785. }