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