264a7d1a98550c2c599435e32e46dc9e18082a20
[integration.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * PNF-REGISTRATION-HANDLER
4  * ================================================================================
5  * Copyright (C) 2018 Nokia. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.pnfsimulator.simulator.client.utils.ssl;
22
23 import org.apache.http.client.HttpClient;
24 import org.apache.http.client.config.RequestConfig;
25 import org.apache.http.conn.ssl.NoopHostnameVerifier;
26 import org.apache.http.conn.ssl.TrustAllStrategy;
27 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
28 import org.apache.http.conn.ssl.TrustStrategy;
29 import org.apache.http.impl.client.HttpClientBuilder;
30 import org.apache.http.impl.client.HttpClients;
31 import org.apache.http.ssl.SSLContextBuilder;
32 import org.apache.http.ssl.SSLContexts;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import javax.net.ssl.SSLContext;
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.net.MalformedURLException;
41 import java.net.URL;
42 import java.security.GeneralSecurityException;
43 import java.security.KeyManagementException;
44 import java.security.KeyStore;
45 import java.security.KeyStoreException;
46 import java.security.NoSuchAlgorithmException;
47 import java.util.Optional;
48
49 public enum SslSupportLevel {
50
51     NONE {
52         public HttpClient getClient(RequestConfig requestConfig, SSLAuthenticationHelper sslAuthenticationHelper) {
53             LOGGER.info("<!-----IN SslSupportLevel.NONE, Creating BasicHttpClient for http protocol----!>");
54             return HttpClientBuilder
55                     .create()
56                     .setDefaultRequestConfig(requestConfig)
57                     .build();
58         }
59     },
60     ALWAYS_TRUST {
61         public HttpClient getClient(RequestConfig requestConfig, SSLAuthenticationHelper sslAuthenticationHelper)
62                 throws GeneralSecurityException, IOException {
63             LoggerFactory.getLogger(SslSupportLevel.class).info("<!-----IN SslSupportLevel.ALWAYS_TRUST, Creating client with SSL support for https protocol----!>");
64             HttpClient client;
65             try {
66                 SSLContext alwaysTrustSslContext = SSLContextBuilder.create().loadTrustMaterial(TRUST_STRATEGY_ALWAYS).build();
67                 client = HttpClients.custom()
68                         .setSSLContext(alwaysTrustSslContext)
69                         .setSSLHostnameVerifier(new NoopHostnameVerifier())
70                         .setDefaultRequestConfig(requestConfig)
71                         .build();
72
73             } catch (GeneralSecurityException e) {
74                 LOGGER.error("Could not initialize client due to SSL exception: {}. Default client without SSL support will be used instead.\nCause: {}", e.getMessage(), e.getCause());
75                 client = NONE.getClient(requestConfig, sslAuthenticationHelper);
76             }
77             return client;
78         }
79     },
80     CLIENT_CERT_AUTH {
81         @Override
82         public HttpClient getClient(RequestConfig requestConfig, SSLAuthenticationHelper sslAuthenticationHelper)
83                 throws GeneralSecurityException, IOException {
84
85             SSLContext sslContext = SSLContexts.custom()
86                     .loadKeyMaterial(readCertificate(sslAuthenticationHelper.getClientCertificateDir(), sslAuthenticationHelper.getClientCertificatePassword(), "PKCS12"), getPasswordAsCharArray(sslAuthenticationHelper.getClientCertificatePassword()))
87                     .loadTrustMaterial(readCertificate(sslAuthenticationHelper.getTrustStoreDir(), sslAuthenticationHelper.getTrustStorePassword(), "JKS"), new TrustSelfSignedStrategy())
88                     .build();
89
90             return HttpClients.custom()
91                     .setSSLContext(sslContext)
92                     .setSSLHostnameVerifier(new NoopHostnameVerifier())
93                     .setDefaultRequestConfig(requestConfig)
94                     .build();
95         }
96
97         private KeyStore readCertificate(String certificate, String password, String type) throws GeneralSecurityException, IOException {
98             try (InputStream keyStoreStream = new FileInputStream(certificate)) {
99                 KeyStore keyStore = KeyStore.getInstance(type);
100                 keyStore.load(keyStoreStream, getPasswordAsCharArray(password));
101                 return keyStore;
102             }
103         }
104
105         private char[] getPasswordAsCharArray(String clientCertificatePassword) {
106             return Optional.ofNullable(clientCertificatePassword).map(String::toCharArray).orElse(null);
107         }
108     };
109
110     private static final Logger LOGGER = LoggerFactory.getLogger(SslSupportLevel.class);
111     private static final TrustStrategy TRUST_STRATEGY_ALWAYS = new TrustAllStrategy();
112
113     public static SslSupportLevel getSupportLevelBasedOnProtocol(String url) throws MalformedURLException {
114         return "https".equals(new URL(url).getProtocol()) ? SslSupportLevel.ALWAYS_TRUST : SslSupportLevel.NONE;
115     }
116
117     public abstract HttpClient getClient(RequestConfig config, SSLAuthenticationHelper sslAuthenticationHelper)
118             throws GeneralSecurityException, IOException;
119
120 }