Start-OBRegistration Vault credentials validation failed - azure

I'm trying to register Windows client machine to a Azure Recovery Services Vault with a powershell script.
I'm having this error:
WARNING: Vault credentials validation failed.
Start-OBRegistration : Vault credentials file provided has expired. We recommend you download a new vault credentials file from the portal and use it within 2 days.
These are my commands:
$cert = New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname aly20-srv.xxx.onmicrosoft.com -NotAfter (Get-Date).AddHours(8)
$certificate =[System.Convert]::ToBase64String($cert.RawData)
$Vault1 = Get-AzRecoveryServicesVault –Name "rsvault-staging"
$CredsPath = "C:\temp"
$CredsFilename = Get-AzRecoveryServicesVaultSettingsFile -Backup -Vault $Vault1 -Path $CredsPath -Certificate $certificate
Import-Module -Name 'C:\Program Files\Microsoft Azure Recovery Services Agent\bin\Modules\MSOnlineBackup'
Start-OBRegistration -VaultCredentials $CredsFilename.FilePath -Confirm:$false
It seems that the vault credentials file created in "C:\temp" is not valid.
If I try to get it directly from azure portal and run "Start-OBRegistration" command it works.
What's the problem? How can I solve?
Thank you.

It looks like you are using "-NotAfter (Get-Date).AddHours(8)"
This will make your certificate expire after 8 hours, the default is 1 year.

Related

Connect-MgGraph in Azure Automation

I am currently busy to convert my Azure AD PowerShell scripts to Microsoft Graph PowerShell. I have already some scripts that I want to run within Azure Automation, but I try to figure out how to connect to Azure Automation.
With Azure AD PowerShell, I have a connected service account in Azure Automation. With Microsoft Graph PowerShell I'm trying to use a RunAs account within the Azure Automation Account with the following connection:
$Connection = Get-AutomationConnection -Name AzureRunAsConnection
# Get certificate from the automation account
$Certificate = Get-AutomationCertificate -Name AzureRunAsCertificate
# Connect to the Graph SDK endpoint using the automation account
Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connection.TenantId -CertificateThumbprint $Connection.CertificateThumbprint
When I run the RunBook to create the connection I get an error:
Connect-MgGraph: C:\Temp\os4k24vd.4cs\xxxxxxxxxxxxxxxxxxx.ps1:5
Line | 5 | Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connec …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0,
| Culture=neutral, PublicKeyToken=xxxxxxx'. The system cannot | find the file specified.
I have the following module installed that is needed for Connect-MgGraph Microsoft.Graph.Authentication >> Runtime: 7.1 When I search on the error, it have something to do that .NET could not find the Json.NET library. But which module I'm missing in Azure Automation, or are there other ways to connect Microsoft Graph PowerShell with Azure Automation?
I hope you are using App only Access approach to connect the Azure Automation. if not refer MSDOC - App only Authentication
To get the Certificate and AppID you can use the below command let
#To get App Id
$AppId = Get-AutomationVariable -Name '<Your AppID>'
# Get TenentId
$TenantId = Get-AutomationVariable -Name '< your tenantId>'
# Get Certificate
$CertificateName = Get-AutomationCertificate -Name '<Your Certificate>'
#Connect the mgGraph
Connect-MgGraph -ClientID $AppId -TenantId $TenantId -CertificateName $CertificateName ## Or -CertificateThumbprint
Still, you are facing issue please give a try Automation Hybrid Runbook Worker for more flexibility.
The problem was not the first connect script, but the runtime version. After changing to PS 5.1 instead of 7.1 it all works. The Runbook now shows 'Welcome to Welcome To Microsoft Graph!'
$Connection = Get-AutomationConnection -Name AzureRunAsConnection
# Connect to the Graph SDK endpoint using the automation account
Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connection.TenantId -CertificateThumbprint $Connection.CertificateThumbprint

Connect-Exchange CertificatePath in Azure Function

I'm trying to understand how to add the parameter -CertificateFilePath in a Powershell Azure Function. Locally you just add the location of the path *c:\locationpath*.
But when used in a Azure Function, I'm not sure how to add the file path from a Function App that has the cert already in TLS/SSL settings where I've uploaded the certificate.
A common way I've seen to do is:
Connect-ExchangeOnline -AppID $AppId -CertificateThumbprint $Thumbprint -Organization company.com
But that usually has a pop up that ask for an account to select which is why it might be failing in the Function. Also I'm trying to use a certificate.
Another way I've seen is using the AZ Vault, which I didn't want to use if my certificates are already in an app registration and in the Function itself in TLS/SSL Settings.
I just want to be able to query Exchange without user credentials with a service I've created. Thank you.
As venkateshdodda-mt Suggested try the below steps
1 Generate Certificate and Service Principal
By credential
By CertificateThumbprint & ApplicationId
By AadAccessToken & AccountId
# Login to Azure AD PowerShell With Admin Account
Connect-AzureAD
# Create the self signed cert
$currentDate = Get-Date
$endDate = $currentDate.AddYears(1)
$notAfter = $endDate.AddYears(1)
$pwd = "YOUR_PASSWORD"
$thumb = (New-SelfSignedCertificate -CertStoreLocation cert:\localmachine\my -DnsName YOUR_DNS -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $notAfter).Thumbprint
$pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
Export-PfxCertificate -cert "cert:\localmachine\my\$thumb" -FilePath YOUR_PFX_PATH.pfx -Password $pwd
# Load the certificate
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("YOUR_PFX_PATH.pfx", $pwd)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
# Create the Azure Active Directory Application
$application = New-AzureADApplication -DisplayName "YOUR_APP_NAME" -IdentifierUris "https://YOUR_APP_NAME"
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "YOUR_PASSWORD" -StartDate $currentDate -EndDate $endDate -Type AsymmetricX509Cert -Usage Verify -Value $keyValue
# Create the Service Principal and connect it to the Application
$sp = New-AzureADServicePrincipal -AppId $application.AppId
# Give the Service Principal Reader access to the current tenant (Get-AzureADDirectoryRole)
Add-AzureADDirectoryRoleMember -ObjectId 72f988bf-86f1-41af-91ab-2d7cd011db47 -RefObjectId $sp.ObjectId
# Get Tenant Detail
$tenant = Get-AzureADTenantDetail
# Now you can login to Azure PowerShell with your Service Principal and Certificate
Connect-AzureAD -TenantId $tenant.ObjectId -ApplicationId $sp.AppId -CertificateThumbprint $thumb
# Output TenantId, AppId and Thumbprint to use in azure function's script
Write-Host "TenantId: "$tenant.ObjectId
Write-Host "AppId: "$sp.AppId
Write-Host "Thumbprint: "$thumb
2 Configure Azure Function to Use Certificate
3 Copy AzureAD PowerShell Module to Azure Function
4 Write PowerShell Script from Azure Function to Connect to Azure AD
for further information check Azure functions check with powershell

VpnClientSetupAMD64.exe missing in Azure point-to-site VPN download

I am trying to setup my first Azure point-to-site VPN. If I'm reading things correctly, the URL I get from this PowerShell code:
$profile = New-AzVpnClientConfiguration -ResourceGroupName $ResourceGroup -Name $GWName -AuthenticationMethod "EapTls"
$profile.VPNProfileSASUrl
should download an executable called VpnClientSetupAMD64.exe that will be in the WindowsAmd64 folder of the downloaded zip file. That executable should do the setup on the native Win 10 1909 client.
The zip file I get doesn't have any executable in it and doesn't have that directory in it. I only get the XML and OVPN files with the config data for the VPN client.
I also tried using the Download VPN Client selection in the GUI Azure portal on the VnetGW/point-to-site page and I get the identical zip file - still no setup exe.
I looked for a way to either directly download the VpnClientSetupAMD64.exe file or to specify the azurevpnconfig.xml file that I do get as a parameter to setup the VPN client but I see nothing applicable.
I understand that I can manually configure the VPN client using the info I have but that doesn't scale.
Can someone give me any pointers?
I had the same issue trying to setup Azure P2S VPN today, the downloaded VPN client is just a configuration file.
Did a bit research and found the solution: https://learn.microsoft.com/en-us/azure/vpn-gateway/openvpn-azure-ad-client
Open Windows store, and install a app "Azure VPN Client". Then you can run Azure VPN Client and import the configuration file.
Be default, the Tunnel type is OpenVPN(SSL) in the Point-to-site configuration UI. Before you generate files using PowerShell, you should select the VpnClientProtocol to SSTP and IKEv2, or one of them because they are used for Windows clients. So you will get the VpnClientSetupAMD64.exe file. You could get more details here.
You also could refer to create a VPN Gateway and add point-to-site configuration using PowerShell.
New-AzVirtualNetworkGateway -Name VNet1GW -ResourceGroupName TestRG1 `
-Location 'East US' -IpConfigurations $gwipconfig -GatewayType Vpn `
-VpnType RouteBased -GatewaySku VpnGw1 -VpnClientProtocol "IKEv2"
# Add the VPN client address pool
$Gateway = Get-AzVirtualNetworkGateway -ResourceGroupName $RG -Name $GWName
Set-AzVirtualNetworkGateway -VirtualNetworkGateway $Gateway -VpnClientAddressPool $VPNClientAddressPool
# Create a self-signed root certificate
$cert = New-SelfSignedCertificate -Type Custom -KeySpec Signature `
-Subject "CN=P2SRootCert" -KeyExportPolicy Exportable `
-HashAlgorithm sha256 -KeyLength 2048 `
-CertStoreLocation "Cert:\CurrentUser\My" -KeyUsageProperty Sign -KeyUsage CertSign
# Export the root certificate to "C:\cert\P2SRootCert.cer"
# Upload the root certificate public key information
$P2SRootCertName = "P2SRootCert.cer"
$filePathForCert = "C:\cert\P2SRootCert.cer"
$cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2($filePathForCert)
$CertBase64 = [system.convert]::ToBase64String($cert.RawData)
$p2srootcert = New-AzVpnClientRootCertificate -Name $P2SRootCertName -PublicCertData $CertBase64
Add-AzVpnClientRootCertificate -VpnClientRootCertificateName $P2SRootCertName `
-VirtualNetworkGatewayname "VNet1GW" `
-ResourceGroupName "TestRG1" -PublicCertData $CertBase64

Azure Portal Application in AD says certificate is expired even after I have updated it

My AD application certificate expired and I have put a new one in and deleted all the old expired ones, however when I go to the application it still shows it as expired
You could follow the steps below to create a new certificate credential for your AD App.
1.Run the PowerShell command in local, change the -FilePath to what you want.
$cert=New-SelfSignedCertificate -Subject "CN=TodoListDaemonWithCert" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature
Export-Certificate -Cert $cert -FilePath C:\Users\joyw\Desktop\user1234.cer
2.Navigate to the Azure Active Directory in the portal -> your AD App -> Certificates & secrets -> Upload certificate.
Or if you don't want to upload the certificate manually, you could use the powrshell script as below, after running the script, refresh the portal, you will find it works fine. Make sure you install the Az module.
Connect-AzAccount
$cert=New-SelfSignedCertificate -Subject "CN=TodoListDaemonWithCert" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature
$binCert = $cert.GetRawCertData()
$credValue = [System.Convert]::ToBase64String($binCert)
New-AzADAppCredential -ApplicationId <application-id of the AD App> -CertValue $credValue -StartDate $cert.NotBefore -EndDate $cert.NotAfter

Import-AzKeyVaultCertificate cmdlet results in: Key not valid for user in specified state

I'm trying to import a .pfx certificate to an Azure keyvault but am having some issues.
Import-AzKeyVaultCertificate -VaultName "SecHash03" -Name "CodeSigning" -FilePath "\path\to\my\cert.pfx"
Results in:
Import-AzKeyVaultCertificate : Key not valid for use in specified state.
At line:1 char:1
+ Import-AzKeyVaultCertificate -VaultName SecHash03 -Name " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Import-AzKeyVaultCertificate], CryptographicException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.ImportAzureKeyVaultCertificate
I'm requesting this cert from an Enterprise CA using certreq from a machine in the same domain as the CA. There is no password required to import the cert. Plan was to then upload that cert to the aforementioned Azure keyvault.
I tried using the Azure portal to import this cert and that works fine; import and usage both works well. So this is not an issue with Roles as suggested in another similar Stackoverflow answer (Importing certificate to Azure Key Vault: Key not valid for use in specified state).
Please advice!
As far as I know, when you import a pre-existing .pfx file cert to Azure key vault, you need to provide a password which is used for protecting the cert as you need to export the cert within the Private Key and include all certificates in the certificate path if possible. For example,
# Export the cert to a PFX with password
$password = ConvertTo-SecureString "Password!" -AsPlainText -Force
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath C:\temp\cert2.pfx -Password $password
# Upload to Key Vault
Import-AzureKeyVaultCertificate -VaultName noel-temp -Name cert2 -FilePath C:\temp\cert2.pfx -Password $password
Alternatively,
If you use a supported CA, you can even configure Key Vault to enroll
for certificates on your behalf. No leaking of keys! For simplicity,
the policy in these examples will be set to generate self-signed certs
from Key Vault.
# Have Key Vault create the certificate with a simple policy
$policy = New-AzureKeyVaultCertificatePolicy -SubjectName "CN=mycluster.southcentralus.cloudapp.azure.com" -IssuerName Self -ValidityInMonths 12
Add-AzureKeyVaultCertificate -VaultName noel-temp -Name cert1 -CertificatePolicy $policy
# Download the secret (private key information) associated with the cert
$secret = Get-AzureKeyVaultSecret -VaultName noel-temp -Name cert1
$secretBytes = [System.Convert]::FromBase64String($secret.SecretValueText)
[System.IO.File]::WriteAllBytes("C:\temp\cert1.pfx", $secretBytes)
# Import the certificate to CurrentUser\My
Import-PfxCertificate -FilePath C:\temp\cert1.pfx -CertStoreLocation cert:\CurrentUser\My -Exportable
You could get more details from these two links:
Importing Certificates to Key Vault
Manage certificates via Azure Key Vault

Resources