Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.25k stars 3.85k forks source link

Import-AzKeyVaultCertificate yields Cannot find the requested object #18494

Closed cveld closed 2 years ago

cveld commented 2 years ago

Description

When running the cmdlet Import-AzKeyVaultCertificate it yields the error Cannot find the requested object.

import-azkeyvaultcertificate -VaultName myvault -name examplecert -FilePath C:\temp\cert\examplecert.pem

I expect the certificate to be imported.

Interestingly when running the az cli counterpart, this runs fine:

az keyvault certificate import --vault-name myvault -n examplecert -f C:\temp\cert\examplecert.pem

Contents of examplecert.pem:

-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCeUmity0so5Kyv
mXtVkeg0IXclvN2StX7IJEx8OJmGmNCRV4gi89i/0RCWtYaEsX/XbYwzel0mqgor
LezaOVs77N6pupyOA+I02ZBYTkpIvDcbzDr/JreEzo/4pEzkGxV4VQD3lfwHsX2K
P1dLPB0E8ZFYZnmHJdKQbyWLJijQt2razCp5h5x0OHhngdMSryxJ/dOvQ3SveSfO
ohXH6xZ3lpRNAx3jLWTmZp4+mGlcz1qpCyxVmWI+a5J6tKy3qMZi0S+ymb5nbS1s
T0mvhaSwLvtNvNyRXTDPVmnR9sbJn2oM/dc4UHGQGMwyGyk5JdgCI47aGZh2wYj9
Z4as1SyBAgMBAAECggEAXIksN9BnyKoHqMcbiEM0piudOUhvdU1xocddkQl/6mSt
GxY/Mra1zD+E46GL00jvwNl9paTyhyPBt8Uq982oXpku96Nj17m7YEp9jK+NyX+A
8lVncjSN9SjKi3h0nKqb3O5KF2vpmBGMn94vxoCHMZmD61hR1cUsklD0b6VJG9v9
T97S32Cac2HHC4oTFln9nVc8Ajufj57Fjq2pXUHQtuRVXdKYn1zjgVc4jjOf366P
Fzgk87OC4wd3HetDAj+QAIul1xU7sAAxlkaE9vbXUXY6sQpEFkhyZKvONHr5asHW
dPQ08l57NPl5mYaF+K1DTvk5jL8Qy1jMZIsWW9YohQKBgQDMwRaF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ARBgNVBAMMClF1b29rZXIgQlYwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQCeUmity0so5KyvmXtVkeg0IXclvN2StX7IJEx8OJmG
mNCRV4gi89i/0RCWtYaEsX/XbYwzel0mqgorLezaOVs77N6pupyOA+I02ZBYTkpI
vDcbzDr/JreEzo/4pEzkGxV4VQD3lfwHsX2KP1dLPB0E8ZFYZnmHJdKQbyWLJijQ
t2razCp5h5x0OHhngdMSryxJ/dOvQ3SveSfOohXH6xZ3lpRNAx3jLWTmZp4+mGlc
z1qpCyxVmWI+a5J6tKy3qMZi0S+ymb5nbS1sT0mvhaSwLvtNvNyRXTDPVmnR9sbJ
n2oM/dc4UHGQGMwyGyk5JdgCI47aGZh2wYj9Z4as1SyBAgMBAAGjYzBhMB0GA1Ud
DgQWBBTMTnCgx7pdjOPjw3bNsh7fR3vnDDAfBgNVHSMEGDAWgBTMTnCgx7pdjOPj
w3bNsh7fR3vnDDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjANBgkq
hkiG9w0BAQsFAAOCAQEAcjrinpLRKTsW+6rY60qycHunRE/GcGVyEkVV5cE1vsc2
ZmLonfNJ3Ixky618hwp9bC38TicXHmwPAQdlbSJTaf/jAE7t7lWqxjnFKbyVR2bt
vxKxl/sKtI50u2jlv6babqdWUR6qo5Hup5zhO8u5MV4wlsY6h5DDNwIN9jHcNswU
1B/c6OFo0aKB3YCr+TPvRcaxSrzE/PpFeS0mU+vgsVrUWXTKSe+PH0hMvkgWek6Y
YLHEo0nZrjEQ8zPRL+R1G12hb2Y4GVo2rIAYV1Rm9mwGOdkQqVNI5+zzO84QILvw
jEUXFu+BAH/TJagf11MMwBrCKDr7T7VIXwL9zvGbLQ==
-----END CERTIFICATE-----

Issue script & Debug output

DEBUG: 10:25:05 PM - ImportAzureKeyVaultCertificate begin processing with ParameterSet 'ImportCertificateFromFile'.
DEBUG: 10:25:05 PM - using account id '<redacted>'...
Import-AzKeyVaultCertificate: Cannot find the requested object.

Environment data

$psversiontable

Name                           Value
----                           -----
PSVersion                      7.2.4
PSEdition                      Core
GitCommitId                    7.2.4
OS                             Microsoft Windows 10.0.22000
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Module versions

Script     4.4.0                 Az.KeyVault

Error output

HistoryId: 57

Message        : Cannot find the requested object.
StackTrace     :    at Internal.Cryptography.Pal.StorePal.FromBlobOrFile(ReadOnlySpan`1 rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
                    at System.Security.Cryptography.X509Certificates.X509Certificate2Collection.Import(String fileName, String password, X509KeyStorageFlags keyStorageFlags)
                    at Microsoft.Azure.Commands.KeyVault.ImportAzureKeyVaultCertificate.InitializeCertificateCollection()
                    at Microsoft.Azure.Commands.KeyVault.ImportAzureKeyVaultCertificate.ExecuteCmdlet()
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.<ExecuteSynchronouslyOrAsJob>b__3_0(T c)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Exception      : Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException
InvocationInfo : {Import-AzKeyVaultCertificate}
Line           : import-azkeyvaultcertificate -VaultName myvault -name examplecert -FilePath C:\temp\cert\examplecert.pem
Position       : At line:1 char:1
                 + import-azkeyvaultcertificate -VaultName myvault -name examplecert - …
                 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId      : 57

(what is the best way to suppress these TTY commands?)

dingmeng-xue commented 2 years ago

@BethanyZhou , please help to look into this issue.

isra-fel commented 2 years ago

Hi @cveld we want to know more about your scenario - were you importing a pre-created certificate to Azure KeyVault, or trying to create a new certificate in KeyVault? I asked because both scenarios involve importing a cert, but their implementation is totally different.

cveld commented 2 years ago

@isra-fel We pre-created it with the openssl tooling.

New-Item -Path $OutputPath -ItemType Directory -Force
openssl genrsa -aes256 -passout pass:1234 -out $OutputPath\root.key.pem 2048

$here = Split-Path $MyInvocation.MyCommand.Path -Parent
$cnffile = Join-Path -Path $here -ChildPath "..\Configs\root-ca.cnf"
openssl req -new -x509 -config $cnffile -passin pass:1234 -key $OutputPath\root.key.pem -subj "/CN=My org" -days 3650 -sha256 -extensions v3_ca -out $OutputPath\root.cert.pem
openssl x509 -passin pass:1234 -noout -text -in $OutputPath\root.cert.pem

openssl pkcs8 -passin pass:1234 -nocrypt -in $OutputPath\root.key.pem -topk8 -out $OutputPath\root.pem

$from = Get-Content -Path $OutputPath\root.cert.pem
Add-Content -Path $OutputPath\root.pem -Value $from
# OpenSSL root CA configuration file.

[ ca ]
default_ca = CA_default

[ CA_default ]
# Directory and file locations.
dir               = .
certs             = certs
crl_dir           = crl
new_certs_dir     = newcerts
database          = index.txt
serial            = serial
RANDFILE          = .rand

# The root key and root certificate.
private_key       = root/myprivatekey.key.pem
certificate       = root/mycertificate.cert.pem

# For certificate revocation lists.
crlnumber         = $dir/crlnumber
crl               = $dir/crl/azure-iot-test-only.intermediate.crl.pem
crl_extensions    = crl_ext
default_crl_days  = 30

# SHA-1 is deprecated, so use SHA-2 instead.
default_md        = sha256

name_opt          = ca_default
cert_opt          = ca_default
default_days      = 375
preserve          = no
policy            = policy_loose

[ policy_strict ]
# The root CA should only sign intermediate certificates that match.
countryName             = optional
stateOrProvinceName     = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ policy_loose ]
# Allow the intermediate CA to sign a more diverse range of certificates.
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

[ req ]
default_bits        = 2048
distinguished_name  = req_distinguished_name
string_mask         = utf8only

# SHA-1 is deprecated, so use SHA-2 instead.
default_md          = sha256

# Extension to add when the -x509 option is used.
x509_extensions     = v3_ca

[ req_distinguished_name ]
# See <https://en.wikipedia.org/wiki/Certificate_signing_request>.
countryName                     = Country Name (2 letter code)
stateOrProvinceName             = State or Province Name
localityName                    = Locality Name
0.organizationName              = Organization Name
organizationalUnitName          = Organizational Unit Name
commonName                      = Common Name
emailAddress                    = Email Address

# Optionally, specify some defaults.
countryName_default             = US
stateOrProvinceName_default     = WA
localityName_default            =
0.organizationName_default      = My Organization
organizationalUnitName_default  =
emailAddress_default            =

[ v3_ca ]
# Extensions for a typical CA.
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ v3_intermediate_ca ]
# Extensions for a typical intermediate CA.
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign

[ usr_cert ]
# Extensions for client certificates.
basicConstraints = CA:FALSE
nsCertType = client, email
nsComment = "OpenSSL Generated Client Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, emailProtection

[ server_cert ]
# Extensions for server certificates.
basicConstraints = CA:FALSE
nsCertType = server
nsComment = "OpenSSL Generated Server Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth

[ crl_ext ]
# Extension for CRLs.
authorityKeyIdentifier=keyid:always

[ ocsp ]
# Extension for OCSP signing certificates.
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
keyUsage = critical, digitalSignature
extendedKeyUsage = critical, OCSPSigning
isra-fel commented 2 years ago

Got it @cveld , thanks. @BethanyZhou is working on this. We are targeting the July 5th release.