trafficRules.go 35 KB

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