Giter VIP home page Giter VIP logo

hakky54 / sslcontext-kickstart Goto Github PK

View Code? Open in Web Editor NEW
475.0 8.0 76.0 4.19 MB

πŸ” A lightweight high level library for configuring a http client or server based on SSLContext or other properties such as TrustManager, KeyManager or Trusted Certificates to communicate over SSL TLS for one way authentication or two way authentication provided by the SSLFactory. Support for Java, Scala and Kotlin based clients with examples. Available client examples are: Apache HttpClient, OkHttp, Spring RestTemplate, Spring WebFlux WebClient Jetty and Netty, the old and the new JDK HttpClient, the old and the new Jersey Client, Google HttpClient, Unirest, Retrofit, Feign, Methanol, Vertx, Scala client Finagle, Featherbed, Dispatch Reboot, AsyncHttpClient, Sttp, Akka, Requests Scala, Http4s Blaze, Kotlin client Fuel, http4k Kohttp and Ktor. Also gRPC, WebSocket and ElasticSearch examples are included

Home Page: https://sslcontext-kickstart.com/

License: Apache License 2.0

Java 99.99% Shell 0.01%
tls ssl certificate keystore truststore mutual-authentication java security https scala

sslcontext-kickstart's Introduction

Hello there πŸ‘‹

  • πŸ‘¨β€πŸ’» I'm Hakan AltΔ±ndağ and working as a freelance software engineer
  • πŸ”­ I’m currently working on Backend Development
  • 🌱 I’m mainly using Java and ElasticSearch
  • πŸ’¬ Ask me about anything, I am happy to help
  • πŸ˜„ Pronouns: Coder, Leader and Kind Hearted
  • πŸ’‘ Occasionaly I do participate in Hackathons
  • πŸ‘¨ Know more about me at Dzone
  • 🌐 Visit my LinkedIn for complete background and contact.
  • πŸ’₯ awesome octoprofile : Hakan AltΔ±ndağ


Get in touch:

Linkedin Badge Github Badge Stack Exchange reputation Gitter


Some Statistics Fun

trophy

Written articles
Used languages and tools









sslcontext-kickstart's People

Contributors

allcontributors[bot] avatar chibenwa avatar dependabot-preview[bot] avatar dependabot[bot] avatar ecki avatar fossabot avatar gitter-badger avatar hakky54 avatar henryju avatar manbucy avatar mbenson avatar nquinquenel avatar snyk-bot avatar sullis avatar tadhgpearson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sslcontext-kickstart's Issues

If multiple certificates are configured, the browser cannot obtain the correct certificate after the host address is entered

Hello, I have configured two certificates through your library, the domain name of one certificate is www.gateway.com.cn, and the domain name of the other certificate is www.ingress.com.cn. My code is written like this

@Bean
    public WebServerFactoryCustomizer<NettyReactiveWebServerFactory> sslServerConsumer() {
        return factory -> {
            factory.addServerCustomizers(httpServer -> httpServer.secure(sslContextSpec -> {
                try {
                    X509ExtendedKeyManager x509ExtendedKeyManager = PemUtils.loadIdentityMaterial(
                            getResource("classpath:ssl/default/server.pem"),
                            getResource("classpath:ssl/default/server-key.pem"));
                    X509ExtendedTrustManager x509ExtendedTrustManager = PemUtils.loadTrustMaterial(getResource("classpath:ssl/default/ca.pem"));
                    SSLFactory.Builder builder = SSLFactory.builder()
                            .withIdentityMaterial(x509ExtendedKeyManager)
                            .withTrustMaterial(x509ExtendedTrustManager);
                    loadOtherCertificate(builder);
                    builder.withProtocols("TLSv1.2");
                    SSLFactory sslFactory = builder.build();
                    System.out.println("ssl init success");
                    X509ExtendedKeyManager keyManager = sslFactory.getKeyManager()
                            .orElseThrow(NullPointerException::new);
                    SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(composeKeyManager((CompositeX509ExtendedKeyManager) keyManager))
                            .ciphers(sslFactory.getCiphers(), SupportedCipherSuiteFilter.INSTANCE)
                            .protocols(sslFactory.getProtocols())
                            .clientAuth(getClientAuth(sslFactory.getSslParameters()));
                    sslFactory.getTrustManager().ifPresent(sslContextBuilder::trustManager);
                    sslContextSpec.sslContext(sslContextBuilder);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }));
        };
    }

    private KeyManager composeKeyManager(CompositeX509ExtendedKeyManager keyManager) {
        return new CustomKeyManager(keyManager.getKeyManagers());
    }

    private void loadOtherCertificate(SSLFactory.Builder builder) throws IOException {
        X509ExtendedKeyManager x509ExtendedKeyManager = PemUtils.loadIdentityMaterial(
                getResource("classpath:ssl/ingress/server.pem"),
                getResource("classpath:ssl/ingress/server-key.pem"));
        X509ExtendedTrustManager x509ExtendedTrustManager = PemUtils.loadTrustMaterial(
                getResource("classpath:ssl/ingress/ca.pem"));
        builder.withIdentityMaterial(x509ExtendedKeyManager)
                .withTrustMaterial(x509ExtendedTrustManager);
    }

    private static ClientAuth getClientAuth(SSLParameters sslParameters) {
        if (sslParameters.getNeedClientAuth()) {
            return ClientAuth.REQUIRE;
        } else if (sslParameters.getWantClientAuth()) {
            return ClientAuth.OPTIONAL;
        } else {
            return ClientAuth.NONE;
        }
    }

    private InputStream getResource(String path) throws IOException {
        Resource resource = ResourceUtils.getResource(path);
        return resource.getInputStream();
    }

When I input www.ingress.com.cn on the browser, the console printed www.gateway.com.cn, there is no other way to match the correct certificate, and the certificate displayed on my browser is www.gateway.com.cn, can you help me

image

Client Certificate not presented by Apache HTTP Client when loaded in SSL Context

First, awesome idea for a project πŸ‘

Describe the bug
When using the PEM Utils and SSL Factory to create an SSL Context for Apache HTTP Client with a client cert, Apache then does not present the client cert.

I'm following your tutorials and have checked the Apache manual too, so I think I'm doing this right

To Reproduce

  1. git clone https://github.com/tadhgpearson/sslfactory-client-cert-test.git
  2. mvn verify

Expected behavior
The SSLContextFactory in this repository uses kickstart to read the cert, CA chain and key file for the client cert, and should build an SSL Context with both the default trust material and this key and trust material.

Then the SSLContextFactoryTest uses Apache HTTP Client and should present the loaded client certificate to the test site... but it doesn't.

Environmental Data:

  • Java Version 11
  • Maven Version 3.6.3
  • Mac OS Catalina

Heads up, thank you for this gem!

Just wanted to thank you for making and maintaining this little gem here.

Very flexible with that build and solves basically all scenarios i could think of. Please take my credits :)

Set Enabled Protocols

Hello,

I could not find a way to set enabled protocols in the sslcontext. This would be useful, if the client want to reject server which supports only old version (say TLSv1.0).

for example:


public SSLFactory.Builder withAllowedProtocols(String[] allowedProtocols) {
      this.allowedProtocols = allowedProtocols;
      return this;
}
private void createSSLContext(KeyManager[] keyManagers, TrustManager[] trustManagers) {
        try {
            this.sslContext = SSLContext.getInstance(this.protocol);
            this.sslContext.init(keyManagers, trustManagers, this.secureRandom);
            //Add following line
            this.sslContext.getDefaultSSLParameters().setProtocols(this.allowedProtocols);
        } catch (KeyManagementException | NoSuchAlgorithmException var4) {
            throw new GenericSSLContextException(var4);
        }
    }

Regards
Winster

Request support check general key with tools PemUtils

//X509ExtendedTrustManager trustManager = PemUtils.loadTrustMaterial("<path_key>");
X509ExtendedKeyManager keyManager = PemUtils.loadIdentityMaterial("path_key_cer", "path_client_key", "scretKeyPass");
SSLFactory sslFactory = SSLFactory.builder()
.withTrustMaterial(trustManager)
.withIdentityMaterial(keyManager)
.build();

SSLFactory sslFactory = SSLFactory.builder()
.withIdentityMaterial(keyManager)
//.withTrustMaterial(trustManager)
.build();

URL wsURL = new URL(urlServer);
HttpsURLConnection httpsConn = (HttpsURLConnection) wsURL.openConnection();
httpsConn.setSSLSocketFactory(sslFactory.getSslSocketFactory());

Hi [sslcontext-kickstart] I using your tools to load key for client site call request, Now I want config a nginx proxy to handler redirect request other server, I can change config urlServer in olds server, and key path_key, path_key_cer, path_client_key, but now I cannot change code server old. How any solution config nginx with key tool PemUtils.loadIdentityMaterial;

2023/01/31 13:44:32 [info] 32#32: *4 SSL_do_handshake() failed (SSL: error:14094416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown:SSL alert number 46) while SSL handshaking, client: 172.17.0.1, server: 0.0.0.0:443

I have try some solution but cannot https://egkatzioura.com/2021/09/24/add-ssl-to-nginx/;
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

org.bouncycastle.pkcs.PKCSException

Describe the bug

i use permUtil to load the perm certificate, a Exception was thrown

To Reproduce

X509ExtendedKeyManager keyManager = PemUtils.parseIdentityMaterial(certificate.getCertificate(), certificate.getPrivateKey(), certificate.getPassphrase().toCharArray());

the error is

Caused by: org.bouncycastle.pkcs.PKCSException: unable to read encrypted data: 1.2.840.113549.1.5.13 not available: Wrong algorithm: AES or Rijndael required
	at org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo.decryptPrivateKeyInfo(Unknown Source)
	at nl.altindag.ssl.decryptor.BouncyFunction.lambda$andThen$0(BouncyFunction.java:22)
	at nl.altindag.ssl.util.PemUtils.extractPrivateKeyInfo(PemUtils.java:493)
	... 55 common frames omitted
Caused by: org.bouncycastle.operator.OperatorCreationException: 1.2.840.113549.1.5.13 not available: Wrong algorithm: AES or Rijndael required
	at org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder$1.get(Unknown Source)
	... 58 common frames omitted
Caused by: java.security.InvalidKeyException: Wrong algorithm: AES or Rijndael required
	at com.sun.crypto.provider.AESCrypt.init(AESCrypt.java:83)
	at com.sun.crypto.provider.CipherBlockChaining.init(CipherBlockChaining.java:93)
	at com.sun.crypto.provider.CipherCore.init(CipherCore.java:591)
	at com.sun.crypto.provider.CipherCore.init(CipherCore.java:619)
	at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:355)
	at javax.crypto.Cipher.implInit(Cipher.java:810)
	at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
	at javax.crypto.Cipher.init(Cipher.java:1539)
	at javax.crypto.Cipher.init(Cipher.java:1470)
	... 59 common frames omitted

JDK version: Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
System: Ubuntu SMP Fri Aug 10 11:14:32 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

however this is ok when using jdk1.8.0_291.jdk

what should i do when using jdk 1.8.0_131-b11?

"The BC provider no longer provides an implementation for KeyFactory.RSA."

Describe the bug
On Android >= Android 9/P (API 28) I get the following error in logcat:

FATAL EXCEPTION: DefaultDispatcher-worker-1
    Process: myapp, PID: 28762
    nl.altindag.ssl.exception.PrivateKeyParseException: org.bouncycastle.openssl.PEMException: unable to convert key pair: The BC provider no longer provides an implementation for KeyFactory.RSA.  Please see https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html for more details.
        at nl.altindag.ssl.util.PemUtils.extractPrivateKey(PemUtils.java:454)
        at nl.altindag.ssl.util.PemUtils.$r8$lambda$s6ElOTWwPljNhjlxXLkUrjqZZdY(Unknown Source:0)
        at nl.altindag.ssl.util.PemUtils$$ExternalSyntheticLambda10.apply(Unknown Source:2)
        at java.util.Optional.map(Optional.java:211)
        at nl.altindag.ssl.util.PemUtils.parsePrivateKey(PemUtils.java:421)
        at nl.altindag.ssl.util.PemUtils.parseIdentityMaterial(PemUtils.java:334)
        at nl.altindag.ssl.util.PemUtils.loadIdentityMaterial(PemUtils.java:306)
        at nl.altindag.ssl.util.PemUtils.loadIdentityMaterial(PemUtils.java:232)
        at nl.altindag.ssl.util.PemUtils.loadIdentityMaterial(PemUtils.java:224)
        ...
     Caused by: org.bouncycastle.openssl.PEMException: unable to convert key pair: The BC provider no longer provides an implementation for KeyFactory.RSA.  Please see https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html for more details.
        at org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter.getPrivateKey(Unknown Source:48)
        at nl.altindag.ssl.util.PemUtils.extractPrivateKey(PemUtils.java:452)
        at nl.altindag.ssl.util.PemUtils.$r8$lambda$s6ElOTWwPljNhjlxXLkUrjqZZdY(Unknown Source:0)Β 
        at nl.altindag.ssl.util.PemUtils$$ExternalSyntheticLambda10.apply(Unknown Source:2)Β 
        at java.util.Optional.map(Optional.java:211)Β 
        at nl.altindag.ssl.util.PemUtils.parsePrivateKey(PemUtils.java:421)Β 
        at nl.altindag.ssl.util.PemUtils.parseIdentityMaterial(PemUtils.java:334)Β 
        at nl.altindag.ssl.util.PemUtils.loadIdentityMaterial(PemUtils.java:306)Β 
        at nl.altindag.ssl.util.PemUtils.loadIdentityMaterial(PemUtils.java:232)Β 
        at nl.altindag.ssl.util.PemUtils.loadIdentityMaterial(PemUtils.java:224)Β 
        ...
     Caused by: java.security.NoSuchAlgorithmException: The BC provider no longer provides an implementation for KeyFactory.RSA.  Please see https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html for more details.
        at sun.security.jca.Providers.checkBouncyCastleDeprecation(Providers.java:386)
        at sun.security.jca.Providers.checkBouncyCastleDeprecation(Providers.java:336)
        at java.security.KeyFactory.getInstance(KeyFactory.java:235)
        at org.bouncycastle.jcajce.util.NamedJcaJceHelper.createKeyFactory(Unknown Source:2)
        at org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter.getKeyFactory(Unknown Source:20)
        at org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter.getPrivateKey(Unknown Source:4)

The error links to this site: https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html

This is my code, how I use this library:

// load private client cert
val cert = javaClass.getResourceAsStream("/credentials/myCert.pem")
val key = javaClass.getResourceAsStream("/credentials/myKey.pem")
if (cert == null || key == null)
    throw Exception("Private certificate or key missing.")
val keyManager = PemUtils.loadIdentityMaterial(cert, key)

// activate client ssl in fuel
val sslFactory = SSLFactory.builder()
    .withIdentityMaterial(keyManager)
    .build()
FuelManager.instance.socketFactory = sslFactory.sslSocketFactory

Environmental Data:

  • Android >= Android 9/P (API 28)
  • io.github.hakky54:sslcontext-kickstart-for-pem:7.2.0
  • I tested several emulators with different Android versions, and it works on devices < API 28, and doesn't work on devices >= API 28

PemUtils parses can't handle single line keys or certs

Describe the bug
A clear and concise description of what the bug is.
PemUtils parsers (parseIdentityMaterial and parseTrustMaterial, etc) require that the -----BEGIN PRIVATE KEY----- sections ends with newline. This is not required and makes it so that it breaks one

-----BEGIN PRIVATE KEY-----KEYSTUFHEREASDASDASD-----END PRIVATE KEY-----

and

-----BEGIN CERTIFICATE-----KEYSTUFHEREASDASDASD-----END CERTIFICATE-----

To Reproduce

  1. Provide as much of a code sample as possible.
  2. provide full stack traces if possible

use any of the PemUtils parses with a single line key info and watch it crash

Expected behavior
A clear and concise description of what you expected to happen.
Handle single line keys and certs with ease.

Screenshots
If applicable, add screenshots to help explain your problem.

Environmental Data:

  • Java Version 11
  • Maven Version -
  • OS Windows

InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Windows

Hi @Hakky54

With the latest version 8.1.0, our QA pipeline failed on Windows (sorry, I made all my previous tests on Linux) with:

javax.net.ssl.SSLException: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
	at org.apache.hc.core5.reactor.ssl.SSLIOSession.convert(SSLIOSession.java:317)
	at org.apache.hc.core5.reactor.ssl.SSLIOSession.doWrap(SSLIOSession.java:324)
	at org.apache.hc.core5.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:367)
	at org.apache.hc.core5.reactor.ssl.SSLIOSession.access$100(SSLIOSession.java:74)
	at org.apache.hc.core5.reactor.ssl.SSLIOSession$1.inputReady(SSLIOSession.java:201)
	at org.apache.hc.core5.reactor.InternalDataChannel.onIOEvent(InternalDataChannel.java:142)
	at org.apache.hc.core5.reactor.InternalChannel.handleIOEvent(InternalChannel.java:51)
	... 5 more
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
	at java.base/java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200)
	at java.base/java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120)
	at java.base/java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104)
	at java.base/sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:99)
	at java.base/sun.security.validator.Validator.getInstance(Validator.java:181)
	at java.base/sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:300)
	at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:176)
	at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:246)
	at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:141)
	at nl.altindag.ssl.trustmanager.CompositeX509ExtendedTrustManager.lambda$checkServerTrusted$5(CompositeX509ExtendedTrustManager.java:91)
	at nl.altindag.ssl.trustmanager.CombinableX509TrustManager.checkTrusted(CombinableX509TrustManager.java:40)
	at nl.altindag.ssl.trustmanager.CompositeX509ExtendedTrustManager.checkServerTrusted(CompositeX509ExtendedTrustManager.java:91)
	at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1335)

Not sure what is the problem...

The failing test is here:
https://github.com/SonarSource/sonarlint-core/blob/130de06eb43f48452138145a05bd4f4647dcdd7d/core/src/test/java/mediumtest/SslMediumTests.java#L110

And this is how we setup the SSLFactory:
https://github.com/SonarSource/sonarlint-core/blob/130de06eb43f48452138145a05bd4f4647dcdd7d/http/src/main/java/org/sonarsource/sonarlint/core/http/HttpClientProvider.java#L57

Trusting a pem certificate

Describe the bug
Thanks for this library, it looks exactly like what I'm looking for: adding a root certificate as trusted so that HTTPS works for all certificates issued by that root certificate.
I however am not sure how to use it, all examples load both a trust material and an identity material, and I only have a public certificate in the pem format. I thought I'd be able to just call SSLFactory.builder().withTrustMaterial(buildTrustManager()).build(); but I'm getting an exception.

To Reproduce

git clone https://github.com/Athou/ssl-test
cd ssl-test
mvn test

I then get the following exception

javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1964)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1921)
        at sun.security.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1904)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1420)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:347)
        at test.SslTest.test(SslTest.java:35)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
        at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:91)
        at sun.security.validator.Validator.getInstance(Validator.java:181)
        at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:312)
        at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:171)
        at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:184)
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1596)
        at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1052)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:987)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1072)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
        at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
        ... 37 more
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
        at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200)
        at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120)
        at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104)
        at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:89)

Expected behavior
The test passes since mockserver issues certificates that have the CertificateAuthorityCertificate.pem as root, as described here https://www.mock-server.com/mock_server/HTTPS_TLS.html (in the "Ensure MockServer Certificates Are Trusted" section)

Environmental Data:

  • Java Version: 8
  • Maven Version: 3.5
  • OS: Windows

Any help would be greatly appreciated :)

android 6.0 Caused by: java.lang.NoClassDefFoundError

Describe the bug
I use android 12、13 platform is work.But use android 6 is crash.

code:

SSLFactory sslFactory = SSLFactory.builder().withTrustMaterial(bks file, password).build
crash log

Caused by: java.lang.NoClassDefFoundError: nl.altindag.ssl.util.KeyStoreUtils$$ExternalSyntheticLambda0 at nl.altindag.ssl.util.KeyStoreUtils.<clinit>(KeyStoreUtils.java:56) at nl.altindag.ssl.SSLFactory$Builder.withTrustMaterial(SSLFactory.java:366)

Expected behavior
I generate SSLSocketFactory crash

Screenshots
image

Environmental Data:

  • android targetsdkversion 32
  • android compilesdkversion 32
  • java 8
  • Gradle: io.github.hakky54:sslcontext-kickstart:7.4.9

Certificate Revocation List?

Today the library do not allow to easily turn on Certificate Revocation List checks.

I would like to have an easy option to turn on OCSP checks using eg PKIXRevocationChecker

EG:

SSLContext context = sslFactoryBuilder.enableCRLOCSPChecks(true)
    .build()
    .getSslContext();

Context: As an email server writter I receive many connections from third parties and checking their certificate validity is rather important,

Support for using multiple identity materials and trust materials not working

Hello,

First of all, a big thanks for this project.
It is well written, well documented, and very helpful!

I am opening an issue regarding the "Support for using multiple identity materials and trust materials" as I believe it might not be behaving correctly.

In order to illustrate my example, I am going to simplify to two different services (instead of a large number)

First service I need to talk to: OrderService. It is a service where one will place orders. (I order a video game, I order a bicycle)

Second service I need to take to, DeliveryService. It is a service where one will deliver something to someone. It can work a standalone, I deliver this contract to this person, often used in conjunction of OrderService, I deliver the video game I just ordered to someone.

The two companies owning the services are competing company, they will enforce client to have it their own keystores. No way possible to go to one company and say: If I bring you the certificate I use to talk to the other service, can you trust it as well? No no.

In order to perform such, I am using this library, where I beforehand verified.

 SSLFactory sslFactory = SSLFactory.builder()
                    .withIdentityMaterial(Paths.get(/path/to/orderservice/client-to-talk-to-orderservice-keystore.p12), "talkToOrderService".toCharArray())
                    .withTrustMaterial(Paths.get(/path/to/truststore.p12), "trustStorePassPhrase".toCharArray())
                    .build();
            return NettySslUtils.forClient(sslFactory).build();

This is working fine to talk to order service

But also, I verified,

 SSLFactory sslFactory = SSLFactory.builder()
                    .withIdentityMaterial(Paths.get(/path/to/deliveryservice/client-to-talk-to-deliveryservice-keystore.p12), "talkToDeliveryService".toCharArray())
                    .withTrustMaterial(Paths.get(/path/to/truststore.p12), "trustStorePassPhrase".toCharArray())
                    .build();
            return NettySslUtils.forClient(sslFactory).build();

This is working fine to talk to delivery service (mock the step to talk to order service)

Now, chaining the two calls, first talk to order service, then to delivery service.

 SSLFactory sslFactory = SSLFactory.builder()
                    .withIdentityMaterial(Paths.get(/path/to/orderservice/client-to-talk-to-orderservice-keystore.p12), "talkToOrderService".toCharArray())
                    .withIdentityMaterial(Paths.get(/path/to/deliveryservice/client-to-talk-to-deliveryservice-keystore.p12), "talkToDeliveryService".toCharArray())
                    .withTrustMaterial(Paths.get(/path/to/truststore.p12), "trustStorePassPhrase".toCharArray())
                    .build();
            return NettySslUtils.forClient(sslFactory).build();

This still yields javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca; nested exception is io.netty.handler.codec.DecoderException: javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca

Could you please help?

Thank you

Provide method to set default Truststore

Is your feature request related to a problem? Please describe.
I was trying to add Truststore to all SSLContext that will be used in the app
Currently this lib requires manual injection of SSLContext into all connection libraries to achieve it.
It's cumbersome when there are few higher level libraries that are using different connection libraries under the hood (eg Apache and OkHttp).

Describe the solution you'd like
It would be good to set single TruststoreFactory (or SSLContext factory) that will generate desired objects.

Additional context
I created a simple TrustManagerFactory that provides TrustManagers.
I would be good to have this functionality out of the box in this lib.

public class SingletonTrustManagerFactorySpi extends TrustManagerFactorySpi {

    private static TrustManager[] trustManagers;

    public static void setTrustManager(TrustManager aTrustManager) {
        trustManagers = new TrustManager[]{aTrustManager};
    }

    @Override
    protected void engineInit(KeyStore keyStore) {
        log.info("Ignoring provided keystore to SingletonTrustManager");
    }

    @Override
    protected void engineInit(ManagerFactoryParameters managerFactoryParameters) {
        log.info("Ignoring provided ManagerFactoryParameters");
    }

    @Override
    protected TrustManager[] engineGetTrustManagers() {
        return trustManagers;
    }
}
public class SingletonTrustManagerFactoryProvider extends Provider {

    public SingletonTrustManagerFactoryProvider() {
        super("TrustManagerFactoryProvider", 1.0, "Provides TrustManagerFactory");
        Service service = new Service(this,
                "TrustManagerFactory",
                "PKIX",
                SingletonTrustManagerFactorySpi.class.getName(),
                ImmutableList.of("SunPKIX", "X509", "X.509"),
                Collections.emptyMap());
        putService(service);
    }
}

This method should be available in TrustManagerUtils

    public void setDefaultTrustManager(TrustManager trustManager) {
        SingletonTrustManagerFactorySpi.setTrustManager(trustManager);

        ProviderList providerList = ProviderList.insertAt(Providers.getProviderList(),
                new SingletonTrustManagerFactoryProvider(), 0);
        Providers.setProviderList(providerList);
    }

Easy way to specify KeyManagerFactory type (PKIX instead of SunX509)

Is your feature request related to a problem? Please describe.
I want to use the New (PKIX) Key Manager (instead of SunX509) for some client auth Keystores. Currently I use factory.withIdendityMaterial(keystore) which internally uses the default KeyStoreManager (which defaults to the SunX509 legacy manager).

Describe the solution you'd like
Adding a withIdendityMaterial(KeyStore ks, String keyManagerType) or allowing to configure the default would help.

Describe alternatives you've considered
There are alternatives using the withIdendityMaterial(KeyManager p), but that requires two utility calls to get a Keystore and a KeyManager first. Is that the intended way?

Example SSL / TLS Configuration for Http Clients

Every http client will have a slightly different configuration for encryption/https and therefor as a developer we need to dive into their documentation to find examples, this will be unfortunately time-consuming. Some clients just only require SSLContext, others will need a SocketFactory, SSLSocketFactory, TrustManager, X509TrustManager, X509ExtendedTrustManager, KeyManager, X509KeyManager, X509ExtendedKeyManager, DefaultSSLParameters or a list of trusted certificates. I wanted to provide an overview of http clients configuration as a cheat-sheet to make our lives easier.

Below is an overview of client configuration examples with and without TLS/SSL enabled and with basic http requests. The examples are from the github project mutual-tls-ssl, which is a practical tutorial for configuring a client and a server for four scenarios:

  • No security
  • One way authentication
  • Two way authentication
  • Two way authentication with trusting the Certificate Authority

Example client configuration and example requests / Cheatsheet

All client examples use the same base ssl configuration created within the SSLConfig class

Java

Kotlin

Scala

Feel free to ask for other client examples here

Add support for Java Platform Module System

End users should still be able to use this library with java 8 while it is also compatible with java modules (Java 11+)
Every maven module should contain module-info.java
Internal libraries should be encapsulated and if required only exposed to sub maven modules.

To be expected:

  • New major release
  • Breaking changes (package name changes in submodules as it is conflicting with the core module)
  • Internal api with public access modifiers will be moved to a sub package internal and will be locked with modules

KeychainStore Ignored Exception on macOS

Describe the bug
On macOS, a KeychainStore exception is printed on the error stream instead of being logged or thrown. This exception happens when a certificate provided by the system has multiple "X509v3 Extended Key Usage" sections.

To Reproduce

  1. On macOS, load any system certificate that has duplicate extensions
  2. The following text should be printed on the err stream of the command line :
    KeychainStore Ignored Exception: java.security.cert.CertificateParsingException: java.io.IOException: Duplicate extensions not allowed

Expected behavior
The system should not print the error instead of logging it, expecially for command line apps.

Environmental Data:

  • Any Java Version
  • Any Maven Version
  • MacOS

Additional context
The faulty code is available on openjdk repository at
https://github.com/openjdk/jdk16/blob/020ec8485251698d1187204ac13321f4726e45ea/src/java.base/macosx/classes/apple/security/KeychainStore.java#L810
https://github.com/openjdk/jdk16/blob/37043b05576c8b81b43ac41a8f06de0d0bbb3f5b/src/java.base/share/classes/sun/security/x509/CertificateExtensions.java#L105

I've written a quick and dirty workaround that decorate the err stream to log the exception instead of printing it.

My question is: is there a better solution?

No end-to-end tests?

Do you have test cases for your various sample configurations that confirm they're secure? Without that it's difficult to trust this project with such a critical security responsibility.

Keystore password is unnecessary

Hello,

First of all, thanks for the handy library. I have a suggestion to drop the keystore password as it is redundant (client would have already a Keystore at hand) in the api that takes KeyStore as the first argument.

For example, this is how I use your library.

SSLFactory.Builder sslFactoryBuilder = SSLFactory.builder()
                                                         .withDefaultTrustMaterial();
        if ((trustStoreResource != null) && (trustStorePassword != null)) {
            KeyStore trustStore = KeyStore.getInstance("PKCS12");
            trustStore.load(trustStoreResource.getInputStream(),
                            trustStorePassword.toCharArray());
            sslFactoryBuilder.withTrustMaterial(
                trustStore, trustStorePassword.toCharArray());
        }

And as you can see, sslFactoryBuilder.withTrustMaterial(trustStore, trustStorePassword.toCharArray());, password is not required there.

Getting All Certificates

Thanks for creating should a great library!

I have a question about getting all the certificates associated with the SSLFactory but I am coming up blank on how exactly to get access to all of them.

I create a factory using the following code:

var builder = SSLFactory.builder()
    .withSwappableTrustMaterial()
    .withSwappableIdentityMaterial()

Followed by either of the following two flows depending on if I am processing a JKS or PEM

//JKS
builder
    .withTrustMaterial(get(<PATH>), <PASSWORD>.toCharArray())
    .withIdentityMaterial(get(<PATH>), <PASSWORD>.toCharArray())

//PEM
builder
    .withTrustMaterial(loadTrustMaterial(get(<PATH>))))
    .withIdentityMaterial(loadIdentityMaterial(get(<PATH>), get(<PATH>)))

var factory = builder.build();

I would like to be able to get all the certificates in use by this factory which I naively thought would be returned by the following call:

factory.getTrustedCertificates()

This seems to only return the certificates loaded using withTrustMaterial which in retrospect makes sense. Is there any way to get the certificates loaded via the withIdentityMaterial calls?

I did some poking around and it seemed that the following gets close:

var key = factory.getKeyManager().get();

Inside the manager there is a credentialsMap which chooses an alias based on the certificates used as the second parameter of withIdentityMaterial but the manager doesn't return a list of the all the aliases.

Any help or suggestions you can provide would be greatly appreciated. Thanks!

Method names withDefaultTrustMaterial vs withSystemTrustMaterial

Currently (at least for me suprisingly) those methods mean this semantically (under linux at least)

withDefaultTrustMaterial adds the default for the system ca store, under linux e.g. ca-certificates which lets you validate officially signed certificates

withSystemTrustMaterial adds the support for OS bases keystores of the user to expand the validation with custom imported certificates. For linux, there is no standard keystore (unless you use android).

Iam not sure what withDefaultTrustMaterial does under macos/windows, i assume that withSystemTrustMaterial under macos actually adds the ability to validate official certificates AND custom certificates.

My suggestion would be to fill up what we know about those methods for each os and then reconsider, if the naming still fits or even if it is very much OS specific.

  • MacOS: IMHO withDefaultTrustMaterial does nothing under macos, withSystemTrustMaterial adds support for official and custom cert validation
  • Linux: withDefaultTrustMaterial adds support for official certificates, while withSystemTrustMaterial does nothing
  • Android: IMHO withDefaultTrustMaterial adds support for official certificates, while withSystemTrustMaterial does add special android certificates (not sure about both).
  • Windows: TBA

The inverse behavior for Linux/MacOS is what concerns me. It's a tripwire i would say

android platform I don't want to use user imported self-signed CA?

Hello, I hava a question about load system cert .

    fun OkHttpClient.Builder.setSSLCertificate(
        trustManager: X509TrustManager,
        bksFile: InputStream? = null,
        password: String? = null,
    ) = apply {
        try {
            val trustManagerFinal: X509TrustManager = trustManager
            val keyManagers = prepareKeyManager(bksFile, password)

            var factory = SSLFactory.builder()
                .withDefaultTrustMaterial()
                .withSystemTrustMaterial()
                .build()

            var combine = TrustManagerUtils.combine(
                trustManagerFinal,
                factory.trustManager.get(),
                factory.trustManager.get()
            )
            factory.sslContext.init(keyManagers, arrayOf<TrustManager?>(combine), null)
            // ι€šθΏ‡sslContextθŽ·ε–SSLSocketFactory对豑
            sslSocketFactory(factory.sslContext.socketFactory,trustManagerFinal)
        } catch (e: NoSuchAlgorithmException) {
            throw AssertionError(e)
        } catch (e: KeyManagementException) {
            throw AssertionError(e)
        }
    }

When I used the sslContext above for my OKHTTP, I found that the CA manually imported by the user in the settings was also added. How to separate CA certificates manually imported by users? I don't want to use the user imported system CA, I just want to use the system pre installed CA certificate

            withDefaultTrustMaterial(), withSystemTrustMaterial()  

The two lines of code load the pre-installed certificate of the Android system and the CA installed by the user. I don't want this. I only need the pre-installed CA of the Android system and the CA certificate I use to load the code, which will be much safer.

PEM helpers to generate easiy a key pair programatically?

Is your feature request related to a problem? Please describe.

As discussed in this email on the James mailing list https://www.mail-archive.com/[email protected]/msg70783.html we are considering adding on-the-fly generation for SSL cryptographic materials as an option.

The goal being to conciliate two requirements:

  • Not shipping default keys - administrators NOT updating the default configuration would be trivially exposed to man-in-the-middle attacks...
  • But at the same time have one signle command startup (docker run ...)

One solution being on the fly key generation.

Describe the solution you'd like

I would enjoy having methods in PEM util (or another one) to create such keys / KeyManager...

Describe alternatives you've considered

Specifying a startup script in the dockerfile creating the keys if missing. Could work too.

Suitable for my demo image where I already have a bash wrapper in place ( apache/james-project#628 contributes it) yet making it more generic to the other production grade docker image can not rely on this approach but might benefit from this 'feature' - for instance people could try the Distributed James docker compose in a single docker-compose up command.

Additional context

James ticket: https://issues.apache.org/jira/browse/JAMES-3640

CombinableX509TrustManager can't completed all trustManager's check

Describe the bug
Hi, i found that CombinableX509TrustManager can't completed all trustManager's check, when some trustManager's trustdCerts is empty.

To Reproduce

public class ElasticsearchTest {
    @Test
    public void test_connect_elasticsearch_server() throws IOException {
        SSLFactory sslFactory = SSLFactory.builder()
                .withSystemTrustMaterial()
                .withTrustMaterial(CertificateUtils.loadCertificate("http_ca.crt"))
                .build();
        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "es123456"));

        RestClient restClient = RestClient.builder(new HttpHost("192.168.169.2", 39200, "https"))
                .setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder
                        .setDefaultCredentialsProvider(basicCredentialsProvider)
                        .setSSLContext(sslFactory.getSslContext())
                        .setSSLHostnameVerifier(sslFactory.getHostnameVerifier())
                )
                .build();
        RestClientTransport restClientTransport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient elasticsearchClient = new ElasticsearchClient(restClientTransport);
        IndicesResponse indices = elasticsearchClient.cat().indices();
    }
}

in withSystemTrustMaterial(), it would load Windows-ROOT keystore and Windows-MY keystore, but now my Windows-MY keystore certicate is empty.
in withTrustMaterial(CertificateUtils.loadCertificate("http_ca.crt")), it would load the elasticsearch's certicate.
trustmanagers

the error is:

Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
	at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:200)
	at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:120)
	at java.security.cert.PKIXBuilderParameters.<init>(PKIXBuilderParameters.java:104)
	at sun.security.validator.PKIXValidator.<init>(PKIXValidator.java:99)
	at sun.security.validator.Validator.getInstance(Validator.java:181)
	at sun.security.ssl.X509TrustManagerImpl.getValidator(X509TrustManagerImpl.java:299)
	at sun.security.ssl.X509TrustManagerImpl.checkTrustedInit(X509TrustManagerImpl.java:175)
	at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:245)
	at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:140)
	at nl.altindag.ssl.trustmanager.CompositeX509ExtendedTrustManager.lambda$checkServerTrusted$6(CompositeX509ExtendedTrustManager.java:110)
	at nl.altindag.ssl.trustmanager.CombinableX509TrustManager.checkTrusted(CombinableX509TrustManager.java:40)
	at nl.altindag.ssl.trustmanager.CompositeX509ExtendedTrustManager.checkServerTrusted(CompositeX509ExtendedTrustManager.java:110)
	at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:630)
	at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(CertificateMessage.java:471)
	at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(CertificateMessage.java:367)
	at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:376)
	at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:479)
	at sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:990)
	at sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:977)
	at java.security.AccessController.doPrivileged(Native Method)
	at sun.security.ssl.SSLEngineImpl$DelegatedTask.run(SSLEngineImpl.java:924)
	at org.apache.http.nio.reactor.ssl.SSLIOSession.doRunTask(SSLIOSession.java:288)
	at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:356)
	... 9 more

I found in CombinableX509TrustManager will check all the TrustManager whether to support the current certificate chain. As a result of my second TrustManage from Windows-MY trustCerts is empty, so when executing callBackConsumer.checkTrusted(trustManager); method throws InvalidAlgorithmParameterException, but my third TrustManager actually can trust the current certificate.
image

Whether all exceptions can be caught in CombinableX509TrustManager.checkTrusted so that all TrustManagers have a chance to be executed, or whether callBackConsumer.checkTrusted(trustManager); is not executed when the trustCerts of the trustManager is empty.

Although I could have avoided this problem in my example by removing .withSystemTrustMaterial(), I think it's still possible that someone could load multiple TrustManagers at the same time, and the trustCerts of one of them might be empty.

Environmental Data:

  • Java Version 1.8.0_321
  • sslcontext-kickstart Version 7.4.2
  • OS: Windows

public methods for getting trustStore, keyStore, KeyManager, TrustManager out of the SSLFactory

Hi, nice project ... I like it.

My request would be:

once I have created and "loaded" everything I want into the val sslFactory: SSLFactory

it would be nice if I could pass this around and still be able to also get the finer building blocks of it.

I'd love to have public(!) methods on it (or somewhere else) to get its

  • trustStore (KeyStore)
  • keyStore (KeyStore)
  • X509ExtendedKeyManager
  • X509ExtendedTrustManager
  • etc.

maybe it is already possible, and I just didn't find on where to find it "in the deeper API"

thanx for considering!

Version 7.4.3 fails to accept all certificates

Describe the bug
It seems that changes in version 7.4.3 skips accept-all truststore configured using
builder.withUnsafeTrustMaterial() or builder.withTrustingAllCertificatesWithoutValidation()

This is because UnsafeX509ExtendedTrustManager has 0 accepted X509Certificate
therefore it is skipped during checking in CombinableX509TrustManager

To Reproduce

SSLFactory.Builder builder = SSLFactory.builder().withDefaultTrustMaterial();
builder.withUnsafeTrustMaterial();
SSLFactory factory = builder.build();

SSLContext sslContext = factory.getSslContext();
SSLContext.setDefault(sslContext);

Expected behavior
Validation of the TLS certificate should pass and connection should be established

Environmental Data:

  • Java Version 11.0
  • Gradle
  • OS MacOS

Additional context
The test passes with 7.3.0 and 7.4.2

No warning for non existent system keystore

Currently, we see that if there is no system keystore (which basically will be the case for all linux based os) a warning is logged

        if (keyStores.isEmpty()) {
            LOGGER.warn("No system KeyStores available for [{}]", operatingSystem);
            return Collections.emptyList();
        }

Considering that this would be the case for all linux systems except android, i would suggest either of this

  • Do log info for linux, warn for all other os
  • log info for all other os

What is your intention / idea with this, could you share it? Thanks!

CVE-2019-20444 io.netty:netty-tcnative-classes:jar:2.0.48.Final:compile (version managed from 2.0.48.Final)

Hello Hakan,

Just wanted to report something, hope you are well!

I upgraded to the latest 7.3.0 version of this project, but after analysis, this is highlighted:

[INFO] +- io.github.hakky54:sslcontext-kickstart-for-netty:jar:7.3.0:compile
[INFO] |  +- io.github.hakky54:sslcontext-kickstart:jar:7.3.0:compile
[INFO] |  |  \- (org.slf4j:slf4j-api:jar:1.7.36:compile - version managed from 1.7.36; omitted for duplicate)
[INFO] |  \- io.netty:netty-handler:jar:4.1.74.Final:compile (version managed from 4.1.74.Final)
[INFO] |     +- io.netty:netty-common:jar:4.1.74.Final:compile (version managed from 4.1.74.Final)
[INFO] |     |  \- (org.graalvm.nativeimage:svm:jar:19.3.6:provided - omitted for conflict with 21.0.0.2)
[INFO] |     +- io.netty:netty-resolver:jar:4.1.74.Final:compile (version managed from 4.1.74.Final)
[INFO] |     |  \- (io.netty:netty-common:jar:4.1.74.Final:compile - version managed from 4.1.74.Final; omitted for duplicate)
[INFO] |     +- io.netty:netty-buffer:jar:4.1.74.Final:compile (version managed from 4.1.74.Final)
[INFO] |     |  \- (io.netty:netty-common:jar:4.1.74.Final:compile - version managed from 4.1.74.Final; omitted for duplicate)
[INFO] |     +- io.netty:netty-transport:jar:4.1.74.Final:compile (version managed from 4.1.74.Final)
[INFO] |     |  +- (io.netty:netty-common:jar:4.1.74.Final:compile - version managed from 4.1.74.Final; omitted for duplicate)
[INFO] |     |  +- (io.netty:netty-buffer:jar:4.1.74.Final:compile - version managed from 4.1.74.Final; omitted for duplicate)
[INFO] |     |  \- (io.netty:netty-resolver:jar:4.1.74.Final:compile - version managed from 4.1.74.Final; omitted for duplicate)
[INFO] |     +- io.netty:netty-codec:jar:4.1.74.Final:compile (version managed from 4.1.74.Final)
[INFO] |     |  +- (io.netty:netty-common:jar:4.1.74.Final:compile - version managed from 4.1.74.Final; omitted for duplicate)
[INFO] |     |  +- (io.netty:netty-buffer:jar:4.1.74.Final:compile - version managed from 4.1.74.Final; omitted for duplicate)
[INFO] |     |  \- (io.netty:netty-transport:jar:4.1.74.Final:compile - version managed from 4.1.74.Final; omitted for duplicate)
[INFO] |     \- io.netty:netty-tcnative-classes:jar:2.0.48.Final:compile (version managed from 2.0.48.Final)

The thing is, io.netty:netty-tcnative-classes:jar:2.0.48.Final is known to have the vulnerability:
CVE-2019-20444

Is there a way to bump this to a version that is safe?

Thank you!

Using BC fails with Java 1.8.292+

stacktrace:

Error:  nl.altindag.ssl.util.PemUtilsShould.loadEncryptedIdentityMaterialFromDirectory  Time elapsed: 0.031 s  <<< ERROR!
nl.altindag.ssl.exception.GenericIOException: nl.altindag.ssl.exception.GenericKeyStoreException: java.security.KeyStoreException: Key protection  algorithm not found: java.security.UnrecoverableKeyException: Encrypt Private Key failed: unrecognized algorithm name: PBEWithSHA1AndDESede
	at nl.altindag.ssl.util.PemUtilsShould.loadEncryptedIdentityMaterialFromDirectory(PemUtilsShould.java:310)
Caused by: nl.altindag.ssl.exception.GenericKeyStoreException: java.security.KeyStoreException: Key protection  algorithm not found: java.security.UnrecoverableKeyException: Encrypt Private Key failed: unrecognized algorithm name: PBEWithSHA1AndDESede
	at nl.altindag.ssl.util.PemUtilsShould.loadEncryptedIdentityMaterialFromDirectory(PemUtilsShould.java:310)
Caused by: java.security.KeyStoreException: Key protection  algorithm not found: java.security.UnrecoverableKeyException: Encrypt Private Key failed: unrecognized algorithm name: PBEWithSHA1AndDESede
	at nl.altindag.ssl.util.PemUtilsShould.loadEncryptedIdentityMaterialFromDirectory(PemUtilsShould.java:310)
Caused by: java.security.UnrecoverableKeyException: Encrypt Private Key failed: unrecognized algorithm name: PBEWithSHA1AndDESede
	at nl.altindag.ssl.util.PemUtilsShould.loadEncryptedIdentityMaterialFromDirectory(PemUtilsShould.java:310)
Caused by: java.security.NoSuchAlgorithmException: unrecognized algorithm name: PBEWithSHA1AndDESede
	at nl.altindag.ssl.util.PemUtilsShould.loadEncryptedIdentityMaterialFromDirectory(PemUtilsShould.java:310)

See bug report at oracle to get the latest update: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8266261

the alias of CertificateEntry

Describe the bug
Hello, I am going to create an SSLContext with the following code, but the resulting SSLContext does not appear to be complete and its trustedCerts is empty.

    SSLFactory sslFactory = SSLFactory.builder()
            .withTrustMaterial(CertificateUtils.loadCertificate("ca.crt"))
            .build();
    SSLContext sslContext = sslFactory.getSslContext();

image

the content of ca.crt

-----BEGIN CERTIFICATE-----
MIIFWTCCA0GgAwIBAgIUW4b6bPPPyRAm0DrDKKJJ8YlSqOkwDQYJKoZIhvcNAQEL
BQAwPDE6MDgGA1UEAxMxRWxhc3RpY3NlYXJjaCBzZWN1cml0eSBhdXRvLWNvbmZp
Z3VyYXRpb24gSFRUUCBDQTAeFw0yMjA0MDUxMjQ1MzVaFw0yNTA0MDQxMjQ1MzVa
MDwxOjA4BgNVBAMTMUVsYXN0aWNzZWFyY2ggc2VjdXJpdHkgYXV0by1jb25maWd1
cmF0aW9uIEhUVFAgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDB
q3aR//NaqXBUqI0AVHuVWJmFMLYwpi/DQLUYifwOlGx4iAb6ePuiA8b7tXAGPn0z
TWFQ82t0DZf/1nXoRmNJO8ardAVWcL7z+VDUY7Hab08GJzRRP/V5b7VL+J+WBQOG
auN0cal3jM14k3FeZApyoL+XqmJ36MSY3WtAPfF3ySH1ltcMguXqN79k3Bxw0mGq
AJt+z4q8Lq2e8vsMKKpSO1vZ0grvffj6MBni2stfZ4ifA6Kubh/yePShKsG/N8nY
K6iJYjwLuVUQ1Eaw6X3s78c+eESTlzZiM6I7qTR1JzW5Fuyz/ZPbDcI1zg+p9H4g
NRaX76Fv9XG/XehLeYxNoTBLytY2d9kdEmW9MIGCqaROabDdxygxcJ5l3aqkBTiA
tq42vguuiQvpLndfGIEA4qh5AFyo+iqP1226+1onHfeXtbtyqjpHIV6RZa8RqNLg
ynmf96NzzHQq1CfKp5CgQB/l3yaAtFxguNyhKftHia518iTjcUpn9f3gmSzDlZy2
KgzZMaw8GwdtT+qac3XCVI7vwjY21uEHbCEklh8ZycAt28Dc0h747MqG9A3xdMDV
lf8iBtGjuxQNJSsOBRY6Up8ajEWeYvEqpKDHVHYxc78qdjGCzltgGIvjzah389mH
UC458l4Ey4Lns4C7NVAteHva9L71CE/zDTwJ3nECqwIDAQABo1MwUTAdBgNVHQ4E
FgQUphpsq/WD1QUsRkr9EQaGinawo9owHwYDVR0jBBgwFoAUphpsq/WD1QUsRkr9
EQaGinawo9owDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAlg8X
PnpSKIkt+a9imOFcddUgoNSCgwAyBuGdnUKTjuDnV2630O7cRky4Ly8gI3hxuV3j
I0JHatPA4Xw8m/8rAkgoega4zCQ89L7w8g1b54NnvnMOQIKs4aQ7TsYQUgyGxj6j
hhs1uLEBgF/uCJR1INZbiw4tjGTJssRSGMUsn7Mto0+3UL3AHqbmQY4IavRDEd2s
zpyGN1acwh9jl50pcKjgM/UYhNgWvGQgOF7MP8+4BWXBn9O7ufdUt4n08yPFP5hn
sOKrScnTCPIVn3uExcYDLDEuRDsQXfDvD03Bm6aFPC+qwr+W7k8WZPc7UW3vLzTg
TPtvnFwTunD3Bzv14b+2BOQH+caOKVyjBn73HzXQ6Xp8KM6ef3+6RZTeomHhqAwr
TG2vVsLzDhZiNjOE1Le3UeT4eAz7psgg+piouaXkY5FnVmMlNqWGkXfmvtMC8JzG
uWGUtSV2plImhQMgfrF4wMhntiNQcHa0Fge0k4I4ajt/HD5Al4yMYCMzx7ocbZLg
bTSDn+PuRt1NBZYC/Icz6L3CaSAVCMIEw145G/ytyu9annHs+hXSx+1ji3MHkF/g
yE65FKuMXoHLhCdN9MoKFEDr6eLlY7l9HWbcfQGpePoX4L/g1nGMVQmssCChkH5r
h5BvtLZEjAtAP6q1Al0phYV6eYQvLE8Dzbw0RQ0=
-----END CERTIFICATE-----

Environmental Data:

  • Java Version 1.8.0_202
  • sslcontext-kickstart Version 7.3.0
  • OS: Windows

Additional context
I found out the cause of the problem, when create X509TrustManagerImpl, its trustedCerts is already empty.
sun.security.ssl.X509TrustManagerImpl
image

sun.security.validator.KeyStores.getTrustedCerts(KeyStore var0)
image

java.security.KeyStore.isCertificateEntry(String alias)
image

sun.security.pkcs12.PKCS12KeyStore.engineIsCertificateEntry(String var1)
the entries keys has the capital letters, but the parameter var1 is lowercase letters
image

Can you consider changing alias to lowercase in the nl.altindag.ssl.util.KeyStoreUtils.createTrustStore(List<T> certificates)
image
or nl.altindag.ssl.util.CertificateUtils.generateAlias(Certificate certificate)
image

SSLFactory withTrustMaterial with null (empty password)

Hello.

I'm trying to load my own TrustMaterial which i have in my own JKS keystore.
But I see you have a validations in all the overloaded methods withTrustMaterial that the password can not be NULL or empty char[].
Do i really need to add a password to my keystore? Right now my JKS has no password at all.

SSLFactory sslFactory = SSLFactory.builder()
        .withDefaultTrustMaterial()
        .withTrustMaterial("keystore/custom-keystore.jks", null)
        .build();

Rename sslcontext package to a generic name

Initially SSLFactory was named SSLContextHelper and it was the only class within the package. Therefor it made sense to name the package nl.altindag.sslcontext.* As the library grows and contains other functionalities such as KeyStoreUtils, TrustManagerUtils, KeyManagerUtils, CompositeX509ExtendedKeyManager, CompositeX509ExtendedTrustManager, PemUtils, JettySslContextUtils, NettySslContextUtils, ApacheSslContextUtils it would make more sense to group them in a more generic name such as nl.altindag.ssl.*

Remove/Disable logging in unsafe HostnameVerifier and TrustManager

the logging in the unsafe variants of HostnameVerifier and TrustManager spam logs. There should be a way to disable this or at least log it to DEBUG.

I see no reason why i would like to know that a self signed certificate is trusted. that's exactly what i want to do else i wouldn't use this specific verifier.

FenixHostnameVerifier issues

Should this be an endsWith()?

can the !empty be removed if you check for size=2 anyway?

.filter(subjectAlternativeName -> !subjectAlternativeName.isEmpty())

Is this intentionally not checking CN?

Collection<List<?>> subjectAlternativeNames = Optional.ofNullable(certificate.getSubjectAlternativeNames())

i can provide a PR for those issues if youmagree it needs to be fixed.

this verifier should probably also carry a warning that it does not know/forbid patterns in TLDs (*.co.uk instead of *.dom.co.uk or even *.com)?

[HELP] Use of .PEM and self signed

Hi,
I'm working with .pem files that out supplier give us.
In DEV environment, it provided us 3 files:

  • certificate
  • private key
  • ca root (self-signed)
X509ExtendedKeyManager keyManager = PemUtils.loadIdentityMaterial(
   //certificate
   Paths.get("certificate.pem"),

   //private key
   Paths.get("private-key.pem"));

//trusted certificate
X509ExtendedTrustManager trustManager = PemUtils.loadTrustMaterial(
   Paths.get("caroot.pem"));


SSLFactory sslFactory = SSLFactory.builder()
   .withIdentityMaterial(keyManager)
   .withTrustMaterial(trustManager)
   .build();

SSLContext contestoSSL = sslFactory.getSslContext();

I pass the context to Spring Integration.
When I call the service, I got:

org.apache.cxf.binding.soap.SoapFault: Policy Falsified

To be honest, I got the same error without using your library but using directly trustore and keystore.
The problem arise some weeks ago only in DEV enviroment.
To avoid the "problem" to update and/or re-create trustore and keystore from .pem files every time the supplier give us a new version of .pem files, we tried to move to a smarter way and your library is the perfect choice for that.
But we got the same error.

Using CURL it works!

curl --location 'https://webserver/service.ws' \
--key "./private-key.pem" \
-E "./certificate.pem" \
--cacert "./caroot.pem" \
--header 'SoapAction: http://....' \
--header 'Content-Type: text/xml' \
--data '<?xml version="1.0" encoding="UTF-8"?><xml>.....</xml>'

If anyone has any suggestions we greatly appreciate it.

Thanks!
Daniele

BasicHostnameVerifier is broken?

It appears that BasicHostnameVerifier doesn't actually check that the hostname in the URL matches the hostname in the SAN part of the peer’s certificate.

As a consequence, a server that had a certificate for say attacker.com could be verified against a client request to victim.com.

`SSLFactory.Builder.withDefaultIdentityMaterial` method

When custom sslContext is created there is no easy way to load "default" keyManager
, although withDefaultTrustMaterial allows it do so for trustManager.

It would be nice to have withDefaultIdentityMaterial method that would utilize default keyManager (javax.net.ssl.keyStore)

Documentation suggests to use

.withIdentityMaterial(Paths.get(System.getProperty("javax.net.ssl.keyStore")), System.getProperty("javax.net.ssl.keyStorePassword").toCharArray(), 
System.getProperty("javax.net.ssl.keyStoreType"))

which probably does the trick, but does not handle the cases when properties are not set. Helper method would do null checks and remove boilerplate code from users of SSLFactory.

And Maybe there is a way to get a reference to internal keyManage. I haven't found one.

How do I use this library with JDBC?

Hello,

Thanks for creating this library. I followed the example to load PEM files to build an SSLFactory. What's next? How do I use it to connect to a MySQL server using JDBC securely, with the server CA certificate and the client's private/public key pairs? I tried a few things but couldn't get anywhere. Thank you!

support keystores on the filesystem instead of only on the classpath

My usecase:
I deploy my application in a docker container in different environments. The appropriate keystore and truststore is mounted in the containers filesystem. In my application I just want to reference "/mnt/certs/truststore.jks", but the current code uses KeyStoreUtils.class.getClassLoader().getResourceAsStream(keystorePath) which only searches in the classpath.
I'd like support for absolute paths on the filesystem.

To not break backwards compatibility, maybe first search in the classpath and if nothing is found try reading from the filesystem.

Misleading NullPointerException when reading an encrypted PEM key and none supplied

Describe the bug

When an encrypted PEM private key is used without supplying a password, a null pointer exception is being returned.

There is not way for the library user (an probably my end users too) to know the reason of this failure is that a password is required.

To Reproduce

            X509ExtendedKeyManager[] x509ExtendedKeyManager = {PemUtils.loadIdentityMaterial(
                        "certs.crt",
                        "encrypted.private.key",
                        null)};
                        
                     
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(kmf.getKeyManagers(), null, null);

Results in :

java.lang.NullPointerException: null
        at java.base/java.util.Objects.requireNonNull(Objects.java:221)
        at nl.altindag.ssl.util.PemUtils.lambda$static$1(PemUtils.java:92)
        at nl.altindag.ssl.util.PemUtils.parsePrivateKey(PemUtils.java:416)
        at nl.altindag.ssl.util.PemUtils.parseIdentityMaterial(PemUtils.java:329)
        at nl.altindag.ssl.util.PemUtils.loadIdentityMaterial(PemUtils.java:301)
        at nl.altindag.ssl.util.PemUtils.loadIdentityMaterial(PemUtils.java:227)

Expected behavior

I expect a dedicated exception with an easy to understand message...

Environmental Data:

  • Java 11 (OpenJDK 11.0.11)
  • Maven 3.6.3
  • Ubuntu

Additional context

I could end up using this library in a contribution to Apache James to not just support keystores but also PEM files.

The ease of use is appealing though I need users to understand by themselves their mistakes before reaching the community (including I) and says stuff like "your soft is not working there is a NPE" without understanding the mistake is theirs...

BTW I could fire a patch if my above proposal is deemed acceptable.

New System Keystores in Windows

With Java 11.0.18 and 17.0.5 a long standing issue (https://bugs.openjdk.org/browse/JDK-6782021) with Windows-MY was solved. This includes the introduction of new keystore types in SunMSCAPI

From: https://bugs.openjdk.org/browse/JDK-8286790

The Windows KeyStore support in the SunMSCAPI provider has been expanded to include access to the local machine location. The new keystore types are:

  • "Windows-MY-LOCALMACHINE"
  • "Windows-ROOT-LOCALMACHINE"

The following keystore types were also added, allowing developers to make it clear they map to the current user:

  • "Windows-MY-CURRENTUSER" (same as "Windows-MY")
  • "Windows-ROOT-CURRENTUSER" (same as "Windows-ROOT")

Perhaps it could be generated automatically from something like:

    try {
        final Provider p = Security.getProvider("SunMSCAPI");
        for(final Enumeration e = p.keys(); e.hasMoreElements();) {
            final String name = e.nextElement().toString();
            if (name.startsWith("KeyStore.")) {
                System.out.println(name.substring(9));
            }

            }
    } catch (final Exception e) {
        System.out.println(e);
    }

Which returns in Java 11/17

Windows-MY-CURRENTUSER
Windows-MY-LOCALMACHINE
Windows-ROOT-LOCALMACHINE
Windows-ROOT-CURRENTUSER
Windows-ROOT
Windows-MY

Could this be added in the KeyStoreUtils.loadSystemKeyStores() ? The new Windows-MY-LOCALMACHINE is very useful for services that run on ACME certificates published automatically to the store (e.g. with win.acme)

Simplify use of system truststore

Under Windows and MacOS, it is possible to use the system truststore in addition to regular keystores.
With the current library, it can be achieved by a code like this:

SSLFactory.Builder result = SSLFactory
                .builder()
                .withDefaultTrustMaterial();
if (isWindows()) {
  KeyStore root = KeyStore.getInstance("Windows-ROOT");
  root.load(null, null);
  result.withTrustMaterial(root, new char[0]);
  KeyStore my = KeyStore.getInstance("Windows-MY");
  my.load(null, null);
  result.withTrustMaterial(my, new char[0]);
} else if (isMacos()) {
  KeyStore keychain = KeyStore.getInstance("KeychainStore");
  keychain.load(null, null);
  result.withTrustMaterial(keychain, new char[0]);
}

I would prefer to have something like:

SSLFactory.Builder result = SSLFactory
                .builder()
                .withDefaultTrustMaterial()
                .withSystemTrustMaterial();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.