https_settings.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. Force bool `json:"force"`
  165. Password string `json:"password"`
  166. }
  167. if st := readJSONBody(w, r, &body); st != 0 {
  168. writeBodyError(w, st, "invalid_input", `expected { "enabled"?, "mode"?, "password" }`)
  169. return
  170. }
  171. // Counted as sign-in attempts: a stolen session must not be a way to
  172. // guess the password without the sign-in's lockout.
  173. if limited, retry := auth.LoginRateLimited(s.db, r); limited {
  174. writeJSON(w, http.StatusTooManyRequests, map[string]any{"error": "rate_limited", "retryAfterSec": retry})
  175. return
  176. }
  177. if me == nil || !s.checkOwnPassword(me.ID, body.Password) {
  178. auth.RegisterLoginFail(s.db, r)
  179. writeError(w, http.StatusUnauthorized, "invalid_credentials", "the password is not correct")
  180. return
  181. }
  182. by := me.Username + " from " + auth.ClientIP(r)
  183. if body.Enabled != nil && !*body.Enabled && !body.Force {
  184. // Agents already moved to HTTPS pin its key and have no way back to
  185. // plain HTTP by themselves: turning it off cuts them off.
  186. if moved := s.agentsByTransport(true); len(moved) > 0 && s.tlsMgr.Enabled() {
  187. writeJSON(w, http.StatusConflict, map[string]any{
  188. "error": "agents_on_https",
  189. "message": "these agents report over HTTPS and would stop reporting",
  190. "agents": moved,
  191. })
  192. return
  193. }
  194. }
  195. if body.Enabled != nil {
  196. if err := s.tlsMgr.SetEnabled(*body.Enabled, by); err != nil {
  197. writeHTTPSError(w, err)
  198. return
  199. }
  200. }
  201. resp := map[string]any{}
  202. if body.Mode != nil {
  203. mode, err := tlsmode.ParseMode(*body.Mode)
  204. if err != nil {
  205. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  206. return
  207. }
  208. if mode == tlsmode.Redirect && !body.Force {
  209. if left := s.agentsOnHTTP(); len(left) > 0 {
  210. writeJSON(w, http.StatusConflict, map[string]any{
  211. "error": "agents_on_http",
  212. "message": "these agents still report over plain HTTP and would stop reporting",
  213. "agents": left,
  214. })
  215. return
  216. }
  217. }
  218. code, expires, err := s.tlsMgr.RequestMode(mode, by)
  219. if err != nil {
  220. writeHTTPSError(w, err)
  221. return
  222. }
  223. if code != "" {
  224. resp["pending"] = mode
  225. resp["expires"] = expires
  226. resp["confirmUrl"] = s.confirmURL(r, code)
  227. }
  228. }
  229. resp["status"] = s.tlsMgr.Status()
  230. writeJSON(w, http.StatusOK, resp)
  231. }
  232. // confirmURL is the HTTPS page the change must be confirmed from.
  233. func (s *server) confirmURL(r *http.Request, code string) string {
  234. u := &url.URL{Path: "/settings", RawQuery: url.Values{"tab": {"https"}, "confirm": {code}}.Encode()}
  235. req := r.Clone(r.Context())
  236. req.URL = u
  237. if target, ok := s.tlsMgr.RedirectTarget(req); ok {
  238. return target
  239. }
  240. return u.String()
  241. }
  242. func (s *server) handleHTTPSConfirm(w http.ResponseWriter, r *http.Request) {
  243. me := auth.UserFromContext(r.Context())
  244. var body struct {
  245. Code string `json:"code"`
  246. }
  247. if st := readJSONBody(w, r, &body); st != 0 {
  248. writeBodyError(w, st, "invalid_input", `expected { "code": "..." }`)
  249. return
  250. }
  251. by := "unknown"
  252. if me != nil {
  253. by = me.Username + " from " + auth.ClientIP(r)
  254. }
  255. if _, err := s.tlsMgr.Confirm(body.Code, auth.IsSecureRequest(r), by); err != nil {
  256. writeHTTPSError(w, err)
  257. return
  258. }
  259. writeJSON(w, http.StatusOK, map[string]any{"status": s.tlsMgr.Status()})
  260. }
  261. // handleHTTPSRenew re-checks the certificate against the host's current
  262. // addresses and names. No password: it changes nothing an admin could not
  263. // already get by waiting for the periodic check - same root, same pins.
  264. func (s *server) handleHTTPSRenew(w http.ResponseWriter, r *http.Request) {
  265. by := "unknown"
  266. if me := auth.UserFromContext(r.Context()); me != nil {
  267. by = me.Username + " from " + auth.ClientIP(r)
  268. }
  269. issued, err := s.tlsMgr.Renew(by)
  270. if err != nil {
  271. writeHTTPSError(w, err)
  272. return
  273. }
  274. writeJSON(w, http.StatusOK, map[string]any{"issued": issued, "status": s.tlsMgr.Status()})
  275. }
  276. func writeHTTPSError(w http.ResponseWriter, err error) {
  277. switch {
  278. case errors.Is(err, tlsmode.ErrLocked):
  279. writeError(w, http.StatusConflict, "locked", err.Error())
  280. case errors.Is(err, tlsmode.ErrNotFull):
  281. writeError(w, http.StatusConflict, "not_full", err.Error())
  282. case errors.Is(err, tlsmode.ErrConfirm):
  283. writeError(w, http.StatusGone, "expired", err.Error())
  284. default:
  285. writeError(w, http.StatusBadRequest, "https_error", err.Error())
  286. }
  287. }
  288. // checkOwnPassword checks the signed-in user's password, as changing it does.
  289. func (s *server) checkOwnPassword(userID int64, password string) bool {
  290. if password == "" {
  291. return false
  292. }
  293. var hash string
  294. if err := s.db.QueryRow("SELECT pass_hash FROM users WHERE id = ?", userID).Scan(&hash); err != nil {
  295. return false
  296. }
  297. return auth.CheckPassword(password, hash)
  298. }
  299. // handleCARoot serves the root certificate. It is public by nature - devices
  300. // need it before they can trust HTTPS - and the page that links it tells the
  301. // admin to compare its fingerprint with the one the server logged.
  302. func (s *server) handleCARoot(asPEM bool) http.HandlerFunc {
  303. return func(w http.ResponseWriter, _ *http.Request) {
  304. ca := s.tlsMgr.CA()
  305. if ca == nil || !s.tlsMgr.Enabled() {
  306. http.NotFound(w, nil)
  307. return
  308. }
  309. if asPEM {
  310. w.Header().Set("Content-Type", "application/x-pem-file")
  311. w.Header().Set("Content-Disposition", `attachment; filename="netpulse-ca.pem"`)
  312. _, _ = w.Write(ca.RootPEM())
  313. return
  314. }
  315. // DER with this type is what Android and iOS offer to install.
  316. w.Header().Set("Content-Type", "application/x-x509-ca-cert")
  317. w.Header().Set("Content-Disposition", `attachment; filename="netpulse-ca.crt"`)
  318. _, _ = w.Write(ca.RootDER())
  319. }
  320. }