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