trafficRules.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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. // ProviderIDs specifies a list of server host providers which match this
  178. // filter. When ProviderIDs is not empty, the current server will apply
  179. // the filter only if its provider ID, from Config.GetProviderID, is in
  180. // ProviderIDs.
  181. ProviderIDs []string
  182. regionLookup map[string]bool
  183. ispLookup map[string]bool
  184. asnLookup map[string]bool
  185. cityLookup map[string]bool
  186. activeAuthorizationIDLookup map[string]bool
  187. providerIDLookup map[string]bool
  188. }
  189. // TrafficRules specify the limits placed on client traffic.
  190. type TrafficRules struct {
  191. // RateLimits specifies data transfer rate limits for the
  192. // client traffic.
  193. RateLimits RateLimits
  194. // DialTCPPortForwardTimeoutMilliseconds is the timeout period
  195. // for dialing TCP port forwards. A value of 0 specifies no timeout.
  196. // When omitted in DefaultRules,
  197. // DEFAULT_TCP_PORT_FORWARD_DIAL_TIMEOUT_MILLISECONDS is used.
  198. DialTCPPortForwardTimeoutMilliseconds *int
  199. // IdleTCPPortForwardTimeoutMilliseconds is the timeout period
  200. // after which idle (no bytes flowing in either direction)
  201. // client TCP port forwards are preemptively closed.
  202. // A value of 0 specifies no idle timeout. When omitted in
  203. // DefaultRules, DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  204. // is used.
  205. IdleTCPPortForwardTimeoutMilliseconds *int
  206. // IdleUDPPortForwardTimeoutMilliseconds is the timeout period
  207. // after which idle (no bytes flowing in either direction)
  208. // client UDP port forwards are preemptively closed.
  209. // A value of 0 specifies no idle timeout. When omitted in
  210. // DefaultRules, DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  211. // is used.
  212. IdleUDPPortForwardTimeoutMilliseconds *int
  213. // MaxTCPDialingPortForwardCount is the maximum number of dialing
  214. // TCP port forwards each client may have open concurrently. When
  215. // persistently at the limit, new TCP port forwards are rejected.
  216. // A value of 0 specifies no maximum. When omitted in
  217. // DefaultRules, DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT is used.
  218. MaxTCPDialingPortForwardCount *int
  219. // MaxTCPPortForwardCount is the maximum number of established TCP
  220. // port forwards each client may have open concurrently. If at the
  221. // limit when a new TCP port forward is established, the LRU
  222. // established TCP port forward is closed.
  223. // A value of 0 specifies no maximum. When omitted in
  224. // DefaultRules, DEFAULT_MAX_TCP_PORT_FORWARD_COUNT is used.
  225. MaxTCPPortForwardCount *int
  226. // MaxUDPPortForwardCount is the maximum number of UDP port
  227. // forwards each client may have open concurrently. If at the
  228. // limit when a new UDP port forward is created, the LRU
  229. // UDP port forward is closed.
  230. // A value of 0 specifies no maximum. When omitted in
  231. // DefaultRules, DEFAULT_MAX_UDP_PORT_FORWARD_COUNT is used.
  232. MaxUDPPortForwardCount *int
  233. // AllowTCPPorts specifies a list of TCP ports that are permitted for port
  234. // forwarding. When set, only ports in the list are accessible to clients.
  235. AllowTCPPorts *common.PortList
  236. // AllowUDPPorts specifies a list of UDP ports that are permitted for port
  237. // forwarding. When set, only ports in the list are accessible to clients.
  238. AllowUDPPorts *common.PortList
  239. // DisallowTCPPorts specifies a list of TCP ports that are not permitted for
  240. // port forwarding. DisallowTCPPorts takes priority over AllowTCPPorts and
  241. // AllowSubnets.
  242. DisallowTCPPorts *common.PortList
  243. // DisallowUDPPorts specifies a list of UDP ports that are not permitted for
  244. // port forwarding. DisallowUDPPorts takes priority over AllowUDPPorts and
  245. // AllowSubnets.
  246. DisallowUDPPorts *common.PortList
  247. // AllowSubnets specifies a list of IP address subnets for which all TCP
  248. // and UDP ports are allowed. This list is consulted if a port is not
  249. // allowed by the AllowTCPPorts or AllowUDPPorts configuration; but not
  250. // if a port is disallowed by DisallowTCPPorts, DisallowUDPPorts,
  251. // DisallowSubnets or DisallowASNs. Each entry is a IP subnet in CIDR
  252. // notation.
  253. AllowSubnets []string
  254. // AllowASNs specifies a list of ASNs for which all TCP and UDP ports are
  255. // allowed. This list is consulted if a port is not allowed by the
  256. // AllowTCPPorts or AllowUDPPorts configuration; but not if a port is
  257. // disallowed by DisallowTCPPorts, DisallowUDPPorts, DisallowSubnets or
  258. // DisallowASNs.
  259. AllowASNs []string
  260. // DisallowSubnets specifies a list of IP address subnets for which all
  261. // TCP and UDP ports are disallowed. Each entry is a IP subnet in CIDR
  262. // notation.
  263. DisallowSubnets []string
  264. // DisallowASNs specifies a list of ASNs for which all TCP and UDP ports
  265. // are disallowed.
  266. DisallowASNs []string
  267. // DisableDiscovery specifies whether to disable server entry discovery,
  268. // to manage load on discovery servers.
  269. DisableDiscovery *bool
  270. }
  271. // RateLimits is a clone of common.RateLimits with pointers
  272. // to fields to enable distinguishing between zero values and
  273. // omitted values in JSON serialized traffic rules.
  274. // See common.RateLimits for field descriptions.
  275. type RateLimits struct {
  276. ReadUnthrottledBytes *int64
  277. ReadBytesPerSecond *int64
  278. WriteUnthrottledBytes *int64
  279. WriteBytesPerSecond *int64
  280. CloseAfterExhausted *bool
  281. // EstablishmentRead/WriteBytesPerSecond are used in place of
  282. // Read/WriteBytesPerSecond for tunnels in the establishment phase, from the
  283. // initial network connection up to the completion of the API handshake.
  284. EstablishmentReadBytesPerSecond *int64
  285. EstablishmentWriteBytesPerSecond *int64
  286. // UnthrottleFirstTunnelOnly specifies whether any
  287. // ReadUnthrottledBytes/WriteUnthrottledBytes apply
  288. // only to the first tunnel in a session.
  289. UnthrottleFirstTunnelOnly *bool
  290. }
  291. // CommonRateLimits converts a RateLimits to a common.RateLimits.
  292. func (rateLimits *RateLimits) CommonRateLimits(handshaked bool) common.RateLimits {
  293. r := common.RateLimits{
  294. ReadUnthrottledBytes: *rateLimits.ReadUnthrottledBytes,
  295. ReadBytesPerSecond: *rateLimits.ReadBytesPerSecond,
  296. WriteUnthrottledBytes: *rateLimits.WriteUnthrottledBytes,
  297. WriteBytesPerSecond: *rateLimits.WriteBytesPerSecond,
  298. CloseAfterExhausted: *rateLimits.CloseAfterExhausted,
  299. }
  300. if !handshaked {
  301. r.ReadBytesPerSecond = *rateLimits.EstablishmentReadBytesPerSecond
  302. r.WriteBytesPerSecond = *rateLimits.EstablishmentWriteBytesPerSecond
  303. }
  304. return r
  305. }
  306. // NewTrafficRulesSet initializes a TrafficRulesSet with
  307. // the rules data in the specified config file.
  308. func NewTrafficRulesSet(filename string) (*TrafficRulesSet, error) {
  309. set := &TrafficRulesSet{}
  310. set.ReloadableFile = common.NewReloadableFile(
  311. filename,
  312. true,
  313. func(fileContent []byte, _ time.Time) error {
  314. var newSet TrafficRulesSet
  315. err := json.Unmarshal(fileContent, &newSet)
  316. if err != nil {
  317. return errors.Trace(err)
  318. }
  319. err = newSet.Validate()
  320. if err != nil {
  321. return errors.Trace(err)
  322. }
  323. // Modify actual traffic rules only after validation
  324. set.MeekRateLimiterHistorySize = newSet.MeekRateLimiterHistorySize
  325. set.MeekRateLimiterThresholdSeconds = newSet.MeekRateLimiterThresholdSeconds
  326. set.MeekRateLimiterTunnelProtocols = newSet.MeekRateLimiterTunnelProtocols
  327. set.MeekRateLimiterRegions = newSet.MeekRateLimiterRegions
  328. set.MeekRateLimiterISPs = newSet.MeekRateLimiterISPs
  329. set.MeekRateLimiterASNs = newSet.MeekRateLimiterASNs
  330. set.MeekRateLimiterCities = newSet.MeekRateLimiterCities
  331. set.MeekRateLimiterGarbageCollectionTriggerCount = newSet.MeekRateLimiterGarbageCollectionTriggerCount
  332. set.MeekRateLimiterReapHistoryFrequencySeconds = newSet.MeekRateLimiterReapHistoryFrequencySeconds
  333. set.DefaultRules = newSet.DefaultRules
  334. set.FilteredRules = newSet.FilteredRules
  335. set.initLookups()
  336. return nil
  337. })
  338. _, err := set.Reload()
  339. if err != nil {
  340. return nil, errors.Trace(err)
  341. }
  342. return set, nil
  343. }
  344. // Validate checks for correct input formats in a TrafficRulesSet.
  345. func (set *TrafficRulesSet) Validate() error {
  346. if set.MeekRateLimiterHistorySize < 0 ||
  347. set.MeekRateLimiterThresholdSeconds < 0 ||
  348. set.MeekRateLimiterGarbageCollectionTriggerCount < 0 ||
  349. set.MeekRateLimiterReapHistoryFrequencySeconds < 0 {
  350. return errors.TraceNew("MeekRateLimiter values must be >= 0")
  351. }
  352. if set.MeekRateLimiterHistorySize > 0 {
  353. if set.MeekRateLimiterThresholdSeconds <= 0 {
  354. return errors.TraceNew("MeekRateLimiterThresholdSeconds must be > 0")
  355. }
  356. }
  357. validateTrafficRules := func(rules *TrafficRules) error {
  358. if (rules.RateLimits.ReadUnthrottledBytes != nil && *rules.RateLimits.ReadUnthrottledBytes < 0) ||
  359. (rules.RateLimits.ReadBytesPerSecond != nil && *rules.RateLimits.ReadBytesPerSecond < 0) ||
  360. (rules.RateLimits.WriteUnthrottledBytes != nil && *rules.RateLimits.WriteUnthrottledBytes < 0) ||
  361. (rules.RateLimits.WriteBytesPerSecond != nil && *rules.RateLimits.WriteBytesPerSecond < 0) ||
  362. (rules.RateLimits.EstablishmentReadBytesPerSecond != nil && *rules.RateLimits.EstablishmentReadBytesPerSecond < 0) ||
  363. (rules.RateLimits.EstablishmentWriteBytesPerSecond != nil && *rules.RateLimits.EstablishmentWriteBytesPerSecond < 0) ||
  364. (rules.DialTCPPortForwardTimeoutMilliseconds != nil && *rules.DialTCPPortForwardTimeoutMilliseconds < 0) ||
  365. (rules.IdleTCPPortForwardTimeoutMilliseconds != nil && *rules.IdleTCPPortForwardTimeoutMilliseconds < 0) ||
  366. (rules.IdleUDPPortForwardTimeoutMilliseconds != nil && *rules.IdleUDPPortForwardTimeoutMilliseconds < 0) ||
  367. (rules.MaxTCPDialingPortForwardCount != nil && *rules.MaxTCPDialingPortForwardCount < 0) ||
  368. (rules.MaxTCPPortForwardCount != nil && *rules.MaxTCPPortForwardCount < 0) ||
  369. (rules.MaxUDPPortForwardCount != nil && *rules.MaxUDPPortForwardCount < 0) {
  370. return errors.TraceNew("TrafficRules values must be >= 0")
  371. }
  372. for _, subnet := range rules.AllowSubnets {
  373. _, _, err := net.ParseCIDR(subnet)
  374. if err != nil {
  375. return errors.Tracef("invalid subnet: %s %s", subnet, err)
  376. }
  377. }
  378. for _, ASN := range rules.AllowASNs {
  379. _, err := strconv.Atoi(ASN)
  380. if err != nil {
  381. return errors.Tracef("invalid ASN: %s %s", ASN, err)
  382. }
  383. }
  384. for _, subnet := range rules.DisallowSubnets {
  385. _, _, err := net.ParseCIDR(subnet)
  386. if err != nil {
  387. return errors.Tracef("invalid subnet: %s %s", subnet, err)
  388. }
  389. }
  390. for _, ASN := range rules.DisallowASNs {
  391. _, err := strconv.Atoi(ASN)
  392. if err != nil {
  393. return errors.Tracef("invalid ASN: %s %s", ASN, err)
  394. }
  395. }
  396. return nil
  397. }
  398. validateFilter := func(filter *TrafficRulesFilter) error {
  399. for paramName := range filter.HandshakeParameters {
  400. validParamName := false
  401. for _, paramSpec := range handshakeRequestParams {
  402. if paramSpec.name == paramName {
  403. validParamName = true
  404. break
  405. }
  406. }
  407. if !validParamName {
  408. return errors.Tracef("invalid parameter name: %s", paramName)
  409. }
  410. }
  411. return nil
  412. }
  413. err := validateTrafficRules(&set.DefaultRules)
  414. if err != nil {
  415. return errors.Trace(err)
  416. }
  417. for _, filteredRule := range set.FilteredRules {
  418. err := validateFilter(&filteredRule.Filter)
  419. if err != nil {
  420. return errors.Trace(err)
  421. }
  422. if filteredRule.ExceptFilter != nil {
  423. err := validateFilter(filteredRule.ExceptFilter)
  424. if err != nil {
  425. return errors.Trace(err)
  426. }
  427. }
  428. err = validateTrafficRules(&filteredRule.Rules)
  429. if err != nil {
  430. return errors.Trace(err)
  431. }
  432. }
  433. return nil
  434. }
  435. const stringLookupThreshold = 5
  436. const intLookupThreshold = 10
  437. // initLookups creates map lookups for filters where the number of string/int
  438. // values to compare against exceeds a threshold where benchmarks show maps
  439. // are faster than looping through a string/int slice.
  440. func (set *TrafficRulesSet) initLookups() {
  441. initTrafficRulesLookups := func(rules *TrafficRules) {
  442. rules.AllowTCPPorts.OptimizeLookups()
  443. rules.AllowUDPPorts.OptimizeLookups()
  444. rules.DisallowTCPPorts.OptimizeLookups()
  445. rules.DisallowUDPPorts.OptimizeLookups()
  446. }
  447. initTrafficRulesFilterLookups := func(filter *TrafficRulesFilter) {
  448. if len(filter.Regions) >= stringLookupThreshold {
  449. filter.regionLookup = make(map[string]bool)
  450. for _, region := range filter.Regions {
  451. filter.regionLookup[region] = true
  452. }
  453. }
  454. if len(filter.ISPs) >= stringLookupThreshold {
  455. filter.ispLookup = make(map[string]bool)
  456. for _, ISP := range filter.ISPs {
  457. filter.ispLookup[ISP] = true
  458. }
  459. }
  460. if len(filter.ASNs) >= stringLookupThreshold {
  461. filter.asnLookup = make(map[string]bool)
  462. for _, ASN := range filter.ASNs {
  463. filter.asnLookup[ASN] = true
  464. }
  465. }
  466. if len(filter.Cities) >= stringLookupThreshold {
  467. filter.cityLookup = make(map[string]bool)
  468. for _, city := range filter.Cities {
  469. filter.cityLookup[city] = true
  470. }
  471. }
  472. if len(filter.ActiveAuthorizationIDs) >= stringLookupThreshold {
  473. filter.activeAuthorizationIDLookup = make(map[string]bool)
  474. for _, ID := range filter.ActiveAuthorizationIDs {
  475. filter.activeAuthorizationIDLookup[ID] = true
  476. }
  477. }
  478. if len(filter.ProviderIDs) >= stringLookupThreshold {
  479. filter.providerIDLookup = make(map[string]bool)
  480. for _, ID := range filter.ProviderIDs {
  481. filter.providerIDLookup[ID] = true
  482. }
  483. }
  484. }
  485. initTrafficRulesLookups(&set.DefaultRules)
  486. for i := range set.FilteredRules {
  487. initTrafficRulesFilterLookups(&set.FilteredRules[i].Filter)
  488. if set.FilteredRules[i].ExceptFilter != nil {
  489. initTrafficRulesFilterLookups(set.FilteredRules[i].ExceptFilter)
  490. }
  491. initTrafficRulesLookups(&set.FilteredRules[i].Rules)
  492. }
  493. // TODO: add lookups for MeekRateLimiter?
  494. }
  495. // GetTrafficRules determines the traffic rules for a client based on its attributes.
  496. // For the return value TrafficRules, all pointer and slice fields are initialized,
  497. // so nil checks are not required. The caller must not modify the returned TrafficRules.
  498. func (set *TrafficRulesSet) GetTrafficRules(
  499. serverProviderID string,
  500. isFirstTunnelInSession bool,
  501. tunnelProtocol string,
  502. geoIPData GeoIPData,
  503. state handshakeState) TrafficRules {
  504. set.ReloadableFile.RLock()
  505. defer set.ReloadableFile.RUnlock()
  506. // Start with a copy of the DefaultRules, and then select the first
  507. // matching Rules from FilteredTrafficRules, taking only the explicitly
  508. // specified fields from that Rules.
  509. //
  510. // Notes:
  511. // - Scalar pointers are used in TrafficRules and RateLimits to distinguish between
  512. // omitted fields (in serialized JSON) and default values. For example, if a filtered
  513. // Rules specifies a field value of 0, this will override the default; but if the
  514. // serialized filtered rule omits the field, the default is to be retained.
  515. // - We use shallow copies and slices and scalar pointers are shared between the
  516. // return value TrafficRules, so callers must treat the return value as immutable.
  517. // This also means that these slices and pointers can remain referenced in memory even
  518. // after a hot reload.
  519. trafficRules := set.DefaultRules
  520. // Populate defaults for omitted DefaultRules fields
  521. if trafficRules.RateLimits.ReadUnthrottledBytes == nil {
  522. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  523. }
  524. if trafficRules.RateLimits.ReadBytesPerSecond == nil {
  525. trafficRules.RateLimits.ReadBytesPerSecond = new(int64)
  526. }
  527. if trafficRules.RateLimits.WriteUnthrottledBytes == nil {
  528. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  529. }
  530. if trafficRules.RateLimits.WriteBytesPerSecond == nil {
  531. trafficRules.RateLimits.WriteBytesPerSecond = new(int64)
  532. }
  533. if trafficRules.RateLimits.CloseAfterExhausted == nil {
  534. trafficRules.RateLimits.CloseAfterExhausted = new(bool)
  535. }
  536. if trafficRules.RateLimits.EstablishmentReadBytesPerSecond == nil {
  537. trafficRules.RateLimits.EstablishmentReadBytesPerSecond = new(int64)
  538. }
  539. if trafficRules.RateLimits.EstablishmentWriteBytesPerSecond == nil {
  540. trafficRules.RateLimits.EstablishmentWriteBytesPerSecond = new(int64)
  541. }
  542. if trafficRules.RateLimits.UnthrottleFirstTunnelOnly == nil {
  543. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = new(bool)
  544. }
  545. intPtr := func(i int) *int {
  546. return &i
  547. }
  548. if trafficRules.DialTCPPortForwardTimeoutMilliseconds == nil {
  549. trafficRules.DialTCPPortForwardTimeoutMilliseconds =
  550. intPtr(DEFAULT_DIAL_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  551. }
  552. if trafficRules.IdleTCPPortForwardTimeoutMilliseconds == nil {
  553. trafficRules.IdleTCPPortForwardTimeoutMilliseconds =
  554. intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  555. }
  556. if trafficRules.IdleUDPPortForwardTimeoutMilliseconds == nil {
  557. trafficRules.IdleUDPPortForwardTimeoutMilliseconds =
  558. intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  559. }
  560. if trafficRules.MaxTCPDialingPortForwardCount == nil {
  561. trafficRules.MaxTCPDialingPortForwardCount =
  562. intPtr(DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT)
  563. }
  564. if trafficRules.MaxTCPPortForwardCount == nil {
  565. trafficRules.MaxTCPPortForwardCount =
  566. intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT)
  567. }
  568. if trafficRules.MaxUDPPortForwardCount == nil {
  569. trafficRules.MaxUDPPortForwardCount =
  570. intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT)
  571. }
  572. if trafficRules.AllowSubnets == nil {
  573. trafficRules.AllowSubnets = make([]string, 0)
  574. }
  575. if trafficRules.AllowASNs == nil {
  576. trafficRules.AllowASNs = make([]string, 0)
  577. }
  578. if trafficRules.DisallowSubnets == nil {
  579. trafficRules.DisallowSubnets = make([]string, 0)
  580. }
  581. if trafficRules.DisallowASNs == nil {
  582. trafficRules.DisallowASNs = make([]string, 0)
  583. }
  584. if trafficRules.DisableDiscovery == nil {
  585. trafficRules.DisableDiscovery = new(bool)
  586. }
  587. // matchFilter is used to check both Filter and any ExceptFilter
  588. matchFilter := func(filter *TrafficRulesFilter) bool {
  589. if len(filter.TunnelProtocols) > 0 {
  590. if !common.Contains(filter.TunnelProtocols, tunnelProtocol) {
  591. return false
  592. }
  593. }
  594. if len(filter.Regions) > 0 {
  595. if filter.regionLookup != nil {
  596. if !filter.regionLookup[geoIPData.Country] {
  597. return false
  598. }
  599. } else {
  600. if !common.Contains(filter.Regions, geoIPData.Country) {
  601. return false
  602. }
  603. }
  604. }
  605. if len(filter.ISPs) > 0 {
  606. if filter.ispLookup != nil {
  607. if !filter.ispLookup[geoIPData.ISP] {
  608. return false
  609. }
  610. } else {
  611. if !common.Contains(filter.ISPs, geoIPData.ISP) {
  612. return false
  613. }
  614. }
  615. }
  616. if len(filter.ASNs) > 0 {
  617. if filter.asnLookup != nil {
  618. if !filter.asnLookup[geoIPData.ASN] {
  619. return false
  620. }
  621. } else {
  622. if !common.Contains(filter.ASNs, geoIPData.ASN) {
  623. return false
  624. }
  625. }
  626. }
  627. if len(filter.Cities) > 0 {
  628. if filter.cityLookup != nil {
  629. if !filter.cityLookup[geoIPData.City] {
  630. return false
  631. }
  632. } else {
  633. if !common.Contains(filter.Cities, geoIPData.City) {
  634. return false
  635. }
  636. }
  637. }
  638. if filter.APIProtocol != "" {
  639. if !state.completed {
  640. return false
  641. }
  642. if state.apiProtocol != filter.APIProtocol {
  643. return false
  644. }
  645. }
  646. if filter.HandshakeParameters != nil {
  647. if !state.completed {
  648. return false
  649. }
  650. for name, values := range filter.HandshakeParameters {
  651. clientValue, err := getStringRequestParam(state.apiParams, name)
  652. if err != nil || !common.ContainsWildcard(values, clientValue) {
  653. return false
  654. }
  655. }
  656. }
  657. if filter.AuthorizationsRevoked {
  658. if !state.completed {
  659. return false
  660. }
  661. if !state.authorizationsRevoked {
  662. return false
  663. }
  664. } else {
  665. if len(filter.ActiveAuthorizationIDs) > 0 {
  666. if !state.completed {
  667. return false
  668. }
  669. if state.authorizationsRevoked {
  670. return false
  671. }
  672. if filter.activeAuthorizationIDLookup != nil {
  673. found := false
  674. for _, ID := range state.activeAuthorizationIDs {
  675. if filter.activeAuthorizationIDLookup[ID] {
  676. found = true
  677. break
  678. }
  679. }
  680. if !found {
  681. return false
  682. }
  683. } else {
  684. if !common.ContainsAny(filter.ActiveAuthorizationIDs, state.activeAuthorizationIDs) {
  685. return false
  686. }
  687. }
  688. }
  689. if len(filter.AuthorizedAccessTypes) > 0 {
  690. if !state.completed {
  691. return false
  692. }
  693. if state.authorizationsRevoked {
  694. return false
  695. }
  696. if !common.ContainsAny(filter.AuthorizedAccessTypes, state.authorizedAccessTypes) {
  697. return false
  698. }
  699. }
  700. }
  701. if len(filter.ProviderIDs) > 0 {
  702. if filter.providerIDLookup != nil {
  703. if !filter.providerIDLookup[serverProviderID] {
  704. return false
  705. }
  706. } else {
  707. if !common.Contains(filter.ProviderIDs, serverProviderID) {
  708. return false
  709. }
  710. }
  711. }
  712. return true
  713. }
  714. // Match filtered rules
  715. //
  716. // TODO: faster lookup?
  717. for _, filteredRules := range set.FilteredRules {
  718. log.WithTraceFields(LogFields{"filter": filteredRules.Filter}).Debug("filter check")
  719. match := matchFilter(&filteredRules.Filter)
  720. if match && filteredRules.ExceptFilter != nil {
  721. match = !matchFilter(filteredRules.ExceptFilter)
  722. }
  723. if !match {
  724. continue
  725. }
  726. log.WithTraceFields(LogFields{"filter": filteredRules.Filter}).Debug("filter match")
  727. // This is the first match. Override defaults using provided fields from selected rules, and return result.
  728. if filteredRules.Rules.RateLimits.ReadUnthrottledBytes != nil {
  729. trafficRules.RateLimits.ReadUnthrottledBytes = filteredRules.Rules.RateLimits.ReadUnthrottledBytes
  730. }
  731. if filteredRules.Rules.RateLimits.ReadBytesPerSecond != nil {
  732. trafficRules.RateLimits.ReadBytesPerSecond = filteredRules.Rules.RateLimits.ReadBytesPerSecond
  733. }
  734. if filteredRules.Rules.RateLimits.WriteUnthrottledBytes != nil {
  735. trafficRules.RateLimits.WriteUnthrottledBytes = filteredRules.Rules.RateLimits.WriteUnthrottledBytes
  736. }
  737. if filteredRules.Rules.RateLimits.WriteBytesPerSecond != nil {
  738. trafficRules.RateLimits.WriteBytesPerSecond = filteredRules.Rules.RateLimits.WriteBytesPerSecond
  739. }
  740. if filteredRules.Rules.RateLimits.CloseAfterExhausted != nil {
  741. trafficRules.RateLimits.CloseAfterExhausted = filteredRules.Rules.RateLimits.CloseAfterExhausted
  742. }
  743. if filteredRules.Rules.RateLimits.EstablishmentReadBytesPerSecond != nil {
  744. trafficRules.RateLimits.EstablishmentReadBytesPerSecond = filteredRules.Rules.RateLimits.EstablishmentReadBytesPerSecond
  745. }
  746. if filteredRules.Rules.RateLimits.EstablishmentWriteBytesPerSecond != nil {
  747. trafficRules.RateLimits.EstablishmentWriteBytesPerSecond = filteredRules.Rules.RateLimits.EstablishmentWriteBytesPerSecond
  748. }
  749. if filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly != nil {
  750. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly
  751. }
  752. if filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds != nil {
  753. trafficRules.DialTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds
  754. }
  755. if filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds != nil {
  756. trafficRules.IdleTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds
  757. }
  758. if filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds != nil {
  759. trafficRules.IdleUDPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds
  760. }
  761. if filteredRules.Rules.MaxTCPDialingPortForwardCount != nil {
  762. trafficRules.MaxTCPDialingPortForwardCount = filteredRules.Rules.MaxTCPDialingPortForwardCount
  763. }
  764. if filteredRules.Rules.MaxTCPPortForwardCount != nil {
  765. trafficRules.MaxTCPPortForwardCount = filteredRules.Rules.MaxTCPPortForwardCount
  766. }
  767. if filteredRules.Rules.MaxUDPPortForwardCount != nil {
  768. trafficRules.MaxUDPPortForwardCount = filteredRules.Rules.MaxUDPPortForwardCount
  769. }
  770. if filteredRules.Rules.AllowTCPPorts != nil {
  771. trafficRules.AllowTCPPorts = filteredRules.Rules.AllowTCPPorts
  772. }
  773. if filteredRules.Rules.AllowUDPPorts != nil {
  774. trafficRules.AllowUDPPorts = filteredRules.Rules.AllowUDPPorts
  775. }
  776. if filteredRules.Rules.DisallowTCPPorts != nil {
  777. trafficRules.DisallowTCPPorts = filteredRules.Rules.DisallowTCPPorts
  778. }
  779. if filteredRules.Rules.DisallowUDPPorts != nil {
  780. trafficRules.DisallowUDPPorts = filteredRules.Rules.DisallowUDPPorts
  781. }
  782. if filteredRules.Rules.AllowSubnets != nil {
  783. trafficRules.AllowSubnets = filteredRules.Rules.AllowSubnets
  784. }
  785. if filteredRules.Rules.AllowASNs != nil {
  786. trafficRules.AllowASNs = filteredRules.Rules.AllowASNs
  787. }
  788. if filteredRules.Rules.DisallowSubnets != nil {
  789. trafficRules.DisallowSubnets = filteredRules.Rules.DisallowSubnets
  790. }
  791. if filteredRules.Rules.DisallowASNs != nil {
  792. trafficRules.DisallowASNs = filteredRules.Rules.DisallowASNs
  793. }
  794. if filteredRules.Rules.DisableDiscovery != nil {
  795. trafficRules.DisableDiscovery = filteredRules.Rules.DisableDiscovery
  796. }
  797. break
  798. }
  799. if *trafficRules.RateLimits.UnthrottleFirstTunnelOnly && !isFirstTunnelInSession {
  800. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  801. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  802. }
  803. log.WithTraceFields(LogFields{"trafficRules": trafficRules}).Debug("selected traffic rules")
  804. return trafficRules
  805. }
  806. func (rules *TrafficRules) AllowTCPPort(
  807. geoIPService *GeoIPService, remoteIP net.IP, port int) bool {
  808. if rules.disallowSubnet(remoteIP) || rules.disallowASN(geoIPService, remoteIP) {
  809. return false
  810. }
  811. if rules.DisallowTCPPorts.Lookup(port) {
  812. return false
  813. }
  814. if rules.AllowTCPPorts.IsEmpty() {
  815. return true
  816. }
  817. if rules.AllowTCPPorts.Lookup(port) {
  818. return true
  819. }
  820. return rules.allowSubnet(remoteIP) || rules.allowASN(geoIPService, remoteIP)
  821. }
  822. func (rules *TrafficRules) AllowUDPPort(
  823. geoIPService *GeoIPService, remoteIP net.IP, port int) bool {
  824. if rules.disallowSubnet(remoteIP) || rules.disallowASN(geoIPService, remoteIP) {
  825. return false
  826. }
  827. if rules.DisallowUDPPorts.Lookup(port) {
  828. return false
  829. }
  830. if rules.AllowUDPPorts.IsEmpty() {
  831. return true
  832. }
  833. if rules.AllowUDPPorts.Lookup(port) {
  834. return true
  835. }
  836. return rules.allowSubnet(remoteIP) || rules.allowASN(geoIPService, remoteIP)
  837. }
  838. func (rules *TrafficRules) allowSubnet(remoteIP net.IP) bool {
  839. return ipInSubnets(remoteIP, rules.AllowSubnets)
  840. }
  841. func (rules *TrafficRules) allowASN(
  842. geoIPService *GeoIPService, remoteIP net.IP) bool {
  843. if len(rules.AllowASNs) == 0 || geoIPService == nil {
  844. return false
  845. }
  846. return common.Contains(
  847. rules.AllowASNs,
  848. geoIPService.LookupISPForIP(remoteIP).ASN)
  849. }
  850. func (rules *TrafficRules) disallowSubnet(remoteIP net.IP) bool {
  851. return ipInSubnets(remoteIP, rules.DisallowSubnets)
  852. }
  853. func ipInSubnets(remoteIP net.IP, subnets []string) bool {
  854. for _, subnet := range subnets {
  855. // TODO: cache parsed results
  856. // Note: ignoring error as config has been validated
  857. _, network, _ := net.ParseCIDR(subnet)
  858. if network.Contains(remoteIP) {
  859. return true
  860. }
  861. }
  862. return false
  863. }
  864. func (rules *TrafficRules) disallowASN(
  865. geoIPService *GeoIPService, remoteIP net.IP) bool {
  866. if len(rules.DisallowASNs) == 0 || geoIPService == nil {
  867. return false
  868. }
  869. return common.Contains(
  870. rules.DisallowASNs,
  871. geoIPService.LookupISPForIP(remoteIP).ASN)
  872. }
  873. // GetMeekRateLimiterConfig gets a snapshot of the meek rate limiter
  874. // configuration values.
  875. func (set *TrafficRulesSet) GetMeekRateLimiterConfig() (
  876. int, int, []string, []string, []string, []string, []string, int, int, int) {
  877. set.ReloadableFile.RLock()
  878. defer set.ReloadableFile.RUnlock()
  879. GCTriggerCount := set.MeekRateLimiterGarbageCollectionTriggerCount
  880. if GCTriggerCount <= 0 {
  881. GCTriggerCount = DEFAULT_MEEK_RATE_LIMITER_GARBAGE_COLLECTOR_TRIGGER_COUNT
  882. }
  883. reapFrequencySeconds := set.MeekRateLimiterReapHistoryFrequencySeconds
  884. if reapFrequencySeconds <= 0 {
  885. reapFrequencySeconds = DEFAULT_MEEK_RATE_LIMITER_REAP_HISTORY_FREQUENCY_SECONDS
  886. }
  887. maxEntries := set.MeekRateLimiterMaxEntries
  888. if maxEntries <= 0 {
  889. maxEntries = DEFAULT_MEEK_RATE_LIMITER_MAX_ENTRIES
  890. }
  891. return set.MeekRateLimiterHistorySize,
  892. set.MeekRateLimiterThresholdSeconds,
  893. set.MeekRateLimiterTunnelProtocols,
  894. set.MeekRateLimiterRegions,
  895. set.MeekRateLimiterISPs,
  896. set.MeekRateLimiterASNs,
  897. set.MeekRateLimiterCities,
  898. GCTriggerCount,
  899. reapFrequencySeconds,
  900. maxEntries
  901. }