Repository Public
1import Foundation23/// An extra `-o Key=Value` option requested by the caller; must pass the builder's allowlist.4public struct SSHOption: Sendable, Hashable, Codable {5 public var key: String6 public var value: String78 public init(_ key: String, _ value: String) {9 self.key = key10 self.value = value11 }12}1314/// A ready-to-spawn command: executable path plus argv. Never run it through a shell.15public struct SSHCommand: Sendable, Hashable, Codable {16 public var executable: String17 public var arguments: [String]1819 public init(executable: String, arguments: [String]) {20 self.executable = executable21 self.arguments = arguments22 }2324 /// The command as a POSIX-shell-quoted string, for display or copy/paste.25 public var displayString: String {26 ([executable] + arguments).map(SSHCommandBuilder.shellQuote).joined(separator: " ")27 }28}2930/// Why ``SSHCommandBuilder`` refused to build a command.31public enum SSHCommandError: Error, Sendable, Equatable, LocalizedError {32 /// The profile field a validation error refers to.33 public enum Field: String, Sendable, Equatable {34 case host, user, proxyJump, option35 }3637 case emptyValue(Field)38 case leadingDash(Field)39 case invalidCharacters(Field)40 case portOutOfRange(Int)41 /// The option would weaken host key verification, change authentication behaviour or run a command.42 case forbiddenOption(String)43 /// The option is not on the allowlist.44 case optionNotAllowed(String)45 case invalidOptionValue(key: String, value: String)4647 public var errorDescription: String? {48 switch self {49 case .emptyValue(let field): return "The \(field.rawValue) value is empty."50 case .leadingDash(let field): return "The \(field.rawValue) value must not start with “-”."51 case .invalidCharacters(let field): return "The \(field.rawValue) value contains characters that are not allowed."52 case .portOutOfRange(let port): return "Port \(port) is outside 1–65535."53 case .forbiddenOption(let key): return "The SSH option “\(key)” is never allowed."54 case .optionNotAllowed(let key): return "The SSH option “\(key)” is not on the allowlist."55 case .invalidOptionValue(let key, let value): return "“\(value)” is not a valid value for the SSH option “\(key)”."56 }57 }58}5960/// Builds argv arrays for the system `/usr/bin/ssh` and `/usr/bin/sftp`.61///62/// Every emitted argument is validated; host key verification options are never emitted.63public enum SSHCommandBuilder {64 public static let sshPath = "/usr/bin/ssh"65 public static let sftpPath = "/usr/bin/sftp"6667 /// Canonical names of the only `-o` options a caller may add.68 public static let allowedOptionKeys: [String] = [69 "AddressFamily", "Compression", "ConnectTimeout", "ConnectionAttempts", "ForwardAgent",70 "RequestTTY", "ServerAliveCountMax", "ServerAliveInterval", "TCPKeepAlive",71 ]7273 /// Options rejected with ``SSHCommandError/forbiddenOption(_:)`` (lowercased).74 static let forbiddenOptionKeys: Set<String> = [75 "stricthostkeychecking", "userknownhostsfile", "globalknownhostsfile", "knownhostscommand",76 "checkhostip", "verifyhostkeydns", "hostkeyalias", "nohostauthenticationforlocalhost",77 "updatehostkeys", "hostkeyalgorithms", "batchmode", "passwordauthentication",78 "kbdinteractiveauthentication", "numberofpasswordprompts", "proxycommand", "localcommand",79 "permitlocalcommand", "remotecommand", "include", "identityfile", "sendenv", "setenv",80 ]8182 /// `ssh [-o K=V]… [-p port] [-l user] [-J jump] -- host`.83 ///84 /// For `.sshConfig` profiles only the alias (and extra options) is emitted, so OpenSSH resolves85 /// user, port and jump hosts from the config itself.86 public static func sshCommand(for profile: SSHHostProfile, extraOptions: [SSHOption] = []) throws -> SSHCommand {87 try command(executable: sshPath, portFlag: "-p", userArguments: { ["-l", $0] }, profile: profile, extraOptions: extraOptions)88 }8990 /// `sftp [-o K=V]… [-P port] [-o User=user] [-J jump] -- host`.91 public static func sftpCommand(for profile: SSHHostProfile, extraOptions: [SSHOption] = []) throws -> SSHCommand {92 try command(executable: sftpPath, portFlag: "-P", userArguments: { ["-o", "User=\($0)"] }, profile: profile, extraOptions: extraOptions)93 }9495 /// Quotes one argument for a POSIX shell (single quotes; safe words are left bare).96 public static func shellQuote(_ argument: String) -> String {97 let safe = !argument.isEmpty && argument.unicodeScalars.allSatisfy {98 isASCIIAlphanumeric($0) || "_@%+=:,./-".unicodeScalars.contains($0)99 }100 return safe ? argument : "'" + argument.replacingOccurrences(of: "'", with: "'\\''") + "'"101 }102103 /// Validates a host name, IP address or config alias (ASCII letters, digits, `.`, `-`, `_`, `:`).104 public static func validateHost(_ host: String) throws {105 try validate(host, field: .host, extra: "._-:")106 guard host.count <= 255 else { throw SSHCommandError.invalidCharacters(.host) }107 }108109 /// Validates a login name (ASCII letters, digits, `.`, `-`, `_`, `@`, `+`).110 public static func validateUser(_ user: String) throws {111 try validate(user, field: .user, extra: "._-@+")112 }113114 /// Validates a TCP port.115 public static func validatePort(_ port: Int) throws {116 guard (1...65535).contains(port) else { throw SSHCommandError.portOutOfRange(port) }117 }118119 /// Validates a `ProxyJump` value: `none`, or comma-separated `[user@]host[:port]` hops.120 public static func validateProxyJump(_ value: String) throws {121 let field = SSHCommandError.Field.proxyJump122 try validate(value, field: field, extra: "._-:@+,[]")123 if value == "none" { return }124 for hop in value.split(separator: ",", omittingEmptySubsequences: false) {125 var rest = hop126 if let at = rest.lastIndex(of: "@") {127 try validate(String(rest[..<at]), field: field, extra: "._-+@")128 rest = rest[rest.index(after: at)...]129 }130 var portText: Substring?131 let hostText: Substring132 if rest.hasPrefix("[") {133 guard let close = rest.firstIndex(of: "]") else { throw SSHCommandError.invalidCharacters(field) }134 hostText = rest[rest.index(after: rest.startIndex)..<close]135 let tail = rest[rest.index(after: close)...]136 if !tail.isEmpty {137 guard tail.hasPrefix(":") else { throw SSHCommandError.invalidCharacters(field) }138 portText = tail.dropFirst()139 }140 try validate(String(hostText), field: field, extra: "._-:")141 } else {142 let parts = rest.split(separator: ":", omittingEmptySubsequences: false)143 guard parts.count <= 2 else { throw SSHCommandError.invalidCharacters(field) }144 hostText = parts[0]145 if parts.count == 2 { portText = parts[1] }146 try validate(String(hostText), field: field, extra: "._-")147 }148 if let portText {149 guard isDigits(String(portText)), let port = Int(portText) else {150 throw SSHCommandError.invalidCharacters(field)151 }152 try validatePort(port)153 }154 }155 }156157 // MARK: - Internals158159 private static func command(160 executable: String,161 portFlag: String,162 userArguments: (String) -> [String],163 profile: SSHHostProfile,164 extraOptions: [SSHOption]165 ) throws -> SSHCommand {166 try validateHost(profile.host)167 var arguments: [String] = []168 for option in extraOptions {169 arguments += ["-o", try validatedOption(option)]170 }171 if profile.source == .manual {172 if let port = profile.port {173 try validatePort(port)174 arguments += [portFlag, String(port)]175 }176 if let user = profile.user {177 try validateUser(user)178 arguments += userArguments(user)179 }180 if let jump = profile.proxyJump {181 try validateProxyJump(jump)182 arguments += ["-J", jump]183 }184 }185 arguments += ["--", profile.host]186 return SSHCommand(executable: executable, arguments: arguments)187 }188189 /// Returns the canonical `Key=Value` for an allowlisted option, or throws.190 static func validatedOption(_ option: SSHOption) throws -> String {191 let key = option.key.lowercased()192 let value = option.value193 if forbiddenOptionKeys.contains(key) { throw SSHCommandError.forbiddenOption(option.key) }194 func oneOf(_ choices: [String]) -> Bool { choices.contains(value.lowercased()) }195 func integer(_ range: ClosedRange<Int>) -> Bool {196 guard isDigits(value), let number = Int(value) else { return false }197 return range.contains(number)198 }199 let canonical: String200 let valid: Bool201 switch key {202 case "connecttimeout": (canonical, valid) = ("ConnectTimeout", integer(1...3600))203 case "connectionattempts": (canonical, valid) = ("ConnectionAttempts", integer(1...10))204 case "serveraliveinterval": (canonical, valid) = ("ServerAliveInterval", integer(0...3600))205 case "serveralivecountmax": (canonical, valid) = ("ServerAliveCountMax", integer(1...100))206 case "forwardagent": (canonical, valid) = ("ForwardAgent", oneOf(["yes", "no"]))207 case "requesttty": (canonical, valid) = ("RequestTTY", oneOf(["yes", "no", "force", "auto"]))208 case "compression": (canonical, valid) = ("Compression", oneOf(["yes", "no"]))209 case "tcpkeepalive": (canonical, valid) = ("TCPKeepAlive", oneOf(["yes", "no"]))210 case "addressfamily": (canonical, valid) = ("AddressFamily", oneOf(["any", "inet", "inet6"]))211 default: throw SSHCommandError.optionNotAllowed(option.key)212 }213 guard valid else { throw SSHCommandError.invalidOptionValue(key: canonical, value: value) }214 return "\(canonical)=\(value.lowercased())"215 }216217 private static func validate(_ value: String, field: SSHCommandError.Field, extra: String) throws {218 guard !value.isEmpty else { throw SSHCommandError.emptyValue(field) }219 guard !value.hasPrefix("-") else { throw SSHCommandError.leadingDash(field) }220 let allowed = extra.unicodeScalars221 guard value.unicodeScalars.allSatisfy({ isASCIIAlphanumeric($0) || allowed.contains($0) }) else {222 throw SSHCommandError.invalidCharacters(field)223 }224 }225226 private static func isASCIIAlphanumeric(_ scalar: Unicode.Scalar) -> Bool {227 switch scalar {228 case "a"..."z", "A"..."Z", "0"..."9": return true229 default: return false230 }231 }232233 private static func isDigits(_ text: String) -> Bool {234 !text.isEmpty && text.count <= 9 && text.unicodeScalars.allSatisfy { ("0"..."9").contains($0) }235 }236}237