/
UserPassAuthenticatingRealm.java
308 lines (280 loc) · 13.3 KB
/
UserPassAuthenticatingRealm.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*******************************************************************************
* Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.service.authentication.shiro.realm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.KapuaRuntimeException;
import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.service.account.Account;
import org.eclipse.kapua.service.account.AccountService;
import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials;
import org.eclipse.kapua.service.authentication.credential.Credential;
import org.eclipse.kapua.service.authentication.credential.CredentialListResult;
import org.eclipse.kapua.service.authentication.credential.CredentialService;
import org.eclipse.kapua.service.authentication.credential.CredentialStatus;
import org.eclipse.kapua.service.authentication.credential.CredentialType;
import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService;
import org.eclipse.kapua.service.authentication.shiro.UsernamePasswordCredentialsImpl;
import org.eclipse.kapua.service.authentication.shiro.exceptions.ExpiredAccountException;
import org.eclipse.kapua.service.authentication.shiro.exceptions.TemporaryLockedAccountException;
import org.eclipse.kapua.service.user.User;
import org.eclipse.kapua.service.user.UserService;
import org.eclipse.kapua.service.user.UserStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Map;
/**
* {@link UsernamePasswordCredentials} based {@link AuthenticatingRealm} implementation.
* <p>
* since 1.0
*/
public class UserPassAuthenticatingRealm extends AuthenticatingRealm {
private static final Logger logger = LoggerFactory.getLogger(UserPassAuthenticatingRealm.class);
private static final KapuaLocator LOCATOR = KapuaLocator.getInstance();
/**
* Realm name
*/
public static final String REALM_NAME = "userPassAuthenticatingRealm";
/**
* Constructor
*
* @throws KapuaException
*/
public UserPassAuthenticatingRealm() throws KapuaException {
setName(REALM_NAME);
CredentialsMatcher credentialsMather = new UserPassCredentialsMatcher();
setCredentialsMatcher(credentialsMather);
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
//
// Extract credentials
UsernamePasswordCredentialsImpl token = (UsernamePasswordCredentialsImpl) authenticationToken;
String tokenUsername = token.getUsername();
//
// Get Services
UserService userService;
AccountService accountService;
CredentialService credentialService;
try {
userService = LOCATOR.getService(UserService.class);
accountService = LOCATOR.getService(AccountService.class);
credentialService = LOCATOR.getService(CredentialService.class);
} catch (KapuaRuntimeException kre) {
throw new ShiroException("Error while getting services!", kre);
}
//
// Get the associated user by name
final User user;
try {
user = KapuaSecurityUtils.doPrivileged(() -> userService.findByName(tokenUsername));
} catch (AuthenticationException ae) {
throw ae;
} catch (Exception e) {
throw new ShiroException("Error while find user!", e);
}
// Check existence
if (user == null) {
throw new UnknownAccountException();
}
// Check disabled
if (UserStatus.DISABLED.equals(user.getStatus())) {
throw new DisabledAccountException();
}
// Check if expired
if (user.getExpirationDate() != null && !user.getExpirationDate().after(new Date())) {
throw new ExpiredCredentialsException();
}
//
// Find account
final Account account;
try {
account = KapuaSecurityUtils.doPrivileged(() -> accountService.find(user.getScopeId()));
} catch (AuthenticationException ae) {
throw ae;
} catch (Exception e) {
throw new ShiroException("Error while find account!", e);
}
// Check existence
if (account == null) {
throw new UnknownAccountException();
}
// Check account expired
if (account.getExpirationDate() != null && !account.getExpirationDate().after(new Date())) {
throw new ExpiredAccountException(account.getExpirationDate());
}
//
// Find credentials
// FIXME: manage multiple credentials and multiple credentials type
Credential credential;
try {
credential = KapuaSecurityUtils.doPrivileged(() -> {
CredentialListResult credentialList = credentialService.findByUserId(user.getScopeId(), user.getId());
if (credentialList != null && !credentialList.isEmpty()) {
Credential credentialMatched = null;
for (Credential c : credentialList.getItems()) {
if (CredentialType.PASSWORD.equals(c.getCredentialType())) {
credentialMatched = c;
break;
}
}
return credentialMatched;
} else {
return null;
}
});
} catch (AuthenticationException ae) {
throw ae;
} catch (Exception e) {
throw new ShiroException("Error while find credentials!", e);
}
// Check existence
if (credential == null) {
throw new UnknownAccountException();
}
// Check credential disabled
if (CredentialStatus.DISABLED.equals(credential.getStatus())) {
throw new DisabledAccountException();
}
// Check if credential expired
if (credential.getExpirationDate() != null && !credential.getExpirationDate().after(new Date())) {
throw new ExpiredCredentialsException();
}
// Check if lockout policy is blocking credential
Map<String, Object> credentialServiceConfig;
try {
credentialServiceConfig = KapuaSecurityUtils.doPrivileged(() -> credentialService.getConfigValues(account.getId()));
boolean lockoutPolicyEnabled = (boolean) credentialServiceConfig.get("lockoutPolicy.enabled");
if (lockoutPolicyEnabled) {
Date now = new Date();
if (credential.getLockoutReset() != null && now.before(credential.getLockoutReset())) {
throw new TemporaryLockedAccountException(credential.getLockoutReset());
}
}
} catch (KapuaException kex) {
throw new ShiroException("Error while checking lockout policy", kex);
}
//
// BuildAuthenticationInfo
return new LoginAuthenticationInfo(getName(),
account,
user,
credential,
credentialServiceConfig);
}
@Override
protected void assertCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info)
throws AuthenticationException {
LoginAuthenticationInfo kapuaInfo = (LoginAuthenticationInfo) info;
CredentialService credentialService = LOCATOR.getService(CredentialService.class);
MfaOptionService mfaOptionService = LOCATOR.getService(MfaOptionService.class);
KapuaId userId = kapuaInfo.getUser().getId();
KapuaId scopeId = kapuaInfo.getUser().getScopeId();
boolean hasMfa = false;
boolean checkedUsernameAndPasswordMatch = false;
boolean userPasswordMatch = true;
try {
if (KapuaSecurityUtils.doPrivileged(() -> mfaOptionService.findByUserId(userId, scopeId) != null)) {
hasMfa = true;
}
} catch (KapuaException e) {
logger.warn(e.toString());
throw new ShiroException("Error while find user!", e);
}
try {
if (hasMfa) {
super.assertCredentialsMatch(authcToken, info);
} else {
userPasswordMatch = ((UserPassCredentialsMatcher) getCredentialsMatcher()).doUsernameAndPasswordMatch(authcToken, info);
checkedUsernameAndPasswordMatch = true;
if (!userPasswordMatch) {
String msg = "Submitted credentials for token [" + authcToken + "] did not match the expected credentials.";
throw new IncorrectCredentialsException(msg);
}
}
} catch (AuthenticationException authenticationEx) {
try {
Credential failedCredential = (Credential) kapuaInfo.getCredentials();
userPasswordMatch = checkedUsernameAndPasswordMatch ?
userPasswordMatch : ((UserPassCredentialsMatcher) getCredentialsMatcher()).doUsernameAndPasswordMatch(authcToken, info);
final boolean hasMfaAndUserPasswordMatch = hasMfa && userPasswordMatch;
KapuaSecurityUtils.doPrivileged(() -> {
Map<String, Object> credentialServiceConfig = kapuaInfo.getCredentialServiceConfig();
boolean lockoutPolicyEnabled = (boolean) credentialServiceConfig.get("lockoutPolicy.enabled");
if (lockoutPolicyEnabled) {
Date now = new Date();
int resetAfterSeconds = (int)credentialServiceConfig.get("lockoutPolicy.resetAfter");
Date firstLoginFailure;
boolean resetAttempts = failedCredential.getFirstLoginFailure() == null ||
now.after(failedCredential.getLoginFailuresReset()) ||
hasMfaAndUserPasswordMatch;
if (resetAttempts) {
firstLoginFailure = now;
failedCredential.setLoginFailures(1);
} else {
firstLoginFailure = failedCredential.getFirstLoginFailure();
failedCredential.setLoginFailures(failedCredential.getLoginFailures() + 1);
}
Date loginFailureWindowExpiration = new Date(firstLoginFailure.getTime() + (resetAfterSeconds * 1000));
failedCredential.setFirstLoginFailure(firstLoginFailure);
failedCredential.setLoginFailuresReset(loginFailureWindowExpiration);
int maxLoginFailures = (int)credentialServiceConfig.get("lockoutPolicy.maxFailures");
if (failedCredential.getLoginFailures() >= maxLoginFailures) {
long lockoutDuration = (int)credentialServiceConfig.get("lockoutPolicy.lockDuration");
Date resetDate = new Date(now.getTime() + (lockoutDuration * 1000));
failedCredential.setLockoutReset(resetDate);
}
}
credentialService.update(failedCredential);
});
} catch (KapuaException kex) {
throw new ShiroException("Error while updating lockout policy", kex);
}
throw authenticationEx;
}
Credential credential = (Credential) kapuaInfo.getCredentials();
credential.setFirstLoginFailure(null);
credential.setLoginFailuresReset(null);
credential.setLockoutReset(null);
credential.setLoginFailures(0);
try {
KapuaSecurityUtils.doPrivileged(() -> credentialService.update(credential));
} catch (KapuaException kex) {
throw new ShiroException("Error while updating lockout policy", kex);
}
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("scopeId", scopeId);
session.setAttribute("userId", userId);
}
@Override
public boolean supports(AuthenticationToken authenticationToken) {
return authenticationToken instanceof UsernamePasswordCredentialsImpl;
}
}