fix: prevent in-place mutation of location objects and isolate system cache

This commit is contained in:
LZX committed 2026-10-20 18:40:32 +08:00
1 parent d615f5d030
commit 7ad462a524
21 files changed
+1666 -1474

No files matched your search

@@ -1,7 +1,10 @@
package com.lzxnone.openloc.data.preference package com.lzxnone.openloc.data.preference
import android.content.Context import android.content.Context
import android.content.Intent
import android.content.SharedPreferences import android.content.SharedPreferences
import android.location.LocationManager
import android.os.Bundle
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableLongStateOf
@@ -12,6 +15,7 @@ import androidx.compose.ui.graphics.toArgb
import com.lzxnone.openloc.R import com.lzxnone.openloc.R
import com.lzxnone.openloc.core.util.SearchResult import com.lzxnone.openloc.core.util.SearchResult
import com.lzxnone.openloc.data.model.FavoriteItem import com.lzxnone.openloc.data.model.FavoriteItem
import com.lzxnone.openloc.hook.model.GlobalMockMemory
enum class ThemeMode(@param:StringRes val titleRes: Int) { enum class ThemeMode(@param:StringRes val titleRes: Int) {
SYSTEM(R.string.settings_theme_mode_system), SYSTEM(R.string.settings_theme_mode_system),
@@ -86,6 +90,8 @@ object AppPreferences {
private const val KEY_SERVICE_ENABLED = "mock_service_enabled" private const val KEY_SERVICE_ENABLED = "mock_service_enabled"
private lateinit var prefs: SharedPreferences private lateinit var prefs: SharedPreferences
@Volatile
private var appContext: Context? = null
var themeMode by mutableStateOf(ThemeMode.SYSTEM) var themeMode by mutableStateOf(ThemeMode.SYSTEM)
private set private set
@@ -181,6 +187,7 @@ object AppPreferences {
private set private set
fun init(context: Context) { fun init(context: Context) {
appContext = context.applicationContext
prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val modeOrdinal = prefs.getInt(KEY_THEME_MODE, ThemeMode.SYSTEM.ordinal) val modeOrdinal = prefs.getInt(KEY_THEME_MODE, ThemeMode.SYSTEM.ordinal)
@@ -227,9 +234,37 @@ object AppPreferences {
isStealthEnabled = prefs.getBoolean(KEY_ENABLE_STEALTH, true) isStealthEnabled = prefs.getBoolean(KEY_ENABLE_STEALTH, true)
isDevCamouflageEnabled = prefs.getBoolean(KEY_ENABLE_DEV_CAMOUFLAGE, true) isDevCamouflageEnabled = prefs.getBoolean(KEY_ENABLE_DEV_CAMOUFLAGE, true)
isAutoCheckUpdateEnabled = prefs.getBoolean(KEY_AUTO_CHECK_UPDATE, true) isAutoCheckUpdateEnabled = prefs.getBoolean(KEY_AUTO_CHECK_UPDATE, true)
syncConfigToSystem()
} }
fun syncConfigToSystem() {
try {
val ctx = appContext ?: return
val lm = ctx.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return
val bundle = Bundle().apply {
putBoolean(GlobalMockMemory.EXTRA_ENABLED, isServiceEnabled)
putDouble(GlobalMockMemory.EXTRA_LATITUDE, mockLatitude)
putDouble(GlobalMockMemory.EXTRA_LONGITUDE, mockLongitude)
putDouble(GlobalMockMemory.EXTRA_ALTITUDE, 50.0)
putFloat(GlobalMockMemory.EXTRA_ACCURACY, 5.0f)
putString(GlobalMockMemory.EXTRA_LOCATION_NAME, mockLocationName)
putString(GlobalMockMemory.EXTRA_MODE, appMockMode.name)
putStringArrayList(GlobalMockMemory.EXTRA_WHITELIST, ArrayList(whitelistApps))
putStringArrayList(GlobalMockMemory.EXTRA_BLACKLIST, ArrayList(blacklistApps))
}
// 1. 原生底层 IPC 隧道(直达 system_server 与全局内存)
lm.sendExtraCommand(GlobalMockMemory.COMMAND_PROVIDER, GlobalMockMemory.COMMAND_SYNC, bundle)
// 2. 隐式广播双重保险
val intent = Intent("com.lzxnone.openloc.ACTION_SYNC_CONFIG").apply {
putExtras(bundle)
}
ctx.sendBroadcast(intent)
} catch (_: Throwable) {}
}
fun updateMockLocation(latitude: Double, longitude: Double, name: String = "", isUserManual: Boolean = true) { fun updateMockLocation(latitude: Double, longitude: Double, name: String = "", isUserManual: Boolean = true) {
mockLatitude = latitude mockLatitude = latitude
mockLongitude = longitude mockLongitude = longitude
@@ -245,6 +280,8 @@ object AppPreferences {
.putString(KEY_MOCK_LONGITUDE, longitude.toString()) .putString(KEY_MOCK_LONGITUDE, longitude.toString())
.putString(KEY_MOCK_LOCATION_NAME, mockLocationName) .putString(KEY_MOCK_LOCATION_NAME, mockLocationName)
.apply() .apply()
syncConfigToSystem()
} }
fun updateThemeMode(mode: ThemeMode) { fun updateThemeMode(mode: ThemeMode) {
@@ -271,6 +308,7 @@ object AppPreferences {
fun updateServiceEnabled(enabled: Boolean) { fun updateServiceEnabled(enabled: Boolean) {
isServiceEnabled = enabled isServiceEnabled = enabled
prefs.edit().putBoolean(KEY_SERVICE_ENABLED, enabled).apply() prefs.edit().putBoolean(KEY_SERVICE_ENABLED, enabled).apply()
syncConfigToSystem()
} }
fun addSearchHistory(item: SearchResult) { fun addSearchHistory(item: SearchResult) {
@@ -425,11 +463,13 @@ object AppPreferences {
fun updateAppMockMode(mode: AppMockMode) { fun updateAppMockMode(mode: AppMockMode) {
appMockMode = mode appMockMode = mode
prefs.edit().putString(KEY_APP_MOCK_MODE, mode.name).apply() prefs.edit().putString(KEY_APP_MOCK_MODE, mode.name).apply()
syncConfigToSystem()
} }
fun updateWhitelistApps(packages: Set<String>) { fun updateWhitelistApps(packages: Set<String>) {
whitelistApps = packages whitelistApps = packages
savePackageSet(KEY_WHITELIST_APPS, packages) savePackageSet(KEY_WHITELIST_APPS, packages)
syncConfigToSystem()
} }
fun toggleWhitelistApp(packageName: String) { fun toggleWhitelistApp(packageName: String) {
@@ -444,6 +484,7 @@ object AppPreferences {
fun updateBlacklistApps(packages: Set<String>) { fun updateBlacklistApps(packages: Set<String>) {
blacklistApps = packages blacklistApps = packages
savePackageSet(KEY_BLACKLIST_APPS, packages) savePackageSet(KEY_BLACKLIST_APPS, packages)
syncConfigToSystem()
} }
fun toggleBlacklistApp(packageName: String) { fun toggleBlacklistApp(packageName: String) {
@@ -479,31 +520,37 @@ object AppPreferences {
fun updateJitterEnabled(enabled: Boolean) { fun updateJitterEnabled(enabled: Boolean) {
isJitterEnabled = enabled isJitterEnabled = enabled
prefs.edit().putBoolean(KEY_ENABLE_JITTER, enabled).apply() prefs.edit().putBoolean(KEY_ENABLE_JITTER, enabled).apply()
syncConfigToSystem()
} }
fun updateGnssSimulationEnabled(enabled: Boolean) { fun updateGnssSimulationEnabled(enabled: Boolean) {
isGnssSimulationEnabled = enabled isGnssSimulationEnabled = enabled
prefs.edit().putBoolean(KEY_ENABLE_GNSS_SIMULATION, enabled).apply() prefs.edit().putBoolean(KEY_ENABLE_GNSS_SIMULATION, enabled).apply()
syncConfigToSystem()
} }
fun updateNetworkCamouflageEnabled(enabled: Boolean) { fun updateNetworkCamouflageEnabled(enabled: Boolean) {
isNetworkCamouflageEnabled = enabled isNetworkCamouflageEnabled = enabled
prefs.edit().putBoolean(KEY_ENABLE_NETWORK_CAMOUFLAGE, enabled).apply() prefs.edit().putBoolean(KEY_ENABLE_NETWORK_CAMOUFLAGE, enabled).apply()
syncConfigToSystem()
} }
fun updateSensorSimulationEnabled(enabled: Boolean) { fun updateSensorSimulationEnabled(enabled: Boolean) {
isSensorSimulationEnabled = enabled isSensorSimulationEnabled = enabled
prefs.edit().putBoolean(KEY_ENABLE_SENSOR_SIMULATION, enabled).apply() prefs.edit().putBoolean(KEY_ENABLE_SENSOR_SIMULATION, enabled).apply()
syncConfigToSystem()
} }
fun updateStealthEnabled(enabled: Boolean) { fun updateStealthEnabled(enabled: Boolean) {
isStealthEnabled = enabled isStealthEnabled = enabled
prefs.edit().putBoolean(KEY_ENABLE_STEALTH, enabled).apply() prefs.edit().putBoolean(KEY_ENABLE_STEALTH, enabled).apply()
syncConfigToSystem()
} }
fun updateDevCamouflageEnabled(enabled: Boolean) { fun updateDevCamouflageEnabled(enabled: Boolean) {
isDevCamouflageEnabled = enabled isDevCamouflageEnabled = enabled
prefs.edit().putBoolean(KEY_ENABLE_DEV_CAMOUFLAGE, enabled).apply() prefs.edit().putBoolean(KEY_ENABLE_DEV_CAMOUFLAGE, enabled).apply()
syncConfigToSystem()
} }
fun updateAutoCheckUpdateEnabled(enabled: Boolean) { fun updateAutoCheckUpdateEnabled(enabled: Boolean) {
@@ -2,12 +2,14 @@ package com.lzxnone.openloc.hook
import android.app.Application import android.app.Application
import android.content.Context import android.content.Context
import com.lzxnone.openloc.hook.client.ThirdPartyNlpHook
import com.lzxnone.openloc.hook.interceptor.AntiDetectionHook import com.lzxnone.openloc.hook.interceptor.AntiDetectionHook
import com.lzxnone.openloc.hook.interceptor.BleHook
import com.lzxnone.openloc.hook.interceptor.GnssHook import com.lzxnone.openloc.hook.interceptor.GnssHook
import com.lzxnone.openloc.hook.interceptor.LocationHook import com.lzxnone.openloc.hook.interceptor.LocationHook
import com.lzxnone.openloc.hook.interceptor.NetworkLocationHook import com.lzxnone.openloc.hook.interceptor.NetworkLocationHook
import com.lzxnone.openloc.hook.interceptor.SensorHook
import com.lzxnone.openloc.hook.system.SystemServerHook import com.lzxnone.openloc.hook.system.SystemServerHook
import com.lzxnone.openloc.hook.system.TelephonyRegistryHook
import de.robv.android.xposed.IXposedHookLoadPackage import de.robv.android.xposed.IXposedHookLoadPackage
import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XC_MethodReplacement import de.robv.android.xposed.XC_MethodReplacement
@@ -16,7 +18,7 @@ import de.robv.android.xposed.XposedHelpers
import de.robv.android.xposed.callbacks.XC_LoadPackage import de.robv.android.xposed.callbacks.XC_LoadPackage
/** /**
* Xposed / LSPosed 统一 Hook 分发主入口 * Xposed / LSPosed 统一路由入口(全新四维工业级架构)
*/ */
class HookEntry : IXposedHookLoadPackage { class HookEntry : IXposedHookLoadPackage {
@@ -24,31 +26,41 @@ class HookEntry : IXposedHookLoadPackage {
private var appContext: Context? = null private var appContext: Context? = null
override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam) { override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam) {
// 1. 系统级全局拦截:如果是 Android 系统框架 (system_server) val pkg = lpparam.packageName
// 只要在 LSPosed 中勾选了【Android 系统 (android)】,整机所有应用全部享受全局定位拦截!
if (lpparam.packageName == "android") { // 1. 系统底层服务 (system_server / UID 1000)
if (pkg == "android" || android.os.Process.myUid() == 1000) {
SystemServerHook.hook(lpparam.classLoader) SystemServerHook.hook(lpparam.classLoader)
return return
} }
// 过滤系统 UI 及框架管理工具进程(避免侵入管理环境) // 2. 电话系统与基站塔管理守护进程
if (isManagementPackage(lpparam.packageName)) { if (pkg == "com.android.phone") {
TelephonyRegistryHook.hook(lpparam.classLoader)
return return
} }
// 2. 如果加载的是本应用自身,Hook 激活判定桩使其恒返回 true // 4. 蓝牙服务守护进程(拦截底层 BLE 室内信标微定位,GhostMapX 架构)
if (lpparam.packageName == MODULE_PACKAGE_NAME) { if (pkg == "com.android.bluetooth") {
BleHook.hookBluetoothProcess(lpparam.classLoader)
return
}
// 过滤系统 UI 及管理工具环境
if (isManagementPackage(pkg)) {
return
}
// 4. 模块自身激活判定
if (pkg == MODULE_PACKAGE_NAME) {
hookSelfActiveStatus(lpparam.classLoader) hookSelfActiveStatus(lpparam.classLoader)
return return
} }
// 3. 注入目标应用进程(客户端双重兜底):挂载 Context 并启动深度拦截链路(WiFi/基站/NMEA) // 5. 目标应用进程(QQ、微信、百度地图、打卡软件等)全链路拦截
initTargetHooks(lpparam) initTargetHooks(lpparam)
} }
/**
* Hook 本身应用的 HookStatus.isModuleActive(),令其返回 true
*/
private fun hookSelfActiveStatus(classLoader: ClassLoader) { private fun hookSelfActiveStatus(classLoader: ClassLoader) {
try { try {
XposedHelpers.findAndHookMethod( XposedHelpers.findAndHookMethod(
@@ -67,14 +79,10 @@ class HookEntry : IXposedHookLoadPackage {
} }
} }
/**
* 目标应用进程初始化与全链路 Hook 挂载
*/
private fun initTargetHooks(lpparam: XC_LoadPackage.LoadPackageParam) { private fun initTargetHooks(lpparam: XC_LoadPackage.LoadPackageParam) {
try { try {
val contextProvider = { appContext } val contextProvider = { appContext }
// 监听 Application 启动以安全捕获应用级 Context
XposedHelpers.findAndHookMethod( XposedHelpers.findAndHookMethod(
Application::class.java, Application::class.java,
"attach", "attach",
@@ -88,14 +96,16 @@ class HookEntry : IXposedHookLoadPackage {
} }
) )
// 挂载定位与防检测核心拦截线 // 全新多层防穿透管道(显式传递绝对已知的应用包名,第 0 毫秒即就绪)
LocationHook.hook(lpparam.classLoader, contextProvider) val pkg = lpparam.packageName
NetworkLocationHook.hook(lpparam.classLoader, contextProvider) LocationHook.hook(lpparam.classLoader, pkg, contextProvider)
GnssHook.hook(lpparam.classLoader, contextProvider) ThirdPartyNlpHook.hook(lpparam.classLoader, pkg, contextProvider)
SensorHook.hook(lpparam.classLoader, contextProvider) NetworkLocationHook.hook(lpparam.classLoader, pkg, contextProvider)
GnssHook.hook(lpparam.classLoader, pkg, contextProvider)
BleHook.hookClient(lpparam.classLoader, pkg)
AntiDetectionHook.hook(lpparam.classLoader, contextProvider) AntiDetectionHook.hook(lpparam.classLoader, contextProvider)
XposedBridge.log("[OpenLoc] Injected target hooks for: ${lpparam.packageName}") XposedBridge.log("[OpenLoc] Fully armed target hooks for: ${lpparam.packageName}")
} catch (t: Throwable) { } catch (t: Throwable) {
XposedBridge.log("[OpenLoc] Error initializing target hooks for ${lpparam.packageName}: ${t.message}") XposedBridge.log("[OpenLoc] Error initializing target hooks for ${lpparam.packageName}: ${t.message}")
} }
@@ -0,0 +1,125 @@
package com.lzxnone.openloc.hook.client
import android.content.Context
import android.location.Location
import android.location.LocationManager
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
import com.lzxnone.openloc.hook.model.GlobalMockMemory
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers
/**
* 客户端系统私有 Transport 内部类与 Fused 融合引流拦截器
* (基于 GhostMapX 核心架构设计)
*/
object ClientTransportHook {
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
hookSystemTransports(classLoader, packageName, contextProvider)
hookFusedProviderRedirect(classLoader, packageName, contextProvider)
}
/**
* 1. 深度拦截客户端必经的系统 Transport 内部类
*/
private fun hookSystemTransports(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
val transportClassNames = listOf(
"android.location.LocationManager\$LocationListenerTransport",
"android.location.LocationManager\$GetCurrentLocationTransport",
"android.location.LocationManager\$BatchedLocationCallbackWrapper"
)
for (className in transportClassNames) {
val clazz = try {
XposedHelpers.findClass(className, classLoader)
} catch (_: Throwable) {
null
} ?: continue
for (method in clazz.declaredMethods) {
if (method.name == "onLocationChanged" || method.name == "onLocation") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!getEffectiveParams(packageName, contextProvider)) return
for (arg in param.args) {
modifyLocationArgument(arg)
}
}
})
} catch (_: Throwable) {}
}
}
}
}
/**
* 2. 强行阻断并重定向 Fused (融合定位) 提供商
*/
private fun hookFusedProviderRedirect(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
try {
val lmClass = LocationManager::class.java
for (method in lmClass.declaredMethods) {
if (method.name == "requestLocationUpdates" || method.name == "requestSingleUpdate") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!getEffectiveParams(packageName, contextProvider)) return
// 如果入参 provider 是 fused,强行引流至 gps
val providerIndex = param.args.indexOfFirst { it is String && it.equals("fused", ignoreCase = true) }
if (providerIndex != -1) {
param.args[providerIndex] = LocationManager.GPS_PROVIDER
}
}
})
} catch (_: Throwable) {}
}
}
} catch (_: Throwable) {}
}
private fun getEffectiveParams(packageName: String, contextProvider: () -> Context?): Boolean {
if (packageName == "com.lzxnone.openloc") return false
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
return true
}
val ctx = contextProvider()
if (ctx != null) {
val config = ConfigFetcher.getConfig(ctx)
return config.shouldMock(packageName.ifBlank { ctx.packageName })
}
return false
}
private fun modifyLocationArgument(arg: Any?) {
if (arg == null) return
if (arg is Location) {
GlobalMockMemory.applyToLocation(arg)
} else if (arg is List<*>) {
for (item in arg) {
if (item is Location) {
GlobalMockMemory.applyToLocation(item)
}
}
} else if (arg.javaClass.name.contains("LocationResult")) {
try {
val list = (XposedHelpers.callMethod(arg, "asList") as? List<*>)
?: (XposedHelpers.getObjectField(arg, "mLocations") as? List<*>)
if (list != null) {
for (loc in list) {
if (loc is Location) {
GlobalMockMemory.applyToLocation(loc)
}
}
}
val lastLoc = XposedHelpers.callMethod(arg, "getLastLocation") as? Location
if (lastLoc != null) {
GlobalMockMemory.applyToLocation(lastLoc)
}
} catch (_: Throwable) {}
}
}
}
@@ -0,0 +1,101 @@
package com.lzxnone.openloc.hook.client
import android.content.Context
import android.location.Location
import com.lzxnone.openloc.hook.model.GlobalMockMemory
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers
/**
* 国内三大巨头自研底层 NLP(网络定位提供商)安全拦截器
* (严格遵循 GhostMapX LJo 规范:绝不粗暴阻断状态机方法,避免引发“位置获取失败”)
*/
object ThirdPartyNlpHook {
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
if (packageName == "com.lzxnone.openloc") return
hookTencentNLP(classLoader, packageName)
hookBaiduNLP(classLoader, packageName)
hookAmapNLP(classLoader, packageName)
}
/**
* 1. 腾讯定位 SDK:仅拦截返回 Location 的方法,绝不破坏 init / isAvailable 等状态机
*/
private fun hookTencentNLP(classLoader: ClassLoader, packageName: String) {
val nlpClass = try {
XposedHelpers.findClass("com.tencent.geolocation.nlp.TencentNLPManager", classLoader)
} catch (_: Throwable) {
null
} ?: return
for (method in nlpClass.declaredMethods) {
if (method.returnType == Location::class.java) {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
val loc = param.result as? Location ?: GlobalMockMemory.createLocation("network")
GlobalMockMemory.applyToLocation(loc)
param.result = loc
}
})
} catch (_: Throwable) {}
}
}
}
/**
* 2. 百度定位核心:绝不拦截 requestLocation 与 requestNLPNormal,防止破坏状态机引发“位置获取失败”
*/
private fun hookBaiduNLP(classLoader: ClassLoader, packageName: String) {
val clientClass = try {
XposedHelpers.findClass("com.baidu.location.LocationClient", classLoader)
} catch (_: Throwable) {
null
} ?: return
for (method in clientClass.declaredMethods) {
if (method.returnType == Location::class.java) {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
val loc = param.result as? Location ?: GlobalMockMemory.createLocation("gps")
GlobalMockMemory.applyToLocation(loc)
param.result = loc
}
})
} catch (_: Throwable) {}
}
}
}
/**
* 3. 高德底层网络定位:拦截位置返回,确保不穿透
*/
private fun hookAmapNLP(classLoader: ClassLoader, packageName: String) {
val nlpClass = try {
XposedHelpers.findClass("com.amap.android.location.NetworkLocationManager", classLoader)
} catch (_: Throwable) {
null
} ?: return
for (method in nlpClass.declaredMethods) {
if (method.returnType == Location::class.java) {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
val loc = param.result as? Location ?: GlobalMockMemory.createLocation("network")
GlobalMockMemory.applyToLocation(loc)
param.result = loc
}
})
} catch (_: Throwable) {}
}
}
}
}
@@ -36,6 +36,95 @@ object AntiDetectionHook {
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) { fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) {
hookPackageManager(classLoader, contextProvider) hookPackageManager(classLoader, contextProvider)
hookLocationEntityFlags(classLoader)
hookSettingsSecure(classLoader)
hookGeocoder(classLoader)
}
/**
* 1. 消除 Location 实体类中的 Mock 标记(isFromMockProvider / isMock)
*/
private fun hookLocationEntityFlags(classLoader: ClassLoader) {
val locationClass = try {
XposedHelpers.findClass("android.location.Location", classLoader)
} catch (_: Throwable) {
null
} ?: return
for (method in locationClass.declaredMethods) {
if (method.name == "isFromMockProvider" || method.name == "isMock") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
param.result = false
}
})
} catch (_: Throwable) {}
}
}
}
/**
* 2. 拦截 Settings.Secure.mock_location 读取
*/
private fun hookSettingsSecure(classLoader: ClassLoader) {
val secureClass = try {
XposedHelpers.findClass("android.provider.Settings\$Secure", classLoader)
} catch (_: Throwable) {
null
} ?: return
for (method in secureClass.declaredMethods) {
if (method.name == "getString" || method.name == "getStringForUser") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val name = param.args.firstOrNull { it is String } as? String
if (name == "mock_location") {
param.result = "0"
}
}
})
} catch (_: Throwable) {}
} else if (method.name == "getInt" || method.name == "getIntForUser") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val name = param.args.firstOrNull { it is String } as? String
if (name == "mock_location") {
param.result = 0
}
}
})
} catch (_: Throwable) {}
}
}
}
/**
* 3. 拦截 Geocoder 经纬度反查街道真实地址(反向地理编码)
*/
private fun hookGeocoder(classLoader: ClassLoader) {
val geocoderClass = try {
XposedHelpers.findClass("android.location.Geocoder", classLoader)
} catch (_: Throwable) {
null
} ?: return
for (method in geocoderClass.declaredMethods) {
if (method.name == "getFromLocation" || method.name == "getFromLocationName") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
// 若需深度伪装,返回空列表防透传
if (param.result == null || (param.result as? List<*>)?.isEmpty() == true) {
param.result = emptyList<Any>()
}
}
})
} catch (_: Throwable) {}
}
}
} }
/** /**
@@ -65,7 +154,7 @@ object AntiDetectionHook {
val ctx = contextProvider() ?: return val ctx = contextProvider() ?: return
if (isCallerExcluded(ctx.packageName)) return if (isCallerExcluded(ctx.packageName)) return
val config = ConfigFetcher.getConfig(ctx) val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isStealthEnabled) { if (config.shouldMock(ctx.packageName)) {
param.throwable = PackageManager.NameNotFoundException(pkgName) param.throwable = PackageManager.NameNotFoundException(pkgName)
} }
} }
@@ -82,7 +171,7 @@ object AntiDetectionHook {
val ctx = contextProvider() ?: return val ctx = contextProvider() ?: return
if (isCallerExcluded(ctx.packageName)) return if (isCallerExcluded(ctx.packageName)) return
val config = ConfigFetcher.getConfig(ctx) val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isStealthEnabled) { if (config.shouldMock(ctx.packageName)) {
param.throwable = PackageManager.NameNotFoundException(pkgName) param.throwable = PackageManager.NameNotFoundException(pkgName)
} }
} }
@@ -97,7 +186,7 @@ object AntiDetectionHook {
val ctx = contextProvider() ?: return val ctx = contextProvider() ?: return
if (isCallerExcluded(ctx.packageName)) return if (isCallerExcluded(ctx.packageName)) return
val config = ConfigFetcher.getConfig(ctx) val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return if (!config.shouldMock(ctx.packageName)) return
val list = param.result as? List<*> ?: return val list = param.result as? List<*> ?: return
val filtered = list.filter { val filtered = list.filter {
@@ -115,7 +204,7 @@ object AntiDetectionHook {
val ctx = contextProvider() ?: return val ctx = contextProvider() ?: return
if (isCallerExcluded(ctx.packageName)) return if (isCallerExcluded(ctx.packageName)) return
val config = ConfigFetcher.getConfig(ctx) val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return if (!config.shouldMock(ctx.packageName)) return
val list = param.result as? List<*> ?: return val list = param.result as? List<*> ?: return
val filtered = list.filter { val filtered = list.filter {
@@ -0,0 +1,106 @@
package com.lzxnone.openloc.hook.interceptor
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import com.lzxnone.openloc.hook.model.GlobalMockMemory
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers
/**
* 蓝牙低功耗 (BLE) 扫描与室内 iBeacon 信标断粮拦截器
* (基于 GhostMapX 核心架构设计)
*
* 核心目标:
* 阻断室内商场、大厦、地铁站通过 BLE iBeacon 信标扫描反查出物理室内位置,
* 彻底封死大厂 App(QQ、微信、打卡软件等)的微定位旁路。
*/
object BleHook {
/**
* 1. 在 com.android.bluetooth 进程中拦截底层 GattService 与 Native 接口
*/
fun hookBluetoothProcess(classLoader: ClassLoader) {
XposedBridge.log("[OpenLoc] [BleHook] Initializing BleHook for com.android.bluetooth...")
// A. GattService 拦截
val gattServiceClass = try {
XposedHelpers.findClass("com.android.bluetooth.gatt.GattService", classLoader)
} catch (_: Throwable) {
null
}
if (gattServiceClass != null) {
for (method in gattServiceClass.declaredMethods) {
if (method.name == "onScanResult" || method.name == "onBatchScanResults" || method.name == "onFoundOrLost") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (GlobalMockMemory.isEnabled) {
// 拦截蓝牙信标广播结果
param.result = null
}
}
})
} catch (_: Throwable) {}
}
}
}
// B. GattNativeInterface 拦截
val nativeInterfaceClass = try {
XposedHelpers.findClass("com.android.bluetooth.gatt.GattNativeInterface", classLoader)
} catch (_: Throwable) {
null
}
if (nativeInterfaceClass != null) {
for (method in nativeInterfaceClass.declaredMethods) {
if (method.name.contains("onScan")) {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (GlobalMockMemory.isEnabled) {
param.result = null
}
}
})
} catch (_: Throwable) {}
}
}
}
}
/**
* 2. 在目标客户端 App 进程中拦截 BluetoothLeScanner.startScan
*/
fun hookClient(classLoader: ClassLoader, packageName: String) {
val scannerClass = try {
XposedHelpers.findClass("android.bluetooth.le.BluetoothLeScanner", classLoader)
} catch (_: Throwable) {
null
} ?: return
for (method in scannerClass.declaredMethods) {
if (method.name == "startScan") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
// 寻找 ScanCallback 参数并阻断或返回空结果
val callback = param.args.firstOrNull { it is ScanCallback } as? ScanCallback
if (callback != null) {
try {
// 给调用者触发一次空的批量扫描结果,避免某些应用抛出未收到扫描回调异常
callback.onBatchScanResults(emptyList())
param.result = null
} catch (_: Throwable) {}
}
}
})
} catch (_: Throwable) {}
}
}
}
}
@@ -7,308 +7,64 @@ import android.location.GnssStatus
import android.location.GpsStatus import android.location.GpsStatus
import android.location.LocationManager import android.location.LocationManager
import android.location.OnNmeaMessageListener import android.location.OnNmeaMessageListener
import android.os.Handler import com.lzxnone.openloc.hook.model.GlobalMockMemory
import android.os.Looper
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
import com.lzxnone.openloc.hook.util.LocationSimulator
import com.lzxnone.openloc.hook.util.VirtualGnssEngine
import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers import de.robv.android.xposed.XposedHelpers
import java.util.Collections
import java.util.WeakHashMap
/** /**
* 全真多星座 GNSS 卫星与 NMEA 报文拦截器 * 轻量稳健的 GNSS 卫星与 NMEA 拦截器(GhostMapX 设计)
* * 不再运行消耗 CPU 的 26 卫星物理引擎与大定时器,
* 1. 深度拦截 GnssStatus.Callback,构造注入 26 颗多星座卫星(GPS、北斗、GLONASS、Galileo) * 专注于阻断真实卫星泄露并抹除冷启动定星超时。
* 2. 维持 1Hz 卫星心跳分发,室内/无真实信号下仍持续稳定分发有效卫星解
* 3. 拦截 NMEA 监听器,全量伪造 $GNGGA、$GNRMC、$GNGSA、$BDGSA、$GPGSV、$BDGSV、$GLGSV
* 4. 兼容旧版 GpsStatus.Listener 探测
*/ */
object GnssHook { object GnssHook {
private val isDeliveringNmea = ThreadLocal.withInitial { false } fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
private val activeGnssCallbacks = Collections.newSetFromMap(WeakHashMap<GnssStatus.Callback, Boolean>()) if (packageName == "com.lzxnone.openloc") return
private val activeGpsListeners = Collections.newSetFromMap(WeakHashMap<GpsStatus.Listener, Boolean>())
@Volatile hookNmeaListener(packageName)
private var isTickerStarted = false hookGpsStatusLegacy(packageName)
private var mainHandler: Handler? = null
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) {
hookNmeaListener(contextProvider)
hookGnssStatusCallbacks(classLoader, contextProvider)
hookGpsStatusLegacy(contextProvider)
} }
/** /**
* 1. 拦截并分发全真 NMEA-0183 多星座报文阵列 * 阻断/规整 NMEA 原始报文,防止经纬度及原始卫星数据穿透
*/ */
private fun hookNmeaListener(contextProvider: () -> Context?) { private fun hookNmeaListener(packageName: String) {
try { try {
val methods = LocationManager::class.java.declaredMethods val methods = LocationManager::class.java.declaredMethods
for (method in methods) { for (method in methods) {
if (method.name == "addNmeaListener") { if (method.name == "addNmeaListener") {
val paramTypes = method.parameterTypes
val listenerIndex = paramTypes.indexOfFirst {
OnNmeaMessageListener::class.java.isAssignableFrom(it)
}
if (listenerIndex != -1) {
try { try {
XposedBridge.hookMethod(method, object : XC_MethodHook() { XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val originalListener = param.args[listenerIndex] as? OnNmeaMessageListener ?: return if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
hookNmeaCallback(originalListener, contextProvider) // 开启模拟定位时,不向应用分发真实硬件原始 NMEA 报文
param.result = true
}
} }
}) })
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
} }
}
} catch (t: Throwable) {
XposedBridge.log("[OpenLoc] hookNmeaListener error: ${t.message}")
}
}
private val hookedNmeaClasses = mutableSetOf<String>()
private fun hookNmeaCallback(listener: OnNmeaMessageListener, contextProvider: () -> Context?) {
val clazz = listener.javaClass
val className = clazz.name
if (hookedNmeaClasses.contains(className)) return
hookedNmeaClasses.add(className)
try {
XposedHelpers.findAndHookMethod(
clazz,
"onNmeaMessage",
String::class.java,
Long::class.javaPrimitiveType,
object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (isDeliveringNmea.get() == true) return
val ctx = contextProvider() ?: return
val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return
val rawMessage = param.args[0] as? String ?: return
val timestamp = param.args[1] as? Long ?: System.currentTimeMillis()
// 当系统开始触发 NMEA 时,动态替换并批量补齐多星座全套报文
if (rawMessage.startsWith("\$GP") || rawMessage.startsWith("\$GN") || rawMessage.startsWith("\$BD")) {
val (curLat, curLng) = LocationSimulator.getSimulatedCoordinates(
config.latitude,
config.longitude,
config.isJitterEnabled
)
val fullNmeaList = VirtualGnssEngine.generateFullNmeaSequence(curLat, curLng, timestamp)
if (fullNmeaList.isNotEmpty()) {
// 替换当前句为第一句($GNGGA)
param.args[0] = fullNmeaList[0]
// 补发剩余语句 ($GNRMC, $GNGSA, $BDGSA, $GPGSV...)
try {
isDeliveringNmea.set(true)
val targetListener = param.thisObject as? OnNmeaMessageListener
if (targetListener != null) {
for (i in 1 until fullNmeaList.size) {
targetListener.onNmeaMessage(fullNmeaList[i], timestamp)
}
}
} finally {
isDeliveringNmea.set(false)
}
}
}
}
}
)
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
/** /**
* 2. 深度拦截 GnssStatus 回调并维持 1Hz 卫星心跳 * 兼容老版本 SDK 的 GpsStatus.Listener,恒定返回已极速定星状态
*/ */
private fun hookGnssStatusCallbacks(classLoader: ClassLoader, contextProvider: () -> Context?) { private fun hookGpsStatusLegacy(packageName: String) {
try { try {
// (1) 拦截 LocationManager.registerGnssStatusCallback 各重载
val methods = LocationManager::class.java.declaredMethods
for (method in methods) {
if (method.name == "registerGnssStatusCallback") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val callback = param.args.firstOrNull { it is GnssStatus.Callback } as? GnssStatus.Callback ?: return
synchronized(activeGnssCallbacks) {
activeGnssCallbacks.add(callback)
}
ensureTickerStarted(contextProvider)
hookSingleGnssCallbackClass(callback.javaClass, contextProvider)
}
})
} catch (_: Throwable) {}
} else if (method.name == "unregisterGnssStatusCallback") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val callback = param.args.firstOrNull { it is GnssStatus.Callback } as? GnssStatus.Callback ?: return
synchronized(activeGnssCallbacks) {
activeGnssCallbacks.remove(callback)
}
}
})
} catch (_: Throwable) {}
}
}
} catch (t: Throwable) {
XposedBridge.log("[OpenLoc] hookGnssStatusCallbacks error: ${t.message}")
}
}
private val hookedGnssCallbackClasses = mutableSetOf<String>()
private fun hookSingleGnssCallbackClass(clazz: Class<*>, contextProvider: () -> Context?) {
val className = clazz.name
if (hookedGnssCallbackClasses.contains(className)) return
hookedGnssCallbackClasses.add(className)
try {
// Hook onSatelliteStatusChanged(GnssStatus)
XposedHelpers.findAndHookMethod(
clazz,
"onSatelliteStatusChanged",
GnssStatus::class.java,
object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return
val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return
val fakeStatus = VirtualGnssEngine.createGnssStatus()
if (fakeStatus != null) {
param.args[0] = fakeStatus
}
}
}
)
} catch (_: Throwable) {}
}
/**
* 3. 启动 1Hz 定时卫星仿真分发调度(针对无真实卫星信号、室内等环境兜底)
*/
private fun ensureTickerStarted(contextProvider: () -> Context?) {
if (isTickerStarted) return
synchronized(this) {
if (isTickerStarted) return
isTickerStarted = true
if (mainHandler == null) {
try {
mainHandler = Handler(Looper.getMainLooper())
} catch (_: Throwable) {}
}
mainHandler?.post(object : Runnable {
override fun run() {
try {
dispatchSimulatedGnssTick(contextProvider)
} catch (_: Throwable) {}
mainHandler?.postDelayed(this, 1000L) // 1 秒刷新一次
}
})
}
}
private val notifiedFirstFixSet = Collections.newSetFromMap(WeakHashMap<GnssStatus.Callback, Boolean>())
private fun dispatchSimulatedGnssTick(contextProvider: () -> Context?) {
val ctx = contextProvider() ?: return
val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return
val fakeStatus = VirtualGnssEngine.createGnssStatus() ?: return
val callbacksSnapshot = synchronized(activeGnssCallbacks) {
activeGnssCallbacks.toList()
}
for (cb in callbacksSnapshot) {
try {
if (!notifiedFirstFixSet.contains(cb)) {
notifiedFirstFixSet.add(cb)
cb.onStarted()
cb.onFirstFix(1200) // 1.2s 极速逼真定位时间
}
cb.onSatelliteStatusChanged(fakeStatus)
} catch (_: Throwable) {}
}
// 兼容旧版 GpsStatus
val listenersSnapshot = synchronized(activeGpsListeners) {
activeGpsListeners.toList()
}
for (listener in listenersSnapshot) {
try {
listener.onGpsStatusChanged(GpsStatus.GPS_EVENT_SATELLITE_STATUS)
} catch (_: Throwable) {}
}
}
/**
* 4. 兼容老版本 SDK 的 GpsStatus.Listener
*/
private fun hookGpsStatusLegacy(contextProvider: () -> Context?) {
try {
// Hook addGpsStatusListener
XposedHelpers.findAndHookMethod(
LocationManager::class.java,
"addGpsStatusListener",
GpsStatus.Listener::class.java,
object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val listener = param.args[0] as? GpsStatus.Listener ?: return
synchronized(activeGpsListeners) {
activeGpsListeners.add(listener)
}
ensureTickerStarted(contextProvider)
}
}
)
// Hook removeGpsStatusListener
XposedHelpers.findAndHookMethod(
LocationManager::class.java,
"removeGpsStatusListener",
GpsStatus.Listener::class.java,
object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val listener = param.args[0] as? GpsStatus.Listener ?: return
synchronized(activeGpsListeners) {
activeGpsListeners.remove(listener)
}
}
}
)
// Hook getGpsStatus(GpsStatus status)
XposedHelpers.findAndHookMethod( XposedHelpers.findAndHookMethod(
LocationManager::class.java, LocationManager::class.java,
"getGpsStatus", "getGpsStatus",
GpsStatus::class.java, GpsStatus::class.java,
object : XC_MethodHook() { object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) { override fun afterHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return
val status = (param.result as? GpsStatus) ?: (param.args[0] as? GpsStatus) ?: return val status = (param.result as? GpsStatus) ?: (param.args.getOrNull(0) as? GpsStatus) ?: return
try { try {
XposedHelpers.setIntField(status, "mTimeToFirstFix", 1200) XposedHelpers.setIntField(status, "mTimeToFirstFix", 1000)
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
} }
@@ -5,222 +5,181 @@ import android.location.Location
import android.location.LocationListener import android.location.LocationListener
import android.location.LocationManager import android.location.LocationManager
import android.os.Build import android.os.Build
import com.lzxnone.openloc.hook.ipc.ConfigFetcher import android.os.Handler
import com.lzxnone.openloc.hook.util.LocationSimulator import android.os.Looper
import android.os.SystemClock
import com.lzxnone.openloc.hook.model.GlobalMockMemory
import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XC_MethodReplacement
import de.robv.android.xposed.XposedBridge import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers import de.robv.android.xposed.XposedHelpers
import java.lang.reflect.Proxy import java.util.Collections
import java.util.WeakHashMap
/** /**
* 原生定位服务 LocationManager 与 Location 实体拦截器 * 客户端 LocationManager 拦截器(严格对齐 GhostMapX LYe/LXe 实现)
*
* 核心机制:
* 1. 绝不盲目 Hook Location.getLatitude/getLongitude(避免破坏地图SDK投影测距与自身重置);
* 2. 绝不 Hook Location.writeToParcel;
* 3. 在客户端 LocationManager 的关键出口拦截:
* - getLastKnownLocation / getLastLocation: afterHookedMethod 篡改或注入新 Location;
* - getCurrentLocation (Android 11+): 拦截 Consumer 并立即交付虚拟坐标;
* - requestLocationUpdates / requestSingleUpdate: 挂钩 Listener 并秒推首帧;
* - 核心传输通道(GetCurrentLocationTransport / BatchedLocationCallbackWrapper / LocationListenerTransport):
* 在其 onLocation / onLocationChanged 回调发生时就地修改 Location 实体。
*/ */
object LocationHook { object LocationHook {
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) { private val mainHandler = Handler(Looper.getMainLooper())
hookLocationEntity() private val hookedListenerClasses = Collections.synchronizedSet(mutableSetOf<String>())
hookLocationManager(classLoader, contextProvider)
fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
// 关键安全防线:针对 OpenLoc 自身绝对放行,确保可无阻获取硬件真实 GPS 回到真实定位点
if (packageName == "com.lzxnone.openloc") return
hookClientLocationManager(classLoader, packageName)
hookLocationTransports(classLoader, packageName)
} }
/** private fun hookClientLocationManager(classLoader: ClassLoader, packageName: String) {
* 1. 拦截 Location 实体类中的 Mock 判定方法 val lmClass = LocationManager::class.java
*/
private fun hookLocationEntity() {
try {
// Hook isFromMockProvider 恒返回 false
XposedHelpers.findAndHookMethod(
Location::class.java,
"isFromMockProvider",
object : XC_MethodReplacement() {
override fun replaceHookedMethod(param: MethodHookParam?): Any {
return false
}
}
)
// Android 12 (API 31)+ isMock() 恒返回 false // 1. getLastKnownLocation 与 getLastLocation 拦截(GhostMapX 经典实现)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val getLastMethods = listOf("getLastKnownLocation", "getLastLocation")
for (methodName in getLastMethods) {
try { try {
XposedHelpers.findAndHookMethod( XposedBridge.hookAllMethods(lmClass, methodName, object : XC_MethodHook() {
Location::class.java,
"isMock",
object : XC_MethodReplacement() {
override fun replaceHookedMethod(param: MethodHookParam?): Any {
return false
}
}
)
} catch (_: Throwable) {}
}
} catch (t: Throwable) {
XposedBridge.log("[OpenLoc] hookLocationEntity failed: ${t.message}")
}
}
/**
* 2. 拦截 LocationManager 的核心定位获取方法
*/
private fun hookLocationManager(classLoader: ClassLoader, contextProvider: () -> Context?) {
try {
// (1) 拦截 getLastKnownLocation
XposedHelpers.findAndHookMethod(
LocationManager::class.java,
"getLastKnownLocation",
String::class.java,
object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) { override fun afterHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName)) return
val provider = param.args[0] as? String ?: LocationManager.GPS_PROVIDER val provider = param.args.firstOrNull { it is String } as? String ?: "gps"
param.result = LocationSimulator.createMockLocation( param.result = GlobalMockMemory.createLocation(provider)
latitude = config.latitude,
longitude = config.longitude,
provider = provider,
isJitterEnabled = config.isJitterEnabled
)
}
}
)
// (2) 拦截 requestLocationUpdates 各重载中传入的 LocationListener
val methods = LocationManager::class.java.declaredMethods
for (method in methods) {
if (method.name == "requestLocationUpdates") {
val paramTypes = method.parameterTypes
val listenerIndex = paramTypes.indexOfFirst {
LocationListener::class.java.isAssignableFrom(it)
}
if (listenerIndex != -1) {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val originalListener = param.args[listenerIndex] as? LocationListener ?: return
// 拦截回调类并 Hook 其 onLocationChanged
hookListenerClass(originalListener.javaClass, contextProvider)
} }
}) })
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
}
}
// (3) Android 12+ 拦截 getCurrentLocation 异步单次定位
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
hookGetCurrentLocation(contextProvider)
}
} catch (t: Throwable) {
XposedBridge.log("[OpenLoc] hookLocationManager failed: ${t.message}")
}
}
/**
* Hook 具体应用实现的 LocationListener.onLocationChanged
*/
private val hookedListenerClasses = mutableSetOf<String>()
private fun hookListenerClass(clazz: Class<*>, contextProvider: () -> Context?) {
val className = clazz.name
if (hookedListenerClasses.contains(className)) return
hookedListenerClasses.add(className)
// 2. isProviderEnabled 恒返回 true
try { try {
// Hook onLocationChanged(Location) XposedBridge.hookAllMethods(lmClass, "isProviderEnabled", object : XC_MethodHook() {
XposedHelpers.findAndHookMethod(
clazz,
"onLocationChanged",
Location::class.java,
object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
val config = ConfigFetcher.getConfig(ctx) val provider = param.args.firstOrNull { it is String } as? String
if (!config.shouldMock(ctx.packageName)) return if (provider == LocationManager.GPS_PROVIDER ||
provider == LocationManager.NETWORK_PROVIDER ||
val location = param.args[0] as? Location provider == "fused") {
if (location != null) { param.result = true
LocationSimulator.applyMockData(location, config.latitude, config.longitude, config.isJitterEnabled)
} else {
param.args[0] = LocationSimulator.createMockLocation(
config.latitude,
config.longitude,
isJitterEnabled = config.isJitterEnabled
)
} }
} }
} }
) })
} catch (_: Throwable) {} } catch (_: Throwable) {}
// Android 14 (API 34)+ 新增 onLocationChanged(List<Location>) // 3. requestLocationUpdates 与 requestSingleUpdate 拦截
val requestMethods = listOf("requestLocationUpdates", "requestSingleUpdate")
for (methodName in requestMethods) {
try { try {
XposedHelpers.findAndHookMethod( XposedBridge.hookAllMethods(lmClass, methodName, object : XC_MethodHook() {
clazz,
"onLocationChanged",
List::class.java,
object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName)) return
@Suppress("UNCHECKED_CAST") // 查找 LocationListener 参数并挂钩其 onLocationChanged
val list = param.args[0] as? List<Location> ?: return for (arg in param.args) {
for (loc in list) { if (arg is LocationListener) {
LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled) hookLocationListenerClass(arg.javaClass, packageName)
} }
} }
} }
)
override fun afterHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
// 注册瞬间秒推首帧,消除冷启动无星等待
val listener = param.args.firstOrNull { it is LocationListener } as? LocationListener ?: return
val provider = param.args.firstOrNull { it is String } as? String ?: "gps"
val mockLoc = GlobalMockMemory.createLocation(provider)
mainHandler.post {
try {
listener.onLocationChanged(mockLoc)
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
/**
* Android 11+ / 12+ 单次定位 getCurrentLocation 拦截
*/
private fun hookGetCurrentLocation(contextProvider: () -> Context?) {
val methods = LocationManager::class.java.declaredMethods
for (method in methods) {
if (method.name == "getCurrentLocation") {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return
val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName)) return
// Consumer<Location> 通常位于最后一位
val lastIndex = param.args.size - 1
if (lastIndex >= 0) {
val originalConsumer = param.args[lastIndex] ?: return
val consumerInterface = originalConsumer.javaClass.interfaces.firstOrNull {
it.name == "java.util.function.Consumer"
} ?: return
val proxy = Proxy.newProxyInstance(
consumerInterface.classLoader,
arrayOf(consumerInterface)
) { _, m, args ->
if (m.name == "accept" && args != null && args.isNotEmpty()) {
val mockLoc = LocationSimulator.createMockLocation(
config.latitude,
config.longitude,
isJitterEnabled = config.isJitterEnabled
)
m.invoke(originalConsumer, mockLoc)
} else {
m.invoke(originalConsumer, *(args ?: emptyArray()))
}
}
param.args[lastIndex] = proxy
}
} }
}) })
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
} }
/**
* 拦截系统 Binder 回调的传输层 Transport(GhostMapX 关键手段)
*/
private fun hookLocationTransports(classLoader: ClassLoader, packageName: String) {
val transportClasses = listOf(
"android.location.LocationManager\$GetCurrentLocationTransport",
"android.location.LocationManager\$BatchedLocationCallbackWrapper",
"android.location.LocationManager\$LocationListenerTransport"
)
for (className in transportClasses) {
try {
val clazz = XposedHelpers.findClassIfExists(className, classLoader) ?: continue
// Hook onLocation
try {
XposedBridge.hookAllMethods(clazz, "onLocation", object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
val loc = param.args.getOrNull(0) as? Location ?: return
param.args[0] = GlobalMockMemory.createLocation(loc.provider ?: "gps")
}
})
} catch (_: Throwable) {}
// Hook onLocationChanged
try {
XposedBridge.hookAllMethods(clazz, "onLocationChanged", object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
val arg = param.args.getOrNull(0) ?: return
if (arg is Location) {
param.args[0] = GlobalMockMemory.createLocation(arg.provider ?: "gps")
} else if (arg is List<*>) {
val mockList = ArrayList<Location>(arg.size)
for (item in arg) {
val provider = (item as? Location)?.provider ?: "gps"
mockList.add(GlobalMockMemory.createLocation(provider))
}
param.args[0] = mockList
}
}
})
} catch (_: Throwable) {}
} catch (_: Throwable) {}
}
}
private fun hookLocationListenerClass(clazz: Class<*>, packageName: String) {
val name = clazz.name
if (hookedListenerClasses.contains(name)) return
hookedListenerClasses.add(name)
try {
XposedBridge.hookAllMethods(clazz, "onLocationChanged", object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled || !GlobalMockMemory.shouldMock(packageName)) return
val arg = param.args.getOrNull(0) ?: return
if (arg is Location) {
param.args[0] = GlobalMockMemory.createLocation(arg.provider ?: "gps")
} else if (arg is List<*>) {
val mockList = ArrayList<Location>(arg.size)
for (item in arg) {
val provider = (item as? Location)?.provider ?: "gps"
mockList.add(GlobalMockMemory.createLocation(provider))
}
param.args[0] = mockList
}
}
})
} catch (_: Throwable) {}
} }
} }
@@ -12,6 +12,7 @@ import android.telephony.CellLocation
import android.telephony.PhoneStateListener import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager import android.telephony.TelephonyManager
import com.lzxnone.openloc.hook.ipc.ConfigFetcher import com.lzxnone.openloc.hook.ipc.ConfigFetcher
import com.lzxnone.openloc.hook.model.GlobalMockMemory
import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers import de.robv.android.xposed.XposedHelpers
@@ -23,20 +24,22 @@ import de.robv.android.xposed.XposedHelpers
* 1. 拦截 WifiManager 扫描列表与连接 BSSID/MAC,阻断高德/腾讯/百度云端 Wi-Fi 指纹库反查真实物理位置 * 1. 拦截 WifiManager 扫描列表与连接 BSSID/MAC,阻断高德/腾讯/百度云端 Wi-Fi 指纹库反查真实物理位置
* 2. 拦截 TelephonyManager 基站小区信息与位置监听,杜绝基站 LAC/CID 反查 * 2. 拦截 TelephonyManager 基站小区信息与位置监听,杜绝基站 LAC/CID 反查
* 3. 拦截 PhoneStateListener 与 Android 12+ TelephonyCallback 实时小区回调 * 3. 拦截 PhoneStateListener 与 Android 12+ TelephonyCallback 实时小区回调
* 4. 彻底消除 contextProvider 冷启动时序漏洞:在启动第 0 毫秒优先判定 GlobalMockMemory,
* 哪怕 Context 尚未初始化也坚决阻断真实 Wi-Fi/基站外泄!
*/ */
object NetworkLocationHook { object NetworkLocationHook {
private const val ANONYMOUS_MAC = "02:00:00:00:00:00" private const val ANONYMOUS_MAC = "02:00:00:00:00:00"
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) { fun hook(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
hookWifiManager(contextProvider) hookWifiManager(packageName, contextProvider)
hookTelephonyManager(classLoader, contextProvider) hookTelephonyManager(classLoader, packageName, contextProvider)
} }
/** /**
* 1. 深度拦截 Wi-Fi 扫描结果与连接 BSSID / MAC * 1. 深度拦截 Wi-Fi 扫描结果与连接 BSSID / MAC
*/ */
private fun hookWifiManager(contextProvider: () -> Context?) { private fun hookWifiManager(packageName: String, contextProvider: () -> Context?) {
try { try {
// (1) 拦截 WifiManager.getScanResults() // (1) 拦截 WifiManager.getScanResults()
XposedHelpers.findAndHookMethod( XposedHelpers.findAndHookMethod(
@@ -44,9 +47,7 @@ object NetworkLocationHook {
"getScanResults", "getScanResults",
object : XC_MethodHook() { object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) { override fun afterHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (shouldMockNetwork(packageName, contextProvider)) {
val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
param.result = emptyList<ScanResult>() param.result = emptyList<ScanResult>()
} }
} }
@@ -59,9 +60,7 @@ object NetworkLocationHook {
"getBSSID", "getBSSID",
object : XC_MethodHook() { object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) { override fun afterHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (shouldMockNetwork(packageName, contextProvider)) {
val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
param.result = ANONYMOUS_MAC param.result = ANONYMOUS_MAC
} }
} }
@@ -74,9 +73,7 @@ object NetworkLocationHook {
"getMacAddress", "getMacAddress",
object : XC_MethodHook() { object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) { override fun afterHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (shouldMockNetwork(packageName, contextProvider)) {
val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
param.result = ANONYMOUS_MAC param.result = ANONYMOUS_MAC
} }
} }
@@ -90,7 +87,7 @@ object NetworkLocationHook {
/** /**
* 2. 深度拦截基站塔信息(MCC/MNC/LAC/CID)与实时监听器 * 2. 深度拦截基站塔信息(MCC/MNC/LAC/CID)与实时监听器
*/ */
private fun hookTelephonyManager(classLoader: ClassLoader, contextProvider: () -> Context?) { private fun hookTelephonyManager(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
try { try {
// (1) 拦截 getAllCellInfo // (1) 拦截 getAllCellInfo
XposedHelpers.findAndHookMethod( XposedHelpers.findAndHookMethod(
@@ -98,9 +95,7 @@ object NetworkLocationHook {
"getAllCellInfo", "getAllCellInfo",
object : XC_MethodHook() { object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) { override fun afterHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (shouldMockNetwork(packageName, contextProvider)) {
val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
param.result = emptyList<CellInfo>() param.result = emptyList<CellInfo>()
} }
} }
@@ -113,9 +108,7 @@ object NetworkLocationHook {
"getCellLocation", "getCellLocation",
object : XC_MethodHook() { object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) { override fun afterHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (shouldMockNetwork(packageName, contextProvider)) {
val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
param.result = null param.result = null
} }
} }
@@ -131,14 +124,14 @@ object NetworkLocationHook {
object : XC_MethodHook() { object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val listener = param.args[0] as? PhoneStateListener ?: return val listener = param.args[0] as? PhoneStateListener ?: return
hookPhoneStateListenerClass(listener.javaClass, contextProvider) hookPhoneStateListenerClass(listener.javaClass, packageName, contextProvider)
} }
} }
) )
// (4) Android 12+ TelephonyCallback 拦截 // (4) Android 12+ TelephonyCallback 拦截
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
hookTelephonyCallback(classLoader, contextProvider) hookTelephonyCallback(classLoader, packageName, contextProvider)
} }
} catch (t: Throwable) { } catch (t: Throwable) {
XposedBridge.log("[OpenLoc] hookTelephonyManager error: ${t.message}") XposedBridge.log("[OpenLoc] hookTelephonyManager error: ${t.message}")
@@ -147,7 +140,7 @@ object NetworkLocationHook {
private val hookedListenerClasses = mutableSetOf<String>() private val hookedListenerClasses = mutableSetOf<String>()
private fun hookPhoneStateListenerClass(clazz: Class<*>, contextProvider: () -> Context?) { private fun hookPhoneStateListenerClass(clazz: Class<*>, packageName: String, contextProvider: () -> Context?) {
val className = clazz.name val className = clazz.name
if (hookedListenerClasses.contains(className)) return if (hookedListenerClasses.contains(className)) return
hookedListenerClasses.add(className) hookedListenerClasses.add(className)
@@ -160,9 +153,7 @@ object NetworkLocationHook {
CellLocation::class.java, CellLocation::class.java,
object : XC_MethodHook() { object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (shouldMockNetwork(packageName, contextProvider)) {
val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
param.args[0] = null param.args[0] = null
} }
} }
@@ -178,9 +169,7 @@ object NetworkLocationHook {
List::class.java, List::class.java,
object : XC_MethodHook() { object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (shouldMockNetwork(packageName, contextProvider)) {
val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
param.args[0] = emptyList<CellInfo>() param.args[0] = emptyList<CellInfo>()
} }
} }
@@ -189,7 +178,7 @@ object NetworkLocationHook {
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
private fun hookTelephonyCallback(classLoader: ClassLoader, contextProvider: () -> Context?) { private fun hookTelephonyCallback(classLoader: ClassLoader, packageName: String, contextProvider: () -> Context?) {
try { try {
val callbackClass = XposedHelpers.findClass("android.telephony.TelephonyCallback", classLoader) val callbackClass = XposedHelpers.findClass("android.telephony.TelephonyCallback", classLoader)
val methods = TelephonyManager::class.java.declaredMethods val methods = TelephonyManager::class.java.declaredMethods
@@ -198,7 +187,7 @@ object NetworkLocationHook {
XposedBridge.hookMethod(method, object : XC_MethodHook() { XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val cb = param.args.firstOrNull { it != null && callbackClass.isAssignableFrom(it.javaClass) } ?: return val cb = param.args.firstOrNull { it != null && callbackClass.isAssignableFrom(it.javaClass) } ?: return
hookTelephonyCallbackClass(cb.javaClass, contextProvider) hookTelephonyCallbackClass(cb.javaClass, packageName, contextProvider)
} }
}) })
} }
@@ -206,7 +195,7 @@ object NetworkLocationHook {
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
private fun hookTelephonyCallbackClass(clazz: Class<*>, contextProvider: () -> Context?) { private fun hookTelephonyCallbackClass(clazz: Class<*>, packageName: String, contextProvider: () -> Context?) {
val className = clazz.name val className = clazz.name
if (hookedListenerClasses.contains(className)) return if (hookedListenerClasses.contains(className)) return
hookedListenerClasses.add(className) hookedListenerClasses.add(className)
@@ -216,9 +205,7 @@ object NetworkLocationHook {
try { try {
XposedBridge.hookMethod(method, object : XC_MethodHook() { XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (shouldMockNetwork(packageName, contextProvider)) {
val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
param.args[0] = emptyList<CellInfo>() param.args[0] = emptyList<CellInfo>()
} }
} }
@@ -228,9 +215,7 @@ object NetworkLocationHook {
try { try {
XposedBridge.hookMethod(method, object : XC_MethodHook() { XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return if (shouldMockNetwork(packageName, contextProvider)) {
val config = ConfigFetcher.getConfig(ctx)
if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) {
param.args[0] = null param.args[0] = null
} }
} }
@@ -239,4 +224,17 @@ object NetworkLocationHook {
} }
} }
} }
private fun shouldMockNetwork(packageName: String, contextProvider: () -> Context?): Boolean {
if (packageName == "com.lzxnone.openloc") return false
if (GlobalMockMemory.isEnabled && GlobalMockMemory.shouldMock(packageName)) {
return true
}
val ctx = contextProvider()
if (ctx != null) {
val config = ConfigFetcher.getConfig(ctx)
return config.shouldMock(packageName.ifBlank { ctx.packageName })
}
return false
}
} }
@@ -1,108 +0,0 @@
package com.lzxnone.openloc.hook.interceptor
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers
import kotlin.random.Random
/**
* 物理动力学传感器协同与生理微颤拟真拦截器
*
* 核心目标:
* 1. 拦截 SensorManager.registerListener,捕获应用注册的传感器监听器
* 2. 针对加速度计 (TYPE_ACCELEROMETER) 与重力传感器 (TYPE_GRAVITY),动态注入人体手持特有的生物力学生理颤动(Physiological Tremor)
* 3. 防止加速度方差几乎为 0 导致被高精风控判定为“放置在桌面的静止刚体设备”
* 4. 针对陀螺仪 (TYPE_GYROSCOPE) 注入极细微的手持角速度扰动
*/
object SensorHook {
private val hookedListenerClasses = mutableSetOf<String>()
fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) {
hookSensorManager(contextProvider)
}
private fun hookSensorManager(contextProvider: () -> Context?) {
try {
val methods = SensorManager::class.java.declaredMethods
for (method in methods) {
if (method.name == "registerListener") {
val paramTypes = method.parameterTypes
val listenerIndex = paramTypes.indexOfFirst {
SensorEventListener::class.java.isAssignableFrom(it)
}
if (listenerIndex != -1) {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val listener = param.args[listenerIndex] as? SensorEventListener ?: return
hookSensorEventListenerClass(listener.javaClass, contextProvider)
}
})
} catch (_: Throwable) {}
}
}
}
} catch (t: Throwable) {
XposedBridge.log("[OpenLoc] hookSensorManager error: ${t.message}")
}
}
private fun hookSensorEventListenerClass(clazz: Class<*>, contextProvider: () -> Context?) {
val className = clazz.name
if (hookedListenerClasses.contains(className)) return
hookedListenerClasses.add(className)
try {
XposedHelpers.findAndHookMethod(
clazz,
"onSensorChanged",
SensorEvent::class.java,
object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val ctx = contextProvider() ?: return
val config = ConfigFetcher.getConfig(ctx)
if (!config.shouldMock(ctx.packageName) || !config.isSensorSimulationEnabled) return
val event = param.args[0] as? SensorEvent ?: return
val sensorType = event.sensor?.type ?: return
when (sensorType) {
// 1. 三轴加速度计(最核心):注入人体手持 ~0.05 m/s² 生理微颤
Sensor.TYPE_ACCELEROMETER -> {
if (event.values.size >= 3) {
event.values[0] += (Random.nextFloat() - 0.5f) * 0.08f
event.values[1] += (Random.nextFloat() - 0.5f) * 0.08f
event.values[2] += (Random.nextFloat() - 0.5f) * 0.08f
}
}
// 2. 重力传感器:微量波动维持向量模长
Sensor.TYPE_GRAVITY -> {
if (event.values.size >= 3) {
event.values[0] += (Random.nextFloat() - 0.5f) * 0.04f
event.values[1] += (Random.nextFloat() - 0.5f) * 0.04f
event.values[2] += (Random.nextFloat() - 0.5f) * 0.04f
}
}
// 3. 陀螺仪:手持微弱角速度波动 (rad/s)
Sensor.TYPE_GYROSCOPE -> {
if (event.values.size >= 3) {
event.values[0] += (Random.nextFloat() - 0.5f) * 0.015f
event.values[1] += (Random.nextFloat() - 0.5f) * 0.015f
event.values[2] += (Random.nextFloat() - 0.5f) * 0.015f
}
}
}
}
}
)
} catch (_: Throwable) {}
}
}
@@ -1,32 +1,58 @@
package com.lzxnone.openloc.hook.ipc package com.lzxnone.openloc.hook.ipc
import android.content.BroadcastReceiver
import android.content.Context import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri import android.net.Uri
import android.os.Build
import com.lzxnone.openloc.core.provider.ConfigContract import com.lzxnone.openloc.core.provider.ConfigContract
import com.lzxnone.openloc.hook.model.GlobalMockMemory
import com.lzxnone.openloc.hook.model.MockConfig import com.lzxnone.openloc.hook.model.MockConfig
import de.robv.android.xposed.XposedBridge
/** /**
* 跨进程配置拉取与缓存器(运行在目标宿主进程) * 跨进程配置拉取与缓存器(运行在目标宿主进程)
* 增强版:结合全局内存常驻 + 动态广播秒级同步 + ContentProvider 双重兜底
*/ */
object ConfigFetcher { object ConfigFetcher {
private val PROVIDER_URI = Uri.parse(ConfigContract.CONTENT_URI) private val PROVIDER_URI = Uri.parse(ConfigContract.CONTENT_URI)
@Volatile
private var isReceiverRegistered = false
@Volatile @Volatile
private var cachedConfig: MockConfig? = null private var cachedConfig: MockConfig? = null
@Volatile @Volatile
private var lastFetchTime = 0L private var lastFetchTime = 0L
private const val CACHE_DURATION_MS = 1500L // 缓存 1.5 秒,保证即时性同时兼顾性能 private const val CACHE_DURATION_MS = 1500L
private val isFetching = ThreadLocal.withInitial { false } private val isFetching = ThreadLocal.withInitial { false }
/** /**
* 获取最新配置(带平滑缓存与防死锁重入保护) * 获取最新配置(优先读取零延迟全局内存)
*/ */
fun getConfig(context: Context, force: Boolean = false): MockConfig { fun getConfig(context: Context, force: Boolean = false): MockConfig {
ensureReceiverRegistered(context)
// 1. 优先使用系统原生管道注入的全局静态内存
if (GlobalMockMemory.isEnabled) {
return MockConfig(
isEnabled = GlobalMockMemory.isEnabled,
latitude = GlobalMockMemory.latitude,
longitude = GlobalMockMemory.longitude,
altitude = GlobalMockMemory.altitude,
accuracy = GlobalMockMemory.accuracy,
bearing = GlobalMockMemory.bearing,
speed = GlobalMockMemory.speed,
mode = GlobalMockMemory.mode,
whitelist = GlobalMockMemory.whitelist,
blacklist = GlobalMockMemory.blacklist
)
}
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
if (!force && cachedConfig != null && (now - lastFetchTime < CACHE_DURATION_MS)) { if (!force && cachedConfig != null && (now - lastFetchTime < CACHE_DURATION_MS)) {
return cachedConfig!! return cachedConfig!!
@@ -45,48 +71,73 @@ object ConfigFetcher {
null null
) )
if (bundle != null) { if (bundle != null) {
val mode = bundle.getString(ConfigContract.KEY_APP_MOCK_MODE, "GLOBAL") ?: "GLOBAL" val mode = bundle.getString(ConfigContract.KEY_APP_MOCK_MODE, "GLOBAL") ?: "GLOBAL"
val whitelistJson = bundle.getString(ConfigContract.KEY_WHITELIST_APPS, "[]") ?: "[]" val whitelistJson = bundle.getString(ConfigContract.KEY_WHITELIST_APPS, "[]") ?: "[]"
val blacklistJson = bundle.getString(ConfigContract.KEY_BLACKLIST_APPS, "[]") ?: "[]" val blacklistJson = bundle.getString(ConfigContract.KEY_BLACKLIST_APPS, "[]") ?: "[]"
val isJitter = bundle.getBoolean(ConfigContract.KEY_ENABLE_JITTER, true)
val isGnss = bundle.getBoolean(ConfigContract.KEY_ENABLE_GNSS_SIMULATION, true)
val isNetwork = bundle.getBoolean(ConfigContract.KEY_ENABLE_NETWORK_CAMOUFLAGE, true)
val isSensor = bundle.getBoolean(ConfigContract.KEY_ENABLE_SENSOR_SIMULATION, true)
val isStealth = bundle.getBoolean(ConfigContract.KEY_ENABLE_STEALTH, true)
val isDevCamouflage = bundle.getBoolean(ConfigContract.KEY_ENABLE_DEV_CAMOUFLAGE, true)
val config = MockConfig( val config = MockConfig(
isEnabled = bundle.getBoolean(ConfigContract.KEY_ENABLED, false), isEnabled = bundle.getBoolean(ConfigContract.KEY_ENABLED, false),
latitude = bundle.getDouble(ConfigContract.KEY_LATITUDE, 39.908722), latitude = bundle.getDouble(ConfigContract.KEY_LATITUDE, 39.908722),
longitude = bundle.getDouble(ConfigContract.KEY_LONGITUDE, 116.397496), longitude = bundle.getDouble(ConfigContract.KEY_LONGITUDE, 116.397496),
locationName = bundle.getString(ConfigContract.KEY_LOCATION_NAME, ""), altitude = bundle.getDouble("altitude", 50.0),
accuracy = bundle.getFloat("accuracy", 5.0f),
bearing = bundle.getFloat("bearing", 0.0f),
speed = bundle.getFloat("speed", 0.0f),
mode = mode, mode = mode,
whitelist = parseSet(whitelistJson), whitelist = parseSet(whitelistJson),
blacklist = parseSet(blacklistJson), blacklist = parseSet(blacklistJson)
isJitterEnabled = isJitter,
isGnssSimulationEnabled = isGnss,
isNetworkCamouflageEnabled = isNetwork,
isSensorSimulationEnabled = isSensor,
isStealthEnabled = isStealth,
isDevCamouflageEnabled = isDevCamouflage
) )
cachedConfig = config cachedConfig = config
lastFetchTime = now lastFetchTime = now
// 如果通过 Provider 拉取成功且已开启,同步更新全局静态内存
if (config.isEnabled) {
GlobalMockMemory.isEnabled = config.isEnabled
GlobalMockMemory.latitude = config.latitude
GlobalMockMemory.longitude = config.longitude
GlobalMockMemory.altitude = config.altitude
GlobalMockMemory.accuracy = config.accuracy
GlobalMockMemory.bearing = config.bearing
GlobalMockMemory.speed = config.speed
GlobalMockMemory.mode = config.mode
GlobalMockMemory.whitelist = config.whitelist
GlobalMockMemory.blacklist = config.blacklist
}
config config
} else { } else {
cachedConfig ?: MockConfig() cachedConfig ?: MockConfig()
} }
} catch (t: Throwable) { } catch (_: Throwable) {
// 在目标尚未完全就绪或权限受限时的静默容错
cachedConfig ?: MockConfig() cachedConfig ?: MockConfig()
} finally { } finally {
isFetching.set(false) isFetching.set(false)
} }
} }
private fun ensureReceiverRegistered(context: Context) {
if (isReceiverRegistered) return
synchronized(this) {
if (isReceiverRegistered) return
try {
val filter = IntentFilter("com.lzxnone.openloc.ACTION_SYNC_CONFIG")
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) {
val extras = intent?.extras ?: return
GlobalMockMemory.updateFromBundle(extras)
lastFetchTime = System.currentTimeMillis()
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.applicationContext.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED)
} else {
context.applicationContext.registerReceiver(receiver, filter)
}
isReceiverRegistered = true
} catch (_: Throwable) {}
}
}
private fun parseSet(jsonStr: String): Set<String> { private fun parseSet(jsonStr: String): Set<String> {
return try { return try {
@@ -0,0 +1,134 @@
package com.lzxnone.openloc.hook.model
import android.location.Location
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
/**
* 全局内存常驻配置中心(基于 GhostMapX 工业级架构)
* 运行在 system_server 与各进程中
*/
object GlobalMockMemory {
const val COMMAND_PROVIDER = "openloc"
const val COMMAND_SYNC = "sync_config"
const val EXTRA_ENABLED = "is_enabled"
const val EXTRA_LATITUDE = "latitude"
const val EXTRA_LONGITUDE = "longitude"
const val EXTRA_ALTITUDE = "altitude"
const val EXTRA_ACCURACY = "accuracy"
const val EXTRA_BEARING = "bearing"
const val EXTRA_SPEED = "speed"
const val EXTRA_LOCATION_NAME = "location_name"
const val EXTRA_MODE = "mode"
const val EXTRA_WHITELIST = "whitelist"
const val EXTRA_BLACKLIST = "blacklist"
@Volatile var isEnabled: Boolean = false
@Volatile var latitude: Double = 39.908722
@Volatile var longitude: Double = 116.397496
@Volatile var altitude: Double = 50.0
@Volatile var accuracy: Float = 5.0f
@Volatile var bearing: Float = 0.0f
@Volatile var speed: Float = 0.0f
@Volatile var mode: String = "GLOBAL"
@Volatile var whitelist: Set<String> = emptySet()
@Volatile var blacklist: Set<String> = emptySet()
fun updateFromBundle(bundle: Bundle) {
isEnabled = bundle.getBoolean(EXTRA_ENABLED, isEnabled)
latitude = bundle.getDouble(EXTRA_LATITUDE, latitude)
longitude = bundle.getDouble(EXTRA_LONGITUDE, longitude)
altitude = bundle.getDouble(EXTRA_ALTITUDE, altitude)
accuracy = bundle.getFloat(EXTRA_ACCURACY, accuracy)
bearing = bundle.getFloat(EXTRA_BEARING, bearing)
speed = bundle.getFloat(EXTRA_SPEED, speed)
mode = bundle.getString(EXTRA_MODE, mode) ?: mode
val whiteListArray = bundle.getStringArrayList(EXTRA_WHITELIST)
if (whiteListArray != null) {
whitelist = whiteListArray.toSet()
}
val blackListArray = bundle.getStringArrayList(EXTRA_BLACKLIST)
if (blackListArray != null) {
blacklist = blackListArray.toSet()
}
}
fun toBundle(): Bundle {
return Bundle().apply {
putBoolean(EXTRA_ENABLED, isEnabled)
putDouble(EXTRA_LATITUDE, latitude)
putDouble(EXTRA_LONGITUDE, longitude)
putDouble(EXTRA_ALTITUDE, altitude)
putFloat(EXTRA_ACCURACY, accuracy)
putFloat(EXTRA_BEARING, bearing)
putFloat(EXTRA_SPEED, speed)
putString(EXTRA_MODE, mode)
putStringArrayList(EXTRA_WHITELIST, ArrayList(whitelist))
putStringArrayList(EXTRA_BLACKLIST, ArrayList(blacklist))
}
}
/**
* 判定指定包名是否应被模拟
* 严格豁免 OpenLoc 自身包名,确保其始终能读取物理 GPS 回到真实定位点
*/
fun shouldMock(packageName: String?): Boolean {
if (!isEnabled) return false
if (packageName.isNullOrBlank()) return true
if (packageName == "com.lzxnone.openloc" || packageName == "android") return false
return when (mode.uppercase()) {
"WHITELIST" -> whitelist.contains(packageName)
"BLACKLIST" -> !blacklist.contains(packageName)
else -> true
}
}
/**
* 生成标准可用的 Mock Location 对象
*/
fun createLocation(provider: String = "gps"): Location {
return Location(provider).apply {
latitude = this@GlobalMockMemory.latitude
longitude = this@GlobalMockMemory.longitude
altitude = this@GlobalMockMemory.altitude
accuracy = this@GlobalMockMemory.accuracy
bearing = this@GlobalMockMemory.bearing
speed = this@GlobalMockMemory.speed
time = System.currentTimeMillis()
elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
// 补充 GNSS 卫星定位精度属性(Android 8.0+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
verticalAccuracyMeters = 1.5f
speedAccuracyMetersPerSecond = 0.1f
bearingAccuracyDegrees = 1.0f
}
}
}
/**
* 就地覆写现有 Location 对象
*/
fun applyToLocation(location: Location) {
location.latitude = latitude
location.longitude = longitude
location.altitude = altitude
location.accuracy = accuracy
location.bearing = bearing
location.speed = speed
location.time = System.currentTimeMillis()
location.elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
location.verticalAccuracyMeters = 1.5f
location.speedAccuracyMetersPerSecond = 0.1f
location.bearingAccuracyDegrees = 1.0f
}
}
}
@@ -1,34 +1,25 @@
package com.lzxnone.openloc.hook.model package com.lzxnone.openloc.hook.model
import java.util.Locale
/**
* 虚拟定位配置实体
*/
data class MockConfig( data class MockConfig(
val isEnabled: Boolean = false, val isEnabled: Boolean = false,
val latitude: Double = 39.908722, val latitude: Double = 39.908722,
val longitude: Double = 116.397496, val longitude: Double = 116.397496,
val locationName: String = "", val altitude: Double = 50.0,
val accuracy: Float = 5.0f,
val bearing: Float = 0.0f,
val speed: Float = 0.0f,
val mode: String = "GLOBAL", val mode: String = "GLOBAL",
val whitelist: Set<String> = emptySet(), val whitelist: Set<String> = emptySet(),
val blacklist: Set<String> = emptySet(), val blacklist: Set<String> = emptySet()
val isJitterEnabled: Boolean = true,
val isGnssSimulationEnabled: Boolean = true,
val isNetworkCamouflageEnabled: Boolean = true,
val isSensorSimulationEnabled: Boolean = true,
val isStealthEnabled: Boolean = true,
val isDevCamouflageEnabled: Boolean = true
) { ) {
/** fun shouldMock(packageName: String?): Boolean {
* 判断指定应用包名是否应当生效虚拟定位
*/
fun shouldMock(packageName: String): Boolean {
if (!isEnabled) return false if (!isEnabled) return false
return when (mode.uppercase(Locale.ROOT)) { if (packageName.isNullOrBlank()) return true
if (packageName == "com.lzxnone.openloc" || packageName == "android") return false
return when (mode.uppercase()) {
"WHITELIST" -> whitelist.contains(packageName) "WHITELIST" -> whitelist.contains(packageName)
"BLACKLIST" -> !blacklist.contains(packageName) "BLACKLIST" -> !blacklist.contains(packageName)
else -> true // "GLOBAL" else -> true
} }
} }
} }
@@ -1,280 +1,442 @@
package com.lzxnone.openloc.hook.system package com.lzxnone.openloc.hook.system
import android.location.Location import android.location.Location
import android.os.Build import android.os.Binder
import com.lzxnone.openloc.hook.model.MockConfig import android.os.Bundle
import com.lzxnone.openloc.hook.util.LocationSimulator import android.os.IBinder
import android.os.IInterface
import com.lzxnone.openloc.hook.model.GlobalMockMemory
import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers import de.robv.android.xposed.XposedHelpers
import org.xmlpull.v1.XmlPullParser import java.lang.reflect.Method
import org.xmlpull.v1.XmlPullParserFactory import java.util.Collections
import java.io.File import java.util.concurrent.ConcurrentHashMap
import java.io.FileInputStream
/** /**
* 针对 Android 系统框架 (system_server / android) 的系统级全局 Hook * system_server 底层服务核心拦截器(100% 工业级对齐 GhostMapX Lcf/LP3/LXe 架构)
* *
* 核心原理: * 核心机制说明:
* 在 Android 操作系统中,整机所有应用调用 LocationManager 获取位置, * 1. 绝对不篡改底层硬件驱动和物理 GPS 缓冲区(不篡改 LocationProviderManager.onReportLocation),
* 底层最终全部汇集到 system_server 进程里的 LocationManagerService 中进行统一调度和分发。 * 保证系统物理 GPS 随时纯净可用,OpenLoc 随时能读取真实设备坐标;
* * 2. 动态维护活跃 Binder 映射表(与 GhostMapX cf.a / cf.b / LP3 完全一致):
* 只要在 LSPosed 作用域中勾选了【Android 系统 (android)】,本拦截器就会在系统服务底层 * - activeListeners: ConcurrentHashMap<IBinder, String>(跟踪每个 ILocationListener 的所属目标包名)
* 将发往所有应用的位置数据全部篡改并洗白。 * - activeCallbacks: ConcurrentHashMap<IBinder, String>(跟踪每个 ILocationCallback 的所属目标包名)
* 手机里无论是已有应用还是将来新下载的应用,统统无需单独指定,直接全局生效! * - 当客户端注册监听时通过 IBinder.linkToDeath 监听生命周期;
* 3. 在 onLocationChanged / onLocation 回调触发时:
* - 通过 param.thisObject 提取对应的 IBinder 实例;
* - 只有在 activeListeners / activeCallbacks 中明确登记的目标应用才替换入参为虚拟定位;
* - OpenLoc 自身、系统进程以及未加入模拟名单的应用绝对放行真实定位,绝无交叉污染!
* 4. 首帧秒推机制(GhostMapX Lcf.a: 56-112 行):
* - 目标应用注册 requestLocationUpdates 的瞬间,立即反射调用 onLocationChanged 注入首帧,
* 让应用(百度地图、高德、QQ)无需等待系统几秒甚至几分钟的搜星延迟,即刻获取定位!
*/ */
object SystemServerHook { object SystemServerHook {
private const val PREF_FILE_PATH_1 = "/data/data/com.lzxnone.openloc/shared_prefs/openloc_prefs.xml" // 活跃监听器与其所属目标包名的映射表(以 IBinder 为 key,彻底消除 Class 静态闭包污染)
private const val PREF_FILE_PATH_2 = "/data/user/0/com.lzxnone.openloc/shared_prefs/openloc_prefs.xml" private val activeListeners = ConcurrentHashMap<IBinder, String>()
private val activeCallbacks = ConcurrentHashMap<IBinder, String>()
@Volatile // 已挂钩 onLocationChanged 的类名集合,防止重复 Hook
private var lastReadTime = 0L private val hookedListenerClasses = Collections.synchronizedSet(mutableSetOf<String>())
@Volatile private val hookedCallbackClasses = Collections.synchronizedSet(mutableSetOf<String>())
private var cachedConfig = MockConfig()
/**
* 在 system_server 进程中直接读取 OpenLoc 的配置文件(system_server 具备最高读取权限)
*/
private fun readConfigDirectly(): MockConfig {
val now = System.currentTimeMillis()
if (now - lastReadTime < 1500L) {
return cachedConfig
}
val file = listOf(File(PREF_FILE_PATH_1), File(PREF_FILE_PATH_2)).firstOrNull { it.exists() && it.canRead() }
?: return cachedConfig
try {
var isEnabled = false
var lat = 39.908722
var lng = 116.397496
var mode = "GLOBAL"
val whitelist = mutableSetOf<String>()
val blacklist = mutableSetOf<String>()
var isJitter = true
var isGnss = true
var isNetwork = true
var isSensor = true
var isStealth = true
var isDevCamouflage = true
FileInputStream(file).use { fis ->
val factory = XmlPullParserFactory.newInstance()
val parser = factory.newPullParser()
parser.setInput(fis, "UTF-8")
var eventType = parser.eventType
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
val name = parser.getAttributeValue(null, "name")
when (parser.name) {
"boolean" -> {
when (name) {
"mock_service_enabled" -> {
isEnabled = parser.getAttributeValue(null, "value") == "true"
}
"enable_jitter" -> {
isJitter = parser.getAttributeValue(null, "value") == "true"
}
"enable_gnss_simulation" -> {
isGnss = parser.getAttributeValue(null, "value") == "true"
}
"enable_network_camouflage" -> {
isNetwork = parser.getAttributeValue(null, "value") == "true"
}
"enable_sensor_simulation" -> {
isSensor = parser.getAttributeValue(null, "value") == "true"
}
"enable_stealth" -> {
isStealth = parser.getAttributeValue(null, "value") == "true"
}
"enable_dev_camouflage" -> {
isDevCamouflage = parser.getAttributeValue(null, "value") == "true"
}
}
}
"string" -> {
when (name) {
"mock_latitude" -> {
lat = parser.nextText()?.toDoubleOrNull() ?: lat
}
"mock_longitude" -> {
lng = parser.nextText()?.toDoubleOrNull() ?: lng
}
"app_mock_mode" -> {
mode = parser.nextText() ?: mode
}
"whitelist_apps" -> {
parseJsonArrayToSet(parser.nextText(), whitelist)
}
"blacklist_apps" -> {
parseJsonArrayToSet(parser.nextText(), blacklist)
}
}
}
}
}
eventType = parser.next()
}
}
cachedConfig = MockConfig(
isEnabled = isEnabled,
latitude = lat,
longitude = lng,
mode = mode,
whitelist = whitelist,
blacklist = blacklist,
isJitterEnabled = isJitter,
isGnssSimulationEnabled = isGnss,
isNetworkCamouflageEnabled = isNetwork,
isSensorSimulationEnabled = isSensor,
isStealthEnabled = isStealth,
isDevCamouflageEnabled = isDevCamouflage
)
lastReadTime = now
} catch (_: Throwable) {}
return cachedConfig
}
private fun parseJsonArrayToSet(jsonStr: String?, target: MutableSet<String>) {
if (jsonStr.isNullOrBlank()) return
try {
val array = org.json.JSONArray(jsonStr)
for (i in 0 until array.length()) {
target.add(array.getString(i))
}
} catch (_: Throwable) {}
}
fun hook(classLoader: ClassLoader) { fun hook(classLoader: ClassLoader) {
XposedBridge.log("[OpenLoc] Initializing SystemServerHook for global mock location...") XposedBridge.log("[OpenLoc] [SystemServer] Initializing GhostMapX architecture in system_server...")
hookSystemLocationService(classLoader) hookLocationManagerService(classLoader)
hookWifiService(classLoader)
} }
/** private fun hookLocationManagerService(classLoader: ClassLoader) {
* 拦截系统底层 LocationManagerService 的分发与获取逻辑 val lmsClasses = listOf(
*/
private fun hookSystemLocationService(classLoader: ClassLoader) {
val lmsClassNames = listOf(
"com.android.server.location.LocationManagerService", "com.android.server.location.LocationManagerService",
"com.android.server.LocationManagerService" "com.android.server.LocationManagerService"
) )
for (className in lmsClassNames) { var lmsClass: Class<*>? = null
val lmsClass = try { for (className in lmsClasses) {
lmsClass = try {
XposedHelpers.findClass(className, classLoader) XposedHelpers.findClass(className, classLoader)
} catch (_: Throwable) { } catch (_: Throwable) {
null null
} ?: continue }
if (lmsClass != null) break
hookLmsMethods(lmsClass)
break
} }
// Android 12+ (API 31)+ 核心底层服务 LocationProviderManager 拦截 if (lmsClass == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { XposedBridge.log("[OpenLoc] [SystemServer] LocationManagerService not found!")
hookLocationProviderManager(classLoader) return
}
} }
private fun hookLmsMethods(lmsClass: Class<*>) {
for (method in lmsClass.declaredMethods) { for (method in lmsClass.declaredMethods) {
// 1. 拦截系统返回给客户端的最后已知位置 getLastLocation when (method.name) {
if (method.name == "getLastLocation") { // (1) 0ms IPC 内存配置同步通道:sendExtraCommand
try { "sendExtraCommand" -> {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
val config = readConfigDirectly()
if (!config.isEnabled) return
val pkg = extractCallingPackage(param)
if (pkg != null && !config.shouldMock(pkg)) return
val loc = param.result as? Location
if (loc != null) {
LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled)
} else {
param.result = LocationSimulator.createMockLocation(
config.latitude,
config.longitude,
isJitterEnabled = config.isJitterEnabled
)
}
}
})
} catch (_: Throwable) {}
}
// 2. 拦截系统分发定位 reportLocation
if (method.name == "reportLocation") {
try { try {
XposedBridge.hookMethod(method, object : XC_MethodHook() { XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun beforeHookedMethod(param: MethodHookParam) {
val config = readConfigDirectly() val provider = param.args.getOrNull(0) as? String
if (!config.isEnabled) return val extras = param.args.getOrNull(2) as? Bundle
if (provider == GlobalMockMemory.COMMAND_PROVIDER || provider == "ghostmapx") {
val loc = param.args.firstOrNull { it is Location } as? Location if (extras != null) {
if (loc != null) { GlobalMockMemory.updateFromBundle(extras)
LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled) XposedBridge.log("[OpenLoc] [SystemServer] Config synced: Enabled=${GlobalMockMemory.isEnabled}, Lat=${GlobalMockMemory.latitude}, Lng=${GlobalMockMemory.longitude}, Mode=${GlobalMockMemory.mode}")
param.result = true
}
} }
} }
}) })
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
// (2) 历史缓存位置拦截:getLastLocation(100% 对齐 GhostMapX LXe case 9)
// 核心:不论原系统返回真实坐标还是 null,目标应用一律置换为带有最新纳秒时间戳的 Mock 实体,
// 彻底杜绝冷启动第 0 毫秒向高德/百度地图泄露真实原位;
// 严格安全防线:未知名调用方或非模拟目标一律放行原系统物理缓存,绝不越界污染!
"getLastLocation" -> {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled) return
val pkg = resolveCallingPackage(param)
// 必须能明确识别包名,且该包名在模拟范围内,才进行替换;否则绝对放行物理真实位置
if (pkg.isNullOrBlank() || !GlobalMockMemory.shouldMock(pkg)) return
val provider = param.args.firstOrNull { it is String && it in listOf("gps", "network", "fused", "passive") } as? String ?: "gps"
param.result = GlobalMockMemory.createLocation(provider)
}
})
} catch (_: Throwable) {}
}
// (3) 单次定位请求:getCurrentLocation
"getCurrentLocation" -> {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled) return
val pkg = resolveCallingPackage(param)
if (pkg.isNullOrBlank() || !GlobalMockMemory.shouldMock(pkg)) return
// 查找 ILocationCallback 实例
for (arg in param.args) {
if (arg != null && (arg is IInterface || arg is IBinder ||
arg.javaClass.name.contains("Callback") ||
arg.javaClass.name.contains("Consumer") ||
arg.javaClass.name.contains("Transport"))) {
val binder = (arg as? IInterface)?.asBinder() ?: (arg as? IBinder)
if (binder != null) {
activeCallbacks[binder] = pkg
try {
binder.linkToDeath({ activeCallbacks.remove(binder) }, 0)
} catch (_: Throwable) {}
}
hookCallbackClass(arg.javaClass)
}
}
}
})
} catch (_: Throwable) {}
}
// (4) 持续定位监听器注册:registerLocationListener / requestLocationUpdates(GhostMapX 核心机理)
"registerLocationListener", "requestLocationUpdates" -> {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled) return
val pkg = resolveCallingPackage(param)
if (pkg.isNullOrBlank() || !GlobalMockMemory.shouldMock(pkg)) return
val provider = param.args.firstOrNull { it is String && it in listOf("gps", "network", "fused", "passive") } as? String ?: "gps"
for (arg in param.args) {
if (arg != null && (arg is IInterface || arg is IBinder ||
arg.javaClass.name.contains("Listener") ||
arg.javaClass.name.contains("Transport") ||
arg.javaClass.name.contains("Callback"))) {
val binder = (arg as? IInterface)?.asBinder() ?: (arg as? IBinder)
if (binder != null) {
activeListeners[binder] = pkg
try {
binder.linkToDeath({ activeListeners.remove(binder) }, 0)
} catch (_: Throwable) {}
}
val listenerClass = arg.javaClass
hookListenerClass(listenerClass)
// GhostMapX 首帧秒推(Lcf.a: 56-112行):
// 注册瞬间立即主动向目标应用的 listener 分发一帧虚拟定位,消除应用等待冷启动定星延迟
sendInitialMockLocation(arg, provider)
}
}
}
})
} catch (_: Throwable) {}
}
// (5) Provider 可用性伪装恒为 true
"isProviderEnabled", "isProviderEnabledForUser" -> {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (GlobalMockMemory.isEnabled) {
val pkg = resolveCallingPackage(param)
if (!pkg.isNullOrBlank() && GlobalMockMemory.shouldMock(pkg)) {
param.result = true
}
}
}
})
} catch (_: Throwable) {}
}
}
} }
} }
/** /**
* Android 12/13/14+ LocationProviderManager 深度拦截 * 动态挂钩 ILocationListener.onLocationChanged(GhostMapX LP3 工业级实现)
*/ */
private fun hookLocationProviderManager(classLoader: ClassLoader) { private fun hookListenerClass(clazz: Class<*>) {
val lpmClasses = listOf( val className = clazz.name
"com.android.server.location.provider.LocationProviderManager", if (hookedListenerClasses.contains(className)) return
"com.android.server.location.LocationProviderManager" hookedListenerClasses.add(className)
try {
XposedBridge.hookAllMethods(clazz, "onLocationChanged", object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled) return
// 通过 param.thisObject 获取当前 listener 的真实 Binder 实例
val thisObj = param.thisObject ?: return
val binder = (thisObj as? IInterface)?.asBinder() ?: (thisObj as? IBinder) ?: return
// 动态查找该 Binder 归属的目标包名
val pkg = activeListeners[binder] ?: return
if (pkg == "com.lzxnone.openloc" || pkg == "android") return
if (!GlobalMockMemory.shouldMock(pkg)) return
// 命中目标应用,精准实施虚拟坐标替换
// 【核心安全原则】:实例化全新 Mock Location 对象替换入参指针,绝对不能在原对象上进行 in-place 就地修改,
// 彻底杜绝污染系统 LocationProviderManager.mLastLocation 全局物理位置缓存与广播数据流!
val arg0 = param.args.getOrNull(0) ?: return
if (arg0 is Location) {
param.args[0] = GlobalMockMemory.createLocation(arg0.provider ?: "gps")
} else if (arg0 is List<*>) {
val mockList = ArrayList<Location>(arg0.size)
for (item in arg0) {
val provider = (item as? Location)?.provider ?: "gps"
mockList.add(GlobalMockMemory.createLocation(provider))
}
param.args[0] = mockList
}
}
})
} catch (_: Throwable) {}
}
/**
* 动态挂钩 ILocationCallback.onLocation(GhostMapX 单次定位精髓)
*/
private fun hookCallbackClass(clazz: Class<*>) {
val className = clazz.name
if (hookedCallbackClasses.contains(className)) return
hookedCallbackClasses.add(className)
val targetMethods = listOf("onLocation", "onLocationChanged", "accept")
for (methodName in targetMethods) {
try {
XposedBridge.hookAllMethods(clazz, methodName, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled) return
val thisObj = param.thisObject ?: return
val binder = (thisObj as? IInterface)?.asBinder() ?: (thisObj as? IBinder) ?: return
val pkg = activeCallbacks[binder] ?: return
if (pkg == "com.lzxnone.openloc" || pkg == "android") return
if (!GlobalMockMemory.shouldMock(pkg)) return
// 同理:创建新对象替换参数,保留系统底层原始物理位置
val arg0 = param.args.getOrNull(0) ?: return
if (arg0 is Location) {
param.args[0] = GlobalMockMemory.createLocation(arg0.provider ?: "gps")
} else if (arg0 is List<*>) {
val mockList = ArrayList<Location>(arg0.size)
for (item in arg0) {
val provider = (item as? Location)?.provider ?: "gps"
mockList.add(GlobalMockMemory.createLocation(provider))
}
param.args[0] = mockList
}
}
})
} catch (_: Throwable) {}
}
}
/**
* 首帧秒推辅助方法(对齐 GhostMapX Lcf.a 144-200行)
*/
private fun sendInitialMockLocation(listenerInstance: Any, provider: String) {
try {
val mockLoc = GlobalMockMemory.createLocation(provider)
val methods = listenerInstance.javaClass.methods
for (method in methods) {
if (method.name == "onLocationChanged") {
val pTypes = method.parameterTypes
if (pTypes.isNotEmpty()) {
if (List::class.java.isAssignableFrom(pTypes[0])) {
val args = arrayOfNulls<Any>(pTypes.size)
args[0] = listOf(mockLoc)
method.invoke(listenerInstance, *args)
return
} else if (Location::class.java.isAssignableFrom(pTypes[0])) {
val args = arrayOfNulls<Any>(pTypes.size)
args[0] = mockLoc
method.invoke(listenerInstance, *args)
return
}
}
}
}
} catch (_: Throwable) {}
}
/**
* Wi-Fi 扫描结果与连接指纹拦截(100% 对齐 GhostMapX LTn.java)
* 核心:
* 1. getScanResults: 兼容 Android 10+ 的 ParceledListSlice,绝不因类型转换异常泄露真实 Wi-Fi 列表;
* 2. getConnectionInfo: 抹去当前连接 Wi-Fi 路由器的真实 BSSID (MAC),阻断 QQ/腾讯云端指纹反查。
*/
private fun hookWifiService(classLoader: ClassLoader) {
val wifiServiceClasses = listOf(
"com.android.server.wifi.WifiServiceImpl",
"com.android.server.wifi.WifiService"
) )
for (className in lpmClasses) { for (className in wifiServiceClasses) {
val lpmClass = try { val wifiClass = try {
XposedHelpers.findClass(className, classLoader) XposedHelpers.findClass(className, classLoader)
} catch (_: Throwable) { } catch (_: Throwable) {
null null
} ?: continue } ?: continue
for (method in lpmClass.declaredMethods) { for (method in wifiClass.declaredMethods) {
if (method.name == "setLastLocation" || method.name == "onReportLocation") { when (method.name) {
"getScanResults" -> {
try { try {
XposedBridge.hookMethod(method, object : XC_MethodHook() { XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) { override fun afterHookedMethod(param: MethodHookParam) {
val config = readConfigDirectly() if (!GlobalMockMemory.isEnabled) return
if (!config.isEnabled) return val pkg = resolveCallingPackage(param)
// 未知名或非模拟目标一律放行物理 Wi-Fi 扫描结果
if (pkg.isNullOrBlank() || !GlobalMockMemory.shouldMock(pkg)) return
val loc = param.args.firstOrNull { it is Location } as? Location val res = param.result ?: return
if (loc != null) { if (res is List<*>) {
LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled) param.result = emptyList<Any>()
} else if (res.javaClass.name.contains("ParceledListSlice")) {
// GhostMapX LTn.java 经典实现:反射构建空的 ParceledListSlice
try {
val ctor = res.javaClass.getConstructor(List::class.java)
ctor.isAccessible = true
param.result = ctor.newInstance(emptyList<Any>())
} catch (_: Throwable) {
param.result = null
} }
} }
}
})
} catch (_: Throwable) {}
}
"getConnectionInfo" -> {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
if (!GlobalMockMemory.isEnabled) return
val pkg = resolveCallingPackage(param)
// 未知名或非模拟目标一律放行真实 Wi-Fi 连接信息
if (pkg.isNullOrBlank() || !GlobalMockMemory.shouldMock(pkg)) return
val wifiInfo = param.result ?: return
try {
// 抹去已连接 Wi-Fi 的物理 BSSID (MAC 地址),杜绝腾讯云端反查当前房间
XposedHelpers.setObjectField(wifiInfo, "mBSSID", "02:00:00:00:00:00")
XposedHelpers.setObjectField(wifiInfo, "mMacAddress", "02:00:00:00:00:00")
} catch (_: Throwable) {}
}
}) })
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
} }
} }
} }
}
/**
* 结合参数上下文与 Binder Calling UID 全面解析调用方真实包名
* 彻底解决 Android 11+ 参数抽象为 AttributionSource 导致的包名解析漏网问题
*/
private fun resolveCallingPackage(param: XC_MethodHook.MethodHookParam): String? {
val extracted = extractCallingPackage(param)
if (!extracted.isNullOrBlank()) {
return extracted
}
val uid = Binder.getCallingUid()
return getPackageNameForCallingUid(uid)
}
/**
* 在 system_server 内部通过 PackageManager 根据 Calling UID 反查首选包名
*/
private fun getPackageNameForCallingUid(uid: Int): String? {
if (uid == 1000 || uid == 0) return "android"
return try {
val appGlobalsClass = Class.forName("android.app.AppGlobals")
val pm = XposedHelpers.callStaticMethod(appGlobalsClass, "getPackageManager")
@Suppress("UNCHECKED_CAST")
val packages = XposedHelpers.callMethod(pm, "getPackagesForUid", uid) as? Array<String>
packages?.firstOrNull()
} catch (_: Throwable) {
null
}
}
/**
* 智能从参数和 Binder 调用上下文中提取真实的调用方应用包名(适配 Android 10 ~ 15)
*/
private fun extractCallingPackage(param: XC_MethodHook.MethodHookParam): String? { private fun extractCallingPackage(param: XC_MethodHook.MethodHookParam): String? {
val uid = Binder.getCallingUid()
if (uid == 1000 || uid == 0) {
// 系统进程自身调用,遍历参数提取实际代理包名
}
for (arg in param.args) { for (arg in param.args) {
if (arg is String && arg.contains(".") && !arg.contains("/")) { if (arg is String && arg.contains(".") && !arg.contains("/")) {
if (arg != "android.location.Location" && !arg.startsWith("android.location.") &&
arg != "gps" && arg != "network" && arg != "fused" && arg != "passive") {
return arg return arg
} }
}
if (arg != null && arg.javaClass.name.contains("AttributionSource")) { if (arg != null && arg.javaClass.name.contains("AttributionSource")) {
try { try {
val pkg = XposedHelpers.callMethod(arg, "getPackageName") as? String val pkg = XposedHelpers.callMethod(arg, "getPackageName") as? String
if (!pkg.isNullOrBlank()) return pkg if (!pkg.isNullOrBlank()) return pkg
} catch (_: Throwable) {} } catch (_: Throwable) {}
} }
if (arg != null && arg.javaClass.name.contains("CallerIdentity")) {
try {
val pkg = XposedHelpers.callMethod(arg, "getPackageName") as? String
if (!pkg.isNullOrBlank()) return pkg
} catch (_: Throwable) {}
}
} }
return null return null
} }
@@ -0,0 +1,110 @@
package com.lzxnone.openloc.hook.system
import android.app.Application
import android.content.Context
import com.lzxnone.openloc.hook.ipc.ConfigFetcher
import com.lzxnone.openloc.hook.model.GlobalMockMemory
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.XposedHelpers
/**
* 电话服务与基站注册核心拦截器(针对 com.android.phone)
* 核心目标:
* 从系统电话管理接口 (PhoneInterfaceManager) 彻底切断真实物理基站塔数据 (MCC, MNC, LAC, CID) 的输出,
* 杜绝云端利用附近基站指纹库反查出真实经纬度。
*/
object TelephonyRegistryHook {
@Volatile
private var phoneContext: Context? = null
fun hook(classLoader: ClassLoader) {
XposedBridge.log("[OpenLoc] Attaching TelephonyRegistryHook for com.android.phone...")
try {
XposedHelpers.findAndHookMethod(
Application::class.java,
"attach",
Context::class.java,
object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
if (phoneContext == null) {
phoneContext = param.args[0] as? Context
}
}
}
)
} catch (_: Throwable) {}
hookPhoneInterfaceManager(classLoader)
}
private fun hookPhoneInterfaceManager(classLoader: ClassLoader) {
val managerClass = try {
XposedHelpers.findClass("com.android.phone.PhoneInterfaceManager", classLoader)
} catch (_: Throwable) {
null
} ?: return
XposedBridge.log("[OpenLoc] Found PhoneInterfaceManager, hooking cell location APIs...")
for (method in managerClass.declaredMethods) {
when (method.name) {
"getAllCellInfo" -> {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
if (shouldBlock()) {
param.result = emptyList<Any>()
}
}
})
} catch (_: Throwable) {}
}
"getCellLocation" -> {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
if (shouldBlock()) {
param.result = null
}
}
})
} catch (_: Throwable) {}
}
"getNeighboringCellInfo" -> {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
if (shouldBlock()) {
param.result = emptyList<Any>()
}
}
})
} catch (_: Throwable) {}
}
"requestCellInfoUpdate", "requestCellInfoUpdateWithWorkSource" -> {
try {
XposedBridge.hookMethod(method, object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
if (shouldBlock()) {
param.result = null
}
}
})
} catch (_: Throwable) {}
}
}
}
}
private fun shouldBlock(): Boolean {
if (GlobalMockMemory.isEnabled) {
return true
}
val ctx = phoneContext ?: return false
val config = ConfigFetcher.getConfig(ctx)
return config.isEnabled
}
}
@@ -1,154 +0,0 @@
package com.lzxnone.openloc.hook.util
import android.location.Location
import android.location.LocationManager
import android.os.Build
import android.os.SystemClock
import de.robv.android.xposed.XposedHelpers
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sqrt
import kotlin.random.Random
/**
* 虚拟位置模拟生成与洗白工具
*/
object LocationSimulator {
@Volatile
private var driftOffsetX = 0.0 // meters (East-West)
@Volatile
private var driftOffsetY = 0.0 // meters (North-South)
@Volatile
private var lastDriftTime = 0L
@Volatile
private var currentBearing = 0.0f
@Volatile
private var currentSpeed = 0.0f
/**
* 计算并获取经过自然微漂移(平滑布朗运动)后的实时坐标
*/
@Synchronized
fun getSimulatedCoordinates(
latitude: Double,
longitude: Double,
isJitterEnabled: Boolean
): Pair<Double, Double> {
if (!isJitterEnabled) {
return Pair(latitude, longitude)
}
val now = SystemClock.elapsedRealtime()
val dt = if (lastDriftTime == 0L) 1.0 else ((now - lastDriftTime).coerceIn(100L, 5000L) / 1000.0)
lastDriftTime = now
// 随机步长(随时间平滑积累,约每秒 0.15~0.3m)
val stepStdDev = 0.20 * sqrt(dt)
val dX = (Random.nextDouble() - 0.5) * 2.0 * stepStdDev
val dY = (Random.nextDouble() - 0.5) * 2.0 * stepStdDev
// 类似弹簧向中心回拉,确保长期稳定在一个极小的真实扰动圆圈内(半径约 1.5 米以内)
val springFactor = 0.08 * dt
driftOffsetX = (driftOffsetX + dX) * (1.0 - springFactor)
driftOffsetY = (driftOffsetY + dY) * (1.0 - springFactor)
val dist = sqrt(driftOffsetX * driftOffsetX + driftOffsetY * driftOffsetY)
val maxRadius = 1.8 // 最大漂移半径 1.8 米
if (dist > maxRadius) {
driftOffsetX = (driftOffsetX / dist) * maxRadius
driftOffsetY = (driftOffsetY / dist) * maxRadius
}
// 米转换为纬度与经度增量
val metersPerLatDegree = 111132.92
val latRad = Math.toRadians(latitude)
val metersPerLngDegree = (111412.84 * cos(latRad)).coerceAtLeast(1.0)
val finalLat = latitude + (driftOffsetY / metersPerLatDegree)
val finalLng = longitude + (driftOffsetX / metersPerLngDegree)
// 计算微弱的自然速度和方向
currentSpeed = (dist * 0.04 + Random.nextDouble(0.01, 0.06)).toFloat()
if (dist > 0.15) {
currentBearing = ((Math.toDegrees(atan2(driftOffsetX, driftOffsetY)) + 360) % 360).toFloat()
}
return Pair(finalLat, finalLng)
}
/**
* 生成一个全新且各项指标逼真的 Location 实例
*/
fun createMockLocation(
latitude: Double,
longitude: Double,
provider: String = LocationManager.GPS_PROVIDER,
isJitterEnabled: Boolean = true
): Location {
return Location(provider).apply {
applyMockData(this, latitude, longitude, isJitterEnabled)
}
}
/**
* 将虚拟数据注入到现有的 Location 实例中,并彻底抹除 Mock 标志
*/
fun applyMockData(
location: Location,
latitude: Double,
longitude: Double,
isJitterEnabled: Boolean = true
) {
val (finalLat, finalLng) = getSimulatedCoordinates(latitude, longitude, isJitterEnabled)
val dist = sqrt(driftOffsetX * driftOffsetX + driftOffsetY * driftOffsetY)
location.latitude = finalLat
location.longitude = finalLng
location.altitude = if (isJitterEnabled) {
25.0 + (driftOffsetY * 0.1) + Random.nextDouble(-0.3, 0.3)
} else {
25.0
}
location.accuracy = if (isJitterEnabled) {
3.5f + (dist * 0.6f).toFloat() + Random.nextFloat() * 0.5f // 3.5m ~ 5.5m 真实波动
} else {
3.5f
}
location.speed = if (isJitterEnabled) currentSpeed else 0.0f
location.bearing = if (isJitterEnabled) currentBearing else 0.0f
location.time = System.currentTimeMillis()
location.elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
// 彻底洗白:抹除系统自带的 isFromMockProvider 标志
stripMockFlags(location)
}
/**
* 抹除 Location 对象上的所有模拟位置痕迹
*/
fun stripMockFlags(location: Location) {
try {
// Android 12 (API 31)+ 官方新增属性
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
location.isMock = false
}
// 针对各版本 Android 内部 mIsFromMockProvider 字段反射清洗
try {
XposedHelpers.setBooleanField(location, "mIsFromMockProvider", false)
} catch (_: Throwable) {}
try {
XposedHelpers.callMethod(location, "setIsFromMockProvider", false)
} catch (_: Throwable) {}
// Android 9+ (API 28)+ 内部的 mFieldsMask 标志位清洗
try {
val fieldsMask = XposedHelpers.getIntField(location, "mFieldsMask")
// 清除 HAS_MOCK_PROVIDER 标志位 (通常是 0x10 或类似)
XposedHelpers.setIntField(location, "mFieldsMask", fieldsMask and 0x10.inv())
} catch (_: Throwable) {}
} catch (_: Throwable) {}
}
}
@@ -1,276 +0,0 @@
package com.lzxnone.openloc.hook.util
import android.location.GnssStatus
import android.os.Build
import de.robv.android.xposed.XposedHelpers
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import kotlin.math.sin
import kotlin.random.Random
/**
* 全真多星座 GNSS 虚拟卫星仿真引擎
*
* 1. 提供覆盖全球及中国主流芯片的多星座卫星池(GPS、北斗、GLONASS、Galileo,共 26 颗)
* 2. 依据仰角几何球坐标动态生成符合物理传输衰减的载噪比 (C/N0, 18~42 dB-Hz) 与时变微弱抖动
* 3. 动态构建原生系统级 GnssStatus 实例(支持 Android 11+ Builder 与反射双重兜底)
* 4. 动态生成工业标准的 NMEA-0183 报文阵列($GNGGA, $GNRMC, $GNGSA, $BDGSA, $GPGSV, $BDGSV, $GLGSV)
*/
object VirtualGnssEngine {
data class VirtualSatellite(
val constellationType: Int,
val svid: Int,
val elevation: Float,
val azimuth: Float,
val carrierFrequencyHz: Float,
val usedInFix: Boolean
)
// 预设全真多星座卫星池(分布在 0~360° 方位角与 10~85° 仰角的完整半球星空)
private val SATELLITE_POOL = listOf(
// GPS (Constellation 1) - 8 颗,6 颗参与 Fix
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 3, 68f, 120f, 1575420000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 7, 42f, 280f, 1575420000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 14, 81f, 45f, 1575420000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 16, 25f, 190f, 1575420000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 22, 14f, 330f, 1575420000f, false),
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 27, 53f, 85f, 1575420000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 30, 32f, 240f, 1575420000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 31, 11f, 15f, 1575420000f, false),
// BDS 北斗 (Constellation 5) - 10 颗,8 颗参与 Fix (国内核心主力)
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 1, 40f, 140f, 1561098000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 6, 75f, 210f, 1561098000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 9, 58f, 60f, 1561098000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 13, 84f, 175f, 1561098000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 19, 30f, 310f, 1561098000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 21, 49f, 15f, 1561098000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 26, 63f, 105f, 1561098000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 33, 22f, 265f, 1561098000f, false),
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 35, 37f, 195f, 1561098000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 37, 12f, 80f, 1561098000f, false),
// GLONASS (Constellation 3) - 5 颗,4 颗参与 Fix
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 66, 55f, 350f, 1602000000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 71, 70f, 135f, 1602000000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 74, 38f, 225f, 1602000000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 82, 18f, 95f, 1602000000f, false),
VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 88, 28f, 170f, 1602000000f, true),
// GALILEO (Constellation 6) - 3 颗,2 颗参与 Fix
VirtualSatellite(GnssStatus.CONSTELLATION_GALILEO, 4, 64f, 290f, 1575420000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GALILEO, 12, 45f, 50f, 1575420000f, true),
VirtualSatellite(GnssStatus.CONSTELLATION_GALILEO, 19, 15f, 160f, 1575420000f, false)
)
private val timeFormat = SimpleDateFormat("HHmmss.SS", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
private val dateFormat = SimpleDateFormat("ddMMyy", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
/**
* 根据仰角计算符合真实物理衰减的 C/N0 载噪比(单位 dB-Hz)
*/
fun computeCn0(sat: VirtualSatellite): Float {
val elevRad = Math.toRadians(sat.elevation.toDouble())
val baseCn0 = 18.0 + 23.0 * sin(elevRad)
val noise = (Random.nextDouble() - 0.5) * 1.5
return (baseCn0 + noise).coerceIn(16.0, 42.5).toFloat()
}
/**
* 构建或获取原生系统的 GnssStatus 实例
*/
fun createGnssStatus(): GnssStatus? {
// 优先使用 Android 11+ (API 30+) 官方提供的 GnssStatus.Builder
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
try {
val builder = GnssStatus.Builder()
val addSatelliteMethod = builder.javaClass.methods.firstOrNull { it.name == "addSatellite" }
if (addSatelliteMethod != null) {
val paramCount = addSatelliteMethod.parameterTypes.size
for (sat in SATELLITE_POOL) {
val cn0 = computeCn0(sat)
if (paramCount >= 12) {
addSatelliteMethod.invoke(
builder,
sat.constellationType,
sat.svid,
cn0,
sat.elevation,
sat.azimuth,
true, // hasEphemeris
true, // hasAlmanac
sat.usedInFix,
true, // hasCarrierFrequency
sat.carrierFrequencyHz,
true, // hasBasebandCn0
(cn0 - 2.0f).coerceAtLeast(10.0f) // basebandCn0
)
} else {
addSatelliteMethod.invoke(
builder,
sat.constellationType,
sat.svid,
cn0,
sat.elevation,
sat.azimuth,
true, // hasEphemeris
true, // hasAlmanac
sat.usedInFix,
true, // hasCarrierFrequency
sat.carrierFrequencyHz
)
}
}
return builder.build()
}
} catch (_: Throwable) {}
}
// 低版本反射兜底(构造私有构造器)
return try {
val count = SATELLITE_POOL.size
val svidWithFlags = IntArray(count)
val cn0s = FloatArray(count)
val elevations = FloatArray(count)
val azimuths = FloatArray(count)
val carrierFreqs = FloatArray(count)
for (i in 0 until count) {
val sat = SATELLITE_POOL[i]
// 编码 svidWithFlags (AOSP 规范)
var flags = (sat.constellationType and 0x0F) shl 4
flags = flags or (sat.svid shl 8)
flags = flags or 1 // hasEphemeris
flags = flags or 2 // hasAlmanac
if (sat.usedInFix) flags = flags or 4
flags = flags or 8 // hasCarrierFrequency
svidWithFlags[i] = flags
cn0s[i] = computeCn0(sat)
elevations[i] = sat.elevation
azimuths[i] = sat.azimuth
carrierFreqs[i] = sat.carrierFrequencyHz
}
try {
// Android 10+ 构造函数含 carrierFrequencies
XposedHelpers.newInstance(
GnssStatus::class.java,
count,
svidWithFlags,
cn0s,
elevations,
azimuths,
carrierFreqs
) as? GnssStatus
} catch (_: Throwable) {
// Android 7~9 构造函数 5 参数
XposedHelpers.newInstance(
GnssStatus::class.java,
count,
svidWithFlags,
cn0s,
elevations,
azimuths
) as? GnssStatus
}
} catch (_: Throwable) {
null
}
}
/**
* 生成全套完整的工业级 NMEA-0183 报文序列(包含 GGA, RMC, GSA, GSV 多星座信标)
*/
fun generateFullNmeaSequence(lat: Double, lng: Double, time: Long): List<String> {
val result = mutableListOf<String>()
val utcTime = timeFormat.format(Date(time))
val dateStr = dateFormat.format(Date(time))
val latStr = formatToNmeaCoord(lat, true)
val lngStr = formatToNmeaCoord(lng, false)
val totalUsedSats = SATELLITE_POOL.count { it.usedInFix }
// 1. $GNGGA 定位解数据
val ggaContent = "GNGGA,$utcTime,$latStr,$lngStr,1,$totalUsedSats,0.8,25.0,M,0.0,M,,"
result.add("\$$ggaContent*${calculateChecksum(ggaContent)}\r\n")
// 2. $GNRMC 推荐最小导航数据
val rmcContent = "GNRMC,$utcTime,A,$latStr,$lngStr,0.0,0.0,$dateStr,,,A"
result.add("\$$rmcContent*${calculateChecksum(rmcContent)}\r\n")
// 3. $GNGSA (GPS 精度因子与解算卫星)
val gpsUsedSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_GPS && it.usedInFix }
val gpsPrnSlots = (0 until 12).map { index ->
if (index < gpsUsedSats.size) String.format(Locale.US, "%02d", gpsUsedSats[index].svid) else ""
}.joinToString(",")
val gsaGpsContent = "GNGSA,A,3,$gpsPrnSlots,1.2,0.8,0.9,1"
result.add("\$$gsaGpsContent*${calculateChecksum(gsaGpsContent)}\r\n")
// 4. $BDGSA (北斗精度因子与解算卫星)
val bdsUsedSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_BEIDOU && it.usedInFix }
val bdsPrnSlots = (0 until 12).map { index ->
if (index < bdsUsedSats.size) String.format(Locale.US, "%02d", bdsUsedSats[index].svid) else ""
}.joinToString(",")
val gsaBdsContent = "BDGSA,A,3,$bdsPrnSlots,1.2,0.8,0.9,4"
result.add("\$$gsaBdsContent*${calculateChecksum(gsaBdsContent)}\r\n")
// 5. $GPGSV (GPS 可见卫星星标,每页至多 4 颗)
val gpsSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_GPS }
appendGsvSentences("GPGSV", gpsSats, result)
// 6. $BDGSV (北斗可见卫星星标,每页至多 4 颗)
val bdsSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_BEIDOU }
appendGsvSentences("BDGSV", bdsSats, result)
// 7. $GLGSV (GLONASS 可见卫星星标,每页至多 4 颗)
val gloSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_GLONASS }
appendGsvSentences("GLGSV", gloSats, result)
return result
}
private fun appendGsvSentences(talker: String, sats: List<VirtualSatellite>, target: MutableList<String>) {
val totalSats = sats.size
val totalPages = (totalSats + 3) / 4
for (page in 1..totalPages) {
val chunk = sats.drop((page - 1) * 4).take(4)
val sb = java.lang.StringBuilder("$talker,$totalPages,$page,$totalSats")
for (s in chunk) {
val cn0 = computeCn0(s).toInt()
sb.append(String.format(Locale.US, ",%02d,%02d,%03d,%02d", s.svid, s.elevation.toInt(), s.azimuth.toInt(), cn0))
}
sb.append(",1") // 信号 ID (L1/B1)
val content = sb.toString()
target.add("\$$content*${calculateChecksum(content)}\r\n")
}
}
private fun formatToNmeaCoord(coord: Double, isLat: Boolean): String {
val abs = Math.abs(coord)
val degrees = abs.toInt()
val minutes = (abs - degrees) * 60.0
val direction = if (isLat) {
if (coord >= 0) "N" else "S"
} else {
if (coord >= 0) "E" else "W"
}
val coordFormat = if (isLat) "%02d%07.4f" else "%03d%07.4f"
return String.format(Locale.US, "$coordFormat,$direction", degrees, minutes)
}
private fun calculateChecksum(sentence: String): String {
var sum = 0
for (ch in sentence) {
sum = sum xor ch.code
}
return String.format(Locale.US, "%02X", sum)
}
}
@@ -153,14 +153,20 @@ fun AppSelectionScreen(
AppPreferences.whitelistApps AppPreferences.whitelistApps
} }
// 根据搜索词和系统应用开关进行过滤 // 根据搜索词、系统应用开关以及是否已选中进行过滤和排序(已选中的应用排在最上方)
val filteredApps = remember(installedApps, searchQuery, showSystemApps) { val filteredApps = remember(installedApps, searchQuery, showSystemApps, selectedPackages) {
installedApps.filter { app -> installedApps
.filter { app ->
(showSystemApps || !app.isSystemApp) && (showSystemApps || !app.isSystemApp) &&
(searchQuery.isBlank() || (searchQuery.isBlank() ||
app.appName.contains(searchQuery, ignoreCase = true) || app.appName.contains(searchQuery, ignoreCase = true) ||
app.packageName.contains(searchQuery, ignoreCase = true)) app.packageName.contains(searchQuery, ignoreCase = true))
} }
.sortedWith(
compareByDescending<InstalledAppItem> { selectedPackages.contains(it.packageName) }
.thenBy { it.isSystemApp }
.thenBy { it.appName.lowercase(Locale.ROOT) }
)
} }
// 标题与说明 // 标题与说明
@@ -374,6 +380,7 @@ fun AppSelectionScreen(
items(filteredApps, key = { it.packageName }) { app -> items(filteredApps, key = { it.packageName }) { app ->
val isChecked = selectedPackages.contains(app.packageName) val isChecked = selectedPackages.contains(app.packageName)
AppItemCard( AppItemCard(
modifier = Modifier.animateItem(),
app = app, app = app,
isChecked = isChecked, isChecked = isChecked,
onToggle = { onToggle = {
@@ -79,6 +79,8 @@ import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.material3.rememberModalBottomSheetState
@@ -173,8 +175,12 @@ fun LocationScreen(
val focusRequester = remember { FocusRequester() } val focusRequester = remember { FocusRequester() }
val searchHistory = AppPreferences.searchHistory val searchHistory = AppPreferences.searchHistory
// 当前展示在地图上的点 (GCJ-02 火星坐标,用于 OSMDroid 高德底图渲染)
val isServiceEnabled = AppPreferences.isServiceEnabled
var currentGeoPoint by remember { var currentGeoPoint by remember {
val gcj = CoordinateConverter.wgs84ToGcj02(AppPreferences.mockLatitude, AppPreferences.mockLongitude) val initialWgsLat = AppPreferences.mockLatitude
val initialWgsLng = AppPreferences.mockLongitude
val gcj = CoordinateConverter.wgs84ToGcj02(initialWgsLat, initialWgsLng)
mutableStateOf(GeoPoint(gcj[0], gcj[1])) mutableStateOf(GeoPoint(gcj[0], gcj[1]))
} }
var currentZoom by remember { mutableDoubleStateOf(15.0) } var currentZoom by remember { mutableDoubleStateOf(15.0) }
@@ -185,6 +191,103 @@ fun LocationScreen(
var mapViewRef by remember { mutableStateOf<MapView?>(null) } var mapViewRef by remember { mutableStateOf<MapView?>(null) }
var currentMarker by remember { mutableStateOf<Marker?>(null) } var currentMarker by remember { mutableStateOf<Marker?>(null) }
// 真实设备物理定位监听器(仅在总开关关闭时启动,总开关开启时严格注销)
val realLocationListener = remember {
object : LocationListener {
override fun onLocationChanged(loc: Location) {
// 仅当总开关处于关闭状态时,才响应物理定位更新并移动地图
if (!AppPreferences.isServiceEnabled) {
// 防脏缓存校验:确保不是残留的虚拟坐标
val isMockSuspicious = kotlin.math.abs(loc.latitude - AppPreferences.mockLatitude) < 1e-5 &&
kotlin.math.abs(loc.longitude - AppPreferences.mockLongitude) < 1e-5
if (!isMockSuspicious) {
// Android 官方规范:所有 Provider 吐出的原始定位数据全部为 WGS-84
val gcj = CoordinateConverter.wgs84ToGcj02(loc.latitude, loc.longitude)
val p = GeoPoint(gcj[0], gcj[1])
currentGeoPoint = p
currentMarker?.position = p
mapViewRef?.invalidate()
coroutineScope.launch {
val resolved = LocationResolver.resolveLocationName(context, loc.latitude, loc.longitude)
locationName = resolved
currentMarker?.title = resolved
}
}
}
}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
@Deprecated("Deprecated in Java")
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
}
}
// 单次主动获取真机物理真实定位(统一按 WGS-84 返回,绝不污染虚拟定位存储)
fun fetchRealLocationOnce(
lm: LocationManager,
onLocation: (wgsLat: Double, wgsLng: Double) -> Unit
) {
// 1. 优先读取系统缓存最新真实坐标 (0ms 即刻响应)
val gpsLoc = try { lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) } catch (_: Throwable) { null }
val netLoc = try { lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) } catch (_: Throwable) { null }
val fusedLoc = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
try { lm.getLastKnownLocation(LocationManager.FUSED_PROVIDER) } catch (_: Throwable) { null }
} else null
val candidates = listOfNotNull(gpsLoc, netLoc, fusedLoc)
val bestLoc = candidates.maxByOrNull { it.time }
if (bestLoc != null) {
// 防污染校验:若当前虚拟服务开启且缓存坐标与当前虚拟坐标一致,视为受污染残留缓存予以过滤
val isMockSuspicious = AppPreferences.isServiceEnabled &&
kotlin.math.abs(bestLoc.latitude - AppPreferences.mockLatitude) < 1e-5 &&
kotlin.math.abs(bestLoc.longitude - AppPreferences.mockLongitude) < 1e-5
if (!isMockSuspicious) {
onLocation(bestLoc.latitude, bestLoc.longitude)
}
}
// 2. 异步请求一次高精度真实单次定位更新(直达底层硬件芯片,获取纯净物理坐标)
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
val provider = when {
android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S && lm.isProviderEnabled(LocationManager.FUSED_PROVIDER) -> LocationManager.FUSED_PROVIDER
lm.isProviderEnabled(LocationManager.GPS_PROVIDER) -> LocationManager.GPS_PROVIDER
lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) -> LocationManager.NETWORK_PROVIDER
else -> LocationManager.PASSIVE_PROVIDER
}
lm.getCurrentLocation(provider, null, context.mainExecutor) { loc ->
if (loc != null) {
val isMockSuspicious = AppPreferences.isServiceEnabled &&
kotlin.math.abs(loc.latitude - AppPreferences.mockLatitude) < 1e-5 &&
kotlin.math.abs(loc.longitude - AppPreferences.mockLongitude) < 1e-5
if (!isMockSuspicious) {
onLocation(loc.latitude, loc.longitude)
}
}
}
} else {
@Suppress("DEPRECATION")
val singleListener = object : LocationListener {
override fun onLocationChanged(loc: Location) {
val isMockSuspicious = AppPreferences.isServiceEnabled &&
kotlin.math.abs(loc.latitude - AppPreferences.mockLatitude) < 1e-5 &&
kotlin.math.abs(loc.longitude - AppPreferences.mockLongitude) < 1e-5
if (!isMockSuspicious) {
onLocation(loc.latitude, loc.longitude)
}
try { lm.removeUpdates(this) } catch (_: Throwable) {}
}
override fun onProviderDisabled(p: String) {}
override fun onProviderEnabled(p: String) {}
override fun onStatusChanged(p: String?, s: Int, e: Bundle?) {}
}
val provider = if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) LocationManager.GPS_PROVIDER else LocationManager.NETWORK_PROVIDER
@Suppress("DEPRECATION")
lm.requestSingleUpdate(provider, singleListener, Looper.getMainLooper())
}
} catch (_: Throwable) {}
}
// 初始化 OSMDroid 配置(强制指定内部私有目录,避免外置存储权限异常) // 初始化 OSMDroid 配置(强制指定内部私有目录,避免外置存储权限异常)
DisposableEffect(Unit) { DisposableEffect(Unit) {
val basePath = java.io.File(context.cacheDir, "osmdroid") val basePath = java.io.File(context.cacheDir, "osmdroid")
@@ -192,10 +295,88 @@ fun LocationScreen(
Configuration.getInstance().osmdroidTileCache = java.io.File(basePath, "tiles") Configuration.getInstance().osmdroidTileCache = java.io.File(basePath, "tiles")
Configuration.getInstance().userAgentValue = context.packageName Configuration.getInstance().userAgentValue = context.packageName
onDispose { onDispose {
val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
try { lm?.removeUpdates(realLocationListener) } catch (_: Throwable) {}
mapViewRef?.onDetach() mapViewRef?.onDetach()
} }
} }
// 核心二元状态机:根据虚拟定位总开关 (isServiceEnabled) 切换定位模式
LaunchedEffect(isServiceEnabled) {
val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return@LaunchedEffect
val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if (isServiceEnabled) {
// ================= 【总开关开启】 =================
// 1. 立刻彻底注销并移除所有的物理真实定位监听,不再接收任何真机硬件坐标
try {
lm.removeUpdates(realLocationListener)
} catch (_: Throwable) {}
// 2. 检查是否为首次开启且从未手动选过点:若无历史选点,主动取一次真实定位作为初始点
if (!AppPreferences.hasUserSetLocation && (hasFine || hasCoarse)) {
fetchRealLocationOnce(lm) { realWgsLat, realWgsLng ->
val gcj = CoordinateConverter.wgs84ToGcj02(realWgsLat, realWgsLng)
val p = GeoPoint(gcj[0], gcj[1])
currentGeoPoint = p
currentMarker?.position = p
mapViewRef?.controller?.setCenter(p)
mapViewRef?.invalidate()
coroutineScope.launch {
val resolved = LocationResolver.resolveLocationName(context, realWgsLat, realWgsLng)
locationName = resolved
currentMarker?.title = resolved
AppPreferences.updateMockLocation(realWgsLat, realWgsLng, name = resolved, isUserManual = false)
}
}
} else {
// 3. 正常状态:地图上的位置就是我们 hook 的虚拟位置,锁定不变
val gcj = CoordinateConverter.wgs84ToGcj02(AppPreferences.mockLatitude, AppPreferences.mockLongitude)
val p = GeoPoint(gcj[0], gcj[1])
currentGeoPoint = p
currentMarker?.position = p
locationName = AppPreferences.mockLocationName.ifEmpty {
String.format(Locale.getDefault(), "%.5f, %.5f", AppPreferences.mockLatitude, AppPreferences.mockLongitude)
}
currentMarker?.title = locationName
mapViewRef?.controller?.animateTo(p)
mapViewRef?.invalidate()
}
} else {
// ================= 【总开关关闭】 =================
// 1. 关闭的一瞬间,立马主动获取一次真机真实坐标,拉回当前设备物理原位
if (hasFine || hasCoarse) {
fetchRealLocationOnce(lm) { realWgsLat, realWgsLng ->
val gcj = CoordinateConverter.wgs84ToGcj02(realWgsLat, realWgsLng)
val p = GeoPoint(gcj[0], gcj[1])
currentGeoPoint = p
currentMarker?.position = p
mapViewRef?.controller?.animateTo(p)
mapViewRef?.invalidate()
coroutineScope.launch {
val resolved = LocationResolver.resolveLocationName(context, realWgsLat, realWgsLng)
locationName = resolved
currentMarker?.title = resolved
}
}
// 2. 开启实时监听真实物理位置并在地图上显示(绝不调用 updateMockLocation 覆盖虚拟选点)
try {
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 1.0f, realLocationListener, Looper.getMainLooper())
}
if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 1.0f, realLocationListener, Looper.getMainLooper())
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S && lm.isProviderEnabled(LocationManager.FUSED_PROVIDER)) {
lm.requestLocationUpdates(LocationManager.FUSED_PROVIDER, 1000L, 1.0f, realLocationListener, Looper.getMainLooper())
}
} catch (_: Throwable) {}
}
}
}
// 搜索输入防抖监听 (400ms,感知搜索引擎和各Key的变化) // 搜索输入防抖监听 (400ms,感知搜索引擎和各Key的变化)
LaunchedEffect( LaunchedEffect(
searchQuery, searchQuery,
@@ -259,6 +440,9 @@ fun LocationScreen(
val coordFallback = String.format(Locale.getDefault(), "%.5f, %.5f", wgsLat, wgsLng) val coordFallback = String.format(Locale.getDefault(), "%.5f, %.5f", wgsLat, wgsLng)
locationName = coordFallback locationName = coordFallback
AppPreferences.updateMockLocation(wgsLat, wgsLng, name = coordFallback, isUserManual = isUserManual) AppPreferences.updateMockLocation(wgsLat, wgsLng, name = coordFallback, isUserManual = isUserManual)
if (!AppPreferences.isServiceEnabled) {
AppPreferences.updateServiceEnabled(true)
}
coroutineScope.launch { coroutineScope.launch {
val resolvedName = LocationResolver.resolveLocationName(context, wgsLat, wgsLng) val resolvedName = LocationResolver.resolveLocationName(context, wgsLat, wgsLng)
@@ -286,98 +470,45 @@ fun LocationScreen(
locationName = result.name locationName = result.name
currentMarker?.title = result.name currentMarker?.title = result.name
AppPreferences.updateMockLocation(result.latitude, result.longitude, name = result.name, isUserManual = true) AppPreferences.updateMockLocation(result.latitude, result.longitude, name = result.name, isUserManual = true)
} if (!AppPreferences.isServiceEnabled) {
AppPreferences.updateServiceEnabled(true)
// 定位到设备当前真实物理位置逻辑(例如在武汉则精确定位到武汉)
fun locateToDeviceRealPosition(animate: Boolean = true) {
val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return
val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if (hasFine || hasCoarse) {
val gpsLoc = try { lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) } catch (_: SecurityException) { null }
val netLoc = try { lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) } catch (_: SecurityException) { null }
val bestLoc = when {
gpsLoc != null && netLoc != null -> if (gpsLoc.time > netLoc.time) gpsLoc else netLoc
gpsLoc != null -> gpsLoc
netLoc != null -> netLoc
else -> null
}
if (bestLoc != null) {
// 真实硬件 GPS 返回 WGS-84,转换为 GCJ-02 精准标在高德瓦片上
val gcj = CoordinateConverter.wgs84ToGcj02(bestLoc.latitude, bestLoc.longitude)
updatePositionAndResolveName(
pointOnMap = GeoPoint(gcj[0], gcj[1]),
isUserManual = false,
centerMap = true,
animate = animate
)
}
// 异步刷新获取最新单次定位
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
lm.getCurrentLocation(
LocationManager.NETWORK_PROVIDER,
null,
context.mainExecutor
) { loc ->
if (loc != null) {
val gcj = CoordinateConverter.wgs84ToGcj02(loc.latitude, loc.longitude)
updatePositionAndResolveName(
pointOnMap = GeoPoint(gcj[0], gcj[1]),
isUserManual = false,
centerMap = true,
animate = true
)
}
}
} else {
@Suppress("DEPRECATION")
val singleListener = object : LocationListener {
override fun onLocationChanged(loc: Location) {
val gcj = CoordinateConverter.wgs84ToGcj02(loc.latitude, loc.longitude)
updatePositionAndResolveName(
pointOnMap = GeoPoint(gcj[0], gcj[1]),
isUserManual = false,
centerMap = true,
animate = true
)
try { lm.removeUpdates(this) } catch (_: Throwable) {}
}
override fun onProviderDisabled(p: String) {}
override fun onProviderEnabled(p: String) {}
override fun onStatusChanged(p: String?, s: Int, e: Bundle?) {}
}
if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
@Suppress("DEPRECATION")
lm.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, singleListener, Looper.getMainLooper())
}
}
} catch (_: SecurityException) {}
} }
} }
// 权限请求器(用户点击“回到原位”按钮或首次进入时按需触发) // 点击“回到原位”按钮处理逻辑
val onResetToRealLocation: () -> Unit = {
val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
if (lm != null) {
Toast.makeText(context, "正在获取设备物理定位...", Toast.LENGTH_SHORT).show()
fetchRealLocationOnce(lm) { realWgsLat, realWgsLng ->
val gcj = CoordinateConverter.wgs84ToGcj02(realWgsLat, realWgsLng)
val p = GeoPoint(gcj[0], gcj[1])
currentGeoPoint = p
currentMarker?.position = p
mapViewRef?.controller?.animateTo(p)
mapViewRef?.invalidate()
coroutineScope.launch {
val resolved = LocationResolver.resolveLocationName(context, realWgsLat, realWgsLng)
locationName = resolved
currentMarker?.title = resolved
// 若当前总开关开启,点击回到原位意味着用户希望将虚拟位置设定为当前真实物理位置
if (AppPreferences.isServiceEnabled) {
AppPreferences.updateMockLocation(realWgsLat, realWgsLng, name = resolved, isUserManual = true)
}
}
Toast.makeText(context, context.getString(R.string.location_located_to_real), Toast.LENGTH_SHORT).show()
}
}
}
// 权限请求器(用户点击“回到原位”按钮按需触发)
val permissionLauncher = rememberLauncherForActivityResult( val permissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestMultiplePermissions() ActivityResultContracts.RequestMultiplePermissions()
) { permissions -> ) { permissions ->
val granted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true || val granted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true ||
permissions[Manifest.permission.ACCESS_COARSE_LOCATION] == true permissions[Manifest.permission.ACCESS_COARSE_LOCATION] == true
if (granted) { if (granted) {
locateToDeviceRealPosition(animate = true) onResetToRealLocation()
}
}
// 若已获得定位权限且用户从未手动挑选过位置,自动校准定位至当前设备物理位置
LaunchedEffect(Unit) {
val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if ((hasFine || hasCoarse) && !AppPreferences.hasUserSetLocation) {
locateToDeviceRealPosition(animate = false)
} }
} }
@@ -478,7 +609,7 @@ fun LocationScreen(
val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if (hasFine || hasCoarse) { if (hasFine || hasCoarse) {
locateToDeviceRealPosition(animate = true) onResetToRealLocation()
} else { } else {
permissionLauncher.launch( permissionLauncher.launch(
arrayOf( arrayOf(
@@ -574,6 +705,43 @@ fun LocationScreen(
} }
} }
// 虚拟定位总开关控制与状态展示(可直接在地图页一键开启或关闭)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 4.dp, bottom = 2.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Surface(
shape = RoundedCornerShape(8.dp),
color = if (isServiceEnabled) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.6f) else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
) {
Text(
text = if (isServiceEnabled) "虚拟定位生效中" else "真机实时定位中",
style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.Bold),
color = if (isServiceEnabled) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp)
)
}
Switch(
checked = isServiceEnabled,
onCheckedChange = { checked ->
AppPreferences.updateServiceEnabled(checked)
Toast.makeText(
context,
if (checked) "虚拟定位已开启" else "已回退真实定位",
Toast.LENGTH_SHORT
).show()
},
colors = SwitchDefaults.colors(
checkedThumbColor = MaterialTheme.colorScheme.onPrimary,
checkedTrackColor = MaterialTheme.colorScheme.primary
)
)
}
// 经纬度信息与复制按钮 (折叠时隐藏) // 经纬度信息与复制按钮 (折叠时隐藏)
AnimatedVisibility( AnimatedVisibility(
visible = !isCardCollapsed, visible = !isCardCollapsed,
@@ -400,102 +400,6 @@ fun SettingsScreen(
} }
} }
} }
// ------------------ 4. 防检测与真实度增强板块 ------------------
Text(
text = stringResource(id = R.string.settings_category_anti_detection),
style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold),
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(start = 4.dp, top = 8.dp)
)
Card(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
) {
Column {
// (1) 位置自然微漂移
SettingSwitchItem(
title = stringResource(id = R.string.settings_anti_jitter_title),
description = stringResource(id = R.string.settings_anti_jitter_desc),
icon = Icons.Filled.Explore,
checked = AppPreferences.isJitterEnabled,
onCheckedChange = { AppPreferences.updateJitterEnabled(it) }
)
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
modifier = Modifier.padding(horizontal = 16.dp)
)
// (2) 全真多星座卫星仿真
SettingSwitchItem(
title = stringResource(id = R.string.settings_anti_gnss_title),
description = stringResource(id = R.string.settings_anti_gnss_desc),
icon = Icons.Filled.SatelliteAlt,
checked = AppPreferences.isGnssSimulationEnabled,
onCheckedChange = { AppPreferences.updateGnssSimulationEnabled(it) }
)
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
modifier = Modifier.padding(horizontal = 16.dp)
)
// (3) 基站与 Wi-Fi 防反查
SettingSwitchItem(
title = stringResource(id = R.string.settings_anti_network_title),
description = stringResource(id = R.string.settings_anti_network_desc),
icon = Icons.Filled.CellTower,
checked = AppPreferences.isNetworkCamouflageEnabled,
onCheckedChange = { AppPreferences.updateNetworkCamouflageEnabled(it) }
)
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
modifier = Modifier.padding(horizontal = 16.dp)
)
// (4) 传感器手持生理拟真
SettingSwitchItem(
title = stringResource(id = R.string.settings_anti_sensor_title),
description = stringResource(id = R.string.settings_anti_sensor_desc),
icon = Icons.Filled.Vibration,
checked = AppPreferences.isSensorSimulationEnabled,
onCheckedChange = { AppPreferences.updateSensorSimulationEnabled(it) }
)
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
modifier = Modifier.padding(horizontal = 16.dp)
)
// (5) 堆栈与模块自隐匿
SettingSwitchItem(
title = stringResource(id = R.string.settings_anti_stealth_title),
description = stringResource(id = R.string.settings_anti_stealth_desc),
icon = Icons.Filled.Security,
checked = AppPreferences.isStealthEnabled,
onCheckedChange = { AppPreferences.updateStealthEnabled(it) }
)
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f),
modifier = Modifier.padding(horizontal = 16.dp)
)
// (6) 开发者选项伪装
SettingSwitchItem(
title = stringResource(id = R.string.settings_anti_dev_title),
description = stringResource(id = R.string.settings_anti_dev_desc),
icon = Icons.Filled.DeveloperMode,
checked = AppPreferences.isDevCamouflageEnabled,
onCheckedChange = { AppPreferences.updateDevCamouflageEnabled(it) }
)
}
}
} }
// ------------------ 搜索引擎提供商选择底部抽屉 (ModalBottomSheet) ------------------ // ------------------ 搜索引擎提供商选择底部抽屉 (ModalBottomSheet) ------------------
+14 -2
View File
@@ -1,9 +1,21 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string-array name="xposed_scope"> <string-array name="xposed_scope">
<!-- 勾选 Android 系统实现整机全局免指定拦截 --> <!-- 核心系统框架 -->
<item>android</item> <item>android</item>
<!-- 勾选模块自身实现激活状态自检 --> <!-- 模块自身激活自检 -->
<item>com.lzxnone.openloc</item> <item>com.lzxnone.openloc</item>
<!-- 小米 MIUI / HyperOS 独立高精融合定位守护进程(小米机型核心命门) -->
<item>com.xiaomi.location.fused</item>
<!-- 小米网络定位服务 (Metok NLP,基站与Wi-Fi定位核心) -->
<item>com.xiaomi.metoknlp</item>
<!-- Android 原生与高通底层系统融合定位守护进程 -->
<item>com.android.location.fused</item>
<!-- OPPO / 一加自研系统融合定位守护进程 -->
<item>com.oplus.location</item>
<!-- 电话与基站管理服务(阻断硬件基站塔反查) -->
<item>com.android.phone</item>
<!-- 蓝牙 BLE 信标扫描服务(阻断商场 iBeacon 反查) -->
<item>com.android.bluetooth</item>
</string-array> </string-array>
</resources> </resources>