902ae59b48a7de1d4c77a8a8b14fef278cbeced5
[appc.git] / appc-adapters / appc-ansible-adapter / appc-ansible-adapter-bundle / src / main / java / org / onap / appc / adapter / ansible / impl / ConnectionBuilder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications Copyright © 2018 IBM.
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.adapter.ansible.impl;
27
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.http.HttpEntity;
39 import org.apache.http.HttpResponse;
40 import org.apache.http.auth.AuthScope;
41 import org.apache.http.auth.UsernamePasswordCredentials;
42 import org.apache.http.client.methods.HttpGet;
43 import org.apache.http.client.methods.HttpPost;
44 import org.apache.http.client.protocol.HttpClientContext;
45 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
46 import org.apache.http.conn.ssl.SSLContexts;
47 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
48 import org.apache.http.entity.StringEntity;
49 import org.apache.http.impl.client.BasicCredentialsProvider;
50 import org.apache.http.impl.client.CloseableHttpClient;
51 import org.apache.http.impl.client.HttpClients;
52 import org.apache.http.util.EntityUtils;
53 import org.onap.appc.adapter.ansible.model.AnsibleResult;
54 import org.onap.appc.adapter.ansible.model.AnsibleResultCodes;
55 import com.att.eelf.configuration.EELFLogger;
56 import com.att.eelf.configuration.EELFManager;
57
58 /**
59  * Returns a custom http client
60  * - based on options
61  * - can create one with ssl using an X509 certificate that does NOT have a known CA
62  * - create one which trusts ALL SSL certificates
63  * - return default httpclient (which only trusts known CAs from default cacerts file for process) this is the default
64  * option
65  **/
66
67 public class ConnectionBuilder {
68
69     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
70
71     private CloseableHttpClient httpClient = null;
72     private HttpClientContext httpContext = new HttpClientContext();
73
74     /**
75      * Constructor that initializes an http client based on certificate
76      **/
77     public ConnectionBuilder(String certFile) throws KeyStoreException, CertificateException, IOException,
78             KeyManagementException, NoSuchAlgorithmException {
79
80         /* Point to the certificate */
81         try(FileInputStream fs = new FileInputStream(certFile)) {
82
83             /* Generate a certificate from the X509 */
84             CertificateFactory cf = CertificateFactory.getInstance("X.509");
85             X509Certificate cert = (X509Certificate) cf.generateCertificate(fs);
86
87             /* Create a keystore object and load the certificate there */
88             KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
89             keystore.load(null, null);
90             keystore.setCertificateEntry("cacert", cert);
91
92             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
93             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
94                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
95
96             httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
97         }
98     }
99
100     /**
101      * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS
102      * file)
103      **/
104     public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException,
105             KeyManagementException, NoSuchAlgorithmException, CertificateException {
106
107         /* Load the specified trustStore */
108         KeyStore keystore = KeyStore.getInstance("JKS");
109         FileInputStream readStream = new FileInputStream(trustStoreFile);
110         keystore.load(readStream, trustStorePasswd);
111
112         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
113         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
114                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
115
116         httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
117     }
118
119     /**
120      * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 or
121      * Default if Mode == 0
122      */
123     public ConnectionBuilder(int mode)
124             throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
125         if (mode == 1) {
126             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
127             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
128                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
129
130             httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
131         } else {
132             httpClient = HttpClients.createDefault();
133         }
134     }
135
136     // Use to create an http context with auth headers
137     public void setHttpContext(String user, String myPassword) {
138
139         // Are credential provided ? If so, set the context to be used
140         if (user != null && !user.isEmpty() && myPassword != null && !myPassword.isEmpty()) {
141             UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, myPassword);
142             AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
143             BasicCredentialsProvider credsprovider = new BasicCredentialsProvider();
144             credsprovider.setCredentials(authscope, credentials);
145             httpContext.setCredentialsProvider(credsprovider);
146         }
147     }
148
149     // Method posts to the ansible server and writes out response to
150     // Ansible result object
151     public AnsibleResult post(String agentUrl, String payload) {
152
153         AnsibleResult result = new AnsibleResult();
154         try {
155
156             HttpPost postObj = new HttpPost(agentUrl);
157             StringEntity bodyParams = new StringEntity(payload, "UTF-8");
158             postObj.setEntity(bodyParams);
159             postObj.addHeader("Content-type", "application/json");
160
161             HttpResponse response = httpClient.execute(postObj, httpContext);
162
163             HttpEntity entity = response.getEntity();
164             String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
165             int responseCode = response.getStatusLine().getStatusCode();
166             result.setStatusCode(responseCode);
167             result.setStatusMessage(responseOutput);
168         } catch (IOException io) {
169             logger.error("Caught IOException", io);
170             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
171             result.setStatusMessage(io.getMessage());
172         }
173         return result;
174     }
175
176     // Method gets information from an Ansible server and writes out response to
177     // Ansible result object
178
179     public AnsibleResult get(String agentUrl) {
180
181         AnsibleResult result = new AnsibleResult();
182
183         try {
184             HttpGet getObj = new HttpGet(agentUrl);
185             HttpResponse response = httpClient.execute(getObj, httpContext);
186
187             HttpEntity entity = response.getEntity();
188             String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
189             int responseCode = response.getStatusLine().getStatusCode();
190             result.setStatusCode(responseCode);
191             result.setStatusMessage(responseOutput);
192         } catch (IOException io) {
193             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
194             result.setStatusMessage(io.getMessage());
195             logger.error("Caught IOException", io);
196         }
197         return result;
198     }
199 }