Skip to content

Instantly share code, notes, and snippets.

@scivision
Created July 23, 2025 16:55
Show Gist options
  • Save scivision/431758996df4d4413db6f64defa3cb0c to your computer and use it in GitHub Desktop.
Save scivision/431758996df4d4413db6f64defa3cb0c to your computer and use it in GitHub Desktop.
Fix SSH key permission on Windows
# usage:
# save this function to Set-SshKeyPermissions.ps1
# then run in PowerShell as the desired user (non-elevated):
#
# .\Set-SshKeyPermissions.ps1
#
# Set-SshKeyPermissions "$Env:USERPROFILE\.ssh"
#
# Ref: https://scivision.dev/ssh-agent-config/
function Set-SshKeyPermissions {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]$KeyPath
)
Write-Host "Setting permissions for $KeyPath"
# Define the owner and the key file/directory
#$Owner = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$UserName = $env:UserName
# This is for your specific user account
# Disable inheritance and remove all existing permissions
Write-Host "Disabling inheritance and removing all existing permissions for $KeyPath..."
icacls "$KeyPath" /c /t /inheritance:d /remove:g Administrator "Authenticated Users" "BUILTIN\Administrators" BUILTIN\Everyone Users System
# Note: We remove 'System' here to reset it, then grant it back explicitly.
# Take ownership if not already owned by the current user
Write-Host "Taking ownership of $KeyPath..."
Takeown /F "$KeyPath"
# Grant Full Control to the current user
Write-Host "Granting Full Control to $UserName for $KeyPath..."
icacls "$KeyPath" /c /t /grant "${UserName}:F"
# Grant Full Control to SYSTEM (important for ssh-agent)
Write-Host "Granting Full Control to SYSTEM for $KeyPath..."
icacls "$KeyPath" /c /t /grant "SYSTEM:F"
# Verify permissions
Write-Host "Verifying permissions for $KeyPath..."
icacls "$KeyPath"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment