manager.go 22 KB

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