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