trafficRules.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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_MAX_TCP_PORT_FORWARD_COUNT = 512
  30. DEFAULT_MAX_UDP_PORT_FORWARD_COUNT = 32
  31. )
  32. // TrafficRulesSet represents the various traffic rules to
  33. // apply to Psiphon client tunnels. The Reload function supports
  34. // hot reloading of rules data while the server is running.
  35. //
  36. // For a given client, the traffic rules are determined by starting
  37. // with DefaultRules, then finding the first (if any)
  38. // FilteredTrafficRules match and overriding the defaults with fields
  39. // set in the selected FilteredTrafficRules.
  40. type TrafficRulesSet struct {
  41. common.ReloadableFile
  42. // DefaultRules are the base values to use as defaults for all
  43. // clients.
  44. DefaultRules TrafficRules
  45. // FilteredTrafficRules is an ordered list of filter/rules pairs.
  46. // For each client, the first matching Filter in FilteredTrafficRules
  47. // determines the additional Rules that are selected and applied
  48. // on top of DefaultRules.
  49. FilteredRules []struct {
  50. Filter TrafficRulesFilter
  51. Rules TrafficRules
  52. }
  53. }
  54. // TrafficRulesFilter defines a filter to match against client attributes.
  55. type TrafficRulesFilter struct {
  56. // TunnelProtocols is a list of client tunnel protocols that must be
  57. // in use to match this filter. When omitted or empty, any protocol
  58. // matches.
  59. TunnelProtocols []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(fileContent []byte) error {
  148. var newSet TrafficRulesSet
  149. err := json.Unmarshal(fileContent, &newSet)
  150. if err != nil {
  151. return common.ContextError(err)
  152. }
  153. err = newSet.Validate()
  154. if err != nil {
  155. return common.ContextError(err)
  156. }
  157. // Modify actual traffic rules only after validation
  158. set.DefaultRules = newSet.DefaultRules
  159. set.FilteredRules = newSet.FilteredRules
  160. return nil
  161. })
  162. _, err := set.Reload()
  163. if err != nil {
  164. return nil, common.ContextError(err)
  165. }
  166. return set, nil
  167. }
  168. // Validate checks for correct input formats in a TrafficRulesSet.
  169. func (set *TrafficRulesSet) Validate() error {
  170. validateTrafficRules := func(rules *TrafficRules) error {
  171. for _, subnet := range rules.AllowSubnets {
  172. _, _, err := net.ParseCIDR(subnet)
  173. if err != nil {
  174. return common.ContextError(
  175. fmt.Errorf("invalid subnet: %s %s", subnet, err))
  176. }
  177. }
  178. return nil
  179. }
  180. err := validateTrafficRules(&set.DefaultRules)
  181. if err != nil {
  182. return common.ContextError(err)
  183. }
  184. for _, filteredRule := range set.FilteredRules {
  185. for paramName, _ := range filteredRule.Filter.HandshakeParameters {
  186. validParamName := false
  187. for _, paramSpec := range baseRequestParams {
  188. if paramSpec.name == paramName {
  189. validParamName = true
  190. break
  191. }
  192. }
  193. if !validParamName {
  194. return common.ContextError(
  195. fmt.Errorf("invalid parameter name: %s", paramName))
  196. }
  197. }
  198. err := validateTrafficRules(&filteredRule.Rules)
  199. if err != nil {
  200. return common.ContextError(err)
  201. }
  202. }
  203. return nil
  204. }
  205. // GetTrafficRules determines the traffic rules for a client based on its attributes.
  206. // For the return value TrafficRules, all pointer and slice fields are initialized,
  207. // so nil checks are not required. The caller must not modify the returned TrafficRules.
  208. func (set *TrafficRulesSet) GetTrafficRules(
  209. tunnelProtocol string, geoIPData GeoIPData, state handshakeState) TrafficRules {
  210. set.ReloadableFile.RLock()
  211. defer set.ReloadableFile.RUnlock()
  212. // Start with a copy of the DefaultRules, and then select the first
  213. // matches Rules from FilteredTrafficRules, taking only the explicitly
  214. // specified fields from that Rules.
  215. //
  216. // Notes:
  217. // - Scalar pointers are used in TrafficRules and RateLimits to distinguish between
  218. // omitted fields (in serialized JSON) and default values. For example, if a filtered
  219. // Rules specifies a field value of 0, this will override the default; but if the
  220. // serialized filtered rule omits the field, the default is to be retained.
  221. // - We use shallow copies and slices and scalar pointers are shared between the
  222. // return value TrafficRules, so callers must treat the return value as immutable.
  223. // This also means that these slices and pointers can remain referenced in memory even
  224. // after a hot reload.
  225. trafficRules := set.DefaultRules
  226. // Populate defaults for omitted DefaultRules fields
  227. if trafficRules.RateLimits.ReadUnthrottledBytes == nil {
  228. trafficRules.RateLimits.ReadUnthrottledBytes = new(int64)
  229. }
  230. if trafficRules.RateLimits.ReadBytesPerSecond == nil {
  231. trafficRules.RateLimits.ReadBytesPerSecond = new(int64)
  232. }
  233. if trafficRules.RateLimits.WriteUnthrottledBytes == nil {
  234. trafficRules.RateLimits.WriteUnthrottledBytes = new(int64)
  235. }
  236. if trafficRules.RateLimits.WriteBytesPerSecond == nil {
  237. trafficRules.RateLimits.WriteBytesPerSecond = new(int64)
  238. }
  239. if trafficRules.RateLimits.CloseAfterExhausted == nil {
  240. trafficRules.RateLimits.CloseAfterExhausted = new(bool)
  241. }
  242. intPtr := func(i int) *int {
  243. return &i
  244. }
  245. if trafficRules.IdleTCPPortForwardTimeoutMilliseconds == nil {
  246. trafficRules.IdleTCPPortForwardTimeoutMilliseconds =
  247. intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  248. }
  249. if trafficRules.IdleUDPPortForwardTimeoutMilliseconds == nil {
  250. trafficRules.IdleUDPPortForwardTimeoutMilliseconds =
  251. intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS)
  252. }
  253. if trafficRules.MaxTCPPortForwardCount == nil {
  254. trafficRules.MaxTCPPortForwardCount =
  255. intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT)
  256. }
  257. if trafficRules.MaxUDPPortForwardCount == nil {
  258. trafficRules.MaxUDPPortForwardCount =
  259. intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT)
  260. }
  261. if trafficRules.AllowTCPPorts == nil {
  262. trafficRules.AllowTCPPorts = make([]int, 0)
  263. }
  264. if trafficRules.AllowUDPPorts == nil {
  265. trafficRules.AllowUDPPorts = make([]int, 0)
  266. }
  267. // TODO: faster lookup?
  268. for _, filteredRules := range set.FilteredRules {
  269. log.WithContextFields(LogFields{"filter": filteredRules.Filter}).Debug("filter check")
  270. if len(filteredRules.Filter.TunnelProtocols) > 0 {
  271. if !common.Contains(filteredRules.Filter.TunnelProtocols, tunnelProtocol) {
  272. continue
  273. }
  274. }
  275. if len(filteredRules.Filter.Regions) > 0 {
  276. if !common.Contains(filteredRules.Filter.Regions, geoIPData.Country) {
  277. continue
  278. }
  279. }
  280. if filteredRules.Filter.APIProtocol != "" {
  281. if !state.completed {
  282. continue
  283. }
  284. if state.apiProtocol != filteredRules.Filter.APIProtocol {
  285. continue
  286. }
  287. }
  288. if filteredRules.Filter.HandshakeParameters != nil {
  289. if !state.completed {
  290. continue
  291. }
  292. mismatch := false
  293. for name, values := range filteredRules.Filter.HandshakeParameters {
  294. clientValue, err := getStringRequestParam(state.apiParams, name)
  295. if err != nil || !common.Contains(values, clientValue) {
  296. mismatch = true
  297. break
  298. }
  299. }
  300. if mismatch {
  301. continue
  302. }
  303. }
  304. log.WithContextFields(LogFields{"filter": filteredRules.Filter}).Debug("filter match")
  305. // This is the first match. Override defaults using provided fields from selected rules, and return result.
  306. if filteredRules.Rules.RateLimits.ReadUnthrottledBytes != nil {
  307. trafficRules.RateLimits.ReadUnthrottledBytes = filteredRules.Rules.RateLimits.ReadUnthrottledBytes
  308. }
  309. if filteredRules.Rules.RateLimits.ReadBytesPerSecond != nil {
  310. trafficRules.RateLimits.ReadBytesPerSecond = filteredRules.Rules.RateLimits.ReadBytesPerSecond
  311. }
  312. if filteredRules.Rules.RateLimits.WriteUnthrottledBytes != nil {
  313. trafficRules.RateLimits.WriteUnthrottledBytes = filteredRules.Rules.RateLimits.WriteUnthrottledBytes
  314. }
  315. if filteredRules.Rules.RateLimits.WriteBytesPerSecond != nil {
  316. trafficRules.RateLimits.WriteBytesPerSecond = filteredRules.Rules.RateLimits.WriteBytesPerSecond
  317. }
  318. if filteredRules.Rules.RateLimits.CloseAfterExhausted != nil {
  319. trafficRules.RateLimits.CloseAfterExhausted = filteredRules.Rules.RateLimits.CloseAfterExhausted
  320. }
  321. if filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds != nil {
  322. trafficRules.IdleTCPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleTCPPortForwardTimeoutMilliseconds
  323. }
  324. if filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds != nil {
  325. trafficRules.IdleUDPPortForwardTimeoutMilliseconds = filteredRules.Rules.IdleUDPPortForwardTimeoutMilliseconds
  326. }
  327. if filteredRules.Rules.MaxTCPPortForwardCount != nil {
  328. trafficRules.MaxTCPPortForwardCount = filteredRules.Rules.MaxTCPPortForwardCount
  329. }
  330. if filteredRules.Rules.MaxUDPPortForwardCount != nil {
  331. trafficRules.MaxUDPPortForwardCount = filteredRules.Rules.MaxUDPPortForwardCount
  332. }
  333. if filteredRules.Rules.AllowTCPPorts != nil {
  334. trafficRules.AllowTCPPorts = filteredRules.Rules.AllowTCPPorts
  335. }
  336. if filteredRules.Rules.AllowUDPPorts != nil {
  337. trafficRules.AllowUDPPorts = filteredRules.Rules.AllowUDPPorts
  338. }
  339. break
  340. }
  341. log.WithContextFields(LogFields{"trafficRules": trafficRules}).Debug("selected traffic rules")
  342. return trafficRules
  343. }