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.common.config.metadata;
18  
19  import java.net.MalformedURLException;
20  import java.net.URL;
21  import java.security.cert.X509Certificate;
22  
23  import javax.net.ssl.X509TrustManager;
24  import javax.xml.namespace.QName;
25  
26  import org.apache.commons.httpclient.HttpClient;
27  import org.apache.commons.httpclient.UsernamePasswordCredentials;
28  import org.apache.commons.httpclient.auth.AuthScope;
29  import org.opensaml.saml2.metadata.provider.HTTPMetadataProvider;
30  import org.opensaml.ws.soap.client.http.HttpClientBuilder;
31  import org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory;
32  import org.opensaml.xml.util.DatatypeHelper;
33  import org.opensaml.xml.util.XMLHelper;
34  import org.slf4j.Logger;
35  import org.slf4j.LoggerFactory;
36  import org.springframework.beans.factory.BeanCreationException;
37  import org.springframework.beans.factory.support.BeanDefinitionBuilder;
38  import org.springframework.beans.factory.xml.ParserContext;
39  import org.w3c.dom.Element;
40  
41  import edu.internet2.middleware.shibboleth.common.config.SpringConfigurationUtils;
42  
43  /**
44   * Spring bean definition parser for Shibboleth file backed url metadata provider definition.
45   */
46  public class HTTPMetadataProviderBeanDefinitionParser extends AbstractReloadingMetadataProviderBeanDefinitionParser {
47  
48      /** Schema type name. */
49      public static final QName TYPE_NAME = new QName(MetadataNamespaceHandler.NAMESPACE, "HTTPMetadataProvider");
50  
51      /** Class logger. */
52      private Logger log = LoggerFactory.getLogger(HTTPMetadataProviderBeanDefinitionParser.class);
53  
54      /** {@inheritDoc} */
55      protected Class getBeanClass(Element element) {
56          return HTTPMetadataProvider.class;
57      }
58  
59      /** {@inheritDoc} */
60      protected void doParse(Element config, ParserContext parserContext, BeanDefinitionBuilder builder) {
61          String providerId = getProviderId(config);
62  
63          super.doParse(config, parserContext, builder);
64  
65          String metadataURL = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "metadataURL"));
66          URL metadataURI = null;
67          try {
68              metadataURI = new URL(metadataURL);
69          } catch (MalformedURLException e) {
70              throw new BeanCreationException("metadataURL attribute for metadata provider " + providerId
71                      + " must be present and must contain a valid URL");
72          }
73  
74          HttpClient httpClient = buildHttpClient(config, providerId, metadataURI);
75          builder.addConstructorArgValue(httpClient);
76  
77          log.debug("Metadata provider '{}' metadata URL: {}", providerId, metadataURL);
78          builder.addConstructorArgValue(metadataURL);
79      }
80  
81      /**
82       * Builds the HTTP client used to fetch metadata.
83       * 
84       * @param config the metadata provider configuration element
85       * @param providerId the ID of the metadata provider
86       * @param metadataURL the URL from which metadata will be fetched
87       * 
88       * @return the constructed HTTP client
89       */
90      protected HttpClient buildHttpClient(Element config, String providerId, URL metadataURL) {
91          HttpClientBuilder builder = new HttpClientBuilder();
92  
93          int requestTimeout = 5000;
94          if (config.hasAttributeNS(null, "requestTimeout")) {
95              requestTimeout = (int) SpringConfigurationUtils.parseDurationToMillis(
96                      "'requestTimeout' on metadata provider " + providerId,
97                      config.getAttributeNS(null, "requestTimeout"), 0);
98          }
99          log.debug("Metadata provider '{}' HTTP request timeout: {}ms", providerId, requestTimeout);
100         builder.setConnectionTimeout(requestTimeout);
101 
102         if (metadataURL.getProtocol().equalsIgnoreCase("https")) {
103             boolean disregardSslCertificate = false;
104             if (config.hasAttributeNS(null, "disregardSslCertificate")) {
105                 disregardSslCertificate = XMLHelper.getAttributeValueAsBoolean(config.getAttributeNodeNS(null,
106                         "disregardSslCertificate"));
107             }
108 
109             log.debug("Metadata provider '{}' disregards server SSL certificate: {}", providerId,
110                     disregardSslCertificate);
111             if (disregardSslCertificate) {
112                 builder.setHttpsProtocolSocketFactory(new TLSProtocolSocketFactory(null, buildNoTrustTrustManager()));
113             }
114         }
115 
116         setHttpProxySettings(builder, config, providerId);
117 
118         HttpClient httpClient = builder.buildClient();
119         setHttpBasicAuthSettings(httpClient, config, providerId, metadataURL);
120 
121         return httpClient;
122     }
123 
124     /**
125      * Builds a {@link X509TrustManager} which bypasses all X.509 validation steps.
126      * 
127      * @return the trustless trust manager
128      */
129     protected X509TrustManager buildNoTrustTrustManager() {
130         X509TrustManager noTrustManager = new X509TrustManager() {
131 
132             /** {@inheritDoc} */
133             public void checkClientTrusted(X509Certificate[] certs, String auth) {
134             }
135 
136             /** {@inheritDoc} */
137             public void checkServerTrusted(X509Certificate[] certs, String auth) {
138             }
139 
140             /** {@inheritDoc} */
141             public X509Certificate[] getAcceptedIssuers() {
142                 return new X509Certificate[] {};
143             }
144         };
145 
146         return noTrustManager;
147     }
148 
149     /**
150      * Sets the HTTP proxy properties, if any, for the HTTP client used to fetch metadata.
151      * 
152      * @param builder the HTTP client builder
153      * @param config the metadata provider configuration
154      * @param providerId the ID of the metadata provider
155      */
156     protected void setHttpProxySettings(HttpClientBuilder builder, Element config, String providerId) {
157         String proxyHost = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "proxyHost"));
158         if (proxyHost == null) {
159             return;
160         }
161         log.debug("Metadata provider '{}' HTTP proxy host: {}", providerId, proxyHost);
162         builder.setProxyHost(proxyHost);
163 
164         if (config.hasAttributeNS(null, "proxyPort")) {
165             int proxyPort = Integer.parseInt(config.getAttributeNS(null, "proxyPort"));
166             log.debug("Metadata provider '{}' HTTP proxy port: ", providerId, proxyPort);
167             builder.setProxyPort(proxyPort);
168         }
169 
170         String proxyUser = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "proxyUser"));
171         if (proxyUser != null) {
172             log.debug("Metadata provider '{}' HTTP proxy username: ", providerId, proxyUser);
173             builder.setProxyUsername(proxyUser);
174             log.debug("Metadata provider '{}' HTTP proxy password not shown", providerId);
175             builder.setProxyPassword(DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "proxyPassword")));
176         }
177     }
178 
179     /**
180      * Sets the basic authentication properties, if any, for the HTTP client used to fetch metadata.
181      * 
182      * @param httpClient the HTTP client
183      * @param config the metadata provider configuration
184      * @param providerId the ID of the metadata provider
185      * @param metadataURL the URL from which metadata will be fetched
186      */
187     protected void setHttpBasicAuthSettings(HttpClient httpClient, Element config, String providerId, URL metadataURL) {
188         String authUser = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "basicAuthUser"));
189         if (authUser == null) {
190             return;
191         }
192         log.debug("Metadata provider '{}' HTTP Basic Auth username: {}", providerId, authUser);
193 
194         String authPassword = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "basicAuthPassword"));
195         log.debug("Metadata provider '{}' HTTP Basic Auth password not show", providerId);
196 
197         UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authUser, authPassword);
198         AuthScope authScope = new AuthScope(metadataURL.getHost(), metadataURL.getPort());
199         httpClient.getState().setCredentials(authScope, credentials);
200     }
201 }