Ustawianie uprawnień klucza prywatnego za pomocą PowerShell
Mam skrypt PowerShell, który instaluje certyfikat pfx wMaszyna lokalna magazyn certyfikatów. Funkcja wygląda tak:
function Add-Certificate {
param
(
[Parameter(Position=1, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$pfxPath,
[Parameter(Position=2, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$pfxPassword
)
Write-Host "Installing certificate" -ForegroundColor Yellow
try
{
$pfxcert = new-object system.security.cryptography.x509certificates.x509certificate2
$pfxcert.Import($pfxPath, $pfxPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
$store = new-object system.security.cryptography.X509Certificates.X509Store -argumentlist "MY", LocalMachine
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite");
$store.Add($pfxcert);
$store.Close();
return $pfxcert
}
catch
{
throw
}
}
Kiedy otwieram Menedżera certyfikatów, aby zweryfikować instalację, widzę, że został poprawnie zainstalowany.
Następnym krokiem w moim procesie jest przypisanie uprawnień do certyfikatu do konta usługi.
function Set-CertificatePermission
{
param
(
[Parameter(Position=1, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$pfxThumbPrint,
[Parameter(Position=2, Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$serviceAccount
)
$cert = Get-ChildItem -Path cert:\LocalMachine\My | Where-Object -FilterScript { $PSItem.ThumbPrint -eq $pfxThumbPrint; };
# Specify the user, the permissions and the permission type
$permission = "$($serviceAccount)","Read,FullControl","Allow"
$accessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission;
# Location of the machine related keys
$keyPath = $env:ProgramData + "\Microsoft\Crypto\RSA\MachineKeys\";
$keyName = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName;
$keyFullPath = $keyPath + $keyName;
try
{
# Get the current acl of the private key
# This is the line that fails!
$acl = Get-Acl -Path $keyFullPath;
# Add the new ace to the acl of the private key
$acl.AddAccessRule($accessRule);
# Write back the new acl
Set-Acl -Path $keyFullPath -AclObject $acl;
}
catch
{
throw $_;
}
}
Ta funkcja zawodzi. W szczególności ta funkcja zawodzi przy próbie oceny polecenia Get-Acl z następującym błędem:Get-Acl: Nie można znaleźć ścieżki „C: ProgramData Microsoft Crypto RSAKeyeKeys \ t
Okazuje się, że plik klucza został zainstalowany w moim profilu mobilnymC: Użytkownicy NazwaUżytkownika AppData Roaming Microsoft Krypto RSA S-1-5-21-1259098847-1967870486-1845911597-155499
Jestem pewien, że coś jest nie tak z funkcją Add-Certificate, ale nie wiem, co to jest. Jak zmusić go do zainstalowania pliku klucza w C: ProgramData Microsoft Crypto RSA Katalog MachineKeys?