Merge 1806 code of vid-common
[vid.git] / vid-app-common / src / main / java / org / onap / vid / aai / util / HttpsAuthClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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.vid.aai.util;
22
23
24 import org.eclipse.jetty.util.security.Password;
25 import org.glassfish.jersey.client.ClientConfig;
26 import org.glassfish.jersey.client.ClientProperties;
27 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
28 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
29 import org.onap.portalsdk.core.util.SystemProperties;
30
31 import javax.net.ssl.*;
32 import javax.ws.rs.client.Client;
33 import javax.ws.rs.client.ClientBuilder;
34 import java.io.FileInputStream;
35 import java.io.IOException;
36 import java.security.*;
37 import java.security.cert.CertificateException;
38 import java.security.cert.X509Certificate;
39
40 /**
41  * The Class HttpsAuthClient.
42  */
43 public class HttpsAuthClient {
44
45
46     public HttpsAuthClient(String certFilePath) {
47         this.certFilePath = certFilePath;
48     }
49
50     private final String certFilePath;
51
52     /** The logger. */
53     static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsAuthClient.class);
54
55     /**
56      * Gets the client.
57      *
58      * @return the client
59      * @throws KeyManagementException the key management exception
60      */
61     public Client getClient(HttpClientMode mode) throws GeneralSecurityException, IOException {
62         ClientConfig config = new ClientConfig();
63         SSLContext ctx;
64
65         try {
66             String truststorePath = getCertificatesPath() + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_FILENAME);
67             String truststorePassword = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_PASSWD_X);
68             String decryptedTruststorePassword = Password.deobfuscate(truststorePassword);
69
70             System.setProperty("javax.net.ssl.trustStore", truststorePath);
71             System.setProperty("javax.net.ssl.trustStorePassword", decryptedTruststorePassword);
72
73             HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
74                 public boolean verify(String string, SSLSession ssls) {
75                     return true;
76                 }
77             });
78             ctx = SSLContext.getInstance("TLSv1.2");
79             KeyManager[] keyManagers = null;
80             TrustManager[] trustManagers = getTrustManager(mode);
81
82             switch (mode) {
83                 case WITH_KEYSTORE:
84                     String aaiKeystorePath = getCertificatesPath() + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_FILENAME);
85                     String aaiKeystorePassword = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_PASSWD_X);
86                     config.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, Boolean.TRUE);
87                     config.connectorProvider(new HttpUrlConnectorProvider().useSetMethodWorkaround());
88                     KeyManagerFactory kmf = getKeyManagerFactory(aaiKeystorePath, aaiKeystorePassword);
89                     keyManagers = kmf.getKeyManagers();
90                     break;
91
92                 case WITHOUT_KEYSTORE:
93                     config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
94                     break;
95
96                 default:
97                     logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config. HttpClientMode is " + mode);
98             }
99
100             ctx.init(keyManagers, trustManagers, null);
101             return ClientBuilder.newBuilder()
102                     .sslContext(ctx)
103                     .hostnameVerifier(new HostnameVerifier() {
104                         @Override
105                         public boolean verify(String s, SSLSession sslSession) {
106                             return true;
107                         }
108                     }).withConfig(config)
109                     .build()
110                     .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class);
111         } catch (Exception e) {
112             logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config", e);
113             throw e;
114         }
115
116     }
117
118     /**
119      * @param aaiKeystorePath
120      * @param aaiKeystorePassword - in OBF format
121      * @return
122      * @throws NoSuchAlgorithmException
123      * @throws KeyStoreException
124      * @throws IOException
125      * @throws CertificateException
126      * @throws UnrecoverableKeyException
127      */
128     private KeyManagerFactory getKeyManagerFactory(String aaiKeystorePath, String aaiKeystorePassword) throws IOException, GeneralSecurityException {
129         String aaiDecryptedKeystorePassword = Password.deobfuscate(aaiKeystorePassword);
130         KeyManagerFactory kmf = null;
131         try (FileInputStream fin = new FileInputStream(aaiKeystorePath)) {
132             kmf = KeyManagerFactory.getInstance("SunX509");
133             KeyStore ks = KeyStore.getInstance("PKCS12");
134             char[] pwd = aaiDecryptedKeystorePassword.toCharArray();
135             ks.load(fin, pwd);
136             kmf.init(ks, pwd);
137         } catch (Exception e) {
138             logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up kmf");
139             logger.error(EELFLoggerDelegate.errorLogger, "Error setting up kmf (keystore path: {}, obfuascated keystore password: {})", aaiKeystorePath, aaiKeystorePassword, e);
140             throw e;
141         }
142         return kmf;
143     }
144
145     private String getCertificatesPath() {
146         return certFilePath;
147     }
148
149     private TrustManager[] getTrustManager(HttpClientMode httpClientMode) {
150         //Creating a trustManager that will accept all certificates.
151         //TODO - remove this one the POMBA certificate is added to the tomcat_keystore file
152         TrustManager[] trustAllCerts = null;
153         if (httpClientMode == HttpClientMode.UNSECURE) {
154
155             trustAllCerts = new TrustManager[]{new X509TrustManager() {
156                 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
157                     return null;
158                 }
159
160                 public void checkClientTrusted(X509Certificate[] certs, String authType) {
161                 }
162
163                 public void checkServerTrusted(X509Certificate[] certs, String authType) {
164                 }
165             }};
166         }
167         return trustAllCerts;
168     }
169
170
171 }