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.getInboundMessageIssuer()).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();
421 log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
422 .getPrincipalName(), requestContext.getInboundMessageIssuer());
423 Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
425 requestContext.setAttributes(principalAttributes);
426 } catch (AttributeRequestException e) {
427 log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
428 + " from relying party " + requestContext.getInboundMessageIssuer(), e);
429 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
430 throw new ProfileException("Error resolving attributes for SAML request "
431 + requestContext.getInboundSAMLMessageId() + " from relying party "
432 + requestContext.getInboundMessageIssuer(), e);
437 * Executes a query for attributes and builds a SAML attribute statement from the results.
439 * @param requestContext current request context
441 * @return attribute statement resulting from the query
443 * @throws ProfileException thrown if there is a problem making the query
445 protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
446 throws ProfileException {
447 log.debug("Creating attribute statement in response to SAML request {} from relying party {}", requestContext
448 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
450 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
451 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
453 if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
454 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
455 .getInboundSAMLMessage(), requestContext.getAttributes().values());
457 return attributeAuthority.buildAttributeStatement(null, requestContext.getAttributes().values());
459 } catch (AttributeRequestException e) {
460 log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
461 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
462 throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
468 * Resolves the principal name of the subject of the request.
470 * @param requestContext current request context
472 * @throws ProfileException thrown if the principal name can not be resolved
474 protected void resolvePrincipal(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
475 AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
476 if (profileConfiguration == null) {
477 log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
478 + requestContext.getInboundMessageIssuer());
479 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
480 "Error resolving principal"));
481 throw new ProfileException(
482 "Unable to resolve principal, no SAML 2 profile configuration for relying party "
483 + requestContext.getInboundMessageIssuer());
485 SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
486 log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
487 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
490 String principal = attributeAuthority.getPrincipal(requestContext);
491 requestContext.setPrincipalName(principal);
492 } catch (AttributeRequestException e) {
493 log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
494 + " from relying party " + requestContext.getInboundMessageIssuer(), e);
495 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
496 "Error resolving principal"));
497 throw new ProfileException("Error resolving attributes for SAML request "
498 + requestContext.getInboundSAMLMessageId() + " from relying party "
499 + requestContext.getInboundMessageIssuer(), e);
504 * Signs the given assertion if either the current profile configuration or the relying party configuration contains
505 * signing credentials.
507 * @param requestContext current request context
508 * @param assertion assertion to sign
510 * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
511 * required, if a signing credential is not configured
513 protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
514 throws ProfileException {
515 log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
516 .getInboundMessageIssuer());
518 boolean signAssertion = false;
520 SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
521 AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
523 if (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.always
524 || (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.conditional && !encoder
525 .providesMessageIntegrity(requestContext))) {
526 signAssertion = true;
527 log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
528 .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
530 } catch (MessageEncodingException e) {
531 log.error("Unable to determine if outbound encoding {} can provide integrity protection", encoder
533 throw new ProfileException("Unable to determine if outbound message should be signed");
536 if (!signAssertion && requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
537 SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
538 if (ssoDescriptor.getWantAssertionsSigned() != null) {
539 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
540 log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
541 .getInboundMessageIssuer(), signAssertion);
545 if (!signAssertion) {
549 log.debug("Determining signing credntial for assertion to relying party {}", requestContext
550 .getInboundMessageIssuer());
551 Credential signatureCredential = profileConfig.getSigningCredential();
552 if (signatureCredential == null) {
553 signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
556 if (signatureCredential == null) {
557 throw new ProfileException("No signing credential is specified for relying party configuration "
558 + requestContext.getRelyingPartyConfiguration().getProviderId()
559 + " or it's SAML2 attribute query profile configuration");
562 log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
563 Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
565 signature.setSigningCredential(signatureCredential);
567 // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
568 // TODO how to pull what keyInfoGenName to use?
569 SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
570 } catch (SecurityException e) {
571 throw new ProfileException("Error preparing signature for signing", e);
574 assertion.setSignature(signature);
576 Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
578 assertionMarshaller.marshall(assertion);
579 Signer.signObject(signature);
580 } catch (MarshallingException e) {
581 log.error("Unable to marshall assertion for signing", e);
582 throw new ProfileException("Unable to marshall assertion for signing", e);
583 } catch (SignatureException e) {
584 log.error("Unable to sign assertion", e);
585 throw new ProfileException("Unable to sign assertion", e);
590 * Build a status message, with an optional second-level failure message.
592 * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
593 * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
594 * null, no second-level Status element will be set.
595 * @param failureMessage An optional second-level failure message
597 * @return a Status object.
599 protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
600 Status status = statusBuilder.buildObject();
602 StatusCode statusCode = statusCodeBuilder.buildObject();
603 statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
604 status.setStatusCode(statusCode);
606 if (secondLevelCode != null) {
607 StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
608 secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
609 statusCode.setStatusCode(secondLevelStatusCode);
612 if (failureMessage != null) {
613 StatusMessage msg = statusMessageBuilder.buildObject();
614 msg.setMessage(failureMessage);
615 status.setStatusMessage(msg);
622 * Builds the SAML subject for the user for the service provider.
624 * @param requestContext current request context
625 * @param confirmationMethod subject confirmation method used for the subject
626 * @param issueInstant instant the subject confirmation data should reflect for issuance
628 * @return SAML subject for the user for the service provider
630 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
631 * name ID attribute or because there are no supported name formats
633 protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
634 DateTime issueInstant) throws ProfileException {
635 Subject subject = subjectBuilder.buildObject();
636 subject.getSubjectConfirmations().add(
637 buildSubjectConfirmation(requestContext, confirmationMethod, issueInstant));
639 NameID nameID = buildNameId(requestContext);
640 if (nameID == null) {
644 requestContext.setSubjectNameIdentifier(nameID);
646 SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
648 if (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.always
649 || (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.conditional && !encoder
650 .providesMessageConfidentiality(requestContext))) {
651 log.debug("Attempting to encrypt NameID to relying party {}", requestContext.getInboundMessageIssuer());
653 Encrypter encrypter = getEncrypter(requestContext.getInboundMessageIssuer());
654 subject.setEncryptedID(encrypter.encrypt(nameID));
655 } catch (SecurityException e) {
656 log.error("Unable to construct encrypter", e);
657 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
658 "Unable to construct NameID"));
659 throw new ProfileException("Unable to construct encrypter", e);
660 } catch (EncryptionException e) {
661 log.error("Unable to encrypt NameID", e);
662 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
663 "Unable to construct NameID"));
664 throw new ProfileException("Unable to encrypt NameID", e);
667 subject.setNameID(nameID);
669 } catch (MessageEncodingException e) {
670 log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
672 throw new ProfileException("Unable to determine if assertions should be encrypted");
679 * Builds the SubjectConfirmation appropriate for this request.
681 * @param requestContext current request context
682 * @param confirmationMethod confirmation method to use for the request
683 * @param issueInstant issue instant of the response
685 * @return the constructed subject confirmation
687 protected SubjectConfirmation buildSubjectConfirmation(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
688 String confirmationMethod, DateTime issueInstant) {
689 SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
690 HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
691 confirmationData.setAddress(inTransport.getPeerAddress());
692 confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
693 confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
694 .getAssertionLifetime()));
696 Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
697 if (relyingPartyEndpoint != null) {
698 if (relyingPartyEndpoint.getResponseLocation() != null) {
699 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
701 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
705 SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
706 subjectConfirmation.setMethod(confirmationMethod);
707 subjectConfirmation.setSubjectConfirmationData(confirmationData);
709 return subjectConfirmation;
713 * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
714 * picking a name format that was requested by the relying party or is mutually supported by both the relying party
715 * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
716 * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
717 * the supported name formats.
719 * @param requestContext current request context
721 * @return the NameID appropriate for this request
723 * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
724 * name ID attribute or because there are no supported name formats
726 protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
727 log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
728 requestContext.getInboundMessageIssuer());
730 List<String> supportedNameFormats = getNameFormats(requestContext);
731 if (supportedNameFormats == null || supportedNameFormats.isEmpty()) {
732 log.debug("No common NameID formats supported by SP {} and IdP, no name identifier will be created.",
733 requestContext.getInboundMessageIssuer());
737 Map<String, BaseAttribute> principalAttributes = requestContext.getAttributes();
738 if (principalAttributes == null || principalAttributes.isEmpty()) {
739 log.debug("No attributes for principal {}, no name identifier will be created.", requestContext
740 .getPrincipalName());
744 log.debug("Supported NameID formats: {}", supportedNameFormats);
746 SAML2NameIDEncoder nameIdEncoder;
747 for (BaseAttribute<?> attribute : principalAttributes.values()) {
748 for (AttributeEncoder encoder : attribute.getEncoders()) {
749 if (encoder instanceof SAML2NameIDEncoder) {
750 nameIdEncoder = (SAML2NameIDEncoder) encoder;
751 if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
752 log.debug("Using attribute {} supporting NameID format {} to create the NameID.", attribute
753 .getId(), nameIdEncoder.getNameFormat());
754 return nameIdEncoder.encode(attribute);
760 log.debug("No attributes for principal {} supports an encoding into a supported name ID format.",
761 requestContext.getPrincipalName());
763 } catch (AttributeEncodingException e) {
764 log.error("Unable to encode NameID attribute", e);
765 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
766 throw new ProfileException("Unable to encode NameID attribute", e);
771 * Gets the NameID format to use when creating NameIDs for the relying party.
773 * @param requestContext current request context
775 * @return list of nameID formats that may be used with the relying party
777 * @throws ProfileException thrown if there is a problem determing the NameID format to use
779 protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
780 throws ProfileException {
781 ArrayList<String> nameFormats = new ArrayList<String>();
783 // Determine name formats supported by both SP and IdP
784 RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
785 if (relyingPartyRole != null) {
786 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
787 if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
788 nameFormats.addAll(relyingPartySupportedFormats);
790 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
791 if (assertingPartyRole != null) {
792 List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
793 if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
794 nameFormats.retainAll(assertingPartySupportedFormats);
800 if (nameFormats.isEmpty()) {
801 nameFormats.add("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
804 // If authn request and name ID policy format specified, make sure it's in the list of supported formats
805 String nameFormat = null;
806 if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
807 AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
808 if (authnRequest.getNameIDPolicy() != null) {
809 nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
810 if (nameFormat != null) {
811 if (nameFormats.contains(nameFormat)) {
813 nameFormats.add(nameFormat);
815 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
816 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
817 throw new ProfileException("NameID format required by relying party is not supported");
828 * Gets the list of NameID formats supported for a given role.
830 * @param role the role to get the list of supported NameID formats
832 * @return list of supported NameID formats
834 protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
835 List<NameIDFormat> nameIDFormats = null;
837 if (role instanceof SSODescriptor) {
838 nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
839 } else if (role instanceof AuthnAuthorityDescriptor) {
840 nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
841 } else if (role instanceof PDPDescriptor) {
842 nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
843 } else if (role instanceof AttributeAuthorityDescriptor) {
844 nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
847 ArrayList<String> supportedFormats = new ArrayList<String>();
848 if (nameIDFormats != null) {
849 for (NameIDFormat format : nameIDFormats) {
850 supportedFormats.add(format.getFormat());
854 return supportedFormats;
858 * Constructs an SAML response message carrying a request error.
860 * @param requestContext current request context
862 * @return the constructed error response
864 protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
865 Response samlResponse = responseBuilder.buildObject();
866 samlResponse.setIssueInstant(new DateTime());
867 populateStatusResponse(requestContext, samlResponse);
869 samlResponse.setStatus(requestContext.getFailureStatus());
875 * Gets an encrypter that may be used encrypt content to a given peer.
877 * @param peerEntityId entity ID of the peer
879 * @return encrypter that may be used encrypt content to a given peer
881 * @throws SecurityException thrown if there is a problem constructing the encrypter. This normally occurs if the
882 * key encryption credential for the peer can not be resolved or a required encryption algorithm is not
883 * supported by the VM's JCE.
885 protected Encrypter getEncrypter(String peerEntityId) throws SecurityException {
886 SecurityConfiguration securityConfiguration = Configuration.getGlobalSecurityConfiguration();
888 EncryptionParameters dataEncParams = SecurityHelper
889 .buildDataEncryptionParams(null, securityConfiguration, null);
891 Credential keyEncryptionCredentials = getKeyEncryptionCredential(peerEntityId);
892 String wrappedJCAKeyAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(dataEncParams.getAlgorithm());
893 KeyEncryptionParameters keyEncParams = SecurityHelper.buildKeyEncryptionParams(keyEncryptionCredentials,
894 wrappedJCAKeyAlgorithm, securityConfiguration, null, null);
896 Encrypter encrypter = new Encrypter(dataEncParams, keyEncParams);
897 encrypter.setKeyPlacement(KeyPlacement.INLINE);
902 * Gets the credential that can be used to encrypt encryption keys for a peer.
904 * @param peerEntityId entity ID of the peer
906 * @return credential that can be used to encrypt encryption keys for a peer
908 * @throws SecurityException thrown if there is a problem resolving the credential from the peer's metadata
910 protected Credential getKeyEncryptionCredential(String peerEntityId) throws SecurityException {
911 MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver(getMetadataProvider());
913 CriteriaSet criteriaSet = new CriteriaSet();
914 criteriaSet.add(new EntityIDCriteria(peerEntityId));
915 criteriaSet.add(new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
916 criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));
918 return kekCredentialResolver.resolveSingle(criteriaSet);