2012-12-10 20:59:23 -05:00
package main
import (
2012-12-17 13:38:33 -05:00
"fmt"
2019-03-20 06:44:51 -07:00
"math/rand"
2019-03-20 14:29:44 -07:00
"net/http"
2014-08-07 16:16:39 -04:00
"os"
2020-04-05 00:12:38 +09:00
"os/signal"
2015-03-19 23:03:00 -04:00
"runtime"
2012-12-10 20:59:23 -05:00
"strings"
2020-04-05 00:12:38 +09:00
"syscall"
2014-11-08 13:26:55 -05:00
"time"
2012-12-10 20:59:23 -05:00
2020-04-13 11:34:25 +01:00
"github.com/oauth2-proxy/oauth2-proxy/pkg/apis/options"
2020-03-29 14:54:36 +01:00
"github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
2020-04-13 11:34:25 +01:00
"github.com/spf13/pflag"
2012-12-10 20:59:23 -05:00
)
func main ( ) {
2019-02-10 08:37:45 -08:00
logger . SetFlags ( logger . Lshortfile )
2020-05-03 16:55:20 +01:00
flagSet := pflag . NewFlagSet ( "oauth2-proxy" , pflag . ExitOnError )
2014-11-09 14:51:10 -05:00
config := flagSet . String ( "config" , "" , "path to config file" )
showVersion := flagSet . Bool ( "version" , false , "print version string" )
2015-02-11 12:07:40 +11:00
flagSet . String ( "http-address" , "127.0.0.1:4180" , "[http://]<addr>:<port> or unix://<path> to listen on for HTTP clients" )
2015-06-07 21:51:47 -04:00
flagSet . String ( "https-address" , ":443" , "<addr>:<port> to listen on for HTTPS clients" )
2020-01-24 17:54:13 +00:00
flagSet . Bool ( "reverse-proxy" , false , "are we running behind a reverse proxy, controls whether headers like X-Real-Ip are accepted" )
2019-10-22 14:19:39 +01:00
flagSet . Bool ( "force-https" , false , "force HTTPS redirect for HTTP requests" )
2019-07-16 11:39:06 +12:00
flagSet . String ( "tls-cert-file" , "" , "path to certificate file" )
flagSet . String ( "tls-key-file" , "" , "path to private key file" )
2014-11-09 14:51:10 -05:00
flagSet . String ( "redirect-url" , "" , "the OAuth Redirect URL. ie: \"https://internalapp.yourcompany.com/oauth2/callback\"" )
2016-10-20 17:49:59 +05:30
flagSet . Bool ( "set-xauthrequest" , false , "set X-Auth-Request-User and X-Auth-Request-Email response headers (useful in Nginx auth_request mode)" )
2020-05-03 16:55:20 +01:00
flagSet . StringSlice ( "upstream" , [ ] string { } , "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" )
2014-11-09 14:51:10 -05:00
flagSet . Bool ( "pass-basic-auth" , true , "pass HTTP Basic Auth, X-Forwarded-User and X-Forwarded-Email information to upstream" )
2020-04-13 14:54:53 +01:00
flagSet . Bool ( "set-basic-auth" , false , "set HTTP Basic Auth information in response (useful in Nginx auth_request mode)" )
2020-03-04 11:27:43 +13:00
flagSet . Bool ( "prefer-email-to-user" , false , "Prefer to use the Email address as the Username when passing information to upstream. Will only use Username if Email is unavailable, eg. htaccess authentication. Used in conjunction with -pass-basic-auth and -pass-user-headers" )
2016-02-08 15:57:47 +00:00
flagSet . Bool ( "pass-user-headers" , true , "pass X-Forwarded-User and X-Forwarded-Email information to upstream" )
2015-07-24 09:17:43 +00:00
flagSet . String ( "basic-auth-password" , "" , "the password to set when passing the HTTP Basic Auth header" )
2015-04-02 20:57:17 -04:00
flagSet . Bool ( "pass-access-token" , false , "pass OAuth access_token to upstream via X-Forwarded-Access-Token header" )
2015-03-17 15:15:15 -04:00
flagSet . Bool ( "pass-host-header" , true , "pass the request Host Header to upstream" )
2018-01-27 10:14:19 +00:00
flagSet . Bool ( "pass-authorization-header" , false , "pass the Authorization Header to upstream" )
flagSet . Bool ( "set-authorization-header" , false , "set Authorization response headers (useful in Nginx auth_request mode)" )
2020-05-03 16:55:20 +01:00
flagSet . StringSlice ( "skip-auth-regex" , [ ] string { } , "bypass authentication for requests path's that match (may be given multiple times)" )
2015-11-11 11:42:35 +11:00
flagSet . Bool ( "skip-provider-button" , false , "will skip sign-in-page to directly reach the next step: oauth/start" )
2017-04-07 14:55:48 +03:00
flagSet . Bool ( "skip-auth-preflight" , false , "will skip authentication for OPTIONS requests" )
2019-08-07 18:48:53 +02:00
flagSet . Bool ( "ssl-insecure-skip-verify" , false , "skip validation of certificates presented when using HTTPS providers" )
flagSet . Bool ( "ssl-upstream-insecure-skip-verify" , false , "skip validation of certificates presented when using HTTPS upstreams" )
2019-01-31 14:02:15 +00:00
flagSet . Duration ( "flush-interval" , time . Duration ( 1 ) * time . Second , "period between response flushing when streaming responses" )
2019-05-01 09:18:54 -07:00
flagSet . Bool ( "skip-jwt-bearer-tokens" , false , "will skip requests that have verified JWT bearer tokens (default false)" )
2020-05-03 16:55:20 +01:00
flagSet . StringSlice ( "extra-jwt-issuers" , [ ] string { } , "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)" )
2014-11-09 14:51:10 -05:00
2020-05-03 16:55:20 +01:00
flagSet . StringSlice ( "email-domain" , [ ] string { } , "authenticate emails with the specified domain (may be given multiple times). Use * to authenticate any email" )
flagSet . StringSlice ( "whitelist-domain" , [ ] string { } , "allowed domains for redirection after authentication. Prefix domain with a . to allow subdomains (eg .example.com)" )
2019-07-28 15:54:39 +02:00
flagSet . String ( "keycloak-group" , "" , "restrict login to members of this group." )
2015-11-09 09:28:34 +01:00
flagSet . String ( "azure-tenant" , "common" , "go to a tenant-specific or common (tenant-independent) endpoint." )
2019-08-16 15:53:22 +02:00
flagSet . String ( "bitbucket-team" , "" , "restrict logins to members of this team" )
flagSet . String ( "bitbucket-repository" , "" , "restrict logins to user with access to this repository" )
2015-05-20 23:23:48 -04:00
flagSet . String ( "github-org" , "" , "restrict logins to members of this organisation" )
flagSet . String ( "github-team" , "" , "restrict logins to members of this team" )
2020-05-11 11:02:40 -06:00
flagSet . String ( "github-repo" , "" , "restrict logins to collaborators of this repository" )
flagSet . String ( "github-token" , "" , "the token to use when verifying repository collaborators (must have push access to the repository)" )
2019-08-06 13:20:54 +02:00
flagSet . String ( "gitlab-group" , "" , "restrict logins to members of this group" )
2020-05-03 16:55:20 +01:00
flagSet . StringSlice ( "google-group" , [ ] string { } , "restrict logins to members of this google group (may be given multiple times)." )
2015-08-20 03:07:02 -07:00
flagSet . String ( "google-admin-email" , "" , "the google admin to impersonate for api calls" )
flagSet . String ( "google-service-account-json" , "" , "the path to the service account json credentials" )
2015-05-21 02:50:21 -04:00
flagSet . String ( "client-id" , "" , "the OAuth Client ID: ie: \"123456.apps.googleusercontent.com\"" )
2014-11-09 14:51:10 -05:00
flagSet . String ( "client-secret" , "" , "the OAuth Client Secret" )
2020-02-17 16:21:04 +02:00
flagSet . String ( "client-secret-file" , "" , "the file with OAuth Client Secret" )
2014-11-09 14:51:10 -05:00
flagSet . String ( "authenticated-emails-file" , "" , "authenticate against emails via file (one per line)" )
2018-02-16 02:14:41 -06:00
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" )
2014-12-09 14:38:57 -06:00
flagSet . Bool ( "display-htpasswd-form" , true , "display username / password login form if an htpasswd file is provided" )
2015-03-17 18:06:06 -04:00
flagSet . String ( "custom-templates-dir" , "" , "path to custom html templates" )
2019-06-19 15:24:25 +01:00
flagSet . String ( "banner" , "" , "custom banner string. Use \"-\" to disable default banner." )
2016-06-18 23:53:42 -04:00
flagSet . String ( "footer" , "" , "custom footer string. Use \"-\" to disable default footer." )
2015-05-29 15:47:40 -07:00
flagSet . String ( "proxy-prefix" , "/oauth2" , "the url root path that this proxy should be nested under (e.g. /<oauth2>/sign_in)" )
2019-06-03 13:51:59 +12:00
flagSet . String ( "ping-path" , "/ping" , "the ping endpoint that can be used for basic health checks" )
2019-03-08 09:15:21 +01:00
flagSet . Bool ( "proxy-websockets" , true , "enables WebSocket proxying" )
2013-07-30 17:31:59 -04:00
2015-06-07 23:52:28 -04:00
flagSet . String ( "cookie-name" , "_oauth2_proxy" , "the name of the cookie that the oauth_proxy creates" )
2016-06-20 07:17:39 -04:00
flagSet . String ( "cookie-secret" , "" , "the seed string for secure cookies (optionally base64 encoded)" )
2020-05-03 16:55:20 +01:00
flagSet . StringSlice ( "cookie-domain" , [ ] string { } , "Optional cookie domains to force cookies to (ie: `.yourcompany.com`). The longest domain matching the request's host will be used (or the shortest cookie domain if there is no match)." )
2019-04-10 00:36:35 +03:00
flagSet . String ( "cookie-path" , "/" , "an optional cookie path to force cookies to (ie: /poc/)*" )
2014-11-09 14:51:10 -05:00
flagSet . Duration ( "cookie-expire" , time . Duration ( 168 ) * time . Hour , "expire timeframe for cookie" )
2015-06-23 14:01:05 -04:00
flagSet . Duration ( "cookie-refresh" , time . Duration ( 0 ) , "refresh the cookie after this duration; 0 to disable" )
2015-03-17 23:13:45 -04:00
flagSet . Bool ( "cookie-secure" , true , "set secure (HTTPS) cookie flag" )
flagSet . Bool ( "cookie-httponly" , true , "set HttpOnly cookie flag" )
2019-12-16 13:10:04 -05:00
flagSet . String ( "cookie-samesite" , "" , "set SameSite cookie attribute (ie: \"lax\", \"strict\", \"none\", or \"\"). " )
2014-11-09 14:51:10 -05:00
2019-05-07 14:05:12 +01:00
flagSet . String ( "session-store-type" , "cookie" , "the session storage provider to use" )
2019-05-24 17:32:55 +01:00
flagSet . String ( "redis-connection-url" , "" , "URL of redis server for redis session storage (eg: redis://HOST[:PORT])" )
2019-05-28 13:26:40 -07:00
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" )
2019-08-13 12:42:23 +02:00
flagSet . String ( "redis-sentinel-master-name" , "" , "Redis sentinel master name. Used in conjunction with --redis-use-sentinel" )
2019-11-07 11:04:40 +01:00
flagSet . String ( "redis-ca-path" , "" , "Redis custom CA path" )
2019-11-12 11:34:14 +01:00
flagSet . Bool ( "redis-insecure-skip-tls-verify" , false , "Use insecure TLS connection to redis" )
2020-05-03 16:55:20 +01:00
flagSet . StringSlice ( "redis-sentinel-connection-urls" , [ ] string { } , "List of Redis sentinel connection URLs (eg redis://HOST[:PORT]). Used in conjunction with --redis-use-sentinel" )
2020-02-06 09:59:12 -08:00
flagSet . Bool ( "redis-use-cluster" , false , "Connect to redis cluster. Must set --redis-cluster-connection-urls to use this feature" )
2020-05-03 16:55:20 +01:00
flagSet . StringSlice ( "redis-cluster-connection-urls" , [ ] string { } , "List of Redis cluster connection URLs (eg redis://HOST[:PORT]). Used in conjunction with --redis-use-cluster" )
2019-05-07 14:05:12 +01:00
2019-02-10 08:37:45 -08:00
flagSet . String ( "logging-filename" , "" , "File to log requests to, empty for stdout" )
flagSet . Int ( "logging-max-size" , 100 , "Maximum size in megabytes of the log file before rotation" )
flagSet . Int ( "logging-max-age" , 7 , "Maximum number of days to retain old log files" )
flagSet . Int ( "logging-max-backups" , 0 , "Maximum number of old log files to retain; 0 to disable" )
flagSet . Bool ( "logging-local-time" , true , "If the time in log files and backup filenames are local or UTC time" )
flagSet . Bool ( "logging-compress" , false , "Should rotated log files be compressed using gzip" )
flagSet . Bool ( "standard-logging" , true , "Log standard runtime information" )
flagSet . String ( "standard-logging-format" , logger . DefaultStandardLoggingFormat , "Template for standard log lines" )
flagSet . Bool ( "request-logging" , true , "Log HTTP requests" )
flagSet . String ( "request-logging-format" , logger . DefaultRequestLoggingFormat , "Template for HTTP request log lines" )
2019-06-22 09:39:46 +12:00
flagSet . String ( "exclude-logging-paths" , "" , "Exclude logging requests to paths (eg: '/path1,/path2,/path3')" )
2019-06-03 13:51:59 +12:00
flagSet . Bool ( "silence-ping-logging" , false , "Disable logging of requests to ping endpoint" )
2019-02-10 08:37:45 -08:00
flagSet . Bool ( "auth-logging" , true , "Log authentication attempts" )
flagSet . String ( "auth-logging-format" , logger . DefaultAuthLoggingFormat , "Template for authentication log lines" )
2015-03-19 16:37:16 -04:00
2015-06-07 21:51:47 -04:00
flagSet . String ( "provider" , "google" , "OAuth provider" )
2019-11-25 18:20:37 +01:00
flagSet . String ( "provider-display-name" , "" , "Provider display name" )
2017-05-09 11:20:35 -07:00
flagSet . String ( "oidc-issuer-url" , "" , "OpenID Connect issuer URL (ie: https://accounts.google.com)" )
2019-07-11 15:58:31 +01:00
flagSet . Bool ( "insecure-oidc-allow-unverified-email" , false , "Don't fail if an email address in an id_token is not verified" )
2020-04-19 04:19:21 -07:00
flagSet . Bool ( "insecure-oidc-skip-issuer-verification" , false , "Do not verify if issuer matches OIDC discovery URL" )
2019-03-04 14:54:22 +01:00
flagSet . Bool ( "skip-oidc-discovery" , false , "Skip OIDC discovery and use manually supplied Endpoints" )
flagSet . String ( "oidc-jwks-url" , "" , "OpenID Connect JWKS URL (ie: https://www.googleapis.com/oauth2/v3/certs)" )
2015-03-30 15:48:30 -04:00
flagSet . String ( "login-url" , "" , "Authentication endpoint" )
flagSet . String ( "redeem-url" , "" , "Token redemption endpoint" )
flagSet . String ( "profile-url" , "" , "Profile access endpoint" )
2015-11-09 09:28:34 +01:00
flagSet . String ( "resource" , "" , "The resource that is protected (Azure AD only)" )
2015-05-08 17:13:35 -04:00
flagSet . String ( "validate-url" , "" , "Access token validation endpoint" )
2015-11-09 00:57:01 +01:00
flagSet . String ( "scope" , "" , "OAuth scope specification" )
2020-03-14 10:53:43 +01:00
flagSet . String ( "prompt" , "" , "OIDC prompt" )
2015-11-09 00:57:01 +01:00
flagSet . String ( "approval-prompt" , "force" , "OAuth approval_prompt" )
2015-03-30 15:48:30 -04:00
2015-11-15 22:08:30 -05:00
flagSet . String ( "signature-key" , "" , "GAP-Signature request signature key (algorithm:secretkey)" )
2020-03-17 18:57:33 +01:00
flagSet . String ( "acr-values" , "" , "acr values string: optional" )
2019-03-20 15:15:47 -07:00
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" )
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" )
2019-03-20 06:44:51 -07:00
flagSet . String ( "pubjwk-url" , "" , "JWK pubkey access endpoint: required by login.gov" )
2019-03-25 11:44:17 -07:00
flagSet . Bool ( "gcp-healthchecks" , false , "Enable GCP/GKE healthcheck endpoints" )
2015-11-15 22:08:30 -05:00
2020-04-28 08:46:46 +02:00
flagSet . String ( "user-id-claim" , "email" , "which claim contains the user ID" )
2020-05-03 16:55:20 +01:00
flagSet . Parse ( os . Args [ 1 : ] )
2014-11-09 14:51:10 -05:00
2014-11-09 21:07:02 -05:00
if * showVersion {
2020-03-29 14:54:36 +01:00
fmt . Printf ( "oauth2-proxy %s (built with %s)\n" , VERSION , runtime . Version ( ) )
2014-11-09 21:07:02 -05:00
return
}
2014-11-09 14:51:10 -05:00
opts := NewOptions ( )
2020-05-03 16:55:20 +01:00
err := options . Load ( * config , flagSet , opts )
2020-04-13 11:34:25 +01:00
if err != nil {
logger . Printf ( "ERROR: Failed to load config: %v" , err )
os . Exit ( 1 )
2014-11-09 14:51:10 -05:00
}
2012-12-10 20:59:23 -05:00
2020-04-13 11:34:25 +01:00
err = opts . Validate ( )
2012-12-10 20:59:23 -05:00
if err != nil {
2019-02-10 08:37:45 -08:00
logger . Printf ( "%s" , err )
2014-11-09 14:51:10 -05:00
os . Exit ( 1 )
2012-12-10 20:59:23 -05:00
}
2019-02-10 08:37:45 -08:00
2015-06-06 14:37:54 -04:00
validator := NewValidator ( opts . EmailDomains , opts . AuthenticatedEmailsFile )
2015-11-09 00:57:01 +01:00
oauthproxy := NewOAuthProxy ( opts , validator )
2014-11-09 14:51:10 -05:00
2019-06-19 15:24:25 +01:00
if len ( opts . Banner ) >= 1 {
if opts . Banner == "-" {
oauthproxy . SignInMessage = ""
} else {
oauthproxy . SignInMessage = opts . Banner
}
} else if len ( opts . EmailDomains ) != 0 && opts . AuthenticatedEmailsFile == "" {
2015-06-06 14:37:54 -04:00
if len ( opts . EmailDomains ) > 1 {
oauthproxy . SignInMessage = fmt . Sprintf ( "Authenticate using one of the following domains: %v" , strings . Join ( opts . EmailDomains , ", " ) )
} else if opts . EmailDomains [ 0 ] != "*" {
oauthproxy . SignInMessage = fmt . Sprintf ( "Authenticate using %v" , opts . EmailDomains [ 0 ] )
2014-11-09 00:26:52 -05:00
}
2012-12-10 20:59:23 -05:00
}
2014-11-09 14:51:10 -05:00
if opts . HtpasswdFile != "" {
2019-02-10 08:37:45 -08:00
logger . Printf ( "using htpasswd file %s" , opts . HtpasswdFile )
2014-11-09 14:51:10 -05:00
oauthproxy . HtpasswdFile , err = NewHtpasswdFromFile ( opts . HtpasswdFile )
2014-12-09 14:38:57 -06:00
oauthproxy . DisplayHtpasswdForm = opts . DisplayHtpasswdForm
2012-12-17 13:38:33 -05:00
if err != nil {
2019-02-10 08:37:45 -08:00
logger . Fatalf ( "FATAL: unable to open %s %s" , opts . HtpasswdFile , err )
2012-12-17 13:38:33 -05:00
}
2012-12-10 20:59:23 -05:00
}
2014-11-09 14:51:10 -05:00
2019-03-20 06:44:51 -07:00
rand . Seed ( time . Now ( ) . UnixNano ( ) )
2019-03-26 08:59:03 -07:00
var handler http . Handler
2019-03-20 14:29:44 -07:00
if opts . GCPHealthChecks {
2019-10-17 16:30:48 +01:00
handler = redirectToHTTPS ( opts , gcpHealthcheck ( LoggingHandler ( oauthproxy ) ) )
2019-03-20 14:29:44 -07:00
} else {
2019-10-17 16:30:48 +01:00
handler = redirectToHTTPS ( opts , LoggingHandler ( oauthproxy ) )
2019-03-20 14:29:44 -07:00
}
2015-06-07 21:51:47 -04:00
s := & Server {
2019-03-26 08:59:03 -07:00
Handler : handler ,
2015-06-07 21:51:47 -04:00
Opts : opts ,
2020-04-05 00:12:38 +09:00
stop : make ( chan struct { } , 1 ) ,
2015-02-11 12:07:40 +11:00
}
2020-04-05 00:12:38 +09:00
// Observe signals in background goroutine.
go func ( ) {
sigint := make ( chan os . Signal , 1 )
signal . Notify ( sigint , os . Interrupt , syscall . SIGTERM )
<- sigint
s . stop <- struct { } { } // notify having caught signal
} ( )
2015-06-07 21:51:47 -04:00
s . ListenAndServe ( )
2012-12-10 20:59:23 -05:00
}