mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 10:03:46 +01:00
440 lines
14 KiB
Go
440 lines
14 KiB
Go
package config
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"fmt"
|
|
"io/fs"
|
|
"net"
|
|
"net/url"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-errors/errors"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
)
|
|
|
|
const (
|
|
// DatabaseEngineSQLite is the sqlite engine name
|
|
DatabaseEngineSQLite = DefaultAdministrationUseSqlite
|
|
// DatabaseEnginePostgres is the postgres engine name
|
|
DatabaseEnginePostgres = "postgres"
|
|
|
|
// EnvDatabaseDSN overrides the database DSN from the config file when
|
|
// set, so a password does not have to be stored in the file
|
|
EnvDatabaseDSN = "PHISHINGCLUB_DATABASE_DSN"
|
|
|
|
// DefaultPostgresMaxOpenConns is the postgres pool size when not set
|
|
DefaultPostgresMaxOpenConns = 25
|
|
// DefaultPostgresMaxIdleConns is the postgres idle pool size when not set
|
|
DefaultPostgresMaxIdleConns = 25
|
|
// DefaultPostgresConnMaxLifetime is the postgres connection lifetime when not set
|
|
DefaultPostgresConnMaxLifetime = 30 * time.Minute
|
|
|
|
// maskedPassword replaces a password in an error that is shown or logged
|
|
maskedPassword = "xxxxx"
|
|
// minMaskedPasswordLength is the shortest password replaced in an error
|
|
// text, a shorter one could match ordinary words of the text
|
|
minMaskedPasswordLength = 4
|
|
// unparseableDSN is shown in place of a DSN pgx can not parse
|
|
unparseableDSN = "<unparseable dsn hidden>"
|
|
)
|
|
|
|
var (
|
|
ErrInvalidDatabaseDSN = errors.New("invalid database DSN")
|
|
ErrInvalidDatabasePool = errors.New("invalid database pool settings")
|
|
// ErrUnsupportedQueryExecMode is a postgres DSN whose
|
|
// default_query_exec_mode does not ask the server for parameter types
|
|
ErrUnsupportedQueryExecMode = errors.New(
|
|
"database DSN default_query_exec_mode must be cache_statement (the default), cache_describe or describe_exec, " +
|
|
"simple_protocol and exec are not supported. PgBouncer transaction pooling is not supported, session pooling is",
|
|
)
|
|
// ErrDatabaseEngineMismatch is a postgres DSN with the sqlite engine
|
|
ErrDatabaseEngineMismatch = errors.New("database DSN is a postgres DSN but the engine is sqlite3, set the engine to postgres")
|
|
|
|
errHiddenDatabaseError = errors.New("database error, the message is hidden as it may hold the password")
|
|
|
|
// keyValueHostRegex finds a host key in a key value DSN
|
|
keyValueHostRegex = regexp.MustCompile(`(^|\s)host\s*=`)
|
|
)
|
|
|
|
// PoolSettings is the resolved connection pool for a database
|
|
type PoolSettings struct {
|
|
MaxOpenConns int
|
|
MaxIdleConns int
|
|
ConnMaxLifetime time.Duration
|
|
}
|
|
|
|
// Pool returns the postgres pool settings with defaults for unset values.
|
|
// sqlite uses a fixed pool in the database package and ignores these.
|
|
func (d Database) Pool() (PoolSettings, error) {
|
|
p := PoolSettings{
|
|
MaxOpenConns: DefaultPostgresMaxOpenConns,
|
|
MaxIdleConns: DefaultPostgresMaxIdleConns,
|
|
ConnMaxLifetime: DefaultPostgresConnMaxLifetime,
|
|
}
|
|
if d.MaxOpenConns < 0 || d.MaxIdleConns < 0 {
|
|
return p, fmt.Errorf("%w: max_open_conns and max_idle_conns must not be negative", ErrInvalidDatabasePool)
|
|
}
|
|
if d.MaxOpenConns > 0 {
|
|
p.MaxOpenConns = d.MaxOpenConns
|
|
}
|
|
if d.MaxIdleConns > 0 {
|
|
p.MaxIdleConns = d.MaxIdleConns
|
|
}
|
|
if d.ConnMaxLifetime != "" {
|
|
lifetime, err := time.ParseDuration(d.ConnMaxLifetime)
|
|
if err != nil || lifetime < 0 {
|
|
return p, fmt.Errorf("%w: conn_max_lifetime must be a duration like 30m, 0 is no limit", ErrInvalidDatabasePool)
|
|
}
|
|
p.ConnMaxLifetime = lifetime
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// Validate checks the engine, the DSN and the pool settings. The errors
|
|
// never hold the DSN.
|
|
func (d Database) Validate() error {
|
|
return d.validate()
|
|
}
|
|
|
|
// validate checks the engine and its settings
|
|
func (d Database) validate() error {
|
|
switch d.Engine {
|
|
case DatabaseEngineSQLite:
|
|
if LooksLikePostgresDSN(d.DSN) {
|
|
return ErrDatabaseEngineMismatch
|
|
}
|
|
return nil
|
|
case DatabaseEnginePostgres:
|
|
if strings.TrimSpace(d.DSN) == "" {
|
|
return ErrMissingDatabaseDSN
|
|
}
|
|
cfg, err := pgx.ParseConfig(d.DSN)
|
|
if err != nil {
|
|
// the parse error is not included as it can hold parts of the
|
|
// DSN, only a fixed hint for the common causes
|
|
if hint := dsnParseHint(d.DSN, err); hint != "" {
|
|
return fmt.Errorf("%w: %s", ErrInvalidDatabaseDSN, hint)
|
|
}
|
|
return ErrInvalidDatabaseDSN
|
|
}
|
|
if err := CheckQueryExecMode(cfg); err != nil {
|
|
return err
|
|
}
|
|
if d.MaxOpenConns == 1 {
|
|
return fmt.Errorf("%w: max_open_conns must be at least 2, one connection holds the instance lock", ErrInvalidDatabasePool)
|
|
}
|
|
if _, err := d.Pool(); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
default:
|
|
return ErrInvalidDatabase
|
|
}
|
|
}
|
|
|
|
// CheckQueryExecMode refuses the pgx query modes that send parameters
|
|
// without asking the server for their types. IN lists bind one array
|
|
// parameter (dbengine.RegisterArrayIN) whose type only the server knows, so
|
|
// they fail in simple_protocol and exec. Those modes are mostly used behind
|
|
// PgBouncer transaction pooling, which also breaks the session level
|
|
// instance lock and SET LOCAL lock_timeout.
|
|
func CheckQueryExecMode(cfg *pgx.ConnConfig) error {
|
|
switch cfg.DefaultQueryExecMode {
|
|
case pgx.QueryExecModeCacheStatement, pgx.QueryExecModeCacheDescribe, pgx.QueryExecModeDescribeExec:
|
|
return nil
|
|
default:
|
|
return ErrUnsupportedQueryExecMode
|
|
}
|
|
}
|
|
|
|
// LooksLikePostgresDSN is true for a postgres URL or a key value DSN that
|
|
// names a host, which is never a sqlite DSN
|
|
func LooksLikePostgresDSN(dsn string) bool {
|
|
s := strings.ToLower(strings.TrimSpace(dsn))
|
|
if isPostgresURL(s) {
|
|
return true
|
|
}
|
|
return keyValueHostRegex.MatchString(s)
|
|
}
|
|
|
|
// isPostgresURL is true for a DSN with a postgres URL scheme
|
|
func isPostgresURL(dsn string) bool {
|
|
lower := strings.ToLower(dsn)
|
|
return strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://")
|
|
}
|
|
|
|
// dsnParseHint returns a fixed hint for a DSN pgx could not parse, or empty.
|
|
// It never returns any part of the DSN or of the error text.
|
|
func dsnParseHint(dsn string, err error) string {
|
|
var pathErr *fs.PathError
|
|
if errors.As(err, &pathErr) {
|
|
return "a file named in the DSN (sslrootcert, sslcert, sslkey or the service file) can not be read"
|
|
}
|
|
if isPostgresURL(dsn) {
|
|
// pgx passes on only the inner error of url.Parse, so it is parsed
|
|
// again here to tell this case apart
|
|
if _, urlErr := url.Parse(dsn); urlErr != nil {
|
|
return "not a valid postgres URL, check the host, the port and that special characters in the user and password are percent encoded"
|
|
}
|
|
}
|
|
var parseErr *pgconn.ParseConfigError
|
|
if errors.As(err, &parseErr) {
|
|
// pgx reports a bad port with no inner error, only its fixed text
|
|
// at the end, so the DSN in the message is never shown
|
|
if errors.Unwrap(parseErr) == nil && strings.HasSuffix(parseErr.Error(), ": invalid port") {
|
|
return "port must be a number from 1 to 65535"
|
|
}
|
|
// compared to the fixed texts of pgx, never shown
|
|
if cause := errors.Unwrap(parseErr); cause != nil {
|
|
switch cause.Error() {
|
|
case "sslmode is invalid":
|
|
return "sslmode must be one of disable, allow, prefer, require, verify-ca or verify-full"
|
|
case `both "sslcert" and "sslkey" are required`:
|
|
return "sslcert and sslkey must be set together"
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// transportLevel is how well a connection attempt is protected
|
|
type transportLevel int
|
|
|
|
const (
|
|
transportPlain transportLevel = iota
|
|
transportUnverified
|
|
transportVerifyCA
|
|
transportVerifyFull
|
|
)
|
|
|
|
// transportOf returns the protection of one connection attempt
|
|
func transportOf(c *tls.Config) transportLevel {
|
|
switch {
|
|
case c == nil:
|
|
return transportPlain
|
|
case c.InsecureSkipVerify && c.VerifyPeerCertificate == nil:
|
|
return transportUnverified
|
|
case c.InsecureSkipVerify:
|
|
return transportVerifyCA
|
|
default:
|
|
return transportVerifyFull
|
|
}
|
|
}
|
|
|
|
// TransportWarning returns a warning when a postgres DSN allows a connection
|
|
// to a host that is not on this machine without a full check of the server
|
|
// certificate and host name, otherwise empty
|
|
func (d Database) TransportWarning() string {
|
|
if d.Engine != DatabaseEnginePostgres {
|
|
return ""
|
|
}
|
|
cfg, err := pgx.ParseConfig(d.DSN)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
// sslmode disable has no TLS config, allow and prefer (the default) have
|
|
// a fallback without TLS. require without a root certificate checks
|
|
// nothing, verify-ca checks the chain but not the host name. The weakest
|
|
// attempt to a host that is not local decides.
|
|
weakest := transportVerifyFull
|
|
check := func(host string, c *tls.Config) {
|
|
if isLocalPostgresHost(host) {
|
|
return
|
|
}
|
|
if l := transportOf(c); l < weakest {
|
|
weakest = l
|
|
}
|
|
}
|
|
check(cfg.Host, cfg.TLSConfig)
|
|
for _, fb := range cfg.Fallbacks {
|
|
check(fb.Host, fb.TLSConfig)
|
|
}
|
|
switch weakest {
|
|
case transportPlain:
|
|
return "database connection may not use TLS (sslmode disable, allow or prefer) to a host that is not local, use sslmode=verify-full"
|
|
case transportUnverified:
|
|
return "database connection to a host that is not local does not verify the server certificate (sslmode require), use sslmode=verify-full"
|
|
case transportVerifyCA:
|
|
return "database connection to a host that is not local does not verify the server host name (sslmode verify-ca), use sslmode=verify-full"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// isLocalPostgresHost is true for a unix socket path or a loopback host
|
|
func isLocalPostgresHost(host string) bool {
|
|
if strings.HasPrefix(host, "/") {
|
|
return true
|
|
}
|
|
if strings.EqualFold(host, "localhost") {
|
|
return true
|
|
}
|
|
ip := net.ParseIP(host)
|
|
return ip != nil && ip.IsLoopback()
|
|
}
|
|
|
|
// DisplayDSN returns the DSN for logs and errors: a sqlite DSN as is, a
|
|
// postgres DSN through MaskDSN
|
|
func (d Database) DisplayDSN() string {
|
|
if d.Engine == DatabaseEnginePostgres {
|
|
return MaskDSN(d.DSN)
|
|
}
|
|
return d.DSN
|
|
}
|
|
|
|
// MaskDSN returns a postgres DSN for logs and errors. It is built only from
|
|
// the user, hosts, ports, database and sslmode that pgx parses, the raw DSN
|
|
// is never shown, so no password or key passphrase can appear in it.
|
|
func MaskDSN(dsn string) string {
|
|
cfg, err := pgx.ParseConfig(dsn)
|
|
if err != nil {
|
|
return unparseableDSN
|
|
}
|
|
if urlUserLost(dsn) {
|
|
return unparseableDSN
|
|
}
|
|
hosts := []string{}
|
|
seen := map[string]bool{}
|
|
add := func(host string, port uint16) {
|
|
h := net.JoinHostPort(host, strconv.Itoa(int(port)))
|
|
if !seen[h] {
|
|
seen[h] = true
|
|
hosts = append(hosts, h)
|
|
}
|
|
}
|
|
add(cfg.Host, cfg.Port)
|
|
for _, fb := range cfg.Fallbacks {
|
|
add(fb.Host, fb.Port)
|
|
}
|
|
return fmt.Sprintf(
|
|
"host=%s user=%s database=%s sslmode=%s",
|
|
strings.Join(hosts, ","), cfg.User, cfg.Database, sslModeOf(cfg),
|
|
)
|
|
}
|
|
|
|
// urlUserLost is true for a postgres URL that holds an @ but parses without
|
|
// user info. A password with an unescaped ? / or # ends the host part early,
|
|
// so parts of it are read as the port, the database or the query, and must
|
|
// not be shown.
|
|
func urlUserLost(dsn string) bool {
|
|
if !isPostgresURL(dsn) || !strings.Contains(dsn, "@") {
|
|
return false
|
|
}
|
|
u, err := url.Parse(dsn)
|
|
return err != nil || u.User == nil
|
|
}
|
|
|
|
// sslModeOf names the sslmode of the first host from the TLS settings pgx
|
|
// made for it
|
|
func sslModeOf(cfg *pgx.ConnConfig) string {
|
|
if strings.HasPrefix(cfg.Host, "/") {
|
|
return "unix socket"
|
|
}
|
|
// the attempts to the first host, the primary one and its fallbacks
|
|
attempts := []*tls.Config{cfg.TLSConfig}
|
|
for _, fb := range cfg.Fallbacks {
|
|
if fb.Host == cfg.Host && fb.Port == cfg.Port {
|
|
attempts = append(attempts, fb.TLSConfig)
|
|
}
|
|
}
|
|
first := transportOf(attempts[0])
|
|
hasPlainFallback := false
|
|
hasTLSFallback := false
|
|
for _, a := range attempts[1:] {
|
|
if a == nil {
|
|
hasPlainFallback = true
|
|
} else {
|
|
hasTLSFallback = true
|
|
}
|
|
}
|
|
switch {
|
|
case first == transportPlain && hasTLSFallback:
|
|
return "allow"
|
|
case first == transportPlain:
|
|
return "disable"
|
|
case first == transportUnverified && hasPlainFallback:
|
|
return "prefer"
|
|
case first == transportUnverified:
|
|
return "require"
|
|
case first == transportVerifyCA:
|
|
return "verify-ca"
|
|
default:
|
|
return "verify-full"
|
|
}
|
|
}
|
|
|
|
// MaskDSNInError returns an error whose text has the DSN and its password
|
|
// replaced. When the text holds neither the error is returned as is so error
|
|
// matching keeps working. A password too short to replace without ruining
|
|
// the text hides the whole text instead.
|
|
func MaskDSNInError(err error, dsn string) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
text := err.Error()
|
|
changed := false
|
|
if dsn != "" && strings.Contains(text, dsn) {
|
|
text = strings.ReplaceAll(text, dsn, MaskDSN(dsn))
|
|
changed = true
|
|
}
|
|
if password := dsnPassword(dsn); password != "" {
|
|
// as written, and percent encoded as in a URL user info or query
|
|
forms := []string{
|
|
password,
|
|
strings.TrimPrefix(url.UserPassword("", password).String(), ":"),
|
|
url.QueryEscape(password),
|
|
url.PathEscape(password),
|
|
}
|
|
for _, form := range forms {
|
|
if !strings.Contains(text, form) {
|
|
continue
|
|
}
|
|
if len(form) < minMaskedPasswordLength {
|
|
return errHiddenDatabaseError
|
|
}
|
|
text = strings.ReplaceAll(text, form, maskedPassword)
|
|
changed = true
|
|
}
|
|
}
|
|
if !changed {
|
|
return err
|
|
}
|
|
return errors.New(text)
|
|
}
|
|
|
|
// dsnPassword returns the password of a postgres DSN or empty
|
|
func dsnPassword(dsn string) string {
|
|
cfg, err := pgx.ParseConfig(dsn)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return cfg.Password
|
|
}
|
|
|
|
// databaseDSNFromEnv returns the DSN override from the environment
|
|
func databaseDSNFromEnv() string {
|
|
return os.Getenv(EnvDatabaseDSN)
|
|
}
|
|
|
|
// ClearDatabaseSecretsFromEnv removes the database secrets from the
|
|
// environment once the pool is open, so no process started later inherits
|
|
// them. pgx reads PGPASSWORD when the DSN is parsed, which happens once when
|
|
// the pool is made, and new connections of the pool use that parsed config.
|
|
// PGSSLPASSWORD is the passphrase of the client key, read at the same time.
|
|
func ClearDatabaseSecretsFromEnv(conf *Config) {
|
|
if conf.Database().Engine != DatabaseEnginePostgres {
|
|
return
|
|
}
|
|
for _, key := range []string{
|
|
"PGPASSWORD",
|
|
"PGSSLPASSWORD",
|
|
EnvDatabaseDSN,
|
|
} {
|
|
_ = os.Unsetenv(key)
|
|
}
|
|
}
|