// Copyright (c) Tailscale Inc & contributors // SPDX-License-Identifier: BSD-3-Clause //go:build (linux && !android) || (darwin && !ios) || freebsd || openbsd || plan9 package tailssh import ( "bytes" "crypto/ecdsa" "crypto/ed25519" "crypto/elliptic" "crypto/mldsa" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "fmt" "os" "path/filepath" "slices" "strings" "sync" "golang.org/x/crypto/ssh" "tailscale.com/types/logger" "tailscale.com/util/mak" ) type hostKeySpec struct { // typ is the filename stem used in /etc/ssh/ssh_host__key and // $TAILSCALE_VAR/ssh/ssh_host__key. typ string // algo is the SSH host key algorithm required in // [ssh.SupportedAlgorithms] for this key type to be used. algo string } // allHostKeySpecs are the SSH host key types that tailssh tries to read from // the system's OpenSSH keys or generate under $TAILSCALE_VAR/ssh. var allHostKeySpecs = []hostKeySpec{ {typ: "rsa", algo: ssh.KeyAlgoRSASHA256}, {typ: "ecdsa", algo: ssh.KeyAlgoECDSA256}, {typ: "ed25519", algo: ssh.KeyAlgoED25519}, {typ: "mldsa44", algo: ssh.KeyAlgoMLDSA44}, {typ: "mldsa44_ed25519", algo: ssh.KeyAlgoMLDSA44Ed25519}, } // supportedHostKeySpecs returns the entries in allHostKeySpecs whose algorithm // is supported by the current build. func supportedHostKeySpecs() []hostKeySpec { supported := ssh.SupportedAlgorithms().HostKeys out := make([]hostKeySpec, 0, len(allHostKeySpecs)) for _, spec := range allHostKeySpecs { if slices.Contains(supported, spec.algo) { out = append(out, spec) } } return out } // 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) 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. func getHostKeyPublicStrings(varRoot string, logf logger.Logf) ([]string, error) { signers, err := getHostKeys(varRoot, logf) if err != nil { return nil, err } var keyStrings []string for _, signer := range signers { keyStrings = append(keyStrings, strings.TrimSpace(string(ssh.MarshalAuthorizedKey(signer.PublicKey())))) } return keyStrings, nil } // getTailscaleHostKeys returns the supported SSH host keys, reusing any // signers already present in existing. func getTailscaleHostKeys(varRoot string, existing map[string]ssh.Signer) (keys []ssh.Signer, err error) { var keyDir string // lazily initialized $TAILSCALE_VAR/ssh dir. for _, spec := range supportedHostKeySpecs() { typ := spec.typ if s, ok := existing[typ]; ok { keys = append(keys, s) continue } if keyDir == "" { if varRoot == "" { return nil, errors.New("no var root for ssh keys") } keyDir = filepath.Join(varRoot, "ssh") if err := os.MkdirAll(keyDir, 0700); err != nil { return nil, err } } hostKey, err := hostKeyFileOrCreate(keyDir, typ) if err != nil { return nil, fmt.Errorf("error creating SSH host key type %q in %q: %w", typ, keyDir, err) } signer, err := ssh.ParsePrivateKey(hostKey) if err != nil { return nil, fmt.Errorf("error parsing SSH host key type %q from %q: %w", typ, keyDir, err) } keys = append(keys, signer) } 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 // their callers. // // Technically we actually want to have a mutex per directory (the keyDir // passed), but that's overkill for how rarely keys are loaded or generated. var keyGenMu sync.Mutex func hostKeyFileOrCreate(keyDir, typ string) ([]byte, error) { keyGenMu.Lock() defer keyGenMu.Unlock() path := filepath.Join(keyDir, "ssh_host_"+typ+"_key") v, err := os.ReadFile(path) if err == nil { return v, nil } if !os.IsNotExist(err) { return nil, err } var priv any switch typ { default: return nil, fmt.Errorf("unsupported key type %q", typ) case "ed25519": _, priv, err = ed25519.GenerateKey(rand.Reader) case "ecdsa": // curve is arbitrary. We pick whatever will at // least pacify clients as the actual encryption // doesn't matter: it's all over WireGuard anyway. curve := elliptic.P256() priv, err = ecdsa.GenerateKey(curve, rand.Reader) case "rsa": // keySize is arbitrary. We pick whatever will at // least pacify clients as the actual encryption // doesn't matter: it's all over WireGuard anyway. const keySize = 2048 priv, err = rsa.GenerateKey(rand.Reader, keySize) case "mldsa44": priv, err = mldsa.GenerateKey(mldsa.MLDSA44()) case "mldsa44_ed25519": priv, err = ssh.GenerateCompositeKey(ssh.KeyAlgoMLDSA44Ed25519) } if err != nil { return nil, err } pemGen, err := marshalHostPrivateKey(priv) if err != nil { return nil, err } // Private host keys are for tailscaled only: no group/other access, // so 0600 rather than 0700 (which would needlessly allow the key to // be walked into). err = os.WriteFile(path, pemGen, 0600) return pemGen, err } func marshalHostPrivateKey(priv any) ([]byte, error) { if _, ok := priv.(*ssh.CompositePrivateKey); ok { block, err := ssh.MarshalPrivateKey(priv, "") if err != nil { return nil, err } return pem.EncodeToMemory(block), nil } mk, err := x509.MarshalPKCS8PrivateKey(priv) if err != nil { return nil, err } return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: mk}), nil } // getSystemHostKeys returns the system's OpenSSH host keys that tailssh can // read, keyed by type. It returns nil if there are none. func getSystemHostKeys(logf logger.Logf) (ret map[string]ssh.Signer) { for _, spec := range supportedHostKeySpecs() { typ := spec.typ filename := testHookSystemHostKeyFile(typ) if filename == "" { continue } hostKey, err := os.ReadFile(filename) if err != nil || len(bytes.TrimSpace(hostKey)) == 0 { continue } signer, err := ssh.ParsePrivateKey(hostKey) if err != nil { logf("warning: error reading host key %s: %v (generating one instead)", filename, err) continue } mak.Set(&ret, typ, signer) } return ret }