Fail to establish SSL connection unless user is in Administrators group - wcf

It is a .NET 6 project. The certificate is imported to the Local Computer store from a pfx file.
Using the following code, skipping the irrelevant parts, everything works fine when the service account is added to the local Administrators group.
var certStore = new X509Store(storeName, storeLocation);
certStore.Open(OpenFlags.ReadOnly);
var _clientCertificate = certStore.Certificates
.Find(X509FindType.FindByThumbprint, thumbprint, false)
.FirstOrDefault();
...
BasicHttpsBinding binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
var client = new Client(binding, endpoint);
client.ClientCredentials.ClientCertificate.Certificate = _clientCertificate;
...
When the account is not in the local Administrators' group the following exception is thrown:
System.ServiceModel.Security.SecurityNegotiationException: Could not establish trust relationship for the SSL/TLS secure channel with authority 'other.service.com'.
---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception.
---> System.ComponentModel.Win32Exception (0x8009030D): The credentials supplied to the package were not recognized
at System.Net.SSPIWrapper.AcquireCredentialsHandle(ISSPIInterface secModule, String package, CredentialUse intent, SCHANNEL_CRED* scc)
at System.Net.Security.SslStreamPal.AcquireCredentialsHandle(CredentialUse credUsage, SCHANNEL_CRED* secureCredential)
at System.Net.Security.SslStreamPal.AcquireCredentialsHandleSchannelCred(SslStreamCertificateContext certificateContext, SslProtocols protocols, EncryptionPolicy policy, Boolean isServer)
at System.Net.Security.SslStreamPal.AcquireCredentialsHandle(SslStreamCertificateContext certificateContext, SslProtocols protocols, EncryptionPolicy policy, Boolean isServer)
What am I missing here?

As far as I know, there may be the following reasons:
When you say that you are not in the local administrator group, the error will be because of the administrator and general members have different permissions. You can try to put the user in the administrator to try again, if successful, this is the problem.
Validate the Web Sites SSL Certificate is Trusted. If the SSL certificate is not trusted, you will need to install the SSL certificate’s root certificate. You can review the case for more solutions.
Hope it helps.

Related

C# Cannot connect to AD using LDAPS

My requirement was to change the user password of AD. So, I created the LDAP SSL secure connection on the AD domain server by following https://bl.ocks.org/magnetikonline/0ccdabfec58eb1929c997d22e7341e45 successfully.
Using the ldp.exe tool (on the same AD server) I am able to connect with the SSL. This means LDAPS is enabled on the AD server.
Now I am trying to connect it from the ASP.NET Core application using the library Novell.Directory.Ldap which is on client-side using the following code:
public LdapConnection GetLDAPConnection(IOptions<ADConfiguration> _settings)
{
LdapConnection connection = new LdapConnection { SecureSocketLayer = true };
connection.Connect(_settings.Value.DomainIPAddress, _settings.Value.Port); //port is 636
connection.Bind(_settings.Value.AdminDn, _settings.Value.Password);
if (connection.Bound)
{
return connection;
}
return null;
}
The Connect method is throwing this error:
System.Security.Authentication.AuthenticationException: 'The remote certificate was rejected by the provided RemoteCertificateValidationCallback.'
Does the client machine also have settings for SSL? Or what else I am missing? Please help
I suspect your problem is using the IP address of the domain controller: _settings.Value.DomainIPAddress
SSL/TLS has two purposes: to encrypt the traffic, and to validate that the server is actually the server you want to be talking to. To address the second purpose, the domain name you use to connect must match the domain name in the certificate. In your case, when it validates the certificate, it sees that you connected to, let's say, 10.0.0.1, but the certificate it gets from the server says it is example.com and the validation fails because it doesn't match.
You will have to either:
Change _settings.Value.DomainIPAddress to the domain name used in the certificate. If you don't have DNS setup for that domain name, you could add an entry in your hosts file.
Tell LdapConnection to ignore certificate errors. The data will still be encrypted, but it won't validate the certificate (domain mismatch, expired cert, etc.). This is not recommended for a production application, but there is an example of that here: https://stackoverflow.com/a/67818854/1202807
Below code worked for me to connect to AD using LDAPS
ldapConnection = new LdapConnection(new LdapDirectoryIdentifier("your.LDAPSserver.com", 636));
var networkCredential = new NetworkCredential("UsernameWithoutDomain", "yourPassword", "AD.yourDOMAIN.com");
ldapConnection.SessionOptions.SecureSocketLayer = true;
ldapConnection.SessionOptions.ProtocolVersion = 3;
ldapConnection.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(ServerCallback);
ldapConnection.AuthType = AuthType.Negotiate;
ldapConnection.Bind(networkCredential);
SearchRequest Srchrequest = new SearchRequest("CN=Users,DC=AD,DC=YOURCOMPANY,DC=COM", "mail=useremail#company.com", System.DirectoryServices.Protocols.SearchScope.Subtree);
SearchResponse SrchResponse = (SearchResponse)ldapConnection.SendRequest(Srchrequest);
// ServerCallback
private static bool ServerCallback(LdapConnection connection, X509Certificate certificate)
{
return true;
}
Surprisingly it is also working when I am not using networkCredential and just using ldapConnection.Bind(); Seems it is using my local credentials as default on my local machine.

Adding a certificate to a WCF client. Cannot find X.509 certificate

I have a WCF client that is going to authenticate against some web service using a certificate issued by said service. At first my client used a https binding as below:
var httpsBinding = new BasicHttpsBinding();
httpsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
httpsBinding.Security.Mode = BasicHttpsSecurityMode.Transport;
but this gave the following error:
InvalidOperationException: The client certificate is not provided.
Specify a client certificate in ClientCredentials.
I then added the following code to my client configuration:
this.ChannelFactory.Credentials.ClientCertificate.SetCertificate("test", System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
System.Security.Cryptography.X509Certificates.StoreName.My);
And now I get the error
System.InvalidOperationException: 'Cannot find the X.509 certificate
using the following search criteria: StoreName 'My', StoreLocation
'LocalMachine', FindType 'FindBySubjectDistinguishedName', FindValue
'test'.'
I am absolutely certain that the certificate is placed in the Personal folder on my Local Machine, but it still cannot find it. I have tried placing the certificate in various folders, renaming it, using the thumbprint for identification, but my application still can't find it. What could be the issue here?
I suggest you set up the certificate by using X509FindType.FindByThumbprint.
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
//client.ClientCredentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.Root, X509FindType.FindByThumbprint, "cbc81f77ed01a9784a12483030ccd497f01be71c");
client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "9ee8be61d875bd6e1108c98b590386d0a489a9ca");
It corresponds to the below value.
In order to allow WCF service could access this local certificate, we usually add Everyone account to the management group of the certificate private key.
Besides, WCF service with authenticating the client with a certificate, this usually requires that we set up both the service certificate and the client certificate on the client-side.
Feel free to let me know if there is anything I can help with.

Certificate based authentication in WCF

I am trying to understand certificate based authentication using the msdn sample https://msdn.microsoft.com/en-us/library/ms731074(v=vs.90).aspx
This is the server code:
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
// Create the URI for the endpoint.
Uri httpUri = new Uri("https://localhost/Calculator");
// Create the service and add an endpoint.
ServiceHost myServiceHost = new ServiceHost(typeof(ServiceModel.Calculator), httpUri);
myServiceHost.AddServiceEndpoint(typeof(ServiceModel.ICalculator), binding, "");
// Open the service.
myServiceHost.Open();
Console.WriteLine("Listening...");
Console.ReadLine();
// Close the service.
myServiceHost.Close();
This is the client code I wrote:
ChannelFactory<ICalculator> factory = null;
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
EndpointAddress address = new EndpointAddress("https://localhost/Calculator");
factory = new ChannelFactory<ICalculator>(binding, address);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "sroger");
ICalculator channel = factory.CreateChannel();
int y = channel.add(9, 8);
I am getting the following exception:
An unhandled exception of type 'System.ServiceModel.CommunicationException' occurred in mscorlib.dll
Additional information: An error occurred while making the HTTP request to https://localhost/Calculator. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.
I am running both client and server from the same machine. And "sroger" is the certificate in my current user\ personal\certificates which corresponds to my machine name..
Not sure what to do from here..Any thoughts?
In the server code what certificate server uses?
Thanks
Gulumal.
https://msdn.microsoft.com/en-us/library/ms731074(v=vs.90).aspx example you used is incomplete.
Consuming https wcf service requires a valid server certificate to work, in your case both client and server certificates are required.
This is because both client and server need to trust each other in a HTTPS connection.
To get started, read https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/message-security-with-mutual-certificates which is a more complete example that includes specifying certificate to authenticate the service.
For a hosted WCF library via https to work you need to do the following in order:
Configure the port with an X.509 certificate (which has been
answered in
webHttpBinding with certificate)
From your server, create certificate request for common name of your
server fully qualified domain name, or at-least including a DNS subjectAltName of your server fully qualified domain name.
(there are different ways to do this, you may already know this
though)
Issue certificate and install certificate on your server
Grab application id from assembly file of your App that hosts WCF
library (i.e [assembly:
Guid("5870aeed-caca-4734-8b09-5c0615402bcf")]) Grab the certificate
thumbprint by viewing certificate properties.
As administrator, open
CMD and run this command to bind X.509 certificate to the port used
by your app on server
netsh http add sslcert ipport=0.0.0.0:443 certhash= appid={} certstorename=MY
netsh http add iplisten ipaddress=0.0.0.0:443
Add this to your server code:
myServiceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySerialNumber, "<certificate thumbprint>");
In your client code, reference your server address by fully qualified domain name that certificate that is specified as certificate Common Name or subject Alt Name

STS Error "The issuer of the token is not a trusted issuer."

So for starters, here's my environment:
SharePoint 2010
Windows Server 2008 Standard
It's a VHD on my local
machine
I'm connected to my work domain I'm also connected to a
VPN as well because some of the resources I need require it
So I have an STS in SharePoint for SSO
The STS is created via PowerShell cmdlets:
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("c:\IdentityServer.cer")
$map1 = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" -IncomingClaimTypeDisplayName "EmailAddress" –SameAsIncoming
# $map2 ... $mapN
$realm = "urn:mycompany:software"
$signinurl = "https://somesignin.com/FederationProvider/"
$ap = New-SPTrustedIdentityTokenIssuer -Name "MyFederationProvider" -Description "My Fed Provider" -Realm $realm -UseWReply -ImportTrustCertificate $cert -ClaimsMappings $map1 -SignInUrl $signinurl -IdentifierClaim $map1.InputClaimType
For the Internet Zone of my SharePoint site, I have the trusted identity provider created above as the Claims Authentication Type.
When I log in everything goes well until I hit this line in the code,
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(signInResponseMessage, Response);
The error I get is:
Exception information:
Exception type: SecurityTokenException
Exception message: The issuer of the token is not a trusted issuer.
Request information:
Request URL: https://mySharePointSite.com:443/_trust/default.aspx
Request path: /_trust/default.aspx
User host address: 127.0.0.1
User:
Is authenticated: False
Authentication Type:
Thread account name: MyDomain\ThreadAccount
Thread information:
Thread ID: 10
Thread account name: MyDomain\ThreadAccount
Is impersonating: False
Stack trace: at Microsoft.SharePoint.IdentityModel.SPTrustedIssuerNameRegistry`1.GetIssuerName(SecurityToken securityToken)
at Microsoft.SharePoint.IdentityModel.SPPassiveIssuerNameRegistry.GetIssuerName(SecurityToken securityToken)
at Microsoft.IdentityModel.Tokens.Saml11.Saml11SecurityTokenHandler.CreateClaims(SamlSecurityToken samlSecurityToken)
at Microsoft.IdentityModel.Tokens.Saml11.Saml11SecurityTokenHandler.ValidateToken(SecurityToken token)
at Microsoft.IdentityModel.Web.TokenReceiver.AuthenticateToken(SecurityToken token, Boolean ensureBearerToken, String endpointUri)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequest request)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
However, the root certificate is in the Trusted Root Certification Authorities in the MMC Certificates snap-in for the Computer Account on the Local Computer.
As well, the root certificate is considered trusted in SharePoint. I added it via the Central Administration->Security->Manage Trust.
Any ideas why I'd still be getting this error?
Do you have an STS running at https://somesignin.com/FederationProvider/?
The documentation for New-SPTrustedIdentityTokenIssuer says that it "Creates an identity provider in the farm." This seems poorly worded to me. It doesn't actually create a new STS. What New-SPTrustedIdentityTokenIssuer really does is configure a trust relationship between sharepoint and an existing 3rd party identity provider. For example,
LiveID:
http://technet.microsoft.com/en-us/library/ff607628.aspx
or ADFS:
http://msdn.microsoft.com/en-us/library/hh446525.aspx
The problem was the certificate being used initially was not from the domain I develop on. For local development a self-signed certificate was created and then the issuer was trusted. And this certificate was added to the manage trust store of my local Sharepoint farm, http://onpointwithsharepoint.blogspot.ca/2012/11/managing-trust-certificates-by-using.html.

wcf service with transport security

I've been struggling with following since few days. Please help me. I'm using XP machine with .Net 3.5. I was following this example http://msdn.microsoft.com/en-us/library/ms729789.aspx. I created a certificate using http://msdn.microsoft.com/en-us/library/ms733813(v=vs.90).aspx and imported the root certificate in the Certificate(Local Computer) > Trusted Root Certification Authorities > Certificates and other one in the Certificate(Local Computer) > Personal > Certificates. I've self hosted service. The hosing code is
ServiceHost svcHost = new ServiceHost(typeof(CalculatorService.CalculatorService), new Uri("https://localhost:8012/CalculatorService"));
ServiceMetadataBehavior smb = svcHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
smb = new ServiceMetadataBehavior();
smb.HttpsGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
svcHost.Description.Behaviors.Add(smb);
svcHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
MetadataExchangeBindings.CreateMexHttpsBinding(),
"mex");
WSHttpBinding b = new WSHttpBinding();
b.Security.Mode= SecurityMode.Transport;
b.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
svcHost.AddServiceEndpoint(typeof(CalculatorService.ICalculator),b , "");
svcHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "SignedByCA");
svcHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
svcHost.Close();
When I try to add reference in the client I get the following error.
There was an error downloading 'https://localhost:8012/CalculatorService/mex'.
The underlying connection was closed: An unexpected error occurred on a send.
Authentication failed because the remote party has closed the transport stream.
Metadata contains a reference that cannot be resolved: 'https://localhost:8012/CalculatorService/mex'.
An error occurred while making the HTTP request to https://localhost:8012/CalculatorService/mex. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.
The underlying connection was closed: An unexpected error occurred on a send.
Authentication failed because the remote party has closed the transport stream.
If the service is defined in the current solution, try building the solution and adding the service reference again.
I think I've tried all possible ways. Now, I've no clue. Please help me. You're my final resource.