Add missing distributionManagement section to poms
[aai/search-data-service.git] / search-data-service / src / main / java / org / onap / aai / sa / searchdbabstraction / elasticsearch / dao / ElasticSearchHttpsController.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.sa.searchdbabstraction.elasticsearch.dao;
22
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.nio.file.Files;
26 import java.nio.file.Paths;
27 import java.security.KeyManagementException;
28 import java.security.KeyStore;
29 import java.security.KeyStoreException;
30 import java.security.NoSuchAlgorithmException;
31 import java.security.UnrecoverableKeyException;
32 import java.security.cert.CertificateException;
33 import java.security.cert.X509Certificate;
34 import java.util.Arrays;
35 import javax.net.ssl.HttpsURLConnection;
36 import javax.net.ssl.KeyManager;
37 import javax.net.ssl.KeyManagerFactory;
38 import javax.net.ssl.SSLContext;
39 import javax.net.ssl.TrustManager;
40 import javax.net.ssl.TrustManagerFactory;
41 import javax.net.ssl.X509TrustManager;
42 import org.onap.aai.cl.api.Logger;
43 import org.onap.aai.cl.eelf.LoggerFactory;
44 import org.onap.aai.sa.searchdbabstraction.elasticsearch.config.ElasticSearchConfig;
45
46 /**
47  * HTTPS (TLS) specific configuration.
48  */
49 public class ElasticSearchHttpsController {
50
51     private static final Logger logger =
52             LoggerFactory.getInstance().getLogger(ElasticSearchHttpsController.class.getName());
53
54     private static final String SSL_PROTOCOL = "TLS";
55     private static final String KEYSTORE_ALGORITHM = "SunX509";
56     private static final String KEYSTORE_TYPE = "PKCS12";
57
58     public ElasticSearchHttpsController(ElasticSearchConfig config) throws NoSuchAlgorithmException, KeyStoreException,
59             CertificateException, IOException, KeyManagementException, UnrecoverableKeyException {
60         logger.debug("Initialising HTTPS configuration");
61
62         SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
63         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEYSTORE_ALGORITHM);
64         KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
65
66         String clientCertPassword = config.getKeyStorePassword();
67
68         char[] pwd = null;
69         if (clientCertPassword != null) {
70             pwd = clientCertPassword.toCharArray();
71         } else {
72             logger.debug("No key store password is defined");
73         }
74
75         TrustManager[] trustManagers = getTrustManagers(config);
76         KeyManager[] keyManagers = null;
77
78         String clientCertFileName = config.getKeyStorePath();
79         if (clientCertFileName != null) {
80             InputStream fin = Files.newInputStream(Paths.get(clientCertFileName));
81             keyStore.load(fin, pwd);
82             kmf.init(keyStore, pwd);
83             keyManagers = kmf.getKeyManagers();
84         }
85
86         ctx.init(keyManagers, trustManagers, null);
87         logger.debug("Initialised SSL context");
88
89         HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
90         HttpsURLConnection.setDefaultHostnameVerifier((host, session) -> host.equalsIgnoreCase(session.getPeerHost()));
91     }
92
93     private TrustManager[] getTrustManagers(ElasticSearchConfig config)
94             throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
95         TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
96         // Using null here initializes the TMF with the default trust store.
97         tmf.init((KeyStore) null);
98
99         // Find the default trust manager.
100         final X509TrustManager defaultTrustManager = findX509TrustManager(tmf);
101
102         String trustStoreFile = config.getTrustStorePath();
103         if (trustStoreFile == null) {
104             logger.debug("No trust store defined");
105             return new TrustManager[] {defaultTrustManager};
106         }
107
108         // Create a new Trust Manager from the local trust store.
109         try (InputStream myKeys = Files.newInputStream(Paths.get(trustStoreFile))) {
110             KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
111             char[] pwdArray = null;
112             if (config.getTrustStorePassword() != null) {
113                 pwdArray = config.getTrustStorePassword().toCharArray();
114             }
115             myTrustStore.load(myKeys, pwdArray);
116             tmf.init(myTrustStore);
117         }
118
119         // Create a custom trust manager that wraps both our trust store and the default.
120         final X509TrustManager finalLocalTm = findX509TrustManager(tmf);
121
122         return new TrustManager[] {new X509TrustManager() {
123             @Override
124             public X509Certificate[] getAcceptedIssuers() {
125                 return defaultTrustManager.getAcceptedIssuers();
126             }
127
128             @Override
129             public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
130                 try {
131                     finalLocalTm.checkServerTrusted(chain, authType);
132                 } catch (CertificateException e) {
133                     defaultTrustManager.checkServerTrusted(chain, authType);
134                 }
135             }
136
137             @Override
138             public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
139                 defaultTrustManager.checkClientTrusted(chain, authType);
140             }
141         }};
142     }
143
144     private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
145         return (X509TrustManager) Arrays.asList(tmf.getTrustManagers()).stream()
146                 .filter(tm -> tm instanceof X509TrustManager).findFirst().orElse(null);
147     }
148 }