trafficRules.go 13 KB

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