Additional work on reconciling generics between type hierarchies
[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.xml.namespace.QName;
25
26 import org.apache.log4j.Logger;
27 import org.joda.time.DateTime;
28 import org.opensaml.common.SAMLObject;
29 import org.opensaml.common.SAMLObjectBuilder;
30 import org.opensaml.common.SAMLVersion;
31 import org.opensaml.common.impl.SAMLObjectContentReference;
32 import org.opensaml.log.Level;
33 import org.opensaml.saml1.core.Assertion;
34 import org.opensaml.saml1.core.AttributeQuery;
35 import org.opensaml.saml1.core.AttributeStatement;
36 import org.opensaml.saml1.core.Audience;
37 import org.opensaml.saml1.core.AudienceRestrictionCondition;
38 import org.opensaml.saml1.core.Conditions;
39 import org.opensaml.saml1.core.ConfirmationMethod;
40 import org.opensaml.saml1.core.NameIdentifier;
41 import org.opensaml.saml1.core.RequestAbstractType;
42 import org.opensaml.saml1.core.Response;
43 import org.opensaml.saml1.core.ResponseAbstractType;
44 import org.opensaml.saml1.core.Statement;
45 import org.opensaml.saml1.core.Status;
46 import org.opensaml.saml1.core.StatusCode;
47 import org.opensaml.saml1.core.StatusMessage;
48 import org.opensaml.saml1.core.Subject;
49 import org.opensaml.saml1.core.SubjectConfirmation;
50 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
51 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
52 import org.opensaml.saml2.metadata.NameIDFormat;
53 import org.opensaml.saml2.metadata.PDPDescriptor;
54 import org.opensaml.saml2.metadata.RoleDescriptor;
55 import org.opensaml.saml2.metadata.SPSSODescriptor;
56 import org.opensaml.saml2.metadata.SSODescriptor;
57 import org.opensaml.xml.XMLObjectBuilder;
58 import org.opensaml.xml.security.credential.Credential;
59 import org.opensaml.xml.signature.Signature;
60 import org.opensaml.xml.signature.Signer;
61
62 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
63 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
64 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
65 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
66 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML1NameIdentifierEncoder;
67 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML1AttributeAuthority;
68 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
69 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
70 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.AbstractSAML1ProfileConfiguration;
71 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
72
73 /** Common implementation details for profile handlers. */
74 public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHandler {
75
76     /** SAML Version for this profile handler. */
77     public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_11;
78
79     /** Class logger. */
80     private static Logger log = Logger.getLogger(AbstractSAML1ProfileHandler.class);
81
82     /** Builder of Response objects. */
83     private SAMLObjectBuilder<Response> responseBuilder;
84
85     /** Builder of Assertion objects. */
86     private SAMLObjectBuilder<Assertion> assertionBuilder;
87
88     /** Builder of Conditions objects. */
89     private SAMLObjectBuilder<Conditions> conditionsBuilder;
90
91     /** Builder of AudienceRestrictionCondition objects. */
92     private SAMLObjectBuilder<AudienceRestrictionCondition> audienceRestrictionConditionBuilder;
93
94     /** Builder of AudienceRestrictionCondition objects. */
95     private SAMLObjectBuilder<Audience> audienceBuilder;
96
97     /** Builder of SubjectConfirmation objects. */
98     private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
99
100     /** Builder of ConfirmationMethod objects. */
101     private SAMLObjectBuilder<ConfirmationMethod> confirmationMethodBuilder;
102
103     /** Builder of Subject objects. */
104     private SAMLObjectBuilder<Subject> subjectBuilder;
105
106     /** Builder for Status objects. */
107     private SAMLObjectBuilder<Status> statusBuilder;
108
109     /** Builder for StatusCode objects. */
110     private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
111
112     /** Builder for StatusMessage objects. */
113     private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
114
115     /** For building signature. */
116     private XMLObjectBuilder<Signature> signatureBuilder;
117
118     /**
119      * Default constructor.
120      */
121     @SuppressWarnings("unchecked")
122     public AbstractSAML1ProfileHandler() {
123         super();
124         responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
125         assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
126                 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
127         conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
128                 Conditions.DEFAULT_ELEMENT_NAME);
129         audienceRestrictionConditionBuilder = (SAMLObjectBuilder<AudienceRestrictionCondition>) getBuilderFactory()
130                 .getBuilder(AudienceRestrictionCondition.DEFAULT_ELEMENT_NAME);
131         audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
132         subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
133                 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
134         confirmationMethodBuilder = (SAMLObjectBuilder<ConfirmationMethod>) getBuilderFactory().getBuilder(
135                 ConfirmationMethod.DEFAULT_ELEMENT_NAME);
136         subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
137         statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
138         statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
139                 StatusCode.DEFAULT_ELEMENT_NAME);
140         statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
141                 StatusMessage.DEFAULT_ELEMENT_NAME);
142         signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
143     }
144
145     /**
146      * Checks that the SAML major version for a request is 1.
147      * 
148      * @param requestContext current request context containing the SAML message
149      * 
150      * @throws ProfileException thrown if the major version of the SAML request is not 1
151      */
152     protected void checkSamlVersion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
153         SAMLObject samlObject = requestContext.getInboundSAMLMessage();
154
155         if (samlObject instanceof RequestAbstractType) {
156             RequestAbstractType request = (RequestAbstractType) samlObject;
157             if (request.getMajorVersion() < 1) {
158                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_LOW,
159                         null));
160                 throw new ProfileException("SAML request major version too low");
161             } else if (request.getMajorVersion() > 1) {
162                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_HIGH,
163                         null));
164                 throw new ProfileException("SAML request major version too low");
165             }
166         }
167     }
168
169     /**
170      * Builds a response to the attribute query within the request context.
171      * 
172      * @param requestContext current request context
173      * @param statements the statements to include in the response
174      * 
175      * @return the built response
176      * 
177      * @throws ProfileException thrown if there is a problem creating the SAML response
178      */
179     protected Response buildResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, List<Statement> statements)
180             throws ProfileException {
181
182         DateTime issueInstant = new DateTime();
183
184         // create the assertion and add the attribute statement
185         Assertion assertion = buildAssertion(requestContext, issueInstant);
186         if (statements != null) {
187             assertion.getStatements().addAll(statements);
188         }
189
190         // create the SAML response and add the assertion
191         Response samlResponse = responseBuilder.buildObject();
192         samlResponse.setIssueInstant(issueInstant);
193         populateStatusResponse(requestContext, samlResponse);
194
195         samlResponse.getAssertions().add(assertion);
196
197         // sign the assertion if it should be signed
198         signAssertion(requestContext, assertion);
199
200         Status status = buildStatus(StatusCode.SUCCESS, null, null);
201         samlResponse.setStatus(status);
202
203         return samlResponse;
204     }
205
206     /**
207      * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
208      * 
209      * @param requestContext current request context
210      * @param issueInstant time to use as assertion issue instant
211      * 
212      * @return the built assertion
213      */
214     protected Assertion buildAssertion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
215         Assertion assertion = assertionBuilder.buildObject();
216         assertion.setID(getIdGenerator().generateIdentifier());
217         assertion.setIssueInstant(issueInstant);
218         assertion.setVersion(SAMLVersion.VERSION_11);
219         assertion.setIssuer(requestContext.getAssertingPartyEntityId());
220
221         Conditions conditions = buildConditions(requestContext, issueInstant);
222         assertion.setConditions(conditions);
223
224         return assertion;
225     }
226
227     /**
228      * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
229      * restrictions, and proxy restrictions.
230      * 
231      * @param requestContext current request context
232      * @param issueInstant timestamp the assertion was created
233      * 
234      * @return constructed conditions
235      */
236     protected Conditions buildConditions(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
237         AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
238
239         Conditions conditions = conditionsBuilder.buildObject();
240         conditions.setNotBefore(issueInstant);
241         conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
242
243         Collection<String> audiences;
244
245         // add audience restrictions
246         audiences = profileConfig.getAssertionAudiences();
247         if (audiences != null && audiences.size() > 0) {
248             AudienceRestrictionCondition audienceRestriction = audienceRestrictionConditionBuilder.buildObject();
249             for (String audienceUri : audiences) {
250                 Audience audience = audienceBuilder.buildObject();
251                 audience.setUri(audienceUri);
252                 audienceRestriction.getAudiences().add(audience);
253             }
254             conditions.getAudienceRestrictionConditions().add(audienceRestriction);
255         }
256
257         return conditions;
258     }
259
260     /**
261      * Builds the SAML subject for the user for the service provider.
262      * 
263      * @param requestContext current request context
264      * @param confirmationMethod subject confirmation method used for the subject
265      * 
266      * @return SAML subject for the user for the service provider
267      * 
268      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
269      *             name ID attribute or because there are no supported name formats
270      */
271     protected Subject buildSubject(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod)
272             throws ProfileException {
273         NameIdentifier nameID = buildNameId(requestContext);
274         requestContext.setSubjectNameIdentifier(nameID);
275
276         ConfirmationMethod method = confirmationMethodBuilder.buildObject();
277         method.setConfirmationMethod(confirmationMethod);
278
279         SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
280         subjectConfirmation.getConfirmationMethods().add(method);
281
282         Subject subject = subjectBuilder.buildObject();
283         subject.setNameIdentifier(nameID);
284         subject.setSubjectConfirmation(subjectConfirmation);
285
286         return subject;
287     }
288
289     /**
290      * Builds a NameIdentifier appropriate for this request. NameIdentifier are built by inspecting the SAML request and
291      * metadata, picking a name format that was requested by the relying party or is mutually supported by both the
292      * relying party and asserting party as described in their metadata entries. Once a set of supported name formats is
293      * determined the principals attributes are inspected for an attribute supported an attribute encoder whose category
294      * is one of the supported name formats.
295      * 
296      * @param requestContext current request context
297      * 
298      * @return the NameIdentifier appropriate for this request
299      * 
300      * @throws ProfileException thrown if a NameIdentifier can not be created either because there was a problem
301      *             encoding the name ID attribute or because there are no supported name formats
302      */
303     protected NameIdentifier buildNameId(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext)
304             throws ProfileException {
305         if (log.isDebugEnabled()) {
306             log.debug("Building assertion NameIdentifier to relying party " + requestContext.getRelyingPartyEntityId()
307                     + " for principal " + requestContext.getPrincipalName());
308         }
309         Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
310         List<String> supportedNameFormats = getNameFormats(requestContext);
311
312         if (log.isDebugEnabled()) {
313             log.debug("Supported name formats: " + supportedNameFormats);
314         }
315
316         if (principalAttributes == null || supportedNameFormats == null) {
317             log.error("No attributes for principal " + requestContext.getPrincipalName()
318                     + " support constructions of NameIdentifier");
319             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
320                     "Unable to construct NameIdentifier"));
321             throw new ProfileException("No principal attributes support NameIdentifier construction");
322         }
323
324         try {
325             SAML1NameIdentifierEncoder nameIdEncoder;
326
327             for (BaseAttribute<?> attribute : principalAttributes.values()) {
328                 for (AttributeEncoder encoder : attribute.getEncoders()) {
329                     if (encoder instanceof SAML1NameIdentifierEncoder) {
330                         nameIdEncoder = (SAML1NameIdentifierEncoder) encoder;
331                         if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
332                             if (log.isDebugEnabled()) {
333                                 log.debug("Using attribute " + attribute.getId() + " suppoting name format "
334                                         + nameIdEncoder.getNameFormat()
335                                         + " to create the NameIdentifier for principal "
336                                         + requestContext.getPrincipalName());
337                             }
338                             return nameIdEncoder.encode(attribute);
339                         }
340                     }
341                 }
342             }
343             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
344                     "Unable to construct NameIdentifier"));
345             throw new ProfileException("No principal attribute supported encoding into the a supported name ID format.");
346         } catch (AttributeEncodingException e) {
347             log.error("Unable to construct NameIdentifier", e);
348             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
349                     "Unable to construct NameIdentifier"));
350             throw new ProfileException("Unable to encode NameIdentifier attribute", e);
351         }
352
353     }
354
355     /**
356      * Gets the NameIdentifier format to use when creating NameIdentifiers for the relying party.
357      * 
358      * @param requestContext current request context
359      * 
360      * @return list of formats that may be used with the relying party
361      * 
362      * @throws ProfileException thrown if there is a problem determing the NameIdentifier format to use
363      */
364     protected List<String> getNameFormats(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext)
365             throws ProfileException {
366         ArrayList<String> nameFormats = new ArrayList<String>();
367
368         RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyRoleMetadata();
369         List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
370
371         if (nameFormats.isEmpty()) {
372             RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyRoleMetadata();
373             List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
374
375             assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
376             nameFormats.addAll(assertingPartySupportedFormats);
377         }
378         if (nameFormats.isEmpty()) {
379             nameFormats.add("urn:oasis:names:tc:SAML:1.0:nameid-format:unspecified");
380         }
381
382         return nameFormats;
383     }
384
385     /**
386      * Gets the list of NameIdentifier formats supported for a given role.
387      * 
388      * @param role the role to get the list of supported NameIdentifier formats
389      * 
390      * @return list of supported NameIdentifier formats
391      */
392     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
393         List<NameIDFormat> nameIDFormats = null;
394
395         if (role instanceof SSODescriptor) {
396             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
397         } else if (role instanceof AuthnAuthorityDescriptor) {
398             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
399         } else if (role instanceof PDPDescriptor) {
400             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
401         } else if (role instanceof AttributeAuthorityDescriptor) {
402             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
403         }
404
405         ArrayList<String> supportedFormats = new ArrayList<String>();
406         if (nameIDFormats != null) {
407             for (NameIDFormat format : nameIDFormats) {
408                 supportedFormats.add(format.getFormat());
409             }
410         }
411
412         return supportedFormats;
413     }
414
415     /**
416      * Constructs an SAML response message carrying a request error.
417      * 
418      * @param requestContext current request context containing the failure status
419      * 
420      * @return the constructed error response
421      */
422     protected Response buildErrorResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) {
423         Response samlResponse = responseBuilder.buildObject();
424         samlResponse.setIssueInstant(new DateTime());
425         populateStatusResponse(requestContext, samlResponse);
426
427         samlResponse.setStatus(requestContext.getFailureStatus());
428
429         return samlResponse;
430     }
431
432     /**
433      * Populates the response's id, in response to, issue instant, version, and issuer properties.
434      * 
435      * @param requestContext current request context
436      * @param response the response to populate
437      */
438     protected void populateStatusResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
439             ResponseAbstractType response) {
440         response.setID(getIdGenerator().generateIdentifier());
441
442         SAMLObject samlMessage = requestContext.getInboundSAMLMessage();
443         if (samlMessage != null && samlMessage instanceof RequestAbstractType) {
444             response.setInResponseTo(((RequestAbstractType) samlMessage).getID());
445         }
446         response.setVersion(SAMLVersion.VERSION_11);
447     }
448
449     /**
450      * Build a status message, with an optional second-level failure message.
451      * 
452      * @param topLevelCode top-level status code
453      * @param secondLevelCode second-level status code
454      * @param failureMessage An optional second-level failure message
455      * 
456      * @return a Status object.
457      */
458     protected Status buildStatus(QName topLevelCode, QName secondLevelCode, String failureMessage) {
459         Status status = statusBuilder.buildObject();
460
461         StatusCode statusCode = statusCodeBuilder.buildObject();
462         statusCode.setValue(topLevelCode);
463         status.setStatusCode(statusCode);
464
465         if (secondLevelCode != null) {
466             StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
467             secondLevelStatusCode.setValue(secondLevelCode);
468             statusCode.setStatusCode(secondLevelStatusCode);
469         }
470
471         if (failureMessage != null) {
472             StatusMessage msg = statusMessageBuilder.buildObject();
473             msg.setMessage(failureMessage);
474             status.setStatusMessage(msg);
475         }
476
477         return status;
478     }
479
480     /**
481      * Resolved the attributes for the principal.
482      * 
483      * @param requestContext current request context
484      * 
485      * @throws ProfileException thrown if attributes can not be resolved
486      */
487     protected void resolveAttributes(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
488         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
489         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
490
491         try {
492             if (log.isDebugEnabled()) {
493                 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
494                         + " of SAML request from relying party " + requestContext.getRelyingPartyEntityId());
495             }
496             Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
497
498             requestContext.setPrincipalAttributes(principalAttributes);
499         } catch (AttributeRequestException e) {
500             log.error("Error resolving attributes for SAML request from relying party "
501                     + requestContext.getRelyingPartyEntityId(), e);
502             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
503             throw new ProfileException("Error resolving attributes for SAML request from relying party "
504                     + requestContext.getRelyingPartyEntityId(), e);
505         }
506     }
507
508     /**
509      * Executes a query for attributes and builds a SAML attribute statement from the results.
510      * 
511      * @param requestContext current request context
512      * @param subjectConfMethod subject confirmation method
513      * 
514      * @return attribute statement resulting from the query
515      * 
516      * @throws ProfileException thrown if there is a problem making the query
517      */
518     protected AttributeStatement buildAttributeStatement(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
519             String subjectConfMethod) throws ProfileException {
520
521         if (log.isDebugEnabled()) {
522             log.debug("Creating attribute statement in response to SAML request from relying party "
523                     + requestContext.getRelyingPartyEntityId());
524         }
525
526         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
527         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
528
529         try {
530             AttributeStatement statment;
531             if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
532                 statment = attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
533                         .getInboundSAMLMessage(), requestContext.getPrincipalAttributes().values());
534             } else {
535                 statment = attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes()
536                         .values());
537             }
538
539             Subject statementSubject = buildSubject(requestContext, subjectConfMethod);
540             statment.setSubject(statementSubject);
541
542             return statment;
543         } catch (AttributeRequestException e) {
544             log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
545             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
546             throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
547                     e);
548         }
549     }
550
551     /**
552      * Resolves the principal name of the subject of the request.
553      * 
554      * @param requestContext current request context
555      * 
556      * @throws ProfileException thrown if the principal name can not be resolved
557      */
558     protected void resolvePrincipal(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
559         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
560         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
561
562         if (log.isDebugEnabled()) {
563             log.debug("Resolving principal name for subject of SAML request from relying party "
564                     + requestContext.getRelyingPartyEntityId());
565         }
566
567         try {
568             String principal = attributeAuthority.getPrincipal(requestContext);
569             requestContext.setPrincipalName(principal);
570         } catch (AttributeRequestException e) {
571             log.error("Error resolving attributes for SAML request from relying party "
572                     + requestContext.getRelyingPartyEntityId(), e);
573             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
574                     "Error resolving principal"));
575             throw new ProfileException("Error resolving attributes for SAML request from relying party "
576                     + requestContext.getRelyingPartyEntityId(), e);
577         }
578     }
579
580     /**
581      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
582      * signing credentials.
583      * 
584      * @param requestContext current request context
585      * @param assertion assertion to sign
586      * 
587      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
588      *             required, if a signing credential is not configured
589      */
590     protected void signAssertion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
591             throws ProfileException {
592         if (log.isDebugEnabled()) {
593             log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyEntityId()
594                     + " should be signed");
595         }
596
597         boolean signAssertion = false;
598
599         RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyRoleMetadata();
600         AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
601
602         if (relyingPartyRole instanceof SPSSODescriptor) {
603             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) relyingPartyRole;
604             if (ssoDescriptor.getWantAssertionsSigned() != null) {
605                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
606                 if (log.isDebugEnabled()) {
607                     log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyEntityId()
608                             + " indicates to sign assertions: " + signAssertion);
609                 }
610             }
611         } else if (profileConfig.getSignAssertions()) {
612             signAssertion = true;
613             log.debug("IdP relying party configuration "
614                     + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
615                     + " indicates to sign assertions: " + signAssertion);
616         }
617
618         if (!signAssertion) {
619             return;
620         }
621
622         if (log.isDebugEnabled()) {
623             log.debug("Determining signing credntial for assertion to relying party "
624                     + requestContext.getRelyingPartyEntityId());
625         }
626         Credential signatureCredential = profileConfig.getSigningCredential();
627         if (signatureCredential == null) {
628             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
629         }
630
631         if (signatureCredential == null) {
632             throw new ProfileException("No signing credential is specified for relying party configuration "
633                     + requestContext.getRelyingPartyConfiguration().getProviderId()
634                     + " or it's SAML2 attribute query profile configuration");
635         }
636
637         if (log.isDebugEnabled()) {
638             log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyEntityId());
639         }
640         SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
641         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
642         signature.getContentReferences().add(contentRef);
643         assertion.setSignature(signature);
644
645         Signer.signObject(signature);
646     }
647
648     /**
649      * Writes an aduit log entry indicating the successful response to the attribute request.
650      * 
651      * @param context current request context
652      */
653     protected void writeAuditLogEntry(BaseSAML1ProfileRequestContext<?, ?, ?> context) {
654         AuditLogEntry auditLogEntry = new AuditLogEntry();
655         auditLogEntry.setMessageProfile(getProfileId());
656         auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
657         auditLogEntry.setPrincipalName(context.getPrincipalName());
658         auditLogEntry.setAssertingPartyId(context.getAssertingPartyEntityId());
659         auditLogEntry.setRelyingPartyId(context.getRelyingPartyEntityId());
660         auditLogEntry.setRequestBinding(getMessageDecoder().getBindingURI());
661         auditLogEntry.setRequestId(null);
662         auditLogEntry.setResponseBinding(getMessageEncoder().getBindingURI());
663         auditLogEntry.setResponseId(context.getOutboundSAMLMessageId());
664         if (context.getReleasedPrincipalAttributeIds() != null) {
665             auditLogEntry.getReleasedAttributes().addAll(context.getReleasedPrincipalAttributeIds());
666         }
667         getAduitLog().log(Level.CRITICAL, auditLogEntry);
668     }
669 }