Accessing Securised Web Service - c#

I need to connect to a provider's web service with a Windows Form application. He gives me a certificate to access it but I have a security problem.
I have done these following steps :
Add certificate to personal store (on IE & Firefox)
Generate a proxy with the remote wsdl (no problem)
Use this code to call a method :
`using (service1.MessagesService m = new service1.MessagesService())
{
X509Certificate crt = new X509Certificate(#"C:\OpenSSL\bin\thecert.p12",string.Empty);
m.ClientCertificates.Add(crt);
var result = m.AuthoriseTransaction(aut);
this.textBox1.AppendText(result.id.ToString());
}`
I have the following error :
The underlying connection was closed: Could not establish trust relationship for the channel SSL / TLS.
Thanks for your help

Your connection isn't being authorised correctly, is the webservice over https? You may need to create a custom implementation of CertificatePolicy. See this article for an example.

Related

Unable to establish https connection with gRPC

I have gRPC client / server code happily working on my local machine with the client using ChannelCredentials.Insecure but need to switch to a secure mode. I dont need any certificate checks just encrypted traffic.
Ive been unable to find any configuration of client server that talks to each other.
Running c# core server (gRPC 2.27.0), & c# .net framework client (gRPC 2.28.1).
The server says it publishing on http & https as below:
[20:12:58 DBG] Using development certificate: CN=localhost (Thumbprint: 3EDA2E5BD559D75C9DCF058E0A6994EED859CD34)
[20:12:58 INF] Now listening on: https://localhost:5001
[20:12:58 INF] Now listening on: http://localhost:5000
and client works with:
ChannelBase channel = new Channel("localhost:5000", ChannelCredentials.Insecure);
var client = new MyApp.MyAppClient(channel);
var response = client.Test(request)
If I switch client to SslCredentials as below
ChannelBase channel = new Channel("localhost:5001", new SslCredentials());
var client = new MyApp.MyAppClient(channel);
var response = client.Test(request)
I get the following errors.
server error
[19:32:53 DBG] Failed to authenticate HTTPS connection.
System.IO.IOException: Authentication failed because the remote party has closed the transport stream.
at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest)
client error
Grpc.Core.RpcException: 'Status(StatusCode=Unavailable, Detail="failed to connect to all addresses")'
I've also tried adding (server) with no change in errors.
services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(options =>
{
options.RevocationMode = X509RevocationMode.NoCheck;
options.ValidateCertificateUse = false;
options.AllowedCertificateTypes = CertificateTypes.SelfSigned;
});
Any suggestions as to what i need to do to make them talk.
So you need to specify roots.pem that correspond to the dev certificate you're using on your server when creating SslCredentials.
If you use parameterless SslCredentials(), it will use the default trust roots which only work for certificates that have been signed by publicly trusted certificate authorities (e.g. if you're talking "official" servers such as googleapis.com etc, definitely not the case for your development certificates that you are using on your server). So you need to use SslCredentials(yourCustomTrustRootsPem).
Btw, with SSL/TLS, there's no such thing as "no certificate checks". The client will ALWAYS check that it connected to the right server (server's certificate are verifiable by their trust roots) - without that the secure communication would make no sense because it would be too susceptible to man-in-the-middle attack. (the server checking authenticity of client is optional though).
Feel free to refer to https://github.com/jtattermusch/grpc-authentication-kubernetes-examples for extra resources.
I had a similar problem and finally found a solution to establish HTTPs connection between
.NET Framework 4.7.2 client (WPF app) and
ASP .NET Core 3.1 gRPC Server (Console).
Indeed the answer of Jan Tattermusch is correct. You need to supply the server side certificate as PEM to the constructor of SslCredentials and in addition, the certificate has to contain the DNS name or IP of the url you are contacting the server through. In your case, I suggest to manually create a self-signed certificate for each server instead of using the developer certificate. This one can be downloaded by your client and then be passed as SslCredentials. Works like a charm.
See my more details on how to do all the details in my answer to a similar question here:
https://stackoverflow.com/a/63565090/378415
Try to check on which port Grpc Service is running after deployment in any way either windows service or other , then give the same in client to consume the service. Eg: If your service is running on https://localhost:5000 then give the same in client.
It will work for sure.
Mostly you will get the above issue when you make a mistake of mismatching the address of service to client.

HANA Service Layer : Could not establish trust relationship for the SSL/TLS secure channel

I am trying to call SAP HANA Service Layer through my code but I am stumbling upon the below error : So can anyone please help me on this.
Error 1st :
AuthenticationException: The remote certificate is invalid according to the validation procedure.
Error 2nd :
WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
Error 3rd :
HttpRequestException: An error occurred while sending the request.
Some more details about the App - I have created the console app in .NET and it executes on the server [HANA Server is locally accessed as both the servers are in the LAN] Linux & Windows Server.
One more thing - My client is not planning to purchase the domain name and SSL certificate for the SAP HANA Service Layer because it will be consumed by my app internally.
The thing is, when I tested the login service via Postman it's working fine and I am getting the session details as well but the same URL is not working through my code so is there anything more I need to do to access the service?
URL - https://172.17.100.35:50000/b1s/v1/Login
using (var client = new HttpClient())
{
var credentials = new { UserName = "admin", Password = "", "" };
var json = JsonConvert.SerializeObject(credentials);
var response = client.PostAsync(url),
new StringContent(json, Encoding.UTF8, "application/json")).Result;
if (response.IsSuccessStatusCode)
{
dynamic content = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
// Access variables from the returned JSON object
var appHref = content.links.applications.href;
}
}
For future googlers getting a 500 error response after sending your request to the Login endpoint, disable ExpectContinue.
client.DefaultRequestHeaders.ExpectContinue = false;
You need to put this code before postAsync
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
This avoid the validation of the certificate.
If you are using self signed certificates you have to accepted them first. that can be done by add it to windows certificates ou by the browser!
if you are making cross-domain calls, you need to change the b1s.config
vim /usr/sap/SAPBusinessOne/ServiceLayer/conf/b1s.conf
(...)
"CorsEnable": true,
"CorsAllowedOrigins": "*"}
do note use * in production MODE <-<<<--

Error SecureChannelFailure, could not create SSL/TLS

I am calling a web service using certifcates and security protocol. The application was running fine but suddenly started giving me web exception.
The request was aborted: Could not create SSL/TLS secure channel.
when I checked status code, it is SecureChannelFailure and HResult is 2146233079.
The web service response is returning NULL.
Part of the code is as follows:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
I appreciate any help.
A few questions that might point you in the right direction
Maybe the certificate you are using has expired?
Maybe you are running the client from a different computer than before which doesn't have the trusted root of the certificate installed?
Maybe the certificate was somehow revoked?
Hope it helps!
It worked for me when I added certs like this
X509Store certificatesStore = new X509Store(storeName, storeLocation);
certificatesStore.Open(OpenFlags.OpenExistingOnly);
var matchingCertificates = certificatesStore.Certificates.Find(X509FindType.FindBySerialNumber, serialNumber, true);
request.ClientCertificates.Add(matchingCertificates );
did you get a resolution to this?
I've noticed that a windows update to my windows 10 machine and the windows 2008RC servers have caused our issue. The problem we have is that we cannot quickly change the 3rd party servers from SHA1 encrypted certs.
A way around it is to uninstall the updates listed here.
https://blogs.windows.com/msedgedev/2016/04/29/sha1-deprecation-roadmap/
Another way around it is to add this line of code:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Ref: Could not establish trust relationship for SSL/TLS secure channel -- SOAP
However this doesn't work for us.

Connecting to Analysis Service from ASP.net application

I am trying to implement ASP.net application which will need to connect Microsoft Analysis Service (SSAS) to retrive data from cube as well as dimensions.
static void Main(string[] args)
{
StringBuilder connectionStringBuilder = new StringBuilder();
connectionStringBuilder.Append("Data Source=MyDataSource;");
connectionStringBuilder.Append("Initial Catalog=MyOlapDatabase;");
connectionStringBuilder.Append(#"User Id=OlapServerMachineName\MyUserName;");
connectionStringBuilder.Append("Password=MyPassword;");
connectionStringBuilder.Append("Provider=MSOLAP.5;");
connectionStringBuilder.Append("Persist Security Info=True;");
connectionStringBuilder.Append("MDX Compatibility=1;");
connectionStringBuilder.Append("Safety Options=2;");
connectionStringBuilder.Append("MDX Missing Member Mode=Error;");
connectionStringBuilder.Append("Update Isolation Level=2;");
using (var connection = new AdomdConnection(connectionStringBuilder.ToString()))
{
connection.Open();
}
}
This code throws the following exception
A connection cannot be made. Ensure that the server is running.
and inner exception says
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
and inner exception of inner exception is
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
On the other hand, I can connect to this Analysis Service from Excel with the same user name and password as shown below
I tried setting up HTTP access to Olap Server as described here. With anonymous authentication on IIS setting, I am able to connect successfully. But when I disable Anonymous option and enable Basic Authentication, again I am not able connect from my client tool but Excel is working fine with Basic Authentication.
But trying to use HTTP access was just for temporary solution. I do not want to use that option. I want to be able connect SSAS like I can in excel from my client app.
My question is, what is the difference between my implementation to connect SSAS (does not work) and excel authentication (works perfect) ?
Thank you in advance.
Instead of putting the user and password on the connection string try wrapping at least your .Open() function call in this impersonator:
https://github.com/OlapPivotTableExtensions/OlapPivotTableExtensions/blob/master/OlapPivotTableExtensions/Impersonater.cs
I have had more success with that than passwords on the connection string.
You shouldn't need the msmdpump HTTP layer unless you prefer it be involved.

The Underlying Connection Was Closed. Could not establish trust relationship with remote server

I'm trying to connect to a web service through HTTPS.
I had success configuring a self-signed certificate by referring to this link Setting up IIS with HTTPS Binding
Now I added some code to the handheld device to call the web service. I had referred to several websites and saw the same code.
public class MyPolicy : ICertificatePolicy
{
public bool CheckValidationResult(
ServicePoint srvPoint
, X509Certificate certificate
, WebRequest request
, int certificateProblem)
{
//Return True to force the certificate to be accepted.
return true;
} // end CheckValidationResult
} // class MyPolicy
I also added this line before calling the web service
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
But I am still getting the error: Could not establish trust relationship with remote server.
Any clues on what's wrong with the code?
The handheld code probably doesn't trust your self-signed certificate. You have to override the default certificate handling to allow it. When calling from a browser, this triggers a warning dialog which allows you to trust the self-signed certificate in a specific case.

Categories

Resources