Jörg Prante 5 months ago
commit b85679f001

57
.gitignore vendored

@ -0,0 +1,57 @@
# Eclipse project files
.project
.classpath
.settings
# IntelliJ IDEA project files and directories
*.iml
*.ipr
*.iws
.idea/
.shelf/
# Geany project file
.geany
# KDevelop project file and directory
.kdev4/
*.kdev4
# Build targets
/target
*/target
# Report directories
/reports
*/reports
# Mac-specific directory that no other operating system needs.
.DS_Store
# JVM crash logs
hs_err_pid*.log
replay_pid*.log
# JVM dumps
*.hprof.xz
*.threads
dependency-reduced-pom.xml
*/.unison.*
# exclude mainframer files
mainframer
.mainframer
# exclude docker-sync stuff
.docker-sync
*/.docker-sync
# exclude vscode files
.vscode/
*.factorypath
# exclude file created by the flatten plugin
.flattened-pom.xml
.java-version

Binary file not shown.

@ -0,0 +1,18 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://maven-central.storage-download.googleapis.com/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip
distributionSha256Sum=7822eb593d29558d8edf87845a2c47e36e2a89d17a84cd2390824633214ed423

@ -0,0 +1,10 @@
brew 'autoconf'
brew 'automake'
brew 'libtool'
brew 'openssl'
brew 'perl'
brew 'ninja'
brew 'golang'
brew 'cmake'
brew 'apr'
brew 'rust'

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@ -0,0 +1,49 @@
The Netty Project
=================
Please visit the Netty web site for more information:
* https://netty.io/
Copyright 2020 The Netty Project
The Netty Project licenses this file to you under the Apache License,
version 2.0 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at:
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
Also, please refer to each LICENSE.<component>.txt file, which is located in
the 'license' directory of the distribution file, for the license terms of the
components that this product depends on.
-------------------------------------------------------------------------------
This product contains the Maven wrapper scripts from 'Maven Wrapper', that provides an easy way to ensure a user has everything necessary to run the Maven build.
* LICENSE:
* license/LICENSE.mvn-wrapper.txt (Apache License 2.0)
* HOMEPAGE:
* https://github.com/takari/maven-wrapper
This product is statically linked against Quiche.
* LICENSE:
* license/LICENSE.quiche.txt (BSD2)
* HOMEPAGE:
* https://github.com/cloudflare/quiche
This product is statically linked against boringssl.
* LICENSE (Combination ISC and OpenSSL license)
* license/LICENSE.boringssl.txt (Combination ISC and OpenSSL license)
* HOMEPAGE:
* https://boringssl.googlesource.com/boringssl/

@ -0,0 +1,52 @@
![Build project](https://github.com/netty/netty-incubator-codec-quic/workflows/Build%20project/badge.svg)
# Netty QUIC codec
This is a new experimental QUIC codec for netty which makes use of [quiche](https://github.com/cloudflare/quiche).
## How to include the dependency
To include the dependency you need to ensure you also specify the right classifier. At the moment we only support Linux
x86_64 / aarch_64, macOS / OSX x86_64 / aarch_64 and Windows x86_64 but this may change.
As an example this is how you would include the dependency in maven:
For Linux x86_64:
```
<dependency>
<groupId>io.netty.incubator</groupId>
<artifactId>netty-incubator-codec-native-quic</artifactId>
<version>0.0.21.Final</version>
<classifier>linux-x86_64</classifier>
</dependency>
```
For macOS / OSX:
```
<dependency>
<groupId>io.netty.incubator</groupId>
<artifactId>netty-incubator-codec-native-quic</artifactId>
<version>0.0.21.Final</version>
<classifier>osx-x86_64</classifier>
</dependency>
```
For Windows:
```
<dependency>
<groupId>io.netty.incubator</groupId>
<artifactId>netty-incubator-codec-native-quic</artifactId>
<version>0.0.21.Final</version>
<classifier>windows-x86_64</classifier>
</dependency>
```
## How to use this codec ?
For some examples please check our
[example package](https://github.com/netty/netty-incubator-codec-quic/tree/main/codec-native-quic/src/test/java/io/netty/incubator/codec/quic).
This contains a server and a client that can speak some limited HTTP/0.9 with each other.
For more "advanced" use cases, consider checking our
[netty-incubator-codec-http3](https://github.com/netty/netty-incubator-codec-http3) project.

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 The Netty Project
~
~ The Netty Project licenses this file to you under the Apache License,
~ version 2.0 (the "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at:
~
~ https://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
~ License for the specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.xbib.netty</groupId>
<artifactId>netty-handler-codec-parent-quic</artifactId>
<version>0.0.56.Final-SNAPSHOT</version>
</parent>
<artifactId>netty-handler-codec-classes-quic</artifactId>
<version>0.0.56.Final-SNAPSHOT</version>
<name>Netty/Handler/Codec/Classes/Quic</name>
<packaging>jar</packaging>
<properties>
<javaModuleName>io.netty.handler.codec.classes.quic</javaModuleName>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>default-jar</id>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
<manifestEntries>
<Automatic-Module-Name>${javaModuleName}</Automatic-Module-Name>
</manifestEntries>
<index>true</index>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-common</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-buffer</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-classes-epoll</artifactId>
<!-- Let's mark as optional as it is not strictly needed -->
<optional>true</optional>
</dependency>
</dependencies>
</project>

@ -0,0 +1,129 @@
/*
* Copyright 2021 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.quic;
import io.netty.handler.ssl.util.LazyX509Certificate;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
final class BoringSSL {
private BoringSSL() { }
static final int SSL_VERIFY_NONE = BoringSSLNativeStaticallyReferencedJniMethods.ssl_verify_none();
static final int SSL_VERIFY_FAIL_IF_NO_PEER_CERT = BoringSSLNativeStaticallyReferencedJniMethods
.ssl_verify_fail_if_no_peer_cert();
static final int SSL_VERIFY_PEER = BoringSSLNativeStaticallyReferencedJniMethods.ssl_verify_peer();
static final int X509_V_OK = BoringSSLNativeStaticallyReferencedJniMethods.x509_v_ok();
static final int X509_V_ERR_CERT_HAS_EXPIRED =
BoringSSLNativeStaticallyReferencedJniMethods.x509_v_err_cert_has_expired();
static final int X509_V_ERR_CERT_NOT_YET_VALID =
BoringSSLNativeStaticallyReferencedJniMethods.x509_v_err_cert_not_yet_valid();
static final int X509_V_ERR_CERT_REVOKED = BoringSSLNativeStaticallyReferencedJniMethods.x509_v_err_cert_revoked();
static final int X509_V_ERR_UNSPECIFIED = BoringSSLNativeStaticallyReferencedJniMethods.x509_v_err_unspecified();
static long SSLContext_new(boolean server, String[] applicationProtocols,
BoringSSLHandshakeCompleteCallback handshakeCompleteCallback,
BoringSSLCertificateCallback certificateCallback,
BoringSSLCertificateVerifyCallback verifyCallback,
BoringSSLTlsextServernameCallback servernameCallback,
BoringSSLKeylogCallback keylogCallback,
BoringSSLSessionCallback sessionCallback,
BoringSSLPrivateKeyMethod privateKeyMethod,
BoringSSLSessionTicketCallback sessionTicketCallback,
int verifyMode,
byte[][] subjectNames) {
return SSLContext_new0(server, toWireFormat(applicationProtocols),
handshakeCompleteCallback, certificateCallback, verifyCallback, servernameCallback,
keylogCallback, sessionCallback, privateKeyMethod, sessionTicketCallback, verifyMode, subjectNames);
}
private static byte[] toWireFormat(String[] applicationProtocols) {
if (applicationProtocols == null) {
return null;
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
for (String p : applicationProtocols) {
byte[] bytes = p.getBytes(StandardCharsets.US_ASCII);
out.write(bytes.length);
out.write(bytes);
}
return out.toByteArray();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static native long SSLContext_new0(boolean server,
byte[] applicationProtocols, Object handshakeCompleteCallback,
Object certificateCallback, Object verifyCallback,
Object servernameCallback, Object keylogCallback,
Object sessionCallback,
Object privateKeyMethod,
Object sessionTicketCallback,
int verifyDepth, byte[][] subjectNames);
static native void SSLContext_set_early_data_enabled(long context, boolean enabled);
static native long SSLContext_setSessionCacheSize(long context, long size);
static native long SSLContext_setSessionCacheTimeout(long context, long size);
static native void SSLContext_setSessionTicketKeys(long context, boolean enableCallback);
static native void SSLContext_free(long context);
static long SSL_new(long context, boolean server, String hostname) {
return SSL_new0(context, server, tlsExtHostName(hostname));
}
static native long SSL_new0(long context, boolean server, String hostname);
static native void SSL_free(long ssl);
static native Runnable SSL_getTask(long ssl);
static native void SSL_cleanup(long ssl);
static native long EVP_PKEY_parse(byte[] bytes, String pass);
static native void EVP_PKEY_free(long key);
static native long CRYPTO_BUFFER_stack_new(long ssl, byte[][] bytes);
static native void CRYPTO_BUFFER_stack_free(long chain);
static native String ERR_last_error();
private static String tlsExtHostName(String hostname) {
if (hostname != null && hostname.endsWith(".")) {
// Strip trailing dot if included.
// See https://github.com/netty/netty-tcnative/issues/400
hostname = hostname.substring(0, hostname.length() - 1);
}
return hostname;
}
static X509Certificate[] certificates(byte[][] chain) {
X509Certificate[] peerCerts = new X509Certificate[chain.length];
for (int i = 0; i < peerCerts.length; i++) {
peerCerts[i] = new LazyX509Certificate(chain[i]);
}
return peerCerts;
}
static byte[][] subjectNames(X509Certificate[] certificates) {
byte[][] subjectNames = new byte[certificates.length][];
for (int i = 0; i < certificates.length; i++) {
subjectNames[i] = certificates[i].getSubjectX500Principal().getEncoded();
}
return subjectNames;
}
}

@ -0,0 +1,57 @@
/*
* Copyright 2021 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.quic;
import io.netty.util.concurrent.Future;
import javax.net.ssl.SSLEngine;
public interface BoringSSLAsyncPrivateKeyMethod {
int SSL_SIGN_RSA_PKCS1_SHA1 = BoringSSLPrivateKeyMethod.SSL_SIGN_RSA_PKCS1_SHA1;
int SSL_SIGN_RSA_PKCS1_SHA256 = BoringSSLPrivateKeyMethod.SSL_SIGN_RSA_PKCS1_SHA256;
int SSL_SIGN_RSA_PKCS1_SHA384 = BoringSSLPrivateKeyMethod.SSL_SIGN_RSA_PKCS1_SHA384;
int SSL_SIGN_RSA_PKCS1_SHA512 = BoringSSLPrivateKeyMethod.SSL_SIGN_RSA_PKCS1_SHA512;
int SSL_SIGN_ECDSA_SHA1 = BoringSSLPrivateKeyMethod.SSL_SIGN_ECDSA_SHA1;
int SSL_SIGN_ECDSA_SECP256R1_SHA256 = BoringSSLPrivateKeyMethod.SSL_SIGN_ECDSA_SECP256R1_SHA256;
int SSL_SIGN_ECDSA_SECP384R1_SHA384 = BoringSSLPrivateKeyMethod.SSL_SIGN_ECDSA_SECP384R1_SHA384;
int SSL_SIGN_ECDSA_SECP521R1_SHA512 = BoringSSLPrivateKeyMethod.SSL_SIGN_ECDSA_SECP521R1_SHA512;
int SSL_SIGN_RSA_PSS_RSAE_SHA256 = BoringSSLPrivateKeyMethod.SSL_SIGN_RSA_PSS_RSAE_SHA256;
int SSL_SIGN_RSA_PSS_RSAE_SHA384 = BoringSSLPrivateKeyMethod.SSL_SIGN_RSA_PSS_RSAE_SHA384;
int SSL_SIGN_RSA_PSS_RSAE_SHA512 = BoringSSLPrivateKeyMethod.SSL_SIGN_RSA_PSS_RSAE_SHA512;
int SSL_SIGN_ED25519 = BoringSSLPrivateKeyMethod.SSL_SIGN_ED25519;
int SSL_SIGN_RSA_PKCS1_MD5_SHA1 = BoringSSLPrivateKeyMethod.SSL_SIGN_RSA_PKCS1_MD5_SHA1;
/**
* Signs the input with the given key and notifies the returned {@link Future} with the signed bytes.
*
* @param engine the {@link SSLEngine}
* @param signatureAlgorithm the algorithm to use for signing
* @param input the digest itself
* @return the {@link Future} that will be notified with the signed data
* (must not be {@code null}) when the operation completes.
*/
Future<byte[]> sign(SSLEngine engine, int signatureAlgorithm, byte[] input);
/**
* Decrypts the input with the given key and notifies the returned {@link Future} with the decrypted bytes.
*
* @param engine the {@link SSLEngine}
* @param input the input which should be decrypted
* @return the {@link Future} that will be notified with the decrypted data
* (must not be {@code null}) when the operation completes.
*/
Future<byte[]> decrypt(SSLEngine engine, byte[] input);
}

@ -0,0 +1,276 @@
/*
* Copyright 2021 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.quic;
import io.netty.util.CharsetUtil;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.security.auth.x500.X500Principal;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
final class BoringSSLCertificateCallback {
private static final byte[] BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n".getBytes(CharsetUtil.US_ASCII);
private static final byte[] END_PRIVATE_KEY = "\n-----END PRIVATE KEY-----\n".getBytes(CharsetUtil.US_ASCII);
/**
* The types contained in the {@code keyTypeBytes} array.
*/
// Extracted from https://github.com/openssl/openssl/blob/master/include/openssl/tls1.h
private static final byte TLS_CT_RSA_SIGN = 1;
private static final byte TLS_CT_DSS_SIGN = 2;
private static final byte TLS_CT_RSA_FIXED_DH = 3;
private static final byte TLS_CT_DSS_FIXED_DH = 4;
private static final byte TLS_CT_ECDSA_SIGN = 64;
private static final byte TLS_CT_RSA_FIXED_ECDH = 65;
private static final byte TLS_CT_ECDSA_FIXED_ECDH = 66;
// Code in this class is inspired by code of conscrypts:
// - https://android.googlesource.com/platform/external/
// conscrypt/+/master/src/main/java/org/conscrypt/OpenSSLEngineImpl.java
// - https://android.googlesource.com/platform/external/
// conscrypt/+/master/src/main/java/org/conscrypt/SSLParametersImpl.java
//
static final String KEY_TYPE_RSA = "RSA";
static final String KEY_TYPE_DH_RSA = "DH_RSA";
static final String KEY_TYPE_EC = "EC";
static final String KEY_TYPE_EC_EC = "EC_EC";
static final String KEY_TYPE_EC_RSA = "EC_RSA";
// key type mappings for types.
private static final Map<String, String> KEY_TYPES = new HashMap<String, String>();
static {
KEY_TYPES.put("RSA", KEY_TYPE_RSA);
KEY_TYPES.put("DHE_RSA", KEY_TYPE_RSA);
KEY_TYPES.put("ECDHE_RSA", KEY_TYPE_RSA);
KEY_TYPES.put("ECDHE_ECDSA", KEY_TYPE_EC);
KEY_TYPES.put("ECDH_RSA", KEY_TYPE_EC_RSA);
KEY_TYPES.put("ECDH_ECDSA", KEY_TYPE_EC_EC);
KEY_TYPES.put("DH_RSA", KEY_TYPE_DH_RSA);
}
private static final Set<String> SUPPORTED_KEY_TYPES = Collections.unmodifiableSet(new LinkedHashSet<>(
Arrays.asList(KEY_TYPE_RSA,
KEY_TYPE_DH_RSA,
KEY_TYPE_EC,
KEY_TYPE_EC_RSA,
KEY_TYPE_EC_EC)));
// Directly returning this is safe as we never modify it within our JNI code.
private static final long[] NO_KEY_MATERIAL_CLIENT_SIDE = new long[] { 0, 0 };
private final QuicheQuicSslEngineMap engineMap;
private final X509ExtendedKeyManager keyManager;
private final String password;
BoringSSLCertificateCallback(QuicheQuicSslEngineMap engineMap, X509ExtendedKeyManager keyManager, String password) {
this.engineMap = engineMap;
this.keyManager = keyManager;
this.password = password;
}
@SuppressWarnings("unused")
long[] handle(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals, String[] authMethods) {
QuicheQuicSslEngine engine = engineMap.get(ssl);
if (engine == null) {
return null;
}
try {
if (keyManager == null) {
if (engine.getUseClientMode()) {
return NO_KEY_MATERIAL_CLIENT_SIDE;
}
return null;
}
if (engine.getUseClientMode()) {
final Set<String> keyTypesSet = supportedClientKeyTypes(keyTypeBytes);
final String[] keyTypes = keyTypesSet.toArray(new String[0]);
final X500Principal[] issuers;
if (asn1DerEncodedPrincipals == null) {
issuers = null;
} else {
issuers = new X500Principal[asn1DerEncodedPrincipals.length];
for (int i = 0; i < asn1DerEncodedPrincipals.length; i++) {
issuers[i] = new X500Principal(asn1DerEncodedPrincipals[i]);
}
}
return removeMappingIfNeeded(ssl, selectKeyMaterialClientSide(ssl, engine, keyTypes, issuers));
} else {
// For now we just ignore the asn1DerEncodedPrincipals as this is kind of inline with what the
// OpenJDK SSLEngineImpl does.
return removeMappingIfNeeded(ssl, selectKeyMaterialServerSide(ssl, engine, authMethods));
}
} catch (SSLException e) {
engineMap.remove(ssl);
return null;
} catch (Throwable cause) {
engineMap.remove(ssl);
throw cause;
}
}
private long[] removeMappingIfNeeded(long ssl, long[] result) {
if (result == null) {
engineMap.remove(ssl);
}
return result;
}
private long[] selectKeyMaterialServerSide(long ssl, QuicheQuicSslEngine engine, String[] authMethods)
throws SSLException {
if (authMethods.length == 0) {
throw new SSLHandshakeException("Unable to find key material");
}
// authMethods may contain duplicates or may result in the same type
// but call chooseServerAlias(...) may be expensive. So let's ensure
// we filter out duplicates.
Set<String> typeSet = new HashSet<String>(KEY_TYPES.size());
for (String authMethod : authMethods) {
String type = KEY_TYPES.get(authMethod);
if (type != null && typeSet.add(type)) {
String alias = chooseServerAlias(engine, type);
if (alias != null) {
return selectMaterial(ssl, engine, alias) ;
}
}
}
throw new SSLHandshakeException("Unable to find key material for auth method(s): "
+ Arrays.toString(authMethods));
}
private long[] selectKeyMaterialClientSide(long ssl, QuicheQuicSslEngine engine, String[] keyTypes,
X500Principal[] issuer) {
String alias = chooseClientAlias(engine, keyTypes, issuer);
// Only try to set the keymaterial if we have a match. This is also consistent with what OpenJDK does:
// https://hg.openjdk.java.net/jdk/jdk11/file/76072a077ee1/
// src/java.base/share/classes/sun/security/ssl/CertificateRequest.java#l362
if (alias != null) {
return selectMaterial(ssl, engine, alias) ;
}
return NO_KEY_MATERIAL_CLIENT_SIDE;
}
private long[] selectMaterial(long ssl, QuicheQuicSslEngine engine, String alias) {
X509Certificate[] certificates = keyManager.getCertificateChain(alias);
if (certificates == null || certificates.length == 0) {
return null;
}
byte[][] certs = new byte[certificates.length][];
for (int i = 0; i < certificates.length; i++) {
try {
certs[i] = certificates[i].getEncoded();
} catch (CertificateEncodingException e) {
return null;
}
}
final long key;
PrivateKey privateKey = keyManager.getPrivateKey(alias);
if (privateKey == BoringSSLKeylessPrivateKey.INSTANCE) {
key = 0;
} else {
byte[] pemKey = toPemEncoded(privateKey);
if (pemKey == null) {
return null;
}
key = BoringSSL.EVP_PKEY_parse(pemKey, password);
}
long chain = BoringSSL.CRYPTO_BUFFER_stack_new(ssl, certs);
engine.setLocalCertificateChain(certificates);
// Return and signal that the key and chain should be released as well.
return new long[] { key, chain };
}
private static byte[] toPemEncoded(PrivateKey key) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
out.write(BEGIN_PRIVATE_KEY);
out.write(Base64.getEncoder().encode(key.getEncoded()));
out.write(END_PRIVATE_KEY);
return out.toByteArray();
} catch (IOException e) {
return null;
}
}
private String chooseClientAlias(QuicheQuicSslEngine engine,
String[] keyTypes, X500Principal[] issuer) {
return keyManager.chooseEngineClientAlias(keyTypes, issuer, engine);
}
private String chooseServerAlias(QuicheQuicSslEngine engine, String type) {
return keyManager.chooseEngineServerAlias(type, null, engine);
}
/**
* Gets the supported key types for client certificates.
*
* @param clientCertificateTypes {@code ClientCertificateType} values provided by the server.
* See https://www.ietf.org/assignments/tls-parameters/tls-parameters.xml.
* @return supported key types that can be used in {@code X509KeyManager.chooseClientAlias} and
* {@code X509ExtendedKeyManager.chooseEngineClientAlias}.
*/
private static Set<String> supportedClientKeyTypes(byte[] clientCertificateTypes) {
if (clientCertificateTypes == null) {
// Try all of the supported key types.
return SUPPORTED_KEY_TYPES;
}
Set<String> result = new HashSet<>(clientCertificateTypes.length);
for (byte keyTypeCode : clientCertificateTypes) {
String keyType = clientKeyType(keyTypeCode);
if (keyType == null) {
// Unsupported client key type -- ignore
continue;
}
result.add(keyType);
}
return result;
}
private static String clientKeyType(byte clientCertificateType) {
// See also https://www.ietf.org/assignments/tls-parameters/tls-parameters.xml
switch (clientCertificateType) {
case TLS_CT_RSA_SIGN:
return KEY_TYPE_RSA; // RFC rsa_sign
case TLS_CT_RSA_FIXED_DH:
return KEY_TYPE_DH_RSA; // RFC rsa_fixed_dh
case TLS_CT_ECDSA_SIGN:
return KEY_TYPE_EC; // RFC ecdsa_sign
case TLS_CT_RSA_FIXED_ECDH:
return KEY_TYPE_EC_RSA; // RFC rsa_fixed_ecdh
case TLS_CT_ECDSA_FIXED_ECDH:
return KEY_TYPE_EC_EC; // RFC ecdsa_fixed_ecdh
default:
return null;
}
}
}

@ -0,0 +1,73 @@
/*
* Copyright 2022 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.quic;
/**
* Execute {@link BoringSSLCertificateCallback#handle(long, byte[], byte[][], String[])}.
*/
final class BoringSSLCertificateCallbackTask extends BoringSSLTask {
private final byte[] keyTypeBytes;
private final byte[][] asn1DerEncodedPrincipals;
private final String[] authMethods;
private final BoringSSLCertificateCallback callback;
// Accessed via JNI.
private long key;
private long chain;
BoringSSLCertificateCallbackTask(long ssl, byte[] keyTypeBytes, byte[][] asn1DerEncodedPrincipals, String[] authMethods,
BoringSSLCertificateCallback callback) {
// It is important that this constructor never throws. Be sure to not change this!
super(ssl);
// It's ok to not clone the arrays as we create these in JNI and not-reuse.
this.keyTypeBytes = keyTypeBytes;
this.asn1DerEncodedPrincipals = asn1DerEncodedPrincipals;
this.authMethods = authMethods;
this.callback = callback;
}
// See https://www.openssl.org/docs/man1.0.2/man3/SSL_set_cert_cb.html.
@Override
protected void runTask(long ssl, TaskCallback taskCallback) {
try {
long[] result = callback.handle(ssl, keyTypeBytes, asn1DerEncodedPrincipals, authMethods);
if (result == null) {
taskCallback.onResult(ssl, 0);
} else {
this.key = result[0];
this.chain = result[1];
taskCallback.onResult(ssl, 1);
}
} catch (Exception e) {
// Just catch the exception and return 0 to fail the handshake.
// The problem is that rethrowing here is really "useless" as we will process it as part of an openssl
// c callback which needs to return 0 for an error to abort the handshake.
taskCallback.onResult(ssl, 0);
}
}
@Override
protected void destroy() {
if (key != 0) {
BoringSSL.EVP_PKEY_free(key);
key = 0;
}
if (chain != 0) {
BoringSSL.CRYPTO_BUFFER_stack_free(chain);
chain = 0;
}
}
}

@ -0,0 +1,124 @@
/*
* Copyright 2021 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.quic;
import io.netty.handler.ssl.OpenSslCertificateException;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CertificateRevokedException;
import java.security.cert.X509Certificate;
final class BoringSSLCertificateVerifyCallback {
private static final boolean TRY_USING_EXTENDED_TRUST_MANAGER;
static {
boolean tryUsingExtendedTrustManager;
try {
Class.forName(X509ExtendedTrustManager.class.getName());
tryUsingExtendedTrustManager = true;
} catch (Throwable cause) {
tryUsingExtendedTrustManager = false;
}
TRY_USING_EXTENDED_TRUST_MANAGER = tryUsingExtendedTrustManager;
}
private final QuicheQuicSslEngineMap engineMap;
private final X509TrustManager manager;
BoringSSLCertificateVerifyCallback(QuicheQuicSslEngineMap engineMap, X509TrustManager manager) {
this.engineMap = engineMap;
this.manager = manager;
}
@SuppressWarnings("unused")
int verify(long ssl, byte[][] x509, String authAlgorithm) {
final QuicheQuicSslEngine engine = engineMap.get(ssl);
if (engine == null) {
// May be null if it was destroyed in the meantime.
return BoringSSL.X509_V_ERR_UNSPECIFIED;
}
if (manager == null) {
engineMap.remove(ssl);
return BoringSSL.X509_V_ERR_UNSPECIFIED;
}
X509Certificate[] peerCerts = BoringSSL.certificates(x509);
try {
if (engine.getUseClientMode()) {
if (TRY_USING_EXTENDED_TRUST_MANAGER && manager instanceof X509ExtendedTrustManager) {
((X509ExtendedTrustManager) manager).checkServerTrusted(peerCerts, authAlgorithm, engine);
} else {
manager.checkServerTrusted(peerCerts, authAlgorithm);
}
} else {
if (TRY_USING_EXTENDED_TRUST_MANAGER && manager instanceof X509ExtendedTrustManager) {
((X509ExtendedTrustManager) manager).checkClientTrusted(peerCerts, authAlgorithm, engine);
} else {
manager.checkClientTrusted(peerCerts, authAlgorithm);
}
}
return BoringSSL.X509_V_OK;
} catch (Throwable cause) {
engineMap.remove(ssl);
// Try to extract the correct error code that should be used.
if (cause instanceof OpenSslCertificateException) {
// This will never return a negative error code as its validated when constructing the
// OpenSslCertificateException.
return ((OpenSslCertificateException) cause).errorCode();
}
if (cause instanceof CertificateExpiredException) {
return BoringSSL.X509_V_ERR_CERT_HAS_EXPIRED;
}
if (cause instanceof CertificateNotYetValidException) {
return BoringSSL.X509_V_ERR_CERT_NOT_YET_VALID;
}
return translateToError(cause);
}
}
private static int translateToError(Throwable cause) {
if (cause instanceof CertificateRevokedException) {
return BoringSSL.X509_V_ERR_CERT_REVOKED;
}
// The X509TrustManagerImpl uses a Validator which wraps a CertPathValidatorException into
// an CertificateException. So we need to handle the wrapped CertPathValidatorException to be
// able to send the correct alert.
Throwable wrapped = cause.getCause();
while (wrapped != null) {
if (wrapped instanceof CertPathValidatorException) {
CertPathValidatorException ex = (CertPathValidatorException) wrapped;
CertPathValidatorException.Reason reason = ex.getReason();
if (reason == CertPathValidatorException.BasicReason.EXPIRED) {
return BoringSSL.X509_V_ERR_CERT_HAS_EXPIRED;
}
if (reason == CertPathValidatorException.BasicReason.NOT_YET_VALID) {
return BoringSSL.X509_V_ERR_CERT_NOT_YET_VALID;
}
if (reason == CertPathValidatorException.BasicReason.REVOKED) {
return BoringSSL.X509_V_ERR_CERT_REVOKED;
}
}
wrapped = wrapped.getCause();
}
return BoringSSL.X509_V_ERR_UNSPECIFIED;
}
}

@ -0,0 +1,40 @@
/*
* Copyright 2022 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.quic;
/**
* Execute {@link BoringSSLCertificateVerifyCallback#verify(long, byte[][], String)}.
*/
final class BoringSSLCertificateVerifyCallbackTask extends BoringSSLTask {
private final byte[][] x509;
private final String authAlgorithm;
private final BoringSSLCertificateVerifyCallback verifier;
BoringSSLCertificateVerifyCallbackTask(long ssl, byte[][] x509, String authAlgorithm,
BoringSSLCertificateVerifyCallback verifier) {
super(ssl);
this.x509 = x509;
this.authAlgorithm = authAlgorithm;
this.verifier = verifier;
}
@Override
protected void runTask(long ssl, TaskCallback callback) {
int result = verifier.verify(ssl, x509, authAlgorithm);
callback.onResult(ssl, result);
}
}

@ -0,0 +1,36 @@
/*
* Copyright 2021 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.quic;
final class BoringSSLHandshakeCompleteCallback {
private final QuicheQuicSslEngineMap map;
BoringSSLHandshakeCompleteCallback(QuicheQuicSslEngineMap map) {
this.map = map;
}
@SuppressWarnings("unused")
void handshakeComplete(long ssl, byte[] id, String cipher, String protocol, byte[] peerCertificate,
byte[][] peerCertificateChain, long creationTime, long timeout, byte[] applicationProtocol,
boolean sessionReused) {
QuicheQuicSslEngine engine = map.get(ssl);
if (engine != null) {
engine.handshakeFinished(id, cipher, protocol, peerCertificate, peerCertificateChain, creationTime,
timeout, applicationProtocol, sessionReused);
}
}
}

@ -0,0 +1,245 @@
/*
* Copyright 2022 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.quic;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.KeyManagerFactorySpi;
import javax.net.ssl.ManagerFactoryParameters;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.KeyStoreSpi;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
import static java.util.Objects.requireNonNull;
/**
* {@link KeyManagerFactory} that can be used to support custom key signing via {@link BoringSSLAsyncPrivateKeyMethod}.
*/
public final class BoringSSLKeylessManagerFactory extends KeyManagerFactory {
final BoringSSLAsyncPrivateKeyMethod privateKeyMethod;
private BoringSSLKeylessManagerFactory(KeyManagerFactory keyManagerFactory,
BoringSSLAsyncPrivateKeyMethod privateKeyMethod) {
super(new KeylessManagerFactorySpi(keyManagerFactory),
keyManagerFactory.getProvider(), keyManagerFactory.getAlgorithm());
this.privateKeyMethod = requireNonNull(privateKeyMethod, "privateKeyMethod");
}
/**
* Creates a new factory instance.
*
* @param privateKeyMethod the {@link BoringSSLAsyncPrivateKeyMethod} that is used for key signing.
* @param chain the {@link File} that contains the {@link X509Certificate} chain.
* @return a new factory instance.
* @throws CertificateException on error.
* @throws IOException on error.
* @throws KeyStoreException on error.
* @throws NoSuchAlgorithmException on error.
* @throws UnrecoverableKeyException on error.
*/
public static BoringSSLKeylessManagerFactory newKeyless(BoringSSLAsyncPrivateKeyMethod privateKeyMethod, File chain)
throws CertificateException, IOException,
KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
return newKeyless(privateKeyMethod, Files.newInputStream(chain.toPath()));
}
/**
* Creates a new factory instance.
*
* @param privateKeyMethod the {@link BoringSSLAsyncPrivateKeyMethod} that is used for key signing.
* @param chain the {@link InputStream} that contains the {@link X509Certificate} chain.
* @return a new factory instance.
* @throws CertificateException on error.
* @throws IOException on error.
* @throws KeyStoreException on error.
* @throws NoSuchAlgorithmException on error.
* @throws UnrecoverableKeyException on error.
*/
public static BoringSSLKeylessManagerFactory newKeyless(BoringSSLAsyncPrivateKeyMethod privateKeyMethod,
InputStream chain)
throws CertificateException, IOException,
KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
return newKeyless(privateKeyMethod, QuicSslContext.toX509Certificates0(chain));
}
/**
* Creates a new factory instance.
*
* @param privateKeyMethod the {@link BoringSSLAsyncPrivateKeyMethod} that is used for key signing.
* @param certificateChain the {@link X509Certificate} chain.
* @return a new factory instance.
* @throws CertificateException on error.
* @throws IOException on error.
* @throws KeyStoreException on error.
* @throws NoSuchAlgorithmException on error.
* @throws UnrecoverableKeyException on error.
*/
public static BoringSSLKeylessManagerFactory newKeyless(BoringSSLAsyncPrivateKeyMethod privateKeyMethod,
X509Certificate... certificateChain)
throws CertificateException, IOException,
KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
checkNotNull(certificateChain, "certificateChain");
KeyStore store = new KeylessKeyStore(certificateChain.clone());
store.load(null, null);
BoringSSLKeylessManagerFactory factory = new BoringSSLKeylessManagerFactory(
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()), privateKeyMethod);
factory.init(store, null);
return factory;
}
private static final class KeylessManagerFactorySpi extends KeyManagerFactorySpi {
private final KeyManagerFactory keyManagerFactory;
KeylessManagerFactorySpi(KeyManagerFactory keyManagerFactory) {
this.keyManagerFactory = requireNonNull(keyManagerFactory, "keyManagerFactory");
}
@Override
protected void engineInit(KeyStore ks, char[] password)
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
keyManagerFactory.init(ks, password);
}
@Override
protected void engineInit(ManagerFactoryParameters spec) {
throw new UnsupportedOperationException("Not supported");
}
@Override
protected KeyManager[] engineGetKeyManagers() {
return keyManagerFactory.getKeyManagers();
}
}
private static final class KeylessKeyStore extends KeyStore {
private static final String ALIAS = "key";
private KeylessKeyStore(final X509Certificate[] certificateChain) {
super(new KeyStoreSpi() {
private final Date creationDate = new Date();
@Override
public Key engineGetKey(String alias, char[] password) {
if (engineContainsAlias(alias)) {
return BoringSSLKeylessPrivateKey.INSTANCE;
}
return null;
}
@Override
public Certificate[] engineGetCertificateChain(String alias) {
return engineContainsAlias(alias)? certificateChain.clone() : null;
}
@Override
public Certificate engineGetCertificate(String alias) {
return engineContainsAlias(alias)? certificateChain[0] : null;
}
@Override
public Date engineGetCreationDate(String alias) {
return engineContainsAlias(alias)? creationDate : null;
}
@Override
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain)
throws KeyStoreException {
throw new KeyStoreException("Not supported");
}
@Override
public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException {
throw new KeyStoreException("Not supported");
}
@Override
public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException {
throw new KeyStoreException("Not supported");
}
@Override
public void engineDeleteEntry(String alias) throws KeyStoreException {
throw new KeyStoreException("Not supported");
}
@Override
public Enumeration<String> engineAliases() {
return Collections.enumeration(Collections.singleton(ALIAS));
}
@Override
public boolean engineContainsAlias(String alias) {
return ALIAS.equals(alias);
}
@Override
public int engineSize() {
return 1;
}
@Override
public boolean engineIsKeyEntry(String alias) {
return engineContainsAlias(alias);
}
@Override
public boolean engineIsCertificateEntry(String alias) {
return engineContainsAlias(alias);
}
@Override
public String engineGetCertificateAlias(Certificate cert) {
if (cert instanceof X509Certificate) {
for (X509Certificate x509Certificate : certificateChain) {
if (x509Certificate.equals(cert)) {
return ALIAS;
}
}
}
return null;
}
@Override
public void engineStore(OutputStream stream, char[] password) {
throw new UnsupportedOperationException();
}
@Override
public void engineLoad(InputStream stream, char[] password) {
if (stream != null && password != null) {
throw new UnsupportedOperationException();
}
}
}, null, "keyless");
}
}
}

@ -0,0 +1,43 @@
/*
* Copyright 2022 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.quic;
import io.netty.util.internal.EmptyArrays;
import java.security.PrivateKey;
final class BoringSSLKeylessPrivateKey implements PrivateKey {
static final BoringSSLKeylessPrivateKey INSTANCE = new BoringSSLKeylessPrivateKey();
private BoringSSLKeylessPrivateKey() {
}
@Override
public String getAlgorithm() {
return "keyless";
}
@Override
public String getFormat() {
return "keyless";