fix: harden authentication flows

This commit is contained in:
2026-11-19 06:20:38 +00:00
parent 9c4dad9ae3
commit 16a325d5b8
9 changed files with 171 additions and 37 deletions
+3
View File
@@ -65,6 +65,9 @@ func (e *aesEncryption) Decrypt(dec string) (string, error) {
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize+gcm.Overhead() {
return "", fmt.Errorf("ciphertext is too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
+50 -9
View File
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"github.com/fossyy/filekeeper/app"
googleOauthHandler "github.com/fossyy/filekeeper/handler/auth/google"
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
"github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types"
@@ -13,6 +14,7 @@ import (
"github.com/redis/go-redis/v9"
"net/http"
"net/url"
"strings"
"time"
)
@@ -45,9 +47,16 @@ type OauthUser struct {
}
func GET(w http.ResponseWriter, r *http.Request) {
_, err := app.Server.Cache.GetCache(r.Context(), "CsrfTokens:"+r.URL.Query().Get("state"))
state := r.URL.Query().Get("state")
if state == "" {
http.Redirect(w, r, "/auth/signin?error=csrf_token_error", http.StatusFound)
return
}
secureStateCookie := session.IsHTTPS(r)
stateJSON, err := app.Server.Cache.GetCache(r.Context(), "CsrfTokens:"+state)
if err != nil {
if errors.Is(err, redis.Nil) {
http.SetCookie(w, &http.Cookie{Name: "oauth_state", Value: "", Path: "/auth/google/callback", MaxAge: -1, HttpOnly: true, Secure: r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https"), SameSite: http.SameSiteLaxMode})
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", "csrf_token_error"), http.StatusFound)
return
}
@@ -55,14 +64,28 @@ func GET(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
return
}
var csrf googleOauthHandler.CsrfToken
if err := json.Unmarshal([]byte(stateJSON), &csrf); err != nil {
http.Redirect(w, r, "/auth/signin?error=csrf_token_error", http.StatusFound)
return
}
if cookie, cookieErr := r.Cookie("oauth_state"); cookieErr != nil || cookie.Value != state {
http.Redirect(w, r, "/auth/signin?error=csrf_token_error", http.StatusFound)
return
}
if csrf.Token != state {
http.Redirect(w, r, "/auth/signin?error=csrf_token_error", http.StatusFound)
return
}
err = app.Server.Cache.DeleteCache(r.Context(), "CsrfTokens:"+r.URL.Query().Get("state"))
err = app.Server.Cache.DeleteCache(r.Context(), "CsrfTokens:"+state)
if err != nil {
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", "csrf_token_error"), http.StatusFound)
return
}
if err := r.URL.Query().Get("error"); err != "" {
http.SetCookie(w, &http.Cookie{Name: "oauth_state", Value: "", Path: "/auth/google/callback", MaxAge: -1, HttpOnly: true, Secure: secureStateCookie, SameSite: http.SameSiteLaxMode})
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", err), http.StatusFound)
return
}
@@ -75,10 +98,18 @@ func GET(w http.ResponseWriter, r *http.Request) {
"redirect_uri": {utils.Getenv("GOOGLE_CALLBACK")},
}
resp, err := http.Post("https://oauth2.googleapis.com/token", "application/x-www-form-urlencoded", bytes.NewBufferString(formData.Encode()))
tokenRequest, err := http.NewRequestWithContext(r.Context(), http.MethodPost, "https://oauth2.googleapis.com/token", bytes.NewBufferString(formData.Encode()))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error("Error:", err)
app.Server.Logger.Error("Error creating token request:", err)
return
}
tokenRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(tokenRequest)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error("Error requesting token:", err)
return
}
defer resp.Body.Close()
@@ -95,8 +126,10 @@ func GET(w http.ResponseWriter, r *http.Request) {
app.Server.Logger.Error("Error reading token response body:", err)
return
}
client := &http.Client{}
if oauthData.AccessToken == "" {
http.Error(w, "Invalid token response", http.StatusBadGateway)
return
}
req, err := http.NewRequestWithContext(r.Context(), "GET", "https://www.googleapis.com/oauth2/v1/userinfo?alt=json", nil)
if err != nil {
@@ -119,7 +152,6 @@ func GET(w http.ResponseWriter, r *http.Request) {
app.Server.Logger.Error("Error user info endpoint returned status: ", userInfoResp.Status)
return
}
var oauthUser OauthUser
if err := json.NewDecoder(userInfoResp.Body).Decode(&oauthUser); err != nil {
w.WriteHeader(http.StatusInternalServerError)
@@ -167,9 +199,10 @@ func GET(w http.ResponseWriter, r *http.Request) {
Authenticated: true,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
http.Redirect(w, r, fmt.Sprintf("/auth/signin?error=%s", "csrf_token_error"), http.StatusFound)
return
}
http.SetCookie(w, &http.Cookie{Name: "oauth_state", Value: "", Path: "/auth/google/callback", MaxAge: -1, HttpOnly: true, Secure: r.TLS != nil, SameSite: http.SameSiteLaxMode})
userAgent := r.Header.Get("User-Agent")
browserInfo, osInfo := utils.ParseUserAgent(userAgent)
@@ -193,7 +226,7 @@ func GET(w http.ResponseWriter, r *http.Request) {
}
cookie, err := r.Cookie("redirect")
if errors.Is(err, http.ErrNoCookie) {
if err != nil || !validRedirect(cookie.Value) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
@@ -201,8 +234,16 @@ func GET(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "redirect",
MaxAge: -1,
Path: "/",
HttpOnly: true,
Secure: session.IsHTTPS(r),
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
return
}
func validRedirect(value string) bool {
return strings.HasPrefix(value, "/") && !strings.HasPrefix(value, "//") && !strings.Contains(value, `\`)
}
+25 -3
View File
@@ -2,10 +2,11 @@ package googleOauthHandler
import (
"encoding/json"
"fmt"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/utils"
"net/http"
"net/url"
"time"
)
@@ -16,6 +17,10 @@ type CsrfToken struct {
func GET(w http.ResponseWriter, r *http.Request) {
token, err := utils.GenerateCSRFToken()
if err != nil {
http.Error(w, "Unable to start Google sign-in", http.StatusInternalServerError)
return
}
csrfToken := CsrfToken{
Token: token,
CreateTime: time.Now(),
@@ -25,12 +30,29 @@ func GET(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
return
}
app.Server.Cache.SetCache(r.Context(), "CsrfTokens:"+token, newCsrfToken, time.Minute*15)
err = app.Server.Cache.SetCache(r.Context(), "CsrfTokens:"+token, newCsrfToken, time.Minute*15)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
return
}
http.Redirect(w, r, fmt.Sprintf("https://accounts.google.com/o/oauth2/auth?scope=email profile&response_type=code&access_type=offline&state=%s&redirect_uri=%s&client_id=%s", token, utils.Getenv("GOOGLE_CALLBACK"), utils.Getenv("GOOGLE_CLIENT_ID")), http.StatusFound)
http.SetCookie(w, &http.Cookie{
Name: "oauth_state", Value: token, Path: "/auth/google/callback", MaxAge: 900,
HttpOnly: true, Secure: session.IsHTTPS(r), SameSite: http.SameSiteLaxMode,
})
oauthURL, err := url.Parse("https://accounts.google.com/o/oauth2/auth")
if err != nil {
http.Error(w, "Unable to start Google sign-in", http.StatusInternalServerError)
return
}
oauthURL.RawQuery = url.Values{
"scope": {"email profile"},
"response_type": {"code"},
"access_type": {"offline"},
"state": {token},
"redirect_uri": {utils.Getenv("GOOGLE_CALLBACK")},
"client_id": {utils.Getenv("GOOGLE_CLIENT_ID")},
}.Encode()
http.Redirect(w, r, oauthURL.String(), http.StatusFound)
return
}
+19
View File
@@ -55,6 +55,11 @@ func POST(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Unauthorized Action", http.StatusUnauthorized)
return
}
if err != nil {
http.Error(w, "Unable to load setup", http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
return
}
var unregisteredUser UnregisteredUser
err = json.Unmarshal([]byte(cache), &unregisteredUser)
@@ -63,6 +68,10 @@ func POST(w http.ResponseWriter, r *http.Request) {
app.Server.Logger.Error(err.Error())
return
}
if unregisteredUser.Email == "" || unregisteredUser.Code != code {
http.Error(w, "Unauthorized Action", http.StatusUnauthorized)
return
}
err = r.ParseForm()
if err != nil {
@@ -89,6 +98,11 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
hashedPassword, err := utils.HashPassword(password)
if err != nil {
http.Error(w, "Unable to create account", http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
return
}
userID := uuid.New()
newUser := models.User{
UserID: userID,
@@ -112,6 +126,11 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
return
}
if err := app.Server.Cache.DeleteCache(r.Context(), "GoogleSetup:"+code); err != nil {
http.Error(w, "Unable to complete setup", http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
return
}
storeSession, err := session.Create(types.User{
UserID: userID,
+10 -2
View File
@@ -1,7 +1,6 @@
package signinHandler
import (
"errors"
"github.com/a-h/templ"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/session"
@@ -9,6 +8,7 @@ import (
"github.com/fossyy/filekeeper/utils"
"github.com/fossyy/filekeeper/view/client/auth/signin"
"net/http"
"strings"
)
var errorMessages = make(map[string]string)
@@ -141,13 +141,17 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
cookie, err := r.Cookie("redirect")
if errors.Is(err, http.ErrNoCookie) {
if err != nil || !validRedirect(cookie.Value) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
http.SetCookie(w, &http.Cookie{
Name: "redirect",
MaxAge: -1,
Path: "/",
HttpOnly: true,
Secure: session.IsHTTPS(r),
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
return
@@ -164,3 +168,7 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
return
}
func validRedirect(value string) bool {
return strings.HasPrefix(value, "/") && !strings.HasPrefix(value, "//") && !strings.Contains(value, `\`)
}
+37 -4
View File
@@ -1,7 +1,7 @@
package totpHandler
import (
"errors"
"crypto/subtle"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/session"
"github.com/fossyy/filekeeper/types"
@@ -9,6 +9,7 @@ import (
"github.com/fossyy/filekeeper/view/client/totp"
"github.com/xlzd/gotp"
"net/http"
"strings"
"time"
)
@@ -38,15 +39,30 @@ func POST(w http.ResponseWriter, r *http.Request) {
return
}
code := r.Form.Get("code")
if len(code) != 6 || !isNumericCode(code) {
http.Error(w, "Invalid code", http.StatusBadRequest)
return
}
_, user, key := session.GetSession(r)
if key == "" || user.Totp == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
decryptedSecret, err := app.Server.Encryption.Decrypt(user.Totp)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
http.Error(w, "Unable to verify code", http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
return
}
totp := gotp.NewDefaultTOTP(decryptedSecret)
if totp.Verify(code, time.Now().Unix()) {
validCode := false
for _, timestamp := range []int64{time.Now().Unix() - 30, time.Now().Unix(), time.Now().Unix() + 30} {
if subtle.ConstantTimeCompare([]byte(totp.At(timestamp)), []byte(code)) == 1 {
validCode = true
}
}
if validCode {
storeSession := session.Get(key)
err := storeSession.Change(types.User{
UserID: user.UserID,
@@ -82,13 +98,17 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
cookie, err := r.Cookie("redirect")
if errors.Is(err, http.ErrNoCookie) {
if err != nil || !validRedirect(cookie.Value) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
http.SetCookie(w, &http.Cookie{
Name: "redirect",
MaxAge: -1,
Path: "/",
HttpOnly: true,
Secure: session.IsHTTPS(r),
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, cookie.Value, http.StatusSeeOther)
return
@@ -105,3 +125,16 @@ func POST(w http.ResponseWriter, r *http.Request) {
}
}
func validRedirect(value string) bool {
return strings.HasPrefix(value, "/") && !strings.HasPrefix(value, "//") && !strings.Contains(value, `\`)
}
func isNumericCode(value string) bool {
for _, digit := range value {
if digit < '0' || digit > '9' {
return false
}
}
return true
}
+1 -1
View File
@@ -11,7 +11,7 @@ import (
func GET(w http.ResponseWriter, r *http.Request) {
userSession := r.Context().Value("user").(types.User)
cookie, err := r.Cookie("Session")
cookie, err := r.Cookie(utils.Getenv("SESSION_NAME"))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
+10 -1
View File
@@ -12,6 +12,15 @@ func DELETE(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
mySession := r.Context().Value("user").(types.User)
mySessionID := r.Context().Value("sessionID").(string)
otherSessionInfo, err := session.GetSessionInfo(mySession.Email, id)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
if otherSessionInfo.SessionID != id {
http.Error(w, "Session not found", http.StatusNotFound)
return
}
if id == mySessionID {
w.Header().Set("HX-Redirect", "/logout")
@@ -20,7 +29,7 @@ func DELETE(w http.ResponseWriter, r *http.Request) {
}
otherSession := session.Get(id)
err := session.RemoveSessionInfo(mySession.Email, otherSession.ID)
err = session.RemoveSessionInfo(mySession.Email, otherSession.ID)
if err != nil {
if errors.Is(err, session.ErrorSessionNotFound) {
w.WriteHeader(http.StatusUnauthorized)
+10 -11
View File
@@ -82,7 +82,10 @@ func (s *Session) Delete() error {
}
func (s *Session) Save(r *http.Request, w http.ResponseWriter) {
maxAge, _ := strconv.Atoi(utils.Getenv("SESSION_MAX_AGE"))
maxAge, err := strconv.Atoi(utils.Getenv("SESSION_MAX_AGE"))
if err != nil {
maxAge = 0
}
http.SetCookie(w, &http.Cookie{
Name: utils.Getenv("SESSION_NAME"),
Value: s.ID,
@@ -137,21 +140,16 @@ func RemoveSessionInfo(email string, id string) error {
}
func RemoveAllSessions(email string) error {
pattern := "UserSessionInfo:" + email + ":*"
keys, err := app.Server.Cache.GetKeys(context.Background(), pattern)
sessions, err := GetSessions(email)
if err != nil {
return err
}
for _, key := range keys {
parts := strings.Split(key, ":")
sessionID := parts[2]
err = app.Server.Cache.DeleteCache(context.Background(), "Session:"+sessionID)
for _, sessionInfo := range sessions {
err = app.Server.Cache.DeleteCache(context.Background(), "Session:"+sessionInfo.SessionID)
if err != nil {
return err
}
err = app.Server.Cache.DeleteCache(context.Background(), key)
err = app.Server.Cache.DeleteCache(context.Background(), "UserSessionInfo:"+email+":"+sessionInfo.SessionID)
if err != nil {
return err
}
@@ -181,7 +179,8 @@ func GetSessionInfo(email string, id string) (*SessionInfo, error) {
}
func GetSession(r *http.Request) (UserStatus, types.User, string) {
cookie, err := r.Cookie("Session")
cookieName := utils.Getenv("SESSION_NAME")
cookie, err := r.Cookie(cookieName)
if err != nil {
return Unauthorized, types.User{}, ""
}