2019-04-25 04:52:08 +07:00
package handlers
import (
2021-02-24 06:35:04 +07:00
"bytes"
2019-04-25 04:52:08 +07:00
"encoding/base64"
"fmt"
"net"
"net/url"
"strings"
2020-05-05 02:39:25 +07:00
"time"
2019-04-25 04:52:08 +07:00
2020-04-05 19:37:21 +07:00
"github.com/valyala/fasthttp"
2021-08-11 08:04:35 +07:00
"github.com/authelia/authelia/v4/internal/authentication"
"github.com/authelia/authelia/v4/internal/authorization"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/middlewares"
"github.com/authelia/authelia/v4/internal/session"
"github.com/authelia/authelia/v4/internal/utils"
2019-04-25 04:52:08 +07:00
)
2020-02-19 05:39:07 +07:00
func isURLUnderProtectedDomain ( url * url . URL , domain string ) bool {
return strings . HasSuffix ( url . Hostname ( ) , domain )
}
func isSchemeHTTPS ( url * url . URL ) bool {
return url . Scheme == "https"
}
2020-02-28 06:28:53 +07:00
func isSchemeWSS ( url * url . URL ) bool {
return url . Scheme == "wss"
}
2020-05-02 12:06:39 +07:00
// parseBasicAuth parses an HTTP Basic Authentication string.
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
2021-12-02 09:21:46 +07:00
func parseBasicAuth ( header [ ] byte , auth string ) ( username , password string , err error ) {
2019-04-25 04:52:08 +07:00
if ! strings . HasPrefix ( auth , authPrefix ) {
2021-02-24 06:35:04 +07:00
return "" , "" , fmt . Errorf ( "%s prefix not found in %s header" , strings . Trim ( authPrefix , " " ) , header )
2019-04-25 04:52:08 +07:00
}
2020-05-06 02:35:32 +07:00
2019-04-25 04:52:08 +07:00
c , err := base64 . StdEncoding . DecodeString ( auth [ len ( authPrefix ) : ] )
if err != nil {
return "" , "" , err
}
2020-05-06 02:35:32 +07:00
2019-04-25 04:52:08 +07:00
cs := string ( c )
s := strings . IndexByte ( cs , ':' )
2020-05-06 02:35:32 +07:00
2019-04-25 04:52:08 +07:00
if s < 0 {
2021-09-17 12:53:40 +07:00
return "" , "" , fmt . Errorf ( "format of %s header must be user:password" , header )
2019-04-25 04:52:08 +07:00
}
2020-05-06 02:35:32 +07:00
2019-04-25 04:52:08 +07:00
return cs [ : s ] , cs [ s + 1 : ] , nil
}
2020-05-02 12:06:39 +07:00
// isTargetURLAuthorized check whether the given user is authorized to access the resource.
2019-04-25 04:52:08 +07:00
func isTargetURLAuthorized ( authorizer * authorization . Authorizer , targetURL url . URL ,
2021-03-05 11:18:31 +07:00
username string , userGroups [ ] string , clientIP net . IP , method [ ] byte , authLevel authentication . Level ) authorizationMatching {
level := authorizer . GetRequiredLevel (
authorization . Subject {
Username : username ,
Groups : userGroups ,
IP : clientIP ,
} ,
authorization . NewObjectRaw ( & targetURL , method ) )
2019-04-25 04:52:08 +07:00
2020-05-06 04:27:38 +07:00
switch {
case level == authorization . Bypass :
2019-04-25 04:52:08 +07:00
return Authorized
2020-05-06 04:27:38 +07:00
case level == authorization . Denied && username != "" :
2019-04-25 04:52:08 +07:00
// If the user is not anonymous, it means that we went through
// all the rules related to that user and knowing who he is we can
2020-04-09 08:05:17 +07:00
// deduce the access is forbidden
2019-04-25 04:52:08 +07:00
// For anonymous users though, we cannot be sure that she
// could not be granted the rights to access the resource. Consequently
2022-01-31 12:25:15 +07:00
// for anonymous users we send Unauthorized instead of Forbidden.
2019-04-25 04:52:08 +07:00
return Forbidden
2020-05-06 04:27:38 +07:00
case level == authorization . OneFactor && authLevel >= authentication . OneFactor ,
level == authorization . TwoFactor && authLevel >= authentication . TwoFactor :
return Authorized
2019-04-25 04:52:08 +07:00
}
2020-05-06 02:35:32 +07:00
2019-04-25 04:52:08 +07:00
return NotAuthorized
}
// verifyBasicAuth verify that the provided username and password are correct and
2020-05-02 12:06:39 +07:00
// that the user is authorized to target the resource.
2021-12-02 09:21:46 +07:00
func verifyBasicAuth ( ctx * middlewares . AutheliaCtx , header , auth [ ] byte ) ( username , name string , groups , emails [ ] string , authLevel authentication . Level , err error ) {
2021-02-24 06:35:04 +07:00
username , password , err := parseBasicAuth ( header , string ( auth ) )
2019-04-25 04:52:08 +07:00
if err != nil {
2021-09-17 12:53:40 +07:00
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "unable to parse content of %s header: %s" , header , err )
2019-04-25 04:52:08 +07:00
}
authenticated , err := ctx . Providers . UserProvider . CheckUserPassword ( username , password )
if err != nil {
2021-12-02 17:28:16 +07:00
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "unable to check credentials extracted from %s header: %w" , header , err )
2019-04-25 04:52:08 +07:00
}
2020-05-02 12:06:39 +07:00
// If the user is not correctly authenticated, send a 401.
2019-04-25 04:52:08 +07:00
if ! authenticated {
2022-01-31 12:25:15 +07:00
// Request Basic Authentication otherwise.
2021-09-17 12:53:40 +07:00
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "user %s is not authenticated" , username )
2019-04-25 04:52:08 +07:00
}
details , err := ctx . Providers . UserProvider . GetDetails ( username )
if err != nil {
2021-09-17 12:53:40 +07:00
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "unable to retrieve details of user %s: %s" , username , err )
2019-04-25 04:52:08 +07:00
}
2020-10-26 18:38:08 +07:00
return username , details . DisplayName , details . Groups , details . Emails , authentication . OneFactor , nil
2019-04-25 04:52:08 +07:00
}
2020-10-26 18:38:08 +07:00
// setForwardedHeaders set the forwarded User, Groups, Name and Email headers.
func setForwardedHeaders ( headers * fasthttp . ResponseHeader , username , name string , groups , emails [ ] string ) {
2019-04-25 04:52:08 +07:00
if username != "" {
2021-12-02 09:21:46 +07:00
headers . SetBytesK ( headerRemoteUser , username )
headers . SetBytesK ( headerRemoteGroups , strings . Join ( groups , "," ) )
headers . SetBytesK ( headerRemoteName , name )
2020-11-16 18:22:16 +07:00
if emails != nil {
2021-12-02 09:21:46 +07:00
headers . SetBytesK ( headerRemoteEmail , emails [ 0 ] )
2020-11-16 18:22:16 +07:00
} else {
2021-12-02 09:21:46 +07:00
headers . SetBytesK ( headerRemoteEmail , "" )
2020-11-16 18:22:16 +07:00
}
2019-04-25 04:52:08 +07:00
}
}
2022-07-08 09:32:43 +07:00
func isSessionInactiveTooLong ( ctx * middlewares . AutheliaCtx , userSession * session . UserSession , isUserAnonymous bool ) ( isInactiveTooLong bool ) {
if userSession . KeepMeLoggedIn || isUserAnonymous || int64 ( ctx . Providers . SessionProvider . Inactivity . Seconds ( ) ) == 0 {
return false
2019-04-25 04:52:08 +07:00
}
2022-07-08 09:32:43 +07:00
isInactiveTooLong = time . Unix ( userSession . LastActivity , 0 ) . Add ( ctx . Providers . SessionProvider . Inactivity ) . Before ( ctx . Clock . Now ( ) )
2019-04-25 04:52:08 +07:00
2022-07-08 09:32:43 +07:00
ctx . Logger . Tracef ( "Inactivity report for user '%s'. Current Time: %d, Last Activity: %d, Maximum Inactivity: %d." , userSession . Username , ctx . Clock . Now ( ) . Unix ( ) , userSession . LastActivity , int ( ctx . Providers . SessionProvider . Inactivity . Seconds ( ) ) )
2019-04-25 04:52:08 +07:00
2022-07-08 09:32:43 +07:00
return isInactiveTooLong
2019-04-25 04:52:08 +07:00
}
2020-05-05 02:39:25 +07:00
// verifySessionCookie verifies if a user is identified by a cookie.
2020-05-06 04:27:38 +07:00
func verifySessionCookie ( ctx * middlewares . AutheliaCtx , targetURL * url . URL , userSession * session . UserSession , refreshProfile bool ,
2020-10-26 18:38:08 +07:00
refreshProfileInterval time . Duration ) ( username , name string , groups , emails [ ] string , authLevel authentication . Level , err error ) {
2020-05-02 12:06:39 +07:00
// No username in the session means the user is anonymous.
2019-04-25 04:52:08 +07:00
isUserAnonymous := userSession . Username == ""
if isUserAnonymous && userSession . AuthenticationLevel != authentication . NotAuthenticated {
2022-07-08 09:32:43 +07:00
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "an anonymous user cannot be authenticated (this might be the sign of a security compromise)" )
2019-04-25 04:52:08 +07:00
}
2022-07-08 09:32:43 +07:00
if isSessionInactiveTooLong ( ctx , userSession , isUserAnonymous ) {
// Destroy the session a new one will be regenerated on next request.
if err = ctx . Providers . SessionProvider . DestroySession ( ctx . RequestCtx ) ; err != nil {
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "unable to destroy session for user '%s' after the session has been inactive too long: %w" , userSession . Username , err )
2019-04-25 04:52:08 +07:00
}
2022-07-08 09:32:43 +07:00
ctx . Logger . Warnf ( "Session destroyed for user '%s' after exceeding configured session inactivity and not being marked as remembered" , userSession . Username )
2022-07-05 06:58:35 +07:00
2022-07-08 09:32:43 +07:00
return "" , "" , nil , nil , authentication . NotAuthenticated , nil
2019-04-25 04:52:08 +07:00
}
2020-05-05 02:39:25 +07:00
2022-07-08 09:32:43 +07:00
if err = verifySessionHasUpToDateProfile ( ctx , targetURL , userSession , refreshProfile , refreshProfileInterval ) ; err != nil {
2020-05-05 02:39:25 +07:00
if err == authentication . ErrUserNotFound {
2022-07-08 09:32:43 +07:00
if err = ctx . Providers . SessionProvider . DestroySession ( ctx . RequestCtx ) ; err != nil {
ctx . Logger . Errorf ( "Unable to destroy user session after provider refresh didn't find the user: %v" , err )
2020-05-05 02:39:25 +07:00
}
2020-05-06 02:35:32 +07:00
2020-10-26 18:38:08 +07:00
return userSession . Username , userSession . DisplayName , userSession . Groups , userSession . Emails , authentication . NotAuthenticated , err
2020-05-05 02:39:25 +07:00
}
2020-05-06 02:35:32 +07:00
2022-07-08 09:32:43 +07:00
ctx . Logger . Errorf ( "Error occurred while attempting to update user details from LDAP: %v" , err )
2021-09-17 12:53:40 +07:00
return "" , "" , nil , nil , authentication . NotAuthenticated , err
2020-05-05 02:39:25 +07:00
}
2020-10-26 18:38:08 +07:00
return userSession . Username , userSession . DisplayName , userSession . Groups , userSession . Emails , userSession . AuthenticationLevel , nil
2019-04-25 04:52:08 +07:00
}
2021-03-05 11:18:31 +07:00
func handleUnauthorized ( ctx * middlewares . AutheliaCtx , targetURL fmt . Stringer , isBasicAuth bool , username string , method [ ] byte ) {
2021-07-22 10:52:37 +07:00
var (
statusCode int
redirectionURL string
friendlyUsername string
friendlyRequestMethod string
)
switch username {
case "" :
friendlyUsername = "<anonymous>"
default :
2021-03-13 11:52:07 +07:00
friendlyUsername = username
}
2021-02-24 06:35:04 +07:00
if isBasicAuth {
2021-03-13 11:52:07 +07:00
ctx . Logger . Infof ( "Access to %s is not authorized to user %s, sending 401 response with basic auth header" , targetURL . String ( ) , friendlyUsername )
2021-02-24 06:35:04 +07:00
ctx . ReplyUnauthorized ( )
ctx . Response . Header . Add ( "WWW-Authenticate" , "Basic realm=\"Authentication required\"" )
return
}
2020-04-25 06:29:36 +07:00
// Kubernetes ingress controller and Traefik use the rd parameter of the verify
// endpoint to provide the URL of the login portal. The target URL of the user
2020-08-21 08:15:20 +07:00
// is computed from X-Forwarded-* headers or X-Original-URL.
2020-04-25 06:29:36 +07:00
rd := string ( ctx . QueryArgs ( ) . Peek ( "rd" ) )
2021-03-05 11:18:31 +07:00
rm := string ( method )
2021-07-22 10:52:37 +07:00
switch rm {
case "" :
friendlyRequestMethod = "unknown"
default :
friendlyRequestMethod = rm
2021-03-05 11:18:31 +07:00
}
2020-04-25 06:29:36 +07:00
if rd != "" {
2021-07-22 10:52:37 +07:00
switch rm {
case "" :
2021-03-05 11:18:31 +07:00
redirectionURL = fmt . Sprintf ( "%s?rd=%s" , rd , url . QueryEscape ( targetURL . String ( ) ) )
2021-07-22 10:52:37 +07:00
default :
redirectionURL = fmt . Sprintf ( "%s?rd=%s&rm=%s" , rd , url . QueryEscape ( targetURL . String ( ) ) , rm )
2020-04-25 06:29:36 +07:00
}
2021-07-22 10:52:37 +07:00
}
2020-05-06 02:35:32 +07:00
2021-07-22 10:52:37 +07:00
switch {
case ctx . IsXHR ( ) || ! ctx . AcceptsMIME ( "text/html" ) || rd == "" :
statusCode = fasthttp . StatusUnauthorized
default :
2021-07-16 10:43:48 +07:00
switch rm {
2021-07-22 10:52:37 +07:00
case fasthttp . MethodGet , fasthttp . MethodOptions , "" :
statusCode = fasthttp . StatusFound
2021-07-16 10:43:48 +07:00
default :
2021-07-22 10:52:37 +07:00
statusCode = fasthttp . StatusSeeOther
2021-07-16 10:43:48 +07:00
}
2021-07-22 10:52:37 +07:00
}
if redirectionURL != "" {
ctx . Logger . Infof ( "Access to %s (method %s) is not authorized to user %s, responding with status code %d with location redirect to %s" , targetURL . String ( ) , friendlyRequestMethod , friendlyUsername , statusCode , redirectionURL )
ctx . SpecialRedirect ( redirectionURL , statusCode )
2020-04-25 06:29:36 +07:00
} else {
2021-07-22 10:52:37 +07:00
ctx . Logger . Infof ( "Access to %s (method %s) is not authorized to user %s, responding with status code %d" , targetURL . String ( ) , friendlyRequestMethod , friendlyUsername , statusCode )
2020-04-25 06:29:36 +07:00
ctx . ReplyUnauthorized ( )
}
}
2022-07-05 06:58:35 +07:00
func updateActivityTimestamp ( ctx * middlewares . AutheliaCtx , isBasicAuth bool ) error {
if isBasicAuth {
2020-04-25 06:29:36 +07:00
return nil
}
userSession := ctx . GetSession ( )
// We don't need to update the activity timestamp when user checked keep me logged in.
if userSession . KeepMeLoggedIn {
return nil
}
2020-05-02 12:06:39 +07:00
// Mark current activity.
2020-04-25 06:29:36 +07:00
userSession . LastActivity = ctx . Clock . Now ( ) . Unix ( )
2020-05-06 02:35:32 +07:00
2020-04-25 06:29:36 +07:00
return ctx . SaveSession ( userSession )
}
2020-05-05 02:39:25 +07:00
// generateVerifySessionHasUpToDateProfileTraceLogs is used to generate trace logs only when trace logging is enabled.
// The information calculated in this function is completely useless other than trace for now.
func generateVerifySessionHasUpToDateProfileTraceLogs ( ctx * middlewares . AutheliaCtx , userSession * session . UserSession ,
details * authentication . UserDetails ) {
groupsAdded , groupsRemoved := utils . StringSlicesDelta ( userSession . Groups , details . Groups )
emailsAdded , emailsRemoved := utils . StringSlicesDelta ( userSession . Emails , details . Emails )
2020-06-19 17:50:21 +07:00
nameDelta := userSession . DisplayName != details . DisplayName
2020-05-05 02:39:25 +07:00
// Check Groups.
var groupsDelta [ ] string
if len ( groupsAdded ) != 0 {
2021-09-17 12:53:40 +07:00
groupsDelta = append ( groupsDelta , fmt . Sprintf ( "added: %s." , strings . Join ( groupsAdded , ", " ) ) )
2020-05-05 02:39:25 +07:00
}
2020-05-06 02:35:32 +07:00
2020-05-05 02:39:25 +07:00
if len ( groupsRemoved ) != 0 {
2021-09-17 12:53:40 +07:00
groupsDelta = append ( groupsDelta , fmt . Sprintf ( "removed: %s." , strings . Join ( groupsRemoved , ", " ) ) )
2020-05-05 02:39:25 +07:00
}
2020-05-06 02:35:32 +07:00
2020-05-05 02:39:25 +07:00
if len ( groupsDelta ) != 0 {
ctx . Logger . Tracef ( "Updated groups detected for %s. %s" , userSession . Username , strings . Join ( groupsDelta , " " ) )
} else {
ctx . Logger . Tracef ( "No updated groups detected for %s" , userSession . Username )
}
2019-04-25 04:52:08 +07:00
2020-05-05 02:39:25 +07:00
// Check Emails.
var emailsDelta [ ] string
if len ( emailsAdded ) != 0 {
2021-09-17 12:53:40 +07:00
emailsDelta = append ( emailsDelta , fmt . Sprintf ( "added: %s." , strings . Join ( emailsAdded , ", " ) ) )
2020-05-05 02:39:25 +07:00
}
2020-05-06 02:35:32 +07:00
2020-05-05 02:39:25 +07:00
if len ( emailsRemoved ) != 0 {
2021-09-17 12:53:40 +07:00
emailsDelta = append ( emailsDelta , fmt . Sprintf ( "removed: %s." , strings . Join ( emailsRemoved , ", " ) ) )
2019-04-25 04:52:08 +07:00
}
2020-05-06 02:35:32 +07:00
2020-05-05 02:39:25 +07:00
if len ( emailsDelta ) != 0 {
ctx . Logger . Tracef ( "Updated emails detected for %s. %s" , userSession . Username , strings . Join ( emailsDelta , " " ) )
} else {
ctx . Logger . Tracef ( "No updated emails detected for %s" , userSession . Username )
}
2020-06-19 17:50:21 +07:00
// Check Name.
if nameDelta {
ctx . Logger . Tracef ( "Updated display name detected for %s. Added: %s. Removed: %s." , userSession . Username , details . DisplayName , userSession . DisplayName )
} else {
ctx . Logger . Tracef ( "No updated display name detected for %s" , userSession . Username )
}
2020-05-05 02:39:25 +07:00
}
2019-04-25 04:52:08 +07:00
2020-05-05 02:39:25 +07:00
func verifySessionHasUpToDateProfile ( ctx * middlewares . AutheliaCtx , targetURL * url . URL , userSession * session . UserSession ,
refreshProfile bool , refreshProfileInterval time . Duration ) error {
// TODO: Add a check for LDAP password changes based on a time format attribute.
2022-06-15 14:51:47 +07:00
// See https://www.authelia.com/o/threatmodel#potential-future-guarantees
2020-05-05 02:39:25 +07:00
ctx . Logger . Tracef ( "Checking if we need check the authentication backend for an updated profile for %s." , userSession . Username )
2020-05-06 02:35:32 +07:00
2021-02-02 08:01:46 +07:00
if ! refreshProfile || userSession . Username == "" || targetURL == nil {
return nil
}
2020-05-05 02:39:25 +07:00
2021-02-02 08:01:46 +07:00
if refreshProfileInterval != schema . RefreshIntervalAlways && userSession . RefreshTTL . After ( ctx . Clock . Now ( ) ) {
return nil
}
2020-05-05 02:39:25 +07:00
2021-02-02 08:01:46 +07:00
ctx . Logger . Debugf ( "Checking the authentication backend for an updated profile for user %s" , userSession . Username )
details , err := ctx . Providers . UserProvider . GetDetails ( userSession . Username )
// Only update the session if we could get the new details.
if err != nil {
return err
}
emailsDiff := utils . IsStringSlicesDifferent ( userSession . Emails , details . Emails )
groupsDiff := utils . IsStringSlicesDifferent ( userSession . Groups , details . Groups )
nameDiff := userSession . DisplayName != details . DisplayName
if ! groupsDiff && ! emailsDiff && ! nameDiff {
ctx . Logger . Tracef ( "Updated profile not detected for %s." , userSession . Username )
2021-09-17 12:53:40 +07:00
// Only update TTL if the user has an interval set.
2021-02-02 08:01:46 +07:00
// We get to this check when there were no changes.
// Also make sure to update the session even if no difference was found.
// This is so that we don't check every subsequent request after this one.
if refreshProfileInterval != schema . RefreshIntervalAlways {
// Update RefreshTTL and save session if refresh is not set to always.
userSession . RefreshTTL = ctx . Clock . Now ( ) . Add ( refreshProfileInterval )
2020-05-05 02:39:25 +07:00
return ctx . SaveSession ( * userSession )
}
2021-02-02 08:01:46 +07:00
} else {
ctx . Logger . Debugf ( "Updated profile detected for %s." , userSession . Username )
2021-08-03 16:55:21 +07:00
if ctx . Configuration . Log . Level == "trace" {
2021-02-02 08:01:46 +07:00
generateVerifySessionHasUpToDateProfileTraceLogs ( ctx , userSession , details )
}
userSession . Emails = details . Emails
userSession . Groups = details . Groups
userSession . DisplayName = details . DisplayName
// Only update TTL if the user has a interval set.
if refreshProfileInterval != schema . RefreshIntervalAlways {
userSession . RefreshTTL = ctx . Clock . Now ( ) . Add ( refreshProfileInterval )
}
// Return the result of save session if there were changes.
return ctx . SaveSession ( * userSession )
2020-02-19 05:39:07 +07:00
}
2020-05-06 02:35:32 +07:00
2020-05-06 04:27:38 +07:00
// Return nil if disabled or if no changes and refresh interval set to always.
2020-05-05 02:39:25 +07:00
return nil
}
2020-02-19 05:39:07 +07:00
2020-05-05 02:39:25 +07:00
func getProfileRefreshSettings ( cfg schema . AuthenticationBackendConfiguration ) ( refresh bool , refreshInterval time . Duration ) {
2021-04-16 08:44:37 +07:00
if cfg . LDAP != nil {
2021-02-02 08:01:46 +07:00
if cfg . RefreshInterval == schema . ProfileRefreshDisabled {
refresh = false
refreshInterval = 0
} else {
2020-05-05 02:39:25 +07:00
refresh = true
2020-05-06 02:35:32 +07:00
2020-05-05 02:39:25 +07:00
if cfg . RefreshInterval != schema . ProfileRefreshAlways {
2022-01-31 12:25:15 +07:00
// Skip Error Check since validator checks it.
2020-05-05 02:39:25 +07:00
refreshInterval , _ = utils . ParseDurationString ( cfg . RefreshInterval )
} else {
refreshInterval = schema . RefreshIntervalAlways
}
}
2020-02-19 05:39:07 +07:00
}
2020-05-06 02:35:32 +07:00
2020-05-05 02:39:25 +07:00
return refresh , refreshInterval
}
2020-02-19 05:39:07 +07:00
2021-02-24 06:35:04 +07:00
func verifyAuth ( ctx * middlewares . AutheliaCtx , targetURL * url . URL , refreshProfile bool , refreshProfileInterval time . Duration ) ( isBasicAuth bool , username , name string , groups , emails [ ] string , authLevel authentication . Level , err error ) {
2021-12-02 09:21:46 +07:00
authHeader := headerProxyAuthorization
2021-02-24 06:35:04 +07:00
if bytes . Equal ( ctx . QueryArgs ( ) . Peek ( "auth" ) , [ ] byte ( "basic" ) ) {
2021-12-02 09:21:46 +07:00
authHeader = headerAuthorization
2021-02-24 06:35:04 +07:00
isBasicAuth = true
}
2021-12-02 09:21:46 +07:00
authValue := ctx . Request . Header . PeekBytes ( authHeader )
2021-02-24 06:35:04 +07:00
if authValue != nil {
isBasicAuth = true
} else if isBasicAuth {
2022-07-08 09:32:43 +07:00
return isBasicAuth , username , name , groups , emails , authLevel , fmt . Errorf ( "basic auth requested via query arg, but no value provided via %s header" , authHeader )
2021-02-24 06:35:04 +07:00
}
if isBasicAuth {
2021-12-02 09:21:46 +07:00
username , name , groups , emails , authLevel , err = verifyBasicAuth ( ctx , authHeader , authValue )
2022-07-08 09:32:43 +07:00
return isBasicAuth , username , name , groups , emails , authLevel , err
2021-02-24 06:35:04 +07:00
}
userSession := ctx . GetSession ( )
2022-07-08 09:32:43 +07:00
if username , name , groups , emails , authLevel , err = verifySessionCookie ( ctx , targetURL , & userSession , refreshProfile , refreshProfileInterval ) ; err != nil {
return isBasicAuth , username , name , groups , emails , authLevel , err
}
2021-02-24 06:35:04 +07:00
2021-12-02 09:21:46 +07:00
sessionUsername := ctx . Request . Header . PeekBytes ( headerSessionUsername )
2021-02-24 06:35:04 +07:00
if sessionUsername != nil && ! strings . EqualFold ( string ( sessionUsername ) , username ) {
ctx . Logger . Warnf ( "Possible cookie hijack or attempt to bypass security detected destroying the session and sending 401 response" )
2022-07-08 09:32:43 +07:00
if err = ctx . Providers . SessionProvider . DestroySession ( ctx . RequestCtx ) ; err != nil {
2021-12-02 09:21:46 +07:00
ctx . Logger . Errorf ( "Unable to destroy user session after handler could not match them to their %s header: %s" , headerSessionUsername , err )
2021-02-24 06:35:04 +07:00
}
2022-07-08 09:32:43 +07:00
return isBasicAuth , username , name , groups , emails , authLevel , fmt . Errorf ( "could not match user %s to their %s header with a value of %s when visiting %s" , username , headerSessionUsername , sessionUsername , targetURL . String ( ) )
2021-02-24 06:35:04 +07:00
}
2022-07-08 09:32:43 +07:00
return isBasicAuth , username , name , groups , emails , authLevel , err
2021-02-24 06:35:04 +07:00
}
2022-04-08 11:13:47 +07:00
// VerifyGET returns the handler verifying if a request is allowed to go through.
func VerifyGET ( cfg schema . AuthenticationBackendConfiguration ) middlewares . RequestHandler {
2020-05-05 02:39:25 +07:00
refreshProfile , refreshProfileInterval := getProfileRefreshSettings ( cfg )
2019-04-25 04:52:08 +07:00
2020-05-05 02:39:25 +07:00
return func ( ctx * middlewares . AutheliaCtx ) {
ctx . Logger . Tracef ( "Headers=%s" , ctx . Request . Header . String ( ) )
2021-05-05 05:06:05 +07:00
targetURL , err := ctx . GetOriginalURL ( )
2019-04-25 04:52:08 +07:00
2020-05-05 02:39:25 +07:00
if err != nil {
2021-09-17 12:53:40 +07:00
ctx . Logger . Errorf ( "Unable to parse target URL: %s" , err )
2021-05-21 19:03:44 +07:00
ctx . ReplyUnauthorized ( )
2020-05-05 02:39:25 +07:00
return
}
2019-04-25 04:52:08 +07:00
2020-05-05 02:39:25 +07:00
if ! isSchemeHTTPS ( targetURL ) && ! isSchemeWSS ( targetURL ) {
2021-09-17 12:53:40 +07:00
ctx . Logger . Errorf ( "Scheme of target URL %s must be secure since cookies are " +
"only transported over a secure connection for security reasons" , targetURL . String ( ) )
2020-05-05 02:39:25 +07:00
ctx . ReplyUnauthorized ( )
2020-05-06 02:35:32 +07:00
2020-04-25 06:29:36 +07:00
return
}
2019-04-25 04:52:08 +07:00
2020-05-05 02:39:25 +07:00
if ! isURLUnderProtectedDomain ( targetURL , ctx . Configuration . Session . Domain ) {
2021-09-17 12:53:40 +07:00
ctx . Logger . Errorf ( "Target URL %s is not under the protected domain %s" ,
targetURL . String ( ) , ctx . Configuration . Session . Domain )
2020-05-05 02:39:25 +07:00
ctx . ReplyUnauthorized ( )
2020-05-06 02:35:32 +07:00
2020-05-05 02:39:25 +07:00
return
}
2019-04-25 04:52:08 +07:00
2021-03-05 11:18:31 +07:00
method := ctx . XForwardedMethod ( )
2021-09-17 12:53:40 +07:00
isBasicAuth , username , name , groups , emails , authLevel , err := verifyAuth ( ctx , targetURL , refreshProfile , refreshProfileInterval )
2021-03-05 11:18:31 +07:00
2020-05-05 02:39:25 +07:00
if err != nil {
2021-09-17 12:53:40 +07:00
ctx . Logger . Errorf ( "Error caught when verifying user authorization: %s" , err )
2020-05-06 02:35:32 +07:00
2022-07-08 09:32:43 +07:00
if err = updateActivityTimestamp ( ctx , isBasicAuth ) ; err != nil {
2021-09-17 12:53:40 +07:00
ctx . Error ( fmt . Errorf ( "unable to update last activity: %s" , err ) , messageOperationFailed )
2020-05-05 02:39:25 +07:00
return
}
2020-05-06 02:35:32 +07:00
2021-03-05 11:18:31 +07:00
handleUnauthorized ( ctx , targetURL , isBasicAuth , username , method )
2020-05-06 02:35:32 +07:00
2020-05-05 02:39:25 +07:00
return
}
2021-03-05 11:18:31 +07:00
authorized := isTargetURLAuthorized ( ctx . Providers . Authorizer , * targetURL , username ,
groups , ctx . RemoteIP ( ) , method , authLevel )
2020-05-05 02:39:25 +07:00
2021-03-05 11:18:31 +07:00
switch authorized {
2020-05-06 04:27:38 +07:00
case Forbidden :
2020-05-05 02:39:25 +07:00
ctx . Logger . Infof ( "Access to %s is forbidden to user %s" , targetURL . String ( ) , username )
ctx . ReplyForbidden ( )
2020-05-06 04:27:38 +07:00
case NotAuthorized :
2021-03-05 11:18:31 +07:00
handleUnauthorized ( ctx , targetURL , isBasicAuth , username , method )
2020-05-06 04:27:38 +07:00
case Authorized :
2020-10-26 18:38:08 +07:00
setForwardedHeaders ( & ctx . Response . Header , username , name , groups , emails )
2020-05-05 02:39:25 +07:00
}
2022-07-08 09:32:43 +07:00
if err = updateActivityTimestamp ( ctx , isBasicAuth ) ; err != nil {
2021-09-17 12:53:40 +07:00
ctx . Error ( fmt . Errorf ( "unable to update last activity: %s" , err ) , messageOperationFailed )
2020-05-05 02:39:25 +07:00
}
2019-04-25 04:52:08 +07:00
}
}