# KeyGuard Local for Windows (PowerShell 5.1 or 7): check the RSA PUBLIC keys of devices in your own private network and print the verdict. # # powershell -ExecutionPolicy Bypass -File .\keyguard-local-v2.ps1 # powershell -ExecutionPolicy Bypass -File .\keyguard-local-v2.ps1 -Hosts 192.168.0.1,192.168.0.20 # # What it does: TCP connect, a TLS handshake per open port (on port 22 the SSH key exchange, up to the host key). # What it never does: no login attempts, no private keys, no internet traffic, no upload. The verdict is computed here and the key file stays on this computer. # The same file can also be opened in the Self-check tab of https://huggingface.co/spaces/FINAL-Bench/KeyGuard (checked inside your browser). # Use it only on networks and devices you own or are authorized to test. MIT License, VIDRAFT. param([string[]]$Hosts, [string]$Subnet, [int[]]$Ports = @(443, 8443, 22), [string]$Out, [switch]$Yes) $ErrorActionPreference = 'Stop' try { Add-Type -AssemblyName System.Numerics -ErrorAction SilentlyContinue } catch { } $ko = (Get-UICulture).TwoLetterISOLanguageName -eq 'ko' function T([string]$k, [string]$e) { if ($ko) { $k } else { $e } } $Big = [System.Numerics.BigInteger] function ConvertTo-Big([byte[]]$b) { # big endian unsigned bytes -> BigInteger $x = New-Object byte[] ($b.Length + 1); for ($i = 0; $i -lt $b.Length; $i++) { $x[$i] = $b[$b.Length - 1 - $i] } return New-Object System.Numerics.BigInteger (, $x) } function Get-Sub([byte[]]$b, [int]$i, [int]$n) { $o = New-Object byte[] $n; [Array]::Copy($b, $i, $o, 0, $n); return , $o } function Get-RsaKey([string]$text) { # @{n;e} of an RSA certificate or ssh-rsa line, else $null try { if ($text.StartsWith('ssh-rsa ')) { $b = [Convert]::FromBase64String($text.Split(' ')[1]); $f = @(); $i = 0 while ($i + 4 -le $b.Length -and $f.Count -lt 3) { $n = ([int]$b[$i] -shl 24) + ([int]$b[$i + 1] -shl 16) + ([int]$b[$i + 2] -shl 8) + $b[$i + 3]; $f += , (Get-Sub $b ($i + 4) $n); $i += 4 + $n } return @{ n = (ConvertTo-Big $f[2]); e = (ConvertTo-Big $f[1]) } } $c = New-Object Security.Cryptography.X509Certificates.X509Certificate2 (, [Convert]::FromBase64String(($text -replace '-----[^-]+-----', '' -replace '\s', ''))) if ($c.PublicKey.Oid.Value -ne '1.2.840.113549.1.1.1') { return $null } $b = $c.PublicKey.EncodedKeyValue.RawData; $v = @() $i = 1; if ($b[$i] -band 0x80) { $i += 1 + ($b[$i] -band 0x7F) } else { $i++ } while ($v.Count -lt 2) { if ($b[$i] -ne 2) { return $null } $i++; $n = [int]$b[$i]; $i++ if ($n -band 0x80) { $k = $n -band 0x7F; $n = 0; for ($q = 0; $q -lt $k; $q++) { $n = ($n -shl 8) + $b[$i]; $i++ } } $v += , (Get-Sub $b $i $n); $i += $n } return @{ n = (ConvertTo-Big $v[0]); e = (ConvertTo-Big $v[1]) } } catch { return $null } } function Get-BitLen($n) { $b = $n.ToByteArray(); $i = $b.Length - 1; while ($i -gt 0 -and $b[$i] -eq 0) { $i-- }; $k = 0; $v = [int]$b[$i]; while ($v) { $k++; $v = $v -shr 1 }; return $i * 8 + $k } function Get-Isqrt($n) { if ($n.IsZero) { return $n } $x = $Big::Pow(2, [int][Math]::Ceiling((Get-BitLen $n) / 2.0)) while ($true) { $y = $Big::Divide($Big::Add($x, $Big::Divide($n, $x)), 2); if ($y -ge $x) { return $x }; $x = $y } } $Sq = @{}; foreach ($m in 64, 63, 65, 11) { $h = New-Object bool[] $m; for ($i = 0; $i -lt $m; $i++) { $h[($i * $i) % $m] = $true }; $Sq[$m] = $h } function Test-Fermat($n) { if ($n.IsEven) { return $true } $a = Get-Isqrt $n; if ($Big::Multiply($a, $a) -lt $n) { $a = $Big::Add($a, 1) } $d = $Big::Subtract($Big::Multiply($a, $a), $n); $step = $Big::Add($Big::Multiply($a, 2), 1) for ($k = 0; $k -lt 2000; $k++) { $m = [int]$Big::Remainder($d, 2882880) # 64*63*65*11 if ($Sq[64][$m % 64] -and $Sq[63][$m % 63] -and $Sq[65][$m % 65] -and $Sq[11][$m % 11]) { $q = Get-Isqrt $d if ($Big::Multiply($q, $q) -eq $d -and $Big::Subtract($a, $q) -gt 1) { return $true } } $d = $Big::Add($d, $step); $step = $Big::Add($step, 2); $a = $Big::Add($a, 1) } return $false } function Test-Roca($n) { foreach ($q in 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 151, 163, 167) { $r = [int]$Big::Remainder($n, $q); if ($r -eq 0) { continue } $x = 1; $hit = $false; for ($i = 1; $i -lt $q; $i++) { $x = ($x * (65537 % $q)) % $q; if ($x -eq $r) { $hit = $true; break } } if (-not $hit) { return $false } } return $true } function Test-PrivateIp([string]$ip) { if ($ip -notmatch '^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$') { return $false } $o = $ip.Split('.') | ForEach-Object { [int]$_ } if (($o | Where-Object { $_ -gt 255 })) { return $false } return ($o[0] -eq 10) -or ($o[0] -eq 127) -or ($o[0] -eq 192 -and $o[1] -eq 168) -or ($o[0] -eq 172 -and $o[1] -ge 16 -and $o[1] -le 31) } function Get-LocalIp { $u = New-Object Net.Sockets.UdpClient try { $u.Connect('192.0.2.1', 9); return $u.Client.LocalEndPoint.Address.ToString() } finally { $u.Close() } # UDP connect sends no packet } function Get-CertPem([string]$ip, [int]$port) { $c = New-Object Net.Sockets.TcpClient try { if (-not $c.ConnectAsync($ip, $port).Wait(3000)) { return $null } $c.ReceiveTimeout = 5000; $c.SendTimeout = 5000 $s = New-Object Net.Security.SslStream($c.GetStream(), $false, { $true }) try { # TLS 1.0 is allowed on purpose: old devices are the target $s.AuthenticateAsClient($ip, $null, [Security.Authentication.SslProtocols]'Tls, Tls11, Tls12', $false) } catch { # TLS 1.3 only devices $s.Dispose(); $c.Close(); $c = New-Object Net.Sockets.TcpClient if (-not $c.ConnectAsync($ip, $port).Wait(3000)) { return $null } $c.ReceiveTimeout = 5000; $c.SendTimeout = 5000 $s = New-Object Net.Security.SslStream($c.GetStream(), $false, { $true }) $s.AuthenticateAsClient($ip) } $b = [Convert]::ToBase64String($s.RemoteCertificate.GetRawCertData()) -replace '(.{64})', "`$1`n" return "-----BEGIN CERTIFICATE-----`n" + $b.TrimEnd() + "`n-----END CERTIFICATE-----" } catch { return $null } finally { $c.Close() } } $Group14 = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF' $Group1 = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF' $Kex = [ordered]@{ 'diffie-hellman-group14-sha256' = $Group14; 'diffie-hellman-group14-sha1' = $Group14; 'diffie-hellman-group1-sha1' = $Group1 } function Get-Rand([int]$n) { $b = New-Object byte[] $n; $r = [Security.Cryptography.RandomNumberGenerator]::Create(); $r.GetBytes($b); $r.Dispose(); return , $b } function ConvertTo-U32([int]$n) { return , [byte[]]@((($n -shr 24) -band 255), (($n -shr 16) -band 255), (($n -shr 8) -band 255), ($n -band 255)) } function ConvertFrom-U32([byte[]]$b, [int]$i) { return ([int]$b[$i] -shl 24) + ([int]$b[$i + 1] -shl 16) + ([int]$b[$i + 2] -shl 8) + $b[$i + 3] } function Read-Exact($st, [int]$n) { $b = New-Object byte[] $n; $k = 0; while ($k -lt $n) { $r = $st.Read($b, $k, $n - $k); if ($r -le 0) { throw 'closed' }; $k += $r }; return , $b } function Read-SshPacket($st) { $n = ConvertFrom-U32 (Read-Exact $st 4) 0; if ($n -lt 2 -or $n -gt 40000) { throw 'bad packet' }; $b = Read-Exact $st $n; return , (Get-Sub $b 1 ($n - 1 - $b[0])) } function Send-SshPacket($st, [byte[]]$body) { $pad = 8 - (($body.Length + 5) % 8); if ($pad -lt 4) { $pad += 8 } $m = [byte[]]((ConvertTo-U32 ($body.Length + $pad + 1)) + [byte]$pad + $body + (Get-Rand $pad)); $st.Write($m, 0, $m.Length); $st.Flush() } function Get-SshRsa([string]$ip, [int]$port) { # RSA host key of an SSH server. Runs the key exchange up to the host key and disconnects: no login step. $c = New-Object Net.Sockets.TcpClient try { if (-not $c.ConnectAsync($ip, $port).Wait(3000)) { return $null } $c.ReceiveTimeout = 5000; $c.SendTimeout = 5000; $st = $c.GetStream(); $line = '' for ($q = 0; $q -lt 20; $q++) { $line = ''; while (-not $line.EndsWith("`n") -and $line.Length -lt 512) { $line += [char](Read-Exact $st 1)[0] }; if ($line.StartsWith('SSH-')) { break } } if (-not $line.StartsWith('SSH-')) { return $null } $v = [Text.Encoding]::ASCII.GetBytes("SSH-2.0-KeyGuardLocal`r`n"); $st.Write($v, 0, $v.Length) $enc = 'aes128-ctr,aes256-ctr,aes128-cbc,3des-cbc'; $mac = 'hmac-sha2-256,hmac-sha2-512,hmac-sha1' $body = [byte[]](@([byte]20) + (Get-Rand 16)) foreach ($x in (($Kex.Keys) -join ','), 'rsa-sha2-512,rsa-sha2-256,ssh-rsa', $enc, $enc, $mac, $mac, 'none', 'none', '', '') { $a = [Text.Encoding]::ASCII.GetBytes($x); $body = [byte[]]($body + (ConvertTo-U32 $a.Length) + $a) } Send-SshPacket $st ([byte[]]($body + [byte[]](0, 0, 0, 0, 0))) $b = Read-SshPacket $st; while ($b[0] -ne 20) { $b = Read-SshPacket $st } $theirs = [Text.Encoding]::ASCII.GetString($b, 21, (ConvertFrom-U32 $b 17)).Split(',') $name = $Kex.Keys | Where-Object { $theirs -contains $_ } | Select-Object -First 1 if (-not $name) { return $null } $p = $Big::Parse('0' + $Kex[$name], [Globalization.NumberStyles]::HexNumber) $e = $Big::ModPow((New-Object System.Numerics.BigInteger 2), (ConvertTo-Big (Get-Rand 32)), $p) $raw = $e.ToByteArray(); [Array]::Reverse($raw) Send-SshPacket $st ([byte[]](@([byte]30) + (ConvertTo-U32 $raw.Length) + $raw)) for ($q = 0; $q -lt 6; $q++) { $b = Read-SshPacket $st if ($b[0] -eq 31) { $k = Get-Sub $b 5 (ConvertFrom-U32 $b 1); if ([Text.Encoding]::ASCII.GetString($k, 4, 7) -eq 'ssh-rsa') { return 'ssh-rsa ' + [Convert]::ToBase64String($k) }; return $null } } } catch { return $null } finally { $c.Close() } return $null } $list = @() if ($Hosts) { $list = @($Hosts | ForEach-Object { $_.Split(',') } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) } else { $base = if ($Subnet) { $Subnet -replace '/24$', '' } else { Get-LocalIp } if ($base -notmatch '^\d{1,3}(\.\d{1,3}){3}$') { Write-Host 'Only an IPv4 /24 network is allowed.'; exit 1 } $p = ($base.Split('.')[0..2]) -join '.' $list = @(1..254 | ForEach-Object { "$p.$_" }) } if ($Ports.Count -gt 5 -or $list.Count -gt 256 -or $list.Count -eq 0) { Write-Host 'At most 5 ports and 256 addresses.'; exit 1 } if (@($list | Where-Object { -not (Test-PrivateIp $_) }).Count) { Write-Host 'Only private addresses are allowed (10.x, 172.16-31.x, 192.168.x).'; exit 1 } Write-Host 'KeyGuard Local v2' Write-Host ("Target: {0} to {1} ({2} addresses), ports {3}" -f $list[0], $list[-1], $list.Count, ($Ports -join ',')) if (-not $Yes) { Write-Host 'Use this only on a network you own or are authorized to test.' Write-Host '본인 소유이거나 점검 권한이 있는 네트워크에서만 사용하십시오.' $q = '' for ($i = 0; $i -lt 3; $i++) { $q = ([string](Read-Host 'Type YES to continue, NO to stop / 계속하려면 YES, 그만두려면 NO')).Trim().ToUpper(); if ($q -in 'YES', 'Y', 'NO', 'N') { break } } if ($q -notin 'YES', 'Y') { Write-Host 'Stopped.'; exit 1 } } $todo = @(foreach ($h in $list) { foreach ($q in $Ports) { [pscustomobject]@{ ip = $h; port = $q } } }) $open = @() for ($i = 0; $i -lt $todo.Count; $i += 64) { $batch = $todo[$i..([Math]::Min($i + 63, $todo.Count - 1))] $run = foreach ($t in $batch) { $c = New-Object Net.Sockets.TcpClient; [pscustomobject]@{ t = $t; c = $c; k = $c.ConnectAsync($t.ip, $t.port) } } $end = [DateTime]::UtcNow.AddMilliseconds(1200) while ([DateTime]::UtcNow -lt $end -and @($run | Where-Object { -not $_.k.IsCompleted }).Count) { Start-Sleep -Milliseconds 40 } foreach ($r in $run) { if ($r.k.IsCompleted -and -not $r.k.IsFaulted -and $r.c.Connected) { $open += $r.t }; $r.c.Close() } Write-Progress -Activity 'KeyGuard Local' -PercentComplete ([Math]::Min(100, 100 * ($i + 64) / $todo.Count)) } Write-Progress -Activity 'KeyGuard Local' -Completed Write-Host ("Open ports: {0}" -f $open.Count) $lines = @('# KeyGuard Local: public keys only'); $keys = @(); $rows = @() foreach ($t in $open) { $lab = '{0}:{1}' -f $t.ip, $t.port $k = if ($t.port -eq 22) { Get-SshRsa $t.ip $t.port } else { Get-CertPem $t.ip $t.port } $v = $null if ($k) { $lines += "# $lab"; $lines += $k; $v = Get-RsaKey $k } if ($v) { $keys += [pscustomobject]@{ lab = $lab; n = $v.n; e = $v.e; share = @() } } elseif ($k) { $rows += (' [-] {0} {1}' -f $lab, (T 'RSA 키가 아님 (점검 대상 아님)' 'not an RSA key (not applicable)')) } else { $rows += (' [-] {0} {1}' -f $lab, (T '공개키를 주지 않음' 'no public key offered')) } } for ($i = 0; $i -lt $keys.Count; $i++) { for ($j = 0; $j -lt $i; $j++) { $g = $Big::GreatestCommonDivisor($keys[$i].n, $keys[$j].n) if (-not $g.IsOne -and $g -ne $keys[$i].n -and $g -ne $keys[$j].n) { $keys[$i].share += $keys[$j].lab; $keys[$j].share += $keys[$i].lab } } } $name = @((T '안전' 'SAFE'), (T '주의' 'CAUTION'), (T '위험' 'DANGER')); $col = @('Green', 'Yellow', 'Red'); $cnt = @(0, 0, 0) Write-Host '' Write-Host (T '=== 점검 결과 ===' '=== RESULT ===') foreach ($k in $keys) { $bits = Get-BitLen $k.n; $lv = 0; $why = @() if ($k.share.Count) { $lv = 2; $why += (T '같은 소수를 쓰는 기기: ' 'shares a prime with ') + ($k.share -join ', ') } if ($bits -le 768) { $lv = 2; $why += (T '짧은 키' 'short key') } elseif ($bits -lt 2048) { $lv = [Math]::Max($lv, 1); $why += (T '2048비트 미만' 'under 2048 bits') } if ($k.e -lt 3 -or $k.e.IsEven) { $lv = 2; $why += (T '비정상 지수' 'abnormal exponent') } if (Test-Fermat $k.n) { $lv = 2; $why += (T '두 소수가 너무 가까움' 'primes too close') } if ($bits -ge 512 -and (Test-Roca $k.n)) { $lv = [Math]::Max($lv, 1); $why += 'ROCA CVE-2017-15361' } if (-not $why.Count) { $why += (T '4대 결함 없음' 'none of the four defects') } $cnt[$lv]++ Write-Host (' [{0}] {1} RSA {2} {3}' -f $name[$lv], $k.lab, $bits, ($why -join ' / ')) -ForegroundColor $col[$lv] } foreach ($x in $rows) { Write-Host $x } Write-Host ((T ' 합계: 안전 {0}, 주의 {1}, 위험 {2}, 대상 아님 {3}' ' Total: safe {0}, caution {1}, danger {2}, not applicable {3}') -f $cnt[0], $cnt[1], $cnt[2], $rows.Count) if (-not $open.Count) { Write-Host (T ' 열린 포트를 찾지 못했습니다. 안전 판정은 아닙니다.' ' No open port was found. This is not a Safe verdict.') } if ($cnt[1] + $cnt[2]) { Write-Host (T ' 위험·주의 키: 사용을 멈추고 펌웨어를 갱신한 뒤 새 키를 만드십시오.' ' Danger or Caution: retire the key, update the firmware and generate a new key.') } $dir = if ($PSScriptRoot) { $PSScriptRoot } else { (Get-Location).Path } $path = if (-not $Out) { Join-Path $dir 'keyguard_keys.txt' } elseif ([IO.Path]::IsPathRooted($Out)) { $Out } else { Join-Path (Get-Location).Path $Out } Write-Host '' try { [IO.File]::WriteAllText($path, (($lines -join "`n") -replace "`r", '') + "`n", (New-Object Text.UTF8Encoding($false))) Write-Host ((T '공개키 파일: {0}' 'Public key file: {0}') -f $path) } catch { Write-Host ((T '파일을 쓰지 못했습니다: {0}' 'Could not write the file: {0}') -f $_.Exception.Message) }