diff --git a/ssh/tailssh/hostkeys.go b/ssh/tailssh/hostkeys.go index c22d3a266..d873663b7 100644 --- a/ssh/tailssh/hostkeys.go +++ b/ssh/tailssh/hostkeys.go @@ -31,12 +31,50 @@ import ( // running as root. var keyTypes = []string{"rsa", "ecdsa", "ed25519"} -// getHostKeys returns the SSH host keys, using the system's OpenSSH keys when -// they are readable (see systemHostKeyFile) and generating Tailscale-specific -// keys as needed. +// testHookSystemHostKeyFile is systemHostKeyFile, replaceable by tests. +var testHookSystemHostKeyFile = systemHostKeyFile + +// hostKeysMu guards hostKeysByRoot. +var hostKeysMu sync.Mutex + +// hostKeysByRoot caches the host keys loaded by [getHostKeys], keyed by var +// root. +var hostKeysByRoot map[string][]ssh.Signer + +// getHostKeys returns the SSH host keys. For each key type, it uses the +// Tailscale-specific key in varRoot if one was previously generated, else the +// system's OpenSSH key if readable (see systemHostKeyFile), else it generates +// a Tailscale-specific key. +// +// Peers only learn this node's host keys from Hostinfo, so the keys must not +// change underneath them. On macOS, launchd's sshd-keygen-wrapper creates +// missing system host keys on any TCP connection to port 22, so preferring +// system keys over previously generated ones would switch keys long after +// they were advertised. +// +// The keys are loaded once per varRoot and then cached for the life of the +// process, so system keys regenerated on disk take effect (and are +// advertised) only when tailscaled restarts. func getHostKeys(varRoot string, logf logger.Logf) ([]ssh.Signer, error) { + hostKeysMu.Lock() + defer hostKeysMu.Unlock() + if keys, ok := hostKeysByRoot[varRoot]; ok { + return keys, nil + } existing := getSystemHostKeys(logf) - return getTailscaleHostKeys(varRoot, existing) + if varRoot != "" { + for typ := range existing { + if _, err := os.Stat(tailscaleHostKeyFile(varRoot, typ)); err == nil { + delete(existing, typ) + } + } + } + keys, err := getTailscaleHostKeys(varRoot, existing) + if err != nil { + return nil, err + } + mak.Set(&hostKeysByRoot, varRoot, keys) + return keys, nil } // getHostKeyPublicStrings returns the SSH host key public key strings. @@ -83,6 +121,12 @@ func getTailscaleHostKeys(varRoot string, existing map[string]ssh.Signer) (keys return keys, nil } +// tailscaleHostKeyFile returns the path of the Tailscale-specific host key of +// the given type in varRoot, as generated by [getTailscaleHostKeys]. +func tailscaleHostKeyFile(varRoot, typ string) string { + return filepath.Join(varRoot, "ssh", "ssh_host_"+typ+"_key") +} + // keyGenMu protects concurrent generation of host keys with // [hostKeyFileOrCreate], making sure two callers don't try to concurrently find // a missing key and generate it at the same time, returning different keys to @@ -142,7 +186,7 @@ func hostKeyFileOrCreate(keyDir, typ string) ([]byte, error) { // read, keyed by type. It returns nil if there are none. func getSystemHostKeys(logf logger.Logf) (ret map[string]ssh.Signer) { for _, typ := range keyTypes { - filename := systemHostKeyFile(typ) + filename := testHookSystemHostKeyFile(typ) if filename == "" { continue } diff --git a/ssh/tailssh/hostkeys_test.go b/ssh/tailssh/hostkeys_test.go index ad0a9b5dc..0873920ca 100644 --- a/ssh/tailssh/hostkeys_test.go +++ b/ssh/tailssh/hostkeys_test.go @@ -9,7 +9,11 @@ import ( "os" "path/filepath" "reflect" + "strings" "testing" + + "golang.org/x/crypto/ssh" + "tailscale.com/tstest" ) func TestSSHKeyGen(t *testing.T) { @@ -50,3 +54,106 @@ func TestSSHKeyGen(t *testing.T) { t.Errorf("got different keys on second call") } } + +// useFakeSystemHostKeys makes the system host key files live in a temp +// directory, which it returns. +func useFakeSystemHostKeys(t *testing.T) string { + sysDir := t.TempDir() + tstest.Replace(t, &testHookSystemHostKeyFile, func(typ string) string { + return filepath.Join(sysDir, "ssh_host_"+typ+"_key") + }) + return sysDir +} + +// writeFakeSystemHostKeys generates host keys of the given types into sysDir, +// as OpenSSH would. +func writeFakeSystemHostKeys(t *testing.T, sysDir string, types ...string) { + t.Helper() + genRoot := t.TempDir() + if _, err := getTailscaleHostKeys(genRoot, nil); err != nil { + t.Fatal(err) + } + for _, typ := range types { + if err := os.Rename(tailscaleHostKeyFile(genRoot, typ), filepath.Join(sysDir, "ssh_host_"+typ+"_key")); err != nil { + t.Fatal(err) + } + } +} + +// forgetHostKeys drops the cached host keys for varRoot, as if tailscaled had +// restarted. +func forgetHostKeys(varRoot string) { + hostKeysMu.Lock() + defer hostKeysMu.Unlock() + delete(hostKeysByRoot, varRoot) +} + +func publicKeyStrings(t *testing.T, signers []ssh.Signer) []string { + t.Helper() + var ret []string + for _, s := range signers { + ret = append(ret, strings.TrimSpace(string(ssh.MarshalAuthorizedKey(s.PublicKey())))) + } + return ret +} + +// TestHostKeysStableWhenSystemKeysAppear tests that the host keys don't change +// when OpenSSH creates its host keys after tailssh has already generated its +// own, as launchd's sshd-keygen-wrapper does on macOS on any connection to +// port 22. Peers only learn this node's keys from Hostinfo, so switching keys +// broke "tailscale ssh" to the node for everyone. +func TestHostKeysStableWhenSystemKeysAppear(t *testing.T) { + sysDir := useFakeSystemHostKeys(t) + varRoot := t.TempDir() + advertised, err := getHostKeyPublicStrings(varRoot, t.Logf) + if err != nil { + t.Fatal(err) + } + + writeFakeSystemHostKeys(t, sysDir, keyTypes...) + + served, err := getHostKeys(varRoot, t.Logf) + if err != nil { + t.Fatal(err) + } + if got := publicKeyStrings(t, served); !reflect.DeepEqual(got, advertised) { + t.Errorf("served host keys changed after system keys appeared:\nadvertised: %q\nserved: %q", advertised, got) + } + + forgetHostKeys(varRoot) + served, err = getHostKeys(varRoot, t.Logf) + if err != nil { + t.Fatal(err) + } + if got := publicKeyStrings(t, served); !reflect.DeepEqual(got, advertised) { + t.Errorf("host keys changed across restart after system keys appeared:\nbefore: %q\nafter: %q", advertised, got) + } +} + +// TestHostKeysPreferGenerated tests that system host keys are used only for +// key types that tailssh hasn't generated its own key for. +func TestHostKeysPreferGenerated(t *testing.T) { + sysDir := useFakeSystemHostKeys(t) + writeFakeSystemHostKeys(t, sysDir, keyTypes...) + sysKeys := getSystemHostKeys(t.Logf) + + varRoot := t.TempDir() + genKeys, err := getTailscaleHostKeys(varRoot, nil) + if err != nil { + t.Fatal(err) + } + for _, typ := range []string{"rsa", "ecdsa"} { + if err := os.Remove(tailscaleHostKeyFile(varRoot, typ)); err != nil { + t.Fatal(err) + } + } + + served, err := getHostKeys(varRoot, t.Logf) + if err != nil { + t.Fatal(err) + } + want := publicKeyStrings(t, []ssh.Signer{sysKeys["rsa"], sysKeys["ecdsa"], genKeys[2]}) + if got := publicKeyStrings(t, served); !reflect.DeepEqual(got, want) { + t.Errorf("served = %q; want system rsa and ecdsa keys and generated ed25519 key %q", got, want) + } +}