-
Notifications
You must be signed in to change notification settings - Fork 268
/
FileSystemSecurityRealm.java
1713 lines (1573 loc) · 84.5 KB
/
FileSystemSecurityRealm.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 2015 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.realm;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import static java.nio.file.StandardOpenOption.DSYNC;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.WRITE;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import static org.wildfly.security.provider.util.ProviderUtil.INSTALLED_PROVIDERS;
import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256;
import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256;
import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
import static org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.Provider;
import java.security.PublicKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.crypto.SecretKey;
import javax.xml.crypto.MarshalException;
import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.wildfly.common.Assert;
import org.wildfly.common.bytes.ByteStringBuilder;
import org.wildfly.common.codec.Base32Alphabet;
import org.wildfly.common.codec.Base64Alphabet;
import org.wildfly.common.iteration.ByteIterator;
import org.wildfly.common.iteration.CodePointIterator;
import org.wildfly.security.auth.SupportLevel;
import org.wildfly.security.auth.principal.NamePrincipal;
import org.wildfly.security.auth.realm.IdentitySharedExclusiveLock.IdentityLock;
import org.wildfly.security.auth.server.ModifiableRealmIdentity;
import org.wildfly.security.auth.server.ModifiableRealmIdentityIterator;
import org.wildfly.security.auth.server.ModifiableSecurityRealm;
import org.wildfly.security.auth.server.NameRewriter;
import org.wildfly.security.auth.server.RealmIdentity;
import org.wildfly.security.auth.server.RealmUnavailableException;
import org.wildfly.security.authz.Attributes;
import org.wildfly.security.authz.AuthorizationIdentity;
import org.wildfly.security.authz.MapAttributes;
import org.wildfly.security.credential.Credential;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.credential.PublicKeyCredential;
import org.wildfly.security.credential.X509CertificateChainPublicCredential;
import org.wildfly.security.encryption.CipherUtil;
import org.wildfly.security.evidence.Evidence;
import org.wildfly.security.password.Password;
import org.wildfly.security.password.PasswordFactory;
import org.wildfly.security.password.interfaces.OneTimePassword;
import org.wildfly.security.password.spec.BasicPasswordSpecEncoding;
import org.wildfly.security.password.spec.Encoding;
import org.wildfly.security.password.spec.OneTimePasswordSpec;
import org.wildfly.security.password.spec.PasswordSpec;
import org.wildfly.security.password.util.ModularCrypt;
import org.wildfly.security.permission.ElytronPermission;
import org.xml.sax.SAXException;
/**
* A simple filesystem-backed security realm.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class FileSystemSecurityRealm implements ModifiableSecurityRealm, CacheableSecurityRealm {
static final ElytronPermission CREATE_SECURITY_REALM = ElytronPermission.forName("createSecurityRealm");
private final Supplier<Provider[]> providers;
static final Map<String, Version> KNOWN_NAMESPACES;
private enum Version {
VERSION_1_0("urn:elytron:1.0", null),
VERSION_1_0_1("urn:elytron:1.0.1", VERSION_1_0),
VERSION_1_1("urn:elytron:identity:1.1", VERSION_1_0_1),
VERSION_1_2("urn:elytron:identity:1.2", VERSION_1_1);
final String namespace;
/*
* In the future we could support multiple parents but wait until that becomes a reality before adding it.
*/
final Version parent;
Version(String namespace, Version parent) {
this.namespace = namespace;
this.parent = parent;
}
String getNamespace() {
return namespace;
}
boolean isAtLeast(Version version) {
return this.equals(version) || (parent != null ? parent.isAtLeast(version) : false);
}
}
static {
Map<String, Version> knownNamespaces = new HashMap<>();
for (Version version : Version.values()) {
knownNamespaces.put(version.namespace, version);
}
KNOWN_NAMESPACES = Collections.unmodifiableMap(knownNamespaces);
}
private final Path root;
private final NameRewriter nameRewriter;
private final int levels;
private final boolean encoded;
private final Charset hashCharset;
private final Encoding hashEncoding;
private final SecretKey secretKey;
private final PrivateKey privateKey;
private final PublicKey publicKey;
private final ConcurrentHashMap<String, String> mainIndex;
private final ConcurrentHashMap<String, IdentitySharedExclusiveLock> realmIdentityLocks = new ConcurrentHashMap<>();
/**
* Construct a new instance of the FileSystemSecurityRealmBuilder.
*
* @return the new FileSystemSecurityRealmBuilder instance
*/
public static FileSystemSecurityRealmBuilder builder() {
return new FileSystemSecurityRealmBuilder();
}
/**
* Construct a new instance.
*
* Construction with enabled security manager requires {@code createSecurityRealm} {@link ElytronPermission}.
*
* @param root the root path of the identity store
* @param nameRewriter the name rewriter to apply to looked up names
* @param levels the number of levels of directory hashing to apply
* @param encoded whether identity names should be BASE32 encoded before using as filename (only applies if the security realm is unencrypted)
* @param hashCharset the character set to use when converting password strings to a byte array. Uses UTF-8 by default.
* @param hashEncoding the string format for the hashed passwords. Uses Base64 by default.
* @param providers The providers supplier
* @param secretKey the SecretKey used to encrypt and decrypt the security realm (if {@code null}, the security realm will be unencrypted)
* @param privateKey the PrivateKey used to verify the integrity of the security realm (if {@code null}, the security realm will not verify integrity)
* @param publicKey the PublicKey used to verify the integrity of the security realm (if {@code null}, the security realm will not verify integrity)
*
*/
public FileSystemSecurityRealm(final Path root, final NameRewriter nameRewriter, final int levels, final boolean encoded, final Encoding hashEncoding, final Charset hashCharset, Supplier<Provider[]> providers, final SecretKey secretKey, final PrivateKey privateKey, final PublicKey publicKey) {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(CREATE_SECURITY_REALM);
}
this.root = root;
this.nameRewriter = nameRewriter;
this.levels = levels;
this.encoded = secretKey == null && encoded;
this.hashCharset = hashCharset != null ? hashCharset : StandardCharsets.UTF_8;
this.hashEncoding = hashEncoding != null ? hashEncoding : Encoding.BASE64;
this.providers = providers != null ? providers : INSTALLED_PROVIDERS;
this.secretKey = secretKey;
this.privateKey = privateKey;
this.publicKey = publicKey;
// mainIndex the index file used to store the checksums of each identity to
// verify integrity of the security realm
this.mainIndex = new ConcurrentHashMap<>();
try {
ModifiableRealmIdentityIterator realmIterator = this.getRealmIdentityIterator();
while (realmIterator.hasNext()) {
Identity identity = (Identity) realmIterator.next();
if (identity.verifyIntegrity()) {
try {
Identity.writeToMainIndex(mainIndex, identity.path, secretKey);
} catch (IOException | GeneralSecurityException e) {
ElytronMessages.log.unableToWriteToMainIndex();
}
}
identity.dispose();
}
realmIterator.close();
} catch (RealmUnavailableException e) {
ElytronMessages.log.tracef("Unable to initialize filesystem realm");
}
}
/**
* Construct a new instance.
*
* Construction with enabled security manager requires {@code createSecurityRealm} {@link ElytronPermission}.
*
* @param root the root path of the identity store
* @param nameRewriter the name rewriter to apply to looked up names
* @param levels the number of levels of directory hashing to apply
* @param encoded whether identity names should be BASE32 encoded before using as filename
* @param hashCharset the character set to use when converting password strings to a byte array. Uses UTF-8 by default.
* @param hashEncoding the string format for the hashed passwords. Uses Base64 by default.
* @param secretKey the SecretKey used to encrypt and decrypt the security realm (if {@code null}, the security realm will be unencrypted)
*/
public FileSystemSecurityRealm(final Path root, final NameRewriter nameRewriter, final int levels, final boolean encoded, final Encoding hashEncoding, final Charset hashCharset, final SecretKey secretKey) {
this(root, nameRewriter, levels, encoded, hashEncoding, hashCharset, INSTALLED_PROVIDERS, secretKey, null, null);
}
/**
* Construct a new instance.
*
* Construction with enabled security manager requires {@code createSecurityRealm} {@link ElytronPermission}.
*
* @param root the root path of the identity store
* @param nameRewriter the name rewriter to apply to looked up names
* @param levels the number of levels of directory hashing to apply
* @param encoded whether identity names should be BASE32 encoded before using as filename
* @param hashCharset the character set to use when converting password strings to a byte array. Uses UTF-8 by default.
* @param hashEncoding the string format for the hashed passwords. Uses Base64 by default.
*/
public FileSystemSecurityRealm(final Path root, final NameRewriter nameRewriter, final int levels, final boolean encoded, final Encoding hashEncoding, final Charset hashCharset) {
this(root, nameRewriter, levels, encoded, hashEncoding, hashCharset, INSTALLED_PROVIDERS, null, null, null);
}
/**
* Construct a new instance.
*
* Construction with enabled security manager requires {@code createSecurityRealm} {@link ElytronPermission}.
*
* @param root the root path of the identity store
* @param nameRewriter the name rewriter to apply to looked up names
* @param levels the number of levels of directory hashing to apply
* @param encoded whether identity names should by BASE32 encoded before using as filename
*/
public FileSystemSecurityRealm(final Path root, final NameRewriter nameRewriter, final int levels, final boolean encoded) {
this(root, nameRewriter, levels, encoded, Encoding.BASE64, StandardCharsets.UTF_8, INSTALLED_PROVIDERS, null, null, null);
}
/**
* Construct a new instance.
*
* @param root the root path of the identity store
* @param nameRewriter the name rewriter to apply to looked up names
* @param levels the number of levels of directory hashing to apply
*/
public FileSystemSecurityRealm(final Path root, final NameRewriter nameRewriter, final int levels) {
this(root, nameRewriter, levels, true);
}
/**
* Construct a new instance.
*
* @param root the root path of the identity store
* @param nameRewriter the name rewriter to apply to looked up names
* @param levels the number of levels of directory hashing to apply
* @param hashEncoding the string format for hashed passwords. Uses Base64 by default.
* @param hashCharset the character set to use when converting password strings to a byte array. Uses UTF-8 by default and must not be {@code null}.
*/
public FileSystemSecurityRealm(final Path root, final NameRewriter nameRewriter, final int levels, final Encoding hashEncoding, final Charset hashCharset) {
this(root, nameRewriter, levels, true, hashEncoding, hashCharset, INSTALLED_PROVIDERS, null, null, null);
}
/**
* Construct a new instance.
*
* @param root the root path of the identity store
* @param levels the number of levels of directory hashing to apply
*/
public FileSystemSecurityRealm(final Path root, final int levels) {
this(root, NameRewriter.IDENTITY_REWRITER, levels, true);
}
/**
* Construct a new instance.
*
* @param root the root path of the identity store
* @param levels the number of levels of directory hashing to apply
* @param hashEncoding the string format for hashed passwords. Uses Base64 by default.
* @param hashCharset the character set to use when converting password strings to a byte array. Uses UTF-8 by default and must not be {@code null}.
*/
public FileSystemSecurityRealm(final Path root, final int levels, final Encoding hashEncoding, final Charset hashCharset) {
this(root, NameRewriter.IDENTITY_REWRITER, levels, true, hashEncoding, hashCharset, INSTALLED_PROVIDERS, null, null, null);
}
/**
* Construct a new instance with 2 levels of hashing.
*
* @param root the root path of the identity store
*/
public FileSystemSecurityRealm(final Path root) {
this(root, NameRewriter.IDENTITY_REWRITER, 2, true);
}
/**
* Construct a new instance with 2 levels of hashing.
*
* @param root the root path of the identity store
* @param hashEncoding the string format for hashed passwords. Uses Base64 by default.
* @param hashCharset the character set to use when converting password strings to a byte array. Uses UTF-8 by default and must not be {@code null}
*/
public FileSystemSecurityRealm(final Path root, final Encoding hashEncoding, final Charset hashCharset) {
this(root, NameRewriter.IDENTITY_REWRITER, 2, true, hashEncoding, hashCharset, INSTALLED_PROVIDERS, null, null, null);
}
public FileSystemSecurityRealm(Path root, int levels, Supplier<Provider[]> providers) {
this(root, NameRewriter.IDENTITY_REWRITER, levels, true, Encoding.BASE64, StandardCharsets.UTF_8, providers, null, null, null);
}
public boolean hasIntegrityEnabled() {
return privateKey != null && publicKey != null;
}
private Path pathFor(String name) {
assert name.codePointCount(0, name.length()) > 0;
String normalizedName = name;
if (encoded) {
normalizedName = Normalizer.normalize(name, Normalizer.Form.NFKC)
.toLowerCase(Locale.ROOT)
.replaceAll("[^a-z0-9]", "_");
}
if (secretKey != null | encoded) {
String base32 = ByteIterator.ofBytes(new ByteStringBuilder().append(name).toArray())
.base32Encode(Base32Alphabet.STANDARD, false).drainToString();
normalizedName = secretKey != null ? base32 : normalizedName + "-" + base32;
}
Path path = root;
int idx = 0;
for (int level = 0; level < levels; level ++) {
int newIdx = normalizedName.offsetByCodePoints(idx, 1);
path = path.resolve(normalizedName.substring(idx, newIdx));
idx = newIdx;
if (idx == normalizedName.length()) {
break;
}
}
return path.resolve(normalizedName + ".xml");
}
public Charset getHashCharset() {
return this.hashCharset;
}
private String nameFor(Path path) {
String fileName = path.toString();
fileName = fileName.substring(0, fileName.length() - 4); // remove ".xml"
if (secretKey != null) {
CodePointIterator it = CodePointIterator.ofString(fileName);
fileName = it.base32Decode(Base32Alphabet.STANDARD, false)
.asUtf8String().drainToString();
} else if (encoded) {
CodePointIterator it = CodePointIterator.ofString(fileName);
it.delimitedBy('-').skipAll();
it.next(); // skip '-'
fileName = it.base32Decode(Base32Alphabet.STANDARD, false)
.asUtf8String().drainToString();
}
return fileName;
}
public RealmIdentity getRealmIdentity(final Principal principal) {
return principal instanceof NamePrincipal ? getRealmIdentity(principal.getName(), false) : RealmIdentity.NON_EXISTENT;
}
public ModifiableRealmIdentity getRealmIdentityForUpdate(final Principal principal) {
return principal instanceof NamePrincipal ? getRealmIdentity(principal.getName(), true) : ModifiableRealmIdentity.NON_EXISTENT;
}
@Override
public void registerIdentityChangeListener(Consumer<Principal> listener) {
// no need to register the listener given that changes to identities are done through the realm
}
private ModifiableRealmIdentity getRealmIdentity(final String name, final boolean exclusive) {
final String finalName = nameRewriter.rewriteName(name);
if (finalName == null) {
throw ElytronMessages.log.invalidName();
}
// Acquire the appropriate lock for the realm identity
IdentitySharedExclusiveLock realmIdentityLock = getRealmIdentityLockForName(finalName);
IdentityLock lock;
if (exclusive) {
lock = realmIdentityLock.lockExclusive();
} else {
lock = realmIdentityLock.lockShared();
}
return new Identity(finalName, pathFor(finalName), lock, hashCharset, hashEncoding, providers, secretKey, privateKey, publicKey, mainIndex);
}
public ModifiableRealmIdentityIterator getRealmIdentityIterator() throws RealmUnavailableException {
return subIterator(root, levels);
}
private ModifiableRealmIdentityIterator subIterator(final Path root, final int levels) {
final DirectoryStream<Path> stream;
final Iterator<Path> iterator;
if (levels == 0) {
try {
stream = Files.newDirectoryStream(root, "*.xml");
iterator = stream.iterator();
} catch (IOException e) {
ElytronMessages.log.debug("Unable to open directory", e);
return ModifiableRealmIdentityIterator.emptyIterator();
}
return new ModifiableRealmIdentityIterator() {
public boolean hasNext() {
if ( ! iterator.hasNext()) {
try {
close();
} catch (IOException e) {
ElytronMessages.log.debug("Unable to close the stream", e);
}
}
return iterator.hasNext();
}
public ModifiableRealmIdentity next() {
final Path path = iterator.next();
final String name = nameFor(path.getFileName());
return getRealmIdentityForUpdate(new NamePrincipal(name));
}
public void close() throws RealmUnavailableException {
try {
stream.close();
} catch (IOException e) {
ElytronMessages.log.debug("Unable to close the stream", e);
}
}
};
} else {
try {
stream = Files.newDirectoryStream(root, entry -> {
final String fileName = entry.getFileName().toString();
return fileName.length() == 1 && !fileName.equals(".") && Files.isDirectory(entry);
});
iterator = stream.iterator();
} catch (IOException e) {
ElytronMessages.log.debug("Unable to open directory", e);
return ModifiableRealmIdentityIterator.emptyIterator();
}
return new ModifiableRealmIdentityIterator() {
private ModifiableRealmIdentityIterator subIterator;
public boolean hasNext() {
for (;;) {
if (subIterator == null) {
if (! iterator.hasNext()) {
try {
close();
} catch (IOException e) {
ElytronMessages.log.debug("Unable to close the stream", e);
}
return false;
}
final Path path = iterator.next();
subIterator = subIterator(path, levels - 1);
} else if (subIterator.hasNext()) {
return true;
} else {
subIterator = null;
}
}
}
public ModifiableRealmIdentity next() {
if (! hasNext()) {
throw new NoSuchElementException();
}
return subIterator.next();
}
public void close() throws RealmUnavailableException {
try {
if (subIterator != null) subIterator.close();
} finally {
try {
stream.close();
} catch (IOException e) {
ElytronMessages.log.debug("Unable to close the stream", e);
}
}
}
};
}
}
public SupportLevel getCredentialAcquireSupport(final Class<? extends Credential> credentialType, final String algorithmName, final AlgorithmParameterSpec parameterSpec) throws RealmUnavailableException {
return SupportLevel.POSSIBLY_SUPPORTED;
}
public SupportLevel getEvidenceVerifySupport(final Class<? extends Evidence> evidenceType, final String algorithmName) throws RealmUnavailableException {
return SupportLevel.POSSIBLY_SUPPORTED;
}
private IdentitySharedExclusiveLock getRealmIdentityLockForName(final String name) {
IdentitySharedExclusiveLock realmIdentityLock = realmIdentityLocks.get(name);
if (realmIdentityLock == null) {
final IdentitySharedExclusiveLock newRealmIdentityLock = new IdentitySharedExclusiveLock();
realmIdentityLock = realmIdentityLocks.putIfAbsent(name, newRealmIdentityLock);
if (realmIdentityLock == null) {
realmIdentityLock = newRealmIdentityLock;
}
}
return realmIdentityLock;
}
@FunctionalInterface
interface CredentialParseFunction {
void parseCredential(String algorithm, String format, String body) throws RealmUnavailableException, XMLStreamException;
}
/**
* Method to update all filesystem's identities signatures with the newly updated key-pair
* Designed to be by WildFly CLI when the {@code :write-attribute(...)} is used for {@code key-store} or {@code key-store-alias}
*
* @throws IOException
* @throws GeneralSecurityException
*/
public void updateRealmKeyPair() throws IOException, GeneralSecurityException {
if (! hasIntegrityEnabled()) {
throw ElytronMessages.log.invalidKeyPairArgument(root.toString());
}
ModifiableRealmIdentityIterator realmIterator = this.getRealmIdentityIterator();
mainIndex.clear();
while (realmIterator.hasNext()) {
Identity identity = (Identity) realmIterator.next();
identity.writeDigitalSignature(String.valueOf(identity.path), identity.name);
Identity.writeToMainIndex(mainIndex, identity.path, identity.secretKey);
identity.dispose();
}
realmIterator.close();
}
/**
* Method to iterate over all filesystem realm identities and verify it's integrity
* Designed to be by WildFly CLI when the {@code :verify-realm-integrity()} is used
* @return Boolean representing if the realm integrity is valid
*/
public boolean verifyRealmIntegrity() throws RealmUnavailableException {
if (! hasIntegrityEnabled()) {
throw ElytronMessages.log.invalidKeyPairArgument(root.toString());
}
ModifiableRealmIdentityIterator realmIterator = this.getRealmIdentityIterator();
while (realmIterator.hasNext()) {
Identity identity = (Identity) realmIterator.next();
if(! identity.verifyIntegrity()) {
return false;
}
identity.dispose();
}
realmIterator.close();
return true;
}
static class Identity implements ModifiableRealmIdentity {
private static final String ENCRYPTION_FORMAT = "enc_base64";
private static final String BASE64_FORMAT = "base64";
private static final String MCF_FORMAT = "crypt";
private static final String X509_FORMAT = "X.509";
private static final String HEX = "hex";
private final String name;
private final Path path;
private Supplier<Provider[]> providers;
private IdentityLock lock;
private final Charset hashCharset;
private final Encoding hashEncoding;
private final SecretKey secretKey;
private final PrivateKey privateKey;
private final PublicKey publicKey;
private final ConcurrentHashMap<String, String> mainIndex;
Identity(final String name, final Path path, final IdentityLock lock, final Charset hashCharset, final Encoding hashEncoding, Supplier<Provider[]> providers, final SecretKey secretKey, final PrivateKey privateKey, final PublicKey publicKey, final ConcurrentHashMap<String, String> mainIndex) {
this.name = name;
this.path = path;
this.lock = lock;
this.hashCharset = hashCharset;
this.hashEncoding = hashEncoding;
this.providers = providers;
this.secretKey = secretKey;
this.privateKey = privateKey;
this.publicKey = publicKey;
this.mainIndex = mainIndex;
}
public Principal getRealmIdentityPrincipal() {
return new NamePrincipal(name);
}
public SupportLevel getCredentialAcquireSupport(final Class<? extends Credential> credentialType, final String algorithmName, final AlgorithmParameterSpec parameterSpec) throws RealmUnavailableException {
Assert.checkNotNullParam("credentialType", credentialType);
List<Credential> credentials = loadCredentials();
for (Credential credential : credentials) {
if (credential.matches(credentialType, algorithmName, parameterSpec)) {
return SupportLevel.SUPPORTED;
}
}
return SupportLevel.UNSUPPORTED;
}
public <C extends Credential> C getCredential(final Class<C> credentialType) throws RealmUnavailableException {
return getCredential(credentialType, null);
}
public <C extends Credential> C getCredential(final Class<C> credentialType, final String algorithmName) throws RealmUnavailableException {
return getCredential(credentialType, algorithmName, null);
}
public <C extends Credential> C getCredential(final Class<C> credentialType, final String algorithmName, final AlgorithmParameterSpec parameterSpec) throws RealmUnavailableException {
Assert.checkNotNullParam("credentialType", credentialType);
List<Credential> credentials = loadCredentials();
for (Credential credential : credentials) {
if (credential.matches(credentialType, algorithmName, parameterSpec)) {
return credentialType.cast(credential.clone());
}
}
return null;
}
public SupportLevel getEvidenceVerifySupport(final Class<? extends Evidence> evidenceType, final String algorithmName) throws RealmUnavailableException {
Assert.checkNotNullParam("evidenceType", evidenceType);
List<Credential> credentials = loadCredentials();
for (Credential credential : credentials) {
if (credential.canVerify(evidenceType, algorithmName)) {
ElytronMessages.log.tracef("FileSystemSecurityRealm - evidence verification SUPPORTED: type = [%s] algorithm = [%s] credentials = [%d]", evidenceType, algorithmName, credentials.size());
return SupportLevel.SUPPORTED;
}
}
ElytronMessages.log.tracef("FileSystemSecurityRealm - evidence verification UNSUPPORTED: type = [%s] algorithm = [%s] credentials = [%d]", evidenceType, algorithmName, credentials.size());
return SupportLevel.UNSUPPORTED;
}
public boolean verifyEvidence(final Evidence evidence) throws RealmUnavailableException {
Assert.checkNotNullParam("evidence", evidence);
if (ElytronMessages.log.isTraceEnabled()) {
try {
final LoadedIdentity loadedIdentity = loadIdentity(false, true);
ElytronMessages.log.tracef("Trying to authenticate identity %s using FileSystemSecurityRealm", (loadedIdentity != null) ? loadedIdentity.getName() : "null");
} catch (RealmUnavailableException e) {
if (e.getCause() instanceof IntegrityException) {
return false;
}
throw e;
}
}
List<Credential> credentials = null;
try {
credentials = loadCredentials();
} catch (RealmUnavailableException e) {
if (e.getCause() instanceof IntegrityException) {
return false;
}
throw e;
}
ElytronMessages.log.tracef("FileSystemSecurityRealm - verification evidence [%s] against [%d] credentials...", evidence, credentials.size());
for (Credential credential : credentials) {
if (credential.canVerify(evidence)) {
boolean verified = false;
if (credential instanceof PasswordCredential) {
verified = ((PasswordCredential )credential).verify(providers, evidence, hashCharset);
} else {
verified = credential.verify(providers, evidence);
}
ElytronMessages.log.tracef("FileSystemSecurityRealm - verification against credential [%s] = %b", credential, verified);
return verified;
}
}
ElytronMessages.log.tracef("FileSystemSecurityRealm - no credential able to verify evidence [%s]", evidence);
return false;
}
List<Credential> loadCredentials() throws RealmUnavailableException {
final LoadedIdentity loadedIdentity = loadIdentity(false, true);
return loadedIdentity == null ? Collections.emptyList() : loadedIdentity.getCredentials();
}
public boolean exists() throws RealmUnavailableException {
if (System.getSecurityManager() == null) {
return Files.exists(path);
}
return AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> Files.exists(path));
}
public void delete() throws RealmUnavailableException {
if (System.getSecurityManager() == null) {
deletePrivileged();
return;
}
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) this::deletePrivileged);
} catch (PrivilegedActionException e) {
if (e.getException() instanceof RealmUnavailableException) {
throw (RealmUnavailableException) e.getException();
}
throw new RuntimeException(e.getException());
}
}
private Void deletePrivileged() throws RealmUnavailableException {
try {
Files.delete(path);
if (publicKey != null) {
mainIndex.remove(path.getFileName().toString());
}
return null;
} catch (NoSuchFileException e) {
throw ElytronMessages.log.fileSystemRealmNotFound(name);
} catch (IOException e) {
throw ElytronMessages.log.fileSystemRealmDeleteFailed(name, e);
}
}
private String tempSuffix() {
final ThreadLocalRandom random = ThreadLocalRandom.current();
char[] array = new char[12];
for (int i = 0; i < array.length; i ++) {
int idx = random.nextInt(36);
if (idx < 26) {
array[i] = (char) ('A' + idx);
} else {
array[i] = (char) ('0' + idx - 26);
}
}
return new String(array);
}
private Path tempPath() {
Path parent = path.getParent();
File file = parent.toFile();
if (!file.exists()) {
file.mkdirs();
}
return parent.resolve(path.getFileName().toString() + '.' + tempSuffix());
}
public void create() throws RealmUnavailableException {
if (System.getSecurityManager() == null) {
createPrivileged();
return;
}
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) this::createPrivileged);
} catch (PrivilegedActionException e) {
if (e.getException() instanceof RealmUnavailableException) {
throw (RealmUnavailableException) e.getException();
}
throw new RuntimeException(e.getException());
}
}
private Void createPrivileged() throws RealmUnavailableException {
for (;;) {
final Path tempPath = tempPath();
final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(tempPath, WRITE, CREATE_NEW, DSYNC))) {
try (AutoCloseableXMLStreamWriterHolder holder = new AutoCloseableXMLStreamWriterHolder(xmlOutputFactory.createXMLStreamWriter(outputStream))) {
String namespace = "";
if (privateKey != null) {
namespace = Version.VERSION_1_2.getNamespace();
} else if (secretKey != null) {
namespace = Version.VERSION_1_1.getNamespace();
} else {
namespace = Version.VERSION_1_0.getNamespace();
}
final XMLStreamWriter streamWriter = holder.getXmlStreamWriter();
// create empty identity
streamWriter.writeStartDocument();
streamWriter.writeCharacters("\n");
streamWriter.writeStartElement("identity");
streamWriter.writeDefaultNamespace(namespace);
streamWriter.writeEndElement();
streamWriter.writeEndDocument();
} catch (XMLStreamException e) {
throw ElytronMessages.log.fileSystemRealmFailedToWrite(tempPath, name, e);
}
} catch (FileAlreadyExistsException ignored) {
// try a new name
continue;
} catch (IOException e) {
throw ElytronMessages.log.fileSystemRealmFailedToOpen(tempPath, name, e);
}
try {
Files.createLink(path, tempPath);
} catch (FileAlreadyExistsException e) {
try {
Files.delete(tempPath);
} catch (IOException e2) {
e.addSuppressed(e2);
}
throw ElytronMessages.log.fileSystemRealmAlreadyExists(name, e);
} catch (IOException e) {
throw ElytronMessages.log.fileSystemRealmFailedToWrite(tempPath, name, e);
}
try {
Files.delete(tempPath);
} catch (IOException ignored) {
// nothing we can do
}
if (privateKey != null) {
try {
writeDigitalSignature(path.toString(), this.name);
writeToMainIndex(this.mainIndex, this.path, this.secretKey);
} catch (RealmUnavailableException e) {
throw ElytronMessages.log.unableToGenerateSignature(path.toString());
} catch (IOException | GeneralSecurityException e) {
throw ElytronMessages.log.unableToAccessMainIndex(this.mainIndex.toString());
}
}
return null;
}
}
public void setCredentials(final Collection<? extends Credential> credentials) throws RealmUnavailableException {
Assert.checkNotNullParam("credential", credentials);
final LoadedIdentity loadedIdentity = loadIdentity(false, false);
if (loadedIdentity == null) {
throw ElytronMessages.log.fileSystemRealmNotFound(name);
}
final LoadedIdentity newIdentity = new LoadedIdentity(name, new ArrayList<>(credentials), loadedIdentity.getAttributes(), hashEncoding);
replaceIdentity(newIdentity);
}
public void setAttributes(final Attributes attributes) throws RealmUnavailableException {
Assert.checkNotNullParam("attributes", attributes);
final LoadedIdentity loadedIdentity = loadIdentity(false, true);
if (loadedIdentity == null) {
throw ElytronMessages.log.fileSystemRealmNotFound(name);
}
final LoadedIdentity newIdentity = new LoadedIdentity(name, loadedIdentity.getCredentials(), attributes, hashEncoding);
replaceIdentity(newIdentity);
}
@Override
public Attributes getAttributes() throws RealmUnavailableException {
final LoadedIdentity loadedIdentity = loadIdentity(true, false);
if (loadedIdentity == null) {
throw ElytronMessages.log.fileSystemRealmNotFound(name);
}
return loadedIdentity.getAttributes().asReadOnly();
}
private void replaceIdentity(final LoadedIdentity newIdentity) throws RealmUnavailableException {
if (System.getSecurityManager() == null) {
replaceIdentityPrivileged(newIdentity);
return;
}
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> replaceIdentityPrivileged(newIdentity));
} catch (PrivilegedActionException e) {
if (e.getException() instanceof RealmUnavailableException) {
throw (RealmUnavailableException) e.getException();
}
throw new RuntimeException(e.getException());
}
}
private Void replaceIdentityPrivileged(final LoadedIdentity newIdentity) throws RealmUnavailableException {
if (!verifyIntegrity()) {
throw new RealmUnavailableException(ElytronMessages.log.invalidIdentitySignature(name));
}
for (;;) {
final Path tempPath = tempPath();
try {
final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
try (OutputStream outputStream = new BufferedOutputStream(
Files.newOutputStream(tempPath, WRITE, CREATE_NEW, DSYNC))) {
try (AutoCloseableXMLStreamWriterHolder holder = new AutoCloseableXMLStreamWriterHolder(xmlOutputFactory.createXMLStreamWriter(outputStream))) {
writeIdentity(holder.getXmlStreamWriter(), newIdentity);
} catch (XMLStreamException | InvalidKeySpecException | NoSuchAlgorithmException
| CertificateEncodingException e) {
throw ElytronMessages.log.fileSystemRealmFailedToWrite(tempPath, name, e);
} catch (GeneralSecurityException e) {
throw ElytronMessages.log.fileSystemRealmEncryptionFailed(e);
}
} catch (FileAlreadyExistsException ignored) {
// try a new name
continue;
} catch (IOException e) {
try {
Files.deleteIfExists(tempPath);
} catch (IOException e2) {
e.addSuppressed(e2);
}
throw ElytronMessages.log.fileSystemRealmFailedToOpen(tempPath, name, e);
}
try {
Files.delete(path);
} catch (IOException e) {
throw ElytronMessages.log.fileSystemUpdatedFailed(path.toAbsolutePath().toString(), e);
}
try {
Files.createLink(path, tempPath);
} catch (FileAlreadyExistsException e) {
try {
Files.deleteIfExists(tempPath);
} catch (IOException e2) {
e.addSuppressed(e2);
}
throw ElytronMessages.log.fileSystemRealmAlreadyExists(name, e);
} catch (IOException e) {
throw ElytronMessages.log.fileSystemRealmFailedToWrite(tempPath, name, e);
}
try {