WCF can't find certificate for CurrentUser - azure

I have a WCF service that is telling me it can't find its certificate:
Cannot find the X.509 certificate using the following search criteria:
StoreName 'My', StoreLocation 'CurrentUser', FindType
'FindByThumbprint', FindValue
'cf51e92041d0440a262df6a357f3f709f6f8d710'.
and the config specifies the certificate by the thumbprint
<serviceCertificate storeLocation="CurrentUser" storeName="My"
findValue="cf51e92041d0440a262df6a357f3f709f6f8d710"
x509FindType="FindByThumbprint" />
Using the powershell command Get-ChildItem cert:\CurrentUser\My finds the certificate. If I change the config file to specify LocalMachine the service starts correctly.
What is going on? I suppose I could change the config file, however, when publishing my service to Azure then it can't find the uploaded certificate because that is looking in CurrentUser. I know I could use different configs for different environments, but I don't want to blindly head down that path without understanding the "why" of things.

Related

Uwp Certificate build pipeline import error

I use the below script to import a certificate in a pipeline build process,
Powershell script:
param($PfxFilePath, $Password)
$absolutePfxFilePath = Resolve-Path -Path $PfxFilePath
Write-Output "Importing store certificate '$absolutePfxFilePath'..."
Add-Type -AssemblyName System.Security
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($absolutePfxFilePath, $Password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
$store = new-object system.security.cryptography.X509Certificates.X509Store -argumentlist "MY", CurrentUser
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::"ReadWrite")
$store.Add($cert)
$store.Close()
Get below error:
. 'C:\JobAppAgent_work\1\s\JobApp\DevOps\Build\Import-PfxCertificate.ps1' -PfxFilePath $env:DOWNLOADSECUREFILE1_SECUREFILEPATH -Password ****
Importing store certificate 'C:\JobAppAgent_work_temp\DD.Job.Desktop_TemporaryKey.pfx'...
##[error]Exception calling "Import" with "3" argument(s): "The specified network password is not correct.
This script was running fine when build was running on Azrure PipeLines. Now I create a private Agent pool that runs on a Window 10 VM.
Make sure that the certificate is valid and has not expired. You can check the expiration date of the certificate by double-clicking on it and viewing the details.
Check that the certificate is properly installed on the machine where the build is being performed. If the certificate is not installed, it will not be available for use in the build process.
Make sure that the certificate is correctly referenced in the build pipeline. This may involve specifying the path to the certificate file or the thumbprint of the certificate.
If you are using a self-signed certificate, make sure that it is trusted by the machine where the build is being performed. To do this, you will need to install the certificate in the trusted root certification authorities store on the machine.
If you are using a certificate from a certificate authority (CA), make sure that the CA is trusted by the machine where the build is being performed. This may involve installing the root certificate of the CA on the machine.
This is a PowerShell script that imports a certificate from a file with a given password into the "MY" store in the current user's certificate store. The certificate is imported using the Import method of the X509Certificate2 class, which takes as input the path to the certificate file, the password, and a set of key storage flags. The script then creates an X509Store object representing the "MY" store in the current user's certificate store, opens the store in read-write mode, adds the imported certificate to the store, and closes the store.
This script assumes that the certificate file is in the Personal Information Exchange (PFX) format, which is a common format for storing certificates and their private keys. PFX files are often used to export or import certificates, and they can be password-protected for added security.
Verify that the password you are using to import the certificate is correct. It's possible that the password has been changed or entered incorrectly.
Check that the certificate file has not been damaged or modified in any way. If the file has been altered, it may be causing the import to fail.
Make sure that the certificate file is accessible to the machine where the script is being run. If the file is on a network share or another machine, check that the machine has the necessary permissions to read the file.
If the certificate file is password-protected, make sure that the password has not expired or been revoked.
Try running the script with different key storage flags to see if that has any effect on the error. For example, you could try using "Exportable" instead of "PersistKeySet" as the key storage flag.

How to fix "The private key is not present in the X.509 certificate"

at the moment I´m working in azure with azure automation and automation account. For executing a runbook I want to authenticate me with a service principal + certificate.
Unfortunately I get the error message "The private key is not present in the X.509 certificate".
I will use:
Add-AzureRmAccount -ServicePrincipal -Tenant xxx -ApplicationId xxx -CertificateThumbprint xxx
But with Login-AzureRmAccount and Connect-AzureRmAccount I get the same error message.
What have I done so far?
Since I´m working in a big company I can´t use a self-signed certificate. Our team have created a .cer-File and .key (Private Key) file for me. After some testing I find out that I need something like this:
Example
Furthermore, I know that I can get this with an .pfx file but this is not accepted from the other team, which will import the certificate to my service principal since they only accept .cer files.
How can I get a .cer file with an public key included?
Thanks a lot!
Your certificate needs to include the private key if you want to sign in with it, which from the error message appears missing. A certificate with the private key included should have a file name of ~.pfx. For reference, check the MS doco here: "Clients which sign in with the service principal also need access to the certificate's private key"

Custom domains/SSL binding in Microsoft Azure server

I have installed SSL successful in my azure server but it's not binding with domain. I am getting following error message.
It is not clear on what certificate you are using. To use a certificate in App Service, the certificate must meet all the following requirements:
Signed by a trusted certificate authority
Exported as a password-protected PFX file
Contains private key at least 2048 bits long
Contains all intermediate certificates in the certificate chain
As highlighted by Snobu you may regenerate the certificate (for Self-Signed) with: extendedKeyUsage = critical,codeSigning,1.3.6.1.5.5.7.3.1 in the x509_extensions in the file. Refer this document for the step-step instructions on uploading a certificate.

how to connect to azure (management) rest api via C# in IIS

I am trying to setup a website (local testing atm), to connect to azure rest api to see our settings. I created a cert locally (W7 machine):
makecert -sky exchange -r -n "CN=azureConnectionNew" -pe -a sha1 -len 2048 -ss My "azureConnectionNew.cer"
I can see the cert in the certs MMC snap in. (do not have a right click edit permissions option when I view the cert in here).
I have a class library that setups up the connection, the cert is passed in by getting the cert (via the thumb string), this works great for the console app, but when I try and do this in a web app it all goes wrong. I get 403 errors.
I first thought that this was due to the fact that the website is running as the ApplicationPoolIdentity so doesn't have access to the cert. So I tried passing in the cert (to the same code as the console app), by loading the actual file:
var path = #"C:\temp\azureconnection\azureConnectionNew.cer";
var cert = new X509Certificate2();
cert.Import(path);
I still get 403 errors.
I tried exporting the cer file from MMC certificates snap in as a pfx file, (with private keys included). I set the local IIS set to use this cert and navigated to the https version of my local site but still got 403.
I am not sure how to include / setup / reference the cert so that IIS can send a HttpWebRequest from the server side to Azure and get a valid response.
It is always better to use Thumbprint of the certificate to get the certificate. Please make sure you have created the certificate correctly. Also please check you have placed the certificate in Personal certificate section in Local Machine. You can check this using MMC snap in. please try below code..
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
var certificate = store.Certificates
.Cast<X509Certificate2>()
.SingleOrDefault(c => string.Equals(c.Thumbprint, “CertificateThumbprint”, StringComparison.OrdinalIgnoreCase)); // please replace CertificateThumbprint with original Thumbprint
This isn't the right way to use the certificate - it needs to be stored in the personal/certificates store of the user running the code (you should update the App Pool identity to be a user who can login and into whose certificates you import the cert. Here's sample code showing you how to use the service API: http://code.msdn.microsoft.com/windowsazure/CSAzureManagementAPI-609fc31a/

Client certificate authentication and CA certificate in Azure

I need to authenticate requests to Azure Cloud Service Web Role using client certificates. How to put the Certification Authority (CA) root certificate in a right trusted store?
I tried to upload it in Management Portal and then defining it in service definition file with AuthRoot store name:
<Certificate name="RootCA" storeLocation="LocalMachine" storeName="AuthRoot" />
What's really strange is that it works... but only sometimes. It may work after an instance reboot, but may not work after a service update or another instance reboot. It seems like a bug in Azure.
When I say "works" I mean server successfully accepts the client certificate and processes the request.
When I say "doesn't work" I mean server doesn't negotiate a connection after certificate checks and "The request was aborted: Could not create SSL/TLS secure channel." exception is thrown on a client side.
How to make it working stable?
UPD:
Found this record in System Windows Event Log (source is Schannel):
When asking for client authentication, this server sends a list of
trusted certificate authorities to the client. The client uses this
list to choose a client certificate that is trusted by the server.
Currently, this server trusts so many certificate authorities that the
list has grown too long. This list has thus been truncated. The
administrator of this machine should review the certificate
authorities trusted for client authentication and remove those that do
not really need to be trusted.
The exact problem is described here: http://support.microsoft.com/kb/2801679.
After December 2012 Windows update a lot of certificates were added to AuthRoot store. So we have to remove them to solve the problem.
To make it I use PowerShell startup task:
Get-ChildItem -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates\AuthRoot\Certificates | Where-Object {$_.Name -notlike "*\<YOUR_CERTIFICATE_THUMBPRINT>"} | Remove-Item
To run it from CMD startup task:
PowerShell -ExecutionPolicy Unrestricted .\Startup.ps1
exit /b %errorlevel%
And in ServiceDefinition.csdef:
<WebRole name="Web">
<Startup>
<Task commandLine="Startup.cmd" executionContext="elevated" taskType="simple" />
</Startup>
<!-- ... ->
</WebRole>

Resources