ca.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. package tlscert
  2. // FORK: a private certificate authority for this server.
  3. //
  4. // Browsers only register a service worker - Web Push, installing the PWA -
  5. // on a certificate they trust outright; an exception accepted for a
  6. // self-signed certificate is not enough. So the server can run its own root
  7. // CA, which the admin installs once on their devices, and serve a leaf it
  8. // signs. Agents pin the root (tlspin accepts a CA pin), so the leaf can be
  9. // re-issued - on renewal, or when the server's addresses change - without
  10. // breaking any of them.
  11. //
  12. // A root the admin's devices trust is a powerful thing to keep on a server.
  13. // Three properties bound it:
  14. //
  15. // - The root carries Name Constraints: private address ranges and
  16. // local DNS names only. A copy of its key cannot be used to impersonate
  17. // any public site to a device that trusts it.
  18. // - Its key is only ever used to sign this server's own leaf, stays in a
  19. // 0700 directory in a 0600 file owned by the service user, and the server
  20. // refuses to start if either has been opened up.
  21. // - It is created once and never replaced implicitly: a missing half of the
  22. // pair is an error, not a reason to mint a new root the devices do not
  23. // trust.
  24. import (
  25. "crypto/ecdsa"
  26. "crypto/elliptic"
  27. "crypto/rand"
  28. "crypto/sha256"
  29. "crypto/tls"
  30. "crypto/x509"
  31. "crypto/x509/pkix"
  32. "encoding/pem"
  33. "errors"
  34. "fmt"
  35. "io/fs"
  36. "math/big"
  37. "net"
  38. "os"
  39. "path/filepath"
  40. "slices"
  41. "strings"
  42. "sync"
  43. "sync/atomic"
  44. "time"
  45. )
  46. const (
  47. caCertFile = "ca.pem"
  48. caKeyFile = "ca-key.pem"
  49. leafCertFile = "leaf.pem"
  50. leafKeyFile = "leaf-key.pem"
  51. rootValidity = 10 * 365 * 24 * time.Hour
  52. rootBackdate = 365 * 24 * time.Hour
  53. // Short-lived leaves limit how long a mis-issued one would be accepted;
  54. // renewal is automatic and the key does not change, so it costs nothing.
  55. leafValidity = 90 * 24 * time.Hour
  56. leafRenewBefore = 30 * 24 * time.Hour
  57. // How often Run re-checks the leaf: for expiry, and for a change in the
  58. // server's addresses.
  59. caCheckEvery = 10 * time.Minute
  60. )
  61. // Address ranges a leaf may name: private, carrier-grade NAT (which overlay
  62. // VPNs use), loopback and IPv6 unique-local.
  63. var permittedIPRanges = []string{
  64. "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10",
  65. "127.0.0.0/8", "::1/128", "fc00::/7",
  66. }
  67. // DNS suffixes that are local by definition or by convention. The host's own
  68. // names and search domains are added when the root is created.
  69. var permittedLocalSuffixes = []string{"lan", "home.arpa", "internal", "local"}
  70. // CAOptions configures OpenCA. The function fields exist for tests; nil
  71. // means the real system.
  72. type CAOptions struct {
  73. Dir string // where the CA and leaf live; created 0700
  74. Names []string // extra names or addresses for the leaf (NETPULSE_TLS_NAMES)
  75. PublicHost string // host of NETPULSE_PUBLIC_URL, if set
  76. Addrs func() ([]net.IP, error)
  77. Hostname func() (string, error)
  78. SearchDomains func() []string
  79. Now func() time.Time
  80. Logf func(format string, args ...any)
  81. }
  82. // CA is the server's private CA and the leaf it serves.
  83. type CA struct {
  84. opts CAOptions
  85. root *x509.Certificate
  86. rootKey *ecdsa.PrivateKey
  87. leafKey *ecdsa.PrivateKey
  88. mu sync.Mutex // serializes Refresh
  89. lastDropped string
  90. uncovered []string // names and addresses the root cannot vouch for
  91. cur atomic.Pointer[tls.Certificate]
  92. }
  93. // OpenCA loads the CA in opts.Dir, creating it on first use, and makes sure
  94. // a current leaf is ready to serve.
  95. func OpenCA(opts CAOptions) (*CA, error) {
  96. if opts.Dir == "" {
  97. return nil, errors.New("tls: no directory for the CA")
  98. }
  99. if opts.Addrs == nil {
  100. opts.Addrs = interfaceAddrs
  101. }
  102. if opts.Hostname == nil {
  103. opts.Hostname = os.Hostname
  104. }
  105. if opts.SearchDomains == nil {
  106. opts.SearchDomains = resolvSearchDomains
  107. }
  108. if opts.Now == nil {
  109. opts.Now = time.Now
  110. }
  111. if opts.Logf == nil {
  112. opts.Logf = func(string, ...any) {}
  113. }
  114. if err := ensurePrivateDir(opts.Dir); err != nil {
  115. return nil, err
  116. }
  117. ca := &CA{opts: opts}
  118. if err := ca.openRoot(); err != nil {
  119. return nil, err
  120. }
  121. key, err := loadOrCreateKey(filepath.Join(opts.Dir, leafKeyFile))
  122. if err != nil {
  123. return nil, fmt.Errorf("tls: leaf key: %w", err)
  124. }
  125. ca.leafKey = key
  126. if err := ca.loadLeaf(); err != nil {
  127. opts.Logf("[netpulse] TLS: the stored leaf cannot be used (%v); issuing a new one", err)
  128. }
  129. if _, err := ca.Refresh(); err != nil {
  130. return nil, err
  131. }
  132. return ca, nil
  133. }
  134. func (ca *CA) openRoot() error {
  135. certPath := filepath.Join(ca.opts.Dir, caCertFile)
  136. keyPath := filepath.Join(ca.opts.Dir, caKeyFile)
  137. haveCert, haveKey := fileExists(certPath), fileExists(keyPath)
  138. switch {
  139. case haveCert && haveKey:
  140. key, err := loadKey(keyPath)
  141. if err != nil {
  142. return fmt.Errorf("tls: CA key: %w", err)
  143. }
  144. cert, err := loadCert(certPath)
  145. if err != nil {
  146. return fmt.Errorf("tls: CA certificate: %w", err)
  147. }
  148. if !cert.IsCA || !key.PublicKey.Equal(cert.PublicKey) {
  149. return fmt.Errorf("tls: %s and %s are not a CA and its key", certPath, keyPath)
  150. }
  151. ca.root, ca.rootKey = cert, key
  152. return nil
  153. case haveCert || haveKey:
  154. // Never mint a replacement: every device that trusts the old root
  155. // would silently stop trusting the server.
  156. return fmt.Errorf("tls: only one of %s and %s exists; restore the other from a backup, "+
  157. "or remove both to create a new CA (every device will need the new root installed)", certPath, keyPath)
  158. }
  159. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  160. if err != nil {
  161. return err
  162. }
  163. tmpl, err := ca.rootTemplate()
  164. if err != nil {
  165. return err
  166. }
  167. der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
  168. if err != nil {
  169. return fmt.Errorf("tls: create CA: %w", err)
  170. }
  171. cert, err := x509.ParseCertificate(der)
  172. if err != nil {
  173. return err
  174. }
  175. // Key first: a crash between the two writes leaves a key without a
  176. // certificate, which openRoot refuses loudly, rather than a certificate
  177. // devices might already trust whose key is lost.
  178. if err := writeKey(keyPath, key); err != nil {
  179. return fmt.Errorf("tls: write CA key: %w", err)
  180. }
  181. if err := writeAtomic(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644); err != nil {
  182. return fmt.Errorf("tls: write CA certificate: %w", err)
  183. }
  184. ca.root, ca.rootKey = cert, key
  185. ca.opts.Logf("[netpulse] TLS: created a private CA; install it on your devices and check its fingerprint: %s", ca.RootSHA256())
  186. return nil
  187. }
  188. func (ca *CA) rootTemplate() (*x509.Certificate, error) {
  189. serial, err := randomSerial()
  190. if err != nil {
  191. return nil, err
  192. }
  193. var ranges []*net.IPNet
  194. for _, r := range permittedIPRanges {
  195. _, n, err := net.ParseCIDR(r)
  196. if err != nil {
  197. return nil, err
  198. }
  199. ranges = append(ranges, n)
  200. }
  201. domains := slices.Clone(permittedLocalSuffixes)
  202. host, _ := ca.opts.Hostname()
  203. domains = append(domains, hostNames(host)...)
  204. // Only this host under each search domain, never the whole domain: a
  205. // search domain can be a company's or a public one, and permitting it
  206. // would let a copy of the CA key vouch for everything in it.
  207. if short := firstLabel(host); short != "" {
  208. for _, d := range ca.opts.SearchDomains() {
  209. domains = append(domains, short+"."+d)
  210. }
  211. }
  212. for _, n := range append(slices.Clone(ca.opts.Names), ca.opts.PublicHost) {
  213. if n = normName(n); n != "" && net.ParseIP(n) == nil {
  214. // A name is permitted with everything below it - name
  215. // constraints cannot say "this name only" - so a public one
  216. // widens what the root may vouch for. Allowed, since it was
  217. // asked for, but said.
  218. if !underLocalSuffix(n) {
  219. ca.opts.Logf("[netpulse] TLS: the CA may also vouch for everything under %s, "+
  220. "which is not a local name (NETPULSE_TLS_NAMES / NETPULSE_PUBLIC_URL)", n)
  221. }
  222. domains = append(domains, n)
  223. }
  224. }
  225. slices.Sort(domains)
  226. domains = slices.Compact(domains)
  227. now := ca.opts.Now()
  228. cn := "NetPulse local CA"
  229. if short := firstLabel(host); short != "" {
  230. cn += " (" + short + ")"
  231. }
  232. // Backdated well past any clock skew: the root is never replaced, so one
  233. // created while the clock ran fast must not stay "not yet valid" for
  234. // months.
  235. notBefore := now.Add(-rootBackdate)
  236. // The name constraints are not marked critical: mbedTLS - OpenWrt's TLS
  237. // library, behind its wget and curl - refuses to load a certificate with
  238. // a critical extension it does not implement, and it does not implement
  239. // this one, so routers could not verify the server at all. Go, OpenSSL,
  240. // Chrome and Firefox enforce them either way; the CA/B Baseline
  241. // Requirements allowed them non-critical for the same reason.
  242. return &x509.Certificate{
  243. SerialNumber: serial,
  244. Subject: pkix.Name{CommonName: cn, Organization: []string{"NetPulse"}},
  245. NotBefore: notBefore,
  246. NotAfter: now.Add(rootValidity),
  247. IsCA: true,
  248. BasicConstraintsValid: true,
  249. MaxPathLen: 0,
  250. MaxPathLenZero: true,
  251. KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
  252. PermittedDNSDomainsCritical: false,
  253. PermittedDNSDomains: domains,
  254. PermittedIPRanges: ranges,
  255. }, nil
  256. }
  257. func (ca *CA) loadLeaf() error {
  258. path := filepath.Join(ca.opts.Dir, leafCertFile)
  259. if !fileExists(path) {
  260. return nil
  261. }
  262. leaf, err := loadCert(path)
  263. if err != nil {
  264. return err
  265. }
  266. ca.store(leaf)
  267. return nil
  268. }
  269. func (ca *CA) store(leaf *x509.Certificate) {
  270. ca.cur.Store(&tls.Certificate{
  271. Certificate: [][]byte{leaf.Raw, ca.root.Raw},
  272. PrivateKey: ca.leafKey,
  273. Leaf: leaf,
  274. })
  275. }
  276. // Refresh re-issues the leaf if it is missing, near expiry, not this CA's,
  277. // not for the leaf key, or names a different set of addresses than the
  278. // server now has. It reports whether it issued one. On failure the leaf being
  279. // served is kept.
  280. func (ca *CA) Refresh() (bool, error) {
  281. ca.mu.Lock()
  282. defer ca.mu.Unlock()
  283. dns, ips := ca.desiredNames()
  284. now := ca.opts.Now()
  285. if cur := ca.cur.Load(); cur != nil && !ca.needsReissue(cur.Leaf, dns, ips, now) {
  286. return false, nil
  287. }
  288. serial, err := randomSerial()
  289. if err != nil {
  290. return false, err
  291. }
  292. tmpl := &x509.Certificate{
  293. SerialNumber: serial,
  294. Subject: pkix.Name{CommonName: "NetPulse"},
  295. NotBefore: now.Add(-time.Hour),
  296. NotAfter: now.Add(leafValidity),
  297. KeyUsage: x509.KeyUsageDigitalSignature,
  298. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  299. DNSNames: dns,
  300. IPAddresses: ips,
  301. }
  302. der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.root, &ca.leafKey.PublicKey, ca.rootKey)
  303. if err != nil {
  304. return false, fmt.Errorf("tls: issue leaf: %w", err)
  305. }
  306. leaf, err := x509.ParseCertificate(der)
  307. if err != nil {
  308. return false, err
  309. }
  310. if err := writeAtomic(filepath.Join(ca.opts.Dir, leafCertFile),
  311. pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644); err != nil {
  312. return false, fmt.Errorf("tls: write leaf: %w", err)
  313. }
  314. ca.store(leaf)
  315. ca.opts.Logf("[netpulse] TLS: issued a certificate for %s, valid until %s",
  316. strings.Join(sanList(dns, ips), ", "), leaf.NotAfter.Format(time.DateOnly))
  317. return true, nil
  318. }
  319. func (ca *CA) needsReissue(leaf *x509.Certificate, dns []string, ips []net.IP, now time.Time) bool {
  320. if leaf == nil || leaf.CheckSignatureFrom(ca.root) != nil {
  321. return true
  322. }
  323. if pub, ok := leaf.PublicKey.(*ecdsa.PublicKey); !ok || !pub.Equal(&ca.leafKey.PublicKey) {
  324. return true
  325. }
  326. if now.Add(leafRenewBefore).After(leaf.NotAfter) || now.Before(leaf.NotBefore) {
  327. return true
  328. }
  329. return !slices.Equal(sanList(leaf.DNSNames, leaf.IPAddresses), sanList(dns, ips))
  330. }
  331. // desiredNames is what the leaf should name now: every address the server
  332. // can be reached at and every name it goes by, limited to what the root may
  333. // vouch for.
  334. func (ca *CA) desiredNames() ([]string, []net.IP) {
  335. var names []string
  336. ips := []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}
  337. if addrs, err := ca.opts.Addrs(); err == nil {
  338. ips = append(ips, addrs...)
  339. } else {
  340. ca.opts.Logf("[netpulse] TLS: cannot list this host's addresses: %v", err)
  341. }
  342. host, _ := ca.opts.Hostname()
  343. names = append(names, hostNames(host)...)
  344. if short := firstLabel(host); short != "" {
  345. for _, d := range ca.opts.SearchDomains() {
  346. names = append(names, short+"."+d)
  347. }
  348. }
  349. for _, n := range append(slices.Clone(ca.opts.Names), ca.opts.PublicHost) {
  350. n = normName(n)
  351. if n == "" {
  352. continue
  353. }
  354. if ip := net.ParseIP(n); ip != nil {
  355. ips = append(ips, ip)
  356. } else {
  357. names = append(names, n)
  358. }
  359. }
  360. var dns, dropped []string
  361. var keep []net.IP
  362. for _, n := range names {
  363. if ca.permitsName(n) {
  364. dns = append(dns, n)
  365. } else {
  366. dropped = append(dropped, n)
  367. }
  368. }
  369. for _, ip := range ips {
  370. if ip.IsLinkLocalUnicast() || ip.IsMulticast() || ip.IsUnspecified() {
  371. continue
  372. }
  373. if ca.permitsIP(ip) {
  374. keep = append(keep, ip)
  375. } else {
  376. dropped = append(dropped, ip.String())
  377. }
  378. }
  379. slices.Sort(dns)
  380. dns = slices.Compact(dns)
  381. slices.SortFunc(keep, func(a, b net.IP) int { return strings.Compare(a.String(), b.String()) })
  382. keep = slices.CompactFunc(keep, func(a, b net.IP) bool { return a.Equal(b) })
  383. // Said once per change, not on every check.
  384. slices.Sort(dropped)
  385. dropped = slices.Compact(dropped)
  386. ca.uncovered = dropped
  387. if d := strings.Join(dropped, ", "); d != ca.lastDropped {
  388. ca.lastDropped = d
  389. if d != "" {
  390. ca.opts.Logf("[netpulse] TLS: the certificate cannot name %s: the CA only vouches for private "+
  391. "addresses, and for local names and the names it was created with. A name can be added by "+
  392. "creating a new CA with it in NETPULSE_TLS_NAMES (docs/https.md, \"Starting over\"); a "+
  393. "public address cannot be covered.", d)
  394. }
  395. }
  396. return dns, keep
  397. }
  398. func (ca *CA) permitsName(n string) bool {
  399. for _, d := range ca.root.PermittedDNSDomains {
  400. if n == d || strings.HasSuffix(n, "."+d) {
  401. return true
  402. }
  403. }
  404. return false
  405. }
  406. func (ca *CA) permitsIP(ip net.IP) bool {
  407. for _, r := range ca.root.PermittedIPRanges {
  408. if r.Contains(ip) {
  409. return true
  410. }
  411. }
  412. return false
  413. }
  414. // Run re-checks the leaf until done is closed.
  415. func (ca *CA) Run(done <-chan struct{}) {
  416. t := time.NewTicker(caCheckEvery)
  417. defer t.Stop()
  418. for {
  419. select {
  420. case <-done:
  421. return
  422. case <-t.C:
  423. if _, err := ca.Refresh(); err != nil {
  424. ca.opts.Logf("[netpulse] TLS: %v (still serving the previous certificate)", err)
  425. }
  426. }
  427. }
  428. }
  429. // TLSConfig serves the current leaf with the root attached, so a client that
  430. // pins the root can verify the chain.
  431. func (ca *CA) TLSConfig() *tls.Config {
  432. return &tls.Config{
  433. GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
  434. return ca.cur.Load(), nil
  435. },
  436. MinVersion: tls.VersionTLS12,
  437. // TLS 1.2 is limited to forward-secret AEAD suites; the key is ECDSA,
  438. // so only ECDSA suites can be used anyway. TLS 1.3 suites are all
  439. // sound and not configurable.
  440. CipherSuites: []uint16{
  441. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  442. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  443. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
  444. },
  445. CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256},
  446. }
  447. }
  448. // Fingerprint is the root's SPKI fingerprint: the pin agents use.
  449. func (ca *CA) Fingerprint() string { return Fingerprint(ca.root) }
  450. // RootSHA256 is the SHA-256 of the root certificate, in the colon-separated
  451. // form phones and browsers show when installing it - what an admin compares.
  452. func (ca *CA) RootSHA256() string {
  453. sum := sha256.Sum256(ca.root.Raw)
  454. parts := make([]string, len(sum))
  455. for i, b := range sum {
  456. parts[i] = fmt.Sprintf("%02X", b)
  457. }
  458. return strings.Join(parts, ":")
  459. }
  460. // RootDER and RootPEM are the root certificate, for devices to install.
  461. func (ca *CA) RootDER() []byte { return slices.Clone(ca.root.Raw) }
  462. func (ca *CA) RootPEM() []byte {
  463. return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca.root.Raw})
  464. }
  465. // Uncovered lists the host's names and addresses the certificate leaves out
  466. // because the root may not vouch for them, as of the last check.
  467. func (ca *CA) Uncovered() []string {
  468. ca.mu.Lock()
  469. defer ca.mu.Unlock()
  470. return slices.Clone(ca.uncovered)
  471. }
  472. // Leaf is the certificate being served now.
  473. func (ca *CA) Leaf() *x509.Certificate {
  474. if cur := ca.cur.Load(); cur != nil {
  475. return cur.Leaf
  476. }
  477. return nil
  478. }
  479. // --- names and addresses ---
  480. func interfaceAddrs() ([]net.IP, error) {
  481. addrs, err := net.InterfaceAddrs()
  482. if err != nil {
  483. return nil, err
  484. }
  485. var ips []net.IP
  486. for _, a := range addrs {
  487. if n, ok := a.(*net.IPNet); ok {
  488. ips = append(ips, n.IP)
  489. }
  490. }
  491. return ips, nil
  492. }
  493. // resolvSearchDomains reads the local DNS domains from /etc/resolv.conf, so
  494. // the leaf names the host as the network's DNS knows it.
  495. func resolvSearchDomains() []string {
  496. data, err := os.ReadFile("/etc/resolv.conf")
  497. if err != nil {
  498. return nil
  499. }
  500. var out []string
  501. for _, line := range strings.Split(string(data), "\n") {
  502. f := strings.Fields(line)
  503. if len(f) < 2 || (f[0] != "search" && f[0] != "domain") {
  504. continue
  505. }
  506. for _, d := range f[1:] {
  507. if d = normName(d); d != "" && d != "." {
  508. out = append(out, d)
  509. }
  510. }
  511. }
  512. return out
  513. }
  514. // hostNames is the host name as given and its first label, lower-cased.
  515. func hostNames(host string) []string {
  516. host = normName(host)
  517. if host == "" {
  518. return nil
  519. }
  520. if short := firstLabel(host); short != host {
  521. return []string{host, short}
  522. }
  523. return []string{host}
  524. }
  525. // underLocalSuffix reports whether n is one of the local suffixes or below
  526. // one.
  527. func underLocalSuffix(n string) bool {
  528. for _, d := range permittedLocalSuffixes {
  529. if n == d || strings.HasSuffix(n, "."+d) {
  530. return true
  531. }
  532. }
  533. return false
  534. }
  535. func firstLabel(host string) string {
  536. host = normName(host)
  537. if i := strings.IndexByte(host, '.'); i >= 0 {
  538. return host[:i]
  539. }
  540. return host
  541. }
  542. func normName(n string) string {
  543. return strings.TrimSuffix(strings.ToLower(strings.TrimSpace(n)), ".")
  544. }
  545. func sanList(dns []string, ips []net.IP) []string {
  546. out := slices.Clone(dns)
  547. for _, ip := range ips {
  548. out = append(out, ip.String())
  549. }
  550. slices.Sort(out)
  551. return out
  552. }
  553. // --- files ---
  554. // ensurePrivateDir creates dir 0700, or checks that an existing one is not
  555. // open to other users.
  556. func ensurePrivateDir(dir string) error {
  557. if err := os.MkdirAll(dir, 0o700); err != nil {
  558. return fmt.Errorf("tls: %w", err)
  559. }
  560. fi, err := os.Stat(dir)
  561. if err != nil {
  562. return fmt.Errorf("tls: %w", err)
  563. }
  564. if fi.Mode().Perm()&0o077 != 0 {
  565. return fmt.Errorf("tls: %s is open to other users (mode %04o); it holds the CA key. Run: chmod 700 %s",
  566. dir, fi.Mode().Perm(), dir)
  567. }
  568. if !ownedByMe(fi) {
  569. return fmt.Errorf("tls: %s is not owned by the user the server runs as", dir)
  570. }
  571. return nil
  572. }
  573. // checkPrivateFile refuses a key file other users could read or replace.
  574. func checkPrivateFile(path string, fi fs.FileInfo) error {
  575. if fi.Mode().Perm()&0o077 != 0 {
  576. return fmt.Errorf("%s is open to other users (mode %04o). Run: chmod 600 %s", path, fi.Mode().Perm(), path)
  577. }
  578. if !ownedByMe(fi) {
  579. return fmt.Errorf("%s is not owned by the user the server runs as", path)
  580. }
  581. return nil
  582. }
  583. func loadOrCreateKey(path string) (*ecdsa.PrivateKey, error) {
  584. if fileExists(path) {
  585. return loadKey(path)
  586. }
  587. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  588. if err != nil {
  589. return nil, err
  590. }
  591. return key, writeKey(path, key)
  592. }
  593. func loadKey(path string) (*ecdsa.PrivateKey, error) {
  594. fi, err := os.Stat(path)
  595. if err != nil {
  596. return nil, err
  597. }
  598. if err := checkPrivateFile(path, fi); err != nil {
  599. return nil, err
  600. }
  601. data, err := os.ReadFile(path)
  602. if err != nil {
  603. return nil, err
  604. }
  605. block, _ := pem.Decode(data)
  606. if block == nil || block.Type != "EC PRIVATE KEY" {
  607. return nil, fmt.Errorf("%s: not a PEM EC private key", path)
  608. }
  609. return x509.ParseECPrivateKey(block.Bytes)
  610. }
  611. func writeKey(path string, key *ecdsa.PrivateKey) error {
  612. der, err := x509.MarshalECPrivateKey(key)
  613. if err != nil {
  614. return err
  615. }
  616. return writeAtomic(path, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}), 0o600)
  617. }
  618. func loadCert(path string) (*x509.Certificate, error) {
  619. data, err := os.ReadFile(path)
  620. if err != nil {
  621. return nil, err
  622. }
  623. block, _ := pem.Decode(data)
  624. if block == nil || block.Type != "CERTIFICATE" {
  625. return nil, fmt.Errorf("%s: not a PEM certificate", path)
  626. }
  627. return x509.ParseCertificate(block.Bytes)
  628. }
  629. // writeAtomic replaces path so that a reader - or a crash - sees either the
  630. // old content or the new, never half of it.
  631. func writeAtomic(path string, data []byte, mode os.FileMode) error {
  632. dir := filepath.Dir(path)
  633. tmp, err := os.CreateTemp(dir, ".tmp-"+filepath.Base(path)+"-*")
  634. if err != nil {
  635. return err
  636. }
  637. name := tmp.Name()
  638. defer os.Remove(name) // no-op once renamed
  639. if err := tmp.Chmod(mode); err != nil {
  640. tmp.Close()
  641. return err
  642. }
  643. if _, err := tmp.Write(data); err != nil {
  644. tmp.Close()
  645. return err
  646. }
  647. if err := tmp.Sync(); err != nil {
  648. tmp.Close()
  649. return err
  650. }
  651. if err := tmp.Close(); err != nil {
  652. return err
  653. }
  654. if err := os.Rename(name, path); err != nil {
  655. return err
  656. }
  657. if d, err := os.Open(dir); err == nil {
  658. _ = d.Sync()
  659. d.Close()
  660. }
  661. return nil
  662. }
  663. func randomSerial() (*big.Int, error) {
  664. return rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
  665. }