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