6ff18b48fe698aef0f4baa78d8cd2c822de9fd2f
[ccsdk/features.git] /
1 /*******************************************************************************
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk feature sdnr wt
4  *  ================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  ******************************************************************************/
21 package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeConnector.test;
22
23 import java.io.BufferedReader;
24 import java.io.File;
25 import java.io.IOException;
26 import java.io.InputStreamReader;
27 import java.net.MalformedURLException;
28 import java.net.URL;
29 import java.security.KeyManagementException;
30 import java.security.NoSuchAlgorithmException;
31 import java.security.SecureRandom;
32 import java.security.cert.Certificate;
33 import java.security.cert.X509Certificate;
34 import javax.net.ssl.HttpsURLConnection;
35 import javax.net.ssl.SSLContext;
36 import javax.net.ssl.SSLPeerUnverifiedException;
37 import javax.net.ssl.SSLSocketFactory;
38 import javax.net.ssl.TrustManager;
39 import javax.net.ssl.X509TrustManager;
40 import org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl.DcaeProviderClient;
41
42 public class HttpsClient{
43
44     private static final MyLogger LOG = MyLogger.getLogger(DcaeProviderClient.class);
45
46     void test() {
47
48         TrustManager tm = new X509TrustManager() {
49
50             @Override
51             public void checkClientTrusted(X509Certificate[] chain, String authType)
52                     throws java.security.cert.CertificateException {
53                 //do nothing, you're the client
54             }
55
56             @Override
57             public void checkServerTrusted(X509Certificate[] chain, String authType)
58                     throws java.security.cert.CertificateException {
59                 /* chain[chain.length -1] is the candidate for the
60                  * root certificate.
61                  * Look it up to see whether it's in your list.
62                  * If not, ask the user for permission to add it.
63                  * If not granted, reject.
64                  * Validate the chain using CertPathValidator and
65                  * your list of trusted roots.
66                  */
67             }
68
69             @Override
70             public X509Certificate[] getAcceptedIssuers() {
71                    //also only relevant for servers
72                  return null;
73             }
74         };
75
76         TrustManager tml[] = new TrustManager[1];
77         tml[0] = tm;
78
79
80         try {
81             SSLContext ctx = SSLContext.getInstance("TLS");
82             ctx.init(null, tml, null);
83             @SuppressWarnings("unused")
84             SSLSocketFactory sslF = ctx.getSocketFactory();
85
86         } catch (NoSuchAlgorithmException | KeyManagementException e) {
87             e.printStackTrace();
88         }
89
90
91     };
92
93     void setupAllTrustingManager() {
94         // Create a trust manager that does not validate certificate chains
95         TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
96             @Override
97             public X509Certificate[] getAcceptedIssuers(){return null;}
98             @Override
99             public void checkClientTrusted(X509Certificate[] certs, String authType){}
100             @Override
101             public void checkServerTrusted(X509Certificate[] certs, String authType){}
102         }};
103
104         // Install the all-trusting trust manager
105         try {
106             SSLContext sc = SSLContext.getInstance("TLS");
107             sc.init(null, trustAllCerts, new SecureRandom());
108             HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
109         } catch (Exception e) {
110             ;
111         }
112     }
113
114     void testIt(String https_url, String keyStoreName, String keyStorePassword){
115
116         LOG.info("Message to: {} begin.", https_url);
117
118         if (https_url.equals("off")) {
119             LOG.info("Function switched off");
120             return;
121         }
122
123         /*
124         KeyManagerFactory keyManagerFactory = null;
125
126         try {
127             KeyStore ks = KeyStore.getInstance("JKS");
128             FileInputStream in = new FileInputStream(keyStoreName);
129             ks.load(in, keyStorePassword.toCharArray());
130
131             CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
132             FileInputStream in2 = new FileInputStream("etc/eventprovider.cert");
133             X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in2);
134
135             KeyStore.Entry newEntry = new KeyStore.TrustedCertificateEntry(cert);
136             ks.setEntry("someAlias", newEntry, null);
137
138             keyManagerFactory = KeyManagerFactory.getInstance("X509");
139             keyManagerFactory.init(ks, "yourKeyStorePassword".toCharArray());
140
141         } catch (KeyStoreException e1) {
142             LOG.info("Exception: {}", e1.getMessage());
143         } catch (FileNotFoundException e1) {
144             LOG.info("Exception: {}", e1.getMessage());
145         } catch (NoSuchAlgorithmException e1) {
146             LOG.info("Exception: {}", e1.getMessage());
147         } catch (CertificateException e1) {
148             LOG.info("Exception: {}", e1.getMessage());
149         } catch (IOException e1) {
150             LOG.info("Exception: {}", e1.getMessage());
151         } catch (UnrecoverableKeyException e1) {
152             LOG.info("Exception: {}", e1.getMessage());
153         }
154
155         // Create a trust manager that does not validate certificate chains
156         TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
157             @Override
158             public X509Certificate[] getAcceptedIssuers(){return null;}
159             @Override
160             public void checkClientTrusted(X509Certificate[] certs, String authType){}
161             @Override
162             public void checkServerTrusted(X509Certificate[] certs, String authType){}
163         }};
164          */
165         File file = new File(keyStoreName);
166         LOG.info("Setup keystore begin "+keyStoreName+" "+keyStorePassword+" Exists: "+file.exists());
167
168         System.setProperty("javax.net.debug","ssl");
169         System.setProperty("javax.net.ssl.keyStoreType", "jks");
170         System.setProperty("javax.net.ssl.keyStore", keyStoreName);
171         System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);
172
173         LOG.info("Setup keystore complete");
174
175         javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
176                 (hostname, sslSession) -> {
177                  LOG.info("Hostname check {}", hostname);
178                  return true;
179               });
180         LOG.info("Setup name verifier.");
181
182         try {
183             /*
184             SSLContext sslContext = SSLContext.getInstance("TLS");
185             sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, null);
186             SSLContext.setDefault(sslContext);
187             */
188
189             URL url = new URL(https_url);
190             LOG.info("Url object created");
191
192             HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
193
194             LOG.info("openConnection");
195
196             //dumpl all cert info
197             print_https_cert(con);
198
199             //dump all the content
200             print_content(con);
201
202         } catch (MalformedURLException e) {
203             LOG.info("Exception: {}", e.getMessage());
204         } catch (IOException e) {
205             LOG.info("Exception: {}", e.getMessage());
206         }
207
208         LOG.info("Message to: {} end.", https_url);
209
210     }
211
212     private void print_https_cert(HttpsURLConnection con){
213
214         StringBuffer logMsg = new StringBuffer();
215
216         if(con!=null){
217
218             try {
219                 logMsg.append("Response Code : " + con.getResponseCode());
220                 logMsg.append("Cipher Suite : " + con.getCipherSuite());
221                 logMsg.append("\n");
222
223                 Certificate[] certs = con.getServerCertificates();
224                 for(Certificate cert : certs){
225                     logMsg.append("Cert Type : " + cert.getType());
226                     logMsg.append("Cert Hash Code : " + cert.hashCode());
227                     logMsg.append("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
228                     logMsg.append("Cert Public Key Format : " + cert.getPublicKey().getFormat());
229                     logMsg.append("\n");
230                 }
231
232
233             } catch (SSLPeerUnverifiedException e) {
234                 logMsg.append(e.getMessage());
235             } catch (IOException e){
236                 logMsg.append(e.getMessage());
237             }
238         } else {
239             logMsg.append("No connection");
240         }
241
242         LOG.info(logMsg.toString());
243    }
244
245     private void print_content(HttpsURLConnection con){
246
247          StringBuffer logMsg = new StringBuffer();
248          if(con!=null){
249
250             try {
251
252
253                 logMsg.append("****** Content of the URL ********");
254                 BufferedReader br =
255                         new BufferedReader(
256                                 new InputStreamReader(con.getInputStream()));
257
258                 String input;
259
260                 while ((input = br.readLine()) != null){
261                     logMsg.append(input);
262                 }
263                 br.close();
264
265
266             } catch (IOException e) {
267                 logMsg.append(e.getMessage());
268             }
269
270         } else {
271             logMsg.append("No connection");
272         }
273
274         LOG.info(logMsg.toString());
275
276     }
277
278     private static class MyLogger {
279
280         private void out( String s, Object...oList) {
281             StringBuffer sb = new StringBuffer();
282             sb.append("-------> ");
283             sb.append(s);
284             sb.append(" P: ");
285             int t = 0;
286             for (Object o: oList) {
287                 sb.append("[");
288                 sb.append(t++);
289                 sb.append("](");
290                 sb.append(o.toString());
291                 sb.append(")");
292             }
293             System.out.println(sb.toString());
294         }
295
296         void info( String s, Object...o) {
297             out(s,o);
298         }
299
300         static MyLogger getLogger(Class<?> c) {
301             return new MyLogger();
302         }
303     }
304 }