如何使用 powershell 向用户授予证书私钥的权限?
How to Grant permission to user on Certificate private key using powershell?
证书已安装在计算机上。现在我想授予应用程序用户对证书私钥的读取权限。
答案在这里。
创建了一个 powershell 脚本文件 AddUserToCertificate。ps1
这是脚本文件的内容。
param(
[string]$userName,
[string]$permission,
[string]$certStoreLocation,
[string]$certThumbprint
);
# check if certificate is already installed
$certificateInstalled = Get-ChildItem cert:$certStoreLocation | Where thumbprint -eq $certThumbprint
# download & install only if certificate is not already installed on machine
if ($certificateInstalled -eq $null)
{
$message="Certificate with thumbprint:"+$certThumbprint+" does not exist at "+$certStoreLocation
Write-Host $message -ForegroundColor Red
exit 1;
}else
{
try
{
$rule = new-object security.accesscontrol.filesystemaccessrule $userName, $permission, allow
$root = "c:\programdata\microsoft\crypto\rsa\machinekeys"
$l = ls Cert:$certStoreLocation
$l = $l |? {$_.thumbprint -like $certThumbprint}
$l |%{
$keyname = $_.privatekey.cspkeycontainerinfo.uniquekeycontainername
$p = [io.path]::combine($root, $keyname)
if ([io.file]::exists($p))
{
$acl = get-acl -path $p
$acl.addaccessrule($rule)
echo $p
set-acl $p $acl
}
}
}
catch
{
Write-Host "Caught an exception:" -ForegroundColor Red
Write-Host "$($_.Exception)" -ForegroundColor Red
exit 1;
}
}
exit $LASTEXITCODE
现在 运行 它作为部署的一部分。在 powershell 控制台 window 中 运行ning 以上脚本的示例。
C:\>.\AddUserToCertificate.ps1 -userName testuser1 -permission read -certStoreLocation \LocalMachine\My -certThumbprint 1fb7603985a8a11d3e85abee194697e9784a253
此示例向用户 testuser1 授予 read 对安装在 \LocalMachine\My[ 中的证书的权限=33=] 并且有指纹 1fb7603985a8a11d3e85abee194697e9784a253
如果您使用的是 ApplicationPoolIdentity,那么您的用户名将为 'IIS AppPool\AppPoolNameHere'
注意:您需要使用' '因为IIS和AppPool之间有一个space。
作为上述脚本的替代。您可以使用 PowerShell 模块。我自己没有尝试过,但模块看起来不错。
http://get-carbon.org/index.html
接受的答案对我不起作用,因为 $_.privatekey
返回空值。我设法访问私钥并为我的应用程序池分配 'Read' 权限,如下所示:
param (
[string]$certStorePath = "Cert:\LocalMachine\My",
[string]$AppPoolName,
[string]$certThumbprint
)
Import-Module WebAdministration
$certificate = Get-ChildItem $certStorePath | Where thumbprint -eq $certThumbprint
if ($certificate -eq $null)
{
$message="Certificate with thumbprint:"+$certThumbprint+" does not exist at "+$certStorePath
Write-Host $message -ForegroundColor Red
exit 1;
}else
{
$rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
$fileName = $rsaCert.key.UniqueName
$path = "$env:ALLUSERSPROFILE\Microsoft\Crypto\Keys$fileName"
$permissions = Get-Acl -Path $path
$access_rule = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS AppPool$AppPoolName", 'Read', 'None', 'None', 'Allow')
$permissions.AddAccessRule($access_rule)
Set-Acl -Path $path -AclObject $permissions
}
您可以使用 WinHttpCertCfg.exe,一个证书配置工具
Link: https://docs.microsoft.com/en-us/windows/desktop/winhttp/winhttpcertcfg-exe--a-certificate-configuration-tool
一些代码示例:
Set privatekeyAcces to Svc-LocalAgent$@mydomain.local
*.\WinHttpCertCfg.exe -g -c LOCAL_MACHINE\MY -s *.d365.mydomain.com -a "Svc-LocalAgent$@mydomain.com"*
添加 Michael Armitage 脚本,这将适用于 PrivateKey 值存在和空白的情况
function setCertificatePermission {
param($accountName, $certificate)
if([string]::IsNullOrEmpty($certificate.PrivateKey))
{
$rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
$fileName = $rsaCert.key.UniqueName
$path = "$env:ALLUSERSPROFILE\Microsoft\Crypto\Keys$fileName"
$permissions = Get-Acl -Path $path
$access_rule = New-Object System.Security.AccessControl.FileSystemAccessRule($accountName, 'FullControl', 'None', 'None', 'Allow')
$permissions.AddAccessRule($access_rule)
Set-Acl -Path $path -AclObject $permissions
} else{
$user = New-Object System.Security.Principal.NTAccount($accountName)
$accessRule = New-Object System.Security.AccessControl.CryptoKeyAccessRule($user, 'FullControl', 'Allow')
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine")
$store.Open("ReadWrite")
$rwCert = $store.Certificates | where {$_.Thumbprint -eq $certificate.Thumbprint}
$csp = New-Object System.Security.Cryptography.CspParameters($rwCert.PrivateKey.CspKeyContainerInfo.ProviderType, $rwCert.PrivateKey.CspKeyContainerInfo.ProviderName, $rwCert.PrivateKey.CspKeyContainerInfo.KeyContainerName)
$csp.Flags = "UseExistingKey","UseMachineKeyStore"
$csp.CryptoKeySecurity = $rwCert.PrivateKey.CspKeyContainerInfo.CryptoKeySecurity
$csp.KeyNumber = $rwCert.PrivateKey.CspKeyContainerInfo.KeyNumber
$csp.CryptoKeySecurity.AddAccessRule($AccessRule)
$rsa2 = New-Object System.Security.Cryptography.RSACryptoServiceProvider($csp)
$store.close()
}
}
几周前我注意到 某些东西 发生了变化(我怀疑是 Windows 更新)并破坏了某些证书使用 CspKeyContainerInfo.UniqueKeyContainerName
属性 在 Michael Armitage 的脚本中引用。一些调查发现 Windows 决定开始使用 CNG 而不是 Crypto Service Provider 来保护密钥。以下脚本解决了我的问题并且应该正确支持 CNG 与 CSP 用例场景:
$serviceUser = "DOMAIN\Service User"
$certificate = Get-ChildItem Cert:\LocalMachine\My | Where-Object Thumbprint -eq "certificatethumbprint"
$privateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
$containerName = ""
if ($privateKey.GetType().Name -ieq "RSACng")
{
$containerName = $privateKey.Key.UniqueName
}
else
{
$containerName = $privateKey.CspKeyContainerInfo.UniqueKeyContainerName
}
$keyFullPath = $env:ProgramData + "\Microsoft\Crypto\RSA\MachineKeys\" + $containerName;
if (-Not (Test-Path -Path $keyFullPath -PathType Leaf))
{
throw "Unable to get the private key container to set permissions."
}
# Get the current ACL of the private key
$acl = (Get-Item $keyFullPath).GetAccessControl()
# Add the new ACE to the ACL of the private key
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($serviceUser, "Read", "Allow")
$acl.AddAccessRule($accessRule);
# Write back the new ACL
Set-Acl -Path $keyFullPath -AclObject $acl;
您当然希望adapt/enhance满足您的特定需求。
证书已安装在计算机上。现在我想授予应用程序用户对证书私钥的读取权限。
答案在这里。
创建了一个 powershell 脚本文件 AddUserToCertificate。ps1
这是脚本文件的内容。
param(
[string]$userName,
[string]$permission,
[string]$certStoreLocation,
[string]$certThumbprint
);
# check if certificate is already installed
$certificateInstalled = Get-ChildItem cert:$certStoreLocation | Where thumbprint -eq $certThumbprint
# download & install only if certificate is not already installed on machine
if ($certificateInstalled -eq $null)
{
$message="Certificate with thumbprint:"+$certThumbprint+" does not exist at "+$certStoreLocation
Write-Host $message -ForegroundColor Red
exit 1;
}else
{
try
{
$rule = new-object security.accesscontrol.filesystemaccessrule $userName, $permission, allow
$root = "c:\programdata\microsoft\crypto\rsa\machinekeys"
$l = ls Cert:$certStoreLocation
$l = $l |? {$_.thumbprint -like $certThumbprint}
$l |%{
$keyname = $_.privatekey.cspkeycontainerinfo.uniquekeycontainername
$p = [io.path]::combine($root, $keyname)
if ([io.file]::exists($p))
{
$acl = get-acl -path $p
$acl.addaccessrule($rule)
echo $p
set-acl $p $acl
}
}
}
catch
{
Write-Host "Caught an exception:" -ForegroundColor Red
Write-Host "$($_.Exception)" -ForegroundColor Red
exit 1;
}
}
exit $LASTEXITCODE
现在 运行 它作为部署的一部分。在 powershell 控制台 window 中 运行ning 以上脚本的示例。
C:\>.\AddUserToCertificate.ps1 -userName testuser1 -permission read -certStoreLocation \LocalMachine\My -certThumbprint 1fb7603985a8a11d3e85abee194697e9784a253
此示例向用户 testuser1 授予 read 对安装在 \LocalMachine\My[ 中的证书的权限=33=] 并且有指纹 1fb7603985a8a11d3e85abee194697e9784a253
如果您使用的是 ApplicationPoolIdentity,那么您的用户名将为 'IIS AppPool\AppPoolNameHere'
注意:您需要使用' '因为IIS和AppPool之间有一个space。
作为上述脚本的替代。您可以使用 PowerShell 模块。我自己没有尝试过,但模块看起来不错。 http://get-carbon.org/index.html
接受的答案对我不起作用,因为 $_.privatekey
返回空值。我设法访问私钥并为我的应用程序池分配 'Read' 权限,如下所示:
param (
[string]$certStorePath = "Cert:\LocalMachine\My",
[string]$AppPoolName,
[string]$certThumbprint
)
Import-Module WebAdministration
$certificate = Get-ChildItem $certStorePath | Where thumbprint -eq $certThumbprint
if ($certificate -eq $null)
{
$message="Certificate with thumbprint:"+$certThumbprint+" does not exist at "+$certStorePath
Write-Host $message -ForegroundColor Red
exit 1;
}else
{
$rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
$fileName = $rsaCert.key.UniqueName
$path = "$env:ALLUSERSPROFILE\Microsoft\Crypto\Keys$fileName"
$permissions = Get-Acl -Path $path
$access_rule = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS AppPool$AppPoolName", 'Read', 'None', 'None', 'Allow')
$permissions.AddAccessRule($access_rule)
Set-Acl -Path $path -AclObject $permissions
}
您可以使用 WinHttpCertCfg.exe,一个证书配置工具 Link: https://docs.microsoft.com/en-us/windows/desktop/winhttp/winhttpcertcfg-exe--a-certificate-configuration-tool
一些代码示例:
Set privatekeyAcces to Svc-LocalAgent$@mydomain.local
*.\WinHttpCertCfg.exe -g -c LOCAL_MACHINE\MY -s *.d365.mydomain.com -a "Svc-LocalAgent$@mydomain.com"*
添加 Michael Armitage 脚本,这将适用于 PrivateKey 值存在和空白的情况
function setCertificatePermission {
param($accountName, $certificate)
if([string]::IsNullOrEmpty($certificate.PrivateKey))
{
$rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
$fileName = $rsaCert.key.UniqueName
$path = "$env:ALLUSERSPROFILE\Microsoft\Crypto\Keys$fileName"
$permissions = Get-Acl -Path $path
$access_rule = New-Object System.Security.AccessControl.FileSystemAccessRule($accountName, 'FullControl', 'None', 'None', 'Allow')
$permissions.AddAccessRule($access_rule)
Set-Acl -Path $path -AclObject $permissions
} else{
$user = New-Object System.Security.Principal.NTAccount($accountName)
$accessRule = New-Object System.Security.AccessControl.CryptoKeyAccessRule($user, 'FullControl', 'Allow')
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine")
$store.Open("ReadWrite")
$rwCert = $store.Certificates | where {$_.Thumbprint -eq $certificate.Thumbprint}
$csp = New-Object System.Security.Cryptography.CspParameters($rwCert.PrivateKey.CspKeyContainerInfo.ProviderType, $rwCert.PrivateKey.CspKeyContainerInfo.ProviderName, $rwCert.PrivateKey.CspKeyContainerInfo.KeyContainerName)
$csp.Flags = "UseExistingKey","UseMachineKeyStore"
$csp.CryptoKeySecurity = $rwCert.PrivateKey.CspKeyContainerInfo.CryptoKeySecurity
$csp.KeyNumber = $rwCert.PrivateKey.CspKeyContainerInfo.KeyNumber
$csp.CryptoKeySecurity.AddAccessRule($AccessRule)
$rsa2 = New-Object System.Security.Cryptography.RSACryptoServiceProvider($csp)
$store.close()
}
}
几周前我注意到 某些东西 发生了变化(我怀疑是 Windows 更新)并破坏了某些证书使用 CspKeyContainerInfo.UniqueKeyContainerName
属性 在 Michael Armitage 的脚本中引用。一些调查发现 Windows 决定开始使用 CNG 而不是 Crypto Service Provider 来保护密钥。以下脚本解决了我的问题并且应该正确支持 CNG 与 CSP 用例场景:
$serviceUser = "DOMAIN\Service User"
$certificate = Get-ChildItem Cert:\LocalMachine\My | Where-Object Thumbprint -eq "certificatethumbprint"
$privateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
$containerName = ""
if ($privateKey.GetType().Name -ieq "RSACng")
{
$containerName = $privateKey.Key.UniqueName
}
else
{
$containerName = $privateKey.CspKeyContainerInfo.UniqueKeyContainerName
}
$keyFullPath = $env:ProgramData + "\Microsoft\Crypto\RSA\MachineKeys\" + $containerName;
if (-Not (Test-Path -Path $keyFullPath -PathType Leaf))
{
throw "Unable to get the private key container to set permissions."
}
# Get the current ACL of the private key
$acl = (Get-Item $keyFullPath).GetAccessControl()
# Add the new ACE to the ACL of the private key
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($serviceUser, "Read", "Allow")
$acl.AddAccessRule($accessRule);
# Write back the new ACL
Set-Acl -Path $keyFullPath -AclObject $acl;
您当然希望adapt/enhance满足您的特定需求。