ed9230d1aedba9b14d81b60e3eb8a8ca8c402973
[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.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;
96
97 /** Common implementation details for profile handlers. */
98 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
99
100     /** SAML Version for this profile handler. */
101     public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
102
103     /** Class logger. */
104     private Logger log = LoggerFactory.getLogger(AbstractSAML2ProfileHandler.class);
105
106     /** For building response. */
107     private SAMLObjectBuilder<Response> responseBuilder;
108
109     /** For building status. */
110     private SAMLObjectBuilder<Status> statusBuilder;
111
112     /** For building statuscode. */
113     private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
114
115     /** For building StatusMessages. */
116     private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
117
118     /** For building assertion. */
119     private SAMLObjectBuilder<Assertion> assertionBuilder;
120
121     /** For building issuer. */
122     private SAMLObjectBuilder<Issuer> issuerBuilder;
123
124     /** For building subject. */
125     private SAMLObjectBuilder<Subject> subjectBuilder;
126
127     /** For building subject confirmation. */
128     private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
129
130     /** For building subject confirmation data. */
131     private SAMLObjectBuilder<SubjectConfirmationData> subjectConfirmationDataBuilder;
132
133     /** For building conditions. */
134     private SAMLObjectBuilder<Conditions> conditionsBuilder;
135
136     /** For building audience restriction. */
137     private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
138
139     /** For building proxy retrictions. */
140     private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
141
142     /** For building audience. */
143     private SAMLObjectBuilder<Audience> audienceBuilder;
144
145     /** For building signature. */
146     private XMLObjectBuilder<Signature> signatureBuilder;
147
148     /** Constructor. */
149     @SuppressWarnings("unchecked")
150     protected AbstractSAML2ProfileHandler() {
151         super();
152
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);
175     }
176
177     /** {@inheritDoc} */
178     protected void populateRequestContext(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
179         BaseSAML2ProfileRequestContext saml2Request = (BaseSAML2ProfileRequestContext) requestContext;
180         try {
181             super.populateRequestContext(requestContext);
182         } catch (ProfileException e) {
183             if (saml2Request.getFailureStatus() == null) {
184                 saml2Request.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null, e.getMessage()));
185             }
186             throw e;
187         }
188     }
189
190     /**
191      * Populates the request context with the information about the user.
192      * 
193      * This method requires the the following request context properties to be populated: inbound message transport,
194      * relying party ID
195      * 
196      * This methods populates the following request context properties: user's session, user's principal name, and
197      * service authentication method
198      * 
199      * @param requestContext current request context
200      */
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());
207             }
208         }
209
210         if (userSession != null) {
211             requestContext.setUserSession(userSession);
212             requestContext.setPrincipalName(userSession.getPrincipalName());
213             requestContext.setPrincipalAuthenticationMethod(userSession.getServicesInformation().get(
214                     requestContext.getPeerEntityId()).getAuthenticationMethod().getAuthenticationMethod());
215         }
216     }
217
218     /**
219      * Checks that the SAML major version for a request is 2.
220      * 
221      * @param requestContext current request context containing the SAML message
222      * 
223      * @throws ProfileException thrown if the major version of the SAML request is not 2
224      */
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");
235         }
236     }
237
238     /**
239      * Builds a response to the attribute query within the request context.
240      * 
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
244      * 
245      * @return the built response
246      * 
247      * @throws ProfileException thrown if there is a problem creating the SAML response
248      */
249     protected Response buildResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
250             String subjectConfirmationMethod, List<Statement> statements) throws ProfileException {
251
252         DateTime issueInstant = new DateTime();
253
254         Subject subject = buildSubject(requestContext, subjectConfirmationMethod, issueInstant);
255
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);
261         }
262
263         // create the SAML response and add the assertion
264         Response samlResponse = responseBuilder.buildObject();
265         samlResponse.setIssueInstant(issueInstant);
266         populateStatusResponse(requestContext, samlResponse);
267
268         // sign the assertion if it should be signed
269         signAssertion(requestContext, assertion);
270
271         SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
272         try {
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());
278                 try {
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);
291                 }
292             } else {
293                 samlResponse.getAssertions().add(assertion);
294             }
295         } catch (MessageEncodingException e) {
296             log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
297                     .getBindingURI());
298             throw new ProfileException("Unable to determine if assertions should be encrypted");
299         }
300
301         Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
302         samlResponse.setStatus(status);
303
304         return samlResponse;
305     }
306
307     /**
308      * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
309      * 
310      * @param requestContext current request context
311      * @param issueInstant time to use as assertion issue instant
312      * 
313      * @return the built assertion
314      */
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));
321
322         Conditions conditions = buildConditions(requestContext, issueInstant);
323         assertion.setConditions(conditions);
324
325         return assertion;
326     }
327
328     /**
329      * Creates an {@link Issuer} populated with information about the relying party.
330      * 
331      * @param requestContext current request context
332      * 
333      * @return the built issuer
334      */
335     protected Issuer buildEntityIssuer(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
336         Issuer issuer = issuerBuilder.buildObject();
337         issuer.setFormat(Issuer.ENTITY);
338         issuer.setValue(requestContext.getLocalEntityId());
339
340         return issuer;
341     }
342
343     /**
344      * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
345      * restrictions, and proxy restrictions.
346      * 
347      * @param requestContext current request context
348      * @param issueInstant timestamp the assertion was created
349      * 
350      * @return constructed conditions
351      */
352     protected Conditions buildConditions(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
353         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
354
355         Conditions conditions = conditionsBuilder.buildObject();
356         conditions.setNotBefore(issueInstant);
357         conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
358
359         Collection<String> audiences;
360
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);
373             }
374         }
375         conditions.getAudienceRestrictions().add(audienceRestriction);
376
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);
385             }
386
387             proxyRestriction.setProxyCount(profileConfig.getProxyCount());
388             conditions.getConditions().add(proxyRestriction);
389         }
390
391         return conditions;
392     }
393
394     /**
395      * Populates the response's id, in response to, issue instant, version, and issuer properties.
396      * 
397      * @param requestContext current request context
398      * @param response the response to populate
399      */
400     protected void populateStatusResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
401             StatusResponseType response) {
402         response.setID(getIdGenerator().generateIdentifier());
403         if (requestContext.getInboundSAMLMessage() != null) {
404             response.setInResponseTo(requestContext.getInboundSAMLMessageId());
405         }
406         response.setVersion(SAMLVersion.VERSION_20);
407         response.setIssuer(buildEntityIssuer(requestContext));
408     }
409
410     /**
411      * Resolves the attributes for the principal.
412      * 
413      * @param requestContext current request context
414      * 
415      * @throws ProfileException thrown if there is a problem resolved attributes
416      */
417     protected void resolveAttributes(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
418         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
419         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
420         try {
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);
424
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);
433         }
434     }
435
436     /**
437      * Executes a query for attributes and builds a SAML attribute statement from the results.
438      * 
439      * @param requestContext current request context
440      * 
441      * @return attribute statement resulting from the query
442      * 
443      * @throws ProfileException thrown if there is a problem making the query
444      */
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());
449
450         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
451         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
452         try {
453             if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
454                 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
455                         .getInboundSAMLMessage(), requestContext.getAttributes().values());
456             } else {
457                 return attributeAuthority.buildAttributeStatement(null, requestContext.getAttributes().values());
458             }
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(),
463                     e);
464         }
465     }
466
467     /**
468      * Resolves the principal name of the subject of the request.
469      * 
470      * @param requestContext current request context
471      * 
472      * @throws ProfileException thrown if the principal name can not be resolved
473      */
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());
484         }
485         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
486         log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
487                 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
488
489         try {
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);
500         }
501     }
502
503     /**
504      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
505      * signing credentials.
506      * 
507      * @param requestContext current request context
508      * @param assertion assertion to sign
509      * 
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
512      */
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());
517
518         boolean signAssertion = false;
519
520         SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
521         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
522         try {
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);
529             }
530         } catch (MessageEncodingException e) {
531             log.error("Unable to determine if outbound encoding {} can provide integrity protection", encoder
532                     .getBindingURI());
533             throw new ProfileException("Unable to determine if outbound message should be signed");
534         }
535
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);
542             }
543         }
544
545         if (!signAssertion) {
546             return;
547         }
548
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();
554         }
555
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");
560         }
561
562         log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
563         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
564
565         signature.setSigningCredential(signatureCredential);
566         try {
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);
572         }
573
574         assertion.setSignature(signature);
575
576         Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
577         try {
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);
586         }
587     }
588
589     /**
590      * Build a status message, with an optional second-level failure message.
591      * 
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
596      * 
597      * @return a Status object.
598      */
599     protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
600         Status status = statusBuilder.buildObject();
601
602         StatusCode statusCode = statusCodeBuilder.buildObject();
603         statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
604         status.setStatusCode(statusCode);
605
606         if (secondLevelCode != null) {
607             StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
608             secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
609             statusCode.setStatusCode(secondLevelStatusCode);
610         }
611
612         if (failureMessage != null) {
613             StatusMessage msg = statusMessageBuilder.buildObject();
614             msg.setMessage(failureMessage);
615             status.setStatusMessage(msg);
616         }
617
618         return status;
619     }
620
621     /**
622      * Builds the SAML subject for the user for the service provider.
623      * 
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
627      * 
628      * @return SAML subject for the user for the service provider
629      * 
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
632      */
633     protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
634             DateTime issueInstant) throws ProfileException {
635         NameID nameID = buildNameId(requestContext);
636         requestContext.setSubjectNameIdentifier(nameID);
637
638         SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
639         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
640         confirmationData.setAddress(inTransport.getPeerAddress());
641         confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
642         confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
643                 .getAssertionLifetime()));
644
645         Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
646         if (relyingPartyEndpoint != null) {
647             if (relyingPartyEndpoint.getResponseLocation() != null) {
648                 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
649             } else {
650                 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
651             }
652         }
653
654         SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
655         subjectConfirmation.setMethod(confirmationMethod);
656         subjectConfirmation.setSubjectConfirmationData(confirmationData);
657
658         Subject subject = subjectBuilder.buildObject();
659         subject.getSubjectConfirmations().add(subjectConfirmation);
660         SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
661         try {
662             if (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.always
663                     || (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.conditional && !encoder
664                             .providesMessageConfidentiality(requestContext))) {
665                 log.debug("Attempting to encrypt NameID to relying party {}", requestContext.getInboundMessageIssuer());
666                 try {
667                     Encrypter encrypter = getEncrypter(requestContext.getInboundMessageIssuer());
668                     subject.setEncryptedID(encrypter.encrypt(nameID));
669                 } catch (SecurityException e) {
670                     log.error("Unable to construct encrypter", e);
671                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
672                             "Unable to construct NameID"));
673                     throw new ProfileException("Unable to construct encrypter", e);
674                 } catch (EncryptionException e) {
675                     log.error("Unable to encrypt NameID", e);
676                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
677                             "Unable to construct NameID"));
678                     throw new ProfileException("Unable to encrypt NameID", e);
679                 }
680             } else {
681                 subject.setNameID(nameID);
682             }
683         } catch (MessageEncodingException e) {
684             log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
685                     .getBindingURI());
686             throw new ProfileException("Unable to determine if assertions should be encrypted");
687         }
688
689         return subject;
690     }
691
692     /**
693      * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
694      * picking a name format that was requested by the relying party or is mutually supported by both the relying party
695      * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
696      * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
697      * the supported name formats.
698      * 
699      * @param requestContext current request context
700      * 
701      * @return the NameID appropriate for this request
702      * 
703      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
704      *             name ID attribute or because there are no supported name formats
705      */
706     protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
707         log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
708                 requestContext.getInboundMessageIssuer());
709
710         Map<String, BaseAttribute> principalAttributes = requestContext.getAttributes();
711         if (principalAttributes == null || principalAttributes.isEmpty()) {
712             log.error("No attributes for principal {}, unable to construct of NameID", requestContext
713                     .getPrincipalName());
714             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
715                     "Unable to construct NameID"));
716             throw new ProfileException("No principal attributes support NameID construction");
717         }
718
719         List<String> supportedNameFormats = getNameFormats(requestContext);
720         if (supportedNameFormats == null || supportedNameFormats.isEmpty()) {
721             log.error("No common NameID formats supported by SP {} and IdP", requestContext.getInboundMessageIssuer());
722             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
723                     "Unable to construct NameID"));
724             throw new ProfileException("No principal attributes support NameID construction");
725         }
726
727         log.debug("Supported NameID formats: {}", supportedNameFormats);
728         try {
729             SAML2NameIDEncoder nameIdEncoder;
730             for (BaseAttribute<?> attribute : principalAttributes.values()) {
731                 for (AttributeEncoder encoder : attribute.getEncoders()) {
732                     if (encoder instanceof SAML2NameIDEncoder) {
733                         nameIdEncoder = (SAML2NameIDEncoder) encoder;
734                         if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
735                             log.debug("Using attribute {} suppoting NameID format {} to create the NameID.", attribute
736                                     .getId(), nameIdEncoder.getNameFormat());
737                             return nameIdEncoder.encode(attribute);
738                         }
739                     }
740                 }
741             }
742
743             log.error("No principal attribute supported encoding into a supported name ID format.");
744             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
745             throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
746         } catch (AttributeEncodingException e) {
747             log.error("Unable to encode NameID attribute", e);
748             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
749             throw new ProfileException("Unable to encode NameID attribute", e);
750         }
751     }
752
753     /**
754      * Gets the NameID format to use when creating NameIDs for the relying party.
755      * 
756      * @param requestContext current request context
757      * 
758      * @return list of nameID formats that may be used with the relying party
759      * 
760      * @throws ProfileException thrown if there is a problem determing the NameID format to use
761      */
762     protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
763             throws ProfileException {
764         ArrayList<String> nameFormats = new ArrayList<String>();
765
766         // Determine name formats supported by both SP and IdP
767         RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
768         if (relyingPartyRole != null) {
769             List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
770             if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
771                 nameFormats.addAll(relyingPartySupportedFormats);
772
773                 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
774                 if (assertingPartyRole != null) {
775                     List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
776                     if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
777                         nameFormats.retainAll(assertingPartySupportedFormats);
778                     }
779                 }
780             }
781         }
782
783         if (nameFormats.isEmpty()) {
784             nameFormats.add("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
785         }
786
787         // If authn request and name ID policy format specified, make sure it's in the list of supported formats
788         String nameFormat = null;
789         if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
790             AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
791             if (authnRequest.getNameIDPolicy() != null) {
792                 nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
793                 if (nameFormat != null) {
794                     if (nameFormats.contains(nameFormat)) {
795                         nameFormats.clear();
796                         nameFormats.add(nameFormat);
797                     } else {
798                         requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
799                                 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
800                         throw new ProfileException("NameID format required by relying party is not supported");
801                     }
802                 }
803
804             }
805         }
806
807         return nameFormats;
808     }
809
810     /**
811      * Gets the list of NameID formats supported for a given role.
812      * 
813      * @param role the role to get the list of supported NameID formats
814      * 
815      * @return list of supported NameID formats
816      */
817     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
818         List<NameIDFormat> nameIDFormats = null;
819
820         if (role instanceof SSODescriptor) {
821             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
822         } else if (role instanceof AuthnAuthorityDescriptor) {
823             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
824         } else if (role instanceof PDPDescriptor) {
825             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
826         } else if (role instanceof AttributeAuthorityDescriptor) {
827             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
828         }
829
830         ArrayList<String> supportedFormats = new ArrayList<String>();
831         if (nameIDFormats != null) {
832             for (NameIDFormat format : nameIDFormats) {
833                 supportedFormats.add(format.getFormat());
834             }
835         }
836
837         return supportedFormats;
838     }
839
840     /**
841      * Constructs an SAML response message carrying a request error.
842      * 
843      * @param requestContext current request context
844      * 
845      * @return the constructed error response
846      */
847     protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
848         Response samlResponse = responseBuilder.buildObject();
849         samlResponse.setIssueInstant(new DateTime());
850         populateStatusResponse(requestContext, samlResponse);
851
852         samlResponse.setStatus(requestContext.getFailureStatus());
853
854         return samlResponse;
855     }
856
857     /**
858      * Gets an encrypter that may be used encrypt content to a given peer.
859      * 
860      * @param peerEntityId entity ID of the peer
861      * 
862      * @return encrypter that may be used encrypt content to a given peer
863      * 
864      * @throws SecurityException thrown if there is a problem constructing the encrypter. This normally occurs if the
865      *             key encryption credential for the peer can not be resolved or a required encryption algorithm is not
866      *             supported by the VM's JCE.
867      */
868     protected Encrypter getEncrypter(String peerEntityId) throws SecurityException {
869         SecurityConfiguration securityConfiguration = Configuration.getGlobalSecurityConfiguration();
870
871         EncryptionParameters dataEncParams = SecurityHelper
872                 .buildDataEncryptionParams(null, securityConfiguration, null);
873
874         Credential keyEncryptionCredentials = getKeyEncryptionCredential(peerEntityId);
875         String wrappedJCAKeyAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(dataEncParams.getAlgorithm());
876         KeyEncryptionParameters keyEncParams = SecurityHelper.buildKeyEncryptionParams(keyEncryptionCredentials,
877                 wrappedJCAKeyAlgorithm, securityConfiguration, null, null);
878
879         Encrypter encrypter = new Encrypter(dataEncParams, keyEncParams);
880         encrypter.setKeyPlacement(KeyPlacement.INLINE);
881         return encrypter;
882     }
883
884     /**
885      * Gets the credential that can be used to encrypt encryption keys for a peer.
886      * 
887      * @param peerEntityId entity ID of the peer
888      * 
889      * @return credential that can be used to encrypt encryption keys for a peer
890      * 
891      * @throws SecurityException thrown if there is a problem resolving the credential from the peer's metadata
892      */
893     protected Credential getKeyEncryptionCredential(String peerEntityId) throws SecurityException {
894         MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver(getMetadataProvider());
895
896         CriteriaSet criteriaSet = new CriteriaSet();
897         criteriaSet.add(new EntityIDCriteria(peerEntityId));
898         criteriaSet.add(new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
899         criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));
900
901         return kekCredentialResolver.resolveSingle(criteriaSet);
902     }
903 }