package install import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "os" "os/user" "path/filepath" "slices" "strings" "syscall" "time" "github.com/jackc/pgx/v5" "github.com/phishingclub/phishingclub/config" ) // connectionTestTimeout bounds the postgres connection test const connectionTestTimeout = 15 * time.Second // applyDatabaseConfig checks the engine, DSN and password from the installer // and sets them on the config. The password is added to the DSN. func applyDatabaseConfig(conf *config.Config, engine, dsn, password string) error { engine = strings.ToLower(strings.TrimSpace(engine)) dsn = strings.TrimSpace(dsn) switch engine { case config.DatabaseEngineSQLite: if password != "" { return errors.New("the database password is only used with postgres") } case config.DatabaseEnginePostgres: if dsn == "" || dsn == config.DefaultAdministrationDSN { return errors.New("postgres needs a DSN, for example postgres://phishingclub@localhost:5432/phishingclub?sslmode=verify-full") } // checked before the password is added, for the hints on a DSN // that can not be read raw := conf.Database() raw.Engine = engine raw.DSN = dsn if err := raw.Validate(); err != nil { return err } withPw, err := dsnWithPassword(dsn, password) if err != nil { return err } dsn = withPw default: return fmt.Errorf("invalid database engine: use %s or %s", config.DatabaseEngineSQLite, config.DatabaseEnginePostgres) } d := conf.Database() d.Engine = engine d.DSN = dsn if err := d.Validate(); err != nil { return err } conf.SetDatabaseEngine(engine) conf.SetDatabaseDSN(dsn) return nil } // dsnWithPassword adds the password to a postgres URL or key value DSN, see // config.DSNWithPassword func dsnWithPassword(dsn, password string) (string, error) { return config.DSNWithPassword(dsn, password) } // testDatabaseConnection connects to postgres once and returns the server // version. The error never holds the password. func testDatabaseConnection(d config.Database) (string, error) { cfg, err := parseWithoutLibpqEnv(d.DSN) if err != nil { return "", config.ErrInvalidDatabaseDSN } ctx, cancel := context.WithTimeout(context.Background(), connectionTestTimeout) defer cancel() conn, err := pgx.ConnectConfig(ctx, cfg) if err != nil { return "", config.MaskDSNInError(err, d.DSN) } defer conn.Close(context.Background()) var version string if err := conn.QueryRow(ctx, "SHOW server_version").Scan(&version); err != nil { return "", config.MaskDSNInError(err, d.DSN) } return version, nil } // libpqEnv are the environment variables pgx reads when it parses a DSN var libpqEnv = []string{ "PGHOST", "PGPORT", "PGDATABASE", "PGUSER", "PGPASSWORD", "PGPASSFILE", "PGAPPNAME", "PGCONNECT_TIMEOUT", "PGSSLMODE", "PGSSLKEY", "PGSSLCERT", "PGSSLSNI", "PGSSLROOTCERT", "PGSSLPASSWORD", "PGSSLNEGOTIATION", "PGTARGETSESSIONATTRS", "PGSERVICE", "PGSERVICEFILE", "PGTZ", "PGOPTIONS", "PGMINPROTOCOLVERSION", "PGMAXPROTOCOLVERSION", } // parseWithoutLibpqEnv parses the DSN for the connection test with the // libpq variables of the installer environment removed and the password // file of the home folder (~/.pgpass) not read. The test then uses what the // config holds, not the passwords or settings of root. The variables are // put back before it returns. func parseWithoutLibpqEnv(dsn string) (*pgx.ConnConfig, error) { var cfg *pgx.ConnConfig var parseErr error if err := withoutLibpqEnv(func() { cfg, parseErr = pgx.ParseConfig(dsn) }); err != nil { return nil, err } return cfg, parseErr } // withoutLibpqEnv runs fn with the libpq variables removed and PGPASSFILE // set to an empty file, and puts the variables back after func withoutLibpqEnv(fn func()) error { saved := map[string]string{} for _, name := range libpqEnv { if v, ok := os.LookupEnv(name); ok { saved[name] = v _ = os.Unsetenv(name) } } defer func() { for _, name := range libpqEnv { if v, ok := saved[name]; ok { _ = os.Setenv(name, v) } else { _ = os.Unsetenv(name) } } }() // an explicit empty password file, a passfile in the DSN still wins if err := os.Setenv("PGPASSFILE", os.DevNull); err != nil { return err } fn() return nil } // describeDatabase returns the transport warning and the target shown for // the DSN, parsed without the libpq variables like the connection test, so // what is shown is what the test uses func describeDatabase(d config.Database) (warning, target string) { if err := withoutLibpqEnv(func() { warning = d.TransportWarning() target = d.DisplayDSN() }); err != nil { return "", "the configured database" } return warning, target } // checkDatabase prints the transport warning and tests the postgres // connection. When the test fails and ask is set, the operator can go on, // as a database that trusts the service user by peer login refuses root. // Without ask a failed test only prints a warning. func checkDatabase(conf *config.Config, ask bool, in io.Reader) error { if !usesPostgres(conf) { return nil } d := conf.Database() warning, target := describeDatabase(d) if warning != "" { fmt.Printf("Warning: %s\n", warning) } fmt.Printf("Testing the database connection to %s\n", target) version, err := testDatabaseConnection(d) if err == nil { fmt.Printf("Connected to PostgreSQL %s\n", version) return nil } fmt.Printf("Database connection failed: %s\n", err) if !ask { fmt.Println("Warning: continuing, the service will not start until the database can be reached") return nil } fmt.Print("Continue anyway? Type 'yes' to continue: ") answer, _ := bufio.NewReader(in).ReadString('\n') if strings.TrimSpace(strings.ToLower(answer)) != "yes" { return errors.New("database connection test failed") } return nil } // maxPlacedConfigSize bounds the config file the installer reads const maxPlacedConfigSize = 1 << 20 // serviceUnitPath is the systemd unit file of the service var serviceUnitPath = filepath.Join("/etc/systemd/system", serviceName+".service") // lookupServiceUser returns nil when the service user exists var lookupServiceUser = func() error { _, err := user.Lookup(serviceUser) return err } // notFirstInstall returns why this is not a first install, empty when // neither the service user nor the unit file of the service exist. After // an install, a process of the service user can still hold a file in the // install folder open for writing, even when the folder and the file are // given to root again, so only the files of a first install are trusted. func notFirstInstall() string { err := lookupServiceUser() if err == nil { return fmt.Sprintf("the %s user exists, this is not a first install", serviceUser) } var unknown user.UnknownUserError if !errors.As(err, &unknown) { return fmt.Sprintf("the %s user can not be looked up", serviceUser) } if _, err := os.Lstat(serviceUnitPath); !errors.Is(err, os.ErrNotExist) { return fmt.Sprintf("%s exists, this is not a first install", serviceUnitPath) } return "" } // trustedOwners are the user ids that may own a placed config, the password // file it names and the folders above them. Only root, tests add their own // user. var trustedOwners = []uint32{0} // placedConfig is a config file placed in the install directory before the // install type placedConfig struct { // postgres is true when the file names the postgres engine postgres bool // conf is the whole config. It is nil when a user other than root could // change the config file or the password file it names. Then no file the // config names is read and the database is not tested, so root never // sends a file to a host chosen by another user. conf *config.Config // untrusted says why conf is nil untrusted string // unread says why the file was not read, then postgres is taken from // the installed unit file unread string } // installedConfig reads the config file in the install directory, nil when // there is none func installedConfig() (*placedConfig, error) { return readPlacedConfig(filepath.Join(installDir, "config.json")) } // checkPlacedDatabase reads the config file placed at path and tests its // database. It returns whether the config runs on postgres. The test is // skipped when a user other than root could change the config file or its // password file. func checkPlacedDatabase(path string) (bool, error) { placed, err := readPlacedConfig(path) if err != nil { return false, err } if placed != nil && placed.unread != "" { // the service reads the config when it starts, so the install goes // on with the engine of the installed unit file fmt.Printf("Warning: %s\n", placed.unread) engine := config.DatabaseEngineSQLite if placed.postgres { engine = config.DatabaseEnginePostgres } fmt.Printf("The install goes on with the %s steps, the service reads the config when it starts\n", engine) return placed.postgres, nil } if placed == nil || !placed.postgres { return false, nil } if placed.conf == nil { fmt.Printf("Skipping the database connection test: %s\n", placed.untrusted) fmt.Println("The test only runs on a first install, before the phishingclub user and its unit file exist, when only root can change the config file, its password file and the folders above them") return true, nil } return true, checkDatabase(placed.conf, false, os.Stdin) } // readPlacedConfig reads the config file at path, nil when there is none. // A symlink on the way is followed only when only root could have made it // (see followTrusted). The file is read for its engine. When it can not be // read that way, or is not valid JSON, unread says why and the engine is // taken from the installed unit file. The whole config, which reads the // password file, is only built on a first install (see notFirstInstall) and // when the config file and the password file can only be changed by root, // see pathNotTrusted. func readPlacedConfig(path string) (*placedConfig, error) { real, err := followTrusted(path) if errors.Is(err, os.ErrNotExist) { return nil, nil } if err != nil { return unreadConfig(fmt.Sprintf("%s is not read: %v", path, err)), nil } // no symlink, and a FIFO in place of the file must not block the read f, err := os.OpenFile(real, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0) // #nosec G304 fixed path in the install directory if errors.Is(err, os.ErrNotExist) { return nil, nil } if err != nil { return unreadConfig(fmt.Sprintf("%s is not read: %v", path, err)), nil } defer f.Close() info, err := f.Stat() if err != nil { return unreadConfig(fmt.Sprintf("%s is not read: %v", path, err)), nil } if !info.Mode().IsRegular() { return unreadConfig(fmt.Sprintf("%s is not read: it is not a regular file", path)), nil } path = real var dto config.ConfigDTO if err := json.NewDecoder(io.LimitReader(f, maxPlacedConfigSize)).Decode(&dto); err != nil { return unreadConfig(fmt.Sprintf("%s is not a valid config, the service will not start until it is fixed: %v", path, err)), nil } placed := &placedConfig{postgres: dto.Database.Engine == config.DatabaseEnginePostgres} if reason := notFirstInstall(); reason != "" { placed.untrusted = reason return placed, nil } if reason := pathNotTrusted(path); reason != "" { placed.untrusted = reason return placed, nil } // the file read is the file checked if checked, err := os.Lstat(path); err != nil || !os.SameFile(info, checked) { placed.untrusted = fmt.Sprintf("%s changed while it was read", path) return placed, nil } // the password file checked, NewConfig picks it the same way passwordFile := "" var passwordInfo os.FileInfo if placed.postgres { passwordFile = dto.Database.PasswordFile if env := os.Getenv(config.EnvDatabasePasswordFile); env != "" { passwordFile = env } if passwordFile != "" { if reason := pathNotTrusted(passwordFile); reason != "" { placed.untrusted = "the password file " + reason return placed, nil } info, err := os.Lstat(passwordFile) if err != nil { placed.untrusted = fmt.Sprintf("the password file %s can not be read", passwordFile) return placed, nil } passwordInfo = info } } readPassword := func(p string) (string, error) { if passwordInfo == nil || p != passwordFile { return "", fmt.Errorf("%w: %s was not checked", config.ErrDatabasePasswordFile, p) } return readCheckedPasswordFile(p, passwordInfo) } conf, err := config.FromDTOWithPasswordReader(&dto, readPassword) if err != nil { return nil, fmt.Errorf("invalid config %s: %w", path, err) } placed.conf = conf return placed, nil } // unreadConfig is a config file that was not read, its engine is taken from // the installed unit file func unreadConfig(reason string) *placedConfig { return &placedConfig{postgres: unitUsesPostgres(), untrusted: reason, unread: reason} } // unitUsesPostgres is true when the installed unit file starts the service // after postgres, as the install on postgres writes it func unitUsesPostgres() bool { f, err := os.OpenFile(serviceUnitPath, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0) // #nosec G304 fixed path of root if err != nil { return false } defer f.Close() if info, err := f.Stat(); err != nil || !info.Mode().IsRegular() { return false } b, err := io.ReadAll(io.LimitReader(f, 1<<16)) return err == nil && strings.Contains(string(b), "postgresql.service") } // readCheckedPasswordFile reads the password file at path that was checked // by pathNotTrusted. It is opened without following a symlink and without // blocking on a FIFO, and it must be the regular file that was checked. func readCheckedPasswordFile(path string, checked os.FileInfo) (string, error) { f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0) // #nosec G304 path checked by pathNotTrusted if err != nil { return "", fmt.Errorf("%w: %s can not be read", config.ErrDatabasePasswordFile, path) } defer f.Close() info, err := f.Stat() if err != nil || !info.Mode().IsRegular() || !os.SameFile(info, checked) { return "", fmt.Errorf("%w: %s changed after it was checked", config.ErrDatabasePasswordFile, path) } return config.ReadDatabasePassword(f, path) } // pathNotTrusted returns why a user other than root could change the file // at path or put another file in its place, empty when only root can. The // path must be absolute and clean (no . or .. parts, as the kernel follows a // symlink before a .. part). The file must be a regular file owned by root, // with one link and not writable by group or others. Every folder from / // down to it must be owned by root, must not be a symlink and must not be // writable by group or others, unless it has the sticky bit (as /tmp), where // others can not move what root owns. func pathNotTrusted(path string) string { if !filepath.IsAbs(path) { return fmt.Sprintf("%s is not an absolute path", path) } if filepath.Clean(path) != path { return fmt.Sprintf("%s is not a clean path", path) } parts := strings.Split(strings.TrimPrefix(path, "/"), "/") current := "/" for i := 0; i <= len(parts); i++ { if i > 0 { current = filepath.Join(current, parts[i-1]) } info, err := os.Lstat(current) if err != nil { return fmt.Sprintf("%s can not be read", current) } last := i == len(parts) if info.Mode()&os.ModeSymlink != 0 { return fmt.Sprintf("%s is a symlink", current) } if last && !info.Mode().IsRegular() { return fmt.Sprintf("%s is not a regular file", current) } if !last && !info.IsDir() { return fmt.Sprintf("%s is not a folder", current) } st, ok := info.Sys().(*syscall.Stat_t) if !ok { return fmt.Sprintf("the owner of %s can not be read", current) } if !slices.Contains(trustedOwners, st.Uid) { return fmt.Sprintf("%s is owned by user %d, not root", current, st.Uid) } if info.Mode().Perm()&0022 != 0 && (last || info.Mode()&os.ModeSticky == 0) { return fmt.Sprintf("%s is writable by group or others", current) } // a hard link can make a file of root appear in a folder of others if last && st.Nlink != 1 { return fmt.Sprintf("%s has more than one hard link", current) } } return "" } // usesPostgres is true when the config runs on postgres func usesPostgres(conf *config.Config) bool { return conf != nil && conf.Database().Engine == config.DatabaseEnginePostgres }