2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * ================================================================================
 
   7  * Copyright (C) 2017 Amdocs
 
   8  * =============================================================================
 
   9  * Licensed under the Apache License, Version 2.0 (the "License");
 
  10  * you may not use this file except in compliance with the License.
 
  11  * You may obtain a copy of the License at
 
  13  *      http://www.apache.org/licenses/LICENSE-2.0
 
  15  * Unless required by applicable law or agreed to in writing, software
 
  16  * distributed under the License is distributed on an "AS IS" BASIS,
 
  17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  18  * See the License for the specific language governing permissions and
 
  19  * limitations under the License.
 
  21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 
  22  * ============LICENSE_END=========================================================
 
  25 package org.onap.ccsdk.sli.adaptors.ansible.impl;
 
  27 import java.io.FileInputStream;
 
  28 import java.io.IOException;
 
  29 import java.security.KeyManagementException;
 
  30 import java.security.KeyStore;
 
  31 import java.security.KeyStoreException;
 
  32 import java.security.NoSuchAlgorithmException;
 
  33 import java.security.cert.CertificateException;
 
  34 import java.security.cert.CertificateFactory;
 
  35 import java.security.cert.X509Certificate;
 
  36 import javax.net.ssl.SSLContext;
 
  37 import javax.net.ssl.SSLException;
 
  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.ccsdk.sli.adaptors.ansible.model.AnsibleResult;
 
  54 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResultCodes;
 
  55 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
 
  56 import com.att.eelf.configuration.EELFLogger;
 
  57 import com.att.eelf.configuration.EELFManager;
 
  60  * Returns a custom http client
 
  62  * - can create one with ssl using an X509 certificate that does NOT have a known CA
 
  63  * - create one which trusts ALL SSL certificates
 
  64  * - return default httpclient (which only trusts known CAs from default cacerts file for process) this is the default
 
  68 public class ConnectionBuilder {
 
  70     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
 
  72     private CloseableHttpClient httpClient = null;
 
  73     private HttpClientContext httpContext = new HttpClientContext();
 
  76      * Constructor that initializes an http client based on certificate
 
  78     public ConnectionBuilder(String certFile) throws KeyStoreException, CertificateException, IOException,
 
  79             KeyManagementException, NoSuchAlgorithmException, SvcLogicException {
 
  81         /* Point to the certificate */
 
  82         FileInputStream fs = new FileInputStream(certFile);
 
  84         /* Generate a certificate from the X509 */
 
  85         CertificateFactory cf = CertificateFactory.getInstance("X.509");
 
  86         X509Certificate cert = (X509Certificate) cf.generateCertificate(fs);
 
  88         /* Create a keystore object and load the certificate there */
 
  89         KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
 
  90         keystore.load(null, null);
 
  91         keystore.setCertificateEntry("cacert", cert);
 
  93         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
 
  94         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
 
  95                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
 
  97         httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
 
 101      * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS
 
 104     public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException,
 
 105             KeyManagementException, NoSuchAlgorithmException, CertificateException {
 
 107         /* Load the specified trustStore */
 
 108         KeyStore keystore = KeyStore.getInstance("JKS");
 
 109         FileInputStream readStream = new FileInputStream(trustStoreFile);
 
 110         keystore.load(readStream, trustStorePasswd);
 
 112         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
 
 113         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
 
 114                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
 
 116         httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
 
 120      * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 or
 
 121      * Default if Mode == 0
 
 123     public ConnectionBuilder(int mode)
 
 124             throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
 
 126             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
 
 127             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
 
 128                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
 
 130             httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
 
 132             httpClient = HttpClients.createDefault();
 
 136     // Use to create an http context with auth headers
 
 137     public void setHttpContext(String user, String myPassword) {
 
 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);
 
 149     // Method posts to the ansible server and writes out response to
 
 150     // Ansible result object
 
 151     public AnsibleResult post(String agentUrl, String payload) {
 
 153         AnsibleResult result = new AnsibleResult();
 
 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");
 
 161             HttpResponse response = httpClient.execute(postObj, httpContext);
 
 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());
 
 176     // Method gets information from an Ansible server and writes out response to
 
 177     // Ansible result object
 
 179     public AnsibleResult get(String agentUrl) {
 
 181         AnsibleResult result = new AnsibleResult();
 
 184             HttpGet getObj = new HttpGet(agentUrl);
 
 185             HttpResponse response = httpClient.execute(getObj, httpContext);
 
 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);