ps/Modules/Cole.PowerShell.Developer/Public/Grant-AclOnCert.ps1

86 lines
3.0 KiB
PowerShell
Raw Permalink Normal View History

2023-05-30 22:51:22 -07:00
function Grant-AclOnCert {
<#
.SYNOPSIS
Set the ACL on a certificate by thumbprint
.PARAMETER Thumbprint
The certificate thumbprint to apply permissions to
.PARAMETER FriendlyName
The certificate friendly name to apply permissions to
.PARAMETER Identity
The user or group to apply privileges to
.PARAMETER FileSystemRights
What rights are being granted
.PARAMETER AccessControlType
AccessControlType of permission to apply. Usually "Allow"
.PARAMETER StoreName
The store where the certificate is found. Most commonly used is 'My'
#>
[CmdletBinding(DefaultParameterSetName = 'Thumbprint')]
param(
[Parameter(Mandatory = $true, ParameterSetName = 'Thumbprint', Position = 0)]
[psobject]$Thumbprint,
[Parameter(Mandatory = $true, ParameterSetName = 'FriendlyName', Position = 0)]
[ValidateNotNullOrEmpty()]
[string]$FriendlyName,
[Parameter(Mandatory = $true)]
[string]$Identity,
[Parameter(Mandatory = $true)]
[System.Security.AccessControl.FileSystemRights]$FileSystemRights,
[Parameter(Mandatory = $false)]
[string]$AccessControlType = "Allow",
[Parameter(Mandatory = $false)]
[string]$StoreName = "My"
)
$logLead = Get-LogLeadName
$certs = @()
if ($PSCmdlet.ParameterSetName -eq 'Thumbprint') {
$certs += Get-Item -Path cert:\LocalMachine\$StoreName\$Thumbprint
}
if ($PSCmdlet.ParameterSetName -eq 'FriendlyName') {
$certs += (Get-ChildItem -Path cert:\LocalMachine\$StoreName\).Where({$_.FriendlyName -eq $FriendlyName})
}
if ($certs.Count -eq 0) {
if ($PSCmdlet.ParameterSetName -eq 'Thumbprint') {
Write-Warning "$logLead : No certificate found at path [cert:\LocalMachine\$StoreName\$Thumbprint]"
}
if ($PSCmdlet.ParameterSetName -eq 'FriendlyName') {
Write-Warning "$logLead : No certificate found at path [cert:\LocalMachine\$StoreName] with FriendlyName [$FriendlyName]"
}
return
}
# This is the known location where these are stored
$keyPath = $env:ProgramData + "\Microsoft\Crypto\RSA\MachineKeys\"
foreach ($cert in $certs) {
# This is a magic value
$keyName = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
# Get the full path of where the file should exist
$keyFullPath = $keyPath + $keyName
if ([string]::IsNullOrWhiteSpace($keyName)) {
Write-Warning "$logLead : Either the file does not exist at [$keyFullPath] or you don't have permission to get details about this file."
return
}
# Get the ACL object so we can add stuff to it
$acl = (Get-Item $keyFullPath).GetAccessControl("Access")
$permission = $Identity,$FileSystemRights,$AccessControlType
$accessRule = New-Object -Type System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission
$acl.AddAccessRule($accessRule)
Set-Acl -Path $keyFullPath -AclObject $acl
}
}