-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathRestrictedSecurity.java
1940 lines (1714 loc) · 83.1 KB
/
RestrictedSecurity.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
/*
* ===========================================================================
* (c) Copyright IBM Corp. 2022, 2025 All Rights Reserved
* ===========================================================================
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* IBM designates this particular file as subject to the "Classpath" exception
* as provided by IBM in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, see <http://www.gnu.org/licenses/>.
*
* ===========================================================================
*/
package openj9.internal.security;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Provider.Service;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import sun.security.util.Debug;
/**
* Configures the security providers when in restricted security mode.
*/
public final class RestrictedSecurity {
private static final Debug debug = Debug.getInstance("semerufips");
// Restricted security mode enable check.
private static final boolean userEnabledFIPS;
private static boolean isFIPSSupported;
private static boolean isFIPSEnabled;
private static final boolean allowSetProperties;
private static final boolean isNSSSupported;
private static final boolean isOpenJCEPlusSupported;
private static final boolean userSetProfile;
private static final boolean shouldEnableSecurity;
private static String selectedProfile;
private static String profileID;
private static boolean securityEnabled;
private static String userSecurityID;
private static ProfileParser profileParser;
private static RestrictedSecurityProperties restricts;
private static final Set<String> unmodifiableProperties = new HashSet<>();
private static final Map<String, List<String>> supportedPlatformsNSS = new HashMap<>();
private static final Map<String, List<String>> supportedPlatformsOpenJCEPlus = new HashMap<>();
static {
supportedPlatformsNSS.put("Arch", List.of("amd64", "ppc64le", "s390x"));
supportedPlatformsNSS.put("OS", List.of("Linux"));
supportedPlatformsOpenJCEPlus.put("Arch", List.of("amd64", "ppc64", "s390x"));
supportedPlatformsOpenJCEPlus.put("OS", List.of("Linux", "AIX", "Windows"));
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
boolean isOsSupported, isArchSupported;
// Check whether the NSS FIPS solution is supported.
isOsSupported = false;
for (String os: supportedPlatformsNSS.get("OS")) {
if (osName.contains(os)) {
isOsSupported = true;
}
}
isArchSupported = false;
for (String arch: supportedPlatformsNSS.get("Arch")) {
if (osArch.contains(arch)) {
isArchSupported = true;
}
}
isNSSSupported = isOsSupported && isArchSupported;
// Check whether the OpenJCEPlus FIPS solution is supported.
isOsSupported = false;
for (String os: supportedPlatformsOpenJCEPlus.get("OS")) {
if (osName.contains(os)) {
isOsSupported = true;
}
}
isArchSupported = false;
for (String arch: supportedPlatformsOpenJCEPlus.get("Arch")) {
if (osArch.contains(arch)) {
isArchSupported = true;
}
}
isOpenJCEPlusSupported = isOsSupported && isArchSupported;
// Check the default solution to see if FIPS is supported.
isFIPSSupported = isNSSSupported;
userEnabledFIPS = Boolean.getBoolean("semeru.fips");
allowSetProperties = Boolean.getBoolean("semeru.fips.allowsetproperties");
if (userEnabledFIPS) {
if (isFIPSSupported) {
// Set to default profile for the default FIPS solution.
selectedProfile = "NSS.140-2";
}
}
// If user has specified a profile, use that
selectedProfile = System.getProperty("semeru.customprofile");
userSetProfile = selectedProfile != null;
// Check if FIPS is supported on this platform without explicitly setting a profile.
if (userEnabledFIPS && !isFIPSSupported && !userSetProfile) {
printStackTraceAndExit("FIPS mode is not supported on this platform by default.\n"
+ " Use the semeru.customprofile system property to use an available FIPS-compliant profile.\n"
+ " Note: Not all platforms support FIPS at the moment.");
}
shouldEnableSecurity = (userEnabledFIPS && isFIPSSupported) || userSetProfile;
}
private RestrictedSecurity() {
super();
}
/**
* Check loaded profiles' hash values.
*
* In order to avoid unintentional changes in profiles and incentivize
* extending profiles, instead of altering them, a digest of the profile
* is calculated and compared to the expected value.
*/
public static void checkHashValues() {
if (profileParser != null) {
profileParser.checkHashValues();
profileParser = null;
}
}
/**
* Check if restricted security mode is enabled.
*
* Restricted security mode is enabled when, on supported platforms,
* the semeru.customprofile system property is used to set a
* specific security profile or the semeru.fips system property is
* set to true.
*
* @return true if restricted security mode is enabled
*/
public static boolean isEnabled() {
return securityEnabled;
}
/**
* Get restricted security mode secure random provider.
*
* Restricted security mode secure random provider can only
* be called in restricted security mode.
*
* @return the secure random provider
*/
public static String getRandomProvider() {
if (!securityEnabled) {
printStackTraceAndExit(
"Restricted security mode secure random provider can only be used when restricted security mode is enabled.");
}
return restricts.jdkSecureRandomProvider;
}
/**
* Get restricted security mode secure random algorithm.
*
* Restricted security mode secure random algorithm can only
* be called in restricted security mode.
*
* @return the secure random algorithm
*/
public static String getRandomAlgorithm() {
if (!securityEnabled) {
printStackTraceAndExit(
"Restricted security mode secure random algorithm can only be used when restricted security mode is enabled.");
}
return restricts.jdkSecureRandomAlgorithm;
}
/**
* Check if the FIPS mode is enabled.
*
* FIPS mode will be enabled when the semeru.fips system property is
* true, and the RestrictedSecurity mode has been successfully initialized.
*
* @return true if FIPS is enabled
*/
public static boolean isFIPSEnabled() {
if (securityEnabled) {
return isFIPSEnabled;
}
return false;
}
/**
* Check if the service is allowed to be used in restricted security mode.
*
* @param service the service to check
* @return true if the service is allowed to be used
*/
public static boolean isServiceAllowed(Service service) {
if (securityEnabled) {
return restricts.isRestrictedServiceAllowed(service, false);
}
return true;
}
/**
* Check if the service is allowed to be registered in restricted security mode.
*
* @param service the service to check
* @return true if the service is allowed to be registered
*/
public static boolean canServiceBeRegistered(Service service) {
if (securityEnabled) {
return restricts.isRestrictedServiceAllowed(service, true);
}
return true;
}
/**
* Check if the provider is allowed in restricted security mode.
*
* @param providerName the provider to check
* @return true if the provider is allowed
*/
public static boolean isProviderAllowed(String providerName) {
if (securityEnabled) {
// Remove argument, e.g. -NSS-FIPS, if present.
int pos = providerName.indexOf('-');
if (pos >= 0) {
providerName = providerName.substring(0, pos);
}
return restricts.isRestrictedProviderAllowed(providerName);
}
return true;
}
/**
* Check if the provider is allowed in restricted security mode.
*
* @param providerClazz the provider class to check
* @return true if the provider is allowed
*/
public static boolean isProviderAllowed(Class<?> providerClazz) {
if (securityEnabled) {
String providerClassName = providerClazz.getName();
// Check if the specified class extends java.security.Provider.
if (java.security.Provider.class.isAssignableFrom(providerClazz)) {
return restricts.isRestrictedProviderAllowed(providerClassName);
}
// For a class that doesn't extend java.security.Provider, no need to
// check allowed or not allowed, always return true to load it.
if (debug != null) {
debug.println("The provider class " + providerClassName + " does not extend java.security.Provider.");
}
}
return true;
}
/**
* Figure out the full profile ID.
*
* Use the default or user selected profile and attempt to find
* an appropriate entry in the java.security properties.
*
* If a profile cannot be found, or multiple defaults are discovered
* for a single profile, an appropriate message is printed and the
* system exits.
*
* @param props the java.security properties
*/
private static void getProfileID(Properties props) {
String potentialProfileID = "RestrictedSecurity." + selectedProfile;
if (selectedProfile.indexOf('.') != -1) {
/* The default profile is used, or the user specified the
* full <profile.version>.
*/
if (debug != null) {
debug.println("Profile specified using full name (i.e., <profile.version>): "
+ selectedProfile);
}
for (Object keyObject : props.keySet()) {
if (keyObject instanceof String key) {
if (key.startsWith(potentialProfileID)) {
profileID = potentialProfileID;
return;
}
}
}
printStackTraceAndExit(selectedProfile + " is not present in the java.security file.");
} else {
/* The user specified the only the <profile> without
* indicating the <version> part.
*/
if (debug != null) {
debug.println("Profile specified without version (i.e., <profile>): "
+ selectedProfile);
}
String defaultMatch = null;
boolean profileExists = false;
String profilePrefix = potentialProfileID + '.';
for (Object keyObject : props.keySet()) {
if (keyObject instanceof String key) {
if (key.startsWith(profilePrefix)) {
profileExists = true;
if (key.endsWith(".desc.default")) {
// Check if property is set to true.
if (Boolean.parseBoolean(props.getProperty(key))) {
// Check if multiple defaults exist and act accordingly.
if (defaultMatch == null) {
defaultMatch = key.substring(0, key.length() - ".desc.default".length());
} else {
printStackTraceAndExit("Multiple default RestrictedSecurity"
+ " profiles for " + selectedProfile);
}
}
}
}
}
}
if (!profileExists) {
printStackTraceAndExit(selectedProfile + " is not present in the java.security file.");
} else if (defaultMatch == null) {
printStackTraceAndExit("No default RestrictedSecurity profile was found for "
+ selectedProfile);
} else {
profileID = defaultMatch;
}
}
}
private static void checkIfKnownProfileSupported() {
if (profileID.contains("NSS") && !isNSSSupported) {
printStackTraceAndExit("NSS RestrictedSecurity profiles are not supported"
+ " on this platform.");
}
if (profileID.contains("OpenJCEPlus") && !isOpenJCEPlusSupported) {
printStackTraceAndExit("OpenJCEPlus RestrictedSecurity profiles are not supported"
+ " on this platform.");
}
if (debug != null) {
debug.println("RestrictedSecurity profile " + profileID
+ " is supported on this platform.");
}
}
private static void checkFIPSCompatibility() {
boolean isFIPSProfile = restricts.descIsFIPS;
if (isFIPSProfile) {
if (debug != null) {
debug.println("RestrictedSecurity profile " + profileID
+ " is specified as FIPS compliant.");
}
isFIPSEnabled = true;
} else {
printStackTraceAndExit("RestrictedSecurity profile " + profileID
+ " is not specified as FIPS compliant, but the semeru.fips"
+ " system property is set to true.");
}
}
/**
* Check whether a security property can be set.
*
* A security property that is FIPS-related and can be set by a RestrictedSecurity
* profile, while FIPS security mode is enabled, cannot be reset programmatically.
*
* Every time an attempt to set a security property is made, a check is
* performed. If the above scenario holds true, a SecurityException is
* thrown.
*
* One can override this behaviour and allow the user to set any security
* property through the use of {@code -Dsemeru.fips.allowsetproperties=true}.
*
* @param key the security property that the user wants to set
* @throws SecurityException
* if the security property is set by the profile and cannot
* be altered
*/
public static void checkSetSecurityProperty(String key) {
if (debug != null) {
debug.println("RestrictedSecurity: Checking whether property '"
+ key + "' can be set.");
}
/*
* Only disallow setting of security properties that are FIPS-related,
* if FIPS has been enabled.
*
* Allow any change, if the 'semeru.fips.allowsetproperties' flag is set to true.
*/
if (unmodifiableProperties.contains(key)) {
if (debug != null) {
debug.println("RestrictedSecurity: Property '" + key + "' cannot be set.");
debug.println("If you want to override the check and allow all security"
+ "properties to be set, use '-Dsemeru.fips.allowsetproperties=true'.");
debug.println("BEWARE: You might not be FIPS compliant if you select to override!");
}
throw new SecurityException("Property '" + key
+ "' cannot be set programmatically when in FIPS mode");
}
if (debug != null) {
debug.println("RestrictedSecurity: Property '"
+ key + "' can be set without issue.");
}
}
/**
* Remove the security providers and only add restricted security providers.
*
* @param props the java.security properties
* @return true if restricted security properties loaded successfully
*/
public static boolean configure(Properties props) {
// Check if restricted security is already initialized.
if (securityEnabled) {
printStackTraceAndExit("Restricted security mode is already initialized, it can't be initialized twice.");
}
try {
if (shouldEnableSecurity) {
if (debug != null) {
debug.println("Restricted security mode is being enabled...");
}
getProfileID(props);
checkIfKnownProfileSupported();
// Initialize restricted security properties from java.security file.
profileParser = new ProfileParser(profileID, props);
restricts = profileParser.getProperties();
// Restricted security properties checks.
restrictsCheck();
// Remove all security providers.
for (Iterator<Map.Entry<Object, Object>> i = props.entrySet().iterator(); i.hasNext();) {
Map.Entry<Object, Object> e = i.next();
String key = (String) e.getKey();
if (key.startsWith("security.provider")) {
if (debug != null) {
debug.println("Removing provider: " + e);
}
i.remove();
}
}
// Add restricted security providers.
setProviders(props);
// Add restricted security Properties.
setProperties(props);
if (debug != null) {
debug.println("Restricted security mode loaded.");
debug.println("Restricted security mode properties: " + props.toString());
}
securityEnabled = true;
}
} catch (Exception e) {
if (debug != null) {
debug.println("Unable to load restricted security mode configurations.");
}
printStackTraceAndExit(e);
}
return securityEnabled;
}
/**
* Add restricted security providers.
*
* @param props the java.security properties
*/
private static void setProviders(Properties props) {
if (debug != null) {
debug.println("Adding restricted security provider.");
}
int pNum = 0;
for (String provider : restricts.providers) {
pNum += 1;
props.setProperty("security.provider." + pNum, provider);
if (debug != null) {
debug.println("Added restricted security provider: " + provider);
}
}
}
/**
* Add restricted security properties.
*
* @param props the java.security properties
*/
private static void setProperties(Properties props) {
if (debug != null) {
debug.println("Adding restricted security properties.");
}
Map<String, String> propsMapping = new HashMap<>();
// JDK properties name as key, restricted security properties value as value.
propsMapping.put("jdk.tls.disabledNamedCurves", restricts.jdkTlsDisabledNamedCurves);
propsMapping.put("jdk.tls.disabledAlgorithms", restricts.jdkTlsDisabledAlgorithms);
propsMapping.put("jdk.tls.ephemeralDHKeySize", restricts.jdkTlsEphemeralDHKeySize);
propsMapping.put("jdk.tls.legacyAlgorithms", restricts.jdkTlsLegacyAlgorithms);
propsMapping.put("jdk.certpath.disabledAlgorithms", restricts.jdkCertpathDisabledAlgorithms);
propsMapping.put("jdk.security.legacyAlgorithms", restricts.jdkSecurityLegacyAlgorithms);
String fipsMode = System.getProperty("com.ibm.fips.mode");
if (fipsMode == null) {
System.setProperty("com.ibm.fips.mode", restricts.jdkFipsMode);
} else if (!fipsMode.equals(restricts.jdkFipsMode)) {
printStackTraceAndExit("Property com.ibm.fips.mode is incompatible with semeru.customprofile and semeru.fips properties");
}
if (userEnabledFIPS && !allowSetProperties) {
// Add all properties that cannot be modified.
unmodifiableProperties.addAll(propsMapping.keySet());
}
for (Map.Entry<String, String> entry : propsMapping.entrySet()) {
String jdkPropsName = entry.getKey();
String propsNewValue = entry.getValue();
if (!isNullOrBlank(propsNewValue)) {
props.setProperty(jdkPropsName, propsNewValue);
if (debug != null) {
debug.println("Added restricted security properties, with property: "
+ jdkPropsName + " value: " + propsNewValue);
}
}
}
// For keyStore and keystore.type, old value not needed, just set the new value.
String keyStoreType = restricts.keyStoreType;
if (!isNullOrBlank(keyStoreType)) {
props.setProperty("keystore.type", keyStoreType);
}
String keyStore = restricts.keyStore;
if (!isNullOrBlank(keyStore)) {
// SSL property "javax.net.ssl.keyStore" set at the JVM level via system properties.
System.setProperty("javax.net.ssl.keyStore", keyStore);
}
}
/**
* Check restricted security properties.
*/
private static void restrictsCheck() {
// Check restricts object.
if (restricts == null) {
printStackTraceAndExit("Restricted security property is null.");
}
// Check if the SunsetDate expired.
if (isPolicySunset(restricts.descSunsetDate)) {
printStackTraceAndExit("Restricted security policy expired.");
}
// Check secure random settings.
if (isNullOrBlank(restricts.jdkSecureRandomProvider)
|| isNullOrBlank(restricts.jdkSecureRandomAlgorithm)) {
printStackTraceAndExit("Restricted security mode secure random is missing.");
}
// If user enabled FIPS, check whether chosen profile is applicable.
if (userEnabledFIPS) {
checkFIPSCompatibility();
}
}
/**
* Check if restricted security policy is sunset.
*
* @param descSunsetDate the sunset date from java.security
* @return true if restricted security policy sunset
*/
private static boolean isPolicySunset(String descSunsetDate) {
boolean isSunset = false;
// Only check if a sunset date is specified in the profile.
if (!isNullOrBlank(descSunsetDate)) {
try {
isSunset = LocalDate.parse(descSunsetDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
.isBefore(LocalDate.now());
} catch (DateTimeParseException except) {
printStackTraceAndExit(
"Restricted security policy sunset date is incorrect, the correct format is yyyy-MM-dd.");
}
}
if (debug != null) {
debug.println("Restricted security policy is sunset: " + isSunset);
}
return isSunset;
}
/**
* Check if the input string is null or blank.
*
* @param string the input string
* @return true if the input string is null or blank
*/
private static boolean isNullOrBlank(String string) {
return (string == null) || string.isBlank();
}
private static void printStackTraceAndExit(Exception exception) {
exception.printStackTrace();
System.exit(1);
}
private static void printStackTraceAndExit(String message) {
printStackTraceAndExit(new RuntimeException(message));
}
/**
* Check if the input string is asterisk (*).
*
* @param string input string for checking
* @return true if the input string is asterisk
*/
private static boolean isAsterisk(String string) {
return "*".equals(string);
}
/**
* This class is used to save and operate on restricted security
* properties which are loaded from the java.security file.
*/
private static final class RestrictedSecurityProperties {
private final String profileID;
private final String descName;
private final boolean descIsDefault;
private final boolean descIsFIPS;
private final String descNumber;
private final String descPolicy;
private final String descSunsetDate;
// Security properties.
private final String jdkTlsDisabledNamedCurves;
private final String jdkTlsDisabledAlgorithms;
private final String jdkTlsEphemeralDHKeySize;
private final String jdkTlsLegacyAlgorithms;
private final String jdkCertpathDisabledAlgorithms;
private final String jdkSecurityLegacyAlgorithms;
private final String keyStoreType;
private final String keyStore;
// For SecureRandom.
final String jdkSecureRandomProvider;
final String jdkSecureRandomAlgorithm;
final String jdkFipsMode;
// Provider with argument (provider name + optional argument).
private final List<String> providers;
// Provider without argument.
private final List<String> providersFullyQualifiedClassName;
// The map is keyed by provider name.
private final Map<String, Constraint[]> providerConstraints;
private RestrictedSecurityProperties(String profileID, ProfileParser parser) {
this.profileID = profileID;
this.descName = parser.getProperty("descName");
this.descIsDefault = parser.descIsDefault;
this.descIsFIPS = parser.descIsFIPS;
this.descNumber = parser.getProperty("descNumber");
this.descPolicy = parser.getProperty("descPolicy");
this.descSunsetDate = parser.getProperty("descSunsetDate");
// Security properties.
this.jdkTlsDisabledNamedCurves = parser.getProperty("jdkTlsDisabledNamedCurves");
this.jdkTlsDisabledAlgorithms = parser.getProperty("jdkTlsDisabledAlgorithms");
this.jdkTlsEphemeralDHKeySize = parser.getProperty("jdkTlsEphemeralDHKeySize");
this.jdkTlsLegacyAlgorithms = parser.getProperty("jdkTlsLegacyAlgorithms");
this.jdkCertpathDisabledAlgorithms = parser.getProperty("jdkCertpathDisabledAlgorithms");
this.jdkSecurityLegacyAlgorithms = parser.getProperty("jdkSecurityLegacyAlgorithms");
this.keyStoreType = parser.getProperty("keyStoreType");
this.keyStore = parser.getProperty("keyStore");
// For SecureRandom.
this.jdkSecureRandomProvider = parser.getProperty("jdkSecureRandomProvider");
this.jdkSecureRandomAlgorithm = parser.getProperty("jdkSecureRandomAlgorithm");
this.jdkFipsMode = parser.getProperty("jdkFipsMode");
this.providers = new ArrayList<>(parser.providers);
this.providersFullyQualifiedClassName = new ArrayList<>(parser.providersFullyQualifiedClassName);
this.providerConstraints = parser.providerConstraints
.entrySet()
.stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> e.getValue().toArray(new Constraint[0])
));
if (debug != null) {
// Print information of utilized security profile.
listUsedProfile();
}
}
/**
* Check if the Service is allowed in restricted security mode.
*
* @param service the Service to check
* @return true if the Service is allowed
*/
boolean isRestrictedServiceAllowed(Service service, boolean isServiceAdded) {
Provider provider = service.getProvider();
String providerClassName = provider.getClass().getName();
if (debug != null) {
debug.println("Checking service " + service.toString() + " offered by provider " + providerClassName + ".");
}
Constraint[] constraints = providerConstraints.get(providerClassName);
if (constraints == null) {
// Disallow unknown providers.
if (debug != null) {
debug.println("Security constraints check."
+ " Disallow unknown provider: " + providerClassName);
}
return false;
} else if (constraints.length == 0) {
// Allow this provider with no constraints.
if (debug != null) {
debug.println("No constraints for provider " + providerClassName + ".");
}
return true;
}
// Check the constraints of this provider.
String type = service.getType();
String algorithm = service.getAlgorithm();
if (debug != null) {
debug.println("Security constraints check of provider.");
}
for (Constraint constraint : constraints) {
String cType = constraint.type;
String cAlgorithm = constraint.algorithm;
String cAttribute = constraint.attributes;
String cAcceptedUses = constraint.acceptedUses;
if (debug != null) {
debug.println("Checking provider constraint:"
+ "\n\tService type: " + cType
+ "\n\tAlgorithm: " + cAlgorithm
+ "\n\tAttributes: " + cAttribute
+ "\n\tAccepted uses: " + cAcceptedUses);
}
if (!isAsterisk(cType) && !type.equals(cType)) {
// The constraint doesn't apply to the service type.
if (debug != null) {
debug.println("The constraint doesn't apply to the service type.");
}
continue;
}
if (!isAsterisk(cAlgorithm) && !algorithm.equalsIgnoreCase(cAlgorithm)) {
// The constraint doesn't apply to the service algorithm.
if (debug != null) {
debug.println("The constraint doesn't apply to the service algorithm.");
}
continue;
}
// For type and algorithm match, and attribute is not *.
// Then continue checking attributes.
if (!isAsterisk(cAttribute)) {
String[] cAttributeArray = cAttribute.split(":");
// For each attribute, must be all matched for return allowed.
for (String attribute : cAttributeArray) {
String[] input = attribute.split("=", 2);
String cName = input[0].trim();
String cValue = input[1].trim();
String sValue = service.getAttribute(cName);
if (debug != null) {
debug.println("Checking specific attribute with:"
+ "\n\tName: " + cName
+ "\n\tValue: " + cValue
+ "\nagainst the service attribute value: " + sValue);
}
if ((sValue == null) || !cValue.equalsIgnoreCase(sValue)) {
// If any attribute doesn't match, return service is not allowed.
if (debug != null) {
debug.println("Attributes don't match!");
debug.println("The following service:"
+ "\n\tService type: " + type
+ "\n\tAlgorithm: " + algorithm
+ "\n\tAttribute: " + cAttribute
+ "\nis NOT allowed in provider: " + providerClassName);
}
return false;
}
if (debug != null) {
debug.println("Attributes match!");
}
}
}
// See if accepted uses have been specified and apply
// them to the call stack.
if (!isServiceAdded && !isNullOrBlank(cAcceptedUses)) {
String[] optionAndValue = cAcceptedUses.split(":");
if (optionAndValue.length != 2) {
printStackTraceAndExit("Incorrect specification of accepted uses in constraint: '"
+ constraint + "'. Couldn't find option and value separated by ':'");
}
String option = optionAndValue[0];
String value = optionAndValue[1];
StackTraceElement[] stackElements = Thread.currentThread().getStackTrace();
boolean found = false;
for (StackTraceElement stackElement : stackElements) {
if (debug != null) {
debug.println("Attempting to match " + stackElement + " with: " + option + " : " + value);
}
String stackElemModule = stackElement.getModuleName();
String stackElemFullClassName = stackElement.getClassName();
int stackElemEnd = stackElemFullClassName.lastIndexOf(".");
String stackElemPackage = null;
if (stackElemEnd != -1) {
stackElemPackage = stackElemFullClassName.substring(0, stackElemEnd);
}
String module;
switch (option) {
case "ModuleAndFullClassName":
String[] moduleAndFullClassName = value.split("/");
if (moduleAndFullClassName.length != 2) {
printStackTraceAndExit("Incorrect specification of accepted uses in constraint: '"
+ constraint + "'. Couldn't find module and classname separated by '/'");
}
module = moduleAndFullClassName[0];
String fullClassName = moduleAndFullClassName[1];
found = (stackElemModule != null) && stackElemModule.equals(module)
&& stackElemFullClassName.equals(fullClassName);
break;
case "ModuleAndPackage":
String[] moduleAndPackage = value.split("/");
if (moduleAndPackage.length != 2) {
printStackTraceAndExit("Incorrect specification of accepted uses in constraint: '"
+ constraint + "'. Couldn't find module and classname separated by '/'");
}
module = moduleAndPackage[0];
String packageValue = moduleAndPackage[1];
found = (stackElemModule != null) && stackElemModule.equals(module)
&& (stackElemPackage != null) && stackElemPackage.equals(packageValue);
break;
case "FullClassName":
found = stackElemFullClassName.equals(value);
break;
case "Package":
found = (stackElemPackage != null) && stackElemPackage.equals(value);
break;
default:
printStackTraceAndExit("Incorrect option to match in constraint: " + constraint);
}
if (found) {
break;
}
}
// If nothing matching the accepted uses is found in the call stack,
// this service is not allowed.
if (!found) {
if (debug != null) {
debug.println("Classes in call stack are not part of accepted uses!");
debug.println("The following service:"
+ "\n\tService type: " + type
+ "\n\tAlgorithm: " + algorithm
+ "\n\tAttribute: " + cAttribute
+ "\n\tAccepted uses: " + cAcceptedUses
+ "\nis NOT allowed in provider: " + providerClassName);
}
return false;
}
}
if (debug != null) {
debug.println("All attributes matched!");
debug.println("The following service:"
+ "\n\tService type: " + type
+ "\n\tAlgorithm: " + algorithm
+ "\n\tAttribute: " + cAttribute
+ "\n\tAccepted uses: " + cAcceptedUses
+ "\nis allowed in provider: " + providerClassName);
}
return true;
}
// No match for any constraint, return NOT allowed.
if (debug != null) {
debug.println("Could not find a constraint to match.");
debug.println("The following service:"
+ "\n\tService type: " + type
+ "\n\tAlgorithm: " + algorithm
+ "\nis NOT allowed in provider: " + providerClassName);
}
return false;
}
/**
* Check if the provider is allowed in restricted security mode.
*
* @param providerClassName the provider to check
* @return true if the provider is allowed
*/
boolean isRestrictedProviderAllowed(String providerClassName) {
if (debug != null) {
debug.println("Checking the provider " + providerClassName + " in restricted security mode.");
}
// Check if the provider fully-qualified cLass name is in restricted
// security provider list. If not, the provider won't be registered.
if (providersFullyQualifiedClassName.contains(providerClassName)) {
if (debug != null) {
debug.println("The provider " + providerClassName + " is allowed in restricted security mode.");
}
return true;
}
if (debug != null) {
debug.println("The provider " + providerClassName + " is not allowed in restricted security mode.");
debug.println("Stack trace:");
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (int i = 1; i < elements.length; i++) {
StackTraceElement stack = elements[i];
debug.println("\tat " + stack.getClassName() + "." + stack.getMethodName() + "("
+ stack.getFileName() + ":" + stack.getLineNumber() + ")");
}
}
return false;
}
/**
* List the RestrictedSecurity profile currently used.
*/
private void listUsedProfile() {
System.out.println();
System.out.println("Utilized Restricted Security Profile Info:");
System.out.println("==========================================");
System.out.println("The Restricted Security profile used is: " + profileID);
System.out.println();
System.out.println(profileID + " Profile Info:");
System.out.println("==========================================");