trafficRules.go 36 KB

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