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.util.ArrayList;
    20
    21  import org.opensaml.common.SAMLObjectBuilder;
    22  import org.opensaml.common.binding.BasicEndpointSelector;
    23  import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
    24  import org.opensaml.common.xml.SAMLConstants;
    25  import org.opensaml.saml2.core.AttributeQuery;
    26  import org.opensaml.saml2.core.AttributeStatement;
    27  import org.opensaml.saml2.core.Response;
    28  import org.opensaml.saml2.core.Statement;
    29  import org.opensaml.saml2.core.StatusCode;
    30  import org.opensaml.saml2.core.Subject;
    31  import org.opensaml.saml2.metadata.AssertionConsumerService;
    32  import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
    33  import org.opensaml.saml2.metadata.Endpoint;
    34  import org.opensaml.saml2.metadata.EntityDescriptor;
    35  import org.opensaml.saml2.metadata.SPSSODescriptor;
    36  import org.opensaml.saml2.metadata.provider.MetadataProvider;
    37  import org.opensaml.ws.message.decoder.MessageDecodingException;
    38  import org.opensaml.ws.transport.http.HTTPInTransport;
    39  import org.opensaml.ws.transport.http.HTTPOutTransport;
    40  import org.opensaml.xml.security.SecurityException;
    41  import org.slf4j.Logger;
    42  import org.slf4j.LoggerFactory;
    43  import org.slf4j.helpers.MessageFormatter;
    44
    45  import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
    46  import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
    47  import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
    48  import edu.internet2.middleware.shibboleth.idp.session.AuthenticationMethodInformation;
    49  import edu.internet2.middleware.shibboleth.idp.session.Session;
    50
    51  /** SAML 2.0 Attribute Query profile handler. */
    52  public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
    53
    54      /** Class logger. */
    55      private static Logger log = LoggerFactory.getLogger(AttributeQueryProfileHandler.class);
    56
    57      /** Builder of assertion consumer service endpoints. */
    58      private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
    59
    60      /** Constructor. */
    61      public AttributeQueryProfileHandler() {
    62          super();
    63
    64          acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
    65                  AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    66      }
    67
    68      /** {@inheritDoc} */
    69      public String getProfileId() {
    70          return AttributeQueryConfiguration.PROFILE_ID;
    71      }
    72
    73      /** {@inheritDoc} */
    74      public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
    75          Response samlResponse;
    76
    77          AttributeQueryContext requestContext = new AttributeQueryContext();
    78
    79          try {
    80              decodeRequest(requestContext, inTransport, outTransport);
    81
    82              if (requestContext.getProfileConfiguration() == null) {
    83                  String msg = MessageFormatter.format(
    84                          "SAML 2 Attribute Query profile is not configured for relying party '{}'", requestContext
    85                                  .getInboundMessage());
    86                  requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
    87                          msg));
    88                  log.warn(msg);
    89                  samlResponse = buildErrorResponse(requestContext);
    90              } else {
    91                  checkSamlVersion(requestContext);
    92
    93                  // Resolve attribute query name id to principal name and place in context
    94                  resolvePrincipal(requestContext);
    95
    96                  Session idpSession = getSessionManager().getSession(requestContext.getPrincipalName());
    97                  if (idpSession != null) {
    98                      AuthenticationMethodInformation authnInfo = idpSession.getAuthenticationMethods().get(
    99                              requestContext.getInboundMessageIssuer());
    100                     if (authnInfo != null) {
    101                         requestContext.setPrincipalAuthenticationMethod(authnInfo.getAuthenticationMethod());
    102                     }
    103                 }
    104
    105                 resolveAttributes(requestContext);
    106                 requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
    107
    108                 // Lookup principal name and attributes, create attribute statement from information
    109                 ArrayList<Statement> statements = new ArrayList<Statement>();
    110                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
    111                 if (attributeStatement != null) {
    112                     statements.add(attributeStatement);
    113                 }
    114
    115                 // create the SAML response
    116                 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches",
    117                         statements);
    118             }
    119         } catch (ProfileException e) {
    120             samlResponse = buildErrorResponse(requestContext);
    121         }
    122
    123         requestContext.setOutboundSAMLMessage(samlResponse);
    124         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
    125         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
    126
    127         encodeResponse(requestContext);
    128         writeAuditLogEntry(requestContext);
    129     }
    130
    131     /**
    132      * Decodes an incoming request and populates a created request context with the resultant information.
    133      *
    134      * @param inTransport inbound message transport
    135      * @param outTransport outbound message transport *
    136      * @param requestContext request context to which decoded information should be added
    137      *
    138      * @throws ProfileException throw if there is a problem decoding the request
    139      */
    140     protected void decodeRequest(AttributeQueryContext requestContext, HTTPInTransport inTransport,
    141             HTTPOutTransport outTransport) throws ProfileException {
    142         if (log.isDebugEnabled()) {
    143             log.debug("Decoding message with decoder binding '{}'",
    144                     getInboundMessageDecoder(requestContext).getBindingURI());
    145         }
    146
    147         requestContext.setCommunicationProfileId(getProfileId());
    148
    149         MetadataProvider metadataProvider = getMetadataProvider();
    150         requestContext.setMetadataProvider(metadataProvider);
    151
    152         requestContext.setInboundMessageTransport(inTransport);
    153         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
    154         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
    155         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    156
    157         requestContext.setOutboundMessageTransport(outTransport);
    158         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
    159
    160         try {
    161             SAMLMessageDecoder decoder = getInboundMessageDecoder(requestContext);
    162             requestContext.setMessageDecoder(decoder);
    163             decoder.decode(requestContext);
    164             log.debug("Decoded request from relying party '{}'", requestContext.getInboundMessage());
    165
    166             if (!(requestContext.getInboundSAMLMessage() instanceof AttributeQuery)) {
    167                 log.warn("Incoming message was not a AttributeQuery, it was a {}", requestContext
    168                         .getInboundSAMLMessage().getClass().getName());
    169                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
    170                         "Invalid SAML AttributeQuery message."));
    171                 throw new ProfileException("Invalid SAML AttributeQuery message.");
    172             }
    173         } catch (MessageDecodingException e) {
    174             String msg = "Error decoding attribute query message";
    175             log.warn(msg, e);
    176             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, msg));
    177             throw new ProfileException(msg);
    178         } catch (SecurityException e) {
    179             String msg = "Message did not meet security requirements";
    180             log.warn(msg, e);
    181             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI, msg));
    182             throw new ProfileException(msg, e);
    183         } finally {
    184             // Set as much information as can be retrieved from the decoded message
    185             populateRequestContext(requestContext);
    186         }
    187     }
    188
    189     /** {@inheritDoc} */
    190     protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    191             throws ProfileException {
    192         super.populateRelyingPartyInformation(requestContext);
    193
    194         EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
    195         if (relyingPartyMetadata != null) {
    196             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    197             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
    198         }
    199     }
    200
    201     /** {@inheritDoc} */
    202     protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
    203             throws ProfileException {
    204         super.populateAssertingPartyInformation(requestContext);
    205
    206         EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
    207         if (localEntityDescriptor != null) {
    208             requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
    209             requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
    210                     .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
    211         }
    212     }
    213
    214     /**
    215      * Populates the request context with information from the inbound SAML message.
    216      *
    217      * This method requires the the following request context properties to be populated: inbound saml message
    218      *
    219      * This methods populates the following request context properties: subject name identifier
    220      *
    221      * @param requestContext current request context
    222      *
    223      * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
    224      */
    225     protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
    226         AttributeQuery query = (AttributeQuery) requestContext.getInboundSAMLMessage();
    227         if (query != null) {
    228             Subject subject = query.getSubject();
    229             if (subject == null) {
    230                 String msg = "Attribute query did not contain a proper subject";
    231                 log.warn(msg);
    232                 ((AttributeQueryContext) requestContext).setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
    233                         msg));
    234                 throw new ProfileException(msg);
    235             }
    236             requestContext.setSubjectNameIdentifier(subject.getNameID());
    237         }
    238     }
    239
    240     /**
    241      * Selects the appropriate endpoint for the relying party and stores it in the request context.
    242      *
    243      * @param requestContext current request context
    244      *
    245      * @return Endpoint selected from the information provided in the request context
    246      */
    247     protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
    248         Endpoint endpoint;
    249
    250         if (getInboundBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
    251             endpoint = acsEndpointBuilder.buildObject();
    252             endpoint.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
    253         } else {
    254             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
    255             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
    256             endpointSelector.setMetadataProvider(getMetadataProvider());
    257             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
    258             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
    259             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
    260             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
    261             endpoint = endpointSelector.selectEndpoint();
    262         }
    263
    264         return endpoint;
    265     }
    266
    267     /** Basic data structure used to accumulate information as a request is being processed. */
    268     protected class AttributeQueryContext extends
    269             BaseSAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
    270
    271     }
    272 }