ingress.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package ingress
  2. import (
  3. "fmt"
  4. "net"
  5. "net/url"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "github.com/pkg/errors"
  11. "github.com/rs/zerolog"
  12. "github.com/urfave/cli/v2"
  13. "github.com/cloudflare/cloudflared/config"
  14. "github.com/cloudflare/cloudflared/ipaccess"
  15. )
  16. var (
  17. ErrNoIngressRules = errors.New("The config file doesn't contain any ingress rules")
  18. errLastRuleNotCatchAll = errors.New("The last ingress rule must match all URLs (i.e. it should not have a hostname or path filter)")
  19. errBadWildcard = errors.New("Hostname patterns can have at most one wildcard character (\"*\") and it can only be used for subdomains, e.g. \"*.example.com\"")
  20. errHostnameContainsPort = errors.New("Hostname cannot contain a port")
  21. ErrURLIncompatibleWithIngress = errors.New("You can't set the --url flag (or $TUNNEL_URL) when using multiple-origin ingress rules")
  22. )
  23. const (
  24. ServiceBastion = "bastion"
  25. ServiceSocksProxy = "socks-proxy"
  26. ServiceWarpRouting = "warp-routing"
  27. )
  28. // FindMatchingRule returns the index of the Ingress Rule which matches the given
  29. // hostname and path. This function assumes the last rule matches everything,
  30. // which is the case if the rules were instantiated via the ingress#Validate method
  31. func (ing Ingress) FindMatchingRule(hostname, path string) (*Rule, int) {
  32. // The hostname might contain port. We only want to compare the host part with the rule
  33. host, _, err := net.SplitHostPort(hostname)
  34. if err == nil {
  35. hostname = host
  36. }
  37. for i, rule := range ing.Rules {
  38. if rule.Matches(hostname, path) {
  39. return &rule, i
  40. }
  41. }
  42. i := len(ing.Rules) - 1
  43. return &ing.Rules[i], i
  44. }
  45. func matchHost(ruleHost, reqHost string) bool {
  46. if ruleHost == reqHost {
  47. return true
  48. }
  49. // Validate hostnames that use wildcards at the start
  50. if strings.HasPrefix(ruleHost, "*.") {
  51. toMatch := strings.TrimPrefix(ruleHost, "*.")
  52. return strings.HasSuffix(reqHost, toMatch)
  53. }
  54. return false
  55. }
  56. // Ingress maps eyeball requests to origins.
  57. type Ingress struct {
  58. Rules []Rule
  59. defaults OriginRequestConfig
  60. }
  61. // NewSingleOrigin constructs an Ingress set with only one rule, constructed from
  62. // legacy CLI parameters like --url or --no-chunked-encoding.
  63. func NewSingleOrigin(c *cli.Context, allowURLFromArgs bool) (Ingress, error) {
  64. service, err := parseSingleOriginService(c, allowURLFromArgs)
  65. if err != nil {
  66. return Ingress{}, err
  67. }
  68. // Construct an Ingress with the single rule.
  69. defaults := originRequestFromSingeRule(c)
  70. ing := Ingress{
  71. Rules: []Rule{
  72. {
  73. Service: service,
  74. Config: setConfig(defaults, config.OriginRequestConfig{}),
  75. },
  76. },
  77. defaults: defaults,
  78. }
  79. return ing, err
  80. }
  81. // WarpRoutingService starts a tcp stream between the origin and requests from
  82. // warp clients.
  83. type WarpRoutingService struct {
  84. Proxy StreamBasedOriginProxy
  85. }
  86. func NewWarpRoutingService() *WarpRoutingService {
  87. return &WarpRoutingService{Proxy: &rawTCPService{name: ServiceWarpRouting}}
  88. }
  89. // Get a single origin service from the CLI/config.
  90. func parseSingleOriginService(c *cli.Context, allowURLFromArgs bool) (originService, error) {
  91. if c.IsSet("hello-world") {
  92. return new(helloWorld), nil
  93. }
  94. if c.IsSet(config.BastionFlag) {
  95. return newBastionService(), nil
  96. }
  97. if c.IsSet("url") {
  98. originURL, err := config.ValidateUrl(c, allowURLFromArgs)
  99. if err != nil {
  100. return nil, errors.Wrap(err, "Error validating origin URL")
  101. }
  102. if isHTTPService(originURL) {
  103. return &httpService{
  104. url: originURL,
  105. }, nil
  106. }
  107. return newTCPOverWSService(originURL), nil
  108. }
  109. if c.IsSet("unix-socket") {
  110. path, err := config.ValidateUnixSocket(c)
  111. if err != nil {
  112. return nil, errors.Wrap(err, "Error validating --unix-socket")
  113. }
  114. return &unixSocketPath{path: path}, nil
  115. }
  116. u, err := url.Parse("http://localhost:8080")
  117. return &httpService{url: u}, err
  118. }
  119. // IsEmpty checks if there are any ingress rules.
  120. func (ing Ingress) IsEmpty() bool {
  121. return len(ing.Rules) == 0
  122. }
  123. // IsSingleRule checks if the user only specified a single ingress rule.
  124. func (ing Ingress) IsSingleRule() bool {
  125. return len(ing.Rules) == 1
  126. }
  127. // StartOrigins will start any origin services managed by cloudflared, e.g. proxy servers or Hello World.
  128. func (ing Ingress) StartOrigins(
  129. wg *sync.WaitGroup,
  130. log *zerolog.Logger,
  131. shutdownC <-chan struct{},
  132. errC chan error,
  133. ) error {
  134. for _, rule := range ing.Rules {
  135. if err := rule.Service.start(wg, log, shutdownC, errC, rule.Config); err != nil {
  136. return errors.Wrapf(err, "Error starting local service %s", rule.Service)
  137. }
  138. }
  139. return nil
  140. }
  141. // CatchAll returns the catch-all rule (i.e. the last rule)
  142. func (ing Ingress) CatchAll() *Rule {
  143. return &ing.Rules[len(ing.Rules)-1]
  144. }
  145. func validate(ingress []config.UnvalidatedIngressRule, defaults OriginRequestConfig) (Ingress, error) {
  146. rules := make([]Rule, len(ingress))
  147. for i, r := range ingress {
  148. cfg := setConfig(defaults, r.OriginRequest)
  149. var service originService
  150. if prefix := "unix:"; strings.HasPrefix(r.Service, prefix) {
  151. // No validation necessary for unix socket filepath services
  152. path := strings.TrimPrefix(r.Service, prefix)
  153. service = &unixSocketPath{path: path}
  154. } else if prefix := "http_status:"; strings.HasPrefix(r.Service, prefix) {
  155. status, err := strconv.Atoi(strings.TrimPrefix(r.Service, prefix))
  156. if err != nil {
  157. return Ingress{}, errors.Wrap(err, "invalid HTTP status")
  158. }
  159. srv := newStatusCode(status)
  160. service = &srv
  161. } else if r.Service == "hello_world" || r.Service == "hello-world" || r.Service == "helloworld" {
  162. service = new(helloWorld)
  163. } else if r.Service == ServiceSocksProxy {
  164. rules := make([]ipaccess.Rule, len(r.OriginRequest.IPRules))
  165. for i, ipRule := range r.OriginRequest.IPRules {
  166. rule, err := ipaccess.NewRuleByCIDR(ipRule.Prefix, ipRule.Ports, ipRule.Allow)
  167. if err != nil {
  168. return Ingress{}, fmt.Errorf("unable to create ip rule for %s: %s", r.Service, err)
  169. }
  170. rules[i] = rule
  171. }
  172. accessPolicy, err := ipaccess.NewPolicy(false, rules)
  173. if err != nil {
  174. return Ingress{}, fmt.Errorf("unable to create ip access policy for %s: %s", r.Service, err)
  175. }
  176. service = newSocksProxyOverWSService(accessPolicy)
  177. } else if r.Service == ServiceBastion || cfg.BastionMode {
  178. // Bastion mode will always start a Websocket proxy server, which will
  179. // overwrite the localService.URL field when `start` is called. So,
  180. // leave the URL field empty for now.
  181. cfg.BastionMode = true
  182. service = newBastionService()
  183. } else {
  184. // Validate URL services
  185. u, err := url.Parse(r.Service)
  186. if err != nil {
  187. return Ingress{}, err
  188. }
  189. if u.Scheme == "" || u.Hostname() == "" {
  190. return Ingress{}, fmt.Errorf("%s is an invalid address, please make sure it has a scheme and a hostname", r.Service)
  191. }
  192. if u.Path != "" {
  193. return Ingress{}, fmt.Errorf("%s is an invalid address, ingress rules don't support proxying to a different path on the origin service. The path will be the same as the eyeball request's path", r.Service)
  194. }
  195. if isHTTPService(u) {
  196. service = &httpService{url: u}
  197. } else {
  198. service = newTCPOverWSService(u)
  199. }
  200. }
  201. if err := validateHostname(r, i, len(ingress)); err != nil {
  202. return Ingress{}, err
  203. }
  204. var pathRegex *regexp.Regexp
  205. if r.Path != "" {
  206. var err error
  207. pathRegex, err = regexp.Compile(r.Path)
  208. if err != nil {
  209. return Ingress{}, errors.Wrapf(err, "Rule #%d has an invalid regex", i+1)
  210. }
  211. }
  212. rules[i] = Rule{
  213. Hostname: r.Hostname,
  214. Service: service,
  215. Path: pathRegex,
  216. Config: cfg,
  217. }
  218. }
  219. return Ingress{Rules: rules, defaults: defaults}, nil
  220. }
  221. func validateHostname(r config.UnvalidatedIngressRule, ruleIndex, totalRules int) error {
  222. // Ensure that the hostname doesn't contain port
  223. _, _, err := net.SplitHostPort(r.Hostname)
  224. if err == nil {
  225. return errHostnameContainsPort
  226. }
  227. // Ensure that there are no wildcards anywhere except the first character
  228. // of the hostname.
  229. if strings.LastIndex(r.Hostname, "*") > 0 {
  230. return errBadWildcard
  231. }
  232. // The last rule should catch all hostnames.
  233. isCatchAllRule := (r.Hostname == "" || r.Hostname == "*") && r.Path == ""
  234. isLastRule := ruleIndex == totalRules-1
  235. if isLastRule && !isCatchAllRule {
  236. return errLastRuleNotCatchAll
  237. }
  238. // ONLY the last rule should catch all hostnames.
  239. if !isLastRule && isCatchAllRule {
  240. return errRuleShouldNotBeCatchAll{index: ruleIndex, hostname: r.Hostname}
  241. }
  242. return nil
  243. }
  244. type errRuleShouldNotBeCatchAll struct {
  245. index int
  246. hostname string
  247. }
  248. func (e errRuleShouldNotBeCatchAll) Error() string {
  249. return fmt.Sprintf("Rule #%d is matching the hostname '%s', but "+
  250. "this will match every hostname, meaning the rules which follow it "+
  251. "will never be triggered.", e.index+1, e.hostname)
  252. }
  253. // ParseIngress parses ingress rules, but does not send HTTP requests to the origins.
  254. func ParseIngress(conf *config.Configuration) (Ingress, error) {
  255. if len(conf.Ingress) == 0 {
  256. return Ingress{}, ErrNoIngressRules
  257. }
  258. return validate(conf.Ingress, originRequestFromYAML(conf.OriginRequest))
  259. }
  260. func isHTTPService(url *url.URL) bool {
  261. return url.Scheme == "http" || url.Scheme == "https" || url.Scheme == "ws" || url.Scheme == "wss"
  262. }