2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017 Amdocs
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.onap.aai.sparky.util.test;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.OutputStream;
31 import java.net.UnknownHostException;
32 import java.security.KeyManagementException;
33 import java.security.KeyStore;
34 import java.security.KeyStoreException;
35 import java.security.MessageDigest;
36 import java.security.NoSuchAlgorithmException;
37 import java.security.cert.CertificateEncodingException;
38 import java.security.cert.CertificateException;
39 import java.security.cert.CertificateParsingException;
40 import java.security.cert.X509Certificate;
41 import java.util.ArrayList;
42 import java.util.Collection;
43 import java.util.List;
45 import javax.net.ssl.SSLContext;
46 import javax.net.ssl.SSLException;
47 import javax.net.ssl.SSLSocket;
48 import javax.net.ssl.SSLSocketFactory;
49 import javax.net.ssl.TrustManager;
50 import javax.net.ssl.TrustManagerFactory;
51 import javax.net.ssl.X509TrustManager;
54 * The Class KeystoreBuilder.
56 public class KeystoreBuilder {
61 private class EndPoint {
62 private String hostname;
66 * Instantiates a new end point.
68 @SuppressWarnings("unused")
72 * Instantiates a new end point.
74 * @param host the host
75 * @param port the port
77 public EndPoint(String host, int port) {
82 public String getHostname() {
86 @SuppressWarnings("unused")
87 public void setHostname(String hostname) {
88 this.hostname = hostname;
91 public int getPort() {
95 public void setPort(int port) {
102 * @see java.lang.Object#toString()
105 public String toString() {
106 return "EndPoint [hostname=" + hostname + ", port=" + port + "]";
111 private List<EndPoint> endpoints = new ArrayList<EndPoint>();
114 * @return the endpoints
116 public List<EndPoint> getEndpoints() {
121 * @param endpoints the endpoints to set
123 public void setEndpoints(List<EndPoint> endpoints) {
124 this.endpoints = endpoints;
128 * Initialize end points list.
130 * @param endpointList the endpoint list
132 private void initializeEndPointsList(String endpointList) {
133 String[] endpointUris = endpointList.split(";");
135 for (String endpointUri : endpointUris) {
137 String ipAndPort = endpointUri.replaceAll("http://", "");
138 ipAndPort = endpointUri.replaceAll("https://", "");
140 // System.out.println("ipAndPortUrl = " + ipAndPort);
142 String[] hostAndPort = ipAndPort.split(":");
144 String hostname = hostAndPort[0];
145 int port = Integer.parseInt(hostAndPort[1]);
147 EndPoint ep = new EndPoint(hostname, port);
154 * Instantiates a new keystore builder.
156 * @param endpointList the endpoint list
157 * @throws NoSuchAlgorithmException the no such algorithm exception
159 public KeystoreBuilder(String endpointList) throws NoSuchAlgorithmException {
160 initializeEndPointsList(endpointList);
161 sha1 = MessageDigest.getInstance("SHA1");
162 md5 = MessageDigest.getInstance("MD5");
165 private static final String SEP = File.separator;
166 private SavingTrustManager savingTrustManager;
167 private SSLSocketFactory sslSocketFactory;
168 private MessageDigest sha1;
169 private MessageDigest md5;
171 private String keystoreFileName;
172 private String keystorePassword;
173 private boolean dumpCertDetails = false;
175 public void setDumpCertDetails(boolean shouldSet) {
176 dumpCertDetails = shouldSet;
182 * @param keystoreFileName the keystore file name
183 * @param keystorePassword the keystore password
184 * @throws KeyStoreException the key store exception
185 * @throws NoSuchAlgorithmException the no such algorithm exception
186 * @throws CertificateException the certificate exception
187 * @throws IOException Signals that an I/O exception has occurred.
188 * @throws KeyManagementException the key management exception
190 public void updateKeystore(String keystoreFileName, String keystorePassword)
191 throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
192 KeyManagementException {
194 this.keystoreFileName = keystoreFileName;
195 this.keystorePassword = keystorePassword;
197 File file = new File(keystoreFileName);
198 String password = keystorePassword;
200 if (file.isFile() == false) {
202 File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
203 file = new File(dir, "jssecacerts");
204 if (file.isFile() == false) {
206 file = new File(dir, "cacerts");
207 System.out.println("keystore file doesn't exist, preloading new file with cacerts");
210 System.out.println("keystore file doesn't exist, preloading new file with jssecacerts");
212 password = "changeit";
216 InputStream in = new FileInputStream(file);
217 ks = KeyStore.getInstance(KeyStore.getDefaultType());
218 ks.load(in, password.toCharArray());
221 SSLContext context = SSLContext.getInstance("TLS");
222 TrustManagerFactory tmf =
223 TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
225 X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
226 savingTrustManager = new SavingTrustManager(defaultTrustManager);
227 context.init(null, new TrustManager[] {savingTrustManager}, null);
228 sslSocketFactory = context.getSocketFactory();
230 System.out.println("About to add the following endpoint server certificates to the keystore:");
231 for (EndPoint ep : endpoints) {
232 System.out.println("\t--------------------------");
233 System.out.println("\t" + ep.toString());
235 X509Certificate[] certChain =
236 getCertificateChainForRemoteEndpoint(ep.getHostname(), ep.getPort());
238 if (certChain == null) {
239 System.out.println("Could not obtain server certificate chain");
243 dumpCertChainInfo(certChain);
245 updateKeyStoreWithCertChain(certChain);
252 * Gets the certificate chain for remote endpoint.
254 * @param hostname the hostname
255 * @param port the port
256 * @return the certificate chain for remote endpoint
257 * @throws UnknownHostException the unknown host exception
258 * @throws IOException Signals that an I/O exception has occurred.
260 private X509Certificate[] getCertificateChainForRemoteEndpoint(String hostname, int port)
261 throws UnknownHostException, IOException {
263 System.out.println("Opening connection to " + hostname + ":" + port + "..");
264 SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(hostname, port);
265 socket.setSoTimeout(10000);
268 System.out.println("Starting SSL handshake...");
269 socket.startHandshake();
271 System.out.println("\nNo errors, certificate is already trusted");
273 } catch (SSLException exc) {
274 System.out.println("\nCaught SSL exception, we are not authorized to access this server yet");
275 // e.printStackTrace(System.out);
278 return savingTrustManager.chain;
283 * Dump cert chain info.
285 * @param chain the chain
286 * @throws NoSuchAlgorithmException the no such algorithm exception
287 * @throws CertificateEncodingException the certificate encoding exception
288 * @throws CertificateParsingException the certificate parsing exception
290 private void dumpCertChainInfo(X509Certificate[] chain)
291 throws NoSuchAlgorithmException, CertificateEncodingException, CertificateParsingException {
293 System.out.println();
294 System.out.println("Server sent " + chain.length + " certificate(s):");
295 System.out.println();
297 for (int i = 0; i < chain.length; i++) {
298 X509Certificate cert = chain[i];
300 if (dumpCertDetails) {
301 System.out.println("Full cert details @ index = " + i + " \n" + cert.toString());
304 System.out.println("Subject: " + cert.getSubjectDN());
305 System.out.println("Issuer: " + cert.getIssuerDN());
306 System.out.println("SubjectAlternativeNames: ");
309 * RFC-5280, pg. 38, section 4.2.1.6 ( Subject Alternative Names )
311 * Finally, the semantics of subject alternative names that include wildcard characters (e.g.,
312 * as a placeholder for a set of names) are not addressed by this specification. Applications
313 * with specific requirements MAY use such names, but they must define the semantics.
315 * id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 }
317 * SubjectAltName ::= GeneralNames
319 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
321 * GeneralName ::= CHOICE { otherName [0] OtherName, rfc822Name [1] IA5String, dNSName [2]
322 * IA5String, <-- the 2 in the output is a type operand x400Address [3] ORAddress,
323 * directoryName [4] Name, ediPartyName [5] EDIPartyName, uniformResourceIdentifier [6]
324 * IA5String, iPAddress [7] OCTET STRING, registeredID [8] OBJECT IDENTIFIER }
326 * OtherName ::= SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY DEFINED BY
329 * EDIPartyName ::= SEQUENCE { nameAssigner [0] DirectoryString OPTIONAL, partyName [1]
334 Collection<List<?>> sans = cert.getSubjectAlternativeNames();
336 for (List<?> san : sans) {
339 * It seems the structure of the array elements contained within the SAN is: [<sanType>,
344 int type = ((Integer) san.get(0)).intValue();
345 String typeStr = getSanType(type);
346 String value = (String) san.get(1);
348 System.out.println(String.format("\tType:'%s', Value: '%s'.", typeStr, value));
357 * Gets the subject alternative names.
359 * @param cert the cert
360 * @return the subject alternative names
361 * @throws CertificateParsingException the certificate parsing exception
363 private List<String> getSubjectAlternativeNames(X509Certificate cert)
364 throws CertificateParsingException {
366 Collection<List<?>> sans = cert.getSubjectAlternativeNames();
367 List<String> subjectAlternativeNames = new ArrayList<String>();
369 for (List<?> san : sans) {
372 * It seems the structure of the array elements contained within the SAN is: [<sanType>,
377 String value = (String) san.get(1);
378 subjectAlternativeNames.add(value);
381 return subjectAlternativeNames;
385 * Update key store with cert chain.
387 * @param chain the chain
388 * @throws NoSuchAlgorithmException the no such algorithm exception
389 * @throws KeyStoreException the key store exception
390 * @throws CertificateException the certificate exception
391 * @throws IOException Signals that an I/O exception has occurred.
393 private void updateKeyStoreWithCertChain(X509Certificate[] chain)
394 throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
396 for (X509Certificate cert : chain) {
398 List<String> sans = getSubjectAlternativeNames(cert);
400 for (String san : sans) {
401 ks.setCertificateEntry(san, cert);
403 "Added certificate to keystore '" + keystoreFileName + "' using alias '" + san + "'");
407 OutputStream out = new FileOutputStream(keystoreFileName);
408 ks.store(out, keystorePassword.toCharArray());
415 * The Class SavingTrustManager.
417 private static class SavingTrustManager implements X509TrustManager {
419 private final X509TrustManager tm;
420 private X509Certificate[] chain;
423 * Instantiates a new saving trust manager.
427 SavingTrustManager(X509TrustManager tm) {
432 public X509Certificate[] getAcceptedIssuers() {
433 throw new UnsupportedOperationException();
439 * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[],
443 public void checkClientTrusted(X509Certificate[] chain, String authType)
444 throws CertificateException {
445 throw new UnsupportedOperationException();
451 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[],
455 public void checkServerTrusted(X509Certificate[] chain, String authType)
456 throws CertificateException {
458 tm.checkServerTrusted(chain, authType);
462 private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
467 * @param type the type
468 * @return the san type
470 // TODO: convert to enum(int,string)
471 private String getSanType(int type) {
480 return "x400Address";
482 return "directoryName";
484 return "ediPartyName";
486 return "uniformResourceIdentifier";
490 return "registeredID";
492 return "unknownSanType";
500 * @param bytes the bytes
503 private static String toHexString(byte[] bytes) {
504 StringBuilder sb = new StringBuilder(bytes.length * 3);
505 for (int b : bytes) {
507 sb.append(HEXDIGITS[b >> 4]);
508 sb.append(HEXDIGITS[b & 15]);
511 return sb.toString();
519 * @param args the arguments
520 * @throws Exception the exception
522 public static void main(String[] args) throws Exception {
525 * Examples: localhost:8440;localhost:8442 d:\1\adhoc_keystore.jks aaiDomain2 false
526 * localhost:8440;localhost:8442 d:\1\adhoc_keystore.jks aaiDomain2 true
529 if (args.length != 4) {
530 System.out.println("Usage: KeyBuilder <[ip:port];*> <keystoreFileName>"
531 + " <keystorePassword> <dumpCertDetails> ");
534 KeystoreBuilder kb = new KeystoreBuilder(args[0]);
535 kb.setDumpCertDetails(Boolean.parseBoolean(args[3]));
536 kb.updateKeystore(args[1], args[2]);