miaopanel
1// Package paneltls generates and loads the panel's own TLS material so the
2// control panel can be reached over HTTPS without a public domain name. The
3// certificate is self signed, valid for the machine hostname and every local
4// address, and is rotated automatically well before it expires.
5package paneltls
6
7import (
8 "crypto/ecdsa"
9 "crypto/elliptic"
10 "crypto/rand"
11 "crypto/sha256"
12 "crypto/tls"
13 "crypto/x509"
14 "crypto/x509/pkix"
15 "encoding/hex"
16 "encoding/pem"
17 "fmt"
18 "math/big"
19 "net"
20 "os"
21 "path/filepath"
22 "strings"
23 "time"
24)
25
26const (
27 certFile = "panel.crt"
28 keyFile = "panel.key"
29 // A long lived self signed certificate keeps browsers quiet for years while
30 // the panel rotates it 30 days before expiry on its own.
31 validity = 10 * 365 * 24 * time.Hour
32 renewBefore = 30 * 24 * time.Hour
33 orgName = "MiaoPanel"
34)
35
36// Material describes the active certificate.
37type Material struct {
38 CertPath string
39 KeyPath string
40 Cert *x509.Certificate
41 Fingerprint string // SHA-256, upper case, colon separated
42 SelfSigned bool
43 Hosts []string
44}
45
46// Ensure returns usable certificate material for dir, generating a fresh self
47// signed certificate when none exists, when it is close to expiry or when the
48// set of local addresses changed (DHCP, new NIC, cloud IP reassignment).
49func Ensure(dir string, hosts []string) (*Material, error) {
50 if err := os.MkdirAll(dir, 0o755); err != nil {
51 return nil, fmt.Errorf("创建证书目录 %s: %w", dir, err)
52 }
53 certPath := filepath.Join(dir, certFile)
54 keyPath := filepath.Join(dir, keyFile)
55 if m, err := load(certPath, keyPath); err == nil {
56 if time.Until(m.Cert.NotAfter) > renewBefore && covers(m.Cert, hosts) {
57 m.Hosts = hosts
58 return m, nil
59 }
60 }
61 return generate(certPath, keyPath, hosts)
62}
63
64// Load reads an existing certificate pair supplied by the operator.
65func Load(certPath, keyPath string) (*Material, error) {
66 m, err := load(certPath, keyPath)
67 if err != nil {
68 return nil, err
69 }
70 m.SelfSigned = false
71 return m, nil
72}
73
74// Config builds a server TLS configuration pinned to TLS 1.2+ and HTTP/1.1.
75// HTTP/2 is intentionally not advertised: the panel speaks plain JSON and the
76// multiplexed listener has to stay dependency free.
77func (m *Material) Config() (*tls.Config, error) {
78 pair, err := tls.LoadX509KeyPair(m.CertPath, m.KeyPath)
79 if err != nil {
80 return nil, fmt.Errorf("加载证书 %s: %w", m.CertPath, err)
81 }
82 return &tls.Config{
83 MinVersion: tls.VersionTLS12,
84 Certificates: []tls.Certificate{pair},
85 NextProtos: []string{"http/1.1"},
86 }, nil
87}
88
89// LocalHosts returns the hostname plus every unicast address of this machine.
90func LocalHosts() []string {
91 seen := map[string]bool{}
92 var out []string
93 add := func(h string) {
94 h = strings.TrimSpace(h)
95 if h == "" || seen[h] {
96 return
97 }
98 seen[h] = true
99 out = append(out, h)
100 }
101 if name, err := os.Hostname(); err == nil {
102 add(name)
103 if i := strings.IndexByte(name, '.'); i > 0 {
104 add(name[:i])
105 }
106 }
107 add("localhost")
108 add("127.0.0.1")
109 if addrs, err := net.InterfaceAddrs(); err == nil {
110 for _, a := range addrs {
111 var ip net.IP
112 switch v := a.(type) {
113 case *net.IPNet:
114 ip = v.IP
115 case *net.IPAddr:
116 ip = v.IP
117 }
118 if ip == nil || ip.IsUnspecified() || ip.IsLinkLocalUnicast() {
119 continue
120 }
121 add(ip.String())
122 }
123 }
124 if ip := localOutboundIP(); ip != nil {
125 add(ip.String())
126 }
127 return out
128}
129
130// localOutboundIP finds the address used for outbound traffic. On hosts with
131// only a public interface the InterfaceAddrs list can miss it (for example a
132// NAT'd container), so dialing a documentation address is a cheap fallback.
133func localOutboundIP() net.IP {
134 for _, target := range []string{"192.0.2.1:80", "198.51.100.1:80"} {
135 c, err := net.DialTimeout("udp", target, 300*time.Millisecond)
136 if err != nil {
137 continue
138 }
139 addr, ok := c.LocalAddr().(*net.UDPAddr)
140 _ = c.Close()
141 if ok && addr.IP != nil && !addr.IP.IsUnspecified() {
142 return addr.IP
143 }
144 }
145 return nil
146}
147
148func load(certPath, keyPath string) (*Material, error) {
149 raw, err := os.ReadFile(certPath)
150 if err != nil {
151 return nil, err
152 }
153 cert, err := parseLeaf(raw)
154 if err != nil {
155 return nil, err
156 }
157 if _, err := tls.LoadX509KeyPair(certPath, keyPath); err != nil {
158 return nil, err
159 }
160 return &Material{
161 CertPath: certPath,
162 KeyPath: keyPath,
163 Cert: cert,
164 Fingerprint: Fingerprint(cert),
165 SelfSigned: cert.CheckSignatureFrom(cert) == nil,
166 }, nil
167}
168
169func parseLeaf(raw []byte) (*x509.Certificate, error) {
170 block, _ := pem.Decode(raw)
171 if block == nil {
172 return nil, fmt.Errorf("证书不是 PEM 格式")
173 }
174 return x509.ParseCertificate(block.Bytes)
175}
176
177func generate(certPath, keyPath string, hosts []string) (*Material, error) {
178 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
179 if err != nil {
180 return nil, err
181 }
182 serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
183 if err != nil {
184 return nil, err
185 }
186 now := time.Now()
187 tmpl := &x509.Certificate{
188 SerialNumber: serial,
189 Subject: pkix.Name{Organization: []string{orgName}, CommonName: "MiaoPanel 面板"},
190 NotBefore: now.Add(-time.Hour),
191 NotAfter: now.Add(validity),
192 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
193 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
194 BasicConstraintsValid: true,
195 }
196 for _, h := range hosts {
197 if ip := net.ParseIP(h); ip != nil {
198 tmpl.IPAddresses = append(tmpl.IPAddresses, ip)
199 continue
200 }
201 tmpl.DNSNames = append(tmpl.DNSNames, h)
202 }
203 if len(tmpl.DNSNames) == 0 && len(tmpl.IPAddresses) == 0 {
204 tmpl.DNSNames = []string{"localhost"}
205 }
206 der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
207 if err != nil {
208 return nil, err
209 }
210 certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
211 keyDER, err := x509.MarshalECPrivateKey(key)
212 if err != nil {
213 return nil, err
214 }
215 keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
216 if err := writeAtomic(certPath, certPEM, 0o644); err != nil {
217 return nil, err
218 }
219 if err := writeAtomic(keyPath, keyPEM, 0o600); err != nil {
220 return nil, err
221 }
222 cert, err := x509.ParseCertificate(der)
223 if err != nil {
224 return nil, err
225 }
226 return &Material{
227 CertPath: certPath,
228 KeyPath: keyPath,
229 Cert: cert,
230 Fingerprint: Fingerprint(cert),
231 SelfSigned: true,
232 Hosts: hosts,
233 }, nil
234}
235
236// Fingerprint renders the SHA-256 fingerprint the way browsers show it.
237func Fingerprint(cert *x509.Certificate) string {
238 sum := sha256.Sum256(cert.Raw)
239 h := strings.ToUpper(hex.EncodeToString(sum[:]))
240 parts := make([]string, 0, len(h)/2)
241 for i := 0; i < len(h); i += 2 {
242 parts = append(parts, h[i:i+2])
243 }
244 return strings.Join(parts, ":")
245}
246
247// covers reports whether every host is already present in the certificate so
248// that a changed LAN or public address triggers a re-issue.
249func covers(cert *x509.Certificate, hosts []string) bool {
250 for _, h := range hosts {
251 if ip := net.ParseIP(h); ip != nil {
252 found := false
253 for _, have := range cert.IPAddresses {
254 if have.Equal(ip) {
255 found = true
256 break
257 }
258 }
259 if !found {
260 return false
261 }
262 continue
263 }
264 found := false
265 for _, have := range cert.DNSNames {
266 if strings.EqualFold(have, h) {
267 found = true
268 break
269 }
270 }
271 if !found {
272 return false
273 }
274 }
275 return true
276}
277
278func writeAtomic(path string, data []byte, mode os.FileMode) error {
279 tmp, err := os.CreateTemp(filepath.Dir(path), ".tls-*.tmp")
280 if err != nil {
281 return err
282 }
283 name := tmp.Name()
284 defer os.Remove(name)
285 if _, err := tmp.Write(data); err != nil {
286 tmp.Close()
287 return err
288 }
289 if err := tmp.Chmod(mode); err != nil {
290 tmp.Close()
291 return err
292 }
293 if err := tmp.Close(); err != nil {
294 return err
295 }
296 return os.Rename(name, path)
297}