JSSE: add LDAPS endpoint identification to X509ExtendedTrustManager

pull/227/head
Chris Conlon 2024-09-05 15:23:44 -06:00
parent ad59d749f1
commit e01db4b4d9
12 changed files with 815 additions and 161 deletions

View File

@ -776,7 +776,7 @@ JNIEXPORT jint JNICALL Java_com_wolfssl_WolfSSLCertificate_X509_1check_1host
hostname = (*jenv)->GetStringUTFChars(jenv, chk, 0); hostname = (*jenv)->GetStringUTFChars(jenv, chk, 0);
if (hostname != NULL) { if (hostname != NULL) {
/* flags and peerNamePtr not used */ /* peerNamePtr not used */
ret = wolfSSL_X509_check_host(x509, hostname, ret = wolfSSL_X509_check_host(x509, hostname,
XSTRLEN(hostname), (unsigned int)flags, NULL); XSTRLEN(hostname), (unsigned int)flags, NULL);
} }

View File

@ -549,6 +549,11 @@ public class WolfSSL {
* level with WolfSSLContext.setDevId() and WolfSSLSession.setDevId() */ * level with WolfSSLContext.setDevId() and WolfSSLSession.setDevId() */
public static int devId = WolfSSL.INVALID_DEVID; public static int devId = WolfSSL.INVALID_DEVID;
/* ------------------------- Flag Values ---------------------------- */
/** WolfSSLCertificate.checkHost() match only wildcards in left-most
* position, used for LDAPS hostname verification. */
public static int WOLFSSL_LEFT_MOST_WILDCARD_ONLY = 0x40;
/* ---------------------------- locks ------------------------------- */ /* ---------------------------- locks ------------------------------- */
/* lock for cleanup */ /* lock for cleanup */

View File

@ -1439,10 +1439,32 @@ public class WolfSSLCertificate implements Serializable {
*/ */
public int checkHost(String hostname) throws IllegalStateException { public int checkHost(String hostname) throws IllegalStateException {
return checkHost(hostname, 0);
}
/**
* Checks that given hostname matches this certificate SubjectAltName
* or CommonName entries, behavior can be controlled via flags.
*
* @param hostname Hostname to check certificate against
* @param flags Flags to control hostname check behavior. Supported options
* include WolfSSL.WOLFSSL_LEFT_MOST_WILDCARD_ONLY to only match
* wildcards on left-most position.
*
* @return WolfSSL.SSL_SUCCESS on successful hostname match,
* WolfSSL.SSL_FAILURE on invalid match or error, or
* WolfSSL.NOT_COMPILED_IN if native wolfSSL has been compiled
* with NO_ASN defined and native API is not available.
*
* @throws IllegalStateException if WolfSSLCertificate has been freed.
*/
public int checkHost(String hostname, long flags)
throws IllegalStateException {
confirmObjectIsActive(); confirmObjectIsActive();
synchronized (x509Lock) { synchronized (x509Lock) {
return X509_check_host(this.x509Ptr, hostname, 0, 0); return X509_check_host(this.x509Ptr, hostname, flags, 0);
} }
} }

View File

@ -50,7 +50,8 @@ import java.security.cert.Certificate;
/** /**
* wolfSSL implementation of X509TrustManager, extends * wolfSSL implementation of X509TrustManager, extends
* X509ExtendedTrustManager for additional hostname verification for HTTPS. * X509ExtendedTrustManager for additional hostname verification for
* HTTPS (RFC 2818) and LDAPS (RFC 2830).
* *
* @author wolfSSL * @author wolfSSL
*/ */
@ -59,6 +60,11 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
private KeyStore store = null; private KeyStore store = null;
/** X509ExtendedTrustManager hostname type HTTPS */
private static int HOSTNAME_TYPE_HTTPS = 1;
/** X509ExtendedTrustManager hostname type LDAPS */
private static int HOSTNAME_TYPE_LDAPS = 2;
/** /**
* Create new WolfSSLTrustX509 object * Create new WolfSSLTrustX509 object
* *
@ -430,18 +436,25 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
} }
/** /**
* Verify hostname using HTTPS verification method. * Verify hostname using HTTPS or LDAPS verification method.
* *
* This method does the following operations in an attempt to verify * For HTTPS hostname verification (RFC 2818):
* the HTTPS type hostname:
* *
* 1. If SNI name has been received during TLS handshake, try to * - If SNI name has been received during TLS handshake, try to
* first verify peer certificate against that. Skip this step when * first verify peer certificate against that. Skip this step when
* on server side verifying the client, since server does not set * on server side verifying the client, since server does not set
* an SNI for the client. * an SNI for the client.
* 2. Otherwise, try to verify certificate against SSLSocket * - Otherwise, try to verify certificate against SSLSocket or SSLEngine
* hostname (SSLSession.getHostName()). * hostname (getHandshakeSession().getHostName()).
* 3. If both of the above fail, fail hostname verification. * - If both of the above fail, fail hostname verification.
* - Hostname matching rules for HTTPS come from RFC 2818
*
* For LDAPS hostname verification (RFC 2830):
*
* - Try to verify certificate against hostname used to create
* the SSLSocket or SSLEngine, obtained via
* getHandshakeSession().getPeerHost().
* - Hostname matching rules for LDAPS come from RFC 2830
* *
* @param cert peer certificate * @param cert peer certificate
* @param socket SSLSocket associated with connection to peer. Only one * @param socket SSLSocket associated with connection to peer. Only one
@ -452,10 +465,13 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
* null. * null.
* @param isClient true if we are calling this from client side, otherwise * @param isClient true if we are calling this from client side, otherwise
* false if calling from server side. * false if calling from server side.
* @param type type of hostname to verify, options are
* HOSTNAME_TYPE_HTTPS or HOSTNAME_TYPE_LDAPS
* @throws CertificateException if hostname cannot be verified * @throws CertificateException if hostname cannot be verified
*/ */
private void verifyHTTPSHostname(X509Certificate cert, SSLSocket socket, private void verifyHostnameByType(X509Certificate cert, SSLSocket socket,
SSLEngine engine, boolean isClient) throws CertificateException { SSLEngine engine, boolean isClient, int type)
throws CertificateException {
String peerHost = null; String peerHost = null;
List<SNIServerName> sniNames = null; List<SNIServerName> sniNames = null;
@ -464,8 +480,16 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
WolfSSLCertificate peerCert = null; WolfSSLCertificate peerCert = null;
int ret = WolfSSL.SSL_FAILURE; int ret = WolfSSL.SSL_FAILURE;
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO, if (type == HOSTNAME_TYPE_HTTPS) {
"verifying HTTPS hostname"); WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"verifying hostname type HTTPS");
} else if (type == HOSTNAME_TYPE_LDAPS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"verifying hostname type LDAPS");
} else {
throw new CertificateException("Unsupported hostname type, " +
"HTTPS and LDAPS only supported currently: " + type);
}
/* Get session associated with SSLSocket or SSLEngine */ /* Get session associated with SSLSocket or SSLEngine */
try { try {
@ -485,12 +509,15 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
peerHost = session.getPeerHost(); peerHost = session.getPeerHost();
} }
/* Get SNI name if SSLSocket has received that from peer. Only check /* Get SNI name if SSLSocket/SSLEngine has received that from peer.
* this when on the client side and verifying a server since SNI * Only check this when on the client side and verifying a server since
* holding expected server name is available on client-side but not * SNI holding expected server name is available on client-side but not
* vice-versa */ * vice-versa. Also only checked for HTTPS type, not LDAPS. As per
if (session != null && isClient && * RFC 2830, the client MUST use the server hostname it used to open
(session instanceof ExtendedSSLSession)) { * the LDAP connection. */
if ((session != null) && isClient &&
(session instanceof ExtendedSSLSession) &&
(type == HOSTNAME_TYPE_HTTPS)) {
sniNames = ((ExtendedSSLSession)session).getRequestedServerNames(); sniNames = ((ExtendedSSLSession)session).getRequestedServerNames();
for (SNIServerName name : sniNames) { for (SNIServerName name : sniNames) {
@ -517,8 +544,8 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
throw new CertificateException(e); throw new CertificateException(e);
} }
/* Try verifying hostname against SNI name */ /* Try verifying hostname against SNI name, if HTTPS type */
if (isClient) { if (isClient && (type == HOSTNAME_TYPE_HTTPS)) {
if (sniHostName != null) { if (sniHostName != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO, WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"trying hostname verification against SNI: " + sniHostName); "trying hostname verification against SNI: " + sniHostName);
@ -541,13 +568,18 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
} }
} }
/* Try verifying hostname against peerHost from SSLSocket/Engine */ /* Try verifying hostname against peerHost from SSLSocket/SSLEngine */
if (peerHost != null) { if (peerHost != null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO, WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"trying hostname verification against peer host: " + "trying hostname verification against peer host: " + peerHost);
peerHost);
ret = peerCert.checkHost(peerHost); if (type == HOSTNAME_TYPE_LDAPS) {
/* LDAPS requires wildcard left-most matching only */
ret = peerCert.checkHost(peerHost,
WolfSSL.WOLFSSL_LEFT_MOST_WILDCARD_ONLY);
} else {
ret = peerCert.checkHost(peerHost);
}
if (ret == WolfSSL.SSL_SUCCESS) { if (ret == WolfSSL.SSL_SUCCESS) {
/* Hostname successfully verified against peer host name */ /* Hostname successfully verified against peer host name */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO, WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
@ -558,10 +590,16 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
} }
if (isClient) { if (isClient) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO, if (type == HOSTNAME_TYPE_HTTPS) {
"hostname verification failed for server peer cert, " + WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"tried SNI (" + sniHostName + "), peer host (" + peerHost + "hostname verification failed for server peer cert, " +
")\n" + peerCert); "tried SNI (" + sniHostName + "), peer host (" + peerHost +
")\n" + peerCert);
} else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"hostname verification failed for server peer cert, " +
"peer host (" + peerHost + ")\n" + peerCert);
}
} else { } else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO, WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"hostname verification failed for client peer cert, " + "hostname verification failed for client peer cert, " +
@ -593,7 +631,7 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
SSLParameters sslParams = null; SSLParameters sslParams = null;
SSLSession session = null; SSLSession session = null;
/* Hostname verification only done if Socket is of SSLSocket, /* Hostname verification on Socket done only if Socket is of SSLSocket,
* not null, and connected */ * not null, and connected */
if ((socket != null) && (socket instanceof SSLSocket) && if ((socket != null) && (socket instanceof SSLSocket) &&
(socket.isConnected())) { (socket.isConnected())) {
@ -614,8 +652,15 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO, WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"verifying hostname, endpoint identification " + "verifying hostname, endpoint identification " +
"algorithm = HTTPS"); "algorithm = HTTPS");
verifyHTTPSHostname(cert, (SSLSocket)socket, verifyHostnameByType(cert, (SSLSocket)socket,
null, isClient); null, isClient, HOSTNAME_TYPE_HTTPS);
}
else if (endpointIdAlgo.equals("LDAPS")) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"verifying hostname, endpoint identification " +
"algorithm = LDAPS");
verifyHostnameByType(cert, (SSLSocket)socket,
null, isClient, HOSTNAME_TYPE_LDAPS);
} }
else { else {
throw new CertificateException( throw new CertificateException(
@ -647,7 +692,15 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO, WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"verifying hostname, endpoint identification " + "verifying hostname, endpoint identification " +
"algorithm = HTTPS"); "algorithm = HTTPS");
verifyHTTPSHostname(cert, null, engine, isClient); verifyHostnameByType(cert, null, engine, isClient,
HOSTNAME_TYPE_HTTPS);
}
else if (endpointIdAlgo.equals("LDAPS")) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
"verifying hostname, endpoint identification " +
"algorithm = LDAPS");
verifyHostnameByType(cert, null, engine, isClient,
HOSTNAME_TYPE_LDAPS);
} }
else { else {
throw new CertificateException( throw new CertificateException(
@ -708,13 +761,13 @@ public final class WolfSSLTrustX509 extends X509ExtendedTrustManager
* Try to build and validate the client certificate chain based on the * Try to build and validate the client certificate chain based on the
* provided certificates and authentication type. * provided certificates and authentication type.
* *
* Also does hostname verification internally if Endpoint Identification * Does hostname verification internally if Endpoint Identification
* Algorithm has been set by application in SSLParameters, and that * Algorithm has been set by application in SSLParameters, and that
* Algorithm matches "HTTPS". If that is set, hostname verification is * Algorithm matches "HTTPS" or "LDAPS". If "HTTPS" is set, hostname
* done using SNI first then peer host value. * verification is done using SNI first then peer host value.
* *
* Other Endpoint Identification Algorithms besides "HTTPS" are not * Other Endpoint Identification Algorithms besides "HTTPS" and "LDAPS"
* currently supported. * are not currently supported.
* *
* @param certs peer certificate chain * @param certs peer certificate chain
* @param type authentication type based on the client certificate * @param type authentication type based on the client certificate

View File

@ -25,11 +25,15 @@ import com.wolfssl.WolfSSL;
import com.wolfssl.WolfSSLException; import com.wolfssl.WolfSSLException;
import com.wolfssl.provider.jsse.WolfSSLProvider; import com.wolfssl.provider.jsse.WolfSSLProvider;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException; import java.security.NoSuchProviderException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.UnrecoverableKeyException;
import java.security.Provider; import java.security.Provider;
import java.security.Security; import java.security.Security;
import java.security.cert.Certificate; import java.security.cert.Certificate;
@ -122,7 +126,10 @@ public class WolfSSLEngineTest {
@Test @Test
public void testSSLEngine() public void testSSLEngine()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
SSLEngine e; SSLEngine e;
/* create new SSLEngine */ /* create new SSLEngine */
@ -142,7 +149,10 @@ public class WolfSSLEngineTest {
@Test @Test
public void testSSLEngineSetCipher() public void testSSLEngineSetCipher()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
SSLEngine e; SSLEngine e;
String sup[]; String sup[];
boolean ok = false; boolean ok = false;
@ -197,7 +207,10 @@ public class WolfSSLEngineTest {
@Test @Test
public void testCipherConnection() public void testCipherConnection()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
String cipher = null; String cipher = null;
@ -305,7 +318,9 @@ public class WolfSSLEngineTest {
@Test @Test
public void testBeginHandshake() public void testBeginHandshake()
throws NoSuchProviderException, NoSuchAlgorithmException, throws NoSuchProviderException, NoSuchAlgorithmException,
SSLException { SSLException, KeyManagementException, KeyStoreException,
CertificateException, IOException, UnrecoverableKeyException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
int ret; int ret;
@ -377,7 +392,10 @@ public class WolfSSLEngineTest {
@Test @Test
public void testConnectionOutIn() public void testConnectionOutIn()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
int ret; int ret;
@ -424,7 +442,9 @@ public class WolfSSLEngineTest {
@Test @Test
public void testSetUseClientMode() public void testSetUseClientMode()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
int ret; int ret;
SSLEngine client; SSLEngine client;
@ -494,7 +514,10 @@ public class WolfSSLEngineTest {
@Test @Test
public void testMutualAuth() public void testMutualAuth()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
int ret; int ret;
@ -569,7 +592,9 @@ public class WolfSSLEngineTest {
@Test @Test
public void testSetWantNeedClientAuth_ClientServerDefaultKeyManager() public void testSetWantNeedClientAuth_ClientServerDefaultKeyManager()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
int ret = 0; int ret = 0;
SSLContext cCtx = null; SSLContext cCtx = null;
@ -634,7 +659,9 @@ public class WolfSSLEngineTest {
@Test @Test
public void testSetWantNeedClientAuth_ClientNoKeyManager() public void testSetWantNeedClientAuth_ClientNoKeyManager()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
int ret = 0; int ret = 0;
SSLContext cCtx = null; SSLContext cCtx = null;
@ -700,7 +727,9 @@ public class WolfSSLEngineTest {
@Test @Test
public void testSetWantNeedClientAuth_ServerNoKeyManager() public void testSetWantNeedClientAuth_ServerNoKeyManager()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
int ret = 0; int ret = 0;
SSLContext cCtx = null; SSLContext cCtx = null;
@ -768,7 +797,9 @@ public class WolfSSLEngineTest {
@Test @Test
public void testSetWantNeedClientAuth_ClientServerExternalTrustAllCerts() public void testSetWantNeedClientAuth_ClientServerExternalTrustAllCerts()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyStoreException, CertificateException, IOException,
UnrecoverableKeyException {
int ret = 0; int ret = 0;
SSLContext cCtx = null; SSLContext cCtx = null;
@ -864,7 +895,9 @@ public class WolfSSLEngineTest {
@Test @Test
public void testSetWantNeedClientAuth_ExternalTrustNoClientCerts() public void testSetWantNeedClientAuth_ExternalTrustNoClientCerts()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyStoreException, CertificateException, IOException,
UnrecoverableKeyException {
int ret = 0; int ret = 0;
SSLContext cCtx = null; SSLContext cCtx = null;
@ -976,7 +1009,10 @@ public class WolfSSLEngineTest {
@Test @Test
public void testReuseSession() public void testReuseSession()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
int ret; int ret;
@ -1064,7 +1100,9 @@ public class WolfSSLEngineTest {
@Test @Test
public void testExtendedThreadingUse() public void testExtendedThreadingUse()
throws NoSuchProviderException, NoSuchAlgorithmException, throws NoSuchProviderException, NoSuchAlgorithmException,
InterruptedException { InterruptedException, KeyManagementException,
KeyStoreException, CertificateException, IOException,
UnrecoverableKeyException {
/* Number of SSLEngine client threads to start up */ /* Number of SSLEngine client threads to start up */
int numThreads = 50; int numThreads = 50;

View File

@ -24,11 +24,17 @@ package com.wolfssl.provider.jsse.test;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.security.NoSuchProviderException; import java.io.IOException;
import java.security.Principal; import java.security.Principal;
import java.security.Provider; import java.security.Provider;
import java.security.Security; import java.security.Security;
import java.security.NoSuchProviderException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyStoreException;
import java.security.KeyManagementException;
import java.security.UnrecoverableKeyException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManager;
import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509KeyManager;
@ -67,7 +73,10 @@ public class WolfSSLKeyX509Test {
} }
@Test @Test
public void testGetClientAliases() { public void testGetClientAliases()
throws NoSuchAlgorithmException, KeyStoreException,
KeyManagementException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
KeyManager[] list; KeyManager[] list;
X509KeyManager km; X509KeyManager km;
@ -137,7 +146,10 @@ public class WolfSSLKeyX509Test {
} }
@Test @Test
public void testChooseClientAlias() { public void testChooseClientAlias()
throws NoSuchAlgorithmException, KeyStoreException,
KeyManagementException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
KeyManager[] km = null; KeyManager[] km = null;
X509KeyManager x509km = null; X509KeyManager x509km = null;
@ -199,7 +211,10 @@ public class WolfSSLKeyX509Test {
} }
@Test @Test
public void testEngineChooseClientAlias() { public void testEngineChooseClientAlias()
throws NoSuchAlgorithmException, KeyStoreException,
KeyManagementException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
KeyManager[] km = null; KeyManager[] km = null;
X509ExtendedKeyManager x509km = null; X509ExtendedKeyManager x509km = null;
@ -264,7 +279,10 @@ public class WolfSSLKeyX509Test {
} }
@Test @Test
public void testGetServerAliases() { public void testGetServerAliases()
throws NoSuchAlgorithmException, KeyStoreException,
KeyManagementException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
KeyManager[] list; KeyManager[] list;
X509KeyManager km; X509KeyManager km;
@ -311,7 +329,10 @@ public class WolfSSLKeyX509Test {
} }
@Test @Test
public void testChooseServerAlias() { public void testChooseServerAlias()
throws NoSuchAlgorithmException, KeyStoreException,
KeyManagementException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
KeyManager[] km = null; KeyManager[] km = null;
X509KeyManager x509km = null; X509KeyManager x509km = null;
@ -373,7 +394,10 @@ public class WolfSSLKeyX509Test {
} }
@Test @Test
public void testChooseEngineServerAlias() { public void testChooseEngineServerAlias()
throws NoSuchAlgorithmException, KeyStoreException,
KeyManagementException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
KeyManager[] km = null; KeyManager[] km = null;
X509ExtendedKeyManager x509km = null; X509ExtendedKeyManager x509km = null;

View File

@ -29,6 +29,7 @@ import static org.junit.Assert.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.Enumeration; import java.util.Enumeration;
import java.io.IOException;
import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext; import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
@ -36,8 +37,12 @@ import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException; import javax.net.ssl.SSLException;
import java.security.Security; import java.security.Security;
import java.security.Provider; import java.security.Provider;
import java.security.NoSuchProviderException; import java.security.KeyStoreException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import com.wolfssl.WolfSSLException; import com.wolfssl.WolfSSLException;
import com.wolfssl.provider.jsse.WolfSSLProvider; import com.wolfssl.provider.jsse.WolfSSLProvider;
@ -72,7 +77,11 @@ public class WolfSSLSessionContextTest {
@Test @Test
public void testGetSessionTimeout() public void testGetSessionTimeout()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException,
NoSuchAlgorithmException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
int ret; int ret;
@ -144,7 +153,11 @@ public class WolfSSLSessionContextTest {
@Test @Test
public void testSetSessionTimeout() public void testSetSessionTimeout()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException,
NoSuchAlgorithmException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
int ret; int ret;
@ -253,7 +266,11 @@ public class WolfSSLSessionContextTest {
@Test @Test
public void testSessionIDsTLS13() public void testSessionIDsTLS13()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException,
NoSuchAlgorithmException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
int ret; int ret;
@ -393,7 +410,11 @@ public class WolfSSLSessionContextTest {
@Test @Test
public void testSessionIDs() public void testSessionIDs()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException,
NoSuchAlgorithmException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
int ret; int ret;

View File

@ -24,12 +24,18 @@ package com.wolfssl.provider.jsse.test;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.security.NoSuchProviderException;
import java.security.Principal; import java.security.Principal;
import java.security.Provider; import java.security.Provider;
import java.security.Security; import java.security.Security;
import java.security.KeyStoreException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList; import java.util.ArrayList;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
@ -77,7 +83,11 @@ public class WolfSSLSessionTest {
@Test @Test
public void testSessionTimeAndCerts() { public void testSessionTimeAndCerts()
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
int ret; int ret;
SSLSession session; SSLSession session;
@ -145,7 +155,11 @@ public class WolfSSLSessionTest {
} }
@Test @Test
public void testNullSession() { public void testNullSession()
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
int ret; int ret;
SSLSession session; SSLSession session;
@ -221,7 +235,11 @@ public class WolfSSLSessionTest {
@Test @Test
public void testBinding() { public void testBinding()
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
int ret; int ret;
String[] values; String[] values;
listner bound = new listner(); listner bound = new listner();
@ -368,7 +386,11 @@ public class WolfSSLSessionTest {
} }
@Test @Test
public void testSessionContext() { public void testSessionContext()
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, CertificateException, IOException,
NoSuchProviderException, UnrecoverableKeyException {
int ret; int ret;
SSLSession session; SSLSession session;
SSLSessionContext context; SSLSessionContext context;

View File

@ -958,7 +958,8 @@ public class WolfSSLSocketTest {
@Test @Test
public void testExtendedThreadingUse() public void testExtendedThreadingUse()
throws NoSuchProviderException, NoSuchAlgorithmException, throws NoSuchProviderException, NoSuchAlgorithmException,
InterruptedException { InterruptedException, KeyManagementException, KeyStoreException,
CertificateException, UnrecoverableKeyException, IOException {
/* Number of SSLSocket client threads to start up */ /* Number of SSLSocket client threads to start up */
int numThreads = 50; int numThreads = 50;
@ -1697,7 +1698,7 @@ public class WolfSSLSocketTest {
/* fail case, no root CA loaded to verify client cert */ /* fail case, no root CA loaded to verify client cert */
this.ctx = tf.createSSLContext("TLSv1.2", ctxProvider, this.ctx = tf.createSSLContext("TLSv1.2", ctxProvider,
/* using null here for JKS, use system certs only */ /* using null here for JKS, use system certs only */
tf.createTrustManager("SunX509", null, ctxProvider), tf.createTrustManager("SunX509", (String)null, ctxProvider),
tf.createKeyManager("SunX509", tf.serverJKS, ctxProvider)); tf.createKeyManager("SunX509", tf.serverJKS, ctxProvider));
ss = (SSLServerSocket)ctx.getServerSocketFactory() ss = (SSLServerSocket)ctx.getServerSocketFactory()

View File

@ -21,6 +21,10 @@
package com.wolfssl.provider.jsse.test; package com.wolfssl.provider.jsse.test;
import java.util.Date;
import java.time.Instant;
import java.time.Duration;
import java.math.BigInteger;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -29,12 +33,17 @@ import java.io.InputStream;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.Security; import java.security.Security;
import java.security.KeyManagementException; import java.security.KeyPairGenerator;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException; import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException; import java.security.UnrecoverableKeyException;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.List; import java.util.List;
@ -52,7 +61,11 @@ import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import com.wolfssl.WolfSSL;
import com.wolfssl.WolfSSLCertificate;
import com.wolfssl.WolfSSLX509Name;
import com.wolfssl.WolfSSLException; import com.wolfssl.WolfSSLException;
import com.wolfssl.WolfSSLJNIException;
/** /**
* Used to create common classes among test cases * Used to create common classes among test cases
@ -217,40 +230,43 @@ class WolfSSLTestFactory {
in.flip(); in.flip();
} }
private TrustManager[] internalCreateTrustManager(String type, String file, private TrustManager[] internalCreateTrustManager(String type,
String provider) { KeyStore store, String file, String provider)
TrustManagerFactory tm; throws NoSuchAlgorithmException, KeyStoreException, IOException,
CertificateException, NoSuchProviderException {
TrustManagerFactory tm = null;
KeyStore cert = null; KeyStore cert = null;
try { try {
if (file != null) { /* Load/get correct KeyStore */
if ((store == null) && (file != null) && !file.isEmpty()) {
InputStream stream = new FileInputStream(file); InputStream stream = new FileInputStream(file);
cert = KeyStore.getInstance(keyStoreType); cert = KeyStore.getInstance(keyStoreType);
cert.load(stream, jksPass); cert.load(stream, jksPass);
stream.close(); stream.close();
} }
else if (store != null) {
cert = store;
}
/* Initialize tm with KeyStore/certs */
if (provider == null) { if (provider == null) {
tm = TrustManagerFactory.getInstance(type); tm = TrustManagerFactory.getInstance(type);
} }
else { else {
tm = TrustManagerFactory.getInstance(type, provider); tm = TrustManagerFactory.getInstance(type, provider);
} }
tm.init(cert); tm.init(cert);
return tm.getTrustManagers(); return tm.getTrustManagers();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException | KeyStoreException |
} catch (KeyStoreException ex) { IOException | CertificateException | NoSuchProviderException ex) {
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) { ex.printStackTrace();
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex); throw ex;
} catch (IOException ex) {
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (CertificateException ex) {
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchProviderException ex) {
Logger.getLogger(WolfSSLTestFactory.class.getName()).log(Level.SEVERE, null, ex);
} }
return null;
} }
/** /**
@ -260,33 +276,62 @@ class WolfSSLTestFactory {
* @param file file name to read from * @param file file name to read from
* @return new trustmanager [] on success and null on failure * @return new trustmanager [] on success and null on failure
*/ */
protected TrustManager[] createTrustManager(String type, String file) { protected TrustManager[] createTrustManager(String type, String file)
return internalCreateTrustManager(type, file, null); throws NoSuchAlgorithmException, KeyStoreException, IOException,
CertificateException, NoSuchProviderException {
return internalCreateTrustManager(type, null, file, null);
} }
/** /**
* Using default password "wolfSSL test" * Create TrustManager[] using default password "wolfSSL test", from
* provided JKS file path.
* *
* @param type of key manager i.e. "SunX509" * @param type of key manager i.e. "SunX509"
* @param file file name to read from * @param file JKS file name to read from
* @return new trustmanager [] on success and null on failure * @return new TrustManager[] on success and null on failure
*/ */
protected TrustManager[] createTrustManager(String type, String file, protected TrustManager[] createTrustManager(String type, String file,
String provider) { String provider) throws NoSuchAlgorithmException, KeyStoreException,
return internalCreateTrustManager(type, file, provider); IOException, CertificateException, NoSuchProviderException {
return internalCreateTrustManager(type, null, file, provider);
} }
private KeyManager[] internalCreateKeyManager(String type, String file, /**
String provider) { * Create TrustManager[] using default password "wolfSSL test", from
KeyManagerFactory km; * provided KeyStore object.
KeyStore pKey; *
* @param type of key manager i.e. "SunX509"
* @param store KeyStore object containing trusted cert(s)
* @return new TrustManager[] on success and null on failure
*/
protected TrustManager[] createTrustManager(String type, KeyStore store,
String provider) throws NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateException, NoSuchProviderException {
return internalCreateTrustManager(type, store, null, provider);
}
private KeyManager[] internalCreateKeyManager(String type, KeyStore store,
String file, String provider) throws NoSuchAlgorithmException,
KeyStoreException, IOException, CertificateException,
NoSuchProviderException, UnrecoverableKeyException {
KeyManagerFactory km = null;
KeyStore pKey = null;
try { try {
/* set up KeyStore */ /* set up KeyStore */
InputStream stream = new FileInputStream(file); if ((store == null) && (file != null) && !file.isEmpty()) {
pKey = KeyStore.getInstance(keyStoreType); InputStream stream = new FileInputStream(file);
pKey.load(stream, jksPass); pKey = KeyStore.getInstance(keyStoreType);
stream.close(); pKey.load(stream, jksPass);
stream.close();
}
else if (store != null) {
pKey = store;
}
/* load private key */ /* load private key */
if (provider == null) { if (provider == null) {
@ -295,51 +340,95 @@ class WolfSSLTestFactory {
else { else {
km = KeyManagerFactory.getInstance(type, provider); km = KeyManagerFactory.getInstance(type, provider);
} }
km.init(pKey, jksPass); km.init(pKey, jksPass);
return km.getKeyManagers(); return km.getKeyManagers();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException | KeyStoreException |
} catch (KeyStoreException ex) { IOException | CertificateException | NoSuchProviderException |
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex); UnrecoverableKeyException ex) {
} catch (FileNotFoundException ex) {
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace();
} catch (IOException ex) { throw ex;
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (CertificateException ex) {
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnrecoverableKeyException ex) {
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchProviderException ex) {
Logger.getLogger(WolfSSLTestFactory.class.getName()).log(Level.SEVERE, null, ex);
} }
return null;
} }
/** /**
* Using default password "wolfSSL test" * Create KeyManager[] using default password "wolfSSL test" and provided
* path to JKS file.
* *
* @param type of key manager i.e. "SunX509" * @param type of key manager i.e. "SunX509"
* @param file file name to read from * @param file JKS file path to read from
* @return new keymanager [] on success and null on failure *
* @return new KeyManager[] on success and null on failure
*/ */
protected KeyManager[] createKeyManager(String type, String file) { protected KeyManager[] createKeyManager(String type, String file)
return internalCreateKeyManager(type, file, null); throws NoSuchAlgorithmException, KeyStoreException, IOException,
CertificateException, NoSuchProviderException,
UnrecoverableKeyException {
return internalCreateKeyManager(type, null, file, null);
} }
/** /**
* Using default password "wolfSSL test" * Create KeyManager[] using default password "wolfSSL test" and provided
* KeyStore object.
* *
* @param type of key manager i.e. "SunX509" * @param type of key manager i.e. "SunX509"
* @param file file name to read from * @param store KeyStore object to read from
* @return new keymanager [] on success and null on failure *
* @return new KeyManager[] on success and null on failure
*/
protected KeyManager[] createKeyManager(String type, KeyStore store)
throws NoSuchAlgorithmException, KeyStoreException, IOException,
CertificateException, NoSuchProviderException,
UnrecoverableKeyException {
return internalCreateKeyManager(type, store, null, null);
}
/**
* Create KeyManager[] using default password "wolfSSL test", provided
* path to JKS file, and specifying a JSSE provider for KeyManagerFactory.
*
* @param type of key manager i.e. "SunX509"
* @param file JKS file path to read from
* @param provider Provider of KeyManagerFactory to use
*
* @return new KeyManager[] on success and null on failure
*/ */
protected KeyManager[] createKeyManager(String type, String file, protected KeyManager[] createKeyManager(String type, String file,
String provider) { String provider) throws NoSuchAlgorithmException, KeyStoreException,
return internalCreateKeyManager(type, file, provider); IOException, CertificateException, NoSuchProviderException,
UnrecoverableKeyException {
return internalCreateKeyManager(type, null, file, provider) ;
} }
private SSLContext internalCreateSSLContext(String protocol, String provider, /**
TrustManager[] tm, KeyManager[] km) { * Create KeyManager[] using default password "wolfSSL test", provided
* KeyStore object, and specifying a JSSE provider for KeyManagerFactory.
*
* @param type of key manager i.e. "SunX509"
* @param store KeyStore object to read from
* @param provider Provider of KeyManagerFactory to use
*
* @return new KeyManager[] on success and null on failure
*/
protected KeyManager[] createKeyManager(String type, KeyStore store,
String provider) throws NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateException, NoSuchProviderException,
UnrecoverableKeyException {
return internalCreateKeyManager(type, store, null, provider);
}
private SSLContext internalCreateSSLContext(String protocol,
String provider, TrustManager[] tm, KeyManager[] km)
throws NoSuchAlgorithmException, KeyManagementException,
NoSuchProviderException, KeyStoreException, CertificateException,
UnrecoverableKeyException, IOException {
SSLContext ctx = null; SSLContext ctx = null;
TrustManager[] localTm = tm; TrustManager[] localTm = tm;
KeyManager[] localKm = km; KeyManager[] localKm = km;
@ -365,15 +454,15 @@ class WolfSSLTestFactory {
ctx.init(localKm, localTm, null); ctx.init(localKm, localTm, null);
return ctx; return ctx;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException | KeyManagementException |
} catch (KeyManagementException ex) { NoSuchProviderException | KeyStoreException |
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex); IOException | CertificateException |
} catch (NoSuchProviderException ex) { UnrecoverableKeyException ex) {
System.out.println("Could not find the provider : " + provider);
Logger.getLogger(WolfSSLEngineTest.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace();
throw ex;
} }
return null;
} }
/** /**
@ -382,7 +471,11 @@ class WolfSSLTestFactory {
* @param protocol to be used when creating context * @param protocol to be used when creating context
* @return new SSLContext on success and null on failure * @return new SSLContext on success and null on failure
*/ */
protected SSLContext createSSLContext(String protocol) { protected SSLContext createSSLContext(String protocol)
throws NoSuchAlgorithmException, KeyManagementException,
NoSuchProviderException, KeyStoreException, CertificateException,
UnrecoverableKeyException, IOException {
return internalCreateSSLContext(protocol, null, null, null); return internalCreateSSLContext(protocol, null, null, null);
} }
@ -393,7 +486,11 @@ class WolfSSLTestFactory {
* @param provider to be used when creating context * @param provider to be used when creating context
* @return new SSLContext on success and null on failure * @return new SSLContext on success and null on failure
*/ */
protected SSLContext createSSLContext(String protocol, String provider) { protected SSLContext createSSLContext(String protocol, String provider)
throws NoSuchAlgorithmException, KeyManagementException,
NoSuchProviderException, KeyStoreException, CertificateException,
UnrecoverableKeyException, IOException {
return internalCreateSSLContext(protocol, provider, null, null); return internalCreateSSLContext(protocol, provider, null, null);
} }
@ -409,7 +506,10 @@ class WolfSSLTestFactory {
* @return new SSLContext on success and null on failure * @return new SSLContext on success and null on failure
*/ */
protected SSLContext createSSLContext(String protocol, String provider, protected SSLContext createSSLContext(String protocol, String provider,
TrustManager[] tm, KeyManager[] km) { TrustManager[] tm, KeyManager[] km) throws NoSuchAlgorithmException,
KeyManagementException, NoSuchProviderException, KeyStoreException,
CertificateException, UnrecoverableKeyException, IOException {
return internalCreateSSLContext(protocol, provider, tm, km); return internalCreateSSLContext(protocol, provider, tm, km);
} }
@ -783,6 +883,118 @@ class WolfSSLTestFactory {
return 0; return 0;
} }
/**
* Helper function, populates test subjectName for cert generation.
* @param commonName Common Name to add to subjectName
* @return new WolfSSLX509Name object
*/
private WolfSSLX509Name generateTestSubjectName(String commonName)
throws WolfSSLException {
WolfSSLX509Name subjectName = new WolfSSLX509Name();
subjectName.setCountryName("US");
subjectName.setStateOrProvinceName("Montana");
subjectName.setStreetAddress("12345 Test Address");
subjectName.setLocalityName("Bozeman");
subjectName.setSurname("Test Surname");
subjectName.setCommonName(commonName);
subjectName.setEmailAddress("support@example.com");
subjectName.setOrganizationName("wolfSSL Inc.");
subjectName.setOrganizationalUnitName("Test and Development");
subjectName.setPostalCode("59715");
subjectName.setUserId("TestUserID");
return subjectName;
}
/**
* Generate a JKS KeyStore object which contains a self-signed certificate
* which contains the provided Common Name and Alt Name, also will have
* basic constraints set to CA:TRUE.
*
* @param commonName Common Name to generate cert with
* @param altName Subject altName to generate cert with
*
* @return new KeyStore object containing newly-generated certificate
*/
protected KeyStore generateSelfSignedCertJKS(String commonName,
String altName, boolean addPrivateKey) throws CertificateException,
WolfSSLException, NoSuchAlgorithmException, IOException,
KeyStoreException, WolfSSLJNIException {
String test_KEY_USAGE =
"digitalSignature,keyEncipherment,dataEncipherment";
String test_EXT_KEY_USAGE =
"clientAuth,serverAuth";
if (commonName == null) {
throw new CertificateException(
"Invalid arguments, null common name");
}
WolfSSLCertificate x509 = new WolfSSLCertificate();
/* Set notBefore/notAfter validity dates */
Instant now = Instant.now();
final Date notBefore = Date.from(now);
final Date notAfter = Date.from(now.plus(Duration.ofDays(365)));
x509.setNotBefore(notBefore);
x509.setNotAfter(notAfter);
/* Set serial number */
x509.setSerialNumber(BigInteger.valueOf(12345));
/* Set Subject Name */
WolfSSLX509Name subjectName = generateTestSubjectName(commonName);
x509.setSubjectName(subjectName);
/* Not setting Issuer, since generating self-signed cert */
/* Set Public Key from generated java.security.PublicKey,
* RSA 2048-bit for now. Add method arguments later if we need
* to generate other alg/sizes. */
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pubKey = keyPair.getPublic();
x509.setPublicKey(pubKey);
/* Add Extensions */
x509.addExtension(WolfSSL.NID_key_usage, test_KEY_USAGE, false);
x509.addExtension(WolfSSL.NID_ext_key_usage, test_EXT_KEY_USAGE, false);
if (altName != null) {
x509.addExtension(WolfSSL.NID_subject_alt_name, altName, false);
}
x509.addExtension(WolfSSL.NID_basic_constraints, true, true);
/* Sign certificate, self-signed with java.security.PrivateKey.
* Sign with SHA-256 for now. Can add method argument later to set
* hash alg if needed. */
PrivateKey privKey = keyPair.getPrivate();
x509.signCert(privKey, "SHA256");
/* Convert to X509Certificate */
X509Certificate tmpX509 = x509.getX509Certificate();
/* Create new KeyStore, load in newly generated cert. Add PrivateKey
* if requested. */
KeyStore store = KeyStore.getInstance("JKS");
store.load(null, jksPass);
if (addPrivateKey) {
store.setKeyEntry("cert_entry", privKey, jksPass,
new X509Certificate[] { tmpX509 });
}
else {
store.setCertificateEntry("cert_entry", tmpX509);
}
/* Free native memory */
subjectName.free();
x509.free();
return store;
}
/** /**
* Returns the DER encoded buffer of the certificate * Returns the DER encoded buffer of the certificate

View File

@ -40,6 +40,7 @@ import java.io.PrintWriter;
import java.time.Instant; import java.time.Instant;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException; import java.security.NoSuchProviderException;
import java.security.Provider; import java.security.Provider;
@ -104,7 +105,9 @@ public class WolfSSLTrustX509Test {
/* Testing WolfSSLTrustX509.getAcceptedIssuers() with all.jks */ /* Testing WolfSSLTrustX509.getAcceptedIssuers() with all.jks */
@Test @Test
public void testCAParsing() public void testCAParsing()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyStoreException, IOException, CertificateException {
TrustManager[] tm; TrustManager[] tm;
X509TrustManager x509tm; X509TrustManager x509tm;
X509Certificate cas[]; X509Certificate cas[];
@ -225,7 +228,9 @@ public class WolfSSLTrustX509Test {
/* Testing WolfSSLTrustX509.getAcceptedIssuers() with server.jks */ /* Testing WolfSSLTrustX509.getAcceptedIssuers() with server.jks */
@Test @Test
public void testServerParsing() public void testServerParsing()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyStoreException, IOException, CertificateException {
TrustManager[] tm; TrustManager[] tm;
X509TrustManager x509tm; X509TrustManager x509tm;
X509Certificate cas[]; X509Certificate cas[];
@ -291,7 +296,9 @@ public class WolfSSLTrustX509Test {
/* Testing WolfSSLTrustX509.getAcceptedIssuers() with all_mixed.jks */ /* Testing WolfSSLTrustX509.getAcceptedIssuers() with all_mixed.jks */
@Test @Test
public void testCAParsingMixed() public void testCAParsingMixed()
throws NoSuchProviderException, NoSuchAlgorithmException { throws NoSuchProviderException, NoSuchAlgorithmException,
KeyStoreException, IOException, CertificateException {
TrustManager[] tm; TrustManager[] tm;
X509TrustManager x509tm; X509TrustManager x509tm;
X509Certificate cas[]; X509Certificate cas[];
@ -360,7 +367,10 @@ public class WolfSSLTrustX509Test {
} }
@Test @Test
public void testSystemLoad() { public void testSystemLoad()
throws NoSuchAlgorithmException, KeyStoreException, IOException,
CertificateException, NoSuchProviderException {
String file = System.getProperty("javax.net.ssl.trustStore"); String file = System.getProperty("javax.net.ssl.trustStore");
TrustManager[] tm; TrustManager[] tm;
@ -371,7 +381,8 @@ public class WolfSSLTrustX509Test {
if (home != null) { if (home != null) {
File f = new File(home.concat("lib/security/jssecacerts")); File f = new File(home.concat("lib/security/jssecacerts"));
if (f.exists()) { if (f.exists()) {
tm = tf.createTrustManager("SunX509", null, provider); tm = tf.createTrustManager(
"SunX509", (String)null, provider);
if (tm == null) { if (tm == null) {
error("\t... failed"); error("\t... failed");
fail("failed to create trustmanager with default"); fail("failed to create trustmanager with default");
@ -382,7 +393,8 @@ public class WolfSSLTrustX509Test {
else { else {
f = new File(home.concat("lib/security/cacerts")); f = new File(home.concat("lib/security/cacerts"));
if (f.exists()) { if (f.exists()) {
tm = tf.createTrustManager("SunX509", null, provider); tm = tf.createTrustManager(
"SunX509", (String)null, provider);
if (tm == null) { if (tm == null) {
error("\t... failed"); error("\t... failed");
fail("failed to create trustmanager with default"); fail("failed to create trustmanager with default");
@ -394,7 +406,7 @@ public class WolfSSLTrustX509Test {
} }
} }
else { else {
tm = tf.createTrustManager("SunX509", null, provider); tm = tf.createTrustManager("SunX509", (String)null, provider);
if (tm == null) { if (tm == null) {
error("\t... failed"); error("\t... failed");
fail("failed to create trustmanager with default"); fail("failed to create trustmanager with default");
@ -412,7 +424,8 @@ public class WolfSSLTrustX509Test {
public void testVerify() public void testVerify()
throws NoSuchProviderException, NoSuchAlgorithmException, throws NoSuchProviderException, NoSuchAlgorithmException,
KeyStoreException, FileNotFoundException, IOException, KeyStoreException, FileNotFoundException, IOException,
CertificateException { CertificateException, NoSuchAlgorithmException {
TrustManager[] tm; TrustManager[] tm;
X509TrustManager x509tm; X509TrustManager x509tm;
X509Certificate cas[]; X509Certificate cas[];
@ -1581,12 +1594,28 @@ public class WolfSSLTrustX509Test {
/* SSLSocket should succeed if server cert changes after resume */ /* SSLSocket should succeed if server cert changes after resume */
testX509ExtendedTrustManagerSSLSocketCertChangeSuccess(); testX509ExtendedTrustManagerSSLSocketCertChangeSuccess();
/* Basic SSLEngine success case, SNI matches server cert CN */ /* Basic SSLEngine success case, HTTPS hostname verification,
* SNI matches server cert CN */
testX509ExtendedTrustManagerSSLEngineBasicSuccess(); testX509ExtendedTrustManagerSSLEngineBasicSuccess();
/* Basic SSLEngine fail case, SNI does not match server cert CN */ /* Basic SSLEngine success case, LDAPS hostname verification,
* SNI matches server cert CN */
testX509ExtendedTrustManagerSSLEngineBasicSuccessLDAPS();
/* Basic SSLEngine fail case, HTTPS hostname verification,
* SNI does not match server cert CN */
testX509ExtendedTrustManagerSSLEngineBasicFail(); testX509ExtendedTrustManagerSSLEngineBasicFail();
/* Basic SSLEngine fail case, LDAPS hostname verification,
* SNI does not match server cert CN */
testX509ExtendedTrustManagerSSLEngineBasicFailLDAPS();
/* LDAPS hostname verification test, wildcard failures */
testX509ExtendedTrustManagerSSLEngineWildcardFailLDAPS();
/* LDAPS hostname verification test, wildcard success */
testX509ExtendedTrustManagerSSLEngineWildcardSuccessLDAPS();
/* SSLEngine should fail if trying to use bad endoint alg */ /* SSLEngine should fail if trying to use bad endoint alg */
testX509ExtendedTrustManagerSSLEngineEndpointAlgFail(); testX509ExtendedTrustManagerSSLEngineEndpointAlgFail();
@ -1866,10 +1895,10 @@ public class WolfSSLTrustX509Test {
srvCtx, ss, serverArgs, 1); srvCtx, ss, serverArgs, 1);
server.start(); server.start();
/* We only support "HTTPS" as an endpoint algorithm. Setting /* We only support "HTTPS" and "LDAPS" as an endpoint algorithms.
* "LDAPS" should fail as unsupported */ * Setting "BADTYPE" should fail as unsupported */
TestArgs clientArgs = new TestArgs( TestArgs clientArgs = new TestArgs(
"LDAPS", "www.wolfssl.com", false, false, true, null); "BADTYPE", "www.wolfssl.com", false, false, true, null);
TestSSLSocketClient client = new TestSSLSocketClient( TestSSLSocketClient client = new TestSSLSocketClient(
cliCtx, ss.getLocalPort(), clientArgs); cliCtx, ss.getLocalPort(), clientArgs);
client.start(); client.start();
@ -1928,6 +1957,39 @@ public class WolfSSLTrustX509Test {
} }
} }
private void testX509ExtendedTrustManagerSSLEngineBasicSuccessLDAPS()
throws CertificateException, IOException, Exception {
int ret;
SSLEngine client;
SSLEngine server;
SSLContext ctx = tf.createSSLContext("TLS", provider);
server = ctx.createSSLEngine();
client = ctx.createSSLEngine("example.com", 11111);
server.setWantClientAuth(true);
server.setNeedClientAuth(true);
client.setUseClientMode(true);
server.setUseClientMode(false);
SSLParameters cliParams = client.getSSLParameters();
/* Enable Endpoint Identification for hostname verification on client */
cliParams.setEndpointIdentificationAlgorithm("LDAPS");
/* Not setting SNI, since LDAPS hostname verification requires server
* name to come directly from when connection was made. Peer cert
* has altName set to "example.com" */
client.setSSLParameters(cliParams);
ret = tf.testConnection(server, client, null, null, "Test mutual auth");
if (ret != 0) {
throw new Exception("Failed SSLEngine connection");
}
}
private void testX509ExtendedTrustManagerSSLEngineBasicFail() private void testX509ExtendedTrustManagerSSLEngineBasicFail()
throws CertificateException, IOException, Exception { throws CertificateException, IOException, Exception {
@ -1965,6 +2027,195 @@ public class WolfSSLTrustX509Test {
} }
} }
private void testX509ExtendedTrustManagerSSLEngineBasicFailLDAPS()
throws CertificateException, IOException, Exception {
int ret;
SSLEngine client;
SSLEngine server;
SSLContext ctx = tf.createSSLContext("TLS", provider);
server = ctx.createSSLEngine();
/* Setting wrong hostname */
client = ctx.createSSLEngine("www.invalid.com", 11111);
server.setWantClientAuth(true);
server.setNeedClientAuth(true);
client.setUseClientMode(true);
server.setUseClientMode(false);
SSLParameters cliParams = client.getSSLParameters();
/* Enable Endpoint Identification for hostname verification on client */
cliParams.setEndpointIdentificationAlgorithm("LDAPS");
client.setSSLParameters(cliParams);
ret = tf.testConnection(server, client, null, null, "Test mutual auth");
if (ret == 0) {
throw new Exception("Expected connection to fail, but did not");
}
}
private void testX509ExtendedTrustManagerSSLEngineWildcardFailLDAPS()
throws CertificateException, IOException, Exception {
int ret;
SSLContext srvCtx = null;
SSLContext cliCtx = null;
KeyStore srvCertStore = null;
SSLEngine client = null;
SSLEngine server = null;
SSLParameters cliParams = null;
/* Generate new KeyStore with new self-signed cert. CN is set to
* invalidname.com so we don't match on that. Subject altName is
* set to '*.example.com' */
srvCertStore = tf.generateSelfSignedCertJKS(
"invalidname.com", "*.example.com", true);
srvCtx = tf.createSSLContext("TLS", provider,
tf.createTrustManager("SunX509", tf.caClientJKS, provider),
tf.createKeyManager("SunX509", srvCertStore, provider));
cliCtx = tf.createSSLContext("TLS", provider,
tf.createTrustManager("SunX509", srvCertStore, provider),
tf.createKeyManager("SunX509", tf.clientJKS, provider));
/* --------------------------------------------------------------------
* LDAPS hostname verification should fail for 'example.com', since
* altName contains '*.example.com'
* ------------------------------------------------------------------ */
server = srvCtx.createSSLEngine();
client = cliCtx.createSSLEngine("example.com", 11111);
server.setWantClientAuth(true);
server.setNeedClientAuth(true);
client.setUseClientMode(true);
server.setUseClientMode(false);
/* Enable Endpoint Identification for hostname verification on client.
* Not setting SNI, since LDAPS hostname verification requires server
* name to come directly from when connection was made. Peer cert
* has altName set to "example.com" */
cliParams = client.getSSLParameters();
cliParams.setEndpointIdentificationAlgorithm("LDAPS");
client.setSSLParameters(cliParams);
ret = tf.testConnection(server, client, null, null, "Test mutual auth");
if (ret == 0) {
throw new Exception(
"Should fail SSLEngine connection, but succeeded");
}
/* --------------------------------------------------------------------
* LDAPS hostname verification should fail for 'a.b.example.com', since
* altName contains '*.example.com' and LDAPS only matches left-most
* wildcard.
* ------------------------------------------------------------------ */
server = srvCtx.createSSLEngine();
client = cliCtx.createSSLEngine("a.b.example.com", 11111);
server.setWantClientAuth(true);
server.setNeedClientAuth(true);
client.setUseClientMode(true);
server.setUseClientMode(false);
/* Enable Endpoint Identification for hostname verification on client.
* Not setting SNI, since LDAPS hostname verification requires server
* name to come directly from when connection was made. Peer cert
* has altName set to "example.com" */
cliParams = client.getSSLParameters();
cliParams.setEndpointIdentificationAlgorithm("LDAPS");
client.setSSLParameters(cliParams);
ret = tf.testConnection(server, client, null, null, "Test mutual auth");
if (ret == 0) {
throw new Exception(
"Should fail SSLEngine connection, but succeeded");
}
/* --------------------------------------------------------------------
* LDAPS hostname verification should fail for 'a.example*.com', since
* altName contains '*.example.com' and LDAPS only matches left-most
* wildcard.
* ------------------------------------------------------------------ */
server = srvCtx.createSSLEngine();
client = cliCtx.createSSLEngine("a.example*.com", 11111);
server.setWantClientAuth(true);
server.setNeedClientAuth(true);
client.setUseClientMode(true);
server.setUseClientMode(false);
/* Enable Endpoint Identification for hostname verification on client.
* Not setting SNI, since LDAPS hostname verification requires server
* name to come directly from when connection was made. Peer cert
* has altName set to "example.com" */
cliParams = client.getSSLParameters();
cliParams.setEndpointIdentificationAlgorithm("LDAPS");
client.setSSLParameters(cliParams);
ret = tf.testConnection(server, client, null, null, "Test mutual auth");
if (ret == 0) {
throw new Exception(
"Should fail SSLEngine connection, but succeeded");
}
}
private void testX509ExtendedTrustManagerSSLEngineWildcardSuccessLDAPS()
throws CertificateException, IOException, Exception {
int ret;
SSLContext srvCtx = null;
SSLContext cliCtx = null;
KeyStore srvCertStore = null;
SSLEngine client = null;
SSLEngine server = null;
SSLParameters cliParams = null;
/* Generate new KeyStore with new self-signed cert. CN is set to
* invalidname.com so we don't match on that. Subject altName is
* set to '*.example.com' */
srvCertStore = tf.generateSelfSignedCertJKS(
"invalidname.com", "*.example.com", true);
srvCtx = tf.createSSLContext("TLS", provider,
tf.createTrustManager("SunX509", tf.caClientJKS, provider),
tf.createKeyManager("SunX509", srvCertStore, provider));
cliCtx = tf.createSSLContext("TLS", provider,
tf.createTrustManager("SunX509", srvCertStore, provider),
tf.createKeyManager("SunX509", tf.clientJKS, provider));
/* --------------------------------------------------------------------
* LDAPS hostname verification 'test.example.com' should match against
* '*.example.com' altName in server cert.
* ------------------------------------------------------------------ */
server = srvCtx.createSSLEngine();
client = cliCtx.createSSLEngine("test.example.com", 11111);
server.setWantClientAuth(true);
server.setNeedClientAuth(true);
client.setUseClientMode(true);
server.setUseClientMode(false);
/* Enable Endpoint Identification for hostname verification on client.
* Not setting SNI, since LDAPS hostname verification requires server
* name to come directly from when connection was made. Peer cert
* has altName set to "example.com" */
cliParams = client.getSSLParameters();
cliParams.setEndpointIdentificationAlgorithm("LDAPS");
client.setSSLParameters(cliParams);
ret = tf.testConnection(server, client, null, null, "Test mutual auth");
if (ret != 0) {
throw new Exception("Failed SSLEngine connection");
}
}
private void testX509ExtendedTrustManagerSSLEngineEndpointAlgFail() private void testX509ExtendedTrustManagerSSLEngineEndpointAlgFail()
throws CertificateException, IOException, Exception { throws CertificateException, IOException, Exception {
@ -2388,7 +2639,6 @@ public class WolfSSLTrustX509Test {
fail("X509ExtendedTrustManager basic external test failed"); fail("X509ExtendedTrustManager basic external test failed");
} }
/* Fail if client or server encountered exception */
Exception srvException = server.getException(); Exception srvException = server.getException();
Exception cliException = client.getException(); Exception cliException = client.getException();

View File

@ -29,13 +29,15 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider; import java.security.Provider;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.Security; import java.security.Security;
import java.security.SignatureException; import java.security.SignatureException;
import java.security.KeyStoreException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateExpiredException;
@ -410,7 +412,11 @@ public class WolfSSLX509Test {
@Test @Test
public void testGetters() { public void testGetters()
throws NoSuchAlgorithmException, KeyStoreException,
KeyManagementException, IOException, CertificateException,
NoSuchProviderException, UnrecoverableKeyException {
SSLEngine server; SSLEngine server;
SSLEngine client; SSLEngine client;
String cipher = null; String cipher = null;