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.openecomp.sparky.util;
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) {
100 * @see java.lang.Object#toString()
103 public String toString() {
104 return "EndPoint [hostname=" + hostname + ", port=" + port + "]";
109 private List<EndPoint> endpoints = new ArrayList<EndPoint>();
112 * Initialize end points list.
114 * @param endpointList the endpoint list
116 private void initializeEndPointsList(String endpointList) {
117 String[] endpointUris = endpointList.split(";");
119 for (String endpointUri : endpointUris) {
121 String ipAndPort = endpointUri.replaceAll("http://", "");
122 ipAndPort = endpointUri.replaceAll("https://", "");
124 // System.out.println("ipAndPortUrl = " + ipAndPort);
126 String[] hostAndPort = ipAndPort.split(":");
128 String hostname = hostAndPort[0];
129 int port = Integer.parseInt(hostAndPort[1]);
131 EndPoint ep = new EndPoint(hostname, port);
138 * Instantiates a new keystore builder.
140 * @param endpointList the endpoint list
141 * @throws NoSuchAlgorithmException the no such algorithm exception
143 public KeystoreBuilder(String endpointList) throws NoSuchAlgorithmException {
144 initializeEndPointsList(endpointList);
145 sha1 = MessageDigest.getInstance("SHA1");
146 md5 = MessageDigest.getInstance("MD5");
149 private static final String SEP = File.separator;
150 private SavingTrustManager savingTrustManager;
151 private SSLSocketFactory sslSocketFactory;
152 private MessageDigest sha1;
153 private MessageDigest md5;
155 private String keystoreFileName;
156 private String keystorePassword;
157 private boolean dumpCertDetails = false;
159 public void setDumpCertDetails(boolean shouldSet) {
160 dumpCertDetails = shouldSet;
166 * @param keystoreFileName the keystore file name
167 * @param keystorePassword the keystore password
168 * @throws KeyStoreException the key store exception
169 * @throws NoSuchAlgorithmException the no such algorithm exception
170 * @throws CertificateException the certificate exception
171 * @throws IOException Signals that an I/O exception has occurred.
172 * @throws KeyManagementException the key management exception
174 public void updateKeystore(String keystoreFileName, String keystorePassword)
175 throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
176 KeyManagementException {
178 this.keystoreFileName = keystoreFileName;
179 this.keystorePassword = keystorePassword;
181 File file = new File(keystoreFileName);
182 String password = keystorePassword;
184 if (file.isFile() == false) {
186 File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
187 file = new File(dir, "jssecacerts");
188 if (file.isFile() == false) {
190 file = new File(dir, "cacerts");
191 System.out.println("keystore file doesn't exist, preloading new file with cacerts");
194 System.out.println("keystore file doesn't exist, preloading new file with jssecacerts");
196 password = "changeit";
200 InputStream in = new FileInputStream(file);
201 ks = KeyStore.getInstance(KeyStore.getDefaultType());
202 ks.load(in, password.toCharArray());
205 SSLContext context = SSLContext.getInstance("TLS");
206 TrustManagerFactory tmf =
207 TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
209 X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
210 savingTrustManager = new SavingTrustManager(defaultTrustManager);
211 context.init(null, new TrustManager[] {savingTrustManager}, null);
212 sslSocketFactory = context.getSocketFactory();
214 System.out.println("About to add the following endpoint server certificates to the keystore:");
215 for (EndPoint ep : endpoints) {
216 System.out.println("\t--------------------------");
217 System.out.println("\t" + ep.toString());
219 X509Certificate[] certChain =
220 getCertificateChainForRemoteEndpoint(ep.getHostname(), ep.getPort());
222 if (certChain == null) {
223 System.out.println("Could not obtain server certificate chain");
227 dumpCertChainInfo(certChain);
229 updateKeyStoreWithCertChain(certChain);
236 * Gets the certificate chain for remote endpoint.
238 * @param hostname the hostname
239 * @param port the port
240 * @return the certificate chain for remote endpoint
241 * @throws UnknownHostException the unknown host exception
242 * @throws IOException Signals that an I/O exception has occurred.
244 private X509Certificate[] getCertificateChainForRemoteEndpoint(String hostname, int port)
245 throws UnknownHostException, IOException {
247 System.out.println("Opening connection to "+hostname+":"+port+"..");
248 SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(hostname, port);
249 socket.setSoTimeout(10000);
252 System.out.println("Starting SSL handshake...");
253 socket.startHandshake();
255 System.out.println("\nNo errors, certificate is already trusted");
257 } catch (SSLException exc) {
258 System.out.println("\nCaught SSL exception, we are not authorized to access this server yet");
259 // e.printStackTrace(System.out);
262 return savingTrustManager.chain;
267 * Dump cert chain info.
269 * @param chain the chain
270 * @throws NoSuchAlgorithmException the no such algorithm exception
271 * @throws CertificateEncodingException the certificate encoding exception
272 * @throws CertificateParsingException the certificate parsing exception
274 private void dumpCertChainInfo(X509Certificate[] chain)
275 throws NoSuchAlgorithmException, CertificateEncodingException, CertificateParsingException {
277 System.out.println();
278 System.out.println("Server sent " + chain.length + " certificate(s):");
279 System.out.println();
281 for (int i = 0; i < chain.length; i++) {
282 X509Certificate cert = chain[i];
284 if (dumpCertDetails) {
285 System.out.println("Full cert details @ index = " + i + " \n" + cert.toString());
288 System.out.println("Subject: " + cert.getSubjectDN());
289 System.out.println("Issuer: " + cert.getIssuerDN());
290 System.out.println("SubjectAlternativeNames: ");
293 * RFC-5280, pg. 38, section 4.2.1.6 ( Subject Alternative Names )
295 * Finally, the semantics of subject alternative names that include wildcard characters (e.g.,
296 * as a placeholder for a set of names) are not addressed by this specification. Applications
297 * with specific requirements MAY use such names, but they must define the semantics.
299 * id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 }
301 * SubjectAltName ::= GeneralNames
303 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
305 * GeneralName ::= CHOICE { otherName [0] OtherName, rfc822Name [1] IA5String, dNSName [2]
306 * IA5String, <-- the 2 in the output is a type operand x400Address [3] ORAddress,
307 * directoryName [4] Name, ediPartyName [5] EDIPartyName, uniformResourceIdentifier [6]
308 * IA5String, iPAddress [7] OCTET STRING, registeredID [8] OBJECT IDENTIFIER }
310 * OtherName ::= SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY DEFINED BY
313 * EDIPartyName ::= SEQUENCE { nameAssigner [0] DirectoryString OPTIONAL, partyName [1]
318 Collection<List<?>> sans = cert.getSubjectAlternativeNames();
320 for (List<?> san : sans) {
323 * It seems the structure of the array elements contained within the SAN is: [<sanType>,
328 int type = ((Integer) san.get(0)).intValue();
329 String typeStr = getSanType(type);
330 String value = (String) san.get(1);
332 System.out.println(String.format("\tType:'%s', Value: '%s'.", typeStr, value));
341 * Gets the subject alternative names.
343 * @param cert the cert
344 * @return the subject alternative names
345 * @throws CertificateParsingException the certificate parsing exception
347 private List<String> getSubjectAlternativeNames(X509Certificate cert)
348 throws CertificateParsingException {
350 Collection<List<?>> sans = cert.getSubjectAlternativeNames();
351 List<String> subjectAlternativeNames = new ArrayList<String>();
353 for (List<?> san : sans) {
356 * It seems the structure of the array elements contained within the SAN is: [<sanType>,
361 String value = (String) san.get(1);
362 subjectAlternativeNames.add(value);
365 return subjectAlternativeNames;
369 * Update key store with cert chain.
371 * @param chain the chain
372 * @throws NoSuchAlgorithmException the no such algorithm exception
373 * @throws KeyStoreException the key store exception
374 * @throws CertificateException the certificate exception
375 * @throws IOException Signals that an I/O exception has occurred.
377 private void updateKeyStoreWithCertChain(X509Certificate[] chain)
378 throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
380 for (X509Certificate cert : chain) {
382 List<String> sans = getSubjectAlternativeNames(cert);
384 for (String san : sans) {
385 ks.setCertificateEntry(san, cert);
387 "Added certificate to keystore '" + keystoreFileName + "' using alias '" + san + "'");
391 OutputStream out = new FileOutputStream(keystoreFileName);
392 ks.store(out, keystorePassword.toCharArray());
399 * The Class SavingTrustManager.
401 private static class SavingTrustManager implements X509TrustManager {
403 private final X509TrustManager tm;
404 private X509Certificate[] chain;
407 * Instantiates a new saving trust manager.
411 SavingTrustManager(X509TrustManager tm) {
416 public X509Certificate[] getAcceptedIssuers() {
417 throw new UnsupportedOperationException();
421 * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String)
424 public void checkClientTrusted(X509Certificate[] chain, String authType)
425 throws CertificateException {
426 throw new UnsupportedOperationException();
430 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String)
433 public void checkServerTrusted(X509Certificate[] chain, String authType)
434 throws CertificateException {
436 tm.checkServerTrusted(chain, authType);
440 private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
445 * @param type the type
446 * @return the san type
448 // TODO: convert to enum(int,string)
449 private String getSanType(int type) {
458 return "x400Address";
460 return "directoryName";
462 return "ediPartyName";
464 return "uniformResourceIdentifier";
468 return "registeredID";
470 return "unknownSanType";
478 * @param bytes the bytes
481 private static String toHexString(byte[] bytes) {
482 StringBuilder sb = new StringBuilder(bytes.length * 3);
483 for (int b : bytes) {
485 sb.append(HEXDIGITS[b >> 4]);
486 sb.append(HEXDIGITS[b & 15]);
489 return sb.toString();
497 * @param args the arguments
498 * @throws Exception the exception
500 public static void main(String[] args) throws Exception {
503 * Examples: localhost:8440;localhost:8442 d:\1\adhoc_keystore.jks aaiDomain2 false
504 * localhost:8440;localhost:8442 d:\1\adhoc_keystore.jks aaiDomain2 true
507 if (args.length != 4) {
509 "Usage: KeyBuilder <[ip:port];*> <keystoreFileName>"
510 + " <keystorePassword> <dumpCertDetails> ");
513 KeystoreBuilder kb = new KeystoreBuilder(args[0]);
514 kb.setDumpCertDetails(Boolean.parseBoolean(args[3]));
515 kb.updateKeystore(args[1], args[2]);