trafficRules.go 15 KB

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