Related
I will block a user from using my app if they fake the location.
So I use isFromMockProvider to check if the location is fake (follow here). But isFromMockProvider() may return false for faked locations in some cases.
public void onLocationChanged(Location location) {
textView.append("long:"+location.getLatitude()+" - lat:"+location.getLongitude()+" - isMock :"+location.isFromMockProvider() + "\n");
}
My case is: I use app Fake GPS location for fake to a location then I disable fake location and go to my app. Then the onLocationChanged returns the fake location with isFromMockProvider() = false
Video recorder: https://www.youtube.com/watch?v=rWVvjOCaZiI (in this video, my current location is 16.06, 108.21, the fake location is 36.26,138.28. You can see in last video the location is 36.26,138.28 but isFromMockProvider=false)
Is there any way to detect if a user uses a fake location in this case? Any help or suggestion would be great appreciated.
DEMO project
Risking a Realistic Answer
I'd like to provide an answer that helps the developer understand the public relations aspect of product design, taking the risk of criticism. Frankly, one cannot write great apps in a computer science vacuum. Satisfying user needs and balancing them with security is one of the primary issues in software interface and behavioral design today, especially in the mobile space.
From this perspective, your question, "Is there any way to detect if a user uses a fake location in this case?" may not be the most pertinent question you face. I'm not being evasive by asking this other question that may help you more and it is something I can answer well: "Is there any way to securely get the data from the user's device's geocoordinate firmware such that it cannot be spoofed?"
The answer to this one is, "No."
Android HTTP Client Contract
It is not part of the Android client-server contract or that of its competitors to guarantee user device location information.
Practical Reason
There is actually a market force that will probably push against such a guarantee indefinitely. Many device owners (and your users) want control over whether people know their true location for privacy and home and family security reasons.
Solution
The next question you can ask yourself as a designer of your software is, "How can the app or library work and provide for the needs I seek to fill with a certain percentage of the user community using today's (or tomorrow's) location spoofing software?"
If you are writing business intelligence software or there is some other statistical aspect to your system, then you need the software equivalent of error bars. If you display the stats, then the error bars would be an appropriate graphing feature. Estimating the percentage of location spoofers out of a population of users would require further study.
I use two ways to identify fake locations.
First, i check mock location, like in other code here.
public static boolean isMockLocationOn(Location location, Context context) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return location.isFromMockProvider();
} else {
String mockLocation = "0";
try {
mockLocation = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION);
} catch (Exception e) {
e.printStackTrace();
}
return !mockLocation.equals("0");
}
}
Second, i check running apps and services, that need permission to access mock location.
public static List<String> getListOfFakeLocationApps(Context context) {
List<String> runningApps = getRunningApps(context);
List<String> fakeApps = new ArrayList<>();
for (String app : runningApps) {
if(!isSystemPackage(context, app) && hasAppPermission(context, app, "android.permission.ACCESS_MOCK_LOCATION")){
fakeApps.add(getApplicationName(context, app));
}
}
return fakeApps;
}
public static List<String> getRunningApps(Context context, boolean includeSystem) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
HashSet<String> runningApps = new HashSet<>();
try {
List<ActivityManager.RunningAppProcessInfo> runAppsList = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runAppsList) {
runningApps.addAll(Arrays.asList(processInfo.pkgList));
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
//can throw securityException at api<18 (maybe need "android.permission.GET_TASKS")
List<ActivityManager.RunningTaskInfo> runningTasks = activityManager.getRunningTasks(1000);
for (ActivityManager.RunningTaskInfo taskInfo : runningTasks) {
runningApps.add(taskInfo.topActivity.getPackageName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
List<ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(1000);
for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
runningApps.add(serviceInfo.service.getPackageName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return new ArrayList<>(runningApps);
}
public static boolean isSystemPackage(Context context, String app){
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo pkgInfo = packageManager.getPackageInfo(app, 0);
return (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return false;
}
public static boolean hasAppPermission(Context context, String app, String permission){
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo;
try {
packageInfo = packageManager.getPackageInfo(app, PackageManager.GET_PERMISSIONS);
if(packageInfo.requestedPermissions!= null){
for (String requestedPermission : packageInfo.requestedPermissions) {
if (requestedPermission.equals(permission)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return false;
}
public static String getApplicationName(Context context, String packageName) {
String appName = packageName;
PackageManager packageManager = context.getPackageManager();
try {
appName = packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)).toString();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appName;
}
(Update)
Unfortunately, google forbid applications from receiving the list of currently running apps.
(It was since 5.1.1, but i still can get app list in test devices runned android 7.1)
Now you can get only list of recently used apps (with request runtime permission for it) by using UsageStatsManager, for example like here Android 5.1.1 and above - getRunningAppProcesses() returns my application package only
So if user close or exit from fake location app, i can't determinate it.
And now, to get list of fake location apps, i try to get locations, and if location.isFromMockProvider() return true, i scan device for all installed apps, that need permission to access mock location like this:
public static List<String> getListOfFakeLocationAppsFromAll(Context context) {
List<String> fakeApps = new ArrayList<>();
List<ApplicationInfo> packages = context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo aPackage : packages) {
boolean isSystemPackage = ((aPackage.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
if(!isSystemPackage && hasAppPermission(context, aPackage.packageName, "android.permission.ACCESS_MOCK_LOCATION")){
fakeApps.add(getApplicationName(context, aPackage.packageName));
}
}
return fakeApps;
}
Answers on This SO question and to a lesser extent the answers on This SO question seem to indicate you are suffering from an unfortunate Caching issue in the FusedLocationApi caused by onLocationChanged being called with an out of date timestamp (thus ignoring the result as it thinks there is already newer data).
To quote Reno's answer:
Unless you have not changed ... so that new APs can be discovered, I'm afraid you will get only cached locations. If you want fresh locations use the GPS provider.
The solution will be to instead call a location from the GPS Provider like so:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
(The code above comes from a longer example here)
I use this method in my projects and it work perfectly till now:
for api < 18
//returns true if mock location enabled, false if not enabled.
public static boolean isMockLocationOn(Context context) {
if (Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
return false;
else
return true;
}
For api >= 18 you should use
location.isFromMockProvider();
The point is location.isFromMockProvider is buggy and some times it will show a mocked location as its OK !!!
There is a workaround in this link with full detail
Location on Android: Stop Mocking Me!
the approach is :
Remember the most recent location labeled as a mock
If a new “non-mock” reading is within 1km of the last mock, reject
it.
Only clear the last mock location after 20 consecutive “non-mock”
readings.
So I am developing an app which works as device owner on the specific Android device. This app is not available on the play store, but gets transferred with a provisioning app from a different device via NFC. Since those devices will be very specific to certain tasks (scanning NFC tags), I want to enable and disable a few things from the very beginning.
I want to disable sound:
devicePolicyManager.setMasterVolumeMuted(adminComponentName, true);
But this doesn't seem to work at all, but no exception either.
But what I really want to do is enabling mobile Data and Roaming, the SIM cards which we are using support that.
devicePolicyManager.setSecureSetting(adminComponentName, Settings.Global.DATA_ROAMING, String.valueOf(1));
devicePolicyManager.setSecureSetting(adminComponentName,"mobile_data",String.valueOf(1));
But sadly, those two lines of code throw a security exception:
java.lang.SecurityException: Permission denial: Device owners cannot update mobile_data
Interestingly, inserting APNs work (later in the code) Any chance to be able to turn on mobile data and data roaming as a device admin/owner? I mean, thats the whole purpose of being a device admin, right?
Here is the full code for reference: (the parts which make the app crash are commented out)
public static void enableRestrictedAppsAndSettings(Activity activity) {
ComponentName adminComponentName = DeviceAdminReceiver.getComponentName(activity);
DevicePolicyManager devicePolicyManager = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// disable keyguard and sound
devicePolicyManager.setKeyguardDisabled(adminComponentName, true);
devicePolicyManager.setMasterVolumeMuted(adminComponentName, true);
devicePolicyManager.setSecureSetting(adminComponentName, Settings.Secure.LOCATION_MODE, String.valueOf(Settings.Secure.LOCATION_MODE_HIGH_ACCURACY));
//devicePolicyManager.setSecureSetting(adminComponentName, Settings.Global.DATA_ROAMING, String.valueOf(1));
//devicePolicyManager.setSecureSetting(adminComponentName,"mobile_data",String.valueOf(1));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (devicePolicyManager.isDeviceOwnerApp(activity.getApplicationContext().getPackageName())) {
devicePolicyManager.enableSystemApp(adminComponentName,"com.sec.android.app.camera");
devicePolicyManager.clearUserRestriction(adminComponentName, UserManager.DISALLOW_DATA_ROAMING);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
L.debug("KIOSK", "APN");
ApnSetting apn;
TelephonyManager manager = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
if (manager.getSimState() == TelephonyManager.SIM_STATE_READY) {
String mcc = manager.getSimOperator().substring(0, 3);
String mnc = manager.getSimOperator().substring(3);
L.debug("KIOSK " + mcc + " "+mnc);
apn = new ApnSetting.Builder()
.setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
.setApnName("em")
.setEntryName("em")
.setOperatorNumeric(mcc + mnc) // this is a must its consists from Telephony.Carriers.MCC + Telephony.Carriers.MNC, In my case, I had to pad the MNC with a leading zero
.setProtocol(ApnSetting.PROTOCOL_IPV4V6) // this is a must
.setRoamingProtocol(ApnSetting.PROTOCOL_IPV4V6) // this is a must
.setCarrierEnabled(true)
.build();
devicePolicyManager.removeOverrideApn(adminComponentName,0);
devicePolicyManager.addOverrideApn(adminComponentName, apn);
devicePolicyManager.setOverrideApnsEnabled(adminComponentName, true);
}
}
}
}
Unfortunately the device owner has no access to mobile data status (you're right, weird restriction for the device owner app!).
However, you can still get the mobile data status and force the user to turn it on or off if the status is wrong. Here're the code samples (thanks to Test if background data and packet data is enabled or not).
public static boolean isMobileDataEnabled(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class clazz = Class.forName(cm.getClass().getName());
Method method = clazz.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
return (Boolean) method.invoke(cm);
} catch (Exception e) {
// Let it will be true by default
return true;
}
}
This code works on Android 5-9 (not tested on Android 10 yet).
So you run a background service which performs this check once per some seconds and requires the user to turn on/off the mobile data in the status bar.
You can see how it is done by cloning this open source Android MDM (this is my project). The method is here: Utils.isMobileDataEnabled(Context context).
I will block a user from using my app if they fake the location.
So I use isFromMockProvider to check if the location is fake (follow here). But isFromMockProvider() may return false for faked locations in some cases.
public void onLocationChanged(Location location) {
textView.append("long:"+location.getLatitude()+" - lat:"+location.getLongitude()+" - isMock :"+location.isFromMockProvider() + "\n");
}
My case is: I use app Fake GPS location for fake to a location then I disable fake location and go to my app. Then the onLocationChanged returns the fake location with isFromMockProvider() = false
Video recorder: https://www.youtube.com/watch?v=rWVvjOCaZiI (in this video, my current location is 16.06, 108.21, the fake location is 36.26,138.28. You can see in last video the location is 36.26,138.28 but isFromMockProvider=false)
Is there any way to detect if a user uses a fake location in this case? Any help or suggestion would be great appreciated.
DEMO project
Risking a Realistic Answer
I'd like to provide an answer that helps the developer understand the public relations aspect of product design, taking the risk of criticism. Frankly, one cannot write great apps in a computer science vacuum. Satisfying user needs and balancing them with security is one of the primary issues in software interface and behavioral design today, especially in the mobile space.
From this perspective, your question, "Is there any way to detect if a user uses a fake location in this case?" may not be the most pertinent question you face. I'm not being evasive by asking this other question that may help you more and it is something I can answer well: "Is there any way to securely get the data from the user's device's geocoordinate firmware such that it cannot be spoofed?"
The answer to this one is, "No."
Android HTTP Client Contract
It is not part of the Android client-server contract or that of its competitors to guarantee user device location information.
Practical Reason
There is actually a market force that will probably push against such a guarantee indefinitely. Many device owners (and your users) want control over whether people know their true location for privacy and home and family security reasons.
Solution
The next question you can ask yourself as a designer of your software is, "How can the app or library work and provide for the needs I seek to fill with a certain percentage of the user community using today's (or tomorrow's) location spoofing software?"
If you are writing business intelligence software or there is some other statistical aspect to your system, then you need the software equivalent of error bars. If you display the stats, then the error bars would be an appropriate graphing feature. Estimating the percentage of location spoofers out of a population of users would require further study.
I use two ways to identify fake locations.
First, i check mock location, like in other code here.
public static boolean isMockLocationOn(Location location, Context context) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return location.isFromMockProvider();
} else {
String mockLocation = "0";
try {
mockLocation = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION);
} catch (Exception e) {
e.printStackTrace();
}
return !mockLocation.equals("0");
}
}
Second, i check running apps and services, that need permission to access mock location.
public static List<String> getListOfFakeLocationApps(Context context) {
List<String> runningApps = getRunningApps(context);
List<String> fakeApps = new ArrayList<>();
for (String app : runningApps) {
if(!isSystemPackage(context, app) && hasAppPermission(context, app, "android.permission.ACCESS_MOCK_LOCATION")){
fakeApps.add(getApplicationName(context, app));
}
}
return fakeApps;
}
public static List<String> getRunningApps(Context context, boolean includeSystem) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
HashSet<String> runningApps = new HashSet<>();
try {
List<ActivityManager.RunningAppProcessInfo> runAppsList = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runAppsList) {
runningApps.addAll(Arrays.asList(processInfo.pkgList));
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
//can throw securityException at api<18 (maybe need "android.permission.GET_TASKS")
List<ActivityManager.RunningTaskInfo> runningTasks = activityManager.getRunningTasks(1000);
for (ActivityManager.RunningTaskInfo taskInfo : runningTasks) {
runningApps.add(taskInfo.topActivity.getPackageName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
List<ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(1000);
for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
runningApps.add(serviceInfo.service.getPackageName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return new ArrayList<>(runningApps);
}
public static boolean isSystemPackage(Context context, String app){
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo pkgInfo = packageManager.getPackageInfo(app, 0);
return (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return false;
}
public static boolean hasAppPermission(Context context, String app, String permission){
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo;
try {
packageInfo = packageManager.getPackageInfo(app, PackageManager.GET_PERMISSIONS);
if(packageInfo.requestedPermissions!= null){
for (String requestedPermission : packageInfo.requestedPermissions) {
if (requestedPermission.equals(permission)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return false;
}
public static String getApplicationName(Context context, String packageName) {
String appName = packageName;
PackageManager packageManager = context.getPackageManager();
try {
appName = packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)).toString();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appName;
}
(Update)
Unfortunately, google forbid applications from receiving the list of currently running apps.
(It was since 5.1.1, but i still can get app list in test devices runned android 7.1)
Now you can get only list of recently used apps (with request runtime permission for it) by using UsageStatsManager, for example like here Android 5.1.1 and above - getRunningAppProcesses() returns my application package only
So if user close or exit from fake location app, i can't determinate it.
And now, to get list of fake location apps, i try to get locations, and if location.isFromMockProvider() return true, i scan device for all installed apps, that need permission to access mock location like this:
public static List<String> getListOfFakeLocationAppsFromAll(Context context) {
List<String> fakeApps = new ArrayList<>();
List<ApplicationInfo> packages = context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo aPackage : packages) {
boolean isSystemPackage = ((aPackage.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
if(!isSystemPackage && hasAppPermission(context, aPackage.packageName, "android.permission.ACCESS_MOCK_LOCATION")){
fakeApps.add(getApplicationName(context, aPackage.packageName));
}
}
return fakeApps;
}
Answers on This SO question and to a lesser extent the answers on This SO question seem to indicate you are suffering from an unfortunate Caching issue in the FusedLocationApi caused by onLocationChanged being called with an out of date timestamp (thus ignoring the result as it thinks there is already newer data).
To quote Reno's answer:
Unless you have not changed ... so that new APs can be discovered, I'm afraid you will get only cached locations. If you want fresh locations use the GPS provider.
The solution will be to instead call a location from the GPS Provider like so:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
(The code above comes from a longer example here)
I use this method in my projects and it work perfectly till now:
for api < 18
//returns true if mock location enabled, false if not enabled.
public static boolean isMockLocationOn(Context context) {
if (Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
return false;
else
return true;
}
For api >= 18 you should use
location.isFromMockProvider();
The point is location.isFromMockProvider is buggy and some times it will show a mocked location as its OK !!!
There is a workaround in this link with full detail
Location on Android: Stop Mocking Me!
the approach is :
Remember the most recent location labeled as a mock
If a new “non-mock” reading is within 1km of the last mock, reject
it.
Only clear the last mock location after 20 consecutive “non-mock”
readings.
I want to switch on wifi as a part of test case using uiautomator tool in android. I tried using following code in uiautomator test case:
WifiManager wi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if(wi.isWifiEnabled()){
wi.setWifiEnabled(false);
}else{
wi.setWifiEnabled(true);
}
but it gave this error:
"getSystemservice" method is undefined for Mainclass
You can actually use UIAutomator to set the WiFi setting on and off. I wrote the code this evening :)
Here's the code. You can add it to the Android example which is here http://developer.android.com/tools/testing/testing_ui.html
Add the following enum at the top of the class
private enum OnOff {
Off,
On
};
Add the new code after:
// Validate that the package name is the expected one
UiObject settingsValidation = new UiObject(new UiSelector()
.packageName("com.android.settings"));
assertTrue("Unable to detect Settings", settingsValidation.exists());
Here is the new code:
UiSelector settingsItems = new UiSelector().className(android.widget.TextView.class.getName());
UiObject wiFi = appViews.getChildByText(settingsItems, "Wi-Fi");
// We can click on Wi-Fi, e.g. wiFi.clickAndWaitForNewWindow();
// So we know we have found the Wi-Fi setting
UiSelector switchElement = new UiSelector().className(android.widget.Switch.class.getName());
setSwitchTo(OnOff.Off); // Or set it to On as you wish :)
}
private void setSwitchTo(OnOff value) throws UiObjectNotFoundException {
String text;
UiObject switchObject = getSwitchObject();
for (int attempts = 0; attempts < 5; attempts++) {
text = switchObject.getText();
boolean switchIsOn = switchObject.isChecked();
final OnOff result;
if (switchIsOn) {
result = OnOff.On;
} else {
result = OnOff.Off;
}
System.out.println("Value of switch is " + switchObject.isSelected() + ", " + text + ", " + switchIsOn);
if (result == value) {
System.out.println("Switch set to correct value " + result);
break;
} else {
switchObject.click();
}
}
}
private UiObject getSwitchObject() {
UiObject switchObject = new UiObject(new UiSelector().className(android.widget.Switch.class.getName()));
assertTrue("Unable to find the switch object", switchObject.exists());
String text;
return switchObject;
}
The loop was to compensate for some behaviour I observed, where the click didn't seem to change the switch position.
To enable WiFi:
device.executeShellCommand("svc wifi enable");
To disable WiFi:
device.executeShellCommand("svc wifi disable");
These are the commands to use on your UiDevice.
Used on production on Android 4.2 and 4.4
To open the Android Wifi settings in your code:
final Intent intent = new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK);
mContext.startActivity(intent);
To click the on/off switch with UiAutomator (after you're sure you're on the good activity):
public void enableWifiOnAndroidWifiSettings(boolean enabled) throws UiObjectNotFoundException {
final UiSelector wifiSwitchSelector = new UiSelector().className(android.widget.Switch.class.getName());
UiObject wifiSwitch = UiDevice.getInstance(sInstrumentation).findObject(wifiSwitchSelector);
if (wifiSwitch.waitForExists(5000) && wifiSwitch.isEnabled()) {
if (wifiSwitch.isChecked() != enabled) {
wifiSwitch.click();
}
}
}
Known limitation: It's searching the first Switch available. If you've custom ROM or if the Android Settings app evolves in the future, it will maybe not be enough.
In my suite tests with UIAutomator I use:
Runtime.getRuntime().exec("\"svc wifi disable\"")
Runtime.getRuntime().exec("\"svc wifi enable\"")
Runtime.getRuntime().exec("\"svc data disable\"")
Runtime.getRuntime().exec("\"svc data enable\"")
You can enable or disable wifi through adb as follows
adb shell sqlite3
/data/data/com.android.providers.settings/databases/settings.db update
secure set value=1 where name='wifi_on'; .exit
But you cannot use uiautomator tool to do the same
You can't do this. A UI Automator test doesn't run as part of the Android framework, so it has no access to Android system services. It's meant to test UIs; it doesn't claim to be a full-featured test framework. Turn on WiFi manually before you run the test.
Looking to find the best way to prevent / detect GPS spoofing on Android. Any suggestions on how this is accomplished, and what can be done to stop it? I am guessing the user has to turn on mock locations to spoof GPS, if this is done, then they can spoof GPS?
I guess I would need to just detect if Mock Locations are enabled? Any other suggestions?
I have done some investigation and sharing my results here,this may be useful for others.
First, we can check whether MockSetting option is turned ON
public static boolean isMockSettingsON(Context context) {
// returns true if mock location enabled, false if not enabled.
if (Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
return false;
else
return true;
}
Second, we can check whether are there other apps in the device, which are using android.permission.ACCESS_MOCK_LOCATION (Location Spoofing Apps)
public static boolean areThereMockPermissionApps(Context context) {
int count = 0;
PackageManager pm = context.getPackageManager();
List<ApplicationInfo> packages =
pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo applicationInfo : packages) {
try {
PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName,
PackageManager.GET_PERMISSIONS);
// Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;
if (requestedPermissions != null) {
for (int i = 0; i < requestedPermissions.length; i++) {
if (requestedPermissions[i]
.equals("android.permission.ACCESS_MOCK_LOCATION")
&& !applicationInfo.packageName.equals(context.getPackageName())) {
count++;
}
}
}
} catch (NameNotFoundException e) {
Log.e("Got exception " , e.getMessage());
}
}
if (count > 0)
return true;
return false;
}
If both above methods, first and second are true, then there are good chances that location may be spoofed or fake.
Now, spoofing can be avoided by using Location Manager's API.
We can remove the test provider before requesting the location updates from both the providers (Network and GPS)
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
Log.d(TAG ,"Removing Test providers")
lm.removeTestProvider(LocationManager.GPS_PROVIDER);
} catch (IllegalArgumentException error) {
Log.d(TAG,"Got exception in removing test provider");
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
I have seen that removeTestProvider(~) works very well over Jelly Bean and onwards version. This API appeared to be unreliable till Ice Cream Sandwich.
Flutter Update:
Use Geolocator and check Position object's isMocked property.
Since API 18, the object Location has the method .isFromMockProvider() so you can filter out fake locations.
If you want to support versions before 18, it is possible to use something like this:
boolean isMock = false;
if (android.os.Build.VERSION.SDK_INT >= 18) {
isMock = location.isFromMockProvider();
} else {
isMock = !Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals("0");
}
It seems that the only way to do this is to prevent Location Spoofing preventing MockLocations. The down side is there are some users who use Bluetooth GPS devices to get a better signal, they won't be able to use the app as they are required to use the mock locations.
To do this, I did the following :
// returns true if mock location enabled, false if not enabled.
if (Settings.Secure.getString(getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
return false;
else return true;
Stumbled upon this thread a couple years later. In 2016, most Android devices will have API level >= 18 and should thus rely on Location.isFromMockProvider() as pointed out by Fernando.
I extensively experimented with fake/mock locations on different Android devices and distros. Unfortunately .isFromMockProvider() is not 100% reliable. Every once in a while, a fake location will not be labeled as mock. This seems to be due to some erroneous internal fusion logic in the Google Location API.
I wrote a detailed blog post about this, if you want to learn more. To summarize, if you subscribe to location updates from the Location API, then switch on a fake GPS app and print the result of each Location.toString() to the console, you will see something like this:
Notice how, in the stream of location updates, one location has the same coordinates as the others, but is not flagged as a mock and has a much poorer location accuracy.
To remedy this problem, I wrote a utility class that will reliably suppress Mock locations across all modern Android versions (API level 15 and up):
LocationAssistant - Hassle-free location updates on Android
Basically, it "distrusts" non-mock locations that are within 1km of the last known mock location and also labels them as a mock. It does this until a significant number of non-mock locations have arrived.
The LocationAssistant can not only reject mock locations, but also unburdens you from most of the hassle of setting up and subscribing to location updates.
To receive only real location updates (i.e. suppress mocks), use it as follows:
public class MyActivity extends Activity implements LocationAssistant.Listener {
private LocationAssistant assistant;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
// You can specify a different accuracy and interval here.
// The last parameter (allowMockLocations) must be 'false' to suppress mock locations.
assistant = new LocationAssistant(this, this, LocationAssistant.Accuracy.HIGH, 5000, false);
}
#Override
protected void onResume() {
super.onResume();
assistant.start();
}
#Override
protected void onPause() {
assistant.stop();
super.onPause();
}
#Override
public void onNewLocationAvailable(Location location) {
// No mock locations arriving here
}
...
}
onNewLocationAvailable() will now only be invoked with real location info. There are some more listener methods you need to implement, but in the context of your question (how to prevent GPS spoofing) this is basically it.
Of course, with a rooted OS you can still find ways of spoofing location info that are impossible for normal apps to detect.
If you happened to know the general location of cell towers, you could check to see if the current cell tower matches the location given (within an error margin of something large, like 10 or more miles).
For example, if your app unlocks features only if the user is in a specific location (your store, for example), you could check gps as well as cell towers. Currently, no gps spoofing app also spoofs the cell towers, so you could see if someone across the country is simply trying to spoof their way into your special features (I'm thinking of the Disney Mobile Magic app, for one example).
This is how the Llama app manages location by default, since checking cell tower ids are much less battery intensive than gps. It isn't useful for very specific locations, but if home and work are several miles away, it can distinguish between the two general locations very easily.
Of course, this would require the user to have a cell signal at all. And you would have to know all the cell towers ids in the area --on all network providers-- or you would run the risk of a false negative.
try this code its very simple and usefull
public boolean isMockLocationEnabled() {
boolean isMockLocation = false;
try {
//if marshmallow
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AppOpsManager opsManager = (AppOpsManager) getApplicationContext().getSystemService(Context.APP_OPS_SERVICE);
isMockLocation = (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), BuildConfig.APPLICATION_ID)== AppOpsManager.MODE_ALLOWED);
} else {
// in marshmallow this will always return true
isMockLocation = !android.provider.Settings.Secure.getString(getApplicationContext().getContentResolver(), "mock_location").equals("0");
}
} catch (Exception e) {
return isMockLocation;
}
return isMockLocation;
}
This scrip is working for all version of android and i find it after many search
LocationManager locMan;
String[] mockProviders = {LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER};
try {
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
for (String p : mockProviders) {
if (p.contentEquals(LocationManager.GPS_PROVIDER))
locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
else
locMan.addTestProvider(p, false, false, false, false, true, true, true, 1,
android.hardware.SensorManager.SENSOR_STATUS_ACCURACY_LOW);
locMan.setTestProviderEnabled(p, true);
locMan.setTestProviderStatus(p, android.location.LocationProvider.AVAILABLE, Bundle.EMPTY,
java.lang.System.currentTimeMillis());
}
} catch (Exception ignored) {
// here you should show dialog which is mean the mock location is not enable
}
You can add additional check based on cell tower triangulation or Wifi Access Points info using Google Maps Geolocation API
The simplest way to get info about CellTowers
final TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = telephonyManager.getNetworkOperator();
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
String operatorName = telephonyManager.getNetworkOperatorName();
final GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();
You can compare your results with site
To get info about Wifi Access Points
final WifiManager mWifiManager = (WifiManager) appContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (mWifiManager != null && mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
// register WiFi scan results receiver
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> results = mWifiManager.getScanResults();//<-result list
}
};
appContext.registerReceiver(broadcastReceiver, filter);
// start WiFi Scan
mWifiManager.startScan();
}
Below approach is working for me getting proper detection of mock location
#Override
public void onLocationChanged (Location location){
boolean isMockLocation = location.isFromMockProvider();
}
Paste this in your activity/where you want to validate fake/mock gps
try {
if (areThereMockPermissionApps(mContext)) {
Log.e(TAG, " - " + "Yup its use fake gps");
List<String> mFakeList = new ArrayList<>();
mFakeList = getListOfFakeLocationAppsInstalled(mContext); // this will return the fake app list
for (int a = 0; a < mFakeList.size(); a++) {
Log.e(TAG, mFakeList.size() + " - " + "NameList ----- " + mFakeList.get(a));
}
} else
Log.e(TAG, " - " + "Nope its not use fake gps");
} catch (Exception w) {
w.printStackTrace();
}
Here you can get the list of installed fake/mock app in your device.
private List<String> getListOfFakeLocationAppsInstalled(Context context) {
List<String> fakeApps = new ArrayList<>();
try {
List<String> runningApps = new ArrayList<>();
final PackageManager pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
runningApps.add(packageInfo.packageName);
} // the getLaunchIntentForPackage returns an intent that you can use with startActivity()
for (String app : runningApps) {
if (!isSystemPackage(context, app) && hasAppPermission(context, app, "android.permission.ACCESS_MOCK_LOCATION")) {
fakeApps.add(getApplicationName(context, app));
}
}
} catch (Exception w) {
w.printStackTrace();
}
return fakeApps;
}
Paste this method in your Helper/same class
public static boolean areThereMockPermissionApps(Context context) {
int count = 0;
try {
PackageManager pm = context.getPackageManager();
List<ApplicationInfo> packages =
pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo applicationInfo : packages) {
try {
PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName,
PackageManager.GET_PERMISSIONS);
// Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;
if (requestedPermissions != null) {
for (int i = 0; i < requestedPermissions.length; i++) {
if (requestedPermissions[i]
.equals("android.permission.ACCESS_MOCK_LOCATION")
&& !applicationInfo.packageName.equals(context.getPackageName())) {
count++;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
Log.e("MockDeductionAgilanbu", "Got exception --- " + e.getMessage());
}
}
} catch (Exception w) {
w.printStackTrace();
}
if (count > 0)
return true;
return false;
}