// Package paneltls generates and loads the panel's own TLS material so the // control panel can be reached over HTTPS without a public domain name. The // certificate is self signed, valid for the machine hostname and every local // address, and is rotated automatically well before it expires. package paneltls import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/hex" "encoding/pem" "fmt" "math/big" "net" "os" "path/filepath" "strings" "time" ) const ( certFile = "panel.crt" keyFile = "panel.key" // A long lived self signed certificate keeps browsers quiet for years while // the panel rotates it 30 days before expiry on its own. validity = 10 * 365 * 24 * time.Hour renewBefore = 30 * 24 * time.Hour orgName = "MiaoPanel" ) // Material describes the active certificate. type Material struct { CertPath string KeyPath string Cert *x509.Certificate Fingerprint string // SHA-256, upper case, colon separated SelfSigned bool Hosts []string } // Ensure returns usable certificate material for dir, generating a fresh self // signed certificate when none exists, when it is close to expiry or when the // set of local addresses changed (DHCP, new NIC, cloud IP reassignment). func Ensure(dir string, hosts []string) (*Material, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("创建证书目录 %s: %w", dir, err) } certPath := filepath.Join(dir, certFile) keyPath := filepath.Join(dir, keyFile) if m, err := load(certPath, keyPath); err == nil { if time.Until(m.Cert.NotAfter) > renewBefore && covers(m.Cert, hosts) { m.Hosts = hosts return m, nil } } return generate(certPath, keyPath, hosts) } // Load reads an existing certificate pair supplied by the operator. func Load(certPath, keyPath string) (*Material, error) { m, err := load(certPath, keyPath) if err != nil { return nil, err } m.SelfSigned = false return m, nil } // Config builds a server TLS configuration pinned to TLS 1.2+ and HTTP/1.1. // HTTP/2 is intentionally not advertised: the panel speaks plain JSON and the // multiplexed listener has to stay dependency free. func (m *Material) Config() (*tls.Config, error) { pair, err := tls.LoadX509KeyPair(m.CertPath, m.KeyPath) if err != nil { return nil, fmt.Errorf("加载证书 %s: %w", m.CertPath, err) } return &tls.Config{ MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{pair}, NextProtos: []string{"http/1.1"}, }, nil } // LocalHosts returns the hostname plus every unicast address of this machine. func LocalHosts() []string { seen := map[string]bool{} var out []string add := func(h string) { h = strings.TrimSpace(h) if h == "" || seen[h] { return } seen[h] = true out = append(out, h) } if name, err := os.Hostname(); err == nil { add(name) if i := strings.IndexByte(name, '.'); i > 0 { add(name[:i]) } } add("localhost") add("127.0.0.1") if addrs, err := net.InterfaceAddrs(); err == nil { for _, a := range addrs { var ip net.IP switch v := a.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil || ip.IsUnspecified() || ip.IsLinkLocalUnicast() { continue } add(ip.String()) } } if ip := localOutboundIP(); ip != nil { add(ip.String()) } return out } // localOutboundIP finds the address used for outbound traffic. On hosts with // only a public interface the InterfaceAddrs list can miss it (for example a // NAT'd container), so dialing a documentation address is a cheap fallback. func localOutboundIP() net.IP { for _, target := range []string{"192.0.2.1:80", "198.51.100.1:80"} { c, err := net.DialTimeout("udp", target, 300*time.Millisecond) if err != nil { continue } addr, ok := c.LocalAddr().(*net.UDPAddr) _ = c.Close() if ok && addr.IP != nil && !addr.IP.IsUnspecified() { return addr.IP } } return nil } func load(certPath, keyPath string) (*Material, error) { raw, err := os.ReadFile(certPath) if err != nil { return nil, err } cert, err := parseLeaf(raw) if err != nil { return nil, err } if _, err := tls.LoadX509KeyPair(certPath, keyPath); err != nil { return nil, err } return &Material{ CertPath: certPath, KeyPath: keyPath, Cert: cert, Fingerprint: Fingerprint(cert), SelfSigned: cert.CheckSignatureFrom(cert) == nil, }, nil } func parseLeaf(raw []byte) (*x509.Certificate, error) { block, _ := pem.Decode(raw) if block == nil { return nil, fmt.Errorf("证书不是 PEM 格式") } return x509.ParseCertificate(block.Bytes) } func generate(certPath, keyPath string, hosts []string) (*Material, error) { key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return nil, err } serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) if err != nil { return nil, err } now := time.Now() tmpl := &x509.Certificate{ SerialNumber: serial, Subject: pkix.Name{Organization: []string{orgName}, CommonName: "MiaoPanel 面板"}, NotBefore: now.Add(-time.Hour), NotAfter: now.Add(validity), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, } for _, h := range hosts { if ip := net.ParseIP(h); ip != nil { tmpl.IPAddresses = append(tmpl.IPAddresses, ip) continue } tmpl.DNSNames = append(tmpl.DNSNames, h) } if len(tmpl.DNSNames) == 0 && len(tmpl.IPAddresses) == 0 { tmpl.DNSNames = []string{"localhost"} } der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) if err != nil { return nil, err } certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) keyDER, err := x509.MarshalECPrivateKey(key) if err != nil { return nil, err } keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}) if err := writeAtomic(certPath, certPEM, 0o644); err != nil { return nil, err } if err := writeAtomic(keyPath, keyPEM, 0o600); err != nil { return nil, err } cert, err := x509.ParseCertificate(der) if err != nil { return nil, err } return &Material{ CertPath: certPath, KeyPath: keyPath, Cert: cert, Fingerprint: Fingerprint(cert), SelfSigned: true, Hosts: hosts, }, nil } // Fingerprint renders the SHA-256 fingerprint the way browsers show it. func Fingerprint(cert *x509.Certificate) string { sum := sha256.Sum256(cert.Raw) h := strings.ToUpper(hex.EncodeToString(sum[:])) parts := make([]string, 0, len(h)/2) for i := 0; i < len(h); i += 2 { parts = append(parts, h[i:i+2]) } return strings.Join(parts, ":") } // covers reports whether every host is already present in the certificate so // that a changed LAN or public address triggers a re-issue. func covers(cert *x509.Certificate, hosts []string) bool { for _, h := range hosts { if ip := net.ParseIP(h); ip != nil { found := false for _, have := range cert.IPAddresses { if have.Equal(ip) { found = true break } } if !found { return false } continue } found := false for _, have := range cert.DNSNames { if strings.EqualFold(have, h) { found = true break } } if !found { return false } } return true } func writeAtomic(path string, data []byte, mode os.FileMode) error { tmp, err := os.CreateTemp(filepath.Dir(path), ".tls-*.tmp") if err != nil { return err } name := tmp.Name() defer os.Remove(name) if _, err := tmp.Write(data); err != nil { tmp.Close() return err } if err := tmp.Chmod(mode); err != nil { tmp.Close() return err } if err := tmp.Close(); err != nil { return err } return os.Rename(name, path) }