Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
added inital, prox rules, proxy setting and traffic redirection
Sourav Kalal70b245d60e0b
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeApp.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeApp.swiftindex 8528b54..89c070b 100644--- a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeApp.swift+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeApp.swift@@ -18,12 +18,24 @@ class ProxyBridgeApp: NSObject {private let runLoop = CFRunLoopGetCurrent()private var tunnelSession: NETunnelProviderSession?private var statusObserver: NSObjectProtocol?+ private var proxyConfig: ProxyConfig?++ struct ProxyConfig {+ let type: String // "socks5" or "http"+ let host: String+ let port: Int+ let username: String?+ let password: String?+ }static func main() {let app = ProxyBridgeApp.sharedprint("ProxyBridge CLI - Starting")+ // Parse command line arguments+ app.parseArguments()+signal(SIGINT, SIG_IGN)signal(SIGTERM, SIG_IGN)@@ -82,6 +94,44 @@ class ProxyBridgeApp: NSObject {print("Listening for connections...")print("")++ // Setup hardcoded proxy for testing+ setupTestProxyAndRule(session: session)+ }++ func setupTestProxyAndRule(session: NETunnelProviderSession) {+ // Set hardcoded SOCKS5 proxy+ let proxyConfig: [String: Any] = [+ "action": "setProxyConfig",+ "proxyType": "socks5",+ "proxyHost": "192.168.1.4",+ "proxyPort": 4444+ ]++ guard let configData = try? JSONSerialization.data(withJSONObject: proxyConfig) else { return }++ try? session.sendProviderMessage(configData) { response in+ print("✓ Proxy configured: socks5://192.168.1.4:4444")++ // After proxy is set, add test rule for curl+ let rule: [String: Any] = [+ "action": "addRule",+ "ruleId": 1,+ "processNames": "com.apple.curl",+ "targetHosts": "*",+ "targetPorts": "*",+ "ruleProtocol": "TCP",+ "ruleAction": "PROXY",+ "enabled": true+ ]++ guard let ruleData = try? JSONSerialization.data(withJSONObject: rule) else { return }++ try? session.sendProviderMessage(ruleData) { response in+ print("✓ Test rule added: com.apple.curl -> * -> * -> PROXY")+ print("")+ }+ }}func checkForLogs() {@@ -97,22 +147,36 @@ class ProxyBridgeApp: NSObject {let proto = log["protocol"],let process = log["process"],let dest = log["destination"],- let port = log["port"] else {+ let port = log["port"],+ let proxy = log["proxy"] else {return}- print("[\(proto)] \(process) -> \(dest):\(port)")+ print("[\(proto)] \(process) -> \(dest):\(port) -> \(proxy)")}}func sendConfig(host: String, port: Int) {guard let session = tunnelSession else { return }- let config = [+ var config: [String: Any] = ["action": "setProxyConfig","host": host,"port": port- ] as [String : Any]+ ]++ // Add proxy config if available+ if let proxy = proxyConfig {+ config["proxyType"] = proxy.type+ config["proxyHost"] = proxy.host+ config["proxyPort"] = proxy.port+ if let username = proxy.username {+ config["proxyUsername"] = username+ }+ if let password = proxy.password {+ config["proxyPassword"] = password+ }+ }guard let data = try? JSONSerialization.data(withJSONObject: config) else { return }@@ -121,6 +185,68 @@ class ProxyBridgeApp: NSObject {}}+ func parseArguments() {+ let args = CommandLine.arguments++ // Look for --proxy argument+ if let proxyIndex = args.firstIndex(of: "--proxy"),+ proxyIndex + 1 < args.count {+ let proxyUrl = args[proxyIndex + 1]++ if let config = parseProxyUrl(proxyUrl) {+ proxyConfig = config+ print("Proxy: \(config.type)://\(config.host):\(config.port)")+ if let username = config.username {+ print("Proxy Auth: \(username):***")+ }+ } else {+ print("WARNING: Invalid proxy format: \(proxyUrl)")+ print("Use: type://ip:port or type://ip:port:username:password")+ print("Examples: socks5://127.0.0.1:1080")+ print(" http://proxy.com:8080:myuser:mypass")+ }+ }+ }++ func parseProxyUrl(_ proxyUrl: String) -> ProxyConfig? {+ var username: String? = nil+ var password: String? = nil++ if proxyUrl.starts(with: "socks5://") {+ let parts = String(proxyUrl.dropFirst(9)).split(separator: ":")+ if parts.count >= 2, let port = Int(parts[1]) {+ if parts.count >= 4 {+ username = String(parts[2])+ password = String(parts[3])+ }+ return ProxyConfig(+ type: "socks5",+ host: String(parts[0]),+ port: port,+ username: username,+ password: password+ )+ }+ } else if proxyUrl.starts(with: "http://") {+ let parts = String(proxyUrl.dropFirst(7)).split(separator: ":")+ if parts.count >= 2, let port = Int(parts[1]) {+ if parts.count >= 4 {+ username = String(parts[2])+ password = String(parts[3])+ }+ return ProxyConfig(+ type: "http",+ host: String(parts[0]),+ port: port,+ username: username,+ password: password+ )+ }+ }++ return nil+ }+func stopProxy() {print("Stopping proxy")NETransparentProxyManager.loadAllFromPreferences { managers, error indiff --git a/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift b/MacOS/ProxyBridge/ProxyBridge/RuleManager.swiftnew file mode 100644index 0000000..d46b814--- /dev/null+++ b/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift@@ -0,0 +1,187 @@+//+// RuleManager.swift+// ProxyBridge+//+// Rule management helper for CLI+//++import Foundation+import NetworkExtension++struct RuleManager {++ // Send addRule command to extension+ static func addRule(+ session: NETunnelProviderSession,+ ruleId: UInt32,+ processNames: String,+ targetHosts: String,+ targetPorts: String,+ protocol: String,+ action: String,+ enabled: Bool = true,+ completion: @escaping (Bool, String) -> Void+ ) {+ let message: [String: Any] = [+ "action": "addRule",+ "ruleId": ruleId,+ "processNames": processNames,+ "targetHosts": targetHosts,+ "targetPorts": targetPorts,+ "ruleProtocol": `protocol`,+ "action": action,+ "enabled": enabled+ ]++ guard let data = try? JSONSerialization.data(withJSONObject: message) else {+ completion(false, "Failed to serialize rule")+ return+ }++ try? session.sendProviderMessage(data) { response in+ guard let responseData = response,+ let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],+ let status = result["status"] as? String else {+ completion(false, "No response from extension")+ return+ }++ if status == "ok" {+ completion(true, "Rule #\(ruleId) added successfully")+ } else if let message = result["message"] as? String {+ completion(false, "Error: \(message)")+ } else {+ completion(false, "Unknown error")+ }+ }+ }++ // Send removeRule command+ static func removeRule(+ session: NETunnelProviderSession,+ ruleId: UInt32,+ completion: @escaping (Bool, String) -> Void+ ) {+ let message: [String: Any] = [+ "action": "removeRule",+ "ruleId": ruleId+ ]++ guard let data = try? JSONSerialization.data(withJSONObject: message) else {+ completion(false, "Failed to serialize message")+ return+ }++ try? session.sendProviderMessage(data) { response in+ guard let responseData = response,+ let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],+ let status = result["status"] as? String else {+ completion(false, "No response from extension")+ return+ }++ if status == "ok" {+ let removed = result["removed"] as? Int ?? 0+ completion(true, "Removed \(removed) rule(s)")+ } else if let message = result["message"] as? String {+ completion(false, "Error: \(message)")+ } else {+ completion(false, "Unknown error")+ }+ }+ }++ // List all rules+ static func listRules(+ session: NETunnelProviderSession,+ completion: @escaping (Bool, [[String: Any]]) -> Void+ ) {+ let message: [String: Any] = [+ "action": "listRules"+ ]++ guard let data = try? JSONSerialization.data(withJSONObject: message) else {+ completion(false, [])+ return+ }++ try? session.sendProviderMessage(data) { response in+ guard let responseData = response,+ let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],+ let status = result["status"] as? String,+ status == "ok",+ let rules = result["rules"] as? [[String: Any]] else {+ completion(false, [])+ return+ }++ completion(true, rules)+ }+ }++ // Clear all rules+ static func clearRules(+ session: NETunnelProviderSession,+ completion: @escaping (Bool, String) -> Void+ ) {+ let message: [String: Any] = [+ "action": "clearRules"+ ]++ guard let data = try? JSONSerialization.data(withJSONObject: message) else {+ completion(false, "Failed to serialize message")+ return+ }++ try? session.sendProviderMessage(data) { response in+ guard let responseData = response,+ let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],+ let status = result["status"] as? String else {+ completion(false, "No response from extension")+ return+ }++ if status == "ok" {+ let cleared = result["cleared"] as? Int ?? 0+ completion(true, "Cleared \(cleared) rule(s)")+ } else if let message = result["message"] as? String {+ completion(false, "Error: \(message)")+ } else {+ completion(false, "Unknown error")+ }+ }+ }++ // Print rules in a nice format+ static func printRules(_ rules: [[String: Any]]) {+ if rules.isEmpty {+ print("No rules configured")+ return+ }++ print("\n=== Proxy Rules ===")+ print(String(format: "%-5s %-15s %-20s %-20s %-10s %-8s %-8s",+ "ID", "Process", "Hosts", "Ports", "Protocol", "Action", "Enabled"))+ print(String(repeating: "-", count: 100))++ for rule in rules {+ let ruleId = rule["ruleId"] as? UInt32 ?? 0+ let processNames = (rule["processNames"] as? String ?? "*").prefix(15)+ let targetHosts = (rule["targetHosts"] as? String ?? "*").prefix(20)+ let targetPorts = (rule["targetPorts"] as? String ?? "*").prefix(20)+ let proto = rule["protocol"] as? String ?? "BOTH"+ let action = rule["action"] as? String ?? "DIRECT"+ let enabled = rule["enabled"] as? Bool ?? true++ print(String(format: "%-5d %-15s %-20s %-20s %-10s %-8s %-8s",+ ruleId,+ String(processNames),+ String(targetHosts),+ String(targetPorts),+ proto,+ action,+ enabled ? "Yes" : "No"))+ }+ print("")+ }+}diff --git a/MacOS/ProxyBridge/extension/AppProxyProvider.swift b/MacOS/ProxyBridge/extension/AppProxyProvider.swiftindex 947919a..613585b 100644--- a/MacOS/ProxyBridge/extension/AppProxyProvider.swift+++ b/MacOS/ProxyBridge/extension/AppProxyProvider.swift@@ -8,11 +8,187 @@import NetworkExtensionimport os.log+// MARK: - Rule Definitions+enum RuleProtocol: String, Codable {+ case tcp = "TCP"+ case udp = "UDP"+ case both = "BOTH"+}++enum RuleAction: String, Codable {+ case proxy = "PROXY"+ case direct = "DIRECT"+ case block = "BLOCK"+}++struct ProxyRule: Codable {+ let ruleId: UInt32+ let processNames: String+ let targetHosts: String+ let targetPorts: String+ let ruleProtocol: RuleProtocol+ let action: RuleAction+ var enabled: Bool++ enum CodingKeys: String, CodingKey {+ case ruleId+ case processNames+ case targetHosts+ case targetPorts+ case ruleProtocol+ case action = "ruleAction"+ case enabled+ }++ func matchesProcess(_ processPath: String) -> Bool {+ return Self.matchProcessList(processNames, processPath: processPath)+ }++ func matchesIP(_ ipString: String) -> Bool {+ return Self.matchIPList(targetHosts, ipString: ipString)+ }++ func matchesPort(_ port: UInt16) -> Bool {+ return Self.matchPortList(targetPorts, port: port)+ }++ private static func matchProcessList(_ processList: String, processPath: String) -> Bool {+ if processList.isEmpty || processList == "*" {+ return true+ }++ let filename = (processPath as NSString).lastPathComponent+ let patterns = processList.components(separatedBy: CharacterSet(charactersIn: ",;"))++ for pattern in patterns {+ let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines)+ if matchProcessPattern(trimmed, processPath: processPath, filename: filename) {+ return true+ }+ }+ return false+ }++ private static func matchProcessPattern(_ pattern: String, processPath: String, filename: String) -> Bool {+ if pattern.isEmpty || pattern == "*" {+ return true+ }++ let isFullPathPattern = pattern.contains("/") || pattern.contains("\\")+ let matchTarget = isFullPathPattern ? processPath : filename++ if pattern.hasSuffix("*") {+ let prefix = String(pattern.dropLast())+ return matchTarget.lowercased().hasPrefix(prefix.lowercased())+ }++ if pattern.hasPrefix("*") {+ let suffix = String(pattern.dropFirst())+ return matchTarget.lowercased().hasSuffix(suffix.lowercased())+ }++ if let starIndex = pattern.firstIndex(of: "*") {+ let prefix = String(pattern[..<starIndex])+ let suffix = String(pattern[pattern.index(after: starIndex)...])+ let lower = matchTarget.lowercased()+ return lower.hasPrefix(prefix.lowercased()) && lower.hasSuffix(suffix.lowercased())+ }++ return matchTarget.lowercased() == pattern.lowercased()+ }++ private static func matchIPList(_ ipList: String, ipString: String) -> Bool {+ if ipList.isEmpty || ipList == "*" {+ return true+ }++ let patterns = ipList.components(separatedBy: ";")+ for pattern in patterns {+ let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines)+ if matchIPPattern(trimmed, ipString: ipString) {+ return true+ }+ }+ return false+ }++ private static func matchIPPattern(_ pattern: String, ipString: String) -> Bool {+ if pattern.isEmpty || pattern == "*" {+ return true+ }++ let patternOctets = pattern.components(separatedBy: ".")+ let ipOctets = ipString.components(separatedBy: ".")++ if patternOctets.count != 4 || ipOctets.count != 4 {+ return false+ }++ for i in 0..<4 {+ if patternOctets[i] == "*" {+ continue+ }+ if patternOctets[i] != ipOctets[i] {+ return false+ }+ }+ return true+ }++ private static func matchPortList(_ portList: String, port: UInt16) -> Bool {+ if portList.isEmpty || portList == "*" {+ return true+ }++ let patterns = portList.components(separatedBy: CharacterSet(charactersIn: ",;"))+ for pattern in patterns {+ let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines)+ if matchPortPattern(trimmed, port: port) {+ return true+ }+ }+ return false+ }++ private static func matchPortPattern(_ pattern: String, port: UInt16) -> Bool {+ if pattern.isEmpty || pattern == "*" {+ return true+ }++ if let dashIndex = pattern.firstIndex(of: "-") {+ let startStr = String(pattern[..<dashIndex])+ let endStr = String(pattern[pattern.index(after: dashIndex)...])++ if let start = UInt16(startStr), let end = UInt16(endStr) {+ return port >= start && port <= end+ }+ return false+ }++ if let patternPort = UInt16(pattern) {+ return port == patternPort+ }+ return false+ }+}+class AppProxyProvider: NETransparentProxyProvider {private let logger = Logger(subsystem: "com.interceptsuite.ProxyBridge.extension", category: "NetworkProxy")private var logQueue: [[String: String]] = []private let queueLock = NSLock()++ // Rule storage+ private var rules: [ProxyRule] = []+ private let rulesLock = NSLock()++ // Proxy configuration+ private var proxyType: String?+ private var proxyHost: String?+ private var proxyPort: Int?+ private var proxyUsername: String?+ private var proxyPassword: String?+ private let proxyLock = NSLock()override func startProxy(options: [String : Any]?, completionHandler: @escaping (Error?) -> Void) {let settings = NETransparentProxyNetworkSettings(tunnelRemoteAddress: "127.0.0.1")@@ -56,12 +232,84 @@ class AppProxyProvider: NETransparentProxyProvider {completionHandler?(nil)}case "setProxyConfig":- if let host = message["host"] as? String,- let port = message["port"] as? Int {- logger.info("Proxy config updated: \(host):\(port)")+ if let proxyType = message["proxyType"] as? String,+ let proxyHost = message["proxyHost"] as? String,+ let proxyPort = message["proxyPort"] as? Int {++ proxyLock.lock()+ self.proxyType = proxyType+ self.proxyHost = proxyHost+ self.proxyPort = proxyPort+ self.proxyUsername = message["proxyUsername"] as? String+ self.proxyPassword = message["proxyPassword"] as? String+ proxyLock.unlock()++ var logMsg = "Proxy config: \(proxyType)://\(proxyHost):\(proxyPort)"+ if let username = message["proxyUsername"] as? String {+ logMsg += " (auth: \(username):***)"+ }+ logger.info("\(logMsg)")}let response = ["status": "ok"]completionHandler?(try? JSONSerialization.data(withJSONObject: response))++ case "addRule":+ if let ruleData = try? JSONSerialization.data(withJSONObject: message),+ let rule = try? JSONDecoder().decode(ProxyRule.self, from: ruleData) {+ rulesLock.lock()+ // Remove existing rule with same ID+ rules.removeAll { $0.ruleId == rule.ruleId }+ rules.append(rule)+ rulesLock.unlock()+ logger.info("Added rule #\(rule.ruleId): \(rule.processNames) -> \(rule.action.rawValue)")+ let response = ["status": "ok"]+ completionHandler?(try? JSONSerialization.data(withJSONObject: response))+ } else {+ let response = ["status": "error", "message": "Invalid rule format"]+ completionHandler?(try? JSONSerialization.data(withJSONObject: response))+ }++ case "removeRule":+ if let ruleId = message["ruleId"] as? UInt32 {+ rulesLock.lock()+ let beforeCount = rules.count+ rules.removeAll { $0.ruleId == ruleId }+ let removed = beforeCount - rules.count+ rulesLock.unlock()+ logger.info("Removed rule #\(ruleId)")+ let response: [String: Any] = ["status": "ok", "removed": removed]+ completionHandler?(try? JSONSerialization.data(withJSONObject: response))+ } else {+ let response = ["status": "error", "message": "Missing ruleId"]+ completionHandler?(try? JSONSerialization.data(withJSONObject: response))+ }++ case "listRules":+ rulesLock.lock()+ let rulesList = rules.map { rule -> [String: Any] in+ return [+ "ruleId": rule.ruleId,+ "processNames": rule.processNames,+ "targetHosts": rule.targetHosts,+ "targetPorts": rule.targetPorts,+ "protocol": rule.ruleProtocol.rawValue,+ "action": rule.action.rawValue,+ "enabled": rule.enabled+ ]+ }+ rulesLock.unlock()+ let response: [String: Any] = ["status": "ok", "rules": rulesList]+ completionHandler?(try? JSONSerialization.data(withJSONObject: response))++ case "clearRules":+ rulesLock.lock()+ let count = rules.count+ rules.removeAll()+ rulesLock.unlock()+ logger.info("Cleared all rules (\(count) rules)")+ let response: [String: Any] = ["status": "ok", "cleared": count]+ completionHandler?(try? JSONSerialization.data(withJSONObject: response))+case "setRules":if let rules = message["rules"] as? [[String: String]] {logger.info("Rules updated: \(rules.count) rules")@@ -82,41 +330,435 @@ class AppProxyProvider: NETransparentProxyProvider {override func handleNewFlow(_ flow: NEAppProxyFlow) -> Bool {if let tcpFlow = flow as? NEAppProxyTCPFlow {- logTCPConnection(tcpFlow)+ return handleTCPFlow(tcpFlow)}// Let all traffic pass through directlyreturn false}- private func logTCPConnection(_ flow: NEAppProxyTCPFlow) {+ private func handleTCPFlow(_ flow: NEAppProxyTCPFlow) -> Bool {let remoteEndpoint = flow.remoteEndpointvar destination = ""- var port = ""+ var portNum: UInt16 = 0+ var portStr = ""if let remoteHost = remoteEndpoint as? NWHostEndpoint {destination = remoteHost.hostname- port = remoteHost.port+ portStr = remoteHost.port+ portNum = UInt16(portStr) ?? 0} else {destination = String(describing: remoteEndpoint)- port = "unknown"+ portStr = "unknown"}- var processName = "unknown"+ var processPath = "unknown"if let metaData = flow.metaData as? NEFlowMetaData {- processName = metaData.sourceAppSigningIdentifier+ processPath = metaData.sourceAppSigningIdentifier+ }++ // Check if proxy is configured+ proxyLock.lock()+ let hasProxyConfig = (proxyHost != nil && proxyPort != nil)+ proxyLock.unlock()++ if !hasProxyConfig {+ sendLogToApp(protocol: "TCP", process: processPath, destination: destination, port: portStr, proxy: "Direct")+ return false+ }++ let matchedRule = findMatchingRule(processPath: processPath, destination: destination, port: portNum, connectionProtocol: .tcp)++ if let rule = matchedRule {+ let action = rule.action.rawValue+ logger.info("Rule #\(rule.ruleId) matched: \(processPath) -> \(destination):\(portStr) -> \(action)")++ sendLogToApp(protocol: "TCP", process: processPath, destination: destination, port: portStr, proxy: action)++ switch rule.action {+ case .direct:+ return false+ case .block:+ flow.closeReadWithError(nil)+ flow.closeWriteWithError(nil)+ return true+ case .proxy:+ proxyTCPFlow(flow, destination: destination, port: portNum)+ return true+ }+ } else {+ sendLogToApp(protocol: "TCP", process: processPath, destination: destination, port: portStr, proxy: "Direct")+ return false+ }+ }++ private func proxyTCPFlow(_ flow: NEAppProxyTCPFlow, destination: String, port: UInt16) {+ proxyLock.lock()+ guard let proxyHost = self.proxyHost,+ let proxyPort = self.proxyPort,+ let proxyType = self.proxyType else {+ proxyLock.unlock()+ logger.error("Proxy config missing")+ flow.closeReadWithError(nil)+ flow.closeWriteWithError(nil)+ return+ }+ let username = self.proxyUsername+ let password = self.proxyPassword+ proxyLock.unlock()++ let proxyEndpoint = NWHostEndpoint(hostname: proxyHost, port: String(proxyPort))+ let proxyConnection = createTCPConnection(to: proxyEndpoint, enableTLS: false, tlsParameters: nil, delegate: nil)++ proxyConnection.addObserver(self, forKeyPath: "state", options: .new, context: nil)++ if proxyType.lowercased() == "socks5" {+ handleSOCKS5Proxy(clientFlow: flow, proxyConnection: proxyConnection, destination: destination, port: port, username: username, password: password)+ } else if proxyType.lowercased() == "http" {+ handleHTTPProxy(clientFlow: flow, proxyConnection: proxyConnection, destination: destination, port: port, username: username, password: password)+ } else {+ logger.error("Unsupported proxy type: \(proxyType)")+ flow.closeReadWithError(nil)+ flow.closeWriteWithError(nil)+ }+ }++ private func handleSOCKS5Proxy(clientFlow: NEAppProxyTCPFlow, proxyConnection: NWTCPConnection, destination: String, port: UInt16, username: String?, password: String?) {+ var greeting: [UInt8]+ if username != nil && password != nil {+ greeting = [0x05, 0x02, 0x00, 0x02]+ } else {+ greeting = [0x05, 0x01, 0x00]+ }++ let greetingData = Data(greeting)+ proxyConnection.write(greetingData) { [weak self] error in+ if let error = error {+ self?.logger.error("SOCKS5 greeting write failed: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ proxyConnection.cancel()+ return+ }++ // Read server response (2 bytes: version, chosen method)+ proxyConnection.readMinimumLength(2, maximumLength: 2) { [weak self] data, error in+ guard let self = self else { return }++ if let error = error {+ self.logger.error("SOCKS5 greeting response failed: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ proxyConnection.cancel()+ return+ }++ guard let data = data, data.count == 2 else {+ self.logger.error("SOCKS5 invalid greeting response")+ clientFlow.closeReadWithError(nil)+ clientFlow.closeWriteWithError(nil)+ proxyConnection.cancel()+ return+ }++ let version = data[0]+ let method = data[1]++ if version != 0x05 {+ self.logger.error("SOCKS5 invalid version: \(version)")+ clientFlow.closeReadWithError(nil)+ clientFlow.closeWriteWithError(nil)+ proxyConnection.cancel()+ return+ }++ if method == 0x00 {+ // No authentication required+ self.sendSOCKS5ConnectRequest(clientFlow: clientFlow, proxyConnection: proxyConnection, destination: destination, port: port)+ } else if method == 0x02 {+ // Username/password authentication required+ self.sendSOCKS5Auth(clientFlow: clientFlow, proxyConnection: proxyConnection, destination: destination, port: port, username: username ?? "", password: password ?? "")+ } else {+ self.logger.error("SOCKS5 no acceptable auth method: \(method)")+ clientFlow.closeReadWithError(nil)+ clientFlow.closeWriteWithError(nil)+ proxyConnection.cancel()+ }+ }+ }+ }++ private func sendSOCKS5Auth(clientFlow: NEAppProxyTCPFlow, proxyConnection: NWTCPConnection, destination: String, port: UInt16, username: String, password: String) {+ // Auth format: [Version(1), Username length, Username, Password length, Password]+ var authData = Data()+ authData.append(0x01) // Auth version+ authData.append(UInt8(username.count))+ authData.append(username.data(using: .utf8) ?? Data())+ authData.append(UInt8(password.count))+ authData.append(password.data(using: .utf8) ?? Data())++ proxyConnection.write(authData) { [weak self] error in+ if let error = error {+ self?.logger.error("SOCKS5 auth write failed: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ proxyConnection.cancel()+ return+ }++ // Read auth response (2 bytes: version, status)+ proxyConnection.readMinimumLength(2, maximumLength: 2) { [weak self] data, error in+ guard let self = self else { return }++ if let error = error {+ self.logger.error("SOCKS5 auth response failed: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ proxyConnection.cancel()+ return+ }++ guard let data = data, data.count == 2, data[1] == 0x00 else {+ self.logger.error("SOCKS5 auth failed")+ clientFlow.closeReadWithError(nil)+ clientFlow.closeWriteWithError(nil)+ proxyConnection.cancel()+ return+ }++ self.sendSOCKS5ConnectRequest(clientFlow: clientFlow, proxyConnection: proxyConnection, destination: destination, port: port)+ }+ }+ }++ private func sendSOCKS5ConnectRequest(clientFlow: NEAppProxyTCPFlow, proxyConnection: NWTCPConnection, destination: String, port: UInt16) {+ var request = Data()+ request.append(0x05)+ request.append(0x01)+ request.append(0x00)++ if let ipAddr = IPv4Address(destination) {+ request.append(0x01)+ request.append(contentsOf: ipAddr.rawValue)+ } else if let ipAddr = IPv6Address(destination) {+ request.append(0x04)+ request.append(contentsOf: ipAddr.rawValue)+ } else {+ request.append(0x03)+ request.append(UInt8(destination.count))+ request.append(destination.data(using: .utf8) ?? Data())+ }++ request.append(UInt8(port >> 8))+ request.append(UInt8(port & 0xFF))++ proxyConnection.write(request) { [weak self] error in+ if let error = error {+ self?.logger.error("SOCKS5 connect write failed: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ proxyConnection.cancel()+ return+ }++ // Read connect response (minimum 10 bytes)+ proxyConnection.readMinimumLength(10, maximumLength: 512) { [weak self] data, error in+ guard let self = self else { return }++ if let error = error {+ self.logger.error("SOCKS5 connect response failed: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ proxyConnection.cancel()+ return+ }++ guard let data = data, data.count >= 10, data[0] == 0x05, data[1] == 0x00 else {+ self.logger.error("SOCKS5 connect failed")+ clientFlow.closeReadWithError(nil)+ clientFlow.closeWriteWithError(nil)+ proxyConnection.cancel()+ return+ }++ self.logger.info("SOCKS5 connection established to \(destination):\(port)")+ self.relayData(clientFlow: clientFlow, proxyConnection: proxyConnection)+ }+ }+ }++ private func handleHTTPProxy(clientFlow: NEAppProxyTCPFlow, proxyConnection: NWTCPConnection, destination: String, port: UInt16, username: String?, password: String?) {+ var request = "CONNECT \(destination):\(port) HTTP/1.1\r\n"+ request += "Host: \(destination):\(port)\r\n"++ if let username = username, let password = password {+ let credentials = "\(username):\(password)"+ if let credData = credentials.data(using: .utf8) {+ let base64Creds = credData.base64EncodedString()+ request += "Proxy-Authorization: Basic \(base64Creds)\r\n"+ }+ }++ request += "\r\n"++ guard let requestData = request.data(using: .utf8) else {+ logger.error("HTTP CONNECT request encoding failed")+ clientFlow.closeReadWithError(nil)+ clientFlow.closeWriteWithError(nil)+ proxyConnection.cancel()+ return+ }++ proxyConnection.write(requestData) { [weak self] error in+ if let error = error {+ self?.logger.error("HTTP CONNECT write failed: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ proxyConnection.cancel()+ return+ }++ // Read HTTP response+ proxyConnection.readMinimumLength(1, maximumLength: 8192) { [weak self] data, error in+ guard let self = self else { return }++ if let error = error {+ self.logger.error("HTTP CONNECT response failed: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ proxyConnection.cancel()+ return+ }++ guard let data = data,+ let response = String(data: data, encoding: .utf8) else {+ self.logger.error("HTTP CONNECT invalid response")+ clientFlow.closeReadWithError(nil)+ clientFlow.closeWriteWithError(nil)+ proxyConnection.cancel()+ return+ }++ if response.contains("200") {+ self.logger.info("HTTP CONNECT established to \(destination):\(port)")+ self.relayData(clientFlow: clientFlow, proxyConnection: proxyConnection)+ } else {+ self.logger.error("HTTP CONNECT failed: \(response)")+ clientFlow.closeReadWithError(nil)+ clientFlow.closeWriteWithError(nil)+ proxyConnection.cancel()+ }+ }+ }+ }++ private func relayData(clientFlow: NEAppProxyTCPFlow, proxyConnection: NWTCPConnection) {+ clientFlow.open(withLocalEndpoint: nil) { [weak self] error in+ if let error = error {+ self?.logger.error("Failed to open client flow: \(error.localizedDescription)")+ proxyConnection.cancel()+ return+ }++ self?.relayClientToProxy(clientFlow: clientFlow, proxyConnection: proxyConnection)+ self?.relayProxyToClient(clientFlow: clientFlow, proxyConnection: proxyConnection)+ }+ }++ private func relayClientToProxy(clientFlow: NEAppProxyTCPFlow, proxyConnection: NWTCPConnection) {+ clientFlow.readData { [weak self] data, error in+ if let error = error {+ self?.logger.error("Client read error: \(error.localizedDescription)")+ proxyConnection.cancel()+ return+ }++ guard let data = data, !data.isEmpty else {+ self?.logger.info("Client closed connection")+ proxyConnection.cancel()+ return+ }++ proxyConnection.write(data) { error in+ if let error = error {+ self?.logger.error("Proxy write error: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ } else {+ // Continue reading from client+ self?.relayClientToProxy(clientFlow: clientFlow, proxyConnection: proxyConnection)+ }+ }+ }+ }++ private func relayProxyToClient(clientFlow: NEAppProxyTCPFlow, proxyConnection: NWTCPConnection) {+ proxyConnection.readMinimumLength(1, maximumLength: 65536) { [weak self] data, error in+ if let error = error {+ self?.logger.error("Proxy read error: \(error.localizedDescription)")+ clientFlow.closeReadWithError(error)+ clientFlow.closeWriteWithError(error)+ return+ }++ guard let data = data, !data.isEmpty else {+ self?.logger.info("Proxy closed connection")+ clientFlow.closeReadWithError(nil)+ clientFlow.closeWriteWithError(nil)+ return+ }++ clientFlow.write(data) { error in+ if let error = error {+ self?.logger.error("Client write error: \(error.localizedDescription)")+ proxyConnection.cancel()+ } else {+ // Continue reading from proxy+ self?.relayProxyToClient(clientFlow: clientFlow, proxyConnection: proxyConnection)+ }+ }+ }+ }++ override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {+ }++ private func findMatchingRule(processPath: String, destination: String, port: UInt16, connectionProtocol: RuleProtocol) -> ProxyRule? {+ rulesLock.lock()+ defer { rulesLock.unlock() }++ for rule in rules {+ guard rule.enabled else { continue }++ if rule.ruleProtocol != .both && rule.ruleProtocol != connectionProtocol {+ continue+ }++ if !rule.matchesProcess(processPath) {+ continue+ }++ if !rule.matchesIP(destination) {+ continue+ }++ if !rule.matchesPort(port) {+ continue+ }++ return rule}- sendLogToApp(protocol: "TCP", process: processName, destination: destination, port: port)+ return nil}- private func sendLogToApp(protocol: String, process: String, destination: String, port: String) {+ private func sendLogToApp(protocol: String, process: String, destination: String, port: String, proxy: String) {let logData: [String: String] = ["type": "connection","protocol": `protocol`,"process": process,"destination": destination,"port": port,- "proxy": "Direct"+ "proxy": proxy]queueLock.lock()