Android VpnService, packet forwarding

I am building a ToyVPN based application to capture tcp / udp packets. After I receive outgoing packets in my application, I would like to forward them to the original destination. I managed to get the destination IP address and port from the headers, but I have no idea how to contact the remote server, and then write the response back to the source. I think this is possible because there is an app . Here is my first first attempt:

private void runVpnConnection() throws Exception {
configure();

FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
FileOutputStream out = new FileOutputStream(
        mInterface.getFileDescriptor());

// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
boolean ok = true;

while (ok) {
    Socket tcpSocket = SocketChannel.open().socket();
    try {
        // Read the outgoing packet from the input stream.
        int length = in.read(packet.array());
        if (length > 0) {

            Log.i(TAG, "-------------------New packet: " + length);
            packet.limit(length);

            // here i get destIP and destIP

            InetAddress serverAddr = InetAddress.getByName(destIP);
            SocketAddress socketadd = new InetSocketAddress(serverAddr,
                    destPort);

            protect(tcpSocket);

            OutputStream outBuffer = tcpSocket.getOutputStream();

            outBuffer.write(packet.array());
            outBuffer.flush();
            // outBuffer.close();
            packet.clear();
        }

        if (tcpSocket.isConnected()) {
            InputStream inBuffer = tcpSocket.getInputStream();
            DataInputStream inStream = new DataInputStream(inBuffer);
            Log.i(TAG, "Response length " + inStream.available());
            if (inStream.available() > 0) {
                Log.i(TAG, "Server says " + inStream.readUTF());
                inStream.readFully(packet.array());
                out.write(packet.array());
                inBuffer.close();
            }
            out.flush();
        }
        packet.clear();
        // Thread.sleep(50);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, e.toString());
        ok = false;
    }
    tcpSocket.close();
}
in.close();
out.close();
}
+4
source share
1 answer

tPacketCapture Traffice , ( , mobiwol, greyshirts , VPNService).

( ) ToyVPN, , ( ), iptables .

, . :

mobiwol "adb shell netcfg", tun0 10.2.3.4/32. .

, , .

+3

Source: https://habr.com/ru/post/1527907/


All Articles