Skip to content

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

Added DNS Proxy for domain name support in macos #33

AnoF-Cyberb80a4f213f2a
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift
index f03091b..7888b97 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift
@@ -448,7 +448,28 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
}
}
}
-
+
+ // enables the dns proxy provider so the extension can see dns resolutions and
+ // build the ip -> domain map used for domain rules
+ func startDNSProxy() {
+ let manager = NEDNSProxyManager.shared()
+ manager.loadFromPreferences { [weak self] _ in
+ guard let self = self else { return }
+ let proto = NEDNSProxyProviderProtocol()
+ proto.providerBundleIdentifier = self.extensionIdentifier
+ manager.providerProtocol = proto
+ manager.localizedDescription = "ProxyBridge DNS"
+ manager.isEnabled = true
+ manager.saveToPreferences { error in
+ if let error = error {
+ self.addLog("ERROR", "DNS proxy setup failed: \(error.localizedDescription)")
+ } else {
+ self.addLog("INFO", "DNS proxy enabled")
+ }
+ }
+ }
+ }
+
private func reloadAndStartTunnel(manager: NETransparentProxyManager) {
manager.loadFromPreferences { [weak self] loadError in
guard let self = self else { return }
@@ -710,6 +731,7 @@ extension ProxyBridgeViewModel: OSSystemExtensionRequestDelegate {
DispatchQueue.main.async {
self.addLog("INFO", "Extension installed successfully")
self.startProxy()
+ self.startDNSProxy()
}
}
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift
index 23179fe..9b7a65f 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift
@@ -443,7 +443,7 @@ struct RuleEditorView: View {
label: "Target hosts",
placeholder: "*",
text: $targetHosts,
- hint: "IPv4: 127.0.0.1; 192.168.1.*; 10.0.0.1-10.0.0.254 IPv6: ::1; 2001:db8:*; fe80::1-fe80::ff"
+ hint: "IP: 127.0.0.1; 192.168.1.*; 10.0.0.1-10.0.0.254; ::1 Domain: github.com; *.github.com; *google*"
)
formField(
diff --git a/MacOS/ProxyBridge/build.sh b/MacOS/ProxyBridge/build.sh
index 4dc1d47..693f656 100755
--- a/MacOS/ProxyBridge/build.sh
+++ b/MacOS/ProxyBridge/build.sh
@@ -39,10 +39,21 @@ mkdir -p "$SCRIPT_DIR/build/component"
cp -R "$APP_PATH" "$SCRIPT_DIR/build/component/"
+# strip AppleDouble junk so it never lands in the payload
+dot_clean "$SCRIPT_DIR/build/component" 2>/dev/null || true
+find "$SCRIPT_DIR/build/component" -name '._*' -delete 2>/dev/null || true
+
echo "Creating installer package..."
+# force BundleIsRelocatable=false so the app always installs to /Applications.
+# otherwise macOS relocates the install onto any existing copy of the app it
+# finds on disk (bundle relocation), leaving /Applications empty.
+pkgbuild --analyze --root build/component build/component.plist
+/usr/libexec/PlistBuddy -c "Set :0:BundleIsRelocatable false" build/component.plist
+
pkgbuild \
--root build/component \
+ --component-plist build/component.plist \
--identifier com.interceptsuite.ProxyBridge \
--version "$VERSION" \
--install-location /Applications \
diff --git a/MacOS/ProxyBridge/extension/AppProxyProvider.swift b/MacOS/ProxyBridge/extension/AppProxyProvider.swift
index d621251..68ce6f2 100644
--- a/MacOS/ProxyBridge/extension/AppProxyProvider.swift
+++ b/MacOS/ProxyBridge/extension/AppProxyProvider.swift
@@ -64,7 +64,29 @@ struct ProxyRule: Codable {
func matchesIP(_ ipString: String) -> Bool {
return Self.matchIPList(targetHosts, ipString: ipString)
}
-
+
+ // matches targetHosts against the destination ip and any domains that
+ // resolved to it (from the dns proxy). a pattern can be an ip/range or a
+ // domain like *.github.com
+ func matchesHost(ip: String, domains: [String]) -> Bool {
+ if targetHosts.isEmpty || targetHosts == "*" { return true }
+ for raw in targetHosts.components(separatedBy: ";") {
+ let pattern = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ if pattern.isEmpty { continue }
+ if Self.matchIPPattern(pattern, ipString: ip) { return true }
+
+ let lowered = pattern.lowercased()
+ // *.example.com also covers the apex example.com, which is what users expect
+ let apex = lowered.hasPrefix("*.") ? String(lowered.dropFirst(2)) : nil
+ for domain in domains {
+ if Self.globMatch(lowered, domain) { return true }
+ if let apex = apex, domain == apex { return true }
+ }
+ }
+ return false
+ }
+
+
func matchesPort(_ port: UInt16) -> Bool {
return Self.matchPortList(targetPorts, port: port)
}
@@ -556,24 +578,29 @@ class AppProxyProvider: NETransparentProxyProvider {
let processName = getProcessName(from: metaData)
let displayName = processName ?? processPath
+ // domains that resolved to this ip (from the dns proxy), used for domain
+ // rules and to show the hostname in the log instead of the raw ip
+ let domains = DNSMapStore.shared.domains(forIP: destination)
+ let logDest = domains.first ?? destination
+
proxyLock.lock()
let hasProxyConfig = !storedProxyConfigs.isEmpty
proxyLock.unlock()
if !hasProxyConfig {
- sendLogToApp(protocol: "TCP", process: displayName, destination: destination, port: portStr, proxy: "Direct")
+ sendLogToApp(protocol: "TCP", process: displayName, destination: logDest, port: portStr, proxy: "Direct")
return false
}
- let matchedRule = findMatchingRule(bundleId: processPath, processName: processName, destination: destination, port: portNum, connectionProtocol: .tcp, checkIpPort: true)
+ let matchedRule = findMatchingRule(bundleId: processPath, processName: processName, destination: destination, port: portNum, connectionProtocol: .tcp, checkIpPort: true, domains: domains)
if let rule = matchedRule {
switch rule.action {
case "DIRECT":
- sendLogToApp(protocol: "TCP", process: displayName, destination: destination, port: portStr, proxy: "Direct")
+ sendLogToApp(protocol: "TCP", process: displayName, destination: logDest, port: portStr, proxy: "Direct")
return false
case "BLOCK":
- sendLogToApp(protocol: "TCP", process: displayName, destination: destination, port: portStr, proxy: "BLOCK")
+ sendLogToApp(protocol: "TCP", process: displayName, destination: logDest, port: portStr, proxy: "BLOCK")
flow.closeReadWithError(nil)
flow.closeWriteWithError(nil)
return true
@@ -583,15 +610,15 @@ class AppProxyProvider: NETransparentProxyProvider {
proxyLock.unlock()
guard let config = config else {
// rule points at a proxy that no longer exists, let it go direct
- sendLogToApp(protocol: "TCP", process: displayName, destination: destination, port: portStr, proxy: "Direct")
+ sendLogToApp(protocol: "TCP", process: displayName, destination: logDest, port: portStr, proxy: "Direct")
return false
}
- sendLogToApp(protocol: "TCP", process: displayName, destination: destination, port: portStr, proxy: proxyLabel(config))
+ sendLogToApp(protocol: "TCP", process: displayName, destination: logDest, port: portStr, proxy: proxyLabel(config))
proxyTCPFlow(flow, destination: destination, port: portNum, config: config)
return true
}
} else {
- sendLogToApp(protocol: "TCP", process: displayName, destination: destination, port: portStr, proxy: "Direct")
+ sendLogToApp(protocol: "TCP", process: displayName, destination: logDest, port: portStr, proxy: "Direct")
return false
}
}
@@ -893,18 +920,14 @@ class AppProxyProvider: NETransparentProxyProvider {
return
}
- // nil datagrams with no error = flow closed cleanly
- guard let datagrams = datagrams, let endpoints = endpoints else {
+ // nil or empty datagrams with no error = flow closed for reading.
+ // re-arming on empty spins at 100% cpu because the read completes
+ // immediately forever once the flow is closed (issue #89 / pr #90)
+ guard let datagrams = datagrams, let endpoints = endpoints, !datagrams.isEmpty else {
self.teardownUDP(clientFlow)
return
}
- // non-nil but empty = nothing this round, just re-arm
- guard !datagrams.isEmpty else {
- self.readAndForwardClientUDP(association)
- return
- }
-
var toSend: [Data] = []
toSend.reserveCapacity(datagrams.count)
@@ -1367,13 +1390,13 @@ class AppProxyProvider: NETransparentProxyProvider {
}
}
- private func findMatchingRule(bundleId: String, processName: String?, destination: String, port: UInt16, connectionProtocol: RuleProtocol, checkIpPort: Bool) -> ProxyRule? {
+ private func findMatchingRule(bundleId: String, processName: String?, destination: String, port: UInt16, connectionProtocol: RuleProtocol, checkIpPort: Bool, domains: [String] = []) -> ProxyRule? {
rulesLock.lock()
let currentRules = rules
rulesLock.unlock()
-
+
var wildcardRule: ProxyRule? = nil
-
+
for rule in currentRules {
guard rule.enabled else { continue }
@@ -1389,7 +1412,7 @@ class AppProxyProvider: NETransparentProxyProvider {
if hasIpFilter || hasPortFilter {
// udp has no destination here, so a filtered wildcard can't match
- if checkIpPort, rule.matchesIP(destination), rule.matchesPort(port) {
+ if checkIpPort, rule.matchesHost(ip: destination, domains: domains), rule.matchesPort(port) {
return rule
}
continue
@@ -1404,7 +1427,7 @@ class AppProxyProvider: NETransparentProxyProvider {
if rule.matchesProcess(bundleId: bundleId, processName: processName) {
if checkIpPort {
- if rule.matchesIP(destination) && rule.matchesPort(port) {
+ if rule.matchesHost(ip: destination, domains: domains) && rule.matchesPort(port) {
return rule
}
} else {
diff --git a/MacOS/ProxyBridge/extension/DNSMapStore.swift b/MacOS/ProxyBridge/extension/DNSMapStore.swift
new file mode 100644
index 0000000..fadeeb7
--- /dev/null
+++ b/MacOS/ProxyBridge/extension/DNSMapStore.swift
@@ -0,0 +1,94 @@
+import Foundation
+
+// Shared IP -> domain map, populated by the DNS proxy and read by the transparent
+// proxy. The two providers can run in separate processes, so the map lives in a
+// file in the app group container. Each process keeps an in-memory copy; the
+// reader reloads only when the file's mtime changes.
+final class DNSMapStore {
+ static let shared = DNSMapStore()
+
+ private let appGroup = "group.com.interceptsuite.ProxyBridge"
+ private let fileURL: URL?
+ private let lock = NSLock()
+ private var map: [String: Set<String>] = [:] // ip -> domains
+ private var order: [String] = [] // insertion order for eviction
+ private let maxEntries = 1024
+ private var lastMtime: Date?
+
+ private init() {
+ fileURL = FileManager.default
+ .containerURL(forSecurityApplicationGroupIdentifier: appGroup)?
+ .appendingPathComponent("dnsmap.json")
+ }
+
+ // wipe the map and its file. called on start so browsing domains don't
+ // linger on disk across sessions.
+ func clear() {
+ lock.lock()
+ map.removeAll()
+ order.removeAll()
+ lastMtime = nil
+ lock.unlock()
+ if let fileURL = fileURL { try? FileManager.default.removeItem(at: fileURL) }
+ }
+
+ // writer side (DNS proxy): remember that these IPs resolved for this domain
+ func record(domain: String, ips: [String]) {
+ let name = domain.lowercased()
+ guard !name.isEmpty, !ips.isEmpty else { return }
+
+ var changed = false
+ lock.lock()
+ for ip in ips {
+ if map[ip] == nil {
+ map[ip] = []
+ order.append(ip)
+ changed = true
+ if order.count > maxEntries {
+ let evicted = order.removeFirst()
+ map[evicted] = nil
+ }
+ }
+ if map[ip]?.insert(name).inserted == true { changed = true }
+ }
+ // only touch the file when something actually changed, most resolutions
+ // are repeats of already-known domains
+ let snapshot = changed ? map : nil
+ lock.unlock()
+
+ if let snapshot = snapshot { persist(snapshot) }
+ }
+
+ // reader side (transparent proxy): domains that resolved to this ip, if any
+ func domains(forIP ip: String) -> [String] {
+ reloadIfChanged()
+ lock.lock()
+ defer { lock.unlock() }
+ return Array(map[ip] ?? [])
+ }
+
+ private func persist(_ snapshot: [String: Set<String>]) {
+ guard let fileURL = fileURL else { return }
+ let plain = snapshot.mapValues { Array($0) }
+ guard let data = try? JSONSerialization.data(withJSONObject: plain) else { return }
+ try? data.write(to: fileURL, options: .atomic)
+ }
+
+ private func reloadIfChanged() {
+ guard let fileURL = fileURL else { return }
+ let mtime = (try? FileManager.default.attributesOfItem(atPath: fileURL.path)[.modificationDate]) as? Date
+ lock.lock()
+ let needsReload = mtime != nil && mtime != lastMtime
+ if needsReload { lastMtime = mtime }
+ lock.unlock()
+
+ guard needsReload,
+ let data = try? Data(contentsOf: fileURL),
+ let plain = try? JSONSerialization.jsonObject(with: data) as? [String: [String]] else {
+ return
+ }
+ lock.lock()
+ map = plain.mapValues { Set($0) }
+ lock.unlock()
+ }
+}
diff --git a/MacOS/ProxyBridge/extension/DNSProxyProvider.swift b/MacOS/ProxyBridge/extension/DNSProxyProvider.swift
new file mode 100644
index 0000000..5f5d820
--- /dev/null
+++ b/MacOS/ProxyBridge/extension/DNSProxyProvider.swift
@@ -0,0 +1,178 @@
+import NetworkExtension
+
+// Intercepts system DNS, forwards each query to the real resolver, and records
+// the resulting IP -> domain mapping so the transparent proxy can match rules by
+// domain. DoH/DoT that an app does itself is not visible here (by design).
+class DNSProxyProvider: NEDNSProxyProvider {
+ private var sessions = Set<NWUDPSession>()
+ private let sessionsLock = NSLock()
+
+ override func startProxy(options: [String: Any]?, completionHandler: @escaping (Error?) -> Void) {
+ // start with a clean map so old browsing domains don't linger on disk
+ DNSMapStore.shared.clear()
+ completionHandler(nil)
+ }
+
+ override func stopProxy(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
+ sessionsLock.lock()
+ let all = sessions
+ sessions.removeAll()
+ sessionsLock.unlock()
+ all.forEach { $0.cancel() }
+ DNSMapStore.shared.clear()
+ completionHandler()
+ }
+
+ override func handleNewFlow(_ flow: NEAppProxyFlow) -> Bool {
+ // only proxy udp dns, let tcp dns (large responses) pass through untouched
+ guard let udp = flow as? NEAppProxyUDPFlow else { return false }
+ udp.open(withLocalEndpoint: nil) { [weak self] error in
+ guard error == nil, let self = self else {
+ udp.closeReadWithError(error)
+ udp.closeWriteWithError(error)
+ return
+ }
+ self.readQueries(udp)
+ }
+ return true
+ }
+
+ private func readQueries(_ flow: NEAppProxyUDPFlow) {
+ flow.readDatagrams { [weak self] datagrams, endpoints, error in
+ guard let self = self else { return }
+
+ guard error == nil, let datagrams = datagrams, let endpoints = endpoints, !datagrams.isEmpty else {
+ flow.closeReadWithError(nil)
+ flow.closeWriteWithError(nil)
+ return
+ }
+
+ for i in 0..<min(datagrams.count, endpoints.count) {
+ guard let server = endpoints[i] as? NWHostEndpoint else { continue }
+ self.forward(query: datagrams[i], to: server, on: flow)
+ }
+
+ self.readQueries(flow)
+ }
+ }
+
+ // forward one query to its resolver, parse the reply, write it back
+ private func forward(query: Data, to server: NWHostEndpoint, on flow: NEAppProxyUDPFlow) {
+ let session = createUDPSession(to: server, from: nil)
+ sessionsLock.lock(); sessions.insert(session); sessionsLock.unlock()
+
+ session.setReadHandler({ [weak self, weak session] responses, _ in
+ guard let self = self else { return }
+ if let responses = responses {
+ for response in responses {
+ if let parsed = DNSParser.parse(response) {
+ DNSMapStore.shared.record(domain: parsed.domain, ips: parsed.ips)
+ }
+ flow.writeDatagrams([response], sentBy: [server]) { _ in }
+ }
+ }
+ // a dns exchange is one response, drop the session afterwards
+ if let session = session { self.drop(session) }
+ }, maxDatagrams: 4)
+
+ session.writeDatagram(query) { _ in }
+
+ // safety net: a dropped/unanswered query must not leak the session forever
+ DispatchQueue.global().asyncAfter(deadline: .now() + 5) { [weak self, weak session] in
+ if let session = session { self?.drop(session) }
+ }
+ }
+
+ private func drop(_ session: NWUDPSession) {
+ sessionsLock.lock()
+ let present = sessions.remove(session) != nil
+ sessionsLock.unlock()
+ if present { session.cancel() }
+ }
+}
+
+// Minimal DNS message parser: pulls the queried name and its A/AAAA answers.
+enum DNSParser {
+ static func parse(_ data: Data) -> (domain: String, ips: [String])? {
+ let b = [UInt8](data)
+ guard b.count >= 12 else { return nil }
+
+ let qdCount = Int(b[4]) << 8 | Int(b[5])
+ let anCount = Int(b[6]) << 8 | Int(b[7])
+ guard qdCount >= 1 else { return nil }
+
+ var i = 12
+ guard let qname = readName(b, &i), i + 4 <= b.count else { return nil }
+ i += 4 // QTYPE + QCLASS
+
+ // skip any extra questions (rare)
+ if qdCount > 1 {
+ for _ in 1..<qdCount {
+ guard skipName(b, &i), i + 4 <= b.count else { return nil }
+ i += 4
+ }
+ }
+
+ var ips: [String] = []
+ for _ in 0..<anCount {
+ guard skipName(b, &i), i + 10 <= b.count else { break }
+ let type = Int(b[i]) << 8 | Int(b[i + 1])
+ let rdlen = Int(b[i + 8]) << 8 | Int(b[i + 9])
+ i += 10
+ guard i + rdlen <= b.count else { break }
+
+ if type == 1, rdlen == 4 {
+ ips.append("\(b[i]).\(b[i + 1]).\(b[i + 2]).\(b[i + 3])")
+ } else if type == 28, rdlen == 16 {
+ var parts: [String] = []
+ for k in stride(from: 0, to: 16, by: 2) {
+ parts.append(String(format: "%x", Int(b[i + k]) << 8 | Int(b[i + k + 1])))
+ }
+ ips.append(parts.joined(separator: ":"))
+ }
+ i += rdlen
+ }
+
+ return ips.isEmpty ? nil : (qname.lowercased(), ips)
+ }
+
+ // reads a name into a string, following compression pointers
+ private static func readName(_ b: [UInt8], _ i: inout Int) -> String? {
+ var labels: [String] = []
+ var j = i
+ var jumped = false
+ var hops = 0
+ while j < b.count {
+ hops += 1
+ if hops > 128 { return nil }
+ let len = Int(b[j])
+ if len == 0 {
+ if !jumped { i = j + 1 }
+ break
+ }
+ if len & 0xC0 == 0xC0 {
+ guard j + 1 < b.count else { return nil }
+ if !jumped { i = j + 2 }
+ jumped = true
+ j = (len & 0x3F) << 8 | Int(b[j + 1])
+ continue
+ }
+ guard j + 1 + len <= b.count else { return nil }
+ labels.append(String(bytes: b[(j + 1)..<(j + 1 + len)], encoding: .utf8) ?? "")
+ j += 1 + len
+ }
+ return labels.joined(separator: ".")
+ }
+
+ // advances the offset past a name without decoding it
+ private static func skipName(_ b: [UInt8], _ i: inout Int) -> Bool {
+ var j = i
+ while j < b.count {
+ let len = Int(b[j])
+ if len == 0 { i = j + 1; return true }
+ if len & 0xC0 == 0xC0 { i = j + 2; return true }
+ j += 1 + len
+ }
+ return false
+ }
+}
diff --git a/MacOS/ProxyBridge/extension/Info.plist b/MacOS/ProxyBridge/extension/Info.plist
index ace0ec2..d8efaf6 100644
--- a/MacOS/ProxyBridge/extension/Info.plist
+++ b/MacOS/ProxyBridge/extension/Info.plist
@@ -12,6 +12,8 @@
<dict>
<key>com.apple.networkextension.app-proxy</key>
<string>$(PRODUCT_MODULE_NAME).AppProxyProvider</string>
+ <key>com.apple.networkextension.dns-proxy</key>
+ <string>$(PRODUCT_MODULE_NAME).DNSProxyProvider</string>
</dict>
</dict>
</dict>