trafficRules.go 16 KB

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