manager.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. // Package tlsmode runs HTTPS with the server's private CA and decides what
  2. // plain HTTP may still do, as settings an admin changes from the web UI
  3. // without a restart.
  4. //
  5. // FORK: see docs/https.md. In short:
  6. //
  7. // - Enabling HTTPS only adds a TLS listener (NETPULSE_TLS_PORT, 443 by
  8. // default) served with a leaf of the private CA. Plain HTTP keeps working
  9. // exactly as before (mode "full"), so enabling it cannot lock anyone out.
  10. // - Mode "migrate" stops plain HTTP from carrying credentials - logins,
  11. // sessions, API tokens - and redirects browsers to HTTPS, while agents
  12. // keep reporting over it until each one has moved.
  13. // - Mode "redirect" leaves plain HTTP with nothing but redirects, the root
  14. // certificate and a loopback health check.
  15. //
  16. // A stricter mode only takes effect once confirmed from a page loaded over
  17. // HTTPS, within a few minutes: the admin has then proved they can reach and
  18. // log in over HTTPS before plain HTTP stops accepting logins.
  19. //
  20. // The environment always wins over the UI (NETPULSE_TLS_ENABLED with
  21. // NETPULSE_TLS_CA, NETPULSE_HTTP_MODE): a setting fixed there is shown as
  22. // locked, and is how to recover over SSH if the UI cannot be reached.
  23. package tlsmode
  24. import (
  25. "context"
  26. "crypto/rand"
  27. "crypto/subtle"
  28. "crypto/x509"
  29. "database/sql"
  30. "encoding/hex"
  31. "errors"
  32. "fmt"
  33. "net"
  34. "net/http"
  35. "net/url"
  36. "os"
  37. "path/filepath"
  38. "slices"
  39. "strconv"
  40. "strings"
  41. "sync"
  42. "sync/atomic"
  43. "syscall"
  44. "time"
  45. "github.com/gnacho/netpulse/server-go/internal/tlscert"
  46. )
  47. // Mode is what plain HTTP may still do once HTTPS is on.
  48. type Mode string
  49. const (
  50. Full Mode = "full"
  51. Migrate Mode = "migrate"
  52. Redirect Mode = "redirect"
  53. )
  54. // ParseMode accepts the three modes; anything else is an error.
  55. func ParseMode(s string) (Mode, error) {
  56. switch m := Mode(s); m {
  57. case Full, Migrate, Redirect:
  58. return m, nil
  59. }
  60. return "", fmt.Errorf("unknown HTTP mode %q (want full, migrate or redirect)", s)
  61. }
  62. const (
  63. kvEnabled = "settings.https.enabled"
  64. kvMode = "settings.https.mode"
  65. kvPort = "settings.https.port" // #978: UI-chosen HTTPS port
  66. // kvCert and kvKey (#1756) point at a certificate on disk that replaces
  67. // the private CA. Both set, or both empty.
  68. kvCert = "settings.https.cert"
  69. kvKey = "settings.https.key"
  70. // kvPortMigrated (FORK) marks that the pre-#978 port was decided once.
  71. kvPortMigrated = "settings.https.port_migrated"
  72. // ConfirmWindow is how long a staged mode change waits for confirmation
  73. // from an HTTPS page before it is dropped.
  74. ConfirmWindow = 5 * time.Minute
  75. )
  76. // KV is the part of the database the manager uses.
  77. type KV interface {
  78. QueryRow(query string, args ...any) *sql.Row
  79. Exec(query string, args ...any) (sql.Result, error)
  80. }
  81. // Options configures New.
  82. type Options struct {
  83. DB KV
  84. DataDir string
  85. Port int // the TLS listener's port
  86. Names []string // NETPULSE_TLS_NAMES
  87. PublicURL string // NETPULSE_PUBLIC_URL
  88. // EnvEnabled is non-nil when the environment decides whether HTTPS with
  89. // the private CA is on; EnvMode is non-empty when it fixes the mode.
  90. EnvEnabled *bool
  91. EnvMode Mode
  92. // EnvPort (#978) is true when NETPULSE_TLS_PORT fixes the port: the UI
  93. // setting is locked, like the rest of the environment. PlainPort is the
  94. // plain HTTP port, which the HTTPS listener cannot reuse.
  95. EnvPort bool
  96. PlainPort int
  97. // Unavailable, when not empty, says why this server's HTTPS is managed
  98. // elsewhere (on-box, or a certificate of the admin's own), and the
  99. // manager stays off.
  100. Unavailable string
  101. // NewServer builds the TLS listener's server with the same timeouts as
  102. // the plain one.
  103. NewServer func(addr string, h http.Handler) *http.Server
  104. Logf func(format string, args ...any)
  105. Now func() time.Time
  106. // CAOptions adjusts the CA's options; tests use it to fake the host.
  107. CAOptions func(tlscert.CAOptions) tlscert.CAOptions
  108. }
  109. // Manager is the HTTPS state of the running server.
  110. type Manager struct {
  111. opts Options
  112. mu sync.Mutex
  113. handler http.Handler
  114. enabled bool
  115. port int // #978: mutable via SetPort (opts.Port is only the default)
  116. ca *tlscert.CA
  117. srv *http.Server
  118. caStop chan struct{}
  119. lastErr string
  120. pending *pendingMode
  121. mode atomic.Value // Mode
  122. caLoaded atomic.Pointer[tlscert.CA]
  123. // reloader serves a certificate set in Settings instead of the CA
  124. // (#1756). Nil when the CA is the source.
  125. reloader *tlscert.Reloader
  126. sniff *sniffServer
  127. }
  128. type pendingMode struct {
  129. mode Mode
  130. code string
  131. expires time.Time
  132. by string
  133. }
  134. // New reads the saved settings. Nothing listens until Start.
  135. func New(opts Options) *Manager {
  136. if opts.Logf == nil {
  137. opts.Logf = func(string, ...any) {}
  138. }
  139. if opts.Now == nil {
  140. opts.Now = time.Now
  141. }
  142. m := &Manager{opts: opts}
  143. m.mode.Store(Full)
  144. if opts.Unavailable != "" {
  145. return m
  146. }
  147. m.enabled = m.savedEnabled()
  148. if opts.EnvEnabled != nil {
  149. m.enabled = *opts.EnvEnabled
  150. }
  151. mode := m.savedMode()
  152. if opts.EnvMode != "" {
  153. mode = opts.EnvMode
  154. }
  155. if !m.enabled {
  156. mode = Full
  157. }
  158. m.mode.Store(mode)
  159. // Puerto (#978): el entorno manda; si no, el kv guardado; si no, el
  160. // default de Options.
  161. m.port = opts.Port
  162. if !opts.EnvPort {
  163. if v := m.savedPort(); v != 0 {
  164. m.port = v
  165. } else if m.kvGet(kvPortMigrated) == "" && m.setUpBeforePortSetting() {
  166. // FORK: HTTPS configured before the port became a setting
  167. // (#978) was set up on the then-default 3443, and its agents
  168. // and bookmarks point there. Moving it to the new default on
  169. // upgrade would cut them off, so record the port it has.
  170. m.port = legacyDefaultPort
  171. m.savePort(legacyDefaultPort)
  172. }
  173. // Decided once, on the first start of a build that has the
  174. // setting: from then on an unrecorded port is simply the default.
  175. m.kvSet(kvPortMigrated, "1")
  176. }
  177. return m
  178. }
  179. // setUpBeforePortSetting says HTTPS had been configured on this install,
  180. // from Settings or from the environment, before its port was recorded. The
  181. // environment alone does not tell an old install from a new one, so there
  182. // it also takes a CA left by an earlier run.
  183. func (m *Manager) setUpBeforePortSetting() bool {
  184. if m.kvGet(kvEnabled) != "" {
  185. return true
  186. }
  187. return m.opts.EnvEnabled != nil && *m.opts.EnvEnabled &&
  188. fileExists(filepath.Join(m.opts.DataDir, "tls", "ca.pem"))
  189. }
  190. // currentPort is the HTTPS port, which SetPort may change at any time.
  191. func (m *Manager) currentPort() int {
  192. m.mu.Lock()
  193. defer m.mu.Unlock()
  194. return m.port
  195. }
  196. // legacyDefaultPort is the HTTPS port before #978 made it a setting.
  197. const legacyDefaultPort = 3443
  198. // Start begins serving HTTPS if it is enabled. h is the API handler, served
  199. // on the TLS listener exactly as on the plain one. An error is returned only
  200. // when the environment asked for HTTPS; a UI setting that cannot be applied
  201. // is reported in the status instead, and plain HTTP keeps working.
  202. func (m *Manager) Start(h http.Handler) error {
  203. m.mu.Lock()
  204. defer m.mu.Unlock()
  205. m.handler = h
  206. m.sniff = newSniffServer(m)
  207. if !m.enabled {
  208. // A CA from an earlier run is opened even with HTTPS off, so the
  209. // plain port can still answer browsers holding an HSTS policy (see
  210. // SniffListener). Failing here only loses that.
  211. if fileExists(filepath.Join(m.opts.DataDir, "tls", "ca.pem")) {
  212. if err := m.openCALocked(); err != nil {
  213. m.opts.Logf("[netpulse] TLS: CA not opened: %v", err)
  214. }
  215. }
  216. return nil
  217. }
  218. if err := m.startLocked(); err != nil {
  219. m.enabled = false
  220. m.mode.Store(Full)
  221. m.lastErr = err.Error()
  222. if m.opts.EnvEnabled != nil && *m.opts.EnvEnabled {
  223. return err
  224. }
  225. m.opts.Logf("[netpulse] HTTPS could not start, plain HTTP only: %v", err)
  226. }
  227. return nil
  228. }
  229. func (m *Manager) openCALocked() error {
  230. if m.ca != nil {
  231. return nil
  232. }
  233. copts := tlscert.CAOptions{
  234. Dir: filepath.Join(m.opts.DataDir, "tls"),
  235. Names: m.opts.Names,
  236. PublicHost: urlHost(m.opts.PublicURL),
  237. Logf: m.opts.Logf,
  238. }
  239. if m.opts.CAOptions != nil {
  240. copts = m.opts.CAOptions(copts)
  241. }
  242. ca, err := tlscert.OpenCA(copts)
  243. if err != nil {
  244. return err
  245. }
  246. m.ca = ca
  247. m.caLoaded.Store(ca)
  248. // Renewal runs for as long as the CA is loaded - with HTTPS off too,
  249. // since the plain port's TLS side still serves the leaf.
  250. m.caStop = make(chan struct{})
  251. go ca.Run(m.caStop)
  252. m.opts.Logf("[netpulse] TLS: root certificate SHA-256 %s", ca.RootSHA256())
  253. m.opts.Logf("[netpulse] TLS: agents pin %s", ca.Fingerprint())
  254. return nil
  255. }
  256. func (m *Manager) startLocked() error {
  257. // #1756: a certificate set in Settings wins over the private CA, so a
  258. // homelab that already has its own PKI serves that. A pair that no
  259. // longer loads fails here, before the listener is bound.
  260. certPath, keyPath := m.savedCert()
  261. var reloader *tlscert.Reloader
  262. if certPath != "" {
  263. r, err := tlscert.NewReloader(certPath, keyPath)
  264. if err != nil {
  265. return fmt.Errorf("the certificate from Settings: %w", err)
  266. }
  267. reloader = r
  268. } else if err := m.openCALocked(); err != nil {
  269. return err
  270. }
  271. addr := fmt.Sprintf(":%d", m.port)
  272. // Turning HTTPS off and on again quickly can find the previous listener
  273. // still closing (stopLocked shuts it down in the background).
  274. var ln net.Listener
  275. var err error
  276. for i := 0; i < 20; i++ {
  277. if ln, err = net.Listen("tcp", addr); err == nil || !errors.Is(err, syscall.EADDRINUSE) {
  278. break
  279. }
  280. time.Sleep(100 * time.Millisecond)
  281. }
  282. if err != nil {
  283. return fmt.Errorf("HTTPS listener on %s: %w", addr, err)
  284. }
  285. srv := m.opts.NewServer(addr, m.handler)
  286. m.reloader = reloader
  287. if reloader != nil {
  288. srv.TLSConfig = reloader.Config()
  289. } else {
  290. srv.TLSConfig = m.ca.TLSConfig()
  291. }
  292. m.srv = srv
  293. go func() {
  294. if err := srv.ServeTLS(ln, "", ""); err != nil && !errors.Is(err, http.ErrServerClosed) {
  295. m.opts.Logf("[netpulse] HTTPS listener stopped: %v", err)
  296. }
  297. }()
  298. m.lastErr = ""
  299. source := "private CA"
  300. if reloader != nil {
  301. source = "certificate from Settings"
  302. }
  303. m.opts.Logf("[netpulse] HTTPS on :%d (%s)", m.port, source)
  304. return nil
  305. }
  306. func (m *Manager) stopLocked() {
  307. if srv := m.srv; srv != nil {
  308. m.srv = nil
  309. m.reloader = nil
  310. // Shutdown closes the listener at once - the port is free to be
  311. // opened again - and lets requests in flight finish, including the
  312. // one that turned HTTPS off, whose answer would otherwise be lost.
  313. go func() {
  314. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  315. defer cancel()
  316. if err := srv.Shutdown(ctx); err != nil {
  317. _ = srv.Close()
  318. }
  319. }()
  320. }
  321. }
  322. // Close stops the TLS listeners and the leaf's renewal.
  323. func (m *Manager) Close() {
  324. m.mu.Lock()
  325. defer m.mu.Unlock()
  326. m.stopLocked()
  327. if m.caStop != nil {
  328. close(m.caStop)
  329. m.caStop = nil
  330. }
  331. if m.sniff != nil {
  332. m.sniff.close()
  333. }
  334. }
  335. // ErrLocked is returned for a change to a setting the environment fixes.
  336. var ErrLocked = errors.New("this setting is fixed in the server's environment")
  337. // ErrNotFull is returned for turning HTTPS off in a stricter mode.
  338. var ErrNotFull = errors.New("choose \"Everything\" first: browsers told to always use HTTPS in a stricter mode " +
  339. "need it answering for a while to be told to stop")
  340. // SetEnabled turns HTTPS on or off, live. Turning it off also returns plain
  341. // HTTP to full service: without HTTPS there is nowhere to redirect to.
  342. func (m *Manager) SetEnabled(on bool, by string) error {
  343. m.mu.Lock()
  344. defer m.mu.Unlock()
  345. if m.opts.Unavailable != "" || m.opts.EnvEnabled != nil {
  346. return ErrLocked
  347. }
  348. if on == m.enabled {
  349. return nil
  350. }
  351. if on {
  352. if err := m.startLocked(); err != nil {
  353. m.lastErr = err.Error()
  354. return err
  355. }
  356. } else {
  357. if m.opts.EnvMode != "" && m.opts.EnvMode != Full {
  358. return fmt.Errorf("%w: NETPULSE_HTTP_MODE=%s needs HTTPS", ErrLocked, m.opts.EnvMode)
  359. }
  360. // Only from full: browsers that got an HSTS policy in a stricter
  361. // mode need a while of full, where HTTPS answers with max-age=0,
  362. // to be told to drop it.
  363. if m.Mode() != Full {
  364. return ErrNotFull
  365. }
  366. m.stopLocked()
  367. m.pending = nil
  368. }
  369. m.enabled = on
  370. m.saveEnabled(on)
  371. // FORK: record the port it was turned on with, so a later change of
  372. // the default never moves a listener its agents are pinned to.
  373. if on && m.savedPort() == 0 {
  374. m.savePort(m.port)
  375. }
  376. m.opts.Logf("[netpulse] HTTPS turned %s by %s", onOff(on), by)
  377. return nil
  378. }
  379. // SetPort changes the HTTPS listener's port, live (#978): with HTTPS on the
  380. // listener rebinds at once (no restart); with HTTPS off the new port applies
  381. // the next time it is turned on. Agents that pinned the old port keep
  382. // trying it - the API warns about them before calling this.
  383. func (m *Manager) SetPort(port int, by string) error {
  384. m.mu.Lock()
  385. defer m.mu.Unlock()
  386. if m.opts.Unavailable != "" || m.opts.EnvPort {
  387. return ErrLocked
  388. }
  389. if port < 1 || port > 65535 {
  390. return fmt.Errorf("the port must be between 1 and 65535")
  391. }
  392. if m.opts.PlainPort != 0 && port == m.opts.PlainPort {
  393. return fmt.Errorf("the HTTPS port cannot be the plain HTTP port (%d)", m.opts.PlainPort)
  394. }
  395. if port == m.port {
  396. return nil
  397. }
  398. old := m.port
  399. m.port = port
  400. if m.enabled {
  401. m.stopLocked()
  402. if err := m.startLocked(); err != nil {
  403. // Roll back: better the old port than no HTTPS at all.
  404. m.port = old
  405. if err2 := m.startLocked(); err2 != nil {
  406. m.enabled = false
  407. m.mode.Store(Full)
  408. m.lastErr = err2.Error()
  409. return fmt.Errorf("HTTPS port %d failed (%v) and restoring %d failed too: %v", port, err, old, err2)
  410. }
  411. m.lastErr = err.Error()
  412. return fmt.Errorf("HTTPS port %d: %w", port, err)
  413. }
  414. }
  415. m.savePort(port)
  416. m.opts.Logf("[netpulse] HTTPS port %d -> %d by %s", old, port, by)
  417. return nil
  418. }
  419. // RequestMode changes what plain HTTP may do. Going back to full takes effect
  420. // at once; a stricter mode is staged and returns the code to confirm it with
  421. // from an HTTPS page (Confirm) before ConfirmWindow runs out.
  422. func (m *Manager) RequestMode(mode Mode, by string) (code string, expires time.Time, err error) {
  423. m.mu.Lock()
  424. defer m.mu.Unlock()
  425. if m.opts.Unavailable != "" || m.opts.EnvMode != "" {
  426. return "", time.Time{}, ErrLocked
  427. }
  428. if !m.enabled && mode != Full {
  429. return "", time.Time{}, errors.New("turn HTTPS on first")
  430. }
  431. if mode == Full {
  432. m.pending = nil
  433. m.applyModeLocked(Full, by)
  434. return "", time.Time{}, nil
  435. }
  436. b := make([]byte, 16)
  437. if _, err := rand.Read(b); err != nil {
  438. return "", time.Time{}, err
  439. }
  440. p := &pendingMode{mode: mode, code: hex.EncodeToString(b), expires: m.opts.Now().Add(ConfirmWindow), by: by}
  441. m.pending = p
  442. m.opts.Logf("[netpulse] HTTP mode %s staged by %s; waiting for confirmation over HTTPS", mode, by)
  443. return p.code, p.expires, nil
  444. }
  445. // ErrConfirm is returned for a confirmation that does not apply.
  446. var ErrConfirm = errors.New("no such change is waiting for confirmation; it may have expired")
  447. // Confirm applies a staged mode change. It must arrive over TLS: the point
  448. // is proving HTTPS works for the admin before plain HTTP is restricted.
  449. func (m *Manager) Confirm(code string, overTLS bool, by string) (Mode, error) {
  450. m.mu.Lock()
  451. defer m.mu.Unlock()
  452. if !overTLS {
  453. return "", errors.New("confirm from the HTTPS address, not over plain HTTP")
  454. }
  455. p := m.pending
  456. if p == nil || m.opts.Now().After(p.expires) ||
  457. subtle.ConstantTimeCompare([]byte(code), []byte(p.code)) != 1 {
  458. return "", ErrConfirm
  459. }
  460. m.pending = nil
  461. m.applyModeLocked(p.mode, by)
  462. return p.mode, nil
  463. }
  464. func (m *Manager) applyModeLocked(mode Mode, by string) {
  465. old := m.Mode()
  466. m.mode.Store(mode)
  467. m.saveMode(mode)
  468. if old != mode {
  469. m.opts.Logf("[netpulse] HTTP mode %s -> %s by %s", old, mode, by)
  470. }
  471. }
  472. // Mode is what plain HTTP may do now.
  473. func (m *Manager) Mode() Mode { return m.mode.Load().(Mode) }
  474. // Enabled reports whether the private-CA HTTPS listener is on.
  475. func (m *Manager) Enabled() bool {
  476. m.mu.Lock()
  477. defer m.mu.Unlock()
  478. return m.enabled
  479. }
  480. // SetCertificate makes the HTTPS listener serve a certificate from disk
  481. // instead of the private CA (#1756), which is what a homelab with its own PKI
  482. // wants. Empty paths go back to the CA. The pair is loaded before anything
  483. // changes, so a typo leaves the running listener untouched.
  484. func (m *Manager) SetCertificate(certPath, keyPath, by string) error {
  485. m.mu.Lock()
  486. defer m.mu.Unlock()
  487. if m.opts.Unavailable != "" {
  488. return ErrLocked
  489. }
  490. certPath, keyPath = strings.TrimSpace(certPath), strings.TrimSpace(keyPath)
  491. if (certPath == "") != (keyPath == "") {
  492. return errors.New("give both the certificate and its key, or neither")
  493. }
  494. if certPath != "" {
  495. if !filepath.IsAbs(certPath) || !filepath.IsAbs(keyPath) {
  496. return errors.New("the certificate and key paths must be absolute")
  497. }
  498. if _, err := tlscert.NewReloader(certPath, keyPath); err != nil {
  499. return fmt.Errorf("the certificate cannot be used: %w", err)
  500. }
  501. }
  502. oldCert, oldKey := m.savedCert()
  503. if certPath == oldCert && keyPath == oldKey {
  504. return nil
  505. }
  506. m.kvSet(kvCert, certPath)
  507. m.kvSet(kvKey, keyPath)
  508. if m.enabled {
  509. m.stopLocked()
  510. if err := m.startLocked(); err != nil {
  511. // Put back what was serving so a bad pair does not leave the
  512. // port closed.
  513. m.kvSet(kvCert, oldCert)
  514. m.kvSet(kvKey, oldKey)
  515. if back := m.startLocked(); back != nil {
  516. m.lastErr = back.Error()
  517. return fmt.Errorf("%w (and the previous certificate did not come back: %v)", err, back)
  518. }
  519. m.lastErr = ""
  520. return err
  521. }
  522. }
  523. source := "the private CA"
  524. if certPath != "" {
  525. source = "the certificate set in Settings"
  526. }
  527. m.opts.Logf("[netpulse] TLS: HTTPS now serves %s (%s)", source, by)
  528. return nil
  529. }
  530. // Fingerprint is the pin agents should use: the SPKI of the certificate the
  531. // listener serves now (the CA's leaf, or the one set in Settings, #1756), or
  532. // "" while HTTPS is off.
  533. func (m *Manager) Fingerprint() string {
  534. m.mu.Lock()
  535. defer m.mu.Unlock()
  536. return m.fingerprintLocked()
  537. }
  538. func (m *Manager) fingerprintLocked() string {
  539. if !m.enabled {
  540. return ""
  541. }
  542. if m.reloader != nil {
  543. return m.reloader.Fingerprint()
  544. }
  545. if ca := m.caLoaded.Load(); ca != nil {
  546. return ca.Fingerprint()
  547. }
  548. return ""
  549. }
  550. // CA is the private CA once it has been opened, for serving its root.
  551. func (m *Manager) CA() *tlscert.CA { return m.caLoaded.Load() }
  552. // CertSource says where the served certificate comes from: "custom" when a
  553. // pair was set in Settings (#1756), "ca" otherwise.
  554. func (m *Manager) CertSource() string {
  555. m.mu.Lock()
  556. defer m.mu.Unlock()
  557. if cert, _ := m.savedCert(); cert != "" {
  558. return "custom"
  559. }
  560. return "ca"
  561. }
  562. // Leaf is the certificate the HTTPS listener serves now, nil while HTTPS is
  563. // off. The trust helpers use it to know which names the server answers to.
  564. func (m *Manager) Leaf() *x509.Certificate {
  565. m.mu.Lock()
  566. defer m.mu.Unlock()
  567. if !m.enabled {
  568. return nil
  569. }
  570. if m.reloader != nil {
  571. return m.reloader.Leaf()
  572. }
  573. if ca := m.caLoaded.Load(); ca != nil {
  574. return ca.Leaf()
  575. }
  576. return nil
  577. }
  578. // Status is what the settings page shows.
  579. type Status struct {
  580. Available bool `json:"available"`
  581. Unavailable string `json:"unavailable,omitempty"`
  582. Enabled bool `json:"enabled"`
  583. EnabledLocked bool `json:"enabledLocked"`
  584. Mode Mode `json:"mode"`
  585. ModeLocked bool `json:"modeLocked"`
  586. Port int `json:"port"`
  587. PortLocked bool `json:"portLocked"`
  588. RootSHA256 string `json:"rootSha256,omitempty"`
  589. Fingerprint string `json:"fingerprint,omitempty"`
  590. // #1756: where the served certificate comes from. "custom" means the
  591. // paths below, so there is no root to download and nothing to renew
  592. // from here.
  593. CertSource string `json:"certSource"`
  594. CertPath string `json:"certPath,omitempty"`
  595. KeyPath string `json:"keyPath,omitempty"`
  596. Names []string `json:"names,omitempty"`
  597. Uncovered []string `json:"uncovered,omitempty"`
  598. ValidUntil time.Time `json:"validUntil,omitzero"`
  599. Pending Mode `json:"pending,omitempty"`
  600. PendingUntil time.Time `json:"pendingUntil,omitzero"`
  601. Error string `json:"error,omitempty"`
  602. }
  603. // Status reports the current state.
  604. func (m *Manager) Status() Status {
  605. m.mu.Lock()
  606. defer m.mu.Unlock()
  607. st := Status{
  608. Available: m.opts.Unavailable == "",
  609. Unavailable: m.opts.Unavailable,
  610. Enabled: m.enabled,
  611. EnabledLocked: m.opts.Unavailable != "" || m.opts.EnvEnabled != nil,
  612. Mode: m.Mode(),
  613. ModeLocked: m.opts.Unavailable != "" || m.opts.EnvMode != "",
  614. Port: m.port,
  615. PortLocked: m.opts.Unavailable != "" || m.opts.EnvPort,
  616. Error: m.lastErr,
  617. }
  618. if p := m.pending; p != nil && m.opts.Now().Before(p.expires) {
  619. st.Pending, st.PendingUntil = p.mode, p.expires
  620. }
  621. certPath, keyPath := m.savedCert()
  622. st.CertSource = "ca"
  623. if certPath != "" {
  624. st.CertSource, st.CertPath, st.KeyPath = "custom", certPath, keyPath
  625. }
  626. if m.enabled {
  627. switch {
  628. case m.reloader != nil:
  629. st.Fingerprint = m.reloader.Fingerprint()
  630. if leaf := m.reloader.Leaf(); leaf != nil {
  631. st.Names = append(slices.Clone(leaf.DNSNames), ipStrings(leaf.IPAddresses)...)
  632. st.ValidUntil = leaf.NotAfter
  633. }
  634. case m.ca != nil:
  635. st.RootSHA256 = m.ca.RootSHA256()
  636. st.Fingerprint = m.ca.Fingerprint()
  637. st.Uncovered = m.ca.Uncovered()
  638. if leaf := m.ca.Leaf(); leaf != nil {
  639. st.Names = append(slices.Clone(leaf.DNSNames), ipStrings(leaf.IPAddresses)...)
  640. st.ValidUntil = leaf.NotAfter
  641. }
  642. }
  643. }
  644. return st
  645. }
  646. // Renew re-reads the host's addresses and names now, instead of at the next
  647. // periodic check, and issues a new certificate if they changed. It reports
  648. // whether it issued one. The root, and so every pin, stays the same.
  649. func (m *Manager) Renew(by string) (bool, error) {
  650. m.mu.Lock()
  651. ca, on, custom := m.ca, m.enabled, m.reloader != nil
  652. m.mu.Unlock()
  653. if custom {
  654. // #1756: nothing to reissue, the file is someone else's.
  655. return false, errors.New("this certificate comes from a file, renew it where it is issued")
  656. }
  657. if ca == nil || !on {
  658. return false, errors.New("turn HTTPS on first")
  659. }
  660. issued, err := ca.Refresh()
  661. if err == nil {
  662. m.opts.Logf("[netpulse] TLS: certificate checked by %s (new one issued: %v)", by, issued)
  663. }
  664. return issued, err
  665. }
  666. // HSTS is the Strict-Transport-Security value for a response, "" for none.
  667. //
  668. // While plain HTTP still serves everything (full), HTTPS responses send
  669. // max-age=0: that clears any HSTS a browser kept from a stricter mode, so
  670. // going back to full really does make plain HTTP usable again. During
  671. // migrate the policy is short, so undoing it is cheap; only redirect, which
  672. // is meant to stay, gets a year. includeSubDomains is never sent.
  673. func (m *Manager) HSTS(secure bool) string {
  674. if !secure || m.CA() == nil {
  675. return ""
  676. }
  677. if !m.Enabled() {
  678. return "max-age=0" // served through the plain port's TLS side
  679. }
  680. switch m.Mode() {
  681. case Migrate:
  682. return "max-age=86400"
  683. case Redirect:
  684. return "max-age=31536000"
  685. default:
  686. return "max-age=0"
  687. }
  688. }
  689. // RedirectTarget is where a plain HTTP request is sent: the same path and
  690. // query, on the HTTPS port, at a host this server's certificate names. The
  691. // request's Host header is only used when the certificate names it, so a
  692. // forged Host cannot turn this into a redirect elsewhere.
  693. func (m *Manager) RedirectTarget(r *http.Request) (string, bool) {
  694. ca := m.caLoaded.Load()
  695. if ca == nil {
  696. return "", false
  697. }
  698. leaf := ca.Leaf()
  699. if leaf == nil {
  700. return "", false
  701. }
  702. named := func(h string) bool { return h != "" && leafNames(leaf.DNSNames, leaf.IPAddresses, h) }
  703. // In order: the name the browser used; the address the request arrived
  704. // on; the public URL's host; any address the certificate names.
  705. host := strings.ToLower(hostOnly(r.Host))
  706. if !named(host) {
  707. host = ""
  708. if a, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); ok {
  709. if h := hostOnly(a.String()); named(h) {
  710. host = h
  711. }
  712. }
  713. if h := urlHost(m.opts.PublicURL); host == "" && named(h) {
  714. host = h
  715. }
  716. if host == "" {
  717. host = firstReachable(leaf.IPAddresses)
  718. }
  719. }
  720. if host == "" {
  721. return "", false
  722. }
  723. u := url.URL{
  724. Scheme: "https",
  725. Host: net.JoinHostPort(host, fmt.Sprint(m.currentPort())),
  726. Path: r.URL.Path,
  727. RawQuery: r.URL.RawQuery,
  728. }
  729. return u.String(), true
  730. }
  731. // --- persistence ---
  732. func (m *Manager) savedEnabled() bool {
  733. return m.kvGet(kvEnabled) == "1"
  734. }
  735. func (m *Manager) savedMode() Mode {
  736. if mode, err := ParseMode(m.kvGet(kvMode)); err == nil {
  737. return mode
  738. }
  739. return Full
  740. }
  741. // savedPort (#978): the UI-chosen port, 0 when absent or invalid.
  742. // savedCert is the certificate pair set in Settings, empty when the private
  743. // CA is the source (#1756).
  744. func (m *Manager) savedCert() (string, string) {
  745. return m.kvGet(kvCert), m.kvGet(kvKey)
  746. }
  747. func (m *Manager) savedPort() int {
  748. v := m.kvGet(kvPort)
  749. if v == "" {
  750. return 0
  751. }
  752. n, err := strconv.Atoi(v)
  753. if err != nil || n < 1 || n > 65535 {
  754. return 0
  755. }
  756. return n
  757. }
  758. func (m *Manager) saveEnabled(on bool) {
  759. v := "0"
  760. if on {
  761. v = "1"
  762. }
  763. m.kvSet(kvEnabled, v)
  764. }
  765. func (m *Manager) saveMode(mode Mode) {
  766. if m.opts.EnvMode == "" {
  767. m.kvSet(kvMode, string(mode))
  768. }
  769. }
  770. func (m *Manager) savePort(port int) {
  771. if !m.opts.EnvPort {
  772. m.kvSet(kvPort, strconv.Itoa(port))
  773. }
  774. }
  775. func (m *Manager) kvGet(key string) string {
  776. if m.opts.DB == nil {
  777. return ""
  778. }
  779. var v string
  780. _ = m.opts.DB.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v)
  781. return v
  782. }
  783. func (m *Manager) kvSet(key, value string) {
  784. if m.opts.DB == nil {
  785. return
  786. }
  787. if _, err := m.opts.DB.Exec(
  788. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  789. key, value); err != nil {
  790. m.opts.Logf("[netpulse] HTTPS: could not save %s: %v", key, err)
  791. }
  792. }
  793. // --- helpers ---
  794. func onOff(b bool) string {
  795. if b {
  796. return "on"
  797. }
  798. return "off"
  799. }
  800. func urlHost(raw string) string {
  801. if raw == "" {
  802. return ""
  803. }
  804. u, err := url.Parse(raw)
  805. if err != nil {
  806. return ""
  807. }
  808. return u.Hostname()
  809. }
  810. func hostOnly(hostport string) string {
  811. if h, _, err := net.SplitHostPort(hostport); err == nil {
  812. return h
  813. }
  814. return hostport
  815. }
  816. func leafNames(dns []string, ips []net.IP, host string) bool {
  817. if ip := net.ParseIP(host); ip != nil {
  818. return slices.ContainsFunc(ips, ip.Equal)
  819. }
  820. for _, d := range dns {
  821. if d == host {
  822. return true
  823. }
  824. }
  825. return false
  826. }
  827. // firstReachable picks an address other devices can use: IPv4, not
  828. // loopback, and outside 172.16/12 when possible - where container bridges
  829. // usually live, which nothing else on the network can reach.
  830. func firstReachable(ips []net.IP) string {
  831. _, bridges, _ := net.ParseCIDR("172.16.0.0/12")
  832. fallback := ""
  833. for _, ip := range ips {
  834. if ip.IsLoopback() || ip.To4() == nil {
  835. continue
  836. }
  837. if !bridges.Contains(ip) {
  838. return ip.String()
  839. }
  840. if fallback == "" {
  841. fallback = ip.String()
  842. }
  843. }
  844. return fallback
  845. }
  846. func ipStrings(ips []net.IP) []string {
  847. out := make([]string, 0, len(ips))
  848. for _, ip := range ips {
  849. out = append(out, ip.String())
  850. }
  851. return out
  852. }
  853. // Available reports whether this server's HTTPS is managed here at all.
  854. func (m *Manager) Available() bool { return m.opts.Unavailable == "" }
  855. func fileExists(path string) bool {
  856. _, err := os.Stat(path)
  857. return err == nil
  858. }