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