672e0df670c6ed09ad79b1cc84fab7916c371ea9
[ccsdk/sli.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24  * ============LICENSE_END=========================================================
25  */
26
27 package org.onap.ccsdk.sli.adaptors.ansible.impl;
28
29 import java.io.FileInputStream;
30 import java.io.IOException;
31 import java.security.KeyManagementException;
32 import java.security.KeyStore;
33 import java.security.KeyStoreException;
34 import java.security.NoSuchAlgorithmException;
35 import java.security.cert.CertificateException;
36 import java.security.cert.CertificateFactory;
37 import java.security.cert.X509Certificate;
38 import javax.net.ssl.SSLContext;
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.methods.HttpGet;
44 import org.apache.http.client.methods.HttpPost;
45 import org.apache.http.client.protocol.HttpClientContext;
46 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
47 import org.apache.http.conn.ssl.SSLContexts;
48 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
49 import org.apache.http.entity.StringEntity;
50 import org.apache.http.impl.client.BasicCredentialsProvider;
51 import org.apache.http.impl.client.CloseableHttpClient;
52 import org.apache.http.impl.client.HttpClients;
53 import org.apache.http.util.EntityUtils;
54 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult;
55 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResultCodes;
56 import org.onap.ccsdk.sli.core.utils.PathValidator;
57
58 import com.att.eelf.configuration.EELFLogger;
59 import com.att.eelf.configuration.EELFManager;
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 {
71
72     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
73
74     private CloseableHttpClient httpClient = null;
75     private HttpClientContext httpContext = new HttpClientContext();
76
77     /**
78      * Constructor that initializes an http client based on certificate
79      **/
80     public ConnectionBuilder(String certFile) 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                 httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
99         }
100     }
101
102     /**
103      * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS
104      * file)
105      **/
106     public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException,
107             KeyManagementException, NoSuchAlgorithmException, CertificateException {
108
109         if (!PathValidator.isValidFilePath(trustStoreFile)) {
110             throw new IOException("Invalid trust store file path");
111         }
112
113         /* Load the specified trustStore */
114         KeyStore keystore = KeyStore.getInstance("JKS");
115         FileInputStream readStream = new FileInputStream(trustStoreFile);
116         keystore.load(readStream, trustStorePasswd);
117
118         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
119         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
120                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
121
122         httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
123     }
124
125     /**
126      * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 or
127      * Default if Mode == 0
128      */
129     public ConnectionBuilder(int mode)
130             throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
131         if (mode == 1) {
132             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
133             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
134                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
135
136             httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
137         } else {
138             httpClient = HttpClients.createDefault();
139         }
140     }
141
142     // Use to create an http context with auth headers
143     public void setHttpContext(String user, String myPassword) {
144
145         // Are credential provided ? If so, set the context to be used
146         if (user != null && !user.isEmpty() && myPassword != null && !myPassword.isEmpty()) {
147             UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, myPassword);
148             AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
149             BasicCredentialsProvider credsprovider = new BasicCredentialsProvider();
150             credsprovider.setCredentials(authscope, credentials);
151             httpContext.setCredentialsProvider(credsprovider);
152         }
153     }
154
155     // Method posts to the ansible server and writes out response to
156     // Ansible result object
157     public AnsibleResult post(String agentUrl, String payload) {
158
159         AnsibleResult result = new AnsibleResult();
160         try {
161
162             HttpPost postObj = new HttpPost(agentUrl);
163             StringEntity bodyParams = new StringEntity(payload, "UTF-8");
164             postObj.setEntity(bodyParams);
165             postObj.addHeader("Content-type", "application/json");
166
167             HttpResponse response = httpClient.execute(postObj, httpContext);
168
169             HttpEntity entity = response.getEntity();
170             String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
171             int responseCode = response.getStatusLine().getStatusCode();
172             result.setStatusCode(responseCode);
173             result.setStatusMessage(responseOutput);
174         } catch (IOException io) {
175             logger.error("Caught IOException", io);
176             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
177             result.setStatusMessage(io.getMessage());
178         }
179         return result;
180     }
181
182     // Method gets information from an Ansible server and writes out response to
183     // Ansible result object
184
185     public AnsibleResult get(String agentUrl) {
186
187         AnsibleResult result = new AnsibleResult();
188
189         try {
190             HttpGet getObj = new HttpGet(agentUrl);
191             HttpResponse response = httpClient.execute(getObj, httpContext);
192
193             HttpEntity entity = response.getEntity();
194             String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
195             int responseCode = response.getStatusLine().getStatusCode();
196             result.setStatusCode(responseCode);
197             result.setStatusMessage(responseOutput);
198         } catch (IOException io) {
199             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
200             result.setStatusMessage(io.getMessage());
201             logger.error("Caught IOException", io);
202         }
203         return result;
204     }
205 }