Windows SSH-externe toegang

Om SSH-externe toegang in Windows in te schakelen, moet meestal gebruik worden gemaakt van de OpenSSH-functionaliteit van Windows. Hieronder volgen de gedetailleerde stappen:

OpenSSH controleren en installeren

  1. Controleren of OpenSSH is geïnstalleerd:

    • Open “Instellingen” > “Apps” > “Apps en functies” > “Optionele functies beheren”.
    • Zoek in de lijst van geïnstalleerde functies naar “OpenSSH-server”. Als deze aanwezig is, betekent dit dat deze al is geïnstalleerd.
  2. OpenSSH installeren:

    • Als u de OpenSSH-server niet kunt vinden, klikt u op de pagina “Optionele functies beheren” op “Functie toevoegen” en zoekt u in de lijst naar “OpenSSH-server”. Klik vervolgens op “Installeren”.

OpenSSH-service starten en configureren

  1. OpenSSH-service starten:

    • Start de opdrachtprompt (met beheerdersrechten) nadat de installatie is voltooid.
    • Voer net start sshd in om de OpenSSH-service te starten. Als u wilt dat de service automatisch wordt gestart bij het opstarten van het systeem, voert u sc config sshd start= auto in.
  2. Firewall configureren:

    • Zorg ervoor dat Windows Firewall SSH-verbindingen toestaat. U kunt dit doen via “Configuratiescherm” > “Systeem en beveiliging” > “Windows Defender Firewall” > “Geavanceerde instellingen”. Vervolgens maakt u een nieuwe binnenkomende regel aan die TCP-poort 22 toestaat.

IP-adres verkrijgen en verbindingsproef uitvoeren

  1. IP-adres verkrijgen:

    • Om vanaf een andere computer verbinding te maken met deze Windows-computer met SSH-service, moet u het IP-adres weten. U kunt het IP-adres van uw computer bekijken door het commando ipconfig in te voeren in de opdrachtprompt.
  2. Verbindingsproef:

    • Gebruik een SSH-client (bijvoorbeeld: PuTTY, Termius, enz.) op een andere computer of mobiel apparaat om verbinding te proberen te maken met uw Windows PC, met het formaat ssh gebruikersnaam@uw_ip_adres. Hierbij is gebruikersnaam de Windows-accountnaam waarmee u wilt inloggen en uw_ip_adres het IP-adres dat u eerder hebt opgezocht.

Configuratie wijzigen

Vermijd het gebruik van wachtwoordlogin, dit is een absoluut verboden gebied. Gebruik zeker een publieke sleutel voor login. We moeten de instellingen wijzigen, wachtwoordlogin uitschakelen en publieke sleutellogin toestaan.

Dit configuratiebestand is niet gemakkelijk te wijzigen, hiervoor zijn speciale rechten vereist en de machtigingen van de map en het bestand moeten specifieke waarden hebben. Hier wordt een script aanbevolen voor het wijzigen.

# Controleer beheerdersrechten
$elevated = [bool]([System.Security.Principal.WindowsPrincipal]::new(
    [System.Security.Principal.WindowsIdentity]::GetCurrent()
).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))

if (-not $elevated) {
    Write-Error "Voer dit script uit als beheerder"
    exit 1
}

# 1. Controleer en installeer OpenSSH-server
Write-Host "OpenSSH-server installatiestatus wordt gecontroleerd..."
$capability = Get-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

if ($capability.State -ne 'Installed') {
    Write-Host "OpenSSH-server wordt geïnstalleerd..."
    Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 | Out-Null
}

# 2. Start en configureer SSH-service voor automatisch opstarten
Write-Host "SSH-service wordt geconfigureerd..."
$service = Get-Service sshd -ErrorAction SilentlyContinue
if (-not $service) {
    Write-Error "OpenSSH-service installatie mislukt"
    exit 1
}

if ($service.Status -ne 'Running') {
    Start-Service sshd
}
Set-Service sshd -StartupType Automatic

# 3. Configuratiebestand wijzigen
$configPath = "C:\ProgramData\ssh\sshd_config"
if (Test-Path $configPath) {
    Write-Host "Origineel configuratiebestand wordt geback-upt..."
    Copy-Item $configPath "$configPath.bak" -Force
} else {
    Write-Error "Configuratiebestand niet gevonden: $configPath"
    exit 1
}

Write-Host "SSH-configuratie wordt gewijzigd..."
$config = Get-Content -Path $configPath -Raw

# Schakel publieke sleutelverificatie in en schakel wachtwoordlogin uit
$config = $config -replace '^#?PubkeyAuthentication .*$','PubkeyAuthentication yes' `
                  -replace '^#?PasswordAuthentication .*$','PasswordAuthentication no'

# Zorg ervoor dat de benodigde configuratie is opgenomen
if ($config -notmatch 'PubkeyAuthentication') {
    $config += "`nPubkeyAuthentication yes"
}
if ($config -notmatch 'PasswordAuthentication') {
    $config += "`nPasswordAuthentication no"
}

# Schrijf terug naar het configuratiebestand
$config | Set-Content -Path $configPath -Encoding UTF8

Bevestig machtigingen voor authorized_keys-bestand

# normale gebruiker
$authKeys = "$env:USERPROFILE\.ssh\authorized_keys"
icacls $authKeys /inheritance:r /grant "$($env:USERNAME):F" /grant "SYSTEM:F"
icacls "$env:USERPROFILE\.ssh" /inheritance:r /grant "$($env:USERNAME):F" /grant "SYSTEM:F"

# beheerder
$adminAuth = "C:\ProgramData\ssh\administrators_authorized_keys"
icacls $adminAuth /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F"

Firewallregels instellen

# SSH-poort toestaan
New-NetFirewallRule -DisplayName "OpenSSH Server (sshd)" -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

Openbare sleutel toevoegen

Normale gebruiker

# normale gebruiker
$userProfile = $env:USERPROFILE
$sshDir = Join-Path $userProfile ".ssh"
$authorizedKeysPath = Join-Path $sshDir "authorized_keys"
$PublicKeyPath = "D:\public_keys\id_rsa.pub"

# .ssh-map maken
if (-not (Test-Path $sshDir)) {
    New-Item -ItemType Directory -Path $sshDir | Out-Null
}

# Machtigingen voor .ssh-map instellen
$currentUser = "$env:USERDOMAIN\$env:USERNAME"
$acl = Get-Acl $sshDir
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
    $currentUser, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
)
$acl.AddAccessRule($rule)
Set-Acl $sshDir $acl

# Openbare sleutel toevoegen
if (Test-Path $PublicKeyPath) {
    $pubKey = Get-Content -Path $PublicKeyPath -Raw
    if ($pubKey) {
        # Zorg ervoor dat de openbare sleutel eindigt met een regeleinde
        if (-not $pubKey.EndsWith("`n")) {
            $pubKey += "`n"
        }

        # Openbare sleutel toevoegen
        Add-Content -Path $authorizedKeysPath -Value $pubKey -Encoding UTF8

        # Bestandsmachtigingen instellen
        $acl = Get-Acl $authorizedKeysPath
        $acl.SetSecurityDescriptorRule(
            (New-Object System.Security.AccessControl.FileSystemAccessRule(
                $currentUser, "FullControl", "None", "None", "Allow"
            ))
        )
        Set-Acl $authorizedKeysPath $acl
    }
} else {
    Write-Error "Openbare sleutelbestand bestaat niet: $PublicKeyPath"
    exit 1
}

# SSH-service opnieuw starten
Write-Host "SSH-service wordt opnieuw gestart..."
Restart-Service sshd

Beheerdersgebruiker

# beheerder
$adminSshDir = "C:\ProgramData\ssh"
$adminAuthKeysPath = Join-Path $adminSshDir "administrators_authorized_keys"
$adminPublicKeyPath = "D:\public_keys\id_rsa.pub"

# Beheerders SSH-map maken
if (-not (Test-Path $adminSshDir)) {
    New-Item -ItemType Directory -Path $adminSshDir | Out-Null
}

# Machtigingen voor beheerders SSH-map instellen
$adminAcl = Get-Acl $adminSshDir
$adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
    "Administrators", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
)
$adminAcl.AddAccessRule($adminRule)
Set-Acl $adminSshDir $adminAcl

# Beheerders openbare sleutel toevoegen
if (Test-Path $adminPublicKeyPath) {
    $adminPubKey = Get-Content -Path $adminPublicKeyPath -Raw
    if ($adminPubKey) {
        # Zorg ervoor dat de openbare sleutel eindigt met een regeleinde
        if (-not $adminPubKey.EndsWith("`n")) {
            $adminPubKey += "`n"
        }

        # Openbare sleutel toevoegen
        Add-Content -Path $adminAuthKeysPath -Value $adminPubKey -Encoding UTF8

        # Bestandsmachtigingen instellen
        $adminAcl = Get-Acl $adminAuthKeysPath
        $adminAcl.SetSecurityDescriptorRule(
            (New-Object System.Security.AccessControl.FileSystemAccessRule(
                "Administrators", "FullControl", "None", "None", "Allow"
            ))
        )
        Set-Acl $adminAuthKeysPath $adminAcl
    }
} else {
    Write-Error "Beheerders openbare sleutelbestand bestaat niet: $adminPublicKeyPath"
    exit 1
}

# SSH-service opnieuw starten
Write-Host "SSH-service wordt opnieuw gestart..."
Restart-Service sshd