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.saml2;
    18
    19  import java.text.MessageFormat;
    20
    21  import org.joda.time.DateTime;
    22  import org.opensaml.common.SAMLObject;
    23  import org.opensaml.common.SAMLObjectBuilder;
    24  import org.opensaml.common.binding.BasicEndpointSelector;
    25  import org.opensaml.common.binding.artifact.SAMLArtifactMap;
    26  import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry;
    27  import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
    28  import org.opensaml.common.xml.SAMLConstants;
    29  import org.opensaml.saml2.binding.SAML2ArtifactMessageContext;
    30  import org.opensaml.saml2.core.ArtifactResolve;
    31  import org.opensaml.saml2.core.ArtifactResponse;
    32  import org.opensaml.saml2.core.NameID;
    33  import org.opensaml.saml2.core.Status;
    34  import org.opensaml.saml2.core.StatusCode;
    35  import org.opensaml.saml2.metadata.AssertionConsumerService;
    36  import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
    37  import org.opensaml.saml2.metadata.Endpoint;
    38  import org.opensaml.saml2.metadata.EntityDescriptor;
    39  import org.opensaml.saml2.metadata.SPSSODescriptor;
    40  import org.opensaml.saml2.metadata.provider.MetadataProvider;
    41  import org.opensaml.ws.message.decoder.MessageDecodingException;
    42  import org.opensaml.ws.transport.http.HTTPInTransport;
    43  import org.opensaml.ws.transport.http.HTTPOutTransport;
    44  import org.opensaml.xml.security.SecurityException;
    45  import org.slf4j.Logger;
    46  import org.slf4j.LoggerFactory;
    47
    48  import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
    49  import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
    50  import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.ArtifactResolutionConfiguration;
    51
    52  /**
    53   * SAML 2.0 Artifact resolution profile handler.
    54   */
    55  public class ArtifactResolution extends AbstractSAML2ProfileHandler {
    56
    57      /** Class logger. */
    58      private final Logger log = LoggerFactory.getLogger(ArtifactResolution.class);
    59
    60      /** Map artifacts to SAML messages. */
    61      private SAMLArtifactMap artifactMap;
    62
    63      /** Artifact response object builder. */
    64      private SAMLObjectBuilder<ArtifactResponse> responseBuilder;
    65
    66      /** Builder of assertion consumer service endpoints. */
    67      private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
    68
    69      /**
    70       * Constructor.
    71       *
    72       * @param map ArtifactMap used to lookup artifacts to be resolved.
    73       */
    74      public ArtifactResolution(SAMLArtifactMap map) {
    75          super();
    76
    77          artifactMap = map;
    78
    79          responseBuilder = (SAMLObjectBuilder<ArtifactResponse>) getBuilderFactory().getBuilder(
    80                  ArtifactResponse.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          ArtifactResponse samlResponse;
    93
    94          ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
    95          try {
    96              decodeRequest(requestContext, inTransport, outTransport);
    97
    98              if (requestContext.getProfileConfiguration() == null) {
    99                  String msg = MessageFormat.format(
    100                         "SAML 2 Artifact Resolve profile is not configured for relying party '{}'", requestContext
    101                                 .getInboundMessageIssuer());
    102                 requestContext
    103                         .setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI, msg));
    104                 log.warn(msg);
    105                 throw new ProfileException(msg);
    106             }
    107
    108             checkSamlVersion(requestContext);
    109
    110             SAMLArtifactMapEntry artifactEntry = artifactMap.get(requestContext.getArtifact());
    111             if (artifactEntry == null || artifactEntry.isExpired()) {
    112                 String msg = MessageFormat.format("Unknown artifact '{}' from relying party '{}'", requestContext
    113                         .getArtifact(), requestContext.getInboundMessageIssuer());
    114                 log.error(msg);
    115                 requestContext
    116                         .setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI, msg));
    117             }
    118
    119             if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
    120                 String msg = MessageFormat.format(
    121                         "Artifact issuer mismatch.  Artifact issued by '{}' but IdP has entity ID of '{}'",
    122                         artifactEntry.getIssuerId(), requestContext.getLocalEntityId());
    123                 log.warn(msg);
    124                 requestContext
    125                         .setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI, msg));
    126                 return;
    127             }
    128
    129             if (!artifactEntry.getRelyingPartyId().equals(requestContext.getInboundMessageIssuer())) {
    130                 String msg = MessageFormat
    131                         .format(
    132                                 "Artifact requester mismatch. Artifact was issued to '{}' but the resolve request came from '{}'",
    133                                 artifactEntry.getRelyingPartyId(), requestContext.getInboundMessageIssuer());
    134                 log.warn(msg);
    135                 requestContext
    136                         .setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI, msg));
    137                 return;
    138             }
    139
    140             // create the SAML response
    141             requestContext.setReferencedMessage(artifactEntry.getSamlMessage());
    142             samlResponse = buildArtifactResponse(requestContext);
    143         } catch (ProfileException e) {
    144             samlResponse = buildArtifactErrorResponse(requestContext);
    145         }
    146
    147         requestContext.setOutboundSAMLMessage(samlResponse);
    148         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
    149         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
    150
    151         encodeResponse(requestContext);
    152         writeAuditLogEntry(requestContext);
    153     }
    154
    155     /**
    156      * Decodes an incoming request and populates a created request context with the resultant information.
    157      *
    158      * @param inTransport inbound message transport
    159      * @param outTransport outbound message transport
    160      * @param requestContext request context to which decoded information should be added
    161      *
    162      * @throws ProfileException throw if there is a problem decoding the request
    163      */
    164     protected void decodeRequest(ArtifactResolutionRequestContext requestContext, HTTPInTransport inTransport,
    165             HTTPOutTransport outTransport) throws ProfileException {
    166         if (log.isDebugEnabled()) {
    167             log.debug("Decoding message with decoder binding '{}'",
    168                     getInboundMessageDecoder(requestContext).getBindingURI());
    169         }
    170
    171         requestContext.setCommunicationProfileId(getProfileId());
    172
    173         MetadataProvider metadataProvider = getMetadataProvider();
    174         requestContext.setMetadataProvider(metadataProvider);
    175
    176         requestContext.setInboundMessageTransport(inTransport);
    177         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
    178         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
    179         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    180
    181         requestContext.setOutboundMessageTransport(outTransport);
    182         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
    183
    184         try {
    185             SAMLMessageDecoder decoder = getInboundMessageDecoder(requestContext);
    186             requestContext.setMessageDecoder(decoder);
    187             decoder.decode(requestContext);
    188             log.debug("Decoded request from relying party '{}'", requestContext.getInboundMessageIssuer());
    189         } catch (MessageDecodingException e) {
    190             String msg = "Error decoding artifact resolve message";
    191             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, msg));
    192             log.warn(msg, e);
    193             throw new ProfileException(msg);
    194         } catch (SecurityException e) {
    195             String msg = "Message did not meet security requirements";
    196             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI, msg));
    197             log.warn(msg, e);
    198             throw new ProfileException(msg, e);
    199         } finally {
    200             populateRequestContext(requestContext);
    201         }
    202     }
    203
    204     /** {@inheritDoc} */
    205     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    206             throws ProfileException {
    207         super.populateRelyingPartyInformation(requestContext);
    208
    209         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
    210         if (relyingPartyMetadata != null) {
    211             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    212             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
    213         }
    214     }
    215
    216     /** {@inheritDoc} */
    217     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    218             throws ProfileException {
    219         super.populateAssertingPartyInformation(requestContext);
    220
    221         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
    222         if (localEntityDescriptor != null) {
    223             requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
    224             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
    225                     .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
    226         }
    227     }
    228
    229     /**
    230      * Populates the request context with information from the inbound SAML message.
    231      *
    232      * This method requires the the following request context properties to be populated: inbound saml message
    233      *
    234      * This methods populates the following request context properties: subject name identifier
    235      *
    236      * @param requestContext current request context
    237      *
    238      * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
    239      */
    240     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
    241         ArtifactResolve samlMessage = (ArtifactResolve) requestContext.getInboundSAMLMessage();
    242         if (samlMessage != null && samlMessage.getArtifact() != null) {
    243             ((ArtifactResolutionRequestContext) requestContext).setArtifact(samlMessage.getArtifact().getArtifact());
    244         }
    245     }
    246
    247     /**
    248      * Selects the appropriate endpoint for the relying party and stores it in the request context.
    249      *
    250      * @param requestContext current request context
    251      *
    252      * @return Endpoint selected from the information provided in the request context
    253      */
    254     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
    255         Endpoint endpoint;
    256
    257         if (getInboundBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
    258             endpoint = acsEndpointBuilder.buildObject();
    259             endpoint.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
    260         } else {
    261             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
    262             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    263             endpointSelector.setMetadataProvider(getMetadataProvider());
    264             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
    265             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
    266             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
    267             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
    268             endpoint = endpointSelector.selectEndpoint();
    269         }
    270
    271         return endpoint;
    272     }
    273
    274     /**
    275      * Constructs a artifact resolution response with the derferenced SAML message inside.
    276      *
    277      * @param requestContext current request context
    278      *
    279      * @return constructed response
    280      */
    281     protected ArtifactResponse buildArtifactResponse(ArtifactResolutionRequestContext requestContext) {
    282         DateTime issueInstant = new DateTime();
    283
    284         // create the SAML response and add the assertion
    285         ArtifactResponse samlResponse = responseBuilder.buildObject();
    286         samlResponse.setIssueInstant(issueInstant);
    287         populateStatusResponse(requestContext, samlResponse);
    288
    289         if (requestContext.getFailureStatus() == null) {
    290             Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
    291             samlResponse.setStatus(status);
    292             samlResponse.setMessage(requestContext.getReferencedMessage());
    293         } else {
    294             samlResponse.setStatus(requestContext.getFailureStatus());
    295         }
    296
    297         return samlResponse;
    298     }
    299
    300     /**
    301      * Constructs an artifact resolution response with an error status as content.
    302      *
    303      * @param requestContext current request context
    304      *
    305      * @return constructed response
    306      */
    307     protected ArtifactResponse buildArtifactErrorResponse(ArtifactResolutionRequestContext requestContext) {
    308         ArtifactResponse samlResponse = responseBuilder.buildObject();
    309         samlResponse.setIssueInstant(new DateTime());
    310         populateStatusResponse(requestContext, samlResponse);
    311
    312         samlResponse.setStatus(requestContext.getFailureStatus());
    313
    314         return samlResponse;
    315     }
    316
    317     /** Represents the internal state of a SAML 2.0 Artifact resolver request while it's being processed by the IdP. */
    318     public class ArtifactResolutionRequestContext extends
    319             BaseSAML2ProfileRequestContext<ArtifactResolve, ArtifactResponse, ArtifactResolutionConfiguration>
    320             implements SAML2ArtifactMessageContext<ArtifactResolve, ArtifactResponse, NameID> {
    321
    322         /** Artifact to be resolved. */
    323         private String artifact;
    324
    325         /** Message referenced by the SAML artifact. */
    326         private SAMLObject referencedMessage;
    327
    328         /** {@inheritDoc} */
    329         public String getArtifact() {
    330             return artifact;
    331         }
    332
    333         /** {@inheritDoc} */
    334         public void setArtifact(String saml2Artifact) {
    335             this.artifact = saml2Artifact;
    336         }
    337
    338         /** {@inheritDoc} */
    339         public SAMLObject getReferencedMessage() {
    340             return referencedMessage;
    341         }
    342
    343         /** {@inheritDoc} */
    344         public void setReferencedMessage(SAMLObject message) {
    345             referencedMessage = message;
    346         }
    347     }
    348 }