4
0

pairing.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // pairing.go — Fase 9 R3: pairing/adopción cero-fricción de agentes.
  2. //
  3. // El servidor on-box genera un pairing token (UUID) en el primer arranque,
  4. // visible en la UI de Ajustes > Adopción y en el log. Al instalar un agente
  5. // nuevo, el admin proporciona el pairing token + el server_fp (ambos visibles
  6. // en la UI). El agente contacta POST /api/agents/pair con ambos; el servidor
  7. // valida el pairing token, crea el agente (slug + token) y devuelve el token
  8. // real del agente + el server_fp para que lo pinee.
  9. //
  10. // POST /api/agents/pair NO requiere sesión (el pairing token ES la auth) pero
  11. // lleva rate limit por IP (mismo que la ingesta, 30/min).
  12. //
  13. // GET /api/pairing/token (admin) — ver el pairing token actual.
  14. // POST /api/pairing/rotate (admin) — rotar el pairing token (invalida el viejo).
  15. package httpapi
  16. import (
  17. "crypto/rand"
  18. "crypto/subtle"
  19. "encoding/hex"
  20. "fmt"
  21. "net/http"
  22. "github.com/gnacho/netpulse/agent/pairproof"
  23. "github.com/gnacho/netpulse/server-go/internal/auth"
  24. "github.com/gnacho/netpulse/server-go/internal/db"
  25. "github.com/gnacho/netpulse/server-go/internal/tlsmode"
  26. )
  27. const pairingTokenKey = "pairing.token"
  28. // newPairingToken genera un UUID v4 como string (crypto/rand).
  29. func newPairingToken() (string, error) {
  30. b := make([]byte, 16)
  31. if _, err := rand.Read(b); err != nil {
  32. return "", err
  33. }
  34. b[6] = (b[6] & 0x0f) | 0x40 // version 4
  35. b[8] = (b[8] & 0x3f) | 0x80 // variant 10
  36. return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]), nil
  37. }
  38. // getPairingToken lee el pairing token actual del kv. Si no existe, lo genera.
  39. func (s *server) getPairingToken() (string, error) {
  40. var existing string
  41. err := s.db.QueryRow("SELECT value FROM kv WHERE key = ?", pairingTokenKey).Scan(&existing)
  42. if err == nil && existing != "" {
  43. return existing, nil
  44. }
  45. // Generar uno nuevo si no existe (primer arranque o migración).
  46. tok, err := newPairingToken()
  47. if err != nil {
  48. return "", err
  49. }
  50. if _, err := s.db.Exec(
  51. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
  52. pairingTokenKey, tok); err != nil {
  53. return "", err
  54. }
  55. return tok, nil
  56. }
  57. // handlePairingToken (GET /api/pairing/token): devuelve el pairing token
  58. // actual (admin only — el token permite adoptar agentes).
  59. func (s *server) handlePairingToken(w http.ResponseWriter, _ *http.Request) {
  60. tok, err := s.getPairingToken()
  61. if err != nil {
  62. writeError(w, http.StatusInternalServerError, "pairing_error")
  63. return
  64. }
  65. writeJSON(w, http.StatusOK, map[string]string{"token": tok, "server_fp": s.fingerprint()})
  66. }
  67. // handlePairingRotate (POST /api/pairing/rotate): genera un pairing token
  68. // nuevo, reemplazando el anterior. Los agentes ya paired siguen funcionando
  69. // (su token de agente es independiente).
  70. func (s *server) handlePairingRotate(w http.ResponseWriter, _ *http.Request) {
  71. tok, err := newPairingToken()
  72. if err != nil {
  73. writeError(w, http.StatusInternalServerError, "token_error")
  74. return
  75. }
  76. if _, err := s.db.Exec(
  77. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  78. pairingTokenKey, tok); err != nil {
  79. writeError(w, http.StatusInternalServerError, "token_error")
  80. return
  81. }
  82. writeJSON(w, http.StatusOK, map[string]string{"token": tok})
  83. }
  84. // pairRequest es el body de POST /api/agents/pair.
  85. type pairRequest struct {
  86. PairingToken string `json:"pairing_token"`
  87. Slug string `json:"slug"`
  88. }
  89. // pairResponse es lo que recibe el agente tras un pairing exitoso.
  90. type pairResponse struct {
  91. Slug string `json:"slug"`
  92. Token string `json:"token"`
  93. ServerFP string `json:"server_fp"`
  94. }
  95. // handleAgentPair (POST /api/agents/pair): valida el pairing token y crea un
  96. // agente nuevo. No requiere sesión (el pairing token es la auth). Rate limited.
  97. //
  98. // #367: además del pairing token de admin (crea o ROTA el agente del slug),
  99. // acepta el token de alta de red del autoenroll cuando AGENT_AUTOENROLL=1.
  100. // El token de red SOLO puede crear agentes para slugs que no existan: si el
  101. // slug ya tiene token, responde 409 slug_taken (un router descubierto nunca
  102. // puede suplantar ni rotar el agente de otro).
  103. func (s *server) handleAgentPair(w http.ResponseWriter, r *http.Request) {
  104. ip := auth.ClientIP(r)
  105. if ok, _ := s.ingestLimit.allow(ip); !ok {
  106. writeError(w, http.StatusTooManyRequests, "rate_limited")
  107. return
  108. }
  109. var body pairRequest
  110. if st := readJSONBody(w, r, &body); st != 0 {
  111. writeBodyError(w, st, "invalid_body",
  112. `Se esperaba { "pairing_token": "...", "slug": "<equipo>" }`)
  113. return
  114. }
  115. if !agentSlugRe.MatchString(body.Slug) || body.PairingToken == "" {
  116. writeError(w, http.StatusBadRequest, "invalid_body",
  117. `Se esperaba { "pairing_token": "...", "slug": "<equipo>" }`)
  118. return
  119. }
  120. // Validar el token: primero el pairing token de admin (semántica
  121. // completa: crear o rotar), después el token de red del autoenroll
  122. // (solo creación de slugs nuevos).
  123. stored, err := s.getPairingToken()
  124. if err != nil {
  125. writeError(w, http.StatusInternalServerError, "pairing_error")
  126. return
  127. }
  128. adminToken := stored != "" && subtle.ConstantTimeCompare([]byte(body.PairingToken), []byte(stored)) == 1
  129. // FORK: once plain HTTP is being retired, the admin pairing token - which
  130. // can create or rotate any agent - is not taken over it: pair over https,
  131. // where the agent proves the server's key first (pair/hello). Refusing
  132. // cannot un-send it, but keeps anything from relying on it.
  133. if adminToken && s.tlsMgr != nil && s.tlsMgr.Enabled() && s.tlsMgr.Mode() != tlsmode.Full && !auth.IsSecureRequest(r) {
  134. writeError(w, http.StatusForbidden, "use_https",
  135. "pair over https: this server no longer takes its pairing token over plain HTTP")
  136. return
  137. }
  138. if !adminToken {
  139. if !s.checkAutoenrollToken(body.PairingToken) {
  140. writeError(w, http.StatusUnauthorized, "invalid_pairing_token")
  141. return
  142. }
  143. var existing string
  144. _ = s.db.QueryRow(
  145. "SELECT COALESCE(value,'') FROM kv WHERE key = ?", agentTokenKey(body.Slug)).Scan(&existing)
  146. if existing != "" {
  147. writeError(w, http.StatusConflict, "slug_taken",
  148. "el slug ya tiene un agente; el autoenroll no puede rotarlo (renombra el equipo o usa el pairing token de admin)")
  149. return
  150. }
  151. }
  152. // Crear el agente (mismo flujo que POST /api/agents).
  153. token, err := newAgentToken()
  154. if err != nil {
  155. writeError(w, http.StatusInternalServerError, "token_error")
  156. return
  157. }
  158. if _, err := s.db.Exec(
  159. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
  160. agentTokenKey(body.Slug), hashAgentToken(token)); err != nil {
  161. writeError(w, http.StatusInternalServerError, "token_error")
  162. return
  163. }
  164. writeJSON(w, http.StatusCreated, pairResponse{
  165. Slug: body.Slug,
  166. Token: token,
  167. ServerFP: s.fingerprint(),
  168. })
  169. }
  170. // handleAgentPairHello (POST /api/agents/pair/hello): FORK. Proves to an
  171. // agent that the key this server serves is the real server's, so an agent
  172. // given a pairing token but no pin can learn the pin without trusting
  173. // whoever answers first. The reply is pairproof.MAC(pairing token, the
  174. // agent's nonce, our fingerprint); the agent checks it against the chain it
  175. // was shown (runtime.ProveServerKey). The pairing token itself is never sent
  176. // to us here, and the reply is useless to anyone who does not hold it.
  177. //
  178. // Only the admin pairing token proves anything. The autoenroll token is
  179. // handed out over UDP to whoever asks, so a MAC keyed with it would prove
  180. // nothing about who answered.
  181. func (s *server) handleAgentPairHello(w http.ResponseWriter, r *http.Request) {
  182. ip := auth.ClientIP(r)
  183. if ok, _ := s.ingestLimit.allow(ip); !ok {
  184. writeError(w, http.StatusTooManyRequests, "rate_limited")
  185. return
  186. }
  187. if r.TLS == nil {
  188. // Also the answer behind a TLS-terminating proxy: the key the agent
  189. // sees is the proxy's, which this server cannot vouch for.
  190. writeError(w, http.StatusBadRequest, "use_https",
  191. "the server's key can only be proven over a direct https connection to it; "+
  192. "behind a TLS-terminating proxy, give the agent NETPULSE_SERVER_FP instead")
  193. return
  194. }
  195. fp := s.fingerprint()
  196. if fp == "" {
  197. writeError(w, http.StatusConflict, "no_fingerprint",
  198. "this server has no key for agents to pin")
  199. return
  200. }
  201. var body struct {
  202. Nonce string `json:"nonce"`
  203. }
  204. if st := readJSONBody(w, r, &body); st != 0 {
  205. writeBodyError(w, st, "invalid_body", `expected { "nonce": "<hex>" }`)
  206. return
  207. }
  208. if b, err := hex.DecodeString(body.Nonce); err != nil || len(b) < 16 || len(b) > 64 {
  209. writeError(w, http.StatusBadRequest, "invalid_body", "nonce must be 16 to 64 random bytes in hex")
  210. return
  211. }
  212. tok, err := s.getPairingToken()
  213. if err != nil || tok == "" {
  214. writeError(w, http.StatusInternalServerError, "pairing_error")
  215. return
  216. }
  217. writeJSON(w, http.StatusOK, map[string]string{
  218. "server_fp": fp,
  219. "mac": pairproof.MAC(tok, body.Nonce, fp),
  220. })
  221. }
  222. // EnsurePairingToken es llamado desde main.go en el primer arranque on-box
  223. // para generar y loguear el pairing token.
  224. func EnsurePairingToken(database *db.DB) (string, error) {
  225. var existing string
  226. err := database.QueryRow("SELECT value FROM kv WHERE key = ?", pairingTokenKey).Scan(&existing)
  227. if err == nil && existing != "" {
  228. return existing, nil
  229. }
  230. tok, err := newPairingToken()
  231. if err != nil {
  232. return "", err
  233. }
  234. if _, err := database.Exec(
  235. "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
  236. pairingTokenKey, tok); err != nil {
  237. return "", err
  238. }
  239. return tok, nil
  240. }