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