View Javadoc

    1   /*
    2    * Copyright 2006 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
    23  import org.joda.time.DateTime;
    24  import org.opensaml.common.SAMLObjectBuilder;
    25  import org.opensaml.common.binding.BasicEndpointSelector;
    26  import org.opensaml.common.binding.artifact.SAMLArtifactMap;
    27  import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry;
    28  import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
    29  import org.opensaml.common.xml.SAMLConstants;
    30  import org.opensaml.saml1.binding.SAML1ArtifactMessageContext;
    31  import org.opensaml.saml1.core.Assertion;
    32  import org.opensaml.saml1.core.AssertionArtifact;
    33  import org.opensaml.saml1.core.NameIdentifier;
    34  import org.opensaml.saml1.core.Request;
    35  import org.opensaml.saml1.core.Response;
    36  import org.opensaml.saml1.core.Status;
    37  import org.opensaml.saml1.core.StatusCode;
    38  import org.opensaml.saml2.metadata.AssertionConsumerService;
    39  import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
    40  import org.opensaml.saml2.metadata.Endpoint;
    41  import org.opensaml.saml2.metadata.EntityDescriptor;
    42  import org.opensaml.saml2.metadata.SPSSODescriptor;
    43  import org.opensaml.saml2.metadata.provider.MetadataProvider;
    44  import org.opensaml.ws.message.decoder.MessageDecodingException;
    45  import org.opensaml.ws.transport.http.HTTPInTransport;
    46  import org.opensaml.ws.transport.http.HTTPOutTransport;
    47  import org.opensaml.xml.security.SecurityException;
    48  import org.slf4j.Logger;
    49  import org.slf4j.LoggerFactory;
    50
    51  import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
    52  import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
    53  import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ArtifactResolutionConfiguration;
    54
    55  /**
    56   * SAML 1 Artifact resolution profile handler.
    57   */
    58  public class ArtifactResolution extends AbstractSAML1ProfileHandler {
    59
    60      /** Class logger. */
    61      private final Logger log = LoggerFactory.getLogger(ArtifactResolution.class);
    62
    63      /** Builder of Response objects. */
    64      private SAMLObjectBuilder<Response> responseBuilder;
    65
    66      /** Builder of assertion consumer service endpoints. */
    67      private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
    68
    69      /** Map artifacts to SAML messages. */
    70      private SAMLArtifactMap artifactMap;
    71
    72      /**
    73       * Constructor.
    74       *
    75       * @param map ArtifactMap used to lookup artifacts to be resolved.
    76       */
    77      public ArtifactResolution(SAMLArtifactMap map) {
    78          super();
    79
    80          artifactMap = map;
    81
    82          responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
    83          acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
    84                  AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    85      }
    86
    87      /** {@inheritDoc} */
    88      public String getProfileId() {
    89          return ArtifactResolutionConfiguration.PROFILE_ID;
    90      }
    91
    92      /** {@inheritDoc} */
    93      public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
    94          Response samlResponse;
    95
    96          ArtifactResolutionRequestContext requestContext = decodeRequest(inTransport, outTransport);
    97
    98          try {
    99              if (requestContext.getProfileConfiguration() == null) {
    100                 log.error("SAML 1 Artifact resolution profile is not configured for relying party "
    101                         + requestContext.getInboundMessageIssuer());
    102                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS, StatusCode.REQUEST_DENIED,
    103                         "SAML 1 Artifact resolution profile is not configured for relying party "
    104                                 + requestContext.getInboundMessageIssuer()));
    105                 throw new ProfileException("SAML 1 Artifact resolution profile is not configured for relying party "
    106                         + requestContext.getInboundMessageIssuer());
    107             }
    108
    109             checkSamlVersion(requestContext);
    110
    111             derferenceArtifacts(requestContext);
    112
    113             // create the SAML response
    114             samlResponse = buildArtifactResponse(requestContext);
    115         } catch (ProfileException e) {
    116             samlResponse = buildErrorResponse(requestContext);
    117         }
    118
    119         requestContext.setOutboundSAMLMessage(samlResponse);
    120         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
    121         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
    122
    123         encodeResponse(requestContext);
    124         writeAuditLogEntry(requestContext);
    125     }
    126
    127     /**
    128      * Decodes an incoming request and populates a created request context with the resultant information.
    129      *
    130      * @param inTransport inbound message transport
    131      * @param outTransport outbound message transport
    132      *
    133      * @return the created request context
    134      *
    135      * @throws ProfileException throw if there is a problem decoding the request
    136      */
    137     protected ArtifactResolutionRequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
    138             throws ProfileException {
    139         log.debug("Decoding message with decoder binding {}", getInboundBinding());
    140
    141         ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
    142         requestContext.setCommunicationProfileId(getProfileId());
    143
    144         MetadataProvider metadataProvider = getMetadataProvider();
    145         requestContext.setMetadataProvider(metadataProvider);
    146
    147         requestContext.setInboundMessageTransport(inTransport);
    148         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
    149         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
    150         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    151
    152         requestContext.setOutboundMessageTransport(outTransport);
    153         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
    154
    155         try {
    156             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
    157             requestContext.setMessageDecoder(decoder);
    158             decoder.decode(requestContext);
    159             log.debug("Decoded request");
    160             return requestContext;
    161         } catch (MessageDecodingException e) {
    162             log.error("Error decoding artifact resolve message", e);
    163             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
    164             throw new ProfileException("Error decoding artifact resolve message",e);
    165         } catch (SecurityException e) {
    166             log.error("Message did not meet security requirements", e);
    167             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
    168                     "Message did not meet security requirements"));
    169             throw new ProfileException("Message did not meet security requirements", e);
    170         } finally {
    171             // Set as much information as can be retrieved from the decoded message
    172             populateRequestContext(requestContext);
    173         }
    174     }
    175
    176     /** {@inheritDoc} */
    177     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    178             throws ProfileException {
    179         super.populateRelyingPartyInformation(requestContext);
    180
    181         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
    182         if (relyingPartyMetadata != null) {
    183             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    184             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
    185         }
    186     }
    187
    188     /** {@inheritDoc} */
    189     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    190             throws ProfileException {
    191         super.populateAssertingPartyInformation(requestContext);
    192
    193         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
    194         if (localEntityDescriptor != null) {
    195             requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
    196             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
    197                     .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
    198         }
    199     }
    200
    201     /** {@inheritDoc} */
    202     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
    203         // nothing to do here
    204     }
    205
    206     /**
    207      * Selects the appropriate endpoint for the relying party and stores it in the request context.
    208      *
    209      * @param requestContext current request context
    210      *
    211      * @return Endpoint selected from the information provided in the request context
    212      */
    213     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
    214         Endpoint endpoint;
    215
    216         if (getInboundBinding().equals(SAMLConstants.SAML1_SOAP11_BINDING_URI)) {
    217             endpoint = acsEndpointBuilder.buildObject();
    218             endpoint.setBinding(SAMLConstants.SAML1_SOAP11_BINDING_URI);
    219         } else {
    220             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
    221             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    222             endpointSelector.setMetadataProvider(getMetadataProvider());
    223             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
    224             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
    225             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
    226             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
    227             endpoint = endpointSelector.selectEndpoint();
    228         }
    229
    230         return endpoint;
    231     }
    232
    233     /**
    234      * Derferences the artifacts within the incoming request and stores them in the request context.
    235      *
    236      * @param requestContext current request context
    237      *
    238      * @throws ProfileException thrown if the incoming request does not contain any {@link AssertionArtifact}s.
    239      */
    240     protected void derferenceArtifacts(ArtifactResolutionRequestContext requestContext) throws ProfileException {
    241         Request request = requestContext.getInboundSAMLMessage();
    242         List<AssertionArtifact> assertionArtifacts = request.getAssertionArtifacts();
    243
    244         if (assertionArtifacts == null || assertionArtifacts.size() == 0) {
    245             log.error("No AssertionArtifacts available in request");
    246             throw new ProfileException("No AssertionArtifacts available in request");
    247         }
    248
    249         ArrayList<Assertion> assertions = new ArrayList<Assertion>();
    250         SAMLArtifactMapEntry artifactEntry;
    251         for (AssertionArtifact assertionArtifact : assertionArtifacts) {
    252             artifactEntry = artifactMap.get(assertionArtifact.getAssertionArtifact());
    253             if (artifactEntry == null || artifactEntry.isExpired()) {
    254                 log.error("Unknown artifact.");
    255             }
    256
    257             if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
    258                 log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
    259                         + " but IdP has entity ID of " + requestContext.getLocalEntityId());
    260             }
    261
    262             artifactMap.remove(assertionArtifact.getAssertionArtifact());
    263             assertions.add((Assertion) artifactEntry.getSamlMessage());
    264         }
    265
    266         requestContext.setDereferencedAssertions(assertions);
    267     }
    268
    269     /**
    270      * Builds the response to the artifact request.
    271      *
    272      * @param requestContext current request context
    273      *
    274      * @return response to the artifact request
    275      */
    276     protected Response buildArtifactResponse(ArtifactResolutionRequestContext requestContext) {
    277         DateTime issueInstant = new DateTime();
    278
    279         // create the SAML response and add the assertion
    280         Response samlResponse = responseBuilder.buildObject();
    281         samlResponse.setIssueInstant(issueInstant);
    282         populateStatusResponse(requestContext, samlResponse);
    283
    284         if (requestContext.getDereferencedAssertions() != null) {
    285             samlResponse.getAssertions().addAll(requestContext.getDereferencedAssertions());
    286         }
    287
    288         Status status = buildStatus(StatusCode.SUCCESS, null, null);
    289         samlResponse.setStatus(status);
    290
    291         return samlResponse;
    292     }
    293
    294     /** Represents the internal state of a SAML 1 Artifact resolver request while it's being processed by the IdP. */
    295     public class ArtifactResolutionRequestContext extends
    296             BaseSAML1ProfileRequestContext<Request, Response, ArtifactResolutionConfiguration> implements
    297             SAML1ArtifactMessageContext<Request, Response, NameIdentifier> {
    298
    299         /** Artifact to be resolved. */
    300         private Collection<String> artifacts;
    301
    302         /** Message referenced by the SAML artifact. */
    303         private Collection<Assertion> referencedAssertions;
    304
    305         /** {@inheritDoc} */
    306         public Collection<String> getArtifacts() {
    307             return artifacts;
    308         }
    309
    310         /** {@inheritDoc} */
    311         public void setArtifacts(Collection<String> encodedArtifacts) {
    312             this.artifacts = encodedArtifacts;
    313         }
    314
    315         /**
    316          * Gets the SAML assertions referenced by the artifact(s).
    317          *
    318          * @return SAML assertions referenced by the artifact(s)
    319          */
    320         public Collection<Assertion> getDereferencedAssertions() {
    321             return referencedAssertions;
    322         }
    323
    324         /**
    325          * Sets the SAML assertions referenced by the artifact(s).
    326          *
    327          * @param assertions SAML assertions referenced by the artifact(s)
    328          */
    329         public void setDereferencedAssertions(Collection<Assertion> assertions) {
    330             referencedAssertions = assertions;
    331         }
    332     }
    333 }