15 "github.com/coreos/go-oidc"
16 "github.com/dgrijalva/jwt-go"
17 "github.com/mbland/hmacauth"
18 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/options"
19 "github.com/oauth2-proxy/oauth2-proxy/pkg/ip"
20 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
21 "github.com/oauth2-proxy/oauth2-proxy/pkg/requests"
22 "github.com/oauth2-proxy/oauth2-proxy/pkg/util"
23 "github.com/oauth2-proxy/oauth2-proxy/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)...)
32 if o.SSLInsecureSkipVerify {
33 insecureTransport := &http.Transport{
34 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
36 http.DefaultClient = &http.Client{Transport: insecureTransport}
37 } else if len(o.ProviderCAFiles) > 0 {
38 pool, err := util.GetCertPool(o.ProviderCAFiles)
40 transport := &http.Transport{
41 TLSClientConfig: &tls.Config{
46 http.DefaultClient = &http.Client{Transport: transport}
48 msgs = append(msgs, fmt.Sprintf("unable to load provider CA file(s): %v", err))
53 msgs = append(msgs, "missing setting: client-id")
55 // login.gov uses a signed JWT to authenticate, not a client-secret
56 if o.ProviderType != "login.gov" {
57 if o.ClientSecret == "" && o.ClientSecretFile == "" {
58 msgs = append(msgs, "missing setting: client-secret or client-secret-file")
60 if o.ClientSecret == "" && o.ClientSecretFile != "" {
61 _, err := ioutil.ReadFile(o.ClientSecretFile)
63 msgs = append(msgs, "could not read client secret file: "+o.ClientSecretFile)
67 if o.AuthenticatedEmailsFile == "" && len(o.EmailDomains) == 0 && o.HtpasswdFile == "" {
68 msgs = append(msgs, "missing setting for email validation: email-domain or authenticated-emails-file required."+
69 "\n use email-domain=* to authorize all email addresses")
72 if o.SetBasicAuth && o.SetAuthorization {
73 msgs = append(msgs, "mutually exclusive: set-basic-auth and set-authorization-header can not both be true")
76 if o.OIDCIssuerURL != "" {
78 ctx := context.Background()
80 if o.InsecureOIDCSkipIssuerVerification && !o.SkipOIDCDiscovery {
81 // go-oidc doesn't let us pass bypass the issuer check this in the oidc.NewProvider call
82 // (which uses discovery to get the URLs), so we'll do a quick check ourselves and if
83 // we get the URLs, we'll just use the non-discovery path.
85 logger.Printf("Performing OIDC Discovery...")
87 requestURL := strings.TrimSuffix(o.OIDCIssuerURL, "/") + "/.well-known/openid-configuration"
88 body, err := requests.New(requestURL).
93 logger.Printf("error: failed to discover OIDC configuration: %v", err)
95 // Prefer manually configured URLs. It's a bit unclear
96 // why you'd be doing discovery and also providing the URLs
97 // explicitly though...
99 o.LoginURL = body.Get("authorization_endpoint").MustString()
102 if o.RedeemURL == "" {
103 o.RedeemURL = body.Get("token_endpoint").MustString()
106 if o.OIDCJwksURL == "" {
107 o.OIDCJwksURL = body.Get("jwks_uri").MustString()
110 if o.ProfileURL == "" {
111 o.ProfileURL = body.Get("userinfo_endpoint").MustString()
114 o.SkipOIDCDiscovery = true
118 // Construct a manual IDTokenVerifier from issuer URL & JWKS URI
119 // instead of metadata discovery if we enable -skip-oidc-discovery.
120 // In this case we need to make sure the required endpoints for
121 // the provider are configured.
122 if o.SkipOIDCDiscovery {
123 if o.LoginURL == "" {
124 msgs = append(msgs, "missing setting: login-url")
126 if o.RedeemURL == "" {
127 msgs = append(msgs, "missing setting: redeem-url")
129 if o.OIDCJwksURL == "" {
130 msgs = append(msgs, "missing setting: oidc-jwks-url")
132 keySet := oidc.NewRemoteKeySet(ctx, o.OIDCJwksURL)
133 o.SetOIDCVerifier(oidc.NewVerifier(o.OIDCIssuerURL, keySet, &oidc.Config{
134 ClientID: o.ClientID,
135 SkipIssuerCheck: o.InsecureOIDCSkipIssuerVerification,
138 // Configure discoverable provider data.
139 provider, err := oidc.NewProvider(ctx, o.OIDCIssuerURL)
143 o.SetOIDCVerifier(provider.Verifier(&oidc.Config{
144 ClientID: o.ClientID,
145 SkipIssuerCheck: o.InsecureOIDCSkipIssuerVerification,
148 o.LoginURL = provider.Endpoint().AuthURL
149 o.RedeemURL = provider.Endpoint().TokenURL
152 o.Scope = "openid email profile"
156 if o.PreferEmailToUser && !o.PassBasicAuth && !o.PassUserHeaders {
157 msgs = append(msgs, "PreferEmailToUser should only be used with PassBasicAuth or PassUserHeaders")
160 if o.SkipJwtBearerTokens {
161 // Configure extra issuers
162 if len(o.ExtraJwtIssuers) > 0 {
163 var jwtIssuers []jwtIssuer
164 jwtIssuers, msgs = parseJwtIssuers(o.ExtraJwtIssuers, msgs)
165 for _, jwtIssuer := range jwtIssuers {
166 verifier, err := newVerifierFromJwtIssuer(jwtIssuer)
168 msgs = append(msgs, fmt.Sprintf("error building verifiers: %s", err))
170 o.SetJWTBearerVerifiers(append(o.GetJWTBearerVerifiers(), verifier))
175 var redirectURL *url.URL
176 redirectURL, msgs = parseURL(o.RawRedirectURL, "redirect", msgs)
177 o.SetRedirectURL(redirectURL)
179 msgs = append(msgs, validateUpstreams(o.UpstreamServers)...)
181 for _, u := range o.SkipAuthRegex {
182 compiledRegex, err := regexp.Compile(u)
184 msgs = append(msgs, fmt.Sprintf("error compiling regex=%q %s", u, err))
187 o.SetCompiledRegex(append(o.GetCompiledRegex(), compiledRegex))
189 msgs = parseProviderInfo(o, msgs)
191 if len(o.GoogleGroups) > 0 || o.GoogleAdminEmail != "" || o.GoogleServiceAccountJSON != "" {
192 if len(o.GoogleGroups) < 1 {
193 msgs = append(msgs, "missing setting: google-group")
195 if o.GoogleAdminEmail == "" {
196 msgs = append(msgs, "missing setting: google-admin-email")
198 if o.GoogleServiceAccountJSON == "" {
199 msgs = append(msgs, "missing setting: google-service-account-json")
203 msgs = parseSignatureKey(o, msgs)
204 msgs = configureLogger(o.Logging, msgs)
207 parser, err := ip.GetRealClientIPParser(o.RealClientIPHeader)
209 msgs = append(msgs, fmt.Sprintf("real_client_ip_header (%s) not accepted parameter value: %v", o.RealClientIPHeader, err))
211 o.SetRealClientIPParser(parser)
213 // Allow the logger to get client IPs
214 logger.SetGetClientFunc(func(r *http.Request) string {
215 return ip.GetClientString(o.GetRealClientIPParser(), r, false)
219 if len(o.TrustedIPs) > 0 && o.ReverseProxy {
220 fmt.Fprintln(os.Stderr, "WARNING: trusting of IPs with --reverse-proxy poses risks if a header spoofing attack is possible.")
223 for i, ipStr := range o.TrustedIPs {
224 if nil == ip.ParseIPNet(ipStr) {
225 msgs = append(msgs, fmt.Sprintf("trusted_ips[%d] (%s) could not be recognized", i, ipStr))
230 return fmt.Errorf("invalid configuration:\n %s",
231 strings.Join(msgs, "\n "))
236func parseProviderInfo(o *options.Options, msgs []string) []string {
237 p := &providers.ProviderData{
239 ClientID: o.ClientID,
240 ClientSecret: o.ClientSecret,
241 ClientSecretFile: o.ClientSecretFile,
243 ApprovalPrompt: o.ApprovalPrompt,
244 AcrValues: o.AcrValues,
246 p.LoginURL, msgs = parseURL(o.LoginURL, "login", msgs)
247 p.RedeemURL, msgs = parseURL(o.RedeemURL, "redeem", msgs)
248 p.ProfileURL, msgs = parseURL(o.ProfileURL, "profile", msgs)
249 p.ValidateURL, msgs = parseURL(o.ValidateURL, "validate", msgs)
250 p.ProtectedResource, msgs = parseURL(o.ProtectedResource, "resource", msgs)
252 o.SetProvider(providers.New(o.ProviderType, p))
253 switch p := o.GetProvider().(type) {
254 case *providers.AzureProvider:
255 p.Configure(o.AzureTenant)
256 case *providers.GitHubProvider:
257 p.SetOrgTeam(o.GitHubOrg, o.GitHubTeam)
258 p.SetRepo(o.GitHubRepo, o.GitHubToken)
259 p.SetUsers(o.GitHubUsers)
260 case *providers.KeycloakProvider:
261 p.SetGroup(o.KeycloakGroup)
262 case *providers.GoogleProvider:
263 if o.GoogleServiceAccountJSON != "" {
264 file, err := os.Open(o.GoogleServiceAccountJSON)
266 msgs = append(msgs, "invalid Google credentials file: "+o.GoogleServiceAccountJSON)
268 p.SetGroupRestriction(o.GoogleGroups, o.GoogleAdminEmail, file)
271 case *providers.BitbucketProvider:
272 p.SetTeam(o.BitbucketTeam)
273 p.SetRepository(o.BitbucketRepository)
274 case *providers.OIDCProvider:
275 p.AllowUnverifiedEmail = o.InsecureOIDCAllowUnverifiedEmail
276 p.UserIDClaim = o.UserIDClaim
277 if o.GetOIDCVerifier() == nil {
278 msgs = append(msgs, "oidc provider requires an oidc issuer URL")
280 p.Verifier = o.GetOIDCVerifier()
282 case *providers.GitLabProvider:
283 p.AllowUnverifiedEmail = o.InsecureOIDCAllowUnverifiedEmail
284 p.Groups = o.GitLabGroup
285 p.EmailDomains = o.EmailDomains
287 if o.GetOIDCVerifier() != nil {
288 p.Verifier = o.GetOIDCVerifier()
290 // Initialize with default verifier for gitlab.com
291 ctx := context.Background()
293 provider, err := oidc.NewProvider(ctx, "https://gitlab.com")
295 msgs = append(msgs, "failed to initialize oidc provider for gitlab.com")
297 p.Verifier = provider.Verifier(&oidc.Config{
298 ClientID: o.ClientID,
301 p.LoginURL, msgs = parseURL(provider.Endpoint().AuthURL, "login", msgs)
302 p.RedeemURL, msgs = parseURL(provider.Endpoint().TokenURL, "redeem", msgs)
305 case *providers.LoginGovProvider:
306 p.PubJWKURL, msgs = parseURL(o.PubJWKURL, "pubjwk", msgs)
308 // JWT key can be supplied via env variable or file in the filesystem, but not both.
310 case o.JWTKey != "" && o.JWTKeyFile != "":
311 msgs = append(msgs, "cannot set both jwt-key and jwt-key-file options")
312 case o.JWTKey == "" && o.JWTKeyFile == "":
313 msgs = append(msgs, "login.gov provider requires a private key for signing JWTs")
315 // The JWT Key is in the commandline argument
316 signKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(o.JWTKey))
318 msgs = append(msgs, "could not parse RSA Private Key PEM")
322 case o.JWTKeyFile != "":
323 // The JWT key is in the filesystem
324 keyData, err := ioutil.ReadFile(o.JWTKeyFile)
326 msgs = append(msgs, "could not read key file: "+o.JWTKeyFile)
328 signKey, err := jwt.ParseRSAPrivateKeyFromPEM(keyData)
330 msgs = append(msgs, "could not parse private key from PEM file:"+o.JWTKeyFile)
339func parseSignatureKey(o *options.Options, msgs []string) []string {
340 if o.SignatureKey == "" {
344 components := strings.Split(o.SignatureKey, ":")
345 if len(components) != 2 {
346 return append(msgs, "invalid signature hash:key spec: "+
350 algorithm, secretKey := components[0], components[1]
353 if hash, err = hmacauth.DigestNameToCryptoHash(algorithm); err != nil {
354 return append(msgs, "unsupported signature hash algorithm: "+
357 o.SetSignatureData(&options.SignatureData{Hash: hash, Key: secretKey})
361// parseJwtIssuers takes in an array of strings in the form of issuer=audience
362// and parses to an array of jwtIssuer structs.
363func parseJwtIssuers(issuers []string, msgs []string) ([]jwtIssuer, []string) {
364 parsedIssuers := make([]jwtIssuer, 0, len(issuers))
365 for _, jwtVerifier := range issuers {
366 components := strings.Split(jwtVerifier, "=")
367 if len(components) < 2 {
368 msgs = append(msgs, fmt.Sprintf("invalid jwt verifier uri=audience spec: %s", jwtVerifier))
371 uri, audience := components[0], strings.Join(components[1:], "=")
372 parsedIssuers = append(parsedIssuers, jwtIssuer{issuerURI: uri, audience: audience})
374 return parsedIssuers, msgs
377// newVerifierFromJwtIssuer takes in issuer information in jwtIssuer info and returns
378// a verifier for that issuer.
379func newVerifierFromJwtIssuer(jwtIssuer jwtIssuer) (*oidc.IDTokenVerifier, error) {
380 config := &oidc.Config{
381 ClientID: jwtIssuer.audience,
383 // Try as an OpenID Connect Provider first
384 var verifier *oidc.IDTokenVerifier
385 provider, err := oidc.NewProvider(context.Background(), jwtIssuer.issuerURI)
388 jwksURI := strings.TrimSuffix(jwtIssuer.issuerURI, "/") + "/.well-known/jwks.json"
389 if err := requests.New(jwksURI).Do().Error(); err != nil {
393 verifier = oidc.NewVerifier(jwtIssuer.issuerURI, oidc.NewRemoteKeySet(context.Background(), jwksURI), config)
395 verifier = provider.Verifier(config)
400// jwtIssuer hold parsed JWT issuer info that's used to construct a verifier.
401type jwtIssuer struct {
406func parseURL(toParse string, urltype string, msgs []string) (*url.URL, []string) {
407 parsed, err := url.Parse(toParse)
409 return nil, append(msgs, fmt.Sprintf(
410 "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