auth.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. // Package auth — autenticación multiusuario (paridad con server/src/auth.js):
  2. // - Cookie `session` = `id.hmac` (UUID v4 . hex(HMAC-SHA256)), httpOnly,
  3. // SameSite=Lax, 30 días; Secure según COOKIE_SECURE / X-Forwarded-Proto.
  4. // - Verificación: split por el ÚLTIMO punto, comparación timing-safe.
  5. // - Secret HMAC: SESSION_SECRET o autogenerado persistido en kv.
  6. // - Sesiones en SQLite (30 d), rotación tras login.
  7. // - Rate-limit persistente (login_attempts): bloqueo 5 min armado cuando
  8. // attempts previos >= 4 (5º fallo), 429 con retryAfterSec.
  9. // - bcrypt cost 10 (hashes bcryptjs $2a/$2b verificables con x/crypto).
  10. package auth
  11. import (
  12. "crypto/hmac"
  13. "crypto/rand"
  14. "crypto/sha256"
  15. "database/sql"
  16. "encoding/hex"
  17. "fmt"
  18. "log"
  19. "net"
  20. "net/http"
  21. "regexp"
  22. "strings"
  23. "golang.org/x/crypto/bcrypt"
  24. "github.com/gnacho/netpulse/server-go/internal/config"
  25. "github.com/gnacho/netpulse/server-go/internal/db"
  26. )
  27. const (
  28. // SessionCookie es el nombre de la cookie de sesión.
  29. SessionCookie = "session"
  30. // SecureSessionCookie is the session cookie's name when it is Secure.
  31. // FORK: cookies are shared by every port and scheme of a host, so a
  32. // Secure "session" set over HTTPS could not be replaced by a login over
  33. // plain HTTP, and was not sent there - signing in over plain HTTP looped
  34. // while both were in use. Under its own name each keeps its own cookie.
  35. // The __Host- prefix makes browsers insist it is Secure, host-only and
  36. // for Path=/.
  37. SecureSessionCookie = "__Host-session"
  38. // SessionTTLMS = 30 días en ms (Max-Age=2592000).
  39. SessionTTLMS = 30 * 24 * 60 * 60 * 1000
  40. // LockMS = 5 minutos en ms.
  41. LockMS = 5 * 60 * 1000
  42. )
  43. // dummyPasswordHash se compara contra la password cuando el usuario no
  44. // existe, para igualar el timing con el camino de usuario válido y no
  45. // filtrar existencia de usuarios (issue #209).
  46. const dummyPasswordHash = "$2a$10$JeMmUvg2.LaUqM9Ir68TBegs4ll8r8KqG6x2f0.wA5f7BUBjtW/yq"
  47. // ---------------------------------------------------------------------------
  48. // Usuarios
  49. // ---------------------------------------------------------------------------
  50. // User fila pública de users (sin pass_hash).
  51. type User struct {
  52. ID int64
  53. Username string
  54. Role string
  55. }
  56. // CountUsers devuelve el número de filas de users. Lo usa el bootstrap
  57. // on-box (Fase 9 R4) para decidir si toca generar la contraseña inicial.
  58. func CountUsers(d *db.DB) (int, error) {
  59. var count int
  60. err := d.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
  61. return count, err
  62. }
  63. // EnsureUsers crea el admin inicial (AUTH_USER/AUTH_PASS) si users está vacía.
  64. func EnsureUsers(d *db.DB, cfg *config.Config) error {
  65. count, err := CountUsers(d)
  66. if err != nil {
  67. return err
  68. }
  69. if count > 0 {
  70. return nil
  71. }
  72. hash, err := bcrypt.GenerateFromPassword([]byte(cfg.AuthPass), 10)
  73. if err != nil {
  74. return err
  75. }
  76. if _, err := d.Exec(
  77. "INSERT INTO users (username, pass_hash, role, created_at) VALUES (?, ?, 'admin', ?)",
  78. cfg.AuthUser, string(hash), db.NowMS(),
  79. ); err != nil {
  80. return err
  81. }
  82. log.Printf("[netpulse] usuario admin inicial creado: %s", cfg.AuthUser)
  83. return nil
  84. }
  85. type userRow struct {
  86. ID int64
  87. Username string
  88. PassHash string
  89. Role string
  90. }
  91. // GetUserByName devuelve la fila de login (con pass_hash) o nil.
  92. func GetUserByName(d *db.DB, username string) *userRow {
  93. var u userRow
  94. err := d.QueryRow("SELECT id, username, pass_hash, role FROM users WHERE username = ?", username).
  95. Scan(&u.ID, &u.Username, &u.PassHash, &u.Role)
  96. if err != nil {
  97. return nil
  98. }
  99. return &u
  100. }
  101. // GetUserByID devuelve {id, username, role} o nil.
  102. func GetUserByID(d *db.DB, id int64) *User {
  103. var u User
  104. err := d.QueryRow("SELECT id, username, role FROM users WHERE id = ?", id).
  105. Scan(&u.ID, &u.Username, &u.Role)
  106. if err != nil {
  107. return nil
  108. }
  109. return &u
  110. }
  111. // CheckPassword verifica bcrypt (cost 10; hashes bcryptjs $2a/$2b portables).
  112. func CheckPassword(password, hash string) bool {
  113. return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
  114. }
  115. // HashPassword genera un hash bcrypt cost 10.
  116. func HashPassword(password string) (string, error) {
  117. h, err := bcrypt.GenerateFromPassword([]byte(password), 10)
  118. return string(h), err
  119. }
  120. // ---------------------------------------------------------------------------
  121. // Secret HMAC
  122. // ---------------------------------------------------------------------------
  123. // EnsureSessionSecret: SESSION_SECRET del env si existe; si no, kv
  124. // `session_secret`; si no existe, se genera (64 chars hex) y se persiste.
  125. func EnsureSessionSecret(d *db.DB, cfg *config.Config) (string, error) {
  126. if cfg.SessionSecret != "" {
  127. return cfg.SessionSecret, nil
  128. }
  129. var value string
  130. err := d.QueryRow("SELECT value FROM kv WHERE key = 'session_secret'").Scan(&value)
  131. if err == nil && value != "" {
  132. return value, nil
  133. }
  134. buf := make([]byte, 32)
  135. if _, err := rand.Read(buf); err != nil {
  136. return "", err
  137. }
  138. secret := hex.EncodeToString(buf)
  139. if _, err := d.Exec(
  140. "INSERT INTO kv (key, value) VALUES ('session_secret', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
  141. secret,
  142. ); err != nil {
  143. return "", err
  144. }
  145. return secret, nil
  146. }
  147. // ---------------------------------------------------------------------------
  148. // Cookie id.hmac
  149. // ---------------------------------------------------------------------------
  150. func hmacHex(secret, id string) string {
  151. m := hmac.New(sha256.New, []byte(secret))
  152. m.Write([]byte(id))
  153. return hex.EncodeToString(m.Sum(nil))
  154. }
  155. // SignSessionID devuelve `${id}.${hmac}`.
  156. func SignSessionID(secret, id string) string {
  157. return id + "." + hmacHex(secret, id)
  158. }
  159. // VerifySessionCookie valida `id.hmac`: split por el ÚLTIMO punto y
  160. // comparación timing-safe. Devuelve el id o "".
  161. func VerifySessionCookie(secret, value string) string {
  162. if value == "" {
  163. return ""
  164. }
  165. dot := strings.LastIndex(value, ".")
  166. if dot <= 0 {
  167. return ""
  168. }
  169. id := value[:dot]
  170. sig := value[dot+1:]
  171. expected := hmacHex(secret, id)
  172. // hmac.Equal es constant-time para entradas de la misma longitud
  173. // (paridad con safeEqual de auth.js:88-92).
  174. if !hmac.Equal([]byte(sig), []byte(expected)) {
  175. return ""
  176. }
  177. return id
  178. }
  179. // cookieRe replica /(?:^|;\s*)session=([^;]+)/ (primera ocurrencia).
  180. var cookieRe = regexp.MustCompile(`(?:^|;\s*)session=([^;]+)`)
  181. func sessionCookieValue(r *http.Request) string {
  182. m := cookieRe.FindStringSubmatch(r.Header.Get("Cookie"))
  183. if m == nil {
  184. return ""
  185. }
  186. return m[1]
  187. }
  188. // FORK: secureCookieRe finds the Secure session cookie (SecureSessionCookie).
  189. var secureCookieRe = regexp.MustCompile(`(?:^|;\s*)__Host-session=([^;]+)`)
  190. // sessionCookieValues is every session cookie the request carries, the
  191. // Secure one first. Browsers only send that one over HTTPS.
  192. func sessionCookieValues(r *http.Request) []string {
  193. var out []string
  194. if m := secureCookieRe.FindStringSubmatch(r.Header.Get("Cookie")); m != nil {
  195. out = append(out, m[1])
  196. }
  197. if v := sessionCookieValue(r); v != "" {
  198. out = append(out, v)
  199. }
  200. return out
  201. }
  202. // validSessionID is the first of the request's session cookies that verifies
  203. // and names a live session, or "".
  204. func validSessionID(d *db.DB, secret string, r *http.Request) string {
  205. for _, v := range sessionCookieValues(r) {
  206. if id := VerifySessionCookie(secret, v); id != "" && GetSession(d, id) != nil {
  207. return id
  208. }
  209. }
  210. return ""
  211. }
  212. // IsSecureRequest: URL https, o primer X-Forwarded-Proto == "https" SOLO si
  213. // TRUST_PROXY (despliegue detrás de proxy con TLS terminado fuera). Sin
  214. // TRUST_PROXY, un cliente de la LAN no puede forzar la cookie Secure
  215. // (hallazgo #1 de la auditoría de seguridad).
  216. func IsSecureRequest(r *http.Request) bool {
  217. if r.TLS != nil || r.URL.Scheme == "https" {
  218. return true
  219. }
  220. if !trustProxy {
  221. return false
  222. }
  223. proto := r.Header.Get("X-Forwarded-Proto")
  224. if proto == "" {
  225. return false
  226. }
  227. first := strings.TrimSpace(strings.Split(proto, ",")[0])
  228. return first == "https"
  229. }
  230. // CookieSecureFlag: always→true, never→false, auto→IsSecureRequest.
  231. func CookieSecureFlag(cfg *config.Config, r *http.Request) bool {
  232. switch cfg.CookieSecure {
  233. case "always":
  234. return true
  235. case "never":
  236. return false
  237. default:
  238. return IsSecureRequest(r)
  239. }
  240. }
  241. // BuildSessionCookie compone el header Set-Cookie (literal de auth.js:119-129).
  242. func BuildSessionCookie(cfg *config.Config, r *http.Request, signedID string, maxAgeSec int64) string {
  243. name := SessionCookie
  244. if CookieSecureFlag(cfg, r) {
  245. name = SecureSessionCookie
  246. }
  247. parts := []string{
  248. fmt.Sprintf("%s=%s", name, signedID),
  249. "Path=/",
  250. "HttpOnly",
  251. "SameSite=Lax",
  252. fmt.Sprintf("Max-Age=%d", maxAgeSec),
  253. }
  254. if CookieSecureFlag(cfg, r) {
  255. parts = append(parts, "Secure")
  256. }
  257. return strings.Join(parts, "; ")
  258. }
  259. // ClearSessionCookie borra la cookie (literal, SIN Secure aunque sea HTTPS).
  260. const ClearSessionCookie = "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"
  261. // ClearSecureSessionCookie deletes the Secure session cookie. FORK: it can
  262. // only be deleted over HTTPS, and must carry Secure to be accepted.
  263. const ClearSecureSessionCookie = "__Host-session=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0"
  264. // ---------------------------------------------------------------------------
  265. // Sesiones en SQLite
  266. // ---------------------------------------------------------------------------
  267. // newUUIDv4 genera un UUID v4 canónico (8-4-4-4-12 hex) con crypto/rand.
  268. func newUUIDv4() string {
  269. var b [16]byte
  270. if _, err := rand.Read(b[:]); err != nil {
  271. panic(err)
  272. }
  273. b[6] = (b[6] & 0x0f) | 0x40 // versión 4
  274. b[8] = (b[8] & 0x3f) | 0x80 // variante RFC 4122
  275. return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
  276. }
  277. // CreateSession crea una sesión (UUID v4, TTL 30 d, ua truncado a 255).
  278. func CreateSession(d *db.DB, ua string, userID int64) string {
  279. id := newUUIDv4()
  280. now := db.NowMS()
  281. if len(ua) > 255 {
  282. ua = ua[:255]
  283. }
  284. _, _ = d.Exec(
  285. "INSERT INTO sessions (id, created_at, expires_at, ua, user_id) VALUES (?, ?, ?, ?, ?)",
  286. id, now, now+SessionTTLMS, ua, userID,
  287. )
  288. return id
  289. }
  290. // DestroySession borra una sesión por id.
  291. func DestroySession(d *db.DB, id string) {
  292. if id != "" {
  293. _, _ = d.Exec("DELETE FROM sessions WHERE id = ?", id)
  294. }
  295. }
  296. // DestroyUserSessions borra todas las sesiones de un usuario (re-login forzado).
  297. func DestroyUserSessions(d *db.DB, userID int64) {
  298. _, _ = d.Exec("DELETE FROM sessions WHERE user_id = ?", userID)
  299. }
  300. // Session es la fila viva de sessions.
  301. type Session struct {
  302. ID string
  303. ExpiresAt int64
  304. UserID sql.NullInt64
  305. }
  306. // GetSession devuelve la sesión si existe y no expiró (si expiró, la borra).
  307. func GetSession(d *db.DB, id string) *Session {
  308. if id == "" {
  309. return nil
  310. }
  311. var s Session
  312. err := d.QueryRow("SELECT id, expires_at, user_id FROM sessions WHERE id = ?", id).
  313. Scan(&s.ID, &s.ExpiresAt, &s.UserID)
  314. if err != nil {
  315. return nil
  316. }
  317. if s.ExpiresAt < db.NowMS() {
  318. DestroySession(d, id)
  319. return nil
  320. }
  321. return &s
  322. }
  323. // SessionUser es el resultado de sessionUserFromRequest.
  324. type SessionUser struct {
  325. SessionID string
  326. User *User
  327. }
  328. // SessionUserFromRequest: cookie válida + sesión en DB con user_id NO nulo +
  329. // usuario existente (una sesión legacy sin user_id NO autentica).
  330. func SessionUserFromRequest(d *db.DB, secret string, r *http.Request) *SessionUser {
  331. id := validSessionID(d, secret, r)
  332. sess := GetSession(d, id)
  333. if sess == nil || !sess.UserID.Valid {
  334. return nil
  335. }
  336. user := GetUserByID(d, sess.UserID.Int64)
  337. if user == nil {
  338. return nil
  339. }
  340. return &SessionUser{SessionID: id, User: user}
  341. }
  342. // SessionIDFromRequest devuelve el id de sesión válida (sin exigir user_id).
  343. func SessionIDFromRequest(d *db.DB, secret string, r *http.Request) string {
  344. return validSessionID(d, secret, r)
  345. }
  346. // ---------------------------------------------------------------------------
  347. // Rate-limit en SQLite (persiste tras reinicios)
  348. // ---------------------------------------------------------------------------
  349. // trustProxy es la configuración global del paquete: si es true, ClientIP
  350. // confía en X-Forwarded-For (despliegue detrás de un proxy/reverse); si es
  351. // false (defecto), usa la IP remota del socket y XFF se ignora — un cliente
  352. // de la LAN no puede falsear su IP para evadir el rate-limit de login o de
  353. // ingesta (auditoría de seguridad, hallazgo #1). Se fija una vez al arrancar
  354. // desde config (TRUST_PROXY).
  355. var trustProxy bool
  356. // SetTrustProxy fija si las cabeceras X-Forwarded-For/-Proto son confiables.
  357. func SetTrustProxy(on bool) { trustProxy = on }
  358. // TrustProxy devuelve el valor actual (útil en tests).
  359. func TrustProxy() bool { return trustProxy }
  360. // ClientIP: primer X-Forwarded-For (solo si TRUST_PROXY) o la IP remota.
  361. func ClientIP(r *http.Request) string {
  362. if trustProxy {
  363. if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
  364. if first := strings.TrimSpace(strings.Split(xff, ",")[0]); first != "" {
  365. return first
  366. }
  367. }
  368. }
  369. if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil && host != "" {
  370. return host
  371. }
  372. if r.RemoteAddr != "" {
  373. return r.RemoteAddr
  374. }
  375. return "unknown"
  376. }
  377. // LoginRateLimited: si la IP está bloqueada → retryAfterSec = ceil(rest/1000).
  378. func LoginRateLimited(d *db.DB, r *http.Request) (limited bool, retryAfterSec int64) {
  379. ip := ClientIP(r)
  380. var lockedUntil int64
  381. err := d.QueryRow("SELECT locked_until FROM login_attempts WHERE ip = ?", ip).Scan(&lockedUntil)
  382. if err != nil {
  383. return false, 0
  384. }
  385. remaining := lockedUntil - db.NowMS()
  386. if remaining > 0 {
  387. return true, (remaining + 999) / 1000
  388. }
  389. return false, 0
  390. }
  391. // RegisterLoginFail registra un fallo: bloquea 5 min cuando el valor ANTERIOR
  392. // de attempts >= 4 (el bloqueo se arma en el 5º fallo — UPSERT literal).
  393. // Decay (issue #211): si el bloqueo previo ya expiró (locked_until en el
  394. // pasado), la cuenta se resetea a 1 y el marcador se limpia — un fallo suelto
  395. // (o un typo) tras el lockout ya no lo rearma al instante, evitando el
  396. // lockout casi permanente por IP. Una ráfaga nueva de 5 fallos tras la
  397. // expiración vuelve a armar el bloqueo.
  398. func RegisterLoginFail(d *db.DB, r *http.Request) {
  399. ip := ClientIP(r)
  400. now := db.NowMS()
  401. _, _ = d.Exec(`
  402. INSERT INTO login_attempts (ip, attempts, locked_until)
  403. VALUES (?, 1, 0)
  404. ON CONFLICT(ip) DO UPDATE SET
  405. attempts = CASE
  406. WHEN locked_until > 0 AND locked_until <= ? THEN 1
  407. ELSE attempts + 1
  408. END,
  409. locked_until = CASE
  410. WHEN locked_until > 0 AND locked_until <= ? THEN 0
  411. WHEN attempts >= 4 THEN ?
  412. ELSE locked_until
  413. END
  414. `, ip, now, now, now+LockMS)
  415. }
  416. // LoginOk borra la fila de login_attempts de la IP.
  417. func LoginOk(d *db.DB, r *http.Request) {
  418. _, _ = d.Exec("DELETE FROM login_attempts WHERE ip = ?", ClientIP(r))
  419. }
  420. // ---------------------------------------------------------------------------
  421. // Login / logout
  422. // ---------------------------------------------------------------------------
  423. // LoginResult es el resultado de HandleLogin.
  424. type LoginResult struct {
  425. SessionID string
  426. User *User
  427. }
  428. // HandleLogin valida credenciales y crea sesión nueva (rotación: invalida la
  429. // sesión previa de la cookie si existía). Nil si credenciales inválidas.
  430. func HandleLogin(d *db.DB, secret string, r *http.Request, username, password string) *LoginResult {
  431. if username == "" || password == "" {
  432. return nil
  433. }
  434. u := GetUserByName(d, username)
  435. if u == nil {
  436. // Compare contra un hash conocido para igualar el timing con el
  437. // camino de usuario válido y no filtrar existencia de usuarios.
  438. _ = bcrypt.CompareHashAndPassword([]byte(dummyPasswordHash), []byte(password))
  439. return nil
  440. }
  441. if !CheckPassword(password, u.PassHash) {
  442. return nil
  443. }
  444. // Rotación de sesión
  445. if prevID := SessionIDFromRequest(d, secret, r); prevID != "" {
  446. DestroySession(d, prevID)
  447. }
  448. id := CreateSession(d, r.Header.Get("User-Agent"), u.ID)
  449. return &LoginResult{SessionID: id, User: &User{ID: u.ID, Username: u.Username, Role: u.Role}}
  450. }
  451. // HandleLogout destruye la sesión de la cookie (si existe y es válida).
  452. func HandleLogout(d *db.DB, secret string, r *http.Request) {
  453. // FORK: every session cookie the request carries - over HTTPS that can
  454. // be both the Secure one and a plain one from a sign-in over HTTP.
  455. for _, v := range sessionCookieValues(r) {
  456. if id := VerifySessionCookie(secret, v); id != "" {
  457. DestroySession(d, id)
  458. }
  459. }
  460. }