WSO2-IS 5.11.0 - Client SCIM - Received fatal alert: certificate_unknown - ssl-certificate

I'm trying to make a request to create a new user in WSO2 Identity Server but I can't connect to the api:
javax.net.ssl|ALL|A9|https-jsse-nio-9443-exec-5|2021-06-02 11:37:20.318 GMT|X509Authentication.java:264|No X.509 cert selected for EC
javax.net.ssl|ALL|A9|https-jsse-nio-9443-exec-5|2021-06-02 11:37:20.318 GMT|X509Authentication.java:264|No X.509 cert selected for EC
javax.net.ssl|DEBUG|AB|https-jsse-nio-9443-exec-7|2021-06-02 11:37:20.408 GMT|Alert.java:238|Received alert message (
"Alert": {
"level" : "fatal",
"description": "certificate_unknown"
}
)
javax.net.ssl|ERROR|AB|https-jsse-nio-9443-exec-7|2021-06-02 11:37:20.410 GMT|TransportContext.java:342|Fatal (CERTIFICATE_UNKNOWN): Received fatal alert: certificate_unknown (
"throwable" : {
javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117)
at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:337)
at java.base/sun.security.ssl.Alert$AlertConsumer.consume(Alert.java:293)
at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:186)
at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:171)
at java.base/sun.security.ssl.SSLEngineImpl.decode(SSLEngineImpl.java:681)
at java.base/sun.security.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:636)
at java.base/sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:454)
at java.base/sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:433)
at java.base/javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:637)
at org.apache.tomcat.util.net.SecureNioChannel.handshakeUnwrap(SecureNioChannel.java:499)
at org.apache.tomcat.util.net.SecureNioChannel.handshake(SecureNioChannel.java:238)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1568)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)}
)
I've already imported my certificate in client-truststore.jks.
Steps:
1-) keytool -genkey -alias custom -keyalg RSA -keysize 2048 -keystore custom.jks -dname "CN=<"wso2-is-ip">, OU=Home,O=Home,L=SL,S=WS,C=LK" -storepass wso2carbon -keypass wso2carbon
2-) keytool -export -alias custom -keystore custom.jks -file custom.pem
3-) Import certificate in /wso2is-5.11.0/repository/resources/security/
keytool -import -alias custom -file custom.pem -keystore client-truststore.jks -storepass wso2carbon
4-) Check if was imported:
keytool -list -v -keystore client-truststore.jks -alias custom -storepass wso2carbon -keypass wso2carbon
Java application:
protected void setKeyStore() {
System.setProperty("javax.net.ssl.trustStore", "custom.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
System.setProperty("javax.net.ssl.trustStoreType", "JKS");
}
protected void submit(HttpMethodBase method) throws IOException {
HttpClient httpUpdateClient = new HttpClient();
// **************************Erro SSL*******************************
int responseStatus = httpUpdateClient.executeMethod(method);
// **************************Erro SSL*******************************
String response = method.getResponseBodyAsString();
System.out.println("/******SCIM response status: " + responseStatus);
System.out.println("SCIM response data: " + response + "******/");
}
Am I missing anything?
PS: WSO2-IS is running on a docker environment in development environment and I'm trying to connect from local machine.

I've used the certificate that comes with WSO2 IS in my application and it worked.
wso2is-5.11.0/repository/resources/security/wso2carbon.jks
protected void setKeyStore() {
System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
}

Related

Getting Error: RabbitMQ.Client.Exceptions.BrokerUnreachableException

I am new to rabbitMQ. I enabled TLS for rabbitMQ on my local. As a part of it I created the certificate on my WINDOWS machine (followed the LINIUX Step) as discussed in the https://www.rabbitmq.com/ssl.html.
Also updated the rabbitMQ.config file as below:
[
{rabbit, [
{ssl_listeners, [5671]},
{ssl_options, [
{cacertfile,"/etc/ca_certificate.pem"},
{certfile,"/etc/private_key.pem"},
{keyfile,"/etc/server_certificate.pem"},
{password, "MySecretPassword"},
{verify,verify_peer},
{fail_if_no_peer_cert,true}
]}
]}
].
Steps followed to create the certificates on WINDOWS MACHINE:
Bash Cmd Prompt:
cd /C/temp/ThirdOne
mkdir testca
cd testca
mkdir certs private
chmod 700 private
echo 01 > serial
touch index.txt
Using OpenSSL CMD
openssl req -x509 -config openssl.cnf -newkey rsa:2048 -days 365 -out ca_certificate.pem -outform PEM -subj /CN=MyTestCA/ -nodes
openssl x509 -in ca_certificate.pem -out ca_certificate.cer -outform DER
mkdir server
cd server
openssl genrsa -out private_key.pem 2048
openssl req -new -key private_key.pem -out req.pem -outform PEM -subj /CN=desktop-s08pnk3/O=server/ -nodes
cd..
openssl ca -config openssl.cnf -in ./server/req.pem -out ./server/server_certificate.pem -notext -batch -extensions server_ca_extensions
openssl pkcs12 -export -out ./server/server_certificate.p12 -in ./server/server_certificate.pem -inkey ./server/private_key.pem -passout pass:MySecretPassword
mkdir client
cd client
openssl genrsa -out private_key.pem 2048
openssl req -new -key private_key.pem -out req.pem -outform PEM -subj /CN=desktop-s08pnk3/O=client/ -nodes
cd..
openssl ca -config openssl.cnf -in ./client/req.pem -out ./client/client_certificate.pem -notext -batch -extensions client_ca_extensions
openssl pkcs12 -export -out ./client/client_certificate.p12 -in ./client/client_certificate.pem -inkey ./client/private_key.pem -passout pass:MySecretPassword
On top of it I installed the certificate of client on Local.
NOTE: My client and server are both are local machine only.
Code that I am using for connecting to rabbit MQ:
private static void RabbitMQWithSSLEnable()
{
try
{
string rabbitmqHostName = "desktop-s08pnk3";
string rabbitmqServerName = "desktop-s08pnk3";
string certificateFilePath = #"C:\temp\ThirdOne\client\client_certificate.pem";
string certificatePassphrase = "MySecretPassword";
string rabbitmqUsername = "test";
string rabbitmqPassword = "test";
var factory = new ConnectionFactory();
factory.HostName = rabbitmqHostName;
factory.UserName = rabbitmqUsername;
factory.Password = rabbitmqPassword;
//factory.Uri = new Uri("amqps://test:test#desktop-s08pnk3");
factory.AuthMechanisms = new IAuthMechanismFactory[] { new ExternalMechanismFactory() };
// Note: This should NEVER be "localhost"
factory.Ssl.ServerName = rabbitmqServerName;
// Path to my .p12 file.
factory.Ssl.CertPath = certificateFilePath;
// Passphrase for the certificate file - set through OpenSSL
factory.Ssl.CertPassphrase = certificatePassphrase;
factory.Ssl.Enabled = true;
// Make sure TLS 1.2 is supported & enabled by your operating system
factory.Ssl.Version = SslProtocols.Tls12;
// This is the default RabbitMQ secure port
factory.Port = AmqpTcpEndpoint.UseDefaultPort;
factory.VirtualHost = "/";
factory.Ssl.AcceptablePolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch | SslPolicyErrors.RemoteCertificateNotAvailable;
//System.Net.ServicePointManager.Expect100Continue = false;
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
// publish some messages...
}
}
}
catch (System.Exception ex)
{
var error = ex.ToString();
System.Console.WriteLine(error);
}
}
The above code is throwing error:
RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable
---> System.AggregateException: One or more errors occurred. (Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..)
---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
---> System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host.
--- End of inner exception stack trace ---
at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessAuthentication(LazyAsyncResult lazyResult, CancellationToken cancellationToken)
at System.Net.Security.SslStream.BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions, CancellationToken cancellationToken, AsyncCallback asyncCallback, Object asyncState)
at System.Net.Security.SslStream.BeginAuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation, AsyncCallback asyncCallback, Object asyncState)
at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__64_1(String arg1, X509CertificateCollection arg2, SslProtocols arg3, AsyncCallback callback, Object state)
at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2,TArg3](Func`6 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, TArg3 arg3, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2,TArg3](Func`6 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, Object state, TaskCreationOptions creationOptions)
at System.Threading.Tasks.TaskFactory.FromAsync[TArg1,TArg2,TArg3](Func`6 beginMethod, Action`1 endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, Object state)
at System.Net.Security.SslStream.AuthenticateAsClientAsync(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
at RabbitMQ.Client.Impl.SslHelper.<>c__DisplayClass2_0.<TcpUpgrade>b__0(SslOption opts)
at RabbitMQ.Client.Impl.SslHelper.TcpUpgrade(Stream tcpStream, SslOption options)
at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
at RabbitMQ.Client.Framing.Impl.IProtocolExtensions.CreateFrameHandler(IProtocol protocol, AmqpTcpEndpoint endpoint, ArrayPool`1 pool, Func`2 socketFactory, TimeSpan connectionTimeout, TimeSpan readTimeout, TimeSpan writeTimeout)
at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint)
at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector)
--- End of inner exception stack trace ---
at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector)
at RabbitMQ.Client.Framing.Impl.AutorecoveringConnection.Init(IEndpointResolver endpoints)
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)
--- End of inner exception stack trace ---
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)
at RabbitMQ.Client.ConnectionFactory.CreateConnection(String clientProvidedName)
at RabbitMQ.Client.ConnectionFactory.CreateConnection()
at RabbitMQ.Explore.Program.RabbitMQWithSSLEnable() in C:\Users\warke\source\repos\RabbitMQ.Explore\RabbitMQ.Explore\Program.cs:line 71
Can anyone please help me to get it resolved?
Thanks.
Below are the things that I tried:
A) Enabled the TLS on internet options.
B) Enabled Ports also.
#Team FYI and Questions:
I installed the client certificate on my local - Not sure on it
as it's not mentioned.
Do I need to installed the Server
Certificate on my local as I am trying to connect to it from local (client and server both are same machine)
I need to do Peer verification, so created both client and server certificate.
The password added in config and while calling the rabbitMQ on from local is the same which I used to create the certificate for Client and Server.
I created a new user for connection i.e. test and given the admin access to it.

CentOS7, KeyStore is N/A while connecting to LDAPS server in Tomcat 8

Environment:
CentOS 7
java-1.8.0-openjdk-1.8.0.292.b10-1.el7_9.x86_64
Tomcat 8.5.63 + self-signed SSL certificate
osixia/docker-openldap + official SSL certificate
Set --env LDAP_TLS_VERIFY_CLIENT=never to skip client certificate validation.
Had been LDAPS login successfully by using ApacheDirectoryStudio and Gawor_ldapbrowser.
I have a server API which run with Tomcat 8, and will connect to an OpenLDAP server via ldaps protocol.
My code is simple as:
LdapContext ctx = null;
try
{
Hashtable<String, String> env = getLDAPBase(this.searcher, this.searcherPwd, this.ldapUrl);
ctx = new InitialLdapContext(env, null); // line 689
return findUserIdInLdap(userid, ctx);
}
public static Hashtable<String, String> getLDAPBase(String ldapUserName, String pwd, String ldapUrl)
{
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, ldapUserName);
env.put(Context.SECURITY_CREDENTIALS, pwd);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUrl);
return env;
}
The API log:
2021/06/02 14:02:55.168,[05863d2e-5ca6-43bb-bd18-3c10689bdcbf]05863d2e-5ca6-43bb-bd18-3c10689bdcbf, userid=test1_LDAP,searchBase=dc=my,dc=com,FILTER_STR=(&(|(sAMAccountName={0})(cn={0})(uid={0}))(objectClass=*))
javax.naming.CommunicationException: q2ldap.my.com:6362 [Root exception is java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)]
at com.sun.jndi.ldap.Connection.<init>(Connection.java:233)
at com.sun.jndi.ldap.LdapClient.<init>(LdapClient.java:137)
at com.sun.jndi.ldap.LdapClient.getInstance(LdapClient.java:1615)
at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2849)
at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:347)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxFromUrl(LdapCtxFactory.java:225)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:189)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:243)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:154)
at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:84)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:695)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:154)
at com.my.OpenLdapAuthenticator.getUserIdInLdap(OpenLdapAuthenticator.java:689)
at com.my.OpenLdapAuthenticator.authenticationFlow(OpenLdapAuthenticator.java:108)
at com.my.LdapAuthManager.authenticate(LdapAuthManager.java:247)
at com.my.ServletPrivateCloudAAA.processRequest(ServletPrivateCloudAAA.java:147)
at com.my.http.api.StaxAPIServlet.doProcess(StaxAPIServlet.java:346)
at com.my.http.api.StaxAPIServlet.service(StaxAPIServlet.java:107)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.my.api.aaa.LockIpFilter.doFilter(LockIpFilter.java:95)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.my.api.aaa.AccessLogFilter.doFilter(AccessLogFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.filters.CorsFilter.handleNonCORS(CorsFilter.java:363)
at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:169)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:186)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:353)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1629)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
at javax.net.ssl.DefaultSSLSocketFactory.throwException(SSLSocketFactory.java:248)
at javax.net.ssl.DefaultSSLSocketFactory.createSocket(SSLSocketFactory.java:262)
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 com.sun.jndi.ldap.Connection.createSocket(Connection.java:345)
at com.sun.jndi.ldap.Connection.<init>(Connection.java:220)
... 51 more
Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
at java.security.Provider$Service.newInstance(Provider.java:1617)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:236)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:164)
at javax.net.ssl.SSLContext.getInstance(SSLContext.java:156)
at javax.net.ssl.SSLContext.getDefault(SSLContext.java:96)
at javax.net.ssl.SSLSocketFactory.getDefault(SSLSocketFactory.java:122)
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 com.sun.jndi.ldap.Connection.createSocket(Connection.java:301)
... 52 more
Caused by: java.security.PrivilegedActionException: java.io.FileNotFoundException: N/A (No such file or directory)
at java.security.AccessController.doPrivileged(Native Method)
at sun.security.ssl.SSLContextImpl$DefaultManagersHolder.getKeyManagers(SSLContextImpl.java:1095)
at sun.security.ssl.SSLContextImpl$DefaultManagersHolder.<clinit>(SSLContextImpl.java:1021)
at sun.security.ssl.SSLContextImpl$DefaultSSLContext.<init>(SSLContextImpl.java:1186)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.security.Provider$Service.newInstance(Provider.java:1595)
... 62 more
Caused by: java.io.FileNotFoundException: N/A (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at sun.security.ssl.SSLContextImpl$DefaultManagersHolder$2.run(SSLContextImpl.java:1099)
at sun.security.ssl.SSLContextImpl$DefaultManagersHolder$2.run(SSLContextImpl.java:1096)
... 71 more
After added -Djava.net.debug=all, I found below in log:
javax.net.ssl|FINE|03 11|https-jsse-nio-443-exec-12|2021-06-02 16:04:37.612 CST|SSLContextImpl.java:1076|keyStore is : N/A
javax.net.ssl|FINE|03 11|https-jsse-nio-443-exec-12|2021-06-02 16:04:37.613 CST|SSLContextImpl.java:1077|keyStore type is : pkcs12
javax.net.ssl|FINE|03 11|https-jsse-nio-443-exec-12|2021-06-02 16:04:37.613 CST|SSLContextImpl.java:1079|keyStore provider is :
javax.net.ssl|FINE|03 11|https-jsse-nio-443-exec-12|2021-06-02 16:04:37.671 CST|SSLEngineOutputRecord.java:266|WRITE: TLS12 application_data, length = 404
I have no idea why there is a N/A keyStore.
CentOS 7 has no default openjdk 9 to install, so I installed openjdk 11, then call my API again.
And the API connected via LDAPS successfully with log:
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.895 CST|SSLContextImpl.java:1088|keyStore is :
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.896 CST|SSLContextImpl.java:1089|keyStore type is : pkcs12
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.896 CST|SSLContextImpl.java:1091|keyStore provider is :
javax.net.ssl|ALL|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.896 CST|SSLContextImpl.java:1126|init keystore
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.896 CST|SSLContextImpl.java:1149|init keymanager of type SunX509
javax.net.ssl|ALL|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.897 CST|SSLContextImpl.java:115|trigger seeding of SecureRandom
javax.net.ssl|ALL|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.897 CST|SSLContextImpl.java:119|done seeding of SecureRandom
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:15.091 CST|SSLSocketOutputRecord.java:309|WRITE: TLS12 application_data, length = 52
But I can't just upgrade the JRE version to solve the problem because our server APIs are compatible only with Java 8.
So upgrading Java version, eg. 11, is not our option in short term.
Is there any hints or suggestions to solve this problem?
Thank you in advance.

CXF SSL configuration for consuming SOAP webservice

Overview
I am going to set SSL configuration for calling a SOAP webservice.
Certificate info:
Certificate file: sureft.p12
Password: sureft
CXF configuration file (cxf.xml):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sec="http://cxf.apache.org/configuration/security"
xmlns:http="http://cxf.apache.org/transports/http/configuration"
xmlns:jaxws="http://java.sun.com/xml/ns/jaxws" xmlns:cxf="http://www.springframework.org/schema/c"
xsi:schemaLocation="
http://cxf.apache.org/configuration/security
http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/transports/http/configuration
http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<http:conduit name="{http://tmr.qld.gov.au/srvc/getregistrationstatus/v2_0}GetRegistrationStatusPort.http-conduit">
<http:tlsClientParameters>
<sec:keyManagers keyPassword="sureft">
<sec:keyStore type="pksc12" password="sureft"
file="keystore/sureft.p12"/>
</sec:keyManagers>
</http:tlsClientParameters>
<http:client AutoRedirect="true" Connection="Keep-Alive"/>
</http:conduit>
</beans>
Issue
However, when the webservice invoked it throws 403:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 403: Forbidden
I had a look on http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html but I couldn't solve the isse.
Now I would be grateful if anyone can help me find solution for this problem.
Update Level 1:
I did the following changes but again 403 raised:
. Creating truststore:
Export Create cer file with name myCert.cer from sureft.p12
Create truststore certificate with name of myTruststore.jks by running: keytool -import -file myCert.cer -alias firstCA -keystore myTrustStore.jks
Changing cxf.xml file as follows to add truststore:
...
<http:tlsClientParameters>
<sec:keyManagers keyPassword="sureft">
<sec:keyStore type="pkcs12" password="sureft"
file="keystore/sureft.p12"/>
</sec:keyManagers>
<sec:trustManagers>
<sec:keyStore type="JKS" password="123456"
file="keystore/myTrustStore.jks"/>
</sec:trustManagers>
</http:tlsClientParameters>
...
Update Level 2
I changed my code as following and the 403 solved but another issue raised:
#RequestMapping(method = RequestMethod.GET)
public void getBillInfo2(String plateNumber) {
QName qname = new QName("http://testURL/srvc/getregistrationstatus/v2_0/", "GetRegistrationStatusService");
URL wsdl = getClass().getResource("wsdl/test.getregistrationstatus.v2_0.wsdl");
GetRegistrationStatusService service = new GetRegistrationStatusService(wsdl, qname);
GetRegistrationStatus registrationStatus = service.getPort(qname, GetRegistrationStatus.class);
Client client = ClientProxy.getClient(registrationStatus);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(32000);
httpClientPolicy.setContentType("application/soap+xml; charset=utf-8");
http.setClient(httpClientPolicy);
GetRegistrationStatusRequest request = new GetRegistrationStatusRequest();
request.setPlateNo(plateNumber);
GetRegistrationStatusResponse result = registrationStatus.execute(request);
log.debug(result.toString());
}
The Exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.xml.ws.soap.SOAPFaultException: Fault string, and possibly fault code, not set
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:980)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.ShallowEtagHeaderFilter.doFilterInternal(ShallowEtagHeaderFilter.java:87)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at com.blss.trails.registration.RegistrationSearchInvocationTest.test(RegistrationSearchInvocationTest.java:47)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: javax.xml.ws.soap.SOAPFaultException: Fault string, and possibly fault code, not set
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)
at com.sun.proxy.$Proxy104.execute(Unknown Source)
at com.blss.trails.registration.RegistrationSearchInvocation.getBillInfo2(RegistrationSearchInvocation.java:72)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
... 46 more
Caused by: java.lang.NullPointerException
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.createConnection(URLConnectionHTTPConduit.java:104)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.setupConnection(URLConnectionHTTPConduit.java:117)
at org.apache.cxf.transport.http.HTTPConduit.prepare(HTTPConduit.java:497)
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:46)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:514)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:423)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:324)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:277)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
... 61 more
Any help would be highly appreciated.
I did the following steps and the problem solved:
Exporting publickey certificate from p12 certificate
Adding it as truststore to my jre cacerts (More info for importing the truststore can be fount in How to solve javax.net.ssl.SSLHandshakeException Error?):
.
keytool -import -file <the cert file> -alias <some meaningful name> keystore <path to cacerts file>
.
Modifying the code as follows:
...
#RequestMapping(method = RequestMethod.GET, path = "/billinfo")
public void getBillInfo(String plateNumber) {
QName qname = new QName("http://tmr.qld.gov.au/srvc/getregistrationstatus/v2_0/", "GetRegistrationStatusService");
URL wsdl = getClass().getResource("wsdl/myWSDL.wsdl");
GetRegistrationStatusService service = new GetRegistrationStatusService(wsdl, qname);
service.addPort(qname, SOAPBinding.SOAP12HTTP_BINDING, "https://myurl/getregistrationstatus_v2_0/");
GetRegistrationStatus registrationStatus = service.getPort(qname, GetRegistrationStatus.class);
Client cxfClient = ClientProxy.getClient(registrationStatus);
cxfClient.getInInterceptors().add(new LoggingInInterceptor());
cxfClient.getOutInterceptors().add(new LoggingOutInterceptor());
cxfClient.getOutFaultInterceptors().add(new FaultOutInterceptor());
HTTPConduit httpConduit = (HTTPConduit) cxfClient.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(32000);
httpClientPolicy.setContentType("application/soap+xml;charset=utf-8");
httpConduit.setClient(httpClientPolicy);
//Keystore setting
try {
final TLSClientParameters tlsCP = new TLSClientParameters();
File p12File = new File("sureft.p12");
KeyStore.Builder builder = KeyStore.Builder.newInstance("PKCS12", null, p12File, new KeyStore.PasswordProtection("sureft".toCharArray()));
KeyStore keyStore = builder.getKeyStore();
String keyPassword = "sureft";
final KeyManager[] myKeyManagers = getKeyManagers(keyStore, keyPassword);
tlsCP.setKeyManagers(myKeyManagers);
httpConduit.setTlsClientParameters(tlsCP);
} catch (Exception e) {
e.printStackTrace();
}
GetRegistrationStatusRequest request = new GetRegistrationStatusRequest();
request.setPlateNo(plateNumber);
GetRegistrationStatusResponse result = registrationStatus.execute(request);
log.debug("Result: " + result.toString());
}
private static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword) throws GeneralSecurityException, IOException {
String alg = KeyManagerFactory.getDefaultAlgorithm();
char[] keyPass = keyPassword != null ? keyPassword.toCharArray() : null;
KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
fac.init(keyStore, keyPass);
return fac.getKeyManagers();
}
...
This was my solution but I would be grateful if anyone could share their solutions here.

ios9 self signed certificate and app transport security

I've spent a while trying to get this working. I have an API that I'm connecting to that i'm trying to switch to SSL with self signed certificates. I have control on the server and app.
I generated a self signed cert according to this:
https://kyup.com/tutorials/create-ssl-certificate-nginx/
sudo openssl genrsa -des3 -out ssl.key 2048
sudo openssl req -new -key ssl.key -out ssl.csr
sudo cp ssl.key ssl.key.orig & sudo openssl rsa -in ssl.key.orig -out ssl.key
sudo openssl x509 -req -days 365 -in ssl.csr -signkey ssl.key -out ssl.crt
I've tried some config options on the server (NGINX)
ssl on;
ssl_certificate /etc/nginx/ssl/ssl.crt;
ssl_certificate_key /etc/nginx/ssl/ssl.key;
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
#ssl_ciphers "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS";
ssl_prefer_server_ciphers on;
And on the client side I've tried some different options with ATS:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
and
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>test.example.com (NOT REALLY MY DOMAIN)</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
and
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>test.example.com (NOT REALLY MY DOMAIN)</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
Depending on different ATS options I get errors:
An SSL error has occurred and a secure connection to the server cannot be made.
or
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
The certificate for this server is invalid. You might be connecting to a server that is pretending to be “MYDOMAIN” which could put your confidential information at risk.
Any ideas? Anyone else struggle with self signed certs?
P.S. I'm on OS X 10.11.2 Beta, Xcode 7.1.1
I figured out the issue. It has nothing to do with App Transport Security. I had to make sure that iOS trusts the certificate since it's not from a trusted authority.
The old school way of doing this by overriding NSURLRequest.allowsAnyHTTPSCertificateForHost doesn't work.
Since i'm using NSURLSession you have to do it with this:
- (id) init {
self = [super init];
NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
return self;
}
- (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
completionHandler(NSURLSessionAuthChallengeUseCredential,[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}
just need add .cer to SecTrust
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if let trust = challenge.protectionSpace.serverTrust,
let pem = Bundle.main.path(forResource: "https", ofType: "cer"),
let data = NSData(contentsOfFile: pem),
let cert = SecCertificateCreateWithData(nil, data) {
let certs = [cert]
SecTrustSetAnchorCertificates(trust, certs as CFArray)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: trust))
return
}
}
// Pinning failed
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}

Trustchain error NetTcpBinding with message (username) security

After a week(!) of searching, I hope someone is able to tell me what I'm doing wrong.
I keep on getting the following error message:
The X.509 certificate CN=localhost chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode.
To start from the beginning. This is my code/config serverside:
ServiceHost svcHost = new ServiceHost(typeof(TestService));
// Enable metadata publishing.
ServiceMetadataBehavior smb = svcHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
svcHost.Description.Behaviors.Add(smb);
ServiceDebugBehavior sdb = svcHost.Description.Behaviors.Find<ServiceDebugBehavior>();
if (sdb == null) { sdb = new ServiceDebugBehavior(); svcHost.Description.Behaviors.Add(sdb); }
sdb.IncludeExceptionDetailInFaults = true;
// Meta data servicepoint
svcHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
// Credentials
CustomUserNamePasswordValidator clientAuthenticationValidator = new TCustomUserNamePasswordValidator();
svcHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
svcHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = (UserNamePasswordValidator) clientAuthenticationValidator;
// Certificate
svcHost.Credentials.ServiceCertificate.Certificate = new X509Certificate2("TestServer.pfx", "password");
svcHost.Credentials.IssuedTokenAuthentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
svcHost.Credentials.IssuedTokenAuthentication.RevocationMode = X509RevocationMode.None;
svcHost.Credentials.IssuedTokenAuthentication.TrustedStoreLocation = StoreLocation.LocalMachine;
// Binding
NetTcpBinding netTcpBinding = new NetTcpBinding();
netTcpBinding.Security.Mode = SecurityMode.Message;
netTcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
netTcpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
netTcpBinding.ReliableSession.Enabled = true;
svcHost.AddServiceEndpoint(typeof(ITestService), netTcpBinding, "");
svcHost.Open();
With the following app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="TestService">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/" />
<add baseAddress="net.tcp://localhost:9595" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
The following commands I used to get the certificates:
Root CA:
makecert.exe -n "CN=TestCA" -r -pe -a sha512 -len 4096 -cy authority -sr LocalMachine -ss Root -sv TestCA.pvk TestCA.cer
pvk2pfx.exe -pvk TestCA.pvk -spc TestCA.cer -pfx TestCA.pfx -po aaaaa
Service:
makecert.exe -n "CN=localhost" -iv TestCA.pvk -ic TestCA.cer -pe -a sha512 -len 4096 -b 12/14/2014 -e 01/01/2020 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -sv TestServer.pvk TestServer.cer
pvk2pfx.exe -pvk TestServer.pvk -spc TestServer.cer -pfx TestServer.pfx -po aaaaa
Where I imported TestCA.cer in Trusted Root CA and, as shown in code, the pfx file is used as servicecertificate.
As far as I understood, I do not have to give a certificate for the client, since it uses username credentials to authenticate itself, where the servicecertificate is used for ssl.
As said, as soon as I start up the client and call a function, I get the above exception.
I already tried to attach the TestServer certificate to the 9595 port with netsh. I run both client and service on the same computer.
I truly hope someone can help.
The issues is most likely caused by a self-signed certificate that is not “trusted” by the client. In order to accommodate this scenario, you have a few options:
Import the self-signed certificate into the client machine’s
“Trusted People” store.
Follow the MSDN guidance to Create and Install Temporary Certificates in WCF for Message Security During Development
Update the client software to bypass the certificate verification check as defined here.