This repository has been archived by the owner on Aug 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
SamlUtils.java
970 lines (742 loc) · 38.7 KB
/
SamlUtils.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
package com.dotcms.plugin.saml.v3;
import com.dotcms.plugin.saml.v3.config.Configuration;
import com.dotcms.plugin.saml.v3.exception.DotSamlException;
import com.dotcms.repackage.org.apache.commons.io.IOUtils;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
import net.shibboleth.utilities.java.support.resolver.Criterion;
import net.shibboleth.utilities.java.support.resolver.ResolverException;
import net.shibboleth.utilities.java.support.security.RandomIdentifierGenerationStrategy;
import org.joda.time.DateTime;
import org.opensaml.core.criterion.EntityIdCriterion;
import org.opensaml.core.xml.XMLObject;
import org.opensaml.core.xml.XMLObjectBuilderFactory;
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
import org.opensaml.core.xml.io.Marshaller;
import org.opensaml.core.xml.io.MarshallerFactory;
import org.opensaml.core.xml.io.MarshallingException;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.messaging.handler.MessageHandlerException;
import org.opensaml.messaging.handler.impl.BasicMessageHandlerChain;
import org.opensaml.saml.common.SAMLVersion;
import org.opensaml.saml.common.SignableSAMLObject;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.saml.saml2.core.*;
import org.opensaml.saml.saml2.encryption.Decrypter;
import org.opensaml.saml.saml2.metadata.Endpoint;
import org.opensaml.saml.saml2.metadata.SingleLogoutService;
import org.opensaml.saml.saml2.metadata.SingleSignOnService;
import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator;
import org.opensaml.security.credential.Credential;
import org.opensaml.security.credential.CredentialSupport;
import org.opensaml.security.credential.impl.KeyStoreCredentialResolver;
import org.opensaml.security.crypto.KeySupport;
import org.opensaml.xmlsec.encryption.support.DecryptionException;
import org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver;
import org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver;
import org.opensaml.xmlsec.signature.support.SignatureException;
import org.opensaml.xmlsec.signature.support.SignatureValidator;
import org.w3c.dom.Element;
import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.transform.OutputKeys;
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 java.io.File;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static com.dotcms.plugin.saml.v3.DotSamlConstants.DOT_SAML_DEFAULT_SERVICE_PROVIDER_PROTOCOL;
import static com.dotmarketing.util.UtilMethods.isSet;
/**
* Provides utils method for the Saml
* @author jsanca
*/
public class SamlUtils {
private final static RandomIdentifierGenerationStrategy secureRandomIdGenerator =
new RandomIdentifierGenerationStrategy();
private final static XMLObjectBuilderFactory builderFactory =
XMLObjectProviderRegistrySupport.getBuilderFactory();
private final static MarshallerFactory marshallerFactory =
XMLObjectProviderRegistrySupport.getMarshallerFactory();
private static final String DEFAULT_ELEMENT_NAME = "DEFAULT_ELEMENT_NAME";
public static final String SAML_SESSION_INDEX = "SAMLSessionIndex";
public static final String SAML_NAME_ID = "SAMLNameID";
public static final String SINGLE_LOGOUT_REASON = "urn:oasis:names:tc:SAML:2.0:logout:user";
private static Map<String, Credential> credentialMap = new ConcurrentHashMap<>();
private static Map<String, Credential> idpCredentialMap = new ConcurrentHashMap<>();
/**
* Build a SAML Object
* @param clazz
* @param <T>
* @return T
*/
public static <T> T buildSAMLObject(final Class<T> clazz) {
T object = null;
QName defaultElementName = null;
try {
defaultElementName = (QName)clazz.getDeclaredField
(DEFAULT_ELEMENT_NAME).get(null);
object = (T)builderFactory.getBuilder(defaultElementName)
.buildObject(defaultElementName);
} catch (IllegalAccessException e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
throw new IllegalArgumentException("Could not create SAML object");
} catch (NoSuchFieldException e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
throw new IllegalArgumentException("Could not create SAML object");
}
return object;
} // buildSAMLObject.
public static LogoutRequest buildLogoutRequest(final Configuration configuration,
final NameID nameID, final String sessionIndexValue) {
final LogoutRequest logoutRequest = buildSAMLObject(LogoutRequest.class);
final String idpSingleLogoutDestionation = getIPDSLODestination(configuration);
SessionIndex sessionIndex = null;
logoutRequest.setIssueInstant(new DateTime());
logoutRequest.setID(generateSecureRandomId());
// IDP logout url
if (!isSet(idpSingleLogoutDestionation)) {
Logger.error(SamlUtils.class, "The idpSingleLogoutDestionation is not set in the idp metadata, neither the configuration files");
throw new DotSamlException("The property: " + DotSamlConstants.DOTCMS_SAML_IDENTITY_PROVIDER_DESTINATION_SLO_URL +
" must be set on the host");
}
if (!isSet(nameID) || !isSet(sessionIndexValue)) {
Logger.error(SamlUtils.class, "The nameID or sessionIndex are null");
throw new DotSamlException("The nameID or sessionIndex are null");
}
Logger.debug(SamlUtils.class, "NameID: " + nameID + ", SessionIndex: " + sessionIndexValue);
// id for the sender
logoutRequest.setDestination(idpSingleLogoutDestionation);
logoutRequest.setIssuer(buildIssuer(configuration));
final NameID newNameID = buildSAMLObject(NameID.class);
newNameID.setValue(nameID.getValue());
newNameID.setFormat(nameID.getFormat());
logoutRequest.setNameID(newNameID);
sessionIndex = buildSAMLObject(SessionIndex.class);
sessionIndex.setSessionIndex(sessionIndexValue);
logoutRequest.getSessionIndexes().add(sessionIndex);
logoutRequest.setReason(SINGLE_LOGOUT_REASON);
logoutRequest.setVersion(SAMLVersion.VERSION_20);
return logoutRequest;
} // buildLogoutRequest
/**
* Return the value of the /AuthnStatement@SessionIndex element in an assertion
*
* @return The value. <code>null</code>, if the assertion does not
* contain the element.
*/
public static String getSessionIndex(final Assertion assertion) {
String sessionIndex = null;
if (assertion != null && assertion.getAuthnStatements() != null) {
if (assertion.getAuthnStatements().size() > 0) {
// We only look into the first AuthnStatement
AuthnStatement authnStatement = assertion.getAuthnStatements().get(0);
sessionIndex = authnStatement.getSessionIndex();
}
}
return sessionIndex;
} // getSessionIndex.
/**
* Build an authentication request.
* @return AuthnRequest
*/
public static AuthnRequest buildAuthnRequest(final HttpServletRequest request, final Configuration configuration) {
final String ipDSSODestination = getIPDSSODestination(configuration);
final AuthnRequest authnRequest = buildSAMLObject(AuthnRequest.class);
// this ensure that the message redirected is not too old
authnRequest.setIssueInstant(new DateTime());
// IDP url
if (!isSet(ipDSSODestination)) {
Logger.error(SamlUtils.class, "The ipDSSODestination is not set in the idp metadata, neither the configuration files");
throw new DotSamlException("The property: " + DotSamlConstants.DOTCMS_SAML_IDENTITY_PROVIDER_DESTINATION_SSO_URL +
" must be set on the host");
}
authnRequest.setDestination(ipDSSODestination);
// Get the protocol from the user, or use a default one: SAMLConstants.SAML2_ARTIFACT_BINDING_URI
authnRequest.setProtocolBinding
(configuration.getStringProperty(DotSamlConstants.DOTCMS_SAML_PROTOCOL_BINDING,
SAMLConstants.SAML2_ARTIFACT_BINDING_URI));
// this is the address that receives the SAML Assertion, after a successful authentication on the IdP.
authnRequest.setAssertionConsumerServiceURL(getAssertionConsumerEndpoint(request, configuration));
// this is a uid or random id just to identified the response.
authnRequest.setID(generateSecureRandomId());
// id for the sender
authnRequest.setIssuer(buildIssuer(configuration));
authnRequest.setNameIDPolicy(buildNameIdPolicy(configuration));
authnRequest.setRequestedAuthnContext(buildRequestedAuthnContext(configuration));
authnRequest.setVersion(SAMLVersion.VERSION_20);
authnRequest.setForceAuthn(configuration.getBooleanProperty
(DotSamlConstants.DOTCMS_SAML_FORCE_AUTHN, false));
return authnRequest;
} // buildAuthnRequest.
/**
* Gets from the dotmarketing-config.properties the destination sso url
* @return String
*/
public static String getIPDSSODestination(final Configuration configuration) {
final String redirectIdentityProviderDestinationSSOURL =
configuration.getIdentityProviderDestinationSSOURL(configuration);
// first check the meta data info., secondly the configuration
return (null != redirectIdentityProviderDestinationSSOURL)?
redirectIdentityProviderDestinationSSOURL:
configuration.getStringProperty(
DotSamlConstants.DOTCMS_SAML_IDENTITY_PROVIDER_DESTINATION_SSO_URL, null);
} // getIPDSSODestination.
/**
* Gets from the dotmarketing-config.properties the destination slo url
* @return String
*/
public static String getIPDSLODestination(final Configuration configuration) {
final String redirectIdentityProviderDestinationSLOURL =
configuration.getIdentityProviderDestinationSLOURL(configuration);
// first check the meta data info., secondly the configuration
return (null != redirectIdentityProviderDestinationSLOURL)?
redirectIdentityProviderDestinationSLOURL:
configuration.getStringProperty(
DotSamlConstants.DOTCMS_SAML_IDENTITY_PROVIDER_DESTINATION_SLO_URL, null);
} // getIPDSSODestination.
public static String getAssertionConsumerEndpoint(final HttpServletRequest request, final Configuration configuration) {
final String assertionConsumerEndpoint =
configuration.getAssertionConsumerEndpoint();
// this is the same original request. Consequently where should be redirected when the authentication is done.
final StringBuilder builder = new StringBuilder(request.getRequestURI());
if (null != request.getQueryString()) {
builder.append('?')
.append(request.getQueryString());
}
return (null != assertionConsumerEndpoint)?
assertionConsumerEndpoint:
builder.toString();
} // getAssertionConsumerEndpoint.
/**
* Generate the Random id
* @return String
*/
public static String generateSecureRandomId() {
return secureRandomIdGenerator.generateIdentifier();
} // generateSecureRandomId.
/**
* Build the Id for the sender.
* @return Issuer
*/
public static Issuer buildIssuer(final Configuration configuration) {
final Issuer issuer =
buildSAMLObject(Issuer.class);
issuer.setValue(getSPIssuerValue(configuration));
return issuer;
} // buildIssuer.
/**
* Get the od for the Issuer, it is the SP identifier on the IdP
* @return String
*/
public static String getSPIssuerValue(final Configuration configuration) {
final String defaultHost = configuration.getSiteName();
return configuration.getStringProperty(
DotSamlConstants.DOTCMS_SAML_SERVICE_PROVIDER_ISSUER,
getSiteName(configuration));
} // getSPIssuerValue.
private static String getSiteName (final Configuration configuration) {
final String defaultHost = configuration.getSiteName();
if (UtilMethods.isSet (defaultHost)) {
return !(defaultHost.trim().startsWith(Configuration.HTTP_SCHEMA) || defaultHost.trim().startsWith(Configuration.HTTPS_SCHEMA))?
Configuration.HTTPS_SCHEMA + defaultHost: defaultHost;
}
return
configuration.getStringProperty(DOT_SAML_DEFAULT_SERVICE_PROVIDER_PROTOCOL, Configuration.HTTPS_SCHEMA) + "://"
+ SPIIssuerResolver.getDefaultServiceProviderIssuer().getHostname();
} // getSiteName.
/**
* Return the policy for the Name ID (which is the IdP identifier for the user)
* @return NameIDPolicy
*/
public static NameIDPolicy buildNameIdPolicy(final Configuration configuration) {
final NameIDPolicy nameIDPolicy = buildSAMLObject(NameIDPolicy.class);
// True if you want that when the user does not exists, allows to create
nameIDPolicy.setAllowCreate(configuration.getBooleanProperty(DotSamlConstants.DOTCMS_SAML_POLICY_ALLOW_CREATE, false));
// todo: should set the SPNameQualifier
// it supports several formats, such as Kerberos, email, Windows Domain Qualified Name, etc.
nameIDPolicy.setFormat(configuration.getStringProperty(
DotSamlConstants.DOTCMS_SAML_NAME_ID_POLICY_FORMAT,
// “The transient identifier is a random identifier that does not have any connection to the user. A transient identifier will be different for every time the user signs in.”
NameIDType.PERSISTENT));
return nameIDPolicy;
} // buildNameIdPolicy.
/**
* if(Properties.getBoolean(Constants.ADD_AUTHN_POLICYNAME,true)){
final NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
nameIdPolicy.setFormat(Properties.getString(Constants.POLICYNAME_FORMAT,Constants.NAMEID_TRASIENT_FORMAT));
nameIdPolicy.setSPNameQualifier(Properties.getString(Constants.POLICYNAME_SPNAMEQUALIFIER,Constants.ISSUER));
nameIdPolicy.setAllowCreate(true);
authRequest.setNameIDPolicy(nameIdPolicy);
}
*/
// todo: keep in mind more than one authentication can be defined
/**
* Build the Authentication context, with the login and password strategies
* @return RequestedAuthnContext
*/
public static RequestedAuthnContext buildRequestedAuthnContext(final Configuration configuration) {
final RequestedAuthnContext requestedAuthnContext =
buildSAMLObject(RequestedAuthnContext.class);
requestedAuthnContext.setComparison
(getAuthnContextComparisonTypeEnumeration(configuration));
final AuthnContextClassRef passwordAuthnContextClassRef =
buildSAMLObject(AuthnContextClassRef.class);
passwordAuthnContextClassRef.setAuthnContextClassRef
(configuration.getStringProperty(DotSamlConstants.DOTCMS_SAML_AUTHN_CONTEXT_CLASS_REF,
AuthnContext.PASSWORD_AUTHN_CTX));
requestedAuthnContext.getAuthnContextClassRefs().
add(passwordAuthnContextClassRef);
return requestedAuthnContext;
} // buildRequestedAuthnContext.
/**
* Based on the configuration properties get the desire comparison type
* @return AuthnContextComparisonTypeEnumeration
*/
public static AuthnContextComparisonTypeEnumeration getAuthnContextComparisonTypeEnumeration(final Configuration configuration) {
AuthnContextComparisonTypeEnumeration comparisonTypeEnumeration =
AuthnContextComparisonTypeEnumeration.MINIMUM;
final String enumName = configuration.getStringProperty
(DotSamlConstants.DOTCMS_SAML_AUTHN_COMPARISON_TYPE, null);
if (isSet(enumName)) {
if (AuthnContextComparisonTypeEnumeration.BETTER.toString().equalsIgnoreCase(enumName)) {
comparisonTypeEnumeration = AuthnContextComparisonTypeEnumeration.BETTER;
} else if (AuthnContextComparisonTypeEnumeration.EXACT.toString().equalsIgnoreCase(enumName)) {
comparisonTypeEnumeration = AuthnContextComparisonTypeEnumeration.EXACT;
} else if (AuthnContextComparisonTypeEnumeration.MAXIMUM.toString().equalsIgnoreCase(enumName)) {
comparisonTypeEnumeration = AuthnContextComparisonTypeEnumeration.MAXIMUM;
} // MINIMUN is not necessary since it is the default one.
}
return comparisonTypeEnumeration;
} // getAuthnContextComparisonTypeEnumeration.
/**
* Get the Logout Identity Provider Destination
* @return Endpoint
*/
public static Endpoint getIdentityProviderSLODestinationEndpoint(final Configuration configuration) {
final SingleLogoutService endpoint = buildSAMLObject(SingleLogoutService.class);
endpoint.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
endpoint.setLocation(getIPDSLODestination(configuration));
return endpoint;
} // getIdentityProviderSLODestinationEndpoint.
/**
* Get the Identity Provider Destination
* @return Endpoint
*/
public static Endpoint getIdentityProviderDestinationEndpoint(final Configuration configuration) {
final SingleSignOnService endpoint = buildSAMLObject(SingleSignOnService.class);
endpoint.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
endpoint.setLocation(getIPDSSODestination(configuration));
return endpoint;
} // getIdentityProviderDestinationEndpoint.
/**
* Get the Assertion decrypted
* @param artifactResponse {@link ArtifactResponse}
* @return Assertion
*/
public static Assertion getAssertion(final ArtifactResponse artifactResponse,
final Configuration configuration) {
final EncryptedAssertion encryptedAssertion = getEncryptedAssertion(artifactResponse);
final Assertion assertion = decryptAssertion(encryptedAssertion, configuration); /// this is the user message itself
return assertion;
} // getAssertion.
/**
* Get the Assertion decrypted
* @param response {@link Response}
* @return Assertion
*/
public static Assertion getAssertion(final Response response,
final Configuration configuration) {
final EncryptedAssertion encryptedAssertion;
Assertion assertion = null;
if (configuration.getBooleanProperty(DotSamlConstants.DOTCMS_SAML_IS_ASSERTION_ENCRYPTED, true)) {
encryptedAssertion = response.getEncryptedAssertions().get(0);
assertion = decryptAssertion(encryptedAssertion, configuration); /// this is the user message itself
} else {
assertion = response.getAssertions().get(0);
}
return assertion;
} // getAssertion.
/**
* Just get the Encrypted assertion from the {@link ArtifactResponse}
* @param artifactResponse {@link ArtifactResponse}
* @return EncryptedAssertion
*/
public static EncryptedAssertion getEncryptedAssertion(final ArtifactResponse artifactResponse) {
final Response response = (Response)artifactResponse.getMessage();
return response.getEncryptedAssertions().get(0);
} // getEncryptedAssertion.
/**
* Decrypt an {@link EncryptedAssertion}
* @param encryptedAssertion {@link EncryptedAssertion}
* @return Assertion
*/
public static Assertion decryptAssertion(final EncryptedAssertion encryptedAssertion,
final Configuration configuration) {
Assertion assertion = null;
final StaticKeyInfoCredentialResolver keyInfoCredentialResolver =
new StaticKeyInfoCredentialResolver(getCredential(configuration));
final Decrypter decrypter = new Decrypter(null,
keyInfoCredentialResolver, new InlineEncryptedKeyResolver());
try {
decrypter.setRootInNewDocument(true);
assertion = decrypter.decrypt(encryptedAssertion);
} catch (DecryptionException e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
throw new DotSamlException(e.getMessage(), e);
}
return assertion;
} // decryptAssertion.
private static void validateSignature(final Assertion assertion,
final Collection<Credential> credentials) throws SignatureException {
for (Credential credential : credentials) {
try {
SignatureValidator.validate(assertion.getSignature(), credential);
return;
} catch (SignatureException ignore) {
Logger.info(SamlUtils.class, "Validation failed with credential: " + ignore.getMessage());
//Logger.error(SamlUtils.class, "Validation failed with credential", ignore);
}
}
throw new SignatureException("Signature cannot be validated");
} // validateSignature.
/**
* Does the verification of the assertiong
* @param assertion {@link Assertion}
*/
public static void verifyAssertionSignature(final Assertion assertion,
final Configuration configuration) {
final SAMLSignatureProfileValidator profileValidator;
if (configuration.getBooleanProperty(DotSamlConstants.DOTCMS_SAML_CHECKIF_ASSERTION_SIGNED, true) && !assertion.isSigned()) {
Logger.error(SamlUtils.class, "The assertion is not signed...");
throw new DotSamlException("The SAML Assertion was not signed");
}
try {
if (configuration.isVerifySignatureProfileNeeded()) {
Logger.debug(SamlUtils.class, "Doing Profile Validation");
profileValidator = new SAMLSignatureProfileValidator();
profileValidator.validate(assertion.getSignature());
Logger.debug(SamlUtils.class, "Done Profile Validation");
} else {
Logger.debug(SamlUtils.class, "Skipping the Verify Signature Profile check");
}
// Ask on the config if the app wants signature validator
if (configuration.isVerifySignatureCredentialsNeeded()) {
if (null != configuration.getSigningCredentials ()) {
Logger.debug(SamlUtils.class, "Validating the signatures: " + configuration.getSigningCredentials ());
validateSignature(assertion, configuration.getSigningCredentials ());
Logger.debug(SamlUtils.class, "Doing signatures validation");
} else {
Logger.debug(SamlUtils.class, "Validating the signature with a IdP Credentials " );
SignatureValidator.validate(assertion.getSignature(), getIdPCredentials(configuration));
Logger.debug(SamlUtils.class, "Done validation of the signature with a IdP Credentials " );
}
} else {
Logger.debug(SamlUtils.class, "Skipping the Verify Signature Profile check");
}
Logger.debug(SamlUtils.class, "SAML Assertion signature verified");
} catch (SignatureException e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
throw new DotSamlException(e.getMessage(), e);
}
} // verifyAssertionSignature.
/**
* Read from the key store using a given password
* @param pathToKeyStore {@link String}
* @param keyStorePassword {@link String}
* @return KeyStore
*/
public static KeyStore readKeyStoreFromFile(final String pathToKeyStore,
final String keyStorePassword,
final String keyStoreType) {
final KeyStore keystore;
InputStream inputStream = null;
try {
keystore = KeyStore.getInstance(keyStoreType);
inputStream = InputStreamUtils.getInputStream(pathToKeyStore);
keystore.load(inputStream, keyStorePassword.toCharArray());
} catch (Exception e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
throw new DotSamlException("Something went wrong reading keystore", e);
} finally {
IOUtils.closeQuietly(inputStream);
}
return keystore;
} // readKeystoreFromFile.
public static Credential createCredential (final Configuration configuration) {
final Map<String, String> passwordMap = new HashMap<String, String>();
final KeyStoreCredentialResolver resolver;
final KeyStore keystore;
final Criterion criterion;
final String password;
final String keyStorePath;
final String keyEntryId;
final String keyStoreEntryPassword;
final CriteriaSet criteriaSet;
final CredentialProvider customCredentialProvider =
configuration.getServiceProviderCustomCredentialProvider();
Credential credential = null;
try {
if (null != customCredentialProvider) {
credential = customCredentialProvider.createCredential();
} else {
keyStorePath = configuration.getStringProperty(
DotSamlConstants.DOTCMS_SAML_KEY_STORE_PATH, "");
password = configuration.getStringProperty(
DotSamlConstants.DOTCMS_SAML_KEY_STORE_PASSWORD, "");
keyEntryId = configuration.getStringProperty(
DotSamlConstants.DOTCMS_SAML_KEY_ENTRY_ID, DotSamlConstants.DOTCMS_SAML_KEY_ENTRY_ID_DEFAULT_VALUE);
keyStoreEntryPassword = configuration.getStringProperty(
DotSamlConstants.DOTCMS_SAML_KEY_STORE_ENTRY_PASSWORD, password);
Logger.debug(SamlUtils.class, "Creating the credentials, using: " + password +
", key store path: " + keyStorePath + ", keyEntryId: " + keyEntryId +
", keyStoreEntryPassword: " + keyStoreEntryPassword);
final String keyStoreType = configuration.getStringProperty(
DotSamlConstants.DOTCMS_SAML_KEY_STORE_TYPE, KeyStore.getDefaultType());
keystore = readKeyStoreFromFile
(keyStorePath, password, keyStoreType);
passwordMap.put(keyEntryId, keyStoreEntryPassword);
resolver = new KeyStoreCredentialResolver(keystore, passwordMap);
criterion = new EntityIdCriterion(keyEntryId);
criteriaSet = new CriteriaSet();
criteriaSet.add(criterion);
credential = resolver.resolveSingle(criteriaSet);
Logger.debug(SamlUtils.class, "Created the credentials: " + credential);
}
} catch (ResolverException e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
throw new DotSamlException("Something went wrong reading credentials", e);
}
return credential;
} // createCredential.
/**
* Get the SP credential
* @return Credential
*/
public static Credential getCredential(final Configuration configuration) {
if (!credentialMap.containsKey(configuration.getSiteName())) {
final Credential credential = createCredential(configuration);
if (null != credential) {
credentialMap.put(configuration.getSiteName(), credential);
} else {
Logger.error(SamlUtils.class, "The credential is null for the site: " +
configuration.getSiteName());
throw new DotSamlException("The credential is null for the site: " +
configuration.getSiteName());
}
}
return credentialMap.get(configuration.getSiteName());
} // getCredential.
private static Credential createIdpCredential (final Configuration configuration) {
KeyPair keyPair = null;
final CredentialProvider customCredentialProvider =
configuration.getIdProviderCustomCredentialProvider();
Credential idpCredential = null;
try {
Logger.debug(SamlUtils.class, "Creating Idp credential");
if (null != customCredentialProvider) {
Logger.debug(SamlUtils.class, "Using custom credential provider");
idpCredential = customCredentialProvider.createCredential();
} else {
Logger.debug(SamlUtils.class, "Using standard credential algorithm");
// this fallback generates just a random keypair not very useful to validate the signature.
keyPair = KeySupport.generateKeyPair("RSA", 1024, null);
idpCredential =
CredentialSupport.getSimpleCredential(keyPair.getPublic(), keyPair.getPrivate());
}
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
throw new DotSamlException(e.getMessage(), e);
}
return idpCredential;
} // createIdpCredential.
public static Credential getIdPCredentials (final Configuration configuration) {
if (!idpCredentialMap.containsKey(configuration)) {
idpCredentialMap.put(configuration.getSiteName(),
createIdpCredential(configuration));
}
return idpCredentialMap.get(configuration.getSiteName());
} // getIdPCredentials.
/**
* Convert to String an {@link XMLObject}
* @param object {@link XMLObject}
* @return String
*/
public static String toXMLObjectString(final XMLObject object) {
final Element element =
(object instanceof SignableSAMLObject &&
SignableSAMLObject.class.cast(object).isSigned() &&
object.getDOM() != null)?
object.getDOM(): toElement(object);
return toElementString(element);
} // toString
/**
* Convert to String an {@link Element}
* @param element {@link Element}
* @return String
*/
public static String toElementString (final Element element) {
final Transformer transformer;
final StreamResult result;
final DOMSource source;
String xmlString = null;
try {
transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
result = new StreamResult(new StringWriter());
source = new DOMSource(element);
transformer.transform(source, result);
xmlString = result.getWriter().toString();
} catch (TransformerException e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
}
return xmlString;
} // toString.
public static Element toElement (final XMLObject object) {
final Marshaller out =
marshallerFactory.getMarshaller(object);
try {
out.marshall(object);
} catch (MarshallingException e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
}
return object.getDOM();
} // toElement.
/**
* Invoke a message handler chain
* @param handlerChain {@link BasicMessageHandlerChain}
* @param context MessageContext
*/
public static <T> void invokeMessageHandlerChain (final BasicMessageHandlerChain<T> handlerChain,
final MessageContext<T> context) {
try {
handlerChain.initialize();
handlerChain.doInvoke(context);
} catch (ComponentInitializationException | MessageHandlerException e) {
Logger.error(SamlUtils.class, e.getMessage(), e);
throw new DotSamlException(e.getMessage(), e);
}
} // invokeMessageHandlerChain.
/**
* Check if we can read the KeyStore from file using the SAML properties.
*
* @param samlProperties {@link Properties} with the values needed.
* @return
*/
public static Set<String> validateKeyStore(Properties samlProperties) {
Set<String> otherErrors = new HashSet<>();
final String pathToKeyStore = samlProperties.getProperty(DotSamlConstants.DOTCMS_SAML_KEY_STORE_PATH);
final String keyStorePassword = samlProperties.getProperty(DotSamlConstants.DOTCMS_SAML_KEY_STORE_PASSWORD);
final String keyStoreType = samlProperties.getProperty(DotSamlConstants.DOTCMS_SAML_KEY_STORE_TYPE, KeyStore.getDefaultType());
final String keyEntryId = UtilMethods.isSet(samlProperties.getProperty(DotSamlConstants.DOTCMS_SAML_KEY_ENTRY_ID))?
samlProperties.getProperty(DotSamlConstants.DOTCMS_SAML_KEY_ENTRY_ID):
DotSamlConstants.DOTCMS_SAML_KEY_ENTRY_ID_DEFAULT_VALUE;
final String keyStoreEntryPassword = (UtilMethods.isSet(samlProperties.getProperty(DotSamlConstants.DOTCMS_SAML_KEY_STORE_ENTRY_PASSWORD)))?
samlProperties.getProperty(DotSamlConstants.DOTCMS_SAML_KEY_STORE_ENTRY_PASSWORD):keyStorePassword;
Credential credential = null;
if ( pathToKeyStore != null
&& keyStorePassword != null
&& keyStoreType != null
&& keyEntryId != null
&& keyStoreEntryPassword != null) {
if (InputStreamUtils.isResourceFile(pathToKeyStore)) {
Logger.debug(SamlUtils.class,
"The " + pathToKeyStore + ", is a file, checking if exists and can read");
final File pathToKeyStoreFile = new File(InputStreamUtils.normalizeFile(pathToKeyStore));
if (!pathToKeyStoreFile.exists() || !pathToKeyStoreFile.canRead()) {
otherErrors.add("The Key Store path: " + pathToKeyStore + ", does not exists or can not read.");
return otherErrors;
}
}
try {
final KeyStore keystore = readKeyStoreFromFile(pathToKeyStore, keyStorePassword, keyStoreType);
final Map<String, String> passwordMap = new HashMap<>();
passwordMap.put(keyEntryId, keyStoreEntryPassword);
final KeyStoreCredentialResolver resolver =
new KeyStoreCredentialResolver(keystore, passwordMap);
final Criterion criterion = new EntityIdCriterion(keyEntryId);
final CriteriaSet criteriaSet = new CriteriaSet();
criteriaSet.add(criterion);
credential = resolver.resolveSingle(criteriaSet);
if (null == credential) {
otherErrors.add("Error reading Key Store, please check the: " +
DotSamlConstants.DOTCMS_SAML_KEY_ENTRY_ID);
}
} catch (DotSamlException e) {
otherErrors.add("Error reading Key Store");
} catch (ResolverException e) {
otherErrors.add("Error reading credentials");
}
}
return otherErrors;
} // validateKeyStore.
/**
* Check if the File Path exists, can access and read.
*
* @param properties {@link Properties} (Key, Value) = (PropertyName, FilePath).
* @param filePathPropertyKeys keys name that have File path in the value.
* @return
*/
public static Set<String> validateFiles(Properties properties, Set<String> filePathPropertyKeys) {
Set<String> missingFiles = new HashSet<>();
for (String fileField : filePathPropertyKeys) {
//If field is missing we don't need to validate.
Logger.debug(SamlUtils.class, "Validating the field: " + fileField);
if ( properties.getProperty(fileField) == null ) {
continue;
}
//Check if the file exists.
String filePath = properties.getProperty(fileField);
File file = new File(filePath);
if ( !file.exists() && !file.canRead() ) {
try {
//Let's try with the URI.
URI uri = new URI(filePath);
file = new File(uri);
if ( !file.exists() && !file.canRead() ) {
missingFiles.add(filePath);
}
} catch (URISyntaxException e){
Logger.debug(SamlUtils.class, "Problem reading file from URI: " + filePath, e);
missingFiles.add(fileField +": " + filePath);
} catch (Exception e) {
Logger.debug(SamlUtils.class, "Problem reading file from URI: " + filePath, e);
missingFiles.add(fileField +": " + filePath + " (" + e.getMessage() + ")");
}
}
}
return missingFiles;
} // validateFiles.
/**
* Validates that properties contains the keys required.
*
* @param properties {@link Properties} (Key, Value) = (PropertyName, FilePath).
* @param keysRequired Property keys required to be in the samlProperties.
* @return
*/
public static Set<String> getMissingProperties(final Properties properties,
final Set<String> keysRequired) {
final Set<String> missingProperties = new HashSet<>(); // todo: make this immutable on 4.x
for (String keyRequired : keysRequired) {
Logger.debug(SamlUtils.class, "Validating missing prop: " + keyRequired);
if ( properties.getProperty(keyRequired) == null || properties.getProperty(keyRequired).trim().equals("") ) {
missingProperties.add(keyRequired);
}
}
return missingProperties;
} // getMissingProperties.
} // E:O:F:SamlUtils.