Last active
April 29, 2025 16:20
-
-
Save Scot-Bernard/fd409ad73b3733c3b9e93dd9055b9814 to your computer and use it in GitHub Desktop.
Set ssh private key permissions on Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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