-
Notifications
You must be signed in to change notification settings - Fork 682
/
SAML2Configuration.java
786 lines (614 loc) · 28.3 KB
/
SAML2Configuration.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
package org.pac4j.saml.config;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.TBSCertificate;
import org.bouncycastle.asn1.x509.Time;
import org.bouncycastle.asn1.x509.V3TBSCertificateGenerator;
import org.bouncycastle.util.encoders.Base64;
import org.opensaml.core.xml.schema.XSAny;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.xmlsec.config.impl.DefaultSecurityConfigurationBootstrap;
import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration;
import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.logout.handler.DefaultLogoutHandler;
import org.pac4j.core.logout.handler.LogoutHandler;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.core.util.InitializableObject;
import org.pac4j.saml.exceptions.SAMLException;
import org.pac4j.saml.metadata.SAML2ServiceProvicerRequestedAttribute;
import org.pac4j.saml.storage.EmptyStorageFactory;
import org.pac4j.saml.storage.SAMLMessageStorageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.WritableResource;
import sun.security.provider.X509Factory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
/**
* The class is responsible for capturing client settings and passing them around.
*
* @author Misagh Moayyed
* @author Jerome Leleu
* @since 1.7
*/
public class SAML2Configuration extends InitializableObject {
private static final Logger LOGGER = LoggerFactory.getLogger(SAML2Configuration.class);
protected static final String RESOURCE_PREFIX = "resource:";
protected static final String CLASSPATH_PREFIX = "classpath:";
protected static final String FILE_PREFIX = "file:";
protected static final String DEFAULT_PROVIDER_NAME = "pac4j-saml";
private Resource keystoreResource;
private String keystorePassword;
private String privateKeyPassword;
private Resource identityProviderMetadataResource;
private String identityProviderEntityId;
private String serviceProviderEntityId;
private int maximumAuthenticationLifetime = 3600;
private int acceptedSkew = 300;
private boolean forceAuth = false;
private boolean passive = false;
private String comparisonType = null;
private String authnRequestBindingType = SAMLConstants.SAML2_POST_BINDING_URI;
private String spLogoutRequestBindingType = SAMLConstants.SAML2_POST_BINDING_URI;
private String spLogoutResponseBindingType = SAMLConstants.SAML2_POST_BINDING_URI;
private String authnContextClassRef = null;
private String nameIdPolicyFormat = null;
private boolean useNameQualifier = true;
private boolean signMetadata;
private WritableResource serviceProviderMetadataResource;
private boolean forceServiceProviderMetadataGeneration;
private boolean forceKeystoreGeneration;
private SAMLMessageStorageFactory samlMessageStorageFactory = new EmptyStorageFactory();
private boolean authnRequestSigned;
private boolean spLogoutRequestSigned;
private final List<SAML2ServiceProvicerRequestedAttribute> requestedServiceProviderAttributes = new ArrayList<>();
private Collection<String> blackListedSignatureSigningAlgorithms;
private List<String> signatureAlgorithms;
private List<String> signatureReferenceDigestMethods;
private String signatureCanonicalizationAlgorithm;
private boolean wantsAssertionsSigned = true;
private String keyStoreAlias;
private String keyStoreType;
private int assertionConsumerServiceIndex = -1;
private int attributeConsumingServiceIndex = -1;
private String providerName;
private Supplier<List<XSAny>> authnRequestExtensions;
private String attributeAsId;
private Map<String, String> mappedAttributes = new LinkedHashMap<>();
private LogoutHandler logoutHandler;
public SAML2Configuration() {
}
public SAML2Configuration(final String keystorePath, final String keystorePassword, final String privateKeyPassword,
final String identityProviderMetadataPath) {
this(null, null, mapPathToResource(keystorePath), keystorePassword, privateKeyPassword,
mapPathToResource(identityProviderMetadataPath), null, null,
DEFAULT_PROVIDER_NAME, null, null);
}
public SAML2Configuration(final Resource keystoreResource, final String keystorePassword, final String privateKeyPassword,
final Resource identityProviderMetadataResource) {
this(null, null, keystoreResource, keystorePassword, privateKeyPassword,
identityProviderMetadataResource, null, null,
DEFAULT_PROVIDER_NAME, null, null);
}
public SAML2Configuration(final Resource keystoreResource, final String keyStoreAlias,
final String keyStoreType, final String keystorePassword, final String privateKeyPassword,
final Resource identityProviderMetadataResource) {
this(keyStoreAlias, keyStoreType, keystoreResource, keystorePassword,
privateKeyPassword, identityProviderMetadataResource, null,
null, DEFAULT_PROVIDER_NAME, null, null);
}
protected SAML2Configuration(final String keyStoreAlias, final String keyStoreType,
final Resource keystoreResource, final String keystorePassword,
final String privateKeyPassword, final Resource identityProviderMetadataResource,
final String identityProviderEntityId, final String serviceProviderEntityId,
final String providerName, final Supplier<List<XSAny>> authnRequestExtensions,
final String attributeAsId) {
this.keyStoreAlias = keyStoreAlias;
this.keyStoreType = keyStoreType;
this.keystoreResource = keystoreResource;
this.keystorePassword = keystorePassword;
this.privateKeyPassword = privateKeyPassword;
this.identityProviderMetadataResource = identityProviderMetadataResource;
this.identityProviderEntityId = identityProviderEntityId;
this.serviceProviderEntityId = serviceProviderEntityId;
this.providerName = providerName;
this.authnRequestExtensions = authnRequestExtensions;
this.attributeAsId = attributeAsId;
}
@Override
protected void internalInit() {
CommonHelper.assertNotNull("keystoreResource", this.keystoreResource);
CommonHelper.assertNotBlank("keystorePassword", this.keystorePassword);
CommonHelper.assertNotBlank("privateKeyPassword", this.privateKeyPassword);
CommonHelper.assertNotNull("identityProviderMetadataResource", this.identityProviderMetadataResource);
if (!this.keystoreResource.exists() || this.forceKeystoreGeneration) {
if (this.keystoreResource instanceof WritableResource) {
LOGGER.warn("Provided keystoreResource does not exist or keystore generation is forced. Creating one for: {}",
this.keystoreResource);
createKeystore();
} else {
throw new TechnicalException("Provided keystoreResource does not exist and cannot be created");
}
}
if (logoutHandler == null) {
logoutHandler = new DefaultLogoutHandler();
}
initSignatureSigningConfiguration();
}
public List<SAML2ServiceProvicerRequestedAttribute> getRequestedServiceProviderAttributes() {
return requestedServiceProviderAttributes;
}
public void setIdentityProviderMetadataResource(final Resource identityProviderMetadataResource) {
this.identityProviderMetadataResource = identityProviderMetadataResource;
}
public void setIdentityProviderMetadataResourceFilepath(final String path) {
this.identityProviderMetadataResource = new FileSystemResource(path);
}
public void setIdentityProviderMetadataResourceClasspath(final String path) {
this.identityProviderMetadataResource = new ClassPathResource(path);
}
public void setIdentityProviderMetadataResourceUrl(final String url) {
this.identityProviderMetadataResource = newUrlResource(url);
}
public void setIdentityProviderMetadataPath(final String path) {
this.identityProviderMetadataResource = mapPathToResource(path);
}
public int getAssertionConsumerServiceIndex() {
return assertionConsumerServiceIndex;
}
public void setAssertionConsumerServiceIndex(final int assertionConsumerServiceIndex) {
this.assertionConsumerServiceIndex = assertionConsumerServiceIndex;
}
public boolean isForceKeystoreGeneration() {
return forceKeystoreGeneration;
}
public void setForceKeystoreGeneration(final boolean forceKeystoreGeneration) {
this.forceKeystoreGeneration = forceKeystoreGeneration;
}
protected static UrlResource newUrlResource(final String url) {
try {
return new UrlResource(url);
} catch (final MalformedURLException e) {
throw new TechnicalException(e);
}
}
protected static Resource mapPathToResource(final String path) {
CommonHelper.assertNotBlank("path", path);
if (path.startsWith(RESOURCE_PREFIX)) {
return new ClassPathResource(path.substring(RESOURCE_PREFIX.length()));
} else if (path.startsWith(CLASSPATH_PREFIX)) {
return new ClassPathResource(path.substring(CLASSPATH_PREFIX.length()));
} else if (path.startsWith(HttpConstants.SCHEME_HTTP) || path.startsWith(HttpConstants.SCHEME_HTTPS)) {
return newUrlResource(path);
} else if (path.startsWith(FILE_PREFIX)) {
return new FileSystemResource(path.substring(FILE_PREFIX.length()));
} else {
return new FileSystemResource(path);
}
}
public int getAcceptedSkew() {
return acceptedSkew;
}
public void setAcceptedSkew(final int acceptedSkew) {
this.acceptedSkew = acceptedSkew;
}
public Resource getIdentityProviderMetadataResource() {
return this.identityProviderMetadataResource;
}
public void setIdentityProviderEntityId(final String identityProviderEntityId) {
this.identityProviderEntityId = identityProviderEntityId;
}
public String getIdentityProviderEntityId() {
return identityProviderEntityId;
}
public void setKeystoreAlias(final String keyStoreAlias) {
this.keyStoreAlias = keyStoreAlias;
}
public void setKeystoreType(final String keyStoreType) {
this.keyStoreType = keyStoreType;
}
public void setKeystoreResource(final Resource keystoreResource) {
this.keystoreResource = keystoreResource;
}
public void setKeystoreResourceFilepath(final String path) {
this.keystoreResource = new FileSystemResource(path);
}
public void setKeystoreResourceClasspath(final String path) {
this.keystoreResource = new ClassPathResource(path);
}
public void setKeystoreResourceUrl(final String url) {
this.keystoreResource = newUrlResource(url);
}
public void setKeystorePath(final String path) {
this.keystoreResource = mapPathToResource(path);
}
public void setKeystorePassword(final String keystorePassword) {
this.keystorePassword = keystorePassword;
}
public void setPrivateKeyPassword(final String privateKeyPassword) {
this.privateKeyPassword = privateKeyPassword;
}
public String getKeyStoreAlias() {
return keyStoreAlias;
}
public String getKeyStoreType() {
return this.keyStoreType;
}
public Resource getKeystoreResource() {
return keystoreResource;
}
public String getKeystorePassword() {
return keystorePassword;
}
public String getPrivateKeyPassword() {
return privateKeyPassword;
}
public void setServiceProviderMetadataResource(final WritableResource serviceProviderMetadataResource) {
this.serviceProviderMetadataResource = serviceProviderMetadataResource;
}
public void setServiceProviderMetadataResourceFilepath(final String path) {
this.serviceProviderMetadataResource = new FileSystemResource(path);
}
public void setServiceProviderMetadataPath(final String path) {
final Resource resource = mapPathToResource(path);
if (!(resource instanceof WritableResource)) {
throw new TechnicalException(path + " must be a writable resource");
} else {
this.serviceProviderMetadataResource = (WritableResource) resource;
}
}
public void setForceServiceProviderMetadataGeneration(final boolean forceServiceProviderMetadataGeneration) {
this.forceServiceProviderMetadataGeneration = forceServiceProviderMetadataGeneration;
}
public WritableResource getServiceProviderMetadataResource() {
return serviceProviderMetadataResource;
}
public void setServiceProviderEntityId(final String serviceProviderEntityId) {
this.serviceProviderEntityId = serviceProviderEntityId;
}
public String getServiceProviderEntityId() {
return serviceProviderEntityId;
}
public boolean isPassive() {
return passive;
}
public void setPassive(final boolean passive) {
this.passive = passive;
}
public boolean isForceAuth() {
return forceAuth;
}
public void setForceAuth(final boolean forceAuth) {
this.forceAuth = forceAuth;
}
public String getComparisonType() {
return comparisonType;
}
public void setComparisonType(final String comparisonType) {
this.comparisonType = comparisonType;
}
public String getAuthnRequestBindingType() {
return authnRequestBindingType;
}
public void setAuthnRequestBindingType(final String authnRequestBindingType) {
this.authnRequestBindingType = authnRequestBindingType;
}
public String getSpLogoutRequestBindingType() {
return spLogoutRequestBindingType;
}
public void setSpLogoutRequestBindingType(final String spLogoutRequestBindingType) {
this.spLogoutRequestBindingType = spLogoutRequestBindingType;
}
public String getSpLogoutResponseBindingType() {
return spLogoutResponseBindingType;
}
public void setSpLogoutResponseBindingType(final String spLogoutResponseBindingType) {
this.spLogoutResponseBindingType = spLogoutResponseBindingType;
}
public String getAuthnContextClassRef() {
return authnContextClassRef;
}
public void setAuthnContextClassRef(final String authnContextClassRef) {
this.authnContextClassRef = authnContextClassRef;
}
public String getNameIdPolicyFormat() {
return nameIdPolicyFormat;
}
public void setNameIdPolicyFormat(final String nameIdPolicyFormat) {
this.nameIdPolicyFormat = nameIdPolicyFormat;
}
public int getMaximumAuthenticationLifetime() {
return maximumAuthenticationLifetime;
}
public void setMaximumAuthenticationLifetime(final int maximumAuthenticationLifetime) {
this.maximumAuthenticationLifetime = maximumAuthenticationLifetime;
}
public boolean isForceServiceProviderMetadataGeneration() {
return forceServiceProviderMetadataGeneration;
}
public SAMLMessageStorageFactory getSamlMessageStorageFactory() {
return samlMessageStorageFactory;
}
public void setSamlMessageStorageFactory(final SAMLMessageStorageFactory samlMessageStorageFactory) {
this.samlMessageStorageFactory = samlMessageStorageFactory;
}
public Collection<String> getBlackListedSignatureSigningAlgorithms() {
return blackListedSignatureSigningAlgorithms;
}
public void setBlackListedSignatureSigningAlgorithms(final Collection<String> blackListedSignatureSigningAlgorithms) {
this.blackListedSignatureSigningAlgorithms = blackListedSignatureSigningAlgorithms;
}
public List<String> getSignatureAlgorithms() {
return signatureAlgorithms;
}
public void setSignatureAlgorithms(final List<String> signatureAlgorithms) {
this.signatureAlgorithms = signatureAlgorithms;
}
public List<String> getSignatureReferenceDigestMethods() {
return signatureReferenceDigestMethods;
}
public void setSignatureReferenceDigestMethods(final List<String> signatureReferenceDigestMethods) {
this.signatureReferenceDigestMethods = signatureReferenceDigestMethods;
}
public String getSignatureCanonicalizationAlgorithm() {
return signatureCanonicalizationAlgorithm;
}
public void setSignatureCanonicalizationAlgorithm(final String signatureCanonicalizationAlgorithm) {
this.signatureCanonicalizationAlgorithm = signatureCanonicalizationAlgorithm;
}
public boolean isWantsAssertionsSigned() {
return this.wantsAssertionsSigned;
}
public void setWantsAssertionsSigned(final boolean wantsAssertionsSigned) {
this.wantsAssertionsSigned = wantsAssertionsSigned;
}
public boolean isAuthnRequestSigned() {
return authnRequestSigned;
}
public void setAuthnRequestSigned(final boolean authnRequestSigned) {
this.authnRequestSigned = authnRequestSigned;
}
public boolean isSpLogoutRequestSigned() {
return spLogoutRequestSigned;
}
public void setSpLogoutRequestSigned(final boolean spLogoutRequestSigned) {
this.spLogoutRequestSigned = spLogoutRequestSigned;
}
public int getAttributeConsumingServiceIndex() {
return attributeConsumingServiceIndex;
}
public void setAttributeConsumingServiceIndex(final int attributeConsumingServiceIndex) {
this.attributeConsumingServiceIndex = attributeConsumingServiceIndex;
}
public String getProviderName() {
return providerName;
}
public void setProviderName(String providerName) {
this.providerName = providerName;
}
public Supplier<List<XSAny>> getAuthnRequestExtensions() {
return authnRequestExtensions;
}
public void setAuthnRequestExtensions(Supplier<List<XSAny>> authnRequestExtensions) {
this.authnRequestExtensions = authnRequestExtensions;
}
public String getAttributeAsId() {
return attributeAsId;
}
public void setAttributeAsId(String attributeAsId) {
this.attributeAsId = attributeAsId;
}
public boolean isUseNameQualifier() {
return useNameQualifier;
}
public void setUseNameQualifier(boolean useNameQualifier) {
this.useNameQualifier = useNameQualifier;
}
public boolean isSignMetadata() {
return signMetadata;
}
public void setSignMetadata(final boolean signMetadata) {
this.signMetadata = signMetadata;
}
public Map<String, String> getMappedAttributes() {
return mappedAttributes;
}
public void setMappedAttributes(final Map<String, String> mappedAttributes) {
this.mappedAttributes = mappedAttributes;
}
public LogoutHandler getLogoutHandler() {
return logoutHandler;
}
public void setLogoutHandler(final LogoutHandler logoutHandler) {
this.logoutHandler = logoutHandler;
}
public LogoutHandler findLogoutHandler() {
init();
return logoutHandler;
}
/**
* Initializes the configuration for a particular client.
*
* @param clientName Name of the client. The configuration can use the value or not.
*/
public void init(final String clientName) {
init();
}
/**
* Generate a self-signed certificate for dn using the provided signature algorithm and key pair.
*
* @param dn X.500 name to associate with certificate issuer/subject.
* @param sigName name of the signature algorithm to use.
* @param sigAlgID algorithm ID associated with the signature algorithm name.
* @param keyPair the key pair to associate with the certificate.
* @return an X509Certificate containing the public key in keyPair.
* @throws Exception
*/
private X509Certificate createSelfSignedCert(X500Name dn, String sigName, AlgorithmIdentifier sigAlgID, KeyPair keyPair)
throws Exception {
final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
certGen.setIssuer(dn);
certGen.setSubject(dn);
certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));
final Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.YEAR, 1);
certGen.setEndDate(new Time(c.getTime()));
certGen.setSignature(sigAlgID);
certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
Signature sig = Signature.getInstance(sigName);
sig.initSign(keyPair.getPrivate());
sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));
TBSCertificate tbsCert = certGen.generateTBSCertificate();
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tbsCert);
v.add(sigAlgID);
v.add(new DERBitString(sig.sign()));
final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
.generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
// check the certificate - this will confirm the encoded sig algorithm ID is correct.
cert.verify(keyPair.getPublic());
return cert;
}
private void createKeystore() {
try {
if (CommonHelper.isBlank(this.keyStoreAlias)) {
this.keyStoreAlias = getClass().getSimpleName();
LOGGER.warn("Using keystore alias {}", this.keyStoreAlias);
}
if (CommonHelper.isBlank(this.keyStoreType)) {
this.keyStoreType = KeyStore.getDefaultType();
LOGGER.warn("Using keystore type {}", this.keyStoreType);
}
final KeyStore ks = KeyStore.getInstance(this.keyStoreType);
final char[] password = this.keystorePassword.toCharArray();
ks.load(null, password);
final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
final KeyPair kp = kpg.genKeyPair();
final String sigAlgName = "SHA1WithRSA";
final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
final String dn = InetAddress.getLocalHost().getHostName();
final PrivateKey signingKey = kp.getPrivate();
final X509Certificate certificate = createSelfSignedCert(new X500Name("CN=" + dn), sigAlgName, sigAlgID, kp);
final char[] keyPassword = this.privateKeyPassword.toCharArray();
ks.setKeyEntry(this.keyStoreAlias, signingKey, keyPassword, new Certificate[]{certificate});
final File keystoreFile = this.keystoreResource.getFile();
try (final FileOutputStream fos = new FileOutputStream(keystoreFile.getCanonicalPath())) {
ks.store(fos, password);
fos.flush();
}
final File signingCertEncoded = getSigningBase64CertificatePath();
writeEncodedCertificateToFile(signingCertEncoded, certificate.getEncoded());
final File signingCertBinary = getSigningBinaryCertificatePath();
writeBinaryCertificateToFile(signingCertBinary, certificate.getEncoded());
final File signingKeyEncoded = getSigningKeyFile();
writeEncodedCertificateToFile(signingKeyEncoded, signingKey.getEncoded());
LOGGER.info("Created keystore {} with key alias {} ",
keystoreResource.getFile().getCanonicalPath(),
ks.aliases().nextElement());
} catch (final Exception e) {
throw new SAMLException("Could not create keystore", e);
}
}
public File getSigningBinaryCertificatePath() throws IOException {
return new File(keystoreResource.getFile().getParentFile(), "saml-signing-cert.crt");
}
public File getSigningBase64CertificatePath() throws IOException {
return new File(keystoreResource.getFile().getParentFile(), "saml-signing-cert.pem");
}
public File getSigningKeyFile() throws IOException {
return new File(keystoreResource.getFile().getParentFile(), "saml-signing-cert.key");
}
private static void writeBinaryCertificateToFile(final File file, final byte[] certificate) {
if (file.exists()) {
final boolean res = file.delete();
LOGGER.debug("Deleted file [{}]:{}", file, res);
}
try (final FileOutputStream fos = new FileOutputStream(file)) {
fos.write(certificate);
fos.flush();
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
private static void writeEncodedCertificateToFile(final File file, final byte[] certificate) {
if (file.exists()) {
final boolean res = file.delete();
LOGGER.debug("Deleted file [{}]:{}", file, res);
}
final Base64 encoder = new Base64();
try (final FileOutputStream fos = new FileOutputStream(file)) {
fos.write(X509Factory.BEGIN_CERT.getBytes(StandardCharsets.UTF_8));
fos.write("\n".getBytes(StandardCharsets.UTF_8));
encoder.encode(certificate, fos);
fos.write(X509Factory.END_CERT.getBytes(StandardCharsets.UTF_8));
fos.flush();
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
private void initSignatureSigningConfiguration() {
// Bootstrap signature signing configuration if not manually set
final BasicSignatureSigningConfiguration config = DefaultSecurityConfigurationBootstrap
.buildDefaultSignatureSigningConfiguration();
if (this.blackListedSignatureSigningAlgorithms == null) {
this.blackListedSignatureSigningAlgorithms = new ArrayList<>(
config.getBlacklistedAlgorithms());
LOGGER.info("Bootstrapped Blacklisted Algorithms");
}
if (this.signatureAlgorithms == null) {
this.signatureAlgorithms = new ArrayList<>(
config.getSignatureAlgorithms());
LOGGER.info("Bootstrapped Signature Algorithms");
}
if (this.signatureReferenceDigestMethods == null) {
this.signatureReferenceDigestMethods = new ArrayList<>(
config.getSignatureReferenceDigestMethods());
this.signatureReferenceDigestMethods
.remove("http://www.w3.org/2001/04/xmlenc#sha512");
LOGGER.info("Bootstrapped Signature Reference Digest Methods");
}
if (this.signatureCanonicalizationAlgorithm == null) {
this.signatureCanonicalizationAlgorithm = config
.getSignatureCanonicalizationAlgorithm();
LOGGER.info("Bootstrapped Canonicalization Algorithm");
}
}
}