Certificate Authentication to a Point to Site Vpn with Azure key vault - powershell

I Want to Create a Point-To-Site vpn from a Virtual netwerk in azure.
For the authentication I want to use certificates, the root certificate is generated in azure key vault. I don't want to authenticate with the rootCertificate.pfx but with the clientCertificate.pfx.
The requirements are
that I don't use an external certificate provider.
I use as much powershell as possible
We followed this Documentation to Create a self-signed certificate in key vault.
https://blogs.technet.microsoft.com/kv/2016/09/26/get-started-with-azure-key-vault-certificates/
After I Created a Root Certificate, it is placed within the key vault. (public part in secrets, private part in keys)
Next We copy/paste the public part(Base64) in the Virtual Network Gateway -> point-to-site Configuration -> Root Certificates
Then I used this powershell script to generate a clientCertificate from the rootCertificate that we made earlier. We export it to our Local Hard Drive.
Login-AzureRmAccount
$kvSecret = Get-AzureKeyVaultSecret -VaultName "akv-contoso-test" -Name "ContosoFirstCertificate"
$kvSecretBytes = [System.Convert]::FromBase64String($kvSecret.SecretValueText)
$rootCertificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList #($kvSecretBytes, $null, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$certStore = New-Object System.Security.Cryptography.X509Certificates.X509Store
$certStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$certStore.Add($rootCertificate)
$clientCertificate = New-SelfSignedCertificate -Type Custom -KeySpec Signature -Subject "CN=Point To Site VPN Client" -KeyExportPolicy Exportable -HashAlgorithm sha256 -KeyLength 2048 -Signer $rootCertificate -TextExtension #("2.5.29.37={text}1.3.6.1.5.5.7.3.2")
$securePassword = ConvertTo-SecureString -String "mysecret" -AsPlainText -Force
Export-PfxCertificate -Cert $clientCertificate -Password $securePassword -FilePath "C:\Users\User\Desktop\Certificates\Point To Site VPN Client.pfx" -ChainOption BuildChain
$certStore.Close()
After that we install the "Point To Site VPN Client.pfx"
The public root certificate is installed in the Trusted Root Certification Authorities. In the chain of trust of my client certificate, the Root Certificate says the following "This certificate is not valid for the selected purpose".
Now I want to connect to the vpn with the Client Certificate.
He tells that the message received was unexpected or badly formatted.
My guess is that there is a problem when we want to generate the Client Certificate out of the keyvault (script above).
Chain of trust and Connection Error

Related

How can I renew Self Signed Code Signing Certificates for Powershell Scripts?

with the following code I generated a new Self Signed Code Signing Certificate for Powershell Scripts in my CA (Not Enterprise PKI!) and deployed it via a GPO (within the PS Skript and the Root Code Signing Certificate):
# Create a certificate to use for signing powershell scripts
$selfsigncert = New-SelfSignedCertificate `
-Subject "CN=PowerShell Code Signing" `
-KeyAlgorithm RSA `
-KeyLength 2048 `
-Type CodeSigningCert `
-CertStoreLocation Cert:\LocalMachine\My\
# Move the root cert into Trusted Root CAs
Move-Item "Cert:\LocalMachine\My\$($selfsigncert.Thumbprint)" Cert:\LocalMachine\Root
# Obtain a reference to the code signing cert in Trusted Root
$selfsignrootcert = "Cert:\LocalMachine\Root\$($selfsigncert.Thumbprint)"
Get-ChildItem cert:\LocalMachine\Root -CodeSigningCert
#Sign the PowerShell Script
Set-AuthenticodeSignature xxx.ps1 #(Get-ChildItem cert:\LocalMachine\Root -codesigning)[0] -IncludeChain "All"
# Verify if signature is valid
Get-AuthenticodeSignature .\xx.ps1 -Verbose | fl
# Edit Displayname of Certificate to uniquely identify the cert
(Get-ChildItem -Path Cert:\LocalMachine\Root\(ThumbprintNumer)).FriendlyName = "XXXX"
Now this works properly, my powershell scripts are getting signed and I can deploy it on my domain with GPO. The only bad thing is the expiration date. When I create the cert like the way I explained here, it is invalid after 1 year. Is it possible, that I can edit the expiration date when I create the cert or renew it manually?
I hope somebody has an answer for me :)
Greetings
TheLizadator

Export certificate as pfx

I'm trying to export my certifcate as pfx. I'm doing that my certmgr.msc but some of the options are gray.
certmgr
So I wanted to use Powershell for this.
I'm going to the catalogue where the certificate is located (cert:\CurrentUser\My) and I'm inducing a syntax:
Export-PfxCertificate -Cert .\4BBB***************************** -FilePath 'C:\Users\jwozniak\Documents\outfile.pfx' -Password (ConvertTo-SecureString -String 'password63' -AsPlainText -Force)
(without * of course)
And I get an below error:
I'd appreciate some guidance.
When a certificate is created, You need to make private key has "Exportable".
Then only Export-PfxCertificate command works fine without errors.
Some of examples which may help you :
1)For creating self signed certificate by marking private key has Exportable
$cert = New-SelfSignedCertificate -DnsName $certname -certStorelocation cert:\localmachine\my -KeyLength 2048 -KeyFriendlyName $certname -FriendlyName $friendlyName -HashAlgorithm sha256 -Keyexportpolicy Exportable
Here parameter -Keyexportpolicy plays an important role for serving the purpose.
2)For Your question how to import certificate with option exportable private key ?
Follow the below command
Import-PfxCertificate -FilePath C:\Temp\$certname.pfx -CertStoreLocation Cert:\LocalMachine\Root -Password $certpwd1 -Exportable
Here parameter -Exportable plays an important role for serving the purpose
A certificate (on windows) has export policies. You cannot get around that except using for instance https://github.com/gentilkiwi/mimikatz

How can I create a self signed certificate?

I create a self signed certificate with powershell in my server.
New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My"
I go on mmc :
File -> Add or Remove Snap-ins -> Certificates -> Add -> Computer account -> Local computer
I expand the Personal folder and you see my localhost certificate
I copy and paste it into Trusted Root Certification Authorities - Certificates
After that I bind my application on IIS :
But I still have the error :
How can I resolve my issue ? Or maybe there an other free solution.
The following commands in PowerShell (run as admin) will do the trick:
1.- We create a new root trusted cert:
$rootCert = New-SelfSignedCertificate -Subject 'CN=TestRootCA,O=TestRootCA,OU=TestRootCA' -KeyExportPolicy Exportable -KeyUsage CertSign,CRLSign,DigitalSignature -KeyLength 2048 -KeyUsageProperty All -KeyAlgorithm 'RSA' -HashAlgorithm 'SHA256' -Provider 'Microsoft Enhanced RSA and AES Cryptographic Provider'
2.- We create the cert from the root trusted cert chain:
New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My" -Signer $rootCert -TextExtension #("2.5.29.37={text}1.3.6.1.5.5.7.3.1") -Provider "Microsoft Strong Cryptographic Provider" -HashAlgorithm "SHA256"
3.- We copy the thumbprint returned by the last command
4.- (If neccesary) We remove the last association ip/port/cert:
netsh http delete sslcert ipport=0.0.0.0:3002
5.- We associate the new certificate with any ip and your port, 3002 in your case (the appid value is any valid guid):
netsh http add sslcert ipport=0.0.0.0:3002 appid='{214124cd-d05b-4309-9af9-9caa44b2b74a}' certhash=here_the_copied_thumbprint
6.- Now, you must drag and drop the TestRootCA from Personal/Certificates folder to Trusted Root Certification Authorities/Certificates.
These commands also resolve the error ERR_CERT_WEAK_SIGNATURE_ALGORITHM returned later by Google Chrome because the certificate is created with SHA256 instead of SHA1
You should copy the certificate to both Personal and Trusted Root Authorities. To set up a self signed with Powershell for IIS the functions below should help you out.
Run the script as administrator - if you are on Windows 10 chances are that you must install module WebAdministration.
#Install-Module -Name 'WebAdministration'
Import-Module -Name WebAdministration
function AddSelfSignedCertificateToSSL([String]$dnsname, [String]$siteName='Default Web Site'){
$newCert = New-SelfSignedCertificate -DnsName $dnsname -CertStoreLocation Cert:\LocalMachine\My
$binding = Get-WebBinding -Name $siteName -Protocol "https"
$binding.AddSslCertificate($newCert.GetCertHashString(), "My")
$newCertThumbprint = $newCert.Thumbprint
$sourceCertificate = $('cert:\localmachine\my\' + $newCertThumbprint)
$store = new-object system.security.cryptography.X509Certificates.X509Store -argumentlist "Root", LocalMachine
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
$store.Add($newCert)
return $newCertThumbprint
}
Write-Host Installing self-signed certificate Cert:\LocalMachine\My and Cert:\LocalMachine\Root ..
$certinstalledThumbprint = AddSelfSignedCertificateToSSL 'someacmeapp.somedomain.net'
Write-Host Added certificate $certinstalledThumbprint to Cert:\LocalMachine\My and Cert:\LocalMachine\Root and set this up as the SSL certificate on Default Web Site.
Note that modern browsers such as Chrome will complain about weak algorithms used in self signed algorithm and the fact that there is no third-party certificate authority such as GoDaddy et cetera that can confirm the validity certificate since it is self signed and has a weak algorithm.

Signing a PowerShell script with self-signed certificates (and without makecert.exe)

I'm trying to sign a .ps1 using self-signed certificates (the use case is for scripts I write myself on my private dev station, so no need to use - or pay for -
a real CA). However, no matter how many guides on the topic of certificates generation and digital signatures I read, I can't seem to get it working.
Here's what I have accomplished so far:
# Create a certificate to use as trusted root of the signing chain
$root = New-SelfSignedCertificate `
-Subject "CN=PowerShell Trusted Authority" `
-FriendlyName "PowerShell Trusted Authority" `
-KeyUsageProperty Sign `
-KeyUsage CertSign, CRLSign, DigitalSignature `
-CertStoreLocation Cert:\LocalMachine\My\ `
-NotAfter (Get-Date).AddYears(10)
# Create a certificate to use for signing powershell scripts
New-SelfSignedCertificate `
-Signer $root `
-Subject "CN=PowerShell Code Signing" `
-KeyAlgorithm RSA `
-KeyLength 2048 `
-Type CodeSigningCert `
-CertStoreLocation Cert:\LocalMachine\My\
# Move the root cert into Trusted Root CAs
Move-Item "Cert:\LocalMachine\My\$($root.Thumbprint)" Cert:\LocalMachine\Root
All of the above done from an administrative powershell instance. After that is done, I can see both certificates, in the expected locations, in the management console, and the certificate path of the signing cert checks out as valid.
I then open a regular PS prompt and attempt to sign the script:
# Obtain a reference to the signing certificate
PS> $cert = Get-ChildItem Cert:\LocalMachine\My\ -CodeSigningCert
# Attempt at signing
PS> Set-AuthenticodeSignature .\Microsoft.PowerShell_profile.ps1 $cert
Directory: C:\Users\tomas\Documents\WindowsPowerShell
SignerCertificate Status Path
----------------- ------ ----
UnknownError Microsoft.PowerShell_profile.ps1
As you can see, the actual signing fails. Looking at the powershell file, I see that no signature has been appended to the script.
If I do the signing from an admin prompt, I seem to get a little further; a signature block is added to the script, and the thumbprint of the signing cert is printed in the output from Set-AuthenticodeSignature, but the status is still UnknownError and execution under the AllSigned policy is still not allowed.
# Output some info about the certificate:
PS> $cert | Format-List
Subject : CN=PowerShell Code Signing
Issuer : CN=PowerShell Trusted Authority
Thumbprint : <omitted>
FriendlyName :
NotBefore : 9/20/2017 10:48:59 PM
NotAfter : 9/20/2018 11:08:59 PM
Extensions : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid,
System.Security.Cryptography.Oid, System.Security.Cryptography.Oid}
I've tried a multitude of variants of New-SelfSignedCertificate incantations, especially to generate the certificate for code signing, but always with the same status message (UnknownError).
My ultimate goal here is to be able to have Set-ExecutionPolicy AllSigned and still run scripts that I've created myself. What am I missing in this process to make that work?
Thinking about this, you don't need a certificate chain trust, therefore, you don't need your first certificate. You can use the second certificate and move it into your Trusted Root folder and it will work. Using the first certificate and then creating another certificate seems to fail because the 'root' is self signed and then can't sign another certificate.
SELF SIGNED CERTIFICATE method
# Create a certificate to use for signing powershell scripts
$selfsigncert = New-SelfSignedCertificate `
-Subject "CN=PowerShell Code Signing" `
-KeyAlgorithm RSA `
-KeyLength 2048 `
-Type CodeSigningCert `
-CertStoreLocation Cert:\LocalMachine\My\
# Move the root cert into Trusted Root CAs
Move-Item "Cert:\LocalMachine\My\$($selfsigncert.Thumbprint)" Cert:\LocalMachine\Root
# Obtain a reference to the code signing cert in Trusted Root
$selfsignrootcert = "Cert:\LocalMachine\Root\$($selfsigncert.Thumbprint)"
# Sign script
Set-AuthenticodeSignature C:\powershell.ps1 $selfsignrootcert
If you have access to an Enterprise Root CA, you can use the method you have used in your question.
ENTERPRISE ROOT CA method (same method as you have in your question) - you need to know your Root CA certificate thumbprint
# Get Enterprise Root CA thumbprint
$rootcert = get-childitem Cert:\LocalMachine\Root\XXXXXXXXXXXX
# Generate certificate
$fromrootcert = New-SelfSignedCertificate `
-Signer $rootcert `
-Subject "CN=PowerShell Code Signing" `
-KeyAlgorithm RSA `
-KeyLength 2048 `
-Type CodeSigningCert `
-CertStoreLocation Cert:\LocalMachine\My\
# Sign script
Set-AuthenticodeSignature C:\powershell.ps1 $fromrootcert
$cert = New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My -Type CodeSigningCert -Subject "Code Signing"
Move-Item -Path $cert.PSPath -Destination "Cert:\CurrentUser\Root"
Set-AuthenticodeSignature -FilePath c:\go.ps1 -Certificate $cert
source
https://blogs.u2u.be/u2u/post/creating-a-self-signed-code-signing-certificate-from-powershell

No certificate error on Login-AzureRmAccount -ServicePrincipal

I have automated few steps utilizing ARM template for Java/Tomcat deployment but I am not getting success in automated login via certificate.
I have created a self-signed certificate using OpenSSL for a fictitious domain “project.company.com”. After following this article to setup an Application in AD and a service principal with contributor role,
https://azure.microsoft.com/en-us/documentation/articles/resource-group-authenticate-service-principal/#provide-certificate-through-automated-powershell-script
I am getting error
“Login-AzureRmAccount : No certificate was found in the certificate store with thumbprint xxxxxxxxxxxxxxxxxxx” for following.
Looks like I am missing something at Azure subscription level. These exact steps work fine for Azure CLI from a Linux box but they don’t work for Azure PowerShell from Windows box.
$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList #("<my-path>/project.company.pfx", "<my-password>")
#$applicationId="xxxxxxxxxxxxxxxxxxxxx"
#$tenantId="dddddddddddddddddddddd"
#$subscriptionId="yyyyyyyyyyyyyyyyyyy"
#Login-AzureRmAccount -CertificateThumbprint $cert.Thumbprint -ApplicationId $applicationId -ServicePrincipal -TenantId $tenantId
$azureAdApplication = Get-AzureRmADApplication -IdentifierUri "https://project.company.com"
$subscription = Get-AzureRmSubscription
Login-AzureRmAccount -CertificateThumbprint $cert.Thumbprint -ApplicationId $azureAdApplication.ApplicationId -ServicePrincipal -TenantId $subscription.TenantId
In order for the Azure cmdlets to detect the correct certificate you need to install the public cert (the .cer file) into the Trusted Root Certificate Authorities store.
While it will work to install a cert into the trusted root cert authorities, this is not advisable as it impacts what other applications on your machine will trust. Instead, install the certficate in the LocalMachine\My store or the CurrentUser\My store.