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