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.URI;
20  import java.net.URISyntaxException;
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          URI metadataURI = null;
67          try {
68              metadataURI = new URI(metadataURL);
69          } catch (URISyntaxException 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, URI 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, config
97                              .getAttributeNS(null, "requestTimeout"), 0);
98          }
99          log.debug("Metadata provider '{}' HTTP request timeout: {}ms", providerId, requestTimeout);
100         builder.setConnectionTimeout(requestTimeout);
101 
102         if (metadataURL.getScheme().equalsIgnoreCase("https")) {
103             boolean disregardSslCertificate = XMLHelper.getAttributeValueAsBoolean(config.getAttributeNodeNS(null,
104                     "disregardSslCertificate"));
105             log.debug("Metadata provider '{}' disregards server SSL certificate: {}", providerId,
106                     disregardSslCertificate);
107             if (disregardSslCertificate) {
108                 builder.setHttpsProtocolSocketFactory(new TLSProtocolSocketFactory(null, buildNoTrustTrustManager()));
109             }
110         }
111 
112         setHttpProxySettings(builder, config, providerId);
113 
114         HttpClient httpClient = builder.buildClient();
115         setHttpBasicAuthSettings(httpClient, config, providerId, metadataURL);
116 
117         return httpClient;
118     }
119 
120     /**
121      * Builds a {@link X509TrustManager} which bypasses all X.509 validation steps.
122      * 
123      * @return the trustless trust manager
124      */
125     protected X509TrustManager buildNoTrustTrustManager() {
126         X509TrustManager noTrustManager = new X509TrustManager() {
127 
128             /** {@inheritDoc} */
129             public void checkClientTrusted(X509Certificate[] certs, String auth) {
130             }
131 
132             /** {@inheritDoc} */
133             public void checkServerTrusted(X509Certificate[] certs, String auth) {
134             }
135 
136             /** {@inheritDoc} */
137             public X509Certificate[] getAcceptedIssuers() {
138                 return new X509Certificate[] {};
139             }
140         };
141 
142         return noTrustManager;
143     }
144 
145     /**
146      * Sets the HTTP proxy properties, if any, for the HTTP client used to fetch metadata.
147      * 
148      * @param builder the HTTP client builder
149      * @param config the metadata provider configuration
150      * @param providerId the ID of the metadata provider
151      */
152     protected void setHttpProxySettings(HttpClientBuilder builder, Element config, String providerId) {
153         String proxyHost = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "proxyHost"));
154         if (proxyHost == null) {
155             return;
156         }
157         log.debug("Metadata provider '{}' HTTP proxy host: {}ms", providerId, proxyHost);
158         builder.setProxyHost(proxyHost);
159 
160         if (config.hasAttributeNS(null, "proxyPort")) {
161             int proxyPort = Integer.parseInt(config.getAttributeNS(null, "proxyPort"));
162             log.debug("Metadata provider '{}' HTTP proxy port: ", providerId, proxyPort);
163             builder.setProxyPort(proxyPort);
164         }
165 
166         String proxyUser = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "proxyUser"));
167         if (proxyUser != null) {
168             log.debug("Metadata provider '{}' HTTP proxy username: ", providerId, proxyUser);
169             builder.setProxyUsername(proxyUser);
170             log.debug("Metadata provider '{}' HTTP proxy password not shown", providerId);
171             builder.setProxyPassword(DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "proxyPassword")));
172         }
173     }
174 
175     /**
176      * Sets the basic authentication properties, if any, for the HTTP client used to fetch metadata.
177      * 
178      * @param httpClient the HTTP client
179      * @param config the metadata provider configuration
180      * @param providerId the ID of the metadata provider
181      * @param metadataURL the URL from which metadata will be fetched
182      */
183     protected void setHttpBasicAuthSettings(HttpClient httpClient, Element config, String providerId, URI metadataURL) {
184         String authUser = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "basicAuthUser"));
185         if (authUser == null) {
186             return;
187         }
188         log.debug("Metadata provider '{}' HTTP Basic Auth username: {}", providerId, authUser);
189 
190         String authPassword = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "basicAuthPassword"));
191         log.debug("Metadata provider '{}' HTTP Basic Auth password not show", providerId);
192 
193         UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authUser, authPassword);
194         AuthScope authScope = new AuthScope(metadataURL.getHost(), metadataURL.getPort());
195         httpClient.getState().setCredentials(authScope, credentials);
196     }
197 }