Host-Key-Popup mit Fingerprint + ctty-run-Helper (Ctty fuer ssh-Prompts), Doku

This commit is contained in:
x3
2026-09-22 09:31:08 +02:00
parent 8511e4fdae
commit 4209c481dc
9 changed files with 375 additions and 6 deletions
@@ -0,0 +1,148 @@
import Foundation
/// Host-Key-Prüfung OHNE interaktiven Yes/No-Prompt (der kommt ohne echtes
/// Terminal/Ctty nicht an — ssh bricht dann mit „Host key verification failed." ab).
/// Ablauf: ssh-keyscan → Fingerprint → Popup (akzeptieren/ablehnen) → known_hosts.
/// Nutzt bewusst ~/.ssh/known_hosts gemeinsam mit Terminal.app.
enum HostKeyStatus: Equatable {
case known
case unknown(HostKeyInfo)
case changed(HostKeyInfo)
case unreachable(String)
}
struct HostKeyInfo: Equatable {
var host: String
var port: Int
var keyType: String
var fingerprintSHA256: String
var fingerprintMD5: String
var allKeyLines: [String]
}
enum HostKeyService {
static var knownHostsPath = NSHomeDirectory() + "/.ssh/known_hosts"
static var scanTimeoutSeconds = "5"
static func canonicalHost(_ host: String, port: Int) -> String {
port == 22 ? host : "[\(host)]:\(port)"
}
@discardableResult
static func run(_ exe: String, _ args: [String]) -> (Int32, String) {
let p = Process()
p.executableURL = URL(fileURLWithPath: exe)
p.arguments = args
let out = Pipe()
p.standardOutput = out
p.standardError = Pipe()
do {
try p.run()
} catch {
return (-1, "")
}
p.waitUntilExit()
let data = out.fileHandleForReading.readDataToEndOfFile()
return (p.terminationStatus, String(data: data, encoding: .utf8) ?? "")
}
/// Rohe Key-Zeilen vom Server (ohne #-Kommentare).
static func keyscan(host: String, port: Int) -> [String] {
let (code, out) = run("/usr/bin/ssh-keyscan", ["-T", scanTimeoutSeconds, "-p", "\(port)", host])
guard code == 0 else { return [] }
return out.split(separator: "\n").map(String.init).filter { line in
let t = line.trimmingCharacters(in: .whitespaces)
return !t.isEmpty && !t.hasPrefix("#") && t.contains(" ")
}
}
static func knownHostsContent() -> String {
(try? String(contentsOfFile: knownHostsPath, encoding: .utf8)) ?? ""
}
static func status(host: String, port: Int) -> HostKeyStatus {
let h = host.trimmingCharacters(in: .whitespacesAndNewlines)
guard !h.isEmpty else { return .unreachable("Kein Host.") }
let lines = keyscan(host: h, port: port)
guard !lines.isEmpty else {
return .unreachable("Host-Key nicht abfragbar (ssh-keyscan ohne Antwort).")
}
guard let info = info(host: h, port: port, lines: lines) else {
return .unreachable("Fingerprint nicht berechenbar.")
}
let (fcode, fout) = run("/usr/bin/ssh-keygen", ["-F", canonicalHost(h, port: port), "-f", knownHostsPath])
let hasEntry = fcode == 0 && fout.contains("found:")
if hasEntry {
let knownKeys = lines.compactMap { $0.split(separator: " ").last.map(String.init) }
if knownKeys.contains(where: { knownHostsContent().contains($0) }) {
return .known
}
return .changed(info)
}
return .unknown(info)
}
/// Bevorzugter Key (ed25519 > ecdsa > Rest) + Fingerprints via ssh-keygen.
static func info(host: String, port: Int, lines: [String]) -> HostKeyInfo? {
func rank(_ l: String) -> Int {
if l.contains("ssh-ed25519") { return 0 }
if l.contains("ecdsa-") { return 1 }
return 2
}
guard let line = lines.sorted(by: { rank($0) < rank($1) }).first else { return nil }
let parts = line.split(separator: " ")
guard parts.count >= 3 else { return nil }
let tmp = FileManager.default.temporaryDirectory.appendingPathComponent("rmm-fp-\(UUID().uuidString)")
do {
try (line + "\n").write(to: tmp, atomically: true, encoding: .utf8)
defer { try? FileManager.default.removeItem(at: tmp) }
let (_, sha) = run("/usr/bin/ssh-keygen", ["-l", "-f", tmp.path])
let (_, md5) = run("/usr/bin/ssh-keygen", ["-l", "-E", "md5", "-f", tmp.path])
return HostKeyInfo(host: host, port: port, keyType: String(parts[1]),
fingerprintSHA256: parseFP(sha), fingerprintMD5: parseFP(md5),
allKeyLines: lines)
} catch {
return nil
}
}
/// Aus `256 SHA256:XYZ host (ED25519)` wird `SHA256:XYZ`.
static func parseFP(_ out: String) -> String {
let parts = out.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: " ")
guard parts.count >= 2 else { return out.trimmingCharacters(in: .whitespacesAndNewlines) }
return String(parts[1])
}
/// Fehlende Key-Zeilen an known_hosts anhängen (0600, ~/.ssh 0700).
static func accept(_ info: HostKeyInfo) -> Bool {
let dir = (knownHostsPath as NSString).deletingLastPathComponent
do {
try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
let existing = knownHostsContent()
let missing = info.allKeyLines.filter { line in
let key = line.split(separator: " ").last.map(String.init) ?? line
return !existing.contains(key)
}
guard !missing.isEmpty else { return true }
if !FileManager.default.fileExists(atPath: knownHostsPath) {
FileManager.default.createFile(atPath: knownHostsPath, contents: nil,
attributes: [.posixPermissions: 0o600])
}
let fh = try FileHandle(forWritingTo: URL(fileURLWithPath: knownHostsPath))
defer { try? fh.close() }
try fh.seekToEnd()
fh.write(((missing.joined(separator: "\n")) + "\n").data(using: .utf8)!)
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: knownHostsPath)
return true
} catch {
return false
}
}
/// Alle Einträge für Host entfernen (ssh-keygen -R).
static func revoke(host: String, port: Int) -> Bool {
let (code, _) = run("/usr/bin/ssh-keygen", ["-R", canonicalHost(host, port: port), "-f", knownHostsPath])
return code == 0
}
}
+37 -3
View File
@@ -80,10 +80,22 @@ final class PTYSession: ObservableObject {
}
masterFD = master
// Ctty-Helper (gleiches Verzeichnis wie dieses Binary — .app wie .build):
// Gibt ssh ein echtes Controlling-Terminal, damit Passwort- und
// Yes/No-Prompts funktionieren (/dev/tty statt stiller Abbrüche).
// Ohne Helper: Legacy-Direktstart (Prompts teils stumm).
let pipe = Pipe()
let p = Process()
p.executableURL = URL(fileURLWithPath: executable)
p.arguments = arguments
if let helper = Self.cttyHelperURL() {
p.executableURL = helper
p.arguments = [slavePath, executable] + arguments
} else {
p.executableURL = URL(fileURLWithPath: executable)
p.arguments = arguments
DispatchQueue.main.async { [weak self] in
self?.note("Hinweis: ohne ctty-run-Helper (eingeschränkte Prompts).")
}
}
var env = ProcessInfo.processInfo.environment
env["TERM"] = "xterm-256color"
if env["LANG"] == nil { env["LANG"] = "de_DE.UTF-8" }
@@ -225,6 +237,17 @@ final class PTYSession: ObservableObject {
lines = [[]]
}
/// ctty-run liegt neben diesem Binary (Contents/MacOS wie .build/debug).
static func cttyHelperURL() -> URL? {
let sibling = URL(fileURLWithPath: CommandLine.arguments[0])
.deletingLastPathComponent()
.appendingPathComponent("ctty-run")
if FileManager.default.isExecutableFile(atPath: sibling.path) {
return sibling
}
return nil
}
func note(_ message: String) {
lines.append([StyledText(text: message, style: TermStyle(fg: 8))])
}
@@ -241,7 +264,7 @@ final class PTYSession: ObservableObject {
func stop() {
let wasRunning = isRunning
process?.terminate()
killTree()
cleanupSync()
if wasRunning {
epoch += 1 // späte terminationHandler-Ausläufer verwerfen
@@ -252,6 +275,14 @@ final class PTYSession: ObservableObject {
}
}
/// Beendet Kind + Enkel (ctty-run-Wächter + ssh teilen die Prozessgruppe).
private func killTree() {
if let pid = process?.processIdentifier, pid > 0 {
Darwin.kill(-pid, SIGTERM)
}
process?.terminate()
}
/// Synchroner Cleanup auf Main: Source canceln, Master schließen, Pipe abklemmen.
/// Laufende ioQueue-Reads bekommen EBADF und beenden sich selbst.
private func cleanupSync() {
@@ -278,6 +309,9 @@ final class PTYSession: ObservableObject {
}
deinit {
if let pid = process?.processIdentifier, pid > 0 {
Darwin.kill(-pid, SIGTERM)
}
process?.terminate()
readSource?.cancel()
if masterFD >= 0 { close(masterFD) }
@@ -11,6 +11,9 @@ struct EmbeddedTerminalView: View {
@State private var input = ""
@State private var secureInput = false
@State private var checking = false
@State private var hostKeyInfo: HostKeyInfo?
@State private var hostKeyChange = false
@State private var showingHostKey = false
var body: some View {
VStack(spacing: 0) {
@@ -98,6 +101,18 @@ struct EmbeddedTerminalView: View {
connect() // Auto-Connect beim Öffnen des Tabs
}
}
.sheet(isPresented: $showingHostKey) {
if let info = hostKeyInfo {
HostKeySheet(info: info, isChange: hostKeyChange,
onAccept: acceptHostKey,
onCancel: {
showingHostKey = false
checking = false
hostKeyInfo = nil
term.fail("Host-Key nicht akzeptiert — Verbindung abgebrochen.")
})
}
}
}
func connect() {
@@ -105,16 +120,47 @@ struct EmbeddedTerminalView: View {
checking = true
TCPCheck.check(host: profile.host, port: profile.port) { message in
DispatchQueue.main.async {
checking = false
if let message {
checking = false
term.fail("Vorab-Check: \(message)")
} else {
return
}
// Host-Key vorab per keyscan prüfen (Yes/No-Prompt käme ohne Ctty nicht an)
let hk = HostKeyService.status(host: profile.host, port: profile.port)
switch hk {
case .known, .unreachable:
checking = false
term.start()
case .unknown(let info):
hostKeyInfo = info
hostKeyChange = false
showingHostKey = true
case .changed(let info):
hostKeyInfo = info
hostKeyChange = true
showingHostKey = true
}
}
}
}
func acceptHostKey() {
guard let info = hostKeyInfo else { return }
showingHostKey = false
if hostKeyChange {
_ = HostKeyService.revoke(host: profile.host, port: profile.port)
}
if HostKeyService.accept(info) {
checking = false
term.note("Host-Key akzeptiert (\(info.keyType), \(info.fingerprintSHA256.prefix(19))…).")
term.start()
} else {
checking = false
term.fail("Host-Key konnte nicht in known_hosts gespeichert werden.")
}
hostKeyInfo = nil
}
func diagnose() {
guard !checking else { return }
checking = true
@@ -0,0 +1,57 @@
import SwiftUI
/// Popup bei unbekanntem/geändertem Host-Key: Fingerprint prüfen, dann
/// akzeptieren (→ known_hosts + verbinden) oder abbrechen.
struct HostKeySheet: View {
var info: HostKeyInfo
var isChange: Bool
var onAccept: () -> Void
var onCancel: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack(spacing: 10) {
Image(systemName: isChange ? "exclamationmark.octagon.fill" : "key.fill")
.font(.title)
.foregroundStyle(isChange ? Dracula.red : Dracula.orange)
VStack(alignment: .leading) {
Text(isChange ? "Host-Key GEÄNDERT" : "Neuer Host-Key")
.font(.headline)
Text("\(info.host):\(info.port) · \(info.keyType)")
.font(.subheadline).foregroundStyle(.secondary)
}
}
if isChange {
Text("Warnung: Der gespeicherte Schlüssel passt NICHT zum Server. Das kann ein neu aufgesetzter Server sein — oder ein Angriff (MITM). Nur fortfahren, wenn du die Änderung erwartest!")
.font(.callout).foregroundStyle(Dracula.red)
} else {
Text("Erstverbindung: Dieser Server ist noch unbekannt. Fingerprint prüfen (z. B. mit dem Server-Admin oder einer Terminal-Verbindung vergleichen), dann akzeptieren.")
.font(.callout).foregroundStyle(.secondary)
}
GroupBox("SHA256-Fingerprint") {
Text(info.fingerprintSHA256)
.font(.system(.body, design: .monospaced))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
GroupBox("MD5-Fingerprint") {
Text(info.fingerprintMD5)
.font(.system(.callout, design: .monospaced))
.foregroundStyle(.secondary)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
HStack {
Button("Abbrechen", role: .cancel, action: onCancel)
Spacer()
Button(isChange ? "Trotzdem ersetzen & verbinden" : "Akzeptieren & verbinden", action: onAccept)
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 480)
}
}