Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
feat(macos): add command line mode (proxybridge --profile) with hardened runner and installer launcher
AnoF-Cyber982d0182e09a
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 659e2b8..6a7fd98 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -412,7 +412,7 @@ The macOS tests are in [`MacOS/tests`](MacOS/tests) (see its `README.md` for detMacOS/tests/logic/run.sh```- They compile the matcher and DNS-map tests against the real extension sources and run them.+ They compile the matcher, DNS-map and command line tests (option parsing, profile loading) against the real sources and run them.2. **End-to-end tests** - run against your **signed** app with the system extension approved:1. Install your signed build, start it and approve the system extension and the network configuration when macOS asks.@@ -427,7 +427,9 @@ The macOS tests are in [`MacOS/tests`](MacOS/tests) (see its `README.md` for detThe suites cover routing (SOCKS5, HTTP, auth, DIRECT, BLOCK, UDP), proxy reply parsing, per-proxy hostnames, 300 parallel TCP connections and UDP flows (memory must stay flat), DNS, and a `leaks` check on the extension.-3. **Add a test** when you fix a bug or change behavior in the extension: extend `MacOS/tests/pbtest.py` / `servers.py`, or add a logic test in `MacOS/tests/logic`.+ If you change the **command line mode** (`CLIArguments.swift`, `CLIProfile.swift`, `CLIRunner.swift`), also run `python3 MacOS/tests/pbtest.py cli` with the ProxyBridge app **quit**.++3. **Add a test** when you fix a bug or change behavior in the extension or the CLI: extend `MacOS/tests/pbtest.py` / `servers.py`, or add a logic test in `MacOS/tests/logic`.**What your macOS pull request must show:** macOS version and chip (Apple silicon or Intel), Xcode version, how you signed the build, which test suites you ran and their result (paste the summary lines), and screenshots or logs for any GUI change.diff --git a/MacOS/ProxyBridge/ProxyBridge/CLIArguments.swift b/MacOS/ProxyBridge/ProxyBridge/CLIArguments.swiftnew file mode 100644index 0000000..d740b1e--- /dev/null+++ b/MacOS/ProxyBridge/ProxyBridge/CLIArguments.swift@@ -0,0 +1,103 @@+import Foundation++// command line options. the app is one executable: no options means the GUI, any+// of these options means the command line mode (see main.swift)+struct CLIOptions: Equatable {+ var help = false+ var version = false+ var update = false+ var listProfiles = false+ var profile: String? // a saved profile name, or "-" for standard input+ var verbose = 0 // 0 silent, 1 log messages, 2 connections, 3 both+}++enum CLIParseResult: Equatable {+ case run(CLIOptions)+ case failure(String)+}++enum CLIArguments {+ static let triggers: Set<String> = ["--cli", "--profile", "--verbose", "--version", "--update", "--list-profiles", "--help", "-h", "-?"]++ // true when the process was started for the command line. a normal launch from+ // Finder or the Dock passes none of these, so it stays the GUI+ static func isCLI(_ args: [String]) -> Bool {+ return args.dropFirst().contains { arg in+ triggers.contains(arg) || arg.hasPrefix("--profile=") || arg.hasPrefix("--verbose=")+ }+ }++ static func parse(_ args: [String]) -> CLIParseResult {+ var o = CLIOptions()+ var i = 1+ while i < args.count {+ var arg = args[i]+ var inline: String?+ if arg.hasPrefix("--"), let eq = arg.firstIndex(of: "=") {+ inline = String(arg[arg.index(after: eq)...])+ arg = String(arg[..<eq])+ }+ switch arg {+ case "--cli": break+ case "--help", "-h", "-?": o.help = true+ case "--version": o.version = true+ case "--update": o.update = true+ case "--list-profiles": o.listProfiles = true+ case "--profile", "--verbose":+ let value: String+ if let inline = inline {+ value = inline+ } else if i + 1 < args.count, !(args[i + 1].hasPrefix("--")) {+ i += 1+ value = args[i]+ } else {+ return .failure("\(arg) requires a value. Use --help.")+ }+ if arg == "--profile" {+ guard !value.isEmpty else { return .failure("--profile requires a profile name, or - to read from standard input.") }+ o.profile = value+ } else {+ guard let level = Int(value), (0...3).contains(level) else { return .failure("--verbose level must be 0-3.") }+ o.verbose = level+ }+ default:+ return .failure("Unknown option '\(args[i])'. Use --help.")+ }+ i += 1+ }+ // running needs a profile, the other options stand on their own+ if !(o.help || o.version || o.update || o.listProfiles) && o.profile == nil {+ return .failure("--profile is required. Use --help.")+ }+ return .run(o)+ }++ static let usage = """+ ProxyBridge CLI - run a ProxyBridge profile without the window.++ USAGE:+ proxybridge --profile <name | -> [options]++ OPTIONS:+ --profile <name> Run a profile saved in the ProxyBridge app (see --list-profiles)+ --profile - Read a profile (.pbprofile, exported from the app) from standard input+ --list-profiles List the saved profiles and exit+ --verbose <0-3> Logging: 0 silent (default), 1 log messages, 2 connections, 3 both+ --update Check for updates+ --version Show the version+ -h, --help Show this help++ EXAMPLES:+ proxybridge --list-profiles+ proxybridge --profile Default --verbose 2+ cat ~/work.pbprofile | proxybridge --profile - --verbose 3++ NOTES:+ - Press Ctrl+C to stop. The rules are cleared and the tunnel is stopped.+ - The system extension has to be approved once (System Settings > Privacy & Security).+ The first run waits for that approval.+ - Quit the ProxyBridge app first: only one of them can control the extension.+ - The app is sandboxed, so a file path cannot be read. Use a saved profile name,+ or pipe the file in with --profile -+ """+}diff --git a/MacOS/ProxyBridge/ProxyBridge/CLIProfile.swift b/MacOS/ProxyBridge/ProxyBridge/CLIProfile.swiftnew file mode 100644index 0000000..640b17c--- /dev/null+++ b/MacOS/ProxyBridge/ProxyBridge/CLIProfile.swift@@ -0,0 +1,137 @@+import Foundation++// a profile as the command line needs it. same layout the app writes when it exports a+// profile (and keeps per profile in its preferences), read without touching the GUI's state+struct CLIProxy: Decodable, Equatable {+ let id: String+ let name: String+ let type: String+ let host: String+ let port: Int+ let username: String?+ let password: String?+ let sendDomain: Bool++ enum CodingKeys: String, CodingKey { case id, name, type, host, port, username, password, sendDomain }++ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ id = try c.decode(String.self, forKey: .id)+ name = try c.decodeIfPresent(String.self, forKey: .name) ?? ""+ type = try c.decode(String.self, forKey: .type)+ host = try c.decode(String.self, forKey: .host)+ port = try c.decode(Int.self, forKey: .port)+ username = try c.decodeIfPresent(String.self, forKey: .username)+ password = try c.decodeIfPresent(String.self, forKey: .password)+ // proxies saved before the option existed behave like the app's default+ sendDomain = try c.decodeIfPresent(Bool.self, forKey: .sendDomain) ?? true+ }++ var label: String { "\(type.uppercased()) \(host):\(port)" }+}++struct CLIProfile {+ var name: String+ var proxies: [CLIProxy]+ var rules: [[String: Any]] // as saved by the app: processNames, targetHosts, targetPorts, protocol, action, enabled+}++enum CLIProfileError: Error, Equatable {+ case invalid(String)+ var message: String { if case .invalid(let m) = self { return m }; return "" }+}++enum CLIProfileLoader {+ // reads a preferences value, injected so tests don't need the real app's preferences+ typealias Reader = (String) -> Any?++ // the app's preferences, read by its bundle identifier so it also works when the+ // executable is started through a link or a launcher script+ static let appReader: Reader = { key in+ CFPreferencesCopyAppValue(key as CFString, "com.interceptsuite.ProxyBridge" as CFString)+ }++ // an exported .pbprofile (json)+ static func parse(json data: Data) throws -> CLIProfile {+ guard let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {+ throw CLIProfileError.invalid("The profile is not valid JSON.")+ }+ guard obj["proxyConfigs"] != nil || obj["proxyRules"] != nil else {+ throw CLIProfileError.invalid("This does not look like a ProxyBridge macOS profile (no proxyConfigs or proxyRules). Profiles exported from the Windows app use a different layout and can't be loaded here.")+ }+ let proxies = try decodeProxies(obj["proxyConfigs"] ?? [])+ let rules = obj["proxyRules"] as? [[String: Any]] ?? []+ return CLIProfile(name: (obj["name"] as? String) ?? "profile", proxies: proxies, rules: rules)+ }++ // a profile saved in the app. the active profile lives in the working keys+ // ("proxyConfigs", "proxyRules"), the others in "profile.<name>.*" snapshots+ static func saved(named name: String, read: Reader) throws -> CLIProfile {+ let names = read("profiles") as? [String] ?? []+ guard names.contains(name) else {+ let list = names.isEmpty ? "none saved yet" : names.joined(separator: ", ")+ throw CLIProfileError.invalid("No saved profile named '\(name)' (available: \(list)). Use --list-profiles.")+ }+ let active = read("activeProfile") as? String+ let configsKey = name == active ? "proxyConfigs" : "profile.\(name).proxyConfigs"+ let rulesKey = name == active ? "proxyRules" : "profile.\(name).proxyRules"+ let proxies = try decodeProxies(read(configsKey) ?? [])+ let rules = read(rulesKey) as? [[String: Any]] ?? []+ return CLIProfile(name: name, proxies: proxies, rules: rules)+ }++ static func savedNames(read: Reader) -> (names: [String], active: String?) {+ (read("profiles") as? [String] ?? [], read("activeProfile") as? String)+ }++ // the proxy list is stored as json Data (or an already decoded array in an export)+ private static func decodeProxies(_ value: Any) throws -> [CLIProxy] {+ let data: Data+ if let d = value as? Data { data = d }+ else if JSONSerialization.isValidJSONObject(value), let d = try? JSONSerialization.data(withJSONObject: value) { data = d }+ else { return [] }+ do { return try JSONDecoder().decode([CLIProxy].self, from: data) }+ catch { throw CLIProfileError.invalid("The proxy list in the profile could not be read: \(error.localizedDescription)") }+ }++ static let maxProxies = 100+ static let maxRules = 5000++ // problems that make the profile unusable. the extension would silently drop some of these+ // (a rule with an unknown protocol) or only fail later, per connection, so they stop the run+ static func errors(for profile: CLIProfile) -> [String] {+ var out: [String] = []+ if profile.proxies.count > maxProxies { out.append("the profile has \(profile.proxies.count) proxies, the limit is \(maxProxies)") }+ if profile.rules.count > maxRules { out.append("the profile has \(profile.rules.count) rules, the limit is \(maxRules)") }+ var ids = Set<String>()+ for p in profile.proxies {+ if !ids.insert(p.id).inserted { out.append("two proxies have the same id '\(p.id)'") }+ if p.host.trimmingCharacters(in: .whitespaces).isEmpty { out.append("a \(p.type) proxy has no host") }+ if !(1...65535).contains(p.port) { out.append("proxy \(p.host) has the port \(p.port), it must be 1-65535") }+ let type = p.type.lowercased()+ if type != "socks5" && type != "http" { out.append("proxy \(p.label) has the type '\(p.type)', it must be socks5 or http") }+ if type == "socks5", (p.username?.utf8.count ?? 0) > 255 || (p.password?.utf8.count ?? 0) > 255 {+ out.append("proxy \(p.label) has a username or password longer than 255 bytes, SOCKS5 can't carry that")+ }+ }+ for (i, rule) in profile.rules.enumerated() {+ let proto = rule["protocol"] as? String ?? "BOTH"+ if !["TCP", "UDP", "BOTH"].contains(proto) { out.append("rule \(i + 1) has the protocol '\(proto)', it must be TCP, UDP or BOTH") }+ }+ return out+ }++ // problems that don't stop the run but the user should know about+ static func warnings(for profile: CLIProfile) -> [String] {+ var out: [String] = []+ let ids = Set(profile.proxies.map { $0.id })+ for (i, rule) in profile.rules.enumerated() {+ let action = rule["action"] as? String ?? "DIRECT"+ if action != "DIRECT" && action != "BLOCK" && !ids.contains(action) {+ out.append("rule \(i + 1) sends traffic to a proxy that is not in this profile, it will go direct")+ }+ }+ if profile.rules.isEmpty { out.append("the profile has no rules, nothing will be redirected") }+ return out+ }+}diff --git a/MacOS/ProxyBridge/ProxyBridge/CLIRunner.swift b/MacOS/ProxyBridge/ProxyBridge/CLIRunner.swiftnew file mode 100644index 0000000..8ced693--- /dev/null+++ b/MacOS/ProxyBridge/ProxyBridge/CLIRunner.swift@@ -0,0 +1,415 @@+import Foundation+import AppKit+import NetworkExtension+import SystemExtensions++// the command line mode of the app: the same executable as the GUI, started with options+// (see main.swift). it does what the GUI does to get traffic redirected, without a window:+// activate the system extension, set up the tunnel, send the profile, and clean up on exit.+enum CLI {+ static let bundleIdentifier = "com.interceptsuite.ProxyBridge"+ static let extensionIdentifier = "com.interceptsuite.ProxyBridge.extension"+ static let maxProfileBytes = 4 * 1024 * 1024+ static var runner: CLIRunner?+ private static var lockDescriptor: Int32 = -1+ private static var outputClosed = false++ // prints a line. when the reader of our output went away (piped into `head`, closed+ // terminal) we stop cleanly instead of dying on SIGPIPE with the rules still active+ static func say(_ text: String) {+ guard !outputClosed else { return }+ if fputs(text + "\n", stdout) == EOF || fflush(stdout) != 0 {+ outputClosed = true+ runner?.stopFromOutside(reason: nil)+ }+ }++ static func warn(_ text: String) {+ FileHandle.standardError.write(Data(("warning: " + text + "\n").utf8))+ }++ static func fail(_ text: String, code: Int32 = 1) -> Never {+ FileHandle.standardError.write(Data(("ERROR: " + CLIText.lines(text) + "\n").utf8))+ exit(code)+ }++ // the version of the app this executable belongs to. falls back to the bundle that+ // holds the real executable in case the process was started through a link+ static func version() -> String {+ if let v = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { return v }+ if let exe = Bundle.main.executableURL?.resolvingSymlinksInPath() {+ let plist = exe.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Info.plist")+ if let d = NSDictionary(contentsOf: plist), let v = d["CFBundleShortVersionString"] as? String { return v }+ }+ return "unknown"+ }++ static func run(arguments: [String]) -> Never {+ // a closed pipe must not kill us: we want to clean up first (see say)+ signal(SIGPIPE, SIG_IGN)++ let options: CLIOptions+ switch CLIArguments.parse(arguments) {+ case .failure(let message): fail(message, code: 2)+ case .run(let o): options = o+ }++ if options.help { say(CLIArguments.usage); exit(0) }+ if options.version { say("ProxyBridge CLI \(version())"); exit(0) }+ if options.listProfiles { listProfiles(); exit(0) }+ if options.update { checkForUpdates() }++ guard let spec = options.profile else { fail("--profile is required. Use --help.", code: 2) }+ let profile: CLIProfile+ do { profile = try loadProfile(spec) } catch let e as CLIProfileError { fail(e.message) } catch { fail(error.localizedDescription) }++ let errors = CLIProfileLoader.errors(for: profile)+ if !errors.isEmpty { fail("The profile can't be used:\n - " + errors.map { CLIText.safe($0) }.joined(separator: "\n - ")) }++ // only one controller at a time: the GUI and the CLI would fight over the same tunnel+ if guiIsRunning() { fail("The ProxyBridge app is running. Quit it first, only one of them can control the extension at a time.") }+ guard takeLock() else { fail("Another ProxyBridge CLI is already running.") }++ for w in CLIProfileLoader.warnings(for: profile) { warn(CLIText.safe(w)) }+ let r = CLIRunner(profile: profile, verbose: options.verbose)+ runner = r+ r.start()+ RunLoop.main.run()+ exit(0)+ }++ private static func listProfiles() {+ let (names, active) = CLIProfileLoader.savedNames(read: CLIProfileLoader.appReader)+ if names.isEmpty { say("No saved profiles. Open the ProxyBridge app once to create the default one."); return }+ for n in names { say((n == active ? "* " : " ") + CLIText.safe(n)) }+ say("(* = the profile the app currently uses)")+ }++ // standard input, with a limit so a huge or endless input can't use all the memory+ private static func readStandardInput() throws -> Data {+ if isatty(STDIN_FILENO) != 0 {+ throw CLIProfileError.invalid("--profile - reads the profile from standard input, but standard input is the terminal. Pipe a file in: cat file.pbprofile | proxybridge --profile -")+ }+ var data = Data()+ while true {+ let chunk = FileHandle.standardInput.availableData+ if chunk.isEmpty { return data }+ data.append(chunk)+ if data.count > maxProfileBytes { throw CLIProfileError.invalid("The profile is larger than \(maxProfileBytes / 1024 / 1024) MB.") }+ }+ }++ private static func loadProfile(_ spec: String) throws -> CLIProfile {+ if spec == "-" { return try CLIProfileLoader.parse(json: readStandardInput()) }+ if spec.contains("/") || spec.hasSuffix(".pbprofile") {+ // the app is sandboxed, so it can only read files that are in its own container+ let path = (spec as NSString).expandingTildeInPath+ guard let data = FileManager.default.contents(atPath: path), data.count <= maxProfileBytes else {+ throw CLIProfileError.invalid("Can't read '\(spec)'. The app is sandboxed and can't open files elsewhere. Use a saved profile name, or pipe the file in: cat \(spec) | proxybridge --profile -")+ }+ return try CLIProfileLoader.parse(json: data)+ }+ return try CLIProfileLoader.saved(named: spec, read: CLIProfileLoader.appReader)+ }++ private static func checkForUpdates() -> Never {+ Task {+ let info = await UpdateService().checkForUpdates()+ if let error = info.error { fail(error) }+ say("Installed: \(info.currentVersion)")+ say("Latest: \(info.latestVersion)")+ if info.isUpdateAvailable {+ say("An update is available: \(CLIText.safe(info.downloadUrl ?? "see https://github.com/InterceptSuite/ProxyBridge/releases"))")+ if let notes = info.releaseNotesUrl { say("Release notes: \(CLIText.safe(notes))") }+ } else {+ say("You are up to date.")+ }+ exit(0)+ }+ RunLoop.main.run()+ exit(0)+ }++ private static func guiIsRunning() -> Bool {+ NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier).contains { $0.processIdentifier != getpid() }+ }++ // a second CLI would clear the first one's rules when it stops+ private static func takeLock() -> Bool {+ let path = NSTemporaryDirectory() + "proxybridge-cli.lock"+ lockDescriptor = open(path, O_CREAT | O_RDWR | O_NOFOLLOW, 0o600)+ return lockDescriptor >= 0 && flock(lockDescriptor, LOCK_EX | LOCK_NB) == 0+ }+}++final class CLIRunner: NSObject, OSSystemExtensionRequestDelegate {+ private let profile: CLIProfile+ private let verbose: Int+ private var manager: NETransparentProxyManager?+ private var session: NETunnelProviderSession?+ private var statusObserver: NSObjectProtocol?+ private var logTimer: Timer?+ private var polling = false+ private var signalSources: [DispatchSourceSignal] = []+ private var extensionActive = false+ private var started = false+ private var stopping = false+ private let clock: DateFormatter = {+ let f = DateFormatter()+ f.dateFormat = "HH:mm:ss"+ return f+ }()++ init(profile: CLIProfile, verbose: Int) {+ self.profile = profile+ self.verbose = verbose+ super.init()+ }++ func start() {+ installSignalHandlers()+ CLI.say("ProxyBridge CLI \(CLI.version())")+ CLI.say("Extension: activating...")+ let request = OSSystemExtensionRequest.activationRequest(forExtensionWithIdentifier: CLI.extensionIdentifier, queue: .main)+ request.delegate = self+ OSSystemExtensionManager.shared.submitRequest(request)+ // the first run can wait for a person to approve the extension, but not forever+ DispatchQueue.main.asyncAfter(deadline: .now() + 300) { [weak self] in+ if let self = self, !self.extensionActive { self.fail("Timed out waiting for the extension. Approve it in System Settings > Privacy & Security and run the command again.") }+ }+ }++ // MARK: - extension++ func request(_ request: OSSystemExtensionRequest, didFinishWithResult result: OSSystemExtensionRequest.Result) {+ DispatchQueue.main.async {+ // an update that macOS finishes after a restart is not running yet+ if result == .willCompleteAfterReboot {+ self.fail("macOS will finish activating the system extension after a restart. Restart your Mac and run the command again.")+ return+ }+ self.extensionActive = true+ CLI.say("Extension: active")+ self.configureTunnel()+ }+ }++ func request(_ request: OSSystemExtensionRequest, didFailWithError error: Error) {+ DispatchQueue.main.async { self.fail("The system extension could not be activated: \(error.localizedDescription)") }+ }++ func requestNeedsUserApproval(_ request: OSSystemExtensionRequest) {+ CLI.say("Extension: waiting for your approval. Open System Settings > Privacy & Security and click Allow, then enter your password. This is needed once.")+ }++ func request(_ request: OSSystemExtensionRequest, actionForReplacingExtension existing: OSSystemExtensionProperties, withExtension ext: OSSystemExtensionProperties) -> OSSystemExtensionRequest.ReplacementAction {+ return .replace+ }++ // MARK: - tunnel++ private func configureTunnel() {+ CLI.say("Network configuration: setting up (macOS asks you to allow it the first time)...")+ NETransparentProxyManager.loadAllFromPreferences { [weak self] managers, error in+ DispatchQueue.main.async {+ guard let self = self else { return }+ if let error = error { self.fail("Could not load the network configuration: \(error.localizedDescription)"); return }+ let manager = managers?.first ?? NETransparentProxyManager()+ manager.localizedDescription = "ProxyBridge Transparent Proxy"+ manager.isEnabled = true+ let proto = NETunnelProviderProtocol()+ proto.providerBundleIdentifier = CLI.extensionIdentifier+ proto.serverAddress = "ProxyBridge"+ manager.protocolConfiguration = proto+ manager.saveToPreferences { saveError in+ DispatchQueue.main.async {+ if let saveError = saveError { self.fail("Could not save the network configuration: \(saveError.localizedDescription)"); return }+ manager.loadFromPreferences { loadError in+ DispatchQueue.main.async {+ if let loadError = loadError { self.fail("Could not reload the network configuration: \(loadError.localizedDescription)"); return }+ self.startTunnel(manager)+ }+ }+ }+ }+ }+ }+ }++ private func startTunnel(_ manager: NETransparentProxyManager) {+ self.manager = manager+ guard let session = manager.connection as? NETunnelProviderSession else { fail("The tunnel session is not available."); return }+ self.session = session++ // watch the tunnel for as long as we run: it connects once, and if something else stops it+ // later (the app being opened, the extension crashing) nothing is redirected any more and+ // the user has to be told instead of being left with a CLI that looks fine+ statusObserver = NotificationCenter.default.addObserver(forName: .NEVPNStatusDidChange, object: session, queue: .main) { [weak self] _ in+ guard let self = self else { return }+ switch session.status {+ case .connected:+ if !self.started { self.applyProfile() }+ case .disconnected, .invalid:+ if self.started && !self.stopping {+ self.fail("The tunnel was stopped by something else (is the ProxyBridge app running?). Nothing is being redirected any more.")+ }+ default: break+ }+ }++ if session.status == .connected { applyProfile(); return }+ do { try session.startTunnel() } catch { fail("Could not start the tunnel: \(error.localizedDescription)"); return }+ DispatchQueue.main.asyncAfter(deadline: .now() + 30) { [weak self] in+ if let self = self, !self.started { self.fail("The tunnel did not start in 30 seconds.") }+ }+ }++ // MARK: - profile++ private func applyProfile() {+ guard !started, !stopping, let session = session else { return }+ started = true+ enableDNSProxy()++ // same messages, same order as the GUI: logging, proxies, then the rules in one step+ send(["action": "setTrafficLogging", "enabled": verbose >= 2]) { _ in+ self.send(["action": "setProxyConfigs", "configs": self.proxyMessages()]) { _ in+ RuleManager.applyRules(session: session, rules: self.profile.rules) { _, count in+ CLI.say("Profile \"\(CLIText.safe(self.profile.name))\": \(self.profile.proxies.count) proxies, \(count) rules applied")+ // the extension skips a rule it can't read, don't let that pass silently+ if count < self.profile.rules.count { CLI.warn("\(self.profile.rules.count - count) rule(s) were rejected by the extension (invalid fields)") }+ CLI.say("Redirecting traffic. Press Ctrl+C to stop.")+ if self.verbose > 0 { self.startLogPolling() }+ }+ }+ }+ }++ private func proxyMessages() -> [[String: Any]] {+ profile.proxies.map { p in+ var dict: [String: Any] = ["id": p.id, "proxyType": p.type, "proxyHost": p.host, "proxyPort": p.port, "sendDomainToProxy": p.sendDomain]+ if let u = p.username { dict["proxyUsername"] = u }+ if let pw = p.password { dict["proxyPassword"] = pw }+ return dict+ }+ }++ // the DNS provider is what makes domain rules and hostnames work, the GUI turns it on too.+ // when it is already set up for this extension it is left alone, saving it again on every+ // start is a needless system configuration change+ private func enableDNSProxy() {+ let dns = NEDNSProxyManager.shared()+ dns.loadFromPreferences { loadError in+ if loadError == nil, dns.isEnabled, dns.providerProtocol?.providerBundleIdentifier == CLI.extensionIdentifier { return }+ let proto = NEDNSProxyProviderProtocol()+ proto.providerBundleIdentifier = CLI.extensionIdentifier+ dns.providerProtocol = proto+ dns.localizedDescription = "ProxyBridge DNS"+ dns.isEnabled = true+ dns.saveToPreferences { error in+ if let error = error { CLI.warn("DNS proxy setup failed: \(error.localizedDescription)") }+ }+ }+ }++ private func send(_ message: [String: Any], completion: (([String: Any]?) -> Void)? = nil) {+ guard let session = session, let data = try? JSONSerialization.data(withJSONObject: message) else { completion?(nil); return }+ do {+ try session.sendProviderMessage(data) { response in+ let object = response.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]+ DispatchQueue.main.async { completion?(object) }+ }+ } catch {+ DispatchQueue.main.async { completion?(nil) }+ }+ }++ // MARK: - logs++ private func startLogPolling() {+ logTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in self?.pollLogs() }+ }++ // the extension answers with at most 100 entries and keeps 500, so when a burst fills an+ // answer, ask again straight away instead of waiting a second and losing the oldest lines.+ // never two requests at once.+ private func pollLogs() {+ guard !polling, !stopping, let session = session, let data = try? JSONSerialization.data(withJSONObject: ["action": "getLogs"]) else { return }+ polling = true+ do {+ try session.sendProviderMessage(data) { response in+ DispatchQueue.main.async {+ self.polling = false+ guard let response = response, let logs = (try? JSONSerialization.jsonObject(with: response)) as? [[String: String]] else { return }+ self.print(logs)+ if logs.count >= 100 { self.pollLogs() }+ }+ }+ } catch {+ polling = false+ }+ }++ // one write per answer, not one per line. everything in an entry came from outside (process+ // names, DNS names, a proxy's reply), so it is made safe to show in a terminal first+ private func print(_ logs: [[String: String]]) {+ let now = clock.string(from: Date())+ var lines: [String] = []+ for log in logs {+ if log["type"] == "connection" {+ guard verbose >= 2 else { continue }+ lines.append("[\(now)] \(CLIText.safe(log["protocol"] ?? "?")) \(CLIText.safe(log["process"] ?? "?")) -> \(CLIText.safe(log["destination"] ?? "?")):\(CLIText.safe(log["port"] ?? "?")) via \(CLIText.safe(log["proxy"] ?? "?"))")+ } else {+ guard verbose == 1 || verbose == 3 else { continue }+ lines.append("[\(now)] [\(CLIText.safe(log["level"] ?? "INFO"))] \(CLIText.safe(log["message"] ?? ""))")+ }+ }+ if !lines.isEmpty { CLI.say(lines.joined(separator: "\n")) }+ }++ // MARK: - stopping++ // Ctrl+C, kill, and closing the Terminal window (SIGHUP) all clean up. SIGKILL can't be caught+ private func installSignalHandlers() {+ for sig in [SIGINT, SIGTERM, SIGHUP] {+ signal(sig, SIG_IGN)+ let source = DispatchSource.makeSignalSource(signal: sig, queue: .main)+ source.setEventHandler { [weak self] in self?.stop(code: 0) }+ source.resume()+ signalSources.append(source)+ }+ }++ // called when our output went away+ func stopFromOutside(reason: String?) {+ DispatchQueue.main.async { self.stop(code: 0) }+ }++ private func fail(_ message: String) {+ FileHandle.standardError.write(Data(("ERROR: " + CLIText.lines(message) + "\n").utf8))+ stop(code: 1)+ }++ // clear the rules and the proxies (so nothing keeps redirecting to a stopped tool), then stop the tunnel+ private func stop(code: Int32) {+ guard !stopping else { return }+ stopping = true+ logTimer?.invalidate()+ guard let session = session else { exit(code) }+ if !started {+ // stopped while still starting: the tunnel may be up already, don't leave it running+ session.stopTunnel()+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { exit(code) }+ return+ }+ CLI.say("Stopping...")+ DispatchQueue.main.asyncAfter(deadline: .now() + 5) { exit(code) } // never hang if the extension doesn't answer+ RuleManager.clearRules(session: session) { _, _ in+ self.send(["action": "clearConfig"]) { _ in+ session.stopTunnel()+ CLI.say("Rules cleared, tunnel stopped.")+ exit(code)+ }+ }+ }+}diff --git a/MacOS/ProxyBridge/ProxyBridge/CLIText.swift b/MacOS/ProxyBridge/ProxyBridge/CLIText.swiftnew file mode 100644index 0000000..3390fb3--- /dev/null+++ b/MacOS/ProxyBridge/ProxyBridge/CLIText.swift@@ -0,0 +1,20 @@+import Foundation++enum CLIText {+ // text that comes from outside (profile names, DNS names, a proxy's error reply, process names)+ // is printed to a terminal. control characters, including the escape that starts terminal+ // escape sequences, are replaced so such text can't rewrite what the user sees+ static func safe(_ text: String) -> String {+ var out = String.UnicodeScalarView()+ for scalar in text.unicodeScalars {+ if scalar.value < 0x20 || (0x7F...0x9F).contains(scalar.value) { out.append("?") } else { out.append(scalar) }+ }+ return String(out)+ }++ // for messages that are built with line breaks on purpose: each line is made safe,+ // the breaks stay (parts that came from outside are made safe before they are joined)+ static func lines(_ text: String) -> String {+ text.split(separator: "\n", omittingEmptySubsequences: false).map { safe(String($0)) }.joined(separator: "\n")+ }+}diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeGUI.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeGUI.swiftindex 81e78e3..335a134 100644--- a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeGUI.swift+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeGUI.swift@@ -26,7 +26,7 @@ enum LoginItem {}}-@main+// no @main here, main.swift starts this for a normal launch (and the command line mode otherwise)struct ProxyBridgeGUIApp: App {@StateObject private var viewModel = ProxyBridgeViewModel()@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegatediff --git a/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift b/MacOS/ProxyBridge/ProxyBridge/RuleManager.swiftindex d8f5441..47d4849 100644--- a/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift+++ b/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift@@ -93,6 +93,16 @@ struct RuleManager {completion: @escaping (Bool, Int) -> Void) {let rules = UserDefaults.standard.array(forKey: "proxyRules") as? [[String: Any]] ?? []+ applyRules(session: session, rules: rules, completion: completion)+ }++ // replaces the extension's rule list with these rules (as saved by the app). also used+ // by the command line, which has its rules in memory instead of in the preferences+ static func applyRules(+ session: NETunnelProviderSession,+ rules: [[String: Any]],+ completion: @escaping (Bool, Int) -> Void+ ) {let payload: [[String: Any]] = rules.map { rule in["processNames": rule["processNames"] as? String ?? "",diff --git a/MacOS/ProxyBridge/ProxyBridge/main.swift b/MacOS/ProxyBridge/ProxyBridge/main.swiftnew file mode 100644index 0000000..73acc40--- /dev/null+++ b/MacOS/ProxyBridge/ProxyBridge/main.swift@@ -0,0 +1,10 @@+import SwiftUI++// one executable, two modes. started with a command line option (--profile, --version, ...)+// it runs without a window (CLIRunner.swift). started normally, from Finder or the Dock,+// it is the app.+if CLIArguments.isCLI(CommandLine.arguments) {+ CLI.run(arguments: CommandLine.arguments)+} else {+ ProxyBridgeGUIApp.main()+}diff --git a/MacOS/ProxyBridge/build.sh b/MacOS/ProxyBridge/build.shindex 24ed30f..0e90f15 100755--- a/MacOS/ProxyBridge/build.sh+++ b/MacOS/ProxyBridge/build.sh@@ -59,9 +59,13 @@ echo "Creating installer package..."pkgbuild --analyze --root build/component build/component.plist/usr/libexec/PlistBuddy -c "Set :0:BundleIsRelocatable false" build/component.plist+# scripts/postinstall installs the `proxybridge` command (a launcher for the app's own executable).+# an installer script that is not executable is skipped silently, so check it here+[ -x "$SCRIPT_DIR/scripts/postinstall" ] || { echo "ERROR: scripts/postinstall is not executable (chmod +x)"; exit 1; }pkgbuild \--root build/component \--component-plist build/component.plist \+ --scripts "$SCRIPT_DIR/scripts" \--identifier com.interceptsuite.ProxyBridge \--version "$VERSION" \--install-location /Applications \diff --git a/MacOS/ProxyBridge/scripts/postinstall b/MacOS/ProxyBridge/scripts/postinstallnew file mode 100755index 0000000..e855e5e--- /dev/null+++ b/MacOS/ProxyBridge/scripts/postinstall@@ -0,0 +1,39 @@+#!/bin/sh+# Runs as root after the ProxyBridge package is installed. Installs the `proxybridge` command, a+# short launcher that starts the app's own executable in command line mode (there is no second+# binary). A failure here must never fail the installation of the app, so it always exits 0.+#+# Fixed paths on purpose: this runs as root, so nothing from the environment is trusted.+# (tests copy the script and replace these two lines)+APP_EXECUTABLE="/Applications/ProxyBridge.app/Contents/MacOS/ProxyBridge"+BIN_DIR="/usr/local/bin"++PATH=/usr/bin:/bin:/usr/sbin:/sbin+export PATH+umask 022+LINK="$BIN_DIR/proxybridge"++[ -x "$APP_EXECUTABLE" ] || exit 0++# never write through a link: a link planted in place of the folder or the command+# would make this root script overwrite whatever it points at+[ -L "$BIN_DIR" ] && exit 0+mkdir -p "$BIN_DIR" 2>/dev/null || exit 0+[ -L "$LINK" ] && rm -f "$LINK" 2>/dev/null++# write to a new private file, then move it into place in one step, so a running or+# half-written launcher is never seen+TMP="$(mktemp "$BIN_DIR/.proxybridge.XXXXXX" 2>/dev/null)" || exit 0+cat > "$TMP" <<LAUNCHER 2>/dev/null || { rm -f "$TMP"; exit 0; }+#!/bin/sh+# ProxyBridge command line, installed by the ProxyBridge package.+APP="$APP_EXECUTABLE"+if [ ! -x "\$APP" ]; then+ echo "ProxyBridge is not installed (expected \$APP)" >&2+ exit 1+fi+exec "\$APP" --cli "\$@"+LAUNCHER+chmod 755 "$TMP" 2>/dev/null+mv -f "$TMP" "$LINK" 2>/dev/null || rm -f "$TMP"+exit 0diff --git a/MacOS/README.md b/MacOS/README.mdindex f1fe828..d7dbf44 100644--- a/MacOS/README.md+++ b/MacOS/README.md@@ -12,6 +12,7 @@ ProxyBridge is a transparent proxy application for macOS that allows you to rout- [Proxy Rules](#proxy-rules)- [Exporting and Importing Rules](#exporting-and-importing-rules)- [Usage](#usage)+ - [Command Line (CLI)](#command-line-cli)- [Limitations](#limitations)- [Building from Source](#building-from-source)- [License](#license)@@ -356,6 +357,39 @@ Connection logs are available in the main window, showing:- **Help** - Check for updates and about information- **Quit** - Exit ProxyBridge+### Command Line (CLI)++ProxyBridge can run without a window, like the Windows CLI. There is **no second program**: the CLI is the same executable as the app, started with command line options. Started normally (Finder, Dock) it is the app.++The installer adds a short command, `proxybridge`, so it works from any folder in Terminal:++```bash+proxybridge --list-profiles # profiles saved in the app (* = the one the app uses)+proxybridge --profile Default --verbose 2 # run a saved profile, show connections+cat ~/work.pbprofile | proxybridge --profile - --verbose 3 # run a profile exported from the app+proxybridge --update # check for updates+proxybridge --version+```++If the command is not found, run the executable directly (it needs no setup): `/Applications/ProxyBridge.app/Contents/MacOS/ProxyBridge --cli --help`.++| Option | |+|--------|---|+| `--profile <name>` | Run a profile saved in the app |+| `--profile -` | Read a profile (`.pbprofile` exported from the app) from standard input |+| `--list-profiles` | List the saved profiles and exit |+| `--verbose <0-3>` | 0 silent (default), 1 log messages, 2 connections, 3 both |+| `--update` | Check for updates |+| `--version`, `-h` / `--help` | Show the version / the help |++It runs in the foreground until you press **Ctrl+C**, which clears the rules and stops the tunnel.++**Things to know**+- **The extension has to be approved once.** The first run asks macOS to activate the system extension and to allow the network configuration, and **waits** until you approve them in *System Settings > Privacy & Security*. After that (or on a Mac where your administrator pre-approved them) it starts without any prompt, and it shares the approval with the app. It cannot be approved over SSH on a Mac nobody has set up yet, the prompt appears on the Mac's screen.+- **Quit the app first.** Only one of the app and the CLI can control the extension at a time, so the CLI refuses to start while the app is running.+- **Profiles are read by name or from standard input**, because the app is sandboxed and can't open arbitrary file paths. A profile exported on Windows uses a different layout and can't be loaded here.+- The app must be installed in `/Applications` (macOS only activates the extension from there). The installer package creates the `proxybridge` command; it is a three-line launcher in `/usr/local/bin`, not another binary.+## Limitations### Apple Network Extension API Constraintsdiff --git a/MacOS/tests/README.md b/MacOS/tests/README.mdindex 19315f8..61f89b6 100644--- a/MacOS/tests/README.md+++ b/MacOS/tests/README.md@@ -54,6 +54,7 @@ If the rules are not active it stops with a message instead of failing every tes| `dns` | 200 uncached lookups through the DNS proxy all return the right answer || `idle` | 40 idle UDP flows are reaped after about 2 minutes while the app still holds the sockets || `leaks` | `leaks` on the extension reports 0 (the extension is a root process, so this needs sudo) |+| `cli` | the command line mode (`ProxyBridge --cli`): version and error handling, a profile piped in over standard input redirects traffic, a BLOCK rule works, a second CLI is refused, Ctrl+C clears everything. **Not in the default set:** quit the app first, and the build installed in `/Applications` must include the CLI |### Hostname suite with a box untickeddiff --git a/MacOS/tests/logic/cli_tests.swift b/MacOS/tests/logic/cli_tests.swiftnew file mode 100644index 0000000..36b06be--- /dev/null+++ b/MacOS/tests/logic/cli_tests.swift@@ -0,0 +1,133 @@+// Command line options and profile loading (CLIArguments.swift, CLIProfile.swift). Compiled as main.swift by run.sh.+import Foundation++var fails = 0+func t(_ name: String, _ ok: Bool) { if !ok { fails += 1; print("FAIL", name) } }+func opts(_ args: [String]) -> CLIOptions? { if case .run(let o) = CLIArguments.parse(["proxybridge"] + args) { return o }; return nil }+func err(_ args: [String]) -> String? { if case .failure(let m) = CLIArguments.parse(["proxybridge"] + args) { return m }; return nil }++// ---- GUI or CLI+t("no options is the GUI", !CLIArguments.isCLI(["/Applications/ProxyBridge.app/Contents/MacOS/ProxyBridge"]))+t("only the program name is the GUI", !CLIArguments.isCLI(["ProxyBridge"]))+t("empty arguments is the GUI", !CLIArguments.isCLI([]))+t("old Finder launch argument is the GUI", !CLIArguments.isCLI(["ProxyBridge", "-psn_0_12345"]))+t("Xcode debug arguments are the GUI", !CLIArguments.isCLI(["ProxyBridge", "-NSDocumentRevisionsDebugMode", "YES"]))+for flag in ["--cli", "--profile", "--verbose", "--version", "--update", "--list-profiles", "--help", "-h", "-?"] {+ t("\(flag) means the command line", CLIArguments.isCLI(["ProxyBridge", flag]))+}+t("--profile=name means the command line", CLIArguments.isCLI(["ProxyBridge", "--profile=work"]))+t("--verbose=2 means the command line", CLIArguments.isCLI(["ProxyBridge", "--verbose=2"]))+t("the program name itself is not an option", !CLIArguments.isCLI(["--profile"])) // argv[0] is skipped++// ---- parsing+t("profile name", opts(["--profile", "work"])?.profile == "work")+t("profile from stdin", opts(["--profile", "-"])?.profile == "-")+t("profile with =", opts(["--profile=work"])?.profile == "work")+t("verbose default is 0", opts(["--profile", "w"])?.verbose == 0)+t("verbose 3", opts(["--profile", "w", "--verbose", "3"])?.verbose == 3)+t("verbose with =", opts(["--profile", "w", "--verbose=2"])?.verbose == 2)+t("verbose before profile", opts(["--verbose", "1", "--profile", "w"]) == CLIOptions(profile: "w", verbose: 1))+t("--cli is accepted and ignored", opts(["--cli", "--profile", "w"])?.profile == "w")+t("help alone", opts(["--help"])?.help == true)+t("-h alone", opts(["-h"])?.help == true)+t("version alone", opts(["--version"])?.version == true)+t("list-profiles alone", opts(["--list-profiles"])?.listProfiles == true)+t("update alone", opts(["--update"])?.update == true)+t("a profile name with spaces is one value", opts(["--profile", "My Work Profile"])?.profile == "My Work Profile")+t("no profile is an error", err([])?.contains("--profile is required") == true)+t("only --verbose is an error", err(["--verbose", "2"])?.contains("--profile is required") == true)+t("--profile without a value", err(["--profile"])?.contains("requires a value") == true)+t("--profile followed by another option", err(["--profile", "--verbose", "2"])?.contains("requires a value") == true)+t("--profile= is empty", err(["--profile="])?.contains("requires a profile name") == true)+t("verbose 4 is rejected", err(["--profile", "w", "--verbose", "4"])?.contains("0-3") == true)+t("verbose -1 is rejected", err(["--profile", "w", "--verbose", "-1"])?.contains("0-3") == true)+t("verbose abc is rejected", err(["--profile", "w", "--verbose", "abc"])?.contains("0-3") == true)+t("unknown option", err(["--profile", "w", "--nope"])?.contains("Unknown option '--nope'") == true)+t("usage documents every option", ["--profile", "--list-profiles", "--verbose", "--update", "--version", "--help", "Ctrl+C", "--profile -"].allSatisfy { CLIArguments.usage.contains($0) })++// ---- profiles+func json(_ o: Any) -> Data { try! JSONSerialization.data(withJSONObject: o) }+let proxyA: [String: Any] = ["id": "p1", "name": "a", "type": "socks5", "host": "127.0.0.1", "port": 1080, "sendDomain": false]+let proxyB: [String: Any] = ["id": "p2", "type": "http", "host": "10.0.0.2", "port": 8080, "username": "u", "password": "pw"] // no name, no sendDomain+let rule1: [String: Any] = ["processNames": "curl", "targetHosts": "*", "targetPorts": "*", "protocol": "TCP", "action": "p1", "enabled": true]+let rule2: [String: Any] = ["processNames": "nc", "targetHosts": "*", "targetPorts": "*", "protocol": "UDP", "action": "BLOCK", "enabled": true]+let exported = json(["name": "work", "trafficLoggingEnabled": true, "proxyConfigs": [proxyA, proxyB], "proxyRules": [rule1, rule2]] as [String: Any])++let p = try! CLIProfileLoader.parse(json: exported)+t("exported profile: name", p.name == "work")+t("exported profile: two proxies", p.proxies.count == 2)+t("exported profile: proxy fields", p.proxies[0].host == "127.0.0.1" && p.proxies[0].port == 1080 && p.proxies[0].type == "socks5")+t("exported profile: sendDomain false is kept", p.proxies[0].sendDomain == false)+t("exported profile: missing sendDomain defaults to true", p.proxies[1].sendDomain == true)+t("exported profile: credentials", p.proxies[1].username == "u" && p.proxies[1].password == "pw")+t("exported profile: missing name is empty", p.proxies[1].name == "")+t("exported profile: rules kept as saved", p.rules.count == 2 && (p.rules[0]["action"] as? String) == "p1")+t("label", p.proxies[0].label == "SOCKS5 127.0.0.1:1080")+t("not json is an error", (try? CLIProfileLoader.parse(json: Data("nope".utf8))) == nil)+do { _ = try CLIProfileLoader.parse(json: json(["ProxyConfigs": [], "ProxyRules": []] as [String: Any])); t("windows layout is refused", false) }+catch let e as CLIProfileError { t("windows layout is refused with an explanation", e.message.contains("Windows")) } catch { t("windows layout error type", false) }+do { _ = try CLIProfileLoader.parse(json: json(["proxyConfigs": [["id": "x"]]] as [String: Any])); t("proxy without host is refused", false) }+catch { t("proxy without host is refused", true) }+t("profile with only rules is fine", (try? CLIProfileLoader.parse(json: json(["proxyRules": [rule2]] as [String: Any])))?.proxies.isEmpty == true)++// saved profiles: the active one is in the working keys, the others in snapshots+let store: [String: Any] = [+ "profiles": ["Default", "work"], "activeProfile": "Default",+ "proxyConfigs": json([proxyA]), "proxyRules": [rule1],+ "profile.work.proxyConfigs": json([proxyB]), "profile.work.proxyRules": [rule2, rule1],+]+let read: CLIProfileLoader.Reader = { store[$0] }+let active = try! CLIProfileLoader.saved(named: "Default", read: read)+t("active profile reads the working keys", active.proxies.count == 1 && active.proxies[0].id == "p1" && active.rules.count == 1)+let other = try! CLIProfileLoader.saved(named: "work", read: read)+t("other profile reads its snapshot", other.proxies[0].id == "p2" && other.rules.count == 2)+do { _ = try CLIProfileLoader.saved(named: "nope", read: read); t("unknown profile is an error", false) }+catch let e as CLIProfileError { t("unknown profile lists what exists", e.message.contains("Default, work") && e.message.contains("--list-profiles")) } catch { t("unknown profile error type", false) }+do { _ = try CLIProfileLoader.saved(named: "x", read: { _ in nil }); t("no profiles saved is an error", false) }+catch let e as CLIProfileError { t("no profiles saved says so", e.message.contains("none saved yet")) } catch { t("error type", false) }+let names = CLIProfileLoader.savedNames(read: read)+t("saved names and active", names.names == ["Default", "work"] && names.active == "Default")+t("an empty profile has empty lists", (try? CLIProfileLoader.saved(named: "e", read: { ["profiles": ["e"]][$0] }))?.proxies.isEmpty == true)++// ---- warnings+let ok = CLIProfile(name: "w", proxies: [try! JSONDecoder().decode(CLIProxy.self, from: json(proxyA))], rules: [rule1, rule2])+t("a good profile has no warnings", CLIProfileLoader.warnings(for: ok).isEmpty)+var dangling = ok; dangling.rules.append(["action": "gone"])+t("a rule pointing at a missing proxy warns", CLIProfileLoader.warnings(for: dangling).contains { $0.contains("rule 3") && $0.contains("go direct") })+t("DIRECT and BLOCK never warn", CLIProfileLoader.warnings(for: CLIProfile(name: "w", proxies: [], rules: [["action": "DIRECT"], ["action": "BLOCK"]])).isEmpty)+t("a rule with no action counts as DIRECT", CLIProfileLoader.warnings(for: CLIProfile(name: "w", proxies: [], rules: [[:]])).isEmpty)+t("no rules warns", CLIProfileLoader.warnings(for: CLIProfile(name: "w", proxies: [], rules: [])).contains { $0.contains("no rules") })+// ---- errors (these stop the run)+func profile(proxies: [[String: Any]] = [], rules: [[String: Any]] = []) -> CLIProfile {+ CLIProfile(name: "w", proxies: proxies.map { try! JSONDecoder().decode(CLIProxy.self, from: json($0)) }, rules: rules)+}+t("a good profile has no errors", CLIProfileLoader.errors(for: ok).isEmpty)+t("port 0 is an error", CLIProfileLoader.errors(for: profile(proxies: [["id": "a", "type": "socks5", "host": "h", "port": 0]])).contains { $0.contains("port 0") })+t("port 65536 is an error", CLIProfileLoader.errors(for: profile(proxies: [["id": "a", "type": "socks5", "host": "h", "port": 65536]])).contains { $0.contains("65536") })+t("port 65535 is fine", CLIProfileLoader.errors(for: profile(proxies: [["id": "a", "type": "http", "host": "h", "port": 65535]])).isEmpty)+t("an empty host is an error", CLIProfileLoader.errors(for: profile(proxies: [["id": "a", "type": "http", "host": " ", "port": 80]])).contains { $0.contains("no host") })+t("an unsupported proxy type is an error", CLIProfileLoader.errors(for: profile(proxies: [["id": "z", "type": "ftp", "host": "h", "port": 1]])).contains { $0.contains("socks5 or http") })+t("proxy types are case-insensitive", CLIProfileLoader.errors(for: profile(proxies: [["id": "a", "type": "SOCKS5", "host": "h", "port": 1]])).isEmpty)+t("duplicate proxy ids are an error", CLIProfileLoader.errors(for: profile(proxies: [["id": "a", "type": "http", "host": "h", "port": 1], ["id": "a", "type": "http", "host": "h2", "port": 2]])).contains { $0.contains("same id") })+let longPw = String(repeating: "x", count: 256)+t("a 256 byte SOCKS5 password is an error", CLIProfileLoader.errors(for: profile(proxies: [["id": "a", "type": "socks5", "host": "h", "port": 1, "password": longPw]])).contains { $0.contains("255 bytes") })+t("a long password is fine for an http proxy", CLIProfileLoader.errors(for: profile(proxies: [["id": "a", "type": "http", "host": "h", "port": 1, "password": longPw]])).isEmpty)+t("an unknown rule protocol is an error", CLIProfileLoader.errors(for: profile(rules: [["protocol": "ICMP", "action": "BLOCK"]])).contains { $0.contains("rule 1") && $0.contains("TCP, UDP or BOTH") })+t("a rule without a protocol means BOTH", CLIProfileLoader.errors(for: profile(rules: [["action": "BLOCK"]])).isEmpty)+t("too many rules is an error", CLIProfileLoader.errors(for: profile(rules: Array(repeating: ["action": "BLOCK"], count: CLIProfileLoader.maxRules + 1))).contains { $0.contains("limit") })+t("exactly the maximum number of rules is fine", CLIProfileLoader.errors(for: profile(rules: Array(repeating: ["action": "BLOCK"], count: CLIProfileLoader.maxRules))).isEmpty)+t("too many proxies is an error", CLIProfileLoader.errors(for: profile(proxies: (0...CLIProfileLoader.maxProxies).map { ["id": "p\($0)", "type": "http", "host": "h", "port": 1] })).contains { $0.contains("limit") })++// ---- terminal safety+t("plain text is unchanged", CLIText.safe("curl -> example.com:443") == "curl -> example.com:443")+t("unicode is unchanged", CLIText.safe("caf\u{e9} \u{1F600} \u{4E2D}") == "caf\u{e9} \u{1F600} \u{4E2D}")+t("an escape sequence is defanged", !CLIText.safe("\u{1b}[2J\u{1b}[31mred").contains("\u{1b}"))+t("escape text becomes visible, not lost", CLIText.safe("a\u{1b}[2Jb") == "a?[2Jb")+t("newline and carriage return are replaced", CLIText.safe("a\nb\rc") == "a?b?c")+t("backspace and bell are replaced", CLIText.safe("a\u{8}b\u{7}") == "a?b?")+t("C1 control characters are replaced", CLIText.safe("a\u{9b}b") == "a?b")+t("DEL is replaced", CLIText.safe("a\u{7f}b") == "a?b")+t("empty stays empty", CLIText.safe("") == "")++print(fails == 0 ? "cli tests: ALL PASS" : "cli tests: \(fails) FAILED")+exit(fails == 0 ? 0 : 1)diff --git a/MacOS/tests/logic/run.sh b/MacOS/tests/logic/run.shindex 8cad922..1b70a8f 100755--- a/MacOS/tests/logic/run.sh+++ b/MacOS/tests/logic/run.sh@@ -4,6 +4,7 @@set -eHERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"EXT="$HERE/../../ProxyBridge/extension"+APP="$HERE/../../ProxyBridge/ProxyBridge"TMP="$(mktemp -d)"trap 'rm -rf "$TMP"' EXIT@@ -17,3 +18,4 @@ run_test() { # <test file> <extension sources...>run_test matcher_tests.swift "$EXT/AppProxyProvider.swift" "$EXT/DNSMapStore.swift"run_test dnsmap_tests.swift "$EXT/DNSMapStore.swift"+run_test cli_tests.swift "$APP/CLIArguments.swift" "$APP/CLIProfile.swift" "$APP/CLIText.swift"diff --git a/MacOS/tests/pbtest.py b/MacOS/tests/pbtest.pyindex baeebae..db54bdf 100644--- a/MacOS/tests/pbtest.py+++ b/MacOS/tests/pbtest.py@@ -17,8 +17,11 @@ suites: functional rule routing, SOCKS5/HTTP/auth, DIRECT, BLOCK, UDP, stuck-hadns 200 uncached DNS lookups through the DNS proxyidle 40 idle UDP flows must be reaped after ~2 minutes (slow)leaks `leaks` on the extension must report 0 (needs `sudo -v` first, or SUDO_ASKPASS)+ cli the command line mode: runs pbtest.pbprofile through `ProxyBridge --cli` from /Applications,+ traffic must be redirected, Ctrl+C must clear everything. Not in the default set: the app+ must be QUIT and the installed build must have the CLIEnvironment: PB_NTP_IP (default: time.apple.com resolved once), PB_EVENTS (event log path)."""-import atexit, concurrent.futures as cf, json, os, random, socket, subprocess, sys, threading, time+import atexit, concurrent.futures as cf, json, os, random, signal, socket, subprocess, sys, threading, timeHERE = os.path.dirname(os.path.abspath(__file__))WORK = os.path.join(HERE, "work")@@ -316,7 +319,50 @@ def leaks():check("L1 leaks reports 0 leaks in the extension", " 0 leaks for 0 total leaked bytes" in line, line.strip() or "no result")-SUITES = {"functional": functional, "replies": replies, "hostnames": hostnames, "stress": stress, "dns": dns, "idle": idle, "leaks": leaks}+def cli():+ print("\n== command line mode ==")+ app = "/Applications/ProxyBridge.app/Contents/MacOS/ProxyBridge"+ if not os.path.exists(app):+ print("SKIP cli: /Applications/ProxyBridge.app is not installed"); return+ if subprocess.run(["pgrep", "-x", "ProxyBridge"], capture_output=True).returncode == 0:+ print("SKIP cli: quit the ProxyBridge app first, the CLI refuses to run next to it"); return+ v = subprocess.run([app, "--cli", "--version"], capture_output=True, text=True)+ check("C1 --version", v.returncode == 0 and v.stdout.startswith("ProxyBridge CLI "), v.stdout.strip() or v.stderr.strip())+ bad = subprocess.run([app, "--cli", "--bogus"], capture_output=True, text=True)+ check("C2 unknown option exits with 2 and a message", bad.returncode == 2 and "Unknown option" in bad.stderr, f"exit {bad.returncode}")+ profile = open(os.path.join(HERE, "pbtest.pbprofile")).read()+ proc = subprocess.Popen([app, "--cli", "--profile", "-", "--verbose", "3"], stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)+ proc.stdin.write(profile); proc.stdin.close()+ lines, ready = [], False+ t_end = time.time() + 120 # the first run can wait for the extension to be approved+ while time.time() < t_end and proc.poll() is None:+ line = proc.stdout.readline()+ if not line:+ break+ lines.append(line.rstrip())+ if "Redirecting traffic" in line:+ ready = True; break+ check("C3 profile applied and redirecting", ready, " | ".join(lines[-4:]))+ if not ready:+ proc.terminate(); return+ time.sleep(2)+ scenario("C4 curl example.com goes through SOCKS5 1080 while the CLI runs", CURL + ["https://example.com"], ("connect", "socks1080", 443), client_ok=HTTP_OK)+ scenario("C5 BLOCK rule is enforced (openssl)", ["openssl", "s_client", "-connect", "example.net:443"], ("connect", None, None), timeout=15, inp=b"",+ client_ok=lambda rc, o, e: b"BEGIN CERTIFICATE" not in o)+ second = subprocess.run([app, "--cli", "--profile", "-"], input=profile, capture_output=True, text=True, timeout=30)+ check("C6 a second CLI is refused", second.returncode != 0 and "already running" in second.stderr, second.stderr.strip()[:80])+ proc.send_signal(signal.SIGINT)+ try:+ proc.wait(timeout=20); out = proc.stdout.read()+ except subprocess.TimeoutExpired:+ proc.kill(); out = ""+ check("C7 Ctrl+C stops it cleanly", proc.returncode == 0 and "Rules cleared" in "\n".join(lines) + out, f"exit {proc.returncode}")+ time.sleep(1)+ scenario("C8 after Ctrl+C curl example.com is no longer redirected", CURL + ["https://example.com"], ("connect", None, None), client_ok=HTTP_OK)+++SUITES = {"cli": cli, "functional": functional, "replies": replies, "hostnames": hostnames, "stress": stress, "dns": dns, "idle": idle, "leaks": leaks}DEFAULT = ["functional", "replies", "hostnames", "stress", "dns", "leaks"]@@ -332,7 +378,9 @@ def main():sys.exit(f"unknown suite {w!r}, see --help")build_pbudp()start_servers()- preflight()+ # every suite but `cli` needs the test rules already active (imported in the app). `cli` activates them itself+ if any(w.split(":")[0] != "cli" for w in wanted):+ preflight()print("extension:", ext_pid(), snap())for w in wanted:name, _, arg = w.partition(":")diff --git a/SECURITY.md b/SECURITY.mdindex dfe7c2f..9c82301 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -102,6 +102,7 @@ ProxyBridge operates with the following security considerations:- `com.apple.security.network.client` and `com.apple.security.network.server`- `com.apple.security.application-groups`- **Hardened runtime** is enabled for both the app and the extension+- **Command line mode** - the app's own executable also runs without a window when started with options (`proxybridge --profile ...`). It is not a separate program, so it has the same signature, entitlements and sandbox. Profiles are read by name or from standard input and are not accepted as command line arguments, so proxy credentials do not appear in the process list. The `proxybridge` command is a short shell launcher installed by the package- **Credential storage** - proxy credentials and configuration stored in **UserDefaults** (not Keychain)- UserDefaults stored at: `~/Library/Containers/com.interceptsuite.ProxyBridge/Data/Library/Preferences/`- **Not encrypted** - stored in plaintext plist format