From 01df84d1feaa4bb006f91aa0beac3538f05357ac Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Fri, 6 Nov 2026 14:13:00 +0000 Subject: [PATCH] hscontrol: check files named by the config without writing Updates #3443 --- hscontrol/app.go | 16 +- hscontrol/check.go | 183 +++++++++++++++++++++++ hscontrol/check_test.go | 320 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 514 insertions(+), 5 deletions(-) create mode 100644 hscontrol/check.go create mode 100644 hscontrol/check_test.go diff --git a/hscontrol/app.go b/hscontrol/app.go index af627dbd2..6f82127b5 100644 --- a/hscontrol/app.go +++ b/hscontrol/app.go @@ -1320,7 +1320,7 @@ func readOrCreatePrivateKey(path string) (*key.MachinePrivate, error) { return nil, fmt.Errorf("ensuring private key directory: %w", err) } - privateKey, err := os.ReadFile(path) + machineKey, err := readPrivateKey(path) if errors.Is(err, os.ErrNotExist) { log.Info().Str("path", path).Msg("no private key file at path, creating...") @@ -1344,14 +1344,20 @@ func readOrCreatePrivateKey(path string) (*key.MachinePrivate, error) { } return &machineKey, nil - } else if err != nil { + } + + return machineKey, err +} + +// readPrivateKey reads and parses a key file without creating anything. +func readPrivateKey(path string) (*key.MachinePrivate, error) { + privateKey, err := os.ReadFile(path) + if err != nil { return nil, fmt.Errorf("reading private key file: %w", err) } - trimmedPrivateKey := strings.TrimSpace(string(privateKey)) - var machineKey key.MachinePrivate - if err = machineKey.UnmarshalText([]byte(trimmedPrivateKey)); err != nil { //nolint:noinlineerr + if err = machineKey.UnmarshalText([]byte(strings.TrimSpace(string(privateKey)))); err != nil { //nolint:noinlineerr return nil, fmt.Errorf("parsing private key: %w", err) } diff --git a/hscontrol/check.go b/hscontrol/check.go new file mode 100644 index 000000000..913377430 --- /dev/null +++ b/hscontrol/check.go @@ -0,0 +1,183 @@ +package hscontrol + +import ( + "crypto/tls" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/juanfont/headscale/hscontrol/derp" + "github.com/juanfont/headscale/hscontrol/dns" + policyv2 "github.com/juanfont/headscale/hscontrol/policy/v2" + "github.com/juanfont/headscale/hscontrol/types" + "github.com/juanfont/headscale/hscontrol/util" +) + +var errTooManyLinks = errors.New("too many symbolic links") + +var errSameKey = errors.New("noise and DERP private keys must differ") + +// CheckFiles parses every file the config names and reports all problems +// together. It never creates, writes or contacts anything. +func CheckFiles(cfg *types.Config) error { + var errs []error + + if cfg.Policy.Mode == types.PolicyModeFile && cfg.Policy.Path != "" { + b, err := os.ReadFile(util.AbsolutePathFromConfigPath(cfg.Policy.Path)) + if err == nil { + _, err = policyv2.ParsePolicy(b) + } + + if err != nil { + errs = append(errs, fmt.Errorf("policy.path: %w", err)) + } + } + + if len(cfg.DERP.Paths) > 0 { + _, err := derp.GetDERPMap(types.DERPConfig{Paths: cfg.DERP.Paths}) + if err != nil { + errs = append(errs, fmt.Errorf("derp.paths: %w", err)) + } + } + + if p := cfg.DNSConfig.ExtraRecordsPath; p != "" { + m, err := dns.NewExtraRecordsManager(p) + if err != nil { + errs = append(errs, fmt.Errorf("dns.extra_records_path: %w", err)) + } else { + m.Close() + } + } + + if cfg.TLS.CertPath != "" { + _, err := tls.LoadX509KeyPair(cfg.TLS.CertPath, cfg.TLS.KeyPath) + if err != nil { + errs = append(errs, fmt.Errorf("loading TLS keypair (tls.cert_path=%q, tls.key_path=%q): %w", + cfg.TLS.CertPath, cfg.TLS.KeyPath, err)) + } + } + + noise, err := readOptionalKey(cfg.NoisePrivateKeyPath) + if err != nil { + errs = append(errs, fmt.Errorf("noise.private_key_path: %w", err)) + } + + if cfg.DERP.ServerEnabled { + derpKey, err := readOptionalKey(cfg.DERP.ServerPrivateKeyPath) + if err != nil { + errs = append(errs, fmt.Errorf("derp.server.private_key_path: %w", err)) + } else if samePath(cfg.NoisePrivateKeyPath, cfg.DERP.ServerPrivateKeyPath) || + noise != "" && noise == derpKey { + errs = append(errs, fmt.Errorf("derp.server.private_key_path: %w", errSameKey)) + } + } + + return errors.Join(errs...) +} + +// readOptionalKey returns the key text, or "" when unset or not yet created. +func readOptionalKey(path string) (string, error) { + if path == "" { + return "", nil + } + + k, err := readPrivateKey(path) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + + if err != nil { + return "", err + } + + b, err := k.MarshalText() + + return string(b), err +} + +// samePath catches a shared key file that does not exist yet, which the +// content comparison cannot see but startup rejects after creating it. +func samePath(a, b string) bool { + if a == "" || b == "" { + return false + } + + ra, errA := resolveLoose(a) + rb, errB := resolveLoose(b) + + return errA == nil && errB == nil && ra == rb +} + +// maxSymlinks bounds link expansion so a loop cannot hang the check. +const maxSymlinks = 255 + +// resolveLoose resolves p like `realpath -m`: symlinks are followed +// component by component, including dangling ones, and names that do not +// exist are kept as-is. p is not cleaned first: ".." after a symlink walks +// the link target, not the lexical parent. +func resolveLoose(p string) (string, error) { + if !filepath.IsAbs(p) { + wd, err := os.Getwd() + if err != nil { + return "", err + } + + p = wd + string(filepath.Separator) + p + } + + sep := string(filepath.Separator) + queue := strings.Split(p, sep) + cur := sep + links := 0 + + for len(queue) > 0 { + c := queue[0] + queue = queue[1:] + + switch c { + case "", ".": + continue + case "..": + cur = filepath.Dir(cur) + + continue + } + + next := filepath.Join(cur, c) + + fi, err := os.Lstat(next) + if errors.Is(err, os.ErrNotExist) { + return filepath.Join(append([]string{next}, queue...)...), nil + } + + if err != nil { + return "", err + } + + if fi.Mode()&os.ModeSymlink == 0 { + cur = next + + continue + } + + links++ + if links > maxSymlinks { + return "", fmt.Errorf("%w resolving %q", errTooManyLinks, p) + } + + target, err := os.Readlink(next) + if err != nil { + return "", err + } + + if filepath.IsAbs(target) { + cur = sep + } + + queue = append(strings.Split(target, sep), queue...) + } + + return cur, nil +} diff --git a/hscontrol/check_test.go b/hscontrol/check_test.go new file mode 100644 index 000000000..66772b849 --- /dev/null +++ b/hscontrol/check_test.go @@ -0,0 +1,320 @@ +package hscontrol + +import ( + "os" + "path/filepath" + "testing" + + policyv2 "github.com/juanfont/headscale/hscontrol/policy/v2" + "github.com/juanfont/headscale/hscontrol/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "tailscale.com/types/key" +) + +func TestCheckFiles(t *testing.T) { + keyText := func(t *testing.T) string { + t.Helper() + + k := key.NewMachine() + b, err := k.MarshalText() + require.NoError(t, err) + + return string(b) + } + + write := func(t *testing.T, path, content string) string { + t.Helper() + require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) + + return path + } + + sharedKeys := func(noise, derp string) *types.Config { + return &types.Config{ + NoisePrivateKeyPath: noise, + DERP: types.DERPConfig{ServerEnabled: true, ServerPrivateKeyPath: derp}, + } + } + + tests := []struct { + name string + build func(t *testing.T, dir string) *types.Config + wantErr []string + check func(t *testing.T, dir string, err error) + }{ + { + name: "nothing referenced", + build: func(*testing.T, string) *types.Config { return &types.Config{} }, + }, + { + name: "missing noise key is not created", + build: func(_ *testing.T, dir string) *types.Config { + return &types.Config{NoisePrivateKeyPath: filepath.Join(dir, "sub", "noise.key")} + }, + check: func(t *testing.T, dir string, _ error) { + t.Helper() + assert.NoDirExists(t, filepath.Join(dir, "sub")) + }, + }, + { + name: "corrupt noise key", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + + return &types.Config{NoisePrivateKeyPath: write(t, filepath.Join(dir, "noise.key"), "garbage")} + }, + wantErr: []string{"parsing private key", "noise.private_key_path"}, + }, + { + name: "derp key equals noise key", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + + k := keyText(t) + + return &types.Config{ + NoisePrivateKeyPath: write(t, filepath.Join(dir, "noise.key"), k), + DERP: types.DERPConfig{ + ServerEnabled: true, + ServerPrivateKeyPath: write(t, filepath.Join(dir, "derp.key"), k), + }, + } + }, + wantErr: []string{"derp.server.private_key_path"}, + }, + { + name: "shared missing key path is rejected and not created", + build: func(_ *testing.T, dir string) *types.Config { + p := filepath.Join(dir, "sub", "shared.key") + + return &types.Config{ + NoisePrivateKeyPath: p, + DERP: types.DERPConfig{ServerEnabled: true, ServerPrivateKeyPath: p}, + } + }, + wantErr: []string{"derp.server.private_key_path", "must differ"}, + check: func(t *testing.T, dir string, _ error) { + t.Helper() + assert.NoDirExists(t, filepath.Join(dir, "sub")) + }, + }, + { + name: "shared missing key via symlinked parent is rejected", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + require.NoError(t, os.Mkdir(filepath.Join(dir, "real"), 0o700)) + require.NoError(t, os.Symlink("real", filepath.Join(dir, "alias"))) + + return &types.Config{ + NoisePrivateKeyPath: filepath.Join(dir, "real", "shared.key"), + DERP: types.DERPConfig{ + ServerEnabled: true, + ServerPrivateKeyPath: filepath.Join(dir, "alias", "shared.key"), + }, + } + }, + wantErr: []string{"derp.server.private_key_path", "must differ"}, + check: func(t *testing.T, dir string, _ error) { + t.Helper() + assert.NoFileExists(t, filepath.Join(dir, "real", "shared.key")) + }, + }, + { + name: "dangling leaf symlink to shared missing key is rejected", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + require.NoError(t, os.Symlink(filepath.Join(dir, "shared.key"), filepath.Join(dir, "alias.key"))) + + return sharedKeys(filepath.Join(dir, "shared.key"), filepath.Join(dir, "alias.key")) + }, + wantErr: []string{"derp.server.private_key_path", "must differ"}, + check: func(t *testing.T, dir string, _ error) { + t.Helper() + assert.NoFileExists(t, filepath.Join(dir, "shared.key")) + }, + }, + { + name: "dangling parent symlink to shared missing key is rejected", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + require.NoError(t, os.Mkdir(filepath.Join(dir, "real"), 0o700)) + require.NoError(t, os.Symlink(filepath.Join(dir, "real", "pending"), filepath.Join(dir, "alias"))) + + return sharedKeys( + filepath.Join(dir, "real", "pending", "shared.key"), + filepath.Join(dir, "alias", "shared.key")) + }, + wantErr: []string{"derp.server.private_key_path", "must differ"}, + check: func(t *testing.T, dir string, _ error) { + t.Helper() + assert.NoDirExists(t, filepath.Join(dir, "real", "pending")) + }, + }, + { + name: "dotdot after symlink with dangling key link is rejected", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "base"), 0o700)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "other", "sub"), 0o700)) + require.NoError(t, os.Symlink("../other/sub", filepath.Join(dir, "base", "link"))) + require.NoError(t, os.Symlink("../base/shared.key", filepath.Join(dir, "other", "shared.key"))) + + return sharedKeys( + filepath.Join(dir, "base", "shared.key"), + dir+"/base/link/../shared.key") + }, + wantErr: []string{"derp.server.private_key_path", "must differ"}, + check: func(t *testing.T, dir string, _ error) { + t.Helper() + assert.NoFileExists(t, filepath.Join(dir, "base", "shared.key")) + }, + }, + { + name: "symlink loop errors without hanging", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + require.NoError(t, os.Symlink("b", filepath.Join(dir, "a"))) + require.NoError(t, os.Symlink("a", filepath.Join(dir, "b"))) + + return sharedKeys(filepath.Join(dir, "noise.key"), filepath.Join(dir, "a")) + }, + wantErr: []string{"derp.server.private_key_path"}, + }, + { + name: "dotdot through symlink to a distinct existing key passes", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "a"), 0o700)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "b", "child"), 0o700)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "b", "a"), 0o700)) + require.NoError(t, os.Symlink(filepath.Join(dir, "b", "child"), filepath.Join(dir, "link"))) + write(t, filepath.Join(dir, "a", "key"), keyText(t)) + write(t, filepath.Join(dir, "b", "a", "key"), keyText(t)) + + return &types.Config{ + NoisePrivateKeyPath: filepath.Join(dir, "a", "key"), + DERP: types.DERPConfig{ + ServerEnabled: true, + ServerPrivateKeyPath: dir + "/link/../a/key", + }, + } + }, + check: func(t *testing.T, _ string, err error) { + t.Helper() + require.NoError(t, err) + }, + }, + { + name: "distinct missing key paths pass", + build: func(_ *testing.T, dir string) *types.Config { + return &types.Config{ + NoisePrivateKeyPath: filepath.Join(dir, "sub", "noise.key"), + DERP: types.DERPConfig{ + ServerEnabled: true, + ServerPrivateKeyPath: filepath.Join(dir, "sub", "derp.key"), + }, + } + }, + check: func(t *testing.T, dir string, err error) { + t.Helper() + require.NoError(t, err) + assert.NoDirExists(t, filepath.Join(dir, "sub")) + }, + }, + { + name: "policy with undefined group", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + + p := write(t, filepath.Join(dir, "policy.hujson"), + `{"acls":[{"action":"accept","src":["group:missing"],"dst":["*:*"]}]}`) + + return &types.Config{Policy: types.PolicyConfig{Mode: types.PolicyModeFile, Path: p}} + }, + wantErr: []string{"policy.path"}, + check: func(t *testing.T, _ string, err error) { + t.Helper() + require.ErrorIs(t, err, policyv2.ErrGroupNotDefined) + }, + }, + { + name: "extra records valid", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + + p := write(t, filepath.Join(dir, "extra.json"), `[{"name":"a.example.com","type":"A","value":"100.64.0.1"}]`) + + return &types.Config{DNSConfig: types.DNSConfig{ExtraRecordsPath: p}} + }, + }, + { + name: "extra records malformed", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + + return &types.Config{DNSConfig: types.DNSConfig{ExtraRecordsPath: write(t, filepath.Join(dir, "extra.json"), "{not json")}} + }, + wantErr: []string{"dns.extra_records_path"}, + }, + { + name: "tls cert missing", + build: func(_ *testing.T, dir string) *types.Config { + return &types.Config{TLS: types.TLSConfig{ + CertPath: filepath.Join(dir, "c.pem"), + KeyPath: filepath.Join(dir, "k.pem"), + }} + }, + wantErr: []string{"tls.cert_path", "tls.key_path"}, + }, + { + name: "derp paths empty map", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + + return &types.Config{DERP: types.DERPConfig{Paths: []string{write(t, filepath.Join(dir, "d.yaml"), "{}")}}} + }, + wantErr: []string{"derp.paths"}, + }, + { + name: "all problems reported together", + build: func(t *testing.T, dir string) *types.Config { + t.Helper() + + p := write(t, filepath.Join(dir, "policy.hujson"), + `{"acls":[{"action":"accept","src":["group:missing"],"dst":["*:*"]}]}`) + + return &types.Config{ + Policy: types.PolicyConfig{Mode: types.PolicyModeFile, Path: p}, + TLS: types.TLSConfig{CertPath: filepath.Join(dir, "c.pem"), KeyPath: filepath.Join(dir, "k.pem")}, + DERP: types.DERPConfig{Paths: []string{write(t, filepath.Join(dir, "d.yaml"), "{}")}}, + } + }, + wantErr: []string{"policy.path", "tls.cert_path", "derp.paths"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + err := CheckFiles(tt.build(t, dir)) + + if len(tt.wantErr) == 0 && tt.check == nil { + require.NoError(t, err) + return + } + + if len(tt.wantErr) == 0 { + require.NoError(t, err) + } + + for _, s := range tt.wantErr { + require.ErrorContains(t, err, s) + } + + if tt.check != nil { + tt.check(t, dir, err) + } + }) + } +}