通过 Powershell 为证书的私钥分配权限 (Win 2012 R2)
Assigning Permission to Certificate's Private Key via Powershell (Win 2012 R2)
在连接到域的 Windows Server 2012 R2 计算机上,我 运行 以下语句:
$target_machine_fqdn = [System.Net.Dns]::GetHostByName($env:computerName)
$certificate_request = Get-Certificate `
-Template 'AcmeComputer' `
-DnsName $target_machine_fqdn `
-CertStoreLocation 'Cert:\LocalMachine\My'
我正在向域的 CA 请求主机证书。语句 returns 没有错误。为机器生成证书并根据要求将其放入 "Cert:\LocalMachine\My"。
问题:我不知道如何授予服务帐户对证书私钥的权限。
现在,大约有 1,000 articles instructing 人如何通过检索 UniqueKeyContainerName
以如下代码开头的代码来授予权限:
$certificate.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
这在这里行不通。虽然证书有私钥,但私钥数据成员为空:
在我刚刚避开的解决方案有效的情况下,私钥在文件系统上。但是,在这种情况下,私钥位于以下注册表中:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates\MY\Keys
使用 Certificates MMC-snapin 时,我可以看到证书。我可以管理私钥的权限。所以,我知道它在那里。不幸的是,我需要自动执行权限分配,因此无法使用 Certificates MMC-snapin。我需要通过 Powershell 以某种方式执行此操作。
我最近自己完成了对证书私钥的自动化访问。我也发现了很多地方告诉我修改硬盘上关键数据的 ACL,但这并不令人满意,因为当我使用 PowerShell 检查私钥的权限时,我添加的用户没有列出。如此多的网络搜索、几篇文章和大量的反复试验使我得出了这个结论。
我首先定义用户对象,以及我想授予他们的访问权限:
# Create NTAccount object to represent the account
$AccountName = 'Domain\UserName'
$User = New-Object System.Security.Principal.NTAccount($AccountName)
# Define AccessRule to be added to the private key, could use 'GenericRead' if all you need is read access
$AccessRule = New-Object System.Security.AccessControl.CryptoKeyAccessRule($User, 'FullControl', 'Allow')
然后我打开本地机器证书存储为 Read/Write,找到我要找的证书:
# Define the thumbprint of the certificate we are interested in
$Thumb = '63CFDDE9A748345CD77C106DAA09B805B33951BF'
# Open Certificate store as read/write
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine")
$store.Open("ReadWrite")
# Look up the certificate's reference object in the store
$RWcert = $store.Certificates | where {$_.Thumbprint -eq $Thumb}
然后我创建一个新的 CSP(加密服务提供商)参数集,基于现有证书,将新的访问规则添加到参数集中。
# Create new CSP parameter object based on existing certificate provider and key name
$csp = New-Object System.Security.Cryptography.CspParameters($RWcert.PrivateKey.CspKeyContainerInfo.ProviderType, $RWcert.PrivateKey.CspKeyContainerInfo.ProviderName, $RWcert.PrivateKey.CspKeyContainerInfo.KeyContainerName)
# Set flags and key security based on existing cert
$csp.Flags = "UseExistingKey","UseMachineKeyStore"
$csp.CryptoKeySecurity = $RWcert.PrivateKey.CspKeyContainerInfo.CryptoKeySecurity
$csp.KeyNumber = $RWcert.PrivateKey.CspKeyContainerInfo.KeyNumber
# Add access rule to CSP object
$csp.CryptoKeySecurity.AddAccessRule($AccessRule)
然后我们使用这些参数实例化一个新的 CSP,它将根据我们定义的标志和我们提供的密钥信息将新的访问规则应用于现有证书。
# Create new CryptoServiceProvider object which updates Key with CSP information created/modified above
$rsa2 = New-Object System.Security.Cryptography.RSACryptoServiceProvider($csp)
然后我们关闭证书存储,就大功告成了。
# Close certificate store
$store.Close()
编辑: 环顾四周后,我意识到我有几个相同的证书。我相信这是由于使用了非 RSA 密码来加密私钥。我使用了 this answer 中的一些信息来解释如何与第三方 CNG 加密提供商合作。我不喜欢必须下载程序集来执行该答案中的操作,但我使用了一些代码来获取密钥的路径(是的,驱动器上有一个密钥),并添加了一个 ACL到文件,它确实可以将权利委托给私钥。所以这就是我所做的...
首先,我们验证证书是否具有基于 CNG 的密钥:
[Security.Cryptography.X509Certificates.X509CertificateExtensionMethods]::HasCngKey($Certificate)
如果 returns True
那么我们就可以继续前进了。我的做到了,我猜你的也会。然后我们通过读取 PrivateKey 数据($Certificate
中缺少)找到硬盘驱动器上的那个密钥,并为它获取 UniqueName
,然后在 Crypto 文件夹中搜索该文件。
$privateKey = [Security.Cryptography.X509Certificates.X509Certificate2ExtensionMethods]::GetCngPrivateKey($Certificate)
$keyContainerName = $privateKey.UniqueName
$keyMaterialFile = gci $env:ALLUSERSPROFILE\Microsoft\Crypto\*Keys$keyContainerName
然后我抓取文件的当前 ACL,创建一个新的 AccessRule 以授予所需用户访问文件的权限,将规则添加到我刚刚抓取的 ACL,并将更新后的 ACL 应用回文件。
$ACL = Get-Acl $keyMaterialFile
$AccountName = 'Domain\User'
$User = New-Object System.Security.Principal.NTAccount($AccountName)
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($User,'FullControl','None','None','Allow')
$ACL.AddAccessRule($AccessRule)
Set-Acl -Path $keyMaterialFile -AclObject $ACL
之后我可以查看 certlm.msc 并验证用户是否有权访问私钥。
依赖更新: 看起来 Microsoft 现在发布了 Security.Cryptography.dll,因此您不必编译它 GitHub。如果您安装了 AzureRM 模块,您可以在许多组件模块中找到 DLL(我从 AzureRM.SiteRecovery 抓取它)。
TheMadTechnician 像 mf'n 冠军一样回答了这个问题。如果他需要我帮他埋葬尸体,他只需要打电话。我正在 他的 答案中添加详细信息,供无法 build/deploy 集会
的人们使用
注意: clrsecurity 项目已 posted 到 CodePlex,该项目已于 2017 年关闭。该项目已移至 github,其中 it can be downloaded。 post 中引用的 clrsecurity 程序集不再受支持。
此外,感谢撰写本文的 Vadims Podāns (Crypt32)
Retrieve CNG key container name and unique name,帮助读者在Powershell中使用非托管代码获取CNG私钥
如果您像我一样不能使用 clrsecurity 程序集,.NET 4.5.6 框架引入了我们可以利用的元素。考虑以下因素:
## Identify the certificate who's private key you want to grant
## permission to
$certificate = $(ls 'cert:\LocalMachine\My\C51280CE3AD1FEA848308B764DDCFA7F43D4AB1A')
## Identify the user you'll be granting permission to
$grantee_name = 'foo\lordAdam'
$grantee = New-Object System.Security.Principal.NTAccount($grantee_name)
## Get the location and permission-of the cert's private key
$privatekey_rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
$privatekey_file_name = $privatekey_rsa.key.UniqueName
$privatekey_path = "${env:ALLUSERSPROFILE}\Microsoft\Crypto\Keys${privatekey_file_name}"
$privatekey_file_permissions = Get-Acl -Path $privatekey_path
## Grant the user 'read' access to the key
$access_rule = New-Object System.Security.AccessControl.FileSystemAccessRule($grantee, 'Read', 'None', 'None', 'Allow')
$privatekey_file_permissions.AddAccessRule($access_rule)
Set-Acl -Path $privatekey_path -AclObject $privatekey_file_permissions
我们正在使用 System.Security.Cryptography.X509Certificates.RSACertificateExtensions
静态 class 的 GetRSAPrivateKey() 方法来 return 我们的私钥。然后我们获取 UniqueName(Key 属性 有一个 UniqueName 属性)。我们用它来推断密钥文件的位置。剩下的就是授予文件权限。
如果您想查看私钥的存储位置,请查看 Key Storage and Retrieval。
在连接到域的 Windows Server 2012 R2 计算机上,我 运行 以下语句:
$target_machine_fqdn = [System.Net.Dns]::GetHostByName($env:computerName)
$certificate_request = Get-Certificate `
-Template 'AcmeComputer' `
-DnsName $target_machine_fqdn `
-CertStoreLocation 'Cert:\LocalMachine\My'
我正在向域的 CA 请求主机证书。语句 returns 没有错误。为机器生成证书并根据要求将其放入 "Cert:\LocalMachine\My"。
问题:我不知道如何授予服务帐户对证书私钥的权限。
现在,大约有 1,000 articles instructing 人如何通过检索 UniqueKeyContainerName
以如下代码开头的代码来授予权限:
$certificate.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
这在这里行不通。虽然证书有私钥,但私钥数据成员为空:
在我刚刚避开的解决方案有效的情况下,私钥在文件系统上。但是,在这种情况下,私钥位于以下注册表中:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SystemCertificates\MY\Keys
使用 Certificates MMC-snapin 时,我可以看到证书。我可以管理私钥的权限。所以,我知道它在那里。不幸的是,我需要自动执行权限分配,因此无法使用 Certificates MMC-snapin。我需要通过 Powershell 以某种方式执行此操作。
我最近自己完成了对证书私钥的自动化访问。我也发现了很多地方告诉我修改硬盘上关键数据的 ACL,但这并不令人满意,因为当我使用 PowerShell 检查私钥的权限时,我添加的用户没有列出。如此多的网络搜索、几篇文章和大量的反复试验使我得出了这个结论。
我首先定义用户对象,以及我想授予他们的访问权限:
# Create NTAccount object to represent the account
$AccountName = 'Domain\UserName'
$User = New-Object System.Security.Principal.NTAccount($AccountName)
# Define AccessRule to be added to the private key, could use 'GenericRead' if all you need is read access
$AccessRule = New-Object System.Security.AccessControl.CryptoKeyAccessRule($User, 'FullControl', 'Allow')
然后我打开本地机器证书存储为 Read/Write,找到我要找的证书:
# Define the thumbprint of the certificate we are interested in
$Thumb = '63CFDDE9A748345CD77C106DAA09B805B33951BF'
# Open Certificate store as read/write
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine")
$store.Open("ReadWrite")
# Look up the certificate's reference object in the store
$RWcert = $store.Certificates | where {$_.Thumbprint -eq $Thumb}
然后我创建一个新的 CSP(加密服务提供商)参数集,基于现有证书,将新的访问规则添加到参数集中。
# Create new CSP parameter object based on existing certificate provider and key name
$csp = New-Object System.Security.Cryptography.CspParameters($RWcert.PrivateKey.CspKeyContainerInfo.ProviderType, $RWcert.PrivateKey.CspKeyContainerInfo.ProviderName, $RWcert.PrivateKey.CspKeyContainerInfo.KeyContainerName)
# Set flags and key security based on existing cert
$csp.Flags = "UseExistingKey","UseMachineKeyStore"
$csp.CryptoKeySecurity = $RWcert.PrivateKey.CspKeyContainerInfo.CryptoKeySecurity
$csp.KeyNumber = $RWcert.PrivateKey.CspKeyContainerInfo.KeyNumber
# Add access rule to CSP object
$csp.CryptoKeySecurity.AddAccessRule($AccessRule)
然后我们使用这些参数实例化一个新的 CSP,它将根据我们定义的标志和我们提供的密钥信息将新的访问规则应用于现有证书。
# Create new CryptoServiceProvider object which updates Key with CSP information created/modified above
$rsa2 = New-Object System.Security.Cryptography.RSACryptoServiceProvider($csp)
然后我们关闭证书存储,就大功告成了。
# Close certificate store
$store.Close()
编辑: 环顾四周后,我意识到我有几个相同的证书。我相信这是由于使用了非 RSA 密码来加密私钥。我使用了 this answer 中的一些信息来解释如何与第三方 CNG 加密提供商合作。我不喜欢必须下载程序集来执行该答案中的操作,但我使用了一些代码来获取密钥的路径(是的,驱动器上有一个密钥),并添加了一个 ACL到文件,它确实可以将权利委托给私钥。所以这就是我所做的...
首先,我们验证证书是否具有基于 CNG 的密钥:
[Security.Cryptography.X509Certificates.X509CertificateExtensionMethods]::HasCngKey($Certificate)
如果 returns True
那么我们就可以继续前进了。我的做到了,我猜你的也会。然后我们通过读取 PrivateKey 数据($Certificate
中缺少)找到硬盘驱动器上的那个密钥,并为它获取 UniqueName
,然后在 Crypto 文件夹中搜索该文件。
$privateKey = [Security.Cryptography.X509Certificates.X509Certificate2ExtensionMethods]::GetCngPrivateKey($Certificate)
$keyContainerName = $privateKey.UniqueName
$keyMaterialFile = gci $env:ALLUSERSPROFILE\Microsoft\Crypto\*Keys$keyContainerName
然后我抓取文件的当前 ACL,创建一个新的 AccessRule 以授予所需用户访问文件的权限,将规则添加到我刚刚抓取的 ACL,并将更新后的 ACL 应用回文件。
$ACL = Get-Acl $keyMaterialFile
$AccountName = 'Domain\User'
$User = New-Object System.Security.Principal.NTAccount($AccountName)
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($User,'FullControl','None','None','Allow')
$ACL.AddAccessRule($AccessRule)
Set-Acl -Path $keyMaterialFile -AclObject $ACL
之后我可以查看 certlm.msc 并验证用户是否有权访问私钥。
依赖更新: 看起来 Microsoft 现在发布了 Security.Cryptography.dll,因此您不必编译它 GitHub。如果您安装了 AzureRM 模块,您可以在许多组件模块中找到 DLL(我从 AzureRM.SiteRecovery 抓取它)。
TheMadTechnician 像 mf'n 冠军一样回答了这个问题。如果他需要我帮他埋葬尸体,他只需要打电话。我正在 他的 答案中添加详细信息,供无法 build/deploy 集会
的人们使用注意: clrsecurity 项目已 posted 到 CodePlex,该项目已于 2017 年关闭。该项目已移至 github,其中 it can be downloaded。 post 中引用的 clrsecurity 程序集不再受支持。
此外,感谢撰写本文的 Vadims Podāns (Crypt32) Retrieve CNG key container name and unique name,帮助读者在Powershell中使用非托管代码获取CNG私钥
如果您像我一样不能使用 clrsecurity 程序集,.NET 4.5.6 框架引入了我们可以利用的元素。考虑以下因素:
## Identify the certificate who's private key you want to grant
## permission to
$certificate = $(ls 'cert:\LocalMachine\My\C51280CE3AD1FEA848308B764DDCFA7F43D4AB1A')
## Identify the user you'll be granting permission to
$grantee_name = 'foo\lordAdam'
$grantee = New-Object System.Security.Principal.NTAccount($grantee_name)
## Get the location and permission-of the cert's private key
$privatekey_rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
$privatekey_file_name = $privatekey_rsa.key.UniqueName
$privatekey_path = "${env:ALLUSERSPROFILE}\Microsoft\Crypto\Keys${privatekey_file_name}"
$privatekey_file_permissions = Get-Acl -Path $privatekey_path
## Grant the user 'read' access to the key
$access_rule = New-Object System.Security.AccessControl.FileSystemAccessRule($grantee, 'Read', 'None', 'None', 'Allow')
$privatekey_file_permissions.AddAccessRule($access_rule)
Set-Acl -Path $privatekey_path -AclObject $privatekey_file_permissions
我们正在使用 System.Security.Cryptography.X509Certificates.RSACertificateExtensions
静态 class 的 GetRSAPrivateKey() 方法来 return 我们的私钥。然后我们获取 UniqueName(Key 属性 有一个 UniqueName 属性)。我们用它来推断密钥文件的位置。剩下的就是授予文件权限。
如果您想查看私钥的存储位置,请查看 Key Storage and Retrieval。