2019-04-24 21:52:08 +00:00
package handlers
import (
2021-02-23 23:35:04 +00:00
"bytes"
2019-04-24 21:52:08 +00:00
"encoding/base64"
"fmt"
"net"
"net/url"
"strings"
2020-05-04 19:39:25 +00:00
"time"
2019-04-24 21:52:08 +00:00
2020-04-05 12:37:21 +00:00
"github.com/valyala/fasthttp"
2021-08-11 01:04:35 +00: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-24 21:52:08 +00:00
)
2020-02-18 22:39:07 +00: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-27 23:28:53 +00:00
func isSchemeWSS ( url * url . URL ) bool {
return url . Scheme == "wss"
}
2020-05-02 05:06:39 +00:00
// parseBasicAuth parses an HTTP Basic Authentication string.
// "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
2021-12-02 02:21:46 +00:00
func parseBasicAuth ( header [ ] byte , auth string ) ( username , password string , err error ) {
2019-04-24 21:52:08 +00:00
if ! strings . HasPrefix ( auth , authPrefix ) {
2021-02-23 23:35:04 +00:00
return "" , "" , fmt . Errorf ( "%s prefix not found in %s header" , strings . Trim ( authPrefix , " " ) , header )
2019-04-24 21:52:08 +00:00
}
2020-05-05 19:35:32 +00:00
2019-04-24 21:52:08 +00:00
c , err := base64 . StdEncoding . DecodeString ( auth [ len ( authPrefix ) : ] )
if err != nil {
return "" , "" , err
}
2020-05-05 19:35:32 +00:00
2019-04-24 21:52:08 +00:00
cs := string ( c )
s := strings . IndexByte ( cs , ':' )
2020-05-05 19:35:32 +00:00
2019-04-24 21:52:08 +00:00
if s < 0 {
2021-09-17 05:53:40 +00:00
return "" , "" , fmt . Errorf ( "format of %s header must be user:password" , header )
2019-04-24 21:52:08 +00:00
}
2020-05-05 19:35:32 +00:00
2019-04-24 21:52:08 +00:00
return cs [ : s ] , cs [ s + 1 : ] , nil
}
2020-05-02 05:06:39 +00:00
// isTargetURLAuthorized check whether the given user is authorized to access the resource.
2019-04-24 21:52:08 +00:00
func isTargetURLAuthorized ( authorizer * authorization . Authorizer , targetURL url . URL ,
2021-03-05 04:18:31 +00:00
username string , userGroups [ ] string , clientIP net . IP , method [ ] byte , authLevel authentication . Level ) authorizationMatching {
2022-09-04 22:21:30 +00:00
hasSubject , level := authorizer . GetRequiredLevel (
2021-03-05 04:18:31 +00:00
authorization . Subject {
Username : username ,
Groups : userGroups ,
IP : clientIP ,
} ,
authorization . NewObjectRaw ( & targetURL , method ) )
2019-04-24 21:52:08 +00:00
2020-05-05 21:27:38 +00:00
switch {
case level == authorization . Bypass :
2019-04-24 21:52:08 +00:00
return Authorized
2022-09-04 22:21:30 +00:00
case level == authorization . Denied && ( username != "" || ! hasSubject ) :
2019-04-24 21:52:08 +00: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 01:05:17 +00:00
// deduce the access is forbidden
2022-09-04 22:21:30 +00:00
// For anonymous users though, we check that the matched rule has no subject
// if matched rule has not subject then this rule applies to all users including anonymous.
2019-04-24 21:52:08 +00:00
return Forbidden
2020-05-05 21:27:38 +00:00
case level == authorization . OneFactor && authLevel >= authentication . OneFactor ,
level == authorization . TwoFactor && authLevel >= authentication . TwoFactor :
return Authorized
2019-04-24 21:52:08 +00:00
}
2020-05-05 19:35:32 +00:00
2019-04-24 21:52:08 +00:00
return NotAuthorized
}
// verifyBasicAuth verify that the provided username and password are correct and
2020-05-02 05:06:39 +00:00
// that the user is authorized to target the resource.
2021-12-02 02:21:46 +00:00
func verifyBasicAuth ( ctx * middlewares . AutheliaCtx , header , auth [ ] byte ) ( username , name string , groups , emails [ ] string , authLevel authentication . Level , err error ) {
2021-02-23 23:35:04 +00:00
username , password , err := parseBasicAuth ( header , string ( auth ) )
2019-04-24 21:52:08 +00:00
if err != nil {
2021-09-17 05:53:40 +00:00
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "unable to parse content of %s header: %s" , header , err )
2019-04-24 21:52:08 +00:00
}
authenticated , err := ctx . Providers . UserProvider . CheckUserPassword ( username , password )
if err != nil {
2021-12-02 10:28:16 +00:00
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "unable to check credentials extracted from %s header: %w" , header , err )
2019-04-24 21:52:08 +00:00
}
2020-05-02 05:06:39 +00:00
// If the user is not correctly authenticated, send a 401.
2019-04-24 21:52:08 +00:00
if ! authenticated {
2022-01-31 05:25:15 +00:00
// Request Basic Authentication otherwise.
2021-09-17 05:53:40 +00:00
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "user %s is not authenticated" , username )
2019-04-24 21:52:08 +00:00
}
details , err := ctx . Providers . UserProvider . GetDetails ( username )
if err != nil {
2021-09-17 05:53:40 +00:00
return "" , "" , nil , nil , authentication . NotAuthenticated , fmt . Errorf ( "unable to retrieve details of user %s: %s" , username , err )
2019-04-24 21:52:08 +00:00
}
2020-10-26 11:38:08 +00:00
return username , details . DisplayName , details . Groups , details . Emails , authentication . OneFactor , nil
2019-04-24 21:52:08 +00:00
}
2020-10-26 11:38:08 +00:00
// setForwardedHeaders set the forwarded User, Groups, Name and Email headers.
func setForwardedHeaders ( headers * fasthttp . ResponseHeader , username , name string , groups , emails [ ] string ) {
2019-04-24 21:52:08 +00:00
if username != "" {
2021-12-02 02:21:46 +00:00
headers . SetBytesK ( headerRemoteUser , username )
headers . SetBytesK ( headerRemoteGroups , strings . Join ( groups , "," ) )
headers . SetBytesK ( headerRemoteName , name )
2020-11-16 11:22:16 +00:00
if emails != nil {
2021-12-02 02:21:46 +00:00
headers . SetBytesK ( headerRemoteEmail , emails [ 0 ] )
2020-11-16 11:22:16 +00:00
} else {
2021-12-02 02:21:46 +00:00
headers . SetBytesK ( headerRemoteEmail , "" )
2020-11-16 11:22:16 +00:00
}
2019-04-24 21:52:08 +00:00
}
}
2022-07-08 02:32:43 +00: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-24 21:52:08 +00:00
}
2022-07-08 02:32:43 +00:00
isInactiveTooLong = time . Unix ( userSession . LastActivity , 0 ) . Add ( ctx . Providers . SessionProvider . Inactivity ) . Before ( ctx . Clock . Now ( ) )
2019-04-24 21:52:08 +00:00
2022-07-08 02:32:43 +00: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-24 21:52:08 +00:00
2022-07-08 02:32:43 +00:00
return isInactiveTooLong
2019-04-24 21:52:08 +00:00
}
2020-05-04 19:39:25 +00:00
// verifySessionCookie verifies if a user is identified by a cookie.
2020-05-05 21:27:38 +00:00
func verifySessionCookie ( ctx * middlewares . AutheliaCtx , targetURL * url . URL , userSession * session . UserSession , refreshProfile bool ,
2020-10-26 11:38:08 +00:00
refreshProfileInterval time . Duration ) ( username , name string , groups , emails [ ] string , authLevel authentication . Level , err error ) {
2020-05-02 05:06:39 +00:00
// No username in the session means the user is anonymous.
2019-04-24 21:52:08 +00:00
isUserAnonymous := userSession . Username == ""
if isUserAnonymous && userSession . AuthenticationLevel != authentication . NotAuthenticated {
2022-07-08 02:32:43 +00: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-24 21:52:08 +00:00
}
2022-07-08 02:32:43 +00: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-24 21:52:08 +00:00
}
2022-07-08 02:32:43 +00:00
ctx . Logger . Warnf ( "Session destroyed for user '%s' after exceeding configured session inactivity and not being marked as remembered" , userSession . Username )
2022-07-04 23:58:35 +00:00
2022-07-08 02:32:43 +00:00
return "" , "" , nil , nil , authentication . NotAuthenticated , nil
2019-04-24 21:52:08 +00:00
}
2020-05-04 19:39:25 +00:00
2022-07-08 02:32:43 +00:00
if err = verifySessionHasUpToDateProfile ( ctx , targetURL , userSession , refreshProfile , refreshProfileInterval ) ; err != nil {
2020-05-04 19:39:25 +00:00
if err == authentication . ErrUserNotFound {
2022-07-08 02:32:43 +00: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-04 19:39:25 +00:00
}
2020-05-05 19:35:32 +00:00
2020-10-26 11:38:08 +00:00
return userSession . Username , userSession . DisplayName , userSession . Groups , userSession . Emails , authentication . NotAuthenticated , err
2020-05-04 19:39:25 +00:00
}
2020-05-05 19:35:32 +00:00
2022-07-08 02:32:43 +00:00
ctx . Logger . Errorf ( "Error occurred while attempting to update user details from LDAP: %v" , err )
2021-09-17 05:53:40 +00:00
return "" , "" , nil , nil , authentication . NotAuthenticated , err
2020-05-04 19:39:25 +00:00
}
2020-10-26 11:38:08 +00:00
return userSession . Username , userSession . DisplayName , userSession . Groups , userSession . Emails , userSession . AuthenticationLevel , nil
2019-04-24 21:52:08 +00:00
}
2021-03-05 04:18:31 +00:00
func handleUnauthorized ( ctx * middlewares . AutheliaCtx , targetURL fmt . Stringer , isBasicAuth bool , username string , method [ ] byte ) {
2021-07-22 03:52:37 +00:00
var (
statusCode int
friendlyUsername string
friendlyRequestMethod string
)
switch username {
case "" :
friendlyUsername = "<anonymous>"
default :
2021-03-13 04:52:07 +00:00
friendlyUsername = username
}
2021-02-23 23:35:04 +00:00
if isBasicAuth {
2021-03-13 04:52:07 +00: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-23 23:35:04 +00:00
ctx . ReplyUnauthorized ( )
ctx . Response . Header . Add ( "WWW-Authenticate" , "Basic realm=\"Authentication required\"" )
return
}
2021-03-05 04:18:31 +00:00
rm := string ( method )
2021-07-22 03:52:37 +00:00
switch rm {
case "" :
friendlyRequestMethod = "unknown"
default :
friendlyRequestMethod = rm
2021-03-05 04:18:31 +00:00
}
2022-10-01 11:47:09 +00:00
redirectionURL := ctxGetPortalURL ( ctx )
if redirectionURL != nil {
if ! utils . IsURISafeRedirection ( redirectionURL , ctx . Configuration . Session . Domain ) {
ctx . Logger . Errorf ( "Configured Portal URL '%s' does not appear to be able to write cookies for the '%s' domain" , redirectionURL , ctx . Configuration . Session . Domain )
ctx . ReplyUnauthorized ( )
return
2020-04-24 23:29:36 +00:00
}
2022-10-01 11:47:09 +00:00
qry := redirectionURL . Query ( )
qry . Set ( "rd" , targetURL . String ( ) )
if rm != "" {
qry . Set ( "rm" , rm )
}
redirectionURL . RawQuery = qry . Encode ( )
2021-07-22 03:52:37 +00:00
}
2020-05-05 19:35:32 +00:00
2021-07-22 03:52:37 +00:00
switch {
2022-10-01 11:47:09 +00:00
case ctx . IsXHR ( ) || ! ctx . AcceptsMIME ( "text/html" ) || redirectionURL == nil :
2021-07-22 03:52:37 +00:00
statusCode = fasthttp . StatusUnauthorized
default :
2021-07-16 03:43:48 +00:00
switch rm {
2021-07-22 03:52:37 +00:00
case fasthttp . MethodGet , fasthttp . MethodOptions , "" :
statusCode = fasthttp . StatusFound
2021-07-16 03:43:48 +00:00
default :
2021-07-22 03:52:37 +00:00
statusCode = fasthttp . StatusSeeOther
2021-07-16 03:43:48 +00:00
}
2021-07-22 03:52:37 +00:00
}
2022-10-01 11:47:09 +00:00
if redirectionURL != nil {
2021-07-22 03:52:37 +00:00
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 )
2022-10-01 11:47:09 +00:00
ctx . SpecialRedirect ( redirectionURL . String ( ) , statusCode )
2020-04-24 23:29:36 +00:00
} else {
2021-07-22 03:52:37 +00: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-24 23:29:36 +00:00
ctx . ReplyUnauthorized ( )
}
}
2022-07-04 23:58:35 +00:00
func updateActivityTimestamp ( ctx * middlewares . AutheliaCtx , isBasicAuth bool ) error {
if isBasicAuth {
2020-04-24 23:29:36 +00: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 05:06:39 +00:00
// Mark current activity.
2020-04-24 23:29:36 +00:00
userSession . LastActivity = ctx . Clock . Now ( ) . Unix ( )
2020-05-05 19:35:32 +00:00
2020-04-24 23:29:36 +00:00
return ctx . SaveSession ( userSession )
}
2020-05-04 19:39:25 +00: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 10:50:21 +00:00
nameDelta := userSession . DisplayName != details . DisplayName
2020-05-04 19:39:25 +00:00
// Check Groups.
var groupsDelta [ ] string
if len ( groupsAdded ) != 0 {
2021-09-17 05:53:40 +00:00
groupsDelta = append ( groupsDelta , fmt . Sprintf ( "added: %s." , strings . Join ( groupsAdded , ", " ) ) )
2020-05-04 19:39:25 +00:00
}
2020-05-05 19:35:32 +00:00
2020-05-04 19:39:25 +00:00
if len ( groupsRemoved ) != 0 {
2021-09-17 05:53:40 +00:00
groupsDelta = append ( groupsDelta , fmt . Sprintf ( "removed: %s." , strings . Join ( groupsRemoved , ", " ) ) )
2020-05-04 19:39:25 +00:00
}
2020-05-05 19:35:32 +00:00
2020-05-04 19:39:25 +00: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-24 21:52:08 +00:00
2020-05-04 19:39:25 +00:00
// Check Emails.
var emailsDelta [ ] string
if len ( emailsAdded ) != 0 {
2021-09-17 05:53:40 +00:00
emailsDelta = append ( emailsDelta , fmt . Sprintf ( "added: %s." , strings . Join ( emailsAdded , ", " ) ) )
2020-05-04 19:39:25 +00:00
}
2020-05-05 19:35:32 +00:00
2020-05-04 19:39:25 +00:00
if len ( emailsRemoved ) != 0 {
2021-09-17 05:53:40 +00:00
emailsDelta = append ( emailsDelta , fmt . Sprintf ( "removed: %s." , strings . Join ( emailsRemoved , ", " ) ) )
2019-04-24 21:52:08 +00:00
}
2020-05-05 19:35:32 +00:00
2020-05-04 19:39:25 +00: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 10:50:21 +00: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-04 19:39:25 +00:00
}
2019-04-24 21:52:08 +00:00
2020-05-04 19:39:25 +00: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 07:51:47 +00:00
// See https://www.authelia.com/o/threatmodel#potential-future-guarantees
2020-05-04 19:39:25 +00:00
ctx . Logger . Tracef ( "Checking if we need check the authentication backend for an updated profile for %s." , userSession . Username )
2020-05-05 19:35:32 +00:00
2021-02-02 01:01:46 +00:00
if ! refreshProfile || userSession . Username == "" || targetURL == nil {
return nil
}
2020-05-04 19:39:25 +00:00
2021-02-02 01:01:46 +00:00
if refreshProfileInterval != schema . RefreshIntervalAlways && userSession . RefreshTTL . After ( ctx . Clock . Now ( ) ) {
return nil
}
2020-05-04 19:39:25 +00:00
2021-02-02 01:01:46 +00: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 05:53:40 +00:00
// Only update TTL if the user has an interval set.
2021-02-02 01:01:46 +00: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-04 19:39:25 +00:00
return ctx . SaveSession ( * userSession )
}
2021-02-02 01:01:46 +00:00
} else {
ctx . Logger . Debugf ( "Updated profile detected for %s." , userSession . Username )
2021-08-03 09:55:21 +00:00
if ctx . Configuration . Log . Level == "trace" {
2021-02-02 01:01:46 +00: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-18 22:39:07 +00:00
}
2020-05-05 19:35:32 +00:00
2020-05-05 21:27:38 +00:00
// Return nil if disabled or if no changes and refresh interval set to always.
2020-05-04 19:39:25 +00:00
return nil
}
2020-02-18 22:39:07 +00:00
2022-10-17 10:51:59 +00:00
func getProfileRefreshSettings ( cfg schema . AuthenticationBackend ) ( refresh bool , refreshInterval time . Duration ) {
2021-04-16 01:44:37 +00:00
if cfg . LDAP != nil {
2021-02-02 01:01:46 +00:00
if cfg . RefreshInterval == schema . ProfileRefreshDisabled {
refresh = false
refreshInterval = 0
} else {
2020-05-04 19:39:25 +00:00
refresh = true
2020-05-05 19:35:32 +00:00
2020-05-04 19:39:25 +00:00
if cfg . RefreshInterval != schema . ProfileRefreshAlways {
2022-01-31 05:25:15 +00:00
// Skip Error Check since validator checks it.
2020-05-04 19:39:25 +00:00
refreshInterval , _ = utils . ParseDurationString ( cfg . RefreshInterval )
} else {
refreshInterval = schema . RefreshIntervalAlways
}
}
2020-02-18 22:39:07 +00:00
}
2020-05-05 19:35:32 +00:00
2020-05-04 19:39:25 +00:00
return refresh , refreshInterval
}
2020-02-18 22:39:07 +00:00
2021-02-23 23:35:04 +00: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 02:21:46 +00:00
authHeader := headerProxyAuthorization
2021-02-23 23:35:04 +00:00
if bytes . Equal ( ctx . QueryArgs ( ) . Peek ( "auth" ) , [ ] byte ( "basic" ) ) {
2021-12-02 02:21:46 +00:00
authHeader = headerAuthorization
2021-02-23 23:35:04 +00:00
isBasicAuth = true
}
2021-12-02 02:21:46 +00:00
authValue := ctx . Request . Header . PeekBytes ( authHeader )
2021-02-23 23:35:04 +00:00
if authValue != nil {
isBasicAuth = true
} else if isBasicAuth {
2022-07-08 02:32:43 +00: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-23 23:35:04 +00:00
}
if isBasicAuth {
2021-12-02 02:21:46 +00:00
username , name , groups , emails , authLevel , err = verifyBasicAuth ( ctx , authHeader , authValue )
2022-07-08 02:32:43 +00:00
return isBasicAuth , username , name , groups , emails , authLevel , err
2021-02-23 23:35:04 +00:00
}
userSession := ctx . GetSession ( )
2022-07-08 02:32:43 +00: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-23 23:35:04 +00:00
2021-12-02 02:21:46 +00:00
sessionUsername := ctx . Request . Header . PeekBytes ( headerSessionUsername )
2021-02-23 23:35:04 +00: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 02:32:43 +00:00
if err = ctx . Providers . SessionProvider . DestroySession ( ctx . RequestCtx ) ; err != nil {
2021-12-02 02:21:46 +00:00
ctx . Logger . Errorf ( "Unable to destroy user session after handler could not match them to their %s header: %s" , headerSessionUsername , err )
2021-02-23 23:35:04 +00:00
}
2022-07-08 02:32:43 +00: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-23 23:35:04 +00:00
}
2022-07-08 02:32:43 +00:00
return isBasicAuth , username , name , groups , emails , authLevel , err
2021-02-23 23:35:04 +00:00
}
2022-04-08 04:13:47 +00:00
// VerifyGET returns the handler verifying if a request is allowed to go through.
2022-10-17 10:51:59 +00:00
func VerifyGET ( cfg schema . AuthenticationBackend ) middlewares . RequestHandler {
2020-05-04 19:39:25 +00:00
refreshProfile , refreshProfileInterval := getProfileRefreshSettings ( cfg )
2019-04-24 21:52:08 +00:00
2020-05-04 19:39:25 +00:00
return func ( ctx * middlewares . AutheliaCtx ) {
ctx . Logger . Tracef ( "Headers=%s" , ctx . Request . Header . String ( ) )
2021-05-04 22:06:05 +00:00
targetURL , err := ctx . GetOriginalURL ( )
2019-04-24 21:52:08 +00:00
2020-05-04 19:39:25 +00:00
if err != nil {
2021-09-17 05:53:40 +00:00
ctx . Logger . Errorf ( "Unable to parse target URL: %s" , err )
2021-05-21 12:03:44 +00:00
ctx . ReplyUnauthorized ( )
2020-05-04 19:39:25 +00:00
return
}
2019-04-24 21:52:08 +00:00
2020-05-04 19:39:25 +00:00
if ! isSchemeHTTPS ( targetURL ) && ! isSchemeWSS ( targetURL ) {
2021-09-17 05:53:40 +00: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-04 19:39:25 +00:00
ctx . ReplyUnauthorized ( )
2020-05-05 19:35:32 +00:00
2020-04-24 23:29:36 +00:00
return
}
2019-04-24 21:52:08 +00:00
2020-05-04 19:39:25 +00:00
if ! isURLUnderProtectedDomain ( targetURL , ctx . Configuration . Session . Domain ) {
2021-09-17 05:53:40 +00:00
ctx . Logger . Errorf ( "Target URL %s is not under the protected domain %s" ,
targetURL . String ( ) , ctx . Configuration . Session . Domain )
2020-05-04 19:39:25 +00:00
ctx . ReplyUnauthorized ( )
2020-05-05 19:35:32 +00:00
2020-05-04 19:39:25 +00:00
return
}
2019-04-24 21:52:08 +00:00
2021-03-05 04:18:31 +00:00
method := ctx . XForwardedMethod ( )
2021-09-17 05:53:40 +00:00
isBasicAuth , username , name , groups , emails , authLevel , err := verifyAuth ( ctx , targetURL , refreshProfile , refreshProfileInterval )
2021-03-05 04:18:31 +00:00
2020-05-04 19:39:25 +00:00
if err != nil {
2021-09-17 05:53:40 +00:00
ctx . Logger . Errorf ( "Error caught when verifying user authorization: %s" , err )
2020-05-05 19:35:32 +00:00
2022-07-08 02:32:43 +00:00
if err = updateActivityTimestamp ( ctx , isBasicAuth ) ; err != nil {
2021-09-17 05:53:40 +00:00
ctx . Error ( fmt . Errorf ( "unable to update last activity: %s" , err ) , messageOperationFailed )
2020-05-04 19:39:25 +00:00
return
}
2020-05-05 19:35:32 +00:00
2021-03-05 04:18:31 +00:00
handleUnauthorized ( ctx , targetURL , isBasicAuth , username , method )
2020-05-05 19:35:32 +00:00
2020-05-04 19:39:25 +00:00
return
}
2021-03-05 04:18:31 +00:00
authorized := isTargetURLAuthorized ( ctx . Providers . Authorizer , * targetURL , username ,
groups , ctx . RemoteIP ( ) , method , authLevel )
2020-05-04 19:39:25 +00:00
2021-03-05 04:18:31 +00:00
switch authorized {
2020-05-05 21:27:38 +00:00
case Forbidden :
2020-05-04 19:39:25 +00:00
ctx . Logger . Infof ( "Access to %s is forbidden to user %s" , targetURL . String ( ) , username )
ctx . ReplyForbidden ( )
2020-05-05 21:27:38 +00:00
case NotAuthorized :
2021-03-05 04:18:31 +00:00
handleUnauthorized ( ctx , targetURL , isBasicAuth , username , method )
2020-05-05 21:27:38 +00:00
case Authorized :
2020-10-26 11:38:08 +00:00
setForwardedHeaders ( & ctx . Response . Header , username , name , groups , emails )
2020-05-04 19:39:25 +00:00
}
2022-07-08 02:32:43 +00:00
if err = updateActivityTimestamp ( ctx , isBasicAuth ) ; err != nil {
2021-09-17 05:53:40 +00:00
ctx . Error ( fmt . Errorf ( "unable to update last activity: %s" , err ) , messageOperationFailed )
2020-05-04 19:39:25 +00:00
}
2019-04-24 21:52:08 +00:00
}
}