Skip to content

Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic

updated CLI , added signal

Sourav Kalale2f52b669622
diff --git a/MacOS/ProxyBridge/ProxyBridge/ContentView.swift b/MacOS/ProxyBridge/ProxyBridge/ContentView.swift
deleted file mode 100644
index c209417..0000000
--- a/MacOS/ProxyBridge/ProxyBridge/ContentView.swift
+++ /dev/null
@@ -1,24 +0,0 @@
-//
-// ContentView.swift
-// ProxyBridge
-//
-// Created by sourav kalal on 13/11/25.
-//
-
-import SwiftUI
-
-struct ContentView: View {
- var body: some View {
- VStack {
- Image(systemName: "globe")
- .imageScale(.large)
- .foregroundStyle(.tint)
- Text("Hello, world!")
- }
- .padding()
- }
-}
-
-#Preview {
- ContentView()
-}
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeApp.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeApp.swift
index 6d495e3..11be1fe 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeApp.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeApp.swift
@@ -1,46 +1,131 @@
//
// ProxyBridgeApp.swift
-// ProxyBridge
+// ProxyBridge - CLI Tool
//
// Created by sourav kalal on 13/11/25.
//
-import SwiftUI
+import Foundation
import NetworkExtension
import SystemExtensions
import os.log
@main
-struct ProxyBridgeApp: App {
- @Environment(\.scenePhase) private var scenePhase
+class ProxyBridgeApp: NSObject {
- init() {
- os_log("App init - installing extension", type: .info)
- installExtension()
+ static let shared = ProxyBridgeApp()
+ private var shouldKeepRunning = true
+ private let runLoop = CFRunLoopGetCurrent()
+ private var tunnelSession: NETunnelProviderSession?
+ private var statusObserver: NSObjectProtocol?
+
+ static func main() {
+ let app = ProxyBridgeApp.shared
+
+ print("ProxyBridge CLI - Starting")
+
+ let sigintSource = DispatchSource.makeSignalSource(signal: SIGINT, queue: .main)
+ sigintSource.setEventHandler {
+ print("\nShutting down...")
+ app.shouldKeepRunning = false
+ app.shutdown()
+ CFRunLoopStop(app.runLoop)
+ }
+ sigintSource.resume()
+ signal(SIGINT, SIG_IGN)
+
+ let sigtermSource = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .main)
+ sigtermSource.setEventHandler {
+ print("\nTerminating...")
+ app.shouldKeepRunning = false
+ app.shutdown()
+ CFRunLoopStop(app.runLoop)
+ }
+ sigtermSource.resume()
+ signal(SIGTERM, SIG_IGN)
+
+ app.installExtension()
+
+ CFRunLoopRun()
+
+ print("ProxyBridge stopped")
+ exit(0)
+ }
+
+ func shutdown() {
+ stopProxy()
+ if let observer = statusObserver {
+ NotificationCenter.default.removeObserver(observer)
+ }
}
- var body: some Scene {
- WindowGroup {
- ContentView()
+ func setupMessageReceiver(session: NETunnelProviderSession) {
+ tunnelSession = session
+
+ statusObserver = NotificationCenter.default.addObserver(
+ forName: .NEVPNStatusDidChange,
+ object: session,
+ queue: .main
+ ) { [weak self] _ in
+ self?.checkForLogs()
+ }
+
+ Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] _ in
+ guard let self = self, self.shouldKeepRunning else { return }
+ self.checkForLogs()
}
- .onChange(of: scenePhase) { oldPhase, newPhase in
- if newPhase == .background {
- os_log("App going to background, stopping proxy", type: .info)
- stopProxy()
+
+ print("Listening for connections...")
+ print("")
+ }
+
+ func checkForLogs() {
+ guard let session = tunnelSession else { return }
+
+ let message = ["action": "getLogs"]
+ guard let data = try? JSONSerialization.data(withJSONObject: message) else { return }
+
+ try? session.sendProviderMessage(data) { response in
+ guard let responseData = response,
+ let log = try? JSONSerialization.jsonObject(with: responseData) as? [String: String],
+ let type = log["type"], type == "connection",
+ let proto = log["protocol"],
+ let process = log["process"],
+ let dest = log["destination"],
+ let port = log["port"] else {
+ return
}
+
+ print("[\(proto)] \(process) -> \(dest):\(port)")
+ }
+ }
+
+ func sendConfig(host: String, port: Int) {
+ guard let session = tunnelSession else { return }
+
+ let config = [
+ "action": "setProxyConfig",
+ "host": host,
+ "port": port
+ ] as [String : Any]
+
+ guard let data = try? JSONSerialization.data(withJSONObject: config) else { return }
+
+ try? session.sendProviderMessage(data) { response in
+ print("Config sent to extension")
}
}
func stopProxy() {
+ print("Stopping proxy")
NETransparentProxyManager.loadAllFromPreferences { managers, error in
guard let manager = managers?.first else { return }
(manager.connection as? NETunnelProviderSession)?.stopTunnel()
- os_log("Proxy tunnel stopped", type: .info)
}
}
func installExtension() {
- os_log("Requesting extension installation", type: .info)
+ print("Installing system extension")
let request = OSSystemExtensionRequest.activationRequest(
forExtensionWithIdentifier: "com.interceptsuite.ProxyBridge.extension",
queue: .main
@@ -54,28 +139,29 @@ class ExtensionDelegate: NSObject, OSSystemExtensionRequestDelegate {
static let shared = ExtensionDelegate()
func request(_ request: OSSystemExtensionRequest, actionForReplacingExtension existing: OSSystemExtensionProperties, withExtension ext: OSSystemExtensionProperties) -> OSSystemExtensionRequest.ReplacementAction {
- os_log("Extension replacement requested", type: .info)
+ print("Replacing existing extension")
return .replace
}
func requestNeedsUserApproval(_ request: OSSystemExtensionRequest) {
- os_log("Extension needs user approval in System Settings", type: .error)
+ print("ERROR: Extension needs user approval in System Settings")
+ print("Go to: System Settings -> Privacy & Security -> Allow")
}
func request(_ request: OSSystemExtensionRequest, didFinishWithResult result: OSSystemExtensionRequest.Result) {
- os_log("Extension installed successfully", type: .info)
+ print("Extension installed successfully")
startProxy()
}
func request(_ request: OSSystemExtensionRequest, didFailWithError error: Error) {
- os_log("Extension installation failed: %{public}@", type: .error, error.localizedDescription)
+ print("ERROR: Extension installation failed: \(error.localizedDescription)")
}
func startProxy() {
- os_log("Starting transparent proxy configuration", type: .info)
+ print("Starting proxy tunnel")
NETransparentProxyManager.loadAllFromPreferences { managers, error in
if let error = error {
- os_log("Failed to load managers: %{public}@", type: .error, error.localizedDescription)
+ print("ERROR: Failed to load managers: \(error.localizedDescription)")
return
}
@@ -91,23 +177,29 @@ class ExtensionDelegate: NSObject, OSSystemExtensionRequestDelegate {
manager.saveToPreferences { saveError in
if let saveError = saveError {
- os_log("Failed to save preferences: %{public}@", type: .error, saveError.localizedDescription)
+ print("ERROR: Failed to save preferences: \(saveError.localizedDescription)")
return
}
- os_log("Transparent proxy configuration saved", type: .info)
+ print("Configuration saved")
manager.loadFromPreferences { loadError in
if let loadError = loadError {
- os_log("Failed to reload preferences: %{public}@", type: .error, loadError.localizedDescription)
+ print("ERROR: Failed to reload preferences: \(loadError.localizedDescription)")
return
}
do {
try (manager.connection as? NETunnelProviderSession)?.startTunnel()
- os_log("Transparent proxy started", type: .info)
+ print("Proxy tunnel started")
+
+ if let session = manager.connection as? NETunnelProviderSession {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
+ ProxyBridgeApp.shared.setupMessageReceiver(session: session)
+ }
+ }
} catch {
- os_log("Failed to start proxy: %{public}@", type: .error, error.localizedDescription)
+ print("ERROR: Failed to start tunnel: \(error.localizedDescription)")
}
}
}
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeRelease.entitlements b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeRelease.entitlements
index b0d02e7..986d1c5 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeRelease.entitlements
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeRelease.entitlements
@@ -8,5 +8,9 @@
</array>
<key>com.apple.developer.system-extension.install</key>
<true/>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>group.com.interceptsuite.ProxyBridge</string>
+ </array>
</dict>
</plist>
diff --git a/MacOS/ProxyBridge/extension/AppProxyProvider.swift b/MacOS/ProxyBridge/extension/AppProxyProvider.swift
index c5d3dfa..6860597 100644
--- a/MacOS/ProxyBridge/extension/AppProxyProvider.swift
+++ b/MacOS/ProxyBridge/extension/AppProxyProvider.swift
@@ -11,10 +11,10 @@ import os.log
class AppProxyProvider: NETransparentProxyProvider {
private let logger = Logger(subsystem: "com.interceptsuite.ProxyBridge.extension", category: "NetworkProxy")
+ private var logQueue: [[String: String]] = []
+ private let queueLock = NSLock()
override func startProxy(options: [String : Any]?, completionHandler: @escaping (Error?) -> Void) {
- logger.info("Configuring transparent proxy")
-
let settings = NETransparentProxyNetworkSettings(tunnelRemoteAddress: "127.0.0.1")
let allTrafficRule = NENetworkRule(
@@ -29,24 +29,47 @@ class AppProxyProvider: NETransparentProxyProvider {
settings.includedNetworkRules = [allTrafficRule]
self.setTunnelNetworkSettings(settings) { error in
- if let error = error {
- self.logger.error("Failed to set network settings: \(error.localizedDescription)")
- completionHandler(error)
- } else {
- self.logger.info("Transparent proxy started")
- completionHandler(nil)
- }
+ completionHandler(error)
}
}
override func stopProxy(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
- logger.info("Proxy stopped: \(reason.rawValue)")
completionHandler()
}
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
- if let handler = completionHandler {
- handler(messageData)
+ guard let message = try? JSONSerialization.jsonObject(with: messageData) as? [String: Any],
+ let action = message["action"] as? String else {
+ completionHandler?(nil)
+ return
+ }
+
+ switch action {
+ case "getLogs":
+ queueLock.lock()
+ if !logQueue.isEmpty {
+ let log = logQueue.removeFirst()
+ queueLock.unlock()
+ completionHandler?(try? JSONSerialization.data(withJSONObject: log))
+ } else {
+ queueLock.unlock()
+ completionHandler?(nil)
+ }
+ case "setProxyConfig":
+ if let host = message["host"] as? String,
+ let port = message["port"] as? Int {
+ logger.info("Proxy config updated: \(host):\(port)")
+ }
+ let response = ["status": "ok"]
+ completionHandler?(try? JSONSerialization.data(withJSONObject: response))
+ case "setRules":
+ if let rules = message["rules"] as? [[String: String]] {
+ logger.info("Rules updated: \(rules.count) rules")
+ }
+ let response = ["status": "ok"]
+ completionHandler?(try? JSONSerialization.data(withJSONObject: response))
+ default:
+ completionHandler?(nil)
}
}
@@ -68,26 +91,63 @@ class AppProxyProvider: NETransparentProxyProvider {
private func logTCPConnection(_ flow: NEAppProxyTCPFlow) {
let remoteEndpoint = flow.remoteEndpoint
+ var destination = ""
+ var port = ""
if let remoteHost = remoteEndpoint as? NWHostEndpoint {
- logger.info("TCP -> \(remoteHost.hostname):\(remoteHost.port)")
+ destination = remoteHost.hostname
+ port = remoteHost.port
} else {
- logger.info("TCP -> \(String(describing: remoteEndpoint))")
+ destination = String(describing: remoteEndpoint)
+ port = "unknown"
}
+ var processName = "unknown"
if let metaData = flow.metaData as? NEFlowMetaData {
- logger.info(" App: \(metaData.sourceAppSigningIdentifier ?? "unknown")")
+ processName = metaData.sourceAppSigningIdentifier
}
+
+ sendLogToApp(protocol: "TCP", process: processName, destination: destination, port: port)
}
private func logUDPConnection(_ flow: NEAppProxyUDPFlow) {
+ var destination = ""
+ var port = ""
+
if let localEndpoint = flow.localEndpoint,
let localHost = localEndpoint as? NWHostEndpoint {
- logger.info("UDP: \(localHost.hostname):\(localHost.port)")
+ destination = localHost.hostname
+ port = localHost.port
+ } else {
+ destination = "unknown"
+ port = "unknown"
}
+ var processName = "unknown"
if let metaData = flow.metaData as? NEFlowMetaData {
- logger.info(" App: \(metaData.sourceAppSigningIdentifier ?? "unknown")")
+ processName = metaData.sourceAppSigningIdentifier
}
+
+ sendLogToApp(protocol: "UDP", process: processName, destination: destination, port: port)
+ }
+
+ private func sendLogToApp(protocol: String, process: String, destination: String, port: String) {
+ let logData: [String: String] = [
+ "type": "connection",
+ "protocol": `protocol`,
+ "process": process,
+ "destination": destination,
+ "port": port,
+ "proxy": "Direct"
+ ]
+
+ queueLock.lock()
+ logQueue.append(logData)
+ if logQueue.count > 1000 {
+ logQueue.removeFirst()
+ }
+ queueLock.unlock()
}
}
+
+
diff --git a/MacOS/ProxyBridge/extension/extension.entitlements b/MacOS/ProxyBridge/extension/extension.entitlements
index 664049b..2658e1b 100644
--- a/MacOS/ProxyBridge/extension/extension.entitlements
+++ b/MacOS/ProxyBridge/extension/extension.entitlements
@@ -6,5 +6,9 @@
<array>
<string>app-proxy-provider</string>
</array>
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>group.com.interceptsuite.ProxyBridge</string>
+ </array>
</dict>
</plist>