You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OkHttpClientBuilder.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonarqube.ws.client;
  21. import java.io.FileInputStream;
  22. import java.io.IOException;
  23. import java.net.HttpURLConnection;
  24. import java.net.Proxy;
  25. import java.security.GeneralSecurityException;
  26. import java.security.KeyStore;
  27. import java.security.KeyStoreException;
  28. import java.security.NoSuchAlgorithmException;
  29. import java.security.NoSuchProviderException;
  30. import java.security.UnrecoverableKeyException;
  31. import java.security.cert.CertificateException;
  32. import java.util.Arrays;
  33. import java.util.concurrent.TimeUnit;
  34. import javax.annotation.Nullable;
  35. import javax.net.ssl.KeyManager;
  36. import javax.net.ssl.KeyManagerFactory;
  37. import javax.net.ssl.SSLContext;
  38. import javax.net.ssl.SSLSocketFactory;
  39. import javax.net.ssl.TrustManager;
  40. import javax.net.ssl.TrustManagerFactory;
  41. import javax.net.ssl.X509TrustManager;
  42. import okhttp3.ConnectionSpec;
  43. import okhttp3.Credentials;
  44. import okhttp3.Interceptor;
  45. import okhttp3.OkHttpClient;
  46. import okhttp3.Request;
  47. import okhttp3.Response;
  48. import static java.nio.charset.StandardCharsets.UTF_8;
  49. import static java.util.Arrays.asList;
  50. import static org.sonarqube.ws.WsUtils.nullToEmpty;
  51. /**
  52. * Helper to build an instance of {@link okhttp3.OkHttpClient} that
  53. * correctly supports HTTPS and proxy authentication. It also handles
  54. * sending of User-Agent header.
  55. */
  56. public class OkHttpClientBuilder {
  57. private static final String NONE = "NONE";
  58. private static final String P11KEYSTORE = "PKCS11";
  59. private static final String PROXY_AUTHORIZATION = "Proxy-Authorization";
  60. private String userAgent;
  61. private Proxy proxy;
  62. private String credentials;
  63. private String proxyLogin;
  64. private String proxyPassword;
  65. private Boolean followRedirects;
  66. private long connectTimeoutMs = -1;
  67. private long readTimeoutMs = -1;
  68. private SSLSocketFactory sslSocketFactory = null;
  69. private X509TrustManager sslTrustManager = null;
  70. /**
  71. * Optional User-Agent. If set, then all the requests sent by the
  72. * {@link OkHttpClient} will include the header "User-Agent".
  73. */
  74. public OkHttpClientBuilder setUserAgent(@Nullable String s) {
  75. this.userAgent = s;
  76. return this;
  77. }
  78. /**
  79. * Optional SSL socket factory with which SSL sockets will be created to establish SSL connections.
  80. * If not set, a default SSL socket factory will be used, base d on the JVM's default key store.
  81. */
  82. public OkHttpClientBuilder setSSLSocketFactory(@Nullable SSLSocketFactory sslSocketFactory) {
  83. this.sslSocketFactory = sslSocketFactory;
  84. return this;
  85. }
  86. /**
  87. * Optional SSL trust manager used to validate certificates.
  88. * If not set, a default system trust manager will be used, based on the JVM's default truststore.
  89. */
  90. public OkHttpClientBuilder setTrustManager(@Nullable X509TrustManager sslTrustManager) {
  91. this.sslTrustManager = sslTrustManager;
  92. return this;
  93. }
  94. /**
  95. * Optional proxy. If set, then all the requests sent by the
  96. * {@link OkHttpClient} will reach the proxy. If not set,
  97. * then the system-wide proxy is used.
  98. */
  99. public OkHttpClientBuilder setProxy(@Nullable Proxy proxy) {
  100. this.proxy = proxy;
  101. return this;
  102. }
  103. /**
  104. * Login required for proxy authentication.
  105. */
  106. public OkHttpClientBuilder setProxyLogin(@Nullable String s) {
  107. this.proxyLogin = s;
  108. return this;
  109. }
  110. /**
  111. * Password used for proxy authentication. It is ignored if
  112. * proxy login is not defined (see {@link #setProxyLogin(String)}).
  113. * It can be null or empty when login is defined.
  114. */
  115. public OkHttpClientBuilder setProxyPassword(@Nullable String s) {
  116. this.proxyPassword = s;
  117. return this;
  118. }
  119. /**
  120. * Sets the default connect timeout for new connections. A value of 0 means no timeout.
  121. * Default is defined by OkHttp (10 seconds in OkHttp 3.3).
  122. */
  123. public OkHttpClientBuilder setConnectTimeoutMs(long l) {
  124. if (l < 0) {
  125. throw new IllegalArgumentException("Connect timeout must be positive. Got " + l);
  126. }
  127. this.connectTimeoutMs = l;
  128. return this;
  129. }
  130. /**
  131. * Set credentials that will be passed on every request
  132. */
  133. public OkHttpClientBuilder setCredentials(String credentials) {
  134. this.credentials = credentials;
  135. return this;
  136. }
  137. /**
  138. * Sets the default read timeout for new connections. A value of 0 means no timeout.
  139. * Default is defined by OkHttp (10 seconds in OkHttp 3.3).
  140. */
  141. public OkHttpClientBuilder setReadTimeoutMs(long l) {
  142. if (l < 0) {
  143. throw new IllegalArgumentException("Read timeout must be positive. Got " + l);
  144. }
  145. this.readTimeoutMs = l;
  146. return this;
  147. }
  148. /**
  149. * Set if redirects should be followed or not.
  150. * Default is defined by OkHttp (true, follow redirects).
  151. */
  152. public OkHttpClientBuilder setFollowRedirects(Boolean followRedirects) {
  153. this.followRedirects = followRedirects;
  154. return this;
  155. }
  156. public OkHttpClient build() {
  157. OkHttpClient.Builder builder = new OkHttpClient.Builder();
  158. builder.proxy(proxy);
  159. if (connectTimeoutMs >= 0) {
  160. builder.connectTimeout(connectTimeoutMs, TimeUnit.MILLISECONDS);
  161. }
  162. if (readTimeoutMs >= 0) {
  163. builder.readTimeout(readTimeoutMs, TimeUnit.MILLISECONDS);
  164. }
  165. builder.addNetworkInterceptor(this::addHeaders);
  166. if (proxyLogin != null) {
  167. builder.proxyAuthenticator((route, response) -> {
  168. if (response.request().header(PROXY_AUTHORIZATION) != null) {
  169. // Give up, we've already attempted to authenticate.
  170. return null;
  171. }
  172. if (HttpURLConnection.HTTP_PROXY_AUTH == response.code()) {
  173. String credential = Credentials.basic(proxyLogin, nullToEmpty(proxyPassword), UTF_8);
  174. return response.request().newBuilder().header(PROXY_AUTHORIZATION, credential).build();
  175. }
  176. return null;
  177. });
  178. }
  179. if (followRedirects != null) {
  180. builder.followRedirects(followRedirects);
  181. builder.followSslRedirects(followRedirects);
  182. }
  183. ConnectionSpec tls = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
  184. .allEnabledTlsVersions()
  185. .allEnabledCipherSuites()
  186. .supportsTlsExtensions(true)
  187. .build();
  188. builder.connectionSpecs(asList(tls, ConnectionSpec.CLEARTEXT));
  189. X509TrustManager trustManager = sslTrustManager != null ? sslTrustManager : systemDefaultTrustManager();
  190. SSLSocketFactory sslFactory = sslSocketFactory != null ? sslSocketFactory : systemDefaultSslSocketFactory(trustManager);
  191. builder.sslSocketFactory(sslFactory, trustManager);
  192. return builder.build();
  193. }
  194. private Response addHeaders(Interceptor.Chain chain) throws IOException {
  195. Request.Builder newRequest = chain.request().newBuilder();
  196. if (userAgent != null) {
  197. newRequest.header("User-Agent", userAgent);
  198. }
  199. if (credentials != null) {
  200. newRequest.header("Authorization", credentials);
  201. }
  202. return chain.proceed(newRequest.build());
  203. }
  204. private static X509TrustManager systemDefaultTrustManager() {
  205. try {
  206. TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  207. trustManagerFactory.init((KeyStore) null);
  208. TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  209. if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
  210. throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
  211. }
  212. return (X509TrustManager) trustManagers[0];
  213. } catch (GeneralSecurityException e) {
  214. // The system has no TLS. Just give up.
  215. throw new AssertionError(e);
  216. }
  217. }
  218. private static SSLSocketFactory systemDefaultSslSocketFactory(X509TrustManager trustManager) {
  219. KeyManager[] defaultKeyManager;
  220. try {
  221. defaultKeyManager = getDefaultKeyManager();
  222. } catch (Exception e) {
  223. throw new IllegalStateException("Unable to get default key manager", e);
  224. }
  225. try {
  226. SSLContext sslContext = SSLContext.getInstance("TLS");
  227. sslContext.init(defaultKeyManager, new TrustManager[] {trustManager}, null);
  228. return sslContext.getSocketFactory();
  229. } catch (GeneralSecurityException e) {
  230. // The system has no TLS. Just give up.
  231. throw new AssertionError(e);
  232. }
  233. }
  234. private static void logDebug(String msg) {
  235. boolean debugEnabled = "all".equals(System.getProperty("javax.net.debug"));
  236. if (debugEnabled) {
  237. System.out.println(msg);
  238. }
  239. }
  240. /**
  241. * Inspired from sun.security.ssl.SSLContextImpl#getDefaultKeyManager()
  242. */
  243. private static synchronized KeyManager[] getDefaultKeyManager() throws KeyStoreException, NoSuchProviderException,
  244. IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
  245. final String defaultKeyStore = System.getProperty("javax.net.ssl.keyStore", "");
  246. String defaultKeyStoreType = System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType());
  247. String defaultKeyStoreProvider = System.getProperty("javax.net.ssl.keyStoreProvider", "");
  248. logDebug("keyStore is : " + defaultKeyStore);
  249. logDebug("keyStore type is : " + defaultKeyStoreType);
  250. logDebug("keyStore provider is : " + defaultKeyStoreProvider);
  251. if (P11KEYSTORE.equals(defaultKeyStoreType) && !NONE.equals(defaultKeyStore)) {
  252. throw new IllegalArgumentException("if keyStoreType is " + P11KEYSTORE + ", then keyStore must be " + NONE);
  253. }
  254. KeyStore ks = null;
  255. String defaultKeyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword", "");
  256. char[] passwd = defaultKeyStorePassword.isEmpty() ? null : defaultKeyStorePassword.toCharArray();
  257. // Try to initialize key store.
  258. if (!defaultKeyStoreType.isEmpty()) {
  259. logDebug("init keystore");
  260. if (defaultKeyStoreProvider.isEmpty()) {
  261. ks = KeyStore.getInstance(defaultKeyStoreType);
  262. } else {
  263. ks = KeyStore.getInstance(defaultKeyStoreType, defaultKeyStoreProvider);
  264. }
  265. if (!defaultKeyStore.isEmpty() && !NONE.equals(defaultKeyStore)) {
  266. try (FileInputStream fs = new FileInputStream(defaultKeyStore)) {
  267. ks.load(fs, passwd);
  268. }
  269. } else {
  270. ks.load(null, passwd);
  271. }
  272. }
  273. // Try to initialize key manager.
  274. logDebug("init keymanager of type " + KeyManagerFactory.getDefaultAlgorithm());
  275. KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  276. if (P11KEYSTORE.equals(defaultKeyStoreType)) {
  277. // do not pass key passwd if using token
  278. kmf.init(ks, null);
  279. } else {
  280. kmf.init(ks, passwd);
  281. }
  282. return kmf.getKeyManagers();
  283. }
  284. }