2018-01-28 14:16:52 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2023-07-29 11:58:50 +00:00
|
|
|
"bytes"
|
2018-01-28 14:16:52 +00:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"os"
|
2018-09-20 13:39:22 +00:00
|
|
|
"os/signal"
|
2018-01-28 14:16:52 +00:00
|
|
|
"path"
|
2019-04-21 17:11:39 +00:00
|
|
|
"strings"
|
2018-09-20 13:39:22 +00:00
|
|
|
"syscall"
|
2023-07-29 11:58:50 +00:00
|
|
|
"text/template"
|
2018-01-28 14:16:52 +00:00
|
|
|
|
2023-07-29 11:58:50 +00:00
|
|
|
"github.com/Masterminds/sprig/v3"
|
2018-01-28 14:16:52 +00:00
|
|
|
"github.com/flosch/pongo2"
|
2018-09-08 17:39:59 +00:00
|
|
|
"github.com/gorilla/context"
|
2018-01-28 14:16:52 +00:00
|
|
|
"github.com/gorilla/sessions"
|
2019-02-21 23:10:43 +00:00
|
|
|
"github.com/pkg/errors"
|
2018-01-28 14:16:52 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2023-07-29 11:58:50 +00:00
|
|
|
yaml "gopkg.in/yaml.v3"
|
2018-11-17 13:42:56 +00:00
|
|
|
|
2019-02-21 23:27:02 +00:00
|
|
|
"github.com/Luzifer/nginx-sso/plugins"
|
2019-11-03 17:50:44 +00:00
|
|
|
"github.com/Luzifer/rconfig/v2"
|
2018-01-28 14:16:52 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type mainConfig struct {
|
2019-04-21 14:58:06 +00:00
|
|
|
ACL acl `yaml:"acl"`
|
|
|
|
AuditLog auditLogger `yaml:"audit_log"`
|
|
|
|
Cookie plugins.CookieConfig `yaml:"cookie"`
|
|
|
|
Listen struct {
|
2018-01-28 14:16:52 +00:00
|
|
|
Addr string `yaml:"addr"`
|
|
|
|
Port int `yaml:"port"`
|
|
|
|
} `yaml:"listen"`
|
|
|
|
Login struct {
|
2019-04-22 17:43:56 +00:00
|
|
|
Title string `yaml:"title" json:"title"`
|
|
|
|
DefaultMethod string `yaml:"default_method" json:"default_method"`
|
|
|
|
DefaultRedirect string `yaml:"default_redirect" json:"default_redirect"`
|
|
|
|
HideMFAField bool `yaml:"hide_mfa_field" json:"hide_mfa_field"`
|
|
|
|
Names map[string]string `yaml:"names" json:"names"`
|
2018-01-28 14:16:52 +00:00
|
|
|
} `yaml:"login"`
|
2019-02-21 23:10:43 +00:00
|
|
|
Plugins struct {
|
|
|
|
Directory string `yaml:"directory"`
|
|
|
|
} `yaml:"plugins"`
|
2018-01-28 14:16:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
cfg = struct {
|
|
|
|
ConfigFile string `flag:"config,c" default:"config.yaml" env:"CONFIG" description:"Location of the configuration file"`
|
2020-04-09 14:08:14 +00:00
|
|
|
AuthKey string `flag:"authkey" env:"COOKIE_AUTHENTICATION_KEY" description:"Cookie authentication key"`
|
2018-01-28 14:16:52 +00:00
|
|
|
LogLevel string `flag:"log-level" default:"info" description:"Level of logs to display (debug, info, warn, error)"`
|
|
|
|
TemplateDir string `flag:"frontend-dir" default:"./frontend/" env:"FRONTEND_DIR" description:"Location of the directory containing the web assets"`
|
|
|
|
VersionAndExit bool `flag:"version" default:"false" description:"Prints current version and exits"`
|
|
|
|
}{}
|
|
|
|
|
|
|
|
mainCfg = mainConfig{}
|
|
|
|
cookieStore *sessions.CookieStore
|
|
|
|
|
|
|
|
version = "dev"
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2023-07-29 11:58:50 +00:00
|
|
|
rconfig.AutoEnv(true)
|
2018-01-28 14:16:52 +00:00
|
|
|
if err := rconfig.Parse(&cfg); err != nil {
|
|
|
|
log.WithError(err).Fatal("Unable to parse commandline options")
|
|
|
|
}
|
|
|
|
|
|
|
|
if l, err := log.ParseLevel(cfg.LogLevel); err != nil {
|
|
|
|
log.WithError(err).Fatal("Unable to parse log level")
|
|
|
|
} else {
|
|
|
|
log.SetLevel(l)
|
|
|
|
}
|
|
|
|
|
|
|
|
if cfg.VersionAndExit {
|
|
|
|
fmt.Printf("nginx-sso %s\n", version)
|
|
|
|
os.Exit(0)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set sane defaults for main configuration
|
2019-06-29 10:40:39 +00:00
|
|
|
mainCfg.Cookie = plugins.DefaultCookieConfig()
|
2018-01-28 14:16:52 +00:00
|
|
|
mainCfg.Listen.Addr = "127.0.0.1"
|
|
|
|
mainCfg.Listen.Port = 8082
|
2019-04-21 17:11:39 +00:00
|
|
|
mainCfg.Login.DefaultRedirect = "debug"
|
2018-11-17 13:42:56 +00:00
|
|
|
mainCfg.AuditLog.TrustedIPHeaders = []string{"X-Forwarded-For", "RemoteAddr", "X-Real-IP"}
|
2018-11-18 11:24:33 +00:00
|
|
|
mainCfg.AuditLog.Headers = []string{"x-origin-uri"}
|
2018-01-28 14:16:52 +00:00
|
|
|
}
|
|
|
|
|
2020-04-07 23:11:48 +00:00
|
|
|
func loadConfiguration() ([]byte, error) {
|
2023-07-29 11:58:50 +00:00
|
|
|
yamlSource, err := os.ReadFile(cfg.ConfigFile)
|
2018-01-28 14:16:52 +00:00
|
|
|
if err != nil {
|
2023-07-29 11:58:50 +00:00
|
|
|
return nil, errors.Wrap(err, "reading configuration file")
|
2018-01-28 14:16:52 +00:00
|
|
|
}
|
|
|
|
|
2023-07-29 11:58:50 +00:00
|
|
|
tpl, err := template.New("config").Funcs(sprig.FuncMap()).Parse(string(yamlSource))
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "parsing config as template")
|
|
|
|
}
|
|
|
|
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
if err = tpl.Execute(buf, nil); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "executing config as template")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = yaml.Unmarshal(buf.Bytes(), &mainCfg); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "loading configuration file")
|
2018-01-28 14:16:52 +00:00
|
|
|
}
|
|
|
|
|
2020-04-09 14:08:14 +00:00
|
|
|
if cfg.AuthKey != "" {
|
|
|
|
mainCfg.Cookie.AuthKey = cfg.AuthKey
|
|
|
|
}
|
|
|
|
|
2023-07-29 11:58:50 +00:00
|
|
|
return buf.Bytes(), nil
|
2020-04-07 23:11:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func initializeModules(yamlSource []byte) error {
|
2019-02-21 23:10:43 +00:00
|
|
|
if mainCfg.Plugins.Directory != "" {
|
2020-04-07 23:11:48 +00:00
|
|
|
if err := loadPlugins(mainCfg.Plugins.Directory); err != nil {
|
2019-02-21 23:10:43 +00:00
|
|
|
return errors.Wrap(err, "Unable to load plugins")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-07 23:11:48 +00:00
|
|
|
if err := initializeAuthenticators(yamlSource); err != nil {
|
2018-09-20 13:39:22 +00:00
|
|
|
return fmt.Errorf("Unable to configure authentication: %s", err)
|
|
|
|
}
|
|
|
|
|
2020-04-07 23:11:48 +00:00
|
|
|
if err := initializeMFAProviders(yamlSource); err != nil {
|
2018-12-24 09:07:49 +00:00
|
|
|
log.WithError(err).Fatal("Unable to configure MFA providers")
|
|
|
|
}
|
|
|
|
|
2018-09-20 13:39:22 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
2020-04-07 23:11:48 +00:00
|
|
|
yamlSource, err := loadConfiguration()
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Fatal("Unable to load configuration")
|
|
|
|
}
|
|
|
|
|
2019-04-21 14:54:32 +00:00
|
|
|
cookieStore = sessions.NewCookieStore([]byte(mainCfg.Cookie.AuthKey))
|
|
|
|
registerModules()
|
|
|
|
|
2020-04-07 23:11:48 +00:00
|
|
|
if err = initializeModules(yamlSource); err != nil {
|
|
|
|
log.WithError(err).Fatal("Unable to initialize modules")
|
2018-01-28 14:16:52 +00:00
|
|
|
}
|
|
|
|
|
2019-04-21 01:40:28 +00:00
|
|
|
http.HandleFunc("/", handleRootRequest)
|
2018-01-28 14:16:52 +00:00
|
|
|
http.HandleFunc("/auth", handleAuthRequest)
|
2019-04-21 17:11:39 +00:00
|
|
|
http.HandleFunc("/debug", handleLoginDebug)
|
2022-12-20 23:59:07 +00:00
|
|
|
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) })
|
2018-01-28 14:16:52 +00:00
|
|
|
http.HandleFunc("/login", handleLoginRequest)
|
|
|
|
http.HandleFunc("/logout", handleLogoutRequest)
|
|
|
|
|
2018-09-20 13:39:22 +00:00
|
|
|
go http.ListenAndServe(
|
|
|
|
fmt.Sprintf("%s:%d", mainCfg.Listen.Addr, mainCfg.Listen.Port),
|
|
|
|
context.ClearHandler(http.DefaultServeMux),
|
|
|
|
)
|
|
|
|
|
|
|
|
sigChan := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(sigChan, syscall.SIGHUP)
|
|
|
|
|
|
|
|
for sig := range sigChan {
|
|
|
|
switch sig {
|
|
|
|
case syscall.SIGHUP:
|
2020-04-07 23:11:48 +00:00
|
|
|
if yamlSource, err = loadConfiguration(); err != nil {
|
2018-09-20 13:39:22 +00:00
|
|
|
log.WithError(err).Error("Unable to reload configuration")
|
2020-04-07 23:14:35 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = initializeModules(yamlSource); err != nil {
|
|
|
|
log.WithError(err).Error("Unable to initialize modules")
|
2018-09-20 13:39:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
default:
|
|
|
|
log.Fatalf("Received unexpected signal: %v", sig)
|
|
|
|
}
|
|
|
|
}
|
2018-01-28 14:16:52 +00:00
|
|
|
}
|
|
|
|
|
2019-04-21 01:40:28 +00:00
|
|
|
func handleRootRequest(res http.ResponseWriter, r *http.Request) {
|
|
|
|
// In case of a request to `/` redirect to login utilizing the default redirect
|
|
|
|
http.Redirect(res, r, "login", http.StatusFound)
|
|
|
|
}
|
|
|
|
|
2018-01-28 14:16:52 +00:00
|
|
|
func handleAuthRequest(res http.ResponseWriter, r *http.Request) {
|
2018-01-28 20:27:23 +00:00
|
|
|
user, groups, err := detectUser(res, r)
|
2018-01-28 14:16:52 +00:00
|
|
|
|
|
|
|
switch err {
|
2019-02-21 23:27:02 +00:00
|
|
|
case plugins.ErrNoValidUserFound:
|
2019-12-28 13:12:18 +00:00
|
|
|
// No valid user found, check whether special anonymous "user" has access
|
2020-04-07 23:14:35 +00:00
|
|
|
// Username is set to 0x0 character to prevent accidental whitelist-match
|
2022-12-21 00:06:02 +00:00
|
|
|
if mainCfg.ACL.HasAccess(string(byte(0x0)), nil, r) {
|
2019-12-28 13:12:18 +00:00
|
|
|
mainCfg.AuditLog.Log(auditEventValidate, r, map[string]string{"result": "anonymous access granted"}) // #nosec G104 - This is only logging
|
|
|
|
res.WriteHeader(http.StatusOK)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-12-29 00:06:12 +00:00
|
|
|
mainCfg.AuditLog.Log(auditEventValidate, r, map[string]string{"result": "no valid user found"}) // #nosec G104 - This is only logging
|
2018-01-28 14:16:52 +00:00
|
|
|
http.Error(res, "No valid user found", http.StatusUnauthorized)
|
|
|
|
|
|
|
|
case nil:
|
|
|
|
if !mainCfg.ACL.HasAccess(user, groups, r) {
|
2018-12-29 00:06:12 +00:00
|
|
|
mainCfg.AuditLog.Log(auditEventAccessDenied, r, map[string]string{"username": user}) // #nosec G104 - This is only logging
|
2018-01-28 14:16:52 +00:00
|
|
|
http.Error(res, "Access denied for this resource", http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-12-29 00:06:12 +00:00
|
|
|
mainCfg.AuditLog.Log(auditEventValidate, r, map[string]string{"result": "valid user found", "username": user}) // #nosec G104 - This is only logging
|
2018-11-17 13:42:56 +00:00
|
|
|
|
2018-01-28 14:16:52 +00:00
|
|
|
res.Header().Set("X-Username", user)
|
|
|
|
res.WriteHeader(http.StatusOK)
|
|
|
|
|
|
|
|
default:
|
|
|
|
log.WithError(err).Error("Error while handling auth request")
|
|
|
|
http.Error(res, "Something went wrong", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleLoginRequest(res http.ResponseWriter, r *http.Request) {
|
2019-04-21 01:22:45 +00:00
|
|
|
redirURL, err := getRedirectURL(r, mainCfg.Login.DefaultRedirect)
|
2019-04-20 22:15:36 +00:00
|
|
|
if err != nil {
|
|
|
|
http.Error(res, "Invalid redirect URL specified", http.StatusBadRequest)
|
|
|
|
}
|
|
|
|
|
2018-01-28 20:27:23 +00:00
|
|
|
if _, _, err := detectUser(res, r); err == nil {
|
2018-01-28 14:16:52 +00:00
|
|
|
// There is already a valid user
|
2019-04-20 22:15:36 +00:00
|
|
|
http.Redirect(res, r, redirURL, http.StatusFound)
|
2018-01-28 14:16:52 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-11-17 13:42:56 +00:00
|
|
|
auditFields := map[string]string{
|
2019-04-20 22:15:36 +00:00
|
|
|
"go": redirURL,
|
2018-11-17 13:42:56 +00:00
|
|
|
}
|
|
|
|
|
2019-04-21 14:54:32 +00:00
|
|
|
if r.Method == "POST" || r.URL.Query().Get("code") != "" {
|
2018-12-24 09:07:49 +00:00
|
|
|
// Simple authentication
|
|
|
|
user, mfaCfgs, err := loginUser(res, r)
|
|
|
|
switch err {
|
2019-02-21 23:27:02 +00:00
|
|
|
case plugins.ErrNoValidUserFound:
|
2019-01-17 22:50:18 +00:00
|
|
|
auditFields["reason"] = "invalid credentials"
|
|
|
|
mainCfg.AuditLog.Log(auditEventLoginFailure, r, auditFields) // #nosec G104 - This is only logging
|
2019-04-20 22:15:36 +00:00
|
|
|
http.Redirect(res, r, "/login?go="+url.QueryEscape(redirURL), http.StatusFound)
|
2018-12-24 09:07:49 +00:00
|
|
|
return
|
|
|
|
case nil:
|
|
|
|
// Don't handle for now, MFA validation comes first
|
|
|
|
default:
|
2019-01-17 22:50:18 +00:00
|
|
|
auditFields["reason"] = "error"
|
|
|
|
auditFields["error"] = err.Error()
|
|
|
|
mainCfg.AuditLog.Log(auditEventLoginFailure, r, auditFields) // #nosec G104 - This is only logging
|
2018-12-24 09:07:49 +00:00
|
|
|
log.WithError(err).Error("Login failed with unexpected error")
|
2019-04-20 22:15:36 +00:00
|
|
|
http.Redirect(res, r, "/login?go="+url.QueryEscape(redirURL), http.StatusFound)
|
2018-12-24 09:07:49 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// MFA validation against configs from login
|
|
|
|
err = validateMFA(res, r, user, mfaCfgs)
|
2018-01-28 14:16:52 +00:00
|
|
|
switch err {
|
2019-02-21 23:27:02 +00:00
|
|
|
case plugins.ErrNoValidUserFound:
|
2018-11-17 13:42:56 +00:00
|
|
|
auditFields["reason"] = "invalid credentials"
|
2018-12-29 00:06:12 +00:00
|
|
|
mainCfg.AuditLog.Log(auditEventLoginFailure, r, auditFields) // #nosec G104 - This is only logging
|
|
|
|
res.Header().Del("Set-Cookie") // Remove login cookie
|
2019-04-20 22:15:36 +00:00
|
|
|
http.Redirect(res, r, "/login?go="+url.QueryEscape(redirURL), http.StatusFound)
|
2018-01-28 14:16:52 +00:00
|
|
|
return
|
2018-11-17 13:42:56 +00:00
|
|
|
|
2018-01-28 14:16:52 +00:00
|
|
|
case nil:
|
2018-12-29 00:06:12 +00:00
|
|
|
mainCfg.AuditLog.Log(auditEventLoginSuccess, r, auditFields) // #nosec G104 - This is only logging
|
2019-04-20 22:15:36 +00:00
|
|
|
http.Redirect(res, r, redirURL, http.StatusFound)
|
2018-01-28 14:16:52 +00:00
|
|
|
return
|
2018-11-17 13:42:56 +00:00
|
|
|
|
2018-01-28 14:16:52 +00:00
|
|
|
default:
|
2018-11-17 13:42:56 +00:00
|
|
|
auditFields["reason"] = "error"
|
|
|
|
auditFields["error"] = err.Error()
|
2018-12-29 00:06:12 +00:00
|
|
|
mainCfg.AuditLog.Log(auditEventLoginFailure, r, auditFields) // #nosec G104 - This is only logging
|
2018-01-28 14:16:52 +00:00
|
|
|
log.WithError(err).Error("Login failed with unexpected error")
|
2018-12-24 09:07:49 +00:00
|
|
|
res.Header().Del("Set-Cookie") // Remove login cookie
|
2019-04-20 22:15:36 +00:00
|
|
|
http.Redirect(res, r, "/login?go="+url.QueryEscape(redirURL), http.StatusFound)
|
2018-01-28 14:16:52 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-21 14:54:32 +00:00
|
|
|
// Store redirect URL in session (required for oAuth2 flows)
|
|
|
|
sess, _ := cookieStore.Get(r, strings.Join([]string{mainCfg.Cookie.Prefix, "main"}, "-")) // #nosec G104 - On error empty session is returned
|
|
|
|
sess.Options = mainCfg.Cookie.GetSessionOpts()
|
|
|
|
sess.Values["go"] = redirURL
|
|
|
|
|
|
|
|
if err := sess.Save(r, res); err != nil {
|
|
|
|
log.WithError(err).Error("Unable to save session")
|
|
|
|
http.Error(res, "Something went wrong", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Render login page
|
2018-01-28 14:16:52 +00:00
|
|
|
tpl := pongo2.Must(pongo2.FromFile(path.Join(cfg.TemplateDir, "index.html")))
|
|
|
|
if err := tpl.ExecuteWriter(pongo2.Context{
|
|
|
|
"active_methods": getFrontendAuthenticators(),
|
2019-04-20 22:15:36 +00:00
|
|
|
"go": redirURL,
|
2018-01-28 14:16:52 +00:00
|
|
|
"login": mainCfg.Login,
|
|
|
|
}, res); err != nil {
|
|
|
|
log.WithError(err).Error("Unable to render template")
|
|
|
|
http.Error(res, "Something went wrong", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleLogoutRequest(res http.ResponseWriter, r *http.Request) {
|
2019-04-21 01:22:45 +00:00
|
|
|
redirURL, err := getRedirectURL(r, mainCfg.Login.DefaultRedirect)
|
2019-04-20 22:15:36 +00:00
|
|
|
if err != nil {
|
|
|
|
http.Error(res, "Invalid redirect URL specified", http.StatusBadRequest)
|
|
|
|
}
|
|
|
|
|
2018-12-29 00:06:12 +00:00
|
|
|
mainCfg.AuditLog.Log(auditEventLogout, r, nil) // #nosec G104 - This is only logging
|
2018-01-28 14:16:52 +00:00
|
|
|
if err := logoutUser(res, r); err != nil {
|
|
|
|
log.WithError(err).Error("Failed to logout user")
|
|
|
|
http.Error(res, "Something went wrong", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-04-20 22:15:36 +00:00
|
|
|
http.Redirect(res, r, redirURL, http.StatusFound)
|
2018-01-28 14:16:52 +00:00
|
|
|
}
|
2019-04-21 17:11:39 +00:00
|
|
|
|
|
|
|
func handleLoginDebug(w http.ResponseWriter, r *http.Request) {
|
|
|
|
user, groups, err := detectUser(w, r)
|
|
|
|
switch err {
|
|
|
|
case nil:
|
|
|
|
// All fine
|
|
|
|
|
|
|
|
case plugins.ErrNoValidUserFound:
|
|
|
|
http.Redirect(w, r, "login", http.StatusFound)
|
|
|
|
return
|
|
|
|
|
|
|
|
default:
|
|
|
|
log.WithError(err).Error("Failed to get user for login debug")
|
|
|
|
http.Error(w, "Something went wrong", http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
fmt.Fprintln(w, "Successfully logged in:")
|
|
|
|
fmt.Fprintf(w, "- Username: %s\n", user)
|
|
|
|
fmt.Fprintf(w, "- Groups: %s\n", strings.Join(groups, ","))
|
|
|
|
}
|