User *asserting* party ID as issuer of messages, not relying party ID... oops
[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.getAssertingPartyId());
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         
543         queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(getMetadataProvider(),
544                 requestContext.getRelyingPartyConfiguration(), (AttributeQuery) requestContext.getSamlRequest());
545         queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
546         queryContext.setPrincipalName(requestContext.getPrincipalName());
547         queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
548         queryContext.setRequest(requestContext.getProfileRequest());
549
550         Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
551         if (userSession != null) {
552             queryContext.setUserSession(userSession);
553             ServiceInformation serviceInfo = userSession.getServicesInformation().get(
554                     requestContext.getRelyingPartyId());
555             if (serviceInfo != null) {
556                 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
557
558                 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
559                 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
560             }
561         }
562
563         return queryContext;
564     }
565
566     /**
567      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
568      * signing credentials.
569      * 
570      * @param requestContext current request context
571      * @param assertion assertion to sign
572      * 
573      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
574      *             required, if a signing credential is not configured
575      */
576     protected void signAssertion(SAML2ProfileRequestContext requestContext, Assertion assertion)
577             throws ProfileException {
578         if (log.isDebugEnabled()) {
579             log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
580                     + " should be signed");
581         }
582
583         boolean signAssertion = false;
584
585         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
586
587         if (requestContext.getRelyingPartyRoleMetadata() instanceof SPSSODescriptor) {
588             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getRelyingPartyRoleMetadata();
589             if (ssoDescriptor.getWantAssertionsSigned() != null) {
590                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
591                 if (log.isDebugEnabled()) {
592                     log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
593                             + " indicates to sign assertions: " + signAssertion);
594                 }
595             }
596         } else if (profileConfig.getSignAssertions()) {
597             signAssertion = true;
598             log.debug("IdP relying party configuration "
599                     + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
600                     + " indicates to sign assertions: " + signAssertion);
601         }
602
603         if (!signAssertion) {
604             return;
605         }
606
607         if (log.isDebugEnabled()) {
608             log.debug("Determining signing credntial for assertion to relying party "
609                     + requestContext.getRelyingPartyId());
610         }
611         Credential signatureCredential = profileConfig.getSigningCredential();
612         if (signatureCredential == null) {
613             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
614         }
615
616         if (signatureCredential == null) {
617             throw new ProfileException("No signing credential is specified for relying party configuration "
618                     + requestContext.getRelyingPartyConfiguration().getProviderId()
619                     + " or it's SAML2 attribute query profile configuration");
620         }
621
622         if (log.isDebugEnabled()) {
623             log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
624         }
625         SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
626         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
627         signature.getContentReferences().add(contentRef);
628         assertion.setSignature(signature);
629
630         Signer.signObject(signature);
631     }
632
633     /**
634      * Build a status message, with an optional second-level failure message.
635      * 
636      * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
637      * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
638      *            null, no second-level Status element will be set.
639      * @param failureMessage An optional second-level failure message
640      * 
641      * @return a Status object.
642      */
643     protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
644         Status status = getStatusBuilder().buildObject();
645
646         StatusCode statusCode = getStatusCodeBuilder().buildObject();
647         statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
648         status.setStatusCode(statusCode);
649
650         if (secondLevelCode != null) {
651             StatusCode secondLevelStatusCode = getStatusCodeBuilder().buildObject();
652             secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
653             statusCode.setStatusCode(secondLevelStatusCode);
654         }
655
656         if (failureMessage != null) {
657             StatusMessage msg = getStatusMessageBuilder().buildObject();
658             msg.setMessage(failureMessage);
659             status.setStatusMessage(msg);
660         }
661
662         return status;
663     }
664
665     /**
666      * Builds the SAML subject for the user for the service provider.
667      * 
668      * @param requestContext current request context
669      * @param confirmationMethod subject confirmation method used for the subject
670      * 
671      * @return SAML subject for the user for the service provider
672      * 
673      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
674      *             name ID attribute or because there are no supported name formats
675      */
676     protected Subject buildSubject(SAML2ProfileRequestContext requestContext, String confirmationMethod)
677             throws ProfileException {
678         NameID nameID = buildNameId(requestContext);
679         requestContext.setSubjectNameID(nameID);
680         // TODO handle encryption
681
682         SubjectConfirmation subjectConfirmation = getSubjectConfirmationBuilder().buildObject();
683         subjectConfirmation.setMethod(confirmationMethod);
684
685         Subject subject = getSubjectBuilder().buildObject();
686         subject.setNameID(nameID);
687         subject.getSubjectConfirmations().add(subjectConfirmation);
688
689         return subject;
690     }
691
692     /**
693      * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
694      * picking a name format that was requested by the relying party or is mutually supported by both the relying party
695      * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
696      * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
697      * the supported name formats.
698      * 
699      * @param requestContext current request context
700      * 
701      * @return the NameID appropriate for this request
702      * 
703      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
704      *             name ID attribute or because there are no supported name formats
705      */
706     protected NameID buildNameId(SAML2ProfileRequestContext requestContext) throws ProfileException {
707         if (log.isDebugEnabled()) {
708             log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
709                     + "/" + requestContext.getRelyingPartyId());
710         }
711         Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
712         List<String> supportedNameFormats = getNameFormats(requestContext);
713
714         if (log.isDebugEnabled()) {
715             log.debug("Supported NameID formats: " + supportedNameFormats);
716         }
717
718         if (principalAttributes != null && supportedNameFormats != null) {
719             try {
720                 AttributeEncoder<NameID> nameIdEncoder = null;
721                 for (BaseAttribute attribute : principalAttributes.values()) {
722                     for (String nameFormat : supportedNameFormats) {
723                         nameIdEncoder = attribute.getEncoderByCategory(nameFormat);
724                         if (nameIdEncoder != null) {
725                             if (log.isDebugEnabled()) {
726                                 log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
727                                         + nameFormat + " to create the NameID for principal "
728                                         + requestContext.getPrincipalName());
729                             }
730                             return nameIdEncoder.encode(attribute);
731                         }
732                     }
733                 }
734             } catch (AttributeEncodingException e) {
735                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
736                         "Unable to construct NameID"));
737                 throw new ProfileException("Unable to encode NameID attribute", e);
738             }
739         }
740
741         requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
742                 "Unable to construct NameID"));
743         throw new ProfileException("No principal attributes support NameID construction");
744     }
745
746     /**
747      * Gets the NameID format to use when creating NameIDs for the relying party.
748      * 
749      * @param requestContext current request context
750      * 
751      * @return list of nameID formats that may be used with the relying party
752      * 
753      * @throws ProfileException thrown if there is a problem determing the NameID format to use
754      */
755     protected List<String> getNameFormats(SAML2ProfileRequestContext requestContext) throws ProfileException {
756         ArrayList<String> nameFormats = new ArrayList<String>();
757
758         List<String> assertingPartySupportedFormats = getEntitySupportedFormats(requestContext
759                 .getAssertingPartyRoleMetadata());
760
761         String nameFormat = null;
762         if (requestContext.getSamlRequest() instanceof AuthnRequest) {
763             AuthnRequest authnRequest = (AuthnRequest) requestContext.getSamlRequest();
764             if (authnRequest.getNameIDPolicy() != null) {
765                 nameFormat = authnRequest.getNameIDPolicy().getFormat();
766                 if (assertingPartySupportedFormats.contains(nameFormat)) {
767                     nameFormats.add(nameFormat);
768                 } else {
769                     requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
770                             StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
771                     throw new ProfileException("NameID format required by relying party is not supported");
772                 }
773             }
774         }
775
776         if (nameFormats.isEmpty()) {
777             List<String> relyingPartySupportedFormats = getEntitySupportedFormats(requestContext
778                     .getRelyingPartyRoleMetadata());
779
780             assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
781             nameFormats.addAll(assertingPartySupportedFormats);
782         }
783         if (nameFormats.isEmpty()) {
784             nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
785         }
786
787         return nameFormats;
788     }
789
790     /**
791      * Gets the list of NameID formats supported for a given role.
792      * 
793      * @param role the role to get the list of supported NameID formats
794      * 
795      * @return list of supported NameID formats
796      */
797     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
798         List<NameIDFormat> nameIDFormats = null;
799
800         if (role instanceof SSODescriptor) {
801             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
802         } else if (role instanceof AuthnAuthorityDescriptor) {
803             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
804         } else if (role instanceof PDPDescriptor) {
805             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
806         } else if (role instanceof AttributeAuthorityDescriptor) {
807             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
808         }
809
810         ArrayList<String> supportedFormats = new ArrayList<String>();
811         if (nameIDFormats != null) {
812             for (NameIDFormat format : nameIDFormats) {
813                 supportedFormats.add(format.getFormat());
814             }
815         }
816
817         return supportedFormats;
818     }
819
820     /**
821      * Constructs an SAML response message carrying a request error.
822      * 
823      * @param requestContext current request context
824      * 
825      * @return the constructed error response
826      */
827     protected Response buildErrorResponse(SAML2ProfileRequestContext requestContext) {
828         Response samlResponse = getResponseBuilder().buildObject();
829         samlResponse.setIssueInstant(new DateTime());
830         populateStatusResponse(requestContext, samlResponse);
831
832         samlResponse.setStatus(requestContext.getFailureStatus());
833
834         return samlResponse;
835     }
836
837     /**
838      * Writes an aduit log entry indicating the successful response to the attribute request.
839      * 
840      * @param context current request context
841      */
842     protected void writeAuditLogEntry(SAML2ProfileRequestContext context) {
843         AuditLogEntry auditLogEntry = new AuditLogEntry();
844         auditLogEntry.setMessageProfile(getProfileId());
845         auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
846         auditLogEntry.setPrincipalName(context.getPrincipalName());
847         auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
848         auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
849         auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
850         auditLogEntry.setRequestId(context.getSamlRequest().getID());
851         auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
852         auditLogEntry.setResponseId(context.getSamlResponse().getID());
853         getAduitLog().log(Level.CRITICAL, auditLogEntry);
854     }
855
856     /**
857      * Contextual object used to accumlate information as profile requests are being processed.
858      * 
859      * @param <RequestType> type of SAML 2 request
860      * @param <ResponseType> type of SAML 2 response
861      * @param <ProfileConfigurationType> configuration type for this profile
862      */
863     protected class SAML2ProfileRequestContext<RequestType extends RequestAbstractType, ResponseType extends StatusResponseType, ProfileConfigurationType extends AbstractSAML2ProfileConfiguration>
864             extends SAMLProfileRequestContext {
865
866         /** SAML request message. */
867         private RequestType samlRequest;
868
869         /** SAML response message. */
870         private ResponseType samlResponse;
871
872         /** Request profile configuration. */
873         private ProfileConfigurationType profileConfiguration;
874
875         /** The NameID of the subject of this request. */
876         private NameID subjectNameID;
877
878         /** The request failure status. */
879         private Status failureStatus;
880
881         /**
882          * Constructor.
883          * 
884          * @param request current profile request
885          * @param response current profile response
886          */
887         public SAML2ProfileRequestContext(ProfileRequest<ServletRequest> request,
888                 ProfileResponse<ServletResponse> response) {
889             super(request, response);
890         }
891
892         /**
893          * Gets the NameID of the subject of this request.
894          * 
895          * @return NameID of the subject of this request
896          */
897         public NameID getSubjectNameID() {
898             return subjectNameID;
899         }
900
901         /**
902          * Sets the NameID of the subject of this request.
903          * 
904          * @param nameID NameID of the subject of this request
905          */
906         public void setSubjectNameID(NameID nameID) {
907             subjectNameID = nameID;
908         }
909
910         /**
911          * Gets the profile configuration for this request.
912          * 
913          * @return profile configuration for this request
914          */
915         public ProfileConfigurationType getProfileConfiguration() {
916             return profileConfiguration;
917         }
918
919         /**
920          * Sets the profile configuration for this request.
921          * 
922          * @param configuration profile configuration for this request
923          */
924         public void setProfileConfiguration(ProfileConfigurationType configuration) {
925             profileConfiguration = configuration;
926         }
927
928         /**
929          * Gets the SAML request message.
930          * 
931          * @return SAML request message
932          */
933         public RequestType getSamlRequest() {
934             return samlRequest;
935         }
936
937         /**
938          * Sets the SAML request message.
939          * 
940          * @param request SAML request message
941          */
942         public void setSamlRequest(RequestType request) {
943             samlRequest = request;
944         }
945
946         /**
947          * Gets the SAML response message.
948          * 
949          * @return SAML response message
950          */
951         public ResponseType getSamlResponse() {
952             return samlResponse;
953         }
954
955         /**
956          * Sets the SAML response message.
957          * 
958          * @param response SAML response message
959          */
960         public void setSamlResponse(ResponseType response) {
961             samlResponse = response;
962         }
963
964         /**
965          * Gets the status reflecting a request failure.
966          * 
967          * @return status reflecting a request failure
968          */
969         public Status getFailureStatus() {
970             return failureStatus;
971         }
972
973         /**
974          * Sets the status reflecting a request failure.
975          * 
976          * @param status status reflecting a request failure
977          */
978         public void setFailureStatus(Status status) {
979             failureStatus = status;
980         }
981     }
982 }