Files
RouterOS/RouterOSAssistant/Core/Networking/SSHTransport.swift
T
KayandClaude Sonnet 5 c9ecd3a0a9 M9/M10: Einfach/Experte-Modus + Experte-Tab (generischer RouterOS-Zugriff)
M9: Einrichten-Wizard bekommt einen Einfach/Experte-Modusschalter
(ModeStepView). Einfach überspringt VLAN, erlaubt nur ein LAN-Netzwerk
ohne Isolation, Firewall-Grundschutz fest an.

M10: neuer "Experte"-Tab mit generischem Motor (RouterOSMenuItem,
RouterOSCommand.remove, ConnectionService.fetchMenuItems, freies
"eigener Menüpfad"-Feld) plus kuratierten Formularen mit Tooltips
(RouterOSSchemaCatalog) für Firewall/NAT/Mangle/Raw/Adress-Listen,
Interfaces, IP, VPN, WLAN, Queues, System, Werkzeuge.

Live gegen einen hEX-Testrouter verifiziert (erst per SSH, dann vom
Nutzer selbst in der App), dabei 7 reale Bugs gefunden und gefixt —
der wichtigste: RouterOS' SSH-CLI gibt bei fehlgeschlagenen Befehlen
Exit-Code 0 zurück, wodurch apply() app-weit Fehler verschluckte statt
sie zu melden. Danach ergänzt: Bestätigungsdialog vor Anlegen/Ändern
+ Auto-Backup vor dem ersten Experte-Tab-Schreibvorgang je Sitzung
(Angleichung an den Wizard), sowie ein Dauer-Editor (Tage/Std/Min/Sek)
für Lease-/Ablaufzeit-Felder statt Freitext.

Details zu allen Bugs/Fixes: HANDOFF.md, CHATLOG.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EW3r6rW1xCf6UT5jNvt6rn
2026-09-14 00:03:50 +02:00

157 lines
7.4 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)
}
/// RouterOS 7.24.2 (verified live against a hEX test device) does *not* include `.id` in
/// `print terse` CLI output, unlike REST's JSON, which always does — every field parses
/// fine, but every item's `id` would otherwise fall back to a synthetic, unusable "row-N".
/// `:put [<menuPath> find]` returns the real internal IDs (e.g. "*C;*1;*2") in the same
/// order as `print terse` (also verified live: position 0 → first ID, position 1 → second),
/// so they're overlaid onto the parsed items by position here.
func fetchMenuItems(menuPath: String, restPath: String) async throws -> [RouterOSMenuItem] {
let output: String
do {
output = try await run("\(menuPath) print without-paging terse")
} catch RouterOSError.invalidResponse(let detail) where detail.contains("bad parameter terse") {
// Singleton menu (e.g. "/ip dns", "/system identity") — no list, no "terse" support.
let plain = try await run("\(menuPath) print without-paging")
return [RouterOSCliParser.parseSingletonItem(plain)]
}
var items = RouterOSCliParser.parseGenericItems(output)
let idOutput = try await run(":put [\(menuPath) find]")
let ids = idOutput
.trimmingCharacters(in: .whitespacesAndNewlines)
.split(separator: ";")
.map(String.init)
for index in items.indices where index < ids.count {
items[index] = RouterOSMenuItem(id: ids[index], fields: items[index].fields)
}
return items
}
/// RouterOS' SSH CLI exits 0 even when a command fails — confirmed live: both
/// `/ip dhcp-server add ...` on an interface that already has one ("failure: server or
/// relay with such interface already exists") and an invalid action ("syntax error (line 1
/// column 46)") returned exit status 0, meaning `run()`'s exit-code check alone silently
/// treats every such failure as success. A mutating command (add/set/remove) is always
/// silent on success in every case observed live this session (15+ menu families) — so any
/// non-empty output here is treated as the error text, since there is no more reliable
/// signal available over this transport.
func apply(_ command: RouterOSCommand) async throws {
let output = try await run(command.cliLine)
let trimmed = output.trimmingCharacters(in: .whitespacesAndNewlines)
guard trimmed.isEmpty else {
throw RouterOSError.invalidResponse(trimmed)
}
}
/// 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))
}
}
}