/
SecurityDomain.java
1266 lines (1133 loc) · 54.2 KB
/
SecurityDomain.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* JBoss, Home of Professional Open Source
* Copyright 2013 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 org.wildfly.security.auth.server;
import static java.security.AccessController.doPrivileged;
import static java.util.Collections.emptyMap;
import static org.wildfly.common.Assert.checkNotNullParam;
import static org.wildfly.security.auth.server._private.ElytronMessages.log;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import org.wildfly.common.Assert;
import org.wildfly.common.function.ExceptionBiFunction;
import org.wildfly.common.function.ExceptionFunction;
import org.wildfly.security.auth.SupportLevel;
import org.wildfly.security.auth.principal.AnonymousPrincipal;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.auth.principal.RealmNestedPrincipal;
import org.wildfly.security.auth.server.event.SecurityEvent;
import org.wildfly.security.authz.AuthorizationIdentity;
import org.wildfly.security.authz.PermissionMapper;
import org.wildfly.security.authz.RoleDecoder;
import org.wildfly.security.authz.RoleMapper;
import org.wildfly.security.authz.Roles;
import org.wildfly.security.credential.BearerTokenCredential;
import org.wildfly.security.credential.Credential;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.evidence.BearerTokenEvidence;
import org.wildfly.security.evidence.Evidence;
import org.wildfly.security.evidence.PasswordGuessEvidence;
import org.wildfly.security.password.interfaces.ClearPassword;
import org.wildfly.security.permission.ElytronPermission;
import org.wildfly.security.permission.PermissionVerifier;
/**
* A security domain. Security domains encapsulate a set of security policies.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a>
*/
public final class SecurityDomain {
private static final ConcurrentHashMap<ClassLoader, SecurityDomain> CLASS_LOADER_DOMAIN_MAP = new ConcurrentHashMap<>();
private static final RealmInfo EMPTY_REALM_INFO = new RealmInfo();
static final ElytronPermission AUTHENTICATE = ElytronPermission.forName("authenticate");
static final ElytronPermission CREATE_SECURITY_DOMAIN = ElytronPermission.forName("createSecurityDomain");
static final ElytronPermission REGISTER_SECURITY_DOMAIN = ElytronPermission.forName("registerSecurityDomain");
static final ElytronPermission GET_SECURITY_DOMAIN = ElytronPermission.forName("getSecurityDomain");
static final ElytronPermission UNREGISTER_SECURITY_DOMAIN = ElytronPermission.forName("unregisterSecurityDomain");
static final ElytronPermission CREATE_AUTH_CONTEXT = ElytronPermission.forName("createServerAuthenticationContext");
static final ElytronPermission GET_IDENTITY = ElytronPermission.forName("getIdentity");
static final ElytronPermission GET_IDENTITY_FOR_UPDATE = ElytronPermission.forName("getIdentityForUpdate");
static final ElytronPermission CREATE_AD_HOC_IDENTITY = ElytronPermission.forName("createAdHocIdentity");
static final ElytronPermission HANDLE_SECURITY_EVENT = ElytronPermission.forName("handleSecurityEvent");
private final Map<String, RealmInfo> realmMap;
private final String defaultRealmName;
private final Function<Principal, Principal> preRealmPrincipalRewriter;
private final RealmMapper realmMapper;
private final Function<Principal, Principal> postRealmPrincipalRewriter;
private final ThreadLocal<Supplier<SecurityIdentity>> currentSecurityIdentity;
private final RoleMapper roleMapper;
private final SecurityIdentity anonymousIdentity;
private final PermissionMapper permissionMapper;
private final Map<String, RoleMapper> categoryRoleMappers;
private final UnaryOperator<SecurityIdentity> securityIdentityTransformer;
private final Predicate<SecurityDomain> trustedSecurityDomain;
private final Consumer<SecurityEvent> securityEventListener;
private final Function<Evidence, Principal> evidenceDecoder;
private final RoleDecoder roleDecoder;
SecurityDomain(Builder builder, final LinkedHashMap<String, RealmInfo> realmMap) {
this.realmMap = realmMap;
this.defaultRealmName = builder.defaultRealmName;
this.preRealmPrincipalRewriter = builder.principalDecoder.andThen(builder.preRealmRewriter);
this.realmMapper = builder.realmMapper;
this.roleMapper = builder.roleMapper;
this.permissionMapper = builder.permissionMapper;
this.postRealmPrincipalRewriter = builder.postRealmRewriter;
this.securityIdentityTransformer = builder.securityIdentityTransformer;
this.trustedSecurityDomain = builder.trustedSecurityDomain;
this.securityEventListener = builder.securityEventListener;
this.evidenceDecoder = builder.evidenceDecoder;
this.roleDecoder = builder.roleDecoder;
final Map<String, RoleMapper> originalRoleMappers = builder.categoryRoleMappers;
final Map<String, RoleMapper> copiedRoleMappers;
if (originalRoleMappers.isEmpty()) {
copiedRoleMappers = emptyMap();
} else if (originalRoleMappers.size() == 1) {
final Map.Entry<String, RoleMapper> entry = originalRoleMappers.entrySet().iterator().next();
copiedRoleMappers = Collections.singletonMap(entry.getKey(), entry.getValue());
} else {
copiedRoleMappers = new LinkedHashMap<>(originalRoleMappers);
}
this.categoryRoleMappers = copiedRoleMappers;
// todo configurable
anonymousIdentity = Assert.assertNotNull(securityIdentityTransformer.apply(new SecurityIdentity(this, AnonymousPrincipal.getInstance(), EMPTY_REALM_INFO, AuthorizationIdentity.EMPTY, copiedRoleMappers, IdentityCredentials.NONE, IdentityCredentials.NONE)));
currentSecurityIdentity = ThreadLocal.withInitial(() -> anonymousIdentity);
}
/**
* Register this {@link SecurityDomain} with the specified {@link ClassLoader}.
*
* Registration with enabled security manager requires {@code registerSecurityDomain} {@link ElytronPermission}.
*
* @throws IllegalStateException If a {@link SecurityDomain} is already associated with the specified {@link ClassLoader}.
* @param classLoader the non {@code null} {@link ClassLoader} to associate this {@link SecurityDomain} with.
*/
public void registerWithClassLoader(ClassLoader classLoader) {
checkNotNullParam("classLoader", classLoader);
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(REGISTER_SECURITY_DOMAIN);
}
final SecurityDomain classLoaderDomain = CLASS_LOADER_DOMAIN_MAP.putIfAbsent(classLoader, this);
if ((classLoaderDomain != null) && (classLoaderDomain != this)) {
throw log.classLoaderSecurityDomainExists();
}
}
/**
* Get the {@link SecurityDomain} associated with the context class loader of the calling Thread or {@code null} if one is
* not associated.
*
* Obtaining security domain with enabled security manager requires {@code getSecurityDomain} {@link ElytronPermission}.
*
* @return the {@link SecurityDomain} associated with the context class loader of the calling Thread or {@code null} if one
* is not associated.
*/
public static SecurityDomain getCurrent() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(GET_SECURITY_DOMAIN);
}
final Thread currentThread = Thread.currentThread();
ClassLoader classLoader;
if (sm != null) {
classLoader = doPrivileged((PrivilegedAction<ClassLoader>) currentThread::getContextClassLoader);
} else {
classLoader = currentThread.getContextClassLoader();
}
return classLoader != null ? CLASS_LOADER_DOMAIN_MAP.get(classLoader) : null;
}
/**
* Get the security domain associated with the given identity.
*
* Obtaining security domain with enabled security manager requires {@code getSecurityDomain} {@link ElytronPermission}.
*
* @param identity the security identity (must not be {@code null})
* @return the identity's security domain (not {@code null})
*/
public static SecurityDomain forIdentity(SecurityIdentity identity) {
checkNotNullParam("identity", identity);
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(GET_SECURITY_DOMAIN);
}
return identity.getSecurityDomain();
}
/**
* Unregister any {@link SecurityDomain} associated with the specified {@link ClassLoader}.
*
* Unregistration with enabled security manager requires {@code unregisterSecurityDomain} {@link ElytronPermission}.
*
* @param classLoader the non {@code null} {@link ClassLoader} to clear any {@link SecurityDomain} association.
*/
public static void unregisterClassLoader(ClassLoader classLoader) {
checkNotNullParam("classLoader", classLoader);
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(UNREGISTER_SECURITY_DOMAIN);
}
CLASS_LOADER_DOMAIN_MAP.remove(classLoader);
}
/**
* Create a new security domain builder.
*
* @return the builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Create a new authentication context for this security domain which can be used to carry out a single authentication
* operation.
*
* Calling with enabled security manager requires {@code createServerAuthenticationContext} {@link ElytronPermission}.
*
* @return the new authentication context
*/
public ServerAuthenticationContext createNewAuthenticationContext() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(CREATE_AUTH_CONTEXT);
}
return new ServerAuthenticationContext(this, MechanismConfigurationSelector.constantSelector(MechanismConfiguration.EMPTY));
}
/**
* Create a new authentication context for this security domain which can be used to carry out a single authentication
* operation.
*
* Calling with enabled security manager requires {@code createServerAuthenticationContext} {@link ElytronPermission}.
*
* @param mechanismConfigurationSelector the selector to use to obtain the mechanism configuration
* @return the new authentication context
*/
public ServerAuthenticationContext createNewAuthenticationContext(MechanismConfigurationSelector mechanismConfigurationSelector) {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(CREATE_AUTH_CONTEXT);
}
return new ServerAuthenticationContext(this, mechanismConfigurationSelector);
}
ServerAuthenticationContext createNewAuthenticationContext(SecurityIdentity capturedIdentity, MechanismConfigurationSelector mechanismConfigurationSelector) {
assert capturedIdentity.getSecurityDomain() == this;
return new ServerAuthenticationContext(capturedIdentity, mechanismConfigurationSelector);
}
/**
* Perform an authentication based on {@link Evidence} alone.
*
* Note: It is the caller's responsibility to destroy any evidence passed into this method.
*
* @param evidence the {@link Evidence} to use for authentication.
* @return the authenticated identity.
* @throws RealmUnavailableException if the requires {@link SecurityRealm} is not available.
* @throws SecurityException if authentication fails.
*/
public SecurityIdentity authenticate(Evidence evidence) throws RealmUnavailableException, SecurityException {
return authenticate((Principal) null, evidence);
}
/**
* Perform an authentication based on {@link Evidence} for the specified identity name.
*
* Note: It is the caller's responsibility to destroy any evidence passed into this method.
*
* @param name the name of the identity to authenticate or {@code null} if the identity is to be derived from the evidence.
* @param evidence the {@link Evidence} to use for authentication.
* @return the authenticated identity.
* @throws RealmUnavailableException if the requires {@link SecurityRealm} is not available.
* @throws SecurityException if authentication fails.
*/
public SecurityIdentity authenticate(String name, Evidence evidence) throws RealmUnavailableException, SecurityException {
return authenticate(name != null ? new NamePrincipal(name) : null, evidence);
}
/**
* Perform an authentication based on {@link Evidence} for the specified identity {@link Principal}.
*
* Note: It is the caller's responsibility to destroy any evidence passed into this method.
*
* Calling with enabled security manager requires {@code authenticate} {@link ElytronPermission}.
*
* @param principal the principal of the identity to authenticate or {@code null} if the identity is to be derived from the evidence.
* @param evidence the {@link Evidence} to use for authentication.
* @return the authenticated identity.
* @throws RealmUnavailableException if the requires {@link SecurityRealm} is not available.
* @throws SecurityException if authentication fails.
*/
public SecurityIdentity authenticate(Principal principal, Evidence evidence) throws RealmUnavailableException, SecurityException {
final SecurityManager securityManager = System.getSecurityManager();
if (securityManager != null) {
securityManager.checkPermission(AUTHENTICATE);
}
try (final ServerAuthenticationContext serverAuthenticationContext = new ServerAuthenticationContext(this,
MechanismConfigurationSelector.constantSelector(MechanismConfiguration.EMPTY))) {
if (principal != null)
serverAuthenticationContext.setAuthenticationPrincipal(principal);
if (serverAuthenticationContext.verifyEvidence(evidence)) {
if (serverAuthenticationContext.authorize()) {
if (evidence instanceof PasswordGuessEvidence) {
PasswordGuessEvidence passwordGuessEvidence = PasswordGuessEvidence.class.cast(evidence);
serverAuthenticationContext.addPrivateCredential(new PasswordCredential(
ClearPassword.createRaw(ClearPassword.ALGORITHM_CLEAR, passwordGuessEvidence.getGuess())));
} else if (evidence instanceof BearerTokenEvidence) {
BearerTokenEvidence tokenEvidence = BearerTokenEvidence.class.cast(evidence);
serverAuthenticationContext.addPrivateCredential(new BearerTokenCredential(tokenEvidence.getToken()));
} else {
log.tracef(
"Evidence [%s] does not map to a supported credential type. Credentials are not available from authorized identity and identity propagation may not work",
evidence.getClass().getName());
}
serverAuthenticationContext.succeed();
return serverAuthenticationContext.getAuthorizedIdentity();
} else {
serverAuthenticationContext.fail();
throw log.authenticationFailedAuthorization();
}
} else {
serverAuthenticationContext.fail();
throw log.authenticationFailedEvidenceVerification();
}
}
}
/**
* Look up a {@link RealmIdentity} by name by wrapping the name in a {@link NamePrincipal} and calling {@link #getIdentity(Principal)}.
* The returned identity must be {@linkplain RealmIdentity#dispose() disposed}.
*
* @param name the name to map (must not be {@code null})
* @return the identity for the name (not {@code null}, may be non-existent)
* @throws RealmUnavailableException if the realm is not able to perform the mapping
* @throws IllegalArgumentException if the name is not valid
* @throws SecurityException if the caller is not authorized to perform the operation
*/
public RealmIdentity getIdentity(String name) throws RealmUnavailableException {
Assert.checkNotNullParam("name", name);
return getIdentity(new NamePrincipal(name));
}
/**
* Look up a {@link RealmIdentity} by principal.
* The returned identity must be {@linkplain RealmIdentity#dispose() disposed}.
*
* Calling with enabled security manager requires {@code getIdentity} {@link ElytronPermission}.
*
* @param principal the principal to map (must not be {@code null})
* @return the identity for the name (not {@code null}, may be non-existent)
* @throws IllegalArgumentException if the principal could not be successfully decoded to a name
* @throws RealmUnavailableException if the realm is not able to perform the mapping
* @throws SecurityException if the caller is not authorized to perform the operation
*/
public RealmIdentity getIdentity(Principal principal) throws RealmUnavailableException, IllegalArgumentException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(GET_IDENTITY);
}
return getIdentityPrivileged(principal, SecurityRealm.class, SecurityRealm::getRealmIdentity, () -> RealmIdentity.NON_EXISTENT, () -> RealmIdentity.ANONYMOUS);
}
/**
* Look up a {@link ModifiableRealmIdentity} by principal.
* The returned identity must be {@linkplain RealmIdentity#dispose() disposed}.
*
* Calling with enabled security manager requires {@code getIdentityForUpdate} {@link ElytronPermission}.
*
* @param principal the principal to map (must not be {@code null})
* @return the identity for the name (not {@code null}, may be non-existent)
* @throws IllegalArgumentException if the principal could not be successfully decoded to a name
* @throws RealmUnavailableException if the realm is not able to perform the mapping
* @throws SecurityException if the caller is not authorized to perform the operation
*/
public ModifiableRealmIdentity getIdentityForUpdate(Principal principal) throws RealmUnavailableException, IllegalArgumentException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(GET_IDENTITY_FOR_UPDATE);
}
return getIdentityPrivileged(principal, ModifiableSecurityRealm.class, ModifiableSecurityRealm::getRealmIdentityForUpdate, () -> ModifiableRealmIdentity.NON_EXISTENT, () -> ModifiableRealmIdentity.NON_EXISTENT);
}
/**
* Get a function which can be used to look up principals without a security manager permission check.
* All returned identities must be {@linkplain RealmIdentity#dispose() disposed}.
*
* Calling with enabled security manager requires {@code getIdentity} {@link ElytronPermission}.
*
* @return the lookup function (not {@code null})
* @throws SecurityException if the caller is not authorized to perform the operation
*/
public ExceptionFunction<Principal, RealmIdentity, RealmUnavailableException> getIdentityLookupFunction() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(GET_IDENTITY);
}
return p -> getIdentityPrivileged(p, SecurityRealm.class, SecurityRealm::getRealmIdentity, () -> RealmIdentity.NON_EXISTENT, () -> RealmIdentity.ANONYMOUS);
}
/**
* Get a function which can be used to look up principals for update without a security manager permission check.
* All returned identities must be {@linkplain RealmIdentity#dispose() disposed}.
* Calling with enabled security manager requires {@code getIdentityForUpdate} {@link ElytronPermission}.
*
* @return the lookup function (not {@code null})
* @throws SecurityException if the caller is not authorized to perform the operation
*/
public ExceptionFunction<Principal, ModifiableRealmIdentity, RealmUnavailableException> getIdentityLookupForUpdateFunction() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(GET_IDENTITY_FOR_UPDATE);
}
return p -> getIdentityPrivileged(p, ModifiableSecurityRealm.class, ModifiableSecurityRealm::getRealmIdentityForUpdate, () -> ModifiableRealmIdentity.NON_EXISTENT, () -> ModifiableRealmIdentity.NON_EXISTENT);
}
<I, R extends SecurityRealm> I getIdentityPrivileged(Principal principal, Class<R> realmType, ExceptionBiFunction<R, Principal, I, RealmUnavailableException> fn, Supplier<I> nonExistent, Supplier<I> anonymous) throws RealmUnavailableException {
Assert.checkNotNullParam("principal", principal);
if (principal instanceof AnonymousPrincipal) {
return anonymous.get();
}
if (principal instanceof RealmNestedPrincipal) {
final RealmNestedPrincipal realmNestedPrincipal = (RealmNestedPrincipal) principal;
final SecurityRealm securityRealm = getRealmInfo(realmNestedPrincipal.getRealmName()).getSecurityRealm();
if (realmType.isInstance(securityRealm)) {
return fn.apply(realmType.cast(securityRealm), realmNestedPrincipal.getNestedPrincipal());
} else {
return nonExistent.get();
}
}
Principal preRealmPrincipal = preRealmPrincipalRewriter.apply(principal);
if (preRealmPrincipal == null) {
throw log.invalidName();
}
String realmName = mapRealmName(preRealmPrincipal, null);
RealmInfo realmInfo = getRealmInfo(realmName);
SecurityRealm securityRealm = realmInfo.getSecurityRealm();
assert securityRealm != null;
Principal postRealmPrincipal = postRealmPrincipalRewriter.apply(preRealmPrincipal);
if (postRealmPrincipal == null) {
throw log.invalidName();
}
Principal realmRewrittenPrincipal = realmInfo.getPrincipalRewriter().apply(postRealmPrincipal);
if (realmRewrittenPrincipal == null) {
throw log.invalidName();
}
log.tracef("Principal mapping: [%s], pre-realm rewritten: [%s], realm name: [%s], post realm rewritten: [%s], realm rewritten: [%s]",
principal, preRealmPrincipal, realmName, postRealmPrincipal, realmRewrittenPrincipal);
if (realmType.isInstance(securityRealm)) {
return fn.apply(realmType.cast(securityRealm), realmRewrittenPrincipal);
} else {
return nonExistent.get();
}
}
SecurityRealm getRealm(final String realmName) {
return getRealmInfo(realmName).getSecurityRealm();
}
RealmInfo getRealmInfo(final String realmName) {
RealmInfo realmInfo = this.realmMap.get(realmName);
if (realmInfo == null) {
realmInfo = this.realmMap.get(this.defaultRealmName);
}
if (realmInfo == null) {
log.tracef("Unable to obtain RealmInfo [%s] and no default set - using empty", realmName);
realmInfo = EMPTY_REALM_INFO;
}
return realmInfo;
}
Collection<RealmInfo> getRealmInfos() {
return realmMap.values();
}
/**
* Determine whether a credential of the given type and algorithm is definitely obtainable, possibly obtainable (for
* some identities), or definitely not obtainable.
*
* Credential is {@link SupportLevel#SUPPORTED}, if it is supported by all realms of the domain.
* Credential is {@link SupportLevel#POSSIBLY_SUPPORTED} if it is supported or possibly supported by at least one realm of the domain.
* Otherwise it is {@link SupportLevel#UNSUPPORTED}.
*
* @param credentialType the exact credential type (must not be {@code null})
* @param algorithmName the algorithm name, or {@code null} if any algorithm is acceptable or the credential type does
* not support algorithm names
* @param parameterSpec the algorithm parameters to match, or {@code null} if any parameters are acceptable or the credential type
* does not support algorithm parameters
* @return the level of support for this credential
*/
public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) {
return getSupportLevel(r -> {
try {
return r.getCredentialAcquireSupport(credentialType, algorithmName, parameterSpec);
} catch (RealmUnavailableException e) {
log.trace("Failed to obtain credential acquire support from realm", e);
return null;
}
});
}
/**
* Determine whether a credential of the given type and algorithm is definitely obtainable, possibly obtainable (for
* some identities), or definitely not obtainable.
*
* Credential is {@link SupportLevel#SUPPORTED}, if it is supported by all realms of the domain.
* Credential is {@link SupportLevel#POSSIBLY_SUPPORTED} if it is supported or possibly supported by at least one realm of the domain.
* Otherwise it is {@link SupportLevel#UNSUPPORTED}.
*
* @param credentialType the exact credential type (must not be {@code null})
* @param algorithmName the algorithm name, or {@code null} if any algorithm is acceptable or the credential type does
* not support algorithm names
* @return the level of support for this credential
*/
public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType, String algorithmName) {
return getCredentialAcquireSupport(credentialType, algorithmName, null);
}
/**
* Determine whether a credential of the given type and algorithm is definitely obtainable, possibly obtainable (for
* some identities), or definitely not obtainable.
*
* Credential is {@link SupportLevel#SUPPORTED}, if it is supported by all realms of the domain.
* Credential is {@link SupportLevel#POSSIBLY_SUPPORTED} if it is supported or possibly supported by at least one realm of the domain.
* Otherwise it is {@link SupportLevel#UNSUPPORTED}.
*
* @param credentialType the exact credential type (must not be {@code null})
* @return the level of support for this credential
*/
public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType) {
return getCredentialAcquireSupport(credentialType, null);
}
/**
* Determine whether a given type of evidence is definitely verifiable, possibly verifiable (for some identities),
* or definitely not verifiable.
*
* Evidence is {@link SupportLevel#SUPPORTED}, if it is supported by all realms of the domain.
* Evidence is {@link SupportLevel#POSSIBLY_SUPPORTED} if it is supported or possibly supported by at least one realm of the domain.
* Otherwise it is {@link SupportLevel#UNSUPPORTED}.
*
* @param evidenceType the type of evidence to be verified (must not be {@code null})
* @param algorithmName the algorithm name, or {@code null} if any algorithm is acceptable or the evidence type does
* not support algorithm names
* @return the level of support for this evidence type
*/
public SupportLevel getEvidenceVerifySupport(Class<? extends Evidence> evidenceType, String algorithmName) {
return getSupportLevel(r -> {
try {
return r.getEvidenceVerifySupport(evidenceType, algorithmName);
} catch (RealmUnavailableException e) {
log.trace("Failed to obtain evidence verify support from realm", e);
return null;
}
});
}
/**
* Determine whether a given type of evidence is definitely verifiable, possibly verifiable (for some identities),
* or definitely not verifiable.
*
* Evidence is {@link SupportLevel#SUPPORTED}, if it is supported by all realms of the domain.
* Evidence is {@link SupportLevel#POSSIBLY_SUPPORTED} if it is supported or possibly supported by at least one realm of the domain.
* Otherwise it is {@link SupportLevel#UNSUPPORTED}.
*
* @param evidenceType the type of evidence to be verified (must not be {@code null})
* @return the level of support for this evidence type
*/
public SupportLevel getEvidenceVerifySupport(Class<? extends Evidence> evidenceType) {
return getEvidenceVerifySupport(evidenceType, null);
}
private SupportLevel getSupportLevel(final Function<SecurityRealm, SupportLevel> getSupportLevel) {
SupportLevel min, max;
min = max = null;
Iterator<RealmInfo> iterator = realmMap.values().iterator();
while (iterator.hasNext()) {
RealmInfo realmInfo = iterator.next();
SecurityRealm realm = realmInfo.getSecurityRealm();
final SupportLevel support = getSupportLevel.apply(realm);
if (support != null) {
if (min == null || max == null) {
min = max = support;
} else {
if (support.compareTo(min) < 0) { min = support; }
if (support.compareTo(max) > 0) { max = support; }
}
}
}
if (min == null || max == null) {
return SupportLevel.UNSUPPORTED;
} else {
return minMax(min, max);
}
}
private SupportLevel minMax(SupportLevel min, SupportLevel max) {
if (min == max) return min;
if (max == SupportLevel.UNSUPPORTED) {
return SupportLevel.UNSUPPORTED;
} else if (min == SupportLevel.SUPPORTED) {
return SupportLevel.SUPPORTED;
} else {
return SupportLevel.POSSIBLY_SUPPORTED;
}
}
/**
* Get the current security identity for this domain.
*
* Code can be executed with given identity using {@code SecurityIdentity.runAs*} methods.
*
* @return the current security identity for this domain (not {@code null})
*/
public SecurityIdentity getCurrentSecurityIdentity() {
final SecurityIdentity identity = currentSecurityIdentity.get().get();
return identity == null ? anonymousIdentity : identity;
}
/**
* Get the anonymous security identity for this realm.
*
* @return the anonymous security identity for this realm (not {@code null})
*/
public SecurityIdentity getAnonymousSecurityIdentity() {
return anonymousIdentity;
}
/**
* Create an empty ad-hoc identity. The identity will have no authorization information and no credentials associated
* with it.
*
* @param name the identity name (must not be {@code null})
* @return the ad-hoc identity
*/
public SecurityIdentity createAdHocIdentity(String name) {
checkNotNullParam("name", name);
return createAdHocIdentity(new NamePrincipal(name));
}
/**
* Create an empty ad-hoc identity. The identity will have no authorization information and no credentials associated
* with it.
*
* Calling with enabled security manager requires {@code createAdHocIdentity} {@link ElytronPermission}.
*
* @param principal the identity principal (must not be {@code null})
* @return the ad-hoc identity
*/
public SecurityIdentity createAdHocIdentity(Principal principal) {
checkNotNullParam("principal", principal);
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(CREATE_AD_HOC_IDENTITY);
}
return new SecurityIdentity(this, principal, EMPTY_REALM_INFO, AuthorizationIdentity.EMPTY, emptyMap(), IdentityCredentials.NONE, IdentityCredentials.NONE);
}
Supplier<SecurityIdentity> getAndSetCurrentSecurityIdentity(Supplier<SecurityIdentity> newIdentity) {
try {
final Supplier<SecurityIdentity> oldIdentity = currentSecurityIdentity.get();
return oldIdentity == null ? anonymousIdentity : oldIdentity;
} finally {
if (newIdentity == anonymousIdentity) {
currentSecurityIdentity.remove();
} else {
currentSecurityIdentity.set(newIdentity);
}
}
}
void setCurrentSecurityIdentity(Supplier<SecurityIdentity> newIdentity) {
if (newIdentity == anonymousIdentity) {
currentSecurityIdentity.remove();
} else {
currentSecurityIdentity.set(newIdentity);
}
}
Roles mapRoles(SecurityIdentity securityIdentity) {
Assert.checkNotNullParam("securityIdentity", securityIdentity);
AuthorizationIdentity identity = securityIdentity.getAuthorizationIdentity();
RealmInfo realmInfo = securityIdentity.getRealmInfo();
// zeroth role mapping, just grab roles from the identity
Roles decodedRoles = realmInfo.getRoleDecoder().decodeRoles(identity);
// determine roles based on any runtime attributes associated with the identity
Roles domainDecodedRoles = securityIdentity.getSecurityDomain().getRoleDecoder().decodeRoles(identity);
Roles combinedRoles = decodedRoles.or(domainDecodedRoles);
// apply the first level mapping, which is based on the role mapper associated with a realm.
Roles realmMappedRoles = realmInfo.getRoleMapper().mapRoles(combinedRoles);
// apply the second level mapping, which is based on the role mapper associated with this security domain.
Roles domainMappedRoles = roleMapper.mapRoles(realmMappedRoles);
if (log.isTraceEnabled()) {
log.tracef("Role mapping: principal [%s] -> decoded roles [%s] -> domain decoded roles [%s] -> realm mapped roles [%s] -> domain mapped roles [%s]",
securityIdentity.getPrincipal(), String.join(", ", decodedRoles), String.join(", ", domainDecodedRoles), String.join(", ", realmMappedRoles), String.join(", ", domainMappedRoles));
}
return domainMappedRoles;
}
PermissionVerifier mapPermissions(final SecurityIdentity securityIdentity) {
Assert.checkNotNullParam("securityIdentity", securityIdentity);
final Roles roles = securityIdentity.getRoles();
PermissionVerifier verifier = permissionMapper.mapPermissions(securityIdentity, roles);
if (log.isTraceEnabled()) {
return (permission) -> {
boolean decision = verifier.implies(permission);
log.tracef("Permission mapping: identity [%s] with roles [%s] implies %s = %b",
securityIdentity.getPrincipal(), String.join(", ", roles), permission, decision);
return decision;
};
} else {
return verifier;
}
}
Function<Principal, Principal> getPreRealmRewriter() {
return preRealmPrincipalRewriter;
}
String mapRealmName(final Principal principal, final Evidence evidence) {
String realm = realmMapper.getRealmMapping(principal, evidence);
return realm != null ? realm : defaultRealmName;
}
String getDefaultRealmName() {
return defaultRealmName;
}
RealmMapper getRealmMapper() {
return realmMapper;
}
Function<Principal, Principal> getPostRealmRewriter() {
return postRealmPrincipalRewriter;
}
RoleMapper getRoleMapper() {
return roleMapper;
}
Map<String, RoleMapper> getCategoryRoleMappers() {
return categoryRoleMappers;
}
SecurityIdentity transform(final SecurityIdentity securityIdentity) {
Assert.checkNotNullParam("securityIdentity", securityIdentity);
return Assert.assertNotNull(securityIdentityTransformer.apply(securityIdentity));
}
boolean trustsDomain(final SecurityDomain domain) {
Assert.checkNotNullParam("domain", domain);
return this == domain || trustedSecurityDomain.test(domain);
}
/**
* Handle a {@link SecurityEvent}.
*
* Calling with enabled security manager requires {@code handleSecurityEvent} {@link ElytronPermission}.
*
* @param securityEvent {@link SecurityEvent} to be handled
* @see Builder#setSecurityEventListener(Consumer)
*/
public void handleSecurityEvent(final SecurityEvent securityEvent) {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(HANDLE_SECURITY_EVENT);
}
if (!securityEvent.getSecurityIdentity().getSecurityDomain().equals(this)) {
log.securityEventIdentityWrongDomain();
}
this.securityEventListener.accept(securityEvent);
}
static void safeHandleSecurityEvent(final SecurityDomain domain, final SecurityEvent event) {
checkNotNullParam("domain", domain);
checkNotNullParam("event", event);
try {
domain.handleSecurityEvent(event);
} catch (Exception e) {
log.eventHandlerFailed(e);
}
}
Function<Evidence, Principal> getEvidenceDecoder() {
return evidenceDecoder;
}
RoleDecoder getRoleDecoder() {
return roleDecoder;
}
/**
* A builder for creating new security domains.
*/
public static final class Builder {
private boolean built = false;
private final HashMap<String, RealmBuilder> realms = new HashMap<>();
private Function<Principal, Principal> preRealmRewriter = Function.identity();
private Function<Principal, Principal> principalDecoder = Function.identity();
private Function<Principal, Principal> postRealmRewriter = Function.identity();
private String defaultRealmName;
private RealmMapper realmMapper = RealmMapper.DEFAULT_REALM_MAPPER;
private RoleMapper roleMapper = RoleMapper.IDENTITY_ROLE_MAPPER;
private PermissionMapper permissionMapper = PermissionMapper.EMPTY_PERMISSION_MAPPER;
private Map<String, RoleMapper> categoryRoleMappers = emptyMap();
private UnaryOperator<SecurityIdentity> securityIdentityTransformer = UnaryOperator.identity();
private Predicate<SecurityDomain> trustedSecurityDomain = domain -> false;
private Consumer<SecurityEvent> securityEventListener = e -> {};
private Function<Evidence, Principal> evidenceDecoder = evidence -> evidence.getDefaultPrincipal();
private RoleDecoder roleDecoder = RoleDecoder.EMPTY;
Builder() {
}
/**
* Sets a pre-realm name rewriter, which rewrites the authentication name before a realm is selected.
*
* @param rewriter the name rewriter (must not be {@code null})
* @return this builder
*/
public Builder setPreRealmRewriter(NameRewriter rewriter) {
return setPreRealmRewriter(rewriter.asPrincipalRewriter());
}
/**
* Sets a pre-realm name rewriter, which rewrites the authentication name before a realm is selected.
*
* @param rewriter the name rewriter (must not be {@code null})
* @return this builder
*/
public Builder setPreRealmRewriter(final Function<Principal, Principal> rewriter) {
Assert.checkNotNullParam("rewriter", rewriter);
assertNotBuilt();
this.preRealmRewriter = rewriter;
return this;
}
/**
* Sets a post-realm name rewriter, which rewrites the authentication name after a realm is selected.
*
* @param rewriter the name rewriter (must not be {@code null})
* @return this builder
*/
public Builder setPostRealmRewriter(NameRewriter rewriter) {
return setPostRealmRewriter(rewriter.asPrincipalRewriter());
}
/**
* Sets a post-realm name rewriter, which rewrites the authentication name after a realm is selected.
*
* @param rewriter the name rewriter (must not be {@code null})
* @return this builder
*/
public Builder setPostRealmRewriter(Function<Principal, Principal> rewriter) {
Assert.checkNotNullParam("rewriter", rewriter);
assertNotBuilt();
this.postRealmRewriter = rewriter;
return this;
}
/**
* Set the realm mapper for this security domain, which selects a realm based on the authentication name.
*
* @param realmMapper the realm mapper (must not be {@code null})
* @return this builder
*/
public Builder setRealmMapper(RealmMapper realmMapper) {
Assert.checkNotNullParam("realmMapper", realmMapper);
assertNotBuilt();
this.realmMapper = realmMapper;
return this;
}
/**
* Set the role mapper for this security domain, which will be used to perform the last mapping before
* returning the roles associated with an identity obtained from this security domain.
*
* @param roleMapper the role mapper (must not be {@code null})
* @return this builder
*/
public Builder setRoleMapper(RoleMapper roleMapper) {
Assert.checkNotNullParam("roleMapper", roleMapper);
assertNotBuilt();
this.roleMapper = roleMapper;
return this;
}
/**
* Set the permission mapper for this security domain, which will be used to obtain and map permissions based on the
* identities from this security domain.
*
* @param permissionMapper the permission mapper (must not be {@code null})
* @return this builder
*/
public Builder setPermissionMapper(PermissionMapper permissionMapper) {
Assert.checkNotNullParam("permissionMapper", permissionMapper);
assertNotBuilt();
this.permissionMapper = permissionMapper;
return this;
}
/**
* Set the principal decoder for this security domain, which will be used to convert {@link Principal} objects
* into names for handling in the realm.
*
* @param principalDecoder the principal decoder (must not be {@code null})
* @return this builder
*/
public Builder setPrincipalDecoder(PrincipalDecoder principalDecoder) {
Assert.checkNotNullParam("principalDecoder", principalDecoder);
assertNotBuilt();
this.principalDecoder = principalDecoder.asPrincipalRewriter();
return this;
}
/**
* Add a realm to this security domain.
*
* @param name the realm's name in this configuration
* @param realm the realm
* @return the new realm builder
*/
public RealmBuilder addRealm(String name, SecurityRealm realm) {
Assert.checkNotNullParam("name", name);
Assert.checkNotNullParam("realm", realm);
assertNotBuilt();
return new RealmBuilder(this, name, realm);
}
Builder addRealm(RealmBuilder realmBuilder) {
realms.put(realmBuilder.getName(), realmBuilder);
return this;
}
/**
* Get the default realm name.
*
* @return the default realm name
*/
public String getDefaultRealmName() {
return defaultRealmName;
}
/**
* Set the default realm name.
*
* @param defaultRealmName the default realm name (must not be {@code null})
*/
public Builder setDefaultRealmName(final String defaultRealmName) {
Assert.checkNotNullParam("defaultRealmName", defaultRealmName);
assertNotBuilt();
this.defaultRealmName = defaultRealmName;
return this;
}
/**
* Get the category role mapper map.
*
* @return the category role mapper map
*/
public Map<String, RoleMapper> getCategoryRoleMappers() {
return categoryRoleMappers;
}
/**