Skip to content

Instantly share code, notes, and snippets.

@Scot-Bernard
Last active January 29, 2023 15:22
Show Gist options
  • Save Scot-Bernard/fd409ad73b3733c3b9e93dd9055b9814 to your computer and use it in GitHub Desktop.
Save Scot-Bernard/fd409ad73b3733c3b9e93dd9055b9814 to your computer and use it in GitHub Desktop.
Set ssh private key permissions on Windows
# To avoid permissions problems, run this on Windows PowerShell, Core edition doesn't have SetAccessControl implemented at base level.
# A variant for it is welcome.
# Allow the powershell session to run this script with:
# Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned
function Set-SshPermissions {
param (
$pkFile
)
# Set inheritance to false
$pkAcl = $pkFile.GetAccessControl('Access')
$pkAcl.SetAccessRuleProtection($True, $True)
$pkFile.SetAccessControl($pkAcl)
# Remove access rules for all exept current user
$pkAcl = $pkFile.GetAccessControl('Access')
foreach ($accessRule in $pkAcl.Access) {
if ($accessRule.IdentityReference -ne $env:USERDOMAIN + "\" + $env:USERNAME ) {
Write-Output("Removing Access rule " + $accessRule.IdentityReference)
$pkAcl.RemoveAccessRuleAll($accessRule)
}
}
Write-Output("Permissions set to current user only:")
$pkAcl.Access | Format-List
$pkFile.SetAccessControl($pkAcl)
}
# Get the private_key file
$pk = $PSScriptRoot + "\my_private_key"
$pkFile = Get-Item -LiteralPath $pk
Set-SshPermissions($pkFile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment