View Javadoc
1   /*
2    * This file is part of dependency-check-core.
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   * Copyright (c) 2014 Jeremy Long. All Rights Reserved.
17   */
18  package org.owasp.dependencycheck.utils;
19  
20  import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21  import org.apache.commons.lang3.StringUtils;
22  
23  import java.io.IOException;
24  import java.net.Authenticator;
25  import java.net.HttpURLConnection;
26  import java.net.InetSocketAddress;
27  import java.net.PasswordAuthentication;
28  import java.net.Proxy;
29  import java.net.SocketAddress;
30  import java.net.URL;
31  
32  /**
33   * A URLConnection Factory to create new connections. This encapsulates several configuration checks to ensure that the connection
34   * uses the correct proxy settings.
35   *
36   * @author Jeremy Long
37   */
38  public final class URLConnectionFactory {
39  
40      /**
41       * Private constructor for this factory.
42       */
43      private URLConnectionFactory() {
44      }
45  
46      /**
47       * Utility method to create an HttpURLConnection. If the application is configured to use a proxy this method will retrieve
48       * the proxy settings and use them when setting up the connection.
49       *
50       * @param url the url to connect to
51       * @return an HttpURLConnection
52       * @throws URLConnectionFailureException thrown if there is an exception
53       */
54      @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", justification = "Just being extra safe")
55      public static HttpURLConnection createHttpURLConnection(URL url) throws URLConnectionFailureException {
56          HttpURLConnection conn = null;
57          final String proxyUrl = Settings.getString(Settings.KEYS.PROXY_SERVER);
58  
59          try {
60              if (proxyUrl != null && !matchNonProxy(url)) {
61                  final int proxyPort = Settings.getInt(Settings.KEYS.PROXY_PORT);
62                  final SocketAddress address = new InetSocketAddress(proxyUrl, proxyPort);
63  
64                  final String username = Settings.getString(Settings.KEYS.PROXY_USERNAME);
65                  final String password = Settings.getString(Settings.KEYS.PROXY_PASSWORD);
66  
67                  if (username != null && password != null) {
68                      final Authenticator auth = new Authenticator() {
69                          @Override
70                          public PasswordAuthentication getPasswordAuthentication() {
71                              if (getRequestorType().equals(Authenticator.RequestorType.PROXY)) {
72                                  return new PasswordAuthentication(username, password.toCharArray());
73                              }
74                              return super.getPasswordAuthentication();
75                          }
76                      };
77                      Authenticator.setDefault(auth);
78                  }
79  
80                  final Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
81                  conn = (HttpURLConnection) url.openConnection(proxy);
82              } else {
83                  conn = (HttpURLConnection) url.openConnection();
84              }
85              final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
86              conn.setConnectTimeout(timeout);
87              conn.setInstanceFollowRedirects(true);
88          } catch (IOException ex) {
89              if (conn != null) {
90                  try {
91                      conn.disconnect();
92                  } finally {
93                      conn = null;
94                  }
95              }
96              throw new URLConnectionFailureException("Error getting connection.", ex);
97          }
98          return conn;
99      }
100 
101     /**
102      * Check if hostname matches nonProxy settings
103      *
104      * @param url the url to connect to
105      * @return matching result. true: match nonProxy
106      */
107     private static boolean matchNonProxy(final URL url) {
108         final String host = url.getHost();
109 
110         // code partially from org.apache.maven.plugins.site.AbstractDeployMojo#getProxyInfo
111         final String nonProxyHosts = Settings.getString(Settings.KEYS.PROXY_NON_PROXY_HOSTS);
112         if (null != nonProxyHosts) {
113             final String[] nonProxies = nonProxyHosts.split("(,)|(;)|(\\|)");
114             for (final String nonProxyHost : nonProxies) {
115                 //if ( StringUtils.contains( nonProxyHost, "*" ) )
116                 if (null != nonProxyHost && nonProxyHost.contains("*")) {
117                     // Handle wildcard at the end, beginning or middle of the nonProxyHost
118                     final int pos = nonProxyHost.indexOf('*');
119                     final String nonProxyHostPrefix = nonProxyHost.substring(0, pos);
120                     final String nonProxyHostSuffix = nonProxyHost.substring(pos + 1);
121                     // prefix*
122                     if (!StringUtils.isEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix) && StringUtils.isEmpty(nonProxyHostSuffix)) {
123                         return true;
124                     }
125                     // *suffix
126                     if (StringUtils.isEmpty(nonProxyHostPrefix) && !StringUtils.isEmpty(nonProxyHostSuffix) && host.endsWith(nonProxyHostSuffix)) {
127                         return true;
128                     }
129                     // prefix*suffix
130                     if (!StringUtils.isEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix) && !StringUtils.isEmpty(nonProxyHostSuffix)
131                             && host.endsWith(nonProxyHostSuffix)) {
132                         return true;
133                     }
134                 } else if (host.equals(nonProxyHost)) {
135                     return true;
136                 }
137             }
138         }
139         return false;
140     }
141 
142     /**
143      * Utility method to create an HttpURLConnection. The use of a proxy here is optional as there may be cases where a proxy is
144      * configured but we don't want to use it (for example, if there's an internal repository configured)
145      *
146      * @param url the URL to connect to
147      * @param proxy whether to use the proxy (if configured)
148      * @return a newly constructed HttpURLConnection
149      * @throws URLConnectionFailureException thrown if there is an exception
150      */
151     public static HttpURLConnection createHttpURLConnection(URL url, boolean proxy) throws URLConnectionFailureException {
152         if (proxy) {
153             return createHttpURLConnection(url);
154         }
155         HttpURLConnection conn = null;
156         try {
157             conn = (HttpURLConnection) url.openConnection();
158             final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
159             conn.setConnectTimeout(timeout);
160             conn.setInstanceFollowRedirects(true);
161         } catch (IOException ioe) {
162             throw new URLConnectionFailureException("Error getting connection.", ioe);
163         }
164         return conn;
165     }
166 }