# MIMA support | Windows PowerShell 5.1+ | run locally as administrator. & { $ErrorActionPreference = 'Stop' $gateway = '192.168.42.1' $keys = @( 'from="192.168.42.1",no-agent-forwarding,no-port-forwarding,no-X11-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIK33dm7xWPcZEl74W4KuYTaiTfjw1KW5rdRsQur+pnYk support' 'from="192.168.42.1",no-agent-forwarding,no-port-forwarding,no-X11-forwarding ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPbtbFPDC5IkBmW6emcAKWMgQ6xftEJc9TQXkX7whFZ6 owner' ) $adminSid = [System.Security.Principal.SecurityIdentifier]'S-1-5-32-544' $systemSid = [System.Security.Principal.SecurityIdentifier]'S-1-5-18' $me = [System.Security.Principal.WindowsPrincipal][System.Security.Principal.WindowsIdentity]::GetCurrent() if (!$me.IsInRole($adminSid) -or ![Environment]::Is64BitProcess) { throw 'Open 64-bit Windows PowerShell as administrator.' } if ((Get-CimInstance Win32_ComputerSystem).DomainRole -ge 4) { throw 'This setup is for a workstation or member server.' } # Confirm the actual LAN router, including on PCs with several adapters. $routes = @(Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 | Where-Object NextHop -eq $gateway) $null = Test-Connection -ComputerName $gateway -Count 1 -Quiet -ErrorAction SilentlyContinue $lan = @(foreach ($route in $routes) { $neighbor = Get-NetNeighbor -InterfaceIndex $route.InterfaceIndex -IPAddress $gateway -ErrorAction SilentlyContinue foreach ($n in $neighbor) { $mac = ($n.LinkLayerAddress -replace '[^0-9A-Fa-f]','').ToLowerInvariant() $digest = [System.Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::ASCII.GetBytes($mac)) if ([BitConverter]::ToString($digest).Replace('-','') -eq 'B2D6E7D27515077EBD04E46A1AD873AA3FE0D57166D9CED70B625B7327A466CF') { $route } } }) if ($lan.Count -ne 1) { throw 'Aziz LAN not identified. Connect this PC to the Aziz router and try again.' } $address = (Get-NetIPAddress -InterfaceIndex $lan[0].InterfaceIndex -AddressFamily IPv4 | Where-Object AddressState -eq 'Preferred' | Select-Object -First 1).IPAddress if (!$address) { throw 'No usable IPv4 address on the Aziz interface.' } $typed = (Read-Host 'Paste whoami from the normal terminal of the Windows user who needs SSH (COMPUTER\user or DOMAIN\user)').Trim() $safeName = '[\p{L}\p{M}\p{Nd}_.\x27 -]+' if ($typed -notmatch "^($safeName)\\($safeName)\z") { throw 'Paste the full output of whoami, including the computer or domain name.' } $userSid = ([Security.Principal.NTAccount]::new($typed)).Translate([Security.Principal.SecurityIdentifier]) $canonical = $userSid.Translate([Security.Principal.NTAccount]).Value if ($userSid.Value -notmatch '^S-1-5-21-\d+-\d+-\d+-\d+\z' -or $canonical -notmatch "^($safeName)\\($safeName)\z") { throw 'This identity is not a local or Active Directory Windows user.' } $domain, $shortName = $canonical -split '\\', 2 if ($domain -eq $env:COMPUTERNAME) { $user = Get-LocalUser -SID $userSid if (!$user.Enabled) { throw 'The selected Windows account is disabled.' } if ($user.Name -eq 'mima-ssh' -and $user.Description -eq 'MIMA SSH support (Aziz)') { throw 'Choose the existing personal Windows user.' } $account = $shortName.ToLowerInvariant() } else { $profile = Get-CimInstance Win32_UserProfile -Filter "SID='$($userSid.Value)'" if (!$profile -or $profile.Special) { throw 'Select a domain user who has signed in on this computer.' } $account = $canonical.ToLowerInvariant() } $bin = Join-Path $env:WINDIR 'System32\OpenSSH' $dir = Join-Path $env:ProgramData 'ssh' $config = Join-Path $dir 'sshd_config' $prior = Get-Service sshd -ErrorAction SilentlyContinue $fresh = !(Test-Path -LiteralPath $config) -and (!$prior -or $prior.Status -ne 'Running') $cap = Get-WindowsCapability -Online -Name 'OpenSSH.Server~~~~0.0.1.0' if ($cap.State -ne 'Installed') { $installed = Add-WindowsCapability -Online -Name 'OpenSSH.Server~~~~0.0.1.0' if ($installed.RestartNeeded) { throw 'Windows requested a reboot. Restart the PC and repeat this step.' } } $daemon = Join-Path $bin 'sshd.exe' $keygen = Join-Path $bin 'ssh-keygen.exe' if (!(Test-Path $daemon) -or !(Test-Path $keygen)) { throw 'Microsoft OpenSSH binaries unavailable.' } if ($fresh) { $defaultRule = Get-NetFirewallRule -Name OpenSSH-Server-In-TCP -ErrorAction SilentlyContinue if ($defaultRule) { $defaultRule | Disable-NetFirewallRule | Out-Null } } if (!(Test-Path $dir)) { New-Item -Path $dir -ItemType Directory | Out-Null } $keyName = "mima-aziz-$($userSid.Value).authorized_keys" $keyFile = Join-Path $dir $keyName $keyText = ($keys -join "`r`n") + "`r`n" if (Test-Path $keyFile) { if ([IO.File]::ReadAllText($keyFile) -cne $keyText) { throw 'Existing support key file differs. Review it first.' } } else { [IO.File]::WriteAllText($keyFile, $keyText, [Text.Encoding]::ASCII) } $acl = New-Object System.Security.AccessControl.FileSecurity $acl.SetOwner($adminSid) $acl.SetAccessRuleProtection($true, $false) foreach ($sid in @($adminSid, $systemSid)) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', 'Allow')) } # The machine's private keys must be accessible only to SYSTEM and Administrators. # The user's public authorized_keys file has a separate ACL below. $privateKeys = @('rsa','ecdsa','ed25519' | ForEach-Object { Join-Path $dir "ssh_host_${_}_key" }) $missing = @($privateKeys | Where-Object { !(Test-Path -LiteralPath $_ -PathType Leaf) }) if ($missing.Count) { & $keygen -A if ($LASTEXITCODE -ne 0) { throw 'OpenSSH host key creation failed.' } } function Test-HostKeyAcl($current) { $owner = $current.GetOwner([Security.Principal.SecurityIdentifier]).Value if ($owner -notin @($systemSid.Value,$adminSid.Value) -or !$current.AreAccessRulesProtected) { return $false } $entries = @($current.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) $full = @($entries | Where-Object { $_.AccessControlType -eq 'Allow' -and $_.FileSystemRights -eq 'FullControl' } | ForEach-Object { $_.IdentityReference.Value } | Sort-Object -Unique) return ($entries.Count -eq 2 -and $full.Count -eq 2 -and $adminSid.Value -in $full -and $systemSid.Value -in $full) } $priorAcls = [ordered]@{} foreach ($path in $privateKeys) { $item = Get-Item -LiteralPath $path if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Unexpected host key link: $path" } $current = Get-Acl -LiteralPath $path if (!(Test-HostKeyAcl $current)) { $priorAcls[$path] = $current.Sddl } } if ($priorAcls.Count) { $aclBackup = Join-Path $dir ("mima-host-acls-" + [guid]::NewGuid() + ".json") [IO.File]::WriteAllText($aclBackup, ($priorAcls | ConvertTo-Json), [Text.UTF8Encoding]::new($false)) foreach ($path in $priorAcls.Keys) { Set-Acl -LiteralPath $path -AclObject $acl if (!(Test-HostKeyAcl (Get-Acl -LiteralPath $path))) { throw "Host key permissions were not applied: $path" } } Write-Output "HOST_KEY_PERMISSIONS=corrected ACL_BACKUP=$aclBackup" } $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($userSid, 'ReadAndExecute', 'Allow')) Set-Acl -LiteralPath $keyFile -AclObject $acl $existed = Test-Path -LiteralPath $config $fresh = $fresh -and !$existed if (!$existed -and !$fresh) { throw 'The running SSH installation has no default configuration file. Check its service configuration first.' } $original = if ($existed) { [IO.File]::ReadAllText($config) } else { '' } $marker = '# MIMA Aziz support' function New-ManagedBlock($login, $filename, [bool]$dedicatedMode, [bool]$legacy) { $loginToken = if ($legacy) { $login } else { '"' + $login + '"' } $firstLines = if ($dedicatedMode) { "$marker (dedicated)`nAllowUsers $loginToken" } else { "$marker`nMatch User $loginToken" } $block = @( $firstLines 'AuthenticationMethods publickey' 'PubkeyAuthentication yes' 'PasswordAuthentication no' 'AllowTcpForwarding no' "AuthorizedKeysFile __PROGRAMDATA__/ssh/$filename" ) -join "`n" if ($dedicatedMode) { $block += "`nSubsystem sftp sftp-server.exe" } elseif (!$legacy) { $block += "`n# End Aziz user settings" } return $block } function Get-CandidateText([string]$before, [bool]$newInstall, $login, $filename) { $normalized = $before.Replace("`r`n","`n") $tagIndex = $normalized.IndexOf($marker, [StringComparison]::Ordinal) $dedicatedMode = $newInstall $base = $normalized $endMark = "`n# End Aziz user settings" if ($tagIndex -ge 0) { $prefix = $normalized.Substring(0,$tagIndex).TrimEnd() $endAt = if ($normalized.Substring($tagIndex).StartsWith("$marker (dedicated)`n")) { -1 } else { $normalized.IndexOf($endMark, $tagIndex, [StringComparison]::Ordinal) } $end = if ($endAt -ge 0) { $endAt + $endMark.Length } else { $normalized.Length } $oldBlock = $normalized.Substring($tagIndex,$end-$tagIndex).TrimEnd() $base = $normalized.Remove($tagIndex,$end-$tagIndex) if ($base.Contains($marker)) { throw 'The SSH configuration has multiple managed sections. Review it first.' } $dedicatedMode = ($oldBlock.StartsWith("$marker (dedicated)`n") -and !$prefix) $oldExpected = New-ManagedBlock 'mima-ssh' 'mima-aziz.authorized_keys' $dedicatedMode $true if ($oldBlock -cne $oldExpected) { $oldUser = [regex]::Match($oldBlock, '(?m)^(?:AllowUsers|Match User) "([^"\r\n]+)"$') $oldFile = [regex]::Match($oldBlock, '(?m)^AuthorizedKeysFile __PROGRAMDATA__/ssh/(mima-aziz-S-1-5-21-\d+-\d+-\d+-\d+\.authorized_keys)$') if (!$oldUser.Success -or !$oldFile.Success -or $oldBlock -cne (New-ManagedBlock $oldUser.Groups[1].Value $oldFile.Groups[1].Value $dedicatedMode $false)) { throw 'The existing managed SSH policy was edited. Review it before replacing it.' } } } $block = New-ManagedBlock $login $filename $dedicatedMode $false if ($dedicatedMode) { $result = "$block`n" } else { # OpenSSH uses the first applicable Match value, including for administrators. $firstMatch = [regex]::Match($base, '(?im)^[ \t]*Match[ \t]+') $at = if ($firstMatch.Success) { $firstMatch.Index } else { $base.Length } $beforeMatch = $base.Substring(0,$at).TrimEnd() $afterMatch = $base.Substring($at).TrimStart([char]10) $result = "$block`n" if ($beforeMatch) { $result = "$beforeMatch`n`n$result" } if ($afterMatch) { $result += "`n$afterMatch" } } return @{ Text=$result.Replace("`n","`r`n"); Dedicated=$dedicatedMode } } $candidate = Get-CandidateText $original $fresh $account $keyName $dedicated = $candidate.Dedicated $temp = Join-Path $dir ('mima-sshd-' + [guid]::NewGuid() + '.tmp') $backup = $null $swapped = $false try { if ($original.Replace("`r",'') -ceq $candidate.Text.Replace("`r",'')) { $testConfig = $config } else { [IO.File]::WriteAllText($temp, $candidate.Text, [Text.UTF8Encoding]::new($false)) $testConfig = $temp } & $daemon -t -f $testConfig if ($LASTEXITCODE -ne 0) { throw 'OpenSSH configuration validation failed.' } $checkArgs = @('-T', '-f', $testConfig) if (!$dedicated) { $checkArgs += @('-C', "user=$account,host=localhost,addr=$gateway,laddr=$address,lport=22") } $outputEncodingBefore = [Console]::OutputEncoding try { [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) $effective = & $daemon @checkArgs } finally { [Console]::OutputEncoding = $outputEncodingBefore } if ($LASTEXITCODE -ne 0) { throw "OpenSSH could not evaluate the candidate policy (exit $LASTEXITCODE). See its message above." } $effective = @($effective | ForEach-Object { $_.Trim() }) $required = @('authenticationmethods publickey', 'passwordauthentication no', 'pubkeyauthentication yes', 'allowtcpforwarding no', 'port 22') foreach ($setting in $required) { if ($effective -notcontains $setting) { throw "OpenSSH effective policy is missing: $setting" } } $keySetting = @(($effective -match '^authorizedkeysfile ') -replace '\\','/') $expected = "authorizedkeysfile __PROGRAMDATA__/ssh/$keyName" $expanded = 'authorizedkeysfile ' + ($keyFile -replace '\\','/') if ($keySetting.Count -ne 1 -or $keySetting[0] -notin @($expected,$expanded)) { throw "OpenSSH returned a different AuthorizedKeysFile: $keySetting" } if ($dedicated -and (@($effective -match '^allowusers ').Count -ne 1 -or $effective -notcontains "allowusers $account")) { throw "OpenSSH does not restrict this dedicated service to $account." } if ($testConfig -eq $temp) { if ($existed) { if ([IO.File]::ReadAllText($config) -cne $original) { throw 'sshd_config changed during setup.' } $backup = "$config.mima-$([guid]::NewGuid()).bak" [IO.File]::Replace($temp, $config, $backup) } else { [IO.File]::Move($temp, $config) } $swapped = $true } $ruleName = 'MIMA-Aziz-SSH' $rule = Get-NetFirewallRule -Name $ruleName -ErrorAction SilentlyContinue if (!$rule) { New-NetFirewallRule -Name $ruleName -DisplayName 'MIMA SSH via Aziz' -Group 'MIMA Aziz support' -Enabled True -Direction Inbound -Profile Any -Action Allow -Protocol TCP -LocalPort 22 -RemoteAddress $gateway -InterfaceAlias $lan[0].InterfaceAlias | Out-Null } else { $ips = @($rule | Get-NetFirewallAddressFilter | Select-Object -ExpandProperty RemoteAddress) $ports = $rule | Get-NetFirewallPortFilter $ifaces = @($rule | Get-NetFirewallInterfaceFilter | Select-Object -ExpandProperty InterfaceAlias) if ($rule.Group -ne 'MIMA Aziz support' -or $rule.Action -ne 'Allow' -or $rule.Direction -ne 'Inbound' -or $rule.Enabled -ne 'True' -or $ips.Count -ne 1 -or $ips[0] -ne $gateway -or $ports.LocalPort -ne '22' -or $ports.Protocol -notin @('TCP','6') -or $ifaces.Count -ne 1 -or $ifaces[0] -ne $lan[0].InterfaceAlias) { throw 'Existing MIMA firewall rule differs. Review it first.' } } Set-Service sshd -StartupType Automatic if ((Get-Service sshd).Status -ne 'Running') { Start-Service sshd } elseif ($swapped) { Restart-Service sshd } (Get-Service sshd).WaitForStatus('Running',[TimeSpan]::FromSeconds(15)) } catch { if ($swapped -and $backup) { [IO.File]::Replace($backup, $config, "$backup.failed") if ($prior -and $prior.Status -eq 'Running') { Restart-Service sshd } } throw } finally { if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp } } $sshdPid = (Get-CimInstance Win32_Service -Filter "Name='sshd'").ProcessId $listening = @(Get-NetTCPConnection -LocalPort 22 -State Listen -ErrorAction SilentlyContinue | Where-Object { $_.OwningProcess -eq $sshdPid -and $_.LocalAddress -in @('0.0.0.0', '::', $address) }) if (!$sshdPid -or !$listening.Count) { throw 'sshd has no TCP 22 listener for the Aziz interface.' } $hostKey = Join-Path $dir 'ssh_host_ed25519_key.pub' $fp = & $keygen -lf $hostKey if ($LASTEXITCODE -ne 0 -or !$fp) { throw 'Could not read the Windows host key fingerprint.' } Write-Output "COMPUTER=$env:COMPUTERNAME" "SSH_USER=$account" "LAN_IP=$address" "HOST_KEY=$fp" }