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