Ansible checks the server's host key, and secrets stay off command lines

- Every playbook ran with ANSIBLE_HOST_KEY_CHECKING=False, so anyone in
  the middle could pose as the server and be handed the sudo password
  and every secret in vars.yml. Ansible's ssh now uses
  StrictHostKeyChecking=accept-new, like interzone's own ssh calls: a
  new server is trusted on first sight, a changed key stops the run.
- The ssh connection-sharing folder in /tmp is only used when it's this
  user's own and closed to others; someone else could have made it
  first and planted a socket.
- Registering a user passed the password in --extra-vars, readable with
  ps. It goes through a 0600 vars file, like the other admin actions.
- The restore source and backup destination are passed as JSON, so a
  path with a space no longer breaks them.
- The update preview's git fetch puts "--" before the URL, as every
  other git call does.
- A domain's backup list no longer includes dumps of another domain
  that starts with the same name and a dash (a.org vs a.org-b.net).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NarratorandClaude Opus 5.5 committed 2026-10-29 19:28:07 +01:00
1 parent 13b14ab230
commit 87e848dede
6 files changed
+84 -17

No files matched your search

+8 -1
View File
@@ -8,6 +8,7 @@ import (
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
@@ -21,12 +22,18 @@ type LocalBackup struct {
Size int64
}
var backupStamp = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}-\d{4}\.sql\.gz$`)
// ListBackups returns the dumps of domain in BackupDir, newest first: those
// "Back up the database" made and those downloaded from the server.
func ListBackups(domain string) []LocalBackup {
m, _ := filepath.Glob(filepath.Join(BackupDir(), domain+"-*.sql.gz"))
var out []LocalBackup
for _, f := range m {
// a.org-* also matches a.org-b.net's dumps.
if !backupStamp.MatchString(strings.TrimPrefix(filepath.Base(f), domain+"-")) {
continue
}
if st, err := os.Stat(f); err == nil && st.Mode().IsRegular() {
out = append(out, LocalBackup{Path: f, Time: st.ModTime(), Size: st.Size()})
}
@@ -105,7 +112,7 @@ func (r *Runner) restore(ctx context.Context) error {
return r.exec(ctx, StepRestore, dir, "ansible-playbook", append([]string{"-i", "inventory/hosts"}, args...)...)
}
r.note(StepRestore, "stopping every service and emptying the database…")
if err := play(prep, "-e", "interzone_restore_src="+src); err != nil {
if err := play(prep, "-e", jsonVars(map[string]string{"interzone_restore_src": src})); err != nil {
return err
}
r.note(StepRestore, "creating an empty database…")
+25
View File
@@ -0,0 +1,25 @@
package deploy
import (
"os"
"path/filepath"
"testing"
)
func TestListBackupsKeepsDomainsApart(t *testing.T) {
t.Setenv("XDG_DATA_HOME", t.TempDir())
if err := os.MkdirAll(BackupDir(), 0o700); err != nil {
t.Fatal(err)
}
for _, n := range []string{"a.org-2026-01-02-0304.sql.gz", "a.org-b.net-2026-01-02-0304.sql.gz"} {
if err := os.WriteFile(filepath.Join(BackupDir(), n), nil, 0o600); err != nil {
t.Fatal(err)
}
}
if l := ListBackups("a.org"); len(l) != 1 || filepath.Base(l[0].Path) != "a.org-2026-01-02-0304.sql.gz" {
t.Errorf("a.org: %+v", l)
}
if l := ListBackups("a.org-b.net"); len(l) != 1 {
t.Errorf("a.org-b.net: %+v", l)
}
}
+1 -1
View File
@@ -64,7 +64,7 @@ func PreviewUpdate(ctx context.Context, c *config.Config) (*Changes, error) {
}
return strings.TrimSpace(string(out)), nil
}
if _, err := git("fetch", "--quiet", c.Sources.PlaybookGit, defaultBranch(dir)); err != nil {
if _, err := git("fetch", "--quiet", "--", c.Sources.PlaybookGit, defaultBranch(dir)); err != nil {
return nil, err
}
ch := &Changes{}
+12 -7
View File
@@ -243,7 +243,6 @@ func Env(c *config.Config) []string {
"GIT_TERMINAL_PROMPT=0",
"ANSIBLE_NOCOLOR=1",
"ANSIBLE_FORCE_COLOR=0",
"ANSIBLE_HOST_KEY_CHECKING=False",
"ANSIBLE_STDOUT_CALLBACK=default",
"PATH="+filepath.Join(venvDir(), "bin")+string(os.PathListSeparator)+os.Getenv("PATH"),
)
@@ -258,9 +257,10 @@ func Env(c *config.Config) []string {
if idx := c.Sources.PyPIIndex; idx != "" {
env = append(env, "PIP_INDEX_URL="+idx)
}
if reuse := sshReuse(); reuse != nil {
env = append(env, "ANSIBLE_SSH_ARGS=-C "+strings.Join(reuse, " "))
}
// A server seen before must still have the same key, as for
// interzone's own ssh calls: Ansible hands it the sudo password and
// every secret.
env = append(env, "ANSIBLE_SSH_ARGS="+strings.Join(append([]string{"-C", "-o", "StrictHostKeyChecking=accept-new"}, sshReuse()...), " "))
return env
}
@@ -570,8 +570,13 @@ func (r *Runner) register(ctx context.Context) error {
if u.Admin {
admin = "yes"
}
vars, _ := json.Marshal(map[string]string{"username": u.Name, "password": u.Password, "admin": admin})
return r.playbookRun(ctx, StepRegister, "--tags=register-user", "--extra-vars", string(vars))
// Through a 0600 file: on the command line, ps shows the password.
f, err := writeVarsFile(r.cfg.PlaybookDir, map[string]string{"username": u.Name, "password": u.Password, "admin": admin})
if err != nil {
return err
}
defer os.Remove(f)
return r.playbookRun(ctx, StepRegister, "--tags=register-user", "--extra-vars", "@"+f)
}
var validateVar = regexp.MustCompile(`(?m)^([a-z0-9_]+_self_check_validate_certificates):`)
@@ -706,7 +711,7 @@ func (r *Runner) backup(ctx context.Context) error {
return err
}
if err := r.exec(ctx, StepBackup, r.cfg.PlaybookDir, "ansible-playbook", "-i", "inventory/hosts", play,
"-e", "interzone_backup_dest="+dest); err != nil {
"-e", jsonVars(map[string]string{"interzone_backup_dest": dest})); err != nil {
return err
}
_ = os.Chmod(dest, 0o600)
+10
View File
@@ -11,6 +11,7 @@ import (
"path/filepath"
"strings"
"sync/atomic"
"syscall"
"time"
"interzone/internal/config"
@@ -43,6 +44,15 @@ func sshReuse() []string {
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil
}
// In a shared /tmp someone else could have made it first, and planted
// a socket that ssh would hand the session (and the sudo password) to.
fi, err := os.Lstat(dir)
if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o700 {
return nil
}
if st, ok := fi.Sys().(*syscall.Stat_t); !ok || int(st.Uid) != os.Getuid() {
return nil
}
return []string{"-o", "ControlMaster=auto", "-o", "ControlPersist=10m", "-o", "ControlPath=" + filepath.Join(dir, "%C"),
"-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3"}
}
+28 -8
View File
@@ -26,6 +26,31 @@ func (t TaskResult) String(key string) string {
// runPlayJSON runs a play against the server with Ansible's json output
// and returns each named task's result. vars are passed through a
// temporary owner-only file so secrets never show up in ps.
// writeVarsFile writes extra vars that hold secrets to a 0600 file in the
// inventory, for "-e @file"; the caller removes it.
func writeVarsFile(dir string, vars any) (string, error) {
f, err := os.CreateTemp(filepath.Join(dir, "inventory"), ".interzone-vars-*.json")
if err != nil {
return "", err
}
err = json.NewEncoder(f).Encode(vars)
if cerr := f.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(f.Name())
return "", err
}
return f.Name(), nil
}
// jsonVars is extra vars as JSON, which Ansible doesn't split on spaces
// the way it does key=value.
func jsonVars(vars map[string]string) string {
b, _ := json.Marshal(vars)
return string(b)
}
func runPlayJSON(ctx context.Context, c *config.Config, name, play string, vars map[string]any, args ...string) (map[string]TaskResult, error) {
bin, err := lookPath("ansible-playbook")
if err != nil {
@@ -56,17 +81,12 @@ func runPlayJSON(ctx context.Context, c *config.Config, name, play string, vars
}
cmdArgs := []string{"-i", "inventory/hosts", playFile}
if len(vars) > 0 {
f, err := os.CreateTemp(filepath.Join(dir, "inventory"), ".interzone-vars-*.json")
f, err := writeVarsFile(dir, vars)
if err != nil {
return nil, err
}
defer os.Remove(f.Name())
if err := json.NewEncoder(f).Encode(vars); err != nil {
f.Close()
return nil, err
}
f.Close()
cmdArgs = append(cmdArgs, "-e", "@"+f.Name())
defer os.Remove(f)
cmdArgs = append(cmdArgs, "-e", "@"+f)
}
cmd := exec.CommandContext(ctx, bin, append(cmdArgs, args...)...)
cmd.Dir = dir