ingress.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package ingress
  2. import (
  3. "fmt"
  4. "net"
  5. "net/url"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "github.com/cloudflare/cloudflared/config"
  11. "github.com/cloudflare/cloudflared/ipaccess"
  12. "github.com/pkg/errors"
  13. "github.com/rs/zerolog"
  14. "github.com/urfave/cli/v2"
  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. // StartOrigins will start any origin services managed by cloudflared, e.g. proxy servers or Hello World.
  124. func (ing Ingress) StartOrigins(
  125. wg *sync.WaitGroup,
  126. log *zerolog.Logger,
  127. shutdownC <-chan struct{},
  128. errC chan error,
  129. ) error {
  130. for _, rule := range ing.Rules {
  131. if err := rule.Service.start(wg, log, shutdownC, errC, rule.Config); err != nil {
  132. return errors.Wrapf(err, "Error starting local service %s", rule.Service)
  133. }
  134. }
  135. return nil
  136. }
  137. // CatchAll returns the catch-all rule (i.e. the last rule)
  138. func (ing Ingress) CatchAll() *Rule {
  139. return &ing.Rules[len(ing.Rules)-1]
  140. }
  141. func validate(ingress []config.UnvalidatedIngressRule, defaults OriginRequestConfig) (Ingress, error) {
  142. rules := make([]Rule, len(ingress))
  143. for i, r := range ingress {
  144. cfg := setConfig(defaults, r.OriginRequest)
  145. var service originService
  146. if prefix := "unix:"; strings.HasPrefix(r.Service, prefix) {
  147. // No validation necessary for unix socket filepath services
  148. path := strings.TrimPrefix(r.Service, prefix)
  149. service = &unixSocketPath{path: path}
  150. } else if prefix := "http_status:"; strings.HasPrefix(r.Service, prefix) {
  151. status, err := strconv.Atoi(strings.TrimPrefix(r.Service, prefix))
  152. if err != nil {
  153. return Ingress{}, errors.Wrap(err, "invalid HTTP status")
  154. }
  155. srv := newStatusCode(status)
  156. service = &srv
  157. } else if r.Service == "hello_world" || r.Service == "hello-world" || r.Service == "helloworld" {
  158. service = new(helloWorld)
  159. } else if r.Service == ServiceSocksProxy {
  160. rules := make([]ipaccess.Rule, len(r.OriginRequest.IPRules))
  161. for i, ipRule := range r.OriginRequest.IPRules {
  162. rule, err := ipaccess.NewRuleByCIDR(ipRule.Prefix, ipRule.Ports, ipRule.Allow)
  163. if err != nil {
  164. return Ingress{}, fmt.Errorf("unable to create ip rule for %s: %s", r.Service, err)
  165. }
  166. rules[i] = rule
  167. }
  168. accessPolicy, err := ipaccess.NewPolicy(false, rules)
  169. if err != nil {
  170. return Ingress{}, fmt.Errorf("unable to create ip access policy for %s: %s", r.Service, err)
  171. }
  172. service = newSocksProxyOverWSService(accessPolicy)
  173. } else if r.Service == ServiceBastion || cfg.BastionMode {
  174. // Bastion mode will always start a Websocket proxy server, which will
  175. // overwrite the localService.URL field when `start` is called. So,
  176. // leave the URL field empty for now.
  177. cfg.BastionMode = true
  178. service = newBastionService()
  179. } else {
  180. // Validate URL services
  181. u, err := url.Parse(r.Service)
  182. if err != nil {
  183. return Ingress{}, err
  184. }
  185. if u.Scheme == "" || u.Hostname() == "" {
  186. return Ingress{}, fmt.Errorf("%s is an invalid address, please make sure it has a scheme and a hostname", r.Service)
  187. }
  188. if u.Path != "" {
  189. 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)
  190. }
  191. if isHTTPService(u) {
  192. service = &httpService{url: u}
  193. } else {
  194. service = newTCPOverWSService(u)
  195. }
  196. }
  197. if err := validateHostname(r, i, len(ingress)); err != nil {
  198. return Ingress{}, err
  199. }
  200. var pathRegex *regexp.Regexp
  201. if r.Path != "" {
  202. var err error
  203. pathRegex, err = regexp.Compile(r.Path)
  204. if err != nil {
  205. return Ingress{}, errors.Wrapf(err, "Rule #%d has an invalid regex", i+1)
  206. }
  207. }
  208. rules[i] = Rule{
  209. Hostname: r.Hostname,
  210. Service: service,
  211. Path: pathRegex,
  212. Config: cfg,
  213. }
  214. }
  215. return Ingress{Rules: rules, defaults: defaults}, nil
  216. }
  217. func validateHostname(r config.UnvalidatedIngressRule, ruleIndex, totalRules int) error {
  218. // Ensure that the hostname doesn't contain port
  219. _, _, err := net.SplitHostPort(r.Hostname)
  220. if err == nil {
  221. return errHostnameContainsPort
  222. }
  223. // Ensure that there are no wildcards anywhere except the first character
  224. // of the hostname.
  225. if strings.LastIndex(r.Hostname, "*") > 0 {
  226. return errBadWildcard
  227. }
  228. // The last rule should catch all hostnames.
  229. isCatchAllRule := (r.Hostname == "" || r.Hostname == "*") && r.Path == ""
  230. isLastRule := ruleIndex == totalRules-1
  231. if isLastRule && !isCatchAllRule {
  232. return errLastRuleNotCatchAll
  233. }
  234. // ONLY the last rule should catch all hostnames.
  235. if !isLastRule && isCatchAllRule {
  236. return errRuleShouldNotBeCatchAll{index: ruleIndex, hostname: r.Hostname}
  237. }
  238. return nil
  239. }
  240. type errRuleShouldNotBeCatchAll struct {
  241. index int
  242. hostname string
  243. }
  244. func (e errRuleShouldNotBeCatchAll) Error() string {
  245. return fmt.Sprintf("Rule #%d is matching the hostname '%s', but "+
  246. "this will match every hostname, meaning the rules which follow it "+
  247. "will never be triggered.", e.index+1, e.hostname)
  248. }
  249. // ParseIngress parses ingress rules, but does not send HTTP requests to the origins.
  250. func ParseIngress(conf *config.Configuration) (Ingress, error) {
  251. if len(conf.Ingress) == 0 {
  252. return Ingress{}, ErrNoIngressRules
  253. }
  254. return validate(conf.Ingress, originRequestFromYAML(conf.OriginRequest))
  255. }
  256. func isHTTPService(url *url.URL) bool {
  257. return url.Scheme == "http" || url.Scheme == "https" || url.Scheme == "ws" || url.Scheme == "wss"
  258. }