Fixing `vagrant ssh` on Windows 10 and above

There is a known problem with the interaction of Vagrant and recent versions of Windows where the system (Windows) OpenSSH client is installed (for example: https://github.com/hashicorp/vagrant/issues/13027 ).

Most advice suggests telling Vagrant to use it’s own internally shipped SSH client, but I’ve found that to be buggy (particularly its handling of Ctrl+C). Windows’ own SSH client only complains because of the open ownership of the SSH private key generated by Vagrant.

The following PowerShell (which I keep as fix_ssh.ps1 in the root of my Vagrant-powered codebase) resolves the problem. Credit to https://superuser.com/a/1329702 for the PS method of fixing the permissions.

Write-Host "Trying to retrieve Vagrant SSH details ... (this may take a moment)"

$VagrantSshKey = "$(vagrant ssh-config | Select-String -Pattern "^  IdentityFile ")".Split(" ")[3]
If (!$VagrantSshKey.EndsWith("private_key")) {
 Write-Host "Could not determine Vagrant private SSH Key location.  Unable to proceed."
 Exit 1
}

Write-Host "Key location is: $VagrantSshKey"
Write-Host "Fixing key permissions..."

# Remove Inheritance:
icacls $VagrantSshKey /c /t /Inheritance:d

# Set Ownership to Owner:
icacls $VagrantSshKey /c /t /Grant:r ${env:UserName}:F

# Remove All Users, except for Owner:
icacls $VagrantSshKey /c /t /Remove:g Administrator "Authenticated Users" BUILTIN\Administrators BUILTIN Everyone System Users

# Verify:
icacls $VagrantSshKey

Write-Host "Fixed SSH private key permissions."

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.