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;
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 * Initialize end points list.
116 * @param endpointList the endpoint list
118 private void initializeEndPointsList(String endpointList) {
119 String[] endpointUris = endpointList.split(";");
121 for (String endpointUri : endpointUris) {
123 String ipAndPort = endpointUri.replaceAll("http://", "");
124 ipAndPort = endpointUri.replaceAll("https://", "");
126 // System.out.println("ipAndPortUrl = " + ipAndPort);
128 String[] hostAndPort = ipAndPort.split(":");
130 String hostname = hostAndPort[0];
131 int port = Integer.parseInt(hostAndPort[1]);
133 EndPoint ep = new EndPoint(hostname, port);
140 * Instantiates a new keystore builder.
142 * @param endpointList the endpoint list
143 * @throws NoSuchAlgorithmException the no such algorithm exception
145 public KeystoreBuilder(String endpointList) throws NoSuchAlgorithmException {
146 initializeEndPointsList(endpointList);
147 sha1 = MessageDigest.getInstance("SHA1");
148 md5 = MessageDigest.getInstance("MD5");
151 private static final String SEP = File.separator;
152 private SavingTrustManager savingTrustManager;
153 private SSLSocketFactory sslSocketFactory;
154 private MessageDigest sha1;
155 private MessageDigest md5;
157 private String keystoreFileName;
158 private String keystorePassword;
159 private boolean dumpCertDetails = false;
161 public void setDumpCertDetails(boolean shouldSet) {
162 dumpCertDetails = shouldSet;
168 * @param keystoreFileName the keystore file name
169 * @param keystorePassword the keystore password
170 * @throws KeyStoreException the key store exception
171 * @throws NoSuchAlgorithmException the no such algorithm exception
172 * @throws CertificateException the certificate exception
173 * @throws IOException Signals that an I/O exception has occurred.
174 * @throws KeyManagementException the key management exception
176 public void updateKeystore(String keystoreFileName, String keystorePassword)
177 throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
178 KeyManagementException {
180 this.keystoreFileName = keystoreFileName;
181 this.keystorePassword = keystorePassword;
183 File file = new File(keystoreFileName);
184 String password = keystorePassword;
186 if (file.isFile() == false) {
188 File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
189 file = new File(dir, "jssecacerts");
190 if (file.isFile() == false) {
192 file = new File(dir, "cacerts");
193 System.out.println("keystore file doesn't exist, preloading new file with cacerts");
196 System.out.println("keystore file doesn't exist, preloading new file with jssecacerts");
198 password = "changeit";
202 InputStream in = new FileInputStream(file);
203 ks = KeyStore.getInstance(KeyStore.getDefaultType());
204 ks.load(in, password.toCharArray());
207 SSLContext context = SSLContext.getInstance("TLS");
208 TrustManagerFactory tmf =
209 TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
211 X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
212 savingTrustManager = new SavingTrustManager(defaultTrustManager);
213 context.init(null, new TrustManager[] {savingTrustManager}, null);
214 sslSocketFactory = context.getSocketFactory();
216 System.out.println("About to add the following endpoint server certificates to the keystore:");
217 for (EndPoint ep : endpoints) {
218 System.out.println("\t--------------------------");
219 System.out.println("\t" + ep.toString());
221 X509Certificate[] certChain =
222 getCertificateChainForRemoteEndpoint(ep.getHostname(), ep.getPort());
224 if (certChain == null) {
225 System.out.println("Could not obtain server certificate chain");
229 dumpCertChainInfo(certChain);
231 updateKeyStoreWithCertChain(certChain);
238 * Gets the certificate chain for remote endpoint.
240 * @param hostname the hostname
241 * @param port the port
242 * @return the certificate chain for remote endpoint
243 * @throws UnknownHostException the unknown host exception
244 * @throws IOException Signals that an I/O exception has occurred.
246 private X509Certificate[] getCertificateChainForRemoteEndpoint(String hostname, int port)
247 throws UnknownHostException, IOException {
249 System.out.println("Opening connection to localhost:8442..");
250 SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket("aai-int1.dev.att.com", 8440);
251 socket.setSoTimeout(10000);
254 System.out.println("Starting SSL handshake...");
255 socket.startHandshake();
257 System.out.println("\nNo errors, certificate is already trusted");
259 } catch (SSLException exc) {
260 System.out.println("\nCaught SSL exception, we are not authorized to access this server yet");
261 // e.printStackTrace(System.out);
264 return savingTrustManager.chain;
269 * Dump cert chain info.
271 * @param chain the chain
272 * @throws NoSuchAlgorithmException the no such algorithm exception
273 * @throws CertificateEncodingException the certificate encoding exception
274 * @throws CertificateParsingException the certificate parsing exception
276 private void dumpCertChainInfo(X509Certificate[] chain)
277 throws NoSuchAlgorithmException, CertificateEncodingException, CertificateParsingException {
279 System.out.println();
280 System.out.println("Server sent " + chain.length + " certificate(s):");
281 System.out.println();
283 for (int i = 0; i < chain.length; i++) {
284 X509Certificate cert = chain[i];
286 if (dumpCertDetails) {
287 System.out.println("Full cert details @ index = " + i + " \n" + cert.toString());
290 System.out.println("Subject: " + cert.getSubjectDN());
291 System.out.println("Issuer: " + cert.getIssuerDN());
292 System.out.println("SubjectAlternativeNames: ");
295 * RFC-5280, pg. 38, section 4.2.1.6 ( Subject Alternative Names )
297 * Finally, the semantics of subject alternative names that include wildcard characters (e.g.,
298 * as a placeholder for a set of names) are not addressed by this specification. Applications
299 * with specific requirements MAY use such names, but they must define the semantics.
301 * id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 }
303 * SubjectAltName ::= GeneralNames
305 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
307 * GeneralName ::= CHOICE { otherName [0] OtherName, rfc822Name [1] IA5String, dNSName [2]
308 * IA5String, <-- the 2 in the output is a type operand x400Address [3] ORAddress,
309 * directoryName [4] Name, ediPartyName [5] EDIPartyName, uniformResourceIdentifier [6]
310 * IA5String, iPAddress [7] OCTET STRING, registeredID [8] OBJECT IDENTIFIER }
312 * OtherName ::= SEQUENCE { type-id OBJECT IDENTIFIER, value [0] EXPLICIT ANY DEFINED BY
315 * EDIPartyName ::= SEQUENCE { nameAssigner [0] DirectoryString OPTIONAL, partyName [1]
320 Collection<List<?>> sans = cert.getSubjectAlternativeNames();
322 for (List<?> san : sans) {
325 * It seems the structure of the array elements contained within the SAN is: [<sanType>,
330 int type = ((Integer) san.get(0)).intValue();
331 String typeStr = getSanType(type);
332 String value = (String) san.get(1);
334 System.out.println(String.format("\tType:'%s', Value: '%s'.", typeStr, value));
343 * Gets the subject alternative names.
345 * @param cert the cert
346 * @return the subject alternative names
347 * @throws CertificateParsingException the certificate parsing exception
349 private List<String> getSubjectAlternativeNames(X509Certificate cert)
350 throws CertificateParsingException {
352 Collection<List<?>> sans = cert.getSubjectAlternativeNames();
353 List<String> subjectAlternativeNames = new ArrayList<String>();
355 for (List<?> san : sans) {
358 * It seems the structure of the array elements contained within the SAN is: [<sanType>,
363 String value = (String) san.get(1);
364 subjectAlternativeNames.add(value);
367 return subjectAlternativeNames;
371 * Update key store with cert chain.
373 * @param chain the chain
374 * @throws NoSuchAlgorithmException the no such algorithm exception
375 * @throws KeyStoreException the key store exception
376 * @throws CertificateException the certificate exception
377 * @throws IOException Signals that an I/O exception has occurred.
379 private void updateKeyStoreWithCertChain(X509Certificate[] chain)
380 throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
382 for (X509Certificate cert : chain) {
384 List<String> sans = getSubjectAlternativeNames(cert);
386 for (String san : sans) {
387 ks.setCertificateEntry(san, cert);
389 "Added certificate to keystore '" + keystoreFileName + "' using alias '" + san + "'");
393 OutputStream out = new FileOutputStream(keystoreFileName);
394 ks.store(out, keystorePassword.toCharArray());
401 * The Class SavingTrustManager.
403 private static class SavingTrustManager implements X509TrustManager {
405 private final X509TrustManager tm;
406 private X509Certificate[] chain;
409 * Instantiates a new saving trust manager.
413 SavingTrustManager(X509TrustManager tm) {
418 public X509Certificate[] getAcceptedIssuers() {
419 throw new UnsupportedOperationException();
425 * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[],
429 public void checkClientTrusted(X509Certificate[] chain, String authType)
430 throws CertificateException {
431 throw new UnsupportedOperationException();
437 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[],
441 public void checkServerTrusted(X509Certificate[] chain, String authType)
442 throws CertificateException {
444 tm.checkServerTrusted(chain, authType);
448 private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
453 * @param type the type
454 * @return the san type
456 // TODO: convert to enum(int,string)
457 private String getSanType(int type) {
466 return "x400Address";
468 return "directoryName";
470 return "ediPartyName";
472 return "uniformResourceIdentifier";
476 return "registeredID";
478 return "unknownSanType";
486 * @param bytes the bytes
489 private static String toHexString(byte[] bytes) {
490 StringBuilder sb = new StringBuilder(bytes.length * 3);
491 for (int b : bytes) {
493 sb.append(HEXDIGITS[b >> 4]);
494 sb.append(HEXDIGITS[b & 15]);
497 return sb.toString();
505 * @param args the arguments
506 * @throws Exception the exception
508 public static void main(String[] args) throws Exception {
510 // String endpointList = "aai-int1.test.att.com:8440;aai-int1.dev.att.com:8442";
513 * Examples: localhost:8440;localhost:8442 d:\1\adhoc_keystore.jks aaiDomain2 false
514 * localhost:8440;localhost:8442 d:\1\adhoc_keystore.jks aaiDomain2 true
517 if (args.length != 4) {
518 System.out.println("Usage: KeyBuilder <[ip:port];*> <keystoreFileName>"
519 + " <keystorePassword> <dumpCertDetails> ");
522 KeystoreBuilder kb = new KeystoreBuilder(args[0]);
523 kb.setDumpCertDetails(Boolean.parseBoolean(args[3]));
524 kb.updateKeystore(args[1], args[2]);