android.net.VpnService Java Examples

The following examples show how to use android.net.VpnService. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RelayTunnel.java    From gnirehtet with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public static RelayTunnel open(VpnService vpnService) throws IOException {
    Log.d(TAG, "Opening a new relay tunnel...");
    // since we use a local socket, we don't need to protect the socket from the vpnService anymore
    // but this is an implementation detail, so keep the method signature
    return new RelayTunnel();
}
 
Example #2
Source File: NetBareThread.java    From NetBare with MIT License 6 votes vote down vote up
private PacketsTransfer(VpnService service, NetBareConfig config) throws IOException {
	int mtu = config.mtu;
	String localIp = config.address.address;
	UidDumper uidDumper = config.dumpUid ? new UidDumper(localIp, config.uidProvider) : null;
	// Register all supported protocols here.
	this.mForwarderRegistry = new LinkedHashMap<>(3);
	// TCP
	this.mForwarderRegistry.put(Protocol.TCP, new TcpProxyServerForwarder(service, localIp, mtu,
			uidDumper));
	// UDP
	this.mForwarderRegistry.put(Protocol.UDP, new UdpProxyServerForwarder(service, mtu,
			uidDumper));
	// ICMP
	this.mForwarderRegistry.put(Protocol.ICMP, new IcmpProxyServerForwarder());

	buffer = new byte[mtu];
}
 
Example #3
Source File: TcpProxyServer.java    From NetBare with MIT License 6 votes vote down vote up
TcpProxyServer(VpnService vpnService, String ip, int mtu)
        throws IOException {
    super("TcpProxyServer");
    this.mVpnService = vpnService;

    this.mSelector = Selector.open();
    this.mServerSocketChannel = ServerSocketChannel.open();
    this.mServerSocketChannel.configureBlocking(false);
    this.mServerSocketChannel.socket().bind(new InetSocketAddress(0));
    this.mServerSocketChannel.register(mSelector, SelectionKey.OP_ACCEPT);

    this.mIp = NetBareUtils.convertIp(ip);
    this.mPort = (short) mServerSocketChannel.socket().getLocalPort();
    this.mMtu = mtu;

    NetBareLog.v("[TCP]proxy server: %s:%d", ip, NetBareUtils.convertPort(mPort));
}
 
Example #4
Source File: ServerActivity.java    From EasyVPN-Free with GNU General Public License v3.0 6 votes vote down vote up
private void startVpn() {
    stopwatch = new Stopwatch();
    connectedServer = currentServer;
    hideCurrentConnection = true;
    adbBlockCheck.setEnabled(false);

    Intent intent = VpnService.prepare(this);

    if (intent != null) {
        VpnStatus.updateStateString("USER_VPN_PERMISSION", "", R.string.state_user_vpn_permission,
                VpnStatus.ConnectionStatus.LEVEL_WAITING_FOR_USER_INPUT);
        // Start the query
        try {
            startActivityForResult(intent, START_VPN_PROFILE);
        } catch (ActivityNotFoundException ane) {
            // Shame on you Sony! At least one user reported that
            // an official Sony Xperia Arc S image triggers this exception
            VpnStatus.logError(R.string.no_vpn_support_image);
        }
    } else {
        onActivityResult(START_VPN_PROFILE, Activity.RESULT_OK, null);
    }
}
 
Example #5
Source File: BootCompleteReceiver.java    From InviZible with GNU General Public License v3.0 6 votes vote down vote up
private void stopServicesForeground(Context context, OperationMode mode, boolean fixTTL) {
    if (mode == VPN_MODE || mode == ROOT_MODE && fixTTL) {
        Intent stopVPNServiceForeground = new Intent(context, VpnService.class);
        stopVPNServiceForeground.setAction(actionStopServiceForeground);
        if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            context.startService(stopVPNServiceForeground);
        } else {
            context.startForegroundService(stopVPNServiceForeground);
        }

    }

    Intent stopModulesServiceForeground = new Intent(context, ModulesService.class);
    stopModulesServiceForeground.setAction(actionStopServiceForeground);
    if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        context.startService(stopModulesServiceForeground);
    } else {
        context.startForegroundService(stopModulesServiceForeground);
    }

    Log.i(LOG_TAG, "BootCompleteReceiver stop running services foreground");
}
 
Example #6
Source File: AutoStarter.java    From Intra with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(final Context context, Intent intent) {
  if (!Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
    return;
  }
  LogWrapper.log(Log.DEBUG, LOG_TAG, "Boot event");
  final VpnController controller = VpnController.getInstance();
  VpnState state = controller.getState(context);
  if (state.activationRequested && !state.on) {
    LogWrapper.log(Log.DEBUG, LOG_TAG, "Autostart enabled");
    if (VpnService.prepare(context) != null) {
      // prepare() returns a non-null intent if VPN permission has not been granted.
      LogWrapper.log(Log.WARN, LOG_TAG, "VPN permission not granted.  Starting UI.");
      Intent startIntent = new Intent(context, MainActivity.class);
      startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      context.startActivity(startIntent);
      return;
    }
    // Delay start until after the remote configuration has been updated, or failed to update.
    RemoteConfig.update().addOnCompleteListener(success -> controller.start(context));
  }
}
 
Example #7
Source File: IntraTileService.java    From Intra with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick() {
    VpnState vpnState = VpnController.getInstance().getState(this);

    if (vpnState.activationRequested) {
        VpnController.getInstance().stop(this);
    } else {
        if (VpnService.prepare(this) == null) {
            // Start VPN service when VPN permission has been granted.
            VpnController.getInstance().start(this);
        } else {
            // Open Main activity when VPN permission has not been granted.
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityAndCollapse(intent);
        }
    }
}
 
Example #8
Source File: IntraVpnService.java    From Intra with Apache License 2.0 6 votes vote down vote up
public VpnService.Builder newBuilder() {
  VpnService.Builder builder = new VpnService.Builder();
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Some WebRTC apps rely on the ability to bind to specific interfaces, which is only
    // possible if we allow bypass.
    builder = builder.allowBypass();

    try {
      // Workaround for any app incompatibility bugs.
      for (String packageName : PersistentState.getExcludedPackages(this)) {
        builder = builder.addDisallowedApplication(packageName);
      }
      // Play Store incompatibility is a known issue, so always exclude it.
      builder = builder.addDisallowedApplication("com.android.vending");
    } catch (PackageManager.NameNotFoundException e) {
      LogWrapper.logException(e);
      Log.e(LOG_TAG, "Failed to exclude an app", e);
    }
  }
  return builder;
}
 
Example #9
Source File: ExternalOpenVPNService.java    From android with GNU General Public License v3.0 6 votes vote down vote up
private void startProfile(VpnProfile vp) {
    Intent vpnPermissionIntent = VpnService.prepare(ExternalOpenVPNService.this);
    /* Check if we need to show the confirmation dialog,
     * Check if we need to ask for username/password */

    int needpw = vp.needUserPWInput(false);

    if (vpnPermissionIntent != null || needpw != 0) {
        Intent shortVPNIntent = new Intent(Intent.ACTION_MAIN);
        shortVPNIntent.setClass(getBaseContext(), ht.vpn.android.LaunchVPN.class);
        shortVPNIntent.putExtra(ht.vpn.android.LaunchVPN.EXTRA_KEY, vp.getUUIDString());
        shortVPNIntent.putExtra(ht.vpn.android.LaunchVPN.EXTRA_HIDELOG, true);
        shortVPNIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(shortVPNIntent);
    } else {
        VPNLaunchHelper.startOpenVpn(vp, getBaseContext());
    }

}
 
Example #10
Source File: ModulesStateLoop.java    From InviZible with GNU General Public License v3.0 6 votes vote down vote up
private void startVPNService() {

        //Start VPN service if it is not started by modules presenters

        final Intent prepareIntent = VpnService.prepare(modulesService);

        if (handler != null && prepareIntent == null) {
            handler.postDelayed(() -> {
                if (modulesService != null && modulesStatus != null && sharedPreferences != null
                        && !sharedPreferences.getBoolean("VPNServiceEnabled", false)
                        && (modulesStatus.getDnsCryptState() == RUNNING || modulesStatus.getTorState() == RUNNING)) {
                    sharedPreferences.edit().putBoolean("VPNServiceEnabled", true).apply();
                    ServiceVPNHelper.start("ModulesStateLoop start VPN service", modulesService);
                }
            }, 10000);
        }
    }
 
Example #11
Source File: ShadowsocksRunnerActivity.java    From Maying with Apache License 2.0 6 votes vote down vote up
private void startBackgroundService() {
    if (ShadowsocksApplication.app.isNatEnabled()) {
        try {
            mServiceBoundContext.bgService.use(ShadowsocksApplication.app.profileId());
            finish();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    } else {
        Intent intent = VpnService.prepare(ShadowsocksRunnerActivity.this);
        if (intent != null) {
            startActivityForResult(intent, REQUEST_CONNECT);
        } else {
            onActivityResult(REQUEST_CONNECT, Activity.RESULT_OK, null);
        }
    }
}
 
Example #12
Source File: Shadowsocks.java    From Maying with Apache License 2.0 6 votes vote down vote up
private void prepareStartService() {
    if (ShadowsocksApplication.app.isNatEnabled()) {
        serviceLoad();
    } else {
        Intent intent = VpnService.prepare(mServiceBoundContext);
        if (intent != null) {
            startActivityForResult(intent, REQUEST_CONNECT);
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    onActivityResult(REQUEST_CONNECT, RESULT_OK, null);
                }
            });
        }
    }
}
 
Example #13
Source File: Shadowsocks.java    From ShadowsocksRR with Apache License 2.0 6 votes vote down vote up
private void prepareStartService() {
    if (app.isNatEnabled()) {
        serviceLoad();
    } else {
        Intent intent = VpnService.prepare(mServiceBoundContext);
        if (intent != null) {
            startActivityForResult(intent, REQUEST_CONNECT);
        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    onActivityResult(REQUEST_CONNECT, RESULT_OK, null);
                }
            });
        }
    }
}
 
Example #14
Source File: ShadowsocksRunnerActivity.java    From ShadowsocksRR with Apache License 2.0 6 votes vote down vote up
private void startBackgroundService() {
    if (app.isNatEnabled()) {
        try {
            mServiceBoundContext.bgService.use(app.profileId());
            finish();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    } else {
        Intent intent = VpnService.prepare(ShadowsocksRunnerActivity.this);
        if (intent != null) {
            startActivityForResult(intent, REQUEST_CONNECT);
        } else {
            onActivityResult(REQUEST_CONNECT, Activity.RESULT_OK, null);
        }
    }
}
 
Example #15
Source File: ProxyService.java    From igniter with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Apply allow or disallow rule on application by package names.
 */
private void applyApplicationOrientedRule(VpnService.Builder builder) {
    boolean workInAllowMode = PreferenceUtils.getBooleanPreference(getContentResolver(),
            Uri.parse(Constants.PREFERENCE_URI),
            Constants.PREFERENCE_KEY_PROXY_IN_ALLOW_MODE, false);
    Set<String> exemptAppPackageNames = getExemptAppPackageNames(workInAllowMode);
    RuleApplier applier;
    if (workInAllowMode) {
        exemptAppPackageNames.remove(getPackageName()); // disallow Igniter
        applier = Builder::addAllowedApplication;
    } else {
        exemptAppPackageNames.add(getPackageName()); // disallow Igniter
        applier = Builder::addDisallowedApplication;
    }
    for (String packageName : exemptAppPackageNames) {
        try {
            applier.applyRule(builder, packageName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            setState(STOPPED);
        }
    }
}
 
Example #16
Source File: GoVpnAdapter.java    From Intra with Apache License 2.0 6 votes vote down vote up
private static ParcelFileDescriptor establishVpn(IntraVpnService vpnService) {
  try {
    VpnService.Builder builder = vpnService.newBuilder()
        .setSession("Intra go-tun2socks VPN")
        .setMtu(VPN_INTERFACE_MTU)
        .addAddress(LanIp.GATEWAY.make(IPV4_TEMPLATE), IPV4_PREFIX_LENGTH)
        .addRoute("0.0.0.0", 0)
        .addDnsServer(LanIp.DNS.make(IPV4_TEMPLATE));
    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
      builder.addDisallowedApplication(vpnService.getPackageName());
    }
    return builder.establish();
  } catch (Exception e) {
    LogWrapper.logException(e);
    return null;
  }
}
 
Example #17
Source File: VPNActivity.java    From SimpleOpenVpn-Android with Apache License 2.0 6 votes vote down vote up
/**
 * 开始连接
 */
public void connectVpn() {
    Intent intent = VpnService.prepare(this);
    if (intent != null) {
        VpnStatus.updateStateString("USER_VPN_PERMISSION", "", R.string.state_user_vpn_permission,
                LEVEL_WAITING_FOR_USER_INPUT);
        // Start the query
        try {
            startActivityForResult(intent, START_VPN_PROFILE);
        } catch (ActivityNotFoundException ane) {
            // Shame on you Sony! At least one user reported that
            // an official Sony Xperia Arc S image triggers this exception
            VpnStatus.logError(R.string.no_vpn_support_image);
        }
    } else {
        onActivityResult(START_VPN_PROFILE, Activity.RESULT_OK, null);
    }
}
 
Example #18
Source File: MainActivity.java    From Intra with Apache License 2.0 6 votes vote down vote up
private boolean prepareVpnService() throws ActivityNotFoundException {
  Intent prepareVpnIntent = null;
  try {
     prepareVpnIntent = VpnService.prepare(this);
  } catch (NullPointerException e) {
    // This exception is not mentioned in the documentation, but it has been encountered by Intra
    // users and also by other developers, e.g. https://stackoverflow.com/questions/45470113.
    LogWrapper.logException(e);
    return false;
  }
  if (prepareVpnIntent != null) {
    Log.i(LOG_TAG, "Prepare VPN with activity");
    startActivityForResult(prepareVpnIntent, REQUEST_CODE_PREPARE_VPN);
    syncDnsStatus();  // Set DNS status to off in case the user does not grant VPN permissions
    return false;
  }
  return true;
}
 
Example #19
Source File: VpnAuthActivity.java    From Cybernet-VPN with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mConfig = getIntent().getStringExtra(KEY_CONFIG);
    mUsername = getIntent().getStringExtra(KEY_USERNAME);
    mPw = getIntent().getStringExtra(KEY_PASSWORD);
    Intent intent = VpnService.prepare(this);
    if (intent != null) {
        startActivityForResult(intent, 0);
    } else {
        startVpn();
        finish();
    }
}
 
Example #20
Source File: Receiver.java    From Android-Firewall with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(final Context context, Intent intent) {
    Log.i(TAG, "Received " + intent);
    Util.logExtras(TAG, intent);

    // Start service
    if (VpnService.prepare(context) == null)
        BlackHoleService.start(context);
}
 
Example #21
Source File: GnirehtetActivity.java    From gnirehtet with Apache License 2.0 5 votes vote down vote up
private boolean startGnirehtet(VpnConfiguration config) {
    Intent vpnIntent = VpnService.prepare(this);
    if (vpnIntent == null) {
        Log.d(TAG, "VPN was already authorized");
        // we got the permission, start the service now
        GnirehtetService.start(this, config);
        return true;
    }

    Log.w(TAG, "VPN requires the authorization from the user, requesting...");
    requestAuthorization(vpnIntent, config);
    return false; // do not finish now
}
 
Example #22
Source File: LocalVpnService.java    From VpnProxy with MIT License 5 votes vote down vote up
@Override
public IBinder onBind(Intent intent) {
    String action = intent.getAction();
    if (action.equals(VpnService.SERVICE_INTERFACE)) {
        return super.onBind(intent);
    }
    return null;
}
 
Example #23
Source File: Daedalus.java    From Daedalus with GNU General Public License v3.0 5 votes vote down vote up
public static boolean prepareAndActivateService(Context context) {
    Intent intent = VpnService.prepare(context);
    if (intent != null) {
        return false;
    } else {
        activateService(context);
        return true;
    }
}
 
Example #24
Source File: AlertActivity.java    From product-emm with Apache License 2.0 5 votes vote down vote up
/**
 * This method starts a VPN connection.
 */
private void startVpn() {

	try {
		JSONObject vpnData = new JSONObject(payload);
		if (!vpnData.isNull(resources.getString(R.string.intent_extra_server))) {
			serverAddress = (String) vpnData.get(resources.getString(R.string.intent_extra_server));
		}
		if (!vpnData.isNull(resources.getString(R.string.intent_extra_server_port))) {
			serverPort = (String) vpnData.get(resources.getString(R.string.intent_extra_server_port));
		}

		if (!vpnData.isNull(resources.getString(R.string.intent_extra_shared_secret))) {
			sharedSecret = (String) vpnData.get(resources.getString(R.string.intent_extra_shared_secret));
		}

		if (!vpnData.isNull(resources.getString(R.string.intent_extra_dns))) {
			dnsServer = (String) vpnData.get(resources.getString(R.string.intent_extra_dns));
		}
	} catch (JSONException e) {
		Log.e(TAG, "Invalid VPN payload " + e);
	}

	Intent intent = VpnService.prepare(this);
	if (intent != null) {
		startActivityForResult(intent, VPN_REQUEST_CODE);
	} else {
		onActivityResult(VPN_REQUEST_CODE, RESULT_OK, null);
	}
}
 
Example #25
Source File: ExternalOpenVPNService.java    From android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Intent prepareVPNService() throws RemoteException {
    checkOpenVPNPermission();

    if (VpnService.prepare(ExternalOpenVPNService.this) == null)
        return null;
    else
        return new Intent(getBaseContext(), GrantPermissionsActivity.class);
}
 
Example #26
Source File: GrantPermissionsActivity.java    From android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onStart() {
    super.onStart();
    Intent i = VpnService.prepare(this);
    if (i == null) {
        onActivityResult(VPN_PREPARE, RESULT_OK, null);
    } else {
        try {
            startActivityForResult(i, VPN_PREPARE);
        } catch (ActivityNotFoundException e) {
            VpnStatus.logError(R.string.no_vpn_support_image);
            finish();
        }
    }
}
 
Example #27
Source File: LaunchVPN.java    From android with GNU General Public License v3.0 5 votes vote down vote up
void launchVPN() {
    int vpnok = mSelectedProfile.checkProfile(this);
    if (vpnok != R.string.no_error_found) {
        showConfigErrorDialog(vpnok);
        return;
    }

    Intent intent = VpnService.prepare(this);
    // Check if we want to fix /dev/tun
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean usecm9fix = prefs.getBoolean("useCM9Fix", false);
    boolean loadTunModule = prefs.getBoolean("loadTunModule", false);

    if (loadTunModule)
        execeuteSUcmd("insmod /system/lib/modules/tun.ko");

    if (usecm9fix && !mCmfixed) {
        execeuteSUcmd("chown system /dev/tun");
    }


    if (intent != null) {
        VpnStatus.updateStateString("USER_VPN_PERMISSION", "", R.string.state_user_vpn_permission, ConnectionStatus.LEVEL_WAITING_FOR_USER_INPUT);
        // Start the query
        startActivityForResult(new Intent(this, GrantPermissionsActivity.class), START_VPN_PROFILE);
    } else {
        onActivityResult(START_VPN_PROFILE, Activity.RESULT_OK, null);
    }

}
 
Example #28
Source File: LocalVpnService.java    From BaoLianDeng with GNU General Public License v3.0 5 votes vote down vote up
@Override
public IBinder onBind(Intent intent) {
    String action = intent.getAction();
    if (action.equals(VpnService.SERVICE_INTERFACE)) {
        return super.onBind(intent);
    }
    return null;
}
 
Example #29
Source File: LocalVPN.java    From LocalVPN with Apache License 2.0 5 votes vote down vote up
private void startVPN()
{
    Intent vpnIntent = VpnService.prepare(this);
    if (vpnIntent != null)
        startActivityForResult(vpnIntent, VPN_REQUEST_CODE);
    else
        onActivityResult(VPN_REQUEST_CODE, RESULT_OK, null);
}
 
Example #30
Source File: VoidVpnLauncher.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
public void setUp() {
    Intent blocking_intent = VpnService.prepare(getApplicationContext()); // stops the VPN connection created by another application.
    if (blocking_intent != null)
        startActivityForResult(blocking_intent, VPN_USER_PERMISSION);
    else {
        onActivityResult(VPN_USER_PERMISSION, RESULT_OK, null);
    }
}