f58c1aa66637375c7d106b8adb5241185975dc9b
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / AbstractSAML2ProfileHandler.java
1 /*
2  * Copyright [2007] [University Corporation for Advanced Internet Development, Inc.]
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
18
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.List;
22 import java.util.Map;
23
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;
83
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.relyingparty.provider.CryptoOperationRequirementLevel;
92 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
93 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
94
95 /** Common implementation details for profile handlers. */
96 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
97
98     /** SAML Version for this profile handler. */
99     public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
100
101     /** Class logger. */
102     private Logger log = LoggerFactory.getLogger(AbstractSAML2ProfileHandler.class);
103
104     /** For building response. */
105     private SAMLObjectBuilder<Response> responseBuilder;
106
107     /** For building status. */
108     private SAMLObjectBuilder<Status> statusBuilder;
109
110     /** For building statuscode. */
111     private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
112
113     /** For building StatusMessages. */
114     private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
115
116     /** For building assertion. */
117     private SAMLObjectBuilder<Assertion> assertionBuilder;
118
119     /** For building issuer. */
120     private SAMLObjectBuilder<Issuer> issuerBuilder;
121
122     /** For building subject. */
123     private SAMLObjectBuilder<Subject> subjectBuilder;
124
125     /** For building subject confirmation. */
126     private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
127
128     /** For building subject confirmation data. */
129     private SAMLObjectBuilder<SubjectConfirmationData> subjectConfirmationDataBuilder;
130
131     /** For building conditions. */
132     private SAMLObjectBuilder<Conditions> conditionsBuilder;
133
134     /** For building audience restriction. */
135     private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
136
137     /** For building proxy retrictions. */
138     private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
139
140     /** For building audience. */
141     private SAMLObjectBuilder<Audience> audienceBuilder;
142
143     /** For building signature. */
144     private XMLObjectBuilder<Signature> signatureBuilder;
145
146     /** Constructor. */
147     @SuppressWarnings("unchecked")
148     protected AbstractSAML2ProfileHandler() {
149         super();
150
151         responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
152         statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
153         statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
154                 StatusCode.DEFAULT_ELEMENT_NAME);
155         statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
156                 StatusMessage.DEFAULT_ELEMENT_NAME);
157         issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
158         assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
159                 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
160         subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
161         subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
162                 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
163         subjectConfirmationDataBuilder = (SAMLObjectBuilder<SubjectConfirmationData>) getBuilderFactory().getBuilder(
164                 SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
165         conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
166                 Conditions.DEFAULT_ELEMENT_NAME);
167         audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
168                 AudienceRestriction.DEFAULT_ELEMENT_NAME);
169         proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
170                 ProxyRestriction.DEFAULT_ELEMENT_NAME);
171         audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
172         signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
173     }
174
175     /**
176      * Checks that the SAML major version for a request is 2.
177      * 
178      * @param requestContext current request context containing the SAML message
179      * 
180      * @throws ProfileException thrown if the major version of the SAML request is not 2
181      */
182     protected void checkSamlVersion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
183         SAMLVersion version = requestContext.getInboundSAMLMessage().getVersion();
184         if (version.getMajorVersion() < 2) {
185             requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
186                     StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
187             throw new ProfileException("SAML request version too low");
188         } else if (version.getMajorVersion() > 2 || version.getMinorVersion() > 0) {
189             requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
190                     StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
191             throw new ProfileException("SAML request version too high");
192         }
193     }
194
195     /**
196      * Builds a response to the attribute query within the request context.
197      * 
198      * @param requestContext current request context
199      * @param subjectConfirmationMethod confirmation method used for the subject
200      * @param statements the statements to include in the response
201      * 
202      * @return the built response
203      * 
204      * @throws ProfileException thrown if there is a problem creating the SAML response
205      */
206     protected Response buildResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
207             String subjectConfirmationMethod, List<Statement> statements) throws ProfileException {
208
209         DateTime issueInstant = new DateTime();
210
211         Subject subject = buildSubject(requestContext, subjectConfirmationMethod, issueInstant);
212
213         // create the assertion and add the attribute statement
214         Assertion assertion = buildAssertion(requestContext, issueInstant);
215         assertion.setSubject(subject);
216         if (statements != null && !statements.isEmpty()) {
217             assertion.getStatements().addAll(statements);
218         }
219
220         // create the SAML response and add the assertion
221         Response samlResponse = responseBuilder.buildObject();
222         samlResponse.setIssueInstant(issueInstant);
223         populateStatusResponse(requestContext, samlResponse);
224
225         // sign the assertion if it should be signed
226         signAssertion(requestContext, assertion);
227
228         SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
229         try {
230             if (requestContext.getProfileConfiguration().getEncryptAssertion() == CryptoOperationRequirementLevel.always
231                     || (requestContext.getProfileConfiguration().getEncryptAssertion() == CryptoOperationRequirementLevel.conditional && !encoder
232                             .providesMessageConfidentiality(requestContext))) {
233                 log.debug("Attempting to encrypt assertion to relying party {}", requestContext
234                         .getInboundMessageIssuer());
235                 try {
236                     Encrypter encrypter = getEncrypter(requestContext.getInboundMessageIssuer());
237                     samlResponse.getEncryptedAssertions().add(encrypter.encrypt(assertion));
238                 } catch (SecurityException e) {
239                     log.error("Unable to construct encrypter", e);
240                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
241                             "Unable to encrypt assertion"));
242                     throw new ProfileException("Unable to construct encrypter", e);
243                 } catch (EncryptionException e) {
244                     log.error("Unable to encrypt assertion", e);
245                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
246                             "Unable to encrypt assertion"));
247                     throw new ProfileException("Unable to encrypt assertion", e);
248                 }
249             } else {
250                 samlResponse.getAssertions().add(assertion);
251             }
252         } catch (MessageEncodingException e) {
253             log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
254                     .getBindingURI());
255             throw new ProfileException("Unable to determine if assertions should be encrypted");
256         }
257
258         Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
259         samlResponse.setStatus(status);
260
261         return samlResponse;
262     }
263
264     /**
265      * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
266      * 
267      * @param requestContext current request context
268      * @param issueInstant time to use as assertion issue instant
269      * 
270      * @return the built assertion
271      */
272     protected Assertion buildAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
273         Assertion assertion = assertionBuilder.buildObject();
274         assertion.setID(getIdGenerator().generateIdentifier());
275         assertion.setIssueInstant(issueInstant);
276         assertion.setVersion(SAMLVersion.VERSION_20);
277         assertion.setIssuer(buildEntityIssuer(requestContext));
278
279         Conditions conditions = buildConditions(requestContext, issueInstant);
280         assertion.setConditions(conditions);
281
282         return assertion;
283     }
284
285     /**
286      * Creates an {@link Issuer} populated with information about the relying party.
287      * 
288      * @param requestContext current request context
289      * 
290      * @return the built issuer
291      */
292     protected Issuer buildEntityIssuer(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
293         Issuer issuer = issuerBuilder.buildObject();
294         issuer.setFormat(Issuer.ENTITY);
295         issuer.setValue(requestContext.getLocalEntityId());
296
297         return issuer;
298     }
299
300     /**
301      * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
302      * restrictions, and proxy restrictions.
303      * 
304      * @param requestContext current request context
305      * @param issueInstant timestamp the assertion was created
306      * 
307      * @return constructed conditions
308      */
309     protected Conditions buildConditions(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
310         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
311
312         Conditions conditions = conditionsBuilder.buildObject();
313         conditions.setNotBefore(issueInstant);
314         conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
315
316         Collection<String> audiences;
317
318         // add audience restrictions
319         AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
320         // TODO we should only do this for certain outgoing bindings, not globally
321         Audience audience = audienceBuilder.buildObject();
322         audience.setAudienceURI(requestContext.getInboundMessageIssuer());
323         audienceRestriction.getAudiences().add(audience);
324         audiences = profileConfig.getAssertionAudiences();
325         if (audiences != null && audiences.size() > 0) {
326             for (String audienceUri : audiences) {
327                 audience = audienceBuilder.buildObject();
328                 audience.setAudienceURI(audienceUri);
329                 audienceRestriction.getAudiences().add(audience);
330             }
331         }
332         conditions.getAudienceRestrictions().add(audienceRestriction);
333
334         // add proxy restrictions
335         audiences = profileConfig.getProxyAudiences();
336         if (audiences != null && audiences.size() > 0) {
337             ProxyRestriction proxyRestriction = proxyRestrictionBuilder.buildObject();
338             for (String audienceUri : audiences) {
339                 audience = audienceBuilder.buildObject();
340                 audience.setAudienceURI(audienceUri);
341                 proxyRestriction.getAudiences().add(audience);
342             }
343
344             proxyRestriction.setProxyCount(profileConfig.getProxyCount());
345             conditions.getConditions().add(proxyRestriction);
346         }
347
348         return conditions;
349     }
350
351     /**
352      * Populates the response's id, in response to, issue instant, version, and issuer properties.
353      * 
354      * @param requestContext current request context
355      * @param response the response to populate
356      */
357     protected void populateStatusResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
358             StatusResponseType response) {
359         response.setID(getIdGenerator().generateIdentifier());
360         if (requestContext.getInboundSAMLMessage() != null) {
361             response.setInResponseTo(requestContext.getInboundSAMLMessageId());
362         }
363         response.setVersion(SAMLVersion.VERSION_20);
364         response.setIssuer(buildEntityIssuer(requestContext));
365     }
366
367     /**
368      * Resolves the attributes for the principal.
369      * 
370      * @param requestContext current request context
371      * 
372      * @throws ProfileException thrown if there is a problem resolved attributes
373      */
374     protected void resolveAttributes(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
375         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
376         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
377
378         try {
379             log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
380                     .getPrincipalName(), requestContext.getInboundMessageIssuer());
381             Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
382
383             requestContext.setAttributes(principalAttributes);
384         } catch (AttributeRequestException e) {
385             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
386                     + " from relying party " + requestContext.getInboundMessageIssuer(), e);
387             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
388             throw new ProfileException("Error resolving attributes for SAML request "
389                     + requestContext.getInboundSAMLMessageId() + " from relying party "
390                     + requestContext.getInboundMessageIssuer(), e);
391         }
392     }
393
394     /**
395      * Executes a query for attributes and builds a SAML attribute statement from the results.
396      * 
397      * @param requestContext current request context
398      * 
399      * @return attribute statement resulting from the query
400      * 
401      * @throws ProfileException thrown if there is a problem making the query
402      */
403     protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
404             throws ProfileException {
405         log.debug("Creating attribute statement in response to SAML request {} from relying party {}", requestContext
406                 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
407
408         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
409         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
410         try {
411             if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
412                 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
413                         .getInboundSAMLMessage(), requestContext.getAttributes().values());
414             } else {
415                 return attributeAuthority.buildAttributeStatement(null, requestContext.getAttributes()
416                         .values());
417             }
418         } catch (AttributeRequestException e) {
419             log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
420             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
421             throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
422                     e);
423         }
424     }
425
426     /**
427      * Resolves the principal name of the subject of the request.
428      * 
429      * @param requestContext current request context
430      * 
431      * @throws ProfileException thrown if the principal name can not be resolved
432      */
433     protected void resolvePrincipal(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
434         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
435         if (profileConfiguration == null) {
436             log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
437                     + requestContext.getInboundMessageIssuer());
438             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
439                     "Error resolving principal"));
440             throw new ProfileException(
441                     "Unable to resolve principal, no SAML 2 profile configuration for relying party "
442                             + requestContext.getInboundMessageIssuer());
443         }
444         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
445         log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
446                 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
447
448         try {
449             String principal = attributeAuthority.getPrincipal(requestContext);
450             requestContext.setPrincipalName(principal);
451         } catch (AttributeRequestException e) {
452             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
453                     + " from relying party " + requestContext.getInboundMessageIssuer(), e);
454             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
455                     "Error resolving principal"));
456             throw new ProfileException("Error resolving attributes for SAML request "
457                     + requestContext.getInboundSAMLMessageId() + " from relying party "
458                     + requestContext.getInboundMessageIssuer(), e);
459         }
460     }
461
462     /**
463      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
464      * signing credentials.
465      * 
466      * @param requestContext current request context
467      * @param assertion assertion to sign
468      * 
469      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
470      *             required, if a signing credential is not configured
471      */
472     protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
473             throws ProfileException {
474         log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
475                 .getInboundMessageIssuer());
476
477         boolean signAssertion = false;
478
479         SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
480         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
481         try {
482             if (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.always
483                     || (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.conditional && !encoder
484                             .providesMessageIntegrity(requestContext))) {
485                 signAssertion = true;
486                 log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
487                         .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
488             }
489         } catch (MessageEncodingException e) {
490             log.error("Unable to determine if outbound encoding {} can provide integrity protection", encoder
491                     .getBindingURI());
492             throw new ProfileException("Unable to determine if outbound message should be signed");
493         }
494
495         if (!signAssertion && requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
496             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
497             if (ssoDescriptor.getWantAssertionsSigned() != null) {
498                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
499                 log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
500                         .getInboundMessageIssuer(), signAssertion);
501             }
502         }
503
504         if (!signAssertion) {
505             return;
506         }
507
508         log.debug("Determining signing credntial for assertion to relying party {}", requestContext
509                 .getInboundMessageIssuer());
510         Credential signatureCredential = profileConfig.getSigningCredential();
511         if (signatureCredential == null) {
512             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
513         }
514
515         if (signatureCredential == null) {
516             throw new ProfileException("No signing credential is specified for relying party configuration "
517                     + requestContext.getRelyingPartyConfiguration().getProviderId()
518                     + " or it's SAML2 attribute query profile configuration");
519         }
520
521         log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
522         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
523
524         signature.setSigningCredential(signatureCredential);
525         try {
526             // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
527             // TODO how to pull what keyInfoGenName to use?
528             SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
529         } catch (SecurityException e) {
530             throw new ProfileException("Error preparing signature for signing", e);
531         }
532
533         assertion.setSignature(signature);
534
535         Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
536         try {
537             assertionMarshaller.marshall(assertion);
538             Signer.signObject(signature);
539         } catch (MarshallingException e) {
540             log.error("Unable to marshall assertion for signing", e);
541             throw new ProfileException("Unable to marshall assertion for signing", e);
542         } catch (SignatureException e) {
543             log.error("Unable to sign assertion", e);
544             throw new ProfileException("Unable to sign assertion", e);
545         }
546     }
547
548     /**
549      * Build a status message, with an optional second-level failure message.
550      * 
551      * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
552      * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
553      *            null, no second-level Status element will be set.
554      * @param failureMessage An optional second-level failure message
555      * 
556      * @return a Status object.
557      */
558     protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
559         Status status = statusBuilder.buildObject();
560
561         StatusCode statusCode = statusCodeBuilder.buildObject();
562         statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
563         status.setStatusCode(statusCode);
564
565         if (secondLevelCode != null) {
566             StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
567             secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
568             statusCode.setStatusCode(secondLevelStatusCode);
569         }
570
571         if (failureMessage != null) {
572             StatusMessage msg = statusMessageBuilder.buildObject();
573             msg.setMessage(failureMessage);
574             status.setStatusMessage(msg);
575         }
576
577         return status;
578     }
579
580     /**
581      * Builds the SAML subject for the user for the service provider.
582      * 
583      * @param requestContext current request context
584      * @param confirmationMethod subject confirmation method used for the subject
585      * @param issueInstant instant the subject confirmation data should reflect for issuance
586      * 
587      * @return SAML subject for the user for the service provider
588      * 
589      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
590      *             name ID attribute or because there are no supported name formats
591      */
592     protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
593             DateTime issueInstant) throws ProfileException {
594         NameID nameID = buildNameId(requestContext);
595         requestContext.setSubjectNameIdentifier(nameID);
596
597         SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
598         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
599         confirmationData.setAddress(inTransport.getPeerAddress());
600         confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
601         confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
602                 .getAssertionLifetime()));
603
604         Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
605         if (relyingPartyEndpoint != null) {
606             if (relyingPartyEndpoint.getResponseLocation() != null) {
607                 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
608             } else {
609                 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
610             }
611         }
612
613         SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
614         subjectConfirmation.setMethod(confirmationMethod);
615         subjectConfirmation.setSubjectConfirmationData(confirmationData);
616
617         Subject subject = subjectBuilder.buildObject();
618         subject.getSubjectConfirmations().add(subjectConfirmation);
619         SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
620         try {
621             if (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.always
622                     || (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.conditional && !encoder
623                             .providesMessageConfidentiality(requestContext))) {
624                 log.debug("Attempting to encrypt NameID to relying party {}", requestContext.getInboundMessageIssuer());
625                 try {
626                     Encrypter encrypter = getEncrypter(requestContext.getInboundMessageIssuer());
627                     subject.setEncryptedID(encrypter.encrypt(nameID));
628                 } catch (SecurityException e) {
629                     log.error("Unable to construct encrypter", e);
630                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
631                             "Unable to construct NameID"));
632                     throw new ProfileException("Unable to construct encrypter", e);
633                 } catch (EncryptionException e) {
634                     log.error("Unable to encrypt NameID", e);
635                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
636                             "Unable to construct NameID"));
637                     throw new ProfileException("Unable to encrypt NameID", e);
638                 }
639             } else {
640                 subject.setNameID(nameID);
641             }
642         } catch (MessageEncodingException e) {
643             log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
644                     .getBindingURI());
645             throw new ProfileException("Unable to determine if assertions should be encrypted");
646         }
647
648         return subject;
649     }
650
651     /**
652      * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
653      * picking a name format that was requested by the relying party or is mutually supported by both the relying party
654      * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
655      * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
656      * the supported name formats.
657      * 
658      * @param requestContext current request context
659      * 
660      * @return the NameID appropriate for this request
661      * 
662      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
663      *             name ID attribute or because there are no supported name formats
664      */
665     protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
666         log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
667                 requestContext.getInboundMessageIssuer());
668
669         Map<String, BaseAttribute> principalAttributes = requestContext.getAttributes();
670         if (principalAttributes == null || principalAttributes.isEmpty()) {
671             log.error("No attributes for principal {}, unable to construct of NameID", requestContext
672                     .getPrincipalName());
673             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
674                     "Unable to construct NameID"));
675             throw new ProfileException("No principal attributes support NameID construction");
676         }
677
678         List<String> supportedNameFormats = getNameFormats(requestContext);
679         if (supportedNameFormats == null || supportedNameFormats.isEmpty()) {
680             log.error("No common NameID formats supported by SP {} and IdP", requestContext.getInboundMessageIssuer());
681             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
682                     "Unable to construct NameID"));
683             throw new ProfileException("No principal attributes support NameID construction");
684         }
685
686         log.debug("Supported NameID formats: {}", supportedNameFormats);
687         try {
688             SAML2NameIDEncoder nameIdEncoder;
689             for (BaseAttribute<?> attribute : principalAttributes.values()) {
690                 for (AttributeEncoder encoder : attribute.getEncoders()) {
691                     if (encoder instanceof SAML2NameIDEncoder) {
692                         nameIdEncoder = (SAML2NameIDEncoder) encoder;
693                         if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
694                             log.debug("Using attribute {} suppoting NameID format {} to create the NameID.", attribute
695                                     .getId(), nameIdEncoder.getNameFormat());
696                             return nameIdEncoder.encode(attribute);
697                         }
698                     }
699                 }
700             }
701
702             log.error("No principal attribute supported encoding into a supported name ID format.");
703             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
704             throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
705         } catch (AttributeEncodingException e) {
706             log.error("Unable to encode NameID attribute", e);
707             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
708             throw new ProfileException("Unable to encode NameID attribute", e);
709         }
710     }
711
712     /**
713      * Gets the NameID format to use when creating NameIDs for the relying party.
714      * 
715      * @param requestContext current request context
716      * 
717      * @return list of nameID formats that may be used with the relying party
718      * 
719      * @throws ProfileException thrown if there is a problem determing the NameID format to use
720      */
721     protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
722             throws ProfileException {
723         ArrayList<String> nameFormats = new ArrayList<String>();
724
725         // Determine name formats supported by both SP and IdP
726         RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
727         if (relyingPartyRole != null) {
728             List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
729             if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
730                 nameFormats.addAll(relyingPartySupportedFormats);
731
732                 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
733                 if (assertingPartyRole != null) {
734                     List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
735                     if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
736                         nameFormats.retainAll(assertingPartySupportedFormats);
737                     }
738                 }
739             }
740         }
741
742         if (nameFormats.isEmpty()) {
743             nameFormats.add("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
744         }
745
746         // If authn request and name ID policy format specified, make sure it's in the list of supported formats
747         String nameFormat = null;
748         if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
749             AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
750             if (authnRequest.getNameIDPolicy() != null) {
751                 nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
752                 if (nameFormat != null) {
753                     if (nameFormats.contains(nameFormat)) {
754                         nameFormats.clear();
755                         nameFormats.add(nameFormat);
756                     } else {
757                         requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
758                                 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
759                         throw new ProfileException("NameID format required by relying party is not supported");
760                     }
761                 }
762
763             }
764         }
765
766         return nameFormats;
767     }
768
769     /**
770      * Gets the list of NameID formats supported for a given role.
771      * 
772      * @param role the role to get the list of supported NameID formats
773      * 
774      * @return list of supported NameID formats
775      */
776     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
777         List<NameIDFormat> nameIDFormats = null;
778
779         if (role instanceof SSODescriptor) {
780             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
781         } else if (role instanceof AuthnAuthorityDescriptor) {
782             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
783         } else if (role instanceof PDPDescriptor) {
784             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
785         } else if (role instanceof AttributeAuthorityDescriptor) {
786             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
787         }
788
789         ArrayList<String> supportedFormats = new ArrayList<String>();
790         if (nameIDFormats != null) {
791             for (NameIDFormat format : nameIDFormats) {
792                 supportedFormats.add(format.getFormat());
793             }
794         }
795
796         return supportedFormats;
797     }
798
799     /**
800      * Constructs an SAML response message carrying a request error.
801      * 
802      * @param requestContext current request context
803      * 
804      * @return the constructed error response
805      */
806     protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
807         Response samlResponse = responseBuilder.buildObject();
808         samlResponse.setIssueInstant(new DateTime());
809         populateStatusResponse(requestContext, samlResponse);
810
811         samlResponse.setStatus(requestContext.getFailureStatus());
812
813         return samlResponse;
814     }
815
816     /**
817      * Gets an encrypter that may be used encrypt content to a given peer.
818      * 
819      * @param peerEntityId entity ID of the peer
820      * 
821      * @return encrypter that may be used encrypt content to a given peer
822      * 
823      * @throws SecurityException thrown if there is a problem constructing the encrypter. This normally occurs if the
824      *             key encryption credential for the peer can not be resolved or a required encryption algorithm is not
825      *             supported by the VM's JCE.
826      */
827     protected Encrypter getEncrypter(String peerEntityId) throws SecurityException {
828         SecurityConfiguration securityConfiguration = Configuration.getGlobalSecurityConfiguration();
829
830         EncryptionParameters dataEncParams = SecurityHelper
831                 .buildDataEncryptionParams(null, securityConfiguration, null);
832
833         Credential keyEncryptionCredentials = getKeyEncryptionCredential(peerEntityId);
834         String wrappedJCAKeyAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(dataEncParams.getAlgorithm());
835         KeyEncryptionParameters keyEncParams = SecurityHelper.buildKeyEncryptionParams(keyEncryptionCredentials,
836                 wrappedJCAKeyAlgorithm, securityConfiguration, null, null);
837
838         Encrypter encrypter = new Encrypter(dataEncParams, keyEncParams);
839         encrypter.setKeyPlacement(KeyPlacement.INLINE);
840         return encrypter;
841     }
842
843     /**
844      * Gets the credential that can be used to encrypt encryption keys for a peer.
845      * 
846      * @param peerEntityId entity ID of the peer
847      * 
848      * @return credential that can be used to encrypt encryption keys for a peer
849      * 
850      * @throws SecurityException thrown if there is a problem resolving the credential from the peer's metadata
851      */
852     protected Credential getKeyEncryptionCredential(String peerEntityId) throws SecurityException {
853         MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver(getMetadataProvider());
854
855         CriteriaSet criteriaSet = new CriteriaSet();
856         criteriaSet.add(new EntityIDCriteria(peerEntityId));
857         criteriaSet.add(new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
858         criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));
859
860         return kekCredentialResolver.resolveSingle(criteriaSet);
861     }
862 }