// Package tlsutil handles certificate generation and trust for lanrdp. // // There is no CA and no public PKI involved: the host generates a // self-signed certificate once and keeps it. Clients pin the host's // certificate fingerprint on first connect (trust-on-first-use, the same // model SSH uses for host keys) and refuse to proceed silently if it ever // changes — that would mean either the host was reinstalled or someone is // intercepting the connection. package tlsutil import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "fmt" "math/big" "os" "path/filepath" "strings" "time" ) const certValidity = 10 * 365 * 24 * time.Hour // LoadOrCreateServerCert loads a persisted self-signed certificate/key pair // from dir, generating a fresh one on first run. func LoadOrCreateServerCert(dir string) (tls.Certificate, error) { certPath := filepath.Join(dir, "host.crt") keyPath := filepath.Join(dir, "host.key") if cert, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil { return cert, nil } if err := os.MkdirAll(dir, 0o700); err != nil { return tls.Certificate{}, err } priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return tls.Certificate{}, err } serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) if err != nil { return tls.Certificate{}, err } tmpl := &x509.Certificate{ SerialNumber: serial, Subject: pkix.Name{CommonName: "lanrdp-host"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(certValidity), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true, } der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv) if err != nil { return tls.Certificate{}, err } certOut, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return tls.Certificate{}, err } defer certOut.Close() if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil { return tls.Certificate{}, err } keyBytes, err := x509.MarshalECPrivateKey(priv) if err != nil { return tls.Certificate{}, err } keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return tls.Certificate{}, err } defer keyOut.Close() if err := pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}); err != nil { return tls.Certificate{}, err } return tls.LoadX509KeyPair(certPath, keyPath) } // Fingerprint returns a SHA-256 fingerprint of a DER-encoded certificate, // formatted like an SSH key fingerprint (colon-separated hex) for easy // out-of-band comparison. func Fingerprint(der []byte) string { sum := sha256.Sum256(der) parts := make([]string, len(sum)) for i, b := range sum { parts[i] = fmt.Sprintf("%02x", b) } return strings.Join(parts, ":") }