Files
RouterOS/RouterOSAssistant/Core/Networking/SSHTransport.swift
T
KayandClaude Sonnet 5 13344c265e M7: SSH-Hostkey-TOFU (ersetzt .acceptAnything())
Größte offene Härtungslücke geschlossen: SSHTransport nutzte bisher
.acceptAnything() für Host-Key-Validierung, akzeptierte also jeden
Schlüssel ohne Prüfung -- ein Man-in-the-Middle im lokalen Netz wäre
unbemerkt geblieben. Jetzt Trust-on-first-use wie beim REST-Zertifikat:

- SSHHostKeyFingerprint: SHA256 über NIOSSHPublicKey.write(to:) (die
  SSH-Wire-Format-Bytes des Schlüssels) -- exakt die Bytes, die auch
  OpenSSH für seine SHA256:-Fingerabdrücke hasht. Per Unit-Test gegen
  einen echten ssh-keygen-erzeugten Testschlüssel kreuzgeprüft
  (SHA256:Hllxv6LLoHl2XTIXGGjUYJHbPFoH2F7iMrR74C5J95g), nicht geraten.
- SSHHostKeyTrustStore: UserDefaults-Persistenz pro Host, Pendant zu
  CertificateTrustStore.
- SSHTransport conformt jetzt selbst zu NIOSSHClientServerAuthentication-
  Delegate (wie RestTransport zu URLSessionDelegate) und übergibt sich
  selbst als .custom(self) Host-Key-Validator.
- ConnectionService: neuer State .needsSSHHostKeyConfirmation, eigener
  Bestätigungs-Retry-Pfad (trustCurrentSSHHostKeyAndRetry), analog zum
  bestehenden Zertifikat-Flow.
- ConnectView: zweiter Bestätigungsdialog mit Warnhinweis, dass ein
  geänderter Fingerabdruck bei zuvor schon verbundenen Routern auf ein
  manipuliertes Netzwerk hindeuten könnte.

BackupService/FactoryResetService bekommen die TOFU-Prüfung automatisch
mit (SSHTransport-Default-Parameter, gleicher UserDefaults-Speicher),
ohne eigene Bestätigungs-UI -- in der Praxis unkritisch, da der
Verbinden-Tab das Vertrauen immer zuerst herstellt.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HReLXMbmPvtQ23p1iWiJNW
2026-09-13 00:40:26 +02:00

117 lines
5.0 KiB
Swift

import Foundation
import Citadel
import NIOCore
import NIOSSH
/// SSH+CLI transport fallback for RouterOS devices/firmware without the REST API (pre-7.1).
final class SSHTransport: RouterOSTransport {
let kind: RouterOSTransportKind = .ssh
private let credentials: RouterOSCredentials
private let hostKeyTrust: SSHHostKeyTrustStore
private var client: SSHClient?
init(credentials: RouterOSCredentials, hostKeyTrust: SSHHostKeyTrustStore = SSHHostKeyTrustStore()) {
self.credentials = credentials
self.hostKeyTrust = hostKeyTrust
}
func connect() async throws {
do {
client = try await SSHClient.connect(
host: credentials.host,
port: credentials.sshPort,
authenticationMethod: .passwordBased(username: credentials.username, password: credentials.password),
hostKeyValidator: .custom(self),
reconnect: .never,
// RouterOS' SSH server typically only offers legacy algorithms
// (diffie-hellman-group14-sha1 key exchange, RSA host keys) that
// Citadel's defaults don't include — `.all` adds them.
algorithms: .all
)
} catch let error as RouterOSError {
throw error
} catch {
// NIOSSHError's `.localizedDescription` is a useless generic NSError-bridged string
// ("The operation couldn't be completed."); its real diagnostics only surface via
// CustomStringConvertible, which `String(describing:)` picks up.
throw RouterOSError.transportUnavailable("SSH-Verbindung fehlgeschlagen: \(String(describing: error))")
}
}
func fetchDeviceInfo() async throws -> RouterDeviceInfo {
let output = try await run("/system resource print without-paging")
return RouterOSCliParser.parseDeviceInfo(output)
}
func fetchInterfaces() async throws -> [NetworkInterface] {
let output = try await run("/interface print without-paging terse")
return RouterOSCliParser.parseInterfaces(output)
}
func disconnect() async {
try? await client?.close()
client = nil
}
/// Full human-readable config export (`/export terse`), used for local backups.
func exportConfiguration() async throws -> String {
try await run("/export terse")
}
func fetchFirewallRuleCounts() async throws -> FirewallRuleCounts {
let filterOutput = try await run("/ip firewall filter print count-only")
let natOutput = try await run("/ip firewall nat print count-only")
let filterCount = Int(filterOutput.trimmingCharacters(in: .whitespacesAndNewlines)) ?? 0
let natCount = Int(natOutput.trimmingCharacters(in: .whitespacesAndNewlines)) ?? 0
return FirewallRuleCounts(filterRuleCount: filterCount, natRuleCount: natCount)
}
func apply(_ command: RouterOSCommand) async throws {
_ = try await run(command.cliLine)
}
/// Restores RouterOS' own vendor-default configuration and reboots the device. See
/// FactoryResetService for why this bypasses the RouterOSCommand add/set model entirely.
func resetToFactoryDefaults() async throws {
_ = try await run("/system reset-configuration no-defaults=no skip-backup=no")
}
/// Runs a command via `executeCommandStream` (not the simpler `executeCommand`), because
/// `executeCommand` discards whatever output it already collected the moment the command
/// exits non-zero — exactly the RouterOS error text we need. Collecting the stream ourselves
/// keeps that text available even when the command fails.
private func run(_ command: String) async throws -> String {
guard let client else { throw RouterOSError.notConnected }
var output = ""
do {
let stream = try await client.executeCommandStream(command)
for try await chunk in stream {
switch chunk {
case .stdout(let buffer), .stderr(let buffer):
output += String(buffer: buffer)
}
}
return output
} catch let failure as SSHClient.CommandFailed {
let detail = output.trimmingCharacters(in: .whitespacesAndNewlines)
throw RouterOSError.invalidResponse(
"RouterOS meldete Fehler (Exit-Code \(failure.exitCode)) für \"\(command)\""
+ (detail.isEmpty ? "" : ": \(detail)")
)
}
}
}
extension SSHTransport: NIOSSHClientServerAuthenticationDelegate {
func validateHostKey(hostKey: NIOSSHPublicKey, validationCompletePromise: EventLoopPromise<Void>) {
let fingerprint = SSHHostKeyFingerprint.sha256(of: hostKey)
if hostKeyTrust.isTrusted(host: credentials.host, fingerprint: fingerprint) {
validationCompletePromise.succeed(())
} else {
validationCompletePromise.fail(RouterOSError.untrustedSSHHostKey(fingerprint: fingerprint))
}
}
}