Android firewall with VpnService

A similar question was asked a few months ago, and while the answers there aren’t very insightful, the comments in the accepted answer give some insight into what may be going wrong.

You should bear in mind which layer in the OSI model your logic resides:

  • Incoming and outgoing streams of the VpnService are in the network layer; you are receiving (and should in turn be transmitting) raw IP packets, as you describe in your question.

    In your sample byte stream, you can see that the incoming byte stream is an IPv4 datagram as the first four bits are 0100 (4). Consult this packet structure specification for details on IPv4.

  • When forwarding the requests, you are in the application layer; you should be transmitting the contents of the UDP or TCP payload (i.e. only their data, not the headers themselves) using respectively a DatagramSocket or a Socket.

    Bear in mind that this skips the transport layer as those implementations take care of constructing the UDP header (in case of DatagramSocket) and the TCP header and options (in case of Socket).

Your application will essentially need to be able to interpret and construct IPv4 and IPv6 headers and options, and as the IP payload, the UDP headers and TCP headers and options.

Leave a Comment