git.iko.soy/typeable/oauth2-proxy
on v5.0.0 help sign in
203 lines 13 kB history raw
1package main
3import (
4 "flag"
5 "fmt"
6 "math/rand"
7 "net/http"
8 "os"
9 "runtime"
10 "strings"
11 "time"
13 "github.com/BurntSushi/toml"
14 options "github.com/mreiferson/go-options"
15 "github.com/pusher/oauth2_proxy/pkg/logger"
18func main() {
19 logger.SetFlags(logger.Lshortfile)
20 flagSet := flag.NewFlagSet("oauth2_proxy", flag.ExitOnError)
22 emailDomains := StringArray{}
23 whitelistDomains := StringArray{}
24 upstreams := StringArray{}
25 skipAuthRegex := StringArray{}
26 jwtIssuers := StringArray{}
27 googleGroups := StringArray{}
28 redisSentinelConnectionURLs := StringArray{}
30 config := flagSet.String("config", "", "path to config file")
31 showVersion := flagSet.Bool("version", false, "print version string")
33 flagSet.String("http-address", "127.0.0.1:4180", "[http://]<addr>:<port> or unix://<path> to listen on for HTTP clients")
34 flagSet.String("https-address", ":443", "<addr>:<port> to listen on for HTTPS clients")
35 flagSet.Bool("reverse-proxy", false, "are we running behind a reverse proxy, controls whether headers like X-Real-Ip are accepted")
36 flagSet.Bool("force-https", false, "force HTTPS redirect for HTTP requests")
37 flagSet.String("tls-cert-file", "", "path to certificate file")
38 flagSet.String("tls-key-file", "", "path to private key file")
39 flagSet.String("redirect-url", "", "the OAuth Redirect URL. ie: \"https://internalapp.yourcompany.com/oauth2/callback\"")
40 flagSet.Bool("set-xauthrequest", false, "set X-Auth-Request-User and X-Auth-Request-Email response headers (useful in Nginx auth_request mode)")
41 flagSet.Var(&upstreams, "upstream", "the http url(s) of the upstream endpoint, file:// paths for static files or static://<status_code> for static response. Routing is based on the path")
42 flagSet.Bool("pass-basic-auth", true, "pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream")
43 flagSet.Bool("pass-user-headers", true, "pass X-Forwarded-User and X-Forwarded-Email information to upstream")
44 flagSet.String("basic-auth-password", "", "the password to set when passing the HTTP Basic Auth header")
45 flagSet.Bool("pass-access-token", false, "pass OAuth access_token to upstream via X-Forwarded-Access-Token header")
46 flagSet.Bool("pass-host-header", true, "pass the request Host Header to upstream")
47 flagSet.Bool("pass-authorization-header", false, "pass the Authorization Header to upstream")
48 flagSet.Bool("set-authorization-header", false, "set Authorization response headers (useful in Nginx auth_request mode)")
49 flagSet.Var(&skipAuthRegex, "skip-auth-regex", "bypass authentication for requests path's that match (may be given multiple times)")
50 flagSet.Bool("skip-provider-button", false, "will skip sign-in-page to directly reach the next step: oauth/start")
51 flagSet.Bool("skip-auth-preflight", false, "will skip authentication for OPTIONS requests")
52 flagSet.Bool("ssl-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS providers")
53 flagSet.Bool("ssl-upstream-insecure-skip-verify", false, "skip validation of certificates presented when using HTTPS upstreams")
54 flagSet.Duration("flush-interval", time.Duration(1)*time.Second, "period between response flushing when streaming responses")
55 flagSet.Bool("skip-jwt-bearer-tokens", false, "will skip requests that have verified JWT bearer tokens (default false)")
56 flagSet.Var(&jwtIssuers, "extra-jwt-issuers", "if skip-jwt-bearer-tokens is set, a list of extra JWT issuer=audience pairs (where the issuer URL has a .well-known/openid-configuration or a .well-known/jwks.json)")
58 flagSet.Var(&emailDomains, "email-domain", "authenticate emails with the specified domain (may be given multiple times). Use * to authenticate any email")
59 flagSet.Var(&whitelistDomains, "whitelist-domain", "allowed domains for redirection after authentication. Prefix domain with a . to allow subdomains (eg .example.com)")
60 flagSet.String("keycloak-group", "", "restrict login to members of this group.")
61 flagSet.String("azure-tenant", "common", "go to a tenant-specific or common (tenant-independent) endpoint.")
62 flagSet.String("bitbucket-team", "", "restrict logins to members of this team")
63 flagSet.String("bitbucket-repository", "", "restrict logins to user with access to this repository")
64 flagSet.String("github-org", "", "restrict logins to members of this organisation")
65 flagSet.String("github-team", "", "restrict logins to members of this team")
66 flagSet.String("gitlab-group", "", "restrict logins to members of this group")
67 flagSet.Var(&googleGroups, "google-group", "restrict logins to members of this google group (may be given multiple times).")
68 flagSet.String("google-admin-email", "", "the google admin to impersonate for api calls")
69 flagSet.String("google-service-account-json", "", "the path to the service account json credentials")
70 flagSet.String("client-id", "", "the OAuth Client ID: ie: \"123456.apps.googleusercontent.com\"")
71 flagSet.String("client-secret", "", "the OAuth Client Secret")
72 flagSet.String("authenticated-emails-file", "", "authenticate against emails via file (one per line)")
73 flagSet.String("htpasswd-file", "", "additionally authenticate against a htpasswd file. Entries must be created with \"htpasswd -s\" for SHA encryption or \"htpasswd -B\" for bcrypt encryption")
74 flagSet.Bool("display-htpasswd-form", true, "display username / password login form if an htpasswd file is provided")
75 flagSet.String("custom-templates-dir", "", "path to custom html templates")
76 flagSet.String("banner", "", "custom banner string. Use \"-\" to disable default banner.")
77 flagSet.String("footer", "", "custom footer string. Use \"-\" to disable default footer.")
78 flagSet.String("proxy-prefix", "/oauth2", "the url root path that this proxy should be nested under (e.g. /<oauth2>/sign_in)")
79 flagSet.String("ping-path", "/ping", "the ping endpoint that can be used for basic health checks")
80 flagSet.Bool("proxy-websockets", true, "enables WebSocket proxying")
82 flagSet.String("cookie-name", "_oauth2_proxy", "the name of the cookie that the oauth_proxy creates")
83 flagSet.String("cookie-secret", "", "the seed string for secure cookies (optionally base64 encoded)")
84 flagSet.String("cookie-domain", "", "an optional cookie domain to force cookies to (ie: .yourcompany.com)*")
85 flagSet.String("cookie-path", "/", "an optional cookie path to force cookies to (ie: /poc/)*")
86 flagSet.Duration("cookie-expire", time.Duration(168)*time.Hour, "expire timeframe for cookie")
87 flagSet.Duration("cookie-refresh", time.Duration(0), "refresh the cookie after this duration; 0 to disable")
88 flagSet.Bool("cookie-secure", true, "set secure (HTTPS) cookie flag")
89 flagSet.Bool("cookie-httponly", true, "set HttpOnly cookie flag")
90 flagSet.String("cookie-samesite", "", "set SameSite cookie attribute (ie: \"lax\", \"strict\", \"none\", or \"\"). ")
92 flagSet.String("session-store-type", "cookie", "the session storage provider to use")
93 flagSet.String("redis-connection-url", "", "URL of redis server for redis session storage (eg: redis://HOST[:PORT])")
94 flagSet.Bool("redis-use-sentinel", false, "Connect to redis via sentinels. Must set --redis-sentinel-master-name and --redis-sentinel-connection-urls to use this feature")
95 flagSet.String("redis-sentinel-master-name", "", "Redis sentinel master name. Used in conjunction with --redis-use-sentinel")
96 flagSet.String("redis-ca-path", "", "Redis custom CA path")
97 flagSet.Bool("redis-insecure-skip-tls-verify", false, "Use insecure TLS connection to redis")
98 flagSet.Var(&redisSentinelConnectionURLs, "redis-sentinel-connection-urls", "List of Redis sentinel connection URLs (eg redis://HOST[:PORT]). Used in conjunction with --redis-use-sentinel")
100 flagSet.String("logging-filename", "", "File to log requests to, empty for stdout")
101 flagSet.Int("logging-max-size", 100, "Maximum size in megabytes of the log file before rotation")
102 flagSet.Int("logging-max-age", 7, "Maximum number of days to retain old log files")
103 flagSet.Int("logging-max-backups", 0, "Maximum number of old log files to retain; 0 to disable")
104 flagSet.Bool("logging-local-time", true, "If the time in log files and backup filenames are local or UTC time")
105 flagSet.Bool("logging-compress", false, "Should rotated log files be compressed using gzip")
107 flagSet.Bool("standard-logging", true, "Log standard runtime information")
108 flagSet.String("standard-logging-format", logger.DefaultStandardLoggingFormat, "Template for standard log lines")
110 flagSet.Bool("request-logging", true, "Log HTTP requests")
111 flagSet.String("request-logging-format", logger.DefaultRequestLoggingFormat, "Template for HTTP request log lines")
112 flagSet.String("exclude-logging-paths", "", "Exclude logging requests to paths (eg: '/path1,/path2,/path3')")
113 flagSet.Bool("silence-ping-logging", false, "Disable logging of requests to ping endpoint")
115 flagSet.Bool("auth-logging", true, "Log authentication attempts")
116 flagSet.String("auth-logging-format", logger.DefaultAuthLoggingFormat, "Template for authentication log lines")
118 flagSet.String("provider", "google", "OAuth provider")
119 flagSet.String("provider-display-name", "", "Provider display name")
120 flagSet.String("oidc-issuer-url", "", "OpenID Connect issuer URL (ie: https://accounts.google.com)")
121 flagSet.Bool("insecure-oidc-allow-unverified-email", false, "Don't fail if an email address in an id_token is not verified")
122 flagSet.Bool("skip-oidc-discovery", false, "Skip OIDC discovery and use manually supplied Endpoints")
123 flagSet.String("oidc-jwks-url", "", "OpenID Connect JWKS URL (ie: https://www.googleapis.com/oauth2/v3/certs)")
124 flagSet.String("login-url", "", "Authentication endpoint")
125 flagSet.String("redeem-url", "", "Token redemption endpoint")
126 flagSet.String("profile-url", "", "Profile access endpoint")
127 flagSet.String("resource", "", "The resource that is protected (Azure AD only)")
128 flagSet.String("validate-url", "", "Access token validation endpoint")
129 flagSet.String("scope", "", "OAuth scope specification")
130 flagSet.String("approval-prompt", "force", "OAuth approval_prompt")
132 flagSet.String("signature-key", "", "GAP-Signature request signature key (algorithm:secretkey)")
133 flagSet.String("acr-values", "http://idmanagement.gov/ns/assurance/loa/1", "acr values string: optional, used by login.gov")
134 flagSet.String("jwt-key", "", "private key in PEM format used to sign JWT, so that you can say something like -jwt-key=\"${OAUTH2_PROXY_JWT_KEY}\": required by login.gov")
135 flagSet.String("jwt-key-file", "", "path to the private key file in PEM format used to sign the JWT so that you can say something like -jwt-key-file=/etc/ssl/private/jwt_signing_key.pem: required by login.gov")
136 flagSet.String("pubjwk-url", "", "JWK pubkey access endpoint: required by login.gov")
137 flagSet.Bool("gcp-healthchecks", false, "Enable GCP/GKE healthcheck endpoints")
139 flagSet.Parse(os.Args[1:])
141 if *showVersion {
142 fmt.Printf("oauth2_proxy %s (built with %s)\n", VERSION, runtime.Version())
143 return
144 }
146 opts := NewOptions()
148 cfg := make(EnvOptions)
149 if *config != "" {
150 _, err := toml.DecodeFile(*config, &cfg)
151 if err != nil {
152 logger.Fatalf("ERROR: failed to load config file %s - %s", *config, err)
153 }
154 }
155 cfg.LoadEnvForStruct(opts)
156 options.Resolve(opts, flagSet, cfg)
158 err := opts.Validate()
159 if err != nil {
160 logger.Printf("%s", err)
161 os.Exit(1)
162 }
164 validator := NewValidator(opts.EmailDomains, opts.AuthenticatedEmailsFile)
165 oauthproxy := NewOAuthProxy(opts, validator)
167 if len(opts.Banner) >= 1 {
168 if opts.Banner == "-" {
169 oauthproxy.SignInMessage = ""
170 } else {
171 oauthproxy.SignInMessage = opts.Banner
172 }
173 } else if len(opts.EmailDomains) != 0 && opts.AuthenticatedEmailsFile == "" {
174 if len(opts.EmailDomains) > 1 {
175 oauthproxy.SignInMessage = fmt.Sprintf("Authenticate using one of the following domains: %v", strings.Join(opts.EmailDomains, ", "))
176 } else if opts.EmailDomains[0] != "*" {
177 oauthproxy.SignInMessage = fmt.Sprintf("Authenticate using %v", opts.EmailDomains[0])
178 }
179 }
181 if opts.HtpasswdFile != "" {
182 logger.Printf("using htpasswd file %s", opts.HtpasswdFile)
183 oauthproxy.HtpasswdFile, err = NewHtpasswdFromFile(opts.HtpasswdFile)
184 oauthproxy.DisplayHtpasswdForm = opts.DisplayHtpasswdForm
185 if err != nil {
186 logger.Fatalf("FATAL: unable to open %s %s", opts.HtpasswdFile, err)
187 }
188 }
190 rand.Seed(time.Now().UnixNano())
192 var handler http.Handler
193 if opts.GCPHealthChecks {
194 handler = redirectToHTTPS(opts, gcpHealthcheck(LoggingHandler(oauthproxy)))
195 } else {
196 handler = redirectToHTTPS(opts, LoggingHandler(oauthproxy))
197 }
198 s := &Server{
199 Handler: handler,
200 Opts: opts,
201 }
202 s.ListenAndServe()