View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.internal.test.util.http;
20  
21  import javax.net.ssl.KeyManagerFactory;
22  import javax.net.ssl.SSLContext;
23  import javax.net.ssl.TrustManagerFactory;
24  
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.io.UncheckedIOException;
28  import java.nio.file.Files;
29  import java.nio.file.Path;
30  import java.nio.file.Paths;
31  import java.nio.file.StandardCopyOption;
32  import java.security.KeyStore;
33  import java.util.Enumeration;
34  
35  /**
36   * Key and trust material shared by {@link HttpTransporterTest} and {@link HttpServer}: the stores are copied from the
37   * test resources into the build directory, where the server reads them, and the client side gets an
38   * {@link SSLContext} that trusts them.
39   */
40  public final class SslTestSupport {
41      public static final Path SERVER_STORE_PATH = Paths.get("target/server-store");
42      public static final Path CLIENT_STORE_PATH = Paths.get("target/client-store");
43      public static final Path PEM_QUICHE_SERVER_PATH = Paths.get("target/pems");
44  
45      private SslTestSupport() {}
46  
47      /**
48       * Copies the server and client stores from the test resources to {@link #SERVER_STORE_PATH} and
49       * {@link #CLIENT_STORE_PATH}, and creates {@link #PEM_QUICHE_SERVER_PATH}.
50       */
51      public static void installKeyStores() {
52          try {
53              try (InputStream keyStoreStream =
54                              SslTestSupport.class.getClassLoader().getResourceAsStream("ssl/server-store");
55                      InputStream trustStoreStream =
56                              SslTestSupport.class.getClassLoader().getResourceAsStream("ssl/client-store"); ) {
57                  Files.copy(keyStoreStream, SERVER_STORE_PATH, StandardCopyOption.REPLACE_EXISTING);
58                  Files.copy(trustStoreStream, CLIENT_STORE_PATH, StandardCopyOption.REPLACE_EXISTING);
59                  Files.createDirectories(PEM_QUICHE_SERVER_PATH);
60              }
61          } catch (IOException e) {
62              throw new UncheckedIOException(e);
63          }
64      }
65  
66      /**
67       * Creates an {@link SSLContext} for the client that extends the default keystore and truststore with the entries
68       * from {@link #SERVER_STORE_PATH} (password {@code "server-pwd"}) and {@link #CLIENT_STORE_PATH}
69       * (password {@code "client-pwd"}).
70       *
71       * @return an {@link SSLContext} combining default and custom key/trust material
72       */
73      public static SSLContext createClientSSLContext() {
74          try {
75              // Load custom key store (KEY_STORE_PATH acts as truststore in "cross connected" setup)
76              KeyStore customTrustStore = KeyStore.getInstance("pkcs12");
77              try (InputStream is = Files.newInputStream(SERVER_STORE_PATH)) {
78                  customTrustStore.load(is, "server-pwd".toCharArray());
79              }
80  
81              // Load custom trust store (TRUST_STORE_PATH acts as keystore in "cross connected" setup)
82              KeyStore customKeyStore = KeyStore.getInstance("pkcs12");
83              try (InputStream is = Files.newInputStream(CLIENT_STORE_PATH)) {
84                  customKeyStore.load(is, "client-pwd".toCharArray());
85              }
86  
87              // Load default truststore and merge custom entries
88              KeyStore defaultTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
89              Path defaultTrustStorePath = Path.of(System.getProperty("java.home"), "lib", "security", "cacerts");
90              if (Files.exists(defaultTrustStorePath)) {
91                  try (InputStream is = Files.newInputStream(defaultTrustStorePath)) {
92                      defaultTrustStore.load(is, "changeit".toCharArray());
93                  }
94              } else {
95                  defaultTrustStore.load(null, null);
96              }
97              Enumeration<String> aliases = customTrustStore.aliases();
98              while (aliases.hasMoreElements()) {
99                  String alias = aliases.nextElement();
100                 defaultTrustStore.setCertificateEntry("custom-trust-" + alias, customTrustStore.getCertificate(alias));
101             }
102 
103             // Load default keystore and merge custom entries
104             KeyStore mergedKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
105             mergedKeyStore.load(null, null);
106             Enumeration<String> keyAliases = customKeyStore.aliases();
107             while (keyAliases.hasMoreElements()) {
108                 String alias = keyAliases.nextElement();
109                 if (customKeyStore.isKeyEntry(alias)) {
110                     mergedKeyStore.setKeyEntry(
111                             alias,
112                             customKeyStore.getKey(alias, "client-pwd".toCharArray()),
113                             "client-pwd".toCharArray(),
114                             customKeyStore.getCertificateChain(alias));
115                 } else {
116                     mergedKeyStore.setCertificateEntry(alias, customKeyStore.getCertificate(alias));
117                 }
118             }
119 
120             TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
121             tmf.init(defaultTrustStore);
122 
123             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
124             kmf.init(mergedKeyStore, "client-pwd".toCharArray());
125 
126             SSLContext sslContext = SSLContext.getInstance("TLS");
127             sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
128             return sslContext;
129         } catch (Exception e) {
130             throw new RuntimeException("Failed to create SSLContext", e);
131         }
132     }
133 }