2 * Copyright [2007] [University Corporation for Advanced Internet Development, Inc.]
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.List;
24 import org.joda.time.DateTime;
25 import org.opensaml.Configuration;
26 import org.opensaml.common.SAMLObjectBuilder;
27 import org.opensaml.common.SAMLVersion;
28 import org.opensaml.common.binding.encoding.SAMLMessageEncoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml2.core.Assertion;
31 import org.opensaml.saml2.core.AttributeQuery;
32 import org.opensaml.saml2.core.AttributeStatement;
33 import org.opensaml.saml2.core.Audience;
34 import org.opensaml.saml2.core.AudienceRestriction;
35 import org.opensaml.saml2.core.AuthnRequest;
36 import org.opensaml.saml2.core.Conditions;
37 import org.opensaml.saml2.core.Issuer;
38 import org.opensaml.saml2.core.NameID;
39 import org.opensaml.saml2.core.ProxyRestriction;
40 import org.opensaml.saml2.core.Response;
41 import org.opensaml.saml2.core.Statement;
42 import org.opensaml.saml2.core.Status;
43 import org.opensaml.saml2.core.StatusCode;
44 import org.opensaml.saml2.core.StatusMessage;
45 import org.opensaml.saml2.core.StatusResponseType;
46 import org.opensaml.saml2.core.Subject;
47 import org.opensaml.saml2.core.SubjectConfirmation;
48 import org.opensaml.saml2.core.SubjectConfirmationData;
49 import org.opensaml.saml2.encryption.Encrypter;
50 import org.opensaml.saml2.encryption.Encrypter.KeyPlacement;
51 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
52 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
53 import org.opensaml.saml2.metadata.Endpoint;
54 import org.opensaml.saml2.metadata.NameIDFormat;
55 import org.opensaml.saml2.metadata.PDPDescriptor;
56 import org.opensaml.saml2.metadata.RoleDescriptor;
57 import org.opensaml.saml2.metadata.SPSSODescriptor;
58 import org.opensaml.saml2.metadata.SSODescriptor;
59 import org.opensaml.security.MetadataCredentialResolver;
60 import org.opensaml.security.MetadataCriteria;
61 import org.opensaml.ws.message.encoder.MessageEncodingException;
62 import org.opensaml.ws.transport.http.HTTPInTransport;
63 import org.opensaml.xml.XMLObjectBuilder;
64 import org.opensaml.xml.encryption.EncryptionException;
65 import org.opensaml.xml.encryption.EncryptionParameters;
66 import org.opensaml.xml.encryption.KeyEncryptionParameters;
67 import org.opensaml.xml.io.Marshaller;
68 import org.opensaml.xml.io.MarshallingException;
69 import org.opensaml.xml.security.CriteriaSet;
70 import org.opensaml.xml.security.SecurityConfiguration;
71 import org.opensaml.xml.security.SecurityException;
72 import org.opensaml.xml.security.SecurityHelper;
73 import org.opensaml.xml.security.credential.Credential;
74 import org.opensaml.xml.security.credential.UsageType;
75 import org.opensaml.xml.security.criteria.EntityIDCriteria;
76 import org.opensaml.xml.security.criteria.UsageCriteria;
77 import org.opensaml.xml.signature.Signature;
78 import org.opensaml.xml.signature.SignatureException;
79 import org.opensaml.xml.signature.Signer;
80 import org.opensaml.xml.util.DatatypeHelper;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
84 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
85 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
86 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
87 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
88 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML2NameIDEncoder;
89 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
90 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
91 import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
92 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.CryptoOperationRequirementLevel;
93 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
94 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
95 import edu.internet2.middleware.shibboleth.idp.session.Session;
97 /** Common implementation details for profile handlers. */
98 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
100 /** SAML Version for this profile handler. */
101 public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
104 private Logger log = LoggerFactory.getLogger(AbstractSAML2ProfileHandler.class);
106 /** For building response. */
107 private SAMLObjectBuilder<Response> responseBuilder;
109 /** For building status. */
110 private SAMLObjectBuilder<Status> statusBuilder;
112 /** For building statuscode. */
113 private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
115 /** For building StatusMessages. */
116 private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
118 /** For building assertion. */
119 private SAMLObjectBuilder<Assertion> assertionBuilder;
121 /** For building issuer. */
122 private SAMLObjectBuilder<Issuer> issuerBuilder;
124 /** For building subject. */
125 private SAMLObjectBuilder<Subject> subjectBuilder;
127 /** For building subject confirmation. */
128 private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
130 /** For building subject confirmation data. */
131 private SAMLObjectBuilder<SubjectConfirmationData> subjectConfirmationDataBuilder;
133 /** For building conditions. */
134 private SAMLObjectBuilder<Conditions> conditionsBuilder;
136 /** For building audience restriction. */
137 private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
139 /** For building proxy retrictions. */
140 private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
142 /** For building audience. */
143 private SAMLObjectBuilder<Audience> audienceBuilder;
145 /** For building signature. */
146 private XMLObjectBuilder<Signature> signatureBuilder;
149 @SuppressWarnings("unchecked")
150 protected AbstractSAML2ProfileHandler() {
153 responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
154 statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
155 statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
156 StatusCode.DEFAULT_ELEMENT_NAME);
157 statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
158 StatusMessage.DEFAULT_ELEMENT_NAME);
159 issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
160 assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
161 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
162 subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
163 subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
164 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
165 subjectConfirmationDataBuilder = (SAMLObjectBuilder<SubjectConfirmationData>) getBuilderFactory().getBuilder(
166 SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
167 conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
168 Conditions.DEFAULT_ELEMENT_NAME);
169 audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
170 AudienceRestriction.DEFAULT_ELEMENT_NAME);
171 proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
172 ProxyRestriction.DEFAULT_ELEMENT_NAME);
173 audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
174 signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
178 protected void populateRequestContext(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
179 BaseSAML2ProfileRequestContext saml2Request = (BaseSAML2ProfileRequestContext) requestContext;
181 super.populateRequestContext(requestContext);
182 } catch (ProfileException e) {
183 if (saml2Request.getFailureStatus() == null) {
184 saml2Request.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null, e.getMessage()));
191 * Populates the request context with the information about the user.
193 * This method requires the the following request context properties to be populated: inbound message transport,
196 * This methods populates the following request context properties: user's session, user's principal name, and
197 * service authentication method
199 * @param requestContext current request context
201 protected void populateUserInformation(BaseSAMLProfileRequestContext requestContext) {
202 Session userSession = getUserSession(requestContext.getInboundMessageTransport());
203 if (userSession == null) {
204 NameID subject = (NameID) requestContext.getSubjectNameIdentifier();
205 if (subject != null && subject.getValue() != null) {
206 userSession = getUserSession(subject.getValue());
210 if (userSession != null) {
211 requestContext.setUserSession(userSession);
212 requestContext.setPrincipalName(userSession.getPrincipalName());
213 requestContext.setPrincipalAuthenticationMethod(userSession.getServicesInformation().get(
214 requestContext.getPeerEntityId()).getAuthenticationMethod().getAuthenticationMethod());
219 * Checks that the SAML major version for a request is 2.
221 * @param requestContext current request context containing the SAML message
223 * @throws ProfileException thrown if the major version of the SAML request is not 2
225 protected void checkSamlVersion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
226 SAMLVersion version = requestContext.getInboundSAMLMessage().getVersion();
227 if (version.getMajorVersion() < 2) {
228 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
229 StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
230 throw new ProfileException("SAML request version too low");
231 } else if (version.getMajorVersion() > 2 || version.getMinorVersion() > 0) {
232 requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
233 StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
234 throw new ProfileException("SAML request version too high");
239 * Builds a response to the attribute query within the request context.
241 * @param requestContext current request context
242 * @param subjectConfirmationMethod confirmation method used for the subject
243 * @param statements the statements to include in the response
245 * @return the built response
247 * @throws ProfileException thrown if there is a problem creating the SAML response
249 protected Response buildResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
250 String subjectConfirmationMethod, List<Statement> statements) throws ProfileException {
252 DateTime issueInstant = new DateTime();
254 Subject subject = buildSubject(requestContext, subjectConfirmationMethod, issueInstant);
256 // create the assertion and add the attribute statement
257 Assertion assertion = buildAssertion(requestContext, issueInstant);
258 assertion.setSubject(subject);
259 if (statements != null && !statements.isEmpty()) {
260 assertion.getStatements().addAll(statements);
263 // create the SAML response and add the assertion
264 Response samlResponse = responseBuilder.buildObject();
265 samlResponse.setIssueInstant(issueInstant);
266 populateStatusResponse(requestContext, samlResponse);
268 // sign the assertion if it should be signed
269 signAssertion(requestContext, assertion);
271 SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
273 if (requestContext.getProfileConfiguration().getEncryptAssertion() == CryptoOperationRequirementLevel.always
274 || (requestContext.getProfileConfiguration().getEncryptAssertion() == CryptoOperationRequirementLevel.conditional && !encoder
275 .providesMessageConfidentiality(requestContext))) {
276 log.debug("Attempting to encrypt assertion to relying party {}", requestContext
277 .getInboundMessageIssuer());
279 Encrypter encrypter = getEncrypter(requestContext.getInboundMessageIssuer());
280 samlResponse.getEncryptedAssertions().add(encrypter.encrypt(assertion));
281 } catch (SecurityException e) {
282 log.error("Unable to construct encrypter", e);
283 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
284 "Unable to encrypt assertion"));
285 throw new ProfileException("Unable to construct encrypter", e);
286 } catch (EncryptionException e) {
287 log.error("Unable to encrypt assertion", e);
288 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
289 "Unable to encrypt assertion"));
290 throw new ProfileException("Unable to encrypt assertion", e);
293 samlResponse.getAssertions().add(assertion);
295 } catch (MessageEncodingException e) {
296 log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
298 throw new ProfileException("Unable to determine if assertions should be encrypted");
301 Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
302 samlResponse.setStatus(status);
308 * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
310 * @param requestContext current request context
311 * @param issueInstant time to use as assertion issue instant
313 * @return the built assertion
315 protected Assertion buildAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
316 Assertion assertion = assertionBuilder.buildObject();
317 assertion.setID(getIdGenerator().generateIdentifier());
318 assertion.setIssueInstant(issueInstant);
319 assertion.setVersion(SAMLVersion.VERSION_20);
320 assertion.setIssuer(buildEntityIssuer(requestContext));
322 Conditions conditions = buildConditions(requestContext, issueInstant);
323 assertion.setConditions(conditions);
329 * Creates an {@link Issuer} populated with information about the relying party.
331 * @param requestContext current request context
333 * @return the built issuer
335 protected Issuer buildEntityIssuer(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
336 Issuer issuer = issuerBuilder.buildObject();
337 issuer.setFormat(Issuer.ENTITY);
338 issuer.setValue(requestContext.getLocalEntityId());
344 * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
345 * restrictions, and proxy restrictions.
347 * @param requestContext current request context
348 * @param issueInstant timestamp the assertion was created
350 * @return constructed conditions
352 protected Conditions buildConditions(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
353 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
355 Conditions conditions = conditionsBuilder.buildObject();
356 conditions.setNotBefore(issueInstant);
357 conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
359 Collection<String> audiences;
361 // add audience restrictions
362 AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
363 // TODO we should only do this for certain outgoing bindings, not globally
364 Audience audience = audienceBuilder.buildObject();
365 audience.setAudienceURI(requestContext.getInboundMessageIssuer());
366 audienceRestriction.getAudiences().add(audience);
367 audiences = profileConfig.getAssertionAudiences();
368 if (audiences != null && audiences.size() > 0) {
369 for (String audienceUri : audiences) {
370 audience = audienceBuilder.buildObject();
371 audience.setAudienceURI(audienceUri);
372 audienceRestriction.getAudiences().add(audience);
375 conditions.getAudienceRestrictions().add(audienceRestriction);
377 // add proxy restrictions
378 audiences = profileConfig.getProxyAudiences();
379 if (audiences != null && audiences.size() > 0) {
380 ProxyRestriction proxyRestriction = proxyRestrictionBuilder.buildObject();
381 for (String audienceUri : audiences) {
382 audience = audienceBuilder.buildObject();
383 audience.setAudienceURI(audienceUri);
384 proxyRestriction.getAudiences().add(audience);
387 proxyRestriction.setProxyCount(profileConfig.getProxyCount());
388 conditions.getConditions().add(proxyRestriction);
395 * Populates the response's id, in response to, issue instant, version, and issuer properties.
397 * @param requestContext current request context
398 * @param response the response to populate
400 protected void populateStatusResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
401 StatusResponseType response) {
402 response.setID(getIdGenerator().generateIdentifier());
403 if (requestContext.getInboundSAMLMessage() != null) {
404 response.setInResponseTo(requestContext.getInboundSAMLMessageId());
406 response.setVersion(SAMLVersion.VERSION_20);
407 response.setIssuer(buildEntityIssuer(requestContext));
411 * Resolves the attributes for the principal.
413 * @param requestContext current request context
415 * @throws ProfileException thrown if there is a problem resolved attributes
417 protected void resolveAttributes(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
418 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
419 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
422 log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
423 .getPrincipalName(), requestContext.getInboundMessageIssuer());
424 Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
426 requestContext.setAttributes(principalAttributes);
427 } catch (AttributeRequestException e) {
428 log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
429 + " from relying party " + requestContext.getInboundMessageIssuer(), e);
430 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
431 throw new ProfileException("Error resolving attributes for SAML request "
432 + requestContext.getInboundSAMLMessageId() + " from relying party "
433 + requestContext.getInboundMessageIssuer(), e);
438 * Executes a query for attributes and builds a SAML attribute statement from the results.
440 * @param requestContext current request context
442 * @return attribute statement resulting from the query
444 * @throws ProfileException thrown if there is a problem making the query
446 protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
447 throws ProfileException {
448 log.debug("Creating attribute statement in response to SAML request {} from relying party {}", requestContext
449 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
451 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
452 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
454 if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
455 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
456 .getInboundSAMLMessage(), requestContext.getAttributes().values());
458 return attributeAuthority.buildAttributeStatement(null, requestContext.getAttributes().values());
460 } catch (AttributeRequestException e) {
461 log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
462 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
463 throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
469 * Resolves the principal name of the subject of the request.
471 * @param requestContext current request context
473 * @throws ProfileException thrown if the principal name can not be resolved
475 protected void resolvePrincipal(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
476 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
477 if (profileConfiguration == null) {
478 log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
479 + requestContext.getInboundMessageIssuer());
480 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
481 "Error resolving principal"));
482 throw new ProfileException(
483 "Unable to resolve principal, no SAML 2 profile configuration for relying party "
484 + requestContext.getInboundMessageIssuer());
486 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
487 log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
488 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
491 String principal = attributeAuthority.getPrincipal(requestContext);
492 requestContext.setPrincipalName(principal);
493 } catch (AttributeRequestException e) {
494 log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
495 + " from relying party " + requestContext.getInboundMessageIssuer(), e);
496 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
497 "Error resolving principal"));
498 throw new ProfileException("Error resolving attributes for SAML request "
499 + requestContext.getInboundSAMLMessageId() + " from relying party "
500 + requestContext.getInboundMessageIssuer(), e);
505 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
506 * signing credentials.
508 * @param requestContext current request context
509 * @param assertion assertion to sign
511 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
512 * required, if a signing credential is not configured
514 protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
515 throws ProfileException {
516 log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
517 .getInboundMessageIssuer());
519 boolean signAssertion = false;
521 SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
522 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
524 if (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.always
525 || (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.conditional && !encoder
526 .providesMessageIntegrity(requestContext))) {
527 signAssertion = true;
528 log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
529 .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
531 } catch (MessageEncodingException e) {
532 log.error("Unable to determine if outbound encoding {} can provide integrity protection", encoder
534 throw new ProfileException("Unable to determine if outbound message should be signed");
537 if (!signAssertion && requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
538 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
539 if (ssoDescriptor.getWantAssertionsSigned() != null) {
540 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
541 log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
542 .getInboundMessageIssuer(), signAssertion);
546 if (!signAssertion) {
550 log.debug("Determining signing credntial for assertion to relying party {}", requestContext
551 .getInboundMessageIssuer());
552 Credential signatureCredential = profileConfig.getSigningCredential();
553 if (signatureCredential == null) {
554 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
557 if (signatureCredential == null) {
558 throw new ProfileException("No signing credential is specified for relying party configuration "
559 + requestContext.getRelyingPartyConfiguration().getProviderId()
560 + " or it's SAML2 attribute query profile configuration");
563 log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
564 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
566 signature.setSigningCredential(signatureCredential);
568 // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
569 // TODO how to pull what keyInfoGenName to use?
570 SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
571 } catch (SecurityException e) {
572 throw new ProfileException("Error preparing signature for signing", e);
575 assertion.setSignature(signature);
577 Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
579 assertionMarshaller.marshall(assertion);
580 Signer.signObject(signature);
581 } catch (MarshallingException e) {
582 log.error("Unable to marshall assertion for signing", e);
583 throw new ProfileException("Unable to marshall assertion for signing", e);
584 } catch (SignatureException e) {
585 log.error("Unable to sign assertion", e);
586 throw new ProfileException("Unable to sign assertion", e);
591 * Build a status message, with an optional second-level failure message.
593 * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
594 * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
595 * null, no second-level Status element will be set.
596 * @param failureMessage An optional second-level failure message
598 * @return a Status object.
600 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
601 Status status = statusBuilder.buildObject();
603 StatusCode statusCode = statusCodeBuilder.buildObject();
604 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
605 status.setStatusCode(statusCode);
607 if (secondLevelCode != null) {
608 StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
609 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
610 statusCode.setStatusCode(secondLevelStatusCode);
613 if (failureMessage != null) {
614 StatusMessage msg = statusMessageBuilder.buildObject();
615 msg.setMessage(failureMessage);
616 status.setStatusMessage(msg);
623 * Builds the SAML subject for the user for the service provider.
625 * @param requestContext current request context
626 * @param confirmationMethod subject confirmation method used for the subject
627 * @param issueInstant instant the subject confirmation data should reflect for issuance
629 * @return SAML subject for the user for the service provider
631 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
632 * name ID attribute or because there are no supported name formats
634 protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
635 DateTime issueInstant) throws ProfileException {
636 NameID nameID = buildNameId(requestContext);
637 requestContext.setSubjectNameIdentifier(nameID);
639 SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
640 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
641 confirmationData.setAddress(inTransport.getPeerAddress());
642 confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
643 confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
644 .getAssertionLifetime()));
646 Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
647 if (relyingPartyEndpoint != null) {
648 if (relyingPartyEndpoint.getResponseLocation() != null) {
649 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
651 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
655 SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
656 subjectConfirmation.setMethod(confirmationMethod);
657 subjectConfirmation.setSubjectConfirmationData(confirmationData);
659 Subject subject = subjectBuilder.buildObject();
660 subject.getSubjectConfirmations().add(subjectConfirmation);
661 SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
663 if (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.always
664 || (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.conditional && !encoder
665 .providesMessageConfidentiality(requestContext))) {
666 log.debug("Attempting to encrypt NameID to relying party {}", requestContext.getInboundMessageIssuer());
668 Encrypter encrypter = getEncrypter(requestContext.getInboundMessageIssuer());
669 subject.setEncryptedID(encrypter.encrypt(nameID));
670 } catch (SecurityException e) {
671 log.error("Unable to construct encrypter", e);
672 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
673 "Unable to construct NameID"));
674 throw new ProfileException("Unable to construct encrypter", e);
675 } catch (EncryptionException e) {
676 log.error("Unable to encrypt NameID", e);
677 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
678 "Unable to construct NameID"));
679 throw new ProfileException("Unable to encrypt NameID", e);
682 subject.setNameID(nameID);
684 } catch (MessageEncodingException e) {
685 log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
687 throw new ProfileException("Unable to determine if assertions should be encrypted");
694 * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
695 * picking a name format that was requested by the relying party or is mutually supported by both the relying party
696 * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
697 * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
698 * the supported name formats.
700 * @param requestContext current request context
702 * @return the NameID appropriate for this request
704 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
705 * name ID attribute or because there are no supported name formats
707 protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
708 log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
709 requestContext.getInboundMessageIssuer());
711 Map<String, BaseAttribute> principalAttributes = requestContext.getAttributes();
712 if (principalAttributes == null || principalAttributes.isEmpty()) {
713 log.error("No attributes for principal {}, unable to construct of NameID", requestContext
714 .getPrincipalName());
715 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
716 "Unable to construct NameID"));
717 throw new ProfileException("No principal attributes support NameID construction");
720 List<String> supportedNameFormats = getNameFormats(requestContext);
721 if (supportedNameFormats == null || supportedNameFormats.isEmpty()) {
722 log.error("No common NameID formats supported by SP {} and IdP", requestContext.getInboundMessageIssuer());
723 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
724 "Unable to construct NameID"));
725 throw new ProfileException("No principal attributes support NameID construction");
728 log.debug("Supported NameID formats: {}", supportedNameFormats);
730 SAML2NameIDEncoder nameIdEncoder;
731 for (BaseAttribute<?> attribute : principalAttributes.values()) {
732 for (AttributeEncoder encoder : attribute.getEncoders()) {
733 if (encoder instanceof SAML2NameIDEncoder) {
734 nameIdEncoder = (SAML2NameIDEncoder) encoder;
735 if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
736 log.debug("Using attribute {} suppoting NameID format {} to create the NameID.", attribute
737 .getId(), nameIdEncoder.getNameFormat());
738 return nameIdEncoder.encode(attribute);
744 log.error("No principal attribute supported encoding into a supported name ID format.");
745 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
746 throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
747 } catch (AttributeEncodingException e) {
748 log.error("Unable to encode NameID attribute", e);
749 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
750 throw new ProfileException("Unable to encode NameID attribute", e);
755 * Gets the NameID format to use when creating NameIDs for the relying party.
757 * @param requestContext current request context
759 * @return list of nameID formats that may be used with the relying party
761 * @throws ProfileException thrown if there is a problem determing the NameID format to use
763 protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
764 throws ProfileException {
765 ArrayList<String> nameFormats = new ArrayList<String>();
767 // Determine name formats supported by both SP and IdP
768 RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
769 if (relyingPartyRole != null) {
770 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
771 if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
772 nameFormats.addAll(relyingPartySupportedFormats);
774 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
775 if (assertingPartyRole != null) {
776 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
777 if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
778 nameFormats.retainAll(assertingPartySupportedFormats);
784 if (nameFormats.isEmpty()) {
785 nameFormats.add("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
788 // If authn request and name ID policy format specified, make sure it's in the list of supported formats
789 String nameFormat = null;
790 if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
791 AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
792 if (authnRequest.getNameIDPolicy() != null) {
793 nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
794 if (nameFormat != null) {
795 if (nameFormats.contains(nameFormat)) {
797 nameFormats.add(nameFormat);
799 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
800 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
801 throw new ProfileException("NameID format required by relying party is not supported");
812 * Gets the list of NameID formats supported for a given role.
814 * @param role the role to get the list of supported NameID formats
816 * @return list of supported NameID formats
818 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
819 List<NameIDFormat> nameIDFormats = null;
821 if (role instanceof SSODescriptor) {
822 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
823 } else if (role instanceof AuthnAuthorityDescriptor) {
824 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
825 } else if (role instanceof PDPDescriptor) {
826 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
827 } else if (role instanceof AttributeAuthorityDescriptor) {
828 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
831 ArrayList<String> supportedFormats = new ArrayList<String>();
832 if (nameIDFormats != null) {
833 for (NameIDFormat format : nameIDFormats) {
834 supportedFormats.add(format.getFormat());
838 return supportedFormats;
842 * Constructs an SAML response message carrying a request error.
844 * @param requestContext current request context
846 * @return the constructed error response
848 protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
849 Response samlResponse = responseBuilder.buildObject();
850 samlResponse.setIssueInstant(new DateTime());
851 populateStatusResponse(requestContext, samlResponse);
853 samlResponse.setStatus(requestContext.getFailureStatus());
859 * Gets an encrypter that may be used encrypt content to a given peer.
861 * @param peerEntityId entity ID of the peer
863 * @return encrypter that may be used encrypt content to a given peer
865 * @throws SecurityException thrown if there is a problem constructing the encrypter. This normally occurs if the
866 * key encryption credential for the peer can not be resolved or a required encryption algorithm is not
867 * supported by the VM's JCE.
869 protected Encrypter getEncrypter(String peerEntityId) throws SecurityException {
870 SecurityConfiguration securityConfiguration = Configuration.getGlobalSecurityConfiguration();
872 EncryptionParameters dataEncParams = SecurityHelper
873 .buildDataEncryptionParams(null, securityConfiguration, null);
875 Credential keyEncryptionCredentials = getKeyEncryptionCredential(peerEntityId);
876 String wrappedJCAKeyAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(dataEncParams.getAlgorithm());
877 KeyEncryptionParameters keyEncParams = SecurityHelper.buildKeyEncryptionParams(keyEncryptionCredentials,
878 wrappedJCAKeyAlgorithm, securityConfiguration, null, null);
880 Encrypter encrypter = new Encrypter(dataEncParams, keyEncParams);
881 encrypter.setKeyPlacement(KeyPlacement.INLINE);
886 * Gets the credential that can be used to encrypt encryption keys for a peer.
888 * @param peerEntityId entity ID of the peer
890 * @return credential that can be used to encrypt encryption keys for a peer
892 * @throws SecurityException thrown if there is a problem resolving the credential from the peer's metadata
894 protected Credential getKeyEncryptionCredential(String peerEntityId) throws SecurityException {
895 MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver(getMetadataProvider());
897 CriteriaSet criteriaSet = new CriteriaSet();
898 criteriaSet.add(new EntityIDCriteria(peerEntityId));
899 criteriaSet.add(new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
900 criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));
902 return kekCredentialResolver.resolveSingle(criteriaSet);