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