1fbf20633ea2de12cc99776007657dbda36f3860
[ccsdk/sli.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : SLI
4  * ================================================================================
5  * Copyright (C) 2021 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  *
19  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.ccsdk.sli.adaptors.ansible.impl;
24
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import java.io.Closeable;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.security.KeyManagementException;
31 import java.security.KeyStore;
32 import java.security.KeyStoreException;
33 import java.security.NoSuchAlgorithmException;
34 import java.security.cert.CertificateException;
35 import java.security.cert.CertificateFactory;
36 import java.security.cert.X509Certificate;
37 import javax.net.ssl.SSLContext;
38 import org.apache.commons.lang.StringUtils;
39 import org.apache.http.HttpEntity;
40 import org.apache.http.HttpResponse;
41 import org.apache.http.auth.AuthScope;
42 import org.apache.http.auth.UsernamePasswordCredentials;
43 import org.apache.http.client.config.RequestConfig;
44 import org.apache.http.client.methods.HttpGet;
45 import org.apache.http.client.methods.HttpPost;
46 import org.apache.http.client.protocol.HttpClientContext;
47 import org.apache.http.conn.ssl.NoopHostnameVerifier;
48 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
49 import org.apache.http.conn.ssl.SSLContexts;
50 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
51 import org.apache.http.entity.StringEntity;
52 import org.apache.http.impl.client.BasicCredentialsProvider;
53 import org.apache.http.impl.client.CloseableHttpClient;
54 import org.apache.http.impl.client.HttpClients;
55 import org.apache.http.util.EntityUtils;
56 import org.json.JSONObject;
57 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult;
58 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResultCodes;
59 import org.onap.ccsdk.sli.core.utils.PathValidator;
60
61 /**
62  * Returns a custom http client
63  * - based on options
64  * - can create one with ssl using an X509 certificate that does NOT have a known CA
65  * - create one which trusts ALL SSL certificates
66  * - return default httpclient (which only trusts known CAs from default cacerts file for process) this is the default
67  * option
68  **/
69
70 public class ConnectionBuilder implements Closeable {
71     private static final String STATUS_CODE_KEY = "StatusCode";
72     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
73
74     private final CloseableHttpClient httpClient;
75     private final HttpClientContext httpContext = new HttpClientContext();
76
77     /**
78      * Constructor that initializes an http client based on certificate
79      **/
80     public ConnectionBuilder(String certFile, int timeout) throws KeyStoreException, CertificateException, IOException,
81             KeyManagementException, NoSuchAlgorithmException {
82
83         /* Point to the certificate */
84         try (FileInputStream fs = new FileInputStream(certFile)) {
85             /* Generate a certificate from the X509 */
86             CertificateFactory cf = CertificateFactory.getInstance("X.509");
87             X509Certificate cert = (X509Certificate) cf.generateCertificate(fs);
88
89             /* Create a keystore object and load the certificate there */
90             KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
91             keystore.load(null, null);
92             keystore.setCertificateEntry("cacert", cert);
93
94             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
95             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
96                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
97
98             RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
99             httpClient = HttpClients.custom().setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
100         }
101     }
102
103     /**
104      * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS
105      * file)
106      **/
107     public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd, int timeout, String serverIP)
108             throws KeyStoreException, IOException, KeyManagementException, NoSuchAlgorithmException,
109             CertificateException {
110         if (!PathValidator.isValidFilePath(trustStoreFile)) {
111             throw new IOException("Invalid trust store file path");
112         }
113
114         /* Load the specified trustStore */
115         KeyStore keystore = KeyStore.getInstance("JKS");
116         FileInputStream readStream = new FileInputStream(trustStoreFile);
117         keystore.load(readStream, trustStorePasswd);
118         if (StringUtils.isNotBlank(serverIP)) {
119             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
120             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());
121
122             RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
123             httpClient = HttpClients.custom().setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
124         } else {
125             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
126             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
127                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
128             RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
129             httpClient = HttpClients.custom().setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
130         }
131     }
132
133     /**
134      * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 or
135      * Default if Mode == 0
136      */
137     public ConnectionBuilder(int mode, int timeout)
138             throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
139         RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
140         if (mode == 1) {
141             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
142             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
143                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
144
145             httpClient = HttpClients.custom().setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
146         } else {
147             httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
148         }
149     }
150
151     // Use to create an http context with auth headers
152     public void setHttpContext(String user, String pswd) {
153
154         // Are credential provided ? If so, set the context to be used
155         if (user != null && !user.isEmpty() && pswd != null && !pswd.isEmpty()) {
156             UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pswd);
157             AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
158             BasicCredentialsProvider credsprovider = new BasicCredentialsProvider();
159             credsprovider.setCredentials(authscope, credentials);
160             httpContext.setCredentialsProvider(credsprovider);
161         }
162     }
163
164     // Method posts to the ansible server and writes out response to
165     // Ansible result object
166     public AnsibleResult post(String agentUrl, String payload) {
167
168         AnsibleResult result = new AnsibleResult();
169         try {
170
171             HttpPost postObj = new HttpPost(agentUrl);
172             StringEntity bodyParams = new StringEntity(payload, "UTF-8");
173             postObj.setEntity(bodyParams);
174             postObj.addHeader("Content-type", "application/json");
175
176             HttpResponse response = httpClient.execute(postObj, httpContext);
177             HttpEntity entity = response.getEntity();
178             String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
179             int responseCode = response.getStatusLine().getStatusCode();
180             result.setStatusCode(responseCode);
181             result.setStatusMessage(responseOutput);
182         } catch (IOException io) {
183             logger.error("Caught IOException", io);
184             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
185             result.setStatusMessage(io.getMessage());
186         }
187         return result;
188     }
189
190     // Method gets information from an Ansible server and writes out response to
191     // Ansible result object
192
193     public AnsibleResult get(String agentUrl) {
194
195         AnsibleResult result = new AnsibleResult();
196
197         try {
198             HttpGet getObj = new HttpGet(agentUrl);
199             HttpResponse response = httpClient.execute(getObj, httpContext);
200             HttpEntity entity = response.getEntity();
201             String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
202             int responseCode = response.getStatusLine().getStatusCode();
203             logger.info("GetResult response for ansible GET URL" + agentUrl + " returned " + responseOutput);
204             JSONObject postResponse = new JSONObject(responseOutput);
205             if (postResponse.has(STATUS_CODE_KEY)) {
206                 int codeStatus = postResponse.getInt(STATUS_CODE_KEY);
207                 if (codeStatus == AnsibleResultCodes.PENDING.getValue()) {
208                     result.setStatusCode(codeStatus);
209                 } else {
210                     result.setStatusCode(responseCode);
211                 }
212             } else {
213                 result.setStatusCode(responseCode);
214             }
215             result.setStatusMessage(responseOutput);
216         } catch (IOException io) {
217             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
218             result.setStatusMessage(io.getMessage());
219             logger.error("Caught IOException", io);
220         }
221         return result;
222     }
223
224     @Override
225     public void close() {
226         try {
227             if (httpClient != null) {
228                 httpClient.close();
229             }
230         } catch (IOException e) {
231             logger.error("Caught IOException during httpClient close", e);
232         }
233     }
234
235 }