diff --git a/Tun/Punchnet/IPPacket.swift b/Tun/Punchnet/NetworkStack/IPPacket.swift similarity index 81% rename from Tun/Punchnet/IPPacket.swift rename to Tun/Punchnet/NetworkStack/IPPacket.swift index 89543ab..0f1fe4f 100644 --- a/Tun/Punchnet/IPPacket.swift +++ b/Tun/Punchnet/NetworkStack/IPPacket.swift @@ -15,26 +15,17 @@ struct IPHeader { let id: UInt16 let offset: UInt16 let timeToLive: UInt8 - let proto:UInt8 + let proto: UInt8 let checksum: UInt16 let source: UInt32 let destination: UInt32 var source_ip: String { - return intToIp(source) + return SDLUtil.int32ToIp(source) } var destination_ip: String { - return intToIp(destination) - } - - private func intToIp(_ num: UInt32) -> String { - let ip0 = (UInt8) (num >> 24 & 0xFF) - let ip1 = (UInt8) (num >> 16 & 0xFF) - let ip2 = (UInt8) (num >> 8 & 0xFF) - let ip3 = (UInt8) (num & 0xFF) - - return "\(ip0).\(ip1).\(ip2).\(ip3)" + return SDLUtil.int32ToIp(destination) } public var description: String { @@ -83,4 +74,15 @@ struct IPPacket { func getPayload() -> Data { return data.subdata(in: 20.. UInt16? { + guard case .ipv4 = IPVersion(rawValue: self.header.version), self.data.count >= 24 else { + return nil + } + + // 系统只会读取到ipv4的数据包,(srcPort:16, dstPort:16, ...) + return UInt16(bytes: (self.data[22], self.data[23])) + } + } diff --git a/Tun/Punchnet/LayerPacket.swift b/Tun/Punchnet/NetworkStack/LayerPacket.swift similarity index 100% rename from Tun/Punchnet/LayerPacket.swift rename to Tun/Punchnet/NetworkStack/LayerPacket.swift diff --git a/Tun/Punchnet/SDLContextActor.swift b/Tun/Punchnet/SDLContextActor.swift index 1fd536b..6475c79 100644 --- a/Tun/Punchnet/SDLContextActor.swift +++ b/Tun/Punchnet/SDLContextActor.swift @@ -498,9 +498,18 @@ actor SDLContextActor { // 检查权限逻辑 let identitySnapshot = self.snapshotPublisher.current() if let ruleMap = identitySnapshot.lookup(data.identityID) { - if ruleMap.isAllow(proto: 2, port: 3) { + let proto = ipPacket.header.proto + switch TransportProtocol(rawValue: proto) { + case .udp, .tcp: + if let dstPort = ipPacket.getDstPort(), ruleMap.isAllow(proto: proto, port: dstPort) { + let packet = NEPacket(data: ipPacket.data, protocolFamily: 2) + self.provider.packetFlow.writePacketObjects([packet]) + } + case .icmp: let packet = NEPacket(data: ipPacket.data, protocolFamily: 2) self.provider.packetFlow.writePacketObjects([packet]) + default: + () } } else { // 向服务器请求权限逻辑