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