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