diff --git a/README.md b/README.md index 1a2da86..2aeec84 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,17 @@ You decide which apps are affected: only the apps you tick in LSPosed see spoofe ## Features -- **Spoof 18 identifiers** across four groups: device, device model, Wi-Fi & Bluetooth, SIM & mobile. +- **Spoof 29 identifiers** across eight groups: device, device model, Wi-Fi & Bluetooth, SIM & mobile, timezone/region/GPS, keyboard, system privacy, and proxy & accounts. - **Edit or randomise** each value individually, or **randomise everything with one tap**. - **Realistic random values**: IMEI and ICCID carry valid Luhn check digits; MAC addresses are valid unicast addresses; SIM values (operator code, name, country, IMSI prefix, phone country code) always belong to the same real operator; brand, manufacturer and model always match a real phone. -- **New identity on every app start** (optional): each launch of a target app gets fresh random values. +- **Named profiles**: keep several identities and switch between them; create, rename and delete. +- **New identity on every app start** (optional): each launch of a target app gets fresh random + identifiers. Configuration (hide lists, keyboard id, proxy) is never re-rolled. +- **Coherent identities**: the SIM operator decides the timezone, region and GPS position too, so a + randomised device does not claim a German carrier while sitting in Tokyo. +- **Privacy switches**: hide an active VPN, hide developer options and ADB, report Google Play as the + installer, block private LAN scans, hide nearby Wi-Fi scan results, add realistic sensor noise. +- **Per-profile proxy**: route app traffic through an HTTP or SOCKS proxy, leaving loopback and LAN direct. - **Master switch** to turn spoofing off without losing your values. - **Export / import** your values as a JSON file. - **Long-press a value to copy it.** @@ -56,6 +63,14 @@ You decide which apps are affected: only the apps you tick in LSPosed see spoofe | | Operator (MCC+MNC) | `getSimOperator`, `getNetworkOperator` | | | Operator name | `getSimOperatorName`, `getNetworkOperatorName`, carrier-ID names, `SubscriptionInfo.getCarrierName` | | | SIM country | `getSimCountryIso`, `getNetworkCountryIso`, `SubscriptionInfo.getCountryIso` | +| Timezone, region & GPS | Timezone | `TimeZone.getDefault` | +| | Region / country | `Locale.getDefault` (country only; the device language is kept) | +| | Latitude, longitude | `Location.getLatitude`, `getLongitude`, `LocationManager.getLastKnownLocation` | +| Keyboard & IME | Default keyboard | `Settings.Secure` `default_input_method` | +| | Hidden keyboards | `InputMethodManager.getInputMethodList`, `getEnabledInputMethodList` | +| System privacy | Hidden apps | `PackageManager.getInstalledPackages`, `getInstalledApplications` | +| Proxy & accounts | Virtual Gmail accounts | `AccountManager.getAccounts`, `getAccountsByType` | +| | Proxy host, port, type | `ProxySelector.getDefault` | Leave a field empty and the app sees the real value. @@ -161,26 +176,39 @@ app/src/main/java/com/hidemydevice/app/ These are good places to start contributing: -- **Device profile isn't fully consistent.** Brand, manufacturer and model are spoofed, but `Build.FINGERPRINT`, `DEVICE` and `PRODUCT` are not. The IMEI's TAC (model prefix) is random rather than matching the chosen model. -- **"New values per launch" is per process.** Apps with several processes may see different values in each one. -- **The "active" banner** shows that LSPosed recognises the module, not that a given target app is in scope. -- **Only `wlan0`** is covered for MAC addresses; Wi-Fi **scan results** are not hooked. +- **Hiding an app only filters lists.** `getInstalledPackages` and `getInstalledApplications` are + filtered, but a direct `getPackageInfo("com.example")` still answers truthfully, and most detectors + ask by name rather than enumerating. +- **Device profile isn't fully consistent.** Brand, manufacturer and model are spoofed, but + `Build.FINGERPRINT`, `DEVICE`, `PRODUCT` and the `ro.product.*` properties are not, which + contradicts them. The IMEI's TAC (model prefix) is random rather than matching the chosen model. +- **Region is only spoofed for `Locale.getDefault`.** An app reading + `getResources().getConfiguration().getLocales()` still sees the real country. +- **Every scoped app sees the same identity**, so apps can still correlate with each other. +- **"New values per launch" is per process.** Apps with several processes may see different values in + each one, and an app that sees a new IMEI on every start can tell something is spoofing it. +- **The "active" banner** shows that LSPosed recognises the module, not that a given target app is in + scope. +- **Only `wlan0`** is covered for MAC addresses. Wi-Fi scan results are hidden (an empty list), not + replaced with plausible ones. - **Dual-SIM**: every slot gets the same IMEI; MEID isn't spoofed. - **Advertising ID** is only spoofed if the app ships Google's unobfuscated `AdvertisingIdClient`. +- **VPN hiding** removes tunnel interfaces and clears the VPN transport, but an app that inspects + routing tables directly may still notice. - **Native code** (JNI, direct syscalls, reading `/sys` or `/proc` files) bypasses Java hooks. ## Roadmap Ideas we'd love help with: -- [ ] Named **profiles** with quick switching -- [ ] **Consistent device profiles** (fingerprint, device, product and IMEI TAC matching the model) +- [ ] **Hide apps from direct lookups** (`getPackageInfo`, `getApplicationInfo`, `queryIntentActivities`) +- [ ] **Consistent device profiles** (fingerprint, device, product, `ro.product.*` and IMEI TAC matching the model) - [ ] **Stable per-app randomisation** (seeded per app, consistent across processes) +- [ ] **Spoof region for `Configuration.getLocales()`**, not just `Locale.getDefault` - [ ] **Pin a value** so "Random all" leaves it alone -- [ ] Spoof Wi-Fi / Bluetooth **scan results** and block **LAN scanning** +- [ ] Spoof Wi-Fi / Bluetooth **scan results** with plausible networks rather than hiding them - [ ] **WebView fingerprint** (user agent, canvas, navigator) -- [ ] **Timezone, region and GPS** spoofing -- [ ] In-app **hook log** viewer +- [ ] In-app **verification screen** showing what a scoped app actually sees - [ ] Unit tests for `Randomizer` and validation - [ ] Translations diff --git a/app/build.gradle b/app/build.gradle index 119377c..a3791b5 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,8 +12,8 @@ android { minSdk = 27 // 34 keeps the classic (non edge-to-edge) window layout targetSdk = 34 - versionCode = 1 - versionName = '1.0.0' + versionCode = 2 + versionName = '1.1.0' } // Release signing comes from environment variables (set by the GitHub workflow from repository diff --git a/app/src/main/java/com/hidemydevice/app/Category.java b/app/src/main/java/com/hidemydevice/app/Category.java index 9b193b7..3d1fe82 100644 --- a/app/src/main/java/com/hidemydevice/app/Category.java +++ b/app/src/main/java/com/hidemydevice/app/Category.java @@ -5,7 +5,11 @@ enum Category { DEVICE(R.string.cat_device, R.drawable.ic_device), MODEL(R.string.cat_model, R.drawable.ic_model), NETWORK(R.string.cat_network, R.drawable.ic_network), - SIM(R.string.cat_sim, R.drawable.ic_sim); + SIM(R.string.cat_sim, R.drawable.ic_sim), + LOCATION_GEO(R.string.cat_location_geo, R.drawable.ic_network), + KEYBOARD_APP(R.string.cat_keyboard_app, R.drawable.ic_code), + SYSTEM_PRIVACY(R.string.cat_system_privacy, R.drawable.ic_shield_on), + PROXIES_ACCOUNTS(R.string.cat_proxies_accounts, R.drawable.ic_person); final int titleRes; final int iconRes; diff --git a/app/src/main/java/com/hidemydevice/app/Field.java b/app/src/main/java/com/hidemydevice/app/Field.java index 680140b..26be150 100644 --- a/app/src/main/java/com/hidemydevice/app/Field.java +++ b/app/src/main/java/com/hidemydevice/app/Field.java @@ -2,6 +2,10 @@ import android.text.InputType; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.TimeZone; import java.util.regex.Pattern; /** Every id the module can spoof. An empty stored value means "leave the real value alone". */ @@ -27,28 +31,94 @@ enum Field { MOBILE_NO(Category.SIM, "mobile_no", "Mobile Number", "6-15 digits, optional leading +", "\\+?\\d{6,15}", InputType.TYPE_CLASS_PHONE), SIM_OPERATOR(Category.SIM, "sim_operator", "SIM Operator (MCC+MNC)", "5-6 digits", "\\d{5,6}", InputType.TYPE_CLASS_NUMBER), SIM_OPERATOR_NAME(Category.SIM, "sim_operator_name", "SIM Operator Name", "Up to 32 characters", ".{1,32}", Field.TEXT), - SIM_COUNTRY(Category.SIM, "sim_country", "SIM Country", "2-letter ISO code, e.g. us", "[a-z]{2}", Field.TEXT); + SIM_COUNTRY(Category.SIM, "sim_country", "SIM Country", "2-letter ISO code, e.g. us", "[a-z]{2}", Field.TEXT), + + TIMEZONE(Category.LOCATION_GEO, Prefs.SPOOF_TIMEZONE, "Timezone", "A zone id, e.g. America/New_York", "[A-Za-z0-9_+/-]{3,40}", Field.TEXT), + REGION(Category.LOCATION_GEO, Prefs.SPOOF_REGION, "Region / Country", "2-letter ISO code, e.g. US", "[A-Za-z]{2}", Field.TEXT), + LATITUDE(Category.LOCATION_GEO, Prefs.SPOOF_LATITUDE, "GPS Latitude", "-90 to 90, e.g. 40.7128", "-?\\d{1,3}(\\.\\d{1,8})?", Field.COORDINATE), + LONGITUDE(Category.LOCATION_GEO, Prefs.SPOOF_LONGITUDE, "GPS Longitude", "-180 to 180, e.g. -74.0060", "-?\\d{1,3}(\\.\\d{1,8})?", Field.COORDINATE), + + // Everything below is configuration rather than an identifier: "Random all" and + // "new values every launch" leave it alone, so a proxy or a hide list keeps working. + DEFAULT_KEYBOARD_ID(Category.KEYBOARD_APP, Prefs.DEFAULT_KEYBOARD_ID, "Virtual Default Keyboard ID", + "e.g. com.google.android.inputmethod.latin/.LatinIME", ".{3,100}", Field.TEXT, Field.CONFIG), + HIDDEN_KEYBOARDS(Category.KEYBOARD_APP, Prefs.HIDDEN_KEYBOARDS, "Hide Suspicious Keyboards", + "Comma-separated package names", ".*", Field.TEXT, Field.CONFIG), + + HIDDEN_APPS(Category.SYSTEM_PRIVACY, Prefs.HIDDEN_APPS, "Hide Installed Apps", + "Comma-separated package names", ".*", Field.TEXT, Field.CONFIG), + + VIRTUAL_GMAIL(Category.PROXIES_ACCOUNTS, Prefs.VIRTUAL_GMAIL_ACCOUNTS, "Virtual Gmail Accounts", + "Comma-separated email addresses", ".*", Field.TEXT, Field.CONFIG), + PROXY_HOST(Category.PROXIES_ACCOUNTS, Prefs.PROXY_HOST, "Proxy Host / IP", + "e.g. 192.168.1.100", "[A-Za-z0-9.:_-]{3,100}", Field.TEXT, Field.CONFIG), + PROXY_PORT(Category.PROXIES_ACCOUNTS, Prefs.PROXY_PORT, "Proxy Port", + "1-65535", "\\d{1,5}", InputType.TYPE_CLASS_NUMBER, Field.CONFIG), + PROXY_TYPE(Category.PROXIES_ACCOUNTS, Prefs.PROXY_TYPE, "Proxy Type", + "HTTP or SOCKS", "(?i)(http|socks)", Field.TEXT, Field.CONFIG); private static final int TEXT = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; + private static final int COORDINATE = InputType.TYPE_CLASS_NUMBER + | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED; private static final String MAC = "([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}"; + private static final boolean CONFIG = false; final Category category; final String key; final String title; final String hint; final int inputType; + /** Whether bulk randomising ("Random all", "new values every launch") may touch this field. */ + final boolean randomizable; private final Pattern pattern; Field(Category category, String key, String title, String hint, String regex, int inputType) { + this(category, key, title, hint, regex, inputType, true); + } + + Field(Category category, String key, String title, String hint, String regex, int inputType, + boolean randomizable) { this.category = category; this.key = key; this.title = title; this.hint = hint; this.inputType = inputType; + this.randomizable = randomizable; this.pattern = Pattern.compile(regex); } boolean isValid(String value) { - return pattern.matcher(value).matches(); + if (!pattern.matcher(value).matches()) { + return false; + } + switch (this) { + // A regex cannot tell "America/New_York" from "Atlantis/Nowhere", and an unknown zone + // id silently resolves to GMT, so check it against the ones the platform knows. + case TIMEZONE: + return Zones.IDS.contains(value); + case LATITUDE: + return inRange(value, 90); + case LONGITUDE: + return inRange(value, 180); + case PROXY_PORT: + int port = Integer.parseInt(value); + return port >= 1 && port <= 65535; + default: + return true; + } + } + + private static boolean inRange(String value, double limit) { + try { + double degrees = Double.parseDouble(value); + return !Double.isNaN(degrees) && Math.abs(degrees) <= limit; + } catch (NumberFormatException e) { + return false; + } + } + + /** Built on first use - {@link TimeZone#getAvailableIDs()} allocates several hundred strings. */ + private static final class Zones { + static final Set IDS = new HashSet<>(Arrays.asList(TimeZone.getAvailableIDs())); } } diff --git a/app/src/main/java/com/hidemydevice/app/Hook.java b/app/src/main/java/com/hidemydevice/app/Hook.java index 6922bd6..0e50c49 100644 --- a/app/src/main/java/com/hidemydevice/app/Hook.java +++ b/app/src/main/java/com/hidemydevice/app/Hook.java @@ -1,20 +1,51 @@ package com.hidemydevice.app; +import android.accounts.Account; +import android.accounts.AccountManager; import android.bluetooth.BluetoothAdapter; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageInfo; +import android.location.Location; +import android.location.LocationManager; import android.media.MediaDrm; +import android.net.ConnectivityManager; +import android.net.NetworkCapabilities; +import android.net.wifi.ScanResult; import android.net.wifi.WifiInfo; +import android.net.wifi.WifiManager; import android.os.Build; +import android.os.SystemClock; import android.provider.Settings; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; +import android.view.inputmethod.InputMethodInfo; +import android.view.inputmethod.InputMethodManager; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.net.InetAddress; +import java.net.InetSocketAddress; import java.net.NetworkInterface; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; import java.util.EnumMap; +import java.util.Enumeration; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.TimeZone; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; @@ -26,16 +57,16 @@ /** * Xposed entry point (see assets/xposed_init). Runs inside every app selected in the module scope. - * - *

The settings are read once, when the app process starts, and a hook is installed only for - * the fields that have a value - unset fields and a disabled module cost nothing at runtime. */ public class Hook implements IXposedHookLoadPackage { private static final String TAG = "HideMyDevice: "; private static final String ADVERTISING_INFO_CLASS = "com.google.android.gms.ads.identifier.AdvertisingIdClient$Info"; + private static final String PACKAGE_MANAGER_CLASS = "android.app.ApplicationPackageManager"; + private static final String PLAY_STORE = "com.android.vending"; private static final AtomicBoolean installed = new AtomicBoolean(); + private static final Random SENSOR_RANDOM = new Random(); @Override public void handleLoadPackage(LoadPackageParam lpparam) { @@ -48,47 +79,59 @@ public void handleLoadPackage(LoadPackageParam lpparam) { } return; } - // Never spoof inside system_server; the hooks belong in the apps that read the ids. if ("android".equals(lpparam.packageName)) { return; } - // A process can host several packages; the framework classes only need hooking once. if (!installed.compareAndSet(false, true)) { return; } XSharedPreferences prefs = new XSharedPreferences(Prefs.PACKAGE, Prefs.NAME); if (!prefs.getFile().canRead()) { - XposedBridge.log(TAG + "cannot read " + prefs.getFile() + " in " + lpparam.packageName - + " - open the Hide My Device app once and save a value"); + XposedBridge.log(TAG + "cannot read " + prefs.getFile() + " in " + lpparam.packageName); return; } if (!prefs.getBoolean(Prefs.ENABLED, true)) { return; } + Map values = load(prefs); - if (values.isEmpty()) { - return; - } + // Every hook installer below swallows its own failures: one unsupported API on one Android + // version must not stop the rest of the module from being applied. hookTelephony(values); hookBuild(values); hookNetwork(values); hookSettings(values); hookMediaDrm(values); hookAdvertisingId(values, lpparam.classLoader); + + hookVpnHiding(prefs); + hookDeveloperMode(prefs); + hookPlayStoreInstaller(prefs); + hookKeyboards(values); + hookLanScan(prefs); + hookWifiScans(prefs); + hookGeoLocationTimezone(values); + hookAccounts(values); + hookHiddenApps(values); + hookSensors(prefs); + hookProxy(prefs, values); } - /** @return the fields to spoof in this process; unset fields are absent */ private static Map load(XSharedPreferences prefs) { Map fresh = prefs.getBoolean(Prefs.RANDOM_EACH_LAUNCH, false) ? Randomizer.all() : null; Map values = new EnumMap<>(Field.class); for (Field field : Field.values()) { - String value = prefs.getString(field.key, ""); - if (value != null && !value.isEmpty()) { - values.put(field, fresh != null ? fresh.get(field) : value); + String value = Prefs.string(prefs, field.key); + if (value.isEmpty()) { + continue; } + // Randomising per launch only applies to identifiers. A re-rolled proxy address or + // hide list would just break the feature the user configured. + String replacement = fresh != null && field.randomizable ? fresh.get(field) : null; + values.put(field, replacement != null ? replacement : value); } return values; } @@ -168,7 +211,6 @@ private static void hookNetwork(Map v) { constant(WifiInfo.class, "getMacAddress", v.get(Field.WIFI_MAC)); constant(WifiInfo.class, "getBSSID", v.get(Field.BSSID)); String ssid = v.get(Field.SSID); - // WifiInfo reports UTF-8 network names wrapped in double quotes constant(WifiInfo.class, "getSSID", ssid == null ? null : "\"" + ssid + "\""); constant(BluetoothAdapter.class, "getAddress", v.get(Field.BT_MAC)); @@ -188,9 +230,8 @@ protected void beforeHookedMethod(MethodHookParam param) { private static void hookSettings(Map v) { String androidId = v.get(Field.ANDROID_ID); String btMac = v.get(Field.BT_MAC); - if (androidId == null && btMac == null) { - return; - } + String defaultIme = v.get(Field.DEFAULT_KEYBOARD_ID); + XC_MethodHook hook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) { @@ -202,10 +243,12 @@ protected void beforeHookedMethod(MethodHookParam param) { param.setResult(androidId); } else if (btMac != null && "bluetooth_address".equals(name)) { param.setResult(btMac); + } else if (defaultIme != null && Settings.Secure.DEFAULT_INPUT_METHOD.equals(name)) { + param.setResult(defaultIme); } } }; - // getString() delegates to getStringForUser(); hook only one of them + if (hookAll(Settings.Secure.class, "getStringForUser", hook) == 0) { hookAll(Settings.Secure.class, "getString", hook); } @@ -226,7 +269,6 @@ protected void beforeHookedMethod(MethodHookParam param) { }); } - /** The advertising id is read through a Google library bundled inside each app. */ private static void hookAdvertisingId(Map v, ClassLoader appClassLoader) { String id = v.get(Field.ADVERTISING_ID); if (id == null) { @@ -238,10 +280,465 @@ private static void hookAdvertisingId(Map v, ClassLoader appClass } } + private static void hookVpnHiding(XSharedPreferences prefs) { + if (!prefs.getBoolean(Prefs.HIDE_VPN, false)) { + return; + } + hookAll(ConnectivityManager.class, "getNetworkCapabilities", new XC_MethodHook() { + @Override + protected void afterHookedMethod(MethodHookParam param) { + NetworkCapabilities nc = (NetworkCapabilities) param.getResult(); + if (nc == null) { + return; + } + try { + XposedHelpers.callMethod(nc, "removeTransportType", NetworkCapabilities.TRANSPORT_VPN); + XposedHelpers.callMethod(nc, "addCapability", NetworkCapabilities.NET_CAPABILITY_NOT_VPN); + } catch (Throwable ignored) { + } + } + }); + + hookAll(NetworkInterface.class, "getNetworkInterfaces", new XC_MethodHook() { + @Override + @SuppressWarnings("unchecked") + protected void afterHookedMethod(MethodHookParam param) { + Object result = param.getResult(); + if (result == null) { + return; + } + List kept = new ArrayList<>(); + for (NetworkInterface ni : Collections.list((Enumeration) result)) { + if (!isTunnel(ni.getName())) { + kept.add(ni); + } + } + param.setResult(Collections.enumeration(kept)); + } + }); + } + + private static boolean isTunnel(String interfaceName) { + String name = interfaceName.toLowerCase(Locale.ROOT); + return name.startsWith("tun") || name.startsWith("ppp") + || name.startsWith("wg") || name.startsWith("tap"); + } + + private static void hookDeveloperMode(XSharedPreferences prefs) { + if (!prefs.getBoolean(Prefs.HIDE_DEV_MODE, false)) { + return; + } + XC_MethodHook hook = new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + if (param.args.length < 2) { + return; + } + String name = String.valueOf(param.args[1]); + if (Settings.Global.DEVELOPMENT_SETTINGS_ENABLED.equals(name) + || Settings.Global.ADB_ENABLED.equals(name) + || "adb_wifi_enabled".equals(name)) { + param.setResult(param.method.getName().startsWith("getInt") ? (Object) 0 : "0"); + } + } + }; + // The *ForUser variants are what the framework actually routes to on recent releases; the + // plain ones remain for older ones and for apps that reflect into them directly. + hookAll(Settings.Global.class, "getInt", hook); + hookAll(Settings.Global.class, "getIntForUser", hook); + hookAll(Settings.Global.class, "getString", hook); + hookAll(Settings.Global.class, "getStringForUser", hook); + } + + private static void hookPlayStoreInstaller(XSharedPreferences prefs) { + if (!prefs.getBoolean(Prefs.SPOOF_PLAY_STORE, false)) { + return; + } + Class pm = XposedHelpers.findClassIfExists(PACKAGE_MANAGER_CLASS, null); + if (pm == null) { + XposedBridge.log(TAG + "no " + PACKAGE_MANAGER_CLASS); + return; + } + hookAll(pm, "getInstallerPackageName", XC_MethodReplacement.returnConstant(PLAY_STORE)); + + // Deprecated since API 30. An app that asks getInstallSourceInfo() instead still sees the + // real installer unless its fields are rewritten too, which makes the spoof trivial to spot. + hookAll(pm, "getInstallSourceInfo", new XC_MethodHook() { + @Override + protected void afterHookedMethod(MethodHookParam param) { + Object info = param.getResult(); + if (info == null) { + return; + } + for (String field : new String[]{ + "mInitiatingPackageName", "mInstallingPackageName", "mOriginatingPackageName", + "mUpdateOwnerPackageName"}) { + try { + XposedHelpers.setObjectField(info, field, PLAY_STORE); + } catch (Throwable ignored) { + // Field names differ between releases; set the ones that exist. + } + } + } + }); + } + + private static void hookKeyboards(Map v) { + Set hidden = csv(v.get(Field.HIDDEN_KEYBOARDS)); + if (hidden.isEmpty()) { + return; + } + XC_MethodHook hook = new XC_MethodHook() { + @Override + @SuppressWarnings("unchecked") + protected void afterHookedMethod(MethodHookParam param) { + List list = (List) param.getResult(); + if (list == null) { + return; + } + List kept = new ArrayList<>(); + for (InputMethodInfo info : list) { + if (!hidden.contains(info.getPackageName())) { + kept.add(info); + } + } + param.setResult(kept); + } + }; + hookAll(InputMethodManager.class, "getInputMethodList", hook); + hookAll(InputMethodManager.class, "getEnabledInputMethodList", hook); + } + + private static void hookLanScan(XSharedPreferences prefs) { + if (!prefs.getBoolean(Prefs.SPOOF_LAN_SCAN, false)) { + return; + } + // Loopback is deliberately left alone: apps run their own local servers on it (WebView + // proxies, media servers), and blocking those breaks the app rather than hiding anything. + hookAll(InetAddress.class, "isReachable", new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + InetAddress address = (InetAddress) param.thisObject; + if (address != null && address.isSiteLocalAddress()) { + param.setResult(false); + } + } + }); + + hookAll(Socket.class, "connect", new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + if (param.args.length == 0 || !(param.args[0] instanceof InetSocketAddress)) { + return; + } + InetAddress address = ((InetSocketAddress) param.args[0]).getAddress(); + if (address != null && address.isSiteLocalAddress()) { + param.setThrowable(new SocketTimeoutException("Connection timed out")); + } + } + }); + } + + private static void hookWifiScans(XSharedPreferences prefs) { + if (!prefs.getBoolean(Prefs.SPOOF_WIFI_SCANS, false)) { + return; + } + // An empty list is what the platform itself returns without location permission, so it is + // the one plausible answer available; fabricating ScanResults would not survive inspection. + hookAll(WifiManager.class, "getScanResults", + XC_MethodReplacement.returnConstant(new ArrayList())); + } + + private static void hookGeoLocationTimezone(Map v) { + String zoneId = v.get(Field.TIMEZONE); + if (zoneId != null) { + TimeZone zone = TimeZone.getTimeZone(zoneId); + if (!zone.getID().equalsIgnoreCase(zoneId)) { + // getTimeZone falls back to GMT for an unknown id rather than failing, which would + // silently put the app in UTC. + XposedBridge.log(TAG + "unknown timezone " + zoneId); + } else { + try { + TimeZone.setDefault(zone); + // getDefault() is specified to hand back a copy; sharing one instance lets an + // app that calls setRawOffset on it corrupt every other caller's zone. + hookAll(TimeZone.class, "getDefault", new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + param.setResult(zone.clone()); + } + }); + } catch (Throwable t) { + XposedBridge.log(TAG + "hookTimezone: " + t); + } + } + } + + hookRegion(v.get(Field.REGION)); + + hookLocation(v.get(Field.LATITUDE), v.get(Field.LONGITUDE)); + } + /** - * Makes every String/CharSequence-returning overload of {@code name} return {@code value}; - * null = no hook. + * Reports {@code region} as the country of {@link Locale#getDefault()}, keeping whatever + * language the device is really set to: forcing the language as well would change the whole app + * UI, which is both visible to the user and a louder signal than the country it hides. + * + *

This has to be a hook rather than a {@link Locale#setDefault} call. The framework applies + * the app's own configuration in {@code ActivityThread.handleBindApplication}, which runs after + * this one and resets the default, so a value set here would simply be overwritten. */ + private static void hookRegion(String region) { + if (region == null) { + return; + } + String country = region.toUpperCase(Locale.ROOT); + // getDefault() is called from String.format, toLowerCase and most of the formatting + // classes, so the callback has to stay cheap. It normally hands back the same instance + // every time, so remembering the last one seen avoids rebuilding the spoofed locale. + AtomicReference memo = new AtomicReference<>(); + hookAll(Locale.class, "getDefault", new XC_MethodHook() { + @Override + protected void afterHookedMethod(MethodHookParam param) { + Locale real = (Locale) param.getResult(); + if (real == null || country.equals(real.getCountry())) { + return; + } + // The {real, spoofed} pair is published as one array so a caller on another + // thread can never read one half against the other's language. + Locale[] cached = memo.get(); + if (cached == null || cached[0] != real) { + cached = new Locale[]{ + real, new Locale(real.getLanguage(), country, real.getVariant())}; + memo.set(cached); + } + param.setResult(cached[1]); + } + }); + } + + private static void hookLocation(String latitude, String longitude) { + if (latitude == null || longitude == null) { + if (latitude != null || longitude != null) { + XposedBridge.log(TAG + "latitude and longitude must both be set to spoof a position"); + } + return; + } + final double lat; + final double lng; + try { + lat = Double.parseDouble(latitude); + lng = Double.parseDouble(longitude); + } catch (NumberFormatException e) { + XposedBridge.log(TAG + "bad coordinates " + latitude + "," + longitude); + return; + } + + hookAll(Location.class, "getLatitude", XC_MethodReplacement.returnConstant(lat)); + hookAll(Location.class, "getLongitude", XC_MethodReplacement.returnConstant(lng)); + + hookAll(LocationManager.class, "getLastKnownLocation", new XC_MethodHook() { + @Override + protected void afterHookedMethod(MethodHookParam param) { + Location location = (Location) param.getResult(); + if (location == null) { + // A fix with no timestamp or accuracy is rejected as stale by most callers, so + // the fabricated one has to look like it was taken just now. + location = new Location(LocationManager.GPS_PROVIDER); + location.setAccuracy(10f); + location.setTime(System.currentTimeMillis()); + location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos()); + } + location.setLatitude(lat); + location.setLongitude(lng); + param.setResult(location); + } + }); + } + + private static void hookAccounts(Map v) { + Set emails = csv(v.get(Field.VIRTUAL_GMAIL)); + if (emails.isEmpty()) { + return; + } + final Account[] accounts; + try { + // new Account("", type) throws, so a stray comma in the list would otherwise take down + // the hooked app rather than this hook. + List list = new ArrayList<>(); + for (String email : emails) { + list.add(new Account(email, "com.google")); + } + accounts = list.toArray(new Account[0]); + } catch (Throwable t) { + XposedBridge.log(TAG + "hookAccounts: " + t); + return; + } + + hookAll(AccountManager.class, "getAccounts", new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + param.setResult(accounts.clone()); + } + }); + + hookAll(AccountManager.class, "getAccountsByType", new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + if (param.args.length > 0 && "com.google".equals(param.args[0])) { + param.setResult(accounts.clone()); + } + } + }); + } + + private static void hookHiddenApps(Map v) { + Set hidden = csv(v.get(Field.HIDDEN_APPS)); + if (hidden.isEmpty()) { + return; + } + Class pm = XposedHelpers.findClassIfExists(PACKAGE_MANAGER_CLASS, null); + if (pm == null) { + XposedBridge.log(TAG + "no " + PACKAGE_MANAGER_CLASS); + return; + } + + hookAll(pm, "getInstalledPackages", new XC_MethodHook() { + @Override + @SuppressWarnings("unchecked") + protected void afterHookedMethod(MethodHookParam param) { + List list = (List) param.getResult(); + if (list == null) { + return; + } + List kept = new ArrayList<>(); + for (PackageInfo info : list) { + if (!hidden.contains(info.packageName)) { + kept.add(info); + } + } + param.setResult(kept); + } + }); + + hookAll(pm, "getInstalledApplications", new XC_MethodHook() { + @Override + @SuppressWarnings("unchecked") + protected void afterHookedMethod(MethodHookParam param) { + List list = (List) param.getResult(); + if (list == null) { + return; + } + List kept = new ArrayList<>(); + for (ApplicationInfo info : list) { + if (!hidden.contains(info.packageName)) { + kept.add(info); + } + } + param.setResult(kept); + } + }); + } + + private static void hookSensors(XSharedPreferences prefs) { + if (!prefs.getBoolean(Prefs.REALISTIC_SENSORS, false)) { + return; + } + Class queue = XposedHelpers.findClassIfExists( + "android.hardware.SystemSensorManager$SensorEventQueue", null); + if (queue == null) { + XposedBridge.log(TAG + "no SensorEventQueue"); + return; + } + hookAll(queue, "dispatchSensorEvent", new XC_MethodHook() { + @Override + protected void beforeHookedMethod(MethodHookParam param) { + if (param.args.length < 2 || !(param.args[1] instanceof float[])) { + return; + } + float[] values = (float[]) param.args[1]; + for (int i = 0; i < values.length; i++) { + float value = values[i]; + // Only perturb a reading that is already a varying measurement. Adding noise to + // an exact 0 or 1 would corrupt the step counter, proximity and trigger + // sensors, whose values are counts and flags rather than magnitudes. + if (value != 0f && value != 1f && !Float.isNaN(value) && !Float.isInfinite(value)) { + values[i] = value + (SENSOR_RANDOM.nextFloat() - 0.5f) * 0.02f; + } + } + } + }); + } + + private static void hookProxy(XSharedPreferences prefs, Map v) { + if (!prefs.getBoolean(Prefs.PROXY_ENABLED, false)) { + return; + } + String host = v.get(Field.PROXY_HOST); + if (host == null) { + XposedBridge.log(TAG + "proxy enabled but no host set"); + return; + } + int port; + try { + port = Integer.parseInt(v.getOrDefault(Field.PROXY_PORT, "8080")); + } catch (NumberFormatException e) { + XposedBridge.log(TAG + "bad proxy port: " + v.get(Field.PROXY_PORT)); + return; + } + + Proxy.Type type = "SOCKS".equalsIgnoreCase(v.get(Field.PROXY_TYPE)) + ? Proxy.Type.SOCKS : Proxy.Type.HTTP; + List proxy = + Collections.singletonList(new Proxy(type, InetSocketAddress.createUnresolved(host, port))); + + try { + ProxySelector selector = new ProxySelector() { + @Override + public List select(URI uri) { + // Sending the app's own loopback and LAN traffic through an external proxy + // breaks it, so only route what actually leaves the device. + return isLocal(uri) ? Collections.singletonList(Proxy.NO_PROXY) : proxy; + } + + @Override + public void connectFailed(URI uri, SocketAddress address, java.io.IOException failure) { + XposedBridge.log(TAG + "proxy connect failed for " + uri + ": " + failure); + } + }; + ProxySelector.setDefault(selector); + hookAll(ProxySelector.class, "getDefault", XC_MethodReplacement.returnConstant(selector)); + } catch (Throwable t) { + XposedBridge.log(TAG + "hookProxy: " + t); + } + } + + private static boolean isLocal(URI uri) { + String host = uri == null ? null : uri.getHost(); + if (host == null) { + return true; + } + if ("localhost".equalsIgnoreCase(host) || host.startsWith("127.") || "::1".equals(host)) { + return true; + } + return host.startsWith("10.") || host.startsWith("192.168.") || host.endsWith(".local"); + } + + /** The trimmed, non-empty entries of a comma-separated preference value. */ + private static Set csv(String value) { + Set entries = new LinkedHashSet<>(); + if (value == null) { + return entries; + } + for (String entry : value.split(",")) { + String trimmed = entry.trim(); + if (!trimmed.isEmpty()) { + entries.add(trimmed); + } + } + return entries; + } + private static void constant(Class cls, String name, String value) { if (value == null) { return; @@ -260,7 +757,6 @@ private static void constant(Class cls, String name, String value) { } } - /** @return the number of overloads hooked; a missing method is simply not hooked */ private static int hookAll(Class cls, String name, XC_MethodHook hook) { try { return XposedBridge.hookAllMethods(cls, name, hook).size(); diff --git a/app/src/main/java/com/hidemydevice/app/MainActivity.java b/app/src/main/java/com/hidemydevice/app/MainActivity.java index ac4070b..d73d5f1 100644 --- a/app/src/main/java/com/hidemydevice/app/MainActivity.java +++ b/app/src/main/java/com/hidemydevice/app/MainActivity.java @@ -3,7 +3,9 @@ import android.content.ClipData; import android.content.ClipboardManager; import android.content.DialogInterface; +import android.content.Intent; import android.content.SharedPreferences; +import android.content.res.ColorStateList; import android.net.Uri; import android.os.Build; import android.os.Bundle; @@ -15,6 +17,7 @@ import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; +import androidx.annotation.StringRes; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; @@ -28,6 +31,7 @@ import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; +import org.json.JSONArray; import org.json.JSONObject; import java.io.ByteArrayOutputStream; @@ -37,20 +41,54 @@ import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.EnumMap; +import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity { private static final String BACKUP_FILE_NAME = "hide-my-device.json"; + private static final String BACKUP_PROFILES = "profiles"; + + /** A global on/off switch: the view in the layout, its preference key and its default. */ + private static final class Toggle { + final int viewId; + final String key; + final boolean defaultValue; + + Toggle(int viewId, String key, boolean defaultValue) { + this.viewId = viewId; + this.key = key; + this.defaultValue = defaultValue; + } + } + + /** + * Every switch on the screen, in layout order. Binding, refreshing, exporting and importing all + * walk this one list, so a new toggle only has to be added here and to the layout. + */ + private static final Toggle[] TOGGLES = { + new Toggle(R.id.enabled, Prefs.ENABLED, true), + new Toggle(R.id.random_each_launch, Prefs.RANDOM_EACH_LAUNCH, false), + new Toggle(R.id.hide_vpn, Prefs.HIDE_VPN, false), + new Toggle(R.id.hide_dev_mode, Prefs.HIDE_DEV_MODE, false), + new Toggle(R.id.spoof_play_store, Prefs.SPOOF_PLAY_STORE, false), + new Toggle(R.id.spoof_lan_scan, Prefs.SPOOF_LAN_SCAN, false), + new Toggle(R.id.spoof_wifi_scans, Prefs.SPOOF_WIFI_SCANS, false), + new Toggle(R.id.realistic_sensors, Prefs.REALISTIC_SENSORS, false), + new Toggle(R.id.proxy_enabled, Prefs.PROXY_ENABLED, false), + }; private final Map valueViews = new EnumMap<>(Field.class); + private final MaterialSwitch[] switchViews = new MaterialSwitch[TOGGLES.length]; + private SharedPreferences prefs; + private ProfileManager profileManager; private boolean worldReadable; + private View fab; private TextView statusText; private ImageView statusIcon; private MaterialCardView statusCard; - private MaterialSwitch enabledSwitch; - private MaterialSwitch randomEachLaunchSwitch; + private TextView profileNameText; private final ActivityResultLauncher exportLauncher = registerForActivityResult( new ActivityResultContracts.CreateDocument("application/json"), this::exportTo); @@ -69,30 +107,34 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); - // LSPosed permits MODE_WORLD_READABLE for enabled modules and moves the file to a place - // the hooked apps can read. Without it Android throws a SecurityException. try { prefs = getSharedPreferences(Prefs.NAME, MODE_WORLD_READABLE); worldReadable = true; } catch (SecurityException e) { prefs = getSharedPreferences(Prefs.NAME, MODE_PRIVATE); } + profileManager = new ProfileManager(prefs); statusCard = findViewById(R.id.status_card); statusText = findViewById(R.id.status_text); statusIcon = findViewById(R.id.status_icon); + profileNameText = findViewById(R.id.profile_name); + + findViewById(R.id.btn_switch_profile).setOnClickListener(v -> showSwitchProfileDialog()); + findViewById(R.id.btn_profile_menu).setOnClickListener(v -> showProfileMenu()); fab = findViewById(R.id.random_all); fab.setOnClickListener(v -> save(Randomizer.all())); - enabledSwitch = findViewById(R.id.enabled); - randomEachLaunchSwitch = findViewById(R.id.random_each_launch); - bindSwitch(enabledSwitch, Prefs.ENABLED, true); - bindSwitch(randomEachLaunchSwitch, Prefs.RANDOM_EACH_LAUNCH, false); + for (int i = 0; i < TOGGLES.length; i++) { + switchViews[i] = findViewById(TOGGLES[i].viewId); + bindSwitch(switchViews[i], TOGGLES[i]); + } ViewGroup list = findViewById(R.id.list); LayoutInflater inflater = getLayoutInflater(); Category lastCategory = null; + for (Field field : Field.values()) { if (field.category != lastCategory) { lastCategory = field.category; @@ -110,6 +152,7 @@ protected void onCreate(Bundle savedInstanceState) { item.setOnLongClickListener(v -> copy(field)); list.addView(item); } + refresh(); MaterialToolbar toolbar = findViewById(R.id.toolbar); @@ -122,7 +165,7 @@ protected void onCreate(Bundle savedInstanceState) { } else if (id == R.id.import_values) { importLauncher.launch(new String[]{"application/json", "text/plain", "application/octet-stream"}); } else if (id == R.id.about) { - startActivity(new android.content.Intent(this, AboutActivity.class)); + startActivity(new Intent(this, AboutActivity.class)); } else { return false; } @@ -130,6 +173,116 @@ protected void onCreate(Bundle savedInstanceState) { }); } + // ------------------------------------------------------------------ profiles + + private void showSwitchProfileDialog() { + List profiles = profileManager.getProfiles(); + String[] names = new String[profiles.size()]; + int selected = 0; + Profile active = profileManager.getActiveProfile(); + for (int i = 0; i < profiles.size(); i++) { + names[i] = profiles.get(i).getName(); + if (active != null && profiles.get(i).getId().equals(active.getId())) { + selected = i; + } + } + + new MaterialAlertDialogBuilder(this) + .setTitle(R.string.select_profile) + .setSingleChoiceItems(names, selected, (dialog, which) -> { + profileManager.setActiveProfile(profiles.get(which)); + dialog.dismiss(); + commit(null, getString(R.string.saved)); + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } + + private void showProfileMenu() { + CharSequence[] actions = { + getString(R.string.create_profile), + getString(R.string.rename_profile), + getString(R.string.delete_profile), + }; + new MaterialAlertDialogBuilder(this) + .setTitle(R.string.profile) + .setItems(actions, (dialog, which) -> { + if (which == 0) { + showNameDialog(R.string.create_profile, "", name -> { + profileManager.setActiveProfile(profileManager.createProfile(name)); + commit(null, getString(R.string.saved)); + }); + } else if (which == 1) { + showRenameProfileDialog(); + } else { + confirmDeleteProfile(); + } + }) + .show(); + } + + private void showRenameProfileDialog() { + Profile active = profileManager.getActiveProfile(); + if (active == null) { + return; + } + showNameDialog(R.string.rename_profile, active.getName(), name -> { + active.setName(name); + profileManager.saveProfiles(); + updateProfileName(); + }); + } + + private void confirmDeleteProfile() { + Profile active = profileManager.getActiveProfile(); + if (active == null) { + return; + } + if (profileManager.getProfiles().size() < 2) { + show(getString(R.string.delete_profile_last)); + return; + } + new MaterialAlertDialogBuilder(this) + .setTitle(R.string.delete_profile) + .setMessage(getString(R.string.delete_profile_message, active.getName())) + .setPositiveButton(R.string.delete_profile, (dialog, which) -> { + profileManager.deleteProfile(active); + commit(null, getString(R.string.saved)); + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } + + private interface NameCallback { + void onName(String name); + } + + private void showNameDialog(@StringRes int title, String initial, NameCallback callback) { + View view = getLayoutInflater().inflate(R.layout.dialog_edit, null); + TextInputLayout layout = view.findViewById(R.id.input_layout); + TextInputEditText input = view.findViewById(R.id.input); + layout.setHint(getString(R.string.profile_name)); + layout.setHelperText(null); + input.setText(initial); + + new MaterialAlertDialogBuilder(this) + .setTitle(title) + .setView(view) + .setPositiveButton(R.string.save, (dialog, which) -> { + String name = String.valueOf(input.getText()).trim(); + callback.onName(name.isEmpty() ? getString(R.string.new_profile) : name); + }) + .setNegativeButton(android.R.string.cancel, null) + .show(); + } + + private void updateProfileName() { + Profile active = profileManager.getActiveProfile(); + profileNameText.setText(active != null ? active.getName() : ""); + } + + // ------------------------------------------------------------------ state + private void showStatus() { boolean active = worldReadable || isModuleActive(); statusText.setText(active ? R.string.status_active : R.string.status_inactive); @@ -142,25 +295,28 @@ private void showStatus() { : com.google.android.material.R.attr.colorOnErrorContainer); statusCard.setCardBackgroundColor(bg); statusText.setTextColor(fg); - statusIcon.setImageTintList(android.content.res.ColorStateList.valueOf(fg)); + statusIcon.setImageTintList(ColorStateList.valueOf(fg)); } - private void bindSwitch(MaterialSwitch view, String key, boolean defaultValue) { - view.setChecked(prefs.getBoolean(key, defaultValue)); + private void bindSwitch(MaterialSwitch view, Toggle toggle) { + view.setChecked(prefs.getBoolean(toggle.key, toggle.defaultValue)); view.setOnCheckedChangeListener((button, checked) -> { - // also fires when refresh() syncs the switch to an imported value - if (prefs.getBoolean(key, defaultValue) != checked) { - commit(prefs.edit().putBoolean(key, checked), getString(R.string.saved)); + if (prefs.getBoolean(toggle.key, toggle.defaultValue) != checked) { + commit(prefs.edit().putBoolean(toggle.key, checked), getString(R.string.saved)); } }); } private void refresh() { showStatus(); - enabledSwitch.setChecked(prefs.getBoolean(Prefs.ENABLED, true)); - randomEachLaunchSwitch.setChecked(prefs.getBoolean(Prefs.RANDOM_EACH_LAUNCH, false)); + updateProfileName(); + + for (int i = 0; i < TOGGLES.length; i++) { + switchViews[i].setChecked(prefs.getBoolean(TOGGLES[i].key, TOGGLES[i].defaultValue)); + } + for (Map.Entry entry : valueViews.entrySet()) { - String value = prefs.getString(entry.getKey().key, ""); + String value = Prefs.string(prefs, entry.getKey().key); TextView view = entry.getValue(); if (value.isEmpty()) { view.setText(R.string.not_set); @@ -177,12 +333,17 @@ private void save(Map values) { for (Map.Entry entry : values.entrySet()) { editor.putString(entry.getKey().key, entry.getValue()); } + // One JSON write for the whole batch: the profile store used to be re-serialised and + // committed once per field, which meant around 25 synchronous writes per "Random all". + profileManager.updateActiveProfile(values); commit(editor, getString(R.string.saved)); } + /** @param editor pending changes to write, or null when the values are already stored. */ private void commit(SharedPreferences.Editor editor, CharSequence message) { - // commit(): the file must be on disk before a target app is started - editor.commit(); + if (editor != null) { + editor.commit(); + } if (!worldReadable) { makeReadableForClassicXposed(); } @@ -194,7 +355,6 @@ private void show(CharSequence message) { Snackbar.make(fab, message, Snackbar.LENGTH_SHORT).setAnchorView(fab).show(); } - /** Best effort for frameworks without LSPosed's preference redirection. */ @SuppressWarnings("ResultOfMethodCallIgnored") private void makeReadableForClassicXposed() { File dataDir = new File(getApplicationInfo().dataDir); @@ -206,21 +366,22 @@ private void makeReadableForClassicXposed() { file.setReadable(true, false); } + // ------------------------------------------------------------------ fields + private void randomize(Field field) { save(Randomizer.linked(field, currentOperator())); } private String currentOperator() { - return prefs.getString(Field.SIM_OPERATOR.key, ""); + return Prefs.string(prefs, Field.SIM_OPERATOR.key); } private boolean copy(Field field) { - String value = prefs.getString(field.key, ""); + String value = Prefs.string(prefs, field.key); if (value.isEmpty()) { return false; } getSystemService(ClipboardManager.class).setPrimaryClip(ClipData.newPlainText(field.title, value)); - // Android 13+ shows its own clipboard confirmation if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { show(getString(R.string.copied, field.title)); } @@ -233,7 +394,7 @@ private void edit(Field field) { TextInputEditText input = view.findViewById(R.id.input); layout.setHelperText(field.hint); input.setInputType(field.inputType); - input.setText(prefs.getString(field.key, "")); + input.setText(Prefs.string(prefs, field.key)); AlertDialog dialog = new MaterialAlertDialogBuilder(this) .setTitle(field.title) @@ -242,7 +403,7 @@ private void edit(Field field) { .setNegativeButton(android.R.string.cancel, null) .setNeutralButton(R.string.random, null) .create(); - // Listeners are attached after show() so these buttons do not auto-dismiss the dialog + dialog.setOnShowListener(d -> { dialog.getButton(DialogInterface.BUTTON_NEUTRAL).setOnClickListener(v -> { input.setText(Randomizer.linked(field, currentOperator()).get(field)); @@ -266,27 +427,37 @@ private void confirmClear() { .setTitle(R.string.clear_all) .setMessage(R.string.clear_all_message) .setPositiveButton(R.string.clear_all, (d, which) -> { - SharedPreferences.Editor editor = prefs.edit(); + Map empty = new EnumMap<>(Field.class); for (Field field : Field.values()) { - editor.remove(field.key); + empty.put(field, ""); } - commit(editor, getString(R.string.saved)); + save(empty); }) .setNegativeButton(android.R.string.cancel, null) .show(); } + // ------------------------------------------------------------------ backup + private void exportTo(Uri uri) { if (uri == null) { return; } try { JSONObject json = new JSONObject(); - json.put(Prefs.ENABLED, prefs.getBoolean(Prefs.ENABLED, true)); - json.put(Prefs.RANDOM_EACH_LAUNCH, prefs.getBoolean(Prefs.RANDOM_EACH_LAUNCH, false)); + for (Toggle toggle : TOGGLES) { + json.put(toggle.key, prefs.getBoolean(toggle.key, toggle.defaultValue)); + } for (Field field : Field.values()) { - json.put(field.key, prefs.getString(field.key, "")); + json.put(field.key, Prefs.string(prefs, field.key)); } + JSONArray profiles = new JSONArray(); + for (Profile profile : profileManager.getProfiles()) { + profiles.put(profile.toJson()); + } + json.put(BACKUP_PROFILES, profiles); + json.put(Prefs.ACTIVE_PROFILE_ID, Prefs.string(prefs, Prefs.ACTIVE_PROFILE_ID)); + try (OutputStream out = getContentResolver().openOutputStream(uri)) { out.write(json.toString(2).getBytes(StandardCharsets.UTF_8)); } @@ -310,8 +481,7 @@ private void importFrom(Uri uri) { } JSONObject json = new JSONObject(new String(bytes.toByteArray(), StandardCharsets.UTF_8)); - SharedPreferences.Editor editor = prefs.edit(); - int imported = 0; + Map values = new EnumMap<>(Field.class); int skipped = 0; for (Field field : Field.values()) { if (!json.has(field.key)) { @@ -319,19 +489,39 @@ private void importFrom(Uri uri) { } String value = json.optString(field.key, "").trim(); if (value.isEmpty() || field.isValid(value)) { - editor.putString(field.key, value); - imported++; + values.put(field, value); } else { skipped++; } } - if (json.has(Prefs.ENABLED)) { - editor.putBoolean(Prefs.ENABLED, json.optBoolean(Prefs.ENABLED, true)); + + SharedPreferences.Editor editor = prefs.edit(); + for (Map.Entry entry : values.entrySet()) { + editor.putString(entry.getKey().key, entry.getValue()); } - if (json.has(Prefs.RANDOM_EACH_LAUNCH)) { - editor.putBoolean(Prefs.RANDOM_EACH_LAUNCH, json.optBoolean(Prefs.RANDOM_EACH_LAUNCH, false)); + for (Toggle toggle : TOGGLES) { + if (json.has(toggle.key)) { + editor.putBoolean(toggle.key, json.optBoolean(toggle.key, toggle.defaultValue)); + } + } + boolean hasProfiles = json.has(BACKUP_PROFILES); + if (hasProfiles) { + editor.putString(Prefs.PROFILES_DATA, json.getJSONArray(BACKUP_PROFILES).toString()); + editor.putString(Prefs.ACTIVE_PROFILE_ID, json.optString(Prefs.ACTIVE_PROFILE_ID, "")); + } + editor.commit(); + + if (hasProfiles) { + // The backup replaced the profile store, so drop the stale in-memory copy before + // anything can write it back out, then mirror the active profile into the flat keys + // so the two cannot disagree. + profileManager.reload(); + profileManager.setActiveProfile(profileManager.getActiveProfile()); + } else { + // A backup from a build without profiles: fold its values into the active one. + profileManager.updateActiveProfile(values); } - commit(editor, getString(R.string.imported, imported, skipped)); + commit(null, getString(R.string.imported, values.size(), skipped)); } catch (Exception e) { show(getString(R.string.import_failed, e.getMessage())); } diff --git a/app/src/main/java/com/hidemydevice/app/Prefs.java b/app/src/main/java/com/hidemydevice/app/Prefs.java index 4f13f97..c69b339 100644 --- a/app/src/main/java/com/hidemydevice/app/Prefs.java +++ b/app/src/main/java/com/hidemydevice/app/Prefs.java @@ -1,5 +1,7 @@ package com.hidemydevice.app; +import android.content.SharedPreferences; + /** Location and non-field keys of the preference file shared between the UI and the hooks. */ final class Prefs { /** The application id (not the Java package); must match applicationId in app/build.gradle. */ @@ -11,6 +13,47 @@ final class Prefs { /** boolean, default false: replace every set value with a fresh random one per app start. */ static final String RANDOM_EACH_LAUNCH = "random_each_launch"; + // Profiles + static final String ACTIVE_PROFILE_ID = "active_profile_id"; + static final String PROFILES_DATA = "profiles_data"; + + // Privacy & Spoofing Feature Switches + static final String HIDE_VPN = "hide_vpn"; + static final String HIDE_DEV_MODE = "hide_dev_mode"; + static final String SPOOF_PLAY_STORE = "spoof_play_store"; + static final String SPOOF_LAN_SCAN = "spoof_lan_scan"; + static final String SPOOF_WIFI_SCANS = "spoof_wifi_scans"; + static final String REALISTIC_SENSORS = "realistic_sensors"; + + // Configurable Values + static final String HIDDEN_KEYBOARDS = "hidden_keyboards"; + static final String DEFAULT_KEYBOARD_ID = "default_keyboard_id"; + static final String SPOOF_TIMEZONE = "spoof_timezone"; + static final String SPOOF_REGION = "spoof_region"; + static final String SPOOF_LATITUDE = "spoof_latitude"; + static final String SPOOF_LONGITUDE = "spoof_longitude"; + static final String HIDDEN_APPS = "hidden_apps"; + static final String VIRTUAL_GMAIL_ACCOUNTS = "virtual_gmail_accounts"; + + // Proxy Settings + static final String PROXY_ENABLED = "proxy_enabled"; + static final String PROXY_HOST = "proxy_host"; + static final String PROXY_PORT = "proxy_port"; + static final String PROXY_TYPE = "proxy_type"; + + /** + * {@link SharedPreferences#getString} that tolerates a key an older build stored under another + * type, instead of letting the {@link ClassCastException} escape into the hooked app. + */ + static String string(SharedPreferences prefs, String key) { + try { + String value = prefs.getString(key, ""); + return value == null ? "" : value; + } catch (ClassCastException e) { + return ""; + } + } + private Prefs() { } } diff --git a/app/src/main/java/com/hidemydevice/app/Profile.java b/app/src/main/java/com/hidemydevice/app/Profile.java new file mode 100644 index 0000000..e12ca6e --- /dev/null +++ b/app/src/main/java/com/hidemydevice/app/Profile.java @@ -0,0 +1,90 @@ +package com.hidemydevice.app; + +import android.content.SharedPreferences; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +/** + * One named set of spoofed values. Only the active profile is mirrored into the flat preference + * keys that {@link Hook} reads; the rest sit in {@link Prefs#PROFILES_DATA} as JSON. + * + *

Everything a profile holds is keyed by {@link Field#key}. The feature switches (enabled, + * random each launch, the hiding toggles, proxy on/off) are deliberately global instead: they + * describe how the module behaves, not which device it pretends to be. + */ +final class Profile { + private final String id; + private String name; + private final Map values = new HashMap<>(); + + Profile(String name) { + this(UUID.randomUUID().toString(), name); + } + + Profile(String id, String name) { + this.id = id; + this.name = name; + } + + /** A profile holding whatever is currently stored in the flat keys. */ + static Profile of(String id, String name, SharedPreferences prefs) { + Profile profile = new Profile(id, name); + for (Field field : Field.values()) { + profile.setValue(field.key, Prefs.string(prefs, field.key)); + } + return profile; + } + + static Profile fromJson(JSONObject json) throws JSONException { + Profile profile = new Profile( + json.optString("id", UUID.randomUUID().toString()), + json.optString("name", "Profile")); + JSONObject stored = json.optJSONObject("values"); + if (stored != null) { + for (Iterator keys = stored.keys(); keys.hasNext(); ) { + String key = keys.next(); + profile.setValue(key, stored.optString(key, "")); + } + } + return profile; + } + + JSONObject toJson() throws JSONException { + JSONObject json = new JSONObject(); + json.put("id", id); + json.put("name", name); + json.put("values", new JSONObject(values)); + return json; + } + + String getId() { + return id; + } + + String getName() { + return name; + } + + void setName(String name) { + this.name = name; + } + + String getValue(String key) { + String value = values.get(key); + return value != null ? value : ""; + } + + void setValue(String key, String value) { + if (value == null || value.isEmpty()) { + values.remove(key); + } else { + values.put(key, value); + } + } +} diff --git a/app/src/main/java/com/hidemydevice/app/ProfileManager.java b/app/src/main/java/com/hidemydevice/app/ProfileManager.java new file mode 100644 index 0000000..24958b5 --- /dev/null +++ b/app/src/main/java/com/hidemydevice/app/ProfileManager.java @@ -0,0 +1,149 @@ +package com.hidemydevice.app; + +import android.content.SharedPreferences; + +import org.json.JSONArray; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * The saved profiles, one of which is mirrored into the flat preference keys the hooks read. + * + *

Writes go through {@link SharedPreferences.Editor#commit()} rather than {@code apply()} so the + * XML file is on disk before the user is told to restart the target apps. + */ +final class ProfileManager { + private static final String DEFAULT_ID = "default"; + + private final SharedPreferences prefs; + private final List profiles = new ArrayList<>(); + private Profile active; + + ProfileManager(SharedPreferences prefs) { + this.prefs = prefs; + reload(); + } + + /** Re-reads the stored profiles, e.g. after an import has replaced them. */ + void reload() { + repairNonStringKeys(); + profiles.clear(); + try { + JSONArray array = new JSONArray(prefs.getString(Prefs.PROFILES_DATA, "[]")); + for (int i = 0; i < array.length(); i++) { + profiles.add(Profile.fromJson(array.getJSONObject(i))); + } + } catch (Exception ignored) { + } + if (profiles.isEmpty()) { + // First run, or an upgrade from a build without profiles: adopt the values already + // stored in the flat keys, so switching away and back does not wipe them. + profiles.add(Profile.of(DEFAULT_ID, "Default profile", prefs)); + saveProfiles(); + } + active = byId(prefs.getString(Prefs.ACTIVE_PROFILE_ID, DEFAULT_ID)); + if (active == null) { + active = profiles.get(0); + } + } + + /** + * Clears any field key an older build wrote under a non-String type. {@code proxy_port} used to + * be stored as an int, which made every later {@code getString} on it throw. + */ + private void repairNonStringKeys() { + SharedPreferences.Editor editor = null; + for (Field field : Field.values()) { + if (!prefs.contains(field.key)) { + continue; + } + try { + prefs.getString(field.key, ""); + } catch (ClassCastException e) { + if (editor == null) { + editor = prefs.edit(); + } + editor.remove(field.key); + } + } + if (editor != null) { + editor.commit(); + } + } + + List getProfiles() { + return profiles; + } + + Profile getActiveProfile() { + return active; + } + + private Profile byId(String id) { + for (Profile profile : profiles) { + if (profile.getId().equals(id)) { + return profile; + } + } + return null; + } + + void saveProfiles() { + try { + JSONArray array = new JSONArray(); + for (Profile profile : profiles) { + array.put(profile.toJson()); + } + prefs.edit().putString(Prefs.PROFILES_DATA, array.toString()).commit(); + } catch (Exception ignored) { + } + } + + Profile createProfile(String name) { + Profile profile = new Profile(name); + profiles.add(profile); + saveProfiles(); + return profile; + } + + /** @return false when {@code profile} is the only one left, which must stay. */ + boolean deleteProfile(Profile profile) { + if (profiles.size() < 2 || !profiles.remove(profile)) { + return false; + } + saveProfiles(); + if (profile.equals(active)) { + setActiveProfile(profiles.get(0)); + } + return true; + } + + void setActiveProfile(Profile profile) { + if (profile == null) { + return; + } + active = profile; + SharedPreferences.Editor editor = prefs.edit(); + editor.putString(Prefs.ACTIVE_PROFILE_ID, profile.getId()); + for (Field field : Field.values()) { + editor.putString(field.key, profile.getValue(field.key)); + } + editor.commit(); + } + + /** + * Records {@code values} in the active profile. The caller is expected to write the same values + * to the flat keys in one editor of its own, so this only touches the profile store. + */ + void updateActiveProfile(Map values) { + if (active == null) { + return; + } + for (Map.Entry entry : values.entrySet()) { + active.setValue(entry.getKey().key, entry.getValue()); + } + saveProfiles(); + } +} diff --git a/app/src/main/java/com/hidemydevice/app/Randomizer.java b/app/src/main/java/com/hidemydevice/app/Randomizer.java index 2f5f721..b953851 100644 --- a/app/src/main/java/com/hidemydevice/app/Randomizer.java +++ b/app/src/main/java/com/hidemydevice/app/Randomizer.java @@ -13,19 +13,24 @@ final class Randomizer { private static final String HEX = "0123456789abcdef"; private static final String SERIAL_CHARS = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"; - /** MCC+MNC, operator name, country ISO, country calling code. */ + /** + * MCC+MNC, operator name, country ISO, country calling code, zone id and the latitude and + * longitude of a large city in that country - so a randomised SIM, timezone, region and GPS + * position all describe the same place. A device whose carrier, clock and coordinates disagree + * stands out more than one that never spoofed them at all. + */ private static final String[][] OPERATORS = { - {"310260", "T-Mobile", "us", "1"}, - {"310410", "AT&T", "us", "1"}, - {"311480", "Verizon", "us", "1"}, - {"302720", "Rogers", "ca", "1"}, - {"23415", "Vodafone UK", "gb", "44"}, - {"23410", "O2 - UK", "gb", "44"}, - {"26201", "Telekom.de", "de", "49"}, - {"20801", "Orange F", "fr", "33"}, - {"22210", "Vodafone IT", "it", "39"}, - {"40445", "Airtel", "in", "91"}, - {"50501", "Telstra", "au", "61"}, + {"310260", "T-Mobile", "us", "1", "America/New_York", "40.7128", "-74.0060"}, + {"310410", "AT&T", "us", "1", "America/Chicago", "41.8781", "-87.6298"}, + {"311480", "Verizon", "us", "1", "America/Los_Angeles", "34.0522", "-118.2437"}, + {"302720", "Rogers", "ca", "1", "America/Toronto", "43.6532", "-79.3832"}, + {"23415", "Vodafone UK", "gb", "44", "Europe/London", "51.5074", "-0.1278"}, + {"23410", "O2 - UK", "gb", "44", "Europe/London", "53.4808", "-2.2426"}, + {"26201", "Telekom.de", "de", "49", "Europe/Berlin", "52.5200", "13.4050"}, + {"20801", "Orange F", "fr", "33", "Europe/Paris", "48.8566", "2.3522"}, + {"22210", "Vodafone IT", "it", "39", "Europe/Rome", "41.9028", "12.4964"}, + {"40445", "Airtel", "in", "91", "Asia/Kolkata", "19.0760", "72.8777"}, + {"50501", "Telstra", "au", "61", "Australia/Sydney", "-33.8688", "151.2093"}, }; /** Build.BRAND, Build.MANUFACTURER, Build.MODEL. */ @@ -52,10 +57,11 @@ private Randomizer() { /** * A new value for {@code field}, together with the fields that are only believable when they - * change with it (operator code/name/country, device brand/manufacturer/model). + * change with it (operator code/name/country, device brand/manufacturer/model, and the + * timezone/region/position that belong to the operator's country). * - * @param operatorCode the MCC+MNC currently in use, so SIM values stay consistent with it; - * may be empty + * @param operatorCode the MCC+MNC currently in use, so SIM and location values stay consistent + * with it; may be empty */ static Map linked(Field field, String operatorCode) { Map values = new EnumMap<>(Field.class); @@ -70,20 +76,32 @@ static Map linked(Field field, String operatorCode) { case MODEL: putDevice(values, pick(DEVICES)); break; + case TIMEZONE: + case REGION: + case LATITUDE: + case LONGITUDE: { + String[] op = find(operatorCode); + putLocation(values, op != null ? op : pick(OPERATORS)); + break; + } default: values.put(field, single(field, operatorCode)); } return values; } - /** Random values for every field, with all SIM values belonging to the same operator. */ + /** + * Random values for every randomisable field, with the SIM, timezone, region and GPS position + * all belonging to the same operator. Configuration fields ({@link Field#randomizable} false) + * are left untouched. + */ static Map all() { String[] op = pick(OPERATORS); Map values = new EnumMap<>(Field.class); putOperator(values, op); putDevice(values, pick(DEVICES)); for (Field field : Field.values()) { - if (!values.containsKey(field)) { + if (field.randomizable && !values.containsKey(field)) { values.put(field, single(field, op[0])); } } @@ -94,6 +112,22 @@ private static void putOperator(Map values, String[] op) { values.put(Field.SIM_OPERATOR, op[0]); values.put(Field.SIM_OPERATOR_NAME, op[1]); values.put(Field.SIM_COUNTRY, op[2]); + // A new carrier moves the device to a new country, so the clock and position follow it. + // The reverse is not true: picking a timezone leaves the SIM alone. + putLocation(values, op); + } + + private static void putLocation(Map values, String[] op) { + values.put(Field.TIMEZONE, op[4]); + values.put(Field.REGION, op[2].toUpperCase(Locale.ROOT)); + // Jitter the city centre by up to ~5km so repeated randomising is not a fixed landmark. + values.put(Field.LATITUDE, jitter(op[5])); + values.put(Field.LONGITUDE, jitter(op[6])); + } + + private static String jitter(String degrees) { + double value = Double.parseDouble(degrees) + (RANDOM.nextDouble() - 0.5) * 0.1; + return String.format(Locale.ROOT, "%.4f", value); } private static void putDevice(Map values, String[] device) { @@ -134,6 +168,29 @@ private static String single(Field field, String operatorCode) { } case MEDIA_DRM: return chars(HEX, 64); + case TIMEZONE: + case REGION: + case LATITUDE: + case LONGITUDE: { + Map location = new EnumMap<>(Field.class); + String[] op = find(operatorCode); + putLocation(location, op != null ? op : pick(OPERATORS)); + return location.get(field); + } + case DEFAULT_KEYBOARD_ID: + return "com.google.android.inputmethod.latin/.LatinIME"; + case HIDDEN_KEYBOARDS: + return "com.baidu.input,com.sohu.inputmethod.sogou"; + case HIDDEN_APPS: + return "com.topjohnwu.magisk,org.meowcat.edxp.manager"; + case VIRTUAL_GMAIL: + return "user" + chars(DIGITS, 6) + "@gmail.com"; + case PROXY_HOST: + return "192.168.1." + (10 + RANDOM.nextInt(200)); + case PROXY_PORT: + return "8080"; + case PROXY_TYPE: + return "HTTP"; default: throw new IllegalArgumentException(field.name()); } diff --git a/app/src/main/res/drawable/ic_more_vert.xml b/app/src/main/res/drawable/ic_more_vert.xml new file mode 100644 index 0000000..ed9ddc5 --- /dev/null +++ b/app/src/main/res/drawable/ic_more_vert.xml @@ -0,0 +1,11 @@ + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index bd18efa..ba81ede 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -1,6 +1,7 @@ @@ -79,7 +80,73 @@ style="?attr/materialCardViewElevatedStyle" android:layout_width="match_parent" android:layout_height="wrap_content" - android:layout_marginBottom="4dp" + android:layout_marginBottom="12dp" + app:cardCornerRadius="20dp"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3280a8b..cd631f9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -43,4 +43,30 @@ Device model Wi-Fi & Bluetooth SIM & mobile + Timezone, Region & GPS + Keyboard & IME + System Privacy & Hiding + Proxy & Virtual Accounts + + + Profile + Profile options + Switch + Select profile + New profile + Rename profile + Delete profile + Delete "%1$s"? Its saved values are lost and the first profile becomes active. + The last profile cannot be deleted. + Profile name + New profile + + + Hide active VPN connection + Hide developer options and ADB state + Report Google Play as the installer + Block private LAN scans + Hide nearby Wi-Fi scan results + Add realistic sensor noise + Send app traffic through the proxy below