无需代理即可使用NEPacketTunnelProvider读取数据包

时间:2019-06-05 15:05:26

标签: ios swift macos networkextension

我想用NEPacketTunnelProvider检查没有指定代理的数据包。不幸的是,我的readPacketObjects完成处理程序从未被调用过,我也不知道为什么。我的常规Internet连接停止了,Wireshark在新界面上显然什么也没有显示,并且在en0上也没有看到任何HTTP连接。

这可能吗? Apple Developer Forums暗示可能不是...但是iOS版的Charles Proxy似乎可以检查所有内容。

我的代码如下:

class TunnelProvider: NEPacketTunnelProvider {
override func startTunnel(options: [String : NSObject]? = nil, completionHandler: @escaping (Error?) -> Void) {
    os_log("starting tunnel")

    let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "127.0.0.1")

    settings.tunnelOverheadBytes = 80
    settings.mtu = 1200

    settings.ipv4Settings = NEIPv4Settings(addresses: ["127.0.0.1", "0.0.0.0"], subnetMasks: ["0.0.0.0", "0.0.0.0"]) // all addresses
    settings.ipv4Settings?.includedRoutes = [NEIPv4Route.default()] // all routes
    settings.ipv4Settings?.excludedRoutes = [NEIPv4Route(destinationAddress: "127.0.0.1", subnetMask: "255.255.255.255")] // avoid local routes

    settings.dnsSettings = NEDNSSettings(servers: ["1.1.1.1", "8.8.8.8", "8.8.4.4"])
    settings.dnsSettings?.matchDomains = [""] // if blank don't use this DNS, use system; if "" then use this

    NSLog("default/included route %@:%@", NEIPv4Route.default().destinationAddress, NEIPv4Route.default().destinationSubnetMask)

    self.setTunnelNetworkSettings(settings) { error in
        if let e = error {
            NSLog("Settings error %@", e.localizedDescription)
            completionHandler(e)
        } else {
            os_log("Settings set without error")

            completionHandler(nil)
        }
    }

    self.readPacketObjects()
}

private func readPacketObjects() {
    NSLog("Inside readPacketObjects %@", self.packetFlow)
    self.packetFlow.readPacketObjects() { packets in
        NSLog("Inside readPacketObjects completionHandler %@", packets)

        self.packetFlow.writePacketObjects(packets)

        self.readPacketObjects()
    }
}

控制台输出

default 10:31:03.177424 -0400   tunnel  starting tunnel
default 10:31:03.177796 -0400   tunnel  default/included route 0.0.0.0:0.0.0.0
default 10:31:03.178602 -0400   tunnel  Inside readPacketObjects <NEPacketTunnelFlow: 0x7f9a69d135e0>
default 10:31:03.356006 -0400   tunnel  Settings set without error

编辑1
settings.ipv4Settings修改为具有特定子网掩码的本地地址后,我可以读取数据包。但是,互联网连接仍然断开,route get输出了错误的地址。

编辑2
通过将DNS服务器添加到排除的路由中,我能够使DNS工作,如here所示。未经修改地写入packetFlow仍无法启用完整路由。

0 个答案:

没有答案