Generate a client certificate with key vault - azure

For our point to site VPN, we want to create a root certificate.
So we can create as many client certificates as we want for all the partners that have the need to login in our VPN. (Azure virtual network)
Doing this manually works perfect. We generate a certificate (self signed) that acts as root ca. We are able to do this in powershell like this:
$cert = New-SelfSignedCertificate -Type Custom -KeySpec Signature -Subject "CN=Kratos Point To Site VPN Root Certificate Win10" -KeyExportPolicy Exportable -HashAlgorithm sha256 -KeyLength 2048 -CertStoreLocation "Cert:\CurrentUser\My" -KeyUsageProperty Sign -KeyUsage CertSign
$clientCert = New-SelfSignedCertificate -Type Custom -KeySpec Signature -Subject "CN=Digicreate Point To Site VPN Client Certificate Win10" -KeyExportPolicy Exportable -HashAlgorithm sha256 -KeyLength 2048 -CertStoreLocation "Cert:\CurrentUser\My" -Signer $cert -TextExtension #("2.5.29.37={text}1.3.6.1.5.5.7.3.2")
However, we prefer to use the key vault for our certificate management. The idea is to create a certificate directly in the key vault by using this command:
Add-AzureKeyVaultCertificate (with the private key not exportable)
Creating the root certificate works perfectly. But I am not able to find how I can sign a new certificate with the 'sign' operations in the key vault.
Do you have a sample on how to this?

Refer to the "Create a certificate manually and get signed by a CA" section in https://blogs.technet.microsoft.com/kv/2016/09/26/get-started-with-azure-key-vault-certificates/

but I would like to create a client certificate based on this root
certificate with azure key vault cmdlets. Is this possible?
Do you mean you want to download the certificate? if yes, we can use this script to download it:
download Private certificate to your D:\cert:
$kvSecret = Get-AzureKeyVaultSecret -VaultName 'jasontest2' -Name 'TestCert01'
$kvSecretBytes = [System.Convert]::FromBase64String($kvSecret.SecretValueText)
$certCollection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certCollection.Import($kvSecretBytes,$null,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$protectedCertificateBytes = $certCollection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, 'test')
$pfxPath = 'D:\cert\test.pfx'
[System.IO.File]::WriteAllBytes($pfxPath, $protectedCertificateBytes)
Download public certificate to your D:\cert:
$cert = Get-AzureKeyVaultCertificate -VaultName 'jasontest2' -Name 'TestCert01'
$filePath ='D:\cert\TestCertificate.cer'
$certBytes = $cert.Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
[System.IO.File]::WriteAllBytes($filePath, $certBytes)
Update:
The $certificateOperation.CertificateSigningRequest is the base4 encoded certificate signing request for the certificate.
Import-AzureKeyVaultCertificate -VaultName $vaultName -Name $certificateName -FilePath C:\test\OutputCertificateFile.cer
More information please refer to this blog.
Update:
We should sign the CertificateSignRequest with the sign operation with your CA server.
Enterprise certificate:
If you are using an enterprise certificate
solution, generate a client certificate with the common name value
format 'name#yourdomain.com', rather than the 'domain name\username'
format. Make sure the client certificate is based on the 'User'
certificate template that has 'Client Authentication' as the first
item in the use list, rather than Smart Card Logon, etc. You can check
the certificate by double-clicking the client certificate and viewing
Details > Enhanced Key Usage.

Related

Azure - Access token request with a certificate - postman

i want to test access to key vault using certificate
Scenario
Second case: Access token request with a certificate
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
I am struggling to supply
client_assertion
An assertion (a JSON web token) that you need to create and sign with the certificate you registered as credentials for your application. Read about certificate credentials to learn how to register your certificate and the format of the assertion.
I dont know why powershell has to bes used, and I dont have pfx, so cant use
https://blogs.aaddevsup.xyz/2020/10/how-to-use-postman-to-perform-a-client-credentials-grant-flow-with-a-certificate/
Is it possible to generate signed JWT using postman?
Note: Certificates in postman added. so that part is taken care
I don't think you can generate client_assertion directly in postman, please use the script below to create a self-assigned certificate, then you can use the script you mentioned to get the token.
$certroopath = "C:\Users\Administrator\Desktop"
$certname = "mycert1"
$certpassword = "P#ssw0rd1234"
$cert = New-SelfSignedCertificate -DnsName "$certname" -CertStoreLocation cert:\CurrentUser\My
$pwd = ConvertTo-SecureString -String $certpassword -Force -AsPlainText
$certwithThumb = "cert:\CurrentUser\my\"+$cert.Thumbprint
$filepath = "$certroopath\$certname.pfx"
Export-PfxCertificate -cert $certwithThumb -FilePath $filepath -Password $pwd

How to obtain certificate issuer thumbprint?

I'm currently attempting to deploy a Service Fabric cluster using the instructions provided here. I've successfully created a certificate using Let's Encrypt and am able to successfully handle all the instructions except for obtaining the certificateIssuerThumbprint value, as indicated as required in the parameters file at the top of this link.
Looking at the certificate details in my Certificate Manager, I don't see a field providing this value. I read through the Chain of Trust page for Let's Encrypt on which I'd expect to find such a value, but I'm not seeing it.
How would I go about looking up what this certificate issuer thumbprint value is?
Thank you!
$secret = Get-AzKeyVaultSecret -VaultName $vault -SecretName $secretName -Version $version
$certBytes = [Convert]::FromBase64String($secret.SecretValueText)
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certBytes, $null, 'Exportable')
$certChain = [System.Security.Cryptography.X509Certificates.X509Chain]::new()
$certChain.Build($cert)
$certificateIssuerThumbprint = ($certChain.ChainElements.Certificate | Where-Object {$_.Subject -eq $cert.Issuer}).Thumbprint
I'm far from an expert on certificates, but here's what I think needs to be done:
In certificate manager, if you simply double click and open the certificate > Certification Path tab, you should see your certificate at the bottom (as a leaf node), and in the Details tab you will see your certificate's thumbprint
There should be a certificate above your certificate - I believe this is the issuer certificate. If you double click that issuer certificate > Details, I think that's the thumbprint you need
#mperian's answer is absolutely spot-on if the certificate lives in an Azure Key Vault.
In my case, the certificates are installed to the stores on the various machines. Building on their excellent answer, here's the Powershell to do the same locally without use of Azure Key Vault.
$thumbprint = ""
$store = "My"
$cert = Get-ChildItem -Path "Cert:\LocalMachine\$store" | Where-Object {$_.Thumbprint -match $thumbprint}
$certChain = [System.Security.Cryptography.X509Certificates.X509Chain]::new()
$certChain.Build($cert)
$certIssuerThumbprint = ($certChain.ChainElements.Certificate | Where-Object {$_.Subject -eq $cert.Issuer}).Thumbprint
You should be able to see that value after you upload it to Keyvault using the script in the link you provided
https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-create-cluster-using-cert-cn#upload-the-certificate-to-a-key-vault
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser -Force
$SubscriptionId = "<subscription ID>"
# Sign in to your Azure account and select your subscription
Login-AzAccount -SubscriptionId $SubscriptionId
$region = "southcentralus"
$KeyVaultResourceGroupName = "mykeyvaultgroup"
$VaultName = "mykeyvault"
$certFilename = "C:\users\sfuser\myclustercert.pfx"
$certname = "myclustercert"
$Password = "P#ssw0rd!123"
# Create new Resource Group
New-AzResourceGroup -Name $KeyVaultResourceGroupName -Location $region
# Create the new key vault
$newKeyVault = New-AzKeyVault -VaultName $VaultName -ResourceGroupName $KeyVaultResourceGroupName -Location $region -EnabledForDeployment
$resourceId = $newKeyVault.ResourceId
# Add the certificate to the key vault.
$PasswordSec = ConvertTo-SecureString -String $Password -AsPlainText -Force
$KVSecret = Import-AzureKeyVaultCertificate -VaultName $vaultName -Name $certName -FilePath $certFilename -Password $PasswordSec
$CertificateThumbprint = $KVSecret.Thumbprint
$CertificateURL = $KVSecret.SecretId
$SourceVault = $resourceId
$CommName = $KVSecret.Certificate.SubjectName.Name
Write-Host "CertificateThumbprint :" $CertificateThumbprint
Write-Host "CertificateURL :" $CertificateURL
Write-Host "SourceVault :" $SourceVault
Write-Host "Common Name :" $CommName
From Create an SF cluster using certificates declared by CN:
"Note
The 'certificateIssuerThumbprint' field allows specifying the expected issuers of certificates with a given subject common name. This field accepts a comma-separated enumeration of SHA1 thumbprints. Note this is a strengthening of the certificate validation - in the case when the issuer is not specified or empty, the certificate will be accepted for authentication if its chain can be built, and ends up in a root trusted by the validator. If the issuer is specified, the certificate will be accepted if the thumbprint of its direct issuer matches any of the values specified in this field - irrespective of whether the root is trusted or not. Please note that a PKI may use different certification authorities to issue certificates for the same subject, and so it is important to specify all expected issuer thumbprints for a given subject.
Specifying the issuer is considered a best practice; while omitting it will continue to work - for certificates chaining up to a trusted root - this behavior has limitations and may be phased out in the near future. Also note that clusters deployed in Azure, and secured with X509 certificates issued by a private PKI and declared by subject may not be able to be validated by the Azure Service Fabric service (for cluster-to-service communication), if the PKI's Certificate Policy is not discoverable, available and accessible."
Note that upon renewing (or re-keying) a certificate, the issuer may well change. A PKI would typically publish all its active issuers in a Certification Practice Statement (CPS) (here is LetsEncrypt's - unfortunately it doesn't seem to list the issuer certificates.)
If you're internal to Microsoft, you would probably know which API to use to retrieve authorized issuers; if you aren't, please contact the PKI of your choice for guidance.

How do you manually renew a certificate in AzureKeyValut

We have a CA that is not supported by Azure KeyVault. We have created certificates and CSRs using KeyVault and submitted them successfully to the CA and imported the signed cert. We now have some certs that pre-date our use of KeyVault that are up for renewal. Our security team has had new signed certs issued by the CA. But when we import the original signed cert and private key (pfx format) and then try to import the new signed cert it fails with "Pending Certificate not found". What's to proper sequence of bring these certs into KeyVault.
An Azure Key Vault certificate is a versioned object. When you create a new certificate, you are creating a new version. Each version of the certificate is conceptually composed of 2 parts - an asymmetric key, and a blob which ties that asymmetric key to an identity.
When you need to use your own CA, AKV generates an asymmetric key and returns the CSR to the user. The user then uses the CSR to obtain a certificate. This is true for every version of the certificate.
If you current version is expiring, you need to create a new version. You need to follow the same steps as you did when creating the first version. You can optionally choose to use the same asymmetric key when creating a new version.
So going off the comment above I was able to get this to work.
#Password for the pfx file of the original cert
$password = ConvertTo-SecureString -String '<UPDATETHIS>' -AsPlainText -Force
#import the orginal cert with private key
Import-AzureKeyVaultCertificate -VaultName 'VaultName' -Name 'Certname' -FilePath 'PATHTOPFXFILE' -Password $password
#set the policy to allow key reuse if the CA will create a new signed cert from the existing CSR
Set-AzureKeyVaultCertificatePolicy -VaultName 'VaultName' -Name 'Certname' -ReuseKeyOnRenewal $true
#create a cert policy object from the existing cert
$certpolicy = Get-AzureKeyVaultCertificatePolicy -VaultName 'VaultName' -Name 'Certname'
#create a pending cert operation, you can pull a new CSR from this if need be
$certificateOperation = Add-AzureKeyVaultCertificate -VaultName 'VaultName' -Name 'Certname' -CertificatePolicy $certpolicy
#import the new signed cert into KeyVault for issuing
Import-AzureKeyVaultCertificate -VaultName 'VaultName' -Name 'Certname' -FilePath 'PATHTONEWSIGNEDCERTINCRT'

How do I use my self signed certificate in another computer?

I created a self signed certificate in Windows 10 using New-SelfSignedCertificate function as below:
New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My -Subject "CN=VBA Code Signing" -KeyAlgorithm RSA -KeyLength 2048 -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -KeyExportPolicy Exportable -KeyUsage DigitalSignature -Type CodeSigningCert
I exported the certificate including the private key and installed in another machine. However, the macro is still being blocked in the second machine. The macro settings is "Disable all macros except digitally signed macros"
Does anybody know why is this happening?
Thanks

How do I import a public certificate to Windows Azure?

I am going to communicate from Windows Azure to another public web service through SSL. And the certificate on public web service is self-signed. Therefore I need to trust the public certificate on my Windows Azure.
How can I import the certificate (.cer) to Windows Azure? The management portal only allow import a certificate with private key.
This is actually an issue with the portal, not with azure itself. Go to the "Add Certificate" section in the portal, click the browse button, navigate to where your .cer file is. The files listed are filtered to .pfx files so you won't see the file you want to import, but, if you type in the name of the file it will work.
This was an issue with the portal. I had thought it was fixed - apparently not. You can always convert the .cer to a .pfx as well (with a lame password). I run this from LINQPad:
void Main()
{
string file = #"C:\temp\deploy\dunnrydeploy.cer";
var cert = X509Certificate2.CreateFromCertFile(file);
var bytes = ((X509Certificate2)cert).Export(X509ContentType.Pfx, "p");
var fs = File.Create(#"C:\temp\deploy\foo.pfx");
using (fs)
{
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
}
}
There are few blogs about how to do thsi - http://blogs.msdn.com/b/jnak/archive/2010/01/29/installing-certificates-in-windows-azure-vms.aspx
This uses manual XML entry for self signed certificates in the Role
<Certificate name="SelfSigned" storeLocation="CurrentUser" storeName="<enter a value>" />
Here is how I obtained a public certificate from a private key and uploaded into Azure.
1) Obtain the certificate using PowerShell:
PS C:\MyWebsite> $cert = New-SelfSignedCertificate -DnsName mycompany.com -CertStoreLocation "cert:\LocalMachine\My" -KeyLength 2048 -KeySpec "KeyExchange"
PS C:\MyWebsite> $password = ConvertTo-SecureString -String "mypassword" -Force -AsPlainText
PS C:\MyWebsite> Export-PfxCertificate -Cert $cert -FilePath ".\mycompany.pfx" -Password $password
2) Then upload the certificate in the portal:
For details please see https://learn.microsoft.com/en-us/azure/cloud-services/cloud-services-certs-create

Resources