@@ -56,6 +56,7 @@ func (api *API) InitUser() {
|
||||
api.BaseRoutes.User.Handle("/email/verify/member", api.APISessionRequired(verifyUserEmailWithoutToken)).Methods(http.MethodPost)
|
||||
api.BaseRoutes.User.Handle("/terms_of_service", api.APISessionRequired(saveUserTermsOfService)).Methods(http.MethodPost)
|
||||
api.BaseRoutes.User.Handle("/terms_of_service", api.APISessionRequired(getUserTermsOfService)).Methods(http.MethodGet)
|
||||
api.BaseRoutes.User.Handle("/reset_failed_attempts", api.APISessionRequired(resetPasswordFailedAttempts)).Methods(http.MethodPost)
|
||||
|
||||
api.BaseRoutes.User.Handle("/auth", api.APISessionRequiredTrustRequester(updateUserAuth)).Methods(http.MethodPut)
|
||||
|
||||
@@ -1861,6 +1862,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) {
|
||||
"api.user.check_user_login_attempts.too_many.app_error",
|
||||
"app.team.join_user_to_team.max_accounts.app_error",
|
||||
"store.sql_user.save.max_accounts.app_error",
|
||||
"api.user.check_user_login_attempts.too_many_ldap.app_error",
|
||||
}
|
||||
|
||||
maskError := true
|
||||
@@ -3525,3 +3527,46 @@ func getUsersWithInvalidEmails(c *Context, w http.ResponseWriter, r *http.Reques
|
||||
c.Logger.Warn("Error writing response", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
|
||||
func resetPasswordFailedAttempts(c *Context, w http.ResponseWriter, r *http.Request) {
|
||||
c.RequireUserId()
|
||||
if c.Err != nil {
|
||||
return
|
||||
}
|
||||
errParams := map[string]any{"userID": c.Params.UserId}
|
||||
|
||||
auditRec := c.MakeAuditRecord("resetPasswordFailedAttempts", audit.Fail)
|
||||
defer c.LogAuditRec(auditRec)
|
||||
|
||||
if !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionSysconsoleWriteUserManagementUsers) {
|
||||
c.Err = model.NewAppError("resetPasswordFailedAttempts", "api.user.reset_password_failed_attempts.permissions.app_error", errParams, "", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := c.App.GetUser(c.Params.UserId)
|
||||
if err != nil {
|
||||
c.Err = err
|
||||
return
|
||||
}
|
||||
auditRec.AddEventPriorState(user)
|
||||
auditRec.AddEventObjectType("user")
|
||||
|
||||
if user.IsSystemAdmin() && !c.App.SessionHasPermissionTo(*c.AppContext.Session(), model.PermissionManageSystem) {
|
||||
c.SetPermissionError(model.PermissionManageSystem)
|
||||
return
|
||||
}
|
||||
|
||||
if user.AuthService != model.UserAuthServiceLdap && user.AuthService != "" {
|
||||
c.Err = model.NewAppError("resetPasswordFailedAttempts", "api.user.reset_password_failed_attempts.ldap_and_email_only.app_error", errParams, "", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := c.App.ResetPasswordFailedAttempts(c.AppContext, user); err != nil {
|
||||
c.Err = err
|
||||
return
|
||||
}
|
||||
|
||||
auditRec.Success()
|
||||
|
||||
ReturnStatusOK(w)
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/dgryski/dgoogauth"
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -8973,6 +8974,221 @@ func TestRevokeAllSessionsForUser(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestResetPasswordFailedAttempts(t *testing.T) {
|
||||
th := SetupEnterprise(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
th.SetupLdapConfig()
|
||||
|
||||
th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
|
||||
|
||||
t.Run("Reset password failed attempts for regular user", func(t *testing.T) {
|
||||
client := th.CreateClient()
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.MaximumLoginAttempts = 10
|
||||
})
|
||||
maxAttempts := th.App.Config().ServiceSettings.MaximumLoginAttempts
|
||||
|
||||
user := th.CreateUser()
|
||||
|
||||
for i := 0; i < *maxAttempts; i++ {
|
||||
_, _, err := client.Login(context.Background(), user.Email, "wrongpassword")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
user, resp, err := th.SystemAdminClient.GetUser(context.Background(), user.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, *maxAttempts, user.FailedAttempts)
|
||||
|
||||
resp, err = th.SystemAdminClient.ResetFailedAttempts(context.Background(), user.Id)
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
|
||||
user, resp, err = th.SystemAdminClient.GetUser(context.Background(), user.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, int(0), user.FailedAttempts)
|
||||
})
|
||||
|
||||
t.Run("Reset password failed attempts for ldap user", func(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.LdapSettings.MaximumLoginAttempts = 5
|
||||
})
|
||||
|
||||
mockCtrl := gomock.NewController(t)
|
||||
defer mockCtrl.Finish()
|
||||
|
||||
mockLdap := &mocks.LdapInterface{}
|
||||
|
||||
username := GenerateTestUsername()
|
||||
|
||||
ldapUser := &model.User{
|
||||
Email: "foobar+testdomainrestriction@mattermost.org",
|
||||
Username: username,
|
||||
AuthService: "ldap",
|
||||
AuthData: &username,
|
||||
EmailVerified: true,
|
||||
}
|
||||
ldapUser, appErr := th.App.CreateUser(th.Context, ldapUser)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
client := th.CreateClient()
|
||||
mockLdap.Mock.On("GetUser", mock.AnythingOfType("*request.Context"), mock.AnythingOfType("string")).Return(ldapUser, nil).Times(5)
|
||||
|
||||
th.App.Channels().Ldap = mockLdap
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
mockedLdapUser := ldapUser
|
||||
mockedLdapUser.FailedAttempts = i
|
||||
mockLdap.Mock.On("DoLogin", mock.AnythingOfType("*request.Context"), mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(mockedLdapUser, &model.AppError{Id: "ent.ldap.do_login.invalid_password.app_error"})
|
||||
_, _, err := client.LoginByLdap(context.Background(), *ldapUser.AuthData, "wrongpassword")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
user, resp, err := th.SystemAdminClient.GetUser(context.Background(), ldapUser.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, int(5), user.FailedAttempts)
|
||||
|
||||
resp, err = th.SystemAdminClient.ResetFailedAttempts(context.Background(), ldapUser.Id)
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
|
||||
user, resp, err = th.SystemAdminClient.GetUser(context.Background(), ldapUser.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, int(0), user.FailedAttempts)
|
||||
})
|
||||
|
||||
t.Run("Regular user unable to reset failed attempts", func(t *testing.T) {
|
||||
client := th.CreateClient()
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.MaximumLoginAttempts = 10
|
||||
})
|
||||
maxAttempts := th.App.Config().ServiceSettings.MaximumLoginAttempts
|
||||
|
||||
user := th.CreateUser()
|
||||
|
||||
for i := 0; i < *maxAttempts; i++ {
|
||||
_, _, err := client.Login(context.Background(), user.Email, "wrongpassword")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
user, resp, err := th.SystemAdminClient.GetUser(context.Background(), user.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, *maxAttempts, user.FailedAttempts)
|
||||
|
||||
resp, err = th.Client.ResetFailedAttempts(context.Background(), user.Id)
|
||||
require.Error(t, err)
|
||||
CheckForbiddenStatus(t, resp)
|
||||
|
||||
user, resp, err = th.SystemAdminClient.GetUser(context.Background(), user.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, *maxAttempts, user.FailedAttempts)
|
||||
})
|
||||
|
||||
t.Run("Reset password failed attempts when user has PermissionSysconsoleWriteUserManagementUsers", func(t *testing.T) {
|
||||
th.AddPermissionToRole(model.PermissionSysconsoleWriteUserManagementUsers.Id, model.SystemUserRoleId)
|
||||
defer th.RemovePermissionFromRole(model.PermissionSysconsoleWriteUserManagementUsers.Id, model.SystemUserRoleId)
|
||||
|
||||
client := th.CreateClient()
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.MaximumLoginAttempts = 10
|
||||
})
|
||||
maxAttempts := th.App.Config().ServiceSettings.MaximumLoginAttempts
|
||||
|
||||
user := th.CreateUser()
|
||||
|
||||
for i := 0; i < *maxAttempts; i++ {
|
||||
_, _, err := client.Login(context.Background(), user.Email, "wrongpassword")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
fetchedUser, resp, err := th.SystemAdminClient.GetUser(context.Background(), user.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, *maxAttempts, fetchedUser.FailedAttempts)
|
||||
|
||||
resp, err = th.Client.ResetFailedAttempts(context.Background(), user.Id)
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
|
||||
fetchedUser, resp, err = th.SystemAdminClient.GetUser(context.Background(), user.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, int(0), fetchedUser.FailedAttempts)
|
||||
})
|
||||
|
||||
t.Run("Unable to reset password failed attempts for sysadmin when user has PermissionSysconsoleWriteUserManagementUsers", func(t *testing.T) {
|
||||
th.AddPermissionToRole(model.PermissionSysconsoleWriteUserManagementUsers.Id, model.SystemUserRoleId)
|
||||
defer th.RemovePermissionFromRole(model.PermissionSysconsoleWriteUserManagementUsers.Id, model.SystemUserRoleId)
|
||||
|
||||
client := th.CreateClient()
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.MaximumLoginAttempts = 10
|
||||
})
|
||||
maxAttempts := th.App.Config().ServiceSettings.MaximumLoginAttempts
|
||||
|
||||
// create sysadmin user
|
||||
sysadmin := th.CreateUser()
|
||||
_, appErr := th.App.UpdateUserRoles(th.Context, sysadmin.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
for i := 0; i < *maxAttempts; i++ {
|
||||
_, _, err := client.Login(context.Background(), sysadmin.Email, "wrongpassword")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
sysadminUser, resp, err := th.SystemAdminClient.GetUser(context.Background(), sysadmin.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, *maxAttempts, sysadminUser.FailedAttempts)
|
||||
|
||||
resp, err = th.Client.ResetFailedAttempts(context.Background(), sysadminUser.Id)
|
||||
require.Error(t, err)
|
||||
CheckForbiddenStatus(t, resp)
|
||||
|
||||
sysadminUser, resp, err = th.SystemAdminClient.GetUser(context.Background(), sysadminUser.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, int(10), sysadminUser.FailedAttempts)
|
||||
})
|
||||
|
||||
t.Run("Reset password failed attempts for sysadmin", func(t *testing.T) {
|
||||
client := th.CreateClient()
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.MaximumLoginAttempts = 10
|
||||
})
|
||||
maxAttempts := th.App.Config().ServiceSettings.MaximumLoginAttempts
|
||||
|
||||
sysadmin := th.CreateUser()
|
||||
_, appErr := th.App.UpdateUserRoles(th.Context, sysadmin.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
for i := 0; i < *maxAttempts; i++ {
|
||||
_, _, err := client.Login(context.Background(), sysadmin.Email, "wrongpassword")
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
sysadminUser, resp, err := th.SystemAdminClient.GetUser(context.Background(), sysadmin.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, *maxAttempts, sysadminUser.FailedAttempts)
|
||||
|
||||
resp, err = th.SystemAdminClient.ResetFailedAttempts(context.Background(), sysadminUser.Id)
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
|
||||
sysadminUser, resp, err = th.SystemAdminClient.GetUser(context.Background(), sysadminUser.Id, "")
|
||||
require.NoError(t, err)
|
||||
CheckOKStatus(t, resp)
|
||||
require.Equal(t, int(0), sysadminUser.FailedAttempts)
|
||||
})
|
||||
}
|
||||
func TestSearchUsersWithMfaEnforced(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
@@ -64,8 +64,8 @@ func (a *App) IsPasswordValid(rctx request.CTX, password string) *model.AppError
|
||||
func (a *App) CheckPasswordAndAllCriteria(rctx request.CTX, userID string, password string, mfaToken string) *model.AppError {
|
||||
// MM-37585
|
||||
// Use locks to avoid concurrently checking AND updating the failed login attempts.
|
||||
a.ch.loginAttemptsMut.Lock()
|
||||
defer a.ch.loginAttemptsMut.Unlock()
|
||||
a.ch.emailLoginAttemptsMut.Lock()
|
||||
defer a.ch.emailLoginAttemptsMut.Unlock()
|
||||
|
||||
user, err := a.GetUser(userID)
|
||||
if err != nil {
|
||||
@@ -149,31 +149,86 @@ func (a *App) DoubleCheckPassword(rctx request.CTX, user *model.User, password s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) checkLdapUserPasswordAndAllCriteria(rctx request.CTX, ldapId *string, password string, mfaToken string) (*model.User, *model.AppError) {
|
||||
if a.Ldap() == nil || ldapId == nil {
|
||||
func (a *App) checkLdapUserPasswordAndAllCriteria(rctx request.CTX, user *model.User, password, mfaToken string) (*model.User, *model.AppError) {
|
||||
// MM-37585: Use locks to avoid concurrently checking AND updating the failed login attempts.
|
||||
a.ch.ldapLoginAttemptsMut.Lock()
|
||||
defer a.ch.ldapLoginAttemptsMut.Unlock()
|
||||
|
||||
// We need to get the latest value of the user from the database after we acquire the lock. user is nil for first-time LDAP users.
|
||||
if user.Id != "" {
|
||||
var err *model.AppError
|
||||
user, err = a.GetUser(user.Id)
|
||||
if err != nil {
|
||||
if err.Id != MissingAccountError {
|
||||
err.StatusCode = http.StatusInternalServerError
|
||||
return nil, err
|
||||
}
|
||||
err.StatusCode = http.StatusBadRequest
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
ldapID := user.AuthData
|
||||
|
||||
if a.Ldap() == nil || ldapID == nil {
|
||||
err := model.NewAppError("doLdapAuthentication", "api.user.login_ldap.not_available.app_error", nil, "", http.StatusNotImplemented)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ldapUser, err := a.Ldap().DoLogin(rctx, *ldapId, password)
|
||||
// First time LDAP users will not have a userID
|
||||
if user.Id != "" {
|
||||
if err := checkUserLoginAttempts(user, *a.Config().LdapSettings.MaximumLoginAttempts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
ldapUser, err := a.Ldap().DoLogin(rctx, *ldapID, password)
|
||||
if err != nil {
|
||||
// If this is a new LDAP user, we need to get the user from the database because DoLogin will have created the user.
|
||||
if user.Id == "" {
|
||||
var getUserByAuthErr *model.AppError
|
||||
ldapUser, getUserByAuthErr = a.GetUserByAuth(ldapID, model.UserAuthServiceLdap)
|
||||
if getUserByAuthErr != nil {
|
||||
return nil, getUserByAuthErr
|
||||
}
|
||||
} else {
|
||||
ldapUser = user
|
||||
}
|
||||
|
||||
// Log a info to make it easier to admin to spot that a user tried to log in with a legitimate user name.
|
||||
if err.Id == "ent.ldap.do_login.invalid_password.app_error" {
|
||||
rctx.Logger().LogM(mlog.MlvlLDAPInfo, "A user tried to sign in, which matched an LDAP account, but the password was incorrect.", mlog.String("ldap_id", *ldapId))
|
||||
rctx.Logger().LogM(mlog.MlvlLDAPInfo, "A user tried to sign in, which matched an LDAP account, but the password was incorrect.", mlog.String("ldap_id", *ldapID))
|
||||
|
||||
if passErr := a.Srv().Store().User().UpdateFailedPasswordAttempts(ldapUser.Id, ldapUser.FailedAttempts+1); passErr != nil {
|
||||
return nil, model.NewAppError("CheckPasswordAndAllCriteria", "app.user.update_failed_pwd_attempts.app_error", nil, "", http.StatusInternalServerError).Wrap(passErr)
|
||||
}
|
||||
}
|
||||
|
||||
err.StatusCode = http.StatusUnauthorized
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := a.CheckUserMfa(rctx, ldapUser, mfaToken); err != nil {
|
||||
if err = a.CheckUserMfa(rctx, ldapUser, mfaToken); err != nil {
|
||||
// If the mfaToken is not set, we assume the client used this as a pre-flight request to query the server
|
||||
// about the MFA state of the user in question
|
||||
if mfaToken != "" && ldapUser.Id != "" {
|
||||
if passErr := a.Srv().Store().User().UpdateFailedPasswordAttempts(ldapUser.Id, ldapUser.FailedAttempts+1); passErr != nil {
|
||||
return nil, model.NewAppError("CheckPasswordAndAllCriteria", "app.user.update_failed_pwd_attempts.app_error", nil, "", http.StatusInternalServerError).Wrap(passErr)
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := checkUserNotDisabled(ldapUser); err != nil {
|
||||
if err = checkUserNotDisabled(ldapUser); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if ldapUser.FailedAttempts > 0 {
|
||||
if passErr := a.Srv().Store().User().UpdateFailedPasswordAttempts(ldapUser.Id, 0); passErr != nil {
|
||||
return nil, model.NewAppError("CheckPasswordAndAllCriteria", "app.user.update_failed_pwd_attempts.app_error", nil, "", http.StatusInternalServerError).Wrap(passErr)
|
||||
}
|
||||
}
|
||||
|
||||
// user successfully authenticated
|
||||
return ldapUser, nil
|
||||
}
|
||||
@@ -286,6 +341,9 @@ func (a *App) MFARequired(rctx request.CTX) *model.AppError {
|
||||
|
||||
func checkUserLoginAttempts(user *model.User, max int) *model.AppError {
|
||||
if user.FailedAttempts >= max {
|
||||
if user.AuthService == model.UserAuthServiceLdap {
|
||||
return model.NewAppError("checkUserLoginAttempts", "api.user.check_user_login_attempts.too_many_ldap.app_error", nil, "user_id="+user.Id, http.StatusUnauthorized)
|
||||
}
|
||||
return model.NewAppError("checkUserLoginAttempts", "api.user.check_user_login_attempts.too_many.app_error", nil, "user_id="+user.Id, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
@@ -316,7 +374,7 @@ func (a *App) authenticateUser(rctx request.CTX, user *model.User, password, mfa
|
||||
return user, err
|
||||
}
|
||||
|
||||
ldapUser, err := a.checkLdapUserPasswordAndAllCriteria(rctx, user.AuthData, password, mfaToken)
|
||||
ldapUser, err := a.checkLdapUserPasswordAndAllCriteria(rctx, user, password, mfaToken)
|
||||
if err != nil {
|
||||
err.StatusCode = http.StatusUnauthorized
|
||||
return user, err
|
||||
|
||||
@@ -13,9 +13,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/dgryski/dgoogauth"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/v8/einterfaces/mocks"
|
||||
)
|
||||
|
||||
func TestParseAuthTokenFromRequest(t *testing.T) {
|
||||
@@ -153,3 +155,211 @@ func TestCheckPasswordAndAllCriteria(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCheckLdapUserPasswordAndAllCriteria(t *testing.T) {
|
||||
th := SetupEnterprise(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
// update config
|
||||
const maxFailedLoginAttempts = 3
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.LdapSettings.MaximumLoginAttempts = maxFailedLoginAttempts
|
||||
*cfg.ServiceSettings.EnableMultifactorAuthentication = true
|
||||
})
|
||||
|
||||
mockLdap := &mocks.LdapInterface{}
|
||||
th.App.Channels().Ldap = mockLdap
|
||||
|
||||
authData := model.NewRandomString(32)
|
||||
|
||||
// create an ldap user by calling createUser
|
||||
ldapUser := &model.User{
|
||||
Email: "ldapuser@mattermost-customer.com",
|
||||
Username: "ldapuser",
|
||||
AuthService: model.UserAuthServiceLdap,
|
||||
AuthData: &authData,
|
||||
EmailVerified: true,
|
||||
}
|
||||
user, appErr := th.App.CreateUser(th.Context, ldapUser)
|
||||
require.Nil(t, appErr)
|
||||
user.AuthData = &authData
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
password string
|
||||
expectedErrID string
|
||||
mockDoLogin func()
|
||||
}{
|
||||
{
|
||||
name: "valid password",
|
||||
password: "password",
|
||||
expectedErrID: "",
|
||||
mockDoLogin: func() {
|
||||
mockLdap.Mock.On("DoLogin", th.Context, authData, "password").Return(user, nil)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "invalid password",
|
||||
password: "wrongpassword",
|
||||
expectedErrID: "api.user.check_user_password.invalid.app_error",
|
||||
mockDoLogin: func() {
|
||||
mockLdap.Mock.On("DoLogin", th.Context, authData, "wrongpassword").Return(nil, &model.AppError{Id: "ent.ldap.do_login.invalid_password.app_error"})
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "too many login attempts",
|
||||
password: "wrongpassword",
|
||||
expectedErrID: "api.user.check_user_login_attempts.too_many_ldap.app_error",
|
||||
mockDoLogin: func() {
|
||||
mockLdap.Mock.On("DoLogin", th.Context, authData, "wrongpassword").Return(nil, &model.AppError{Id: "ent.ldap.do_login.invalid_password.app_error"}).Once()
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Reset login attempts
|
||||
err := th.App.Srv().Store().User().UpdateFailedPasswordAttempts(user.Id, 0)
|
||||
require.NoError(t, err)
|
||||
|
||||
tc.mockDoLogin()
|
||||
|
||||
ldapUser := user
|
||||
|
||||
// Simulate failed login attempts if necessary
|
||||
if tc.expectedErrID == "api.user.check_user_login_attempts.too_many_ldap.app_error" {
|
||||
for i := 0; i < maxFailedLoginAttempts-1; i++ {
|
||||
_, appErr = th.App.checkLdapUserPasswordAndAllCriteria(th.Context, ldapUser, "wrongpassword", "")
|
||||
require.NotNil(t, appErr)
|
||||
require.Equal(t, "ent.ldap.do_login.invalid_password.app_error", appErr.Id)
|
||||
}
|
||||
}
|
||||
// Call the method with the test case parameters
|
||||
_, appErr := th.App.checkLdapUserPasswordAndAllCriteria(th.Context, ldapUser, tc.password, "")
|
||||
|
||||
// Verify the returned error matches the expected error
|
||||
if tc.expectedErrID == "" {
|
||||
require.Nil(t, appErr)
|
||||
} else {
|
||||
require.NotNil(t, appErr)
|
||||
}
|
||||
|
||||
if tc.expectedErrID == "api.user.check_user_login_attempts.too_many_ldap.app_error" {
|
||||
updatedUser, err := th.App.GetUser(ldapUser.Id)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, maxFailedLoginAttempts, updatedUser.FailedAttempts)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckLdapUserPasswordConcurrency(t *testing.T) {
|
||||
th := SetupEnterprise(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
// update config
|
||||
const maxFailedLoginAttempts = 1
|
||||
const concurrentAttempts = 10
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.LdapSettings.MaximumLoginAttempts = maxFailedLoginAttempts
|
||||
*cfg.ServiceSettings.EnableMultifactorAuthentication = true
|
||||
})
|
||||
|
||||
authData := model.NewRandomString(32)
|
||||
|
||||
// create an ldap user by calling createUser
|
||||
ldapUser := &model.User{
|
||||
Email: "ldapuser@mattermost-customer.com",
|
||||
Username: "ldapuser",
|
||||
AuthService: model.UserAuthServiceLdap,
|
||||
AuthData: &authData,
|
||||
EmailVerified: true,
|
||||
}
|
||||
user, appErr := th.App.CreateUser(th.Context, ldapUser)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
// setup MFA
|
||||
secret, appErr := th.App.GenerateMfaSecret(user.Id)
|
||||
require.Nil(t, appErr)
|
||||
err := th.Server.Store().User().UpdateMfaActive(user.Id, true)
|
||||
require.NoError(t, err)
|
||||
err = th.Server.Store().User().UpdateMfaSecret(user.Id, secret.Secret)
|
||||
require.NoError(t, err)
|
||||
|
||||
user, appErr = th.App.GetUser(user.Id)
|
||||
require.Nil(t, appErr)
|
||||
user.AuthData = &authData
|
||||
|
||||
t.Run("validate concurrent failed attempts to bypass checks", func(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
password string
|
||||
mfaToken string
|
||||
expectedErrID string
|
||||
doLoginExpectedErrID string
|
||||
}{
|
||||
{
|
||||
name: "should not breach max. login attempts when password is wrong",
|
||||
password: "wrong password",
|
||||
mfaToken: "",
|
||||
doLoginExpectedErrID: "ent.ldap.do_login.invalid_password.app_error",
|
||||
expectedErrID: "ent.ldap.do_login.invalid_password.app_error",
|
||||
},
|
||||
{
|
||||
name: "should not breach max. login attempts when MFA is wrong",
|
||||
password: "password",
|
||||
mfaToken: "123456",
|
||||
doLoginExpectedErrID: "",
|
||||
expectedErrID: "api.user.check_user_mfa.bad_code.app_error",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
mockLdap := &mocks.LdapInterface{}
|
||||
th.App.Channels().Ldap = mockLdap
|
||||
// Reset login attempts
|
||||
err := th.App.Srv().Store().User().UpdateFailedPasswordAttempts(user.Id, 0)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Capture all concurrent errors
|
||||
appErrs := make([]*model.AppError, concurrentAttempts)
|
||||
|
||||
// Wait to complete the test
|
||||
var completeWG sync.WaitGroup
|
||||
completeWG.Add(concurrentAttempts)
|
||||
|
||||
for i := 0; i < concurrentAttempts; i++ {
|
||||
go func(i int) {
|
||||
defer completeWG.Done()
|
||||
|
||||
if tc.doLoginExpectedErrID == "ent.ldap.do_login.invalid_password.app_error" {
|
||||
mockLdap.Mock.On("DoLogin", mock.AnythingOfType("*request.Context"), mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(nil, &model.AppError{Id: tc.doLoginExpectedErrID})
|
||||
} else {
|
||||
mockLdap.Mock.On("DoLogin", mock.AnythingOfType("*request.Context"), mock.AnythingOfType("string"), tc.password).Return(user, nil)
|
||||
}
|
||||
_, appErrs[i] = th.App.checkLdapUserPasswordAndAllCriteria(th.Context, user, tc.password, tc.mfaToken)
|
||||
}(i)
|
||||
}
|
||||
|
||||
completeWG.Wait()
|
||||
|
||||
expectedErrsCount := 0
|
||||
for i := 0; i < concurrentAttempts; i++ {
|
||||
if appErrs[i].Id == tc.expectedErrID {
|
||||
expectedErrsCount++
|
||||
continue
|
||||
}
|
||||
|
||||
if appErrs[i] != nil {
|
||||
require.Equal(t, "api.user.check_user_login_attempts.too_many_ldap.app_error", appErrs[i].Id, "All other errors should be of too many login attempts only.")
|
||||
}
|
||||
}
|
||||
|
||||
// Password/MFA failure attempts should not breach the maxFailedAttempts
|
||||
// even during concurrent access by the same user.
|
||||
require.Equal(t, maxFailedLoginAttempts, expectedErrsCount)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -80,10 +80,11 @@ type Channels struct {
|
||||
postReminderMut sync.Mutex
|
||||
postReminderTask *model.ScheduledTask
|
||||
|
||||
interruptQuitChan chan struct{}
|
||||
scheduledPostMut sync.Mutex
|
||||
scheduledPostTask *model.ScheduledTask
|
||||
loginAttemptsMut sync.Mutex
|
||||
interruptQuitChan chan struct{}
|
||||
scheduledPostMut sync.Mutex
|
||||
scheduledPostTask *model.ScheduledTask
|
||||
emailLoginAttemptsMut sync.Mutex
|
||||
ldapLoginAttemptsMut sync.Mutex
|
||||
}
|
||||
|
||||
func NewChannels(s *Server) (*Channels, error) {
|
||||
|
||||
@@ -153,11 +153,8 @@ func (a *App) SwitchLdapToEmail(c request.CTX, ldapPassword, code, email, newPas
|
||||
return "", model.NewAppError("SwitchLdapToEmail", "api.user.ldap_to_email.not_available.app_error", nil, "", http.StatusNotImplemented)
|
||||
}
|
||||
|
||||
if err := ldapInterface.CheckPasswordAuthData(c, *user.AuthData, ldapPassword); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if err := a.CheckUserMfa(c, user, code); err != nil {
|
||||
user, err = a.checkLdapUserPasswordAndAllCriteria(c, user, ldapPassword, code)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
|
||||
@@ -2922,3 +2922,12 @@ func (a *App) UserIsFirstAdmin(rctx request.CTX, user *model.User) bool {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *App) ResetPasswordFailedAttempts(c request.CTX, user *model.User) *model.AppError {
|
||||
err := a.Srv().Store().User().UpdateFailedPasswordAttempts(user.Id, 0)
|
||||
if err != nil {
|
||||
return model.NewAppError("ResetPasswordFailedAttempts", "app.user.reset_password_failed_attempts.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Ссылка в новой задаче
Block a user