Android firewall z VpnService
[6]}próbuję zaimplementować prosty firewall dla Androida z vpnservice dla projektu BS. Wybieram VpnService, ponieważ będzie działać na urządzeniach Nie zakorzenionych. Rejestruje połączenia i pozwala filtrować połączenie. (Na podstawie IP)
Istnieje aplikacja, która to robi, więc jest to możliwe.
Poszperałem trochę i odkryłem, że vpnservice tworzy interfejs Tun. Nic więcej. (Brak implementacji VPN tylko tunel) pozwala dać adres do tego interfejsu i dodaj trasy. Zwraca deskryptor pliku. Możesz odczytywać Pakiety wychodzące i zapisywać pakiety przychodzące.
Stworzyłem klasę pochodną VpnService i uruchomiłem usługę. Mogę skonfigurować tun0
za pomocą VpnService.Klasa budowniczego. Kiedy patrzę na mobiwol's
Połączenie z adb shell netcfg
tworzy interfejs tun0
o adresie 10.2.3.4/32. Przekierowuje wszystkie pakiety do tej sieci prywatnej i wysyła do Internetu. Próbuję tego samego. Utworzono interfejs z adresem 10.0.0.2/32. Dodał a trasa z funkcją addRoute. 0.0.0.0 / 0 więc mogę przechwycić wszystkie pakiety z całej sieci o ile rozumiem. (Jestem całkiem nowy w tym temacie i wciąż się uczę. Znalazłem kawałki przez internet, więc nie jestem pewien. Popraw mnie, jeśli się mylę.)
Utworzyłem 2 wątki w serwisie. Czyta się z deskryptora pliku i zapisuje go do 127.0.0.1 z chronionym gniazdem. (Nie jestem pewien, czy powinienem czytać/pisać do 127.0.0.1. Może w tym tkwi problem. )
Przeanalizowałem pakiety, które przeczytałem z deskryptora pliku. Na przykład:
01000101 byte:69 //ipv4 20byte header
00000000 byte:0 //TOS
00000000 byte:0 //Total Length
00111100 byte:60 //Total Length
11111100 byte:-4 //ID
11011011 byte:-37 //ID
01000000 byte:64 //fragment
00000000 byte:0 //"
01000000 byte:64 //TTL
00000110 byte:6 //Protocol 6 -> TCP
01011110 byte:94 //Header checksum
11001111 byte:-49 //Header checksum
00001010 byte:10 //10.0.0.2
00000000 byte:0
00000000 byte:0
00000010 byte:2
10101101 byte:-83 //173.194.39.78 //google
00111110 byte:-62
00100111 byte:39
******** byte:78
10110100 byte:-76 // IP option
01100101 byte:101
00000001 byte:1
10111011 byte:-69
//20byte IP haeder
01101101 byte:109
. . //40byte data (i couldnt parse TCP header,
I think its not needed when I route this in IP layer)
. .
. .
00000110 byte:6
Nie znalazłem żadnego innego nagłówka IP w reszcie danych. Myślę, że powinna istnieć enkapsulacja między siecią 10.0.0.2 do sieci lokalnej (192.168.2.1) i Internetem. Nie jestem pewien.
Moim prawdziwym problemem jest to, że utknąłem w wątku nadchodzących pakietów. Nic nie umiem czytać. Brak odpowiedzi. Jak widać na zrzucie ekranu Brak przychodzących danych:
Próbuję odczytać z tego samego połączenia, którego używam do zapisu do 127.0.0.1 z chronionym gniazdem.
Android interfejs Tun (tun0) połączenie internetowe
Wszystkie pakiety 10.0.0.2 127.0.0.1? 192.168.2.1 Internet?
Nie mogłem znaleźć niczego pomocnego na temat VpnService. (Przykład ToyVPN jest po prostu bezużyteczny) czytałem dokumenty o Linuksie Tun / Tap, ale jego o tunelowaniu między hostem a zdalnym. Chcę hosta i pilota na tym samym urządzeniu. Nie jak tunelowanie.
Jak mogę to zrobić?Edit: Code / align = "left" / Jest na bardzo wczesnym etapie. Jak wspomniałem wcześniej, jest to klasa pochodna VpnService. 2 wątki (odczyt i zapis) utworzone w wątku serwisowym.
package com.git.firewall;
public class GITVpnService extends VpnService implements Handler.Callback, Runnable {
private static final String TAG = "GITVpnService";
private String mServerAddress = "127.0.0.1";
private int mServerPort = 55555;
private PendingIntent mConfigureIntent;
private Handler mHandler;
private Thread mThread;
private ParcelFileDescriptor mInterface;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Stop the previous session by interrupting the thread.
if (mThread != null) {
mThread.interrupt();
}
// Start a new session by creating a new thread.
mThread = new Thread(this, "VpnThread");
mThread.start();
return START_STICKY;
}
@Override
public void onDestroy() {
if (mThread != null) {
mThread.interrupt();
}
}
@Override
public boolean handleMessage(Message message) {
if (message != null) {
Toast.makeText(this, (String)message.obj, Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public synchronized void run() {
try {
Log.i(TAG, "Starting");
InetSocketAddress server = new InetSocketAddress(
mServerAddress, mServerPort);
run(server);
} catch (Exception e) {
Log.e(TAG, "Got " + e.toString());
try {
mInterface.close();
} catch (Exception e2) {
// ignore
}
Message msgObj = mHandler.obtainMessage();
msgObj.obj = "Disconnected";
mHandler.sendMessage(msgObj);
} finally {
}
}
DatagramChannel mTunnel = null;
private boolean run(InetSocketAddress server) throws Exception {
boolean connected = false;
android.os.Debug.waitForDebugger();
// Create a DatagramChannel as the VPN tunnel.
mTunnel = DatagramChannel.open();
// Protect the tunnel before connecting to avoid loopback.
if (!protect(mTunnel.socket())) {
throw new IllegalStateException("Cannot protect the tunnel");
}
// Connect to the server.
mTunnel.connect(server);
// For simplicity, we use the same thread for both reading and
// writing. Here we put the tunnel into non-blocking mode.
mTunnel.configureBlocking(false);
// Authenticate and configure the virtual network interface.
handshake();
// Now we are connected. Set the flag and show the message.
connected = true;
Message msgObj = mHandler.obtainMessage();
msgObj.obj = "Connected";
mHandler.sendMessage(msgObj);
new Thread ()
{
public void run ()
{
// Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
int length;
try
{
while (true)
{
while ((length = in.read(packet.array())) > 0) {
// Write the outgoing packet to the tunnel.
packet.limit(length);
debugPacket(packet); // Packet size, Protocol, source, destination
mTunnel.write(packet);
packet.clear();
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}.start();
new Thread ()
{
public void run ()
{
DatagramChannel tunnel = mTunnel;
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(8096);
// Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(mInterface.getFileDescriptor());
while (true)
{
try
{
// Read the incoming packet from the tunnel.
int length;
while ((length = tunnel.read(packet)) > 0)
{
// Write the incoming packet to the output stream.
out.write(packet.array(), 0, length);
packet.clear();
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}.start();
return connected;
}
private void handshake() throws Exception {
if (mInterface == null)
{
Builder builder = new Builder();
builder.setMtu(1500);
builder.addAddress("10.0.0.2",32);
builder.addRoute("0.0.0.0", 0);
//builder.addRoute("192.168.2.0",24);
//builder.addDnsServer("8.8.8.8");
// Close the old interface since the parameters have been changed.
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
// Create a new interface using the builder and save the parameters.
mInterface = builder.setSession("GIT VPN")
.setConfigureIntent(mConfigureIntent)
.establish();
}
}
private void debugPacket(ByteBuffer packet)
{
/*
for(int i = 0; i < length; ++i)
{
byte buffer = packet.get();
Log.d(TAG, "byte:"+buffer);
}*/
int buffer = packet.get();
int version;
int headerlength;
version = buffer >> 4;
headerlength = buffer & 0x0F;
headerlength *= 4;
Log.d(TAG, "IP Version:"+version);
Log.d(TAG, "Header Length:"+headerlength);
String status = "";
status += "Header Length:"+headerlength;
buffer = packet.get(); //DSCP + EN
buffer = packet.getChar(); //Total Length
Log.d(TAG, "Total Length:"+buffer);
buffer = packet.getChar(); //Identification
buffer = packet.getChar(); //Flags + Fragment Offset
buffer = packet.get(); //Time to Live
buffer = packet.get(); //Protocol
Log.d(TAG, "Protocol:"+buffer);
status += " Protocol:"+buffer;
buffer = packet.getChar(); //Header checksum
String sourceIP = "";
buffer = packet.get(); //Source IP 1st Octet
sourceIP += buffer;
sourceIP += ".";
buffer = packet.get(); //Source IP 2nd Octet
sourceIP += buffer;
sourceIP += ".";
buffer = packet.get(); //Source IP 3rd Octet
sourceIP += buffer;
sourceIP += ".";
buffer = packet.get(); //Source IP 4th Octet
sourceIP += buffer;
Log.d(TAG, "Source IP:"+sourceIP);
status += " Source IP:"+sourceIP;
String destIP = "";
buffer = packet.get(); //Destination IP 1st Octet
destIP += buffer;
destIP += ".";
buffer = packet.get(); //Destination IP 2nd Octet
destIP += buffer;
destIP += ".";
buffer = packet.get(); //Destination IP 3rd Octet
destIP += buffer;
destIP += ".";
buffer = packet.get(); //Destination IP 4th Octet
destIP += buffer;
Log.d(TAG, "Destination IP:"+destIP);
status += " Destination IP:"+destIP;
/*
msgObj = mHandler.obtainMessage();
msgObj.obj = status;
mHandler.sendMessage(msgObj);
*/
//Log.d(TAG, "version:"+packet.getInt());
//Log.d(TAG, "version:"+packet.getInt());
//Log.d(TAG, "version:"+packet.getInt());
}
}
2 answers
Podobne pytanie zadano kilka miesięcy temu i chociaż odpowiedzi nie są zbyt wnikliwe, komentarze w zaakceptowanej odpowiedzi dają pewien wgląd w to, co może pójść nie tak.
Należy pamiętać, która warstwa w modelu OSI znajduje się twoja logika:
-
Przychodzące i wychodzące strumienie usługi VPN znajdują się w warstwie sieciowej; odbierasz (i powinieneś z kolei transmitować) surowe pakiety IP, jak opisujesz w swoim pytanie.
W przykładowym strumieniu bajtów możesz zobaczyć, że przychodzący strumień bajtów jest datagramem IPv4, ponieważ pierwsze cztery bity to
0100
(4). Więcej informacji na temat IPv4 można znaleźć w specyfikacji struktury pakietów . -
Podczas przesyłania żądań znajdujesz się w warstwie aplikacji; powinieneś przesyłać zawartość ładunku UDP lub TCP (tj. tylko ich dane, a nie same nagłówki) za pomocą odpowiednio DatagramSocket lub Gniazdo.
Należy pamiętać, że pomija to warstwę transportową, ponieważ implementacje te zajmują się konstruowaniem nagłówka UDP (w przypadku DatagramSocket) oraz nagłówka i opcji TCP (w przypadku Socket).
Twoja aplikacja będzie zasadniczo musiała być w stanie interpretować i konstruować nagłówki i opcje IPv4 i IPv6, a jako ładunek IP, nagłówki UDP i nagłówki i opcje TCP.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:43
Może lepiej poszukać projektów open source, takich jak OpenVpn . Działa na poziomie API 14+ (Ice Cream Sandwhich) bez dostępu do roota .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-30 04:20:17