View Javadoc

1   /*
2    * Copyright 2008 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 org.opensaml.common.binding.decoding;
18  
19  import java.net.MalformedURLException;
20  import java.net.URL;
21  
22  import javax.servlet.http.HttpServletRequest;
23  
24  import org.opensaml.common.SAMLObject;
25  import org.opensaml.common.SignableSAMLObject;
26  import org.opensaml.common.binding.SAMLMessageContext;
27  import org.opensaml.ws.message.decoder.BaseMessageDecoder;
28  import org.opensaml.ws.message.decoder.MessageDecodingException;
29  import org.opensaml.ws.transport.InTransport;
30  import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
31  import org.opensaml.xml.parse.ParserPool;
32  import org.opensaml.xml.security.SecurityException;
33  import org.opensaml.xml.util.DatatypeHelper;
34  import org.slf4j.Logger;
35  import org.slf4j.LoggerFactory;
36  
37  /**
38   * Base class for all SAML message decoders.
39   */
40  public abstract class BaseSAMLMessageDecoder extends BaseMessageDecoder implements SAMLMessageDecoder {
41      
42      /** Class logger. */
43      private final Logger log = LoggerFactory.getLogger(BaseSAMLMessageDecoder.class);
44  
45      /** Constructor. */
46      public BaseSAMLMessageDecoder() {
47          super();
48      }
49  
50      /**
51       * Constructor.
52       *
53       * @param pool parser pool used to deserialize messages
54       */
55      public BaseSAMLMessageDecoder(ParserPool pool) {
56          super(pool);
57      }
58  
59      /**
60       * Determine whether the SAML message represented by the message context is digitally signed.
61       * 
62       * <p>The default behavior is to examine whether an XML signature is present on the 
63       * SAML protocol message.  Subclasses may augment or replace with binding-specific behavior.</p>
64       * 
65       * @param messageContext current message context
66       * @return true if the message is considered to be digitially signed, false otherwise
67       */
68      protected boolean isMessageSigned(SAMLMessageContext messageContext) {
69          SAMLObject samlMessage = messageContext.getInboundSAMLMessage();
70          if (samlMessage instanceof SignableSAMLObject) {
71              return ((SignableSAMLObject)samlMessage).isSigned();
72          } else {
73              return false;
74          }
75      }
76      
77      /**
78       * Determine whether the binding implemented by the decoder requires the presence within the message 
79       * of information indicating the intended message destination endpoint URI.
80       * 
81       * 
82       * @param samlMsgCtx current SAML message context
83       * @return true if the intended message destination endpoint is required, false if not
84       */
85      protected abstract boolean isIntendedDestinationEndpointURIRequired(SAMLMessageContext samlMsgCtx);
86      
87      /**
88       * Extract the message information which indicates to what receiver endpoint URI the
89       * SAML message was intended to be delivered.
90       * 
91       * @param samlMsgCtx the SAML message context being processed
92       * @return the value of the intended destination endpoint URI, or null if not present or empty
93       * @throws MessageDecodingException thrown if the message is not an instance of SAML message that
94       *              could be processed by the decoder
95       */
96      protected abstract String getIntendedDestinationEndpointURI(SAMLMessageContext samlMsgCtx) 
97          throws MessageDecodingException;
98      
99      /**
100      * Extract the transport endpoint at which this message was received.
101      * 
102      * <p>This default implementation assumes an underlying message context {@link InTransport} type
103      * of {@link HttpServletRequestAdapter} and returns the string representation of the underlying
104      * request URL as constructed via {@link HttpServletRequest#getRequestURL()}.</p>
105      * 
106      * <p>Subclasses should override if binding-specific behavior or support for other transport
107      * typs is required.  In this case, see also {@link #compareEndpointURIs(String, String)}.</p>
108      * 
109      * 
110      * @param messageContext current message context
111      * @return string representing the transport endpoint URI at which the current message was received
112      * @throws MessageDecodingException thrown if the endpoint can not be extracted from the message
113      *                              context and converted to a string representation
114      */
115     protected String getActualReceiverEndpointURI(SAMLMessageContext messageContext) throws MessageDecodingException {
116         InTransport inTransport = messageContext.getInboundMessageTransport();
117         if (! (inTransport instanceof HttpServletRequestAdapter)) {
118             log.error("Message context InTransport instance was an unsupported type: {}", 
119                     inTransport.getClass().getName());
120             throw new MessageDecodingException("Message context InTransport instance was an unsupported type");
121         }
122         HttpServletRequest httpRequest = ((HttpServletRequestAdapter)inTransport).getWrappedRequest();
123         
124         StringBuffer urlBuilder = httpRequest.getRequestURL();
125         
126         return urlBuilder.toString();
127     }
128 
129     /**
130      * Compare the message endpoint URI's specified.
131      * 
132      * <p>This default implementation handles endpoint URI's that are URL's.  Comparison is handled
133      * via constructing {@link URL} instances and using that implementation's equals() method.</p>
134      * 
135      * <p>Subclasses should override if binding-specific behavior is required, or to support other
136      * types of URI's.  In this case, see also {@link #getActualReceiverEndpointURI(SAMLMessageContext)}.</p>
137      * 
138      * @param messageDestination the intended message destination endpoint URI
139      * @param receiverEndpoint the endpoint URI at which the message was received
140      * @return true if the endpoints are equivalent, false otherwise
141      * @throws MessageDecodingException thrown if the endpoints specified are not equivalent
142      */
143     protected boolean compareEndpointURIs(String messageDestination, String receiverEndpoint) 
144             throws MessageDecodingException {
145         
146         URL messageURL = null;
147         try {
148             messageURL = new URL(messageDestination);
149         } catch (MalformedURLException e) {
150             log.error("Message destination URL was malformed in destination check: {}", e.getMessage());
151             throw new MessageDecodingException("Message destination URL was malformed in destination check");
152         }
153         
154         URL endpointURL = null;
155         try {
156             endpointURL = new URL(receiverEndpoint);
157         } catch (MalformedURLException e) {
158             log.error("Recipient endpoint URL was malformed in destination check: {}", e.getMessage());
159             throw new MessageDecodingException("Recipient endpoint URL was malformed in destination check");
160         }
161         
162         return messageURL.equals(endpointURL);
163     }
164     
165     /**
166      * Check the validity of the SAML protocol message receiver endpoint against
167      * requirements indicated in the message.
168      * 
169      * @param messageContext current message context
170      * 
171      * @throws SecurityException thrown if the message Destination attribute is invalid
172      *                                  with respect to the receiver's endpoint
173      * @throws MessageDecodingException thrown if there is a problem decoding and processing
174      *                                  the message Destination or receiver
175      *                                  endpoint information
176      */
177     protected void checkEndpointURI(SAMLMessageContext messageContext) 
178             throws SecurityException, MessageDecodingException {
179         
180         log.debug("Checking SAML message intended destination endpoint against receiver endpoint");
181         
182         String messageDestination = 
183             DatatypeHelper.safeTrimOrNullString(getIntendedDestinationEndpointURI(messageContext));
184         
185         boolean bindingRequires = isIntendedDestinationEndpointURIRequired(messageContext);
186         
187         if (messageDestination == null) {
188             if (bindingRequires) {
189                 log.error("SAML message intended destination endpoint URI required by binding was empty");
190                 throw new SecurityException("SAML message intended destination (required by binding) was not present");
191             } else {
192                 log.debug("SAML message intended destination endpoint in message was empty, not required by binding, skipping");
193                 return;
194             }
195         }
196         
197         String receiverEndpoint = getActualReceiverEndpointURI(messageContext);
198         
199         log.debug("Intended message destination endpoint: {}", messageDestination);
200         log.debug("Actual message receiver endpoint: {}", receiverEndpoint);
201         
202         boolean matched = compareEndpointURIs(messageDestination, receiverEndpoint);
203         if (!matched) {
204             log.error("SAML message intended destination endpoint '{}' did not match the recipient endpoint '{}'",
205                     messageDestination, receiverEndpoint);
206             throw new SecurityException("SAML message intended destination endpoint did not match recipient endpoint");
207         } else {
208             log.debug("SAML message intended destination endpoint matched recipient endpoint");
209         }
210     }
211 
212 }