Skip to content

Instantly share code, notes, and snippets.

@gabriel-samfira
Created November 9, 2021 10:57
Show Gist options
  • Save gabriel-samfira/34476332f2ccc326c0207e184d053383 to your computer and use it in GitHub Desktop.
Save gabriel-samfira/34476332f2ccc326c0207e184d053383 to your computer and use it in GitHub Desktop.
slight improvement to fetch ssh keys from github
Param(
[parameter(Mandatory=$true)]
[string]$SSHPublicKey
)
$ErrorActionPreference = "Stop"
function Get-SSHKeyFromGithub {
Param(
[Parameter(Mandatory=$true)]
[string]$SSHKeyString
)
if ($SSHKeyString.StartsWith("gh:")) {
$user = $SSHKeyString.Substring(3)
if (!$user) {
Throw("Invalid SSH key string {0}" -f @($SSHPublicKey))
}
$baseURL = "https://github.com/{0}.keys" -f @($user)
$keys = wget -UseBasicParsing $baseURL
return $keys.Content
} else if ($SSHKeyString.StartsWith("ssh")) {
return $SSHKeyString
}
Throw("Invalid ssh key string")
}
function Set-SSHPublicKey {
Param(
[Parameter(Mandatory=$true)]
[string]$SSHKeyString
)
if(!$SSHKeyString) {
return
}
$authorizedKeysFile = Join-Path $env:ProgramData "ssh\administrators_authorized_keys"
Set-Content -Path $authorizedKeysFile -Value $SSHKeyString -Encoding ascii
$acl = Get-Acl $authorizedKeysFile
$acl.SetAccessRuleProtection($true, $false)
$administratorsRule = New-Object system.security.accesscontrol.filesystemaccessrule("Administrator
s", "FullControl", "Allow")
$systemRule = New-Object system.security.accesscontrol.filesystemaccessrule("SYSTEM", "FullControl
", "Allow")
$acl.SetAccessRule($administratorsRule)
$acl.SetAccessRule($systemRule)
$acl | Set-Acl
}
# Install OpenSSH
$(
Get-WindowsCapability -Online -Name OpenSSH* | Add-WindowsCapability -Online
$sshd = Get-Service sshd -ErrorAction SilentlyContinue
if (!$sshd) {
Throw("SSH service is missing. Reboot may be required after capability install.")
}
Set-Service -Name sshd -StartupType Automatic
Start-Service sshd
# Fetch SSH Keys from github if called with a github ID
# eg: gh:gabriel-samfira
# Return string as is otherwise
$keys = Get-SSHKeyFromGithub -SSHKeyString $SSHPublicKey
# Authorize SSH key
Set-SSHPublicKey -SSHKeyString $keys
# Set PowerShell as default shell
New-ItemProperty -Force -Path "HKLM:\SOFTWARE\OpenSSH" -PropertyType String `
-Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
) *>$1 > C:\output.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment