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