Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

sha256 hash API keys in the users table. Closes #3081.

Kailash Nadhc3bdea510d0d
diff --git a/cmd/init.go b/cmd/init.go
index 00e6d67a..044ac0f9 100644
--- a/cmd/init.go
+++ b/cmd/init.go
@@ -1169,7 +1169,7 @@ func initAuth(co *core.Core, db *sql.DB, ko *koanf.Koanf) (bool, *auth.Auth) {
if len(username) > 2 && len(password) > 6 {
u := auth.User{
Username: username,
- Password: null.String{Valid: true, String: password},
+ Password: null.String{Valid: true, String: auth.HashAPIToken(password)},
PasswordLogin: true,
HasPassword: true,
Status: auth.UserStatusEnabled,
diff --git a/cmd/install.go b/cmd/install.go
index f5449a1a..89338858 100644
--- a/cmd/install.go
+++ b/cmd/install.go
@@ -342,7 +342,7 @@ func installUser(username, password, apiUsername string, q *models.Queries) {
var (
email = null.String{String: apiUsername + "@api", Valid: true}
- password = null.String{String: tk, Valid: true}
+ password = null.String{String: auth.HashAPIToken(tk), Valid: true}
)
if _, err := q.CreateUser.Exec(apiUsername, false, password, email, apiUsername, auth.UserTypeAPI, role.ID, nil, auth.UserStatusEnabled); err != nil {
diff --git a/cmd/users.go b/cmd/users.go
index b75f7ebc..4796d3e5 100644
--- a/cmd/users.go
+++ b/cmd/users.go
@@ -131,11 +131,7 @@ func (a *App) UpdateUser(c echo.Context) error {
}
// Validate password if password login is enabled.
- if u.PasswordLogin && u.Password.String != "" {
- if !strHasLen(u.Password.String, 8, stdInputMaxLen) {
- return echo.NewHTTPError(http.StatusBadRequest, a.i18n.Ts("globals.messages.invalidFields", "name", "password"))
- }
-
+ if u.PasswordLogin {
if u.Password.String != "" {
// If a password is sent, validate it before updating in the DB. If it's not set, leave the password in the DB untouched.
if !strHasLen(u.Password.String, 8, stdInputMaxLen) {
diff --git a/i18n/it.json b/i18n/it.json
index dc88ee61..8dc36f06 100644
--- a/i18n/it.json
+++ b/i18n/it.json
@@ -590,11 +590,7 @@
"settings.smtp.name": "SMTP",
"settings.smtp.retries": "Tentativi",
"settings.smtp.retriesHelp": "Numero di tentativi in caso di errore invio messaggio.",
-<<<<<<< HEAD
"settings.smtp.retryDelay": "Ritardo di nuovo tentativo",
-=======
- "settings.smtp.retryDelay": "Ritardo di tentativo",
->>>>>>> 8b4743b4 (Auto-translate new i18n language strings.)
"settings.smtp.retryDelayHelp": "Tempo di attesa prima di riprovare dopo un errore (s per secondi, m per minuti). 0s disabilita il ritardo.",
"settings.smtp.sendTest": "Invia email",
"settings.smtp.setCustomHeaders": "Definisci intestazioni personalizzate",
diff --git a/internal/auth/auth.go b/internal/auth/auth.go
index c5410db5..87db1a8a 100644
--- a/internal/auth/auth.go
+++ b/internal/auth/auth.go
@@ -2,9 +2,11 @@ package auth
import (
"context"
+ "crypto/sha256"
"crypto/subtle"
"database/sql"
"encoding/base64"
+ "encoding/hex"
"errors"
"fmt"
"log"
@@ -138,7 +140,7 @@ func (o *Auth) GetAPIToken(user string, token string) (User, bool) {
t, ok := o.apiUsers[user]
o.RUnlock()
- if !ok || subtle.ConstantTimeCompare([]byte(t.Password.String), []byte(token)) != 1 {
+ if !ok || subtle.ConstantTimeCompare([]byte(t.Password.String), []byte(HashAPIToken(token))) != 1 {
return User{}, false
}
@@ -392,6 +394,12 @@ func GetSessionID(c echo.Context) string {
return sess.ID()
}
+// HashAPIToken returns the SHA-256 hex digest of an API token.
+func HashAPIToken(token string) string {
+ sum := sha256.Sum256([]byte(token))
+ return hex.EncodeToString(sum[:])
+}
+
// validateSession checks if the cookie session is valid (in the DB) and returns the session and user details.
func (o *Auth) validateSession(c echo.Context) (*simplesessions.Session, User, error) {
// Cookie session.
diff --git a/internal/auth/models.go b/internal/auth/models.go
index bbd9d0aa..9b8f7b46 100644
--- a/internal/auth/models.go
+++ b/internal/auth/models.go
@@ -87,7 +87,7 @@ type User struct {
Username string `db:"username" json:"username"`
- // For API users, this is the plaintext API token.
+ // For API users, this stores the SHA-256 token hash.
Password null.String `db:"password" json:"password,omitempty"`
PasswordLogin bool `db:"password_login" json:"password_login"`
diff --git a/internal/core/users.go b/internal/core/users.go
index 800180a0..125bc301 100644
--- a/internal/core/users.go
+++ b/internal/core/users.go
@@ -42,23 +42,29 @@ func (c *Core) GetUser(id int, username, email string) (auth.User, error) {
// CreateUser creates a new user.
func (c *Core) CreateUser(u auth.User) (auth.User, error) {
- var id int
+ var (
+ apiToken string
+ dbPassword = u.Password
+ )
// If it's an API user, generate a random token for password
// and set the e-mail to default.
if u.Type == auth.UserTypeAPI {
- // Generate a random admin password.
- tk, err := utils.GenerateRandomString(32)
+ // Generate a random API token.
+ tk, err := utils.GenerateRandomString(48)
if err != nil {
return auth.User{}, err
}
+ apiToken = tk
u.Email = null.String{String: u.Username + "@api", Valid: true}
u.PasswordLogin = false
u.Password = null.String{String: tk, Valid: true}
+ dbPassword = null.String{String: auth.HashAPIToken(tk), Valid: true}
}
- if err := c.q.CreateUser.Get(&id, u.Username, u.PasswordLogin, u.Password, u.Email, u.Name, u.Type, u.UserRoleID, u.ListRoleID, u.Status); err != nil {
+ var id int
+ if err := c.q.CreateUser.Get(&id, u.Username, u.PasswordLogin, dbPassword, u.Email, u.Name, u.Type, u.UserRoleID, u.ListRoleID, u.Status); err != nil {
return auth.User{}, echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("globals.messages.errorCreating", "name", "{globals.terms.user}", "error", pqErrMsg(err)))
}
@@ -70,6 +76,10 @@ func (c *Core) CreateUser(u auth.User) (auth.User, error) {
}
out, err := c.GetUser(id, "", "")
+ if u.Type == auth.UserTypeAPI {
+ out.Password = null.String{String: apiToken, Valid: true}
+ }
+
return out, err
}
diff --git a/internal/migrations/v6.2.0.go b/internal/migrations/v6.2.0.go
index 7c07a399..c803c8d6 100644
--- a/internal/migrations/v6.2.0.go
+++ b/internal/migrations/v6.2.0.go
@@ -62,5 +62,18 @@ func V6_2_0(db *sqlx.DB, fs stuffbin.FileSystem, ko *koanf.Koanf, lo *log.Logger
return err
}
+ // Hash existing API tokens. This is idempotent by skipping values that
+ // already look like lowercase SHA-256 hex digests.
+ if _, err := db.Exec(`
+ UPDATE users
+ SET password = ENCODE(DIGEST(password, 'sha256'), 'hex')
+ WHERE type = 'api'
+ AND password IS NOT NULL
+ AND password != ''
+ AND password !~ '^[a-f0-9]{64}$';
+ `); err != nil {
+ return err
+ }
+
return nil
}
diff --git a/queries/users.sql b/queries/users.sql
index f2c9e0c2..105cc131 100644
--- a/queries/users.sql
+++ b/queries/users.sql
@@ -26,7 +26,13 @@ WITH u AS (
UPDATE users SET
username=(CASE WHEN $2 != '' THEN $2 ELSE username END),
password_login=$3,
- password=(CASE WHEN $3 = TRUE THEN (CASE WHEN $4 != '' THEN CRYPT($4, GEN_SALT('bf')) ELSE password END) ELSE NULL END),
+ password=(
+ CASE
+ WHEN users.type = 'api' AND ($7 = '' OR $7 = 'api') THEN password
+ WHEN $3 = TRUE THEN (CASE WHEN $4 != '' THEN CRYPT($4, GEN_SALT('bf')) ELSE password END)
+ ELSE NULL
+ END
+ ),
email=(CASE WHEN $5 != '' THEN $5 ELSE email END),
name=(CASE WHEN $6 != '' THEN $6 ELSE name END),
type=(CASE WHEN $7 != '' THEN $7::user_type ELSE type END),