https_settings.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. package httpapi
  2. // FORK: Settings > HTTPS - turning HTTPS on, choosing what plain HTTP may
  3. // still do, and handing out the private CA's root. See internal/tlsmode.
  4. //
  5. // GET /api/settings/https (admin) state, and the agents still on HTTP
  6. // POST /api/settings/https (admin, password) {enabled?, mode?, port?, cert?, key?, force?}
  7. // POST /api/settings/https/confirm (admin, over HTTPS) {code}
  8. // GET /netpulse-ca.crt | .pem (anyone) the root, for devices to install
  9. import (
  10. "errors"
  11. "net/http"
  12. "net/url"
  13. "slices"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/gnacho/netpulse/server-go/internal/auth"
  18. "github.com/gnacho/netpulse/server-go/internal/security"
  19. "github.com/gnacho/netpulse/server-go/internal/tlscert"
  20. "github.com/gnacho/netpulse/server-go/internal/tlsmode"
  21. )
  22. type agentTransport struct {
  23. TLS bool
  24. At time.Time
  25. saved time.Time // when it was last written to kv
  26. }
  27. const (
  28. agentTransportPrefix = "agent.transport."
  29. // An agent silent for longer than this no longer counts as "still on
  30. // HTTP": it is gone, or will show up again when it next reports.
  31. agentTransportWindow = 24 * time.Hour
  32. // Written to kv when the transport changes, and at most this often
  33. // otherwise - not on every push.
  34. agentTransportSaveEvery = time.Hour
  35. )
  36. // noteAgentTransport records how an agent's push arrived. It is kept in kv
  37. // too: the check before refusing plain HTTP to agents must not forget them
  38. // because the server restarted.
  39. func (s *server) noteAgentTransport(slug string, overTLS bool) {
  40. now := time.Now()
  41. t := agentTransport{TLS: overTLS, At: now}
  42. if v, ok := s.agentTransport.Load(slug); ok {
  43. prev := v.(agentTransport)
  44. t.saved = prev.saved
  45. if prev.TLS != overTLS {
  46. t.saved = time.Time{}
  47. }
  48. }
  49. if s.db != nil && now.Sub(t.saved) >= agentTransportSaveEvery {
  50. v := "http"
  51. if overTLS {
  52. v = "tls"
  53. }
  54. if _, err := s.db.Exec(
  55. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  56. agentTransportPrefix+slug, v+" "+strconv.FormatInt(now.Unix(), 10)); err == nil {
  57. t.saved = now
  58. }
  59. }
  60. s.agentTransport.Store(slug, t)
  61. }
  62. // agentOnHTTP is an agent and the last time it reported.
  63. type agentOnHTTP struct {
  64. Slug string `json:"slug"`
  65. LastSeen time.Time `json:"lastSeen"`
  66. }
  67. // agentsByTransport lists the agents whose last push came over TLS (tls) or
  68. // over plain HTTP (!tls): recent ones, that still exist.
  69. func (s *server) agentsByTransport(tls bool) []agentOnHTTP {
  70. last := map[string]agentTransport{}
  71. if s.db != nil {
  72. rows, err := s.db.Query("SELECT key, value FROM kv WHERE key LIKE ?", agentTransportPrefix+"%")
  73. if err == nil {
  74. for rows.Next() {
  75. var k, v string
  76. if rows.Scan(&k, &v) != nil {
  77. continue
  78. }
  79. kind, ts, _ := strings.Cut(v, " ")
  80. sec, err := strconv.ParseInt(ts, 10, 64)
  81. if err != nil {
  82. continue
  83. }
  84. last[strings.TrimPrefix(k, agentTransportPrefix)] = agentTransport{TLS: kind == "tls", At: time.Unix(sec, 0)}
  85. }
  86. rows.Close()
  87. }
  88. }
  89. s.agentTransport.Range(func(k, v any) bool {
  90. last[k.(string)] = v.(agentTransport)
  91. return true
  92. })
  93. // Never nil: the page reads the list's length, and a JSON null there
  94. // took the whole Settings page down.
  95. out := []agentOnHTTP{}
  96. for slug, t := range last {
  97. if t.TLS != tls || time.Since(t.At) > agentTransportWindow || !s.agentExists(slug) {
  98. continue
  99. }
  100. out = append(out, agentOnHTTP{Slug: slug, LastSeen: t.At})
  101. }
  102. slices.SortFunc(out, func(a, b agentOnHTTP) int { return strings.Compare(a.Slug, b.Slug) })
  103. return out
  104. }
  105. func (s *server) agentsOnHTTP() []agentOnHTTP { return s.agentsByTransport(false) }
  106. // agentExists: a deleted agent's token is gone.
  107. func (s *server) agentExists(slug string) bool {
  108. if s.db == nil {
  109. return true
  110. }
  111. var v string
  112. return s.db.QueryRow("SELECT value FROM kv WHERE key = ?", agentTokenKey(slug)).Scan(&v) == nil
  113. }
  114. // hsts decides the Strict-Transport-Security header (see security.Middleware:
  115. // it is per host, not per port).
  116. func (s *server) hsts(r *http.Request) string {
  117. secure := auth.IsSecureRequest(r)
  118. // Once the private CA exists the manager decides - with HTTPS off too,
  119. // when the plain port's TLS side answers max-age=0.
  120. if s.tlsMgr != nil && s.tlsMgr.Available() && s.tlsMgr.CA() != nil {
  121. return s.tlsMgr.HSTS(secure)
  122. }
  123. switch {
  124. case r.TLS != nil && s.cfg != nil && s.cfg.Onbox:
  125. // On-box, PORT itself is TLS: no plain port is left to break.
  126. return security.HSTS
  127. case r.TLS == nil && secure:
  128. // Behind a TLS-terminating proxy the server trusts, which serves
  129. // every port of the name.
  130. return security.HSTS
  131. default:
  132. // The extra TLS listener while PORT still serves plain HTTP: a
  133. // policy from it would make browsers rewrite http://name:PORT to
  134. // https://name:PORT, where nothing speaks TLS.
  135. return ""
  136. }
  137. }
  138. func (s *server) registerHTTPS(mux *http.ServeMux) {
  139. if s.tlsMgr == nil {
  140. return
  141. }
  142. mux.Handle("GET /api/settings/https", auth.RequireAdmin(http.HandlerFunc(s.handleHTTPSStatus)))
  143. mux.Handle("POST /api/settings/https", auth.RequireAdmin(http.HandlerFunc(s.handleHTTPSChange)))
  144. mux.Handle("POST /api/settings/https/confirm", auth.RequireAdmin(http.HandlerFunc(s.handleHTTPSConfirm)))
  145. mux.Handle("POST /api/settings/https/renew", auth.RequireAdmin(http.HandlerFunc(s.handleHTTPSRenew)))
  146. mux.HandleFunc("GET /netpulse-ca.crt", s.handleCARoot(false))
  147. mux.HandleFunc("GET /netpulse-ca.pem", s.handleCARoot(true))
  148. }
  149. type httpsStatus struct {
  150. tlsmode.Status
  151. AgentsOnHTTP []agentOnHTTP `json:"agentsOnHttp"`
  152. }
  153. func (s *server) handleHTTPSStatus(w http.ResponseWriter, _ *http.Request) {
  154. writeJSON(w, http.StatusOK, httpsStatus{Status: s.tlsMgr.Status(), AgentsOnHTTP: s.agentsOnHTTP()})
  155. }
  156. // handleHTTPSChange turns HTTPS on or off and requests a mode. Every change
  157. // asks for the admin's password again: transport security is not something
  158. // a stolen session cookie alone should be able to change, in either
  159. // direction.
  160. func (s *server) handleHTTPSChange(w http.ResponseWriter, r *http.Request) {
  161. me := auth.UserFromContext(r.Context())
  162. var body struct {
  163. Enabled *bool `json:"enabled"`
  164. Mode *string `json:"mode"`
  165. Port *int `json:"port"`
  166. Cert *string `json:"cert"`
  167. Key *string `json:"key"`
  168. Force bool `json:"force"`
  169. Password string `json:"password"`
  170. }
  171. if st := readJSONBody(w, r, &body); st != 0 {
  172. writeBodyError(w, st, "invalid_input", `expected { "enabled"?, "mode"?, "port"?, "cert"?, "key"?, "password" }`)
  173. return
  174. }
  175. // Counted as sign-in attempts: a stolen session must not be a way to
  176. // guess the password without the sign-in's lockout.
  177. if limited, retry := auth.LoginRateLimited(s.db, r); limited {
  178. writeJSON(w, http.StatusTooManyRequests, map[string]any{"error": "rate_limited", "retryAfterSec": retry})
  179. return
  180. }
  181. if me == nil || !s.checkOwnPassword(me.ID, body.Password) {
  182. auth.RegisterLoginFail(s.db, r)
  183. writeError(w, http.StatusUnauthorized, "invalid_credentials", "the password is not correct")
  184. return
  185. }
  186. by := me.Username + " from " + auth.ClientIP(r)
  187. if body.Enabled != nil && !*body.Enabled && !body.Force {
  188. // Agents already moved to HTTPS pin its key and have no way back to
  189. // plain HTTP by themselves: turning it off cuts them off.
  190. if moved := s.agentsByTransport(true); len(moved) > 0 && s.tlsMgr.Enabled() {
  191. writeJSON(w, http.StatusConflict, map[string]any{
  192. "error": "agents_on_https",
  193. "message": "these agents report over HTTPS and would stop reporting",
  194. "agents": moved,
  195. })
  196. return
  197. }
  198. }
  199. // Puerto HTTPS (#978): cambiarlo reconecta el listener al momento. Los
  200. // agentes que ya reportan por HTTPS apuntan al puerto viejo y no tienen
  201. // vuelta solos: mismo aviso que al desactivar, salvo force.
  202. if body.Port != nil && *body.Port != s.tlsMgr.Status().Port {
  203. httpsPort := *body.Port
  204. if !body.Force && s.tlsMgr.Enabled() {
  205. if moved := s.agentsByTransport(true); len(moved) > 0 {
  206. writeJSON(w, http.StatusConflict, map[string]any{
  207. "error": "agents_on_https",
  208. "message": "these agents report over HTTPS on the current port and would stop reporting",
  209. "agents": moved,
  210. })
  211. return
  212. }
  213. }
  214. if err := s.tlsMgr.SetPort(httpsPort, by); err != nil {
  215. writeHTTPSError(w, err)
  216. return
  217. }
  218. }
  219. if body.Cert != nil || body.Key != nil {
  220. cert, key := "", ""
  221. if body.Cert != nil {
  222. cert = strings.TrimSpace(*body.Cert)
  223. }
  224. if body.Key != nil {
  225. key = strings.TrimSpace(*body.Key)
  226. }
  227. // #1756: agents on HTTPS pin the key they were given. Switching to
  228. // a certificate with a different key leaves them unable to verify,
  229. // so it needs the same acknowledgement as turning HTTPS off. A
  230. // renewal that keeps the key (certbot --reuse-key) does not.
  231. if !body.Force && s.tlsMgr.Enabled() && cert != "" {
  232. if moved := s.agentsByTransport(true); len(moved) > 0 {
  233. if r, err := tlscert.NewReloader(cert, key); err == nil && r.Fingerprint() != s.tlsMgr.Fingerprint() {
  234. writeJSON(w, http.StatusConflict, map[string]any{
  235. "error": "agents_on_https",
  236. "message": "this certificate has a different key, so the agents pinned to the current one would stop reporting",
  237. "agents": moved,
  238. })
  239. return
  240. }
  241. }
  242. }
  243. if err := s.tlsMgr.SetCertificate(cert, key, by); err != nil {
  244. writeHTTPSError(w, err)
  245. return
  246. }
  247. }
  248. if body.Enabled != nil {
  249. if err := s.tlsMgr.SetEnabled(*body.Enabled, by); err != nil {
  250. writeHTTPSError(w, err)
  251. return
  252. }
  253. }
  254. resp := map[string]any{}
  255. if body.Mode != nil {
  256. mode, err := tlsmode.ParseMode(*body.Mode)
  257. if err != nil {
  258. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  259. return
  260. }
  261. if mode == tlsmode.Redirect && !body.Force {
  262. if left := s.agentsOnHTTP(); len(left) > 0 {
  263. writeJSON(w, http.StatusConflict, map[string]any{
  264. "error": "agents_on_http",
  265. "message": "these agents still report over plain HTTP and would stop reporting",
  266. "agents": left,
  267. })
  268. return
  269. }
  270. }
  271. code, expires, err := s.tlsMgr.RequestMode(mode, by)
  272. if err != nil {
  273. writeHTTPSError(w, err)
  274. return
  275. }
  276. if code != "" {
  277. resp["pending"] = mode
  278. resp["expires"] = expires
  279. resp["confirmUrl"] = s.confirmURL(r, code)
  280. }
  281. }
  282. resp["status"] = s.tlsMgr.Status()
  283. writeJSON(w, http.StatusOK, resp)
  284. }
  285. // confirmURL is the HTTPS page the change must be confirmed from.
  286. func (s *server) confirmURL(r *http.Request, code string) string {
  287. u := &url.URL{Path: "/settings", RawQuery: url.Values{"tab": {"https"}, "confirm": {code}}.Encode()}
  288. req := r.Clone(r.Context())
  289. req.URL = u
  290. if target, ok := s.tlsMgr.RedirectTarget(req); ok {
  291. return target
  292. }
  293. return u.String()
  294. }
  295. func (s *server) handleHTTPSConfirm(w http.ResponseWriter, r *http.Request) {
  296. me := auth.UserFromContext(r.Context())
  297. var body struct {
  298. Code string `json:"code"`
  299. }
  300. if st := readJSONBody(w, r, &body); st != 0 {
  301. writeBodyError(w, st, "invalid_input", `expected { "code": "..." }`)
  302. return
  303. }
  304. by := "unknown"
  305. if me != nil {
  306. by = me.Username + " from " + auth.ClientIP(r)
  307. }
  308. if _, err := s.tlsMgr.Confirm(body.Code, auth.IsSecureRequest(r), by); err != nil {
  309. writeHTTPSError(w, err)
  310. return
  311. }
  312. writeJSON(w, http.StatusOK, map[string]any{"status": s.tlsMgr.Status()})
  313. }
  314. // handleHTTPSRenew re-checks the certificate against the host's current
  315. // addresses and names. No password: it changes nothing an admin could not
  316. // already get by waiting for the periodic check - same root, same pins.
  317. func (s *server) handleHTTPSRenew(w http.ResponseWriter, r *http.Request) {
  318. by := "unknown"
  319. if me := auth.UserFromContext(r.Context()); me != nil {
  320. by = me.Username + " from " + auth.ClientIP(r)
  321. }
  322. issued, err := s.tlsMgr.Renew(by)
  323. if err != nil {
  324. writeHTTPSError(w, err)
  325. return
  326. }
  327. writeJSON(w, http.StatusOK, map[string]any{"issued": issued, "status": s.tlsMgr.Status()})
  328. }
  329. func writeHTTPSError(w http.ResponseWriter, err error) {
  330. switch {
  331. case errors.Is(err, tlsmode.ErrLocked):
  332. writeError(w, http.StatusConflict, "locked", err.Error())
  333. case errors.Is(err, tlsmode.ErrNotFull):
  334. writeError(w, http.StatusConflict, "not_full", err.Error())
  335. case errors.Is(err, tlsmode.ErrConfirm):
  336. writeError(w, http.StatusGone, "expired", err.Error())
  337. default:
  338. writeError(w, http.StatusBadRequest, "https_error", err.Error())
  339. }
  340. }
  341. // checkOwnPassword checks the signed-in user's password, as changing it does.
  342. func (s *server) checkOwnPassword(userID int64, password string) bool {
  343. if password == "" {
  344. return false
  345. }
  346. var hash string
  347. if err := s.db.QueryRow("SELECT pass_hash FROM users WHERE id = ?", userID).Scan(&hash); err != nil {
  348. return false
  349. }
  350. return auth.CheckPassword(password, hash)
  351. }
  352. // handleCARoot serves the root certificate. It is public by nature - devices
  353. // need it before they can trust HTTPS - and the page that links it tells the
  354. // admin to compare its fingerprint with the one the server logged.
  355. func (s *server) handleCARoot(asPEM bool) http.HandlerFunc {
  356. return func(w http.ResponseWriter, _ *http.Request) {
  357. ca := s.tlsMgr.CA()
  358. if ca == nil || !s.tlsMgr.Enabled() {
  359. http.NotFound(w, nil)
  360. return
  361. }
  362. if asPEM {
  363. w.Header().Set("Content-Type", "application/x-pem-file")
  364. w.Header().Set("Content-Disposition", `attachment; filename="netpulse-ca.pem"`)
  365. _, _ = w.Write(ca.RootPEM())
  366. return
  367. }
  368. // DER with this type is what Android and iOS offer to install.
  369. w.Header().Set("Content-Type", "application/x-x509-ca-cert")
  370. w.Header().Set("Content-Disposition", `attachment; filename="netpulse-ca.crt"`)
  371. _, _ = w.Write(ca.RootDER())
  372. }
  373. }