-
Notifications
You must be signed in to change notification settings - Fork 188
/
AuthenticationEvaluatorImpl.java
471 lines (394 loc) · 19.8 KB
/
AuthenticationEvaluatorImpl.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/**
* Copyright (c) 2016-2017 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.model.impl.security;
import java.util.Collection;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Component;
import com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.model.api.AuthenticationEvaluator;
import com.evolveum.midpoint.model.api.context.AbstractAuthenticationContext;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.crypto.Protector;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.schema.util.MiscSchemaUtil;
import com.evolveum.midpoint.security.api.Authorization;
import com.evolveum.midpoint.security.api.ConnectionEnvironment;
import com.evolveum.midpoint.security.api.MidPointPrincipal;
import com.evolveum.midpoint.security.api.SecurityUtil;
import com.evolveum.midpoint.security.api.UserProfileService;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
/**
* @author semancik
*
*/
public abstract class AuthenticationEvaluatorImpl<C extends AbstractCredentialType, T extends AbstractAuthenticationContext> implements AuthenticationEvaluator<T> {
private static final Trace LOGGER = TraceManager.getTrace(AuthenticationEvaluatorImpl.class);
@Autowired
private Protector protector;
@Autowired
private Clock clock;
// Has to be package-private so the tests can manipulate it
@Autowired
UserProfileService userProfileService;
@Autowired
private SecurityHelper securityHelper;
protected abstract void checkEnteredCredentials(ConnectionEnvironment connEnv, T authCtx);
protected abstract boolean supportsLockoutCheck();
protected abstract boolean suportsAuthzCheck();
protected abstract C getCredential(CredentialsType credentials);
protected abstract void validateCredentialNotNull(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credential);
protected abstract boolean passwordMatches(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C passwordType,
T authCtx);
protected abstract CredentialPolicyType getEffectiveCredentialPolicy(SecurityPolicyType securityPolicy, T authnCtx) throws SchemaException;
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv, T authnCtx)
throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
checkEnteredCredentials(connEnv, authnCtx);
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), true);
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
if (credentials == null) {
recordAuthenticationFailure(principal, connEnv, "no credentials in user");
throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
}
// PasswordType passwordType = credentials.getPassword();
SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
CredentialPolicyType credentialsPolicy = null;
try {
credentialsPolicy = getEffectiveCredentialPolicy(securityPolicy, authnCtx);
} catch (SchemaException e) {
// TODO how to properly hanlde the error????
throw new AuthenticationServiceException("Bad config");
}
if (supportsLockoutCheck()){
// Lockout
if (isLockedOut(getCredential(credentials), credentialsPolicy)) {
recordAuthenticationFailure(principal, connEnv, "password locked-out");
throw new LockedException("web.security.provider.locked");
}
}
if (suportsAuthzCheck()){
// Authorizations
if (!hasAnyAuthorization(principal)) {
recordAuthenticationFailure(principal, connEnv, "no authorizations");
throw new DisabledException("web.security.provider.access.denied");
}
}
// Password age
checkPasswordValidityAndAge(connEnv, principal, getCredential(credentials), credentialsPolicy);
if (passwordMatches(connEnv, principal, getCredential(credentials), authnCtx)) {
recordPasswordAuthenticationSuccess(principal, connEnv, getCredential(credentials), credentialsPolicy);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,
authnCtx.getEnteredCredential(), principal.getAuthorities());
return token;
} else {
recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy, "password mismatch");
throw new BadCredentialsException("web.security.provider.invalid");
}
}
/**
* Special-purpose method used for Web Service authentication based on javax.security callbacks.
*
* In that case there is no reasonable way how to reuse existing methods. Therefore this method is NOT part of the
* AuthenticationEvaluator interface. It is mostly a glue to make the old Java security code work.
*/
public String getAndCheckUserPassword(ConnectionEnvironment connEnv, String enteredUsername)
throws AuthenticationCredentialsNotFoundException, DisabledException, LockedException,
CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException, UsernameNotFoundException {
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true);
UserType userType = principal.getUser();
CredentialsType credentials = userType.getCredentials();
if (credentials == null) {
recordAuthenticationFailure(principal, connEnv, "no credentials in user");
throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
}
PasswordType passwordType = credentials.getPassword();
SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
PasswordCredentialsPolicyType passwordCredentialsPolicy = SecurityUtil.getEffectivePasswordCredentialsPolicy(securityPolicy);
// Lockout
if (isLockedOut(passwordType, passwordCredentialsPolicy)) {
recordAuthenticationFailure(principal, connEnv, "password locked-out");
throw new LockedException("web.security.provider.locked");
}
// Authorizations
if (!hasAnyAuthorization(principal)) {
recordAuthenticationFailure(principal, connEnv, "no authorizations");
throw new AccessDeniedException("web.security.provider.access.denied");
}
// Password age
checkPasswordValidityAndAge(connEnv, principal, passwordType.getValue(), passwordType.getMetadata(), passwordCredentialsPolicy);
return getPassword(connEnv, principal, passwordType.getValue());
}
@Override
public PreAuthenticatedAuthenticationToken authenticateUserPreAuthenticated(ConnectionEnvironment connEnv,
String enteredUsername) {
MidPointPrincipal principal = getAndCheckPrincipal(connEnv, enteredUsername, true);
// Authorizations
if (!hasAnyAuthorization(principal)) {
recordAuthenticationFailure(principal, connEnv, "no authorizations");
throw new AccessDeniedException("web.security.provider.access.denied");
}
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, null, principal.getAuthorities());
recordAuthenticationSuccess(principal, connEnv);
return token;
}
@NotNull
private MidPointPrincipal getAndCheckPrincipal(ConnectionEnvironment connEnv, String enteredUsername, boolean checkActivation) {
if (StringUtils.isBlank(enteredUsername)) {
recordAuthenticationFailure(enteredUsername, connEnv, "no username");
throw new UsernameNotFoundException("web.security.provider.invalid");
}
MidPointPrincipal principal;
try {
principal = userProfileService.getPrincipal(enteredUsername);
} catch (ObjectNotFoundException e) {
recordAuthenticationFailure(enteredUsername, connEnv, "no user");
throw new UsernameNotFoundException("web.security.provider.invalid");
} catch (SchemaException e) {
recordAuthenticationFailure(enteredUsername, connEnv, "schema error");
throw new AccessDeniedException("web.security.provider.invalid");
}
if (principal == null) {
recordAuthenticationFailure(enteredUsername, connEnv, "no user");
throw new UsernameNotFoundException("web.security.provider.invalid");
}
if (checkActivation && !principal.isEnabled()) {
recordAuthenticationFailure(principal, connEnv, "user disabled");
throw new DisabledException("web.security.provider.disabled");
}
return principal;
}
private boolean hasAnyAuthorization(MidPointPrincipal principal) {
Collection<Authorization> authorizations = principal.getAuthorities();
if (authorizations == null || authorizations.isEmpty()){
return false;
}
for (Authorization auth : authorizations){
if (auth.getAction() != null && !auth.getAction().isEmpty()){
return true;
}
}
return false;
}
private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, C credentials,
P passwordCredentialsPolicy) {
if (credentials == null) {
recordAuthenticationFailure(principal, connEnv, "no stored credential value");
throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad");
}
validateCredentialNotNull(connEnv, principal, credentials);
if (passwordCredentialsPolicy == null) {
return;
}
Duration maxAge = passwordCredentialsPolicy.getMaxAge();
if (maxAge != null) {
MetadataType credentialMetedata = credentials.getMetadata();
XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(credentialMetedata);
if (changeTimestamp != null) {
XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
if (clock.isPast(passwordValidUntil)) {
recordAuthenticationFailure(principal, connEnv, "password expired");
throw new CredentialsExpiredException("web.security.provider.password.bad");
}
}
}
}
private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, MetadataType passwordMetadata,
CredentialPolicyType passwordCredentialsPolicy) {
if (protectedString == null) {
recordAuthenticationFailure(principal, connEnv, "no stored password value");
throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
}
if (passwordCredentialsPolicy == null) {
return;
}
Duration maxAge = passwordCredentialsPolicy.getMaxAge();
if (maxAge != null) {
XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(passwordMetadata);
if (changeTimestamp != null) {
XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp, maxAge);
if (clock.isPast(passwordValidUntil)) {
recordAuthenticationFailure(principal, connEnv, "password expired");
throw new CredentialsExpiredException("web.security.provider.password.bad");
}
}
}
}
protected boolean matchDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, String decryptedValue,
String enteredPassword){
return enteredPassword.equals(decryptedValue);
}
protected boolean decryptAndMatch(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString,
String enteredPassword) {
String decryptedPassword = getDecryptedValue(connEnv, principal, protectedString);
return enteredPassword.equals(decryptedPassword);
}
protected String getDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString) {
String decryptedPassword;
if (protectedString.getEncryptedDataType() != null) {
try {
decryptedPassword = protector.decryptString(protectedString);
} catch (EncryptionException e) {
recordAuthenticationFailure(principal, connEnv, "error decrypting password: "+e.getMessage());
throw new AuthenticationServiceException("web.security.provider.unavailable", e);
}
} else {
LOGGER.warn("Authenticating user based on clear value. Please check objects, "
+ "this should not happen. Protected string should be encrypted.");
decryptedPassword = protectedString.getClearValue();
}
return decryptedPassword;
}
private String getPassword(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString) {
String decryptedPassword;
if (protectedString.getEncryptedDataType() != null) {
try {
decryptedPassword = protector.decryptString(protectedString);
} catch (EncryptionException e) {
recordAuthenticationFailure(principal, connEnv, "error decrypting password: "+e.getMessage());
throw new AuthenticationServiceException("web.security.provider.unavailable", e);
}
} else {
LOGGER.warn("Authenticating user based on clear value. Please check objects, "
+ "this should not happen. Protected string should be encrypted.");
decryptedPassword = protectedString.getClearValue();
}
return decryptedPassword;
}
private boolean isLockedOut(AbstractCredentialType credentialsType, CredentialPolicyType credentialsPolicy) {
return isOverFailedLockoutAttempts(credentialsType, credentialsPolicy) && !isLockoutExpired(credentialsType, credentialsPolicy);
}
private boolean isOverFailedLockoutAttempts(AbstractCredentialType credentialsType, CredentialPolicyType credentialsPolicy) {
int failedLogins = credentialsType.getFailedLogins() != null ? credentialsType.getFailedLogins() : 0;
return isOverFailedLockoutAttempts(failedLogins, credentialsPolicy);
}
private boolean isOverFailedLockoutAttempts(int failedLogins, CredentialPolicyType credentialsPolicy) {
return credentialsPolicy != null && credentialsPolicy.getLockoutMaxFailedAttempts() != null &&
credentialsPolicy.getLockoutMaxFailedAttempts() > 0 && failedLogins >= credentialsPolicy.getLockoutMaxFailedAttempts();
}
private boolean isLockoutExpired(AbstractCredentialType credentialsType, CredentialPolicyType credentialsPolicy) {
Duration lockoutDuration = credentialsPolicy.getLockoutDuration();
if (lockoutDuration == null) {
return false;
}
LoginEventType lastFailedLogin = credentialsType.getLastFailedLogin();
if (lastFailedLogin == null) {
return true;
}
XMLGregorianCalendar lastFailedLoginTimestamp = lastFailedLogin.getTimestamp();
if (lastFailedLoginTimestamp == null) {
return true;
}
XMLGregorianCalendar lockedUntilTimestamp = XmlTypeConverter.addDuration(lastFailedLoginTimestamp, lockoutDuration);
return clock.isPast(lockedUntilTimestamp);
}
private void recordPasswordAuthenticationSuccess(MidPointPrincipal principal, ConnectionEnvironment connEnv,
C passwordType, CredentialPolicyType passwordCredentialsPolicy) {
Integer failedLogins = passwordType.getFailedLogins();
if (failedLogins != null && failedLogins > 0) {
passwordType.setFailedLogins(0);
}
LoginEventType event = new LoginEventType();
event.setTimestamp(clock.currentTimeXMLGregorianCalendar());
event.setFrom(connEnv.getRemoteHost());
passwordType.setPreviousSuccessfulLogin(passwordType.getLastSuccessfulLogin());
passwordType.setLastSuccessfulLogin(event);
ActivationType activation = principal.getUser().getActivation();
if (activation != null) {
activation.setLockoutStatus(LockoutStatusType.NORMAL);
activation.setLockoutExpirationTimestamp(null);
}
userProfileService.updateUser(principal);
recordAuthenticationSuccess(principal, connEnv);
}
private void recordAuthenticationSuccess(@NotNull MidPointPrincipal principal, @NotNull ConnectionEnvironment connEnv) {
securityHelper.auditLoginSuccess(principal.getUser(), connEnv);
}
private void recordPasswordAuthenticationFailure(@NotNull MidPointPrincipal principal, @NotNull ConnectionEnvironment connEnv,
@NotNull C passwordType, CredentialPolicyType passwordCredentialsPolicy, String reason) {
Integer failedLogins = passwordType.getFailedLogins();
LoginEventType lastFailedLogin = passwordType.getLastFailedLogin();
XMLGregorianCalendar lastFailedLoginTs = null;
if (lastFailedLogin != null) {
lastFailedLoginTs = lastFailedLogin.getTimestamp();
}
if (passwordCredentialsPolicy != null) {
Duration lockoutFailedAttemptsDuration = passwordCredentialsPolicy.getLockoutFailedAttemptsDuration();
if (lockoutFailedAttemptsDuration != null) {
if (lastFailedLoginTs != null) {
XMLGregorianCalendar failedLoginsExpirationTs = XmlTypeConverter.addDuration(lastFailedLoginTs, lockoutFailedAttemptsDuration);
if (clock.isPast(failedLoginsExpirationTs)) {
failedLogins = 0;
}
}
}
}
if (failedLogins == null) {
failedLogins = 1;
} else {
failedLogins++;
}
passwordType.setFailedLogins(failedLogins);
LoginEventType event = new LoginEventType();
event.setTimestamp(clock.currentTimeXMLGregorianCalendar());
event.setFrom(connEnv.getRemoteHost());
passwordType.setLastFailedLogin(event);
ActivationType activationType = principal.getUser().getActivation();
if (failedLogins != null && isOverFailedLockoutAttempts(failedLogins, passwordCredentialsPolicy)) {
if (activationType == null) {
activationType = new ActivationType();
principal.getUser().setActivation(activationType);
}
activationType.setLockoutStatus(LockoutStatusType.LOCKED);
XMLGregorianCalendar lockoutExpirationTs = null;
if (passwordCredentialsPolicy != null) {
Duration lockoutDuration = passwordCredentialsPolicy.getLockoutDuration();
if (lockoutDuration != null) {
lockoutExpirationTs = XmlTypeConverter.addDuration(event.getTimestamp(), lockoutDuration);
}
}
activationType.setLockoutExpirationTimestamp(lockoutExpirationTs);
}
userProfileService.updateUser(principal);
recordAuthenticationFailure(principal, connEnv, reason);
}
protected void recordAuthenticationFailure(@NotNull MidPointPrincipal principal, ConnectionEnvironment connEnv, String reason) {
securityHelper.auditLoginFailure(principal.getUsername(), principal.getUser(), connEnv, reason);
}
protected void recordAuthenticationFailure(String username, ConnectionEnvironment connEnv, String reason) {
securityHelper.auditLoginFailure(username, null, connEnv, reason);
}
}