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