View Javadoc

    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.io.IOException;
    20  import java.util.ArrayList;
    21
    22  import javax.servlet.RequestDispatcher;
    23  import javax.servlet.ServletException;
    24  import javax.servlet.http.HttpServletRequest;
    25  import javax.servlet.http.HttpServletResponse;
    26
    27  import org.opensaml.common.SAMLObjectBuilder;
    28  import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
    29  import org.opensaml.common.xml.SAMLConstants;
    30  import org.opensaml.saml1.core.AttributeStatement;
    31  import org.opensaml.saml1.core.AuthenticationStatement;
    32  import org.opensaml.saml1.core.Request;
    33  import org.opensaml.saml1.core.Response;
    34  import org.opensaml.saml1.core.Statement;
    35  import org.opensaml.saml1.core.StatusCode;
    36  import org.opensaml.saml1.core.Subject;
    37  import org.opensaml.saml1.core.SubjectLocality;
    38  import org.opensaml.saml2.metadata.AssertionConsumerService;
    39  import org.opensaml.saml2.metadata.Endpoint;
    40  import org.opensaml.saml2.metadata.EntityDescriptor;
    41  import org.opensaml.saml2.metadata.IDPSSODescriptor;
    42  import org.opensaml.saml2.metadata.SPSSODescriptor;
    43  import org.opensaml.ws.message.decoder.MessageDecodingException;
    44  import org.opensaml.ws.transport.http.HTTPInTransport;
    45  import org.opensaml.ws.transport.http.HTTPOutTransport;
    46  import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
    47  import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
    48  import org.opensaml.xml.security.SecurityException;
    49  import org.opensaml.xml.util.DatatypeHelper;
    50  import org.slf4j.Logger;
    51  import org.slf4j.LoggerFactory;
    52  import org.slf4j.helpers.MessageFormatter;
    53
    54  import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
    55  import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
    56  import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
    57  import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
    58  import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
    59  import edu.internet2.middleware.shibboleth.common.relyingparty.provider.SAMLMDRelyingPartyConfigurationManager;
    60  import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
    61  import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
    62  import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
    63  import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
    64  import edu.internet2.middleware.shibboleth.idp.util.HttpServletHelper;
    65
    66  /** Shibboleth SSO request profile handler. */
    67  public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
    68
    69      /** Class logger. */
    70      private final Logger log = LoggerFactory.getLogger(ShibbolethSSOProfileHandler.class);
    71
    72      /** Builder of AuthenticationStatement objects. */
    73      private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
    74
    75      /** Builder of SubjectLocality objects. */
    76      private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
    77
    78      /** Builder of Endpoint objects. */
    79      private SAMLObjectBuilder<Endpoint> endpointBuilder;
    80
    81      /** URL of the authentication manager servlet. */
    82      private String authenticationManagerPath;
    83
    84      /**
    85       * Constructor.
    86       *
    87       * @param authnManagerPath path to the authentication manager servlet
    88       *
    89       * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
    90       *             null or empty
    91       */
    92      public ShibbolethSSOProfileHandler(String authnManagerPath) {
    93          if (DatatypeHelper.isEmpty(authnManagerPath)) {
    94              throw new IllegalArgumentException("Authentication manager path may not be null");
    95          }
    96          authenticationManagerPath = authnManagerPath;
    97
    98          authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
    99                  AuthenticationStatement.DEFAULT_ELEMENT_NAME);
    100
    101         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
    102                 SubjectLocality.DEFAULT_ELEMENT_NAME);
    103
    104         endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
    105                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    106     }
    107
    108     /** {@inheritDoc} */
    109     public String getProfileId() {
    110         return ShibbolethSSOConfiguration.PROFILE_ID;
    111     }
    112
    113     /** {@inheritDoc} */
    114     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
    115         log.debug("Processing incoming request");
    116
    117         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
    118         LoginContext loginContext = HttpServletHelper.getLoginContext(httpRequest);
    119
    120         if (loginContext == null) {
    121             log.debug("Incoming request does not contain a login context, processing as first leg of request");
    122             performAuthentication(inTransport, outTransport);
    123         } else {
    124             log.debug("Incoming request contains a login context, processing as second leg of request");
    125             completeAuthenticationRequest(inTransport, outTransport);
    126         }
    127     }
    128
    129     /**
    130      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
    131      * authenticating the user.
    132      *
    133      * @param inTransport inbound message transport
    134      * @param outTransport outbound message transport
    135      *
    136      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
    137      *             authentication manager
    138      */
    139     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
    140             throws ProfileException {
    141
    142         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
    143         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
    144         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
    145
    146         decodeRequest(requestContext, inTransport, outTransport);
    147         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
    148
    149         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
    150         loginContext.setDefaultAuthenticationMethod(rpConfig.getDefaultAuthenticationMethod());
    151         ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
    152         if (ssoConfig == null) {
    153             String msg = MessageFormatter.format("Shibboleth SSO profile is not configured for relying party '{}'",
    154                     loginContext.getRelyingPartyId());
    155             log.warn(msg);
    156             throw new ProfileException(msg);
    157         }
    158
    159         HttpServletHelper.bindLoginContext(loginContext, httpRequest);
    160
    161         try {
    162             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
    163             dispatcher.forward(httpRequest, httpResponse);
    164             return;
    165         } catch (IOException e) {
    166             String msg = "Error forwarding Shibboleth SSO request to AuthenticationManager";
    167             log.error(msg, e);
    168             throw new ProfileException(msg, e);
    169         } catch (ServletException e) {
    170             String msg = "Error forwarding Shibboleth SSO request to AuthenticationManager";
    171             log.error(msg, e);
    172             throw new ProfileException(msg, e);
    173         }
    174     }
    175
    176     /**
    177      * Decodes an incoming request and populates a created request context with the resultant information.
    178      *
    179      * @param inTransport inbound message transport
    180      * @param outTransport outbound message transport
    181      * @param requestContext the request context to which decoded information should be added
    182      *
    183      * @throws ProfileException throw if there is a problem decoding the request
    184      */
    185     protected void decodeRequest(ShibbolethSSORequestContext requestContext, HTTPInTransport inTransport,
    186             HTTPOutTransport outTransport) throws ProfileException {
    187         if (log.isDebugEnabled()) {
    188             log.debug("Decoding message with decoder binding {}",
    189                     getInboundMessageDecoder(requestContext).getBindingURI());
    190         }
    191
    192         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
    193
    194         requestContext.setCommunicationProfileId(getProfileId());
    195
    196         requestContext.setMetadataProvider(getMetadataProvider());
    197         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
    198
    199         requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
    200         requestContext.setInboundMessageTransport(inTransport);
    201         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
    202         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    203
    204         requestContext.setOutboundMessageTransport(outTransport);
    205         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
    206
    207         SAMLMessageDecoder decoder = getInboundMessageDecoder(requestContext);
    208         requestContext.setMessageDecoder(decoder);
    209         try {
    210             decoder.decode(requestContext);
    211             log.debug("Decoded Shibboleth SSO request from relying party '{}'", requestContext
    212                     .getInboundMessageIssuer());
    213         } catch (MessageDecodingException e) {
    214             String msg = "Error decoding Shibboleth SSO request";
    215             log.warn(msg, e);
    216             throw new ProfileException(msg, e);
    217         } catch (SecurityException e) {
    218             String msg = "Shibboleth SSO request does not meet security requirements";
    219             log.warn(msg, e);
    220             throw new ProfileException("msg", e);
    221         }
    222
    223         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
    224         loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
    225         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
    226         loginContext.setSpTarget(requestContext.getRelayState());
    227         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
    228         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
    229         requestContext.setLoginContext(loginContext);
    230     }
    231
    232     /**
    233      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
    234      * after they've been authenticated.
    235      *
    236      * @param inTransport inbound message transport
    237      * @param outTransport outbound message transport
    238      *
    239      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
    240      */
    241     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
    242             throws ProfileException {
    243         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
    244         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) HttpServletHelper.getLoginContext(httpRequest);
    245
    246         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
    247
    248         Response samlResponse;
    249         try {
    250             if (loginContext.getAuthenticationFailure() != null) {
    251                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
    252                 throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
    253             }
    254
    255             resolveAttributes(requestContext);
    256
    257             ArrayList<Statement> statements = new ArrayList<Statement>();
    258             statements.add(buildAuthenticationStatement(requestContext));
    259             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
    260                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
    261                         "urn:oasis:names:tc:SAML:1.0:cm:bearer");
    262                 if (attributeStatement != null) {
    263                     requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
    264                     statements.add(attributeStatement);
    265                 }
    266             }
    267
    268             samlResponse = buildResponse(requestContext, statements);
    269         } catch (ProfileException e) {
    270             samlResponse = buildErrorResponse(requestContext);
    271         }
    272
    273         requestContext.setOutboundSAMLMessage(samlResponse);
    274         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
    275         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
    276         encodeResponse(requestContext);
    277         writeAuditLogEntry(requestContext);
    278     }
    279
    280     /**
    281      * Creates an authentication request context from the current environmental information.
    282      *
    283      * @param loginContext current login context
    284      * @param in inbound transport
    285      * @param out outbount transport
    286      *
    287      * @return created authentication request context
    288      *
    289      * @throws ProfileException thrown if there is a problem creating the context
    290      */
    291     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
    292             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
    293         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
    294         requestContext.setCommunicationProfileId(getProfileId());
    295
    296         requestContext.setMessageDecoder(getInboundMessageDecoder(requestContext));
    297
    298         requestContext.setLoginContext(loginContext);
    299         requestContext.setRelayState(loginContext.getSpTarget());
    300
    301         requestContext.setInboundMessageTransport(in);
    302         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
    303
    304         requestContext.setOutboundMessageTransport(out);
    305         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
    306
    307         requestContext.setMetadataProvider(getMetadataProvider());
    308
    309         String relyingPartyId = loginContext.getRelyingPartyId();
    310         requestContext.setPeerEntityId(relyingPartyId);
    311         requestContext.setInboundMessageIssuer(relyingPartyId);
    312
    313         populateRequestContext(requestContext);
    314
    315         return requestContext;
    316     }
    317
    318     /** {@inheritDoc} */
    319     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    320             throws ProfileException {
    321         super.populateRelyingPartyInformation(requestContext);
    322
    323         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
    324         if (relyingPartyMetadata != null) {
    325             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    326             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
    327         }
    328     }
    329
    330     /** {@inheritDoc} */
    331     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    332             throws ProfileException {
    333         super.populateAssertingPartyInformation(requestContext);
    334
    335         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
    336         if (localEntityDescriptor != null) {
    337             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
    338             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
    339                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
    340         }
    341     }
    342
    343     /** {@inheritDoc} */
    344     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
    345         // nothing to do here
    346     }
    347
    348     /**
    349      * Selects the appropriate endpoint for the relying party and stores it in the request context.
    350      *
    351      * @param requestContext current request context
    352      *
    353      * @return Endpoint selected from the information provided in the request context
    354      */
    355     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
    356         ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
    357
    358         Endpoint endpoint = null;
    359         if (requestContext.getRelyingPartyConfiguration().getRelyingPartyId() == SAMLMDRelyingPartyConfigurationManager.ANONYMOUS_RP_NAME) {
    360             if (loginContext.getSpAssertionConsumerService() != null) {
    361                 endpoint = endpointBuilder.buildObject();
    362                 endpoint.setLocation(loginContext.getSpAssertionConsumerService());
    363                 endpoint.setBinding(getSupportedOutboundBindings().get(0));
    364                 log.warn("Generating endpoint for anonymous relying party. ACS url {} and binding {}", new Object[] {
    365                         requestContext.getInboundMessageIssuer(), endpoint.getLocation(), endpoint.getBinding(), });
    366             } else {
    367                 log.warn("Unable to generate endpoint for anonymous party.  No ACS url provided.");
    368             }
    369         } else {
    370             ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
    371             endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
    372             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    373             endpointSelector.setMetadataProvider(getMetadataProvider());
    374             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
    375             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
    376             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
    377             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
    378             endpoint = endpointSelector.selectEndpoint();
    379         }
    380
    381         return endpoint;
    382     }
    383
    384     /**
    385      * Builds the authentication statement for the authenticated principal.
    386      *
    387      * @param requestContext current request context
    388      *
    389      * @return the created statement
    390      *
    391      * @throws ProfileException thrown if the authentication statement can not be created
    392      */
    393     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
    394             throws ProfileException {
    395         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
    396
    397         AuthenticationStatement statement = authnStatementBuilder.buildObject();
    398         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
    399         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
    400
    401         statement.setSubjectLocality(buildSubjectLocality(requestContext));
    402
    403         Subject statementSubject;
    404         Endpoint endpoint = selectEndpoint(requestContext);
    405         if (endpoint.getBinding().equals(SAMLConstants.SAML1_ARTIFACT_BINDING_URI)) {
    406             statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:artifact");
    407         } else {
    408             statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
    409         }
    410         statement.setSubject(statementSubject);
    411
    412         return statement;
    413     }
    414
    415     /**
    416      * Constructs the subject locality for the authentication statement.
    417      *
    418      * @param requestContext current request context
    419      *
    420      * @return subject locality for the authentication statement
    421      */
    422     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
    423         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
    424
    425         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
    426         subjectLocality.setIPAddress(inTransport.getPeerAddress());
    427
    428         return subjectLocality;
    429     }
    430
    431     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
    432     public class ShibbolethSSORequestContext extends
    433             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
    434
    435         /** SP-provide assertion consumer service URL. */
    436         private String spAssertionConsumerService;
    437
    438         /** Current login context. */
    439         private ShibbolethSSOLoginContext loginContext;
    440
    441         /**
    442          * Gets the current login context.
    443          *
    444          * @return current login context
    445          */
    446         public ShibbolethSSOLoginContext getLoginContext() {
    447             return loginContext;
    448         }
    449
    450         /**
    451          * Sets the current login context.
    452          *
    453          * @param context current login context
    454          */
    455         public void setLoginContext(ShibbolethSSOLoginContext context) {
    456             loginContext = context;
    457         }
    458
    459         /**
    460          * Gets the SP-provided assertion consumer service URL.
    461          *
    462          * @return SP-provided assertion consumer service URL
    463          */
    464         public String getSpAssertionConsumerService() {
    465             return spAssertionConsumerService;
    466         }
    467
    468         /**
    469          * Sets the SP-provided assertion consumer service URL.
    470          *
    471          * @param acs SP-provided assertion consumer service URL
    472          */
    473         public void setSpAssertionConsumerService(String acs) {
    474             spAssertionConsumerService = acs;
    475         }
    476     }
    477 }