a8729454d72519526334b25e8132b2b0d61c7f7d
[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.SAML2NameIDAttributeEncoder;
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) {
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         samlResponse.getAssertions().add(assertion);
222
223         // sign the assertion if it should be signed
224         signAssertion(requestContext, assertion);
225
226         Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
227         samlResponse.setStatus(status);
228
229         return samlResponse;
230     }
231
232     /**
233      * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
234      * 
235      * @param requestContext current request context
236      * @param issueInstant time to use as assertion issue instant
237      * 
238      * @return the built assertion
239      */
240     protected Assertion buildAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
241         Assertion assertion = assertionBuilder.buildObject();
242         assertion.setID(getIdGenerator().generateIdentifier());
243         assertion.setIssueInstant(issueInstant);
244         assertion.setVersion(SAMLVersion.VERSION_20);
245         assertion.setIssuer(buildEntityIssuer(requestContext));
246
247         Conditions conditions = buildConditions(requestContext, issueInstant);
248         assertion.setConditions(conditions);
249
250         return assertion;
251     }
252
253     /**
254      * Creates an {@link Issuer} populated with information about the relying party.
255      * 
256      * @param requestContext current request context
257      * 
258      * @return the built issuer
259      */
260     protected Issuer buildEntityIssuer(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
261         Issuer issuer = issuerBuilder.buildObject();
262         issuer.setFormat(Issuer.ENTITY);
263         issuer.setValue(requestContext.getLocalEntityId());
264
265         return issuer;
266     }
267
268     /**
269      * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
270      * restrictions, and proxy restrictions.
271      * 
272      * @param requestContext current request context
273      * @param issueInstant timestamp the assertion was created
274      * 
275      * @return constructed conditions
276      */
277     protected Conditions buildConditions(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
278         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
279
280         Conditions conditions = conditionsBuilder.buildObject();
281         conditions.setNotBefore(issueInstant);
282         conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
283
284         Collection<String> audiences;
285
286         // add audience restrictions
287         audiences = profileConfig.getAssertionAudiences();
288         if (audiences != null && audiences.size() > 0) {
289             AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
290             for (String audienceUri : audiences) {
291                 Audience audience = audienceBuilder.buildObject();
292                 audience.setAudienceURI(audienceUri);
293                 audienceRestriction.getAudiences().add(audience);
294             }
295             conditions.getAudienceRestrictions().add(audienceRestriction);
296         }
297
298         // add proxy restrictions
299         audiences = profileConfig.getProxyAudiences();
300         if (audiences != null && audiences.size() > 0) {
301             ProxyRestriction proxyRestriction = proxyRestrictionBuilder.buildObject();
302             Audience audience;
303             for (String audienceUri : audiences) {
304                 audience = audienceBuilder.buildObject();
305                 audience.setAudienceURI(audienceUri);
306                 proxyRestriction.getAudiences().add(audience);
307             }
308
309             proxyRestriction.setProxyCount(profileConfig.getProxyCount());
310             conditions.getConditions().add(proxyRestriction);
311         }
312
313         return conditions;
314     }
315
316     /**
317      * Populates the response's id, in response to, issue instant, version, and issuer properties.
318      * 
319      * @param requestContext current request context
320      * @param response the response to populate
321      */
322     protected void populateStatusResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
323             StatusResponseType response) {
324         response.setID(getIdGenerator().generateIdentifier());
325         if (requestContext.getInboundSAMLMessage() != null) {
326             response.setInResponseTo(requestContext.getInboundSAMLMessageId());
327         }
328         response.setVersion(SAMLVersion.VERSION_20);
329         response.setIssuer(buildEntityIssuer(requestContext));
330     }
331
332     /**
333      * Resolves the attributes for the principal.
334      * 
335      * @param requestContext current request context
336      * 
337      * @throws ProfileException thrown if there is a problem resolved attributes
338      */
339     protected void resolveAttributes(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
340         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
341         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
342
343         try {
344             log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
345                     .getPrincipalName(), requestContext.getInboundMessageIssuer());
346             Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
347
348             requestContext.setAttributes(principalAttributes);
349         } catch (AttributeRequestException e) {
350             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
351                     + " from relying party " + requestContext.getInboundMessageIssuer(), e);
352             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
353             throw new ProfileException("Error resolving attributes for SAML request "
354                     + requestContext.getInboundSAMLMessageId() + " from relying party "
355                     + requestContext.getInboundMessageIssuer(), e);
356         }
357     }
358
359     /**
360      * Executes a query for attributes and builds a SAML attribute statement from the results.
361      * 
362      * @param requestContext current request context
363      * 
364      * @return attribute statement resulting from the query
365      * 
366      * @throws ProfileException thrown if there is a problem making the query
367      */
368     protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
369             throws ProfileException {
370         log.debug("Creating attribute statement in response to SAML request {} from relying party {}", requestContext
371                 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
372
373         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
374         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
375         try {
376             if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
377                 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
378                         .getInboundSAMLMessage(), requestContext.getPrincipalAttributes().values());
379             } else {
380                 return attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes()
381                         .values());
382             }
383         } catch (AttributeRequestException e) {
384             log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
385             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
386             throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
387                     e);
388         }
389     }
390
391     /**
392      * Resolves the principal name of the subject of the request.
393      * 
394      * @param requestContext current request context
395      * 
396      * @throws ProfileException thrown if the principal name can not be resolved
397      */
398     protected void resolvePrincipal(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
399         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
400         if (profileConfiguration == null) {
401             log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
402                     + requestContext.getInboundMessageIssuer());
403             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
404                     "Error resolving principal"));
405             throw new ProfileException(
406                     "Unable to resolve principal, no SAML 2 profile configuration for relying party "
407                             + requestContext.getInboundMessageIssuer());
408         }
409         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
410         log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
411                 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
412
413         try {
414             String principal = attributeAuthority.getPrincipal(requestContext);
415             requestContext.setPrincipalName(principal);
416         } catch (AttributeRequestException e) {
417             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
418                     + " from relying party " + requestContext.getInboundMessageIssuer(), e);
419             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
420                     "Error resolving principal"));
421             throw new ProfileException("Error resolving attributes for SAML request "
422                     + requestContext.getInboundSAMLMessageId() + " from relying party "
423                     + requestContext.getInboundMessageIssuer(), e);
424         }
425     }
426
427     /**
428      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
429      * signing credentials.
430      * 
431      * @param requestContext current request context
432      * @param assertion assertion to sign
433      * 
434      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
435      *             required, if a signing credential is not configured
436      */
437     protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
438             throws ProfileException {
439         log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
440                 .getInboundMessageIssuer());
441
442         boolean signAssertion = false;
443
444         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
445         if (profileConfig.getSignAssertions()) {
446             signAssertion = true;
447             log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
448                     .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
449         }
450
451         if (!signAssertion && requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
452             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
453             if (ssoDescriptor.getWantAssertionsSigned() != null) {
454                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
455                 log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
456                         .getInboundMessageIssuer(), signAssertion);
457             }
458         }
459
460         if (!signAssertion) {
461             return;
462         }
463
464         log.debug("Determining signing credntial for assertion to relying party {}", requestContext
465                 .getInboundMessageIssuer());
466         Credential signatureCredential = profileConfig.getSigningCredential();
467         if (signatureCredential == null) {
468             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
469         }
470
471         if (signatureCredential == null) {
472             throw new ProfileException("No signing credential is specified for relying party configuration "
473                     + requestContext.getRelyingPartyConfiguration().getProviderId()
474                     + " or it's SAML2 attribute query profile configuration");
475         }
476
477         log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
478         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
479
480         signature.setSigningCredential(signatureCredential);
481         try {
482             // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
483             // TODO how to pull what keyInfoGenName to use?
484             SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
485         } catch (SecurityException e) {
486             throw new ProfileException("Error preparing signature for signing", e);
487         }
488
489         assertion.setSignature(signature);
490
491         Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
492         try {
493             assertionMarshaller.marshall(assertion);
494             Signer.signObject(signature);
495         } catch (MarshallingException e) {
496             log.error("Unable to marshall assertion for signing", e);
497             throw new ProfileException("Unable to marshall assertion for signing", e);
498         }
499     }
500
501     /**
502      * Build a status message, with an optional second-level failure message.
503      * 
504      * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
505      * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
506      *            null, no second-level Status element will be set.
507      * @param failureMessage An optional second-level failure message
508      * 
509      * @return a Status object.
510      */
511     protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
512         Status status = statusBuilder.buildObject();
513
514         StatusCode statusCode = statusCodeBuilder.buildObject();
515         statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
516         status.setStatusCode(statusCode);
517
518         if (secondLevelCode != null) {
519             StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
520             secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
521             statusCode.setStatusCode(secondLevelStatusCode);
522         }
523
524         if (failureMessage != null) {
525             StatusMessage msg = statusMessageBuilder.buildObject();
526             msg.setMessage(failureMessage);
527             status.setStatusMessage(msg);
528         }
529
530         return status;
531     }
532
533     /**
534      * Builds the SAML subject for the user for the service provider.
535      * 
536      * @param requestContext current request context
537      * @param confirmationMethod subject confirmation method used for the subject
538      * @param issueInstant instant the subject confirmation data should reflect for issuance
539      * 
540      * @return SAML subject for the user for the service provider
541      * 
542      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
543      *             name ID attribute or because there are no supported name formats
544      */
545     protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
546             DateTime issueInstant) throws ProfileException {
547         NameID nameID = buildNameId(requestContext);
548         requestContext.setSubjectNameIdentifier(nameID);
549
550         SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
551         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
552         confirmationData.setAddress(inTransport.getPeerAddress());
553         confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
554         confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
555                 .getAssertionLifetime()));
556
557         Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
558         if (relyingPartyEndpoint != null) {
559             if (relyingPartyEndpoint.getResponseLocation() != null) {
560                 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
561             } else {
562                 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
563             }
564         }
565
566         SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
567         subjectConfirmation.setMethod(confirmationMethod);
568         subjectConfirmation.setSubjectConfirmationData(confirmationData);
569
570         Subject subject = subjectBuilder.buildObject();
571         subject.getSubjectConfirmations().add(subjectConfirmation);
572
573         if (requestContext.getProfileConfiguration().getEncryptNameID()) {
574             try {
575                 Encrypter encrypter = getEncrypter(requestContext.getPeerEntityId());
576                 subject.setEncryptedID(encrypter.encrypt(nameID));
577             } catch (SecurityException e) {
578                 log.error("Unable to construct encrypter", e);
579                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
580                         "Unable to construct NameID"));
581                 throw new ProfileException("Unable to construct encrypter", e);
582             } catch (EncryptionException e) {
583                 log.error("Unable to encrypt NameID", e);
584                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
585                         "Unable to construct NameID"));
586                 throw new ProfileException("Unable to encrypt NameID", e);
587             }
588         } else {
589             subject.setNameID(nameID);
590         }
591
592         return subject;
593     }
594
595     /**
596      * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
597      * picking a name format that was requested by the relying party or is mutually supported by both the relying party
598      * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
599      * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
600      * the supported name formats.
601      * 
602      * @param requestContext current request context
603      * 
604      * @return the NameID appropriate for this request
605      * 
606      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
607      *             name ID attribute or because there are no supported name formats
608      */
609     protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
610         log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
611                 requestContext.getInboundMessageIssuer());
612         Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
613         List<String> supportedNameFormats = getNameFormats(requestContext);
614
615         log.debug("Supported NameID formats: {}", supportedNameFormats);
616
617         if (principalAttributes == null || supportedNameFormats == null) {
618             log.error("No attributes for principal " + requestContext.getPrincipalName()
619                     + " support constructions of NameID");
620             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
621                     "Unable to construct NameID"));
622             throw new ProfileException("No principal attributes support NameID construction");
623         }
624
625         try {
626             SAML2NameIDAttributeEncoder nameIdEncoder;
627             for (BaseAttribute<?> attribute : principalAttributes.values()) {
628                 for (AttributeEncoder encoder : attribute.getEncoders()) {
629                     if (encoder instanceof SAML2NameIDAttributeEncoder) {
630                         nameIdEncoder = (SAML2NameIDAttributeEncoder) encoder;
631                         if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
632                             log.debug("Using attribute {} suppoting NameID format {} to create the NameID.", attribute
633                                     .getId(), nameIdEncoder.getNameFormat());
634                             return nameIdEncoder.encode(attribute);
635                         }
636                     }
637                 }
638             }
639
640             log.error("No principal attribute supported encoding into a supported name ID format.");
641             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
642             throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
643         } catch (AttributeEncodingException e) {
644             log.error("Unable to encode NameID attribute", e);
645             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
646             throw new ProfileException("Unable to encode NameID attribute", e);
647         }
648     }
649
650     /**
651      * Gets the NameID format to use when creating NameIDs for the relying party.
652      * 
653      * @param requestContext current request context
654      * 
655      * @return list of nameID formats that may be used with the relying party
656      * 
657      * @throws ProfileException thrown if there is a problem determing the NameID format to use
658      */
659     protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
660             throws ProfileException {
661         ArrayList<String> nameFormats = new ArrayList<String>();
662
663         // Determine name formats supported by both SP and IdP
664         RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
665         if (relyingPartyRole != null) {
666             List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
667             if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
668                 nameFormats.addAll(relyingPartySupportedFormats);
669
670                 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
671                 if (assertingPartyRole != null) {
672                     List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
673                     if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
674                         nameFormats.retainAll(assertingPartySupportedFormats);
675                     }
676                 }
677             }
678         }
679
680         if (nameFormats.isEmpty()) {
681             nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
682         }
683
684         // If authn request and name ID policy format specified, make sure it's in the list of supported formats
685         String nameFormat = null;
686         if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
687             AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
688             if (authnRequest.getNameIDPolicy() != null) {
689                 nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
690                 if (nameFormat != null) {
691                     if (nameFormats.contains(nameFormat)) {
692                         nameFormats.clear();
693                         nameFormats.add(nameFormat);
694                     } else {
695                         requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
696                                 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
697                         throw new ProfileException("NameID format required by relying party is not supported");
698                     }
699                 }
700
701             }
702         }
703
704         return nameFormats;
705     }
706
707     /**
708      * Gets the list of NameID formats supported for a given role.
709      * 
710      * @param role the role to get the list of supported NameID formats
711      * 
712      * @return list of supported NameID formats
713      */
714     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
715         List<NameIDFormat> nameIDFormats = null;
716
717         if (role instanceof SSODescriptor) {
718             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
719         } else if (role instanceof AuthnAuthorityDescriptor) {
720             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
721         } else if (role instanceof PDPDescriptor) {
722             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
723         } else if (role instanceof AttributeAuthorityDescriptor) {
724             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
725         }
726
727         ArrayList<String> supportedFormats = new ArrayList<String>();
728         if (nameIDFormats != null) {
729             for (NameIDFormat format : nameIDFormats) {
730                 supportedFormats.add(format.getFormat());
731             }
732         }
733
734         return supportedFormats;
735     }
736
737     /**
738      * Constructs an SAML response message carrying a request error.
739      * 
740      * @param requestContext current request context
741      * 
742      * @return the constructed error response
743      */
744     protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
745         Response samlResponse = responseBuilder.buildObject();
746         samlResponse.setIssueInstant(new DateTime());
747         populateStatusResponse(requestContext, samlResponse);
748
749         samlResponse.setStatus(requestContext.getFailureStatus());
750
751         return samlResponse;
752     }
753
754     /**
755      * Gets an encrypter that may be used encrypt content to a given peer.
756      * 
757      * @param peerEntityId entity ID of the peer
758      * 
759      * @return encrypter that may be used encrypt content to a given peer
760      * 
761      * @throws SecurityException thrown if there is a problem constructing the encrypter. This normally occurs if the
762      *             key encryption credential for the peer can not be resolved or a required encryption algorithm is not
763      *             supported by the VM's JCE.
764      */
765     protected Encrypter getEncrypter(String peerEntityId) throws SecurityException {
766         SecurityConfiguration securityConfiguration = Configuration.getGlobalSecurityConfiguration();
767
768         EncryptionParameters dataEncParams = SecurityHelper
769                 .buildDataEncryptionParams(null, securityConfiguration, null);
770
771         Credential keyEncryptionCredentials = getKeyEncryptionCredential(peerEntityId);
772         String wrappedJCAKeyAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(dataEncParams.getAlgorithm());
773         KeyEncryptionParameters keyEncParams = SecurityHelper.buildKeyEncryptionParams(keyEncryptionCredentials,
774                 wrappedJCAKeyAlgorithm, securityConfiguration, null, null);
775
776         Encrypter encrypter = new Encrypter(dataEncParams, keyEncParams);
777         encrypter.setKeyPlacement(KeyPlacement.INLINE);
778         return encrypter;
779     }
780
781     /**
782      * Gets the credential that can be used to encrypt encryption keys for a peer.
783      * 
784      * @param peerEntityId entity ID of the peer
785      * 
786      * @return credential that can be used to encrypt encryption keys for a peer
787      * 
788      * @throws SecurityException thrown if there is a problem resolving the credential from the peer's metadata
789      */
790     protected Credential getKeyEncryptionCredential(String peerEntityId) throws SecurityException {
791         MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver(getMetadataProvider());
792
793         CriteriaSet criteriaSet = new CriteriaSet();
794         criteriaSet.add(new EntityIDCriteria(peerEntityId));
795         criteriaSet.add(new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
796         criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));
797
798         return kekCredentialResolver.resolveSingle(criteriaSet);
799     }
800 }