TLS on Windows Phone 7 - send client certificate in Bouncy Castle - security

I have problem with sending client certificate to server on Window Phone 7 by using Bouncy Castle.
I created my own TlsAuthentication and TlsCredential class inherited from interfaces. But in method
public TlsCredentials GetClientCredentials(CertificateRequest certificateRequest)
{
return this.TlsCredentials;
}
an exception occurs.
Below is my exception:
An exception of type 'Org.BouncyCastle.Crypto.Tls.TlsFatalAlert' occurred in bouncywp71.DLL and wasn't handled before a managed/native boundary
A first chance exception of type 'System.IO.IOException' occurred in bouncywp71.DLL
An exception of type 'System.IO.IOException' occurred in bouncywp71.DLL and wasn't handled before a managed/native boundary
Internal TLS error, this could be an attack
at Org.BouncyCastle.Crypto.Tls.TlsProtocolHandler.FailWithError(AlertLevel alertLevel, AlertDescription alertDescription)
at Org.BouncyCastle.Crypto.Tls.TlsProtocolHandler.SafeReadData()
at Org.BouncyCastle.Crypto.Tls.TlsProtocolHandler.Connect(TlsClient tlsClient)
at MYAPP.MyTest2.Network.Security.MyTestSecureClient.HandleConnectionReady()
at SocketEx.TcpClient.InnerConnect(EndPoint myEndpoint)
at MYAPP.MyTest2.Network.Security.MyTestSecureClient..ctor(String host, Int32 port, TlsClient tlsClient)
at MYAPP.MyTest2.Network.Security.MyTestSecureClient..ctor(String host, Int32 port)
at MYAPP.MyTest2.Network.ConnectionManager.CreateConnection(String host, Int32 port)
at MYAPP.MyTest2.Network.ConnectionManager..ctor(String host, Int32 port)
at MYAPP.MyTest2.Network.MyTestService.CreateConnectionManager(String host, Int32 port)
at MYAPP.MyTest2.Network.MyTestService.Login(LoginRequestModel request)
at MYAPP.MyTest2.ViewModel.LoginViewModel.<Login>b__1()
at MYAPP.MyTest2.Common.Helpers.ThreadHandler.<>c__DisplayClass3`1.<Execute>b__0(Object x)
If anyone know how to fix this, please help me !
Regards,
Artur

Related

Getting error falling CreateServerCertificateAsync: Could not get server cert while using test certs at IoT Edge device(azure)

I am trying to enable certs at the IoT Edge device end I am using the demo certs but the iothub module is failing with below error
2021-04-27 02:08:48.364 +00:00 Edge Hub Main()
Unhandled exception. System.AggregateException: One or more errors occurred. (Error calling CreateServerCertificateAsync: Could not get server cert
caused by: internal error)
---> Microsoft.Azure.Devices.Edge.Util.Edged.WorkloadCommunicationException- Message:Error calling CreateServerCertificateAsync: Could not get server cert
caused by: internal error, StatusCode:500, at: at Microsoft.Azure.Devices.Edge.Util.Edged.Version_2019_01_30.WorkloadClient.HandleException(Exception ex, String operation) in /home/vsts/work/1/s/edge-util/src/Microsoft.Azure.Devices.Edge.Util/edged/version_2019_01_30/WorkloadClient.cs:line 109
at Microsoft.Azure.Devices.Edge.Util.Edged.WorkloadClientVersioned.Execute[T](Func`1 func, String operation) in /home/vsts/work/1/s/edge-util/src/Microsoft.Azure.Devices.Edge.Util/edged/WorkloadClientVersioned.cs:line 77
at Microsoft.Azure.Devices.Edge.Util.Edged.Version_2019_01_30.WorkloadClient.CreateServerCertificateAsync(String hostname, DateTime expiration) in /home/vsts/work/1/s/edge-util/src/Microsoft.Azure.Devices.Edge.Util/edged/version_2019_01_30/WorkloadClient.cs:line 35
at Microsoft.Azure.Devices.Edge.Util.CertificateHelper.GetServerCertificatesFromEdgelet(Uri workloadUri, String workloadApiVersion, String workloadClientApiVersion, String moduleId, String moduleGenerationId, String edgeHubHostname, DateTime expiration) in /home/vsts/work/1/s/edge-util/src/Microsoft.Azure.Devices.Edge.Util/CertificateHelper.cs:line 260
at Microsoft.Azure.Devices.Edge.Hub.Service.EdgeHubCertificates.LoadAsync(IConfigurationRoot configuration, ILogger logger) in /home/vsts/work/1/s/edge-hub/src/Microsoft.Azure.Devices.Edge.Hub.Service/EdgeHubCertificates.cs:line 54
at Microsoft.Azure.Devices.Edge.Hub.Service.Program.MainAsync(IConfigurationRoot configuration) in /home/vsts/work/1/s/edge-hub/src/Microsoft.Azure.Devices.Edge.Hub.Service/Program.cs:line 54
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at Microsoft.Azure.Devices.Edge.Hub.Service.Program.Main() in /home/vsts/work/1/s/edge-hub/src/Microsoft.Azure.Devices.Edge.Hub.Service/Program.cs:line 33
Please find the config in /etc/aziot/config.toml file
trust_bundle_cert = "file:///home/azureuser/cert/certs/azure-iot-test-only.root.ca.cert.pem"
[edge_ca]
cert = "file:///home/azureuser/cert/certs/iot-edge-device-ca-test-device-ca-certs-full-chain.cert.pem"
pk = "file:///home/azureuser/cert/certs/iot-edge-device-ca-test-device-ca-certs.cert.pem"
[provisioning]
source = "manual"
connection_string ="HostName=XXXXXXXXX-dev.azure-devices.net;DeviceId=test-device;SharedAccessKey=XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
I made a mistake while mentioning the path to the root ca. The issue is resolved

How to Nak a ServiceStack RabbitMQ message within the RegisterHandler?

I'd like to be able to requeue a message from within my Service Endpoint that has been wired up through the RegisterHandler method of RabbitMQ Server. e.g.
mqServer.RegisterHandler<OutboundILeadPhone>(m =>
{
var db = container.Resolve<IFrontEndRepository>();
db.SaveMessage(m as Message);
return ServiceController.ExecuteMessage(m);
}, noOfThreads: 1);
or here.
public object Post(OutboundILeadPhone request)
{
throw new OutBoundAgentNotFoundException(); // added after mythz posted his first response
}
I don't see any examples how this is accomplished, so I'm starting to believe that it may not be possible with the ServiceStack abstraction. On the other hand, this looks promising.
Thank you, Stephen
Update
Throwing an exception in the Service does nak it, but then the message is sent to the OutboundILeadPhone.dlq which is normal ServiceStack behavior. Guess what I'm looking for is a way for the message to stay in the OutboundILeadPhone.inq queue.
Throwing an exception in your Service will automatically Nak the message. This default exception handling behavior can also be overridden with RabbitMqServer's RegisterHandler API that takes an Exception callback, i.e:
void RegisterHandler<T>(
Func<IMessage<T>, object> processMessageFn,
Action<IMessage<T>, Exception> processExceptionEx);
void RegisterHandler<T>(
Func<IMessage<T>, object> processMessageFn,
Action<IMessage<T>, Exception> processExceptionEx,
int noOfThreads)

Sending Exception from client to server over the network

I want to throw exception from server to client over the network like this.... this is server cod sending exception
InvalidOperationException ex = new InvalidOperationException("Duplicate Key Found");
streamWriter.WriteLine(ex);
and in client side :
object serverResponse = streamReader.ReadLine();
i read object like this from server but whenever i display its type it say serverResponse is of Type System.String rather than InvalidOperationException please help me in this.
Console.WriteLine("Type Is:" + serverResponse.GetType());

InvalidProgramException in System.ServiceModel.Dispatcher.ClientRuntime after KB2742595

When ever I install the security Patch KB2742595 on my web server I'm start getting the " Exception type: InvalidProgramException
Exception message: Common Language Runtime detected an invalid program.
at System.ServiceModel.Dispatcher.ClientRuntime..ctor(String contractName, String contractNamespace)"
Stack trace: at System.ServiceModel.Dispatcher.ClientRuntime..ctor(String contractName, String contractNamespace)
at System.ServiceModel.Description.DispatcherBuilder.BuildProxyBehavior(ServiceEndpoint serviceEndpoint, BindingParameterCollection& parameters)
at System.ServiceModel.Channels.ServiceChannelFactory.BuildChannelFactory(ServiceEndpoint serviceEndpoint, Boolean useActiveAutoClose)
at System.ServiceModel.ChannelFactory.CreateFactory()
at System.ServiceModel.ChannelFactory.OnOpening()
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open()
The configuration is W Server 2K8 SP1 and communicating the WCF service over nettcp.
Please help.

.NET 4.0 client certificate validation error

I have the following code
var factory = new ChannelFactory<INewsClient>();
factory.Credentials.ClientCertificate.Certificate = GetCertificate();
factory.Endpoint.Address = new EndpointAddress("https://blabla.com/myservice/");
var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
factory.Endpoint.Binding = binding;
var channel = factory.CreateChannel();
channel.GetNews();
It works in .NET 3.5, but not in .NET4.0. Bizzare huh?
The Certificate I am using doesn't validate on the local machine (no chain). In 3.5, the client cert's validity is irrelevant to establishing SSL, but when migrating to 4.0, the certificate is validated before being used for SSL. (I can see errors in the CAPI2 Event logs). Resulting in an ugly SecurityNegotiationException...
Stack Trace:
System.ServiceModel.Security.SecurityNegotiationException: Could not establish secure channel for SSL/TLS with authority 'pep.uat.dialectpayments.com'. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ConsoleApplication2.Program.INewsClient.Get()
at ConsoleApplication2.Program.Main(String[] args) in d:\dev\ConsoleApplication2\Program.cs:line 44
In our security architecture, certs are validated against an LDAP directory on the server, therefore no need for clients to know the full chain.
Question is, how do I disable this new behaviour?
Ok, I'll provide my own answer here...
In a nutshell: It seems you cannot use a non-persistent CSP with .NET 4 for X509. I.e. Your CSP must have a KeyContainerName for it to work.
My GetCertificate() method was doing the following: (i.e. Non-Persistent)
var certificate = new X509Certificate2(#"C:\public.cer");
var rsa = RSA.Create();
rsa.FromXmlString("<RSAKeyValue>......</RSAKeyValue>");
certificate.PrivateKey = rsa;
return certificate;
Changing it to this makes my sample work in 3.5 and 4.0: (Setting KeyContainerName will create a physical entry in your crypto folders)
var certificate = new X509Certificate2(#"C:\public.cer");
CspParameters parameters = new CspParameters { KeyContainerName = "KeyContainer" };
var rsa = new RSACryptoServiceProvider(parameters);
rsa.FromXmlString("<RSAKeyValue>......</RSAKeyValue>");
certificate.PrivateKey = rsa;
return certificate;
For simplicity, I was trying to export the private key into a .pfx file, but couldn't using the first approach in .NET 4.0, but could using .NET 3.5. Somwhow, the private key is not exportable in .NET 4.0.
This link helped me fix it.
Still, would be nice to know what's changed between 3.5 and 4.0 here.

Resources