trafficRules.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. "fmt"
  23. "net"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  25. )
  26. const (
  27. DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS = 30000
  28. DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS = 30000
  29. DEFAULT_DIAL_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS = 10000
  30. DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT = 64
  31. DEFAULT_MAX_TCP_PORT_FORWARD_COUNT = 512
  32. DEFAULT_MAX_UDP_PORT_FORWARD_COUNT = 32
  33. )
  34. // TrafficRulesSet represents the various traffic rules to
  35. // apply to Psiphon client tunnels. The Reload function supports
  36. // hot reloading of rules data while the server is running.
  37. //
  38. // For a given client, the traffic rules are determined by starting
  39. // with DefaultRules, then finding the first (if any)
  40. // FilteredTrafficRules match and overriding the defaults with fields
  41. // set in the selected FilteredTrafficRules.
  42. type TrafficRulesSet struct {
  43. common.ReloadableFile
  44. // DefaultRules are the base values to use as defaults for all
  45. // clients.
  46. DefaultRules TrafficRules
  47. // FilteredTrafficRules is an ordered list of filter/rules pairs.
  48. // For each client, the first matching Filter in FilteredTrafficRules
  49. // determines the additional Rules that are selected and applied
  50. // on top of DefaultRules.
  51. FilteredRules []struct {
  52. Filter TrafficRulesFilter
  53. Rules TrafficRules
  54. }
  55. }
  56. // TrafficRulesFilter defines a filter to match against client attributes.
  57. type TrafficRulesFilter struct {
  58. // TunnelProtocols is a list of client tunnel protocols that must be
  59. // in use to match this filter. When omitted or empty, any protocol
  60. // matches.
  61. TunnelProtocols []string
  62. // Regions is a list of client GeoIP countries that the client must
  63. // reolve to to match this filter. When omitted or empty, any client
  64. // region matches.
  65. Regions []string
  66. // APIProtocol specifies whether the client must use the SSH
  67. // API protocol (when "ssh") or the web API protocol (when "web").
  68. // When omitted or blank, any API protocol matches.
  69. APIProtocol string
  70. // HandshakeParameters specifies handshake API parameter names and
  71. // a list of values, one of which must be specified to match this
  72. // filter. Only scalar string API parameters may be filtered.
  73. HandshakeParameters map[string][]string
  74. // AuthorizedAccessTypes specifies a list of access types, at least
  75. // one of which the client must have presented an active authorization
  76. // for and which must not be revoked.
  77. // AuthorizedAccessTypes is ignored when AuthorizationsRevoked is true.
  78. AuthorizedAccessTypes []string
  79. // AuthorizationsRevoked indicates whether the client's authorizations
  80. // must have been revoked. When true, authorizations must have been
  81. // revoked. When omitted or false, this field is ignored.
  82. AuthorizationsRevoked bool
  83. }
  84. // TrafficRules specify the limits placed on client traffic.
  85. type TrafficRules struct {
  86. // RateLimits specifies data transfer rate limits for the
  87. // client traffic.
  88. RateLimits RateLimits
  89. // DialTCPPortForwardTimeoutMilliseconds is the timeout period
  90. // for dialing TCP port forwards. A value of 0 specifies no timeout.
  91. // When omitted in DefaultRules,
  92. // DEFAULT_TCP_PORT_FORWARD_DIAL_TIMEOUT_MILLISECONDS is used.
  93. DialTCPPortForwardTimeoutMilliseconds *int
  94. // IdleTCPPortForwardTimeoutMilliseconds is the timeout period
  95. // after which idle (no bytes flowing in either direction)
  96. // client TCP port forwards are preemptively closed.
  97. // A value of 0 specifies no idle timeout. When omitted in
  98. // DefaultRules, DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  99. // is used.
  100. IdleTCPPortForwardTimeoutMilliseconds *int
  101. // IdleUDPPortForwardTimeoutMilliseconds is the timeout period
  102. // after which idle (no bytes flowing in either direction)
  103. // client UDP port forwards are preemptively closed.
  104. // A value of 0 specifies no idle timeout. When omitted in
  105. // DefaultRules, DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS
  106. // is used.
  107. IdleUDPPortForwardTimeoutMilliseconds *int
  108. // MaxTCPDialingPortForwardCount is the maximum number of dialing
  109. // TCP port forwards each client may have open concurrently. When
  110. // persistently at the limit, new TCP port forwards are rejected.
  111. // A value of 0 specifies no maximum. When omitted in
  112. // DefaultRules, DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT is used.
  113. MaxTCPDialingPortForwardCount *int
  114. // MaxTCPPortForwardCount is the maximum number of established TCP
  115. // port forwards each client may have open concurrently. If at the
  116. // limit when a new TCP port forward is established, the LRU
  117. // established TCP port forward is closed.
  118. // A value of 0 specifies no maximum. When omitted in
  119. // DefaultRules, DEFAULT_MAX_TCP_PORT_FORWARD_COUNT is used.
  120. MaxTCPPortForwardCount *int
  121. // MaxUDPPortForwardCount is the maximum number of UDP port
  122. // forwards each client may have open concurrently. If at the
  123. // limit when a new UDP port forward is created, the LRU
  124. // UDP port forward is closed.
  125. // A value of 0 specifies no maximum. When omitted in
  126. // DefaultRules, DEFAULT_MAX_UDP_PORT_FORWARD_COUNT is used.
  127. MaxUDPPortForwardCount *int
  128. // AllowTCPPorts specifies a whitelist of TCP ports that
  129. // are permitted for port forwarding. When set, only ports
  130. // in the list are accessible to clients.
  131. AllowTCPPorts []int
  132. // AllowUDPPorts specifies a whitelist of UDP ports that
  133. // are permitted for port forwarding. When set, only ports
  134. // in the list are accessible to clients.
  135. AllowUDPPorts []int
  136. // AllowSubnets specifies a list of IP address subnets for
  137. // which all TCP and UDP ports are allowed. This list is
  138. // consulted if a port is disallowed by the AllowTCPPorts
  139. // or AllowUDPPorts configuration. Each entry is a IP subnet
  140. // in CIDR notation.
  141. // Limitation: currently, AllowSubnets only matches port
  142. // forwards where the client sends an IP address. Domain
  143. // names aren not resolved before checking AllowSubnets.
  144. AllowSubnets []string
  145. }
  146. // RateLimits is a clone of common.RateLimits with pointers
  147. // to fields to enable distinguishing between zero values and
  148. // omitted values in JSON serialized traffic rules.
  149. // See common.RateLimits for field descriptions.
  150. type RateLimits struct {
  151. ReadUnthrottledBytes *int64
  152. ReadBytesPerSecond *int64
  153. WriteUnthrottledBytes *int64
  154. WriteBytesPerSecond *int64
  155. CloseAfterExhausted *bool
  156. // UnthrottleFirstTunnelOnly specifies whether any
  157. // ReadUnthrottledBytes/WriteUnthrottledBytes apply
  158. // only to the first tunnel in a session.
  159. UnthrottleFirstTunnelOnly *bool
  160. }
  161. // CommonRateLimits converts a RateLimits to a common.RateLimits.
  162. func (rateLimits *RateLimits) CommonRateLimits() common.RateLimits {
  163. return common.RateLimits{
  164. ReadUnthrottledBytes: *rateLimits.ReadUnthrottledBytes,
  165. ReadBytesPerSecond: *rateLimits.ReadBytesPerSecond,
  166. WriteUnthrottledBytes: *rateLimits.WriteUnthrottledBytes,
  167. WriteBytesPerSecond: *rateLimits.WriteBytesPerSecond,
  168. CloseAfterExhausted: *rateLimits.CloseAfterExhausted,
  169. }
  170. }
  171. // NewTrafficRulesSet initializes a TrafficRulesSet with
  172. // the rules data in the specified config file.
  173. func NewTrafficRulesSet(filename string) (*TrafficRulesSet, error) {
  174. set := &TrafficRulesSet{}
  175. set.ReloadableFile = common.NewReloadableFile(
  176. filename,
  177. func(fileContent []byte) error {
  178. var newSet TrafficRulesSet
  179. err := json.Unmarshal(fileContent, &newSet)
  180. if err != nil {
  181. return common.ContextError(err)
  182. }
  183. err = newSet.Validate()
  184. if err != nil {
  185. return common.ContextError(err)
  186. }
  187. // Modify actual traffic rules only after validation
  188. set.DefaultRules = newSet.DefaultRules
  189. set.FilteredRules = newSet.FilteredRules
  190. return nil
  191. })
  192. _, err := set.Reload()
  193. if err != nil {
  194. return nil, common.ContextError(err)
  195. }
  196. return set, nil
  197. }
  198. // Validate checks for correct input formats in a TrafficRulesSet.
  199. func (set *TrafficRulesSet) Validate() error {
  200. validateTrafficRules := func(rules *TrafficRules) error {
  201. for _, subnet := range rules.AllowSubnets {
  202. _, _, err := net.ParseCIDR(subnet)
  203. if err != nil {
  204. return common.ContextError(
  205. fmt.Errorf("invalid subnet: %s %s", subnet, err))
  206. }
  207. }
  208. return nil
  209. }
  210. err := validateTrafficRules(&set.DefaultRules)
  211. if err != nil {
  212. return common.ContextError(err)
  213. }
  214. for _, filteredRule := range set.FilteredRules {
  215. for paramName := range filteredRule.Filter.HandshakeParameters {
  216. validParamName := false
  217. for _, paramSpec := range baseRequestParams {
  218. if paramSpec.name == paramName {
  219. validParamName = true
  220. break
  221. }
  222. }
  223. if !validParamName {
  224. return common.ContextError(
  225. fmt.Errorf("invalid parameter name: %s", paramName))
  226. }
  227. }
  228. err := validateTrafficRules(&filteredRule.Rules)
  229. if err != nil {
  230. return common.ContextError(err)
  231. }
  232. }
  233. return nil
  234. }
  235. // GetTrafficRules determines the traffic rules for a client based on its attributes.
  236. // For the return value TrafficRules, all pointer and slice fields are initialized,
  237. // so nil checks are not required. The caller must not modify the returned TrafficRules.
  238. func (set *TrafficRulesSet) GetTrafficRules(
  239. isFirstTunnelInSession bool,
  240. tunnelProtocol string,
  241. geoIPData GeoIPData,
  242. state handshakeState) TrafficRules {
  243. set.ReloadableFile.RLock()
  244. defer set.ReloadableFile.RUnlock()
  245. // Start with a copy of the DefaultRules, and then select the first
  246. // matching Rules from FilteredTrafficRules, taking only the explicitly
  247. // specified fields from that Rules.
  248. //
  249. // Notes:
  250. // - Scalar pointers are used in TrafficRules and RateLimits to distinguish between
  251. // omitted fields (in serialized JSON) and default values. For example, if a filtered
  252. // Rules specifies a field value of 0, this will override the default; but if the
  253. // serialized filtered rule omits the field, the default is to be retained.
  254. // - We use shallow copies and slices and scalar pointers are shared between the
  255. // return value TrafficRules, so callers must treat the return value as immutable.
  256. // This also means that these slices and pointers can remain referenced in memory even
  257. // after a hot reload.
  258. trafficRules := set.DefaultRules
  259. // Populate defaults for omitted DefaultRules fields
  260. if trafficRules.RateLimits.ReadUnthrottledBytes == nil {
  261. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  262. }
  263. if trafficRules.RateLimits.ReadBytesPerSecond == nil {
  264. trafficRules.RateLimits.ReadBytesPerSecond = new(int64)
  265. }
  266. if trafficRules.RateLimits.WriteUnthrottledBytes == nil {
  267. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  268. }
  269. if trafficRules.RateLimits.WriteBytesPerSecond == nil {
  270. trafficRules.RateLimits.WriteBytesPerSecond = new(int64)
  271. }
  272. if trafficRules.RateLimits.CloseAfterExhausted == nil {
  273. trafficRules.RateLimits.CloseAfterExhausted = new(bool)
  274. }
  275. if trafficRules.RateLimits.UnthrottleFirstTunnelOnly == nil {
  276. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = new(bool)
  277. }
  278. intPtr := func(i int) *int {
  279. return &i
  280. }
  281. if trafficRules.DialTCPPortForwardTimeoutMilliseconds == nil {
  282. trafficRules.DialTCPPortForwardTimeoutMilliseconds =
  283. intPtr(DEFAULT_DIAL_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  284. }
  285. if trafficRules.IdleTCPPortForwardTimeoutMilliseconds == nil {
  286. trafficRules.IdleTCPPortForwardTimeoutMilliseconds =
  287. intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  288. }
  289. if trafficRules.IdleUDPPortForwardTimeoutMilliseconds == nil {
  290. trafficRules.IdleUDPPortForwardTimeoutMilliseconds =
  291. intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  292. }
  293. if trafficRules.MaxTCPDialingPortForwardCount == nil {
  294. trafficRules.MaxTCPDialingPortForwardCount =
  295. intPtr(DEFAULT_MAX_TCP_DIALING_PORT_FORWARD_COUNT)
  296. }
  297. if trafficRules.MaxTCPPortForwardCount == nil {
  298. trafficRules.MaxTCPPortForwardCount =
  299. intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT)
  300. }
  301. if trafficRules.MaxUDPPortForwardCount == nil {
  302. trafficRules.MaxUDPPortForwardCount =
  303. intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT)
  304. }
  305. if trafficRules.AllowTCPPorts == nil {
  306. trafficRules.AllowTCPPorts = make([]int, 0)
  307. }
  308. if trafficRules.AllowUDPPorts == nil {
  309. trafficRules.AllowUDPPorts = make([]int, 0)
  310. }
  311. // TODO: faster lookup?
  312. for _, filteredRules := range set.FilteredRules {
  313. log.WithContextFields(LogFields{"filter": filteredRules.Filter}).Debug("filter check")
  314. if len(filteredRules.Filter.TunnelProtocols) > 0 {
  315. if !common.Contains(filteredRules.Filter.TunnelProtocols, tunnelProtocol) {
  316. continue
  317. }
  318. }
  319. if len(filteredRules.Filter.Regions) > 0 {
  320. if !common.Contains(filteredRules.Filter.Regions, geoIPData.Country) {
  321. continue
  322. }
  323. }
  324. if filteredRules.Filter.APIProtocol != "" {
  325. if !state.completed {
  326. continue
  327. }
  328. if state.apiProtocol != filteredRules.Filter.APIProtocol {
  329. continue
  330. }
  331. }
  332. if filteredRules.Filter.HandshakeParameters != nil {
  333. if !state.completed {
  334. continue
  335. }
  336. mismatch := false
  337. for name, values := range filteredRules.Filter.HandshakeParameters {
  338. clientValue, err := getStringRequestParam(state.apiParams, name)
  339. if err != nil || !common.Contains(values, clientValue) {
  340. mismatch = true
  341. break
  342. }
  343. }
  344. if mismatch {
  345. continue
  346. }
  347. }
  348. if filteredRules.Filter.AuthorizationsRevoked {
  349. if !state.completed {
  350. continue
  351. }
  352. if !state.authorizationsRevoked {
  353. continue
  354. }
  355. } else if len(filteredRules.Filter.AuthorizedAccessTypes) > 0 {
  356. if !state.completed {
  357. continue
  358. }
  359. if state.authorizationsRevoked {
  360. continue
  361. }
  362. if !common.ContainsAny(filteredRules.Filter.AuthorizedAccessTypes, state.authorizedAccessTypes) {
  363. continue
  364. }
  365. }
  366. log.WithContextFields(LogFields{"filter": filteredRules.Filter}).Debug("filter match")
  367. // This is the first match. Override defaults using provided fields from selected rules, and return result.
  368. if filteredRules.Rules.RateLimits.ReadUnthrottledBytes != nil {
  369. trafficRules.RateLimits.ReadUnthrottledBytes = filteredRules.Rules.RateLimits.ReadUnthrottledBytes
  370. }
  371. if filteredRules.Rules.RateLimits.ReadBytesPerSecond != nil {
  372. trafficRules.RateLimits.ReadBytesPerSecond = filteredRules.Rules.RateLimits.ReadBytesPerSecond
  373. }
  374. if filteredRules.Rules.RateLimits.WriteUnthrottledBytes != nil {
  375. trafficRules.RateLimits.WriteUnthrottledBytes = filteredRules.Rules.RateLimits.WriteUnthrottledBytes
  376. }
  377. if filteredRules.Rules.RateLimits.WriteBytesPerSecond != nil {
  378. trafficRules.RateLimits.WriteBytesPerSecond = filteredRules.Rules.RateLimits.WriteBytesPerSecond
  379. }
  380. if filteredRules.Rules.RateLimits.CloseAfterExhausted != nil {
  381. trafficRules.RateLimits.CloseAfterExhausted = filteredRules.Rules.RateLimits.CloseAfterExhausted
  382. }
  383. if filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly != nil {
  384. trafficRules.RateLimits.UnthrottleFirstTunnelOnly = filteredRules.Rules.RateLimits.UnthrottleFirstTunnelOnly
  385. }
  386. if filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds != nil {
  387. trafficRules.DialTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.DialTCPPortForwardTimeoutMilliseconds
  388. }
  389. if filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds != nil {
  390. trafficRules.IdleTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds
  391. }
  392. if filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds != nil {
  393. trafficRules.IdleUDPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds
  394. }
  395. if filteredRules.Rules.MaxTCPDialingPortForwardCount != nil {
  396. trafficRules.MaxTCPDialingPortForwardCount = filteredRules.Rules.MaxTCPDialingPortForwardCount
  397. }
  398. if filteredRules.Rules.MaxTCPPortForwardCount != nil {
  399. trafficRules.MaxTCPPortForwardCount = filteredRules.Rules.MaxTCPPortForwardCount
  400. }
  401. if filteredRules.Rules.MaxUDPPortForwardCount != nil {
  402. trafficRules.MaxUDPPortForwardCount = filteredRules.Rules.MaxUDPPortForwardCount
  403. }
  404. if filteredRules.Rules.AllowTCPPorts != nil {
  405. trafficRules.AllowTCPPorts = filteredRules.Rules.AllowTCPPorts
  406. }
  407. if filteredRules.Rules.AllowUDPPorts != nil {
  408. trafficRules.AllowUDPPorts = filteredRules.Rules.AllowUDPPorts
  409. }
  410. break
  411. }
  412. if *trafficRules.RateLimits.UnthrottleFirstTunnelOnly && !isFirstTunnelInSession {
  413. *trafficRules.RateLimits.ReadUnthrottledBytes = 0
  414. *trafficRules.RateLimits.WriteUnthrottledBytes = 0
  415. }
  416. log.WithContextFields(LogFields{"trafficRules": trafficRules}).Debug("selected traffic rules")
  417. return trafficRules
  418. }