View Javadoc
1   /*
2    * Copyright 2021 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty.handler.codec.quic;
18  
19  import io.netty.handler.ssl.ClientAuth;
20  import io.netty.handler.ssl.SessionIdContextBuilder;
21  import io.netty.handler.ssl.SslContextOption;
22  import io.netty.handler.ssl.util.KeyManagerFactoryWrapper;
23  import io.netty.handler.ssl.util.TrustManagerFactoryWrapper;
24  import io.netty.util.Mapping;
25  import io.netty.util.SecureObjectIdentityHash;
26  import org.jetbrains.annotations.Nullable;
27  
28  import javax.net.ssl.KeyManager;
29  import javax.net.ssl.KeyManagerFactory;
30  import javax.net.ssl.SSLEngine;
31  import javax.net.ssl.SSLParameters;
32  import javax.net.ssl.TrustManager;
33  import javax.net.ssl.TrustManagerFactory;
34  import javax.net.ssl.X509ExtendedKeyManager;
35  import java.io.File;
36  import java.net.Socket;
37  import java.nio.charset.StandardCharsets;
38  import java.security.KeyStore;
39  import java.security.Principal;
40  import java.security.PrivateKey;
41  import java.security.cert.X509Certificate;
42  import java.util.ArrayList;
43  import java.util.Arrays;
44  import java.util.HashMap;
45  import java.util.List;
46  import java.util.Map;
47  
48  import static io.netty.util.internal.ObjectUtil.checkNotNull;
49  
50  /**
51   * Builder for configuring a new SslContext for creation.
52   */
53  public final class QuicSslContextBuilder {
54  
55      /**
56       * Special {@link X509ExtendedKeyManager} implementation which will just fail the certificate selection.
57       * This is used as a "dummy" implementation when SNI is used as we should always select an other
58       * {@link QuicSslContext} based on the provided hostname.
59       */
60      private static final X509ExtendedKeyManager SNI_KEYMANAGER = new X509ExtendedKeyManager() {
61          private final X509Certificate[] emptyCerts = new X509Certificate[0];
62          private final String[] emptyStrings = new String[0];
63  
64          @Override
65          public String[] getClientAliases(String keyType, Principal[] issuers) {
66              return emptyStrings;
67          }
68  
69          @Override
70          @Nullable
71          public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
72              return null;
73          }
74  
75          @Override
76          public String[] getServerAliases(String keyType, Principal[] issuers) {
77              return emptyStrings;
78          }
79  
80          @Override
81          @Nullable
82          public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
83              return null;
84          }
85  
86          @Override
87          public X509Certificate[] getCertificateChain(String alias) {
88              return emptyCerts;
89          }
90  
91          @Override
92          @Nullable
93          public PrivateKey getPrivateKey(String alias) {
94              return null;
95          }
96      };
97  
98      /**
99       * Creates a builder for new client-side {@link QuicSslContext} that can be used for {@code QUIC}.
100      */
101     public static QuicSslContextBuilder forClient() {
102         return new QuicSslContextBuilder(false);
103     }
104 
105     /**
106      * Creates a builder for new server-side {@link QuicSslContext} that can be used for {@code QUIC}.
107      *
108      * @param keyFile a PKCS#8 private key file in PEM format
109      * @param keyPassword the password of the {@code keyFile}, or {@code null} if it's not
110      *     password-protected
111      * @param certChainFile an X.509 certificate chain file in PEM format
112      * @see #keyManager(File, String, File)
113      */
114     public static QuicSslContextBuilder forServer(
115             File keyFile, @Nullable String keyPassword, File certChainFile) {
116         return new QuicSslContextBuilder(true).keyManager(keyFile, keyPassword, certChainFile);
117     }
118 
119     /**
120      * Creates a builder for new server-side {@link QuicSslContext} that can be used for {@code QUIC}.
121      *
122      * @param key a PKCS#8 private key
123      * @param keyPassword the password of the {@code keyFile}, or {@code null} if it's not
124      *     password-protected
125      * @param certChain the X.509 certificate chain
126      * @see #keyManager(File, String, File)
127      */
128     public static QuicSslContextBuilder forServer(
129             PrivateKey key, @Nullable String keyPassword, X509Certificate... certChain) {
130         return new QuicSslContextBuilder(true).keyManager(key, keyPassword, certChain);
131     }
132 
133     /**
134      * Creates a builder for new server-side {@link QuicSslContext} that can be used for {@code QUIC}.
135      *
136      * @param keyManagerFactory non-{@code null} factory for server's private key
137      * @see #keyManager(KeyManagerFactory, String)
138      */
139     public static QuicSslContextBuilder forServer(KeyManagerFactory keyManagerFactory, @Nullable String password) {
140         return new QuicSslContextBuilder(true).keyManager(keyManagerFactory, password);
141     }
142 
143     /**
144      * Creates a builder for new server-side {@link QuicSslContext} with {@link KeyManager} that can be used for
145      * {@code QUIC}.
146      *
147      * @param keyManager non-{@code null} KeyManager for server's private key
148      * @param keyPassword the password of the {@code keyFile}, or {@code null} if it's not
149      *     password-protected
150      */
151     public static QuicSslContextBuilder forServer(KeyManager keyManager, @Nullable String keyPassword) {
152         return new QuicSslContextBuilder(true).keyManager(keyManager, keyPassword);
153     }
154 
155     /**
156      * Enables support for
157      * <a href="https://quicwg.org/ops-drafts/draft-ietf-quic-manageability.html#name-server-name-indication-sni">
158      *     SNI</a> on the server side.
159      *
160      * @param mapping   the {@link Mapping} that is used to map names to the {@link QuicSslContext} to use.
161      *                  Usually using {@link io.netty.util.DomainWildcardMappingBuilder} should be used
162      *                  to create the {@link Mapping}.
163      */
164     public static QuicSslContext buildForServerWithSni(Mapping<? super String, ? extends QuicSslContext> mapping) {
165         return forServer(SNI_KEYMANAGER, null).sni(mapping).build();
166     }
167 
168     private static final Map.Entry[] EMPTY_ENTRIES = new Map.Entry[0];
169     private static final byte[] SESSION_ID_CONTEXT_SEED =
170         "netty-server-session-id-context-v1".getBytes(StandardCharsets.ISO_8859_1);
171     private static final SecureObjectIdentityHash IDENTITY_HASHES = new SecureObjectIdentityHash();
172 
173     private final boolean forServer;
174     private final Map<SslContextOption<?>, Object> options = new HashMap<>();
175     private TrustManagerFactory trustManagerFactory;
176     // The certificates trustManagerFactory was built from, or null if it was not built from plain certificates.
177     private X509Certificate[] trustCertCollection;
178     private String keyPassword;
179     private KeyManagerFactory keyManagerFactory;
180     // The certificate chain keyManagerFactory was built from, or null if it was not built from a plain chain.
181     private X509Certificate[] keyCertChain;
182     private long sessionCacheSize = 20480;
183     private long sessionTimeout = 300;
184     private ClientAuth clientAuth = ClientAuth.NONE;
185     private String[] applicationProtocols;
186     private Boolean earlyData;
187     private BoringSSLKeylog keylog;
188     private Mapping<? super String, ? extends QuicSslContext> mapping;
189     private String endpointIdentificationAlgorithm;
190     private final SessionIdContextBuilder sessionIdContextBuilder = new SessionIdContextBuilder(IDENTITY_HASHES)
191         .setSeed(SESSION_ID_CONTEXT_SEED)
192         .setClientAuth(clientAuth);
193 
194     private QuicSslContextBuilder(boolean forServer) {
195         this.forServer = forServer;
196         if (!forServer) {
197              this.endpointIdentificationAlgorithm = QuicheQuicSslContext.defaultEndpointVerificationAlgorithm;
198         }
199     }
200 
201     /**
202      * Enables
203      * <a href="https://quicwg.org/ops-drafts/draft-ietf-quic-manageability.html#name-server-name-indication-sni">
204      *     SNI</a> support on the server side.
205      * <p>
206      * The provided {@link Mapping} receives the hostname from the client and returns the
207      * {@link QuicSslContext} to use for that connection. The returned context's settings
208      * (such as {@link #clientAuth(ClientAuth)}, {@link #trustManager(TrustManagerFactory)}, etc.)
209      * will be applied to the connection.
210      * <p>
211      * Use {@link io.netty.util.DomainWildcardMappingBuilder} to create the {@link Mapping} when
212      * matching against domain patterns is needed.
213      *
214      * @param mapping the {@link Mapping} that maps hostnames to {@link QuicSslContext} instances
215      * @return this builder
216      * @throws NullPointerException if {@code mapping} is {@code null}
217      */
218     public QuicSslContextBuilder sni(Mapping<? super String, ? extends QuicSslContext> mapping) {
219         if (!forServer) {
220             throw new UnsupportedOperationException("Only supported for server");
221         }
222         this.mapping = checkNotNull(mapping, "mapping");
223         return this;
224     }
225 
226     /**
227      * Configure a {@link SslContextOption}.
228      */
229     public <T> QuicSslContextBuilder option(SslContextOption<T> option, T value) {
230         if (value == null) {
231             options.remove(option);
232         } else {
233             options.put(option, value);
234         }
235         return this;
236     }
237 
238     /**
239      * Enable / disable the usage of early data.
240      * <p>
241      * Early data is never accepted by a server that is configured with {@link ClientAuth#REQUIRE}, independent of
242      * this setting, as the client certificate can not be verified before the handshake completed.
243      */
244     public QuicSslContextBuilder earlyData(boolean enabled) {
245         this.earlyData = enabled;
246         return this;
247     }
248 
249     /**
250      * Enable / disable keylog. When enabled, TLS keys are logged to an internal logger named
251      * "io.netty.handler.codec.quic.BoringSSLLogginKeylog" with DEBUG level, see
252      * {@link BoringSSLKeylog} for detail, logging keys are following
253      * <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format">
254      *     NSS Key Log Format</a>. This is intended for debugging use with tools like Wireshark.
255      */
256     public QuicSslContextBuilder keylog(boolean enabled) {
257         keylog(enabled ? BoringSSLLoggingKeylog.INSTANCE : null);
258         return this;
259     }
260 
261     /**
262      * Enable / disable keylog. When enabled, TLS keys are logged to {@link BoringSSLKeylog#logKey(SSLEngine, String)}
263      * logging keys are following
264      * <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format">
265      *     NSS Key Log Format</a>. This is intended for debugging use with tools like Wireshark.
266      */
267     public QuicSslContextBuilder keylog(@Nullable BoringSSLKeylog keylog) {
268         this.keylog = keylog;
269         return this;
270     }
271 
272     /**
273      * Trusted certificates for verifying the remote endpoint's certificate. The file should
274      * contain an X.509 certificate collection in PEM format. {@code null} uses the system default
275      * which only works with Java 8u261 and later as these versions support TLS1.3,
276      * see <a href="https://www.oracle.com/java/technologies/javase/8u261-relnotes.html">
277      *     JDK 8u261 Update Release Notes</a>
278      */
279     public QuicSslContextBuilder trustManager(@Nullable File trustCertCollectionFile) {
280         try {
281             return trustManager(QuicheQuicSslContext.toX509Certificates0(trustCertCollectionFile));
282         } catch (Exception e) {
283             throw new IllegalArgumentException("File does not contain valid certificates: "
284                     + trustCertCollectionFile, e);
285         }
286     }
287 
288     /**
289      * Trusted certificates for verifying the remote endpoint's certificate. {@code null} uses the system default
290      * which only works with Java 8u261 and later as these versions support TLS1.3,
291      * see <a href="https://www.oracle.com/java/technologies/javase/8u261-relnotes.html">
292      *     JDK 8u261 Update Release Notes</a>
293      */
294     public QuicSslContextBuilder trustManager(X509Certificate @Nullable ... trustCertCollection) {
295         try {
296             trustManager(QuicheQuicSslContext.buildTrustManagerFactory0(trustCertCollection));
297         } catch (Exception e) {
298             throw new IllegalArgumentException(e);
299         }
300         // Remember the certificates as (unlike a custom TrustManagerFactory) they can be used to tell if two
301         // contexts trust the same certificates. Needs to be done after the TrustManagerFactory was set as this
302         // forgets about them.
303         this.trustCertCollection = trustCertCollection == null ? null :
304             Arrays.copyOf(trustCertCollection, trustCertCollection.length);
305         sessionIdContextBuilder.setTrustedCertificates(this.trustCertCollection);
306         return this;
307     }
308 
309     /**
310      * Trusted manager for verifying the remote endpoint's certificate. {@code null} uses the system default
311      * which only works with Java 8u261 and later as these versions support TLS1.3,
312      * see <a href="https://www.oracle.com/java/technologies/javase/8u261-relnotes.html">
313      *     JDK 8u261 Update Release Notes</a>
314      */
315     public QuicSslContextBuilder trustManager(@Nullable TrustManagerFactory trustManagerFactory) {
316         this.trustManagerFactory = trustManagerFactory;
317         this.trustCertCollection = null;
318         sessionIdContextBuilder.setTrustManagerFactory(trustManagerFactory);
319         return this;
320     }
321 
322     /**
323      * A single trusted manager for verifying the remote endpoint's certificate.
324      * This is helpful when custom implementation of {@link TrustManager} is needed.
325      * Internally, a simple wrapper of {@link TrustManagerFactory} that only produces this
326      * specified {@link TrustManager} will be created, thus all the requirements specified in
327      * {@link #trustManager(TrustManagerFactory trustManagerFactory)} also apply here.
328      */
329     public QuicSslContextBuilder trustManager(TrustManager trustManager) {
330         trustManager(new TrustManagerFactoryWrapper(trustManager));
331         sessionIdContextBuilder.setTrustManager(trustManager);
332         return this;
333     }
334 
335     /**
336      * Identifying certificate for this host. {@code keyCertChainFile} and {@code keyFile} may
337      * be {@code null} for client contexts, which disables mutual authentication.
338      *
339      * @param keyFile a PKCS#8 private key file in PEM format
340      * @param keyPassword the password of the {@code keyFile}, or {@code null} if it's not
341      *     password-protected
342      * @param keyCertChainFile an X.509 certificate chain file in PEM format
343      */
344     public QuicSslContextBuilder keyManager(
345             @Nullable File keyFile, @Nullable String keyPassword, @Nullable File keyCertChainFile) {
346         X509Certificate[] keyCertChain;
347         PrivateKey key;
348         try {
349             keyCertChain = QuicheQuicSslContext.toX509Certificates0(keyCertChainFile);
350         } catch (Exception e) {
351             throw new IllegalArgumentException("File does not contain valid certificates: " + keyCertChainFile, e);
352         }
353         try {
354             key = QuicheQuicSslContext.toPrivateKey0(keyFile, keyPassword);
355         } catch (Exception e) {
356             throw new IllegalArgumentException("File does not contain valid private key: " + keyFile, e);
357         }
358         return keyManager(key, keyPassword, keyCertChain);
359     }
360 
361     /**
362      * Identifying certificate for this host. {@code keyCertChain} and {@code key} may
363      * be {@code null} for client contexts, which disables mutual authentication.
364      *
365      * @param key a PKCS#8 private key file
366      * @param keyPassword the password of the {@code key}, or {@code null} if it's not
367      *     password-protected
368      * @param certChain an X.509 certificate chain
369      */
370     public QuicSslContextBuilder keyManager(
371             @Nullable PrivateKey key, @Nullable String keyPassword, X509Certificate @Nullable ... certChain) {
372         try {
373             java.security.KeyStore ks = java.security.KeyStore.getInstance(KeyStore.getDefaultType());
374             ks.load(null);
375             char[] pass = keyPassword == null ? new char[0]: keyPassword.toCharArray();
376             ks.setKeyEntry("alias", key, pass, certChain);
377             KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
378                     KeyManagerFactory.getDefaultAlgorithm());
379             keyManagerFactory.init(ks, pass);
380             keyManager(keyManagerFactory, keyPassword);
381         } catch (Exception e) {
382             throw new IllegalArgumentException(e);
383         }
384         // Remember the chain as (unlike a custom KeyManagerFactory) it can be used to tell if two contexts present
385         // the same certificates. Needs to be done after the KeyManagerFactory was set as this forgets about it.
386         this.keyCertChain = certChain == null ? null : Arrays.copyOf(certChain, certChain.length);
387         sessionIdContextBuilder.setKeyCertificateChain(this.keyCertChain);
388         return this;
389     }
390 
391     /**
392      * Identifying manager for this host. {@code keyManagerFactory} may be {@code null} for
393      * client contexts, which disables mutual authentication.
394      */
395     public QuicSslContextBuilder keyManager(
396             @Nullable KeyManagerFactory keyManagerFactory, @Nullable String keyPassword) {
397         this.keyPassword = keyPassword;
398         this.keyManagerFactory = keyManagerFactory;
399         this.keyCertChain = null;
400         sessionIdContextBuilder.setKeyManagerFactory(keyManagerFactory);
401         return this;
402     }
403 
404     /**
405      * A single key manager managing the identity information of this host.
406      * This is helpful when custom implementation of {@link KeyManager} is needed.
407      * Internally, a wrapper of {@link KeyManagerFactory} that only produces this specified
408      * {@link KeyManager} will be created, thus all the requirements specified in
409      * {@link #keyManager(KeyManagerFactory, String)} also apply here.
410      */
411     public QuicSslContextBuilder keyManager(KeyManager keyManager, @Nullable String password) {
412         keyManager(new KeyManagerFactoryWrapper(keyManager), password);
413         sessionIdContextBuilder.setKeyManager(keyManager);
414         return this;
415     }
416 
417     /**
418      * Application protocol negotiation configuration. {@code null} disables support.
419      */
420     public QuicSslContextBuilder applicationProtocols(String @Nullable ... applicationProtocols) {
421         this.applicationProtocols = applicationProtocols == null ? null :
422             Arrays.copyOf(applicationProtocols, applicationProtocols.length);
423         return this;
424     }
425 
426     /**
427      * Set the size of the cache used for storing SSL session objects. {@code 0} to use the
428      * default value.
429      */
430     public QuicSslContextBuilder sessionCacheSize(long sessionCacheSize) {
431         this.sessionCacheSize = sessionCacheSize;
432         return this;
433     }
434 
435     /**
436      * Set the timeout for the cached SSL session objects, in seconds. {@code 0} to use the
437      * default value.
438      */
439     public QuicSslContextBuilder sessionTimeout(long sessionTimeout) {
440         this.sessionTimeout = sessionTimeout;
441         return this;
442     }
443 
444     /**
445      * Sets the client authentication mode.
446      */
447     public QuicSslContextBuilder clientAuth(ClientAuth clientAuth) {
448         if (!forServer) {
449             throw new UnsupportedOperationException("Only supported for server");
450         }
451         this.clientAuth = checkNotNull(clientAuth, "clientAuth");
452         sessionIdContextBuilder.setClientAuth(clientAuth);
453         return this;
454     }
455 
456     /**
457      * Specify the endpoint identification algorithm (aka. hostname verification algorithm) that clients will use as
458      * part of authenticating servers.
459      * <p>
460      * See <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#jssenames">
461      *     Java Security Standard Names</a> for a list of supported algorithms.
462      *
463      * @param algorithm either {@code "HTTPS"}, {@code "LDAPS"}, or {@code null} (disables hostname verification).
464      * @see SSLParameters#setEndpointIdentificationAlgorithm(String)
465      */
466     public QuicSslContextBuilder endpointIdentificationAlgorithm(String algorithm) {
467         endpointIdentificationAlgorithm = algorithm;
468         return this;
469     }
470 
471     /**
472      * Create new {@link QuicSslContext} instance with configured settings that can be used for {@code QUIC}.
473      *
474      */
475     public QuicSslContext build() {
476         if (forServer) {
477             return new QuicheQuicSslContext(true, sessionTimeout, sessionCacheSize, clientAuth, trustManagerFactory,
478                     trustCertCollection, keyManagerFactory, keyCertChain, keyPassword, mapping, earlyData, keylog,
479                     applicationProtocols, null, sessionIdContextBuilder, toArray(options.entrySet(), EMPTY_ENTRIES));
480         } else {
481             return new QuicheQuicSslContext(false, sessionTimeout, sessionCacheSize, clientAuth, trustManagerFactory,
482                     trustCertCollection, keyManagerFactory, keyCertChain, keyPassword, mapping, earlyData, keylog,
483                     applicationProtocols, endpointIdentificationAlgorithm, sessionIdContextBuilder,
484                     toArray(options.entrySet(), EMPTY_ENTRIES));
485         }
486     }
487 
488     private static <T> T[] toArray(Iterable<? extends T> iterable, T[] prototype) {
489         if (iterable == null) {
490             return null;
491         }
492         final List<T> list = new ArrayList<>();
493         for (T element : iterable) {
494             list.add(element);
495         }
496         return list.toArray(prototype);
497     }
498 }