validation.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package validation
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "net/url"
  7. "strings"
  8. "time"
  9. "net/http"
  10. "github.com/pkg/errors"
  11. "golang.org/x/net/idna"
  12. "gopkg.in/coreos/go-oidc.v2"
  13. )
  14. const (
  15. defaultScheme = "http"
  16. accessDomain = "cloudflareaccess.com"
  17. accessCertPath = "/cdn-cgi/access/certs"
  18. accessJwtHeader = "Cf-access-jwt-assertion"
  19. )
  20. var (
  21. supportedProtocols = []string{"http", "https", "rdp", "ssh", "smb", "tcp"}
  22. validationTimeout = time.Duration(30 * time.Second)
  23. )
  24. func ValidateHostname(hostname string) (string, error) {
  25. if hostname == "" {
  26. return "", nil
  27. }
  28. // users gives url(contains schema) not just hostname
  29. if strings.Contains(hostname, ":") || strings.Contains(hostname, "%3A") {
  30. unescapeHostname, err := url.PathUnescape(hostname)
  31. if err != nil {
  32. return "", fmt.Errorf("Hostname(actually a URL) %s has invalid escape characters %s", hostname, unescapeHostname)
  33. }
  34. hostnameToURL, err := url.Parse(unescapeHostname)
  35. if err != nil {
  36. return "", fmt.Errorf("Hostname(actually a URL) %s has invalid format %s", hostname, hostnameToURL)
  37. }
  38. asciiHostname, err := idna.ToASCII(hostnameToURL.Hostname())
  39. if err != nil {
  40. return "", fmt.Errorf("Hostname(actually a URL) %s has invalid ASCII encdoing %s", hostname, asciiHostname)
  41. }
  42. return asciiHostname, nil
  43. }
  44. asciiHostname, err := idna.ToASCII(hostname)
  45. if err != nil {
  46. return "", fmt.Errorf("Hostname %s has invalid ASCII encdoing %s", hostname, asciiHostname)
  47. }
  48. hostnameToURL, err := url.Parse(asciiHostname)
  49. if err != nil {
  50. return "", fmt.Errorf("Hostname %s is not valid", hostnameToURL)
  51. }
  52. return hostnameToURL.RequestURI(), nil
  53. }
  54. // ValidateUrl returns a validated version of `originUrl` with a scheme prepended (by default http://).
  55. // Note: when originUrl contains a scheme, the path is removed:
  56. // ValidateUrl("https://localhost:8080/api/") => "https://localhost:8080"
  57. // but when it does not, the path is preserved:
  58. // ValidateUrl("localhost:8080/api/") => "http://localhost:8080/api/"
  59. // This is arguably a bug, but changing it might break some cloudflared users.
  60. func ValidateUrl(originUrl string) (string, error) {
  61. if originUrl == "" {
  62. return "", fmt.Errorf("URL should not be empty")
  63. }
  64. if net.ParseIP(originUrl) != nil {
  65. return validateIP("", originUrl, "")
  66. } else if strings.HasPrefix(originUrl, "[") && strings.HasSuffix(originUrl, "]") {
  67. // ParseIP doesn't recoginze [::1]
  68. return validateIP("", originUrl[1:len(originUrl)-1], "")
  69. }
  70. host, port, err := net.SplitHostPort(originUrl)
  71. // user might pass in an ip address like 127.0.0.1
  72. if err == nil && net.ParseIP(host) != nil {
  73. return validateIP("", host, port)
  74. }
  75. unescapedUrl, err := url.PathUnescape(originUrl)
  76. if err != nil {
  77. return "", fmt.Errorf("URL %s has invalid escape characters %s", originUrl, unescapedUrl)
  78. }
  79. parsedUrl, err := url.Parse(unescapedUrl)
  80. if err != nil {
  81. return "", fmt.Errorf("URL %s has invalid format", originUrl)
  82. }
  83. // if the url is in the form of host:port, IsAbs() will think host is the schema
  84. var hostname string
  85. hasScheme := parsedUrl.IsAbs() && parsedUrl.Host != ""
  86. if hasScheme {
  87. err := validateScheme(parsedUrl.Scheme)
  88. if err != nil {
  89. return "", err
  90. }
  91. // The earlier check for ip address will miss the case http://[::1]
  92. // and http://[::1]:8080
  93. if net.ParseIP(parsedUrl.Hostname()) != nil {
  94. return validateIP(parsedUrl.Scheme, parsedUrl.Hostname(), parsedUrl.Port())
  95. }
  96. hostname, err = ValidateHostname(parsedUrl.Hostname())
  97. if err != nil {
  98. return "", fmt.Errorf("URL %s has invalid format", originUrl)
  99. }
  100. if parsedUrl.Port() != "" {
  101. return fmt.Sprintf("%s://%s", parsedUrl.Scheme, net.JoinHostPort(hostname, parsedUrl.Port())), nil
  102. }
  103. return fmt.Sprintf("%s://%s", parsedUrl.Scheme, hostname), nil
  104. } else {
  105. if host == "" {
  106. hostname, err = ValidateHostname(originUrl)
  107. if err != nil {
  108. return "", fmt.Errorf("URL no %s has invalid format", originUrl)
  109. }
  110. return fmt.Sprintf("%s://%s", defaultScheme, hostname), nil
  111. } else {
  112. hostname, err = ValidateHostname(host)
  113. if err != nil {
  114. return "", fmt.Errorf("URL %s has invalid format", originUrl)
  115. }
  116. // This is why the path is preserved when `originUrl` doesn't have a schema.
  117. // Using `parsedUrl.Port()` here, instead of `port`, would remove the path
  118. return fmt.Sprintf("%s://%s", defaultScheme, net.JoinHostPort(hostname, port)), nil
  119. }
  120. }
  121. }
  122. func validateScheme(scheme string) error {
  123. for _, protocol := range supportedProtocols {
  124. if scheme == protocol {
  125. return nil
  126. }
  127. }
  128. return fmt.Errorf("Currently Argo Tunnel does not support %s protocol.", scheme)
  129. }
  130. func validateIP(scheme, host, port string) (string, error) {
  131. if scheme == "" {
  132. scheme = defaultScheme
  133. }
  134. if port != "" {
  135. return fmt.Sprintf("%s://%s", scheme, net.JoinHostPort(host, port)), nil
  136. } else if strings.Contains(host, ":") {
  137. // IPv6
  138. return fmt.Sprintf("%s://[%s]", scheme, host), nil
  139. }
  140. return fmt.Sprintf("%s://%s", scheme, host), nil
  141. }
  142. func ValidateHTTPService(originURL string, hostname string, transport http.RoundTripper) error {
  143. parsedURL, err := url.Parse(originURL)
  144. if err != nil {
  145. return err
  146. }
  147. client := &http.Client{
  148. Transport: transport,
  149. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  150. return http.ErrUseLastResponse
  151. },
  152. Timeout: validationTimeout,
  153. }
  154. initialRequest, err := http.NewRequest("GET", parsedURL.String(), nil)
  155. if err != nil {
  156. return err
  157. }
  158. initialRequest.Host = hostname
  159. _, initialErr := client.Do(initialRequest)
  160. if initialErr != nil {
  161. // Attempt the same endpoint via the other protocol (http/https); maybe we have better luck?
  162. oldScheme := parsedURL.Scheme
  163. parsedURL.Scheme = toggleProtocol(parsedURL.Scheme)
  164. secondRequest, err := http.NewRequest("GET", parsedURL.String(), nil)
  165. if err != nil {
  166. return err
  167. }
  168. secondRequest.Host = hostname
  169. _, secondErr := client.Do(secondRequest)
  170. if secondErr == nil { // Worked this time--advise the user to switch protocols
  171. return errors.Errorf(
  172. "%s doesn't seem to work over %s, but does seem to work over %s. Reason: %v. Consider changing the origin URL to %s",
  173. parsedURL.Host,
  174. oldScheme,
  175. parsedURL.Scheme,
  176. initialErr,
  177. parsedURL,
  178. )
  179. }
  180. }
  181. return initialErr
  182. }
  183. func toggleProtocol(httpProtocol string) string {
  184. switch httpProtocol {
  185. case "http":
  186. return "https"
  187. case "https":
  188. return "http"
  189. default:
  190. return httpProtocol
  191. }
  192. }
  193. // Access checks if a JWT from Cloudflare Access is valid.
  194. type Access struct {
  195. verifier *oidc.IDTokenVerifier
  196. }
  197. func NewAccessValidator(ctx context.Context, domain, issuer, applicationAUD string) (*Access, error) {
  198. domainURL, err := ValidateUrl(domain)
  199. if err != nil {
  200. return nil, err
  201. }
  202. issuerURL, err := ValidateUrl(issuer)
  203. if err != nil {
  204. return nil, err
  205. }
  206. // An issuerURL from Cloudflare Access will always use HTTPS.
  207. issuerURL = strings.Replace(issuerURL, "http:", "https:", 1)
  208. keySet := oidc.NewRemoteKeySet(ctx, domainURL+accessCertPath)
  209. return &Access{oidc.NewVerifier(issuerURL, keySet, &oidc.Config{ClientID: applicationAUD})}, nil
  210. }
  211. func (a *Access) Validate(ctx context.Context, jwt string) error {
  212. token, err := a.verifier.Verify(ctx, jwt)
  213. if err != nil {
  214. return errors.Wrapf(err, "token is invalid: %s", jwt)
  215. }
  216. // Perform extra sanity checks, just to be safe.
  217. if token == nil {
  218. return fmt.Errorf("token is nil: %s", jwt)
  219. }
  220. if !strings.HasSuffix(token.Issuer, accessDomain) {
  221. return fmt.Errorf("token has non-cloudflare issuer of %s: %s", token.Issuer, jwt)
  222. }
  223. return nil
  224. }
  225. func (a *Access) ValidateRequest(ctx context.Context, r *http.Request) error {
  226. return a.Validate(ctx, r.Header.Get(accessJwtHeader))
  227. }