git.iko.soy/typeable/oauth2-proxy
on remove-gap-headers help sign in
416 lines 13 kB history raw
1package validation
3import (
4 "context"
5 "crypto"
6 "crypto/tls"
7 "fmt"
8 "io/ioutil"
9 "net/http"
10 "net/url"
11 "os"
12 "regexp"
13 "strings"
15 "github.com/coreos/go-oidc"
16 "github.com/dgrijalva/jwt-go"
17 "github.com/mbland/hmacauth"
18 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
19 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/ip"
20 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
21 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
22 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/util"
23 "github.com/oauth2-proxy/oauth2-proxy/v7/providers"
26// Validate checks that required options are set and validates those that they
27// are of the correct format
28func Validate(o *options.Options) error {
29 msgs := validateCookie(o.Cookie)
30 msgs = append(msgs, validateSessionCookieMinimal(o)...)
31 msgs = append(msgs, validateRedisSessionStore(o)...)
33 if o.SSLInsecureSkipVerify {
34 // InsecureSkipVerify is a configurable option we allow
35 /* #nosec G402 */
36 insecureTransport := &http.Transport{
37 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
38 }
39 http.DefaultClient = &http.Client{Transport: insecureTransport}
40 } else if len(o.ProviderCAFiles) > 0 {
41 pool, err := util.GetCertPool(o.ProviderCAFiles)
42 if err == nil {
43 transport := &http.Transport{
44 TLSClientConfig: &tls.Config{
45 RootCAs: pool,
46 },
47 }
49 http.DefaultClient = &http.Client{Transport: transport}
50 } else {
51 msgs = append(msgs, fmt.Sprintf("unable to load provider CA file(s): %v", err))
52 }
53 }
55 if o.ClientID == "" {
56 msgs = append(msgs, "missing setting: client-id")
57 }
58 // login.gov uses a signed JWT to authenticate, not a client-secret
59 if o.ProviderType != "login.gov" {
60 if o.ClientSecret == "" && o.ClientSecretFile == "" {
61 msgs = append(msgs, "missing setting: client-secret or client-secret-file")
62 }
63 if o.ClientSecret == "" && o.ClientSecretFile != "" {
64 _, err := ioutil.ReadFile(o.ClientSecretFile)
65 if err != nil {
66 msgs = append(msgs, "could not read client secret file: "+o.ClientSecretFile)
67 }
68 }
69 }
70 if o.AuthenticatedEmailsFile == "" && len(o.EmailDomains) == 0 && o.HtpasswdFile == "" {
71 msgs = append(msgs, "missing setting for email validation: email-domain or authenticated-emails-file required."+
72 "\n use email-domain=* to authorize all email addresses")
73 }
75 if o.OIDCIssuerURL != "" {
77 ctx := context.Background()
79 if o.InsecureOIDCSkipIssuerVerification && !o.SkipOIDCDiscovery {
80 // go-oidc doesn't let us pass bypass the issuer check this in the oidc.NewProvider call
81 // (which uses discovery to get the URLs), so we'll do a quick check ourselves and if
82 // we get the URLs, we'll just use the non-discovery path.
84 logger.Printf("Performing OIDC Discovery...")
86 requestURL := strings.TrimSuffix(o.OIDCIssuerURL, "/") + "/.well-known/openid-configuration"
87 body, err := requests.New(requestURL).
88 WithContext(ctx).
89 Do().
90 UnmarshalJSON()
91 if err != nil {
92 logger.Errorf("error: failed to discover OIDC configuration: %v", err)
93 } else {
94 // Prefer manually configured URLs. It's a bit unclear
95 // why you'd be doing discovery and also providing the URLs
96 // explicitly though...
97 if o.LoginURL == "" {
98 o.LoginURL = body.Get("authorization_endpoint").MustString()
99 }
101 if o.RedeemURL == "" {
102 o.RedeemURL = body.Get("token_endpoint").MustString()
103 }
105 if o.OIDCJwksURL == "" {
106 o.OIDCJwksURL = body.Get("jwks_uri").MustString()
107 }
109 if o.ProfileURL == "" {
110 o.ProfileURL = body.Get("userinfo_endpoint").MustString()
111 }
113 o.SkipOIDCDiscovery = true
114 }
115 }
117 // Construct a manual IDTokenVerifier from issuer URL & JWKS URI
118 // instead of metadata discovery if we enable -skip-oidc-discovery.
119 // In this case we need to make sure the required endpoints for
120 // the provider are configured.
121 if o.SkipOIDCDiscovery {
122 if o.LoginURL == "" {
123 msgs = append(msgs, "missing setting: login-url")
124 }
125 if o.RedeemURL == "" {
126 msgs = append(msgs, "missing setting: redeem-url")
127 }
128 if o.OIDCJwksURL == "" {
129 msgs = append(msgs, "missing setting: oidc-jwks-url")
130 }
131 keySet := oidc.NewRemoteKeySet(ctx, o.OIDCJwksURL)
132 o.SetOIDCVerifier(oidc.NewVerifier(o.OIDCIssuerURL, keySet, &oidc.Config{
133 ClientID: o.ClientID,
134 SkipIssuerCheck: o.InsecureOIDCSkipIssuerVerification,
135 }))
136 } else {
137 // Configure discoverable provider data.
138 provider, err := oidc.NewProvider(ctx, o.OIDCIssuerURL)
139 if err != nil {
140 return err
141 }
142 o.SetOIDCVerifier(provider.Verifier(&oidc.Config{
143 ClientID: o.ClientID,
144 SkipIssuerCheck: o.InsecureOIDCSkipIssuerVerification,
145 }))
147 o.LoginURL = provider.Endpoint().AuthURL
148 o.RedeemURL = provider.Endpoint().TokenURL
149 }
150 if o.Scope == "" {
151 o.Scope = "openid email profile"
153 if len(o.AllowedGroups) > 0 {
154 o.Scope += " groups"
155 }
156 }
157 }
159 if o.SkipJwtBearerTokens {
160 // Configure extra issuers
161 if len(o.ExtraJwtIssuers) > 0 {
162 var jwtIssuers []jwtIssuer
163 jwtIssuers, msgs = parseJwtIssuers(o.ExtraJwtIssuers, msgs)
164 for _, jwtIssuer := range jwtIssuers {
165 verifier, err := newVerifierFromJwtIssuer(jwtIssuer)
166 if err != nil {
167 msgs = append(msgs, fmt.Sprintf("error building verifiers: %s", err))
168 }
169 o.SetJWTBearerVerifiers(append(o.GetJWTBearerVerifiers(), verifier))
170 }
171 }
172 }
174 var redirectURL *url.URL
175 redirectURL, msgs = parseURL(o.RawRedirectURL, "redirect", msgs)
176 o.SetRedirectURL(redirectURL)
178 msgs = append(msgs, validateUpstreams(o.UpstreamServers)...)
180 for _, u := range o.SkipAuthRegex {
181 compiledRegex, err := regexp.Compile(u)
182 if err != nil {
183 msgs = append(msgs, fmt.Sprintf("error compiling regex=%q %s", u, err))
184 continue
185 }
186 o.SetCompiledRegex(append(o.GetCompiledRegex(), compiledRegex))
187 }
188 msgs = parseProviderInfo(o, msgs)
190 if len(o.GoogleGroups) > 0 || o.GoogleAdminEmail != "" || o.GoogleServiceAccountJSON != "" {
191 if len(o.GoogleGroups) < 1 {
192 msgs = append(msgs, "missing setting: google-group")
193 }
194 if o.GoogleAdminEmail == "" {
195 msgs = append(msgs, "missing setting: google-admin-email")
196 }
197 if o.GoogleServiceAccountJSON == "" {
198 msgs = append(msgs, "missing setting: google-service-account-json")
199 }
200 }
202 msgs = parseSignatureKey(o, msgs)
203 msgs = configureLogger(o.Logging, msgs)
205 if o.ReverseProxy {
206 parser, err := ip.GetRealClientIPParser(o.RealClientIPHeader)
207 if err != nil {
208 msgs = append(msgs, fmt.Sprintf("real_client_ip_header (%s) not accepted parameter value: %v", o.RealClientIPHeader, err))
209 }
210 o.SetRealClientIPParser(parser)
212 // Allow the logger to get client IPs
213 logger.SetGetClientFunc(func(r *http.Request) string {
214 return ip.GetClientString(o.GetRealClientIPParser(), r, false)
215 })
216 }
218 if len(o.TrustedIPs) > 0 && o.ReverseProxy {
219 _, err := fmt.Fprintln(os.Stderr, "WARNING: trusting of IPs with --reverse-proxy poses risks if a header spoofing attack is possible.")
220 if err != nil {
221 panic(err)
222 }
223 }
225 for i, ipStr := range o.TrustedIPs {
226 if nil == ip.ParseIPNet(ipStr) {
227 msgs = append(msgs, fmt.Sprintf("trusted_ips[%d] (%s) could not be recognized", i, ipStr))
228 }
229 }
231 if len(msgs) != 0 {
232 return fmt.Errorf("invalid configuration:\n %s",
233 strings.Join(msgs, "\n "))
234 }
235 return nil
238func parseProviderInfo(o *options.Options, msgs []string) []string {
239 p := &providers.ProviderData{
240 Scope: o.Scope,
241 ClientID: o.ClientID,
242 ClientSecret: o.ClientSecret,
243 ClientSecretFile: o.ClientSecretFile,
244 Prompt: o.Prompt,
245 ApprovalPrompt: o.ApprovalPrompt,
246 AcrValues: o.AcrValues,
247 }
248 p.LoginURL, msgs = parseURL(o.LoginURL, "login", msgs)
249 p.RedeemURL, msgs = parseURL(o.RedeemURL, "redeem", msgs)
250 p.ProfileURL, msgs = parseURL(o.ProfileURL, "profile", msgs)
251 p.ValidateURL, msgs = parseURL(o.ValidateURL, "validate", msgs)
252 p.ProtectedResource, msgs = parseURL(o.ProtectedResource, "resource", msgs)
254 o.SetProvider(providers.New(o.ProviderType, p))
255 switch p := o.GetProvider().(type) {
256 case *providers.AzureProvider:
257 p.Configure(o.AzureTenant)
258 case *providers.GitHubProvider:
259 p.SetOrgTeam(o.GitHubOrg, o.GitHubTeam)
260 p.SetRepo(o.GitHubRepo, o.GitHubToken)
261 p.SetUsers(o.GitHubUsers)
262 case *providers.KeycloakProvider:
263 p.SetGroup(o.KeycloakGroup)
264 case *providers.GoogleProvider:
265 if o.GoogleServiceAccountJSON != "" {
266 file, err := os.Open(o.GoogleServiceAccountJSON)
267 if err != nil {
268 msgs = append(msgs, "invalid Google credentials file: "+o.GoogleServiceAccountJSON)
269 } else {
270 p.SetGroupRestriction(o.GoogleGroups, o.GoogleAdminEmail, file)
271 }
272 }
273 case *providers.BitbucketProvider:
274 p.SetTeam(o.BitbucketTeam)
275 p.SetRepository(o.BitbucketRepository)
276 case *providers.OIDCProvider:
277 p.AllowUnverifiedEmail = o.InsecureOIDCAllowUnverifiedEmail
278 p.UserIDClaim = o.UserIDClaim
279 p.GroupsClaim = o.OIDCGroupsClaim
280 if o.GetOIDCVerifier() == nil {
281 msgs = append(msgs, "oidc provider requires an oidc issuer URL")
282 } else {
283 p.Verifier = o.GetOIDCVerifier()
284 }
285 case *providers.GitLabProvider:
286 p.AllowUnverifiedEmail = o.InsecureOIDCAllowUnverifiedEmail
287 p.Groups = o.GitLabGroup
288 p.EmailDomains = o.EmailDomains
290 if o.GetOIDCVerifier() != nil {
291 p.Verifier = o.GetOIDCVerifier()
292 } else {
293 // Initialize with default verifier for gitlab.com
294 ctx := context.Background()
296 provider, err := oidc.NewProvider(ctx, "https://gitlab.com")
297 if err != nil {
298 msgs = append(msgs, "failed to initialize oidc provider for gitlab.com")
299 } else {
300 p.Verifier = provider.Verifier(&oidc.Config{
301 ClientID: o.ClientID,
302 })
304 p.LoginURL, msgs = parseURL(provider.Endpoint().AuthURL, "login", msgs)
305 p.RedeemURL, msgs = parseURL(provider.Endpoint().TokenURL, "redeem", msgs)
306 }
307 }
308 case *providers.LoginGovProvider:
309 p.PubJWKURL, msgs = parseURL(o.PubJWKURL, "pubjwk", msgs)
311 // JWT key can be supplied via env variable or file in the filesystem, but not both.
312 switch {
313 case o.JWTKey != "" && o.JWTKeyFile != "":
314 msgs = append(msgs, "cannot set both jwt-key and jwt-key-file options")
315 case o.JWTKey == "" && o.JWTKeyFile == "":
316 msgs = append(msgs, "login.gov provider requires a private key for signing JWTs")
317 case o.JWTKey != "":
318 // The JWT Key is in the commandline argument
319 signKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(o.JWTKey))
320 if err != nil {
321 msgs = append(msgs, "could not parse RSA Private Key PEM")
322 } else {
323 p.JWTKey = signKey
324 }
325 case o.JWTKeyFile != "":
326 // The JWT key is in the filesystem
327 keyData, err := ioutil.ReadFile(o.JWTKeyFile)
328 if err != nil {
329 msgs = append(msgs, "could not read key file: "+o.JWTKeyFile)
330 }
331 signKey, err := jwt.ParseRSAPrivateKeyFromPEM(keyData)
332 if err != nil {
333 msgs = append(msgs, "could not parse private key from PEM file:"+o.JWTKeyFile)
334 } else {
335 p.JWTKey = signKey
336 }
337 }
338 }
339 return msgs
342func parseSignatureKey(o *options.Options, msgs []string) []string {
343 if o.SignatureKey == "" {
344 return msgs
345 }
347 components := strings.Split(o.SignatureKey, ":")
348 if len(components) != 2 {
349 return append(msgs, "invalid signature hash:key spec: "+
350 o.SignatureKey)
351 }
353 algorithm, secretKey := components[0], components[1]
354 var hash crypto.Hash
355 var err error
356 if hash, err = hmacauth.DigestNameToCryptoHash(algorithm); err != nil {
357 return append(msgs, "unsupported signature hash algorithm: "+
358 o.SignatureKey)
359 }
360 o.SetSignatureData(&options.SignatureData{Hash: hash, Key: secretKey})
361 return msgs
364// parseJwtIssuers takes in an array of strings in the form of issuer=audience
365// and parses to an array of jwtIssuer structs.
366func parseJwtIssuers(issuers []string, msgs []string) ([]jwtIssuer, []string) {
367 parsedIssuers := make([]jwtIssuer, 0, len(issuers))
368 for _, jwtVerifier := range issuers {
369 components := strings.Split(jwtVerifier, "=")
370 if len(components) < 2 {
371 msgs = append(msgs, fmt.Sprintf("invalid jwt verifier uri=audience spec: %s", jwtVerifier))
372 continue
373 }
374 uri, audience := components[0], strings.Join(components[1:], "=")
375 parsedIssuers = append(parsedIssuers, jwtIssuer{issuerURI: uri, audience: audience})
376 }
377 return parsedIssuers, msgs
380// newVerifierFromJwtIssuer takes in issuer information in jwtIssuer info and returns
381// a verifier for that issuer.
382func newVerifierFromJwtIssuer(jwtIssuer jwtIssuer) (*oidc.IDTokenVerifier, error) {
383 config := &oidc.Config{
384 ClientID: jwtIssuer.audience,
385 }
386 // Try as an OpenID Connect Provider first
387 var verifier *oidc.IDTokenVerifier
388 provider, err := oidc.NewProvider(context.Background(), jwtIssuer.issuerURI)
389 if err != nil {
390 // Try as JWKS URI
391 jwksURI := strings.TrimSuffix(jwtIssuer.issuerURI, "/") + "/.well-known/jwks.json"
392 if err := requests.New(jwksURI).Do().Error(); err != nil {
393 return nil, err
394 }
396 verifier = oidc.NewVerifier(jwtIssuer.issuerURI, oidc.NewRemoteKeySet(context.Background(), jwksURI), config)
397 } else {
398 verifier = provider.Verifier(config)
399 }
400 return verifier, nil
403// jwtIssuer hold parsed JWT issuer info that's used to construct a verifier.
404type jwtIssuer struct {
405 issuerURI string
406 audience string
409func parseURL(toParse string, urltype string, msgs []string) (*url.URL, []string) {
410 parsed, err := url.Parse(toParse)
411 if err != nil {
412 return nil, append(msgs, fmt.Sprintf(
413 "error parsing %s-url=%q %s", urltype, toParse, err))
414 }
415 return parsed, msgs