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