https_settings.go 12 KB

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