Lots of code cleanup
[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
421         try {
422             log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
423                     .getPrincipalName(), requestContext.getInboundMessageIssuer());
424             Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
425
426             requestContext.setAttributes(principalAttributes);
427         } catch (AttributeRequestException e) {
428             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
429                     + " from relying party " + requestContext.getInboundMessageIssuer(), e);
430             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
431             throw new ProfileException("Error resolving attributes for SAML request "
432                     + requestContext.getInboundSAMLMessageId() + " from relying party "
433                     + requestContext.getInboundMessageIssuer(), e);
434         }
435     }
436
437     /**
438      * Executes a query for attributes and builds a SAML attribute statement from the results.
439      * 
440      * @param requestContext current request context
441      * 
442      * @return attribute statement resulting from the query
443      * 
444      * @throws ProfileException thrown if there is a problem making the query
445      */
446     protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
447             throws ProfileException {
448         log.debug("Creating attribute statement in response to SAML request {} from relying party {}", requestContext
449                 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
450
451         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
452         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
453         try {
454             if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
455                 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
456                         .getInboundSAMLMessage(), requestContext.getAttributes().values());
457             } else {
458                 return attributeAuthority.buildAttributeStatement(null, requestContext.getAttributes().values());
459             }
460         } catch (AttributeRequestException e) {
461             log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
462             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
463             throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
464                     e);
465         }
466     }
467
468     /**
469      * Resolves the principal name of the subject of the request.
470      * 
471      * @param requestContext current request context
472      * 
473      * @throws ProfileException thrown if the principal name can not be resolved
474      */
475     protected void resolvePrincipal(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
476         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
477         if (profileConfiguration == null) {
478             log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
479                     + requestContext.getInboundMessageIssuer());
480             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
481                     "Error resolving principal"));
482             throw new ProfileException(
483                     "Unable to resolve principal, no SAML 2 profile configuration for relying party "
484                             + requestContext.getInboundMessageIssuer());
485         }
486         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
487         log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
488                 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
489
490         try {
491             String principal = attributeAuthority.getPrincipal(requestContext);
492             requestContext.setPrincipalName(principal);
493         } catch (AttributeRequestException e) {
494             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
495                     + " from relying party " + requestContext.getInboundMessageIssuer(), e);
496             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
497                     "Error resolving principal"));
498             throw new ProfileException("Error resolving attributes for SAML request "
499                     + requestContext.getInboundSAMLMessageId() + " from relying party "
500                     + requestContext.getInboundMessageIssuer(), e);
501         }
502     }
503
504     /**
505      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
506      * signing credentials.
507      * 
508      * @param requestContext current request context
509      * @param assertion assertion to sign
510      * 
511      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
512      *             required, if a signing credential is not configured
513      */
514     protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
515             throws ProfileException {
516         log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
517                 .getInboundMessageIssuer());
518
519         boolean signAssertion = false;
520
521         SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
522         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
523         try {
524             if (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.always
525                     || (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.conditional && !encoder
526                             .providesMessageIntegrity(requestContext))) {
527                 signAssertion = true;
528                 log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
529                         .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
530             }
531         } catch (MessageEncodingException e) {
532             log.error("Unable to determine if outbound encoding {} can provide integrity protection", encoder
533                     .getBindingURI());
534             throw new ProfileException("Unable to determine if outbound message should be signed");
535         }
536
537         if (!signAssertion && requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
538             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
539             if (ssoDescriptor.getWantAssertionsSigned() != null) {
540                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
541                 log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
542                         .getInboundMessageIssuer(), signAssertion);
543             }
544         }
545
546         if (!signAssertion) {
547             return;
548         }
549
550         log.debug("Determining signing credntial for assertion to relying party {}", requestContext
551                 .getInboundMessageIssuer());
552         Credential signatureCredential = profileConfig.getSigningCredential();
553         if (signatureCredential == null) {
554             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
555         }
556
557         if (signatureCredential == null) {
558             throw new ProfileException("No signing credential is specified for relying party configuration "
559                     + requestContext.getRelyingPartyConfiguration().getProviderId()
560                     + " or it's SAML2 attribute query profile configuration");
561         }
562
563         log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
564         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
565
566         signature.setSigningCredential(signatureCredential);
567         try {
568             // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
569             // TODO how to pull what keyInfoGenName to use?
570             SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
571         } catch (SecurityException e) {
572             throw new ProfileException("Error preparing signature for signing", e);
573         }
574
575         assertion.setSignature(signature);
576
577         Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
578         try {
579             assertionMarshaller.marshall(assertion);
580             Signer.signObject(signature);
581         } catch (MarshallingException e) {
582             log.error("Unable to marshall assertion for signing", e);
583             throw new ProfileException("Unable to marshall assertion for signing", e);
584         } catch (SignatureException e) {
585             log.error("Unable to sign assertion", e);
586             throw new ProfileException("Unable to sign assertion", e);
587         }
588     }
589
590     /**
591      * Build a status message, with an optional second-level failure message.
592      * 
593      * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
594      * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
595      *            null, no second-level Status element will be set.
596      * @param failureMessage An optional second-level failure message
597      * 
598      * @return a Status object.
599      */
600     protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
601         Status status = statusBuilder.buildObject();
602
603         StatusCode statusCode = statusCodeBuilder.buildObject();
604         statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
605         status.setStatusCode(statusCode);
606
607         if (secondLevelCode != null) {
608             StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
609             secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
610             statusCode.setStatusCode(secondLevelStatusCode);
611         }
612
613         if (failureMessage != null) {
614             StatusMessage msg = statusMessageBuilder.buildObject();
615             msg.setMessage(failureMessage);
616             status.setStatusMessage(msg);
617         }
618
619         return status;
620     }
621
622     /**
623      * Builds the SAML subject for the user for the service provider.
624      * 
625      * @param requestContext current request context
626      * @param confirmationMethod subject confirmation method used for the subject
627      * @param issueInstant instant the subject confirmation data should reflect for issuance
628      * 
629      * @return SAML subject for the user for the service provider
630      * 
631      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
632      *             name ID attribute or because there are no supported name formats
633      */
634     protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
635             DateTime issueInstant) throws ProfileException {
636         NameID nameID = buildNameId(requestContext);
637         requestContext.setSubjectNameIdentifier(nameID);
638
639         SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
640         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
641         confirmationData.setAddress(inTransport.getPeerAddress());
642         confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
643         confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
644                 .getAssertionLifetime()));
645
646         Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
647         if (relyingPartyEndpoint != null) {
648             if (relyingPartyEndpoint.getResponseLocation() != null) {
649                 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
650             } else {
651                 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
652             }
653         }
654
655         SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
656         subjectConfirmation.setMethod(confirmationMethod);
657         subjectConfirmation.setSubjectConfirmationData(confirmationData);
658
659         Subject subject = subjectBuilder.buildObject();
660         subject.getSubjectConfirmations().add(subjectConfirmation);
661         SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
662         try {
663             if (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.always
664                     || (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.conditional && !encoder
665                             .providesMessageConfidentiality(requestContext))) {
666                 log.debug("Attempting to encrypt NameID to relying party {}", requestContext.getInboundMessageIssuer());
667                 try {
668                     Encrypter encrypter = getEncrypter(requestContext.getInboundMessageIssuer());
669                     subject.setEncryptedID(encrypter.encrypt(nameID));
670                 } catch (SecurityException e) {
671                     log.error("Unable to construct encrypter", e);
672                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
673                             "Unable to construct NameID"));
674                     throw new ProfileException("Unable to construct encrypter", e);
675                 } catch (EncryptionException e) {
676                     log.error("Unable to encrypt NameID", e);
677                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
678                             "Unable to construct NameID"));
679                     throw new ProfileException("Unable to encrypt NameID", e);
680                 }
681             } else {
682                 subject.setNameID(nameID);
683             }
684         } catch (MessageEncodingException e) {
685             log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
686                     .getBindingURI());
687             throw new ProfileException("Unable to determine if assertions should be encrypted");
688         }
689
690         return subject;
691     }
692
693     /**
694      * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
695      * picking a name format that was requested by the relying party or is mutually supported by both the relying party
696      * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
697      * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
698      * the supported name formats.
699      * 
700      * @param requestContext current request context
701      * 
702      * @return the NameID appropriate for this request
703      * 
704      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
705      *             name ID attribute or because there are no supported name formats
706      */
707     protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
708         log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
709                 requestContext.getInboundMessageIssuer());
710
711         Map<String, BaseAttribute> principalAttributes = requestContext.getAttributes();
712         if (principalAttributes == null || principalAttributes.isEmpty()) {
713             log.error("No attributes for principal {}, unable to construct of NameID", requestContext
714                     .getPrincipalName());
715             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
716                     "Unable to construct NameID"));
717             throw new ProfileException("No principal attributes support NameID construction");
718         }
719
720         List<String> supportedNameFormats = getNameFormats(requestContext);
721         if (supportedNameFormats == null || supportedNameFormats.isEmpty()) {
722             log.error("No common NameID formats supported by SP {} and IdP", requestContext.getInboundMessageIssuer());
723             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
724                     "Unable to construct NameID"));
725             throw new ProfileException("No principal attributes support NameID construction");
726         }
727
728         log.debug("Supported NameID formats: {}", supportedNameFormats);
729         try {
730             SAML2NameIDEncoder nameIdEncoder;
731             for (BaseAttribute<?> attribute : principalAttributes.values()) {
732                 for (AttributeEncoder encoder : attribute.getEncoders()) {
733                     if (encoder instanceof SAML2NameIDEncoder) {
734                         nameIdEncoder = (SAML2NameIDEncoder) encoder;
735                         if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
736                             log.debug("Using attribute {} suppoting NameID format {} to create the NameID.", attribute
737                                     .getId(), nameIdEncoder.getNameFormat());
738                             return nameIdEncoder.encode(attribute);
739                         }
740                     }
741                 }
742             }
743
744             log.error("No principal attribute supported encoding into a supported name ID format.");
745             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
746             throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
747         } catch (AttributeEncodingException e) {
748             log.error("Unable to encode NameID attribute", e);
749             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
750             throw new ProfileException("Unable to encode NameID attribute", e);
751         }
752     }
753
754     /**
755      * Gets the NameID format to use when creating NameIDs for the relying party.
756      * 
757      * @param requestContext current request context
758      * 
759      * @return list of nameID formats that may be used with the relying party
760      * 
761      * @throws ProfileException thrown if there is a problem determing the NameID format to use
762      */
763     protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
764             throws ProfileException {
765         ArrayList<String> nameFormats = new ArrayList<String>();
766
767         // Determine name formats supported by both SP and IdP
768         RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
769         if (relyingPartyRole != null) {
770             List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
771             if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
772                 nameFormats.addAll(relyingPartySupportedFormats);
773
774                 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
775                 if (assertingPartyRole != null) {
776                     List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
777                     if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
778                         nameFormats.retainAll(assertingPartySupportedFormats);
779                     }
780                 }
781             }
782         }
783
784         if (nameFormats.isEmpty()) {
785             nameFormats.add("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
786         }
787
788         // If authn request and name ID policy format specified, make sure it's in the list of supported formats
789         String nameFormat = null;
790         if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
791             AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
792             if (authnRequest.getNameIDPolicy() != null) {
793                 nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
794                 if (nameFormat != null) {
795                     if (nameFormats.contains(nameFormat)) {
796                         nameFormats.clear();
797                         nameFormats.add(nameFormat);
798                     } else {
799                         requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
800                                 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
801                         throw new ProfileException("NameID format required by relying party is not supported");
802                     }
803                 }
804
805             }
806         }
807
808         return nameFormats;
809     }
810
811     /**
812      * Gets the list of NameID formats supported for a given role.
813      * 
814      * @param role the role to get the list of supported NameID formats
815      * 
816      * @return list of supported NameID formats
817      */
818     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
819         List<NameIDFormat> nameIDFormats = null;
820
821         if (role instanceof SSODescriptor) {
822             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
823         } else if (role instanceof AuthnAuthorityDescriptor) {
824             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
825         } else if (role instanceof PDPDescriptor) {
826             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
827         } else if (role instanceof AttributeAuthorityDescriptor) {
828             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
829         }
830
831         ArrayList<String> supportedFormats = new ArrayList<String>();
832         if (nameIDFormats != null) {
833             for (NameIDFormat format : nameIDFormats) {
834                 supportedFormats.add(format.getFormat());
835             }
836         }
837
838         return supportedFormats;
839     }
840
841     /**
842      * Constructs an SAML response message carrying a request error.
843      * 
844      * @param requestContext current request context
845      * 
846      * @return the constructed error response
847      */
848     protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
849         Response samlResponse = responseBuilder.buildObject();
850         samlResponse.setIssueInstant(new DateTime());
851         populateStatusResponse(requestContext, samlResponse);
852
853         samlResponse.setStatus(requestContext.getFailureStatus());
854
855         return samlResponse;
856     }
857
858     /**
859      * Gets an encrypter that may be used encrypt content to a given peer.
860      * 
861      * @param peerEntityId entity ID of the peer
862      * 
863      * @return encrypter that may be used encrypt content to a given peer
864      * 
865      * @throws SecurityException thrown if there is a problem constructing the encrypter. This normally occurs if the
866      *             key encryption credential for the peer can not be resolved or a required encryption algorithm is not
867      *             supported by the VM's JCE.
868      */
869     protected Encrypter getEncrypter(String peerEntityId) throws SecurityException {
870         SecurityConfiguration securityConfiguration = Configuration.getGlobalSecurityConfiguration();
871
872         EncryptionParameters dataEncParams = SecurityHelper
873                 .buildDataEncryptionParams(null, securityConfiguration, null);
874
875         Credential keyEncryptionCredentials = getKeyEncryptionCredential(peerEntityId);
876         String wrappedJCAKeyAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(dataEncParams.getAlgorithm());
877         KeyEncryptionParameters keyEncParams = SecurityHelper.buildKeyEncryptionParams(keyEncryptionCredentials,
878                 wrappedJCAKeyAlgorithm, securityConfiguration, null, null);
879
880         Encrypter encrypter = new Encrypter(dataEncParams, keyEncParams);
881         encrypter.setKeyPlacement(KeyPlacement.INLINE);
882         return encrypter;
883     }
884
885     /**
886      * Gets the credential that can be used to encrypt encryption keys for a peer.
887      * 
888      * @param peerEntityId entity ID of the peer
889      * 
890      * @return credential that can be used to encrypt encryption keys for a peer
891      * 
892      * @throws SecurityException thrown if there is a problem resolving the credential from the peer's metadata
893      */
894     protected Credential getKeyEncryptionCredential(String peerEntityId) throws SecurityException {
895         MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver(getMetadataProvider());
896
897         CriteriaSet criteriaSet = new CriteriaSet();
898         criteriaSet.add(new EntityIDCriteria(peerEntityId));
899         criteriaSet.add(new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
900         criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));
901
902         return kekCredentialResolver.resolveSingle(criteriaSet);
903     }
904 }