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