<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SSL &#8211; Pauls Blog</title>
	<atom:link href="https://sterl.org/tag/ssl/feed/" rel="self" type="application/rss+xml" />
	<link>https://sterl.org</link>
	<description></description>
	<lastBuildDate>Thu, 17 Jun 2021 09:23:18 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Spring Boot RestTemplate no SSL check</title>
		<link>https://sterl.org/2019/06/spring-boot-resttemplate-no-ssl-check/</link>
					<comments>https://sterl.org/2019/06/spring-boot-resttemplate-no-ssl-check/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Sun, 16 Jun 2019 18:56:00 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<category><![CDATA[CodeGen]]></category>
		<category><![CDATA[HTTPS]]></category>
		<category><![CDATA[skip ssl]]></category>
		<category><![CDATA[SSL]]></category>
		<category><![CDATA[Swagger]]></category>
		<guid isPermaLink="false">https://sterl.org/?p=662</guid>

					<description><![CDATA[Problem By default the Spring RestTempalte and the swagger OpenAPI client does an SSL check. This is usually not required on the test system, as so the goal is to remove the SSL check from the Spring Boot Rest Template. RestTemplate Apache HTTP Client pom.xml Swagger OpenAPI Client Furthermore sometimes it is required to remove&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Problem</h2>



<p>By default the Spring RestTempalte and the swagger OpenAPI client does an SSL check. This is usually not required on the test system, as so the goal is to remove the SSL check from the Spring Boot Rest Template.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Remote host closed connection during handshake; nested exception is javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
</pre></div>


<h2 class="wp-block-heading">RestTemplate</h2>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@Bean
public RestTemplate restTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final RestTemplate restTemplate = new RestTemplate(sslFactory());
    return restTemplate;
}

@Bean
public HttpComponentsClientHttpRequestFactory sslFactory() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -&gt; true;

    final SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                    .loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();

    final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

    final CloseableHttpClient httpClient = HttpClients.custom()
                    .setMaxConnPerRoute(250)
                    .setMaxConnTotal(250)
                    .setSSLSocketFactory(csf)
                    // during the SSL check we have also the verification of the host name,
                    // this can be skipped to like this:
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .build();

    final HttpComponentsClientHttpRequestFactory requestFactory =
                    new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);

    return requestFactory;
}</pre></div>



<h2 class="wp-block-heading">Apache HTTP Client pom.xml</h2>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;xml&quot;,&quot;mime&quot;:&quot;application/xml&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;XML&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;xml&quot;}">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;
    &lt;artifactId&gt;httpclient&lt;/artifactId&gt;
&lt;/dependency&gt;</pre></div>



<h2 class="wp-block-heading">Swagger OpenAPI Client</h2>



<p>Furthermore sometimes it is required to remove the SSL check from the OpenAPI Swagger ApiClient.</p>



<h2 class="wp-block-heading">Use the Spring RestTemplate for Swagger Client</h2>



<p>Add the following flag: -Dio.swagger.parser.util.RemoteUrl.trustAll=true&nbsp;</p>



<h2 class="wp-block-heading">Configure Swagger Client</h2>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">// If a using spring rest template assign here the RestTemplate
final XyzApi result = new XyzApi(new ApiClient(restTemplate));</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;xml&quot;,&quot;mime&quot;:&quot;application/xml&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;XML&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;xml&quot;}">&lt;plugin&gt;
    &lt;groupId&gt;org.openapitools&lt;/groupId&gt;
    &lt;artifactId&gt;openapi-generator-maven-plugin&lt;/artifactId&gt;
    &lt;executions&gt;
        &lt;execution&gt;
            &lt;id&gt;xyz-client&lt;/id&gt;
          &lt;goals&gt;
            &lt;goal&gt;generate&lt;/goal&gt;
          &lt;/goals&gt;
          &lt;configuration&gt;
          	    &lt;!-- use Spring RestTemaplte, optional --&gt;
                &lt;library&gt;resttemplate&lt;/library&gt;
	            &lt;!-- skip SSL check --&gt;
                &lt;environmentVariables&gt;
                    &lt;io.swagger.parser.util.RemoteUrl.trustAll&gt;true&lt;/io.swagger.parser.util.RemoteUrl.trustAll&gt;
                &lt;/environmentVariables&gt;</pre></div>



<h2 class="wp-block-heading">Links</h2>



<ul class="wp-block-list"><li>https://pragmaticintegrator.wordpress.com/2017/08/13/small-hack-to-avoid-ssl-validation-in-spring-resttemplate/</li><li>http://progressivecoder.com/avoid-ssl-validation-spring-boot-resttemplate/</li><li>https://dev.to/mnpaa/disable-skip-ssl-validation-in-springboot-resttemplate-1ec2</li><li>https://github.com/swagger-api/swagger-codegen/wiki/FAQ#is-there-a-way-to-disable-certificate-verification</li></ul>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2019/06/spring-boot-resttemplate-no-ssl-check/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Java SSLContext and the SSLSocketFactory self-signed certificate</title>
		<link>https://sterl.org/2016/07/self-signed-certificate-java-sslcontext-and-sslsocketfactory/</link>
					<comments>https://sterl.org/2016/07/self-signed-certificate-java-sslcontext-and-sslsocketfactory/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Tue, 19 Jul 2016 15:10:53 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[certificate]]></category>
		<category><![CDATA[SSL]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=175</guid>

					<description><![CDATA[Problem Often we want to connect to create a secure SSL connection to an HTTPs endpoint which is secured by a self-signed Certificate. If we do so just with a simple call we usually face an nice exception like: Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Problem</h2>



<p>Often we want to connect to create a secure SSL connection to an HTTPs endpoint which is secured by a self-signed Certificate. If we do so just with a simple call we usually face an nice exception like: </p>



<pre>
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
	at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
	at sun.security.validator.Validator.validate(Validator.java:260)
	at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
	at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
	at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1479)
	... 47 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
	at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
	at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
	at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
	... 53 more
</pre>



<h2 class="wp-block-heading">Solution</h2>



<p>Often I see that either somebody uses an trust all or just overwrites the default Socket Factory (HttpsURLConnection.setDefaultSSLSocketFactory(<code>sc.getSocketFactory())</code>).  This is maybe okay for just a test but should be used in production-ready code.</p>



<p>Overall it is simple to fix it. We just need to know how the stuff works. In short, we have usually always:</p>



<ul class="wp-block-list"><li> SSLSocketFactory &#8212; creates the Socket connection in case of an SSL connection </li><li> SSLContext &#8212; responsible for the verification of the certificate </li></ul>



<h3 class="wp-block-heading">Export Certificate</h3>



<p> First, we need to get the certificate. Either use Firefox to download it or the command line: </p>



<pre class="wp-block-code"><code>openssl s_client -connect google.de:443 -showcerts</code></pre>



<p>The <code>pem</code> file is here e.g.: </p>



<pre>
-----BEGIN CERTIFICATE-----
MIIDfTCCAuagAwIBAgIDErvmMA0GCSqGSIb3DQEBBQUAME4xCzAJBgNVBAYTAlVT
MRAwDgYDVQQKEwdFcXVpZmF4MS0wKwYDVQQLEyRFcXVpZmF4IFNlY3VyZSBDZXJ0
aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDIwNTIxMDQwMDAwWhcNMTgwODIxMDQwMDAw
WjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UE
AxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9m
OSm9BXiLnTjoBbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIu
T8rxh0PBFpVXLVDviS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6c
JmTM386DGXHKTubU1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmR
Cw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5asz
PeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo4HwMIHtMB8GA1UdIwQYMBaAFEjm
aPkr0rKV10fYIyAQTzOYkJ/UMB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrM
TjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjA6BgNVHR8EMzAxMC+g
LaArhilodHRwOi8vY3JsLmdlb3RydXN0LmNvbS9jcmxzL3NlY3VyZWNhLmNybDBO
BgNVHSAERzBFMEMGBFUdIAAwOzA5BggrBgEFBQcCARYtaHR0cHM6Ly93d3cuZ2Vv
dHJ1c3QuY29tL3Jlc291cmNlcy9yZXBvc2l0b3J5MA0GCSqGSIb3DQEBBQUAA4GB
AHbhEm5OSxYShjAGsoEIz/AIx8dxfmbuwu3UOx//8PDITtZDOLC5MH0Y0FWDomrL
NhGc6Ehmo21/uBPUR/6LWlxz/K7ZGzIZOKuXNBSqltLroxwUCEm2u+WR74M26x1W
b8ravHNjkOR/ez4iyz0H7V84dJzjA1BOoa+Y7mHyhD8S
-----END CERTIFICATE-----
</pre>



<h3 class="wp-block-heading">Create SSLContext including the Certificate</h3>



<p>You can either import this pem file into your trust store or just create the trust store using the pem on the fly:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public static SSLContext buildSslContext(InputStream... inputStreams) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
  X509Certificate cert;
  KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  trustStore.load(null);

  for (InputStream inputStream : inputStreams) {
    try {
      CertificateFactory certificateFactory = CertificateFactory.getInstance(&quot;X.509&quot;);
      cert = (X509Certificate)certificateFactory.generateCertificate(inputStream);
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
    String alias = cert.getSubjectX500Principal().getName();
    trustStore.setCertificateEntry(alias, cert);
  }

  TrustManagerFactory tmf = TrustManagerFactory.getInstance(&quot;X509&quot;);
  tmf.init(trustStore);
  TrustManager[] trustManagers = tmf.getTrustManagers();
  SSLContext sslContext = SSLContext.getInstance(&quot;TLS&quot;);
  sslContext.init(null, trustManagers, null);

  return sslContext;
}</pre></div>



<h3 class="wp-block-heading">Put the SSLSocketFactory together </h3>



<p>I assume the <code>pem</code> file is in the source folder here, for maven <code>src/main/resources</code>. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">SSLContext sslContext = CryptoUtil.buildSslContext(
  this.getClass().getResourceAsStream(&quot;/my-cert.pem&quot;));
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);</pre></div>



<p>Now we have the SSLSocketFactory, lets put it to use. </p>



<h3 class="wp-block-heading">Use the SSLConnectionSocketFactory</h3>



<p>Here I will use the created socket factory to configure the Apache HTTP client and use it again in the Spring RestTemplate: </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">// this two lines are just repeated from above
SSLContext sslContext = CryptoUtil.buildSslContext(this.getClass().getResourceAsStream(&quot;/beta-comfylight-cert.pem&quot;));
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

// here we create the Http Client using our SSL Socket Factory and so trust relation
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);

// create the spring REST Template using our apache HTTP client
RestTemplate restTemplate = new RestTemplate(requestFactory);</pre></div>



<h2 class="wp-block-heading">Summary</h2>



<p>What have we achieved now?</p>



<ul class="wp-block-list"><li>We have an SSL Socket Factory which just trust our &#8222;server&#8220; / &#8222;certificate&#8220;</li><li>We haven&#8217;t overwritten any default socket factory in the application, which could cause problems in other subsystems as we then just trust &#8222;us&#8220;</li><li>We haven&#8217;t used a trust all, which would be fine for a test but would render the SSL encryption useless in production (<a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack">man in the middle attack</a>&#8230;)</li></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2016/07/self-signed-certificate-java-sslcontext-and-sslsocketfactory/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
