trafficRules.go 14 KB

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