hibiscus/auth.go

106 lines
3.4 KiB
Go
Raw Normal View History

2024-03-15 18:34:24 +03:00
package main
import (
"crypto/sha256"
"crypto/subtle"
2024-03-20 16:18:23 +03:00
"fmt"
"log/slog"
2024-03-15 18:34:24 +03:00
"net/http"
2024-03-20 16:18:23 +03:00
"os"
"strings"
"time"
2024-03-15 18:34:24 +03:00
)
2024-03-20 16:18:23 +03:00
type failedLogin struct {
Username string
Password string
Timestamp time.Time
}
var failedLogins []failedLogin
// NoteLoginFail attempts to log and counteract bruteforce attacks.
2024-03-20 16:18:23 +03:00
func NoteLoginFail(username string, password string, r *http.Request) {
slog.Warn("failed auth", "username", username, "password", password, "address", r.RemoteAddr)
NotifyTelegram(fmt.Sprintf(TranslatableText("info.telegram.auth_fail")+":\nusername=%s\npassword=%s\nremote=%s", username, password, r.RemoteAddr))
2024-03-20 16:18:23 +03:00
attempt := failedLogin{username, password, time.Now()}
updatedLogins := []failedLogin{attempt}
for _, attempt := range failedLogins {
if 100 > time.Now().Sub(attempt.Timestamp).Abs().Seconds() {
updatedLogins = append(updatedLogins, attempt)
}
}
failedLogins = updatedLogins
// At least 3 failed attempts in last 100 seconds -> likely bruteforce
2024-03-28 11:05:23 +03:00
if len(failedLogins) >= 3 && Cfg.Scram {
2024-03-20 16:18:23 +03:00
Scram()
}
}
2024-03-18 19:33:57 +03:00
// BasicAuth is a middleware that handles authentication & authorization for the app.
// It uses BasicAuth because I doubt there is a need for something sophisticated in a small hobby project.
// Originally taken from Alex Edwards's https://www.alexedwards.net/blog/basic-authentication-in-go, MIT Licensed (13.03.2024).
2024-03-18 19:33:57 +03:00
func BasicAuth(next http.Handler) http.Handler {
2024-03-15 18:34:24 +03:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok {
// Calculate SHA-256 hashes for equal length in ConstantTimeCompare
usernameHash := sha256.Sum256([]byte(username))
passwordHash := sha256.Sum256([]byte(password))
2024-03-17 18:11:20 +03:00
expectedUsernameHash := sha256.Sum256([]byte(Cfg.Username))
expectedPasswordHash := sha256.Sum256([]byte(Cfg.Password))
2024-03-15 18:34:24 +03:00
usernameMatch := subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1
passwordMatch := subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1
if usernameMatch && passwordMatch {
next.ServeHTTP(w, r)
return
2024-03-20 16:18:23 +03:00
} else {
NoteLoginFail(username, password, r)
2024-03-15 18:34:24 +03:00
}
}
// Unauthorized, inform client that we have auth and return 401
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
})
}
2024-03-20 16:18:23 +03:00
// Scram shuts down the service, useful in case of suspected attack.
2024-03-20 16:18:23 +03:00
func Scram() {
slog.Warn("SCRAM triggered, shutting down")
NotifyTelegram(TranslatableText("info.telegram.scram"))
os.Exit(0)
2024-03-20 16:18:23 +03:00
}
// NotifyTelegram attempts to send a message to admin through Telegram.
2024-03-20 16:18:23 +03:00
func NotifyTelegram(msg string) {
if Cfg.TelegramChat == "" || Cfg.TelegramToken == "" {
2024-05-04 15:39:15 +03:00
slog.Debug("ignoring telegram request due to lack of credentials")
2024-03-20 16:18:23 +03:00
return
}
client := &http.Client{}
data := "chat_id=" + Cfg.TelegramChat + "&text=" + msg
if Cfg.TelegramTopic != "" {
data += "&message_thread_id=" + Cfg.TelegramTopic
}
req, err := http.NewRequest("POST", "https://api.telegram.org/bot"+Cfg.TelegramToken+"/sendMessage", strings.NewReader(data))
2024-03-20 16:18:23 +03:00
if err != nil {
slog.Error("failed telegram request", "error", err)
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
slog.Error("failed telegram request", "error", err)
return
}
if resp.StatusCode != 200 {
slog.Error("failed telegram request", "status", resp.Status)
}
}