trafficRules.go 12 KB

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