Files
bryanpedini 99fa5de747 feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders
- feat(auth): add argon2id passwords, sessions, rate limiter, authorization and audit builders
- feat(cli): add check and audit commands
- feat(api): add api framework, login, page routes and account, user, delegation and audit handlers
- test(auth): cover passwords, sessions, rate limiter, authorization and audit builders
- test(api): cover the api framework, sessions, client origin, headers and cross-origin refusal
- test(api): cover account, user, delegation and audit handlers and the authorization matrix
- test(ui): cover login, logout, page routes and the page authorization matrix
2026-11-19 15:46:12 +01:00

299 lines
7.7 KiB
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"golang.org/x/crypto/argon2"
)
const (
argon2Memory = 64 * 1024
argon2Iterations = 3
argon2Parallelism = 2
argon2SaltBytes = 16
argon2KeyBytes = 32
maxConcurrentHashes = 4
phcMaxMemory = 1 << 20
phcMaxIterations = 64
phcMaxParallelism = 16
phcMinBytes = 8
phcMaxBytes = 64
sessionTokenBytes = 32
sessionCookieName = "coredns_webui_session"
sessionTouchInterval = time.Minute
minPasswordBytes = 12
maxPasswordBytes = 256
maxUserAgentRunes = 255
reservedUsername = "cli"
roleAdmin = "admin"
roleUser = "user"
)
const dummyPasswordHash = "$argon2id$v=19$m=65536,t=3,p=2$c2VjdXJpdHktZHVtbXktMQ$2v9Q3n6Pq0m0V4bJxv1q8kP0cQ8Zr5u3m2b0YQ8d9xE"
var usernamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
var hashSlots = make(chan struct{}, maxConcurrentHashes)
var (
errInvalidPasswordHash = errors.New("invalid password hash")
errNoSession = errors.New("no valid session")
)
type phcHash struct {
memory uint32
iterations uint32
parallelism uint8
salt []byte
key []byte
}
var dummyPHC = mustParsePHC(dummyPasswordHash)
func mustParsePHC(encoded string) phcHash {
h, err := parsePHC(encoded)
if err != nil {
panic(err)
}
return h
}
func argon2Key(password string, h phcHash) []byte {
hashSlots <- struct{}{}
defer func() { <-hashSlots }()
return argon2.IDKey([]byte(password), h.salt, h.iterations, h.memory, h.parallelism, uint32(len(h.key)))
}
func hashPassword(password string) (string, error) {
return hashPasswordWith(rand.Reader, password)
}
func hashPasswordWith(random io.Reader, password string) (string, error) {
h := phcHash{
memory: argon2Memory,
iterations: argon2Iterations,
parallelism: argon2Parallelism,
salt: make([]byte, argon2SaltBytes),
key: make([]byte, argon2KeyBytes),
}
if _, err := io.ReadFull(random, h.salt); err != nil {
return "", fmt.Errorf("password salt: %w", err)
}
h.key = argon2Key(password, h)
return encodePHC(h), nil
}
func encodePHC(h phcHash) string {
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, h.memory, h.iterations, h.parallelism,
base64.RawStdEncoding.EncodeToString(h.salt), base64.RawStdEncoding.EncodeToString(h.key))
}
func parsePHCParam(s, name string, max uint64) (uint64, error) {
v, ok := strings.CutPrefix(s, name+"=")
if !ok || v == "" || strings.Trim(v, "0123456789") != "" || (len(v) > 1 && v[0] == '0') {
return 0, errInvalidPasswordHash
}
n, err := strconv.ParseUint(v, 10, 32)
if err != nil || n == 0 || n > max {
return 0, errInvalidPasswordHash
}
return n, nil
}
func parsePHCBytes(s string) ([]byte, error) {
b, err := base64.RawStdEncoding.Strict().DecodeString(s)
if err != nil || len(b) < phcMinBytes || len(b) > phcMaxBytes {
return nil, errInvalidPasswordHash
}
return b, nil
}
func parsePHC(encoded string) (phcHash, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != "v="+strconv.Itoa(argon2.Version) {
return phcHash{}, errInvalidPasswordHash
}
params := strings.Split(parts[3], ",")
if len(params) != 3 {
return phcHash{}, errInvalidPasswordHash
}
m, err := parsePHCParam(params[0], "m", phcMaxMemory)
if err != nil {
return phcHash{}, err
}
t, err := parsePHCParam(params[1], "t", phcMaxIterations)
if err != nil {
return phcHash{}, err
}
p, err := parsePHCParam(params[2], "p", phcMaxParallelism)
if err != nil {
return phcHash{}, err
}
if m < 8*p {
return phcHash{}, errInvalidPasswordHash
}
salt, err := parsePHCBytes(parts[4])
if err != nil {
return phcHash{}, err
}
key, err := parsePHCBytes(parts[5])
if err != nil {
return phcHash{}, err
}
return phcHash{memory: uint32(m), iterations: uint32(t), parallelism: uint8(p), salt: salt, key: key}, nil
}
func verifyPassword(password, encoded string) bool {
h, err := parsePHC(encoded)
valid := err == nil
if !valid {
h = dummyPHC
}
key := argon2Key(password, h)
return subtle.ConstantTimeCompare(key, h.key) == 1 && valid
}
type passwordVerifier func(password, encoded string) bool
func verifyLogin(verify passwordVerifier, user *userRow, password string) bool {
encoded := dummyPasswordHash
active := user != nil && !user.DeletedAt.Valid
if active {
encoded = user.PasswordHash
}
match := verify(password, encoded)
return active && match
}
func validUsernameSyntax(username string) bool {
return usernamePattern.MatchString(username)
}
func checkUsername(username string) error {
if !validUsernameSyntax(username) {
return errors.New("username must be 1 to 64 characters of lowercase letters, digits, dots, underscores and hyphens, starting with a letter or digit")
}
if username == reservedUsername {
return errors.New("username is reserved")
}
return nil
}
func checkPasswordRules(password string) error {
if len(password) < minPasswordBytes || len(password) > maxPasswordBytes {
return fmt.Errorf("password must be %d to %d bytes", minPasswordBytes, maxPasswordBytes)
}
if !utf8.ValidString(password) {
return errors.New("password must be valid UTF-8")
}
for _, r := range password {
if unicode.IsControl(r) {
return errors.New("password must not contain control characters")
}
}
return nil
}
func validRole(role string) bool {
return role == roleAdmin || role == roleUser
}
func newSessionToken(random io.Reader) (string, []byte, error) {
raw := make([]byte, sessionTokenBytes)
if _, err := io.ReadFull(random, raw); err != nil {
return "", nil, fmt.Errorf("session token: %w", err)
}
token := base64.RawURLEncoding.EncodeToString(raw)
return token, sessionTokenHash(token), nil
}
func sessionTokenHash(token string) []byte {
sum := sha256.Sum256([]byte(token))
return sum[:]
}
func validSessionToken(token string) bool {
if len(token) != base64.RawURLEncoding.EncodedLen(sessionTokenBytes) {
return false
}
raw, err := base64.RawURLEncoding.Strict().DecodeString(token)
return err == nil && len(raw) == sessionTokenBytes
}
func sessionValid(s sessionRow, u userRow, now time.Time, idle, maxAge time.Duration) bool {
return !u.DeletedAt.Valid && now.Before(s.ExpiresAt) && now.Sub(s.CreatedAt) < maxAge && now.Sub(s.LastSeenAt) < idle
}
func sessionTouchDue(s sessionRow, now time.Time) bool {
return now.Sub(s.LastSeenAt) >= sessionTouchInterval
}
func newSessionRow(tokenHash []byte, userID int64, now time.Time, maxAge time.Duration, origin, userAgent string) sessionRow {
return sessionRow{
TokenHash: tokenHash,
UserID: userID,
CreatedAt: now,
LastSeenAt: now,
ExpiresAt: now.Add(maxAge),
Origin: origin,
UserAgent: printableText(userAgent, maxUserAgentRunes),
}
}
func sessionCookie(token string, secure bool) *http.Cookie {
return &http.Cookie{
Name: sessionCookieName,
Value: token,
Path: "/",
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteStrictMode,
}
}
func expiredSessionCookie(secure bool) *http.Cookie {
c := sessionCookie("", secure)
c.MaxAge = -1
return c
}
func requestSessionToken(r *http.Request) (string, bool) {
c, err := r.Cookie(sessionCookieName)
if err != nil || !validSessionToken(c.Value) {
return "", false
}
return c.Value, true
}
func printableText(s string, maxRunes int) string {
var b strings.Builder
n := 0
for i, r := range s {
if maxRunes >= 0 && n == maxRunes {
break
}
if (r == utf8.RuneError && !strings.HasPrefix(s[i:], "�")) || !unicode.IsPrint(r) {
r = ' '
}
b.WriteRune(r)
n++
}
return b.String()
}