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  package io.netty.handler.codec.quic;
17  
18  import io.netty.buffer.ByteBufAllocator;
19  import io.netty.handler.ssl.ApplicationProtocolNegotiator;
20  import io.netty.handler.ssl.ClientAuth;
21  import io.netty.handler.ssl.SessionIdContextBuilder;
22  import io.netty.handler.ssl.SslContext;
23  import io.netty.handler.ssl.SslContextOption;
24  import io.netty.handler.ssl.SslHandler;
25  import io.netty.util.AbstractReferenceCounted;
26  import io.netty.util.Mapping;
27  import io.netty.util.ReferenceCounted;
28  import io.netty.util.internal.EmptyArrays;
29  import io.netty.util.internal.SystemPropertyUtil;
30  import io.netty.util.internal.logging.InternalLogger;
31  import io.netty.util.internal.logging.InternalLoggerFactory;
32  import org.jetbrains.annotations.Nullable;
33  
34  import javax.net.ssl.KeyManager;
35  import javax.net.ssl.KeyManagerFactory;
36  import javax.net.ssl.SSLSession;
37  import javax.net.ssl.TrustManager;
38  import javax.net.ssl.TrustManagerFactory;
39  import javax.net.ssl.X509ExtendedKeyManager;
40  import javax.net.ssl.X509ExtendedTrustManager;
41  import javax.net.ssl.X509TrustManager;
42  import java.io.File;
43  import java.io.IOException;
44  import java.security.KeyStore;
45  import java.security.KeyStoreException;
46  import java.security.NoSuchAlgorithmException;
47  import java.security.PrivateKey;
48  import java.security.cert.CertificateException;
49  import java.security.cert.X509Certificate;
50  import java.util.Arrays;
51  import java.util.Collections;
52  import java.util.Enumeration;
53  import java.util.Iterator;
54  import java.util.LinkedHashSet;
55  import java.util.List;
56  import java.util.Map;
57  import java.util.NoSuchElementException;
58  import java.util.Set;
59  import java.util.concurrent.Executor;
60  import java.util.function.BiConsumer;
61  import java.util.function.LongFunction;
62  
63  import static io.netty.util.internal.ObjectUtil.checkNotNull;
64  import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
65  
66  final class QuicheQuicSslContext extends QuicSslContext {
67  
68      private static final InternalLogger LOGGER = InternalLoggerFactory.getInstance(QuicheQuicSslContext.class);
69  
70      // Use default that is supported in java 11 and earlier and also in OpenSSL / BoringSSL.
71      // See https://github.com/netty/netty-tcnative/issues/567
72      // See https://www.java.com/en/configure_crypto.html for ordering
73      private static final String[] DEFAULT_NAMED_GROUPS = { "x25519", "secp256r1", "secp384r1", "secp521r1" };
74      private static final String[] NAMED_GROUPS;
75  
76      static final String defaultEndpointVerificationAlgorithm = SslContext.defaultEndpointVerificationAlgorithm;
77  
78      static {
79          String[] namedGroups = DEFAULT_NAMED_GROUPS;
80          Set<String> defaultConvertedNamedGroups = new LinkedHashSet<>(namedGroups.length);
81          for (int i = 0; i < namedGroups.length; i++) {
82              defaultConvertedNamedGroups.add(GroupsConverter.toBoringSSL(namedGroups[i]));
83          }
84  
85          // Call Quic.isAvailable() first to ensure native lib is loaded.
86          // See https://github.com/netty/netty-incubator-codec-quic/issues/759
87          if (Quic.isAvailable()) {
88              final long sslCtx = BoringSSL.SSLContext_new();
89              try {
90                  // Let's filter out any group that is not supported from the default.
91                  Iterator<String> defaultGroupsIter = defaultConvertedNamedGroups.iterator();
92                  while (defaultGroupsIter.hasNext()) {
93                      if (BoringSSL.SSLContext_set1_groups_list(sslCtx, defaultGroupsIter.next()) == 0) {
94                          // Not supported, let's remove it. This could for example be the case if we use
95                          // fips and the configure group is not supported when using FIPS.
96                          // See https://github.com/netty/netty-tcnative/issues/883
97                          defaultGroupsIter.remove();
98                      }
99                  }
100 
101                 String groups = SystemPropertyUtil.get("jdk.tls.namedGroups", null);
102                 if (groups != null) {
103                     String[] nGroups = groups.split(",");
104                     Set<String> supportedNamedGroups = new LinkedHashSet<>(nGroups.length);
105                     Set<String> supportedConvertedNamedGroups = new LinkedHashSet<>(nGroups.length);
106 
107                     Set<String> unsupportedNamedGroups = new LinkedHashSet<>();
108                     for (String namedGroup : nGroups) {
109                         String converted = GroupsConverter.toBoringSSL(namedGroup);
110                         // Will return 0 on failure.
111                         if (BoringSSL.SSLContext_set1_groups_list(sslCtx, converted) == 0) {
112                             unsupportedNamedGroups.add(namedGroup);
113                         } else {
114                             supportedConvertedNamedGroups.add(converted);
115                             supportedNamedGroups.add(namedGroup);
116                         }
117                     }
118 
119                     if (supportedNamedGroups.isEmpty()) {
120                         namedGroups = defaultConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS);
121                         LOGGER.info("All configured namedGroups are not supported: {}. Use default: {}.",
122                                 Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS)),
123                                 Arrays.toString(DEFAULT_NAMED_GROUPS));
124                     } else {
125                         String[] groupArray = supportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS);
126                         if (unsupportedNamedGroups.isEmpty()) {
127                             LOGGER.info("Using configured namedGroups -D 'jdk.tls.namedGroup': {} ",
128                                     Arrays.toString(groupArray));
129                         } else {
130                             LOGGER.info("Using supported configured namedGroups: {}. Unsupported namedGroups: {}. ",
131                                     Arrays.toString(groupArray),
132                                     Arrays.toString(unsupportedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS)));
133                         }
134                         namedGroups = supportedConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS);
135                     }
136                 } else {
137                     namedGroups = defaultConvertedNamedGroups.toArray(EmptyArrays.EMPTY_STRINGS);
138                 }
139             } finally {
140                 BoringSSL.SSLContext_free(sslCtx);
141             }
142         }
143         NAMED_GROUPS = namedGroups;
144     }
145 
146     final ClientAuth clientAuth;
147     private final boolean server;
148     private final String endpointIdentificationAlgorithm;
149     @SuppressWarnings("deprecation")
150     private final ApplicationProtocolNegotiator apn;
151     private long sessionCacheSize;
152     private long sessionTimeout;
153     private final QuicheQuicSslSessionContext sessionCtx;
154     private final QuicheQuicSslEngineMap engineMap = new QuicheQuicSslEngineMap();
155     private final QuicClientSessionCache sessionCache;
156 
157     private final BoringSSLSessionTicketCallback sessionTicketCallback = new BoringSSLSessionTicketCallback();
158 
159     final NativeSslContext nativeSslContext;
160 
161     QuicheQuicSslContext(boolean server, long sessionTimeout, long sessionCacheSize,
162                          ClientAuth clientAuth, @Nullable TrustManagerFactory trustManagerFactory,
163                          X509Certificate @Nullable [] trustCertCollection,
164                          @Nullable KeyManagerFactory keyManagerFactory,
165                          X509Certificate @Nullable [] keyCertChain, String password,
166                          @Nullable Mapping<? super String, ? extends QuicSslContext> mapping,
167                          @Nullable Boolean earlyData, @Nullable BoringSSLKeylog keylog,
168                          String[] applicationProtocols, String endpointIdentificationAlgorithm,
169                          SessionIdContextBuilder sessionIdContext,
170                          Map.Entry<SslContextOption<?>, Object>... ctxOptions) {
171         Quic.ensureAvailability();
172         this.server = server;
173         this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm;
174         this.clientAuth = server ? checkNotNull(clientAuth, "clientAuth") : ClientAuth.NONE;
175         final X509TrustManager trustManager;
176         if (trustManagerFactory == null) {
177             try {
178                 trustManagerFactory =
179                         TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
180                 trustManagerFactory.init((KeyStore) null);
181                 trustManager = chooseTrustManager(trustManagerFactory);
182             } catch (Exception e) {
183                 throw new IllegalStateException(e);
184             }
185         } else {
186             trustManager = chooseTrustManager(trustManagerFactory);
187         }
188         if (this.endpointIdentificationAlgorithm != null && !this.endpointIdentificationAlgorithm.isEmpty() &&
189             !(trustManager instanceof X509ExtendedTrustManager)) {
190             throw new UnsupportedOperationException(
191                 "Endpoint identification algorithm '" + this.endpointIdentificationAlgorithm + "' is " +
192                     "configured but the trust manager does not support extended trust manager verification. " +
193                     "Please provide an X509ExtendedTrustManager.");
194         }
195         final X509ExtendedKeyManager keyManager;
196         if (keyManagerFactory == null) {
197             if (server) {
198                 throw new IllegalArgumentException("No KeyManagerFactory");
199             }
200             keyManager = null;
201         } else {
202             keyManager = chooseKeyManager(keyManagerFactory);
203         }
204         String[] groups = NAMED_GROUPS;
205         String[] sigalgs = EmptyArrays.EMPTY_STRINGS;
206         Map<String, String> serverKeyTypes = null;
207         Set<String> clientKeyTypes = null;
208 
209         if (ctxOptions != null) {
210             for (Map.Entry<SslContextOption<?>, Object> ctxOpt : ctxOptions) {
211                 SslContextOption<?> option = ctxOpt.getKey();
212 
213                 if (option == BoringSSLContextOption.GROUPS) {
214                     String[] groupsArray = (String[]) ctxOpt.getValue();
215                     Set<String> groupsSet = new LinkedHashSet<String>(groupsArray.length);
216                     for (String group : groupsArray) {
217                         groupsSet.add(GroupsConverter.toBoringSSL(group));
218                     }
219                     groups = groupsSet.toArray(EmptyArrays.EMPTY_STRINGS);
220                 } else if (option == BoringSSLContextOption.SIGNATURE_ALGORITHMS) {
221                     String[] sigalgsArray = (String[]) ctxOpt.getValue();
222                     Set<String> sigalgsSet = new LinkedHashSet<String>(sigalgsArray.length);
223                     for (String sigalg : sigalgsArray) {
224                         sigalgsSet.add(sigalg);
225                     }
226                     sigalgs = sigalgsSet.toArray(EmptyArrays.EMPTY_STRINGS);
227                 } else if (option == BoringSSLContextOption.CLIENT_KEY_TYPES) {
228                     clientKeyTypes = (Set<String>) ctxOpt.getValue();
229                 } else if (option == BoringSSLContextOption.SERVER_KEY_TYPES) {
230                     serverKeyTypes = (Map<String, String>) ctxOpt.getValue();
231                 } else {
232                     LOGGER.debug("Skipping unsupported " + SslContextOption.class.getSimpleName()
233                             + ": " + ctxOpt.getKey());
234                 }
235             }
236         }
237         final BoringSSLPrivateKeyMethod privateKeyMethod;
238         if (keyManagerFactory instanceof  BoringSSLKeylessManagerFactory) {
239             privateKeyMethod = new BoringSSLAsyncPrivateKeyMethodAdapter(engineMap,
240                     ((BoringSSLKeylessManagerFactory) keyManagerFactory).privateKeyMethod);
241         } else {
242             privateKeyMethod = null;
243         }
244         sessionCache = server ? null : new QuicClientSessionCache();
245         int verifyMode = server ? boringSSLVerifyModeForServer(this.clientAuth) : BoringSSL.SSL_VERIFY_PEER;
246         nativeSslContext = new NativeSslContext(BoringSSL.SSLContext_new(server, applicationProtocols,
247                 new BoringSSLHandshakeCompleteCallback(engineMap),
248                 new BoringSSLCertificateCallback(engineMap, keyManager, password, serverKeyTypes, clientKeyTypes),
249                 new BoringSSLCertificateVerifyCallback(engineMap, trustManager),
250                 mapping == null ? null : new BoringSSLTlsextServernameCallback(engineMap, mapping),
251                 keylog == null ? null : new BoringSSLKeylogCallback(engineMap, keylog),
252                 server ? null : new BoringSSLSessionCallback(engineMap, sessionCache), privateKeyMethod,
253                 sessionTicketCallback, verifyMode,
254                 BoringSSL.subjectNames(trustManager.getAcceptedIssuers())));
255         boolean success = false;
256         try {
257             if (groups.length > 0 && BoringSSL.SSLContext_set1_groups_list(nativeSslContext.ctx, groups) == 0) {
258                 String msg = "failed to set curves / groups list: " + Arrays.toString(groups);
259                 String lastError = BoringSSL.ERR_last_error();
260                 if (lastError != null) {
261                     // We have some more details about why the operations failed, include these into the message.
262                     msg += ". " + lastError;
263                 }
264                 throw new IllegalStateException(msg);
265             }
266 
267             if (sigalgs.length > 0 && BoringSSL.SSLContext_set1_sigalgs_list(nativeSslContext.ctx, sigalgs) == 0) {
268                 String msg = "failed to set signature algorithm list: " + Arrays.toString(sigalgs);
269                 String lastError = BoringSSL.ERR_last_error();
270                 if (lastError != null) {
271                     // We have some more details about why the operations failed, include these into the message.
272                     msg += ". " + lastError;
273                 }
274                 throw new IllegalStateException(msg);
275             }
276 
277             apn = new QuicheQuicApplicationProtocolNegotiator(applicationProtocols);
278             if (this.sessionCache != null) {
279                 // Cache is handled via our own implementation.
280                 this.sessionCache.setSessionCacheSize((int) sessionCacheSize);
281                 this.sessionCache.setSessionTimeout((int) sessionTimeout);
282             } else {
283                 // Cache is handled by BoringSSL internally
284                 BoringSSL.SSLContext_setSessionCacheSize(
285                         nativeSslContext.address(), sessionCacheSize);
286                 this.sessionCacheSize = sessionCacheSize;
287 
288                 BoringSSL.SSLContext_setSessionCacheTimeout(
289                         nativeSslContext.address(), sessionTimeout);
290                 this.sessionTimeout = sessionTimeout;
291 
292                 // Derive the session_id_context from what distinguishes this context, so sessions can not be
293                 // resumed across QuicSslContext instances that differ in their ClientAuth mode or trust / key
294                 // configuration, even if session-ticket keys or a session cache are shared between them.
295                 if (!BoringSSL.SSLContext_setSessionIdContext(nativeSslContext.address(), sessionIdContext.build())) {
296                     // Without a session_id_context we must not continue as resumption would not be scoped.
297                     String msg = "failed to set session id context";
298                     String lastError = BoringSSL.ERR_last_error();
299                     if (lastError != null) {
300                         msg += ": " + lastError;
301                     }
302                     throw new IllegalStateException(msg);
303                 }
304             }
305             if (server && this.clientAuth == ClientAuth.REQUIRE) {
306                 // A client certificate is not re-requested when a session is resumed, and the peer certificates are
307                 // only available once the handshake completed. Early data would hence be handed to the application
308                 // before we are able to verify that the client authenticated itself, so never accept it here.
309                 BoringSSL.SSLContext_set_early_data_enabled(nativeSslContext.address(), false);
310             } else if (earlyData != null) {
311                 BoringSSL.SSLContext_set_early_data_enabled(nativeSslContext.address(), earlyData);
312             }
313             sessionCtx = new QuicheQuicSslSessionContext(this);
314             success = true;
315         } finally {
316             if (!success) {
317                 nativeSslContext.release();
318             }
319         }
320     }
321 
322     private X509ExtendedKeyManager chooseKeyManager(KeyManagerFactory keyManagerFactory) {
323         for (KeyManager manager: keyManagerFactory.getKeyManagers()) {
324             if (manager instanceof X509ExtendedKeyManager) {
325                 return (X509ExtendedKeyManager) manager;
326             }
327         }
328         throw new IllegalArgumentException("No X509ExtendedKeyManager included");
329     }
330 
331     private static X509TrustManager chooseTrustManager(TrustManagerFactory trustManagerFactory) {
332         for (TrustManager manager: trustManagerFactory.getTrustManagers()) {
333             if (manager instanceof X509TrustManager) {
334                 return (X509TrustManager) manager;
335             }
336         }
337         throw new IllegalArgumentException("No X509TrustManager included");
338     }
339 
340      static X509Certificate @Nullable [] toX509Certificates0(@Nullable File file) throws CertificateException {
341         return toX509Certificates(file);
342     }
343 
344     static PrivateKey toPrivateKey0(@Nullable File keyFile, @Nullable String keyPassword) throws Exception {
345         return toPrivateKey(keyFile, keyPassword);
346     }
347 
348     static TrustManagerFactory buildTrustManagerFactory0(
349             X509Certificate @Nullable [] certCollection)
350             throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
351         return buildTrustManagerFactory(certCollection, null, null);
352     }
353 
354     private static int boringSSLVerifyModeForServer(ClientAuth mode) {
355         switch (mode) {
356             case NONE:
357                 return BoringSSL.SSL_VERIFY_NONE;
358             case REQUIRE:
359                 return BoringSSL.SSL_VERIFY_PEER | BoringSSL.SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
360             case OPTIONAL:
361                 return BoringSSL.SSL_VERIFY_PEER;
362             default:
363                 throw new Error("Unexpected mode: " + mode);
364         }
365     }
366 
367     @Nullable
368     QuicheQuicConnection createConnection(LongFunction<Long> connectionCreator, QuicheQuicSslEngine engine) {
369         nativeSslContext.retain();
370         long ssl = BoringSSL.SSL_new(nativeSslContext.address(), isServer(), engine.tlsHostName);
371         engineMap.put(ssl, engine);
372         long connection = connectionCreator.apply(ssl);
373         if (connection == -1) {
374             engineMap.remove(ssl);
375             // We retained before but as we don't create a QuicheQuicConnection and transfer ownership we need to
376             // explict call release again here.
377             nativeSslContext.release();
378             return null;
379         }
380         // The connection will call nativeSslContext.release() once it is freed.
381         return new QuicheQuicConnection(connection, ssl, engine, nativeSslContext);
382     }
383 
384     /**
385      * Add the given engine to this context
386      *
387      * @param engine    the engine to add.
388      * @return          the pointer address of this context.
389      */
390     long add(QuicheQuicSslEngine engine) {
391         nativeSslContext.retain();
392         engine.connection.reattach(nativeSslContext);
393         engineMap.put(engine.connection.ssl, engine);
394         return nativeSslContext.address();
395     }
396 
397     /**
398      * Remove the given engine from this context.
399      *
400      * @param engine    the engine to remove.
401      */
402     void remove(QuicheQuicSslEngine engine) {
403         QuicheQuicSslEngine removed = engineMap.remove(engine.connection.ssl);
404         assert removed == null || removed == engine;
405         engine.removeSessionFromCacheIfInvalid();
406     }
407 
408     @Nullable
409     QuicClientSessionCache getSessionCache() {
410         return sessionCache;
411     }
412 
413     @Override
414     public boolean isClient() {
415         return !server;
416     }
417 
418     @Override
419     public List<String> cipherSuites() {
420         return Arrays.asList("TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384");
421     }
422 
423     @Override
424     public long sessionCacheSize() {
425         if (sessionCache != null) {
426             return sessionCache.getSessionCacheSize();
427         } else {
428             synchronized (this) {
429                 return sessionCacheSize;
430             }
431         }
432     }
433 
434     @Override
435     public long sessionTimeout() {
436         if (sessionCache != null) {
437             return sessionCache.getSessionTimeout();
438         } else {
439             synchronized (this) {
440                 return sessionTimeout;
441             }
442         }
443     }
444 
445     @Override
446     public ApplicationProtocolNegotiator applicationProtocolNegotiator() {
447         return apn;
448     }
449 
450     @Override
451     public QuicSslEngine newEngine(ByteBufAllocator alloc) {
452         return new QuicheQuicSslEngine(this, null, -1, endpointIdentificationAlgorithm);
453     }
454 
455     @Override
456     public QuicSslEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) {
457         return new QuicheQuicSslEngine(this, peerHost, peerPort, endpointIdentificationAlgorithm);
458     }
459 
460     @Override
461     public QuicSslSessionContext sessionContext() {
462         return sessionCtx;
463     }
464 
465     @Override
466     protected SslHandler newHandler(ByteBufAllocator alloc, boolean startTls) {
467         throw new UnsupportedOperationException();
468     }
469 
470     @Override
471     public SslHandler newHandler(ByteBufAllocator alloc, Executor delegatedTaskExecutor) {
472         throw new UnsupportedOperationException();
473     }
474 
475     @Override
476     protected SslHandler newHandler(ByteBufAllocator alloc, boolean startTls, Executor executor) {
477         throw new UnsupportedOperationException();
478     }
479 
480     @Override
481     protected SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort, boolean startTls) {
482         throw new UnsupportedOperationException();
483     }
484 
485     @Override
486     public SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort,
487                                  Executor delegatedTaskExecutor) {
488         throw new UnsupportedOperationException();
489     }
490 
491     @Override
492     protected SslHandler newHandler(ByteBufAllocator alloc, String peerHost, int peerPort,
493                                     boolean startTls, Executor delegatedTaskExecutor) {
494         throw new UnsupportedOperationException();
495     }
496 
497     @Override
498     protected void finalize() throws Throwable {
499         try {
500             nativeSslContext.release();
501         } finally {
502             super.finalize();
503         }
504     }
505 
506     void setSessionTimeout(int seconds) throws IllegalArgumentException {
507         checkPositiveOrZero(seconds, "seconds");
508         if (sessionCache != null) {
509             sessionCache.setSessionTimeout(seconds);
510         } else {
511             BoringSSL.SSLContext_setSessionCacheTimeout(nativeSslContext.address(), seconds);
512             this.sessionTimeout = seconds;
513         }
514     }
515 
516     void setSessionCacheSize(int size) throws IllegalArgumentException {
517         checkPositiveOrZero(size, "size");
518         if (sessionCache != null) {
519             sessionCache.setSessionCacheSize(size);
520         } else {
521             BoringSSL.SSLContext_setSessionCacheSize(nativeSslContext.address(), size);
522             sessionCacheSize = size;
523         }
524     }
525 
526     void setSessionTicketKeys(SslSessionTicketKey @Nullable [] ticketKeys) {
527         sessionTicketCallback.setSessionTicketKeys(ticketKeys);
528         BoringSSL.SSLContext_setSessionTicketKeys(
529                 nativeSslContext.address(), ticketKeys != null && ticketKeys.length != 0);
530     }
531 
532     @SuppressWarnings("deprecation")
533     private static final class QuicheQuicApplicationProtocolNegotiator implements ApplicationProtocolNegotiator {
534         private final List<String> protocols;
535 
536         QuicheQuicApplicationProtocolNegotiator(String @Nullable ... protocols) {
537             if (protocols == null) {
538                 this.protocols = Collections.emptyList();
539             } else {
540                 this.protocols = Collections.unmodifiableList(Arrays.asList(protocols));
541             }
542         }
543 
544         @Override
545         public List<String> protocols() {
546             return protocols;
547         }
548     }
549 
550     private static final class QuicheQuicSslSessionContext implements QuicSslSessionContext {
551         private final QuicheQuicSslContext context;
552 
553         QuicheQuicSslSessionContext(QuicheQuicSslContext context) {
554             this.context = context;
555         }
556 
557         @Override
558         @Nullable
559         public SSLSession getSession(byte[] sessionId) {
560             return null;
561         }
562 
563         @Override
564         public Enumeration<byte[]> getIds() {
565             return new Enumeration<byte[]>() {
566                 @Override
567                 public boolean hasMoreElements() {
568                     return false;
569                 }
570 
571                 @Override
572                 public byte[] nextElement() {
573                     throw new NoSuchElementException();
574                 }
575             };
576         }
577 
578         @Override
579         public void setSessionTimeout(int seconds) throws IllegalArgumentException {
580             context.setSessionTimeout(seconds);
581         }
582 
583         @Override
584         public int getSessionTimeout() {
585             return (int) context.sessionTimeout();
586         }
587 
588         @Override
589         public void setSessionCacheSize(int size) throws IllegalArgumentException {
590             context.setSessionCacheSize(size);
591         }
592 
593         @Override
594         public int getSessionCacheSize() {
595             return (int) context.sessionCacheSize();
596         }
597 
598         @Override
599         public void setTicketKeys(SslSessionTicketKey @Nullable ... keys) {
600             context.setSessionTicketKeys(keys);
601         }
602     }
603 
604     static final class NativeSslContext extends AbstractReferenceCounted {
605         private final long ctx;
606 
607         NativeSslContext(long ctx) {
608             this.ctx = ctx;
609         }
610 
611         long address() {
612             return ctx;
613         }
614 
615         @Override
616         protected void deallocate() {
617             BoringSSL.SSLContext_free(ctx);
618         }
619 
620         @Override
621         public ReferenceCounted touch(Object hint) {
622             return this;
623         }
624 
625         @Override
626         public String toString() {
627             return "NativeSslContext{" +
628                     "ctx=" + ctx +
629                     '}';
630         }
631     }
632 
633     private static final class BoringSSLAsyncPrivateKeyMethodAdapter implements BoringSSLPrivateKeyMethod {
634         private final QuicheQuicSslEngineMap engineMap;
635         private final BoringSSLAsyncPrivateKeyMethod privateKeyMethod;
636 
637         BoringSSLAsyncPrivateKeyMethodAdapter(QuicheQuicSslEngineMap engineMap,
638                                               BoringSSLAsyncPrivateKeyMethod privateKeyMethod) {
639             this.engineMap = engineMap;
640             this.privateKeyMethod = privateKeyMethod;
641         }
642 
643         @Override
644         public void sign(long ssl, int signatureAlgorithm, byte[] input, BiConsumer<byte[], Throwable> callback) {
645             final QuicheQuicSslEngine engine = engineMap.get(ssl);
646             if (engine == null) {
647                 // May be null if it was destroyed in the meantime.
648                 callback.accept(null, null);
649             } else {
650                 privateKeyMethod.sign(engine, signatureAlgorithm, input).addListener(f -> {
651                     Throwable cause = f.cause();
652                     if (cause != null) {
653                         callback.accept(null, cause);
654                     } else {
655                         callback.accept((byte[]) f.getNow(), null);
656                     }
657                 });
658             }
659         }
660 
661         @Override
662         public void decrypt(long ssl, byte[] input, BiConsumer<byte[], Throwable> callback) {
663             final QuicheQuicSslEngine engine = engineMap.get(ssl);
664             if (engine == null) {
665                 // May be null if it was destroyed in the meantime.
666                 callback.accept(null, null);
667             } else {
668                 privateKeyMethod.decrypt(engine, input).addListener(f -> {
669                     Throwable cause = f.cause();
670                     if (cause != null) {
671                         callback.accept(null, cause);
672                     } else {
673                         callback.accept((byte[]) f.getNow(), null);
674                     }
675                 });
676             }
677         }
678     }
679 }