trafficRules.go 12 KB

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