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
36 insecureTransport := &http.Transport{
37 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
39 http.DefaultClient = &http.Client{Transport: insecureTransport}
40 } else if len(o.ProviderCAFiles) > 0 {
41 pool, err := util.GetCertPool(o.ProviderCAFiles)
43 transport := &http.Transport{
44 TLSClientConfig: &tls.Config{
49 http.DefaultClient = &http.Client{Transport: transport}
51 msgs = append(msgs, fmt.Sprintf("unable to load provider CA file(s): %v", err))
56 msgs = append(msgs, "missing setting: client-id")
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")
63 if o.ClientSecret == "" && o.ClientSecretFile != "" {
64 _, err := ioutil.ReadFile(o.ClientSecretFile)
66 msgs = append(msgs, "could not read client secret file: "+o.ClientSecretFile)
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")
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).
92 logger.Errorf("error: failed to discover OIDC configuration: %v", err)
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...
98 o.LoginURL = body.Get("authorization_endpoint").MustString()
101 if o.RedeemURL == "" {
102 o.RedeemURL = body.Get("token_endpoint").MustString()
105 if o.OIDCJwksURL == "" {
106 o.OIDCJwksURL = body.Get("jwks_uri").MustString()
109 if o.ProfileURL == "" {
110 o.ProfileURL = body.Get("userinfo_endpoint").MustString()
113 o.SkipOIDCDiscovery = true
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")
125 if o.RedeemURL == "" {
126 msgs = append(msgs, "missing setting: redeem-url")
128 if o.OIDCJwksURL == "" {
129 msgs = append(msgs, "missing setting: oidc-jwks-url")
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,
137 // Configure discoverable provider data.
138 provider, err := oidc.NewProvider(ctx, o.OIDCIssuerURL)
142 o.SetOIDCVerifier(provider.Verifier(&oidc.Config{
143 ClientID: o.ClientID,
144 SkipIssuerCheck: o.InsecureOIDCSkipIssuerVerification,
147 o.LoginURL = provider.Endpoint().AuthURL
148 o.RedeemURL = provider.Endpoint().TokenURL
151 o.Scope = "openid email profile"
153 if len(o.AllowedGroups) > 0 {
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)
167 msgs = append(msgs, fmt.Sprintf("error building verifiers: %s", err))
169 o.SetJWTBearerVerifiers(append(o.GetJWTBearerVerifiers(), verifier))
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)
183 msgs = append(msgs, fmt.Sprintf("error compiling regex=%q %s", u, err))
186 o.SetCompiledRegex(append(o.GetCompiledRegex(), compiledRegex))
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")
194 if o.GoogleAdminEmail == "" {
195 msgs = append(msgs, "missing setting: google-admin-email")
197 if o.GoogleServiceAccountJSON == "" {
198 msgs = append(msgs, "missing setting: google-service-account-json")
202 msgs = parseSignatureKey(o, msgs)
203 msgs = configureLogger(o.Logging, msgs)
206 parser, err := ip.GetRealClientIPParser(o.RealClientIPHeader)
208 msgs = append(msgs, fmt.Sprintf("real_client_ip_header (%s) not accepted parameter value: %v", o.RealClientIPHeader, err))
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)
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.")
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))
232 return fmt.Errorf("invalid configuration:\n %s",
233 strings.Join(msgs, "\n "))
238func parseProviderInfo(o *options.Options, msgs []string) []string {
239 p := &providers.ProviderData{
241 ClientID: o.ClientID,
242 ClientSecret: o.ClientSecret,
243 ClientSecretFile: o.ClientSecretFile,
245 ApprovalPrompt: o.ApprovalPrompt,
246 AcrValues: o.AcrValues,
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)
268 msgs = append(msgs, "invalid Google credentials file: "+o.GoogleServiceAccountJSON)
270 p.SetGroupRestriction(o.GoogleGroups, o.GoogleAdminEmail, file)
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")
283 p.Verifier = o.GetOIDCVerifier()
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()
293 // Initialize with default verifier for gitlab.com
294 ctx := context.Background()
296 provider, err := oidc.NewProvider(ctx, "https://gitlab.com")
298 msgs = append(msgs, "failed to initialize oidc provider for gitlab.com")
300 p.Verifier = provider.Verifier(&oidc.Config{
301 ClientID: o.ClientID,
304 p.LoginURL, msgs = parseURL(provider.Endpoint().AuthURL, "login", msgs)
305 p.RedeemURL, msgs = parseURL(provider.Endpoint().TokenURL, "redeem", msgs)
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.
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")
318 // The JWT Key is in the commandline argument
319 signKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(o.JWTKey))
321 msgs = append(msgs, "could not parse RSA Private Key PEM")
325 case o.JWTKeyFile != "":
326 // The JWT key is in the filesystem
327 keyData, err := ioutil.ReadFile(o.JWTKeyFile)
329 msgs = append(msgs, "could not read key file: "+o.JWTKeyFile)
331 signKey, err := jwt.ParseRSAPrivateKeyFromPEM(keyData)
333 msgs = append(msgs, "could not parse private key from PEM file:"+o.JWTKeyFile)
342func parseSignatureKey(o *options.Options, msgs []string) []string {
343 if o.SignatureKey == "" {
347 components := strings.Split(o.SignatureKey, ":")
348 if len(components) != 2 {
349 return append(msgs, "invalid signature hash:key spec: "+
353 algorithm, secretKey := components[0], components[1]
356 if hash, err = hmacauth.DigestNameToCryptoHash(algorithm); err != nil {
357 return append(msgs, "unsupported signature hash algorithm: "+
360 o.SetSignatureData(&options.SignatureData{Hash: hash, Key: secretKey})
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))
374 uri, audience := components[0], strings.Join(components[1:], "=")
375 parsedIssuers = append(parsedIssuers, jwtIssuer{issuerURI: uri, audience: audience})
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,
386 // Try as an OpenID Connect Provider first
387 var verifier *oidc.IDTokenVerifier
388 provider, err := oidc.NewProvider(context.Background(), jwtIssuer.issuerURI)
391 jwksURI := strings.TrimSuffix(jwtIssuer.issuerURI, "/") + "/.well-known/jwks.json"
392 if err := requests.New(jwksURI).Do().Error(); err != nil {
396 verifier = oidc.NewVerifier(jwtIssuer.issuerURI, oidc.NewRemoteKeySet(context.Background(), jwksURI), config)
398 verifier = provider.Verifier(config)
403// jwtIssuer hold parsed JWT issuer info that's used to construct a verifier.
404type jwtIssuer struct {
409func parseURL(toParse string, urltype string, msgs []string) (*url.URL, []string) {
410 parsed, err := url.Parse(toParse)
412 return nil, append(msgs, fmt.Sprintf(
413 "error parsing %s-url=%q %s", urltype, toParse, err))
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list