file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
XFusedLocationApi.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XFusedLocationApi.java
package biz.bokhorst.xprivacy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import android.app.PendingIntent; import android.location.Location; import android.os.Binder; import android.util.Log; public class XFusedLocationApi extends XHook { private Methods mMethod; private String mClassName; private static final Map<Object, Object> mMapProxy = new WeakHashMap<Object, Object>(); private XFusedLocationApi(Methods method, String restrictionName, String className) { super(restrictionName, method.name(), "GMS5." + method.name()); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // Location getLastLocation(GoogleApiClient client) // abstract PendingResult<Status> removeLocationUpdates(GoogleApiClient client, LocationListener listener) // abstract PendingResult<Status> removeLocationUpdates(GoogleApiClient client, PendingIntent callbackIntent) // abstract PendingResult<Status> requestLocationUpdates(GoogleApiClient client, LocationRequest request, LocationListener listener, Looper looper) // abstract PendingResult<Status> requestLocationUpdates(GoogleApiClient client, LocationRequest request, LocationListener listener) // abstract PendingResult<Status> requestLocationUpdates(GoogleApiClient client, LocationRequest request, PendingIntent callbackIntent) // https://developer.android.com/reference/com/google/android/gms/location/FusedLocationProviderApi.html // @formatter:on private enum Methods { getLastLocation, removeLocationUpdates, requestLocationUpdates }; public static List<XHook> getInstances(Object instance) { String className = instance.getClass().getName(); Util.log(null, Log.INFO, "Hooking FusedLocationApi class=" + className + " uid=" + Binder.getCallingUid()); List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XFusedLocationApi(Methods.getLastLocation, PrivacyManager.cLocation, className)); listHook.add(new XFusedLocationApi(Methods.removeLocationUpdates, null, className)); listHook.add(new XFusedLocationApi(Methods.requestLocationUpdates, PrivacyManager.cLocation, className)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case getLastLocation: // Do nothing break; case removeLocationUpdates: if (param.args.length > 1) if (param.args[1] instanceof PendingIntent) { if (isRestricted(param, PrivacyManager.cLocation, "GMS5.requestLocationUpdates")) param.setResult(XGoogleApiClient.getPendingResult(param.thisObject.getClass().getClassLoader())); } else synchronized (mMapProxy) { if (mMapProxy.containsKey(param.args[1])) param.args[1] = mMapProxy.get(param.args[1]); } break; case requestLocationUpdates: if (param.args.length > 2) if (isRestricted(param)) if (param.args[2] instanceof PendingIntent) param.setResult(XGoogleApiClient.getPendingResult(param.thisObject.getClass().getClassLoader())); else if (param.thisObject != null && param.args[2] != null) { // Create proxy ClassLoader cl = param.thisObject.getClass().getClassLoader(); Class<?> ll = Class.forName("com.google.android.gms.location.LocationListener", false, cl); InvocationHandler ih = new OnLocationChangedHandler(Binder.getCallingUid(), param.args[2]); Object proxy = Proxy.newProxyInstance(cl, new Class<?>[] { ll }, ih); // Use proxy synchronized (mMapProxy) { mMapProxy.put(param.args[2], proxy); } param.args[2] = proxy; } break; } } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case getLastLocation: Location location = (Location) param.getResult(); if (location != null && isRestricted(param)) param.setResult(PrivacyManager.getDefacedLocation(Binder.getCallingUid(), location)); break; case removeLocationUpdates: case requestLocationUpdates: // Do nothing break; } } private class OnLocationChangedHandler implements InvocationHandler { private int mUid; private Object mTarget; public OnLocationChangedHandler(int uid, Object target) { mUid = uid; mTarget = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("onLocationChanged".equals(method.getName())) args[0] = PrivacyManager.getDefacedLocation(mUid, (Location) args[0]); return method.invoke(mTarget, args); } } }
4,665
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XIpPrefix.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XIpPrefix.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Binder; import biz.bokhorst.xprivacy.XHook; public class XIpPrefix extends XHook { private Methods mMethod; private XIpPrefix(Methods method, String restrictionName) { super(restrictionName, method.name(), "IpPrefix." + method.name()); mMethod = method; } public String getClassName() { return "android.net.IpPrefix"; } // public InetAddress getAddress() // public byte[] getRawAddress() // https://developer.android.com/reference/android/net/IpPrefix.html // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/android/net/IpPrefix.java private enum Methods { getAddress, getRawAddress }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XIpPrefix(Methods.getAddress, PrivacyManager.cInternet)); listHook.add(new XIpPrefix(Methods.getRawAddress, PrivacyManager.cInternet)); return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case getAddress: if (isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), "InetAddress")); break; case getRawAddress: if (param.getResult() != null) if (isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), "IPInt")); break; } } }
1,545
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
Hook.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/Hook.java
package biz.bokhorst.xprivacy; import android.annotation.SuppressLint; import android.os.Build; public class Hook implements Comparable<Hook> { private String mRestrictionName; private String mMethodName; private String[] mPermissions; private int mSdkFrom; private int mSdkTo = Integer.MAX_VALUE; private Version mFrom; private String mReplacedRestriction; private String mReplacedMethod; private boolean mDangerous = false; private boolean mRestart = false; private boolean mNoUsageData = false; private boolean mNoOnDemand = false; private String mWhitelist = null; private boolean mNotify = false; private int mAOSPSdk = 0; private int mNotAOSPSdk = 0; private boolean mUnsafe = false; private boolean mOptional = false; private boolean mObsolete = false; private String mAnnotation = null; public Hook(String restrictionName, String methodName) { mRestrictionName = restrictionName; mMethodName = methodName; } public Hook(String restrictionName, String methodName, String permissions, int sdk, String from, String replaces) { mRestrictionName = restrictionName; mMethodName = methodName; mPermissions = (permissions == null ? null : permissions.split(",")); mSdkFrom = sdk; mFrom = (from == null ? null : new Version(from)); if (replaces != null) { int slash = replaces.indexOf('/'); if (slash > 0) { mReplacedRestriction = replaces.substring(0, slash); mReplacedMethod = replaces.substring(slash + 1); if ("".equals(mReplacedMethod)) mReplacedMethod = methodName; } else { mReplacedRestriction = mRestrictionName; mReplacedMethod = replaces; } } } // Definitions public Hook to(int sdk) { mSdkTo = sdk; return this; } public Hook dangerous() { mDangerous = true; return this; } @SuppressLint("FieldGetter") public void toggleDangerous() { String name = String.format("%s.%s.%s", PrivacyManager.cSettingDangerous, this.getRestrictionName(), this.getName()); PrivacyManager.setSetting(0, name, Boolean.toString(!isDangerous())); } public Hook restart() { mRestart = true; return this; } public Hook noUsageData() { mNoUsageData = true; return this; } public Hook noOnDemand() { mNoOnDemand = true; return this; } public Hook whitelist(String whitelist) { mWhitelist = whitelist; return this; } public Hook doNotify() { mNotify = true; return this; } public Hook AOSP(int sdk) { mAOSPSdk = sdk; return this; } public Hook notAOSP(int sdk) { mNotAOSPSdk = sdk; if (!PrivacyManager.cIPC.equals(mRestrictionName)) mUnsafe = true; return this; } public Hook unsafe() { mUnsafe = true; return this; } protected Hook optional() { mOptional = true; return this; } protected Hook obsolete() { mObsolete = true; return this; } public void annotate(String text) { mAnnotation = text; } // Getters public String getRestrictionName() { return mRestrictionName; } public String getName() { return mMethodName; } public String[] getPermissions() { return mPermissions; } public boolean isAvailable() { if (mObsolete) return false; if (Build.VERSION.SDK_INT < mSdkFrom) return false; if (Build.VERSION.SDK_INT > mSdkTo) return false; if (mAOSPSdk > 0 && !isAOSP(mAOSPSdk)) return false; if (mNotAOSPSdk > 0 && isAOSP(mNotAOSPSdk)) return false; return true; } public static boolean isAOSP(int sdk) { if (!PrivacyManager.cVersion3) return false; if (Build.VERSION.SDK_INT >= sdk) { if ("true".equals(System.getenv("XPrivacy.AOSP"))) return true; if (Build.DISPLAY == null || Build.HOST == null) return false; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) // @formatter:off return ( isAOSP() || isCyanogenMod() || isOmni() || isMIUI() || isSlim() || isParanoidAndroid() || isCarbon() || isDirtyUnicorns() || isLiquidSmooth() || isAndroidRevolutionHD() || isMahdi() || isOmega() ); // @formatter:on else return isAOSP(); } else return false; } public static boolean isAOSP() { return Build.HOST.endsWith(".google.com"); } public static boolean isCyanogenMod() { return Build.HOST.equals("cyanogenmod") || Build.DISPLAY.startsWith("cm_"); } public static boolean isOmni() { return Build.DISPLAY.startsWith("slim"); } public static boolean isMIUI() { return Build.HOST.equals("xiaomi"); } public static boolean isSlim() { return Build.DISPLAY.startsWith("omni"); } public static boolean isParanoidAndroid() { return Build.HOST.startsWith("paranoid") || Build.DISPLAY.startsWith("pa_"); } public static boolean isCarbon() { return Build.DISPLAY.startsWith("carbon"); } public static boolean isDirtyUnicorns() { return Build.DISPLAY.startsWith("du_"); } public static boolean isLiquidSmooth() { return Build.DISPLAY.startsWith("liquid_"); } public static boolean isAndroidRevolutionHD() { return Build.DISPLAY.startsWith("Android Revolution HD"); } public static boolean isMahdi() { return Build.HOST.startsWith("mahdi"); } public static boolean isOmega() { return Build.DISPLAY.startsWith("Omega"); } public Version getFrom() { return mFrom; } public String getReplacedRestriction() { return mReplacedRestriction; } public String getReplacedMethod() { return mReplacedMethod; } @SuppressLint("FieldGetter") public boolean isDangerous() { String name = String.format("%s.%s.%s", PrivacyManager.cSettingDangerous, this.getRestrictionName(), this.getName()); return PrivacyManager.getSettingBool(0, name, mDangerous); } public boolean isDangerousDefined() { return mDangerous; } public boolean isRestartRequired() { return mRestart; } public boolean hasUsageData() { return !mNoUsageData; } public boolean canOnDemand() { return !mNoOnDemand; } public String whitelist() { return mWhitelist; } public boolean shouldNotify() { return mNotify; } public boolean isUnsafe() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) return false; if (PrivacyManager.cVersion3) return mUnsafe; else return false; } public boolean isOptional() { return mOptional; } public String getAnnotation() { return mAnnotation; } // Comparison @Override public int hashCode() { return (mRestrictionName.hashCode() ^ mMethodName.hashCode()); } @Override public boolean equals(Object obj) { Hook other = (Hook) obj; return (mRestrictionName.equals(other.mRestrictionName) && mMethodName.equals(other.mMethodName)); } @Override public int compareTo(Hook another) { int x = mRestrictionName.compareTo(another.mRestrictionName); return (x == 0 ? mMethodName.compareTo(another.mMethodName) : x); } @Override public String toString() { return String.format("%s/%s", mRestrictionName, mMethodName); } }
6,914
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XActivityRecognitionApi.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XActivityRecognitionApi.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Binder; import android.util.Log; public class XActivityRecognitionApi extends XHook { private Methods mMethod; private String mClassName; private XActivityRecognitionApi(Methods method, String restrictionName, String className) { super(restrictionName, method.name(), "GMS5." + method.name()); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // Location getLastLocation(GoogleApiClient client) // abstract PendingResult<Status> removeActivityUpdates(GoogleApiClient client, PendingIntent callbackIntent) // abstract PendingResult<Status> requestActivityUpdates(GoogleApiClient client, long detectionIntervalMillis, PendingIntent callbackIntent) // https://developer.android.com/reference/com/google/android/gms/location/ActivityRecognitionApi.html // @formatter:on private enum Methods { removeActivityUpdates, requestActivityUpdates }; public static List<XHook> getInstances(Object instance) { String className = instance.getClass().getName(); Util.log(null, Log.INFO, "Hooking ActivityRecognitionApi class=" + className + " uid=" + Binder.getCallingUid()); List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XActivityRecognitionApi(Methods.removeActivityUpdates, null, className)); listHook.add(new XActivityRecognitionApi(Methods.requestActivityUpdates, PrivacyManager.cLocation, className)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case removeActivityUpdates: if (isRestricted(param, PrivacyManager.cLocation, "GMS5.requestActivityUpdates")) param.setResult(XGoogleApiClient.getPendingResult(param.thisObject.getClass().getClassLoader())); break; case requestActivityUpdates: if (isRestricted(param)) param.setResult(XGoogleApiClient.getPendingResult(param.thisObject.getClass().getClassLoader())); break; } } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
2,127
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XAppWidgetManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XAppWidgetManager.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.appwidget.AppWidgetProviderInfo; import android.os.Build; public class XAppWidgetManager extends XHook { private Methods mMethod; private String mClassName; private XAppWidgetManager(Methods method, String restrictionName) { super(restrictionName, method.name().replace("Srv_", ""), method.name()); mMethod = method; if (method.name().startsWith("Srv_")) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) mClassName = "com.android.server.appwidget.AppWidgetServiceImpl"; else mClassName = "com.android.server.AppWidgetService"; else mClassName = "android.appwidget.AppWidgetManager"; } public String getClassName() { return mClassName; } // @formatter:off // public List<AppWidgetProviderInfo> getInstalledProviders() // public List<AppWidgetProviderInfo> getInstalledProvidersForProfile(UserHandle profile) // frameworks/base/core/java/android/appwidget/AppWidgetManager.java // http://developer.android.com/reference/android/appwidget/AppWidgetManager.html // public List<AppWidgetProviderInfo> getInstalledProviders(int categoryFilter, int userId) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.4_r1/com/android/server/AppWidgetService.java // @formatter:on private enum Methods { getInstalledProviders, getInstalledProvidersForProfile, Srv_getInstalledProviders, Srv_getInstalledProvidersForProfile }; public static List<XHook> getInstances(boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (server) { listHook.add(new XAppWidgetManager(Methods.Srv_getInstalledProviders, PrivacyManager.cSystem)); listHook.add(new XAppWidgetManager(Methods.Srv_getInstalledProvidersForProfile, PrivacyManager.cSystem)); } else { listHook.add(new XAppWidgetManager(Methods.getInstalledProviders, PrivacyManager.cSystem)); listHook.add(new XAppWidgetManager(Methods.getInstalledProvidersForProfile, PrivacyManager.cSystem)); } return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case getInstalledProviders: case getInstalledProvidersForProfile: case Srv_getInstalledProviders: case Srv_getInstalledProvidersForProfile: if (param.getResult() != null) if (isRestricted(param)) param.setResult(new ArrayList<AppWidgetProviderInfo>()); break; } } }
2,548
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
PrivacyService.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/PrivacyService.java
package biz.bokhorst.xprivacy; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.graphics.PixelFormat; import android.net.Uri; import android.os.Binder; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Process; import android.os.RemoteException; import android.os.StrictMode; import android.os.SystemClock; import android.os.StrictMode.ThreadPolicy; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.util.Log; import android.util.Patterns; import android.util.SparseArray; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; public class PrivacyService extends IPrivacyService.Stub { private static int mXUid = -1; private static Object mAm; private static Context mContext; private static String mSecret = null; private static Thread mWorker = null; private static Handler mHandler = null; private static long mOnDemandLastAnswer = 0; private static Semaphore mOndemandSemaphore = new Semaphore(1, true); private static List<String> mListError = new ArrayList<String>(); private static IPrivacyService mClient = null; private static final String cTableRestriction = "restriction"; private static final String cTableUsage = "usage"; private static final String cTableSetting = "setting"; private static final int cCurrentVersion = 481; private static final String cServiceName = "xprivacy481"; private boolean mCorrupt = false; private boolean mNotified = false; private SQLiteDatabase mDb = null; private SQLiteDatabase mDbUsage = null; private SQLiteStatement stmtGetRestriction = null; private SQLiteStatement stmtGetSetting = null; private SQLiteStatement stmtGetUsageRestriction = null; private SQLiteStatement stmtGetUsageMethod = null; private ReentrantReadWriteLock mLock = new ReentrantReadWriteLock(true); private ReentrantReadWriteLock mLockUsage = new ReentrantReadWriteLock(true); private AtomicLong mCount = new AtomicLong(0); private AtomicLong mRestricted = new AtomicLong(0); private Map<CSetting, CSetting> mSettingCache = new HashMap<CSetting, CSetting>(); private Map<CRestriction, CRestriction> mAskedOnceCache = new HashMap<CRestriction, CRestriction>(); private Map<CRestriction, CRestriction> mRestrictionCache = new HashMap<CRestriction, CRestriction>(); private final long cMaxUsageDataHours = 12; private final int cMaxUsageDataCount = 700; private final int cMaxOnDemandDialog = 20; // seconds private ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new PriorityThreadFactory()); final class PriorityThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; } } // sqlite3 /data/system/xprivacy/xprivacy.db private PrivacyService() { } private static PrivacyService mPrivacyService = null; private static String getServiceName() { return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? "user." : "") + cServiceName; } public static void register(List<String> listError, ClassLoader classLoader, String secret, Object am) { // Store secret and errors mAm = am; mSecret = secret; mListError.addAll(listError); try { // Register privacy service mPrivacyService = new PrivacyService(); // @formatter:off // public static void addService(String name, IBinder service) // public static void addService(String name, IBinder service, boolean allowIsolated) // @formatter:on // Requires this in /service_contexts // xprivacy453 u:object_r:system_server_service:s0 Class<?> cServiceManager = Class.forName("android.os.ServiceManager", false, classLoader); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class, boolean.class); mAddService.invoke(null, getServiceName(), mPrivacyService, true); } else { Method mAddService = cServiceManager.getDeclaredMethod("addService", String.class, IBinder.class); mAddService.invoke(null, getServiceName(), mPrivacyService); } // This will and should open the database Util.log(null, Log.WARN, "Service registered name=" + getServiceName() + " version=" + cCurrentVersion); // Publish semaphore to activity manager service XActivityManagerService.setSemaphore(mOndemandSemaphore); // Get context if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Field fContext = null; Class<?> cam = am.getClass(); while (cam != null && fContext == null) try { fContext = cam.getDeclaredField("mContext"); } catch (NoSuchFieldException ignored) { cam = cam.getSuperclass(); } if (fContext == null) Util.log(null, Log.ERROR, am.getClass().getName() + ".mContext not found"); else { fContext.setAccessible(true); mContext = (Context) fContext.get(am); } } // Start a worker thread mWorker = new Thread(new Runnable() { @Override public void run() { try { Looper.prepare(); mHandler = new Handler(); Looper.loop(); } catch (Throwable ex) { Util.bug(null, ex); } } }); mWorker.start(); } catch (Throwable ex) { Util.bug(null, ex); } } public static boolean isRegistered() { return (mPrivacyService != null); } public static boolean checkClient() { // Runs client side try { IPrivacyService client = getClient(); if (client != null) return (client.getVersion() == cCurrentVersion); } catch (SecurityException ignored) { } catch (Throwable ex) { Util.bug(null, ex); } return false; } public static IPrivacyService getClient() { // Runs client side if (mClient == null) try { // public static IBinder getService(String name) Class<?> cServiceManager = Class.forName("android.os.ServiceManager"); Method mGetService = cServiceManager.getDeclaredMethod("getService", String.class); mClient = IPrivacyService.Stub.asInterface((IBinder) mGetService.invoke(null, getServiceName())); } catch (Throwable ex) { Util.bug(null, ex); } return mClient; } public static void reportErrorInternal(String message) { synchronized (mListError) { mListError.add(message); } } public static PRestriction getRestrictionProxy(final PRestriction restriction, boolean usage, String secret) throws RemoteException { if (isRegistered()) return mPrivacyService.getRestriction(restriction, usage, secret); else { IPrivacyService client = getClient(); if (client == null) { Log.w("XPrivacy", "No client for " + restriction); PRestriction result = new PRestriction(restriction); result.restricted = false; return result; } else return client.getRestriction(restriction, usage, secret); } } public static PSetting getSettingProxy(PSetting setting) throws RemoteException { if (isRegistered()) return mPrivacyService.getSetting(setting); else { IPrivacyService client = getClient(); if (client == null) { Log.w("XPrivacy", "No client for " + setting + " uid=" + Process.myUid() + " pid=" + Process.myPid()); Log.w("XPrivacy", Log.getStackTraceString(new Exception("StackTrace"))); return setting; } else return client.getSetting(setting); } } // Management @Override public int getVersion() throws RemoteException { enforcePermission(-1); return cCurrentVersion; } @Override public List<String> check() throws RemoteException { enforcePermission(-1); List<String> listError = new ArrayList<String>(); synchronized (mListError) { int c = 0; int i = 0; while (i < mListError.size()) { String msg = mListError.get(i); c += msg.length(); if (c < 10000) listError.add(msg); else break; i++; } } return listError; } @Override public boolean databaseCorrupt() { return mCorrupt; } @Override public void reportError(String message) throws RemoteException { reportErrorInternal(message); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Map getStatistics() throws RemoteException { Map map = new HashMap(); map.put("restriction_count", mCount.longValue()); map.put("restriction_restricted", mRestricted.longValue()); map.put("uptime_milliseconds", SystemClock.elapsedRealtime()); return map; }; // Restrictions @Override public void setRestriction(PRestriction restriction) throws RemoteException { try { enforcePermission(restriction.uid); setRestrictionInternal(restriction); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setRestrictionInternal(PRestriction restriction) throws RemoteException { // Validate if (restriction.restrictionName == null) { Util.log(null, Log.ERROR, "Set invalid restriction " + restriction); Util.logStack(null, Log.ERROR); throw new RemoteException("Invalid restriction"); } try { SQLiteDatabase db = getDb(); if (db == null) return; // 0 not restricted, ask // 1 restricted, ask // 2 not restricted, asked // 3 restricted, asked mLock.writeLock().lock(); try { db.beginTransaction(); try { // Create category record if (restriction.methodName == null) { ContentValues cvalues = new ContentValues(); cvalues.put("uid", restriction.uid); cvalues.put("restriction", restriction.restrictionName); cvalues.put("method", ""); cvalues.put("restricted", (restriction.restricted ? 1 : 0) + (restriction.asked ? 2 : 0)); db.insertWithOnConflict(cTableRestriction, null, cvalues, SQLiteDatabase.CONFLICT_REPLACE); } // Create method exception record if (restriction.methodName != null) { ContentValues mvalues = new ContentValues(); mvalues.put("uid", restriction.uid); mvalues.put("restriction", restriction.restrictionName); mvalues.put("method", restriction.methodName); mvalues.put("restricted", (restriction.restricted ? 0 : 1) + (restriction.asked ? 2 : 0)); db.insertWithOnConflict(cTableRestriction, null, mvalues, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } // Update cache synchronized (mRestrictionCache) { for (CRestriction key : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (key.isSameMethod(restriction)) mRestrictionCache.remove(key); CRestriction key = new CRestriction(restriction, restriction.extra); if (mRestrictionCache.containsKey(key)) mRestrictionCache.remove(key); mRestrictionCache.put(key, key); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setRestrictionList(List<PRestriction> listRestriction) throws RemoteException { int uid = -1; for (PRestriction restriction : listRestriction) if (uid < 0) uid = restriction.uid; else if (uid != restriction.uid) throw new SecurityException(); enforcePermission(uid); for (PRestriction restriction : listRestriction) setRestrictionInternal(restriction); } @Override public PRestriction getRestriction(final PRestriction restriction, boolean usage, String secret) throws RemoteException { long start = System.currentTimeMillis(); // Translate isolated uid restriction.uid = getIsolatedUid(restriction.uid); boolean ccached = false; boolean mcached = false; int userId = Util.getUserId(restriction.uid); final PRestriction mresult = new PRestriction(restriction); // Disable strict mode ThreadPolicy oldPolicy = StrictMode.getThreadPolicy(); ThreadPolicy newPolicy = new ThreadPolicy.Builder(oldPolicy).permitDiskReads().permitDiskWrites().build(); StrictMode.setThreadPolicy(newPolicy); try { // No permissions enforced, but usage data requires a secret // Sanity checks if (restriction.restrictionName == null) { Util.log(null, Log.ERROR, "Get invalid restriction " + restriction); return mresult; } if (usage && restriction.methodName == null) { Util.log(null, Log.ERROR, "Get invalid restriction " + restriction); return mresult; } // Get meta data Hook hook = null; if (restriction.methodName != null) { hook = PrivacyManager.getHook(restriction.restrictionName, restriction.methodName); if (hook == null) // Can happen after updating Util.log(null, Log.WARN, "Hook not found in service: " + restriction); else if (hook.getFrom() != null) { String version = getSetting(new PSetting(userId, "", PrivacyManager.cSettingVersion, null)).value; if (version != null && new Version(version).compareTo(hook.getFrom()) < 0) if (hook.getReplacedRestriction() == null) { Util.log(null, Log.WARN, "Disabled version=" + version + " from=" + hook.getFrom() + " hook=" + hook); return mresult; } else { restriction.restrictionName = hook.getReplacedRestriction(); restriction.methodName = hook.getReplacedMethod(); Util.log(null, Log.WARN, "Checking " + restriction + " instead of " + hook); } } } // Process IP address if (restriction.extra != null && Meta.cTypeIPAddress.equals(hook.whitelist())) { int colon = restriction.extra.lastIndexOf(':'); String address = (colon >= 0 ? restriction.extra.substring(0, colon) : restriction.extra); String port = (colon >= 0 ? restriction.extra.substring(colon) : ""); int slash = address.indexOf('/'); if (slash == 0) // IP address restriction.extra = address.substring(slash + 1) + port; else if (slash > 0) // Domain name restriction.extra = address.substring(0, slash) + port; } // Check for system component if (!PrivacyManager.isApplication(restriction.uid)) if (!getSettingBool(userId, PrivacyManager.cSettingSystem, false)) return mresult; // Check if restrictions enabled if (usage && !getSettingBool(restriction.uid, PrivacyManager.cSettingRestricted, true)) return mresult; // Check if can be restricted if (!PrivacyManager.canRestrict(restriction.uid, getXUid(), restriction.restrictionName, restriction.methodName, false)) mresult.asked = true; else { // Check cache for method CRestriction key = new CRestriction(restriction, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) { mcached = true; CRestriction cache = mRestrictionCache.get(key); mresult.restricted = cache.restricted; mresult.asked = cache.asked; } } if (!mcached) { boolean methodFound = false; PRestriction cresult = new PRestriction(restriction.uid, restriction.restrictionName, null); // Check cache for category CRestriction ckey = new CRestriction(cresult, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(ckey)) { ccached = true; CRestriction crestriction = mRestrictionCache.get(ckey); cresult.restricted = crestriction.restricted; cresult.asked = crestriction.asked; mresult.restricted = cresult.restricted; mresult.asked = cresult.asked; } } // Get database reference SQLiteDatabase db = getDb(); if (db == null) return mresult; // Precompile statement when needed if (stmtGetRestriction == null) { String sql = "SELECT restricted FROM " + cTableRestriction + " WHERE uid=? AND restriction=? AND method=?"; stmtGetRestriction = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); try { db.beginTransaction(); try { if (!ccached) try { synchronized (stmtGetRestriction) { stmtGetRestriction.clearBindings(); stmtGetRestriction.bindLong(1, restriction.uid); stmtGetRestriction.bindString(2, restriction.restrictionName); stmtGetRestriction.bindString(3, ""); long state = stmtGetRestriction.simpleQueryForLong(); cresult.restricted = ((state & 1) != 0); cresult.asked = ((state & 2) != 0); mresult.restricted = cresult.restricted; mresult.asked = cresult.asked; } } catch (SQLiteDoneException ignored) { } if (restriction.methodName != null) try { synchronized (stmtGetRestriction) { stmtGetRestriction.clearBindings(); stmtGetRestriction.bindLong(1, restriction.uid); stmtGetRestriction.bindString(2, restriction.restrictionName); stmtGetRestriction.bindString(3, restriction.methodName); long state = stmtGetRestriction.simpleQueryForLong(); // Method can be excepted if (mresult.restricted) mresult.restricted = ((state & 1) == 0); // Category asked=true takes precedence if (!mresult.asked) mresult.asked = ((state & 2) != 0); methodFound = true; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.readLock().unlock(); } // Default dangerous if (!methodFound && hook != null && hook.isDangerous()) if (!getSettingBool(userId, PrivacyManager.cSettingDangerous, false)) { if (mresult.restricted) mresult.restricted = false; if (!mresult.asked) mresult.asked = (hook.whitelist() == null); } // Check whitelist if (usage && hook != null && hook.whitelist() != null && restriction.extra != null) { String value = getSetting(new PSetting(restriction.uid, hook.whitelist(), restriction.extra, null)).value; if (value == null) { for (String xextra : getXExtra(restriction, hook)) { value = getSetting(new PSetting(restriction.uid, hook.whitelist(), xextra, null)).value; if (value != null) break; } } if (value != null) { // true means allow, false means block mresult.restricted = !Boolean.parseBoolean(value); mresult.asked = true; } } // Fallback if (!mresult.restricted && usage && PrivacyManager.isApplication(restriction.uid) && !getSettingBool(userId, PrivacyManager.cSettingMigrated, false)) { if (hook != null && !hook.isDangerous()) { mresult.restricted = PrivacyProvider.getRestrictedFallback(null, restriction.uid, restriction.restrictionName, restriction.methodName); Util.log(null, Log.WARN, "Fallback " + mresult); } } // Update cache CRestriction cukey = new CRestriction(cresult, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(cukey)) mRestrictionCache.remove(cukey); mRestrictionCache.put(cukey, cukey); } CRestriction ukey = new CRestriction(mresult, restriction.extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(ukey)) mRestrictionCache.remove(ukey); mRestrictionCache.put(ukey, ukey); } } // Ask to restrict OnDemandResult oResult = new OnDemandResult(); if (!mresult.asked && usage) { oResult = onDemandDialog(hook, restriction, mresult); // Update cache if (oResult.ondemand && !oResult.once) { CRestriction okey = new CRestriction(mresult, oResult.whitelist ? restriction.extra : null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(okey)) mRestrictionCache.remove(okey); mRestrictionCache.put(okey, okey); } } } // Notify user if (!oResult.ondemand && mresult.restricted && usage && hook != null && hook.shouldNotify()) { notifyRestricted(restriction); mresult.time = new Date().getTime(); } } // Store usage data if (usage && hook != null) storeUsageData(restriction, secret, mresult); } catch (SQLiteException ex) { notifyException(ex); } catch (Throwable ex) { Util.bug(null, ex); } finally { StrictMode.setThreadPolicy(oldPolicy); } long ms = System.currentTimeMillis() - start; Util.log( null, ms < PrivacyManager.cWarnServiceDelayMs ? Log.INFO : Log.WARN, String.format("Get service %s%s %d ms", restriction, (ccached ? " (ccached)" : "") + (mcached ? " (mcached)" : ""), ms)); if (mresult.debug) Util.logStack(null, Log.WARN); if (usage) { mCount.incrementAndGet(); if (mresult.restricted) mRestricted.incrementAndGet(); } return mresult; } private void storeUsageData(final PRestriction restriction, String secret, final PRestriction mresult) throws RemoteException { // Check if enabled final int userId = Util.getUserId(restriction.uid); if (getSettingBool(userId, PrivacyManager.cSettingUsage, true) && !getSettingBool(restriction.uid, PrivacyManager.cSettingNoUsageData, false)) { // Check secret boolean allowed = true; if (Util.getAppId(Binder.getCallingUid()) != getXUid()) { if (mSecret == null || !mSecret.equals(secret)) { allowed = false; Util.log(null, Log.WARN, "Invalid secret restriction=" + restriction); } } if (allowed) { mExecutor.execute(new Runnable() { public void run() { try { if (XActivityManagerService.canWriteUsageData()) { SQLiteDatabase dbUsage = getDbUsage(); if (dbUsage == null) return; // Parameter String extra = ""; if (restriction.extra != null) if (getSettingBool(userId, PrivacyManager.cSettingParameters, false)) extra = restriction.extra; // Value if (restriction.value != null) if (!getSettingBool(userId, PrivacyManager.cSettingValues, false)) restriction.value = null; mLockUsage.writeLock().lock(); try { dbUsage.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("uid", restriction.uid); values.put("restriction", restriction.restrictionName); values.put("method", restriction.methodName); values.put("restricted", mresult.restricted); values.put("time", new Date().getTime()); values.put("extra", extra); if (restriction.value == null) values.putNull("value"); else values.put("value", restriction.value); dbUsage.insertWithOnConflict(cTableUsage, null, values, SQLiteDatabase.CONFLICT_REPLACE); dbUsage.setTransactionSuccessful(); } finally { dbUsage.endTransaction(); } } finally { mLockUsage.writeLock().unlock(); } } } catch (SQLiteException ex) { Util.log(null, Log.WARN, ex.toString()); } catch (Throwable ex) { Util.bug(null, ex); } } }); } } } @Override public List<PRestriction> getRestrictionList(PRestriction selector) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(selector.uid); PRestriction query; if (selector.restrictionName == null) for (String sRestrictionName : PrivacyManager.getRestrictions()) { PRestriction restriction = new PRestriction(selector.uid, sRestrictionName, null, false); query = getRestriction(restriction, false, null); restriction.restricted = query.restricted; restriction.asked = query.asked; result.add(restriction); } else for (Hook md : PrivacyManager.getHooks(selector.restrictionName, null)) { PRestriction restriction = new PRestriction(selector.uid, selector.restrictionName, md.getName(), false); query = getRestriction(restriction, false, null); restriction.restricted = query.restricted; restriction.asked = query.asked; result.add(restriction); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public boolean isRestrictionSet(PRestriction restriction) throws RemoteException { try { // No permissions required boolean set = false; SQLiteDatabase db = getDb(); if (db != null) { // Precompile statement when needed if (stmtGetRestriction == null) { String sql = "SELECT restricted FROM " + cTableRestriction + " WHERE uid=? AND restriction=? AND method=?"; stmtGetRestriction = db.compileStatement(sql); } // Execute statement mLock.readLock().lock(); try { db.beginTransaction(); try { try { synchronized (stmtGetRestriction) { stmtGetRestriction.clearBindings(); stmtGetRestriction.bindLong(1, restriction.uid); stmtGetRestriction.bindString(2, restriction.restrictionName); stmtGetRestriction.bindString(3, restriction.methodName); stmtGetRestriction.simpleQueryForLong(); set = true; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.readLock().unlock(); } } return set; } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void deleteRestrictions(int uid, String restrictionName) throws RemoteException { try { enforcePermission(uid); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); try { db.beginTransaction(); try { if ("".equals(restrictionName)) db.delete(cTableRestriction, "uid=?", new String[] { Integer.toString(uid) }); else db.delete(cTableRestriction, "uid=? AND restriction=?", new String[] { Integer.toString(uid), restrictionName }); Util.log(null, Log.WARN, "Restrictions deleted uid=" + uid + " category=" + restrictionName); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } // Clear caches synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Usage @Override public long getUsage(List<PRestriction> listRestriction) throws RemoteException { long lastUsage = 0; try { int uid = -1; for (PRestriction restriction : listRestriction) if (uid < 0) uid = restriction.uid; else if (uid != restriction.uid) throw new SecurityException(); enforcePermission(uid); SQLiteDatabase dbUsage = getDbUsage(); // Precompile statement when needed if (stmtGetUsageRestriction == null) { String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=?"; stmtGetUsageRestriction = dbUsage.compileStatement(sql); } if (stmtGetUsageMethod == null) { String sql = "SELECT MAX(time) FROM " + cTableUsage + " WHERE uid=? AND restriction=? AND method=?"; stmtGetUsageMethod = dbUsage.compileStatement(sql); } mLockUsage.readLock().lock(); try { dbUsage.beginTransaction(); try { for (PRestriction restriction : listRestriction) { if (restriction.methodName == null) try { synchronized (stmtGetUsageRestriction) { stmtGetUsageRestriction.clearBindings(); stmtGetUsageRestriction.bindLong(1, restriction.uid); stmtGetUsageRestriction.bindString(2, restriction.restrictionName); lastUsage = Math.max(lastUsage, stmtGetUsageRestriction.simpleQueryForLong()); } } catch (SQLiteDoneException ignored) { } else try { synchronized (stmtGetUsageMethod) { stmtGetUsageMethod.clearBindings(); stmtGetUsageMethod.bindLong(1, restriction.uid); stmtGetUsageMethod.bindString(2, restriction.restrictionName); stmtGetUsageMethod.bindString(3, restriction.methodName); lastUsage = Math.max(lastUsage, stmtGetUsageMethod.simpleQueryForLong()); } } catch (SQLiteDoneException ignored) { } } dbUsage.setTransactionSuccessful(); } finally { dbUsage.endTransaction(); } } finally { mLockUsage.readLock().unlock(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return lastUsage; } @Override public List<PRestriction> getUsageList(int uid, String restrictionName) throws RemoteException { List<PRestriction> result = new ArrayList<PRestriction>(); try { enforcePermission(-1); SQLiteDatabase dbUsage = getDbUsage(); int userId = Util.getUserId(Binder.getCallingUid()); mLockUsage.readLock().lock(); try { dbUsage.beginTransaction(); try { String sFrom = Long.toString(new Date().getTime() - cMaxUsageDataHours * 60L * 60L * 1000L); Cursor cursor; if (uid == 0) { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra", "value" }, "time>?", new String[] { sFrom }, null, null, "time DESC"); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra", "value" }, "restriction=? AND time>?", new String[] { restrictionName, sFrom }, null, null, "time DESC"); } else { if ("".equals(restrictionName)) cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra", "value" }, "uid=? AND time>?", new String[] { Integer.toString(uid), sFrom }, null, null, "time DESC"); else cursor = dbUsage.query(cTableUsage, new String[] { "uid", "restriction", "method", "restricted", "time", "extra", "value" }, "uid=? AND restriction=? AND time>?", new String[] { Integer.toString(uid), restrictionName, sFrom }, null, null, "time DESC"); } if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (usage data)"); else try { int count = 0; while (count++ < cMaxUsageDataCount && cursor.moveToNext()) { PRestriction data = new PRestriction(); data.uid = cursor.getInt(0); data.restrictionName = cursor.getString(1); data.methodName = cursor.getString(2); data.restricted = (cursor.getInt(3) > 0); data.time = cursor.getLong(4); data.extra = cursor.getString(5); if (cursor.isNull(6)) data.value = null; else data.value = cursor.getString(6); if (userId == 0 || Util.getUserId(data.uid) == userId) result.add(data); } } finally { cursor.close(); } dbUsage.setTransactionSuccessful(); } finally { dbUsage.endTransaction(); } } finally { mLockUsage.readLock().unlock(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return result; } @Override public void deleteUsage(int uid) throws RemoteException { try { enforcePermission(uid); SQLiteDatabase dbUsage = getDbUsage(); mLockUsage.writeLock().lock(); try { dbUsage.beginTransaction(); try { if (uid == 0) dbUsage.delete(cTableUsage, null, new String[] {}); else dbUsage.delete(cTableUsage, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Usage data deleted uid=" + uid); dbUsage.setTransactionSuccessful(); } finally { dbUsage.endTransaction(); } } finally { mLockUsage.writeLock().unlock(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } // Settings @Override public void setSetting(PSetting setting) throws RemoteException { try { enforcePermission(setting.uid); setSettingInternal(setting); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } private void setSettingInternal(PSetting setting) throws RemoteException { try { SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); try { db.beginTransaction(); try { if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } if (PrivacyManager.cSettingAOSPMode.equals(setting.name)) if (setting.value == null || Boolean.toString(false).equals(setting.value)) new File("/data/system/xprivacy/aosp").delete(); else new File("/data/system/xprivacy/aosp").createNewFile(); // Update cache CSetting key = new CSetting(setting.uid, setting.type, setting.name); key.setValue(setting.value); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); if (setting.value != null) mSettingCache.put(key, key); } // Clear restrictions for white list if (Meta.isWhitelist(setting.type)) for (String restrictionName : PrivacyManager.getRestrictions()) for (Hook hook : PrivacyManager.getHooks(restrictionName, null)) if (setting.type.equals(hook.whitelist())) { PRestriction restriction = new PRestriction(setting.uid, hook.getRestrictionName(), hook.getName()); Util.log(null, Log.WARN, "Clearing cache for " + restriction); synchronized (mRestrictionCache) { for (CRestriction mkey : new ArrayList<CRestriction>(mRestrictionCache.keySet())) if (mkey.isSameMethod(restriction)) { Util.log(null, Log.WARN, "Removing " + mkey); mRestrictionCache.remove(mkey); } } } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void setSettingList(List<PSetting> listSetting) throws RemoteException { int uid = -1; for (PSetting setting : listSetting) if (uid < 0) uid = setting.uid; else if (uid != setting.uid) throw new SecurityException(); enforcePermission(uid); for (PSetting setting : listSetting) setSettingInternal(setting); } @Override public PSetting getSetting(PSetting setting) throws RemoteException { long start = System.currentTimeMillis(); // Translate isolated uid setting.uid = getIsolatedUid(setting.uid); int userId = Util.getUserId(setting.uid); // Special case if (Meta.cTypeAccountHash.equals(setting.type)) try { setting.type = Meta.cTypeAccount; setting.name = Util.sha1(setting.name); } catch (Throwable ex) { Util.bug(null, ex); } // Default result PSetting result = new PSetting(setting.uid, setting.type, setting.name, setting.value); // Disable strict mode ThreadPolicy oldPolicy = StrictMode.getThreadPolicy(); ThreadPolicy newPolicy = new ThreadPolicy.Builder(oldPolicy).permitDiskReads().permitDiskWrites().build(); StrictMode.setThreadPolicy(newPolicy); try { // No permissions enforced // Check cache CSetting key = new CSetting(setting.uid, setting.type, setting.name); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) { result.value = mSettingCache.get(key).getValue(); if (result.value == null) result.value = setting.value; // default value return result; } } // No persmissions required SQLiteDatabase db = getDb(); if (db == null) return result; // Fallback if (!PrivacyManager.cSettingMigrated.equals(setting.name) && !getSettingBool(userId, PrivacyManager.cSettingMigrated, false)) { if (setting.uid == 0) result.value = PrivacyProvider.getSettingFallback(setting.name, null, false); if (result.value == null) { result.value = PrivacyProvider.getSettingFallback( String.format("%s.%d", setting.name, setting.uid), setting.value, false); return result; } } // Precompile statement when needed if (stmtGetSetting == null) { String sql = "SELECT value FROM " + cTableSetting + " WHERE uid=? AND type=? AND name=?"; stmtGetSetting = db.compileStatement(sql); } // Execute statement boolean found = false; mLock.readLock().lock(); try { db.beginTransaction(); try { try { synchronized (stmtGetSetting) { stmtGetSetting.clearBindings(); stmtGetSetting.bindLong(1, setting.uid); stmtGetSetting.bindString(2, setting.type); stmtGetSetting.bindString(3, setting.name); result.value = stmtGetSetting.simpleQueryForString(); found = true; } } catch (SQLiteDoneException ignored) { } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.readLock().unlock(); } // Add to cache key.setValue(found ? result.value : null); synchronized (mSettingCache) { if (mSettingCache.containsKey(key)) mSettingCache.remove(key); mSettingCache.put(key, key); } // Default value if (result.value == null) result.value = setting.value; } catch (SQLiteException ex) { notifyException(ex); } catch (Throwable ex) { Util.bug(null, ex); } finally { StrictMode.setThreadPolicy(oldPolicy); } long ms = System.currentTimeMillis() - start; Util.log(null, ms < PrivacyManager.cWarnServiceDelayMs ? Log.INFO : Log.WARN, String.format("Get service %s %d ms", setting, ms)); return result; } @Override public List<PSetting> getSettingList(PSetting selector) throws RemoteException { List<PSetting> listSetting = new ArrayList<PSetting>(); try { enforcePermission(selector.uid); SQLiteDatabase db = getDb(); if (db == null) return listSetting; mLock.readLock().lock(); try { db.beginTransaction(); try { Cursor cursor; if (selector.type == null) cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=?", new String[] { Integer.toString(selector.uid) }, null, null, null); else cursor = db.query(cTableSetting, new String[] { "type", "name", "value" }, "uid=? AND type=?", new String[] { Integer.toString(selector.uid), selector.type }, null, null, null); if (cursor == null) Util.log(null, Log.WARN, "Database cursor null (settings)"); else try { while (cursor.moveToNext()) listSetting.add(new PSetting(selector.uid, cursor.getString(0), cursor.getString(1), cursor.getString(2))); } finally { cursor.close(); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.readLock().unlock(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } return listSetting; } @Override public void deleteSettings(int uid) throws RemoteException { try { enforcePermission(uid); SQLiteDatabase db = getDb(); if (db == null) return; mLock.writeLock().lock(); try { db.beginTransaction(); try { db.delete(cTableSetting, "uid=?", new String[] { Integer.toString(uid) }); Util.log(null, Log.WARN, "Settings deleted uid=" + uid); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } // Clear cache synchronized (mSettingCache) { mSettingCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void clear() throws RemoteException { try { enforcePermission(0); SQLiteDatabase db = getDb(); SQLiteDatabase dbUsage = getDbUsage(); if (db == null || dbUsage == null) return; mLock.writeLock().lock(); try { db.beginTransaction(); try { db.execSQL("DELETE FROM " + cTableRestriction); db.execSQL("DELETE FROM " + cTableSetting); Util.log(null, Log.WARN, "Database cleared"); // Reset migrated ContentValues values = new ContentValues(); values.put("uid", 0); values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } // Clear caches synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mSettingCache) { mSettingCache.clear(); } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } Util.log(null, Log.WARN, "Caches cleared"); mLockUsage.writeLock().lock(); try { dbUsage.beginTransaction(); try { dbUsage.execSQL("DELETE FROM " + cTableUsage); Util.log(null, Log.WARN, "Usage database cleared"); dbUsage.setTransactionSuccessful(); } finally { dbUsage.endTransaction(); } } finally { mLockUsage.writeLock().unlock(); } } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void flush() throws RemoteException { try { enforcePermission(0); synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mAskedOnceCache) { mAskedOnceCache.clear(); } synchronized (mSettingCache) { mSettingCache.clear(); } Util.log(null, Log.WARN, "Service cache flushed"); } catch (Throwable ex) { Util.bug(null, ex); throw new RemoteException(ex.toString()); } } @Override public void dump(int uid) throws RemoteException { if (uid == 0) { } else { synchronized (mRestrictionCache) { for (CRestriction crestriction : mRestrictionCache.keySet()) if (crestriction.getUid() == uid) Util.log(null, Log.WARN, "Dump crestriction=" + crestriction); } synchronized (mAskedOnceCache) { for (CRestriction crestriction : mAskedOnceCache.keySet()) if (crestriction.getUid() == uid && !crestriction.isExpired()) Util.log(null, Log.WARN, "Dump asked=" + crestriction); } synchronized (mSettingCache) { for (CSetting csetting : mSettingCache.keySet()) if (csetting.getUid() == uid) Util.log(null, Log.WARN, "Dump csetting=" + csetting); } } } // Helper classes final class OnDemandResult { public boolean ondemand = false; public boolean once = false; public boolean whitelist = false; } final class OnDemandDialogHolder { public View dialog = null; public CountDownLatch latch = new CountDownLatch(1); public boolean reset = false; } // Helper methods private OnDemandResult onDemandDialog(final Hook hook, final PRestriction restriction, final PRestriction result) { final OnDemandResult oResult = new OnDemandResult(); try { int userId = Util.getUserId(restriction.uid); // Check if application if (!PrivacyManager.isApplication(restriction.uid)) if (!getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false)) return oResult; // Check for exceptions if (hook != null && !hook.canOnDemand()) return oResult; if (!PrivacyManager.canRestrict(restriction.uid, getXUid(), restriction.restrictionName, restriction.methodName, false)) return oResult; // Check if enabled if (!getSettingBool(userId, PrivacyManager.cSettingOnDemand, true)) return oResult; if (!getSettingBool(restriction.uid, PrivacyManager.cSettingOnDemand, false)) return oResult; // Check version String version = getSetting(new PSetting(userId, "", PrivacyManager.cSettingVersion, "0.0")).value; if (new Version(version).compareTo(new Version("2.1.5")) < 0) return oResult; // Get activity manager context final Context context = getContext(); if (context == null) return oResult; long token = 0; try { token = Binder.clearCallingIdentity(); // Get application info final ApplicationInfoEx appInfo = new ApplicationInfoEx(context, restriction.uid); // Check for system application if (appInfo.isSystem()) if (new Version(version).compareTo(new Version("2.0.38")) < 0) return oResult; // Check if activity manager agrees if (!XActivityManagerService.canOnDemand()) return oResult; // Check if activity manager locked if (isAMLocked(restriction.uid)) { Util.log(null, Log.WARN, "On demand locked " + restriction); return oResult; } // Go ask Util.log(null, Log.WARN, "On demand " + restriction); mOndemandSemaphore.acquireUninterruptibly(); try { // Check if activity manager still agrees if (!XActivityManagerService.canOnDemand()) return oResult; // Check if activity manager locked now if (isAMLocked(restriction.uid)) { Util.log(null, Log.WARN, "On demand acquired locked " + restriction); return oResult; } Util.log(null, Log.WARN, "On demanding " + restriction); // Check if method not asked before CRestriction mkey = new CRestriction(restriction, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(mkey)) { CRestriction mrestriction = mRestrictionCache.get(mkey); if (mrestriction.asked) { Util.log(null, Log.WARN, "Already asked " + restriction); result.restricted = mrestriction.restricted; result.asked = true; return oResult; } } } // Check if category not asked before (once) CRestriction ckey = new CRestriction(restriction, null); ckey.setMethodName(null); synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(ckey)) { CRestriction carestriction = mAskedOnceCache.get(ckey); if (!carestriction.isExpired()) { Util.log(null, Log.WARN, "Already asked once category " + restriction); result.restricted = carestriction.restricted; result.asked = true; return oResult; } } } // Check if method not asked before once synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(mkey)) { CRestriction marestriction = mAskedOnceCache.get(mkey); if (!marestriction.isExpired()) { Util.log(null, Log.WARN, "Already asked once method " + restriction); result.restricted = marestriction.restricted; result.asked = true; return oResult; } } } // Check if whitelist not asked before if (restriction.extra != null && hook != null && hook.whitelist() != null) { CSetting skey = new CSetting(restriction.uid, hook.whitelist(), restriction.extra); synchronized (mSettingCache) { if (mSettingCache.containsKey(skey)) { String value = mSettingCache.get(skey).getValue(); if (value != null) { Util.log(null, Log.WARN, "Already asked whitelist " + skey); result.restricted = Boolean.parseBoolean(value); result.asked = true; return oResult; } } for (String xextra : getXExtra(restriction, hook)) { CSetting xkey = new CSetting(restriction.uid, hook.whitelist(), xextra); if (mSettingCache.containsKey(xkey)) { String value = mSettingCache.get(xkey).getValue(); if (value != null) { Util.log(null, Log.WARN, "Already asked whitelist " + xkey); result.restricted = Boolean.parseBoolean(value); result.asked = true; return oResult; } } } } } final OnDemandDialogHolder holder = new OnDemandDialogHolder(); // Build dialog parameters final WindowManager.LayoutParams params = new WindowManager.LayoutParams(); params.type = WindowManager.LayoutParams.TYPE_PHONE; params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND; params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE; params.dimAmount = 0.85f; params.width = WindowManager.LayoutParams.WRAP_CONTENT; params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.format = PixelFormat.TRANSLUCENT; params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN; params.gravity = Gravity.CENTER; // Get window manager final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Show dialog mHandler.post(new Runnable() { @Override public void run() { try { // Build dialog holder.dialog = getOnDemandView(restriction, hook, appInfo, result, context, holder, oResult); // Handle reset button ((Button) holder.dialog.findViewById(R.id.btnReset)) .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ((ProgressBar) holder.dialog.findViewById(R.id.pbProgress)) .setProgress(cMaxOnDemandDialog * 20); holder.reset = true; holder.latch.countDown(); } }); // Make dialog visible wm.addView(holder.dialog, params); // Update progress bar Runnable runProgress = new Runnable() { @Override public void run() { if (holder.dialog != null && holder.dialog.isShown()) { // Update progress bar ProgressBar progressBar = (ProgressBar) holder.dialog .findViewById(R.id.pbProgress); if (progressBar.getProgress() > 0) { progressBar.incrementProgressBy(-1); mHandler.postDelayed(this, 50); } // Check if activity manager locked if (isAMLocked(restriction.uid)) { Util.log(null, Log.WARN, "On demand dialog locked " + restriction); ((Button) holder.dialog.findViewById(R.id.btnDontKnow)).callOnClick(); } } } }; mHandler.postDelayed(runProgress, 50); // Enabled buttons after one second boolean repeat = (SystemClock.elapsedRealtime() - mOnDemandLastAnswer < 1000); mHandler.postDelayed(new Runnable() { @Override public void run() { if (holder.dialog != null && holder.dialog.isShown()) { holder.dialog.findViewById(R.id.btnAllow).setEnabled(true); holder.dialog.findViewById(R.id.btnDontKnow).setEnabled(true); holder.dialog.findViewById(R.id.btnDeny).setEnabled(true); } } }, repeat ? 0 : 1000); } catch (NameNotFoundException ex) { Util.log(null, Log.WARN, ex.toString()); } catch (Throwable ex) { Util.bug(null, ex); } } }); // Wait for choice, reset or timeout do { holder.reset = false; boolean choice = holder.latch.await(cMaxOnDemandDialog, TimeUnit.SECONDS); if (holder.reset) { holder.latch = new CountDownLatch(1); Util.log(null, Log.WARN, "On demand reset " + restriction); } else if (choice) oResult.ondemand = true; else Util.log(null, Log.WARN, "On demand timeout " + restriction); } while (holder.reset); mOnDemandLastAnswer = SystemClock.elapsedRealtime(); // Dismiss dialog mHandler.post(new Runnable() { @Override public void run() { View dialog = holder.dialog; if (dialog != null) wm.removeView(dialog); } }); } finally { mOndemandSemaphore.release(); } } finally { Binder.restoreCallingIdentity(token); } } catch (Throwable ex) { Util.bug(null, ex); } return oResult; } @SuppressLint("InflateParams") private View getOnDemandView(final PRestriction restriction, final Hook hook, ApplicationInfoEx appInfo, final PRestriction result, Context context, final OnDemandDialogHolder holder, final OnDemandResult oResult) throws NameNotFoundException, RemoteException { // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Reference views final View view = LayoutInflater.from(context.createPackageContext(self, 0)).inflate(R.layout.ondemand, null); ImageView ivAppIcon = (ImageView) view.findViewById(R.id.ivAppIcon); TextView tvUid = (TextView) view.findViewById(R.id.tvUid); TextView tvAppName = (TextView) view.findViewById(R.id.tvAppName); TextView tvCategory = (TextView) view.findViewById(R.id.tvCategory); TextView tvFunction = (TextView) view.findViewById(R.id.tvFunction); TextView tvParameters = (TextView) view.findViewById(R.id.tvParameters); TableRow rowParameters = (TableRow) view.findViewById(R.id.rowParameters); TextView tvDefault = (TextView) view.findViewById(R.id.tvDefault); TextView tvInfoCategory = (TextView) view.findViewById(R.id.tvInfoCategory); final CheckBox cbExpert = (CheckBox) view.findViewById(R.id.cbExpert); final CheckBox cbCategory = (CheckBox) view.findViewById(R.id.cbCategory); final CheckBox cbOnce = (CheckBox) view.findViewById(R.id.cbOnce); final Spinner spOnce = (Spinner) view.findViewById(R.id.spOnce); final LinearLayout llWhiteList = (LinearLayout) view.findViewById(R.id.llWhiteList); final CheckBox cbWhitelist = (CheckBox) view.findViewById(R.id.cbWhitelist); final CheckBox cbWhitelistExtra1 = (CheckBox) view.findViewById(R.id.cbWhitelistExtra1); final CheckBox cbWhitelistExtra2 = (CheckBox) view.findViewById(R.id.cbWhitelistExtra2); final CheckBox cbWhitelistExtra3 = (CheckBox) view.findViewById(R.id.cbWhitelistExtra3); ProgressBar mProgress = (ProgressBar) view.findViewById(R.id.pbProgress); Button btnDeny = (Button) view.findViewById(R.id.btnDeny); Button btnDontKnow = (Button) view.findViewById(R.id.btnDontKnow); Button btnAllow = (Button) view.findViewById(R.id.btnAllow); final int userId = Util.getUserId(Process.myUid()); boolean expert = getSettingBool(userId, PrivacyManager.cSettingODExpert, false); boolean category = getSettingBool(userId, PrivacyManager.cSettingODCategory, true); boolean once = getSettingBool(userId, PrivacyManager.cSettingODOnce, false); expert = expert || !category || once; final boolean whitelistDangerous = (hook != null && hook.isDangerous() && hook.whitelist() != null); // Set values if ((hook != null && hook.isDangerous()) || appInfo.isSystem()) view.setBackgroundResource(R.color.color_dangerous_dialog); else view.setBackgroundResource(android.R.color.background_dark); // Application information ivAppIcon.setImageDrawable(appInfo.getIcon(context)); tvUid.setText(Integer.toString(appInfo.getUid())); tvAppName.setText(TextUtils.join(", ", appInfo.getApplicationName())); // Restriction information int catId = resources.getIdentifier("restrict_" + restriction.restrictionName, "string", self); tvCategory.setText(resources.getString(catId)); tvFunction.setText(restriction.methodName); if (restriction.extra == null) rowParameters.setVisibility(View.GONE); else tvParameters.setText(restriction.extra); String defaultAction = resources.getString(result.restricted ? R.string.title_deny : R.string.title_allow); tvDefault.setText(defaultAction); // Help int helpId = resources.getIdentifier("restrict_help_" + restriction.restrictionName, "string", self); tvInfoCategory.setText(resources.getString(helpId)); // Expert mode cbExpert.setChecked(expert); if (expert) { for (View child : Util.getViewsByTag((ViewGroup) view, "details")) child.setVisibility(View.VISIBLE); for (View child : Util.getViewsByTag((ViewGroup) view, "nodetails")) child.setVisibility(View.GONE); } if (expert || whitelistDangerous) llWhiteList.setVisibility(View.VISIBLE); // Category cbCategory.setChecked(category); // Once cbOnce.setChecked(once); int osel = Integer .parseInt(getSetting(new PSetting(userId, "", PrivacyManager.cSettingODOnceDuration, "0")).value); spOnce.setSelection(osel); // Whitelisting if (hook != null && hook.whitelist() != null && restriction.extra != null) { cbWhitelist.setText(resources.getString(R.string.title_whitelist, restriction.extra)); cbWhitelist.setVisibility(View.VISIBLE); String[] xextra = getXExtra(restriction, hook); if (xextra.length > 0) { cbWhitelistExtra1.setText(resources.getString(R.string.title_whitelist, xextra[0])); cbWhitelistExtra1.setVisibility(View.VISIBLE); } if (xextra.length > 1) { cbWhitelistExtra2.setText(resources.getString(R.string.title_whitelist, xextra[1])); cbWhitelistExtra2.setVisibility(View.VISIBLE); } if (xextra.length > 2) { cbWhitelistExtra3.setText(resources.getString(R.string.title_whitelist, xextra[2])); cbWhitelistExtra3.setVisibility(View.VISIBLE); } } cbExpert.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { setSettingBool(userId, "", PrivacyManager.cSettingODExpert, isChecked); if (!isChecked) { setSettingBool(userId, "", PrivacyManager.cSettingODCategory, true); setSettingBool(userId, "", PrivacyManager.cSettingODOnce, false); cbCategory.setChecked(true); cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra1.setChecked(false); cbWhitelistExtra2.setChecked(false); cbWhitelistExtra3.setChecked(false); } for (View child : Util.getViewsByTag((ViewGroup) view, "details")) child.setVisibility(isChecked ? View.VISIBLE : View.GONE); for (View child : Util.getViewsByTag((ViewGroup) view, "nodetails")) child.setVisibility(isChecked ? View.GONE : View.VISIBLE); if (!whitelistDangerous) llWhiteList.setVisibility(isChecked ? View.VISIBLE : View.GONE); } }); // Category, once and whitelist exclude each other cbCategory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbWhitelist.setChecked(false); cbWhitelistExtra1.setChecked(false); cbWhitelistExtra2.setChecked(false); cbWhitelistExtra3.setChecked(false); } } }); cbOnce.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbWhitelist.setChecked(false); cbWhitelistExtra1.setChecked(false); cbWhitelistExtra2.setChecked(false); cbWhitelistExtra3.setChecked(false); } } }); cbWhitelist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelistExtra1.setChecked(false); cbWhitelistExtra2.setChecked(false); cbWhitelistExtra3.setChecked(false); } } }); cbWhitelistExtra1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra2.setChecked(false); cbWhitelistExtra3.setChecked(false); } } }); cbWhitelistExtra2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra1.setChecked(false); cbWhitelistExtra3.setChecked(false); } } }); cbWhitelistExtra3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cbCategory.setChecked(false); cbOnce.setChecked(false); cbWhitelist.setChecked(false); cbWhitelistExtra1.setChecked(false); cbWhitelistExtra2.setChecked(false); } } }); // Setup progress bar mProgress.setMax(cMaxOnDemandDialog * 20); mProgress.setProgress(cMaxOnDemandDialog * 20); btnAllow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Allow result.restricted = false; result.asked = true; if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, oResult, hook); else if (cbWhitelistExtra1.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook)[0], result, oResult, hook); else if (cbWhitelistExtra2.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook)[1], result, oResult, hook); else if (cbWhitelistExtra3.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook)[2], result, oResult, hook); else { setSettingBool(userId, "", PrivacyManager.cSettingODCategory, cbCategory.isChecked()); setSettingBool(userId, "", PrivacyManager.cSettingODOnce, cbOnce.isChecked()); if (cbOnce.isChecked()) onDemandOnce(restriction, cbCategory.isChecked(), result, oResult, spOnce); else onDemandChoice(restriction, cbCategory.isChecked(), false); } holder.latch.countDown(); } }); btnDontKnow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Deny once result.restricted = !(hook != null && hook.isDangerous()); result.asked = true; onDemandOnce(restriction, false, result, oResult, spOnce); holder.latch.countDown(); } }); btnDeny.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Deny result.restricted = true; result.asked = true; if (cbWhitelist.isChecked()) onDemandWhitelist(restriction, null, result, oResult, hook); else if (cbWhitelistExtra1.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook)[0], result, oResult, hook); else if (cbWhitelistExtra2.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook)[1], result, oResult, hook); else if (cbWhitelistExtra3.isChecked()) onDemandWhitelist(restriction, getXExtra(restriction, hook)[2], result, oResult, hook); else { setSettingBool(userId, "", PrivacyManager.cSettingODCategory, cbCategory.isChecked()); setSettingBool(userId, "", PrivacyManager.cSettingODOnce, cbOnce.isChecked()); if (cbOnce.isChecked()) onDemandOnce(restriction, cbCategory.isChecked(), result, oResult, spOnce); else onDemandChoice(restriction, cbCategory.isChecked(), true); } holder.latch.countDown(); } }); return view; } private String[] getXExtra(PRestriction restriction, Hook hook) { List<String> listResult = new ArrayList<String>(); if (restriction.extra != null && hook != null) if (hook.whitelist().equals(Meta.cTypeFilename)) { // Top folders of file name File file = new File(restriction.extra); for (int i = 1; i <= 3 && file != null; i++) { String parent = file.getParent(); if (!TextUtils.isEmpty(parent)) listResult.add(parent + File.separatorChar + "*"); file = file.getParentFile(); } } else if (hook.whitelist().equals(Meta.cTypeIPAddress)) { // sub-domain or sub-net int colon = restriction.extra.lastIndexOf(':'); String address = (colon >= 0 ? restriction.extra.substring(0, colon) : restriction.extra); if (Patterns.IP_ADDRESS.matcher(address).matches()) { int dot = address.lastIndexOf('.'); listResult.add(address.substring(0, dot) + ".*" + (colon >= 0 ? restriction.extra.substring(colon) : "")); if (colon >= 0) listResult.add(address.substring(0, dot) + ".*:*"); } else { int dot = restriction.extra.indexOf('.'); if (dot > 0) { listResult.add('*' + restriction.extra.substring(dot)); if (colon >= 0) listResult.add('*' + restriction.extra.substring(dot, colon) + ":*"); } } } else if (hook.whitelist().equals(Meta.cTypeUrl)) { // Top folders of file name Uri uri = Uri.parse(restriction.extra); if ("file".equals(uri.getScheme())) { File file = new File(uri.getPath()); for (int i = 1; i <= 3 && file != null; i++) { String parent = file.getParent(); if (!TextUtils.isEmpty(parent)) listResult.add(parent + File.separatorChar + "*"); file = file.getParentFile(); } } } else if (hook.whitelist().equals(Meta.cTypeMethod) || hook.whitelist().equals(Meta.cTypeTransaction) || hook.whitelist().equals(Meta.cTypeAction)) { String[] component = restriction.extra.split(":"); if (component.length == 2) listResult.add(component[0] + ":*"); } return listResult.toArray(new String[0]); } private void onDemandWhitelist(PRestriction restriction, String xextra, PRestriction result, OnDemandResult oResult, Hook hook) { try { Util.log(null, Log.WARN, (result.restricted ? "Black" : "White") + "listing " + restriction + " xextra=" + xextra); oResult.whitelist = true; // Set white/black list setSettingInternal(new PSetting(restriction.uid, hook.whitelist(), (xextra == null ? restriction.extra : xextra), Boolean.toString(!result.restricted))); if (!PrivacyManager.getSettingBool(restriction.uid, PrivacyManager.cSettingWhitelistNoModify, false)) if (restriction.methodName == null || !PrivacyManager.cMethodNoState.contains(restriction.methodName)) { // Mark state as changed setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState, Integer.toString(ApplicationInfoEx.STATE_CHANGED))); // Update modification time setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis()))); } } catch (Throwable ex) { Util.bug(null, ex); } } private void onDemandOnce(PRestriction restriction, boolean category, PRestriction result, OnDemandResult oResult, Spinner spOnce) { oResult.once = true; // Get duration String value = (String) spOnce.getSelectedItem(); if (value == null) result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; else { char unit = value.charAt(value.length() - 1); value = value.substring(0, value.length() - 1); if (unit == 's') result.time = new Date().getTime() + Integer.parseInt(value) * 1000; else if (unit == 'm') result.time = new Date().getTime() + Integer.parseInt(value) * 60 * 1000; else result.time = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; try { int userId = Util.getUserId(restriction.uid); String sel = Integer.toString(spOnce.getSelectedItemPosition()); setSettingInternal(new PSetting(userId, "", PrivacyManager.cSettingODOnceDuration, sel)); } catch (Throwable ex) { Util.bug(null, ex); } } Util.log(null, Log.WARN, (result.restricted ? "Deny" : "Allow") + " once " + restriction + " category=" + category + " until=" + new Date(result.time)); CRestriction key = new CRestriction(result, null); key.setExpiry(result.time); if (category) { key.setMethodName(null); key.setExtra(null); } synchronized (mAskedOnceCache) { if (mAskedOnceCache.containsKey(key)) mAskedOnceCache.remove(key); mAskedOnceCache.put(key, key); } } private void onDemandChoice(PRestriction restriction, boolean category, boolean restrict) { try { PRestriction result = new PRestriction(restriction); // Get current category restriction state boolean prevRestricted = false; CRestriction key = new CRestriction(restriction.uid, restriction.restrictionName, null, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) prevRestricted = mRestrictionCache.get(key).restricted; } Util.log(null, Log.WARN, "On demand choice " + restriction + " category=" + category + " restrict=" + restrict + " prev=" + prevRestricted); if (category || (restrict && restrict != prevRestricted)) { // Set category restriction result.methodName = null; result.restricted = restrict; result.asked = category; setRestrictionInternal(result); // Clear category on change for (Hook hook : PrivacyManager.getHooks(restriction.restrictionName, null)) if (!PrivacyManager.canRestrict(restriction.uid, getXUid(), restriction.restrictionName, hook.getName(), false)) { result.methodName = hook.getName(); result.restricted = false; result.asked = true; setRestrictionInternal(result); } else { result.methodName = hook.getName(); result.restricted = restrict && !hook.isDangerous(); result.asked = category || (hook.isDangerous() && hook.whitelist() == null); setRestrictionInternal(result); } } if (!category) { // Set method restriction result.methodName = restriction.methodName; result.restricted = restrict; result.asked = true; result.extra = restriction.extra; setRestrictionInternal(result); } // Mark state as changed setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingState, Integer.toString(ApplicationInfoEx.STATE_CHANGED))); // Update modification time setSettingInternal(new PSetting(restriction.uid, "", PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis()))); } catch (Throwable ex) { Util.bug(null, ex); } } private void notifyRestricted(final PRestriction restriction) { final Context context = getContext(); if (context != null && mHandler != null) mHandler.post(new Runnable() { @Override public void run() { long token = 0; try { token = Binder.clearCallingIdentity(); // Get resources String self = PrivacyService.class.getPackage().getName(); Resources resources = context.getPackageManager().getResourcesForApplication(self); // Notify user String text = resources.getString(R.string.msg_restrictedby); text += " (" + restriction.uid + " " + restriction.restrictionName + "/" + restriction.methodName + ")"; Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } catch (NameNotFoundException ex) { Util.bug(null, ex); } finally { Binder.restoreCallingIdentity(token); } } }); } private void notifyException(Throwable ex) { Util.bug(null, ex); if (mNotified) return; Context context = getContext(); if (context == null) return; try { Intent intent = new Intent("biz.bokhorst.xprivacy.action.EXCEPTION"); intent.putExtra("Message", ex.toString()); context.sendBroadcast(intent); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); // Build notification NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context); notificationBuilder.setSmallIcon(R.drawable.ic_launcher); notificationBuilder.setContentTitle(context.getString(R.string.app_name)); notificationBuilder.setContentText(ex.toString()); notificationBuilder.setWhen(System.currentTimeMillis()); notificationBuilder.setAutoCancel(true); Notification notification = notificationBuilder.build(); // Display notification notificationManager.notify(Util.NOTIFY_CORRUPT, notification); mNotified = true; } catch (Throwable exex) { Util.bug(null, exex); } } private boolean getSettingBool(int uid, String name, boolean defaultValue) throws RemoteException { return getSettingBool(uid, "", name, defaultValue); } private boolean getSettingBool(int uid, String type, String name, boolean defaultValue) throws RemoteException { String value = getSetting(new PSetting(uid, type, name, Boolean.toString(defaultValue))).value; return Boolean.parseBoolean(value); } private void setSettingBool(int uid, String type, String name, boolean value) { try { setSettingInternal(new PSetting(uid, type, name, Boolean.toString(value))); } catch (RemoteException ex) { Util.bug(null, ex); } } private void enforcePermission(int uid) { if (uid >= 0) if (Util.getUserId(uid) != Util.getUserId(Binder.getCallingUid())) throw new SecurityException("uid=" + uid + " calling=" + Binder.getCallingUid()); int callingUid = Util.getAppId(Binder.getCallingUid()); if (callingUid != getXUid() && callingUid != Process.SYSTEM_UID) throw new SecurityException("xuid=" + mXUid + " calling=" + Binder.getCallingUid()); } private boolean isAMLocked(int uid) { try { Object am; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) am = mAm; else { Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService"); am = cam.getMethod("self").invoke(null); } boolean locked = Thread.holdsLock(am); if (locked) { boolean freeze = getSettingBool(uid, PrivacyManager.cSettingFreeze, false); if (!freeze) freeze = getSettingBool(0, PrivacyManager.cSettingFreeze, false); if (freeze) return false; } return locked; } catch (Throwable ex) { Util.bug(null, ex); return false; } } private Context getContext() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) return mContext; else { // public static ActivityManagerService self() // frameworks/base/services/java/com/android/server/am/ActivityManagerService.java try { Class<?> cam = Class.forName("com.android.server.am.ActivityManagerService"); Object am = cam.getMethod("self").invoke(null); if (am == null) return null; Field mContext = cam.getDeclaredField("mContext"); mContext.setAccessible(true); return (Context) mContext.get(am); } catch (Throwable ex) { Util.bug(null, ex); return null; } } } private int getIsolatedUid(int uid) { if (PrivacyManager.isIsolated(uid)) try { Field fmIsolatedProcesses = null; Class<?> cam = mAm.getClass(); while (cam != null && fmIsolatedProcesses == null) try { fmIsolatedProcesses = cam.getDeclaredField("mIsolatedProcesses"); } catch (NoSuchFieldException ignored) { cam = cam.getSuperclass(); } if (fmIsolatedProcesses == null) throw new Exception(mAm.getClass().getName() + ".mIsolatedProcesses not found"); fmIsolatedProcesses.setAccessible(true); SparseArray<?> mIsolatedProcesses = (SparseArray<?>) fmIsolatedProcesses.get(mAm); Object processRecord = mIsolatedProcesses.get(uid); Field fInfo = processRecord.getClass().getDeclaredField("info"); fInfo.setAccessible(true); ApplicationInfo info = (ApplicationInfo) fInfo.get(processRecord); Util.log(null, Log.WARN, "Translated isolated uid=" + uid + " into application uid=" + info.uid + " pkg=" + info.packageName); return info.uid; } catch (Throwable ex) { Util.bug(null, ex); } return uid; } private int getXUid() { if (mXUid < 0) try { Context context = getContext(); if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { String self = PrivacyService.class.getPackage().getName(); ApplicationInfo xInfo = pm.getApplicationInfo(self, 0); mXUid = xInfo.uid; } } } catch (Throwable ignored) { // The package manager may not be up-to-date yet } return mXUid; } private File getDbFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "xprivacy.db"); } private File getDbUsageFile() { return new File(Environment.getDataDirectory() + File.separator + "system" + File.separator + "xprivacy" + File.separator + "usage.db"); } private void setupDatabase() { try { File dbFile = getDbFile(); // Create database folder dbFile.getParentFile().mkdirs(); // Check database folder if (dbFile.getParentFile().isDirectory()) Util.log(null, Log.WARN, "Database folder=" + dbFile.getParentFile()); else Util.log(null, Log.WARN, "Does not exist folder=" + dbFile.getParentFile()); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { // Move database from data/xprivacy folder File folder = new File(Environment.getDataDirectory() + File.separator + "xprivacy"); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } Util.log(null, Log.WARN, "Deleting folder=" + folder); folder.delete(); } // Move database from data/application folder folder = new File(Environment.getDataDirectory() + File.separator + "data" + File.separator + PrivacyService.class.getPackage().getName()); if (folder.exists()) { File[] oldFiles = folder.listFiles(); if (oldFiles != null) for (File file : oldFiles) if (file.getName().startsWith("xprivacy.db")) { File target = new File(dbFile.getParentFile() + File.separator + file.getName()); boolean status = Util.move(file, target); Util.log(null, Log.WARN, "Moved " + file + " to " + target + " ok=" + status); } Util.log(null, Log.WARN, "Deleting folder=" + folder); folder.delete(); } } // Set database file permissions // Owner: rwx (system) // Group: rwx (system) // World: --- Util.setPermissions(dbFile.getParentFile().getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); File[] files = dbFile.getParentFile().listFiles(); if (files != null) for (File file : files) if (file.getName().startsWith("xprivacy.db") || file.getName().startsWith("usage.db")) Util.setPermissions(file.getAbsolutePath(), 0770, Process.SYSTEM_UID, Process.SYSTEM_UID); } catch (Throwable ex) { Util.bug(null, ex); } } private SQLiteDatabase getDb() { synchronized (this) { // Check current reference if (mDb != null && !mDb.isOpen()) { mDb = null; Util.log(null, Log.ERROR, "Database not open"); } if (mDb == null) try { setupDatabase(); // Create/upgrade database when needed File dbFile = getDbFile(); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); // Check database integrity if (db.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Database integrity ok"); else { // http://www.sqlite.org/howtocorrupt.html mCorrupt = true; Util.log(null, Log.ERROR, "Database corrupt"); Cursor cursor = db.rawQuery("PRAGMA integrity_check", null); try { while (cursor.moveToNext()) { String message = cursor.getString(0); Util.log(null, Log.ERROR, message); } } finally { cursor.close(); } db.close(); // Backup database file File dbBackup = new File(dbFile.getParentFile() + File.separator + "xprivacy.backup"); dbBackup.delete(); dbFile.renameTo(dbBackup); File dbJournal = new File(dbFile.getAbsolutePath() + "-journal"); File dbJournalBackup = new File(dbBackup.getAbsolutePath() + "-journal"); dbJournalBackup.delete(); dbJournal.renameTo(dbJournalBackup); Util.log(null, Log.ERROR, "Old database backup: " + dbBackup.getAbsolutePath()); // Create new database db = SQLiteDatabase.openOrCreateDatabase(dbFile, null); Util.log(null, Log.ERROR, "New, empty database created"); } // Update migration status if (db.getVersion() > 1) { Util.log(null, Log.WARN, "Updating migration status"); mLock.writeLock().lock(); try { db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put("uid", 0); if (db.getVersion() > 9) values.put("type", ""); values.put("name", PrivacyManager.cSettingMigrated); values.put("value", Boolean.toString(true)); db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } // Upgrade database if needed if (db.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating database"); mLock.writeLock().lock(); try { db.beginTransaction(); try { // http://www.sqlite.org/lang_createtable.html db.execSQL("CREATE TABLE restriction (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL)"); db.execSQL("CREATE TABLE setting (uid INTEGER NOT NULL, name TEXT NOT NULL, value TEXT)"); db.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); db.execSQL("CREATE UNIQUE INDEX idx_restriction ON restriction(uid, restriction, method)"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, name)"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method)"); db.setVersion(1); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } if (db.needUpgrade(2)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); // Old migrated indication db.setVersion(2); } if (db.needUpgrade(3)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); try { db.beginTransaction(); try { db.execSQL("DELETE FROM usage WHERE method=''"); db.setVersion(3); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } if (db.needUpgrade(4)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); try { db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value IS NULL"); db.setVersion(4); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } if (db.needUpgrade(5)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); try { db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE value = ''"); db.execSQL("DELETE FROM setting WHERE name = 'Random@boot' AND value = 'false'"); db.setVersion(5); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } if (db.needUpgrade(6)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); try { db.beginTransaction(); try { db.execSQL("DELETE FROM setting WHERE name LIKE 'OnDemand.%'"); db.setVersion(6); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } if (db.needUpgrade(7)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); try { db.beginTransaction(); try { db.execSQL("ALTER TABLE usage ADD COLUMN extra TEXT"); db.setVersion(7); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } if (db.needUpgrade(8)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); try { db.beginTransaction(); try { db.execSQL("DROP INDEX idx_usage"); db.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); db.setVersion(8); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } if (db.needUpgrade(9)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); try { db.beginTransaction(); try { db.execSQL("DROP TABLE usage"); db.setVersion(9); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } if (db.needUpgrade(10)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); try { db.beginTransaction(); try { db.execSQL("ALTER TABLE setting ADD COLUMN type TEXT"); db.execSQL("DROP INDEX idx_setting"); db.execSQL("CREATE UNIQUE INDEX idx_setting ON setting(uid, type, name)"); db.execSQL("UPDATE setting SET type=''"); db.setVersion(10); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } if (db.needUpgrade(11)) { Util.log(null, Log.WARN, "Upgrading from version=" + db.getVersion()); mLock.writeLock().lock(); try { db.beginTransaction(); try { List<PSetting> listSetting = new ArrayList<PSetting>(); Cursor cursor = db.query(cTableSetting, new String[] { "uid", "name", "value" }, null, null, null, null, null); if (cursor != null) try { while (cursor.moveToNext()) { int uid = cursor.getInt(0); String name = cursor.getString(1); String value = cursor.getString(2); if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.") || name.startsWith("Template.")) { int dot = name.indexOf('.'); String type = name.substring(0, dot); listSetting .add(new PSetting(uid, type, name.substring(dot + 1), value)); listSetting.add(new PSetting(uid, "", name, null)); } else if (name.startsWith("Whitelist.")) { String[] component = name.split("\\."); listSetting.add(new PSetting(uid, component[1], name.replace( component[0] + "." + component[1] + ".", ""), value)); listSetting.add(new PSetting(uid, "", name, null)); } } } finally { cursor.close(); } for (PSetting setting : listSetting) { Util.log(null, Log.WARN, "Converting " + setting); if (setting.value == null) db.delete(cTableSetting, "uid=? AND type=? AND name=?", new String[] { Integer.toString(setting.uid), setting.type, setting.name }); else { // Create record ContentValues values = new ContentValues(); values.put("uid", setting.uid); values.put("type", setting.type); values.put("name", setting.name); values.put("value", setting.value); // Insert/update record db.insertWithOnConflict(cTableSetting, null, values, SQLiteDatabase.CONFLICT_REPLACE); } } db.setVersion(11); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } finally { mLock.writeLock().unlock(); } } Util.log(null, Log.WARN, "Running VACUUM"); mLock.writeLock().lock(); try { db.execSQL("VACUUM"); } catch (Throwable ex) { Util.bug(null, ex); } finally { mLock.writeLock().unlock(); } Util.log(null, Log.WARN, "Database version=" + db.getVersion()); mDb = db; } catch (Throwable ex) { mDb = null; // retry Util.bug(null, ex); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream( "/cache/xprivacy.log", true)); outputStreamWriter.write(ex.toString()); outputStreamWriter.write("\n"); outputStreamWriter.write(Log.getStackTraceString(ex)); outputStreamWriter.write("\n"); outputStreamWriter.close(); } catch (Throwable exex) { Util.bug(null, exex); } } return mDb; } } private SQLiteDatabase getDbUsage() { synchronized (this) { // Check current reference if (mDbUsage != null && !mDbUsage.isOpen()) { mDbUsage = null; Util.log(null, Log.ERROR, "Usage database not open"); } if (mDbUsage == null) try { // Create/upgrade database when needed File dbUsageFile = getDbUsageFile(); SQLiteDatabase dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); // Check database integrity if (dbUsage.isDatabaseIntegrityOk()) Util.log(null, Log.WARN, "Usage database integrity ok"); else { dbUsage.close(); dbUsageFile.delete(); new File(dbUsageFile + "-journal").delete(); dbUsage = SQLiteDatabase.openOrCreateDatabase(dbUsageFile, null); Util.log(null, Log.WARN, "Deleted corrupt usage data database"); } // Upgrade database if needed if (dbUsage.needUpgrade(1)) { Util.log(null, Log.WARN, "Creating usage database"); mLockUsage.writeLock().lock(); try { dbUsage.beginTransaction(); try { dbUsage.execSQL("CREATE TABLE usage (uid INTEGER NOT NULL, restriction TEXT NOT NULL, method TEXT NOT NULL, extra TEXT NOT NULL, restricted INTEGER NOT NULL, time INTEGER NOT NULL)"); dbUsage.execSQL("CREATE UNIQUE INDEX idx_usage ON usage(uid, restriction, method, extra)"); dbUsage.setVersion(1); dbUsage.setTransactionSuccessful(); } finally { dbUsage.endTransaction(); } } finally { mLockUsage.writeLock().unlock(); } } if (dbUsage.needUpgrade(2)) { Util.log(null, Log.WARN, "Upgrading usage database from version=" + dbUsage.getVersion()); mLockUsage.writeLock().lock(); try { dbUsage.beginTransaction(); try { dbUsage.execSQL("ALTER TABLE usage ADD COLUMN value TEXT"); dbUsage.setVersion(2); dbUsage.setTransactionSuccessful(); } finally { dbUsage.endTransaction(); } } finally { mLockUsage.writeLock().unlock(); } } Util.log(null, Log.WARN, "Changing to asynchronous mode"); try { dbUsage.rawQuery("PRAGMA synchronous=OFF", null); } catch (Throwable ex) { Util.bug(null, ex); } Util.log(null, Log.WARN, "Usage database version=" + dbUsage.getVersion()); mDbUsage = dbUsage; } catch (Throwable ex) { mDbUsage = null; // retry Util.bug(null, ex); } return mDbUsage; } } }
94,584
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
PrivacyManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/PrivacyManager.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.net.Inet4Address; import java.net.InetAddress; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.location.Location; import android.os.Build; import android.os.Process; import android.os.RemoteException; import android.util.Log; import android.util.SparseArray; public class PrivacyManager { public static final boolean cVersion3 = true; // This should correspond with restrict_<name> in strings.xml public static final String cAccounts = "accounts"; public static final String cBrowser = "browser"; public static final String cCalendar = "calendar"; public static final String cCalling = "calling"; public static final String cClipboard = "clipboard"; public static final String cContacts = "contacts"; public static final String cDictionary = "dictionary"; public static final String cEMail = "email"; public static final String cIdentification = "identification"; public static final String cInternet = "internet"; public static final String cIPC = "ipc"; public static final String cLocation = "location"; public static final String cMedia = "media"; public static final String cMessages = "messages"; public static final String cNetwork = "network"; public static final String cNfc = "nfc"; public static final String cNotifications = "notifications"; public static final String cOverlay = "overlay"; public static final String cPhone = "phone"; public static final String cSensors = "sensors"; public static final String cShell = "shell"; public static final String cStorage = "storage"; public static final String cSystem = "system"; public static final String cView = "view"; // This should correspond with the above definitions private static final String cRestrictionNames[] = new String[] { cAccounts, cBrowser, cCalendar, cCalling, cClipboard, cContacts, cDictionary, cEMail, cIdentification, cInternet, cIPC, cLocation, cMedia, cMessages, cNetwork, cNfc, cNotifications, cOverlay, cPhone, cSensors, cShell, cStorage, cSystem, cView }; public static List<String> cMethodNoState = Arrays.asList(new String[] { "IntentFirewall", "checkPermission", "checkUidPermission" }); // Setting names public final static String cSettingSerial = "Serial"; public final static String cSettingLatitude = "Latitude"; public final static String cSettingLongitude = "Longitude"; public final static String cSettingAltitude = "Altitude"; public final static String cSettingMac = "Mac"; public final static String cSettingIP = "IP"; public final static String cSettingImei = "IMEI"; public final static String cSettingPhone = "Phone"; public final static String cSettingId = "ID"; public final static String cSettingGsfId = "GSF_ID"; public final static String cSettingAdId = "AdId"; public final static String cSettingMcc = "MCC"; public final static String cSettingMnc = "MNC"; public final static String cSettingCountry = "Country"; public final static String cSettingOperator = "Operator"; public final static String cSettingIccId = "ICC_ID"; public final static String cSettingSubscriber = "Subscriber"; public final static String cSettingSSID = "SSID"; public final static String cSettingUa = "UA"; public final static String cSettingOpenTab = "OpenTab"; public final static String cSettingSelectedCategory = "SelectedCategory"; public final static String cSettingFUsed = "FUsed"; public final static String cSettingFInternet = "FInternet"; public final static String cSettingFRestriction = "FRestriction"; public final static String cSettingFRestrictionNot = "FRestrictionNot"; public final static String cSettingFPermission = "FPermission"; public final static String cSettingFOnDemand = "FOnDemand"; public final static String cSettingFOnDemandNot = "FOnDemandNot"; public final static String cSettingFUser = "FUser"; public final static String cSettingFSystem = "FSystem"; public final static String cSettingSortMode = "SortMode"; public final static String cSettingSortInverted = "SortInverted"; public final static String cSettingModifyTime = "ModifyTime"; public final static String cSettingTheme = "Theme"; public final static String cSettingSalt = "Salt"; public final static String cSettingVersion = "Version"; public final static String cSettingFirstRun = "FirstRun"; public final static String cSettingTutorialMain = "TutorialMain"; public final static String cSettingTutorialDetails = "TutorialDetails"; public final static String cSettingNotify = "Notify"; public final static String cSettingLog = "Log"; public final static String cSettingDangerous = "Dangerous"; public final static String cSettingExperimental = "Experimental"; public final static String cSettingRandom = "Random@boot"; public final static String cSettingState = "State"; public final static String cSettingConfidence = "Confidence"; public final static String cSettingHttps = "Https"; public final static String cSettingRegistered = "Registered"; public final static String cSettingUsage = "UsageData"; public final static String cSettingParameters = "Parameters"; public final static String cSettingValues = "Values"; public final static String cSettingSystem = "RestrictSystem"; public final static String cSettingRestricted = "Retricted"; public final static String cSettingOnDemand = "OnDemand"; public final static String cSettingMigrated = "Migrated"; public final static String cSettingCid = "Cid"; public final static String cSettingLac = "Lac"; public final static String cSettingBlacklist = "Blacklist"; public final static String cSettingResolve = "Resolve"; public final static String cSettingNoResolve = "NoResolve"; public final static String cSettingFreeze = "Freeze"; public final static String cSettingPermMan = "PermMan"; public final static String cSettingIntentWall = "IntentWall"; public final static String cSettingSafeMode = "SafeMode"; public final static String cSettingTestVersions = "TestVersions"; public final static String cSettingOnDemandSystem = "OnDemandSystem"; public final static String cSettingLegacy = "Legacy"; public final static String cSettingAOSPMode = "AOSPMode"; public final static String cSettingChangelog = "Changelog"; public final static String cSettingUpdates = "Updates"; public final static String cSettingMethodExpert = "MethodExpert"; public final static String cSettingWhitelistNoModify = "WhitelistNoModify"; public final static String cSettingNoUsageData = "NoUsageData"; public final static String cSettingODExpert = "ODExpert"; public final static String cSettingODCategory = "ODCategory"; public final static String cSettingODOnce = "ODOnce"; public final static String cSettingODOnceDuration = "ODOnceDuration"; // Special value names public final static String cValueRandom = "#Random#"; public final static String cValueRandomLegacy = "\nRandom\n"; // Constants public final static int cXposedAppProcessMinVersion = 46; public final static int cWarnServiceDelayMs = 200; public final static int cWarnHookDelayMs = 200; private final static int cMaxExtra = 128; private final static String cDeface = "DEFACE"; // Caching public final static int cRestrictionCacheTimeoutMs = 15 * 1000; public final static int cSettingCacheTimeoutMs = 30 * 1000; private static Map<String, Map<String, Hook>> mMethod = new LinkedHashMap<String, Map<String, Hook>>(); private static Map<String, List<String>> mRestart = new LinkedHashMap<String, List<String>>(); private static Map<String, List<Hook>> mPermission = new LinkedHashMap<String, List<Hook>>(); private static Map<CSetting, CSetting> mSettingsCache = new HashMap<CSetting, CSetting>(); private static Map<CSetting, CSetting> mTransientCache = new HashMap<CSetting, CSetting>(); private static Map<CRestriction, CRestriction> mRestrictionCache = new HashMap<CRestriction, CRestriction>(); private static SparseArray<Map<String, Boolean>> mPermissionRestrictionCache = new SparseArray<Map<String, Boolean>>(); private static SparseArray<Map<Hook, Boolean>> mPermissionHookCache = new SparseArray<Map<Hook, Boolean>>(); // Meta data static { List<Hook> listHook = Meta.get(); List<String> listRestriction = getRestrictions(); for (Hook hook : listHook) { String restrictionName = hook.getRestrictionName(); if (restrictionName == null) restrictionName = ""; // Check restriction else if (!listRestriction.contains(restrictionName)) if (hook.isAvailable()) Util.log(null, Log.WARN, "Not found restriction=" + restrictionName + " hook=" + hook); // Enlist method if (!mMethod.containsKey(restrictionName)) mMethod.put(restrictionName, new HashMap<String, Hook>()); mMethod.get(restrictionName).put(hook.getName(), hook); // Cache restart required methods if (hook.isRestartRequired()) { if (!mRestart.containsKey(restrictionName)) mRestart.put(restrictionName, new ArrayList<String>()); mRestart.get(restrictionName).add(hook.getName()); } // Enlist permissions String[] permissions = hook.getPermissions(); if (permissions != null) for (String perm : permissions) if (!perm.equals("")) { String aPermission = (perm.contains(".") ? perm : "android.permission." + perm); if (!mPermission.containsKey(aPermission)) mPermission.put(aPermission, new ArrayList<Hook>()); if (!mPermission.get(aPermission).contains(hook)) mPermission.get(aPermission).add(hook); } } // Util.log(null, Log.WARN, listHook.size() + " hooks"); } public static List<String> getRestrictions() { List<String> listRestriction = new ArrayList<String>(Arrays.asList(cRestrictionNames)); if (Hook.isAOSP(19)) listRestriction.remove(cIPC); return listRestriction; } public static TreeMap<String, String> getRestrictions(Context context) { Collator collator = Collator.getInstance(Locale.getDefault()); TreeMap<String, String> tmRestriction = new TreeMap<String, String>(collator); for (String restrictionName : getRestrictions()) { int stringId = context.getResources().getIdentifier("restrict_" + restrictionName, "string", context.getPackageName()); tmRestriction.put(stringId == 0 ? restrictionName : context.getString(stringId), restrictionName); } return tmRestriction; } public static Hook getHook(String _restrictionName, String methodName) { String restrictionName = (_restrictionName == null ? "" : _restrictionName); if (mMethod.containsKey(restrictionName)) if (mMethod.get(restrictionName).containsKey(methodName)) return mMethod.get(restrictionName).get(methodName); return null; } public static List<Hook> getHooks(String restrictionName, Version version) { List<Hook> listMethod = new ArrayList<Hook>(); for (String methodName : mMethod.get(restrictionName).keySet()) { Hook hook = mMethod.get(restrictionName).get(methodName); if (!hook.isAvailable()) continue; if (version != null && hook.getFrom() != null && version.compareTo(hook.getFrom()) < 0) continue; if ("IntentFirewall".equals(hook.getName())) if (!PrivacyManager.getSettingBool(0, PrivacyManager.cSettingIntentWall, false)) continue; if ("checkPermission".equals(hook.getName()) || "checkUidPermission".equals(hook.getName())) if (!PrivacyManager.getSettingBool(0, PrivacyManager.cSettingPermMan, false)) continue; listMethod.add(mMethod.get(restrictionName).get(methodName)); } Collections.sort(listMethod); return listMethod; } public static List<String> getPermissions(String restrictionName, Version version) { List<String> listPermission = new ArrayList<String>(); for (Hook md : getHooks(restrictionName, version)) if (md.getPermissions() != null) for (String permission : md.getPermissions()) if (!listPermission.contains(permission)) listPermission.add(permission); return listPermission; } // Restrictions public static PRestriction getRestrictionEx(int uid, String restrictionName, String methodName) { PRestriction query = new PRestriction(uid, restrictionName, methodName, false); PRestriction result = new PRestriction(uid, restrictionName, methodName, false, true); try { // Check cache boolean cached = false; CRestriction key = new CRestriction(uid, restrictionName, methodName, null); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) { CRestriction entry = mRestrictionCache.get(key); if (!entry.isExpired()) { cached = true; result.restricted = entry.restricted; result.asked = entry.asked; } } } if (!cached) { // Get restriction result = PrivacyService.getRestrictionProxy(query, false, ""); if (result.debug) Util.logStack(null, Log.WARN); // Add to cache key.restricted = result.restricted; key.asked = result.asked; if (result.time > 0) { key.setExpiry(result.time); Util.log(null, Log.WARN, "Caching " + result + " until " + new Date(result.time)); } synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) mRestrictionCache.remove(key); mRestrictionCache.put(key, key); } } } catch (RemoteException ex) { Util.bug(null, ex); } return result; } public static boolean getRestriction(final XHook hook, int uid, String restrictionName, String methodName, String secret) { return getRestrictionExtra(hook, uid, restrictionName, methodName, null, null, secret); } public static boolean getRestrictionExtra(final XHook hook, int uid, String restrictionName, String methodName, String extra, String secret) { return getRestrictionExtra(hook, uid, restrictionName, methodName, extra, null, secret); } public static boolean getRestrictionExtra(final XHook hook, int uid, String restrictionName, String methodName, String extra, String value, String secret) { long start = System.currentTimeMillis(); PRestriction result = new PRestriction(uid, restrictionName, methodName, false, true); // Check uid if (uid <= 0) return false; // Check secret if (secret == null) { Util.log(null, Log.ERROR, "Secret missing restriction=" + restrictionName + "/" + methodName); Util.logStack(hook, Log.ERROR); secret = ""; } // Check restriction if (restrictionName == null || restrictionName.equals("")) { Util.log(hook, Log.ERROR, "restriction empty method=" + methodName); Util.logStack(hook, Log.ERROR); return false; } // Check usage if (methodName == null || methodName.equals("")) { Util.log(hook, Log.ERROR, "Method empty"); Util.logStack(hook, Log.ERROR); } else if (getHook(restrictionName, methodName) == null) { Util.log(hook, Log.ERROR, "Unknown method=" + methodName); Util.logStack(hook, Log.ERROR); } // Check extra if (extra != null && extra.length() > cMaxExtra) extra = extra.substring(0, cMaxExtra) + "..."; result.extra = extra; // Check cache boolean cached = false; CRestriction key = new CRestriction(uid, restrictionName, methodName, extra); synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) { CRestriction entry = mRestrictionCache.get(key); if (!entry.isExpired()) { cached = true; result.restricted = entry.restricted; result.asked = entry.asked; } } } // Get restriction if (!cached) try { PRestriction query = new PRestriction(uid, restrictionName, methodName, false); query.extra = extra; query.value = value; PRestriction restriction = PrivacyService.getRestrictionProxy(query, true, secret); result.restricted = restriction.restricted; if (restriction.debug) Util.logStack(null, Log.WARN); // Add to cache if (result.time >= 0) { key.restricted = result.restricted; key.asked = result.asked; if (result.time > 0) { key.setExpiry(result.time); Util.log(null, Log.WARN, "Caching " + result + " until " + new Date(result.time)); } synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(key)) mRestrictionCache.remove(key); mRestrictionCache.put(key, key); } } } catch (Throwable ex) { Util.bug(hook, ex); } // Result long ms = System.currentTimeMillis() - start; Util.log(hook, ms < cWarnServiceDelayMs ? Log.INFO : Log.WARN, String.format("Get client %s%s %d ms", result, (cached ? " (cached)" : ""), ms)); return result.restricted; } public static void setRestriction(int uid, String restrictionName, String methodName, boolean restricted, boolean asked) { checkCaller(); // Check uid if (uid == 0) { Util.log(null, Log.WARN, "uid=0"); return; } // Build list of restrictions List<String> listRestriction = new ArrayList<String>(); if (restrictionName == null) listRestriction.addAll(PrivacyManager.getRestrictions()); else listRestriction.add(restrictionName); // Create list of restrictions to set List<PRestriction> listPRestriction = new ArrayList<PRestriction>(); for (String rRestrictionName : listRestriction) listPRestriction.add(new PRestriction(uid, rRestrictionName, methodName, restricted, asked)); // Make exceptions if (methodName == null) for (String rRestrictionName : listRestriction) for (Hook md : getHooks(rRestrictionName, null)) { if (!canRestrict(uid, Process.myUid(), rRestrictionName, md.getName(), false)) listPRestriction.add(new PRestriction(uid, rRestrictionName, md.getName(), false, true)); else if (md.isDangerous()) listPRestriction.add(new PRestriction(uid, rRestrictionName, md.getName(), false, md .whitelist() == null)); } setRestrictionList(listPRestriction); } public static List<String> cIDCant = Arrays.asList(new String[] { "getString", "Srv_Android_ID", "%serialno", "SERIAL" }); public static boolean canRestrict(int uid, int xuid, String restrictionName, String methodName, boolean system) { int _uid = Util.getAppId(uid); int userId = Util.getUserId(uid); if (_uid == Process.SYSTEM_UID) { if (PrivacyManager.cIdentification.equals(restrictionName)) return false; if (PrivacyManager.cShell.equals(restrictionName) && "loadLibrary".equals(methodName)) return false; } if (system) if (!isApplication(_uid)) if (!getSettingBool(userId, PrivacyManager.cSettingSystem, false)) return false; // @formatter:off if (_uid == Util.getAppId(xuid) && ((PrivacyManager.cIdentification.equals(restrictionName) && cIDCant.contains(methodName)) || PrivacyManager.cIPC.equals(restrictionName) || PrivacyManager.cStorage.equals(restrictionName) || PrivacyManager.cSystem.equals(restrictionName) || PrivacyManager.cView.equals(restrictionName))) return false; // @formatter:on Hook hook = getHook(restrictionName, methodName); if (hook != null && hook.isUnsafe()) if (getSettingBool(userId, PrivacyManager.cSettingSafeMode, false)) return false; return true; } public static void updateState(int uid) { setSetting(uid, cSettingState, Integer.toString(ApplicationInfoEx.STATE_CHANGED)); setSetting(uid, cSettingModifyTime, Long.toString(System.currentTimeMillis())); } public static void setRestrictionList(List<PRestriction> listRestriction) { checkCaller(); if (listRestriction.size() > 0) try { PrivacyService.getClient().setRestrictionList(listRestriction); // Clear cache synchronized (mRestrictionCache) { mRestrictionCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); } } public static List<PRestriction> getRestrictionList(int uid, String restrictionName) { checkCaller(); try { return PrivacyService.getClient().getRestrictionList(new PRestriction(uid, restrictionName, null, false)); } catch (Throwable ex) { Util.bug(null, ex); } return new ArrayList<PRestriction>(); } public static boolean isRestrictionSet(PRestriction restriction) { try { return PrivacyService.getClient().isRestrictionSet(restriction); } catch (Throwable ex) { Util.bug(null, ex); return false; } } public static void deleteRestrictions(int uid, String restrictionName, boolean deleteWhitelists) { checkCaller(); try { // Delete restrictions PrivacyService.getClient().deleteRestrictions(uid, restrictionName == null ? "" : restrictionName); // Clear associated whitelists if (deleteWhitelists && uid > 0) { for (PSetting setting : getSettingList(uid, null)) if (Meta.isWhitelist(setting.type)) setSetting(uid, setting.type, setting.name, null); } // Clear cache synchronized (mRestrictionCache) { mRestrictionCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); } // Mark as new/changed setSetting(uid, cSettingState, Integer.toString(restrictionName == null ? ApplicationInfoEx.STATE_CHANGED : ApplicationInfoEx.STATE_ATTENTION)); // Change app modification time setSetting(uid, cSettingModifyTime, Long.toString(System.currentTimeMillis())); } public static List<Boolean> getRestartStates(int uid, String restrictionName) { // Returns a list of restriction states for functions whose application // requires the app to be restarted. List<Boolean> listRestartRestriction = new ArrayList<Boolean>(); Set<String> listRestriction = new HashSet<String>(); if (restrictionName == null) listRestriction = mRestart.keySet(); else if (mRestart.keySet().contains(restrictionName)) listRestriction.add(restrictionName); try { for (String restriction : listRestriction) { for (String method : mRestart.get(restriction)) listRestartRestriction.add(getRestrictionEx(uid, restriction, method).restricted); } } catch (Throwable ex) { Util.bug(null, ex); } return listRestartRestriction; } public static void applyTemplate(int uid, String templateName, String restrictionName, boolean methods, boolean clear, boolean invert) { checkCaller(); int userId = Util.getUserId(uid); // Check on-demand boolean ondemand = getSettingBool(userId, PrivacyManager.cSettingOnDemand, true); // Build list of restrictions List<String> listRestriction = new ArrayList<String>(); if (restrictionName == null) listRestriction.addAll(getRestrictions()); else listRestriction.add(restrictionName); // Apply template Util.log(null, Log.WARN, "Applying template=" + templateName); boolean hasOndemand = false; List<PRestriction> listPRestriction = new ArrayList<PRestriction>(); for (String rRestrictionName : listRestriction) { // Cleanup if (clear) deleteRestrictions(uid, rRestrictionName, false); // Parent String parentValue = getSetting(userId, templateName, rRestrictionName, Boolean.toString(!ondemand) + "+ask"); boolean parentRestricted = parentValue.contains("true"); boolean parentAsked = (!ondemand || parentValue.contains("asked")); hasOndemand = hasOndemand || !parentAsked; // Merge PRestriction parentMerge; if (clear) parentMerge = new PRestriction(uid, rRestrictionName, null, parentRestricted, parentAsked); else parentMerge = getRestrictionEx(uid, rRestrictionName, null); // Apply if (canRestrict(uid, Process.myUid(), rRestrictionName, null, true)) if (invert && ((parentRestricted && parentMerge.restricted) || (!parentAsked && !parentMerge.asked))) { listPRestriction.add(new PRestriction(uid, rRestrictionName, null, parentRestricted ? false : parentMerge.restricted, !parentAsked ? true : parentMerge.asked)); continue; // leave functions } else listPRestriction.add(new PRestriction(uid, rRestrictionName, null, parentMerge.restricted || parentRestricted, parentMerge.asked && parentAsked)); // Childs if (methods) for (Hook hook : getHooks(rRestrictionName, null)) if (canRestrict(uid, Process.myUid(), rRestrictionName, hook.getName(), true)) { // Child String settingName = rRestrictionName + "." + hook.getName(); String childValue = getSetting(userId, templateName, settingName, null); if (childValue == null) childValue = Boolean.toString(parentRestricted && !hook.isDangerous()) + (parentAsked || (hook.isDangerous() && hook.whitelist() == null) ? "+asked" : "+ask"); boolean restricted = childValue.contains("true"); boolean asked = (!ondemand || childValue.contains("asked")); // Merge PRestriction childMerge; if (clear) childMerge = new PRestriction(uid, rRestrictionName, hook.getName(), parentRestricted && restricted, parentAsked || asked); else childMerge = getRestrictionEx(uid, rRestrictionName, hook.getName()); // Invert if (invert && parentRestricted && restricted) { restricted = false; childMerge.restricted = false; } if (invert && !parentAsked && !asked) { asked = true; childMerge.asked = true; } // Apply if ((parentRestricted && !restricted) || (!parentAsked && asked) || (invert ? false : hook.isDangerous() || !clear)) { PRestriction child = new PRestriction(uid, rRestrictionName, hook.getName(), (parentRestricted && restricted) || childMerge.restricted, (parentAsked || asked) && childMerge.asked); listPRestriction.add(child); } } } // Apply result setRestrictionList(listPRestriction); if (hasOndemand) PrivacyManager.setSetting(uid, PrivacyManager.cSettingOnDemand, Boolean.toString(true)); } // White/black listing public static Map<String, TreeMap<String, Boolean>> listWhitelisted(int uid, String type) { checkCaller(); Map<String, TreeMap<String, Boolean>> mapWhitelisted = new HashMap<String, TreeMap<String, Boolean>>(); for (PSetting setting : getSettingList(uid, type)) if (Meta.isWhitelist(setting.type)) { if (!mapWhitelisted.containsKey(setting.type)) mapWhitelisted.put(setting.type, new TreeMap<String, Boolean>()); mapWhitelisted.get(setting.type).put(setting.name, Boolean.parseBoolean(setting.value)); } return mapWhitelisted; } // Usage public static long getUsage(int uid, String restrictionName, String methodName) { checkCaller(); try { List<PRestriction> listRestriction = new ArrayList<PRestriction>(); if (restrictionName == null) for (String sRestrictionName : getRestrictions()) listRestriction.add(new PRestriction(uid, sRestrictionName, methodName, false)); else listRestriction.add(new PRestriction(uid, restrictionName, methodName, false)); return PrivacyService.getClient().getUsage(listRestriction); } catch (Throwable ex) { Util.bug(null, ex); return 0; } } public static List<PRestriction> getUsageList(Context context, int uid, String restrictionName) { checkCaller(); List<PRestriction> listUsage = new ArrayList<PRestriction>(); try { listUsage.addAll(PrivacyService.getClient().getUsageList(uid, restrictionName == null ? "" : restrictionName)); } catch (Throwable ex) { Util.log(null, Log.ERROR, "getUsageList"); Util.bug(null, ex); } Collections.sort(listUsage, new ParcelableRestrictionCompare()); return listUsage; } public static class ParcelableRestrictionCompare implements Comparator<PRestriction> { @Override public int compare(PRestriction one, PRestriction another) { if (one.time < another.time) return 1; else if (one.time > another.time) return -1; else return 0; } } public static void deleteUsage(int uid) { checkCaller(); try { PrivacyService.getClient().deleteUsage(uid); } catch (Throwable ex) { Util.bug(null, ex); } } // Settings public static String getSalt(int userId) { String def = (Build.SERIAL == null ? "" : Build.SERIAL); return getSetting(userId, cSettingSalt, def); } public static void removeLegacySalt(int userId) { String def = (Build.SERIAL == null ? "" : Build.SERIAL); String salt = getSetting(userId, cSettingSalt, null); if (def.equals(salt)) setSetting(userId, cSettingSalt, null); } public static boolean getSettingBool(int uid, String name, boolean defaultValue) { return Boolean.parseBoolean(getSetting(uid, name, Boolean.toString(defaultValue))); } public static boolean getSettingBool(int uid, String type, String name, boolean defaultValue) { return Boolean.parseBoolean(getSetting(uid, type, name, Boolean.toString(defaultValue))); } public static String getSetting(int uid, String name, String defaultValue) { return getSetting(uid, "", name, defaultValue); } public static String getSetting(int uid, String type, String name, String defaultValue) { long start = System.currentTimeMillis(); String value = null; // Check cache boolean cached = false; boolean willExpire = false; CSetting key = new CSetting(uid, type, name); synchronized (mSettingsCache) { if (mSettingsCache.containsKey(key)) { CSetting entry = mSettingsCache.get(key); if (!entry.isExpired()) { cached = true; value = entry.getValue(); willExpire = entry.willExpire(); } } } // Get settings if (!cached) try { value = PrivacyService.getSettingProxy(new PSetting(Math.abs(uid), type, name, null)).value; if (value == null) if (uid > 99) { int userId = Util.getUserId(uid); value = PrivacyService.getSettingProxy(new PSetting(userId, type, name, null)).value; } // Add to cache if (value == null) key.setValue(defaultValue); else key.setValue(value); synchronized (mSettingsCache) { if (mSettingsCache.containsKey(key)) mSettingsCache.remove(key); mSettingsCache.put(key, key); } } catch (Throwable ex) { Util.bug(null, ex); } if (value == null) value = defaultValue; long ms = System.currentTimeMillis() - start; if (!willExpire && !cSettingLog.equals(name)) Util.log(null, ms < cWarnServiceDelayMs ? Log.INFO : Log.WARN, String.format( "Get setting uid=%d %s/%s=%s%s %d ms", uid, type, name, value, (cached ? " (cached)" : ""), ms)); return value; } public static void setSetting(int uid, String name, String value) { setSetting(uid, "", name, value); } public static void setSetting(int uid, String type, String name, String value) { checkCaller(); try { PrivacyService.getClient().setSetting(new PSetting(uid, type, name, value)); // Update cache CSetting key = new CSetting(uid, type, name); key.setValue(value); synchronized (mSettingsCache) { if (mSettingsCache.containsKey(key)) mSettingsCache.remove(key); mSettingsCache.put(key, key); } } catch (Throwable ex) { Util.bug(null, ex); } } public static void setSettingList(List<PSetting> listSetting) { checkCaller(); if (listSetting.size() > 0) try { PrivacyService.getClient().setSettingList(listSetting); // Clear cache synchronized (mSettingsCache) { mSettingsCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); } } public static List<PSetting> getSettingList(int uid, String type) { checkCaller(); try { return PrivacyService.getClient().getSettingList(new PSetting(uid, type, null, null)); } catch (Throwable ex) { Util.bug(null, ex); } return new ArrayList<PSetting>(); } public static void deleteSettings(int uid) { checkCaller(); try { PrivacyService.getClient().deleteSettings(uid); // Clear cache synchronized (mSettingsCache) { mSettingsCache.clear(); } } catch (Throwable ex) { Util.bug(null, ex); } } private static final List<String> cSettingAppSpecific = Arrays.asList(new String[] { cSettingRandom, cSettingSerial, cSettingLatitude, cSettingLongitude, cSettingAltitude, cSettingMac, cSettingIP, cSettingImei, cSettingPhone, cSettingId, cSettingGsfId, cSettingAdId, cSettingMcc, cSettingMnc, cSettingCountry, cSettingOperator, cSettingIccId, cSettingCid, cSettingLac, cSettingSubscriber, cSettingSSID, cSettingUa }); public static boolean hasSpecificSettings(int uid) { boolean specific = false; for (PSetting setting : getSettingList(uid, "")) if (cSettingAppSpecific.contains(setting.name)) { specific = true; break; } return specific; } public static String getTransient(String name, String defaultValue) { CSetting csetting = new CSetting(0, "", name); synchronized (mTransientCache) { if (mTransientCache.containsKey(csetting)) return mTransientCache.get(csetting).getValue(); } return defaultValue; } public static void setTransient(String name, String value) { CSetting setting = new CSetting(0, "", name); setting.setValue(value); synchronized (mTransientCache) { mTransientCache.put(setting, setting); } } // Common public static void clear() { checkCaller(); try { PrivacyService.getClient().clear(); flush(); } catch (Throwable ex) { Util.bug(null, ex); } } public static void flush() { synchronized (mSettingsCache) { mSettingsCache.clear(); } synchronized (mRestrictionCache) { mRestrictionCache.clear(); } synchronized (mPermissionRestrictionCache) { mPermissionRestrictionCache.clear(); } synchronized (mPermissionHookCache) { mPermissionHookCache.clear(); } } // Defacing @SuppressLint("DefaultLocale") public static Object getDefacedProp(int uid, String name) { // Serial number if (name.equals("SERIAL") || name.equals("%serialno")) { String value = getSetting(uid, cSettingSerial, cDeface); return (cValueRandom.equals(value) ? getRandomProp("SERIAL") : value); } // Host name if (name.equals("%hostname")) return cDeface; // MAC addresses if (name.equals("MAC") || name.equals("%macaddr")) { String mac = getSetting(uid, cSettingMac, "DE:FA:CE:DE:FA:CE"); if (cValueRandom.equals(mac)) return getRandomProp("MAC"); StringBuilder sb = new StringBuilder(mac.replace(":", "")); while (sb.length() != 12) sb.insert(0, '0'); while (sb.length() > 12) sb.deleteCharAt(sb.length() - 1); for (int i = 10; i > 0; i -= 2) sb.insert(i, ':'); return sb.toString(); } // cid if (name.equals("%cid")) return cDeface; // IMEI if (name.equals("getDeviceId") || name.equals("%imei")) { String value = getSetting(uid, cSettingImei, "000000000000000"); return (cValueRandom.equals(value) ? getRandomProp("IMEI") : value); } // Phone if (name.equals("PhoneNumber") || name.equals("getLine1AlphaTag") || name.equals("getLine1Number") || name.equals("getMsisdn") || name.equals("getVoiceMailAlphaTag") || name.equals("getVoiceMailNumber") || name.equals("getCompleteVoiceMailNumber")) { String value = getSetting(uid, cSettingPhone, cDeface); return (cValueRandom.equals(value) ? getRandomProp("PHONE") : value); } // Android ID if (name.equals("ANDROID_ID")) { String value = getSetting(uid, cSettingId, cDeface); return (cValueRandom.equals(value) ? getRandomProp("ANDROID_ID") : value); } // Telephony manager if (name.equals("getGroupIdLevel1")) return null; if (name.equals("getIsimDomain")) return null; if (name.equals("getIsimImpi")) return null; if (name.equals("getIsimImpu")) return null; if (name.equals("getNetworkCountryIso") || name.equals("CountryIso")) { // ISO country code String value = getSetting(uid, cSettingCountry, "XX"); return (cValueRandom.equals(value) ? getRandomProp("ISO3166") : value); } if (name.equals("getNetworkOperator")) // MCC+MNC: test network return getSetting(uid, cSettingMcc, "001") + getSetting(uid, cSettingMnc, "01"); if (name.equals("getNetworkOperatorName")) return getSetting(uid, cSettingOperator, cDeface); if (name.equals("getSimCountryIso")) { // ISO country code String value = getSetting(uid, cSettingCountry, "XX"); return (cValueRandom.equals(value) ? getRandomProp("ISO3166") : value); } if (name.equals("getSimOperator")) // MCC+MNC: test network return getSetting(uid, cSettingMcc, "001") + getSetting(uid, cSettingMnc, "01"); if (name.equals("getSimOperatorName")) return getSetting(uid, cSettingOperator, cDeface); if (name.equals("getSimSerialNumber") || name.equals("getIccSerialNumber") || name.equals("getIccSerialNumber")) return getSetting(uid, cSettingIccId, null); if (name.equals("getSubscriberId")) { // IMSI for a GSM phone String value = getSetting(uid, cSettingSubscriber, null); return (cValueRandom.equals(value) ? getRandomProp("SubscriberId") : value); } if (name.equals("SSID")) { // Default hidden network String value = getSetting(uid, cSettingSSID, ""); return (cValueRandom.equals(value) ? getRandomProp("SSID") : value); } // Google services framework ID if (name.equals("GSF_ID")) { long gsfid = 0xDEFACE; try { String value = getSetting(uid, cSettingGsfId, "DEFACE"); if (cValueRandom.equals(value)) value = getRandomProp(name); gsfid = Long.parseLong(value.toLowerCase(), 16); } catch (Throwable ignored) { } return gsfid; } // Advertisement ID if (name.equals("AdvertisingId")) { String adid = getSetting(uid, cSettingAdId, "DEFACE00-0000-0000-0000-000000000000"); if (cValueRandom.equals(adid)) adid = getRandomProp(name); return adid; } if (name.equals("InetAddress")) { // Set address String ip = getSetting(uid, cSettingIP, null); if (ip != null) try { return InetAddress.getByName(ip); } catch (Throwable ignored) { } // Any address (0.0.0.0) try { Field unspecified = Inet4Address.class.getDeclaredField("ANY"); unspecified.setAccessible(true); return (InetAddress) unspecified.get(Inet4Address.class); } catch (Throwable ex) { Util.bug(null, ex); return null; } } if (name.equals("IPInt")) { // Set address String ip = getSetting(uid, cSettingIP, null); if (ip != null) try { InetAddress inet = InetAddress.getByName(ip); if (inet.getClass().equals(Inet4Address.class)) { byte[] b = inet.getAddress(); return b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24); } } catch (Throwable ex) { Util.bug(null, ex); } // Any address (0.0.0.0) return 0; } if (name.equals("Bytes3")) return new byte[] { (byte) 0xDE, (byte) 0xFA, (byte) 0xCE }; if (name.equals("UA")) return getSetting(uid, cSettingUa, "Mozilla/5.0 (Linux; U; Android; en-us) AppleWebKit/999+ (KHTML, like Gecko) Safari/999.9"); // InputDevice if (name.equals("DeviceDescriptor")) return cDeface; // getExtraInfo if (name.equals("ExtraInfo")) return cDeface; if (name.equals("MCC")) return getSetting(uid, cSettingMcc, "001"); if (name.equals("MNC")) return getSetting(uid, cSettingMnc, "01"); if (name.equals("CID")) try { return Integer.parseInt(getSetting(uid, cSettingCid, "0")) & 0xFFFF; } catch (Throwable ignored) { return -1; } if (name.equals("LAC")) try { return Integer.parseInt(getSetting(uid, cSettingLac, "0")) & 0xFFFF; } catch (Throwable ignored) { return -1; } if (name.equals("USB")) return cDeface; if (name.equals("BTName")) return cDeface; if (name.equals("CastID")) return cDeface; // Fallback Util.log(null, Log.ERROR, "Fallback value name=" + name); Util.logStack(null, Log.ERROR); return cDeface; } public static Location getDefacedLocation(int uid, Location location) { // Christmas Island ~ -10.5 / 105.667 String sLat = getSetting(uid, cSettingLatitude, "-10.5"); String sLon = getSetting(uid, cSettingLongitude, "105.667"); String sAlt = getSetting(uid, cSettingAltitude, "686"); // Backward compatibility if ("".equals(sLat)) sLat = "-10.5"; if ("".equals(sLon)) sLon = "105.667"; if (cValueRandom.equals(sLat)) sLat = getRandomProp("LAT"); if (cValueRandom.equals(sLon)) sLon = getRandomProp("LON"); if (cValueRandom.equals(sAlt)) sAlt = getRandomProp("ALT"); // 1 degree ~ 111111 m // 1 m ~ 0,000009 degrees if (location == null) location = new Location(cDeface); location.setLatitude(Float.parseFloat(sLat) + (Math.random() * 2.0 - 1.0) * location.getAccuracy() * 9e-6); location.setLongitude(Float.parseFloat(sLon) + (Math.random() * 2.0 - 1.0) * location.getAccuracy() * 9e-6); location.setAltitude(Float.parseFloat(sAlt) + (Math.random() * 2.0 - 1.0) * location.getAccuracy()); return location; } @SuppressLint("DefaultLocale") public static String getRandomProp(String name) { Random r = new Random(); if (name.equals("SERIAL")) { long v = r.nextLong(); return Long.toHexString(v).toUpperCase(); } if (name.equals("MAC")) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 6; i++) { if (i != 0) sb.append(':'); int v = r.nextInt(256); if (i == 0) v = v & 0xFC; // unicast, globally unique sb.append(Integer.toHexString(0x100 | v).substring(1)); } return sb.toString().toUpperCase(); } // IMEI/MEID if (name.equals("IMEI")) { // http://en.wikipedia.org/wiki/Reporting_Body_Identifier String[] rbi = new String[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "30", "33", "35", "44", "45", "49", "50", "51", "52", "53", "54", "86", "91", "98", "99" }; String imei = rbi[r.nextInt(rbi.length)]; while (imei.length() < 14) imei += Character.forDigit(r.nextInt(10), 10); imei += getLuhnDigit(imei); return imei; } if (name.equals("PHONE")) { String phone = "0"; for (int i = 1; i < 10; i++) phone += Character.forDigit(r.nextInt(10), 10); return phone; } if (name.equals("ANDROID_ID")) { long v = r.nextLong(); return Long.toHexString(v); } if (name.equals("ISO3166")) { String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String country = Character.toString(letters.charAt(r.nextInt(letters.length()))) + Character.toString(letters.charAt(r.nextInt(letters.length()))); return country; } if (name.equals("GSF_ID")) { long v = Math.abs(r.nextLong()); return Long.toString(v, 16).toUpperCase(); } if (name.equals("AdvertisingId")) return UUID.randomUUID().toString().toUpperCase(); if (name.equals("LAT")) { double d = r.nextDouble() * 180 - 90; d = Math.rint(d * 1e7) / 1e7; return Double.toString(d); } if (name.equals("LON")) { double d = r.nextDouble() * 360 - 180; d = Math.rint(d * 1e7) / 1e7; return Double.toString(d); } if (name.equals("ALT")) { double d = r.nextDouble() * 2 * 686; return Double.toString(d); } if (name.equals("SubscriberId")) { String subscriber = "00101"; while (subscriber.length() < 15) subscriber += Character.forDigit(r.nextInt(10), 10); return subscriber; } if (name.equals("SSID")) { String ssid = ""; while (ssid.length() < 6) ssid += (char) (r.nextInt(26) + 'A'); ssid += Character.forDigit(r.nextInt(10), 10); ssid += Character.forDigit(r.nextInt(10), 10); return ssid; } return ""; } private static char getLuhnDigit(String x) { // http://en.wikipedia.org/wiki/Luhn_algorithm int sum = 0; for (int i = 0; i < x.length(); i++) { int n = Character.digit(x.charAt(x.length() - 1 - i), 10); if (i % 2 == 0) { n *= 2; if (n > 9) n -= 9; // n = (n % 10) + 1; } sum += n; } return Character.forDigit((sum * 9) % 10, 10); } // Helper methods public static void checkCaller() { if (PrivacyService.isRegistered()) { Util.log(null, Log.ERROR, "Privacy manager call from service"); Util.logStack(null, Log.ERROR); } } public static final int FIRST_ISOLATED_UID = 99000; public static final int LAST_ISOLATED_UID = 99999; public static final int FIRST_SHARED_APPLICATION_GID = 50000; public static final int LAST_SHARED_APPLICATION_GID = 59999; public static boolean isApplication(int uid) { uid = Util.getAppId(uid); return (uid >= Process.FIRST_APPLICATION_UID && uid <= Process.LAST_APPLICATION_UID); } public static boolean isShared(int uid) { uid = Util.getAppId(uid); return (uid >= FIRST_SHARED_APPLICATION_GID && uid <= LAST_SHARED_APPLICATION_GID); } public static boolean isIsolated(int uid) { uid = Util.getAppId(uid); return (uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID); } public static boolean hasPermission(Context context, ApplicationInfoEx appInfo, String restrictionName, Version version) { int uid = appInfo.getUid(); synchronized (mPermissionRestrictionCache) { if (mPermissionRestrictionCache.get(uid) == null) mPermissionRestrictionCache.append(uid, new HashMap<String, Boolean>()); if (!mPermissionRestrictionCache.get(uid).containsKey(restrictionName)) { boolean permission = hasPermission(context, appInfo.getPackageName(), getPermissions(restrictionName, version)); mPermissionRestrictionCache.get(uid).put(restrictionName, permission); } return mPermissionRestrictionCache.get(uid).get(restrictionName); } } public static boolean hasPermission(Context context, ApplicationInfoEx appInfo, Hook md) { int uid = appInfo.getUid(); synchronized (mPermissionHookCache) { if (mPermissionHookCache.get(uid) == null) mPermissionHookCache.append(uid, new HashMap<Hook, Boolean>()); if (!mPermissionHookCache.get(uid).containsKey(md)) { List<String> listPermission = (md.getPermissions() == null ? null : Arrays.asList(md.getPermissions())); boolean permission = hasPermission(context, appInfo.getPackageName(), listPermission); mPermissionHookCache.get(uid).put(md, permission); } return mPermissionHookCache.get(uid).get(md); } } public static void clearPermissionCache(int uid) { synchronized (mPermissionRestrictionCache) { if (mPermissionRestrictionCache.get(uid) != null) mPermissionRestrictionCache.remove(uid); } synchronized (mPermissionHookCache) { if (mPermissionHookCache.get(uid) != null) mPermissionHookCache.remove(uid); } } @SuppressLint("DefaultLocale") private static boolean hasPermission(Context context, List<String> listPackage, List<String> listPermission) { try { if (listPermission == null || listPermission.size() == 0 || listPermission.contains("")) return true; PackageManager pm = context.getPackageManager(); for (String packageName : listPackage) { // Check absolute permissions for (String apermission : listPermission) if (apermission.contains(".")) if (pm.checkPermission(apermission, packageName) == PackageManager.PERMISSION_GRANTED) return true; // Check relative permissions PackageInfo pInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); if (pInfo != null && pInfo.requestedPermissions != null) for (String rPermission : pInfo.requestedPermissions) for (String permission : listPermission) if (rPermission.toLowerCase().contains(permission.toLowerCase())) { String aPermission = "android.permission." + permission; if (!aPermission.equals(rPermission)) Util.log(null, Log.WARN, "Check permission=" + permission + "/" + rPermission); return true; } } } catch (NameNotFoundException ex) { Util.log(null, Log.WARN, ex.toString()); } catch (Throwable ex) { Util.bug(null, ex); } return false; } }
48,049
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XActivityManagerService.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XActivityManagerService.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Semaphore; import android.annotation.SuppressLint; import android.os.Build; import android.util.Log; @SuppressLint("InlinedApi") public class XActivityManagerService extends XHook { private Methods mMethod; private static Semaphore mOndemandSemaphore; private static boolean mFinishedBooting = false; private static boolean mLockScreen = false; private static boolean mSleeping = false; private static boolean mShutdown = false; private XActivityManagerService(Methods method) { super(null, method.name(), null); mMethod = method; } @Override public boolean isVisible() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) if (mMethod == Methods.goingToSleep || mMethod == Methods.wakingUp) return false; return (mMethod != Methods.appNotResponding && mMethod != Methods.finishBooting && mMethod != Methods.updateSleepIfNeededLocked); } public String getClassName() { return "com.android.server.am.ActivityManagerService"; } // @formatter:off // 4.2+ public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) // 4.3+ public boolean inputDispatchingTimedOut(final ProcessRecord proc, final ActivityRecord activity, final ActivityRecord parent, final boolean aboveSystem, String reason) // 4.0.3+ final void appNotResponding(ProcessRecord app, ActivityRecord activity, ActivityRecord parent, boolean aboveSystem, final String annotation) // 4.0.3+ public void systemReady(final Runnable goingCallback) // 4.0.3+ final void finishBooting() // 4.1+ public void setLockScreenShown(boolean shown) // 4.0.3-5.0.x public void goingToSleep() // 4.0.3-5.0.x public void wakingUp() // 4.0.3+ public boolean shutdown(int timeout) // 4.2+ public final void activityResumed(IBinder token) // public final void activityPaused(IBinder token) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/com/android/server/am/ActivityManagerService.java/ // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/com/android/server/am/ActivityRecord.java/ // @formatter:on // @formatter:off private enum Methods { inputDispatchingTimedOut, appNotResponding, systemReady, finishBooting, setLockScreenShown, goingToSleep, wakingUp, shutdown, updateSleepIfNeededLocked }; // @formatter:on public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XActivityManagerService(Methods.inputDispatchingTimedOut)); listHook.add(new XActivityManagerService(Methods.appNotResponding)); listHook.add(new XActivityManagerService(Methods.systemReady)); listHook.add(new XActivityManagerService(Methods.finishBooting)); // setLockScreenShown appears to be not present in some 4.2.2 ROMs listHook.add(new XActivityManagerService(Methods.setLockScreenShown)); listHook.add(new XActivityManagerService(Methods.goingToSleep)); listHook.add(new XActivityManagerService(Methods.wakingUp)); listHook.add(new XActivityManagerService(Methods.shutdown)); listHook.add(new XActivityManagerService(Methods.updateSleepIfNeededLocked)); return listHook; } public static void setSemaphore(Semaphore semaphore) { mOndemandSemaphore = semaphore; } public static boolean canOnDemand() { return (mFinishedBooting && !mLockScreen && !mSleeping); } public static boolean canWriteUsageData() { return !mShutdown; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case inputDispatchingTimedOut: // Delay foreground ANRs while on demand dialog open if (mOndemandSemaphore != null && mOndemandSemaphore.availablePermits() < 1) { Util.log(this, Log.WARN, "Foreground ANR uid=" + getUidANR(param)); param.setResult(5 * 1000); // 5 seconds } break; case appNotResponding: // Ignore background ANRs while on demand dialog open if (mOndemandSemaphore != null && mOndemandSemaphore.availablePermits() < 1) { Util.log(this, Log.WARN, "Background ANR uid=" + getUidANR(param)); param.setResult(null); } break; case systemReady: // Do nothing break; case finishBooting: // Do nothing break; case setLockScreenShown: if (param.args.length > 0 && param.args[0] instanceof Boolean) try { if ((Boolean) param.args[0]) { mLockScreen = true; Util.log(this, Log.WARN, "Lockscreen=" + mLockScreen); } } catch (Throwable ex) { Util.bug(this, ex); } break; case goingToSleep: mSleeping = true; Util.log(this, Log.WARN, "Sleeping=" + mSleeping); break; case wakingUp: // Do nothing break; case shutdown: mShutdown = true; Util.log(this, Log.WARN, "Shutdown"); break; case updateSleepIfNeededLocked: // Do nothing; break; } } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case inputDispatchingTimedOut: case appNotResponding: break; case systemReady: // Do nothing Util.log(this, Log.WARN, "System ready"); break; case finishBooting: mFinishedBooting = true; Util.log(this, Log.WARN, "Finished booting"); break; case setLockScreenShown: if (param.args.length > 0 && param.args[0] instanceof Boolean) if (!(Boolean) param.args[0]) { mLockScreen = false; Util.log(this, Log.WARN, "Lockscreen=" + mLockScreen); } break; case goingToSleep: // Do nothing break; case wakingUp: mSleeping = false; Util.log(this, Log.WARN, "Sleeping=" + mSleeping); break; case shutdown: // Do nothing break; case updateSleepIfNeededLocked: if (param.thisObject != null) { Field methodSleeping = param.thisObject.getClass().getDeclaredField("mSleeping"); methodSleeping.setAccessible(true); mSleeping = (Boolean) methodSleeping.get(param.thisObject); Util.log(this, Log.WARN, "Sleeping=" + mSleeping); } break; } } // Helper methods private int getUidANR(XParam param) throws IllegalAccessException { int uid = -1; try { Class<?> pr = Class.forName("com.android.server.am.ProcessRecord"); if (param.args.length > 0 && param.args[0] != null && param.args[0].getClass().equals(pr)) { Field fUid = pr.getDeclaredField("uid"); fUid.setAccessible(true); uid = (Integer) fUid.get(param.args[0]); } } catch (ClassNotFoundException ignored) { } catch (NoSuchFieldException ignored) { } catch (Throwable ex) { Util.bug(this, ex); } return uid; } }
6,649
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XPrivacy.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XPrivacy.java
package biz.bokhorst.xprivacy; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Random; import android.content.Context; import android.os.Build; import android.os.Process; import android.util.Log; import de.robv.android.xposed.IXposedHookZygoteInit; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XC_MethodHook; import static de.robv.android.xposed.XposedHelpers.findClass; public class XPrivacy implements IXposedHookLoadPackage, IXposedHookZygoteInit { private static String mSecret = null; private static List<String> mListHookError = new ArrayList<String>(); private static List<CRestriction> mListDisabled = new ArrayList<CRestriction>(); public void initZygote(StartupParam startupParam) throws Throwable { Util.log(null, Log.WARN, "Init path=" + startupParam.modulePath); // Check for LBE security master if (Util.hasLBE()) { Util.log(null, Log.ERROR, "LBE installed"); return; } // Generate secret mSecret = Long.toHexString(new Random().nextLong()); // Reading files with SELinux enabled can result in bootloops boolean selinux = Util.isSELinuxEnforced(); if ("true".equals(Util.getXOption("ignoreselinux"))) { selinux = false; Log.w("Xprivacy", "Ignoring SELinux"); } // Read list of disabled hooks if (mListDisabled.size() == 0 && !selinux) { File disabled = new File("/data/system/xprivacy/disabled"); if (disabled.exists() && disabled.canRead()) try { Log.w("XPrivacy", "Reading " + disabled.getAbsolutePath()); FileInputStream fis = new FileInputStream(disabled); InputStreamReader ir = new InputStreamReader(fis); BufferedReader br = new BufferedReader(ir); String line; while ((line = br.readLine()) != null) if (line.length() > 0 && !line.startsWith("#")) { String[] name = line.split("/"); if (name.length > 0) { String methodName = (name.length > 1 ? name[1] : null); CRestriction restriction = new CRestriction(0, name[0], methodName, null); Log.w("XPrivacy", "Disabling " + restriction); mListDisabled.add(restriction); } } br.close(); ir.close(); fis.close(); } catch (Throwable ex) { Log.w("XPrivacy", ex.toString()); } } // AOSP mode override if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && !selinux) try { Class<?> libcore = Class.forName("libcore.io.Libcore"); Field fOs = libcore.getDeclaredField("os"); fOs.setAccessible(true); Object os = fOs.get(null); Method setenv = os.getClass().getMethod("setenv", String.class, String.class, boolean.class); setenv.setAccessible(true); boolean aosp = new File("/data/system/xprivacy/aosp").exists(); setenv.invoke(os, "XPrivacy.AOSP", Boolean.toString(aosp), false); Util.log(null, Log.WARN, "AOSP mode forced=" + aosp); } catch (Throwable ex) { Util.bug(null, ex); } /* * ActivityManagerService is the beginning of the main "android" * process. This is where the core java system is started, where the * system context is created and so on. In pre-lollipop we can access * this class directly, but in lollipop we have to visit ActivityThread * first, since this class is now responsible for creating a class * loader that can be used to access ActivityManagerService. It is no * longer possible to do so via the normal boot class loader. Doing it * like this will create a consistency between older and newer Android * versions. * * Note that there is no need to handle arguments in this case. And we * don't need them so in case they change over time, we will simply use * the hookAll feature. */ try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Class<?> at = Class.forName("android.app.ActivityThread"); XposedBridge.hookAllMethods(at, "systemMain", new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { try { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class<?> am = Class.forName("com.android.server.am.ActivityManagerService", false, loader); XposedBridge.hookAllConstructors(am, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { try { PrivacyService.register(mListHookError, loader, mSecret, param.thisObject); hookSystem(loader); } catch (Throwable ex) { Util.bug(null, ex); } } }); } catch (Throwable ex) { Util.bug(null, ex); } } }); } else { Class<?> cSystemServer = Class.forName("com.android.server.SystemServer"); Method mMain = cSystemServer.getDeclaredMethod("main", String[].class); XposedBridge.hookMethod(mMain, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { try { PrivacyService.register(mListHookError, null, mSecret, null); } catch (Throwable ex) { Util.bug(null, ex); } } }); } hookZygote(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) hookSystem(null); } catch (Throwable ex) { Util.bug(null, ex); } } public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable { // Check for LBE security master if (Util.hasLBE()) return; hookPackage(lpparam.packageName, lpparam.classLoader); } private void hookZygote() throws Throwable { Log.w("XPrivacy", "Hooking Zygote"); /* * Add nixed User Space / System Server hooks */ // Account manager hookAll(XAccountManager.getInstances(null, false), null, mSecret, false); // Activity manager hookAll(XActivityManager.getInstances(null, false), null, mSecret, false); // App widget manager hookAll(XAppWidgetManager.getInstances(false), null, mSecret, false); // Bluetooth adapater hookAll(XBluetoothAdapter.getInstances(false), null, mSecret, false); // Clipboard manager hookAll(XClipboardManager.getInstances(null, false), null, mSecret, false); // Content resolver hookAll(XContentResolver.getInstances(false), null, mSecret, false); // Package manager service hookAll(XPackageManager.getInstances(null, false), null, mSecret, false); // SMS manager hookAll(XSmsManager.getInstances(false), null, mSecret, false); // Telephone service hookAll(XTelephonyManager.getInstances(null, false), null, mSecret, false); // Usage statistics manager hookAll(XUsageStatsManager.getInstances(false), null, mSecret, false); /* * Add pure user space hooks */ // Intent receive hookAll(XActivityThread.getInstances(), null, mSecret, false); // Runtime hookAll(XRuntime.getInstances(), null, mSecret, false); // Application hookAll(XApplication.getInstances(), null, mSecret, false); // Audio record hookAll(XAudioRecord.getInstances(), null, mSecret, false); // Binder device hookAll(XBinder.getInstances(), null, mSecret, false); // Bluetooth device hookAll(XBluetoothDevice.getInstances(), null, mSecret, false); // Camera hookAll(XCamera.getInstances(), null, mSecret, false); // Camera2 device hookAll(XCameraDevice2.getInstances(), null, mSecret, false); // Connectivity manager hookAll(XConnectivityManager.getInstances(null, false), null, mSecret, false); // Context wrapper hookAll(XContextImpl.getInstances(), null, mSecret, false); // Environment hookAll(XEnvironment.getInstances(), null, mSecret, false); // Inet address hookAll(XInetAddress.getInstances(), null, mSecret, false); // Input device hookAll(XInputDevice.getInstances(), null, mSecret, false); // IO bridge hookAll(XIoBridge.getInstances(), null, mSecret, false); // IP prefix hookAll(XIpPrefix.getInstances(), null, mSecret, false); // Link properties hookAll(XLinkProperties.getInstances(), null, mSecret, false); // Location manager hookAll(XLocationManager.getInstances(null, false), null, mSecret, false); // Media recorder hookAll(XMediaRecorder.getInstances(), null, mSecret, false); // Network info hookAll(XNetworkInfo.getInstances(), null, mSecret, false); // Network interface hookAll(XNetworkInterface.getInstances(), null, mSecret, false); // NFC adapter hookAll(XNfcAdapter.getInstances(), null, mSecret, false); // Process hookAll(XProcess.getInstances(), null, mSecret, false); // Process builder hookAll(XProcessBuilder.getInstances(), null, mSecret, false); // Resources hookAll(XResources.getInstances(), null, mSecret, false); // Sensor manager hookAll(XSensorManager.getInstances(null, false), null, mSecret, false); // Settings secure hookAll(XSettingsSecure.getInstances(), null, mSecret, false); // SIP manager hookAll(XSipManager.getInstances(), null, mSecret, false); // System properties hookAll(XSystemProperties.getInstances(), null, mSecret, false); // USB device hookAll(XUsbDevice.getInstances(), null, mSecret, false); // Web view hookAll(XWebView.getInstances(), null, mSecret, false); // Window service hookAll(XWindowManager.getInstances(null, false), null, mSecret, false); // Wi-Fi service hookAll(XWifiManager.getInstances(null, false), null, mSecret, false); // Intent send hookAll(XActivity.getInstances(), null, mSecret, false); } private void hookSystem(ClassLoader classLoader) throws Throwable { Log.w("XPrivacy", "Hooking system"); /* * Add nixed User Space / System Server hooks */ // Account manager hookAll(XAccountManager.getInstances(null, true), classLoader, mSecret, false); // Activity manager hookAll(XActivityManager.getInstances(null, true), classLoader, mSecret, false); // App widget manager hookAll(XAppWidgetManager.getInstances(true), classLoader, mSecret, false); // Bluetooth adapater hookAll(XBluetoothAdapter.getInstances(true), classLoader, mSecret, false); // Clipboard manager hookAll(XClipboardManager.getInstances(null, true), classLoader, mSecret, false); // Content resolver hookAll(XContentResolver.getInstances(true), classLoader, mSecret, false); // Location manager service hookAll(XLocationManager.getInstances(null, true), classLoader, mSecret, false); // Package manager service hookAll(XPackageManager.getInstances(null, true), classLoader, mSecret, false); // SMS manager hookAll(XSmsManager.getInstances(true), classLoader, mSecret, false); // Telephone service if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) hookAll(XTelephonyManager.getInstances(null, true), classLoader, mSecret, false); hookAll(XTelephonyManager.getRegistryInstances(), classLoader, mSecret, false); // Usage statistics manager hookAll(XUsageStatsManager.getInstances(true), classLoader, mSecret, false); // Wi-Fi service hookAll(XWifiManager.getInstances(null, true), classLoader, mSecret, false); /* * Add pure system server hooks */ // Activity manager service hookAll(XActivityManagerService.getInstances(), classLoader, mSecret, false); // Intent firewall hookAll(XIntentFirewall.getInstances(), classLoader, mSecret, false); } private void hookPackage(String packageName, ClassLoader classLoader) { Log.w("XPrivacy", "Hooking package=" + packageName); // Skip hooking self String self = XPrivacy.class.getPackage().getName(); if (packageName.equals(self)) { hookAll(XUtilHook.getInstances(), classLoader, mSecret, false); return; } // Build SERIAL if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || Process.myUid() != Process.SYSTEM_UID) if (PrivacyManager.getRestrictionExtra(null, Process.myUid(), PrivacyManager.cIdentification, "SERIAL", null, Build.SERIAL, mSecret)) try { Field serial = Build.class.getField("SERIAL"); serial.setAccessible(true); serial.set(null, PrivacyManager.getDefacedProp(Process.myUid(), "SERIAL")); } catch (Throwable ex) { Util.bug(null, ex); } // Activity recognition try { Class.forName("com.google.android.gms.location.ActivityRecognitionClient", false, classLoader); hookAll(XActivityRecognitionClient.getInstances(), classLoader, mSecret, false); } catch (Throwable ignored) { } // Advertising Id try { Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient$Info", false, classLoader); hookAll(XAdvertisingIdClientInfo.getInstances(), classLoader, mSecret, false); } catch (Throwable ignored) { } // Cast device try { Class.forName("com.google.android.gms.cast.CastDevice", false, classLoader); hookAll(XCastDevice.getInstances(), classLoader, mSecret, false); } catch (Throwable ignored) { } // Google auth try { Class.forName("com.google.android.gms.auth.GoogleAuthUtil", false, classLoader); hookAll(XGoogleAuthUtil.getInstances(), classLoader, mSecret, false); } catch (Throwable ignored) { } // GoogleApiClient.Builder try { Class.forName("com.google.android.gms.common.api.GoogleApiClient$Builder", false, classLoader); hookAll(XGoogleApiClient.getInstances(), classLoader, mSecret, false); } catch (Throwable ignored) { } // Google Map V1 try { Class.forName("com.google.android.maps.GeoPoint", false, classLoader); hookAll(XGoogleMapV1.getInstances(), classLoader, mSecret, false); } catch (Throwable ignored) { } // Google Map V2 try { Class.forName("com.google.android.gms.maps.GoogleMap", false, classLoader); hookAll(XGoogleMapV2.getInstances(), classLoader, mSecret, false); } catch (Throwable ignored) { } // Location client try { Class.forName("com.google.android.gms.location.LocationClient", false, classLoader); hookAll(XLocationClient.getInstances(), classLoader, mSecret, false); } catch (Throwable ignored) { } // Phone interface manager if ("com.android.phone".equals(packageName)) { hookAll(XTelephonyManager.getPhoneInstances(), classLoader, mSecret, false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) hookAll(XTelephonyManager.getInstances(null, true), classLoader, mSecret, false); } // Providers hookAll(XContentResolver.getPackageInstances(packageName, classLoader), classLoader, mSecret, false); } public static void handleGetSystemService(String name, String className, String secret) { if (PrivacyManager.getTransient(className, null) == null) { PrivacyManager.setTransient(className, Boolean.toString(true)); if (name.equals(Context.ACCOUNT_SERVICE)) hookAll(XAccountManager.getInstances(className, false), null, secret, true); else if (name.equals(Context.ACTIVITY_SERVICE)) hookAll(XActivityManager.getInstances(className, false), null, secret, true); else if (name.equals(Context.CLIPBOARD_SERVICE)) hookAll(XClipboardManager.getInstances(className, false), null, secret, true); else if (name.equals(Context.CONNECTIVITY_SERVICE)) hookAll(XConnectivityManager.getInstances(className, false), null, secret, true); else if (name.equals(Context.LOCATION_SERVICE)) hookAll(XLocationManager.getInstances(className, false), null, secret, true); else if (name.equals("PackageManager")) hookAll(XPackageManager.getInstances(className, false), null, secret, true); else if (name.equals(Context.SENSOR_SERVICE)) hookAll(XSensorManager.getInstances(className, false), null, secret, true); else if (name.equals(Context.TELEPHONY_SERVICE)) hookAll(XTelephonyManager.getInstances(className, false), null, secret, true); else if (name.equals(Context.WINDOW_SERVICE)) hookAll(XWindowManager.getInstances(className, false), null, secret, true); else if (name.equals(Context.WIFI_SERVICE)) hookAll(XWifiManager.getInstances(className, false), null, secret, true); } } public static void hookAll(List<XHook> listHook, ClassLoader classLoader, String secret, boolean dynamic) { for (XHook hook : listHook) if (hook.getRestrictionName() == null) hook(hook, classLoader, secret); else { CRestriction crestriction = new CRestriction(0, hook.getRestrictionName(), null, null); CRestriction mrestriction = new CRestriction(0, hook.getRestrictionName(), hook.getMethodName(), null); if (mListDisabled.contains(crestriction) || mListDisabled.contains(mrestriction)) Util.log(hook, Log.WARN, "Skipping disabled hook " + hook); else hook(hook, classLoader, secret); } } private static void hook(final XHook hook, ClassLoader classLoader, String secret) { // Get meta data Hook md = PrivacyManager.getHook(hook.getRestrictionName(), hook.getSpecifier()); if (md == null) { String message = "Not found hook=" + hook; mListHookError.add(message); Util.log(hook, Log.ERROR, message); } else if (!md.isAvailable()) return; // Provide secret if (secret == null) Util.log(hook, Log.ERROR, "Secret missing hook=" + hook); hook.setSecret(secret); try { // Find class Class<?> hookClass = null; try { hookClass = findClass(hook.getClassName(), classLoader); } catch (Throwable ex) { String message = "Class not found hook=" + hook; int level = (md != null && md.isOptional() ? Log.WARN : Log.ERROR); if ("isXposedEnabled".equals(hook.getMethodName())) level = Log.WARN; if (level == Log.ERROR) mListHookError.add(message); Util.log(hook, level, message); return; } // Get members List<Member> listMember = new ArrayList<Member>(); List<Class<?>[]> listParameters = new ArrayList<Class<?>[]>(); Class<?> clazz = hookClass; while (clazz != null && !"android.content.ContentProvider".equals(clazz.getName())) try { if (hook.getMethodName() == null) { for (Constructor<?> constructor : clazz.getDeclaredConstructors()) if (!Modifier.isAbstract(constructor.getModifiers()) && Modifier.isPublic(constructor.getModifiers()) ? hook.isVisible() : !hook .isVisible()) listMember.add(constructor); break; } else { for (Method method : clazz.getDeclaredMethods()) if (method.getName().equals(hook.getMethodName()) && !Modifier.isAbstract(method.getModifiers()) && (Modifier.isPublic(method.getModifiers()) ? hook.isVisible() : !hook.isVisible())) { // Check for same function in sub class boolean different = true; for (Class<?>[] parameters : listParameters) { boolean same = (parameters.length == method.getParameterTypes().length); for (int p = 0; same && p < parameters.length; p++) if (!parameters[p].equals(method.getParameterTypes()[p])) { same = false; break; } if (same) { different = false; break; } } if (different) { listMember.add(method); listParameters.add(method.getParameterTypes()); } } } clazz = clazz.getSuperclass(); } catch (Throwable ex) { if (ex.getClass().equals(ClassNotFoundException.class) || ex.getClass().equals(NoClassDefFoundError.class)) break; else throw ex; } // Hook members for (Member member : listMember) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) if ((member.getModifiers() & Modifier.NATIVE) != 0) Util.log(hook, Log.WARN, "Native method=" + member); XposedBridge.hookMethod(member, new XMethodHook(hook)); } catch (NoSuchFieldError ex) { Util.log(hook, Log.WARN, ex.toString()); } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } // Check if members found if (listMember.isEmpty() && !hook.getClassName().startsWith("com.google.android.gms")) { String message = "Method not found hook=" + hook; int level = (md != null && md.isOptional() ? Log.WARN : Log.ERROR); if ("isXposedEnabled".equals(hook.getMethodName())) level = Log.WARN; if (level == Log.ERROR) mListHookError.add(message); Util.log(hook, level, message); } } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } } // Helper classes private static class XMethodHook extends XC_MethodHook { private XHook mHook; public XMethodHook(XHook hook) { mHook = hook; } @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { try { // Do not restrict Zygote if (Process.myUid() <= 0) return; // Pre processing XParam xparam = XParam.fromXposed(param); long start = System.currentTimeMillis(); // Execute hook mHook.before(xparam); long ms = System.currentTimeMillis() - start; if (ms > PrivacyManager.cWarnHookDelayMs) Util.log(mHook, Log.WARN, String.format("%s %d ms", param.method.getName(), ms)); // Post processing if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); param.setObjectExtra("xextra", xparam.getExtras()); } catch (Throwable ex) { Util.bug(null, ex); } } @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { if (!param.hasThrowable()) try { // Do not restrict Zygote if (Process.myUid() <= 0) return; // Pre processing XParam xparam = XParam.fromXposed(param); xparam.setExtras(param.getObjectExtra("xextra")); long start = System.currentTimeMillis(); // Execute hook mHook.after(xparam); long ms = System.currentTimeMillis() - start; if (ms > PrivacyManager.cWarnHookDelayMs) Util.log(mHook, Log.WARN, String.format("%s %d ms", param.method.getName(), ms)); // Post processing if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); } catch (Throwable ex) { Util.bug(null, ex); } } }; }
22,526
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XCamera.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XCamera.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; public class XCamera extends XHook { private Methods mMethod; private XCamera(Methods method, String restrictionName) { super(restrictionName, method.name(), "Camera." + method.name()); mMethod = method; } public String getClassName() { return "android.hardware.Camera"; } // @formatter:off // public void setPreviewCallback(Camera.PreviewCallback cb) // public void setPreviewCallbackWithBuffer(Camera.PreviewCallback cb) // public void setPreviewDisplay(SurfaceHolder holder) // public void setPreviewTexture(SurfaceTexture surfaceTexture) // public final void setOneShotPreviewCallback (Camera.PreviewCallback cb) // public native final void startPreview() // public void stopPreview() // public final void takePicture(ShutterCallback shutter, PictureCallback raw, PictureCallback jpeg) // public final void takePicture(ShutterCallback shutter, PictureCallback raw, PictureCallback postview, PictureCallback jpeg) // frameworks/base/core/java/android/hardware/Camera.java // http://developer.android.com/reference/android/hardware/Camera.html // @formatter:on private enum Methods { setPreviewCallback, setPreviewCallbackWithBuffer, setPreviewDisplay, setPreviewTexture, setOneShotPreviewCallback, startPreview, stopPreview, takePicture }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); for (Methods cam : Methods.values()) listHook.add(new XCamera(cam, cam == Methods.stopPreview ? null : PrivacyManager.cMedia)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case setPreviewCallback: case setPreviewCallbackWithBuffer: case setPreviewDisplay: case setPreviewTexture: case setOneShotPreviewCallback: case startPreview: case takePicture: if (isRestricted(param)) param.setResult(null); break; case stopPreview: if (isRestricted(param, PrivacyManager.cMedia, "Camera.startPreview")) param.setResult(null); break; } } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
2,182
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
RState.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/RState.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Process; public class RState { public int mUid; public String mRestrictionName; public String mMethodName; public boolean restricted; public boolean asked = false; public boolean partialRestricted = false; public boolean partialAsk = false; public RState(int uid, String restrictionName, String methodName, Version version) { mUid = uid; mRestrictionName = restrictionName; mMethodName = methodName; int userId = Util.getUserId(Process.myUid()); // Get if on demand boolean onDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true); if (onDemand) onDemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, false); boolean allRestricted = true; boolean someRestricted = false; boolean allAsk = true; boolean someAsk = false; if (methodName == null) { if (restrictionName == null) { // Examine the category state someAsk = onDemand; for (String rRestrictionName : PrivacyManager.getRestrictions()) { PRestriction query = PrivacyManager.getRestrictionEx(uid, rRestrictionName, null); allRestricted = (allRestricted && query.restricted); someRestricted = (someRestricted || query.restricted); allAsk = (allAsk && !query.asked); someAsk = (someAsk || !query.asked); } asked = !onDemand; } else { // Examine the category/method states PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, null); someRestricted = query.restricted; someAsk = !query.asked; for (PRestriction restriction : PrivacyManager.getRestrictionList(uid, restrictionName)) { Hook hook = PrivacyManager.getHook(restrictionName, restriction.methodName); if (version != null && hook != null && hook.getFrom() != null && version.compareTo(hook.getFrom()) < 0) continue; allRestricted = (allRestricted && restriction.restricted); someRestricted = (someRestricted || restriction.restricted); if (hook == null || hook.canOnDemand()) { allAsk = (allAsk && !restriction.asked); someAsk = (someAsk || !restriction.asked); } } asked = query.asked; } } else { // Examine the method state PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, methodName); allRestricted = query.restricted; someRestricted = false; asked = query.asked; } boolean isApp = PrivacyManager.isApplication(uid); boolean odSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false); restricted = (allRestricted || someRestricted); asked = (!onDemand || !(isApp || odSystem) || asked); partialRestricted = (!allRestricted && someRestricted); partialAsk = (onDemand && (isApp || odSystem) && !allAsk && someAsk); } public void toggleRestriction() { if (mMethodName == null) { // Get restrictions to change List<String> listRestriction; if (mRestrictionName == null) listRestriction = PrivacyManager.getRestrictions(); else { listRestriction = new ArrayList<String>(); listRestriction.add(mRestrictionName); } // Change restriction if (restricted) PrivacyManager.deleteRestrictions(mUid, mRestrictionName, (mRestrictionName == null)); else { for (String restrictionName : listRestriction) PrivacyManager.setRestriction(mUid, restrictionName, null, true, false); PrivacyManager.updateState(mUid); } } else { PRestriction query = PrivacyManager.getRestrictionEx(mUid, mRestrictionName, null); PrivacyManager.setRestriction(mUid, mRestrictionName, mMethodName, !restricted, query.asked); PrivacyManager.updateState(mUid); } } public void toggleAsked() { asked = !asked; if (mRestrictionName == null) PrivacyManager.setSetting(mUid, PrivacyManager.cSettingOnDemand, Boolean.toString(!asked)); else { // Avoid re-doing all exceptions for dangerous functions List<PRestriction> listPRestriction = new ArrayList<PRestriction>(); listPRestriction.add(new PRestriction(mUid, mRestrictionName, mMethodName, restricted, asked)); PrivacyManager.setRestrictionList(listPRestriction); PrivacyManager.setSetting(mUid, PrivacyManager.cSettingState, Integer.toString(ApplicationInfoEx.STATE_CHANGED)); PrivacyManager.setSetting(mUid, PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis())); } } }
4,485
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
Requirements.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/Requirements.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.Inet4Address; import java.net.InterfaceAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.location.GpsStatus; import android.net.Uri; import android.net.wifi.WifiInfo; import android.os.Build; import android.os.IBinder; import android.text.TextUtils; import android.util.Log; public class Requirements { private static String[] cIncompatible = new String[] { "com.lbe.security" }; @SuppressWarnings("unchecked") public static void check(final ActivityBase context) { // Check Android version if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(R.string.app_name); alertDialogBuilder.setMessage(R.string.app_wrongandroid); alertDialogBuilder.setIcon(context.getThemed(R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent androidIntent = new Intent(Intent.ACTION_VIEW); androidIntent.setData(Uri.parse("https://github.com/M66B/XPrivacy#installation")); context.startActivity(androidIntent); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } // Check if XPrivacy is enabled if (Util.isXposedEnabled()) { // Check privacy client try { if (PrivacyService.checkClient()) { List<String> listError = (List<String>) PrivacyService.getClient().check(); if (listError.size() > 0) sendSupportInfo(TextUtils.join("\r\n", listError), context); } } catch (Throwable ex) { sendSupportInfo(ex.toString(), context); } } else { // @formatter:off AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(R.string.app_name); alertDialogBuilder.setMessage(R.string.app_notenabled); alertDialogBuilder.setIcon(context.getThemed(R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent xInstallerIntent = new Intent("de.robv.android.xposed.installer.OPEN_SECTION") .setPackage("de.robv.android.xposed.installer") .putExtra("section", "modules") .putExtra("module", context.getPackageName()) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(xInstallerIntent); } }); // @formatter:on AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } // Check pro enabler Version version = Util.getProEnablerVersion(context); if (version != null && !Util.isValidProEnablerVersion(version)) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(R.string.app_name); alertDialogBuilder.setMessage(R.string.app_wrongenabler); alertDialogBuilder.setIcon(context.getThemed(R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent storeIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName() + ".pro")); context.startActivity(storeIntent); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } // Check incompatible apps checkCompatibility(context); // Check activity thread try { Class<?> clazz = Class.forName("android.app.ActivityThread", false, null); try { clazz.getDeclaredMethod("unscheduleGcIdler"); } catch (NoSuchMethodException ex) { reportClass(clazz, context); } } catch (ClassNotFoundException ex) { sendSupportInfo(ex.toString(), context); } // Check activity thread receiver data try { Class<?> clazz = Class.forName("android.app.ActivityThread$ReceiverData", false, null); if (!checkField(clazz, "intent")) reportClass(clazz, context); } catch (ClassNotFoundException ex) { try { reportClass(Class.forName("android.app.ActivityThread", false, null), context); } catch (ClassNotFoundException exex) { sendSupportInfo(exex.toString(), context); } } // Check file utils try { Class<?> clazz = Class.forName("android.os.FileUtils", false, null); try { clazz.getDeclaredMethod("setPermissions", String.class, int.class, int.class, int.class); } catch (NoSuchMethodException ex) { reportClass(clazz, context); } } catch (ClassNotFoundException ex) { sendSupportInfo(ex.toString(), context); } // Check interface address if (!checkField(InterfaceAddress.class, "address") || !checkField(InterfaceAddress.class, "broadcastAddress") || (PrivacyService.getClient() != null && PrivacyManager.getDefacedProp(0, "InetAddress") == null)) reportClass(InterfaceAddress.class, context); // Check package manager service if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) try { Class<?> clazz = Class.forName("com.android.server.pm.PackageManagerService", false, null); try { try { clazz.getDeclaredMethod("getPackageUid", String.class, int.class); } catch (NoSuchMethodException ignored) { clazz.getDeclaredMethod("getPackageUid", String.class); } } catch (NoSuchMethodException ex) { reportClass(clazz, context); } } catch (ClassNotFoundException ex) { sendSupportInfo(ex.toString(), context); } // Check GPS status if (!checkField(GpsStatus.class, "mSatellites")) reportClass(GpsStatus.class, context); // Check service manager try { Class<?> clazz = Class.forName("android.os.ServiceManager", false, null); try { // @formatter:off // public static void addService(String name, IBinder service) // public static void addService(String name, IBinder service, boolean allowIsolated) // public static String[] listServices() // public static IBinder checkService(String name) // @formatter:on Method listServices = clazz.getDeclaredMethod("listServices"); Method getService = clazz.getDeclaredMethod("getService", String.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) clazz.getDeclaredMethod("addService", String.class, IBinder.class, boolean.class); else clazz.getDeclaredMethod("addService", String.class, IBinder.class); // Get services Map<String, String> mapService = new HashMap<String, String>(); String[] services = (String[]) listServices.invoke(null); if (services != null) for (String service : services) if (service != null) { IBinder binder = (IBinder) getService.invoke(null, service); String descriptor = (binder == null ? null : binder.getInterfaceDescriptor()); mapService.put(service, descriptor); } if (mapService.size() > 0) { // Check services int i = 0; List<String> listMissing = new ArrayList<String>(); for (String name : XBinder.cServiceName) { String descriptor = XBinder.cServiceDescriptor.get(i++); if (descriptor != null && !XBinder.cServiceOptional.contains(name)) { // Check name boolean checkDescriptor = false; if (name.equals("telephony.registry")) { if (mapService.containsKey(name)) checkDescriptor = true; else if (!mapService.containsKey("telephony.msim.registry")) listMissing.add(name); } else if (name.equals("telephony.msim.registry")) { if (mapService.containsKey(name)) checkDescriptor = true; else if (!mapService.containsKey("telephony.registry")) listMissing.add(name); } else if (name.equals("bluetooth")) { if (mapService.containsKey(name)) checkDescriptor = true; else if (!mapService.containsKey("bluetooth_manager")) listMissing.add(name); } else if (name.equals("bluetooth_manager")) { if (mapService.containsKey(name)) checkDescriptor = true; else if (!mapService.containsKey("bluetooth")) listMissing.add(name); } else { if (mapService.containsKey(name)) checkDescriptor = true; else listMissing.add(name); } // Check descriptor if (checkDescriptor) { String d = mapService.get(name); if (d != null && !d.equals(descriptor)) listMissing.add(descriptor); } } } // Check result if (listMissing.size() > 0) { List<String> listService = new ArrayList<String>(); for (String service : mapService.keySet()) listService.add(String.format("%s: %s", service, mapService.get(service))); sendSupportInfo("Missing:\r\n" + TextUtils.join("\r\n", listMissing) + "\r\n\r\nAvailable:\r\n" + TextUtils.join("\r\n", listService), context); } } } catch (NoSuchMethodException ex) { reportClass(clazz, context); } catch (Throwable ex) { Util.bug(null, ex); } } catch (ClassNotFoundException ex) { sendSupportInfo(ex.toString(), context); } // Check wifi info if (!checkField(WifiInfo.class, "mSupplicantState") || !checkField(WifiInfo.class, "mBSSID") || !checkField(WifiInfo.class, "mIpAddress") || !checkField(WifiInfo.class, "mMacAddress") || !(checkField(WifiInfo.class, "mSSID") || checkField(WifiInfo.class, "mWifiSsid"))) reportClass(WifiInfo.class, context); // Check mWifiSsid.octets if (checkField(WifiInfo.class, "mWifiSsid")) try { Class<?> clazz = Class.forName("android.net.wifi.WifiSsid", false, null); try { clazz.getDeclaredMethod("createFromAsciiEncoded", String.class); } catch (NoSuchMethodException ex) { reportClass(clazz, context); } } catch (ClassNotFoundException ex) { sendSupportInfo(ex.toString(), context); } // Check Inet4Address/ANY try { Inet4Address.class.getDeclaredField("ANY"); } catch (Throwable ex) { reportClass(Inet4Address.class, context); } // Check context services checkService(context, Context.ACCOUNT_SERVICE, new String[] { "android.accounts.AccountManager", "com.intel.arkham.ExtendAccountManager" /* Asus */, "android.privacy.surrogate.PrivacyAccountManager" /* PDroid */}); checkService(context, Context.ACTIVITY_SERVICE, new String[] { "android.app.ActivityManager", "android.app.ActivityManagerEx" }); checkService(context, Context.CLIPBOARD_SERVICE, new String[] { "android.content.ClipboardManager" }); checkService(context, Context.CONNECTIVITY_SERVICE, new String[] { "android.net.ConnectivityManager", "android.net.ConnectivityManagerEx", "android.net.MultiSimConnectivityManager", "android.privacy.surrogate.PrivacyConnectivityManager" /* PDroid */}); checkService(context, Context.LOCATION_SERVICE, new String[] { "android.location.LocationManager", "android.location.ZTEPrivacyLocationManager", "android.privacy.surrogate.PrivacyLocationManager" /* PDroid */}); Class<?> serviceClass = context.getPackageManager().getClass(); if (!"android.app.ApplicationPackageManager".equals(serviceClass.getName()) && !"amazon.content.pm.AmazonPackageManagerImpl".equals(serviceClass.getName())) reportClass(serviceClass, context); checkService(context, Context.SENSOR_SERVICE, new String[] { "android.hardware.SensorManager", "android.hardware.SystemSensorManager" }); checkService(context, Context.TELEPHONY_SERVICE, new String[] { "android.telephony.TelephonyManager", "android.telephony.MSimTelephonyManager", "android.telephony.MultiSimTelephonyManager", "android.telephony.ZTEPrivacyTelephonyManager", "android.telephony.ZTEPrivacyMSimTelephonyManager", "com.motorola.android.telephony.MotoTelephonyManager", "android.privacy.surrogate.PrivacyTelephonyManager" /* PDroid */}); checkService(context, Context.WINDOW_SERVICE, new String[] { "android.view.WindowManagerImpl", "android.view.Window$LocalWindowManager", "amazon.view.AmazonWindowManagerImpl" }); checkService(context, Context.WIFI_SERVICE, new String[] { "android.net.wifi.WifiManager", "com.amazon.net.AmazonWifiManager", "com.amazon.android.service.AmazonWifiManager", "android.privacy.surrogate.PrivacyWifiManager" /* PDroid */}); } public static void checkService(ActivityBase context, String name, String[] className) { Object service = context.getSystemService(name); if (service == null) sendSupportInfo("Service missing name=" + name, context); else if (!Arrays.asList(className).contains(service.getClass().getName())) reportClass(service.getClass(), context); } public static void checkCompatibility(ActivityBase context) { for (String packageName : cIncompatible) try { ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(packageName, 0); if (appInfo.enabled) { String name = context.getPackageManager().getApplicationLabel(appInfo).toString(); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(R.string.app_name); alertDialogBuilder.setMessage(String.format(context.getString(R.string.app_incompatible), name)); alertDialogBuilder.setIcon(context.getThemed(R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } } catch (NameNotFoundException ex) { } } private static boolean checkField(Class<?> clazz, String fieldName) { try { clazz.getDeclaredField(fieldName); return true; } catch (NoSuchFieldException ex) { return false; } } private static void reportClass(Class<?> clazz, ActivityBase context) { StringBuilder sb = new StringBuilder(); sb.append(String.format("Incompatible %s", clazz.getName())); sb.append("\r\n"); sb.append("\r\n"); for (Constructor<?> constructor : clazz.getConstructors()) { sb.append(constructor.toString()); sb.append("\r\n"); } sb.append("\r\n"); for (Method method : clazz.getDeclaredMethods()) { sb.append(method.toString()); sb.append("\r\n"); } sb.append("\r\n"); for (Field field : clazz.getDeclaredFields()) { sb.append(field.toString()); sb.append("\r\n"); } sb.append("\r\n"); sendSupportInfo(sb.toString(), context); } public static void sendSupportInfo(final String text, final ActivityBase context) { Util.log(null, Log.WARN, text); if (Util.hasValidFingerPrint(context) && !"Genymotion".equals(Build.MANUFACTURER)) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(R.string.app_name); alertDialogBuilder.setMessage(R.string.msg_support_info); alertDialogBuilder.setIcon(context.getThemed(R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int _which) { String ourVersion = Util.getSelfVersionName(context); StringBuilder sb = new StringBuilder(text); sb.insert(0, "\r\n"); sb.insert(0, String.format("Id: %s\r\n", Build.ID)); sb.insert(0, String.format("Display: %s\r\n", Build.DISPLAY)); sb.insert(0, String.format("Host: %s\r\n", Build.HOST)); sb.insert(0, String.format("Device: %s\r\n", Build.DEVICE)); sb.insert(0, String.format("Product: %s\r\n", Build.PRODUCT)); sb.insert(0, String.format("Model: %s\r\n", Build.MODEL)); sb.insert(0, String.format("Manufacturer: %s\r\n", Build.MANUFACTURER)); sb.insert(0, String.format("Brand: %s\r\n", Build.BRAND)); sb.insert(0, "\r\n"); sb.insert(0, String.format("Android: %s (SDK %d)\r\n", Build.VERSION.RELEASE, Build.VERSION.SDK_INT)); sb.insert(0, String.format("XPrivacy: %s\r\n", ourVersion)); Intent sendEmail = new Intent(Intent.ACTION_SEND); sendEmail.setType("message/rfc822"); sendEmail.putExtra(Intent.EXTRA_EMAIL, new String[] { "marcel+support@faircode.eu" }); sendEmail.putExtra(Intent.EXTRA_SUBJECT, "XPrivacy " + ourVersion + "/" + Build.VERSION.RELEASE + " support info"); sendEmail.putExtra(Intent.EXTRA_TEXT, sb.toString()); try { context.startActivity(sendEmail); } catch (Throwable ex) { Util.bug(null, ex); } } }); alertDialogBuilder.setNegativeButton(context.getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } } }
17,652
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XSystemProperties.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XSystemProperties.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Binder; import android.util.Log; public class XSystemProperties extends XHook { private Methods mMethod; private String mPropertyName; private XSystemProperties(Methods method, String restrictionName, String propertyName) { super(restrictionName, method.name(), propertyName); mMethod = method; mPropertyName = propertyName; } public String getClassName() { return "android.os.SystemProperties"; } // public static String get(String key) // public static String get(String key, String def) // public static boolean getBoolean(String key, boolean def) // public static int getInt(String key, int def) // public static long getLong(String key, long def) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/android/os/SystemProperties.java/ private enum Methods { get, getBoolean, getInt, getLong }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); String[] props = new String[] { "%imei", "%hostname", "%serialno", "%macaddr", "%cid" }; for (String prop : props) for (Methods getter : Methods.values()) listHook.add(new XSystemProperties(getter, PrivacyManager.cIdentification, prop)); return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { String key = (param.args.length > 0 ? (String) param.args[0] : null); if (key != null) if (mPropertyName.startsWith("%") ? key.contains(mPropertyName.substring(1)) : key.equals(mPropertyName)) if (mMethod == Methods.get) { if (param.getResult() != null && isRestrictedExtra(param, mPropertyName, key)) param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), mPropertyName)); } else if (param.args.length > 1) { if (isRestrictedExtra(param, mPropertyName, key)) param.setResult(param.args[1]); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } }
2,129
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XActivityRecognitionClient.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XActivityRecognitionClient.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; public class XActivityRecognitionClient extends XHook { private Methods mMethod; private XActivityRecognitionClient(Methods method, String restrictionName) { super(restrictionName, method.name(), String.format("GMS.%s", method.name())); mMethod = method; } public String getClassName() { return "com.google.android.gms.location.ActivityRecognitionClient"; } // @formatter:off // public void removeActivityUpdates(PendingIntent callbackIntent) // public void requestActivityUpdates(long detectionIntervalMillis, PendingIntent callbackIntent) // http://developer.android.com/reference/com/google/android/gms/location/ActivityRecognitionClient.html // @formatter:on private enum Methods { removeActivityUpdates, requestActivityUpdates }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XActivityRecognitionClient(Methods.removeActivityUpdates, null)); listHook.add(new XActivityRecognitionClient(Methods.requestActivityUpdates, PrivacyManager.cLocation)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case removeActivityUpdates: if (isRestricted(param, PrivacyManager.cLocation, "GMS.requestActivityUpdates")) param.setResult(null); break; case requestActivityUpdates: if (isRestricted(param)) param.setResult(null); break; } } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
1,584
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XIoBridge.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XIoBridge.java
package biz.bokhorst.xprivacy; import java.io.FileNotFoundException; import java.net.InetAddress; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.os.Binder; import android.os.Process; import android.text.TextUtils; import android.util.Log; public class XIoBridge extends XHook { private Methods mMethod; private String mFileName; private static String mExternalStorage = null; private static String mEmulatedSource = null; private static String mEmulatedTarget = null; private static String mMediaStorage = null; private static String mSecondaryStorage = null; private XIoBridge(Methods method, String restrictionName) { super(restrictionName, method.name(), null); mMethod = method; mFileName = null; } private XIoBridge(Methods method, String restrictionName, String fileName) { super(restrictionName, method.name(), fileName); mMethod = method; mFileName = fileName; } public String getClassName() { return "libcore.io.IoBridge"; } // @formatter:off // public static void connect(FileDescriptor fd, InetAddress inetAddress, int port) throws SocketException // public static void connect(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs) throws SocketException, SocketTimeoutException // public static FileDescriptor open(String path, int flags) throws FileNotFoundException // public static FileDescriptor socket(boolean stream) throws SocketException // https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/Environment.java // https://android.googlesource.com/platform/libcore/+/android-5.0.1_r1/luni/src/main/java/libcore/io/IoBridge.java // @formatter:on private enum Methods { open, connect }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XIoBridge(Methods.connect, PrivacyManager.cInternet)); listHook.add(new XIoBridge(Methods.open, PrivacyManager.cStorage)); listHook.add(new XIoBridge(Methods.open, PrivacyManager.cIdentification, "/proc")); listHook.add(new XIoBridge(Methods.open, PrivacyManager.cIdentification, "/system/build.prop")); listHook.add(new XIoBridge(Methods.open, PrivacyManager.cIdentification, "/sys/block/.../cid")); listHook.add(new XIoBridge(Methods.open, PrivacyManager.cIdentification, "/sys/class/.../cid")); return listHook; } @Override @SuppressLint("SdCardPath") protected void before(XParam param) throws Throwable { if (mMethod == Methods.connect) { if (param.args.length > 2 && param.args[1] instanceof InetAddress && param.args[2] instanceof Integer) { InetAddress address = (InetAddress) param.args[1]; int port = (Integer) param.args[2]; String hostName; int uid = Binder.getCallingUid(); boolean resolve = PrivacyManager.getSettingBool(uid, PrivacyManager.cSettingResolve, false); boolean noresolve = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingNoResolve, false); if (resolve && !noresolve) try { hostName = address.getHostName(); } catch (Throwable ignored) { hostName = address.toString(); } else hostName = address.toString(); if (isRestrictedExtra(param, hostName + ":" + port)) param.setThrowable(new SocketException("XPrivacy")); } } else if (mMethod == Methods.open) { if (param.args.length > 0) { String fileName = (String) param.args[0]; if (mFileName == null && fileName != null) { // Get storage folders if (mExternalStorage == null) { mExternalStorage = System.getenv("EXTERNAL_STORAGE"); mEmulatedSource = System.getenv("EMULATED_STORAGE_SOURCE"); mEmulatedTarget = System.getenv("EMULATED_STORAGE_TARGET"); mMediaStorage = System.getenv("MEDIA_STORAGE"); mSecondaryStorage = System.getenv("SECONDARY_STORAGE"); if (TextUtils.isEmpty(mMediaStorage)) mMediaStorage = "/data/media"; } // Check storage folders if (fileName.startsWith("/sdcard") || (mExternalStorage != null && fileName.startsWith(mExternalStorage)) || (mEmulatedSource != null && fileName.startsWith(mEmulatedSource)) || (mEmulatedTarget != null && fileName.startsWith(mEmulatedTarget)) || (mMediaStorage != null && fileName.startsWith(mMediaStorage)) || (mSecondaryStorage != null && fileName.startsWith(mSecondaryStorage))) if (isRestrictedExtra(param, fileName)) param.setThrowable(new FileNotFoundException("XPrivacy")); } else if (fileName.startsWith(mFileName) || mFileName.contains("...")) { // Zygote, Android if (Util.getAppId(Process.myUid()) == Process.SYSTEM_UID) return; // Proc white list if (mFileName.equals("/proc")) if ("/proc/self/cmdline".equals(fileName)) return; // Check if restricted if (mFileName.contains("...")) { String[] component = mFileName.split("\\.\\.\\."); if (fileName.startsWith(component[0]) && fileName.endsWith(component[1])) if (isRestricted(param, mFileName)) param.setThrowable(new FileNotFoundException("XPrivacy")); } else if (mFileName.equals("/proc")) { if (isRestrictedExtra(param, mFileName, fileName)) param.setThrowable(new FileNotFoundException("XPrivacy")); } else { if (isRestricted(param, mFileName)) param.setThrowable(new FileNotFoundException("XPrivacy")); } } } } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
5,660
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XActivityThread.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XActivityThread.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Intent; import android.nfc.NfcAdapter; import android.os.Binder; import android.os.Message; import android.provider.Telephony; import android.service.notification.NotificationListenerService; import android.telephony.TelephonyManager; import android.util.Log; @SuppressLint("InlinedApi") public class XActivityThread extends XHook { private Methods mMethod; private static Map<String, String> mapActionRestriction = new HashMap<String, String>(); static { // Intent receive: calling mapActionRestriction.put(Intent.ACTION_NEW_OUTGOING_CALL, PrivacyManager.cCalling); mapActionRestriction.put(TelephonyManager.ACTION_PHONE_STATE_CHANGED, PrivacyManager.cPhone); mapActionRestriction.put(TelephonyManager.ACTION_RESPOND_VIA_MESSAGE, PrivacyManager.cCalling); // Intent receive: C2DM mapActionRestriction.put("com.google.android.c2dm.intent.REGISTRATION", PrivacyManager.cNotifications); mapActionRestriction.put("com.google.android.c2dm.intent.RECEIVE", PrivacyManager.cNotifications); // Intent receive: NFC mapActionRestriction.put(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED, PrivacyManager.cNfc); mapActionRestriction.put(NfcAdapter.ACTION_NDEF_DISCOVERED, PrivacyManager.cNfc); mapActionRestriction.put(NfcAdapter.ACTION_TAG_DISCOVERED, PrivacyManager.cNfc); mapActionRestriction.put(NfcAdapter.ACTION_TECH_DISCOVERED, PrivacyManager.cNfc); // Intent receive: SMS mapActionRestriction.put(Telephony.Sms.Intents.DATA_SMS_RECEIVED_ACTION, PrivacyManager.cMessages); mapActionRestriction.put(Telephony.Sms.Intents.SMS_RECEIVED_ACTION, PrivacyManager.cMessages); mapActionRestriction.put(Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION, PrivacyManager.cMessages); mapActionRestriction.put(Telephony.Sms.Intents.SMS_DELIVER_ACTION, PrivacyManager.cMessages); mapActionRestriction.put(Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION, PrivacyManager.cMessages); // Intent receive: notifications mapActionRestriction.put(NotificationListenerService.SERVICE_INTERFACE, PrivacyManager.cNotifications); // Intent receive: package changes mapActionRestriction.put(Intent.ACTION_PACKAGE_ADDED, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_PACKAGE_REPLACED, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_PACKAGE_RESTARTED, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_PACKAGE_REMOVED, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_PACKAGE_CHANGED, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_PACKAGE_DATA_CLEARED, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_PACKAGE_FIRST_LAUNCH, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_PACKAGE_FULLY_REMOVED, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_PACKAGE_VERIFIED, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE, PrivacyManager.cSystem); mapActionRestriction.put(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE, PrivacyManager.cSystem); } private XActivityThread(Methods method) { super(null, method.name(), null); mMethod = method; } public String getClassName() { return (mMethod == Methods.handleReceiver ? "android.app.ActivityThread" : "android.os.MessageQueue"); } @Override public boolean isVisible() { return false; } private enum Methods { next, handleReceiver }; // @formatter:off // private void handleReceiver(ReceiverData data) // frameworks/base/core/java/android/app/ActivityThread.java // final Message next() // frameworks/base/core/java/android/android/os/MessageQueue.java // @formatter:on public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XActivityThread(Methods.next)); listHook.add(new XActivityThread(Methods.handleReceiver)); return listHook; } @Override protected void before(XParam param) throws Throwable { if (mMethod == Methods.next) { // Do nothing } else if (mMethod == Methods.handleReceiver) { if (param.args.length > 0 && param.args[0] != null) { Field fieldIntent = param.args[0].getClass().getDeclaredField("intent"); fieldIntent.setAccessible(true); Intent intent = (Intent) fieldIntent.get(param.args[0]); if (intent != null) { if (checkIntent(Binder.getCallingUid(), intent)) { finish(param); param.setResult(null); } } } } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } @Override protected void after(XParam param) throws Throwable { if (mMethod == Methods.next) { Message msg = (Message) param.getResult(); if (msg != null) { if (msg.obj instanceof Intent) { Intent intent = (Intent) msg.obj; if (intent != null) if (checkIntent(Binder.getCallingUid(), intent)) param.setResult(null); } } } else if (mMethod == Methods.handleReceiver) { // Do nothing } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } private boolean checkIntent(int uid, Intent intent) throws Throwable { String action = intent.getAction(); if (mapActionRestriction.containsKey(action)) { // Get restriction category String restrictionName = mapActionRestriction.get(action); if (Intent.ACTION_NEW_OUTGOING_CALL.equals(action)) { // Outgoing call if (intent.hasExtra(Intent.EXTRA_PHONE_NUMBER)) { String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); if (phoneNumber != null) if (isRestrictedExtraValue(uid, restrictionName, action, phoneNumber, phoneNumber)) intent.putExtra(Intent.EXTRA_PHONE_NUMBER, (String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "PhoneNumber")); } } else if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(action)) { // Incoming call if (intent.hasExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)) { String phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); if (phoneNumber != null) { if (isRestrictedExtraValue(uid, restrictionName, action, phoneNumber, phoneNumber)) intent.putExtra(TelephonyManager.EXTRA_INCOMING_NUMBER, (String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "PhoneNumber")); } } } else if (PrivacyManager.cSystem.equals(restrictionName)) { // Package event if (isRestrictedExtra(uid, restrictionName, action, intent.getDataString())) { String[] packageNames; if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE) || action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) packageNames = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); else packageNames = new String[] { intent.getData().getSchemeSpecificPart() }; for (String packageName : packageNames) if (!XPackageManager.isPackageAllowed(0, packageName)) return true; } } else if (isRestrictedExtra(uid, restrictionName, action, intent.getDataString())) return true; } return false; } private void finish(XParam param) { // unscheduleGcIdler if (param.thisObject != null) try { Method unschedule = param.thisObject.getClass().getDeclaredMethod("unscheduleGcIdler"); unschedule.setAccessible(true); unschedule.invoke(param.thisObject); } catch (Throwable ex) { Util.bug(this, ex); } // data.finish if (param.args[0] instanceof BroadcastReceiver.PendingResult) try { BroadcastReceiver.PendingResult pr = (BroadcastReceiver.PendingResult) param.args[0]; pr.finish(); } catch (IllegalStateException ignored) { // No receivers for action ... } catch (Throwable ex) { Util.bug(this, ex); } } }
8,142
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
ActivityShare.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/ActivityShare.java
package biz.bokhorst.xprivacy; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.net.ssl.SSLException; import javax.xml.parsers.SAXParserFactory; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.HttpHostConnectException; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import org.json.JSONObject; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xmlpull.v1.XmlSerializer; import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.PowerManager; import android.os.Process; import android.provider.ContactsContract; import android.provider.Settings.Secure; import android.support.v4.app.NotificationCompat; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.util.Patterns; import android.util.SparseArray; import android.util.Xml; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TextView; import android.widget.EditText; import android.widget.Toast; @SuppressLint("Wakelock") public class ActivityShare extends ActivityBase { private int mActionId; private AppListAdapter mAppAdapter; private SparseArray<AppState> mAppsByUid; private boolean mRunning = false; private boolean mAbort = false; private int mProgressCurrent; private int mProgressWidth = 0; private String mFileName = null; private boolean mInteractive = false; private static final int STATE_WAITING = 0; private static final int STATE_RUNNING = 1; private static final int STATE_SUCCESS = 2; private static final int STATE_FAILURE = 3; private static final int ACTIVITY_IMPORT_SELECT = 0; public static final String cUidList = "UidList"; public static final String cRestriction = "Restriction"; public static final String cInteractive = "Interactive"; public static final String cChoice = "Choice"; public static final String cFileName = "FileName"; public static final String HTTP_BASE_URL = "http://crowd.xprivacy.eu/"; public static final String HTTPS_BASE_URL = "https://crowd.xprivacy.eu/"; public static final int cSubmitLimit = 10; public static final int cProtocolVersion = 4; public static final String ACTION_EXPORT = "biz.bokhorst.xprivacy.action.EXPORT"; public static final String ACTION_IMPORT = "biz.bokhorst.xprivacy.action.IMPORT"; public static final String ACTION_FETCH = "biz.bokhorst.xprivacy.action.FETCH"; public static final String ACTION_SUBMIT = "biz.bokhorst.xprivacy.action.SUBMIT"; public static final String ACTION_TOGGLE = "biz.bokhorst.xprivacy.action.TOGGLE"; public static final int CHOICE_CLEAR = 1; public static final int CHOICE_TEMPLATE = 2; public static final int TIMEOUT_MILLISEC = 45000; private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new PriorityThreadFactory()); private static class PriorityThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.NORM_PRIORITY); return t; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Check privacy service client if (!PrivacyService.checkClient()) return; // Get data int userId = Util.getUserId(Process.myUid()); final Bundle extras = getIntent().getExtras(); final String action = getIntent().getAction(); final int[] uids = (extras != null && extras.containsKey(cUidList) ? extras.getIntArray(cUidList) : new int[0]); final String restrictionName = (extras != null ? extras.getString(cRestriction) : null); int choice = (extras != null && extras.containsKey(cChoice) ? extras.getInt(cChoice) : -1); if (action.equals(ACTION_EXPORT)) mFileName = (extras != null && extras.containsKey(cFileName) ? extras.getString(cFileName) : null); // License check if (action.equals(ACTION_IMPORT) || action.equals(ACTION_EXPORT)) { if (!Util.isProEnabled() && Util.hasProLicense(this) == null) { Util.viewUri(this, ActivityMain.cProUri); finish(); return; } } else if (action.equals(ACTION_FETCH) || (action.equals(ACTION_TOGGLE) && uids.length > 1)) { if (Util.hasProLicense(this) == null) { Util.viewUri(this, ActivityMain.cProUri); finish(); return; } } // Registration check if (action.equals(ACTION_SUBMIT) && !registerDevice(this)) { finish(); return; } // Check whether we need a user interface if (extras != null && extras.containsKey(cInteractive) && extras.getBoolean(cInteractive, false)) mInteractive = true; // Set layout setContentView(R.layout.sharelist); setSupportActionBar((Toolbar) findViewById(R.id.widgetToolbar)); // Reference controls final TextView tvDescription = (TextView) findViewById(R.id.tvDescription); final ScrollView svToggle = (ScrollView) findViewById(R.id.svToggle); final RadioGroup rgToggle = (RadioGroup) findViewById(R.id.rgToggle); final Spinner spRestriction = (Spinner) findViewById(R.id.spRestriction); RadioButton rbClear = (RadioButton) findViewById(R.id.rbClear); RadioButton rbTemplateFull = (RadioButton) findViewById(R.id.rbTemplateFull); RadioButton rbODEnable = (RadioButton) findViewById(R.id.rbEnableOndemand); RadioButton rbODDisable = (RadioButton) findViewById(R.id.rbDisableOndemand); final Spinner spTemplate = (Spinner) findViewById(R.id.spTemplate); final CheckBox cbClear = (CheckBox) findViewById(R.id.cbClear); final Button btnOk = (Button) findViewById(R.id.btnOk); final Button btnCancel = (Button) findViewById(R.id.btnCancel); // Set title if (action.equals(ACTION_TOGGLE)) { mActionId = R.string.menu_toggle; getSupportActionBar().setSubtitle(R.string.menu_toggle); } else if (action.equals(ACTION_IMPORT)) { mActionId = R.string.menu_import; getSupportActionBar().setSubtitle(R.string.menu_import); } else if (action.equals(ACTION_EXPORT)) { mActionId = R.string.menu_export; getSupportActionBar().setSubtitle(R.string.menu_export); } else if (action.equals(ACTION_FETCH)) { mActionId = R.string.menu_fetch; getSupportActionBar().setSubtitle(R.string.menu_fetch); } else if (action.equals(ACTION_SUBMIT)) { mActionId = R.string.menu_submit; getSupportActionBar().setSubtitle(R.string.menu_submit); } else { finish(); return; } // Get localized restriction name List<String> listRestrictionName = new ArrayList<String>(PrivacyManager.getRestrictions(this).navigableKeySet()); listRestrictionName.add(0, getString(R.string.menu_all)); // Build restriction adapter SpinnerAdapter saRestriction = new SpinnerAdapter(this, android.R.layout.simple_spinner_item); saRestriction.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); saRestriction.addAll(listRestrictionName); // Setup restriction spinner int pos = 0; if (restrictionName != null) for (String restriction : PrivacyManager.getRestrictions(this).values()) { pos++; if (restrictionName.equals(restriction)) break; } spRestriction.setAdapter(saRestriction); spRestriction.setSelection(pos); // Build template adapter SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item); spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); String defaultName = PrivacyManager.getSetting(userId, Meta.cTypeTemplateName, "0", getString(R.string.title_default)); spAdapter.add(defaultName); for (int i = 1; i <= 4; i++) { String alternateName = PrivacyManager.getSetting(userId, Meta.cTypeTemplateName, Integer.toString(i), getString(R.string.title_alternate) + " " + i); spAdapter.add(alternateName); } spTemplate.setAdapter(spAdapter); // Build application list AppListTask appListTask = new AppListTask(); appListTask.executeOnExecutor(mExecutor, uids); // Import/export filename if (action.equals(ACTION_EXPORT) || action.equals(ACTION_IMPORT)) { // Check for availability of sharing intent Intent file = new Intent(Intent.ACTION_GET_CONTENT); file.setType("file/*"); boolean hasIntent = Util.isIntentAvailable(ActivityShare.this, file); // Get file name if (mFileName == null) if (action.equals(ACTION_EXPORT)) { String packageName = null; if (uids.length == 1) try { ApplicationInfoEx appInfo = new ApplicationInfoEx(this, uids[0]); packageName = appInfo.getPackageName().get(0); } catch (Throwable ex) { Util.bug(null, ex); } mFileName = getFileName(this, hasIntent, packageName); } else mFileName = (hasIntent ? null : getFileName(this, false, null)); if (mFileName == null) fileChooser(); else showFileName(); if (action.equals(ACTION_IMPORT)) cbClear.setVisibility(View.VISIBLE); } else if (action.equals(ACTION_FETCH)) { tvDescription.setText(getBaseURL()); cbClear.setVisibility(View.VISIBLE); } else if (action.equals(ACTION_TOGGLE)) { tvDescription.setVisibility(View.GONE); spRestriction.setVisibility(View.VISIBLE); svToggle.setVisibility(View.VISIBLE); // Listen for radio button rgToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { btnOk.setEnabled(checkedId >= 0); spRestriction.setVisibility(checkedId == R.id.rbEnableOndemand || checkedId == R.id.rbDisableOndemand ? View.GONE : View.VISIBLE); spTemplate .setVisibility(checkedId == R.id.rbTemplateCategory || checkedId == R.id.rbTemplateFull || checkedId == R.id.rbTemplateMergeSet || checkedId == R.id.rbTemplateMergeReset ? View.VISIBLE : View.GONE); } }); boolean ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true); rbODEnable.setVisibility(ondemand ? View.VISIBLE : View.GONE); rbODDisable.setVisibility(ondemand ? View.VISIBLE : View.GONE); if (choice == CHOICE_CLEAR) rbClear.setChecked(true); else if (choice == CHOICE_TEMPLATE) rbTemplateFull.setChecked(true); } else tvDescription.setText(getBaseURL()); if (mInteractive) { // Enable ok // (showFileName does this for export/import) if (action.equals(ACTION_SUBMIT) || action.equals(ACTION_FETCH)) btnOk.setEnabled(true); // Listen for ok btnOk.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { btnOk.setEnabled(false); // Toggle if (action.equals(ACTION_TOGGLE)) { mRunning = true; for (int i = 0; i < rgToggle.getChildCount(); i++) ((RadioButton) rgToggle.getChildAt(i)).setEnabled(false); int pos = spRestriction.getSelectedItemPosition(); String restrictionName = (pos == 0 ? null : (String) PrivacyManager .getRestrictions(ActivityShare.this).values().toArray()[pos - 1]); new ToggleTask().executeOnExecutor(mExecutor, restrictionName); // Import } else if (action.equals(ACTION_IMPORT)) { mRunning = true; cbClear.setEnabled(false); new ImportTask().executeOnExecutor(mExecutor, new File(mFileName), cbClear.isChecked()); } // Export else if (action.equals(ACTION_EXPORT)) { mRunning = true; new ExportTask().executeOnExecutor(mExecutor, new File(mFileName)); // Fetch } else if (action.equals(ACTION_FETCH)) { if (uids.length > 0) { mRunning = true; cbClear.setEnabled(false); new FetchTask().executeOnExecutor(mExecutor, cbClear.isChecked()); } } // Submit else if (action.equals(ACTION_SUBMIT)) { if (uids.length > 0) { if (uids.length <= cSubmitLimit) { mRunning = true; new SubmitTask().executeOnExecutor(mExecutor); } else { String message = getString(R.string.msg_limit, cSubmitLimit + 1); Toast.makeText(ActivityShare.this, message, Toast.LENGTH_LONG).show(); btnOk.setEnabled(false); } } } } }); } else btnOk.setEnabled(false); // Listen for cancel btnCancel.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { if (mRunning) { mAbort = true; Toast.makeText(ActivityShare.this, getString(R.string.msg_abort), Toast.LENGTH_LONG).show(); } else finish(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent dataIntent) { super.onActivityResult(requestCode, resultCode, dataIntent); // Import select if (requestCode == ACTIVITY_IMPORT_SELECT) if (resultCode == RESULT_CANCELED || dataIntent == null) finish(); else { String fileName = dataIntent.getData().getPath(); mFileName = fileName.replace("/document/primary:", Environment.getExternalStorageDirectory() .getAbsolutePath() + File.separatorChar); showFileName(); } } // State management public void setState(int uid, int state, String message) { final AppState app = mAppsByUid.get(uid); app.message = message; app.state = state; runOnUiThread(new Runnable() { @Override public void run() { if (mAppAdapter != null) { mAppAdapter.notifyDataSetChanged(); int position = mAppAdapter.getPosition(app); if (position >= 0) { ListView lvShare = (ListView) findViewById(R.id.lvShare); lvShare.smoothScrollToPosition(position); } } } }); } public void setState(int uid, int state) { AppState app = mAppsByUid.get(uid); app.state = state; } public void setMessage(int uid, String message) { AppState app = mAppsByUid.get(uid); app.message = message; } // App info and share state private class AppState implements Comparable<AppState> { public int state = STATE_WAITING; public String message = null; public ApplicationInfoEx appInfo; public AppState(int uid) { appInfo = new ApplicationInfoEx(ActivityShare.this, uid); } @Override public int compareTo(AppState other) { return this.appInfo.compareTo(other.appInfo); } } // Adapters private class SpinnerAdapter extends ArrayAdapter<String> { public SpinnerAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } } private class AppListAdapter extends ArrayAdapter<AppState> { private LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); public AppListAdapter(Context context, int resource, List<AppState> objects) { super(context, resource, objects); } public List<Integer> getListUid() { List<Integer> uids = new ArrayList<Integer>(); for (int i = 0; i < this.getCount(); i++) uids.add(this.getItem(i).appInfo.getUid()); return uids; } public List<ApplicationInfoEx> getListAppInfo() { List<ApplicationInfoEx> apps = new ArrayList<ApplicationInfoEx>(); for (int i = 0; i < this.getCount(); i++) apps.add(this.getItem(i).appInfo); return apps; } private class ViewHolder { private View row; private int position; public ImageView imgIcon; public ImageView imgInfo; public TextView tvName; public ImageView imgResult; public ProgressBar pbRunning; public TextView tvMessage; public ViewHolder(View theRow, int thePosition) { row = theRow; position = thePosition; imgIcon = (ImageView) row.findViewById(R.id.imgIcon); imgInfo = (ImageView) row.findViewById(R.id.imgInfo); tvName = (TextView) row.findViewById(R.id.tvApp); imgResult = (ImageView) row.findViewById(R.id.imgResult); pbRunning = (ProgressBar) row.findViewById(R.id.pbRunning); tvMessage = (TextView) row.findViewById(R.id.tvMessage); } } @Override @SuppressLint("InflateParams") public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.shareentry, null); holder = new ViewHolder(convertView, position); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); holder.position = position; } // Get info final AppState xApp = getItem(holder.position); // Set background color if (xApp.appInfo.isSystem()) holder.row.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous))); else holder.row.setBackgroundColor(Color.TRANSPARENT); // Display icon holder.imgIcon.setImageDrawable(xApp.appInfo.getIcon(ActivityShare.this)); holder.imgIcon.setVisibility(View.VISIBLE); holder.imgInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Packages can be selected on the web site Util.viewUri(ActivityShare.this, Uri.parse(String.format(getBaseURL() + "?package_name=%s", xApp.appInfo.getPackageName().get(0)))); } }); // Set app name holder.tvName.setText(xApp.appInfo.toString()); // Show app share state if (TextUtils.isEmpty(xApp.message)) holder.tvMessage.setVisibility(View.GONE); else { holder.tvMessage.setVisibility(View.VISIBLE); holder.tvMessage.setText(xApp.message); } switch (xApp.state) { case STATE_WAITING: holder.imgResult.setVisibility(View.GONE); holder.pbRunning.setVisibility(View.GONE); break; case STATE_RUNNING: holder.imgResult.setVisibility(View.GONE); holder.pbRunning.setVisibility(View.VISIBLE); break; case STATE_SUCCESS: holder.imgResult.setBackgroundResource(R.drawable.btn_check_buttonless_on); holder.imgResult.setVisibility(View.VISIBLE); holder.pbRunning.setVisibility(View.GONE); break; case STATE_FAILURE: holder.imgResult.setBackgroundResource(R.drawable.indicator_input_error); holder.imgResult.setVisibility(View.VISIBLE); holder.pbRunning.setVisibility(View.GONE); break; default: Util.log(null, Log.ERROR, "Unknown state=" + xApp.state); break; } return convertView; } } // Tasks private class AppListTask extends AsyncTask<int[], Object, List<AppState>> { private ProgressDialog mProgressDialog; @Override protected List<AppState> doInBackground(int[]... params) { int[] uids = params[0]; List<AppState> apps = new ArrayList<AppState>(); mAppsByUid = new SparseArray<AppState>(); if (!mInteractive && mActionId == R.string.menu_export) { // Build list of distinct uids for export List<Integer> listUid = new ArrayList<Integer>(); for (PackageInfo pInfo : getPackageManager().getInstalledPackages(0)) if (!listUid.contains(pInfo.applicationInfo.uid)) listUid.add(pInfo.applicationInfo.uid); // Convert to primitive array uids = new int[listUid.size()]; for (int i = 0; i < listUid.size(); i++) uids[i] = listUid.get(i); } mProgressDialog.setMax(uids.length); for (int i = 0; i < uids.length; i++) { mProgressDialog.setProgress(i); AppState app = new AppState(uids[i]); apps.add(app); mAppsByUid.put(uids[i], app); } Collections.sort(apps); return apps; } @SuppressWarnings("deprecation") @Override protected void onPreExecute() { super.onPreExecute(); TypedArray ta = getTheme().obtainStyledAttributes(new int[] { R.attr.progress_horizontal }); int progress_horizontal = ta.getResourceId(0, 0); ta.recycle(); // Show progress dialog mProgressDialog = new ProgressDialog(ActivityShare.this); mProgressDialog.setMessage(getString(R.string.msg_loading)); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setProgressDrawable(getResources().getDrawable(progress_horizontal)); mProgressDialog.setProgressNumberFormat(null); mProgressDialog.setCancelable(false); mProgressDialog.setCanceledOnTouchOutside(false); mProgressDialog.show(); } @Override protected void onPostExecute(List<AppState> listApp) { if (!ActivityShare.this.isFinishing()) { // Display app list mAppAdapter = new AppListAdapter(ActivityShare.this, R.layout.shareentry, listApp); ListView lvShare = (ListView) findViewById(R.id.lvShare); lvShare.setAdapter(mAppAdapter); // Dismiss progress dialog if (mProgressDialog.isShowing()) try { mProgressDialog.dismiss(); } catch (IllegalArgumentException ignored) { } // Launch non-interactive export if (!mInteractive && mActionId == R.string.menu_export) { mRunning = true; new ExportTask().executeOnExecutor(mExecutor, new File(mFileName)); } } super.onPostExecute(listApp); } } private class ToggleTask extends AsyncTask<String, Integer, Throwable> { @Override protected Throwable doInBackground(String... params) { // Get wakelock PowerManager pm = (PowerManager) ActivityShare.this.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XPrivacy.Toggle"); wl.acquire(); try { // Get data mProgressCurrent = 0; List<Integer> lstUid = mAppAdapter.getListUid(); final String restrictionName = params[0]; int actionId = ((RadioGroup) ActivityShare.this.findViewById(R.id.rgToggle)).getCheckedRadioButtonId(); Spinner spTemplate = ((Spinner) ActivityShare.this.findViewById(R.id.spTemplate)); String templateName = Meta.cTypeTemplate; if (spTemplate.getSelectedItemPosition() > 0) templateName = Meta.cTypeTemplate + spTemplate.getSelectedItemPosition(); for (Integer uid : lstUid) try { if (mAbort) throw new AbortException(ActivityShare.this); // Update progess publishProgress(++mProgressCurrent, lstUid.size() + 1); setState(uid, STATE_RUNNING, null); List<Boolean> oldState = PrivacyManager.getRestartStates(uid, restrictionName); if (actionId == R.id.rbClear) { PrivacyManager.deleteRestrictions(uid, restrictionName, (restrictionName == null)); if (restrictionName == null) { PrivacyManager.deleteUsage(uid); PrivacyManager.deleteSettings(uid); } } else if (actionId == R.id.rbRestrict) { PrivacyManager.setRestriction(uid, restrictionName, null, true, false); PrivacyManager.updateState(uid); } else if (actionId == R.id.rbTemplateCategory) PrivacyManager.applyTemplate(uid, templateName, restrictionName, false, true, false); else if (actionId == R.id.rbTemplateFull) PrivacyManager.applyTemplate(uid, templateName, restrictionName, true, true, false); else if (actionId == R.id.rbTemplateMergeSet) PrivacyManager.applyTemplate(uid, templateName, restrictionName, true, false, false); else if (actionId == R.id.rbTemplateMergeReset) PrivacyManager.applyTemplate(uid, templateName, restrictionName, true, false, true); else if (actionId == R.id.rbEnableOndemand) { PrivacyManager.setSetting(uid, PrivacyManager.cSettingOnDemand, Boolean.toString(true)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingNotify, Boolean.toString(false)); } else if (actionId == R.id.rbDisableOndemand) { PrivacyManager.setSetting(uid, PrivacyManager.cSettingOnDemand, Boolean.toString(false)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingNotify, Boolean.toString(true)); } else Util.log(null, Log.ERROR, "Unknown action=" + actionId); List<Boolean> newState = PrivacyManager.getRestartStates(uid, restrictionName); setState(uid, STATE_SUCCESS, !newState.equals(oldState) ? getString(R.string.msg_restart) : null); } catch (Throwable ex) { setState(uid, STATE_FAILURE, ex.getMessage()); return ex; } } finally { wl.release(); } return null; } @Override protected void onProgressUpdate(Integer... values) { blueStreakOfProgress(values[0], values[1]); super.onProgressUpdate(values); } @Override protected void onPostExecute(Throwable result) { if (!ActivityShare.this.isFinishing()) done(result); super.onPostExecute(result); } } private class ExportTask extends AsyncTask<File, Integer, Throwable> { private File mFile; @Override protected Throwable doInBackground(File... params) { // Get wakelock PowerManager pm = (PowerManager) ActivityShare.this.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XPrivacy.Export"); wl.acquire(); mProgressCurrent = 0; try { mFile = params[0]; List<Integer> listUid = mAppAdapter.getListUid(); Util.log(null, Log.INFO, "Exporting " + mFile); String android_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID); FileOutputStream fos = new FileOutputStream(mFile); try { // Start serialization XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(fos, "UTF-8"); serializer.startDocument(null, Boolean.valueOf(true)); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); serializer.startTag(null, "XPrivacy"); // Process package map for (PackageInfo pInfo : getPackageManager().getInstalledPackages(0)) if (listUid.size() == 1 ? pInfo.applicationInfo.uid == listUid.get(0) : true) { serializer.startTag(null, "PackageInfo"); serializer.attribute(null, "Id", Integer.toString(pInfo.applicationInfo.uid)); serializer.attribute(null, "Name", pInfo.packageName); serializer.endTag(null, "PackageInfo"); } // Process global settings if (listUid.size() > 1) { List<PSetting> listGlobalSetting = PrivacyManager.getSettingList(0, null); for (PSetting setting : listGlobalSetting) { // Serialize setting serializer.startTag(null, "Setting"); serializer.attribute(null, "Id", ""); serializer.attribute(null, "Type", setting.type); serializer.attribute(null, "Name", setting.name); if (setting.value != null) serializer.attribute(null, "Value", setting.value); serializer.endTag(null, "Setting"); } } // Process application settings and restrictions for (int uid : listUid) try { if (mAbort) throw new AbortException(ActivityShare.this); publishProgress(++mProgressCurrent, listUid.size() + 1); setState(uid, STATE_RUNNING, null); // Process application settings List<PSetting> listAppSetting = PrivacyManager.getSettingList(uid, null); for (PSetting setting : listAppSetting) { // Bind accounts/contacts to same device if (Meta.cTypeAccount.equals(setting.type) || Meta.cTypeContact.equals(setting.type)) setting.name += "." + android_id; // Serialize setting serializer.startTag(null, "Setting"); serializer.attribute(null, "Id", Integer.toString(uid)); serializer.attribute(null, "Type", setting.type); serializer.attribute(null, "Name", setting.name); serializer.attribute(null, "Value", setting.value); serializer.endTag(null, "Setting"); } // Process restrictions for (String restrictionName : PrivacyManager.getRestrictions()) { // Category PRestriction crestricted = PrivacyManager.getRestrictionEx(uid, restrictionName, null); serializer.startTag(null, "Restriction"); serializer.attribute(null, "Id", Integer.toString(uid)); serializer.attribute(null, "Name", restrictionName); serializer.attribute(null, "Restricted", Boolean.toString(crestricted.restricted)); serializer.attribute(null, "Asked", Boolean.toString(crestricted.asked)); serializer.endTag(null, "Restriction"); // Methods for (Hook md : PrivacyManager.getHooks(restrictionName, null)) { PRestriction mrestricted = PrivacyManager.getRestrictionEx(uid, restrictionName, md.getName()); if ((crestricted.restricted && !mrestricted.restricted) || (!crestricted.asked && mrestricted.asked) || md.isDangerous()) { serializer.startTag(null, "Restriction"); serializer.attribute(null, "Id", Integer.toString(uid)); serializer.attribute(null, "Name", restrictionName); serializer.attribute(null, "Method", md.getName()); serializer.attribute(null, "Restricted", Boolean.toString(mrestricted.restricted)); serializer.attribute(null, "Asked", Boolean.toString(mrestricted.asked)); serializer.endTag(null, "Restriction"); } } } setState(uid, STATE_SUCCESS, null); } catch (Throwable ex) { setState(uid, STATE_FAILURE, ex.getMessage()); throw ex; } // End serialization serializer.endTag(null, "XPrivacy"); serializer.endDocument(); serializer.flush(); } finally { fos.close(); } // Display message Util.log(null, Log.INFO, "Exporting finished"); return null; } catch (Throwable ex) { Util.bug(null, ex); if (mFile.exists()) mFile.delete(); return ex; } finally { wl.release(); } } @Override protected void onProgressUpdate(Integer... values) { blueStreakOfProgress(values[0], values[1]); super.onProgressUpdate(values); } @Override protected void onPostExecute(Throwable result) { if (!ActivityShare.this.isFinishing()) if (mInteractive) { done(result); // Share if (result == null) { Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("text/xml"); intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + mFileName)); startActivity(Intent.createChooser(intent, String.format(getString(R.string.msg_saved_to), mFileName))); } } else { done(result); finish(); } super.onPostExecute(result); } } private class ImportTask extends AsyncTask<Object, Integer, Throwable> { @Override protected Throwable doInBackground(Object... params) { // Get wakelock PowerManager pm = (PowerManager) ActivityShare.this.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XPrivacy.Import"); wl.acquire(); try { // Parameters File file = (File) params[0]; boolean clear = (Boolean) params[1]; List<Integer> listUidSelected = mAppAdapter.getListUid(); // Progress mProgressCurrent = 0; final int max = listUidSelected.size() + 1; Runnable progress = new Runnable() { @Override public void run() { publishProgress(++mProgressCurrent, max); } }; // Parse XML Util.log(null, Log.INFO, "Importing " + file); FileInputStream fis = null; Map<String, Map<String, List<ImportHandler.MethodDescription>>> mapPackage; try { fis = new FileInputStream(file); XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); ImportHandler importHandler = new ImportHandler(clear, listUidSelected, progress); xmlReader.setContentHandler(importHandler); xmlReader.parse(new InputSource(fis)); mapPackage = importHandler.getPackageMap(); if (mAbort) throw new AbortException(ActivityShare.this); } finally { if (fis != null) fis.close(); } // Progress int progressMax = mapPackage.size(); // Process result (legacy) for (String packageName : mapPackage.keySet()) { if (mAbort) throw new AbortException(ActivityShare.this); int uid = 0; try { publishProgress(++mProgressCurrent, progressMax + 1); // Get uid uid = getPackageManager().getPackageInfo(packageName, 0).applicationInfo.uid; if (listUidSelected.contains(uid)) { Util.log(null, Log.INFO, "Importing " + packageName); setState(uid, STATE_RUNNING, null); // Reset existing restrictions List<Boolean> oldState = PrivacyManager.getRestartStates(uid, null); PrivacyManager.deleteRestrictions(uid, null, true); // Set imported restrictions for (String restrictionName : mapPackage.get(packageName).keySet()) { PrivacyManager.setRestriction(uid, restrictionName, null, true, false); for (ImportHandler.MethodDescription md : mapPackage.get(packageName).get( restrictionName)) PrivacyManager.setRestriction(uid, restrictionName, md.getMethodName(), md.isRestricted(), false); } PrivacyManager.updateState(uid); List<Boolean> newState = PrivacyManager.getRestartStates(uid, null); setState(uid, STATE_SUCCESS, !newState.equals(oldState) ? getString(R.string.msg_restart) : null); } } catch (NameNotFoundException ignored) { } catch (Throwable ex) { if (listUidSelected.contains(uid)) setState(uid, STATE_FAILURE, ex.getMessage()); Util.bug(null, ex); } } // Display message Util.log(null, Log.INFO, "Importing finished"); return null; } catch (Throwable ex) { return ex; } finally { wl.release(); } } @Override protected void onProgressUpdate(Integer... values) { blueStreakOfProgress(values[0], values[1]); super.onProgressUpdate(values); } @Override protected void onPostExecute(Throwable result) { if (!ActivityShare.this.isFinishing()) done(result); super.onPostExecute(result); } } private class ImportHandler extends DefaultHandler { private boolean mClear; private List<Integer> mListUidSelected; private List<Integer> mListUidSettings = new ArrayList<Integer>(); private List<Integer> mListUidRestrictions = new ArrayList<Integer>(); private int lastUid = -1; private List<Boolean> mOldState = null; private SparseArray<String> mMapId = new SparseArray<String>(); private Map<String, Integer> mMapUid = new HashMap<String, Integer>(); private Map<String, Map<String, List<MethodDescription>>> mMapPackage = new HashMap<String, Map<String, List<MethodDescription>>>(); private Runnable mProgress; private String android_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID); public ImportHandler(boolean clear, List<Integer> listUidSelected, Runnable progress) { mClear = clear; mListUidSelected = listUidSelected; mProgress = progress; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) { try { if (qName.equals("XPrivacy")) { // Root } else if (qName.equals("PackageInfo")) { // Package info int id = Integer.parseInt(attributes.getValue("Id")); String name = attributes.getValue("Name"); mMapId.put(id, name); } else if (qName.equals("Setting")) { // Setting String id = attributes.getValue("Id"); String type = attributes.getValue("Type"); String name = attributes.getValue("Name"); String value = attributes.getValue("Value"); // Failsafe if (name == null) return; // Do not import version number if (name.equals(PrivacyManager.cSettingVersion)) return; // Decode legacy type if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.") || name.startsWith("Template.") || name.startsWith("Whitelist.")) { name = name.replace("Whitelist.", ""); int dot = name.indexOf('.'); type = name.substring(0, dot); name = name.substring(dot + 1); } else if (type == null) type = ""; // Import accounts/contacts only for same device if (Meta.cTypeAccount.equals(type) || Meta.cTypeContact.equals(type)) if (name.endsWith("." + android_id)) name = name.replace("." + android_id, ""); else return; if (id == null) { // Legacy Util.log(null, Log.WARN, "Legacy " + name + "=" + value); int userId = Util.getUserId(Process.myUid()); PrivacyManager.setSetting(userId, name, value); } else if ("".equals(id)) { // Global setting if (mListUidSelected.size() > 1) { int userId = Util.getUserId(Process.myUid()); PrivacyManager.setSetting(userId, type, name, value); } } else { // Application setting int iid = Integer.parseInt(id); int uid = getUid(iid); if (mListUidSelected.contains(uid)) { // Check for abort if (mAbort && !mListUidSettings.contains(uid)) { setState(uid, STATE_FAILURE); setMessage(uid, getString(R.string.msg_aborted)); return; } // Check for new uid if (!mListUidSettings.contains(uid)) { // Mark previous as success if (lastUid > 0) { boolean restart = !PrivacyManager.getRestartStates(lastUid, null).equals(mOldState); setState(lastUid, STATE_SUCCESS, restart ? getString(R.string.msg_restart) : null); } // Update state lastUid = uid; mListUidSettings.add(uid); // Update visible state setState(uid, STATE_RUNNING, null); // Clear settings if (mClear) PrivacyManager.deleteSettings(uid); } PrivacyManager.setSetting(uid, type, name, value); } } } else if (qName.equals("Package")) { // Restriction (legacy) String packageName = attributes.getValue("Name"); String restrictionName = attributes.getValue("Restriction"); String methodName = attributes.getValue("Method"); boolean restricted = Boolean.parseBoolean(attributes.getValue("Restricted")); Util.log(null, Log.WARN, "Legacy package=" + packageName + " " + restrictionName + "/" + methodName + "=" + restricted); // Map package restriction if (!mMapPackage.containsKey(packageName)) mMapPackage.put(packageName, new HashMap<String, List<MethodDescription>>()); if (!mMapPackage.get(packageName).containsKey(restrictionName)) mMapPackage.get(packageName).put(restrictionName, new ArrayList<MethodDescription>()); if (methodName != null) { MethodDescription md = new MethodDescription(methodName, restricted); mMapPackage.get(packageName).get(restrictionName).add(md); } } else if (qName.equals("Restriction")) { // Restriction (new style) int id = Integer.parseInt(attributes.getValue("Id")); String restrictionName = attributes.getValue("Name"); String methodName = attributes.getValue("Method"); boolean restricted = Boolean.parseBoolean(attributes.getValue("Restricted")); boolean asked = Boolean.parseBoolean(attributes.getValue("Asked")); // Get uid int uid = getUid(id); if (mListUidSelected.contains(uid)) { // Check for abort if (mAbort && !mListUidRestrictions.contains(uid)) { setState(uid, STATE_FAILURE); setMessage(uid, getString(R.string.msg_aborted)); return; } // Check for new uid if (!mListUidRestrictions.contains(uid)) { // Mark previous as success if (lastUid > 0) { PrivacyManager.updateState(lastUid); boolean restart = !PrivacyManager.getRestartStates(lastUid, null).equals(mOldState); setState(lastUid, STATE_SUCCESS, restart ? getString(R.string.msg_restart) : null); } // Update state lastUid = uid; mListUidRestrictions.add(uid); mOldState = PrivacyManager.getRestartStates(uid, null); // Update visible state setState(uid, STATE_RUNNING, null); runOnUiThread(mProgress); // Clear restrictions if (mClear) PrivacyManager.deleteRestrictions(uid, null, false); } // Set restriction PrivacyManager.setRestriction(uid, restrictionName, methodName, restricted, asked); } } else Util.log(null, Log.WARN, "Unknown element name=" + qName); } catch (Throwable ex) { Util.bug(null, ex); } } @Override public void endElement(String uri, String localName, String qName) { if (qName.equals("XPrivacy")) { if (lastUid > 0) { PrivacyManager.updateState(lastUid); boolean restart = !PrivacyManager.getRestartStates(lastUid, null).equals(mOldState); setState(lastUid, STATE_SUCCESS, restart ? getString(R.string.msg_restart) : null); } // Cleanup salt int userId = Util.getUserId(Process.myUid()); PrivacyManager.removeLegacySalt(userId); } } private int getUid(int id) { String packageName = mMapId.get(id); if (packageName == null) { Util.log(null, Log.WARN, "Unknown id=" + id); return -1; } else if (!mMapUid.containsKey(packageName)) try { int newuid = ActivityShare.this.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.uid; mMapUid.put(packageName, newuid); } catch (NameNotFoundException ex) { // Do not lookup again mMapUid.put(packageName, -1); Util.log(null, Log.WARN, "Unknown package name=" + packageName); } return (mMapUid.containsKey(packageName) ? mMapUid.get(packageName) : -1); } public Map<String, Map<String, List<MethodDescription>>> getPackageMap() { return mMapPackage; } public class MethodDescription { private String mMethodName; private boolean mRestricted; public MethodDescription(String methodName, boolean restricted) { mMethodName = methodName; mRestricted = restricted; } public String getMethodName() { return mMethodName; } public boolean isRestricted() { return mRestricted; } } } private class FetchTask extends AsyncTask<Boolean, Integer, Throwable> { @Override @SuppressLint("DefaultLocale") protected Throwable doInBackground(Boolean... params) { // Get wakelock PowerManager pm = (PowerManager) ActivityShare.this.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XPrivacy.Fetch"); wl.acquire(); try { // Get data boolean clear = params[0]; List<ApplicationInfoEx> lstApp = mAppAdapter.getListAppInfo(); int userId = Util.getUserId(Process.myUid()); String[] license = Util.getProLicenseUnchecked(); String android_id = Secure.getString(ActivityShare.this.getContentResolver(), Secure.ANDROID_ID); PackageInfo xInfo = getPackageManager().getPackageInfo(getPackageName(), 0); String confidence = PrivacyManager.getSetting(userId, PrivacyManager.cSettingConfidence, ""); // Initialize progress mProgressCurrent = 0; // Process applications for (ApplicationInfoEx appInfo : lstApp) try { publishProgress(++mProgressCurrent, lstApp.size() + 1); if (mAbort) throw new AbortException(ActivityShare.this); setState(appInfo.getUid(), STATE_RUNNING, ActivityShare.this.getString(R.string.menu_fetch)); JSONArray appName = new JSONArray(); for (String name : appInfo.getApplicationName()) appName.put(name); JSONArray pkgName = new JSONArray(); for (String name : appInfo.getPackageName()) pkgName.put(name); JSONArray pkgVersion = new JSONArray(); for (String version : appInfo.getPackageVersionName(ActivityShare.this)) pkgVersion.put(version); // Encode package JSONObject jRoot = new JSONObject(); jRoot.put("protocol_version", cProtocolVersion); jRoot.put("android_id", Util.md5(android_id).toLowerCase()); jRoot.put("android_sdk", Build.VERSION.SDK_INT); jRoot.put("xprivacy_version", xInfo.versionCode); jRoot.put("application_name", appName); jRoot.put("package_name", pkgName); jRoot.put("package_version", pkgVersion); jRoot.put("email", license[1]); jRoot.put("signature", license[2]); jRoot.put("confidence", confidence); // Fetch HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); HttpClient httpclient = new DefaultHttpClient(httpParams); HttpPost httpost = new HttpPost(getBaseURL() + "?format=json&action=fetch"); httpost.setEntity(new ByteArrayEntity(jRoot.toString().getBytes("UTF-8"))); httpost.setHeader("Accept", "application/json"); httpost.setHeader("Content-type", "application/json"); HttpResponse response = httpclient.execute(httpost); StatusLine statusLine = response.getStatusLine(); if (mAbort) throw new AbortException(ActivityShare.this); setState(appInfo.getUid(), STATE_RUNNING, ActivityShare.this.getString(R.string.msg_applying)); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { // Succeeded ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); // Deserialize JSONObject status = new JSONObject(out.toString("UTF-8")); if (status.getBoolean("ok")) { JSONArray settings = status.getJSONArray("settings"); // Delete existing restrictions List<Boolean> oldState = PrivacyManager.getRestartStates(appInfo.getUid(), null); // Clear existing restriction if (clear) PrivacyManager.deleteRestrictions(appInfo.getUid(), null, true); // Set fetched restrictions List<PRestriction> listRestriction = new ArrayList<PRestriction>(); for (int i = 0; i < settings.length(); i++) { JSONObject entry = settings.getJSONObject(i); String restrictionName = entry.getString("restriction"); String methodName = entry.has("method") ? entry.getString("method") : null; int voted_restricted = entry.getInt("restricted"); int voted_not_restricted = entry.getInt("not_restricted"); boolean restricted = (voted_restricted > voted_not_restricted); if (clear || restricted) listRestriction.add(new PRestriction(appInfo.getUid(), restrictionName, methodName, restricted)); } PrivacyManager.setRestrictionList(listRestriction); List<Boolean> newState = PrivacyManager.getRestartStates(appInfo.getUid(), null); // Mark as new/changed PrivacyManager.setSetting(appInfo.getUid(), PrivacyManager.cSettingState, Integer.toString(ApplicationInfoEx.STATE_ATTENTION)); // Change app modification time PrivacyManager.setSetting(appInfo.getUid(), PrivacyManager.cSettingModifyTime, Long.toString(System.currentTimeMillis())); setState(appInfo.getUid(), STATE_SUCCESS, !newState.equals(oldState) ? getString(R.string.msg_restart) : null); } else { int errno = status.getInt("errno"); String message = status.getString("error"); ServerException ex = new ServerException(ActivityShare.this, errno, message); setState(appInfo.getUid(), STATE_FAILURE, ex.getMessage()); } } else { // Failed response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (Throwable ex) { setState(appInfo.getUid(), STATE_FAILURE, ex.getMessage()); throw ex; } return null; } catch (ConnectTimeoutException ex) { return ex; } catch (HttpHostConnectException ex) { return ex; } catch (SocketTimeoutException ex) { return ex; } catch (SSLException ex) { return ex; } catch (UnknownHostException ex) { return ex; } catch (IOException ex) { return ex; } catch (Throwable ex) { Util.bug(null, ex); return ex; } finally { wl.release(); } } @Override protected void onProgressUpdate(Integer... values) { blueStreakOfProgress(values[0], values[1]); super.onProgressUpdate(values); } @Override protected void onPostExecute(Throwable result) { if (!ActivityShare.this.isFinishing()) done(result); super.onPostExecute(result); } } @SuppressLint("DefaultLocale") private class SubmitTask extends AsyncTask<Object, Integer, Throwable> { @Override protected Throwable doInBackground(Object... params) { // Get wakelock PowerManager pm = (PowerManager) ActivityShare.this.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XPrivacy.Submit"); wl.acquire(); try { // Get data List<ApplicationInfoEx> lstApp = mAppAdapter.getListAppInfo(); // Initialize progress mProgressCurrent = 0; for (ApplicationInfoEx appInfo : lstApp) try { if (mAbort) throw new AbortException(ActivityShare.this); // Update progess publishProgress(++mProgressCurrent, lstApp.size() + 1); setState(appInfo.getUid(), STATE_RUNNING, ActivityShare.this.getString(R.string.msg_loading)); // Check if any account allowed boolean allowedAccounts = false; AccountManager accountManager = AccountManager.get(ActivityShare.this); for (Account account : accountManager.getAccounts()) { String sha1 = Util.sha1(account.name + account.type); boolean allowed = PrivacyManager.getSettingBool(appInfo.getUid(), Meta.cTypeAccount, sha1, false); if (allowed) { allowedAccounts = true; break; } } // Check if any application allowed boolean allowedApplications = false; for (ApplicationInfoEx aAppInfo : ApplicationInfoEx.getXApplicationList(ActivityShare.this, null)) for (String packageName : aAppInfo.getPackageName()) { boolean allowed = PrivacyManager.getSettingBool(-appInfo.getUid(), Meta.cTypeApplication, packageName, false); if (allowed) { allowedApplications = true; break; } } // Check if any contact allowed boolean allowedContacts = false; Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID }, null, null, null); if (cursor != null) try { while (cursor.moveToNext()) { long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID)); boolean allowed = PrivacyManager.getSettingBool(-appInfo.getUid(), Meta.cTypeContact, Long.toString(id), false); if (allowed) { allowedContacts = true; break; } } } finally { cursor.close(); } // Get white lists Map<String, TreeMap<String, Boolean>> mapWhitelist = PrivacyManager.listWhitelisted( appInfo.getUid(), null); // Encode restrictions JSONArray jSettings = new JSONArray(); for (String restrictionName : PrivacyManager.getRestrictions()) { boolean restricted = PrivacyManager.getRestrictionEx(appInfo.getUid(), restrictionName, null).restricted; // Category long used = PrivacyManager.getUsage(appInfo.getUid(), restrictionName, null); JSONObject jRestriction = new JSONObject(); jRestriction.put("restriction", restrictionName); jRestriction.put("restricted", restricted); jRestriction.put("used", used); if (restrictionName.equals(PrivacyManager.cAccounts)) jRestriction.put("allowed", allowedAccounts ? 1 : 0); else if (restrictionName.equals(PrivacyManager.cSystem)) jRestriction.put("allowed", allowedApplications ? 1 : 0); else if (restrictionName.equals(PrivacyManager.cContacts)) jRestriction.put("allowed", allowedContacts ? 1 : 0); jSettings.put(jRestriction); // Methods for (Hook md : PrivacyManager.getHooks(restrictionName, null)) { boolean mRestricted = restricted && PrivacyManager.getRestrictionEx(appInfo.getUid(), restrictionName, md.getName()).restricted; long mUsed = PrivacyManager.getUsage(appInfo.getUid(), restrictionName, md.getName()); boolean mWhitelisted = false; if (md.whitelist() != null && mapWhitelist.containsKey(md.whitelist())) for (Boolean allowed : mapWhitelist.get(md.whitelist()).values()) if (mRestricted ? allowed : !allowed) { mWhitelisted = true; break; } JSONObject jMethod = new JSONObject(); jMethod.put("restriction", restrictionName); jMethod.put("method", md.getName()); jMethod.put("restricted", mRestricted); jMethod.put("used", mUsed); jMethod.put("allowed", mWhitelisted ? 1 : 0); jSettings.put(jMethod); } } // Get data String[] license = Util.getProLicenseUnchecked(); PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); String android_id = Secure .getString(ActivityShare.this.getContentResolver(), Secure.ANDROID_ID); JSONArray appName = new JSONArray(); for (String name : appInfo.getApplicationName()) appName.put(name); JSONArray pkgName = new JSONArray(); for (String name : appInfo.getPackageName()) pkgName.put(name); JSONArray pkgVersionName = new JSONArray(); for (String version : appInfo.getPackageVersionName(ActivityShare.this)) pkgVersionName.put(version); JSONArray pkgVersionCode = new JSONArray(); for (Integer version : appInfo.getPackageVersionCode(ActivityShare.this)) pkgVersionCode.put((int) version); // Encode package JSONObject jRoot = new JSONObject(); jRoot.put("protocol_version", cProtocolVersion); jRoot.put("android_id", Util.md5(android_id).toLowerCase()); jRoot.put("android_sdk", Build.VERSION.SDK_INT); jRoot.put("xprivacy_version", pInfo.versionCode); jRoot.put("application_name", appName); jRoot.put("package_name", pkgName); jRoot.put("package_version_name", pkgVersionName); jRoot.put("package_version_code", pkgVersionCode); jRoot.put("settings", jSettings); if (license != null) { jRoot.put("email", license[1]); jRoot.put("signature", license[2]); } if (mAbort) throw new AbortException(ActivityShare.this); setState(appInfo.getUid(), STATE_RUNNING, ActivityShare.this.getString(R.string.menu_submit)); // Submit HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); HttpClient httpclient = new DefaultHttpClient(httpParams); HttpPost httpost = new HttpPost(getBaseURL() + "?format=json&action=submit"); httpost.setEntity(new ByteArrayEntity(jRoot.toString().getBytes("UTF-8"))); httpost.setHeader("Accept", "application/json"); httpost.setHeader("Content-type", "application/json"); HttpResponse response = httpclient.execute(httpost); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { // Succeeded ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); JSONObject status = new JSONObject(out.toString("UTF-8")); if (status.getBoolean("ok")) { // Mark as shared PrivacyManager.setSetting(appInfo.getUid(), PrivacyManager.cSettingState, Integer.toString(ApplicationInfoEx.STATE_SHARED)); setState(appInfo.getUid(), STATE_SUCCESS, null); } else { int errno = status.getInt("errno"); String message = status.getString("error"); ServerException ex = new ServerException(ActivityShare.this, errno, message); // Mark as unregistered if (errno == ServerException.cErrorNotActivated) { int userId = Util.getUserId(Process.myUid()); PrivacyManager.setSetting(userId, PrivacyManager.cSettingRegistered, Boolean.toString(false)); throw ex; } else setState(appInfo.getUid(), STATE_FAILURE, ex.getMessage()); } } else { // Failed response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (Throwable ex) { setState(appInfo.getUid(), STATE_FAILURE, ex.getMessage()); throw ex; } return null; } catch (ConnectTimeoutException ex) { return ex; } catch (HttpHostConnectException ex) { return ex; } catch (SocketTimeoutException ex) { return ex; } catch (SSLException ex) { return ex; } catch (UnknownHostException ex) { return ex; } catch (IOException ex) { return ex; } catch (Throwable ex) { Util.bug(null, ex); return ex; } finally { wl.release(); } } @Override protected void onProgressUpdate(Integer... values) { blueStreakOfProgress(values[0], values[1]); super.onProgressUpdate(values); } @Override protected void onPostExecute(Throwable result) { if (!ActivityShare.this.isFinishing()) done(result); super.onPostExecute(result); } } @SuppressLint("InflateParams") public static boolean registerDevice(final ActivityBase context) { int userId = Util.getUserId(Process.myUid()); if (Util.hasProLicense(context) == null && !PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingRegistered, false)) { // Get accounts String email = null; for (Account account : AccountManager.get(context).getAccounts()) if ("com.google".equals(account.type)) { email = account.name; break; } LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = LayoutInflater.inflate(R.layout.register, null); final EditText input = (EditText) view.findViewById(R.id.etEmail); if (email != null) input.setText(email); // Build dialog AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle(R.string.msg_register); alertDialogBuilder.setIcon(context.getThemed(R.attr.icon_launcher)); alertDialogBuilder.setView(view); alertDialogBuilder.setPositiveButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String email = input.getText().toString(); if (Patterns.EMAIL_ADDRESS.matcher(email).matches()) new RegisterTask(context).executeOnExecutor(mExecutor, email); } }); alertDialogBuilder.setNegativeButton(context.getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do nothing } }); // Show dialog AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); return false; } return true; } @SuppressLint("DefaultLocale") private static class RegisterTask extends AsyncTask<String, String, Throwable> { private ActivityBase mContext; public RegisterTask(ActivityBase context) { mContext = context; } protected Throwable doInBackground(String... params) { // Get wakelock PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XPrivacy.Register"); wl.acquire(); try { String android_id = Secure.getString(mContext.getContentResolver(), Secure.ANDROID_ID); // Encode message JSONObject jRoot = new JSONObject(); jRoot.put("protocol_version", cProtocolVersion); jRoot.put("email", params[0]); jRoot.put("android_id", Util.md5(android_id).toLowerCase()); // Submit HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); HttpClient httpclient = new DefaultHttpClient(httpParams); HttpPost httpost = new HttpPost(getBaseURL() + "device?format=json&action=register"); httpost.setEntity(new ByteArrayEntity(jRoot.toString().getBytes("UTF-8"))); httpost.setHeader("Accept", "application/json"); httpost.setHeader("Content-type", "application/json"); HttpResponse response = httpclient.execute(httpost); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { // Succeeded ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); JSONObject status = new JSONObject(out.toString("UTF-8")); if (status.getBoolean("ok")) { // Mark as registered int userId = Util.getUserId(Process.myUid()); PrivacyManager.setSetting(userId, PrivacyManager.cSettingRegistered, Boolean.toString(true)); return null; } else { int errno = status.getInt("errno"); String message = status.getString("error"); throw new ServerException(errno, message); } } else { // Failed response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (ConnectTimeoutException ex) { return ex; } catch (HttpHostConnectException ex) { return ex; } catch (SocketTimeoutException ex) { return ex; } catch (SSLException ex) { return ex; } catch (UnknownHostException ex) { return ex; } catch (IOException ex) { return ex; } catch (Throwable ex) { Util.bug(null, ex); return ex; } finally { wl.release(); } } @Override protected void onPostExecute(Throwable result) { if (!mContext.isFinishing()) { String message; if (result == null) message = mContext.getString(R.string.msg_registered); else message = result.getMessage(); // Build dialog AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); alertDialogBuilder.setTitle(R.string.app_name); alertDialogBuilder.setMessage(message); alertDialogBuilder.setIcon(mContext.getThemed(R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(mContext.getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); // Show dialog AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } super.onPostExecute(result); } } public static class UpdateTask extends AsyncTask<Object, Object, Object> { private Context mContext; private NotificationCompat.Builder builder; private Notification notification; private NotificationManager notificationManager; public UpdateTask(Context context) { mContext = context; builder = new NotificationCompat.Builder(context); notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); } @Override protected void onPreExecute() { // Build notification builder.setSmallIcon(R.drawable.ic_launcher); builder.setContentTitle(mContext.getString(R.string.app_name)); builder.setAutoCancel(false); builder.setOngoing(true); } @Override @SuppressLint("DefaultLocale") protected Object doInBackground(Object... args) { try { // Notify builder.setContentText(mContext.getString(R.string.title_update_checking)); builder.setWhen(System.currentTimeMillis()); notification = builder.build(); notificationManager.notify(Util.NOTIFY_UPDATE, notification); // Encode package String[] license = Util.getProLicenseUnchecked(); int userId = Util.getUserId(Process.myUid()); boolean test = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingTestVersions, false); String android_id = Secure.getString(mContext.getContentResolver(), Secure.ANDROID_ID); JSONObject jRoot = new JSONObject(); jRoot.put("protocol_version", cProtocolVersion); jRoot.put("android_id", Util.md5(android_id).toLowerCase()); jRoot.put("android_sdk", Build.VERSION.SDK_INT); jRoot.put("xprivacy_version", Util.getSelfVersionCode(mContext)); jRoot.put("xprivacy_version_name", Util.getSelfVersionName(mContext)); jRoot.put("test_versions", test); jRoot.put("email", license[1]); jRoot.put("signature", license[2]); // Update HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); HttpClient httpclient = new DefaultHttpClient(httpParams); HttpPost httpost = new HttpPost(getBaseURL() + "?format=json&action=update"); httpost.setEntity(new ByteArrayEntity(jRoot.toString().getBytes("UTF-8"))); httpost.setHeader("Accept", "application/json"); httpost.setHeader("Content-type", "application/json"); HttpResponse response = httpclient.execute(httpost); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { String contentType = response.getFirstHeader("Content-Type").getValue(); if ("application/octet-stream".equals(contentType)) { // Update notification builder.setContentText(mContext.getString(R.string.title_update_downloading)); builder.setWhen(System.currentTimeMillis()); notification = builder.build(); notificationManager.notify(Util.NOTIFY_UPDATE, notification); // Download APK File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); folder.mkdirs(); String fileName = response.getFirstHeader("Content-Disposition").getElements()[0] .getParameterByName("filename").getValue(); File download = new File(folder, fileName); FileOutputStream fos = null; try { fos = new FileOutputStream(download); response.getEntity().writeTo(fos); } finally { if (fos != null) fos.close(); } return download; } else if ("application/json".equals(contentType)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); throw new IOException(out.toString("UTF-8")); } else throw new IOException(contentType); } else return statusLine; } catch (Throwable ex) { Util.bug(null, ex); return ex; } } @Override protected void onPostExecute(Object result) { if (result instanceof StatusLine) { notificationManager.cancel(Util.NOTIFY_UPDATE); StatusLine status = (StatusLine) result; if (status.getStatusCode() == 204) { // No Content String none = mContext.getString(R.string.title_update_none); Toast.makeText(mContext, none, Toast.LENGTH_LONG).show(); } else Toast.makeText(mContext, status.getStatusCode() + " " + status.getReasonPhrase(), Toast.LENGTH_LONG) .show(); } else if (result instanceof Throwable) { notificationManager.cancel(Util.NOTIFY_UPDATE); Throwable ex = (Throwable) result; Toast.makeText(mContext, ex.toString(), Toast.LENGTH_LONG).show(); } else { File download = (File) result; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(download), "application/vnd.android.package-archive"); PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Update notification builder.setContentText(mContext.getString(R.string.title_update_install)); builder.setWhen(System.currentTimeMillis()); builder.setAutoCancel(true); builder.setOngoing(false); builder.setContentIntent(pi); notification = builder.build(); notificationManager.notify(Util.NOTIFY_UPDATE, notification); } } } // Helper methods private void blueStreakOfProgress(Integer current, Integer max) { // Set up the progress bar if (mProgressWidth == 0) { final View vShareProgressEmpty = (View) findViewById(R.id.vShareProgressEmpty); mProgressWidth = vShareProgressEmpty.getMeasuredWidth(); } // Display stuff if (max == 0) max = 1; int width = (int) ((float) mProgressWidth) * current / max; View vShareProgressFull = (View) findViewById(R.id.vShareProgressFull); vShareProgressFull.getLayoutParams().width = width; vShareProgressFull.invalidate(); vShareProgressFull.requestLayout(); } private void done(Throwable ex) { String result = null; if (ex != null && !(ex instanceof AbortException)) result = ex.getMessage(); // Check result string and display toast with error if (result != null) Toast.makeText(this, result, Toast.LENGTH_LONG).show(); // Reset progress bar blueStreakOfProgress(0, 1); mRunning = false; // Update buttons final Button btnCancel = (Button) findViewById(R.id.btnCancel); final Button btnOk = (Button) findViewById(R.id.btnOk); btnCancel.setEnabled(false); btnOk.setEnabled(true); // Handle close btnOk.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public void fileChooser() { Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT); Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/.xprivacy/"); chooseFile.setDataAndType(uri, "text/xml"); Intent intent = Intent.createChooser(chooseFile, getString(R.string.app_name)); startActivityForResult(intent, ACTIVITY_IMPORT_SELECT); } private void showFileName() { TextView tvDescription = (TextView) findViewById(R.id.tvDescription); tvDescription.setText(mFileName); Button btnOk = (Button) findViewById(R.id.btnOk); btnOk.setEnabled(true); } public static String getBaseURL() { int userId = Util.getUserId(Process.myUid()); if (PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingHttps, true)) return HTTPS_BASE_URL; else return HTTP_BASE_URL; } public static String getFileName(Context context, boolean multiple, String packageName) { File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + ".xprivacy"); folder.mkdir(); String fileName; if (multiple) { SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ROOT); fileName = String.format("%s_XPrivacy_%s_%s%s.xml", format.format(new Date()), Util.getSelfVersionName(context), Build.DEVICE, (packageName == null ? "" : "_" + packageName)); } else fileName = "XPrivacy.xml"; return new File(folder + File.separator + fileName).getAbsolutePath(); } // Helper classes public static class AbortException extends Exception { private static final long serialVersionUID = 1L; public AbortException(Context context) { super(context.getString(R.string.msg_aborted)); } } public static class ServerException extends Exception { private int mErrorNo; private Context mContext = null; private static final long serialVersionUID = 1L; public final static int cErrorNotActivated = 206; public final static int cErrorNoRestrictions = 305; public ServerException(int errorno, String message) { super(message); mErrorNo = errorno; } public ServerException(Context context, int errorno, String message) { super(message); mErrorNo = errorno; mContext = context; } @Override @SuppressLint("DefaultLocale") public String getMessage() { if (mErrorNo == cErrorNoRestrictions && mContext != null) return mContext.getString(R.string.msg_no_restrictions); return String.format("Error %d: %s", mErrorNo, super.getMessage()); // general: // 'errno' => 101, 'error' => 'Empty request' // 'errno' => 102, 'error' => 'Please upgrade to at least ...' // 'errno' => 103, 'error' => 'Error connecting to database' // 'errno' => 104, 'error' => 'Unknown action: ...' // submit: // 'errno' => 201, 'error' => 'Not authorized' // 'errno' => 202, 'error' => 'Android ID missing' // 'errno' => 203, 'error' => 'Package name missing' // 'errno' => 204, 'error' => 'Too many packages for application' // 'errno' => 205, 'error' => 'Error storing restrictions' // 'errno' => 206, 'error' => 'Device not activated' // 'errno' => 207, 'error' => 'Unknown category' // fetch: // 'errno' => 301, 'error' => 'Not authorized' // 'errno' => 303, 'error' => 'Package name missing' // 'errno' => 304, 'error' => 'Too many packages for application' // 'errno' => 305, 'error' => 'No restrictions available' // 'errno' => 306, 'error' => 'Error retrieving restrictions' // 'errno' => 307, 'error' => 'There is a maximum of ...' } } }
75,001
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XConnectionCallbacks.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XConnectionCallbacks.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Binder; import android.util.Log; public class XConnectionCallbacks extends XHook { private Methods mMethod; private String mClassName; private XConnectionCallbacks(Methods method, String restrictionName, String className) { super(restrictionName, method.name(), "GMS5." + method.name()); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // abstract void onConnected(Bundle connectionHint) // https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.ConnectionCallbacks.html // @formatter:on private enum Methods { onConnected }; public static List<XHook> getInstances(Object instance) { String className = instance.getClass().getName(); Util.log(null, Log.INFO, "Hooking class=" + className + " uid=" + Binder.getCallingUid()); List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XConnectionCallbacks(Methods.onConnected, null, className)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case onConnected: Util.log(this, Log.WARN, "GoogleApiClient onConnected uid=" + Binder.getCallingUid()); ClassLoader loader = param.thisObject.getClass().getClassLoader(); // FusedLocationApi try { Class<?> cLoc = Class.forName("com.google.android.gms.location.LocationServices", false, loader); Object fusedLocationApi = cLoc.getDeclaredField("FusedLocationApi").get(null); if (PrivacyManager.getTransient(fusedLocationApi.getClass().getName(), null) == null) { PrivacyManager.setTransient(fusedLocationApi.getClass().getName(), Boolean.toString(true)); if (fusedLocationApi != null) XPrivacy.hookAll(XFusedLocationApi.getInstances(fusedLocationApi), loader, getSecret(), true); } } catch (ClassNotFoundException ex) { Util.log(this, Log.WARN, ex.toString()); } catch (NoSuchFieldException ex) { Util.log(this, Log.WARN, ex.toString()); } catch (ExceptionInInitializerError ex) { Util.log(this, Log.WARN, ex.toString()); } // ActivityRecognitionApi try { Class<?> cRec = Class.forName("com.google.android.gms.location.ActivityRecognition", false, loader); Object activityRecognitionApi = cRec.getDeclaredField("ActivityRecognitionApi").get(null); if (PrivacyManager.getTransient(activityRecognitionApi.getClass().getName(), null) == null) { PrivacyManager.setTransient(activityRecognitionApi.getClass().getName(), Boolean.toString(true)); if (activityRecognitionApi != null) XPrivacy.hookAll(XActivityRecognitionApi.getInstances(activityRecognitionApi), loader, getSecret(), true); } } catch (ClassNotFoundException ex) { Util.log(this, Log.WARN, ex.toString()); } catch (NoSuchFieldException ex) { Util.log(this, Log.WARN, ex.toString()); } catch (ExceptionInInitializerError ex) { Util.log(this, Log.WARN, ex.toString()); } // AppIndexApi try { Class<?> cApp = Class.forName("com.google.android.gms.appindexing.AppIndex", false, loader); Object appIndexApi = cApp.getDeclaredField("AppIndexApi").get(null); if (PrivacyManager.getTransient(appIndexApi.getClass().getName(), null) == null) { PrivacyManager.setTransient(appIndexApi.getClass().getName(), Boolean.toString(true)); if (appIndexApi != null) XPrivacy.hookAll(XAppIndexApi.getInstances(appIndexApi), loader, getSecret(), true); } } catch (ClassNotFoundException ex) { Util.log(this, Log.WARN, ex.toString()); } catch (NoSuchFieldException ex) { Util.log(this, Log.WARN, ex.toString()); } catch (ExceptionInInitializerError ex) { Util.log(this, Log.WARN, ex.toString()); } // PlaceDetectionApi try { Class<?> cPlaces = Class.forName("com.google.android.gms.location.places.Places", false, loader); Object placeDetectionApi = cPlaces.getDeclaredField("PlaceDetectionApi").get(null); if (PrivacyManager.getTransient(placeDetectionApi.getClass().getName(), null) == null) { PrivacyManager.setTransient(placeDetectionApi.getClass().getName(), Boolean.toString(true)); if (placeDetectionApi != null) XPrivacy.hookAll(XPlaceDetectionApi.getInstances(placeDetectionApi), loader, getSecret(), true); } } catch (ClassNotFoundException ex) { Util.log(this, Log.WARN, ex.toString()); } catch (NoSuchFieldException ex) { Util.log(this, Log.WARN, ex.toString()); } catch (ExceptionInInitializerError ex) { Util.log(this, Log.WARN, ex.toString()); } break; } } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
4,780
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XBinder.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XBinder.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Context; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.os.Parcel; import android.os.Process; import android.util.Log; import android.util.SparseArray; public class XBinder extends XHook { private Methods mMethod; private static long mToken = 0; private static Map<String, Boolean> mMapClassSystem = new HashMap<String, Boolean>(); private static Map<String, SparseArray<String>> mMapCodeName = new HashMap<String, SparseArray<String>>(); private static final int BITS_TOKEN = 16; private static final int FLAG_ALL = 0xFFFF; private static final int MASK_TOKEN = 0xFFFF; private static final int PING_TRANSACTION = ('_' << 24) | ('P' << 16) | ('N' << 8) | 'G'; private static final int DUMP_TRANSACTION = ('_' << 24) | ('D' << 16) | ('M' << 8) | 'P'; private static final int INTERFACE_TRANSACTION = ('_' << 24) | ('N' << 16) | ('T' << 8) | 'F'; private static final int TWEET_TRANSACTION = ('_' << 24) | ('T' << 16) | ('W' << 8) | 'T'; private static final int LIKE_TRANSACTION = ('_' << 24) | ('L' << 16) | ('I' << 8) | 'K'; private static final int SYSPROPS_TRANSACTION = ('_' << 24) | ('S' << 16) | ('P' << 8) | 'R'; // Service name should one-to-one correspond to the other lists // @formatter:off public static List<String> cServiceName = Arrays.asList(new String[] { "account", "activity", "clipboard", "connectivity", "content", "location", "telephony.registry", "telephony.msim.registry", "package", "iphonesubinfo", "iphonesubinfo_msim", "window", "wifi", "sip", "isms", "nfc", "appwidget", "bluetooth", "bluetooth_manager", "input", "sensorservice", "usb", "media.camera", "<noname>", "<noname>", "<noname>" }); // @formatter:on // @formatter:off public static List<String> cServiceDescriptor = Arrays.asList(new String[] { "android.accounts.IAccountManager", "android.app.IActivityManager", "android.content.IClipboard", "android.net.IConnectivityManager", "android.content.IContentService", "android.location.ILocationManager", "com.android.internal.telephony.ITelephonyRegistry", "com.android.internal.telephony.ITelephonyRegistryMSim", "android.content.pm.IPackageManager", "com.android.internal.telephony.IPhoneSubInfo", "com.android.internal.telephony.msim.IPhoneSubInfoMSim", "android.view.IWindowManager", "android.net.wifi.IWifiManager", "android.net.sip.ISipService", "com.android.internal.telephony.ISms", "android.nfc.INfcAdapter", "com.android.internal.appwidget.IAppWidgetService", "android.bluetooth.IBluetooth", "android.bluetooth.IBluetoothManager", "android.hardware.input.IInputManager", "android.gui.SensorServer", "android.hardware.usb.IUsbManager", "android.hardware.ICameraService", "android.app.IApplicationThread", "android.content.IContentProvider", "android.view.IWindowSession" }); // @formatter:on // @formatter:off public static List<String> cServiceOptional = Arrays.asList(new String[] { "<noname>", "iphonesubinfo", "iphonesubinfo_msim", "sip", "isms", "nfc", "bluetooth", "bluetooth_manager" }); // @formatter:on private XBinder(Methods method, String restrictionName) { super(restrictionName, method.name(), null); mMethod = method; } public String getClassName() { return (mMethod == Methods.transact ? "android.os.BinderProxy" : "android.os.Binder"); } public boolean isVisible() { return (mMethod != Methods.execTransact); } @Override public void setSecret(String secret) { super.setSecret(secret); mToken = (secret.hashCode() & MASK_TOKEN); } // @formatter:off // private boolean execTransact(int code, int dataObj, int replyObj, int flags) // public final boolean transact(int code, Parcel data, Parcel reply, int flags) // public native boolean transact(int code, Parcel data, Parcel reply, int flags) // frameworks/base/core/java/android/os/Binder.java // http://developer.android.com/reference/android/os/Binder.html // @formatter:on private enum Methods { execTransact, transact }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XBinder(Methods.execTransact, null)); // Binder listHook.add(new XBinder(Methods.transact, null)); // BinderProxy return listHook; } @Override protected void before(XParam param) throws Throwable { if (mMethod == Methods.execTransact) { // execTransact calls the overridden onTransact // Check for direct IPC checkIPC(param); } else if (mMethod == Methods.transact) { markIPC(param); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } @Override protected void after(XParam param) throws Throwable { // Do nothing } private void markIPC(XParam param) throws Throwable { // Allow management transactions int code = (Integer) param.args[0]; if (isManagementTransaction(code)) return; // Only for applications int uid = Binder.getCallingUid(); if (!PrivacyManager.isApplication(uid)) return; // Check interface name IBinder binder = (IBinder) param.thisObject; String descriptor = (binder == null ? null : binder.getInterfaceDescriptor()); if (!cServiceDescriptor.contains(descriptor)) return; // Search this object in call stack boolean ok = false; boolean found = false; StackTraceElement[] ste = Thread.currentThread().getStackTrace(); for (int i = 0; i < ste.length; i++) if (ste[i].getClassName().equals(param.thisObject.getClass().getName())) { found = true; // Check if caller class in user space String callerClassName = (i + 2 < ste.length ? ste[i + 2].getClassName() : null); if (callerClassName != null && !callerClassName.startsWith("java.lang.reflect.")) synchronized (mMapClassSystem) { if (!mMapClassSystem.containsKey(callerClassName)) try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class<?> clazz = Class.forName(callerClassName, false, loader); boolean boot = Context.class.getClassLoader().equals(clazz.getClassLoader()); mMapClassSystem.put(callerClassName, boot); } catch (ClassNotFoundException ignored) { mMapClassSystem.put(callerClassName, true); } ok = mMapClassSystem.get(callerClassName); } break; } // Conditionally mark if (ok) { int flags = (Integer) param.args[3]; if ((flags & ~FLAG_ALL) != 0) Util.log(this, Log.ERROR, "Unknown flags=" + Integer.toHexString(flags) + " descriptor=" + descriptor + " code=" + code + " uid=" + Binder.getCallingUid()); flags |= (mToken << BITS_TOKEN); param.args[3] = flags; } else { int level = (found ? Log.WARN : Log.ERROR); Util.log(this, level, "Unmarked descriptor=" + descriptor + " found=" + found + " code=" + code + " uid=" + Binder.getCallingUid()); Util.logStack(this, level, true); } } // Entry point from android_util_Binder.cpp's onTransact private void checkIPC(XParam param) throws Throwable { // Allow management transactions int code = (Integer) param.args[0]; if (isManagementTransaction(code)) return; // Only for applications int uid = Binder.getCallingUid(); if (!PrivacyManager.isApplication(uid)) return; // Check interface name IBinder binder = (IBinder) param.thisObject; String descriptor = (binder == null ? null : binder.getInterfaceDescriptor()); if (!cServiceDescriptor.contains(descriptor)) return; // Get token int flags = (Integer) param.args[3]; long token = (flags >> BITS_TOKEN) & MASK_TOKEN; flags &= FLAG_ALL; param.args[3] = flags; // Check token if (token != mToken) { String[] name = descriptor.split("\\."); String interfaceName = name[name.length - 1]; // Get transaction code name String codeName; synchronized (mMapCodeName) { if (!mMapCodeName.containsKey(descriptor)) { SparseArray<String> sa = new SparseArray<String>(); mMapCodeName.put(descriptor, sa); List<Class<?>> listClass = new ArrayList<Class<?>>(); if (param.thisObject.getClass().getSuperclass() != null) listClass.add(param.thisObject.getClass().getSuperclass()); try { listClass.add(Class.forName(descriptor)); } catch (ClassNotFoundException ignored) { } for (Class<?> clazz : listClass) for (Field field : clazz.getDeclaredFields()) try { if (field.getName().startsWith("TRANSACTION_") || field.getName().endsWith("_TRANSACTION")) { field.setAccessible(true); Integer txCode = (Integer) field.get(null); String txName = field.getName().replace("TRANSACTION_", "") .replace("_TRANSACTION", ""); sa.put(txCode, txName); } } catch (Throwable ignore) { } } codeName = mMapCodeName.get(descriptor).get(code); } if (codeName == null) { codeName = Integer.toString(code); Util.log(this, Log.WARN, "Unknown transaction=" + descriptor + ":" + code + " class=" + param.thisObject.getClass() + " uid=" + Binder.getCallingUid()); Util.logStack(this, Log.INFO); } Util.log(this, Log.INFO, "can restrict transaction=" + interfaceName + ":" + codeName + " flags=" + flags + " uid=" + uid + " my=" + Process.myUid()); if (isRestrictedExtra(uid, PrivacyManager.cIPC, "Binder", interfaceName + ":" + codeName)) { Util.log(this, Log.WARN, "Restricting " + interfaceName + ":" + codeName + " code=" + code); // Get reply parcel Parcel reply = null; try { // static protected final Parcel obtain(int obj) // frameworks/base/core/java/android/os/Parcel.java Method methodObtain = Parcel.class.getDeclaredMethod("obtain", Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? int.class : long.class); methodObtain.setAccessible(true); reply = (Parcel) methodObtain.invoke(null, param.args[2]); } catch (NoSuchMethodException ex) { Util.bug(this, ex); } // Block IPC if (reply == null) Util.log(this, Log.ERROR, "reply is null uid=" + uid); else { reply.setDataPosition(0); reply.writeException(new SecurityException("XPrivacy")); } param.setResult(true); } } } private static boolean isManagementTransaction(int code) { return (code == PING_TRANSACTION || code == DUMP_TRANSACTION || code == INTERFACE_TRANSACTION || code == TWEET_TRANSACTION || code == LIKE_TRANSACTION || code == SYSPROPS_TRANSACTION); } }
10,779
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
Version.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/Version.java
package biz.bokhorst.xprivacy; public class Version implements Comparable<Version> { private String mVersion; public Version(String version) { mVersion = version; } private String get() { return mVersion; } @Override public int compareTo(Version other) { String[] lhs = this.get().split("\\."); String[] rhs = other.get().split("\\."); int length = Math.max(lhs.length, rhs.length); for (int i = 0; i < length; i++) { int vLhs = (i < lhs.length ? Integer.parseInt(lhs[i]) : 0); int vRhs = (i < rhs.length ? Integer.parseInt(rhs[i]) : 0); if (vLhs < vRhs) return -1; if (vLhs > vRhs) return 1; } return 0; } @Override public String toString() { return mVersion; } }
719
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XResources.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XResources.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.content.res.Configuration; import android.os.Binder; import android.util.Log; public class XResources extends XHook { private Methods mMethod; private XResources(Methods method) { super(null, method.name(), null); mMethod = method; } public String getClassName() { return "android.content.res.Resources"; } // public void updateConfiguration(Configuration config, ...) // frameworks/base/core/java/android/content/res/Resources.java // http://developer.android.com/reference/android/content/res/Resources.html // http://developer.android.com/reference/android/content/res/Configuration.html private enum Methods { updateConfiguration }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XResources(Methods.updateConfiguration)); return listHook; } @Override protected void before(XParam param) throws Throwable { if (mMethod == Methods.updateConfiguration) { if (param.args.length > 0 && param.args[0] != null && param.args[0] instanceof Configuration) { boolean restricted = false; int uid = Binder.getCallingUid(); Configuration config = new Configuration((Configuration) param.args[0]); if (getRestricted(uid, PrivacyManager.cPhone, "Configuration.MCC")) { restricted = true; try { config.mcc = Integer.parseInt((String) PrivacyManager.getDefacedProp(uid, "MCC")); } catch (Throwable ex) { config.mcc = 1; } } if (getRestricted(uid, PrivacyManager.cPhone, "Configuration.MNC")) { restricted = true; try { config.mnc = Integer.parseInt((String) PrivacyManager.getDefacedProp(uid, "MNC")); } catch (Throwable ex) { config.mnc = 1; } } if (restricted) param.args[0] = config; } } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
2,056
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XTelephonyManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XTelephonyManager.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.PhoneStateListener; import android.telephony.ServiceState; import android.telephony.SignalStrength; import android.telephony.CellInfo; import android.telephony.gsm.GsmCellLocation; import android.util.Log; public class XTelephonyManager extends XHook { private Methods mMethod; private String mClassName; private static final String cClassName = "android.telephony.TelephonyManager"; private static final Map<PhoneStateListener, XPhoneStateListener> mListener = new WeakHashMap<PhoneStateListener, XPhoneStateListener>(); private enum Srv { SubInfo, Registry, Phone, SICtl }; private XTelephonyManager(Methods method, String restrictionName, Srv srv) { super(restrictionName, method.name().replace("Srv_", "").replace("5", ""), method.name()); mMethod = method; if (srv == Srv.SubInfo) mClassName = "com.android.internal.telephony.PhoneSubInfo"; else if (srv == Srv.Registry) mClassName = "com.android.server.TelephonyRegistry"; else if (srv == Srv.Phone) mClassName = "com.android.phone.PhoneInterfaceManager"; else if (srv == Srv.SICtl) mClassName = "com.android.internal.telephony.PhoneSubInfoController"; else Util.log(null, Log.ERROR, "Unknown srv=" + srv.name()); } private XTelephonyManager(Methods method, String restrictionName, String className) { super(restrictionName, method.name(), null); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // public void disableLocationUpdates() // public void enableLocationUpdates() // public List<CellInfo> getAllCellInfo() // public CellLocation getCellLocation() // public String getDeviceId() // public String getGroupIdLevel1() // public String getIsimDomain() // public String getIsimImpi() // public String[] getIsimImpu() // public String getLine1AlphaTag() // public String getLine1Number() // public String getMsisdn() // public List<NeighboringCellInfo> getNeighboringCellInfo() // public String getNetworkCountryIso() // public String getNetworkOperator() // public String getNetworkOperatorName() // public String getSimCountryIso() // public String getSimOperator() // public String getSimOperatorName() // public static int getPhoneType(int networkMode) // public String getSimSerialNumber() // public String getSubscriberId() // public String getVoiceMailAlphaTag() // public String getVoiceMailNumber() // public void listen(PhoneStateListener listener, int events) // frameworks/base/telephony/java/android/telephony/TelephonyManager.java // http://developer.android.com/reference/android/telephony/TelephonyManager.html // public String getDeviceId() // public String getSubscriberId() // public String getGroupIdLevel1() // public String getIccSerialNumber() // public String getImei() // public String getLine1Number() // public String getLine1AlphaTag() // public String getMsisdn() // public String getVoiceMailNumber() // public String getVoiceMailAlphaTag() // public String getCompleteVoiceMailNumber() // public String getIsimImpi() // public String getIsimDomain() // public String[] getIsimImpu() // public String getIsimIst() // public String[] getIsimPcscf() // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/com/android/internal/telephony/PhoneSubInfo.java // public void listen(java.lang.String pkg, IPhoneStateListener callback, int events, boolean notifyNow) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/com/android/server/TelephonyRegistry.java // public void enableLocationUpdates() // public void enableLocationUpdatesForSubscriber(long subId) // public void disableLocationUpdates() // public void disableLocationUpdatesForSubscriber(long subId) // public List<android.telephony.CellInfo> getAllCellInfo() // public android.os.Bundle getCellLocation() // public String getCdmaMdn(long subId) // public String getCdmaMin(long subId) // public String getLine1AlphaTagForDisplay(long subId) // public String getLine1NumberForDisplay(long subId) // public List<android.telephony.NeighboringCellInfo> getNeighboringCellInfo() // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/com/android/internal/telephony/ITelephony.java // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/5.0.0_r1/com/android/phone/PhoneInterfaceManager.java // @formatter:on // @formatter:off private enum Methods { disableLocationUpdates, enableLocationUpdates, getAllCellInfo, getCellLocation, getDeviceId, getGroupIdLevel1, getIsimDomain, getIsimImpi, getIsimImpu, getLine1AlphaTag, getLine1Number, getMsisdn, getNeighboringCellInfo, getNetworkCountryIso, getNetworkOperator, getNetworkOperatorName, getSimCountryIso, getSimOperator, getSimOperatorName, getSimSerialNumber, getSubscriberId, getVoiceMailAlphaTag, getVoiceMailNumber, listen, Srv_getDeviceId, Srv_getGroupIdLevel1, Srv_getIccSerialNumber, Srv_getIsimDomain, Srv_getIsimImpi, Srv_getIsimImpu, Srv_getLine1AlphaTag, Srv_getLine1Number, Srv_getMsisdn, Srv_getSubscriberId, Srv_getCompleteVoiceMailNumber, Srv_getVoiceMailNumber, Srv_getVoiceMailAlphaTag, Srv_getImei, Srv_getIsimIst, Srv_getIsimPcscf, Srv_listen, Srv_enableLocationUpdates, Srv_disableLocationUpdates, Srv_getAllCellInfo, Srv_getCellLocation, Srv_getNeighboringCellInfo, Srv_enableLocationUpdatesForSubscriber, Srv_disableLocationUpdatesForSubscriber, Srv_getCdmaMdn, Srv_getCdmaMin, Srv_getLine1AlphaTagForDisplay, Srv_getLine1NumberForDisplay, // Android 5.x // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.0_r1/com/android/internal/telephony/PhoneSubInfoController.java Srv_getCompleteVoiceMailNumberForSubscriber5, Srv_getDeviceId5, Srv_getDeviceIdForPhone5, Srv_getDeviceIdForSubscriber5, Srv_getGroupIdLevel1ForSubscriber5, Srv_getIccSerialNumberForSubscriber5, Srv_getImeiForSubscriber5, Srv_getIsimDomain5, Srv_getIsimImpi5, Srv_getIsimImpu5, Srv_getIsimIst5, Srv_getIsimPcscf5, Srv_getLine1AlphaTagForSubscriber5, Srv_getLine1NumberForSubscriber5, Srv_getMsisdnForSubscriber5, Srv_getNaiForSubscriber5, // new Srv_getSubscriberIdForSubscriber5, Srv_getVoiceMailAlphaTagForSubscriber5, Srv_getVoiceMailNumberForSubscriber5 }; // @formatter:on public static List<XHook> getInstances(String className, boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (!cClassName.equals(className)) { if (className == null) className = cClassName; if (server) { // PhoneSubInfo/Controller if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { listHook.add(new XTelephonyManager(Methods.Srv_getDeviceId, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getGroupIdLevel1, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getIccSerialNumber, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimDomain, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimImpi, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimImpu, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getLine1AlphaTag, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getLine1Number, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getMsisdn, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getSubscriberId, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getCompleteVoiceMailNumber, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getVoiceMailAlphaTag, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getVoiceMailNumber, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getImei, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimIst, PrivacyManager.cPhone, Srv.SubInfo)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimPcscf, PrivacyManager.cPhone, Srv.SubInfo)); } else { listHook.add(new XTelephonyManager(Methods.Srv_getDeviceIdForPhone5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getDeviceIdForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getGroupIdLevel1ForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getIccSerialNumberForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimDomain5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimImpi5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimImpu5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getLine1AlphaTagForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getLine1NumberForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getMsisdnForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getSubscriberIdForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getCompleteVoiceMailNumberForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getVoiceMailAlphaTagForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getVoiceMailNumberForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getImeiForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimIst5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getIsimPcscf5, PrivacyManager.cPhone, Srv.SICtl)); listHook.add(new XTelephonyManager(Methods.Srv_getNaiForSubscriber5, PrivacyManager.cPhone, Srv.SICtl)); } } else { listHook.add(new XTelephonyManager(Methods.disableLocationUpdates, null, className)); listHook.add(new XTelephonyManager(Methods.enableLocationUpdates, PrivacyManager.cLocation, className)); listHook.add(new XTelephonyManager(Methods.getAllCellInfo, PrivacyManager.cLocation, className)); listHook.add(new XTelephonyManager(Methods.getCellLocation, PrivacyManager.cLocation, className)); listHook.add(new XTelephonyManager(Methods.getDeviceId, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getGroupIdLevel1, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getIsimDomain, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getIsimImpi, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getIsimImpu, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getLine1AlphaTag, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getLine1Number, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getMsisdn, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getNeighboringCellInfo, PrivacyManager.cLocation, className)); listHook.add(new XTelephonyManager(Methods.getSimSerialNumber, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getSubscriberId, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getVoiceMailAlphaTag, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getVoiceMailNumber, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.listen, PrivacyManager.cLocation, className)); listHook.add(new XTelephonyManager(Methods.listen, PrivacyManager.cPhone, className)); // No permissions required listHook.add(new XTelephonyManager(Methods.getNetworkCountryIso, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getNetworkOperator, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getNetworkOperatorName, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getSimCountryIso, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getSimOperator, PrivacyManager.cPhone, className)); listHook.add(new XTelephonyManager(Methods.getSimOperatorName, PrivacyManager.cPhone, className)); } } return listHook; } public static List<XHook> getPhoneInstances() { List<XHook> listHook = new ArrayList<XHook>(); if (Hook.isAOSP(19)) { listHook.add(new XTelephonyManager(Methods.Srv_enableLocationUpdates, PrivacyManager.cLocation, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_disableLocationUpdates, null, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_getAllCellInfo, PrivacyManager.cLocation, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_getCellLocation, PrivacyManager.cLocation, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_getNeighboringCellInfo, PrivacyManager.cLocation, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_enableLocationUpdatesForSubscriber, PrivacyManager.cLocation, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_disableLocationUpdatesForSubscriber, null, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_getCdmaMdn, PrivacyManager.cPhone, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_getCdmaMin, PrivacyManager.cPhone, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_getLine1AlphaTagForDisplay, PrivacyManager.cPhone, Srv.Phone)); listHook.add(new XTelephonyManager(Methods.Srv_getLine1NumberForDisplay, PrivacyManager.cPhone, Srv.Phone)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) listHook.add(new XTelephonyManager(Methods.Srv_getDeviceId5, PrivacyManager.cPhone, Srv.Phone)); return listHook; } public static List<XHook> getRegistryInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XTelephonyManager(Methods.Srv_listen, PrivacyManager.cLocation, Srv.Registry)); listHook.add(new XTelephonyManager(Methods.Srv_listen, PrivacyManager.cPhone, Srv.Registry)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case disableLocationUpdates: if (isRestricted(param, PrivacyManager.cLocation, "enableLocationUpdates")) param.setResult(null); break; case Srv_disableLocationUpdates: if (isRestricted(param, PrivacyManager.cLocation, "Srv_enableLocationUpdates")) param.setResult(null); break; case Srv_disableLocationUpdatesForSubscriber: if (isRestricted(param, PrivacyManager.cLocation, "Srv_enableLocationUpdatesForSubscriber")) param.setResult(null); break; case enableLocationUpdates: case Srv_enableLocationUpdates: case Srv_enableLocationUpdatesForSubscriber: if (isRestricted(param)) param.setResult(null); break; case getAllCellInfo: case getCellLocation: case getDeviceId: case getGroupIdLevel1: case getIsimDomain: case getIsimImpi: case getIsimImpu: case getLine1AlphaTag: case getLine1Number: case getMsisdn: case getNeighboringCellInfo: case getNetworkCountryIso: case getNetworkOperator: case getNetworkOperatorName: case getSimCountryIso: case getSimOperator: case getSimOperatorName: case getSimSerialNumber: case getSubscriberId: case getVoiceMailAlphaTag: case getVoiceMailNumber: case Srv_getAllCellInfo: case Srv_getCellLocation: case Srv_getNeighboringCellInfo: break; case listen: if (param.args.length > 1 && param.args[0] instanceof PhoneStateListener && param.args[1] instanceof Integer) { PhoneStateListener listener = (PhoneStateListener) param.args[0]; int event = (Integer) param.args[1]; if (event == PhoneStateListener.LISTEN_NONE) { // Remove synchronized (mListener) { XPhoneStateListener xListener = mListener.get(listener); if (xListener != null) { param.args[0] = xListener; Util.log(this, Log.WARN, "Removed count=" + mListener.size() + " uid=" + Binder.getCallingUid()); } } } else if (isRestricted(param)) try { // Replace XPhoneStateListener xListener; synchronized (mListener) { xListener = mListener.get(listener); if (xListener == null) { xListener = new XPhoneStateListener(listener); mListener.put(listener, xListener); Util.log(this, Log.WARN, "Added count=" + mListener.size() + " uid=" + Binder.getCallingUid()); } } param.args[0] = xListener; } catch (Throwable ignored) { // Some implementations require a looper // which is not according to the documentation // and stock source code } } break; case Srv_listen: if (isRestricted(param)) param.setResult(null); break; case Srv_getDeviceId: case Srv_getGroupIdLevel1: case Srv_getIccSerialNumber: case Srv_getIsimDomain: case Srv_getIsimImpi: case Srv_getIsimImpu: case Srv_getLine1AlphaTag: case Srv_getLine1Number: case Srv_getMsisdn: case Srv_getSubscriberId: case Srv_getCompleteVoiceMailNumber: case Srv_getVoiceMailNumber: case Srv_getVoiceMailAlphaTag: case Srv_getImei: case Srv_getIsimIst: case Srv_getIsimPcscf: case Srv_getCdmaMdn: case Srv_getCdmaMin: case Srv_getLine1AlphaTagForDisplay: case Srv_getLine1NumberForDisplay: break; case Srv_getCompleteVoiceMailNumberForSubscriber5: case Srv_getDeviceId5: case Srv_getDeviceIdForPhone5: case Srv_getDeviceIdForSubscriber5: case Srv_getGroupIdLevel1ForSubscriber5: case Srv_getIccSerialNumberForSubscriber5: case Srv_getImeiForSubscriber5: case Srv_getIsimDomain5: case Srv_getIsimImpi5: case Srv_getIsimImpu5: case Srv_getIsimIst5: case Srv_getIsimPcscf5: case Srv_getLine1AlphaTagForSubscriber5: case Srv_getLine1NumberForSubscriber5: case Srv_getMsisdnForSubscriber5: case Srv_getNaiForSubscriber5: case Srv_getSubscriberIdForSubscriber5: case Srv_getVoiceMailAlphaTagForSubscriber5: case Srv_getVoiceMailNumberForSubscriber5: break; } } @Override protected void after(XParam param) throws Throwable { int uid = Binder.getCallingUid(); switch (mMethod) { case disableLocationUpdates: case enableLocationUpdates: case Srv_disableLocationUpdates: case Srv_enableLocationUpdates: case Srv_disableLocationUpdatesForSubscriber: case Srv_enableLocationUpdatesForSubscriber: break; case getAllCellInfo: case Srv_getAllCellInfo: if (param.getResult() != null) if (isRestricted(param)) param.setResult(new ArrayList<CellInfo>()); break; case getCellLocation: if (param.getResult() != null) if (isRestricted(param)) param.setResult(getDefacedCellLocation(uid)); break; case Srv_getCellLocation: if (param.getResult() != null) if (isRestricted(param)) param.setResult(getDefacedCellBundle(uid)); break; case getNeighboringCellInfo: case Srv_getNeighboringCellInfo: if (param.getResult() != null && isRestricted(param)) param.setResult(new ArrayList<NeighboringCellInfo>()); break; case listen: case Srv_listen: break; case getDeviceId: case getGroupIdLevel1: case getIsimDomain: case getIsimImpi: case getIsimImpu: case getNetworkCountryIso: case getNetworkOperator: case getNetworkOperatorName: case getSimCountryIso: case getSimOperator: case getSimOperatorName: case getSimSerialNumber: case getSubscriberId: if (param.getResult() != null) if (isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(uid, mMethod.name())); break; case getLine1AlphaTag: case getLine1Number: case getMsisdn: case getVoiceMailAlphaTag: case getVoiceMailNumber: String phoneNumber = (String) param.getResult(); if (phoneNumber != null) if (isRestrictedValue(param, phoneNumber)) param.setResult(PrivacyManager.getDefacedProp(uid, mMethod.name())); break; case Srv_getDeviceId: case Srv_getGroupIdLevel1: case Srv_getIccSerialNumber: case Srv_getIsimDomain: case Srv_getIsimImpi: case Srv_getIsimImpu: case Srv_getSubscriberId: case Srv_getImei: case Srv_getDeviceId5: case Srv_getDeviceIdForPhone5: case Srv_getDeviceIdForSubscriber5: case Srv_getGroupIdLevel1ForSubscriber5: case Srv_getIccSerialNumberForSubscriber5: case Srv_getImeiForSubscriber5: case Srv_getIsimDomain5: case Srv_getIsimImpi5: case Srv_getIsimImpu5: case Srv_getNaiForSubscriber5: case Srv_getSubscriberIdForSubscriber5: if (param.getResult() != null) if (isRestricted(param)) { String name = mMethod.name(); name = name.replace("Srv_", ""); name = name.replace("ForPhone", ""); name = name.replace("ForSubscriber", ""); name = name.replace("5", ""); param.setResult(PrivacyManager.getDefacedProp(uid, name)); } break; case Srv_getLine1AlphaTag: case Srv_getLine1Number: case Srv_getMsisdn: case Srv_getCompleteVoiceMailNumber: case Srv_getVoiceMailNumber: case Srv_getVoiceMailAlphaTag: case Srv_getLine1AlphaTagForDisplay: case Srv_getLine1NumberForDisplay: case Srv_getCompleteVoiceMailNumberForSubscriber5: case Srv_getLine1AlphaTagForSubscriber5: case Srv_getLine1NumberForSubscriber5: case Srv_getMsisdnForSubscriber5: case Srv_getVoiceMailAlphaTagForSubscriber5: case Srv_getVoiceMailNumberForSubscriber5: String srvPhoneNumber = (String) param.getResult(); if (srvPhoneNumber != null) if (isRestrictedValue(param, srvPhoneNumber)) { String name = mMethod.name(); name = name.replace("Srv_", ""); name = name.replace("ForSubscriber", ""); name = name.replace("5", ""); param.setResult(PrivacyManager.getDefacedProp(uid, name)); } break; case Srv_getIsimIst: case Srv_getIsimPcscf: case Srv_getCdmaMdn: case Srv_getCdmaMin: case Srv_getIsimIst5: case Srv_getIsimPcscf5: if (param.getResult() != null) if (isRestricted(param)) param.setResult(null); break; } } private static CellLocation getDefacedCellLocation(int uid) { int cid = (Integer) PrivacyManager.getDefacedProp(uid, "CID"); int lac = (Integer) PrivacyManager.getDefacedProp(uid, "LAC"); if (cid > 0 && lac > 0) { GsmCellLocation cellLocation = new GsmCellLocation(); cellLocation.setLacAndCid(lac, cid); return cellLocation; } else return CellLocation.getEmpty(); } private static Bundle getDefacedCellBundle(int uid) { Bundle result = new Bundle(); int cid = (Integer) PrivacyManager.getDefacedProp(uid, "CID"); int lac = (Integer) PrivacyManager.getDefacedProp(uid, "LAC"); if (cid > 0 && lac > 0) { result.putInt("lac", lac); result.putInt("cid", cid); } return result; } private class XPhoneStateListener extends PhoneStateListener { private PhoneStateListener mListener; public XPhoneStateListener(PhoneStateListener listener) { mListener = listener; } @Override public void onCallForwardingIndicatorChanged(boolean cfi) { mListener.onCallForwardingIndicatorChanged(cfi); } @Override public void onCallStateChanged(int state, String incomingNumber) { mListener.onCallStateChanged(state, (String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "PhoneNumber")); } @Override public void onCellInfoChanged(List<CellInfo> cellInfo) { mListener.onCellInfoChanged(new ArrayList<CellInfo>()); } @Override public void onCellLocationChanged(CellLocation location) { mListener.onCellLocationChanged(getDefacedCellLocation(Binder.getCallingUid())); } @Override public void onDataActivity(int direction) { mListener.onDataActivity(direction); } @Override public void onDataConnectionStateChanged(int state) { mListener.onDataConnectionStateChanged(state); } @Override public void onDataConnectionStateChanged(int state, int networkType) { mListener.onDataConnectionStateChanged(state, networkType); } @Override public void onMessageWaitingIndicatorChanged(boolean mwi) { mListener.onMessageWaitingIndicatorChanged(mwi); } @Override public void onServiceStateChanged(ServiceState serviceState) { mListener.onServiceStateChanged(serviceState); } @Override @SuppressWarnings("deprecation") public void onSignalStrengthChanged(int asu) { mListener.onSignalStrengthChanged(asu); } @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { mListener.onSignalStrengthsChanged(signalStrength); } } }
25,828
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XActivityManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XActivityManager.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Intent; import android.net.Uri; public class XActivityManager extends XHook { private Methods mMethod; private String mClassName; private static final String cClassName = "android.app.ActivityManager"; private static Map<String, String> mapIntentRestriction = new HashMap<String, String>(); static { mapIntentRestriction.put(Intent.ACTION_VIEW, PrivacyManager.cView); } private XActivityManager(Methods method, String restrictionName, String className) { super(restrictionName, method.name().replace("Srv_", ""), method.name()); mMethod = method; if (className == null) mClassName = "com.android.server.am.ActivityManagerService"; else mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // public List<RecentTaskInfo> getRecentTasks(int maxNum, int flags) // public List<RunningAppProcessInfo> getRunningAppProcesses() // public List<RunningServiceInfo> getRunningServices(int maxNum) // public List<RunningTaskInfo> getRunningTasks(int maxNum) // frameworks/base/core/java/android/app/ActivityManager.java // http://developer.android.com/reference/android/app/ActivityManager.html // public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, int userId) // public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() // public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) // public List<RunningTaskInfo> getTasks(int maxNum, int flags, IThumbnailReceiver receiver) // public int startActivities(IApplicationThread caller, String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options, int userId) // public int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags, String profileFile, ParcelFileDescriptor profileFd, Bundle options) // public int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags, String profileFile,ParcelFileDescriptor profileFd, Bundle options, int userId) // public WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags, String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) // public int startActivityWithConfig(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, Configuration newConfig, Bundle options, int userId) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.2_r1/com/android/server/am/ActivityManagerService.java // public int startActivityAsCaller(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flags, ProfilerInfo profilerInfo, Bundle options, int userId) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/android/accounts/IAccountManager.java/ // @formatter:on // @formatter:off private enum Methods { getRecentTasks, getRunningAppProcesses, getRunningServices, getRunningTasks, Srv_getRecentTasks, Srv_getRunningAppProcesses, Srv_getServices, Srv_getTasks, Srv_startActivities, Srv_startActivity, Srv_startActivityAsCaller, Srv_startActivityAsUser, Srv_startActivityAndWait, Srv_startActivityWithConfig }; // @formatter:on public static List<XHook> getInstances(String className, boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (!cClassName.equals(className)) { if (className == null) className = cClassName; for (Methods act : Methods.values()) if (act.name().startsWith("Srv_")) { if (server) if (act.name().startsWith("Srv_start")) listHook.add(new XActivityManager(act, null, null)); else listHook.add(new XActivityManager(act, PrivacyManager.cSystem, null)); } else if (!server) listHook.add(new XActivityManager(act, PrivacyManager.cSystem, className)); } return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case getRecentTasks: case getRunningAppProcesses: case getRunningServices: case getRunningTasks: case Srv_getRecentTasks: case Srv_getRunningAppProcesses: case Srv_getServices: case Srv_getTasks: break; case Srv_startActivities: if (param.args.length > 2 && param.args[2] instanceof Intent[]) { List<Intent> listIntent = new ArrayList<Intent>(); for (Intent intent : (Intent[]) param.args[2]) if (!isRestricted(param, intent)) listIntent.add(intent); if (listIntent.size() == 0) param.setResult(0); // ActivityManager.START_SUCCESS else param.args[2] = listIntent.toArray(new Intent[0]); } break; case Srv_startActivity: case Srv_startActivityAsCaller: case Srv_startActivityAsUser: case Srv_startActivityWithConfig: if (param.args.length > 2 && param.args[2] instanceof Intent) { Intent intent = (Intent) param.args[2]; if (isRestricted(param, intent)) param.setResult(0); // ActivityManager.START_SUCCESS } break; case Srv_startActivityAndWait: if (param.args.length > 2 && param.args[2] instanceof Intent) { Intent intent = (Intent) param.args[2]; if (isRestricted(param, intent)) { Class<?> cWaitResult = Class.forName("android.app.IActivityManager.WaitResult"); Field fWho = cWaitResult.getDeclaredField("who"); Class<?> we = this.getClass(); ComponentName component = new ComponentName(we.getPackage().getName(), we.getName()); Object waitResult = cWaitResult.getConstructor().newInstance(); fWho.set(waitResult, component); param.setResult(waitResult); } } break; } } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case getRecentTasks: case Srv_getRecentTasks: if (param.getResult() != null && isRestricted(param)) param.setResult(new ArrayList<ActivityManager.RecentTaskInfo>()); break; case getRunningAppProcesses: case Srv_getRunningAppProcesses: if (param.getResult() != null && isRestricted(param)) param.setResult(new ArrayList<ActivityManager.RunningAppProcessInfo>()); break; case getRunningServices: case Srv_getServices: if (param.getResult() != null && isRestricted(param)) param.setResult(new ArrayList<ActivityManager.RunningServiceInfo>()); break; case getRunningTasks: case Srv_getTasks: if (param.getResult() != null && isRestricted(param)) param.setResult(new ArrayList<ActivityManager.RunningTaskInfo>()); break; case Srv_startActivities: case Srv_startActivity: case Srv_startActivityAsCaller: case Srv_startActivityAsUser: case Srv_startActivityAndWait: case Srv_startActivityWithConfig: break; } } // Helper methods private boolean isRestricted(XParam param, Intent intent) throws Throwable { String action = intent.getAction(); if (mapIntentRestriction.containsKey(action)) { String restrictionName = mapIntentRestriction.get(action); if (Intent.ACTION_VIEW.equals(action)) { Uri uri = intent.getData(); if (uri != null) return isRestrictedExtra(param, restrictionName, "Srv_" + action, uri.toString()); } else return isRestricted(param, restrictionName, "Srv_" + action); } return false; } }
7,887
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XAdvertisingIdClientInfo.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XAdvertisingIdClientInfo.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Binder; import android.util.Log; public class XAdvertisingIdClientInfo extends XHook { private Methods mMethod; private XAdvertisingIdClientInfo(Methods method, String restrictionName, String specifier) { super(restrictionName, method.name(), specifier); mMethod = method; } public String getClassName() { return "com.google.android.gms.ads.identifier.AdvertisingIdClient$Info"; } // @formatter:off // String getId() // http://developer.android.com/reference/com/google/android/gms/ads/identifier/AdvertisingIdClient.Info.html // @formatter:on private enum Methods { getId }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XAdvertisingIdClientInfo(Methods.getId, PrivacyManager.cIdentification, "AdvertisingId")); return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { if (mMethod == Methods.getId) { String adid = (String) param.getResult(); if (adid != null) if (isRestrictedValue(param, adid)) param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), "AdvertisingId")); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } }
1,406
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XNetworkInterface.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XNetworkInterface.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import android.os.Binder; import android.util.Log; public class XNetworkInterface extends XHook { private Methods mMethod; private XNetworkInterface(Methods method, String restrictionName) { super(restrictionName, method.name(), "NetworkInterface." + method.name()); mMethod = method; } public String getClassName() { return "java.net.NetworkInterface"; } // Internet: // - public static NetworkInterface getByIndex(int index) // - public static NetworkInterface getByInetAddress(InetAddress address) // - public static NetworkInterface getByName(String interfaceName) // - public static Enumeration<NetworkInterface> getNetworkInterfaces() // Network: // - public byte[] getHardwareAddress() // - public Enumeration<InetAddress> getInetAddresses() // - public List<InterfaceAddress> getInterfaceAddresses() // libcore/luni/src/main/java/java/net/NetworkInterface.java // http://developer.android.com/reference/java/net/NetworkInterface.html // @formatter:off private enum Methods { getByIndex, getByInetAddress, getByName, getNetworkInterfaces, getHardwareAddress, getInetAddresses, getInterfaceAddresses }; // @formatter:on public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XNetworkInterface(Methods.getByIndex, PrivacyManager.cInternet)); listHook.add(new XNetworkInterface(Methods.getByInetAddress, PrivacyManager.cInternet)); listHook.add(new XNetworkInterface(Methods.getByName, PrivacyManager.cInternet)); listHook.add(new XNetworkInterface(Methods.getNetworkInterfaces, PrivacyManager.cInternet)); listHook.add(new XNetworkInterface(Methods.getHardwareAddress, PrivacyManager.cNetwork)); listHook.add(new XNetworkInterface(Methods.getInetAddresses, PrivacyManager.cNetwork)); listHook.add(new XNetworkInterface(Methods.getInterfaceAddresses, PrivacyManager.cNetwork)); return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { if (getRestrictionName().equals(PrivacyManager.cInternet)) { // Internet: fake offline state if (mMethod == Methods.getByIndex || mMethod == Methods.getByInetAddress || mMethod == Methods.getByName || mMethod == Methods.getNetworkInterfaces) { if (param.getResult() != null && isRestricted(param)) param.setResult(null); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } else if (getRestrictionName().equals(PrivacyManager.cNetwork)) { // Network NetworkInterface ni = (NetworkInterface) param.thisObject; if (ni != null) if (param.getResult() != null && isRestricted(param)) if (mMethod == Methods.getHardwareAddress) { String mac = (String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "MAC"); long lMac = Long.parseLong(mac.replace(":", ""), 16); byte[] address = ByteBuffer.allocate(8).putLong(lMac).array(); param.setResult(address); } else if (mMethod == Methods.getInetAddresses) { @SuppressWarnings("unchecked") Enumeration<InetAddress> addresses = (Enumeration<InetAddress>) param.getResult(); List<InetAddress> listAddress = new ArrayList<InetAddress>(); for (InetAddress address : Collections.list(addresses)) if (address.isAnyLocalAddress() || address.isLoopbackAddress()) listAddress.add(address); else listAddress.add((InetAddress) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "InetAddress")); param.setResult(Collections.enumeration(listAddress)); } else if (mMethod == Methods.getInterfaceAddresses) { @SuppressWarnings("unchecked") List<InterfaceAddress> listAddress = (List<InterfaceAddress>) param.getResult(); for (InterfaceAddress address : listAddress) { // address try { Field fieldAddress = InterfaceAddress.class.getDeclaredField("address"); fieldAddress.setAccessible(true); fieldAddress.set(address, PrivacyManager.getDefacedProp(Binder.getCallingUid(), "InetAddress")); } catch (Throwable ex) { Util.bug(this, ex); } // broadcastAddress try { Field fieldBroadcastAddress = InterfaceAddress.class .getDeclaredField("broadcastAddress"); fieldBroadcastAddress.setAccessible(true); fieldBroadcastAddress.set(address, PrivacyManager.getDefacedProp(Binder.getCallingUid(), "InetAddress")); } catch (Throwable ex) { Util.bug(this, ex); } } } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } } }
5,005
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
WhitelistTask.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/WhitelistTask.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Spinner; import android.widget.AdapterView.OnItemSelectedListener; public class WhitelistTask extends AsyncTask<Object, Object, Object> { private int mUid; private String mType; private ActivityBase mContext; private WhitelistAdapter mWhitelistAdapter; private Map<String, TreeMap<String, Boolean>> mListWhitelist; public WhitelistTask(int uid, String type, ActivityBase context) { mUid = uid; mType = type; mContext = context; } @Override protected Object doInBackground(Object... params) { mListWhitelist = PrivacyManager.listWhitelisted(mUid, null); mWhitelistAdapter = new WhitelistAdapter(mContext, R.layout.whitelistentry, mUid, mListWhitelist); return null; } @Override @SuppressLint({ "DefaultLocale", "InflateParams" }) protected void onPostExecute(Object result) { if (!mContext.isFinishing()) { // Build dialog AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); alertDialogBuilder.setTitle(R.string.menu_whitelists); alertDialogBuilder.setIcon(mContext.getThemed(R.attr.icon_launcher)); if (mListWhitelist.keySet().size() > 0) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View llWhitelists = inflater.inflate(R.layout.whitelists, null); int index = 0; int selected = -1; final List<String> localizedType = new ArrayList<String>(); for (String type : mListWhitelist.keySet()) { String name = "whitelist_" + type.toLowerCase().replace("/", ""); int id = mContext.getResources().getIdentifier(name, "string", mContext.getPackageName()); if (id == 0) localizedType.add(name); else localizedType.add(mContext.getResources().getString(id)); if (type.equals(mType)) selected = index; index++; } Spinner spWhitelistType = (Spinner) llWhitelists.findViewById(R.id.spWhitelistType); ArrayAdapter<String> whitelistTypeAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_dropdown_item, localizedType); spWhitelistType.setAdapter(whitelistTypeAdapter); spWhitelistType.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mWhitelistAdapter.setType(mListWhitelist.keySet().toArray(new String[0])[position]); } @Override public void onNothingSelected(AdapterView<?> view) { } }); if (selected >= 0) spWhitelistType.setSelection(selected); ListView lvWhitelist = (ListView) llWhitelists.findViewById(R.id.lvWhitelist); lvWhitelist.setAdapter(mWhitelistAdapter); int position = spWhitelistType.getSelectedItemPosition(); if (position != AdapterView.INVALID_POSITION) mWhitelistAdapter.setType(mListWhitelist.keySet().toArray(new String[0])[position]); alertDialogBuilder.setView(llWhitelists); } alertDialogBuilder.setPositiveButton(mContext.getString(R.string.msg_done), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do nothing } }); // Show dialog AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } super.onPostExecute(result); } }
3,803
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XCameraDevice2.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XCameraDevice2.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.util.Log; public class XCameraDevice2 extends XHook { private Methods mMethod; private XCameraDevice2(Methods method, String restrictionName) { super(restrictionName, method.name(), "Camera2." + method.name()); mMethod = method; } public String getClassName() { return "android.hardware.camera2.impl.CameraDeviceImpl"; } // @formatter:off // public int capture(CaptureRequest request, CaptureListener listener, Handler handler) // public int captureBurst(List<CaptureRequest> requests, CaptureListener listener, Handler handler) // public int setRepeatingRequest(CaptureRequest request, CaptureListener listener, Handler handler) // public int setRepeatingBurst(List<CaptureRequest> requests, CaptureListener listener, Handler handler) // frameworks/base/core/java/android/hardware/camera2/impl/CameraDevice.java // http://developer.android.com/reference/android/hardware/camera2/CameraDevice.html // @formatter:on private enum Methods { capture, captureBurst, setRepeatingRequest, setRepeatingBurst }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); for (Methods cam : Methods.values()) listHook.add(new XCameraDevice2(cam, PrivacyManager.cMedia)); return listHook; } @Override protected void before(XParam param) throws Throwable { if (mMethod == Methods.capture || mMethod == Methods.captureBurst) { if (isRestricted(param)) param.setResult(0); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
1,717
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XSmsManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XSmsManager.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.telephony.SmsMessage; public class XSmsManager extends XHook { private Methods mMethod; private XSmsManager(Methods method, String restrictionName) { super(restrictionName, method.name().replace("Srv_", ""), method.name()); mMethod = method; } public String getClassName() { if (mMethod.name().startsWith("Srv_")) return "com.android.internal.telephony.IccSmsInterfaceManager"; else return "android.telephony.SmsManager"; } // @formatter:off // public static ArrayList<SmsMessage> getAllMessagesFromIcc() // public Bundle getCarrierConfigValues() // public void sendDataMessage(String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent) // public void sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents) // public void sendMultimediaMessage(Context context, Uri contentUri, String locationUrl, Bundle configOverrides, PendingIntent sentIntent) // public void sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent) // frameworks/base/telephony/java/android/telephony/SmsManager.java // http://developer.android.com/reference/android/telephony/SmsManager.html // public List<SmsRawData> getAllMessagesFromIccEf(String callingPackage) // public void sendData(java.lang.String callingPkg, java.lang.String destAddr, java.lang.String scAddr, int destPort, byte[] data, android.app.PendingIntent sentIntent, android.app.PendingIntent deliveryIntent) // public void sendMultipartText(java.lang.String callingPkg, java.lang.String destinationAddress, java.lang.String scAddress, java.util.List<java.lang.String> parts, java.util.List<android.app.PendingIntent> sentIntents, java.util.List<android.app.PendingIntent> deliveryIntents) // public void sendText(java.lang.String callingPkg, java.lang.String destAddr, java.lang.String scAddr, java.lang.String text, android.app.PendingIntent sentIntent, android.app.PendingIntent deliveryIntent) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.2_r1/com/android/internal/telephony/IccSmsInterfaceManager.java/ // @formatter:on // @formatter:off private enum Methods { getAllMessagesFromIcc, getCarrierConfigValues, sendDataMessage, sendMultipartTextMessage, sendMultimediaMessage, sendTextMessage, Srv_getAllMessagesFromIccEf, Srv_sendData, Srv_sendMultipartText, Srv_sendText }; // @formatter:on public static List<XHook> getInstances(boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (server) { listHook.add(new XSmsManager(Methods.Srv_getAllMessagesFromIccEf, PrivacyManager.cMessages)); listHook.add(new XSmsManager(Methods.Srv_sendData, PrivacyManager.cCalling)); listHook.add(new XSmsManager(Methods.Srv_sendMultipartText, PrivacyManager.cCalling)); listHook.add(new XSmsManager(Methods.Srv_sendText, PrivacyManager.cCalling)); } else { listHook.add(new XSmsManager(Methods.getAllMessagesFromIcc, PrivacyManager.cMessages)); listHook.add(new XSmsManager(Methods.getCarrierConfigValues, PrivacyManager.cMessages)); listHook.add(new XSmsManager(Methods.sendDataMessage, PrivacyManager.cCalling)); listHook.add(new XSmsManager(Methods.sendMultimediaMessage, PrivacyManager.cCalling)); listHook.add(new XSmsManager(Methods.sendMultipartTextMessage, PrivacyManager.cCalling)); listHook.add(new XSmsManager(Methods.sendTextMessage, PrivacyManager.cCalling)); } return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case getAllMessagesFromIcc: case getCarrierConfigValues: // Do nothing break; case sendDataMessage: case sendMultipartTextMessage: case sendTextMessage: if (param.args.length > 0 && param.args[0] instanceof String) if (isRestrictedExtra(param, (String) param.args[0])) param.setResult(null); break; case sendMultimediaMessage: if (isRestricted(param)) param.setResult(null); break; case Srv_getAllMessagesFromIccEf: // Do nothing break; case Srv_sendData: case Srv_sendText: case Srv_sendMultipartText: if (param.args.length > 1 && (param.args[1] == null || param.args[1] instanceof String)) if (isRestrictedExtra(param, (String) param.args[1])) param.setResult(null); break; } } @Override @SuppressWarnings("rawtypes") protected void after(XParam param) throws Throwable { switch (mMethod) { case getAllMessagesFromIcc: if (param.getResult() != null && isRestricted(param)) param.setResult(new ArrayList<SmsMessage>()); break; case getCarrierConfigValues: if (param.getResult() != null && isRestricted(param)) param.setResult(new Bundle()); break; case sendDataMessage: case sendMultimediaMessage: case sendMultipartTextMessage: case sendTextMessage: // Do nothing break; case Srv_getAllMessagesFromIccEf: if (param.getResult() != null && isRestricted(param)) param.setResult(new ArrayList()); break; case Srv_sendData: case Srv_sendText: case Srv_sendMultipartText: // Do nothing break; } } }
5,410
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XParam.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XParam.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import android.util.Log; import de.robv.android.xposed.XC_MethodHook.MethodHookParam; public class XParam { public Member method; public Object thisObject; public Object[] args; private Object mResult; private Throwable mThrowable; private boolean mHasResult = false; private boolean mHasThrowable = false; private Map<String, Object> mExtra = null; private XParam() { } public static XParam fromXposed(MethodHookParam param) { XParam xparam = new XParam(); xparam.method = param.method; xparam.thisObject = param.thisObject; xparam.args = param.args; xparam.mResult = param.getResult(); xparam.mThrowable = param.getThrowable(); if (xparam.args == null) xparam.args = new Object[] {}; return xparam; } public boolean doesReturn(Class<?> result) { if (this.method instanceof Method) return (((Method) this.method).getReturnType().equals(result)); return false; } public void setResult(Object result) { if (result instanceof Throwable) { Util.log(null, Log.ERROR, "Set result throwable=" + result); setThrowable((Throwable) result); } else { mResult = result; mHasResult = true; } } public boolean hasResult() { return mHasResult; } public Object getResult() { return mResult; } public boolean doesThrow(Class<?> ex) { if (this.method instanceof Method) for (Class<?> t : ((Method) this.method).getExceptionTypes()) if (t.equals(ex)) return true; return false; } public void setThrowable(Throwable ex) { mThrowable = ex; mHasThrowable = true; } public boolean hasThrowable() { return mHasThrowable; } public Throwable getThrowable() { return mThrowable; } public Object getExtras() { return mExtra; } @SuppressWarnings("unchecked") public void setExtras(Object extra) { mExtra = (Map<String, Object>) extra; } public void setObjectExtra(String name, Object value) { if (mExtra == null) mExtra = new HashMap<String, Object>(); mExtra.put(name, value); } public Object getObjectExtra(String name) { return (mExtra == null ? null : mExtra.get(name)); } }
2,238
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
CSetting.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/CSetting.java
package biz.bokhorst.xprivacy; import java.util.Date; import android.util.Log; public class CSetting { private long mTimestamp; private int mUid; private String mType; private String mName; private String mValue; public CSetting(int uid, String type, String name) { mTimestamp = new Date().getTime(); mUid = Math.abs(uid); mType = type; mName = name; mValue = null; if (type == null) { Util.log(null, Log.WARN, "CSetting null"); Util.logStack(null, Log.WARN); } } public void setValue(String value) { mValue = value; } public boolean willExpire() { if (mUid == 0) { if (mName.equals(PrivacyManager.cSettingVersion)) return false; if (mName.equals(PrivacyManager.cSettingLog)) return false; if (mName.equals(PrivacyManager.cSettingExperimental)) return false; } return true; } public boolean isExpired() { return (willExpire() ? (mTimestamp + PrivacyManager.cSettingCacheTimeoutMs < new Date().getTime()) : false); } public int getUid() { return mUid; } public String getValue() { return mValue; } @Override public boolean equals(Object obj) { CSetting other = (CSetting) obj; return (this.mUid == other.mUid && this.mType.equals(other.mType) && this.mName.equals(other.mName)); } @Override public int hashCode() { return mUid ^ mType.hashCode() ^ mName.hashCode(); } @Override public String toString() { return mUid + ":" + mType + "/" + mName + "=" + mValue; } }
1,465
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XActivity.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XActivity.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.annotation.SuppressLint; import android.content.Intent; import android.net.Uri; import android.provider.MediaStore; public class XActivity extends XHook { private Methods mMethod; private String mActionName; private XActivity(Methods method, String restrictionName, String actionName) { super(restrictionName, method.name(), actionName); mMethod = method; mActionName = actionName; } public String getClassName() { return "android.app.Activity"; } // @formatter:off // public Object getSystemService(String name) // public void startActivities(Intent[] intents) // public void startActivities(Intent[] intents, Bundle options) // public void startActivity(Intent intent) // public void startActivity(Intent intent, Bundle options) // public void startActivityForResult(Intent intent, int requestCode) // public void startActivityForResult(Intent intent, int requestCode, Bundle options) // public void startActivityFromChild(Activity child, Intent intent, int requestCode) // public void startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options) // public void startActivityFromFragment(Fragment fragment, Intent intent, int requestCode) // public void startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options) // public boolean startActivityIfNeeded(Intent intent, int requestCode) // public boolean startActivityIfNeeded(Intent intent, int requestCode, Bundle options) // public boolean startNextMatchingActivity(Intent intent) // public boolean startNextMatchingActivity(Intent intent, Bundle options) // frameworks/base/core/java/android/app/Activity.java // @formatter:on // @formatter:off private enum Methods { getSystemService, startActivities, startActivity, startActivityForResult, startActivityFromChild, startActivityFromFragment, startActivityIfNeeded, startNextMatchingActivity }; // @formatter:on @SuppressLint("InlinedApi") public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XActivity(Methods.getSystemService, null, null)); List<Methods> startMethods = new ArrayList<Methods>(Arrays.asList(Methods.values())); startMethods.remove(Methods.getSystemService); // Intent send: browser for (Methods activity : startMethods) listHook.add(new XActivity(activity, PrivacyManager.cView, Intent.ACTION_VIEW)); // Intent send: call/dial for (Methods activity : startMethods) { listHook.add(new XActivity(activity, PrivacyManager.cCalling, Intent.ACTION_CALL)); listHook.add(new XActivity(activity, PrivacyManager.cCalling, Intent.ACTION_DIAL)); } // Intent send: media for (Methods activity : startMethods) { listHook.add(new XActivity(activity, PrivacyManager.cMedia, MediaStore.ACTION_IMAGE_CAPTURE)); listHook.add(new XActivity(activity, PrivacyManager.cMedia, MediaStore.ACTION_IMAGE_CAPTURE_SECURE)); listHook.add(new XActivity(activity, PrivacyManager.cMedia, MediaStore.ACTION_VIDEO_CAPTURE)); } return listHook; } @Override @SuppressLint("DefaultLocale") protected void before(XParam param) throws Throwable { // Get intent(s) Intent[] intents = null; switch (mMethod) { case getSystemService: // Do nothing break; case startActivity: case startActivityForResult: case startActivityIfNeeded: case startNextMatchingActivity: if (param.args.length > 0 && param.args[0] instanceof Intent) intents = new Intent[] { (Intent) param.args[0] }; break; case startActivityFromChild: case startActivityFromFragment: if (param.args.length > 1 && param.args[1] instanceof Intent) intents = new Intent[] { (Intent) param.args[1] }; break; case startActivities: if (param.args.length > 0 && param.args[0] instanceof Intent[]) intents = (Intent[]) param.args[0]; break; } // Process intent(s) if (intents != null) for (Intent intent : intents) if (mActionName.equals(intent.getAction())) { boolean restricted = false; if (mActionName.equals(Intent.ACTION_VIEW)) { Uri uri = intent.getData(); if (uri != null) if (isRestrictedExtra(param, mActionName, uri.toString())) restricted = true; } else restricted = isRestricted(param, mActionName); if (restricted) { if (mMethod == Methods.startActivityIfNeeded) param.setResult(true); else param.setResult(null); return; } } } @Override protected void after(XParam param) throws Throwable { if (mMethod == Methods.getSystemService) if (param.args.length > 0 && param.args[0] instanceof String && param.getResult() != null) { String name = (String) param.args[0]; Object instance = param.getResult(); XPrivacy.handleGetSystemService(name, instance.getClass().getName(), getSecret()); } } }
4,973
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XEnvironment.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XEnvironment.java
package biz.bokhorst.xprivacy; import java.io.File; import java.util.ArrayList; import java.util.List; import android.os.Build; import android.os.Environment; import biz.bokhorst.xprivacy.XHook; public class XEnvironment extends XHook { private Methods mMethod; private XEnvironment(Methods method, String restrictionName) { super(restrictionName, method.name(), null); mMethod = method; } public String getClassName() { return "android.os.Environment"; } // public static String getExternalStorageState() // frameworks/base/core/java/android/os/Environment.java // http://developer.android.com/reference/android/os/Environment.html private enum Methods { getExternalStorageState }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XEnvironment(Methods.getExternalStorageState, PrivacyManager.cStorage)); return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case getExternalStorageState: if (param.getResult() != null) { String extra = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) if (param.args.length > 0 && param.args[0] instanceof File) extra = ((File) param.args[0]).getAbsolutePath(); if (isRestrictedExtra(param, extra)) param.setResult(Environment.MEDIA_UNMOUNTED); } break; } } }
1,486
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XAppIndexApi.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XAppIndexApi.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Binder; import android.util.Log; public class XAppIndexApi extends XHook { private Methods mMethod; private String mClassName; private XAppIndexApi(Methods method, String restrictionName, String className) { super(restrictionName, method.name(), "GMS5." + method.name()); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // abstract PendingResult<Status> view(GoogleApiClient apiClient, Activity activity, Intent viewIntent, String title, Uri webUrl, List<AppIndexApi.AppIndexingLink> outLinks) // abstract PendingResult<Status> view(GoogleApiClient apiClient, Activity activity, Uri appIndexingUrl, String title, Uri webUrl, List<AppIndexApi.AppIndexingLink> outLinks) // abstract PendingResult<Status> viewEnd(GoogleApiClient apiClient, Activity activity, Uri appIndexingUrl) // abstract PendingResult<Status> viewEnd(GoogleApiClient apiClient, Activity activity, Intent viewIntent) // https://developer.android.com/reference/com/google/android/gms/appindexing/AppIndexApi.html // @formatter:on private enum Methods { view, viewEnd }; public static List<XHook> getInstances(Object instance) { String className = instance.getClass().getName(); Util.log(null, Log.INFO, "Hooking AppIndex class=" + className + " uid=" + Binder.getCallingUid()); List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XAppIndexApi(Methods.viewEnd, null, className)); listHook.add(new XAppIndexApi(Methods.view, PrivacyManager.cView, className)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case viewEnd: if (isRestricted(param, PrivacyManager.cView, "GMS5.view")) param.setResult(XGoogleApiClient.getPendingResult(param.thisObject.getClass().getClassLoader())); break; case view: if (isRestricted(param)) param.setResult(XGoogleApiClient.getPendingResult(param.thisObject.getClass().getClassLoader())); break; } } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
2,201
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XHook.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XHook.java
package biz.bokhorst.xprivacy; import android.annotation.SuppressLint; import android.os.Binder; public abstract class XHook { private String mRestrictionName; private String mMethodName; private String mSpecifier; private String mSecret; protected XHook(String restrictionName, String methodName, String specifier) { mRestrictionName = restrictionName; mMethodName = methodName; mSpecifier = specifier; } abstract public String getClassName(); public boolean isVisible() { return true; } public String getRestrictionName() { return mRestrictionName; } public String getMethodName() { return mMethodName; } public String getSpecifier() { return (mSpecifier == null ? mMethodName : mSpecifier); } public void setSecret(String secret) { mSecret = secret; } protected String getSecret() { return mSecret; } abstract protected void before(XParam param) throws Throwable; abstract protected void after(XParam param) throws Throwable; protected boolean isRestricted(XParam param) throws Throwable { return isRestricted(param, getSpecifier()); } protected boolean isRestrictedExtra(XParam param, String extra) throws Throwable { int uid = Binder.getCallingUid(); return PrivacyManager.getRestrictionExtra(this, uid, mRestrictionName, getSpecifier(), extra, mSecret); } protected boolean isRestrictedExtra(XParam param, String methodName, String extra) throws Throwable { int uid = Binder.getCallingUid(); return PrivacyManager.getRestrictionExtra(this, uid, mRestrictionName, methodName, extra, mSecret); } protected boolean isRestrictedExtra(XParam param, String restrictionName, String methodName, String extra) throws Throwable { int uid = Binder.getCallingUid(); return PrivacyManager.getRestrictionExtra(this, uid, restrictionName, methodName, extra, mSecret); } protected boolean isRestrictedExtra(int uid, String restrictionName, String methodName, String extra) throws Throwable { return PrivacyManager.getRestrictionExtra(this, uid, restrictionName, methodName, extra, mSecret); } protected boolean isRestrictedValue(int uid, String value) throws Throwable { return PrivacyManager.getRestrictionExtra(this, uid, mRestrictionName, getSpecifier(), null, value, mSecret); } protected boolean isRestrictedValue(XParam param, String value) throws Throwable { int uid = Binder.getCallingUid(); return PrivacyManager.getRestrictionExtra(this, uid, mRestrictionName, getSpecifier(), null, value, mSecret); } protected boolean isRestrictedValue(int uid, String methodName, String value) throws Throwable { return PrivacyManager.getRestrictionExtra(this, uid, mRestrictionName, methodName, null, value, mSecret); } protected boolean isRestrictedValue(int uid, String restrictionName, String methodName, String value) throws Throwable { return PrivacyManager.getRestrictionExtra(this, uid, restrictionName, methodName, null, value, mSecret); } protected boolean isRestrictedExtraValue(int uid, String restrictionName, String methodName, String extra, String value) throws Throwable { return PrivacyManager.getRestrictionExtra(this, uid, restrictionName, methodName, extra, value, mSecret); } protected boolean isRestricted(XParam param, String methodName) throws Throwable { int uid = Binder.getCallingUid(); return PrivacyManager.getRestriction(this, uid, mRestrictionName, methodName, mSecret); } protected boolean isRestricted(XParam param, String restrictionName, String methodName) throws Throwable { int uid = Binder.getCallingUid(); return PrivacyManager.getRestriction(this, uid, restrictionName, methodName, mSecret); } protected boolean getRestricted(int uid) throws Throwable { return PrivacyManager.getRestriction(this, uid, mRestrictionName, getSpecifier(), mSecret); } protected boolean getRestricted(int uid, String methodName) throws Throwable { return PrivacyManager.getRestriction(this, uid, mRestrictionName, methodName, mSecret); } protected boolean getRestricted(int uid, String restrictionName, String methodName) throws Throwable { return PrivacyManager.getRestriction(this, uid, restrictionName, methodName, mSecret); } @Override @SuppressLint("FieldGetter") public String toString() { return getRestrictionName() + "/" + getSpecifier() + " (" + getClassName() + ")"; } }
4,344
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
Util.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/Util.java
package biz.bokhorst.xprivacy; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.StackOverflowError; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.lang.RuntimeException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.nio.channels.FileChannel; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.HttpHostConnectException; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Process; import android.os.RemoteException; import android.os.TransactionTooLargeException; import android.os.UserHandle; import android.util.Base64; import android.util.DisplayMetrics; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; @SuppressWarnings("deprecation") public class Util { private static boolean mPro = false; private static boolean mLog = true; private static boolean mLogDetermined = false; private static Boolean mHasLBE = null; private static Version MIN_PRO_VERSION = new Version("1.20"); private static String LICENSE_FILE_NAME = "XPrivacy_license.txt"; public static int NOTIFY_RESTART = 0; public static int NOTIFY_NOTXPOSED = 1; public static int NOTIFY_SERVICE = 2; public static int NOTIFY_MIGRATE = 3; public static int NOTIFY_RANDOMIZE = 4; public static int NOTIFY_UPGRADE = 5; public static int NOTIFY_UPDATE = 6; public static int NOTIFY_CORRUPT = 7; public static void log(XHook hook, int priority, String msg) { // Check if logging enabled int uid = Process.myUid(); if (!mLogDetermined && uid > 0) { mLogDetermined = true; try { mLog = PrivacyManager.getSettingBool(0, PrivacyManager.cSettingLog, false); } catch (Throwable ignored) { mLog = false; } } // Log if enabled if (priority != Log.DEBUG && (priority == Log.INFO ? mLog : true)) if (hook == null) Log.println(priority, "XPrivacy", msg); else Log.println(priority, String.format("XPrivacy/%s", hook.getClass().getSimpleName()), msg); // Report to service if (uid > 0 && priority == Log.ERROR) if (PrivacyService.isRegistered()) PrivacyService.reportErrorInternal(msg); else try { IPrivacyService client = PrivacyService.getClient(); if (client != null) client.reportError(msg); } catch (RemoteException ignored) { } } public static void bug(XHook hook, Throwable ex) { if (ex instanceof InvocationTargetException) { InvocationTargetException exex = (InvocationTargetException) ex; if (exex.getTargetException() != null) ex = exex.getTargetException(); } int priority; if (ex instanceof ActivityShare.AbortException) priority = Log.WARN; else if (ex instanceof ActivityShare.ServerException) priority = Log.WARN; else if (ex instanceof ConnectTimeoutException) priority = Log.WARN; else if (ex instanceof FileNotFoundException) priority = Log.WARN; else if (ex instanceof HttpHostConnectException) priority = Log.WARN; else if (ex instanceof NameNotFoundException) priority = Log.WARN; else if (ex instanceof NoClassDefFoundError) priority = Log.WARN; else if (ex instanceof OutOfMemoryError) priority = Log.WARN; else if (ex instanceof RuntimeException) priority = Log.WARN; else if (ex instanceof SecurityException) priority = Log.WARN; else if (ex instanceof SocketTimeoutException) priority = Log.WARN; else if (ex instanceof SSLPeerUnverifiedException) priority = Log.WARN; else if (ex instanceof StackOverflowError) priority = Log.WARN; else if (ex instanceof TransactionTooLargeException) priority = Log.WARN; else if (ex instanceof UnknownHostException) priority = Log.WARN; else if (ex instanceof UnsatisfiedLinkError) priority = Log.WARN; else priority = Log.ERROR; boolean xprivacy = false; for (StackTraceElement frame : ex.getStackTrace()) if (frame.getClassName() != null && frame.getClassName().startsWith("biz.bokhorst.xprivacy")) { xprivacy = true; break; } if (!xprivacy) priority = Log.WARN; log(hook, priority, ex.toString() + " uid=" + Process.myUid() + "\n" + Log.getStackTraceString(ex)); } public static void logStack(XHook hook, int priority) { logStack(hook, priority, false); } public static void logStack(XHook hook, int priority, boolean cl) { StringBuilder trace = new StringBuilder(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); for (StackTraceElement ste : Thread.currentThread().getStackTrace()) { trace.append(ste.toString()); if (cl) try { Class<?> clazz = Class.forName(ste.getClassName(), false, loader); trace.append(" ["); trace.append(clazz.getClassLoader().toString()); trace.append("]"); } catch (ClassNotFoundException ignored) { } trace.append("\n"); } log(hook, priority, trace.toString()); } public static boolean isXposedEnabled() { // Will be hooked to return true log(null, Log.WARN, "XPrivacy not enabled"); return false; } public static void setPro(boolean enabled) { mPro = enabled; } public static boolean isProEnabled() { return mPro; } public static String hasProLicense(Context context) { try { // Get license String[] license = getProLicenseUnchecked(); if (license == null) return null; String name = license[0]; String email = license[1]; String signature = license[2]; // Get bytes byte[] bEmail = email.getBytes("UTF-8"); byte[] bSignature = hex2bytes(signature); if (bEmail.length == 0 || bSignature.length == 0) { Util.log(null, Log.ERROR, "Licensing: invalid file"); return null; } // Verify license boolean licensed = verifyData(bEmail, bSignature, getPublicKey(context)); if (licensed) Util.log(null, Log.INFO, "Licensing: ok"); else Util.log(null, Log.ERROR, "Licensing: invalid"); // Return result if (licensed) return name; } catch (Throwable ex) { Util.bug(null, ex); } return null; } @SuppressLint("NewApi") public static int getAppId(int uid) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) try { // UserHandle: public static final int getAppId(int uid) Method method = (Method) UserHandle.class.getDeclaredMethod("getAppId", int.class); uid = (Integer) method.invoke(null, uid); } catch (Throwable ex) { Util.log(null, Log.WARN, ex.toString()); } return uid; } @SuppressLint("NewApi") public static int getUserId(int uid) { int userId = 0; if (uid > 99) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) try { // UserHandle: public static final int getUserId(int uid) Method method = (Method) UserHandle.class.getDeclaredMethod("getUserId", int.class); userId = (Integer) method.invoke(null, uid); } catch (Throwable ex) { Util.log(null, Log.WARN, ex.toString()); } } else userId = uid; return userId; } public static String getUserDataDirectory(int uid) { // Build data directory String dataDir = Environment.getDataDirectory() + File.separator; int userId = getUserId(uid); if (userId == 0) dataDir += "data"; else dataDir += "user" + File.separator + userId; dataDir += File.separator + Util.class.getPackage().getName(); return dataDir; } public static String[] getProLicenseUnchecked() { // Get license file name String storageDir = Environment.getExternalStorageDirectory().getAbsolutePath(); File licenseFile = new File(storageDir + File.separator + LICENSE_FILE_NAME); if (!licenseFile.exists()) licenseFile = new File(storageDir + File.separator + ".xprivacy" + File.separator + LICENSE_FILE_NAME); if (!licenseFile.exists()) licenseFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + LICENSE_FILE_NAME); String importedLicense = importProLicense(licenseFile); if (importedLicense == null) return null; // Check license file licenseFile = new File(importedLicense); if (licenseFile.exists()) { // Read license try { IniFile iniFile = new IniFile(licenseFile); String name = iniFile.get("name", ""); String email = iniFile.get("email", ""); String signature = iniFile.get("signature", ""); if (name == null || email == null || signature == null) return null; else { // Check expiry if (email.endsWith("@faircode.eu")) { long expiry = Long.parseLong(email.split("\\.")[0]); long time = System.currentTimeMillis() / 1000L; if (time > expiry) { Util.log(null, Log.WARN, "Licensing: expired"); return null; } } // Valid return new String[] { name, email, signature }; } } catch (FileNotFoundException ex) { return null; } catch (Throwable ex) { bug(null, ex); return null; } } else Util.log(null, Log.INFO, "Licensing: no license file"); return null; } public static String importProLicense(File licenseFile) { // Get imported license file name String importedLicense = getUserDataDirectory(Process.myUid()) + File.separator + LICENSE_FILE_NAME; File out = new File(importedLicense); // Check if license file exists if (licenseFile.exists() && licenseFile.canRead()) { try { // Import license file Util.log(null, Log.WARN, "Licensing: importing " + out.getAbsolutePath()); InputStream is = null; is = new FileInputStream(licenseFile.getAbsolutePath()); try { OutputStream os = null; try { os = new FileOutputStream(out.getAbsolutePath()); byte[] buffer = new byte[1024]; int read; while ((read = is.read(buffer)) != -1) os.write(buffer, 0, read); os.flush(); } finally { if (os != null) os.close(); } } finally { if (is != null) is.close(); } // Protect imported license file setPermissions(out.getAbsolutePath(), 0700, Process.myUid(), Process.myUid()); // Remove original license file licenseFile.delete(); } catch (FileNotFoundException ignored) { } catch (Throwable ex) { Util.bug(null, ex); } } return (out.exists() && out.canRead() ? importedLicense : null); } public static Version getProEnablerVersion(Context context) { try { String proPackageName = context.getPackageName() + ".pro"; PackageManager pm = context.getPackageManager(); PackageInfo pi = pm.getPackageInfo(proPackageName, 0); return new Version(pi.versionName); } catch (NameNotFoundException ignored) { } catch (Throwable ex) { Util.bug(null, ex); } return null; } public static boolean isValidProEnablerVersion(Version version) { return (version.compareTo(MIN_PRO_VERSION) >= 0); } private static boolean hasValidProEnablerSignature(Context context) { return (context.getPackageManager() .checkSignatures(context.getPackageName(), context.getPackageName() + ".pro") == PackageManager.SIGNATURE_MATCH); } public static boolean isProEnablerInstalled(Context context) { Version version = getProEnablerVersion(context); if (version != null && isValidProEnablerVersion(version) && hasValidProEnablerSignature(context)) { Util.log(null, Log.INFO, "Licensing: enabler installed"); return true; } Util.log(null, Log.INFO, "Licensing: enabler not installed"); return false; } public static boolean hasMarketLink(Context context, String packageName) { try { PackageManager pm = context.getPackageManager(); String installer = pm.getInstallerPackageName(packageName); if (installer != null) return installer.equals("com.android.vending") || installer.contains("google"); } catch (Exception ex) { log(null, Log.WARN, ex.toString()); } return false; } public static void viewUri(Context context, Uri uri) { Intent infoIntent = new Intent(Intent.ACTION_VIEW); infoIntent.setData(uri); if (isIntentAvailable(context, infoIntent)) context.startActivity(infoIntent); else Toast.makeText(context, "View action not available", Toast.LENGTH_LONG).show(); } public static boolean hasLBE() { if (mHasLBE == null) { mHasLBE = false; try { File apps = new File(Environment.getDataDirectory() + File.separator + "app"); File[] files = (apps == null ? null : apps.listFiles()); if (files != null) for (File file : files) if (file.getName().startsWith("com.lbe.security")) { mHasLBE = true; break; } } catch (Throwable ex) { Util.bug(null, ex); } } return mHasLBE; } public static boolean isSELinuxEnforced() { try { Class<?> cSELinux = Class.forName("android.os.SELinux"); if ((Boolean) cSELinux.getDeclaredMethod("isSELinuxEnabled").invoke(null)) if ((Boolean) cSELinux.getDeclaredMethod("isSELinuxEnforced").invoke(null)) return true; } catch (Throwable t) { } return false; } public static String getXOption(String name) { try { Class<?> cSystemProperties = Class.forName("android.os.SystemProperties"); Method spGet = cSystemProperties.getDeclaredMethod("get", String.class); String options = (String) spGet.invoke(null, "xprivacy.options"); Log.w("XPrivacy", "Options=" + options); if (options != null) for (String option : options.split(",")) { String[] nv = option.split("="); if (nv[0].equals(name)) if (nv.length > 1) return nv[1]; else return "true"; } } catch (Throwable ex) { Log.e("XPrivacy", ex.toString() + "\n" + Log.getStackTraceString(ex)); } return null; } public static int getSelfVersionCode(Context context) { try { String self = Util.class.getPackage().getName(); PackageManager pm = context.getPackageManager(); PackageInfo pInfo = pm.getPackageInfo(self, 0); return pInfo.versionCode; } catch (NameNotFoundException ex) { Util.bug(null, ex); return 0; } } public static String getSelfVersionName(Context context) { try { String self = Util.class.getPackage().getName(); PackageManager pm = context.getPackageManager(); PackageInfo pInfo = pm.getPackageInfo(self, 0); return pInfo.versionName; } catch (NameNotFoundException ex) { Util.bug(null, ex); return null; } } private static byte[] hex2bytes(String hex) { // Convert hex string to byte array int len = hex.length(); byte[] result = new byte[len / 2]; for (int i = 0; i < len; i += 2) result[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16)); return result; } private static PublicKey getPublicKey(Context context) throws Throwable { // Read public key String sPublicKey = ""; InputStreamReader isr = new InputStreamReader(context.getAssets().open("XPrivacy_public_key.txt"), "UTF-8"); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); while (line != null) { if (!line.startsWith("-----")) sPublicKey += line; line = br.readLine(); } br.close(); isr.close(); // Create public key byte[] bPublicKey = Base64.decode(sPublicKey, Base64.NO_WRAP); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec encodedPubKeySpec = new X509EncodedKeySpec(bPublicKey); return keyFactory.generatePublic(encodedPubKeySpec); } private static boolean verifyData(byte[] data, byte[] signature, PublicKey publicKey) throws Throwable { // Verify signature Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(publicKey); verifier.update(data); return verifier.verify(signature); } public static String sha1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { // SHA1 int userId = Util.getUserId(Process.myUid()); String salt = PrivacyManager.getSalt(userId); MessageDigest digest = MessageDigest.getInstance("SHA-1"); byte[] bytes = (text + salt).getBytes("UTF-8"); digest.update(bytes, 0, bytes.length); bytes = digest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bytes) sb.append(String.format("%02X", b)); return sb.toString(); } public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { // MD5 int userId = Util.getUserId(Process.myUid()); String salt = PrivacyManager.getSalt(userId); byte[] bytes = MessageDigest.getInstance("MD5").digest((text + salt).getBytes("UTF-8")); StringBuilder sb = new StringBuilder(); for (byte b : bytes) sb.append(String.format("%02X", b)); return sb.toString(); } @SuppressLint("DefaultLocale") public static boolean hasValidFingerPrint(Context context) { try { PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES); byte[] cert = packageInfo.signatures[0].toByteArray(); MessageDigest digest = MessageDigest.getInstance("SHA1"); byte[] bytes = digest.digest(cert); StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; ++i) sb.append((Integer.toHexString((bytes[i] & 0xFF) | 0x100)).substring(1, 3).toLowerCase()); String calculated = sb.toString(); String expected = context.getString(R.string.fingerprint); return calculated.equals(expected); } catch (Throwable ex) { bug(null, ex); return false; } } public static boolean isDebuggable(Context context) { return ((context.getApplicationContext().getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); } public static boolean isIntentAvailable(Context context, Intent intent) { PackageManager packageManager = context.getPackageManager(); return (packageManager.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES).size() > 0); } public static void setPermissions(String path, int mode, int uid, int gid) { try { // frameworks/base/core/java/android/os/FileUtils.java Class<?> fileUtils = Class.forName("android.os.FileUtils"); Method setPermissions = fileUtils .getMethod("setPermissions", String.class, int.class, int.class, int.class); setPermissions.invoke(null, path, mode, uid, gid); Util.log(null, Log.WARN, "Changed permission path=" + path + " mode=" + Integer.toOctalString(mode) + " uid=" + uid + " gid=" + gid); } catch (Throwable ex) { Util.bug(null, ex); } } public static void copy(File src, File dst) throws IOException { FileInputStream inStream = null; try { inStream = new FileInputStream(src); FileOutputStream outStream = null; try { outStream = new FileOutputStream(dst); FileChannel inChannel = inStream.getChannel(); FileChannel outChannel = outStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (outStream != null) outStream.close(); } } finally { if (inStream != null) inStream.close(); } } public static boolean move(File src, File dst) { try { copy(src, dst); } catch (IOException ex) { Util.bug(null, ex); return false; } return src.delete(); } public static List<View> getViewsByTag(ViewGroup root, String tag) { List<View> views = new ArrayList<View>(); for (int i = 0; i < root.getChildCount(); i++) { View child = root.getChildAt(i); if (child instanceof ViewGroup) views.addAll(getViewsByTag((ViewGroup) child, tag)); if (tag.equals(child.getTag())) views.add(child); } return views; } public static float dipToPixels(Context context, float dipValue) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics); } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) inSampleSize *= 2; } return inSampleSize; } public static String getSEContext() { try { Class<?> cSELinux = Class.forName("android.os.SELinux"); Method mGetContext = cSELinux.getDeclaredMethod("getContext"); return (String) mGetContext.invoke(null); } catch (Throwable ex) { Util.bug(null, ex); return null; } } }
21,509
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
BootReceiver.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/BootReceiver.java
package biz.bokhorst.xprivacy; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent bootIntent) { // Start boot update Intent changeIntent = new Intent(); changeIntent.setClass(context, UpdateService.class); changeIntent.putExtra(UpdateService.cAction, UpdateService.cActionBoot); context.startService(changeIntent); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); // Check if Xposed enabled if (Util.isXposedEnabled() && PrivacyService.checkClient()) try { if (PrivacyService.getClient().databaseCorrupt()) { // Build notification NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context); notificationBuilder.setSmallIcon(R.drawable.ic_launcher); notificationBuilder.setContentTitle(context.getString(R.string.app_name)); notificationBuilder.setContentText(context.getString(R.string.msg_corrupt)); notificationBuilder.setWhen(System.currentTimeMillis()); notificationBuilder.setAutoCancel(true); Notification notification = notificationBuilder.build(); // Display notification notificationManager.notify(Util.NOTIFY_CORRUPT, notification); } else context.sendBroadcast(new Intent("biz.bokhorst.xprivacy.action.ACTIVE")); } catch (Throwable ex) { Util.bug(null, ex); } else { // Create Xposed installer intent // @formatter:off Intent xInstallerIntent = new Intent("de.robv.android.xposed.installer.OPEN_SECTION") .setPackage("de.robv.android.xposed.installer") .putExtra("section", "modules") .putExtra("module", context.getPackageName()) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // @formatter:on PendingIntent pi = (xInstallerIntent == null ? null : PendingIntent.getActivity(context, 0, xInstallerIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // Build notification NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context); notificationBuilder.setSmallIcon(R.drawable.ic_launcher); notificationBuilder.setContentTitle(context.getString(R.string.app_name)); notificationBuilder.setContentText(context.getString(R.string.app_notenabled)); notificationBuilder.setWhen(System.currentTimeMillis()); notificationBuilder.setAutoCancel(true); if (pi != null) notificationBuilder.setContentIntent(pi); Notification notification = notificationBuilder.build(); // Display notification notificationManager.notify(Util.NOTIFY_NOTXPOSED, notification); } } }
2,895
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
ApplicationEx.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/ApplicationEx.java
package biz.bokhorst.xprivacy; import android.app.Application; import android.util.Log; public class ApplicationEx extends Application { private Thread.UncaughtExceptionHandler mPrevHandler; @Override public void onCreate() { super.onCreate(); Util.log(null, Log.WARN, "UI started"); mPrevHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { Util.bug(null, ex); if (mPrevHandler != null) mPrevHandler.uncaughtException(thread, ex); } }); } public void onDestroy() { Util.log(null, Log.WARN, "UI stopped"); } }
710
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
PSetting.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/PSetting.java
package biz.bokhorst.xprivacy; import android.os.Parcel; import android.os.Parcelable; public class PSetting implements Parcelable { public int uid; public String type; public String name; public String value; public PSetting() { } public PSetting(PSetting other) { uid = other.uid; type = other.type; name = other.name; value = other.value; } public PSetting(int _uid, String _type, String _name, String _value) { uid = _uid; type = _type; name = _name; value = _value; } public static final Parcelable.Creator<PSetting> CREATOR = new Parcelable.Creator<PSetting>() { public PSetting createFromParcel(Parcel in) { return new PSetting(in); } public PSetting[] newArray(int size) { return new PSetting[size]; } }; private PSetting(Parcel in) { readFromParcel(in); } @Override public void writeToParcel(Parcel out, int flags) { out.writeInt(uid); out.writeInt(type == null ? 1 : 0); if (type != null) out.writeString(type); out.writeInt(name == null ? 1 : 0); if (name != null) out.writeString(name); out.writeInt(value == null ? 1 : 0); if (value != null) out.writeString(value); } public void readFromParcel(Parcel in) { uid = in.readInt(); type = (in.readInt() > 0 ? null : in.readString()); name = (in.readInt() > 0 ? null : in.readString()); value = (in.readInt() > 0 ? null : in.readString()); } @Override public int describeContents() { return 0; } @Override public String toString() { return "uid=" + uid + " " + type + "/" + name + "=" + (value == null ? "null" : value); } }
1,587
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XMediaRecorder.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XMediaRecorder.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; public class XMediaRecorder extends XHook { private Methods mMethod; private XMediaRecorder(Methods method, String restrictionName) { super(restrictionName, method.name(), "MediaRecorder." + method.name()); mMethod = method; } public String getClassName() { return "android.media.MediaRecorder"; } // void setOutputFile(FileDescriptor fd) // void setOutputFile(String path) // public prepare() // public native void start() // void stop() // frameworks/base/media/java/android/media/MediaRecorder.java // http://developer.android.com/reference/android/media/MediaRecorder.html private enum Methods { setOutputFile, prepare, start, stop }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XMediaRecorder(Methods.setOutputFile, PrivacyManager.cMedia)); listHook.add(new XMediaRecorder(Methods.prepare, null)); listHook.add(new XMediaRecorder(Methods.start, PrivacyManager.cMedia)); listHook.add(new XMediaRecorder(Methods.stop, null)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case setOutputFile: case start: if (isRestricted(param)) param.setResult(null); break; case prepare: case stop: if (isRestricted(param, PrivacyManager.cMedia, "MediaRecorder.start")) param.setResult(null); break; } } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
1,562
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
IniFile.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/IniFile.java
package biz.bokhorst.xprivacy; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IniFile { private Map<String, String> mIni = new HashMap<String, String>(); public IniFile(File file) throws IOException { String line; Pattern pattern = Pattern.compile("\\s*([^=]*)=(.*)"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); while ((line = br.readLine()) != null) if (!line.startsWith("#")) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { String key = matcher.group(1).trim(); String value = matcher.group(2).trim(); mIni.put(key, value); } } br.close(); fr.close(); } public String get(String key, String defaultvalue) { return mIni.get(key); } }
937
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XClipboardManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XClipboardManager.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Build; public class XClipboardManager extends XHook { private Methods mMethod; private String mClassName; private static final String cClassName = "android.content.ClipboardManager"; private XClipboardManager(Methods method, String restrictionName) { super(restrictionName, method.name().replace("Srv_", ""), method.name()); mMethod = method; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) mClassName = "com.android.server.clipboard.ClipboardService"; else mClassName = "com.android.server.ClipboardService"; } private XClipboardManager(Methods method, String restrictionName, String className) { super(restrictionName, method.name(), null); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // public void addPrimaryClipChangedListener(OnPrimaryClipChangedListener what) // public ClipData getPrimaryClip() // public ClipDescription getPrimaryClipDescription() // public CharSequence getText() // public boolean hasPrimaryClip() // public boolean hasText() // public void removePrimaryClipChangedListener(ClipboardManager.OnPrimaryClipChangedListener what) // frameworks/base/core/java/android/content/ClipboardManager.java // http://developer.android.com/reference/android/content/ClipboardManager.html // @formatter:on // @formatter:off private enum Methods { addPrimaryClipChangedListener, getPrimaryClip, getPrimaryClipDescription, getText, hasPrimaryClip, hasText, removePrimaryClipChangedListener, Srv_addPrimaryClipChangedListener, Srv_getPrimaryClip, Srv_getPrimaryClipDescription, Srv_hasClipboardText, Srv_hasPrimaryClip, Srv_removePrimaryClipChangedListener }; // @formatter:on public static List<XHook> getInstances(String className, boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (!cClassName.equals(className)) { if (className == null) className = cClassName; for (Methods clip : Methods.values()) if (clip.name().startsWith("Srv_")) { if (server) if (clip == Methods.Srv_removePrimaryClipChangedListener) listHook.add(new XClipboardManager(clip, null)); else listHook.add(new XClipboardManager(clip, PrivacyManager.cClipboard)); } else if (!server) { if (clip == Methods.removePrimaryClipChangedListener) listHook.add(new XClipboardManager(clip, null, className)); else listHook.add(new XClipboardManager(clip, PrivacyManager.cClipboard, className)); } } return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case addPrimaryClipChangedListener: case Srv_addPrimaryClipChangedListener: if (isRestricted(param)) param.setResult(null); break; case getPrimaryClip: case getPrimaryClipDescription: case getText: case hasPrimaryClip: case hasText: break; case removePrimaryClipChangedListener: if (isRestricted(param, PrivacyManager.cClipboard, "addPrimaryClipChangedListener")) param.setResult(null); break; case Srv_removePrimaryClipChangedListener: if (isRestricted(param, PrivacyManager.cClipboard, "Srv_addPrimaryClipChangedListener")) param.setResult(null); break; case Srv_getPrimaryClip: case Srv_getPrimaryClipDescription: case Srv_hasClipboardText: case Srv_hasPrimaryClip: break; } } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case addPrimaryClipChangedListener: case removePrimaryClipChangedListener: case Srv_addPrimaryClipChangedListener: case Srv_removePrimaryClipChangedListener: break; case getPrimaryClip: case getPrimaryClipDescription: case getText: case Srv_getPrimaryClip: case Srv_getPrimaryClipDescription: if (param.getResult() != null) if (isRestricted(param)) param.setResult(null); break; case hasPrimaryClip: case hasText: case Srv_hasClipboardText: case Srv_hasPrimaryClip: if (param.getResult() instanceof Boolean) if (isRestricted(param)) param.setResult(false); break; } } }
4,218
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XWebView.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XWebView.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.os.Binder; import android.webkit.WebView; public class XWebView extends XHook { private Methods mMethod; private XWebView(Methods method, String restrictionName) { super(restrictionName, (method == Methods.WebView ? null : method.name()), (method == Methods.WebView ? method .name() : null)); mMethod = method; } public String getClassName() { return "android.webkit.WebView"; } // @formatter:off // public WebView(Context context) // public WebView(Context context, AttributeSet attrs) // public WebView(Context context, AttributeSet attrs, int defStyle) // public WebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) // public WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) // protected WebView(Context context, AttributeSet attrs, int defStyle, Map<String, Object> javaScriptInterfaces, boolean privateBrowsing) // public WebSettings getSettings() // public void loadUrl(String url) // public void loadUrl(String url, Map<String, String> additionalHttpHeaders) // public postUrl(String url, byte[] postData) // http://developer.android.com/reference/android/webkit/WebView.html // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/android/webkit/WebView.java/ // @formatter:on private enum Methods { WebView, loadUrl, postUrl, getSettings }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XWebView(Methods.WebView, null)); listHook.add(new XWebView(Methods.loadUrl, PrivacyManager.cView)); listHook.add(new XWebView(Methods.postUrl, PrivacyManager.cView)); listHook.add(new XWebView(Methods.getSettings, null)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case WebView: case getSettings: // Do nothing break; case loadUrl: case postUrl: if (param.args.length > 0 && param.thisObject instanceof WebView) { String extra = (param.args[0] instanceof String ? (String) param.args[0] : null); if (isRestrictedExtra(param, extra)) param.setResult(null); } break; } } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case WebView: if (param.args.length > 0 && param.thisObject instanceof WebView) { if (isRestricted(param, PrivacyManager.cView, "initUserAgentString")) { String ua = (String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "UA"); WebView webView = (WebView) param.thisObject; if (webView.getSettings() != null) webView.getSettings().setUserAgentString(ua); } } break; case loadUrl: case postUrl: // Do nothing break; case getSettings: if (param.getResult() != null) { Class<?> clazz = param.getResult().getClass(); if (PrivacyManager.getTransient(clazz.getName(), null) == null) { PrivacyManager.setTransient(clazz.getName(), Boolean.toString(true)); XPrivacy.hookAll(XWebSettings.getInstances(param.getResult()), clazz.getClassLoader(), getSecret(), true); } } break; } } }
3,254
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
ApplicationInfoEx.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/ApplicationInfoEx.java
package biz.bokhorst.xprivacy; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; @SuppressLint("DefaultLocale") public class ApplicationInfoEx implements Comparable<ApplicationInfoEx> { private int mUid; private TreeMap<String, ApplicationInfo> mMapAppInfo = null; private Map<String, PackageInfo> mMapPkgInfo = new HashMap<String, PackageInfo>(); // Cache private Boolean mInternet = null; private Boolean mFrozen = null; private long mInstallTime = -1; private long mUpdateTime = -1; public static final int STATE_ATTENTION = 0; public static final int STATE_CHANGED = 1; public static final int STATE_SHARED = 2; public ApplicationInfoEx(Context context, int uid) { mUid = uid; mMapAppInfo = new TreeMap<String, ApplicationInfo>(); PackageManager pm = context.getPackageManager(); String[] packages = pm.getPackagesForUid(uid); if (packages != null) for (String packageName : packages) try { ApplicationInfo appInfo = pm.getApplicationInfo(packageName, 0); mMapAppInfo.put(pm.getApplicationLabel(appInfo).toString(), appInfo); } catch (NameNotFoundException ignored) { } } public static List<ApplicationInfoEx> getXApplicationList(Context context, ProgressDialog dialog) { // Get references PackageManager pm = context.getPackageManager(); // Get app list SparseArray<ApplicationInfoEx> mapApp = new SparseArray<ApplicationInfoEx>(); List<ApplicationInfoEx> listApp = new ArrayList<ApplicationInfoEx>(); List<ApplicationInfo> listAppInfo = pm.getInstalledApplications(PackageManager.GET_META_DATA); if (dialog != null) dialog.setMax(listAppInfo.size()); for (int app = 0; app < listAppInfo.size(); app++) { if (dialog != null) dialog.setProgress(app + 1); ApplicationInfo appInfo = listAppInfo.get(app); Util.log(null, Log.INFO, "package=" + appInfo.packageName + " uid=" + appInfo.uid); ApplicationInfoEx appInfoEx = new ApplicationInfoEx(context, appInfo.uid); if (mapApp.get(appInfoEx.getUid()) == null) { mapApp.put(appInfoEx.getUid(), appInfoEx); listApp.add(appInfoEx); } } // Sort result Collections.sort(listApp); return listApp; } public ArrayList<String> getApplicationName() { return new ArrayList<String>(mMapAppInfo.navigableKeySet()); } public String getApplicationName(String packageName) { for (Entry<String, ApplicationInfo> entry : mMapAppInfo.entrySet()) if (entry.getValue().packageName.equals(packageName)) return entry.getKey(); return ""; } public List<String> getPackageName() { List<String> listPackageName = new ArrayList<String>(); for (ApplicationInfo appInfo : mMapAppInfo.values()) listPackageName.add(appInfo.packageName); return listPackageName; } private void getPackageInfo(Context context, String packageName) throws NameNotFoundException { PackageManager pm = context.getPackageManager(); mMapPkgInfo.put(packageName, pm.getPackageInfo(packageName, 0)); } public List<String> getPackageVersionName(Context context) { List<String> listVersionName = new ArrayList<String>(); for (String packageName : this.getPackageName()) try { getPackageInfo(context, packageName); String version = mMapPkgInfo.get(packageName).versionName; if (version == null) listVersionName.add("???"); else listVersionName.add(version); } catch (NameNotFoundException ex) { listVersionName.add(ex.getMessage()); } return listVersionName; } public String getPackageVersionName(Context context, String packageName) { try { getPackageInfo(context, packageName); String version = mMapPkgInfo.get(packageName).versionName; if (version == null) return "???"; else return version; } catch (NameNotFoundException ex) { return ex.getMessage(); } } public List<Integer> getPackageVersionCode(Context context) { List<Integer> listVersionCode = new ArrayList<Integer>(); for (String packageName : this.getPackageName()) try { getPackageInfo(context, packageName); listVersionCode.add(mMapPkgInfo.get(packageName).versionCode); } catch (NameNotFoundException ex) { listVersionCode.add(0); } return listVersionCode; } public Drawable getIcon(Context context) { // Pick first icon if (mMapAppInfo.size() > 0) return mMapAppInfo.firstEntry().getValue().loadIcon(context.getPackageManager()); else return new ColorDrawable(Color.TRANSPARENT); } public Bitmap getIconBitmap(Context context) { if (mMapAppInfo.size() > 0) { try { final ApplicationInfo appInfo = mMapAppInfo.firstEntry().getValue(); if (appInfo.icon == 0) appInfo.icon = android.R.drawable.sym_def_app_icon; final Resources resources = context.getPackageManager().getResourcesForApplication(appInfo); final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(resources, appInfo.icon, options); final int pixels = Math.round(Util.dipToPixels(context, 48)); options.inSampleSize = Util.calculateInSampleSize(options, pixels, pixels); options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(resources, appInfo.icon, options); } catch (NameNotFoundException ex) { Util.bug(null, ex); return null; } } else return null; } public boolean hasInternet(Context context) { if (mInternet == null) { mInternet = false; PackageManager pm = context.getPackageManager(); for (ApplicationInfo appInfo : mMapAppInfo.values()) if (pm.checkPermission("android.permission.INTERNET", appInfo.packageName) == PackageManager.PERMISSION_GRANTED) { mInternet = true; break; } } return mInternet; } public boolean isFrozen(Context context) { if (mFrozen == null) { PackageManager pm = context.getPackageManager(); boolean enabled = false; for (ApplicationInfo appInfo : mMapAppInfo.values()) try { int setting = pm.getApplicationEnabledSetting(appInfo.packageName); enabled = (enabled || setting == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT); enabled = (enabled || setting == PackageManager.COMPONENT_ENABLED_STATE_ENABLED); if (enabled) break; } catch (IllegalArgumentException ignored) { } mFrozen = !enabled; } return mFrozen; } public int getUid() { return mUid; } @SuppressLint("FieldGetter") public int getState(Context context) { return Integer.parseInt(PrivacyManager.getSetting(-getUid(), PrivacyManager.cSettingState, Integer.toString(STATE_CHANGED))); } public long getInstallTime(Context context) { if (mInstallTime == -1) { long now = System.currentTimeMillis(); mInstallTime = now; for (String packageName : this.getPackageName()) try { getPackageInfo(context, packageName); long time = mMapPkgInfo.get(packageName).firstInstallTime; if (time < mInstallTime) mInstallTime = time; } catch (NameNotFoundException ex) { } if (mInstallTime == now) // no install time, so assume it is old mInstallTime = 0; } return mInstallTime; } public long getUpdateTime(Context context) { if (mUpdateTime == -1) { mUpdateTime = 0; for (String packageName : this.getPackageName()) try { getPackageInfo(context, packageName); long time = mMapPkgInfo.get(packageName).lastUpdateTime; if (time > mUpdateTime) mUpdateTime = time; } catch (NameNotFoundException ex) { } } return mUpdateTime; } @SuppressLint("FieldGetter") public long getModificationTime(Context context) { return Long.parseLong(PrivacyManager.getSetting(-getUid(), PrivacyManager.cSettingModifyTime, "0")); } public boolean isSystem() { boolean mSystem = false; for (ApplicationInfo appInfo : mMapAppInfo.values()) { mSystem = ((appInfo.flags & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0); mSystem = mSystem || appInfo.packageName.equals(this.getClass().getPackage().getName()); mSystem = mSystem || appInfo.packageName.equals(this.getClass().getPackage().getName() + ".pro"); mSystem = mSystem || appInfo.packageName.equals("de.robv.android.xposed.installer"); } return mSystem; } public boolean isShared() { for (ApplicationInfo appInfo : mMapAppInfo.values()) if (PrivacyManager.isShared(appInfo.uid)) return true; return false; } public boolean isIsolated() { for (ApplicationInfo appInfo : mMapAppInfo.values()) if (PrivacyManager.isIsolated(appInfo.uid)) return true; return false; } @Override @SuppressLint("FieldGetter") public String toString() { return String.format("%d %s", getUid(), TextUtils.join(", ", getApplicationName())); } @Override public int compareTo(ApplicationInfoEx other) { // Locale respecting sorter Collator collator = Collator.getInstance(Locale.getDefault()); return collator.compare(TextUtils.join(", ", getApplicationName()), TextUtils.join(", ", other.getApplicationName())); } }
9,788
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
ActivityBase.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/ActivityBase.java
package biz.bokhorst.xprivacy; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.pm.PackageInfo; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Bitmap.Config; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Process; import android.support.v7.app.AppCompatActivity; import android.util.TypedValue; import android.view.View; import android.widget.TextView; @SuppressLint("Registered") public class ActivityBase extends AppCompatActivity { private int mThemeId; private Bitmap[] mCheck = null; @Override protected void onCreate(Bundle savedInstanceState) { if (PrivacyService.checkClient()) { // Set theme int userId = Util.getUserId(Process.myUid()); String themeName = PrivacyManager.getSetting(userId, PrivacyManager.cSettingTheme, ""); mThemeId = (themeName.equals("Dark") ? R.style.CustomTheme : R.style.CustomTheme_Light); setTheme(mThemeId); } super.onCreate(savedInstanceState); // Check if Privacy client available if (!PrivacyService.checkClient()) { setContentView(R.layout.reboot); try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); TextView tvVersion = (TextView) findViewById(R.id.tvVersion); tvVersion.setText(pInfo.versionName); } catch (Throwable ex) { Util.bug(null, ex); } // Show reason if (PrivacyService.getClient() == null) { ((TextView) findViewById(R.id.tvRebootClient)).setVisibility(View.VISIBLE); Requirements.checkCompatibility(this); } else { ((TextView) findViewById(R.id.tvRebootVersion)).setVisibility(View.VISIBLE); Requirements.check(this); } // Show if updating if (isUpdating()) ((TextView) findViewById(R.id.tvServiceUpdating)).setVisibility(View.VISIBLE); } } private boolean isUpdating() { ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) if (UpdateService.class.getName().equals(service.service.getClassName())) return true; return false; } protected Bitmap getOffCheckBox() { if (mCheck == null) buildCheckBoxes(); return mCheck[0]; } protected Bitmap getHalfCheckBox() { if (mCheck == null) buildCheckBoxes(); return mCheck[1]; } protected Bitmap getFullCheckBox() { if (mCheck == null) buildCheckBoxes(); return mCheck[2]; } protected Bitmap getOnDemandCheckBox() { if (mCheck == null) buildCheckBoxes(); return mCheck[3]; } protected Bitmap getCheckBoxImage(RState state, boolean expert) { if (state.partialRestricted) if (expert) return getHalfCheckBox(); else return getFullCheckBox(); else if (state.restricted) return getFullCheckBox(); else return getOffCheckBox(); } protected Bitmap getAskBoxImage(RState state, boolean expert) { if (state.partialAsk) if (expert) return getHalfCheckBox(); else return getOnDemandCheckBox(); else if (state.asked) return getOffCheckBox(); else return getOnDemandCheckBox(); } @SuppressWarnings("deprecation") private void buildCheckBoxes() { mCheck = new Bitmap[4]; int userId = Util.getUserId(Process.myUid()); String themeName = PrivacyManager.getSetting(userId, PrivacyManager.cSettingTheme, ""); int colorAccent = getResources().getColor( themeName.equals("Dark") ? R.color.color_accent_dark : R.color.color_accent_light); // Get off check box TypedArray ta2 = getTheme().obtainStyledAttributes(new int[] { android.R.attr.listChoiceIndicatorMultiple }); Drawable off = ta2.getDrawable(0); ta2.recycle(); off.setBounds(0, 0, off.getIntrinsicWidth(), off.getIntrinsicHeight()); // Get check mark Drawable checkmark = getResources().getDrawable(R.drawable.checkmark); checkmark.setBounds(0, 0, off.getIntrinsicWidth(), off.getIntrinsicHeight()); checkmark.setColorFilter(colorAccent, Mode.SRC_ATOP); // Get check mark outline Drawable checkmarkOutline = getResources().getDrawable(R.drawable.checkmark_outline); checkmarkOutline.setBounds(0, 0, off.getIntrinsicWidth(), off.getIntrinsicHeight()); // Create off check box mCheck[0] = Bitmap.createBitmap(off.getIntrinsicWidth(), off.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas0 = new Canvas(mCheck[0]); off.draw(canvas0); // Create half check box mCheck[1] = Bitmap.createBitmap(off.getIntrinsicWidth(), off.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas1 = new Canvas(mCheck[1]); off.draw(canvas1); Paint paint1 = new Paint(); paint1.setStyle(Paint.Style.FILL); paint1.setColor(colorAccent); float wborder = off.getIntrinsicWidth() / 3f; float hborder = off.getIntrinsicHeight() / 3f; canvas1.drawRect(wborder, hborder, off.getIntrinsicWidth() - wborder, off.getIntrinsicHeight() - hborder, paint1); // Create full check box mCheck[2] = Bitmap.createBitmap(off.getIntrinsicWidth(), off.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas2 = new Canvas(mCheck[2]); off.draw(canvas2); checkmark.draw(canvas2); checkmarkOutline.draw(canvas2); // Get question mark Drawable questionmark = getResources().getDrawable(R.drawable.ondemand); questionmark.setBounds(0, 0, off.getIntrinsicWidth(), off.getIntrinsicHeight()); questionmark.setColorFilter(colorAccent, Mode.SRC_ATOP); // Get question mark outline Drawable questionmarkOutline = getResources().getDrawable(R.drawable.questionmark_outline); questionmarkOutline.setBounds(0, 0, off.getIntrinsicWidth(), off.getIntrinsicHeight()); // Create question check box mCheck[3] = Bitmap.createBitmap(off.getIntrinsicWidth(), off.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas3 = new Canvas(mCheck[3]); off.draw(canvas3); questionmark.draw(canvas3); questionmarkOutline.draw(canvas3); } public int getThemed(int attr) { TypedValue tv = new TypedValue(); getTheme().resolveAttribute(attr, tv, true); return tv.resourceId; } }
6,217
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XWindowManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XWindowManager.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import android.util.Log; import android.view.View; import android.view.WindowManager; public class XWindowManager extends XHook { private Methods mMethod; private String mClassName; private static final String cClassName = "android.view.WindowManagerImpl"; private static final Map<View, WindowManager.LayoutParams> mViewParam = new WeakHashMap<View, WindowManager.LayoutParams>(); private XWindowManager(Methods method, String restrictionName, String className) { super(restrictionName, method.name(), null); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // public void addView(View view, ViewGroup.LayoutParams params) // public void removeView(View view) // public void updateViewLayout(View view, ViewGroup.LayoutParams params) // http://developer.android.com/reference/android/view/ViewManager.html // http://developer.android.com/reference/android/view/WindowManager.html // @formatter:on private enum Methods { addView, removeView, updateViewLayout }; public static List<XHook> getInstances(String className, boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (!cClassName.equals(className)) { if (className == null) className = cClassName; listHook.add(new XWindowManager(Methods.addView, PrivacyManager.cOverlay, className)); listHook.add(new XWindowManager(Methods.removeView, null, className)); listHook.add(new XWindowManager(Methods.updateViewLayout, null, className)); } return listHook; } @Override protected void before(XParam param) throws Throwable { if (mMethod == Methods.addView || mMethod == Methods.removeView || mMethod == Methods.updateViewLayout) { View view = (View) param.args[0]; if (view != null) { // Get params WindowManager.LayoutParams wmParams = null; synchronized (mViewParam) { if (param.args.length > 1) { wmParams = (WindowManager.LayoutParams) param.args[1]; if (wmParams != null) mViewParam.put(view, wmParams); } else if (mViewParam.containsKey(view)) wmParams = mViewParam.get(view); } // Check for system alert/overlay if (wmParams != null) if (wmParams.type == WindowManager.LayoutParams.TYPE_SYSTEM_ALERT || wmParams.type == WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY) if (mMethod == Methods.removeView || mMethod == Methods.updateViewLayout) { if (isRestricted(param, PrivacyManager.cOverlay, "addView")) param.setResult(null); } else if (isRestricted(param)) param.setResult(null); } } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
2,919
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XInetAddress.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XInetAddress.java
package biz.bokhorst.xprivacy; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; public class XInetAddress extends XHook { @SuppressWarnings("unused") private Methods mMethod; private XInetAddress(Methods method, String restrictionName, String specifier) { super(restrictionName, method.name(), "InetAddress." + method.name()); mMethod = method; } public String getClassName() { return "java.net.InetAddress"; } // public static InetAddress[] getAllByName(String host) // public static InetAddress[] getAllByNameOnNet(String host, int netId) // public static InetAddress getByAddress(byte[] ipAddress) // public static InetAddress getByAddress(String hostName, byte[] ipAddress) // public static InetAddress getByName(String host) // public static InetAddress getByNameOnNet(String host, int netId) // libcore/luni/src/main/java/java/net/InetAddress.java // http://developer.android.com/reference/java/net/InetAddress.html // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/android/net/Network.java private enum Methods { getAllByName, getAllByNameOnNet, getByAddress, getByName, getByNameOnNet }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); for (Methods addr : Methods.values()) listHook.add(new XInetAddress(addr, PrivacyManager.cInternet, null)); return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { Object result = param.getResult(); if (result != null) { // Get addresses InetAddress[] addresses; if (result instanceof InetAddress) addresses = new InetAddress[] { (InetAddress) result }; else if (result instanceof InetAddress[]) addresses = (InetAddress[]) result; else addresses = new InetAddress[0]; // Check if restricted boolean restrict = false; for (InetAddress address : addresses) if (!address.isLoopbackAddress()) { restrict = true; break; } // Restrict if (restrict) if (param.args.length > 0 && param.args[0] instanceof String) { if (isRestrictedExtra(param, (String) param.args[0])) param.setThrowable(new UnknownHostException("XPrivacy")); } else { if (isRestricted(param)) param.setThrowable(new UnknownHostException("XPrivacy")); } } } }
2,485
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
CRestriction.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/CRestriction.java
package biz.bokhorst.xprivacy; import java.util.Date; public class CRestriction { private long mExpiry; private int mUid; private String mRestrictionName; private String mMethodName; private String mExtra; public boolean restricted; public boolean asked; public CRestriction(int uid, String restrictionName, String methodName, String extra) { mExpiry = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; mUid = uid; mRestrictionName = restrictionName; mMethodName = methodName; mExtra = extra; restricted = false; asked = false; } public CRestriction(PRestriction restriction, String extra) { mExpiry = new Date().getTime() + PrivacyManager.cRestrictionCacheTimeoutMs; mUid = restriction.uid; mRestrictionName = restriction.restrictionName; mMethodName = restriction.methodName; mExtra = extra; restricted = restriction.restricted; asked = restriction.asked; } public void setExpiry(long time) { mExpiry = time; } public boolean isExpired() { return (new Date().getTime() > mExpiry); } public int getUid() { return mUid; } public void setMethodName(String methodName) { mMethodName = methodName; } public void setExtra(String extra) { mExtra = extra; } public boolean isSameMethod(PRestriction restriction) { // @formatter:off return (restriction.uid == mUid && restriction.restrictionName.equals(mRestrictionName) && (restriction.methodName == null || restriction.methodName.equals(mMethodName))); // @formatter:on } @Override public boolean equals(Object obj) { CRestriction other = (CRestriction) obj; // @formatter:off return (mUid == other.mUid && mRestrictionName.equals(other.mRestrictionName) && (mMethodName == null ? other.mMethodName == null : mMethodName.equals(other.mMethodName)) && (mExtra == null ? other.mExtra == null : mExtra.equals(other.mExtra))); // @formatter:on } @Override public int hashCode() { int hash = mUid; if (mRestrictionName != null) hash = hash ^ mRestrictionName.hashCode(); if (mMethodName != null) hash = hash ^ mMethodName.hashCode(); if (mExtra != null) hash = hash ^ mExtra.hashCode(); return hash; } @Override public String toString() { return mUid + ":" + mRestrictionName + "/" + mMethodName + "(" + mExtra + ")" + "=" + restricted + "/" + asked; } }
2,349
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XConnectivityManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XConnectivityManager.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.net.NetworkInfo; public class XConnectivityManager extends XHook { private Methods mMethod; private String mClassName; private static final String cClassName = "android.net.ConnectivityManager"; private XConnectivityManager(Methods method, String restrictionName, String className) { super(restrictionName, method.name(), "Connectivity." + method.name()); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // public NetworkInfo getActiveNetworkInfo() // public NetworkInfo[] getAllNetworkInfo() // public NetworkInfo getNetworkInfo(int networkType) // frameworks/base/core/java/android/net/ConnectivityManager.java // http://developer.android.com/reference/android/net/ConnectivityManager.html private enum Methods { getActiveNetworkInfo, getAllNetworkInfo, getNetworkInfo }; public static List<XHook> getInstances(String className, boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (!cClassName.equals(className)) { if (className == null) className = cClassName; for (Methods connmgr : Methods.values()) listHook.add(new XConnectivityManager(connmgr, PrivacyManager.cInternet, className)); } return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case getActiveNetworkInfo: case getNetworkInfo: if (param.getResult() != null && isRestricted(param)) param.setResult(null); break; case getAllNetworkInfo: if (param.getResult() != null && isRestricted(param)) param.setResult(new NetworkInfo[0]); break; } } }
1,795
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XLocationManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XLocationManager.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import android.app.PendingIntent; import android.location.Location; import android.os.Binder; import android.os.Bundle; import android.os.IInterface; import android.util.Log; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.LocationListener; public class XLocationManager extends XHook { private Methods mMethod; private String mClassName; private static final String cClassName = "android.location.LocationManager"; private static final Map<Object, Object> mMapProxy = new WeakHashMap<Object, Object>(); private XLocationManager(Methods method, String restrictionName, String className) { super(restrictionName, method.name().replace("Srv_", ""), method.name()); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // public void addGeofence(LocationRequest request, Geofence fence, PendingIntent intent) // public boolean addGpsStatusListener(GpsStatus.Listener listener) // public boolean addNmeaListener(GpsStatus.NmeaListener listener) // public void addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent) // public List<String> getAllProviders() // public String getBestProvider(Criteria criteria, boolean enabledOnly) // public GpsStatus getGpsStatus(GpsStatus status) // public Location getLastKnownLocation(String provider) // public List<String> getProviders(boolean enabledOnly) // public List<String> getProviders(Criteria criteria, boolean enabledOnly) // public boolean isProviderEnabled(String provider) // public void removeUpdates(LocationListener listener) // public void removeUpdates(PendingIntent intent) // public void requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener) // public void requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener, Looper looper) // public void requestLocationUpdates(long minTime, float minDistance, Criteria criteria, LocationListener listener, Looper looper) // public void requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent) // public void requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntent intent) // public void requestSingleUpdate(String provider, LocationListener listener, Looper looper) // public void requestSingleUpdate(Criteria criteria, LocationListener listener, Looper looper) // public void requestSingleUpdate(String provider, PendingIntent intent) // public void requestSingleUpdate(Criteria criteria, PendingIntent intent) // public boolean sendExtraCommand(String provider, String command, Bundle extras) // frameworks/base/location/java/android/location/LocationManager.java // http://developer.android.com/reference/android/location/LocationManager.html // public void requestLocationUpdates(LocationRequest request, ILocationListener listener, android.app.PendingIntent intent, java.lang.String packageName) // public void removeUpdates(ILocationListener listener, android.app.PendingIntent intent, java.lang.String packageName) // public void requestGeofence(LocationRequest request, Geofence geofence, android.app.PendingIntent intent, java.lang.String packageName) // public void removeGeofence(Geofence fence, android.app.PendingIntent intent, java.lang.String packageName) // public Location getLastLocation(LocationRequest request, java.lang.String packageName) // public boolean addGpsStatusListener(IGpsStatusListener listener, java.lang.String packageName) // public void removeGpsStatusListener(IGpsStatusListener listener) // public java.util.List<java.lang.String> getAllProviders() // public java.util.List<java.lang.String> getProviders(Criteria criteria, boolean enabledOnly) // public java.lang.String getBestProvider(Criteria criteria, boolean enabledOnly) // public boolean isProviderEnabled(java.lang.String provider) // public boolean sendExtraCommand(java.lang.String provider, java.lang.String command, android.os.Bundle extras) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.4_r1/com/android/server/LocationManagerService.java // public boolean addGpsMeasurementsListener(IGpsMeasurementsListener listener, String packageName) // public boolean addGpsNavigationMessageListener(IGpsNavigationMessageListener listener, String packageName) // public boolean removeGpsMeasurementsListener(IGpsMeasurementsListener listener) // public boolean removeGpsNavigationMessageListener(IGpsNavigationMessageListener listener) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/com/android/server/LocationManagerService.java // @formatter:on // @formatter:off private enum Methods { addGeofence, addGpsStatusListener, addNmeaListener, addProximityAlert, getAllProviders, getBestProvider, getProviders, isProviderEnabled, getGpsStatus, getLastKnownLocation, removeUpdates, requestLocationUpdates, requestSingleUpdate, sendExtraCommand, Srv_requestLocationUpdates, Srv_removeUpdates, Srv_requestGeofence, Srv_removeGeofence, Srv_getLastLocation, Srv_addGpsStatusListener, Srv_removeGpsStatusListener, Srv_getAllProviders, Srv_getProviders, Srv_getBestProvider, Srv_isProviderEnabled, Srv_sendExtraCommand, Srv_addGpsMeasurementsListener, Srv_addGpsNavigationMessageListener, Srv_removeGpsMeasurementsListener, Srv_removeGpsNavigationMessageListener }; // @formatter:on public static List<XHook> getInstances(String className, boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (!cClassName.equals(className)) { if (className == null) className = cClassName; for (Methods loc : Methods.values()) if (loc == Methods.removeUpdates) listHook.add(new XLocationManager(loc, null, className)); else if (loc.name().startsWith("Srv_remove")) { if (server) listHook.add(new XLocationManager(loc, null, "com.android.server.LocationManagerService")); } else if (loc.name().startsWith("Srv_")) { if (server) listHook.add(new XLocationManager(loc, PrivacyManager.cLocation, "com.android.server.LocationManagerService")); } else listHook.add(new XLocationManager(loc, PrivacyManager.cLocation, className)); } return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case addGeofence: case addProximityAlert: case Srv_requestGeofence: if (isRestricted(param)) param.setResult(null); break; case Srv_removeGeofence: if (isRestricted(param, PrivacyManager.cLocation, "Srv_requestGeofence")) param.setResult(null); break; case addGpsStatusListener: case addNmeaListener: case Srv_addGpsStatusListener: case Srv_addGpsMeasurementsListener: case Srv_addGpsNavigationMessageListener: if (isRestricted(param)) param.setResult(false); break; case Srv_removeGpsStatusListener: if (isRestricted(param, PrivacyManager.cLocation, "Srv_addGpsStatusListener")) param.setResult(null); break; case Srv_removeGpsMeasurementsListener: if (isRestricted(param, PrivacyManager.cLocation, "Srv_addGpsMeasurementsListener")) param.setResult(null); break; case Srv_removeGpsNavigationMessageListener: if (isRestricted(param, PrivacyManager.cLocation, "Srv_addGpsNavigationMessageListener")) param.setResult(null); break; case getAllProviders: case getBestProvider: case getGpsStatus: case getLastKnownLocation: case getProviders: case isProviderEnabled: case Srv_getAllProviders: case Srv_getProviders: case Srv_getBestProvider: case Srv_isProviderEnabled: case Srv_getLastLocation: // Do nothing break; case removeUpdates: if (isRestricted(param, PrivacyManager.cLocation, "requestLocationUpdates")) unproxyLocationListener(param, 0, true); break; case requestLocationUpdates: if (param.args.length > 0 && param.args[0] instanceof String) { if (isRestrictedExtra(param, (String) param.args[0])) proxyLocationListener(param, 3, LocationListener.class, true); } else { if (isRestricted(param)) proxyLocationListener(param, 3, LocationListener.class, true); } break; case Srv_removeUpdates: if (isRestricted(param, PrivacyManager.cLocation, "Srv_requestLocationUpdates")) if (param.args.length > 1) if (param.args[0] != null) // ILocationListener unproxyLocationListener(param, 0, false); else if (param.args[1] != null) // PendingIntent param.setResult(null); break; case Srv_requestLocationUpdates: if (isRestricted(param)) if (param.args.length > 2) if (param.args[1] != null) // ILocationListener proxyLocationListener(param, 1, Class.forName("android.location.ILocationListener"), false); else if (param.args[2] != null) // PendingIntent param.setResult(null); break; case requestSingleUpdate: if (param.args.length > 0 && param.args[0] instanceof String) { if (isRestrictedExtra(param, (String) param.args[0])) proxyLocationListener(param, 1, LocationListener.class, true); } else { if (isRestricted(param)) proxyLocationListener(param, 1, LocationListener.class, true); } break; case sendExtraCommand: case Srv_sendExtraCommand: // Do nothing break; } } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case addGeofence: case addNmeaListener: case addGpsStatusListener: case addProximityAlert: case Srv_requestGeofence: case Srv_addGpsStatusListener: case Srv_addGpsMeasurementsListener: case Srv_addGpsNavigationMessageListener: case Srv_removeGeofence: case Srv_removeGpsStatusListener: case Srv_removeGpsMeasurementsListener: case Srv_removeGpsNavigationMessageListener: // Do nothing break; case isProviderEnabled: case Srv_isProviderEnabled: if (param.args.length > 0) { String provider = (String) param.args[0]; if (isRestrictedExtra(param, provider)) param.setResult(false); } break; case getGpsStatus: if (param.getResult() instanceof GpsStatus) if (isRestricted(param)) { GpsStatus status = (GpsStatus) param.getResult(); // private GpsSatellite mSatellites[] try { Field mSatellites = status.getClass().getDeclaredField("mSatellites"); mSatellites.setAccessible(true); mSatellites.set(status, new GpsSatellite[0]); } catch (Throwable ex) { Util.bug(null, ex); } } break; case getProviders: case getAllProviders: case Srv_getAllProviders: case Srv_getProviders: if (isRestricted(param)) param.setResult(new ArrayList<String>()); break; case getBestProvider: case Srv_getBestProvider: if (param.getResult() != null) if (isRestricted(param)) param.setResult(null); break; case getLastKnownLocation: if (param.args.length > 0 && param.getResult() instanceof Location) { String provider = (String) param.args[0]; Location location = (Location) param.getResult(); if (isRestrictedExtra(param, provider)) param.setResult(PrivacyManager.getDefacedLocation(Binder.getCallingUid(), location)); } break; case Srv_getLastLocation: if (param.getResult() instanceof Location) { Location location = (Location) param.getResult(); if (isRestricted(param)) param.setResult(PrivacyManager.getDefacedLocation(Binder.getCallingUid(), location)); } break; case removeUpdates: case requestLocationUpdates: case requestSingleUpdate: case Srv_removeUpdates: case Srv_requestLocationUpdates: // Do nothing break; case sendExtraCommand: case Srv_sendExtraCommand: if (param.args.length > 0) { String provider = (String) param.args[0]; if (isRestrictedExtra(param, provider)) param.setResult(false); } break; } } private void proxyLocationListener(XParam param, int arg, Class<?> interfaze, boolean client) throws Throwable { if (param.args.length > arg) if (param.args[arg] instanceof PendingIntent) param.setResult(null); else if (param.args[arg] != null && param.thisObject != null) { if (client) { Object key = param.args[arg]; synchronized (mMapProxy) { // Reuse existing proxy if (mMapProxy.containsKey(key)) { Util.log(this, Log.INFO, "Reuse existing proxy uid=" + Binder.getCallingUid()); param.args[arg] = mMapProxy.get(key); return; } // Already proxied if (mMapProxy.containsValue(key)) { Util.log(this, Log.INFO, "Already proxied uid=" + Binder.getCallingUid()); return; } } // Create proxy Util.log(this, Log.INFO, "Creating proxy uid=" + Binder.getCallingUid()); Object proxy = new ProxyLocationListener(Binder.getCallingUid(), (LocationListener) param.args[arg]); // Use proxy synchronized (mMapProxy) { mMapProxy.put(key, proxy); } param.args[arg] = proxy; } else { // Create proxy ClassLoader cl = param.thisObject.getClass().getClassLoader(); InvocationHandler ih = new OnLocationChangedHandler(Binder.getCallingUid(), param.args[arg]); Object proxy = Proxy.newProxyInstance(cl, new Class<?>[] { interfaze }, ih); Object key = param.args[arg]; if (key instanceof IInterface) key = ((IInterface) key).asBinder(); // Use proxy synchronized (mMapProxy) { mMapProxy.put(key, proxy); } param.args[arg] = proxy; } } } private void unproxyLocationListener(XParam param, int arg, boolean client) { if (param.args.length > arg) if (param.args[arg] instanceof PendingIntent) param.setResult(null); else if (param.args[arg] != null) { if (client) { Object key = param.args[arg]; synchronized (mMapProxy) { if (mMapProxy.containsKey(key)) { Util.log(this, Log.INFO, "Removing proxy uid=" + Binder.getCallingUid()); param.args[arg] = mMapProxy.get(key); } } } else { Object key = param.args[arg]; if (key instanceof IInterface) key = ((IInterface) key).asBinder(); synchronized (mMapProxy) { if (mMapProxy.containsKey(key)) param.args[arg] = mMapProxy.get(key); } } } } private static class ProxyLocationListener implements LocationListener { private int mUid; private LocationListener mListener; public ProxyLocationListener(int uid, LocationListener listener) { mUid = uid; mListener = listener; } @Override public void onLocationChanged(Location location) { Util.log(null, Log.INFO, "Location changed uid=" + Binder.getCallingUid()); Location fakeLocation = PrivacyManager.getDefacedLocation(mUid, location); mListener.onLocationChanged(fakeLocation); } @Override public void onProviderDisabled(String provider) { mListener.onProviderDisabled(provider); } @Override public void onProviderEnabled(String provider) { mListener.onProviderEnabled(provider); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { mListener.onStatusChanged(provider, status, extras); } } private class OnLocationChangedHandler implements InvocationHandler { private int mUid; private Object mTarget; public OnLocationChangedHandler(int uid, Object target) { mUid = uid; mTarget = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("onLocationChanged".equals(method.getName())) args[0] = PrivacyManager.getDefacedLocation(mUid, (Location) args[0]); return method.invoke(mTarget, args); } } }
16,050
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XSipManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XSipManager.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.util.Log; public class XSipManager extends XHook { private Methods mMethod; private XSipManager(Methods method, String restrictionName) { super(restrictionName, method.name(), "SIP." + method.name()); mMethod = method; } public String getClassName() { return "android.net.sip.SipManager"; } // @formatter:off // static boolean isApiSupported(Context context) // static boolean isSipWifiOnly(Context context) // static boolean isVoipSupported(Context context) // public static SipManager newInstance (Context context) // http://developer.android.com/reference/android/net/sip/SipManager.html // @formatter:on private enum Methods { isApiSupported, isSipWifiOnly, isVoipSupported, newInstance }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XSipManager(Methods.isApiSupported, PrivacyManager.cCalling)); listHook.add(new XSipManager(Methods.isSipWifiOnly, PrivacyManager.cCalling)); listHook.add(new XSipManager(Methods.isVoipSupported, PrivacyManager.cCalling)); listHook.add(new XSipManager(Methods.newInstance, PrivacyManager.cCalling)); return listHook; } @Override protected void before(XParam param) throws Throwable { if (mMethod == Methods.isApiSupported || mMethod == Methods.isSipWifiOnly || mMethod == Methods.isVoipSupported) { if (isRestricted(param)) param.setResult(false); } else if (mMethod == Methods.newInstance) { if (isRestricted(param)) param.setResult(null); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
1,781
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XGoogleMapV1.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XGoogleMapV1.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; public class XGoogleMapV1 extends XHook { private Methods mMethod; private XGoogleMapV1(Methods method, String restrictionName) { super(restrictionName, method.name(), String.format("MapV1.%s", method.name())); mMethod = method; } public String getClassName() { return "com.google.android.maps.MyLocationOverlay"; } // boolean enableMyLocation() // void disableMyLocation() // https://developers.google.com/maps/documentation/android/v1/reference/index private enum Methods { enableMyLocation, disableMyLocation }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XGoogleMapV1(Methods.enableMyLocation, PrivacyManager.cLocation)); listHook.add(new XGoogleMapV1(Methods.disableMyLocation, null)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case enableMyLocation: if (isRestricted(param)) param.setResult(false); break; case disableMyLocation: if (isRestricted(param, PrivacyManager.cLocation, "MapV1.enableMyLocation")) param.setResult(null); break; } } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
1,309
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
PRestriction.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/PRestriction.java
package biz.bokhorst.xprivacy; import android.annotation.SuppressLint; import android.os.Parcel; import android.os.Parcelable; public class PRestriction implements Parcelable { public int uid; public String restrictionName; public String methodName; public boolean restricted; public boolean asked; public String extra; public String value; public long time; public boolean debug; // The extra is never needed in the result public PRestriction() { } public PRestriction(PRestriction other) { uid = other.uid; restrictionName = other.restrictionName; methodName = other.methodName; restricted = other.restricted; asked = other.asked; extra = null; value = other.value; time = other.time; debug = other.debug; } public PRestriction(int _uid, String category, String method) { uid = _uid; restrictionName = category; methodName = method; restricted = false; asked = false; extra = null; value = null; time = 0; debug = false; } public PRestriction(int _uid, String category, String method, boolean _restricted) { uid = _uid; restrictionName = category; methodName = method; restricted = _restricted; asked = false; extra = null; value = null; time = 0; debug = false; } public PRestriction(int _uid, String category, String method, boolean _restricted, boolean _asked) { uid = _uid; restrictionName = category; methodName = method; restricted = _restricted; asked = _asked; extra = null; value = null; time = 0; debug = false; } public static final Parcelable.Creator<PRestriction> CREATOR = new Parcelable.Creator<PRestriction>() { public PRestriction createFromParcel(Parcel in) { return new PRestriction(in); } public PRestriction[] newArray(int size) { return new PRestriction[size]; } }; private PRestriction(Parcel in) { readFromParcel(in); } @Override public void writeToParcel(Parcel out, int flags) { out.writeInt(uid); out.writeInt(restrictionName == null ? 1 : 0); if (restrictionName != null) out.writeString(restrictionName); out.writeInt(methodName == null ? 1 : 0); if (methodName != null) out.writeString(methodName); out.writeInt(restricted ? 1 : 0); out.writeInt(asked ? 1 : 0); out.writeInt(extra == null ? 1 : 0); if (extra != null) out.writeString(extra); out.writeInt(value == null ? 1 : 0); if (value != null) out.writeString(value); out.writeLong(time); out.writeInt(debug ? 1 : 0); } public void readFromParcel(Parcel in) { uid = in.readInt(); restrictionName = (in.readInt() > 0 ? null : in.readString()); methodName = (in.readInt() > 0 ? null : in.readString()); restricted = (in.readInt() > 0 ? true : false); asked = (in.readInt() > 0 ? true : false); extra = (in.readInt() > 0 ? null : in.readString()); value = (in.readInt() > 0 ? null : in.readString()); time = in.readLong(); debug = (in.readInt() > 0 ? true : false); } @Override public int describeContents() { return 0; } @Override @SuppressLint("DefaultLocale") public String toString() { return String.format("%d/%s(%s;%s) %s=%srestricted%s", uid, methodName, extra, value, restrictionName, (restricted ? "" : "!"), (asked ? "" : "?")); } }
3,235
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XUsageStatsManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XUsageStatsManager.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.usage.ConfigurationStats; import android.app.usage.UsageStats; import biz.bokhorst.xprivacy.XHook; public class XUsageStatsManager extends XHook { private Methods mMethod; private XUsageStatsManager(Methods method, String restrictionName) { super(restrictionName, method.name().replace("Srv_", ""), method.name()); mMethod = method; } @Override public boolean isVisible() { return !mMethod.name().startsWith("Srv_"); } public String getClassName() { if (mMethod.name().startsWith("Srv_")) return "com.android.server.usage.UserUsageStatsService"; else return "android.app.usage.UsageStatsManager"; } // @formatter:off // public Map<String, UsageStats> queryAndAggregateUsageStats(long beginTime, long endTime) // public List<ConfigurationStats> queryConfigurations(int intervalType, long beginTime, long endTime) // public UsageEvents queryEvents(long beginTime, long endTime) // public List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) // https://developer.android.com/reference/android/app/usage/UsageStatsManager.html // List<ConfigurationStats> queryConfigurationStats(int userId, int bucketType, long beginTime, long endTime) // UsageEvents queryEvents(int userId, long beginTime, long endTime) // List<UsageStats> queryUsageStats(int userId, int bucketType, long beginTime, long endTime) // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/com/android/server/usage/UsageStatsService.java private enum Methods { queryAndAggregateUsageStats, queryConfigurations, queryEvents, queryUsageStats, Srv_queryConfigurationStats, Srv_queryEvents, Srv_queryUsageStats }; // @formatter:on public static List<XHook> getInstances(boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (server) { listHook.add(new XUsageStatsManager(Methods.Srv_queryConfigurationStats, PrivacyManager.cSystem)); listHook.add(new XUsageStatsManager(Methods.Srv_queryEvents, PrivacyManager.cSystem)); listHook.add(new XUsageStatsManager(Methods.Srv_queryUsageStats, PrivacyManager.cSystem)); } else { listHook.add(new XUsageStatsManager(Methods.queryAndAggregateUsageStats, PrivacyManager.cSystem)); listHook.add(new XUsageStatsManager(Methods.queryConfigurations, PrivacyManager.cSystem)); listHook.add(new XUsageStatsManager(Methods.queryEvents, PrivacyManager.cSystem)); listHook.add(new XUsageStatsManager(Methods.queryUsageStats, PrivacyManager.cSystem)); } return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case queryAndAggregateUsageStats: case queryConfigurations: case queryUsageStats: case Srv_queryConfigurationStats: case Srv_queryUsageStats: // Do nothing break; case queryEvents: if (isRestricted(param)) if (param.args.length > 1) { param.args[0] = 0; param.args[1] = 0; } break; case Srv_queryEvents: if (isRestricted(param)) if (param.args.length > 2) { param.args[1] = 0; param.args[2] = 0; } break; } } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case queryAndAggregateUsageStats: if (isRestricted(param)) param.setResult(new HashMap<String, UsageStats>()); break; case queryConfigurations: case Srv_queryConfigurationStats: if (isRestricted(param)) param.setResult(new ArrayList<ConfigurationStats>()); break; case queryEvents: case Srv_queryEvents: // Do nothing break; case queryUsageStats: case Srv_queryUsageStats: if (isRestricted(param)) param.setResult(new ArrayList<UsageStats>()); break; } } }
3,825
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XBluetoothAdapter.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XBluetoothAdapter.java
package biz.bokhorst.xprivacy; import biz.bokhorst.xprivacy.XHook; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.bluetooth.BluetoothDevice; import android.os.Binder; public class XBluetoothAdapter extends XHook { private Methods mMethod; private String mClassName; private XBluetoothAdapter(Methods method, String restrictionName) { super(restrictionName, method.name().replace("Srv_", ""), "Bluetooth." + method.name()); mMethod = method; if (method.name().startsWith("Srv_")) mClassName = "com.android.server.BluetoothManagerService"; else mClassName = "android.bluetooth.BluetoothAdapter"; } public String getClassName() { return mClassName; } // @formatter:off // public String getAddress() // public Set<BluetoothDevice> getBondedDevices() // public String getName() // frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java // http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.4_r1/com/android/server/BluetoothManagerService.java // @formatter:on private enum Methods { getAddress, getBondedDevices, Srv_getAddress, Srv_getName }; public static List<XHook> getInstances(boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (server) { listHook.add(new XBluetoothAdapter(Methods.Srv_getAddress, PrivacyManager.cNetwork)); listHook.add(new XBluetoothAdapter(Methods.Srv_getName, PrivacyManager.cNetwork)); } else { listHook.add(new XBluetoothAdapter(Methods.getAddress, PrivacyManager.cNetwork)); listHook.add(new XBluetoothAdapter(Methods.getBondedDevices, PrivacyManager.cNetwork)); } return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { int uid = Binder.getCallingUid(); switch (mMethod) { case getAddress: case Srv_getAddress: if (param.getResult() != null) if (isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(uid, "MAC")); break; case Srv_getName: if (param.getResult() != null) if (isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(uid, "BTName")); break; case getBondedDevices: if (param.getResult() != null && isRestricted(param)) param.setResult(new HashSet<BluetoothDevice>()); break; } } }
2,479
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XNetworkInfo.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XNetworkInfo.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.net.NetworkInfo; import android.os.Binder; import android.util.Log; public class XNetworkInfo extends XHook { private Methods mMethod; private XNetworkInfo(Methods method, String restrictionName) { super(restrictionName, method.name(), "NetworkInfo." + method.name()); mMethod = method; } public String getClassName() { return "android.net.NetworkInfo"; } // public DetailedState getDetailedState() // public State getState() // public boolean isConnected() // public boolean isConnectedOrConnecting() // frameworks/base/core/java/android/net/NetworkInfo.java // http://developer.android.com/reference/android/net/NetworkInfo.html private enum Methods { getDetailedState, getExtraInfo, getState, isConnected, isConnectedOrConnecting }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); for (Methods ninfo : Methods.values()) if (ninfo == Methods.getExtraInfo) listHook.add(new XNetworkInfo(ninfo, PrivacyManager.cNetwork)); else listHook.add(new XNetworkInfo(ninfo, PrivacyManager.cInternet)); return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { if (mMethod == Methods.getDetailedState) { if (param.getResult() != null && isRestricted(param)) param.setResult(NetworkInfo.DetailedState.DISCONNECTED); } else if (mMethod == Methods.getExtraInfo) { if (param.getResult() != null && isRestricted(param)) param.setResult(PrivacyManager.getDefacedProp(Binder.getCallingUid(), "ExtraInfo")); } else if (mMethod == Methods.getState) { if (param.getResult() != null && isRestricted(param)) param.setResult(NetworkInfo.State.DISCONNECTED); } else if (mMethod == Methods.isConnected || mMethod == Methods.isConnectedOrConnecting) { if (isRestricted(param)) param.setResult(false); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } }
2,106
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XGoogleAuthUtil.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XGoogleAuthUtil.java
package biz.bokhorst.xprivacy; import java.io.IOException; import java.util.ArrayList; import java.util.List; import android.accounts.Account; import android.util.Log; public class XGoogleAuthUtil extends XHook { private Methods mMethod; private XGoogleAuthUtil(Methods method, String restrictionName, String specifier) { super(restrictionName, method.name(), specifier); mMethod = method; } public String getClassName() { return "com.google.android.gms.auth.GoogleAuthUtil"; } // @formatter:off // static String getToken(Context context, String accountName, String scope) // static String getToken(Context context, String accountName, String scope, Bundle extras) // static String getTokenWithNotification(Context context, String accountName, String scope, Bundle extras) // static String getTokenWithNotification(Context context, String accountName, String scope, Bundle extras, Intent callback) // static String getTokenWithNotification(Context context, String accountName, String scope, Bundle extras, String authority, Bundle syncBundle) // https://developer.android.com/reference/com/google/android/gms/auth/GoogleAuthUtil.html // @formatter:on private enum Methods { getToken, getTokenWithNotification }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XGoogleAuthUtil(Methods.getToken, PrivacyManager.cAccounts, "getTokenGoogle")); listHook.add(new XGoogleAuthUtil(Methods.getTokenWithNotification, PrivacyManager.cAccounts, "getTokenWithNotificationGoogle")); return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { if (mMethod == Methods.getToken || mMethod == Methods.getTokenWithNotification) { if (param.args.length > 1) { String accountName = null; if (param.args[1] instanceof String) accountName = (String) param.args[1]; else if (param.args[1] instanceof Account) accountName = ((Account) param.args[1]).type; if (param.getResult() != null && isRestrictedExtra(param, accountName)) param.setThrowable(new IOException("XPrivacy")); } } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } }
2,300
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
ActivityUsage.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/ActivityUsage.java
package biz.bokhorst.xprivacy; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.os.Process; import android.support.v4.app.NavUtils; import android.support.v4.app.TaskStackBuilder; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class ActivityUsage extends ActivityBase { private boolean mAll = true; private int mUid; private String mRestrictionName; private UsageAdapter mUsageAdapter; public static final String cUid = "Uid"; public static final String cRestriction = "Restriction"; private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new PriorityThreadFactory()); private static class PriorityThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.NORM_PRIORITY); return t; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Check privacy service client if (!PrivacyService.checkClient()) return; // Set layout setContentView(R.layout.usagelist); setSupportActionBar((Toolbar) findViewById(R.id.widgetToolbar)); // Get uid Bundle extras = getIntent().getExtras(); mUid = (extras == null ? 0 : extras.getInt(cUid, 0)); mRestrictionName = (extras == null ? null : extras.getString(cRestriction)); // Show title updateTitle(); // Start task to get usage data UsageTask usageTask = new UsageTask(); usageTask.executeOnExecutor(mExecutor, (Object) null); // Up navigation getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override protected void onResume() { super.onResume(); if (mUsageAdapter != null) mUsageAdapter.notifyDataSetChanged(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); if (inflater != null && PrivacyService.checkClient()) { inflater.inflate(R.menu.usage, menu); return true; } else return false; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.menu_whitelists).setVisible(mUid != 0); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { UsageTask usageTask; switch (item.getItemId()) { case android.R.id.home: Intent upIntent = NavUtils.getParentActivityIntent(this); if (upIntent != null) if (NavUtils.shouldUpRecreateTask(this, upIntent)) TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities(); else NavUtils.navigateUpTo(this, upIntent); return true; case R.id.menu_usage_all: mAll = !mAll; if (mUsageAdapter != null) mUsageAdapter.getFilter().filter(Boolean.toString(mAll)); return true; case R.id.menu_refresh: updateTitle(); usageTask = new UsageTask(); usageTask.executeOnExecutor(mExecutor, (Object) null); return true; case R.id.menu_clear: PrivacyManager.deleteUsage(mUid); usageTask = new UsageTask(); usageTask.executeOnExecutor(mExecutor, (Object) null); return true; case R.id.menu_whitelists: if (Util.hasProLicense(this) == null) { // Redirect to pro page Util.viewUri(this, ActivityMain.cProUri); } else { WhitelistTask whitelistsTask = new WhitelistTask(mUid, null, this); whitelistsTask.executeOnExecutor(mExecutor, (Object) null); } return true; case R.id.menu_settings: Intent intent = new Intent(this, ActivitySettings.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } // Tasks private class UsageTask extends AsyncTask<Object, Object, List<PRestriction>> { @Override protected List<PRestriction> doInBackground(Object... arg0) { List<PRestriction> listUsageData = new ArrayList<PRestriction>(); for (PRestriction usageData : PrivacyManager.getUsageList(ActivityUsage.this, mUid, mRestrictionName)) listUsageData.add(usageData); return listUsageData; } @Override protected void onPostExecute(List<PRestriction> listUsageData) { if (!ActivityUsage.this.isFinishing()) { mUsageAdapter = new UsageAdapter(ActivityUsage.this, R.layout.usageentry, listUsageData); ListView lvUsage = (ListView) findViewById(R.id.lvUsage); lvUsage.setAdapter(mUsageAdapter); mUsageAdapter.getFilter().filter(Boolean.toString(mAll)); } super.onPostExecute(listUsageData); } } // Adapters private class UsageAdapter extends ArrayAdapter<PRestriction> { private boolean mHasProLicense = false; private List<PRestriction> mListUsageData; private LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); public UsageAdapter(Context context, int textViewResourceId, List<PRestriction> objects) { super(context, textViewResourceId, objects); mHasProLicense = (Util.hasProLicense(ActivityUsage.this) != null); mListUsageData = new ArrayList<PRestriction>(); mListUsageData.addAll(objects); } @Override public Filter getFilter() { return new UsageFilter(); } private class UsageFilter extends Filter { public UsageFilter() { } @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); // Get argument boolean all = Boolean.parseBoolean((String) constraint); // Match applications List<PRestriction> lstResult = new ArrayList<PRestriction>(); for (PRestriction usageData : UsageAdapter.this.mListUsageData) { if (all ? true : usageData.restricted) lstResult.add(usageData); } synchronized (this) { results.values = lstResult; results.count = lstResult.size(); } return results; } @Override @SuppressWarnings("unchecked") protected void publishResults(CharSequence constraint, FilterResults results) { clear(); if (results.values == null) notifyDataSetInvalidated(); else { addAll((ArrayList<PRestriction>) results.values); notifyDataSetChanged(); } } } private class ViewHolder { private View row; private int position; public LinearLayout llUsage; public TextView tvTime; public ImageView imgIcon; public ImageView imgRestricted; public TextView tvApp; public TextView tvRestriction; public TextView tvParameter; public TextView tvValue; public ViewHolder(View theRow, int thePosition) { row = theRow; position = thePosition; llUsage = (LinearLayout) row.findViewById(R.id.llUsage); tvTime = (TextView) row.findViewById(R.id.tvTime); imgIcon = (ImageView) row.findViewById(R.id.imgIcon); imgRestricted = (ImageView) row.findViewById(R.id.imgRestricted); tvApp = (TextView) row.findViewById(R.id.tvApp); tvRestriction = (TextView) row.findViewById(R.id.tvRestriction); tvParameter = (TextView) row.findViewById(R.id.tvParameter); tvValue = (TextView) row.findViewById(R.id.tvValue); } } private class HolderTask extends AsyncTask<Object, Object, Object> { private int position; private ViewHolder holder; private PRestriction usageData; private Drawable icon = null; private boolean system; private Hook hook; public HolderTask(int thePosition, ViewHolder theHolder, PRestriction theUsageData) { position = thePosition; holder = theHolder; usageData = theUsageData; } @Override protected Object doInBackground(Object... params) { if (usageData != null) { ApplicationInfoEx appInfo = new ApplicationInfoEx(ActivityUsage.this, usageData.uid); icon = appInfo.getIcon(ActivityUsage.this); system = appInfo.isSystem(); hook = PrivacyManager.getHook(usageData.restrictionName, usageData.methodName); return holder; } return null; } @Override protected void onPostExecute(Object result) { if (holder.position == position && result != null) { if (system || (hook != null && hook.isDangerous())) holder.row.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous))); else holder.row.setBackgroundColor(Color.TRANSPARENT); holder.imgIcon.setImageDrawable(icon); holder.imgIcon.setVisibility(View.VISIBLE); View.OnClickListener clickListener = new View.OnClickListener() { @Override public void onClick(View view) { PRestriction usageData = mUsageAdapter.getItem(position); Intent intent = new Intent(ActivityUsage.this, ActivityApp.class); intent.putExtra(ActivityApp.cUid, usageData.uid); intent.putExtra(ActivityApp.cRestrictionName, usageData.restrictionName); intent.putExtra(ActivityApp.cMethodName, usageData.methodName); startActivity(intent); } }; View.OnLongClickListener longClickListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { int userId = Util.getUserId(Process.myUid()); final PRestriction usageData = mUsageAdapter.getItem(position); final Hook hook = PrivacyManager.getHook(usageData.restrictionName, usageData.methodName); boolean isApp = PrivacyManager.isApplication(usageData.uid); boolean odSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false); final boolean wnomod = PrivacyManager.getSettingBool(usageData.uid, PrivacyManager.cSettingWhitelistNoModify, false); if ((isApp || odSystem) && hook != null && hook.whitelist() != null && usageData.extra != null) { if (Util.hasProLicense(ActivityUsage.this) == null) Util.viewUri(ActivityUsage.this, ActivityMain.cProUri); else { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityUsage.this); alertDialogBuilder.setTitle(R.string.menu_whitelists); alertDialogBuilder.setMessage(usageData.restrictionName + "/" + usageData.methodName + "(" + usageData.extra + ")"); alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(getString(R.string.title_deny), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Deny PrivacyManager.setSetting(usageData.uid, hook.whitelist(), usageData.extra, Boolean.toString(false)); if (!wnomod) PrivacyManager.updateState(usageData.uid); } }); alertDialogBuilder.setNeutralButton(getString(R.string.title_allow), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Allow PrivacyManager.setSetting(usageData.uid, hook.whitelist(), usageData.extra, Boolean.toString(true)); if (!wnomod) PrivacyManager.updateState(usageData.uid); } }); alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } return true; } else return false; } }; holder.llUsage.setOnClickListener(clickListener); holder.tvRestriction.setOnClickListener(clickListener); holder.llUsage.setOnLongClickListener(longClickListener); holder.tvRestriction.setOnLongClickListener(longClickListener); } } } @Override @SuppressLint("InflateParams") public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.usageentry, null); holder = new ViewHolder(convertView, position); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); holder.position = position; } // Get data PRestriction usageData = getItem(position); // Build entry holder.row.setBackgroundColor(Color.TRANSPARENT); Date date = new Date(usageData.time); SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.ROOT); holder.tvTime.setText(format.format(date)); holder.imgIcon.setVisibility(View.INVISIBLE); holder.imgRestricted.setVisibility(usageData.restricted ? View.VISIBLE : View.INVISIBLE); holder.tvApp.setText(Integer.toString(usageData.uid)); holder.tvRestriction.setText(String.format("%s/%s", usageData.restrictionName, usageData.methodName)); if (!TextUtils.isEmpty(usageData.extra) && mHasProLicense) { holder.tvParameter.setText(usageData.extra); holder.tvParameter.setVisibility(View.VISIBLE); } else holder.tvParameter.setVisibility(View.GONE); if (usageData.value != null && mHasProLicense) { holder.tvValue.setText(getString(R.string.title_original) + ": " + usageData.value); holder.tvValue.setVisibility(View.VISIBLE); } else holder.tvValue.setVisibility(View.GONE); // Async update new HolderTask(position, holder, usageData).executeOnExecutor(mExecutor, (Object) null); return convertView; } } // Helpers private void updateTitle() { if (mUid == 0) { // Get statistics long count = 0; long restricted = 0; double persec = 0; try { @SuppressWarnings("rawtypes") Map statistics = PrivacyService.getClient().getStatistics(); count = (Long) statistics.get("restriction_count"); restricted = (Long) statistics.get("restriction_restricted"); long uptime = (Long) statistics.get("uptime_milliseconds"); persec = (double) count / (uptime / 1000); } catch (Throwable ex) { Util.bug(null, ex); } // Set sub title getSupportActionBar().setSubtitle(String.format("%d/%d %.2f/s", restricted, count, persec)); } else getSupportActionBar().setSubtitle( TextUtils.join(", ", new ApplicationInfoEx(this, mUid).getApplicationName())); } }
15,142
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XNfcAdapter.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XNfcAdapter.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.util.Log; public class XNfcAdapter extends XHook { private Methods mMethod; protected XNfcAdapter(Methods method, String restrictionName) { super(restrictionName, method.name(), null); mMethod = method; } @Override public String getClassName() { return "android.nfc.NfcAdapter"; } private enum Methods { getDefaultAdapter, getNfcAdapter }; // public static NfcAdapter getDefaultAdapter() [deprecated] // public static NfcAdapter getDefaultAdapter(Context context) // public static synchronized NfcAdapter getNfcAdapter(Context context) // frameworks/base/core/java/android/nfc/NfcAdapter.java // http://developer.android.com/reference/android/nfc/NfcAdapter.html // NfcManager.getDefaultAdapter calls NfcAdapter.getNfcAdapter // http://developer.android.com/reference/android/nfc/NfcManager.html public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XNfcAdapter(Methods.getDefaultAdapter, PrivacyManager.cNfc)); listHook.add(new XNfcAdapter(Methods.getNfcAdapter, PrivacyManager.cNfc)); return listHook; } @Override protected void before(XParam param) throws Throwable { if (mMethod == Methods.getDefaultAdapter || mMethod == Methods.getNfcAdapter) { if (isRestricted(param)) param.setResult(null); } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName()); } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
1,577
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
ActivityApp.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/ActivityApp.java
package biz.bokhorst.xprivacy; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.AlertDialog; import android.app.Dialog; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Process; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.support.v4.app.NavUtils; import android.support.v4.app.TaskStackBuilder; import android.support.v7.widget.SwitchCompat; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.Window; import android.widget.BaseExpandableListAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnGroupExpandListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; public class ActivityApp extends ActivityBase { private ApplicationInfoEx mAppInfo = null; private SwitchCompat swEnabled = null; private RestrictionAdapter mPrivacyListAdapter = null; public static final String cUid = "Uid"; public static final String cRestrictionName = "RestrictionName"; public static final String cMethodName = "MethodName"; public static final String cAction = "Action"; public static final int cActionClear = 1; public static final int cActionSettings = 2; public static final int cActionRefresh = 3; private static final int MENU_LAUNCH = 1; private static final int MENU_SETTINGS = 2; private static final int MENU_KILL = 3; private static final int MENU_STORE = 4; private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new PriorityThreadFactory()); private static class PriorityThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.NORM_PRIORITY); return t; } } private boolean mPackageChangeReceiverRegistered = false; private BroadcastReceiver mPackageChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int uid = intent.getIntExtra(Intent.EXTRA_UID, 0); if (mAppInfo.getUid() == uid) finish(); } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final int userId = Util.getUserId(Process.myUid()); // Check privacy service client if (!PrivacyService.checkClient()) return; // Set layout setContentView(R.layout.restrictionlist); setSupportActionBar((Toolbar) findViewById(R.id.widgetToolbar)); // Annotate Meta.annotate(this.getResources()); // Get arguments Bundle extras = getIntent().getExtras(); if (extras == null) { finish(); return; } int uid = extras.getInt(cUid); String restrictionName = (extras.containsKey(cRestrictionName) ? extras.getString(cRestrictionName) : null); String methodName = (extras.containsKey(cMethodName) ? extras.getString(cMethodName) : null); // Get app info mAppInfo = new ApplicationInfoEx(this, uid); if (mAppInfo.getPackageName().size() == 0) { finish(); return; } // Set sub title getSupportActionBar().setSubtitle(TextUtils.join(", ", mAppInfo.getApplicationName())); // Handle info click ImageView imgInfo = (ImageView) findViewById(R.id.imgInfo); imgInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Packages can be selected on the web site Util.viewUri(ActivityApp.this, Uri.parse(String.format(ActivityShare.getBaseURL() + "?package_name=%s", mAppInfo.getPackageName().get(0)))); } }); // Display app name TextView tvAppName = (TextView) findViewById(R.id.tvApp); tvAppName.setText(mAppInfo.toString()); // Background color if (mAppInfo.isSystem()) { LinearLayout llInfo = (LinearLayout) findViewById(R.id.llInfo); llInfo.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous))); } // Display app icon final ImageView imgIcon = (ImageView) findViewById(R.id.imgIcon); imgIcon.setImageDrawable(mAppInfo.getIcon(this)); // Handle icon click imgIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openContextMenu(imgIcon); } }); // Display on-demand state final ImageView imgCbOnDemand = (ImageView) findViewById(R.id.imgCbOnDemand); boolean isApp = PrivacyManager.isApplication(mAppInfo.getUid()); boolean odSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false); boolean gondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true); if ((isApp || odSystem) && gondemand) { boolean ondemand = PrivacyManager .getSettingBool(-mAppInfo.getUid(), PrivacyManager.cSettingOnDemand, false); imgCbOnDemand.setImageBitmap(ondemand ? getOnDemandCheckBox() : getOffCheckBox()); imgCbOnDemand.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean ondemand = !PrivacyManager.getSettingBool(-mAppInfo.getUid(), PrivacyManager.cSettingOnDemand, false); PrivacyManager.setSetting(mAppInfo.getUid(), PrivacyManager.cSettingOnDemand, Boolean.toString(ondemand)); imgCbOnDemand.setImageBitmap(ondemand ? getOnDemandCheckBox() : getOffCheckBox()); if (mPrivacyListAdapter != null) mPrivacyListAdapter.notifyDataSetChanged(); } }); } else imgCbOnDemand.setVisibility(View.GONE); // Display restriction state swEnabled = (SwitchCompat) findViewById(R.id.swEnable); swEnabled.setChecked(PrivacyManager.getSettingBool(mAppInfo.getUid(), PrivacyManager.cSettingRestricted, true)); swEnabled.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { PrivacyManager.setSetting(mAppInfo.getUid(), PrivacyManager.cSettingRestricted, Boolean.toString(isChecked)); if (mPrivacyListAdapter != null) mPrivacyListAdapter.notifyDataSetChanged(); imgCbOnDemand.setEnabled(isChecked); } }); imgCbOnDemand.setEnabled(swEnabled.isChecked()); // Add context menu to icon registerForContextMenu(imgIcon); // Check if internet access if (!mAppInfo.hasInternet(this)) { ImageView imgInternet = (ImageView) findViewById(R.id.imgInternet); imgInternet.setVisibility(View.INVISIBLE); } // Check if frozen if (!mAppInfo.isFrozen(this)) { ImageView imgFrozen = (ImageView) findViewById(R.id.imgFrozen); imgFrozen.setVisibility(View.INVISIBLE); } // Display version TextView tvVersion = (TextView) findViewById(R.id.tvVersion); tvVersion.setText(TextUtils.join(", ", mAppInfo.getPackageVersionName(this))); // Display package name TextView tvPackageName = (TextView) findViewById(R.id.tvPackageName); tvPackageName.setText(TextUtils.join(", ", mAppInfo.getPackageName())); // Fill privacy expandable list view adapter final ExpandableListView elvRestriction = (ExpandableListView) findViewById(R.id.elvRestriction); elvRestriction.setGroupIndicator(null); mPrivacyListAdapter = new RestrictionAdapter(this, R.layout.restrictionentry, mAppInfo, restrictionName, methodName); elvRestriction.setAdapter(mPrivacyListAdapter); // Listen for group expand elvRestriction.setOnGroupExpandListener(new OnGroupExpandListener() { @Override public void onGroupExpand(final int groupPosition) { if (!PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingMethodExpert, false)) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this); alertDialogBuilder.setTitle(R.string.app_name); alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher)); alertDialogBuilder.setMessage(R.string.msg_method_expert); alertDialogBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { PrivacyManager.setSetting(userId, PrivacyManager.cSettingMethodExpert, Boolean.toString(true)); if (mPrivacyListAdapter != null) mPrivacyListAdapter.notifyDataSetChanged(); } }); alertDialogBuilder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { elvRestriction.collapseGroup(groupPosition); } }); alertDialogBuilder.setCancelable(false); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } } }); // Go to method if (restrictionName != null) { int groupPosition = new ArrayList<String>(PrivacyManager.getRestrictions(this).values()) .indexOf(restrictionName); elvRestriction.setSelectedGroup(groupPosition); elvRestriction.expandGroup(groupPosition); if (methodName != null) { Version version = new Version(Util.getSelfVersionName(this)); int childPosition = PrivacyManager.getHooks(restrictionName, version).indexOf( new Hook(restrictionName, methodName)); elvRestriction.setSelectedChild(groupPosition, childPosition, true); } } // Listen for package add/remove IntentFilter iff = new IntentFilter(); iff.addAction(Intent.ACTION_PACKAGE_REMOVED); iff.addDataScheme("package"); registerReceiver(mPackageChangeReceiver, iff); mPackageChangeReceiverRegistered = true; // Up navigation getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Tutorial if (!PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingTutorialDetails, false)) { ((ScrollView) findViewById(R.id.svTutorialHeader)).setVisibility(View.VISIBLE); ((ScrollView) findViewById(R.id.svTutorialDetails)).setVisibility(View.VISIBLE); } View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View view) { ViewParent parent = view.getParent(); while (!parent.getClass().equals(ScrollView.class)) parent = parent.getParent(); ((View) parent).setVisibility(View.GONE); PrivacyManager.setSetting(userId, PrivacyManager.cSettingTutorialDetails, Boolean.TRUE.toString()); } }; ((Button) findViewById(R.id.btnTutorialHeader)).setOnClickListener(listener); ((Button) findViewById(R.id.btnTutorialDetails)).setOnClickListener(listener); // Process actions if (extras.containsKey(cAction)) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(mAppInfo.getUid()); if (extras.getInt(cAction) == cActionClear) optionClear(); else if (extras.getInt(cAction) == cActionSettings) optionSettings(); } } @Override protected void onNewIntent(Intent intent) { Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(cAction) && extras.getInt(cAction) == cActionRefresh) { // Update on demand check box ImageView imgCbOnDemand = (ImageView) findViewById(R.id.imgCbOnDemand); boolean ondemand = PrivacyManager .getSettingBool(-mAppInfo.getUid(), PrivacyManager.cSettingOnDemand, false); imgCbOnDemand.setImageBitmap(ondemand ? getOnDemandCheckBox() : getOffCheckBox()); // Update restriction list if (mPrivacyListAdapter != null) mPrivacyListAdapter.notifyDataSetChanged(); } else { setIntent(intent); recreate(); } } @Override protected void onResume() { super.onResume(); // Update switch if (swEnabled != null) swEnabled.setChecked(PrivacyManager.getSettingBool(mAppInfo.getUid(), PrivacyManager.cSettingRestricted, true)); // Update on demand check box int userId = Util.getUserId(Process.myUid()); ImageView imgCbOnDemand = (ImageView) findViewById(R.id.imgCbOnDemand); boolean isApp = PrivacyManager.isApplication(mAppInfo.getUid()); boolean odSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false); boolean gondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true); if ((isApp || odSystem) && gondemand) { boolean ondemand = PrivacyManager .getSettingBool(-mAppInfo.getUid(), PrivacyManager.cSettingOnDemand, false); imgCbOnDemand.setImageBitmap(ondemand ? getOnDemandCheckBox() : getOffCheckBox()); } // Update list if (mPrivacyListAdapter != null) mPrivacyListAdapter.notifyDataSetChanged(); } @Override protected void onDestroy() { super.onDestroy(); if (mPackageChangeReceiverRegistered) { unregisterReceiver(mPackageChangeReceiver); mPackageChangeReceiverRegistered = false; } } @Override public boolean onCreateOptionsMenu(final Menu menu) { MenuInflater inflater = getMenuInflater(); if (inflater != null && PrivacyService.checkClient()) { inflater.inflate(R.menu.app, menu); // Add all contact groups menu.findItem(R.id.menu_contacts).getSubMenu() .add(-1, R.id.menu_contacts, Menu.NONE, getString(R.string.menu_all)); // Add other contact groups in the background new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... arg0) { try { String where = ContactsContract.Groups.GROUP_VISIBLE + " = 1"; where += " AND " + ContactsContract.Groups.SUMMARY_COUNT + " > 0"; Cursor cursor = getContentResolver().query( ContactsContract.Groups.CONTENT_SUMMARY_URI, new String[] { ContactsContract.Groups._ID, ContactsContract.Groups.TITLE, ContactsContract.Groups.ACCOUNT_NAME, ContactsContract.Groups.SUMMARY_COUNT }, where, null, ContactsContract.Groups.TITLE + ", " + ContactsContract.Groups.ACCOUNT_NAME); if (cursor != null) try { while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Groups._ID)); String title = cursor.getString(cursor .getColumnIndex(ContactsContract.Groups.TITLE)); String account = cursor.getString(cursor .getColumnIndex(ContactsContract.Groups.ACCOUNT_NAME)); menu.findItem(R.id.menu_contacts).getSubMenu() .add(id, R.id.menu_contacts, Menu.NONE, title + "/" + account); } } finally { cursor.close(); } } catch (Throwable ex) { Util.bug(null, ex); } return null; } }.executeOnExecutor(mExecutor); return true; } else return false; } // Application context menu @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // Check if running boolean running = false; ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); for (RunningAppProcessInfo info : activityManager.getRunningAppProcesses()) if (info.uid == mAppInfo.getUid()) running = true; PackageManager pm = getPackageManager(); List<String> listPackageNames = mAppInfo.getPackageName(); List<String> listApplicationName = mAppInfo.getApplicationName(); for (int i = 0; i < listPackageNames.size(); i++) { Menu appMenu = (listPackageNames.size() == 1) ? menu : menu.addSubMenu(i, Menu.NONE, Menu.NONE, listApplicationName.get(i)); // Launch MenuItem launch = appMenu.add(i, MENU_LAUNCH, Menu.NONE, getString(R.string.menu_app_launch)); if (pm.getLaunchIntentForPackage(listPackageNames.get(i)) == null) launch.setEnabled(false); // Settings appMenu.add(i, MENU_SETTINGS, Menu.NONE, getString(R.string.menu_app_settings)); // Kill MenuItem kill = appMenu.add(i, MENU_KILL, Menu.NONE, getString(R.string.menu_app_kill)); kill.setEnabled(running && PrivacyManager.isApplication(mAppInfo.getUid())); // Play store MenuItem store = appMenu.add(i, MENU_STORE, Menu.NONE, getString(R.string.menu_app_store)); if (!Util.hasMarketLink(this, listPackageNames.get(i))) store.setEnabled(false); } } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_LAUNCH: optionLaunch(item.getGroupId()); return true; case MENU_SETTINGS: optionAppSettings(item.getGroupId()); return true; case MENU_KILL: optionKill(item.getGroupId()); return true; case MENU_STORE: optionStore(item.getGroupId()); return true; default: return super.onContextItemSelected(item); } } private void optionLaunch(int which) { Intent intentLaunch = getPackageManager().getLaunchIntentForPackage(mAppInfo.getPackageName().get(which)); startActivity(intentLaunch); } private void optionAppSettings(int which) { Intent intentSettings = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + mAppInfo.getPackageName().get(which))); startActivity(intentSettings); } private void optionKill(final int which) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this); alertDialogBuilder.setTitle(R.string.menu_app_kill); alertDialogBuilder.setMessage(R.string.msg_sure); alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int _which) { XApplication.manage(ActivityApp.this, mAppInfo.getPackageName().get(which), XApplication.cActionKillProcess); Toast.makeText(ActivityApp.this, getString(R.string.msg_done), Toast.LENGTH_LONG).show(); } }); alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } private void optionStore(int which) { Util.viewUri(this, Uri.parse("market://details?id=" + mAppInfo.getPackageName().get(which))); } // Options @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean accountsRestricted = PrivacyManager.getRestrictionEx(mAppInfo.getUid(), PrivacyManager.cAccounts, null).restricted; boolean appsRestricted = PrivacyManager.getRestrictionEx(mAppInfo.getUid(), PrivacyManager.cSystem, null).restricted; boolean contactsRestricted = PrivacyManager.getRestrictionEx(mAppInfo.getUid(), PrivacyManager.cContacts, null).restricted; menu.findItem(R.id.menu_accounts).setEnabled(accountsRestricted); menu.findItem(R.id.menu_applications).setEnabled(appsRestricted); menu.findItem(R.id.menu_contacts).setEnabled(contactsRestricted); boolean mounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); menu.findItem(R.id.menu_export).setEnabled(mounted); menu.findItem(R.id.menu_import).setEnabled(mounted); menu.findItem(R.id.menu_submit).setEnabled(Util.hasValidFingerPrint(this)); menu.findItem(R.id.menu_dump).setVisible(Util.isDebuggable(this)); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent upIntent = NavUtils.getParentActivityIntent(this); if (upIntent != null) if (NavUtils.shouldUpRecreateTask(this, upIntent)) TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities(); else NavUtils.navigateUpTo(this, upIntent); return true; case R.id.menu_usage: optionUsage(); return true; case R.id.menu_accounts: optionAccounts(); return true; case R.id.menu_applications: optionApplications(); return true; case R.id.menu_contacts: if (item.getGroupId() != 0) { optionContacts(item.getGroupId()); return true; } else return false; case R.id.menu_whitelists: optionWhitelists(null); return true; case R.id.menu_apply: optionTemplate(); return true; case R.id.menu_clear: optionClear(); return true; case R.id.menu_export: optionExport(); return true; case R.id.menu_import: optionImport(); return true; case R.id.menu_submit: optionSubmit(); return true; case R.id.menu_fetch: optionFetch(); return true; case R.id.menu_settings: optionSettings(); return true; case R.id.menu_dump: optionDump(); return true; case R.id.menu_legend: optionLegend(); return true; case R.id.menu_tutorial: optionTutorial(); return true; default: return super.onOptionsItemSelected(item); } } private void optionUsage() { Intent intent = new Intent(this, ActivityUsage.class); intent.putExtra(ActivityUsage.cUid, mAppInfo.getUid()); startActivity(intent); } private void optionAccounts() { AccountsTask accountsTask = new AccountsTask(); accountsTask.executeOnExecutor(mExecutor, (Object) null); } private void optionApplications() { if (Util.hasProLicense(this) == null) { // Redirect to pro page Util.viewUri(this, ActivityMain.cProUri); } else { ApplicationsTask appsTask = new ApplicationsTask(); appsTask.executeOnExecutor(mExecutor, (Object) null); } } private void optionContacts(int groupId) { if (Util.hasProLicense(this) == null) { // Redirect to pro page Util.viewUri(this, ActivityMain.cProUri); } else { ContactsTask contactsTask = new ContactsTask(); contactsTask.executeOnExecutor(mExecutor, groupId); } } private void optionWhitelists(String type) { if (Util.hasProLicense(this) == null) { // Redirect to pro page Util.viewUri(this, ActivityMain.cProUri); } else { WhitelistTask whitelistsTask = new WhitelistTask(mAppInfo.getUid(), type, this); whitelistsTask.executeOnExecutor(mExecutor, (Object) null); } } private void optionTemplate() { Intent intent = new Intent(ActivityShare.ACTION_TOGGLE); intent.putExtra(ActivityShare.cInteractive, true); intent.putExtra(ActivityShare.cUidList, new int[] { mAppInfo.getUid() }); intent.putExtra(ActivityShare.cChoice, ActivityShare.CHOICE_TEMPLATE); startActivity(intent); } private void optionClear() { Intent intent = new Intent(ActivityShare.ACTION_TOGGLE); intent.putExtra(ActivityShare.cInteractive, true); intent.putExtra(ActivityShare.cUidList, new int[] { mAppInfo.getUid() }); intent.putExtra(ActivityShare.cChoice, ActivityShare.CHOICE_CLEAR); startActivity(intent); } private void optionExport() { Intent intent = new Intent(ActivityShare.ACTION_EXPORT); intent.putExtra(ActivityShare.cUidList, new int[] { mAppInfo.getUid() }); intent.putExtra(ActivityShare.cInteractive, true); startActivity(intent); } private void optionImport() { Intent intent = new Intent(ActivityShare.ACTION_IMPORT); intent.putExtra(ActivityShare.cUidList, new int[] { mAppInfo.getUid() }); intent.putExtra(ActivityShare.cInteractive, true); startActivity(intent); } private void optionSubmit() { if (ActivityShare.registerDevice(this)) { Intent intent = new Intent("biz.bokhorst.xprivacy.action.SUBMIT"); intent.putExtra(ActivityShare.cUidList, new int[] { mAppInfo.getUid() }); intent.putExtra(ActivityShare.cInteractive, true); startActivity(intent); } } private void optionFetch() { Intent intent = new Intent("biz.bokhorst.xprivacy.action.FETCH"); intent.putExtra(ActivityShare.cUidList, new int[] { mAppInfo.getUid() }); intent.putExtra(ActivityShare.cInteractive, true); startActivity(intent); } private void optionSettings() { Intent intent = new Intent(ActivityApp.this, ActivitySettings.class); intent.putExtra(ActivitySettings.cUid, mAppInfo.getUid()); startActivity(intent); } private void optionDump() { try { PrivacyService.getClient().dump(mAppInfo.getUid()); } catch (Throwable ex) { Util.bug(null, ex); } } private void optionLegend() { // Show help Dialog dialog = new Dialog(ActivityApp.this); dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON); dialog.setTitle(R.string.menu_legend); dialog.setContentView(R.layout.legend); dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, getThemed(R.attr.icon_launcher)); ((ImageView) dialog.findViewById(R.id.imgHelpHalf)).setImageBitmap(getHalfCheckBox()); ((ImageView) dialog.findViewById(R.id.imgHelpOnDemand)).setImageBitmap(getOnDemandCheckBox()); for (View child : Util.getViewsByTag((ViewGroup) dialog.findViewById(android.R.id.content), "main")) child.setVisibility(View.GONE); ((LinearLayout) dialog.findViewById(R.id.llUnsafe)).setVisibility(PrivacyManager.cVersion3 ? View.VISIBLE : View.GONE); dialog.setCancelable(true); dialog.show(); } private void optionTutorial() { ((ScrollView) findViewById(R.id.svTutorialHeader)).setVisibility(View.VISIBLE); ((ScrollView) findViewById(R.id.svTutorialDetails)).setVisibility(View.VISIBLE); int userId = Util.getUserId(Process.myUid()); PrivacyManager.setSetting(userId, PrivacyManager.cSettingTutorialDetails, Boolean.FALSE.toString()); } // Tasks private class AccountsTask extends AsyncTask<Object, Object, Object> { private List<CharSequence> mListAccount; private Account[] mAccounts; private boolean[] mSelection; @Override protected Object doInBackground(Object... params) { // Get accounts mListAccount = new ArrayList<CharSequence>(); AccountManager accountManager = AccountManager.get(ActivityApp.this); mAccounts = accountManager.getAccounts(); mSelection = new boolean[mAccounts.length]; for (int i = 0; i < mAccounts.length; i++) try { mListAccount.add(String.format("%s (%s)", mAccounts[i].name, mAccounts[i].type)); String sha1 = Util.sha1(mAccounts[i].name + mAccounts[i].type); mSelection[i] = PrivacyManager.getSettingBool(-mAppInfo.getUid(), Meta.cTypeAccount, sha1, false); } catch (Throwable ex) { Util.bug(null, ex); } return null; } @Override protected void onPostExecute(Object result) { if (!ActivityApp.this.isFinishing()) { // Build dialog AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this); alertDialogBuilder.setTitle(R.string.menu_accounts); alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher)); alertDialogBuilder.setMultiChoiceItems(mListAccount.toArray(new CharSequence[0]), mSelection, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) { try { Account account = mAccounts[whichButton]; String sha1 = Util.sha1(account.name + account.type); PrivacyManager.setSetting(mAppInfo.getUid(), Meta.cTypeAccount, sha1, Boolean.toString(isChecked)); } catch (Throwable ex) { Util.bug(null, ex); Toast toast = Toast.makeText(ActivityApp.this, ex.toString(), Toast.LENGTH_LONG); toast.show(); } } }); alertDialogBuilder.setPositiveButton(getString(R.string.msg_done), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mPrivacyListAdapter != null) mPrivacyListAdapter.notifyDataSetChanged(); } }); // Show dialog AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } super.onPostExecute(result); } } private class ApplicationsTask extends AsyncTask<Object, Object, Object> { private CharSequence[] mApp; private String[] mPackage; private boolean[] mSelection; @Override protected Object doInBackground(Object... params) { // Get applications int count = 0; Map<String, List<String>> mapApp = new HashMap<String, List<String>>(); for (ApplicationInfoEx appInfo : ApplicationInfoEx.getXApplicationList(ActivityApp.this, null)) for (int p = 0; p < appInfo.getPackageName().size(); p++) { String appName = appInfo.getApplicationName().get(p); List<String> listPkg; if (mapApp.containsKey(appName)) listPkg = mapApp.get(appName); else { listPkg = new ArrayList<String>(); mapApp.put(appName, listPkg); } listPkg.add(appInfo.getPackageName().get(p)); count++; } // Sort applications List<String> listApp = new ArrayList<String>(mapApp.keySet()); Collator collator = Collator.getInstance(Locale.getDefault()); Collections.sort(listApp, collator); // Build selection arrays int i = 0; mApp = new CharSequence[count]; mPackage = new String[count]; mSelection = new boolean[count]; for (String appName : listApp) { List<String> listPkg = mapApp.get(appName); Collections.sort(listPkg, collator); for (String pkgName : listPkg) { mApp[i] = (pkgName.equals(appName) ? appName : String.format("%s (%s)", appName, pkgName)); mPackage[i] = pkgName; mSelection[i] = PrivacyManager.getSettingBool(-mAppInfo.getUid(), Meta.cTypeApplication, pkgName, false); i++; } } return null; } @Override protected void onPostExecute(Object result) { if (!ActivityApp.this.isFinishing()) { // Build dialog AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this); alertDialogBuilder.setTitle(R.string.menu_applications); alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher)); alertDialogBuilder.setMultiChoiceItems(mApp, mSelection, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) { try { PrivacyManager.setSetting(mAppInfo.getUid(), Meta.cTypeApplication, mPackage[whichButton], Boolean.toString(isChecked)); } catch (Throwable ex) { Util.bug(null, ex); Toast toast = Toast.makeText(ActivityApp.this, ex.toString(), Toast.LENGTH_LONG); toast.show(); } } }); alertDialogBuilder.setPositiveButton(getString(R.string.msg_done), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mPrivacyListAdapter != null) mPrivacyListAdapter.notifyDataSetChanged(); } }); // Show dialog AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } super.onPostExecute(result); } } private class ContactsTask extends AsyncTask<Integer, Object, Object> { private List<CharSequence> mListContact; private long[] mIds; private boolean[] mSelection; @Override protected Object doInBackground(Integer... params) { // Map contacts Map<Long, String> mapContact = new LinkedHashMap<Long, String>(); Cursor cursor; if (params[0] < 0) cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID, Phone.DISPLAY_NAME }, null, null, Phone.DISPLAY_NAME); else cursor = getContentResolver() .query(ContactsContract.Data.CONTENT_URI, new String[] { ContactsContract.Contacts._ID, Phone.DISPLAY_NAME, GroupMembership.GROUP_ROW_ID }, GroupMembership.GROUP_ROW_ID + "= ?", new String[] { Integer.toString(params[0]) }, Phone.DISPLAY_NAME); if (cursor != null) try { while (cursor.moveToNext()) { long id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID)); String contact = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME)); if (contact != null) mapContact.put(id, contact); } } finally { cursor.close(); } // Build dialog data mListContact = new ArrayList<CharSequence>(); mIds = new long[mapContact.size() + 1]; mSelection = new boolean[mapContact.size() + 1]; mListContact.add("[" + getString(R.string.menu_all) + "]"); mIds[0] = -1; mSelection[0] = false; int i = 0; for (Long id : mapContact.keySet()) { mListContact.add(mapContact.get(id)); mIds[i + 1] = id; mSelection[i++ + 1] = PrivacyManager.getSettingBool(-mAppInfo.getUid(), Meta.cTypeContact, Long.toString(id), false); } return null; } @Override protected void onPostExecute(Object result) { if (!ActivityApp.this.isFinishing()) { // Build dialog AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityApp.this); alertDialogBuilder.setTitle(R.string.menu_contacts); alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher)); alertDialogBuilder.setMultiChoiceItems(mListContact.toArray(new CharSequence[0]), mSelection, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(final DialogInterface dialog, int whichButton, final boolean isChecked) { // Contact if (whichButton == 0) { ((AlertDialog) dialog).getListView().setEnabled(false); ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); ((AlertDialog) dialog).setCancelable(false); new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... arg0) { for (int i = 1; i < mSelection.length; i++) { mSelection[i] = isChecked; PrivacyManager.setSetting(mAppInfo.getUid(), Meta.cTypeContact, Long.toString(mIds[i]), Boolean.toString(mSelection[i])); } return null; } @Override protected void onPostExecute(Object result) { for (int i = 1; i < mSelection.length; i++) ((AlertDialog) dialog).getListView().setItemChecked(i, mSelection[i]); ((AlertDialog) dialog).getListView().setEnabled(true); ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled( true); ((AlertDialog) dialog).setCancelable(true); } }.executeOnExecutor(mExecutor); } else PrivacyManager.setSetting(mAppInfo.getUid(), Meta.cTypeContact, Long.toString(mIds[whichButton]), Boolean.toString(isChecked)); } }); alertDialogBuilder.setPositiveButton(getString(R.string.msg_done), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mPrivacyListAdapter != null) mPrivacyListAdapter.notifyDataSetChanged(); } }); // Show dialog AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } super.onPostExecute(result); } } // Adapters private class RestrictionAdapter extends BaseExpandableListAdapter { private Context mContext; private ApplicationInfoEx mAppInfo; private String mSelectedRestrictionName; private String mSelectedMethodName; private List<String> mListRestriction; private HashMap<Integer, List<Hook>> mHook; private Version mVersion; private LayoutInflater mInflater; public RestrictionAdapter(Context context, int resource, ApplicationInfoEx appInfo, String selectedRestrictionName, String selectedMethodName) { mContext = context; mAppInfo = appInfo; mSelectedRestrictionName = selectedRestrictionName; mSelectedMethodName = selectedMethodName; mListRestriction = new ArrayList<String>(); mHook = new LinkedHashMap<Integer, List<Hook>>(); mVersion = new Version(Util.getSelfVersionName(context)); mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); int userId = Util.getUserId(Process.myUid()); boolean fUsed = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUsed, false); boolean fPermission = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFPermission, false); for (String rRestrictionName : PrivacyManager.getRestrictions(mContext).values()) { boolean isUsed = (PrivacyManager.getUsage(mAppInfo.getUid(), rRestrictionName, null) > 0); boolean hasPermission = PrivacyManager.hasPermission(mContext, mAppInfo, rRestrictionName, mVersion); if (mSelectedRestrictionName != null || ((fUsed ? isUsed : true) && (fPermission ? isUsed || hasPermission : true))) mListRestriction.add(rRestrictionName); } } @Override public Object getGroup(int groupPosition) { return mListRestriction.get(groupPosition); } @Override public int getGroupCount() { return mListRestriction.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition * 1000; } private class GroupViewHolder { private View row; private int position; public ImageView imgIndicator; public ImageView imgUsed; public ImageView imgGranted; public ImageView imgInfo; public TextView tvName; public ImageView imgWhitelist; public ImageView imgCbRestricted; public ProgressBar pbRunning; public ImageView imgCbAsk; public LinearLayout llName; public GroupViewHolder(View theRow, int thePosition) { row = theRow; position = thePosition; imgIndicator = (ImageView) row.findViewById(R.id.imgIndicator); imgUsed = (ImageView) row.findViewById(R.id.imgUsed); imgGranted = (ImageView) row.findViewById(R.id.imgGranted); imgInfo = (ImageView) row.findViewById(R.id.imgInfo); tvName = (TextView) row.findViewById(R.id.tvName); imgWhitelist = (ImageView) row.findViewById(R.id.imgWhitelist); imgCbRestricted = (ImageView) row.findViewById(R.id.imgCbRestricted); pbRunning = (ProgressBar) row.findViewById(R.id.pbRunning); imgCbAsk = (ImageView) row.findViewById(R.id.imgCbAsk); llName = (LinearLayout) row.findViewById(R.id.llName); } } private class GroupHolderTask extends AsyncTask<Object, Object, Object> { private int position; private GroupViewHolder holder; private String restrictionName; private boolean used; private boolean permission; private RState rstate; private boolean ondemand; private boolean whitelist; private boolean enabled; private boolean can; private boolean methodExpert; public GroupHolderTask(int thePosition, GroupViewHolder theHolder, String theRestrictionName) { position = thePosition; holder = theHolder; restrictionName = theRestrictionName; } @Override protected Object doInBackground(Object... params) { if (restrictionName != null) { // Get info int userId = Util.getUserId(Process.myUid()); used = (PrivacyManager.getUsage(mAppInfo.getUid(), restrictionName, null) != 0); permission = PrivacyManager.hasPermission(mContext, mAppInfo, restrictionName, mVersion); rstate = new RState(mAppInfo.getUid(), restrictionName, null, mVersion); boolean isApp = PrivacyManager.isApplication(mAppInfo.getUid()); boolean odSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false); boolean gondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true); ondemand = ((isApp || odSystem) && gondemand); if (ondemand) ondemand = PrivacyManager.getSettingBool(-mAppInfo.getUid(), PrivacyManager.cSettingOnDemand, false); whitelist = false; String wName = null; if (PrivacyManager.cAccounts.equals(restrictionName)) wName = Meta.cTypeAccount; else if (PrivacyManager.cSystem.equals(restrictionName)) wName = Meta.cTypeApplication; else if (PrivacyManager.cContacts.equals(restrictionName)) wName = Meta.cTypeContact; if (wName != null) { boolean blacklist = PrivacyManager.getSettingBool(-mAppInfo.getUid(), PrivacyManager.cSettingBlacklist, false); if (blacklist) whitelist = true; else for (PSetting setting : PrivacyManager.getSettingList(mAppInfo.getUid(), wName)) if (Boolean.parseBoolean(setting.value)) { whitelist = true; break; } } if (!whitelist) for (Hook hook : PrivacyManager.getHooks(restrictionName, mVersion)) if (hook.whitelist() != null) if (PrivacyManager.getSettingList(mAppInfo.getUid(), hook.whitelist()).size() > 0) { whitelist = true; break; } enabled = PrivacyManager.getSettingBool(mAppInfo.getUid(), PrivacyManager.cSettingRestricted, true); can = PrivacyManager.canRestrict(rstate.mUid, Process.myUid(), rstate.mRestrictionName, null, true); methodExpert = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingMethodExpert, false); return holder; } return null; } @Override protected void onPostExecute(Object result) { if (holder.position == position && result != null) { // Set data holder.tvName.setTypeface(null, used ? Typeface.BOLD_ITALIC : Typeface.NORMAL); holder.imgUsed.setVisibility(used ? View.VISIBLE : View.INVISIBLE); holder.imgGranted.setVisibility(permission ? View.VISIBLE : View.INVISIBLE); // Show whitelist icon holder.imgWhitelist.setVisibility(whitelist ? View.VISIBLE : View.GONE); if (whitelist) holder.imgWhitelist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (PrivacyManager.cAccounts.equals(restrictionName)) optionAccounts(); else if (PrivacyManager.cSystem.equals(restrictionName)) optionApplications(); else if (PrivacyManager.cContacts.equals(restrictionName)) optionContacts(-1); } }); else holder.imgWhitelist.setClickable(false); // Display restriction holder.imgCbRestricted.setImageBitmap(getCheckBoxImage(rstate, methodExpert)); holder.imgCbRestricted.setVisibility(View.VISIBLE); if (ondemand) { holder.imgCbAsk.setImageBitmap(getAskBoxImage(rstate, methodExpert)); holder.imgCbAsk.setVisibility(View.VISIBLE); } else holder.imgCbAsk.setVisibility(View.GONE); // Check if can be restricted holder.llName.setEnabled(enabled && can); holder.tvName.setEnabled(enabled && can); holder.imgCbAsk.setEnabled(enabled && can); // Listen for restriction changes holder.llName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { holder.llName.setEnabled(false); holder.imgCbRestricted.setVisibility(View.GONE); holder.pbRunning.setVisibility(View.VISIBLE); new AsyncTask<Object, Object, Object>() { private List<Boolean> oldState; private List<Boolean> newState; @Override protected Object doInBackground(Object... arg0) { // Change restriction oldState = PrivacyManager.getRestartStates(mAppInfo.getUid(), restrictionName); rstate.toggleRestriction(); newState = PrivacyManager.getRestartStates(mAppInfo.getUid(), restrictionName); return null; } @Override protected void onPostExecute(Object result) { // Refresh display // Needed to update children notifyDataSetChanged(); // Notify restart if (!newState.equals(oldState)) Toast.makeText(mContext, getString(R.string.msg_restart), Toast.LENGTH_LONG) .show(); holder.pbRunning.setVisibility(View.GONE); holder.imgCbRestricted.setVisibility(View.VISIBLE); holder.llName.setEnabled(true); } }.executeOnExecutor(mExecutor); } }); // Listen for ask changes if (ondemand) holder.imgCbAsk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { holder.imgCbAsk.setVisibility(View.GONE); holder.pbRunning.setVisibility(View.VISIBLE); new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... arg0) { rstate.toggleAsked(); return null; } @Override protected void onPostExecute(Object result) { // Needed to update children notifyDataSetChanged(); holder.pbRunning.setVisibility(View.GONE); holder.imgCbAsk.setVisibility(View.VISIBLE); } }.executeOnExecutor(mExecutor); } }); else holder.imgCbAsk.setClickable(false); } } } @Override @SuppressLint("InflateParams") public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { GroupViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.restrictionentry, null); holder = new GroupViewHolder(convertView, groupPosition); convertView.setTag(holder); } else { holder = (GroupViewHolder) convertView.getTag(); holder.position = groupPosition; } // Get entry final String restrictionName = (String) getGroup(groupPosition); // Indicator state holder.imgIndicator.setImageResource(getThemed(isExpanded ? R.attr.icon_expander_maximized : R.attr.icon_expander_minimized)); // Disable indicator for empty groups if (getChildrenCount(groupPosition) == 0) holder.imgIndicator.setVisibility(View.INVISIBLE); else holder.imgIndicator.setVisibility(View.VISIBLE); // Display if used holder.tvName.setTypeface(null, Typeface.NORMAL); holder.imgUsed.setVisibility(View.INVISIBLE); // Check if permission holder.imgGranted.setVisibility(View.INVISIBLE); // Display localized name TreeMap<String, String> tmRestriction = PrivacyManager.getRestrictions(mContext); int index = new ArrayList<String>(tmRestriction.values()).indexOf(restrictionName); final String title = (String) tmRestriction.navigableKeySet().toArray()[index]; holder.tvName.setText(title); holder.imgWhitelist.setVisibility(View.GONE); // Display restriction holder.imgCbRestricted.setVisibility(View.INVISIBLE); holder.imgCbAsk.setVisibility(View.INVISIBLE); // Async update new GroupHolderTask(groupPosition, holder, restrictionName).executeOnExecutor(mExecutor, (Object) null); // Handle info holder.imgInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int stringId = getResources().getIdentifier("restrict_help_" + restrictionName, "string", getPackageName()); // Build dialog Dialog dlgHelp = new Dialog(mContext); dlgHelp.requestWindowFeature(Window.FEATURE_LEFT_ICON); dlgHelp.setTitle(title); dlgHelp.setContentView(R.layout.helpcat); dlgHelp.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, ActivityApp.this.getThemed(R.attr.icon_launcher)); dlgHelp.setCancelable(true); // Set info TextView tvInfo = (TextView) dlgHelp.findViewById(R.id.tvInfo); tvInfo.setText(stringId); dlgHelp.show(); } }); return convertView; } private List<Hook> getHooks(int groupPosition) { if (!mHook.containsKey(groupPosition)) { int userId = Util.getUserId(Process.myUid()); boolean fUsed = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUsed, false); boolean fPermission = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFPermission, false); List<Hook> listMethod = new ArrayList<Hook>(); String restrictionName = mListRestriction.get(groupPosition); for (Hook hook : PrivacyManager.getHooks((String) getGroup(groupPosition), mVersion)) { // Filter boolean isUsed = (PrivacyManager.getUsage(mAppInfo.getUid(), restrictionName, hook.getName()) > 0); boolean hasPermission = PrivacyManager.hasPermission(mContext, mAppInfo, hook); if (mSelectedMethodName != null || ((fUsed ? isUsed : true) && (fPermission ? isUsed || hasPermission : true))) listMethod.add(hook); } mHook.put(groupPosition, listMethod); } return mHook.get(groupPosition); } @Override public Object getChild(int groupPosition, int childPosition) { return getHooks(groupPosition).get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return groupPosition * 1000 + childPosition; } @Override public int getChildrenCount(int groupPosition) { return getHooks(groupPosition).size(); } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } private class ChildViewHolder { private View row; private int groupPosition; private int childPosition; public ImageView imgUsed; public ImageView imgGranted; public ImageView imgInfo; public TextView tvMethodName; public ImageView imgUnsafe; public ImageView imgMethodWhitelist; public ImageView imgCbMethodRestricted; public ProgressBar pbRunning; public ImageView imgCbMethodAsk; public LinearLayout llMethodName; private ChildViewHolder(View theRow, int gPosition, int cPosition) { row = theRow; groupPosition = gPosition; childPosition = cPosition; imgUsed = (ImageView) row.findViewById(R.id.imgUsed); imgGranted = (ImageView) row.findViewById(R.id.imgGranted); imgInfo = (ImageView) row.findViewById(R.id.imgInfo); tvMethodName = (TextView) row.findViewById(R.id.tvMethodName); imgUnsafe = (ImageView) row.findViewById(R.id.imgUnsafe); imgMethodWhitelist = (ImageView) row.findViewById(R.id.imgMethodWhitelist); imgCbMethodRestricted = (ImageView) row.findViewById(R.id.imgCbMethodRestricted); pbRunning = (ProgressBar) row.findViewById(R.id.pbRunning); imgCbMethodAsk = (ImageView) row.findViewById(R.id.imgCbMethodAsk); llMethodName = (LinearLayout) row.findViewById(R.id.llMethodName); } } private class ChildHolderTask extends AsyncTask<Object, Object, Object> { private int groupPosition; private int childPosition; private ChildViewHolder holder; private String restrictionName; private Hook md; private long lastUsage; private PRestriction parent; private boolean permission; private RState rstate; private boolean ondemand; private boolean whitelist; private boolean enabled; private boolean can; public ChildHolderTask(int gPosition, int cPosition, ChildViewHolder theHolder, String theRestrictionName) { groupPosition = gPosition; childPosition = cPosition; holder = theHolder; restrictionName = theRestrictionName; } @Override protected Object doInBackground(Object... params) { if (restrictionName != null) { // Get info int userId = Util.getUserId(Process.myUid()); md = (Hook) getChild(groupPosition, childPosition); lastUsage = PrivacyManager.getUsage(mAppInfo.getUid(), restrictionName, md.getName()); parent = PrivacyManager.getRestrictionEx(mAppInfo.getUid(), restrictionName, null); permission = PrivacyManager.hasPermission(mContext, mAppInfo, md); rstate = new RState(mAppInfo.getUid(), restrictionName, md.getName(), mVersion); boolean isApp = PrivacyManager.isApplication(mAppInfo.getUid()); boolean odSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false); boolean gondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true); ondemand = ((isApp || odSystem) && gondemand); if (ondemand) ondemand = PrivacyManager.getSettingBool(-mAppInfo.getUid(), PrivacyManager.cSettingOnDemand, false); if (md.whitelist() == null) whitelist = false; else whitelist = PrivacyManager.listWhitelisted(mAppInfo.getUid(), md.whitelist()).size() > 0; enabled = PrivacyManager.getSettingBool(mAppInfo.getUid(), PrivacyManager.cSettingRestricted, true); can = PrivacyManager.canRestrict(rstate.mUid, Process.myUid(), rstate.mRestrictionName, rstate.mMethodName, true); return holder; } return null; } @Override protected void onPostExecute(Object result) { if (holder.groupPosition == groupPosition && holder.childPosition == childPosition && result != null) { // Set data if (lastUsage > 0) { CharSequence sLastUsage = DateUtils.getRelativeTimeSpanString(lastUsage, new Date().getTime(), DateUtils.SECOND_IN_MILLIS, 0); holder.tvMethodName.setText(String.format("%s (%s)", md.getName(), sLastUsage)); } holder.llMethodName.setEnabled(parent.restricted); holder.tvMethodName.setEnabled(parent.restricted); holder.imgCbMethodAsk.setEnabled(!parent.asked); holder.imgUsed.setImageResource(getThemed(md.hasUsageData() && enabled && can ? R.attr.icon_used : R.attr.icon_used_grayed)); holder.imgUsed.setVisibility(lastUsage == 0 && md.hasUsageData() && enabled && can ? View.INVISIBLE : View.VISIBLE); holder.tvMethodName.setTypeface(null, lastUsage == 0 ? Typeface.NORMAL : Typeface.BOLD_ITALIC); holder.imgGranted.setVisibility(permission ? View.VISIBLE : View.INVISIBLE); // Show whitelist icon holder.imgMethodWhitelist.setVisibility(whitelist ? View.VISIBLE : View.INVISIBLE); if (whitelist) holder.imgMethodWhitelist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ActivityApp.this.optionWhitelists(md.whitelist()); } }); else holder.imgMethodWhitelist.setClickable(false); // Display restriction holder.imgCbMethodRestricted.setImageBitmap(getCheckBoxImage(rstate, true)); holder.imgCbMethodRestricted.setVisibility(View.VISIBLE); // Show asked state if (ondemand) { holder.imgCbMethodAsk.setImageBitmap(getAskBoxImage(rstate, true)); holder.imgCbMethodAsk.setVisibility(md.canOnDemand() ? View.VISIBLE : View.INVISIBLE); } else holder.imgCbMethodAsk.setVisibility(View.GONE); holder.llMethodName.setEnabled(enabled && can); holder.tvMethodName.setEnabled(enabled && can); holder.imgCbMethodAsk.setEnabled(enabled && can); // Listen for restriction changes if (parent.restricted) holder.llMethodName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { holder.llMethodName.setEnabled(false); holder.imgCbMethodRestricted.setVisibility(View.GONE); holder.pbRunning.setVisibility(View.VISIBLE); new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... arg0) { // Change restriction rstate.toggleRestriction(); return null; } @Override protected void onPostExecute(Object result) { // Refresh display // Needed to update parent notifyDataSetChanged(); // Notify restart if (md.isRestartRequired()) Toast.makeText(mContext, getString(R.string.msg_restart), Toast.LENGTH_LONG) .show(); holder.pbRunning.setVisibility(View.GONE); holder.imgCbMethodRestricted.setVisibility(View.VISIBLE); holder.llMethodName.setEnabled(true); } }.executeOnExecutor(mExecutor); } }); else holder.llMethodName.setClickable(false); // Listen for ask changes if (ondemand && !parent.asked) holder.imgCbMethodAsk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { holder.imgCbMethodAsk.setVisibility(View.GONE); holder.pbRunning.setVisibility(View.VISIBLE); new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... arg0) { rstate.toggleAsked(); return null; } @Override protected void onPostExecute(Object result) { // Needed to update parent notifyDataSetChanged(); holder.pbRunning.setVisibility(View.GONE); holder.imgCbMethodAsk.setVisibility(View.VISIBLE); } }.executeOnExecutor(mExecutor); } }); else holder.imgCbMethodAsk.setClickable(false); } } } @Override @SuppressLint("InflateParams") public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { ChildViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.restrictionchild, null); holder = new ChildViewHolder(convertView, groupPosition, childPosition); convertView.setTag(holder); } else { holder = (ChildViewHolder) convertView.getTag(); holder.groupPosition = groupPosition; holder.childPosition = childPosition; } // Get entry final String restrictionName = (String) getGroup(groupPosition); final Hook hook = (Hook) getChild(groupPosition, childPosition); // Set background color if (hook.isDangerous()) holder.row.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous))); else holder.row.setBackgroundColor(Color.TRANSPARENT); holder.llMethodName.setEnabled(false); holder.tvMethodName.setEnabled(false); holder.imgCbMethodAsk.setEnabled(false); // Display method name holder.tvMethodName.setText(hook.getName()); holder.tvMethodName.setTypeface(null, Typeface.NORMAL); // Display if used holder.imgUsed.setVisibility(View.INVISIBLE); // Hide if permissions holder.imgGranted.setVisibility(View.INVISIBLE); // Function help if (hook.getAnnotation() == null) holder.imgInfo.setVisibility(View.GONE); else { holder.imgInfo.setVisibility(View.VISIBLE); holder.imgInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { View parent = ActivityApp.this.findViewById(android.R.id.content); showHelp(ActivityApp.this, parent, hook); } }); } // Show if unsafe holder.imgUnsafe.setVisibility(hook != null && hook.isUnsafe() ? View.VISIBLE : View.INVISIBLE); // Hide whitelist icon holder.imgMethodWhitelist.setVisibility(View.INVISIBLE); // Display restriction holder.llMethodName.setClickable(false); holder.imgCbMethodRestricted.setVisibility(View.INVISIBLE); holder.imgCbMethodAsk.setVisibility(View.INVISIBLE); // Async update new ChildHolderTask(groupPosition, childPosition, holder, restrictionName).executeOnExecutor(mExecutor, (Object) null); return convertView; } @Override public boolean hasStableIds() { return true; } } @SuppressLint("InflateParams") public static void showHelp(ActivityBase context, View parent, Hook hook) { // Build dialog Dialog dlgHelp = new Dialog(context); dlgHelp.requestWindowFeature(Window.FEATURE_LEFT_ICON); dlgHelp.setTitle(R.string.app_name); dlgHelp.setContentView(R.layout.helpfunc); dlgHelp.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, context.getThemed(R.attr.icon_launcher)); dlgHelp.setCancelable(true); // Set title TextView tvTitle = (TextView) dlgHelp.findViewById(R.id.tvTitle); tvTitle.setText(hook.getName()); // Set info TextView tvInfo = (TextView) dlgHelp.findViewById(R.id.tvInfo); tvInfo.setText(Html.fromHtml(hook.getAnnotation())); tvInfo.setMovementMethod(LinkMovementMethod.getInstance()); // Set permissions String[] permissions = hook.getPermissions(); if (permissions != null && permissions.length > 0) if (!permissions[0].equals("")) { TextView tvPermissions = (TextView) dlgHelp.findViewById(R.id.tvPermissions); tvPermissions.setText(Html.fromHtml(TextUtils.join("<br />", permissions))); } dlgHelp.show(); } }
61,305
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
ActivitySettings.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/ActivitySettings.java
package biz.bokhorst.xprivacy; import java.io.File; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Environment; import android.os.Process; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class ActivitySettings extends ActivityBase implements OnCheckedChangeListener, OnClickListener { private int userId; private int uid; private boolean isApp; private boolean odSystem; private boolean expert; private CheckBox cbNotify; private CheckBox cbOnDemand; private CheckBox cbBlacklist; private CheckBox cbUsage; private CheckBox cbParameters; private CheckBox cbValues; private CheckBox cbLog; private CheckBox cbSystem; private CheckBox cbExperimental; private CheckBox cbHttps; private CheckBox cbAOSP; private EditText etConfidence; private EditText etQuirks; private Button btnFlush; private Button btnClearDb; private CheckBox cbRandom; private EditText etSerial; private EditText etLat; private EditText etLon; private EditText etAlt; private EditText etSearch; private EditText etMac; private EditText etIP; private EditText etImei; private EditText etPhone; private EditText etId; private EditText etGsfId; private EditText etAdId; private EditText etMcc; private EditText etMnc; private EditText etCountry; private EditText etOperator; private EditText etIccId; private EditText etCid; private EditText etLac; private EditText etSubscriber; private EditText etSSID; private EditText etUa; private CheckBox cbSerial; private CheckBox cbLat; private CheckBox cbLon; private CheckBox cbAlt; private CheckBox cbMac; private CheckBox cbImei; private CheckBox cbPhone; private CheckBox cbId; private CheckBox cbGsfId; private CheckBox cbAdId; private CheckBox cbCountry; private CheckBox cbSubscriber; private CheckBox cbSSID; public static final String ACTION_SETTINGS = "biz.bokhorst.xprivacy.action.SETTINGS"; public static final String cUid = "Uid"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings); setSupportActionBar((Toolbar) findViewById(R.id.widgetToolbar)); setTitle(R.string.menu_settings); userId = Util.getUserId(Process.myUid()); final Bundle extras = getIntent().getExtras(); if (extras != null && extras.containsKey(cUid)) uid = extras.getInt(cUid); else uid = userId; // Reference controls TextView tvInfo = (TextView) findViewById(R.id.tvInfo); cbNotify = (CheckBox) findViewById(R.id.cbNotify); cbOnDemand = (CheckBox) findViewById(R.id.cbOnDemand); cbBlacklist = (CheckBox) findViewById(R.id.cbBlacklist); cbUsage = (CheckBox) findViewById(R.id.cbUsage); cbParameters = (CheckBox) findViewById(R.id.cbParameters); cbValues = (CheckBox) findViewById(R.id.cbValues); cbLog = (CheckBox) findViewById(R.id.cbLog); CheckBox cbExpert = (CheckBox) findViewById(R.id.cbExpert); cbSystem = (CheckBox) findViewById(R.id.cbSystem); cbExperimental = (CheckBox) findViewById(R.id.cbExperimental); cbHttps = (CheckBox) findViewById(R.id.cbHttps); cbAOSP = (CheckBox) findViewById(R.id.cbAOSP); LinearLayout llConfidence = (LinearLayout) findViewById(R.id.llConfidence); etConfidence = (EditText) findViewById(R.id.etConfidence); etQuirks = (EditText) findViewById(R.id.etQuirks); btnFlush = (Button) findViewById(R.id.btnFlush); btnClearDb = (Button) findViewById(R.id.btnClearDb); cbRandom = (CheckBox) findViewById(R.id.cbRandom); Button btnRandom = (Button) findViewById(R.id.btnRandom); Button btnClear = (Button) findViewById(R.id.btnClear); etSerial = (EditText) findViewById(R.id.etSerial); etLat = (EditText) findViewById(R.id.etLat); etLon = (EditText) findViewById(R.id.etLon); etAlt = (EditText) findViewById(R.id.etAlt); etSearch = (EditText) findViewById(R.id.etSearch); Button btnSearch = (Button) findViewById(R.id.btnSearch); etMac = (EditText) findViewById(R.id.etMac); etIP = (EditText) findViewById(R.id.etIP); etImei = (EditText) findViewById(R.id.etImei); etPhone = (EditText) findViewById(R.id.etPhone); etId = (EditText) findViewById(R.id.etId); etGsfId = (EditText) findViewById(R.id.etGsfId); etAdId = (EditText) findViewById(R.id.etAdId); etMcc = (EditText) findViewById(R.id.etMcc); etMnc = (EditText) findViewById(R.id.etMnc); etCountry = (EditText) findViewById(R.id.etCountry); etOperator = (EditText) findViewById(R.id.etOperator); etIccId = (EditText) findViewById(R.id.etIccId); etCid = (EditText) findViewById(R.id.etCid); etLac = (EditText) findViewById(R.id.etLac); etSubscriber = (EditText) findViewById(R.id.etSubscriber); etSSID = (EditText) findViewById(R.id.etSSID); etUa = (EditText) findViewById(R.id.etUa); cbSerial = (CheckBox) findViewById(R.id.cbSerial); cbLat = (CheckBox) findViewById(R.id.cbLat); cbLon = (CheckBox) findViewById(R.id.cbLon); cbAlt = (CheckBox) findViewById(R.id.cbAlt); cbMac = (CheckBox) findViewById(R.id.cbMac); cbImei = (CheckBox) findViewById(R.id.cbImei); cbPhone = (CheckBox) findViewById(R.id.cbPhone); cbId = (CheckBox) findViewById(R.id.cbId); cbGsfId = (CheckBox) findViewById(R.id.cbGsfId); cbAdId = (CheckBox) findViewById(R.id.cbAdId); cbCountry = (CheckBox) findViewById(R.id.cbCountry); cbSubscriber = (CheckBox) findViewById(R.id.cbSubscriber); cbSSID = (CheckBox) findViewById(R.id.cbSSID); // Listen for changes cbParameters.setOnCheckedChangeListener(this); cbValues.setOnCheckedChangeListener(this); cbExpert.setOnCheckedChangeListener(this); cbSerial.setOnCheckedChangeListener(this); cbLat.setOnCheckedChangeListener(this); cbLon.setOnCheckedChangeListener(this); cbAlt.setOnCheckedChangeListener(this); cbMac.setOnCheckedChangeListener(this); cbImei.setOnCheckedChangeListener(this); cbPhone.setOnCheckedChangeListener(this); cbId.setOnCheckedChangeListener(this); cbGsfId.setOnCheckedChangeListener(this); cbAdId.setOnCheckedChangeListener(this); cbCountry.setOnCheckedChangeListener(this); cbSubscriber.setOnCheckedChangeListener(this); cbSSID.setOnCheckedChangeListener(this); // Get current values boolean usage = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingUsage, true); boolean parameters = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingParameters, false); boolean values = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingValues, false); boolean log = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingLog, false); boolean components = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingSystem, false); boolean experimental = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingExperimental, false); boolean https = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingHttps, true); boolean aosp = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingAOSPMode, false); String confidence = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingConfidence, ""); // Get quirks boolean freeze = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingFreeze, false); boolean resolve = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingResolve, false); boolean noresolve = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingNoResolve, false); boolean permman = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingPermMan, false); boolean iwall = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingIntentWall, false); boolean safemode = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingSafeMode, false); boolean test = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingTestVersions, false); boolean updates = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingUpdates, false); boolean odsystem = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemandSystem, false); boolean wnomod = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingWhitelistNoModify, false); boolean nousage = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingNoUsageData, false); List<String> listQuirks = new ArrayList<String>(); if (freeze) listQuirks.add("freeze"); if (resolve) listQuirks.add("resolve"); if (noresolve) listQuirks.add("noresolve"); if (permman) listQuirks.add("permman"); if (iwall) listQuirks.add("iwall"); if (safemode) listQuirks.add("safemode"); if (test) listQuirks.add("test"); if (updates) listQuirks.add("updates"); if (odsystem) listQuirks.add("odsystem"); if (wnomod) listQuirks.add("wnomod"); if (nousage) listQuirks.add("nousage"); Collections.sort(listQuirks); String quirks = TextUtils.join(",", listQuirks.toArray()); expert = (components || experimental || !https || aosp || !"".equals(confidence) || listQuirks.size() > 0); // Application specific boolean notify = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingNotify, true); boolean ondemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, uid == userId); boolean blacklist = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingBlacklist, false); boolean enabled = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingRestricted, true); // Common boolean random = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingRandom, false); String serial = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingSerial, ""); String lat = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingLatitude, ""); String lon = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingLongitude, ""); String alt = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingAltitude, ""); String mac = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingMac, ""); String imei = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingImei, ""); String phone = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingPhone, ""); String id = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingId, ""); String gsfid = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingGsfId, ""); String adid = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingAdId, ""); String country = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingCountry, ""); String subscriber = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingSubscriber, ""); String ssid = PrivacyManager.getSetting(-uid, PrivacyManager.cSettingSSID, ""); // Set current values if (uid == userId) { // Global settings tvInfo.setVisibility(View.GONE); cbUsage.setChecked(usage); cbParameters.setChecked(parameters); cbValues.setChecked(values); if (userId == 0) cbLog.setChecked(log); else { cbLog.setVisibility(View.GONE); btnFlush.setVisibility(View.GONE); btnClearDb.setVisibility(View.GONE); } cbExpert.setChecked(expert); if (PrivacyManager.cVersion3 && (!Util.isSELinuxEnforced() || "true".equals(Util.getXOption("ignoreselinux")))) cbAOSP.setVisibility(View.VISIBLE); if (expert) { cbSystem.setChecked(components); cbExperimental.setChecked(experimental); cbHttps.setChecked(https); cbAOSP.setChecked(aosp); etConfidence.setText(confidence); etQuirks.setText(quirks); } else { cbSystem.setEnabled(false); cbExperimental.setEnabled(false); cbHttps.setEnabled(false); cbHttps.setChecked(true); cbAOSP.setEnabled(false); cbAOSP.setChecked(false); etConfidence.setEnabled(false); etQuirks.setEnabled(false); btnFlush.setEnabled(false); btnClearDb.setEnabled(false); } } else { // Display application names ApplicationInfoEx appInfo = new ApplicationInfoEx(this, uid); getSupportActionBar().setSubtitle(TextUtils.join(", ", appInfo.getApplicationName())); // Disable global settings cbUsage.setVisibility(View.GONE); cbParameters.setVisibility(View.GONE); cbValues.setVisibility(View.GONE); cbLog.setVisibility(View.GONE); cbSystem.setVisibility(View.GONE); cbExperimental.setVisibility(View.GONE); cbHttps.setVisibility(View.GONE); cbAOSP.setVisibility(View.GONE); llConfidence.setVisibility(View.GONE); btnFlush.setVisibility(View.GONE); btnClearDb.setVisibility(View.GONE); cbExpert.setChecked(expert); if (expert) etQuirks.setText(quirks); else etQuirks.setEnabled(false); } boolean gnotify = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingNotify, true); if (uid == userId || gnotify) cbNotify.setChecked(notify); else cbNotify.setVisibility(View.GONE); isApp = PrivacyManager.isApplication(uid); odSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false); boolean gondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true); if (uid == userId || ((isApp || odSystem) && gondemand)) { cbOnDemand.setChecked(ondemand); cbOnDemand.setEnabled(enabled); } else cbOnDemand.setVisibility(View.GONE); String blFileName = Environment.getExternalStorageDirectory().getPath() + "/.xprivacy/blacklist"; if (uid == userId || !new File(blFileName).exists()) cbBlacklist.setVisibility(View.GONE); else cbBlacklist.setChecked(blacklist); // Common cbRandom.setChecked(random); // Set randomize on access check boxes cbSerial.setChecked(serial.equals(PrivacyManager.cValueRandom)); cbLat.setChecked(lat.equals(PrivacyManager.cValueRandom)); cbLon.setChecked(lon.equals(PrivacyManager.cValueRandom)); cbAlt.setChecked(alt.equals(PrivacyManager.cValueRandom)); cbMac.setChecked(mac.equals(PrivacyManager.cValueRandom)); cbImei.setChecked(imei.equals(PrivacyManager.cValueRandom)); cbPhone.setChecked(phone.equals(PrivacyManager.cValueRandom)); cbId.setChecked(id.equals(PrivacyManager.cValueRandom)); cbGsfId.setChecked(gsfid.equals(PrivacyManager.cValueRandom)); cbAdId.setChecked(adid.equals(PrivacyManager.cValueRandom)); cbCountry.setChecked(country.equals(PrivacyManager.cValueRandom)); cbSubscriber.setChecked(subscriber.equals(PrivacyManager.cValueRandom)); cbSSID.setChecked(ssid.equals(PrivacyManager.cValueRandom)); // Set fake values etSerial.setText(cbSerial.isChecked() ? "" : serial); etLat.setText(cbLat.isChecked() ? "" : lat); etLon.setText(cbLon.isChecked() ? "" : lon); etAlt.setText(cbAlt.isChecked() ? "" : alt); etMac.setText(cbMac.isChecked() ? "" : mac); etImei.setText(cbImei.isChecked() ? "" : imei); etPhone.setText(cbPhone.isChecked() ? "" : phone); etId.setText(cbId.isChecked() ? "" : id); etGsfId.setText(cbGsfId.isChecked() ? "" : gsfid); etAdId.setText(cbAdId.isChecked() ? "" : adid); etCountry.setText(cbCountry.isChecked() ? "" : country); etSubscriber.setText(cbSubscriber.isChecked() ? "" : subscriber); etSSID.setText(cbSSID.isChecked() ? "" : ssid); etSerial.setEnabled(!cbSerial.isChecked()); etLat.setEnabled(!cbLat.isChecked()); etLon.setEnabled(!cbLon.isChecked()); etAlt.setEnabled(!cbAlt.isChecked()); etSearch.setEnabled(Geocoder.isPresent()); btnSearch.setEnabled(Geocoder.isPresent()); etMac.setEnabled(!cbMac.isChecked()); etImei.setEnabled(!cbImei.isChecked()); etPhone.setEnabled(!cbPhone.isChecked()); etId.setEnabled(!cbId.isChecked()); etGsfId.setEnabled(!cbGsfId.isChecked()); etAdId.setEnabled(!cbAdId.isChecked()); etCountry.setEnabled(!cbCountry.isChecked()); etSubscriber.setEnabled(!cbSubscriber.isChecked()); etSSID.setEnabled(!cbSSID.isChecked()); etIP.setText(PrivacyManager.getSetting(-uid, PrivacyManager.cSettingIP, "")); etMcc.setText(PrivacyManager.getSetting(-uid, PrivacyManager.cSettingMcc, "")); etMnc.setText(PrivacyManager.getSetting(-uid, PrivacyManager.cSettingMnc, "")); etOperator.setText(PrivacyManager.getSetting(-uid, PrivacyManager.cSettingOperator, "")); etIccId.setText(PrivacyManager.getSetting(-uid, PrivacyManager.cSettingIccId, "")); etCid.setText(PrivacyManager.getSetting(-uid, PrivacyManager.cSettingCid, "")); etLac.setText(PrivacyManager.getSetting(-uid, PrivacyManager.cSettingLac, "")); etUa.setText(PrivacyManager.getSetting(-uid, PrivacyManager.cSettingUa, "")); btnFlush.setOnClickListener(this); btnClearDb.setOnClickListener(this); btnRandom.setOnClickListener(this); btnClear.setOnClickListener(this); btnSearch.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); if (inflater != null && PrivacyService.checkClient()) { inflater.inflate(R.menu.settings, menu); return true; } else return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_cancel: finish(); return true; case R.id.menu_save: optionSave(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { switch (buttonView.getId()) { case R.id.cbParameters: case R.id.cbValues: if (isChecked && Util.hasProLicense(this) == null) { buttonView.setChecked(false); Util.viewUri(this, ActivityMain.cProUri); } break; case R.id.cbExpert: cbSystem.setEnabled(isChecked); cbExperimental.setEnabled(isChecked); cbHttps.setEnabled(isChecked); cbAOSP.setEnabled(isChecked); etConfidence.setEnabled(isChecked); etQuirks.setEnabled(isChecked); btnFlush.setEnabled(isChecked); btnClearDb.setEnabled(isChecked); if (isChecked) { if (!expert) Toast.makeText(this, getString(R.string.msg_expert), Toast.LENGTH_LONG).show(); } else { cbSystem.setChecked(false); cbExperimental.setChecked(false); cbHttps.setChecked(true); cbAOSP.setChecked(false); etConfidence.setText(""); etQuirks.setText(""); } break; case R.id.cbSerial: etSerial.setEnabled(!isChecked); break; case R.id.cbLat: etLat.setEnabled(!isChecked); break; case R.id.cbLon: etLon.setEnabled(!isChecked); break; case R.id.cbAlt: etAlt.setEnabled(!isChecked); break; case R.id.cbMac: etMac.setEnabled(!isChecked); break; case R.id.cbImei: etImei.setEnabled(!isChecked); break; case R.id.cbPhone: etPhone.setEnabled(!isChecked); break; case R.id.cbId: etId.setEnabled(!isChecked); break; case R.id.cbGsfId: etGsfId.setEnabled(!isChecked); break; case R.id.cbAdId: etAdId.setEnabled(!isChecked); break; case R.id.cbCountry: etCountry.setEnabled(!isChecked); break; case R.id.cbSubscriber: etSubscriber.setEnabled(!isChecked); break; case R.id.cbSSID: etSSID.setEnabled(!isChecked); break; } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnFlush: flush(); break; case R.id.btnClearDb: clearDB(); break; case R.id.btnRandom: randomize(); break; case R.id.btnClear: clear(); break; case R.id.btnSearch: search(); break; } } private void clearDB() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivitySettings.this); alertDialogBuilder.setTitle(R.string.menu_clear_db); alertDialogBuilder.setMessage(R.string.msg_sure); alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { PrivacyManager.clear(); Toast.makeText(ActivitySettings.this, getString(R.string.msg_reboot), Toast.LENGTH_LONG).show(); finish(); // Refresh main UI Intent intent = new Intent(ActivitySettings.this, ActivityMain.class); intent.putExtra(ActivityMain.cAction, ActivityMain.cActionRefresh); startActivity(intent); } }); alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } private void randomize() { etSerial.setText(PrivacyManager.getRandomProp("SERIAL")); etLat.setText(PrivacyManager.getRandomProp("LAT")); etLon.setText(PrivacyManager.getRandomProp("LON")); etAlt.setText(PrivacyManager.getRandomProp("ALT")); etMac.setText(PrivacyManager.getRandomProp("MAC")); etImei.setText(PrivacyManager.getRandomProp("IMEI")); etPhone.setText(PrivacyManager.getRandomProp("PHONE")); etId.setText(PrivacyManager.getRandomProp("ANDROID_ID")); etGsfId.setText(PrivacyManager.getRandomProp("GSF_ID")); etAdId.setText(PrivacyManager.getRandomProp("AdvertisingId")); etCountry.setText(PrivacyManager.getRandomProp("ISO3166")); etSubscriber.setText(PrivacyManager.getRandomProp("SubscriberId")); etSSID.setText(PrivacyManager.getRandomProp("SSID")); } private void clear() { final EditText[] edits = new EditText[] { etSerial, etLat, etLon, etAlt, etMac, etIP, etImei, etPhone, etId, etGsfId, etAdId, etMcc, etMnc, etCountry, etOperator, etIccId, etCid, etLac, etSubscriber, etSSID, etUa }; final CheckBox[] boxes = new CheckBox[] { cbSerial, cbLat, cbLon, cbAlt, cbMac, cbImei, cbPhone, cbId, cbGsfId, cbAdId, cbCountry, cbSubscriber, cbSSID }; for (EditText edit : edits) edit.setText(""); etSearch.setText(""); for (CheckBox box : boxes) box.setChecked(false); } private void search() { try { String search = etSearch.getText().toString(); final List<Address> listAddress = new Geocoder(ActivitySettings.this).getFromLocationName(search, 1); if (listAddress.size() > 0) { Address address = listAddress.get(0); // Get coordinates if (address.hasLatitude()) { cbLat.setChecked(false); etLat.setText(Double.toString(address.getLatitude())); } if (address.hasLongitude()) { cbLon.setChecked(false); etLon.setText(Double.toString(address.getLongitude())); } // Get address StringBuilder sb = new StringBuilder(); for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) { if (i != 0) sb.append(", "); sb.append(address.getAddressLine(i)); } etSearch.setText(sb.toString()); } } catch (Throwable ex) { Toast.makeText(ActivitySettings.this, ex.getMessage(), Toast.LENGTH_LONG).show(); } } private void flush() { Intent flushIntent = new Intent(UpdateService.cFlush); flushIntent.setPackage(getPackageName()); startService(flushIntent); Toast.makeText(ActivitySettings.this, getString(R.string.msg_done), Toast.LENGTH_LONG).show(); } @SuppressLint("DefaultLocale") private void optionSave() { if (uid == userId) { // Global settings PrivacyManager.setSetting(uid, PrivacyManager.cSettingUsage, Boolean.toString(cbUsage.isChecked())); PrivacyManager.setSetting(uid, PrivacyManager.cSettingParameters, Boolean.toString(cbParameters.isChecked())); PrivacyManager.setSetting(uid, PrivacyManager.cSettingValues, Boolean.toString(cbValues.isChecked())); if (userId == 0) PrivacyManager.setSetting(uid, PrivacyManager.cSettingLog, Boolean.toString(cbLog.isChecked())); PrivacyManager.setSetting(uid, PrivacyManager.cSettingSystem, Boolean.toString(cbSystem.isChecked())); PrivacyManager.setSetting(uid, PrivacyManager.cSettingExperimental, Boolean.toString(cbExperimental.isChecked())); PrivacyManager.setSetting(uid, PrivacyManager.cSettingHttps, Boolean.toString(cbHttps.isChecked())); PrivacyManager.setSetting(uid, PrivacyManager.cSettingAOSPMode, Boolean.toString(cbAOSP.isChecked())); PrivacyManager.setSetting(uid, PrivacyManager.cSettingConfidence, etConfidence.getText().toString()); } // Quirks List<String> listQuirks = Arrays .asList(etQuirks.getText().toString().toLowerCase().replace(" ", "").split(",")); PrivacyManager.setSetting(uid, PrivacyManager.cSettingFreeze, Boolean.toString(listQuirks.contains("freeze"))); PrivacyManager .setSetting(uid, PrivacyManager.cSettingResolve, Boolean.toString(listQuirks.contains("resolve"))); PrivacyManager.setSetting(uid, PrivacyManager.cSettingNoResolve, Boolean.toString(listQuirks.contains("noresolve"))); PrivacyManager .setSetting(uid, PrivacyManager.cSettingPermMan, Boolean.toString(listQuirks.contains("permman"))); PrivacyManager.setSetting(uid, PrivacyManager.cSettingIntentWall, Boolean.toString(listQuirks.contains("iwall"))); PrivacyManager.setSetting(uid, PrivacyManager.cSettingSafeMode, Boolean.toString(listQuirks.contains("safemode"))); PrivacyManager.setSetting(uid, PrivacyManager.cSettingTestVersions, Boolean.toString(listQuirks.contains("test"))); PrivacyManager .setSetting(uid, PrivacyManager.cSettingUpdates, Boolean.toString(listQuirks.contains("updates"))); PrivacyManager.setSetting(uid, PrivacyManager.cSettingOnDemandSystem, Boolean.toString(listQuirks.contains("odsystem"))); PrivacyManager.setSetting(uid, PrivacyManager.cSettingWhitelistNoModify, Boolean.toString(listQuirks.contains("wnomod"))); PrivacyManager.setSetting(uid, PrivacyManager.cSettingNoUsageData, Boolean.toString(listQuirks.contains("nousage"))); // Notifications PrivacyManager.setSetting(uid, PrivacyManager.cSettingNotify, Boolean.toString(cbNotify.isChecked())); // On demand restricting if (uid == userId || (isApp || odSystem)) PrivacyManager.setSetting(uid, PrivacyManager.cSettingOnDemand, Boolean.toString(cbOnDemand.isChecked())); if (uid != userId) PrivacyManager.setSetting(uid, PrivacyManager.cSettingBlacklist, Boolean.toString(cbBlacklist.isChecked())); // Random at boot PrivacyManager.setSetting(uid, PrivacyManager.cSettingRandom, cbRandom.isChecked() ? Boolean.toString(true) : null); // Serial# PrivacyManager.setSetting(uid, PrivacyManager.cSettingSerial, getValue(cbSerial, etSerial)); // Set latitude if (cbLat.isChecked()) PrivacyManager.setSetting(uid, PrivacyManager.cSettingLatitude, PrivacyManager.cValueRandom); else try { float lat = Float.parseFloat(etLat.getText().toString().replace(',', '.')); if (lat < -90 || lat > 90) throw new InvalidParameterException(); PrivacyManager.setSetting(uid, PrivacyManager.cSettingLatitude, Float.toString(lat)); } catch (Throwable ignored) { PrivacyManager.setSetting(uid, PrivacyManager.cSettingLatitude, null); } // Set longitude if (cbLon.isChecked()) PrivacyManager.setSetting(uid, PrivacyManager.cSettingLongitude, PrivacyManager.cValueRandom); else try { float lon = Float.parseFloat(etLon.getText().toString().replace(',', '.')); if (lon < -180 || lon > 180) throw new InvalidParameterException(); PrivacyManager.setSetting(uid, PrivacyManager.cSettingLongitude, Float.toString(lon)); } catch (Throwable ignored) { PrivacyManager.setSetting(uid, PrivacyManager.cSettingLongitude, null); } // Set altitude if (cbAlt.isChecked()) PrivacyManager.setSetting(uid, PrivacyManager.cSettingAltitude, PrivacyManager.cValueRandom); else try { float alt = Float.parseFloat(etAlt.getText().toString().replace(',', '.')); if (alt < -10000 || alt > 10000) throw new InvalidParameterException(); PrivacyManager.setSetting(uid, PrivacyManager.cSettingAltitude, Float.toString(alt)); } catch (Throwable ignored) { PrivacyManager.setSetting(uid, PrivacyManager.cSettingAltitude, null); } // Check Gsf ID try { String value = etGsfId.getText().toString(); if (!"".equals(value)) Long.parseLong(value.toLowerCase(), 16); } catch (NumberFormatException ignored) { etGsfId.setText(""); } // Other settings PrivacyManager.setSetting(uid, PrivacyManager.cSettingMac, getValue(cbMac, etMac)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingIP, getValue(null, etIP)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingImei, getValue(cbImei, etImei)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingPhone, getValue(cbPhone, etPhone)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingId, getValue(cbId, etId)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingGsfId, getValue(cbGsfId, etGsfId)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingAdId, getValue(cbAdId, etAdId)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingMcc, getValue(null, etMcc)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingMnc, getValue(null, etMnc)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingCountry, getValue(cbCountry, etCountry)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingOperator, getValue(null, etOperator)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingIccId, getValue(null, etIccId)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingCid, getValue(null, etCid)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingLac, getValue(null, etLac)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingSubscriber, getValue(cbSubscriber, etSubscriber)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingSSID, getValue(cbSSID, etSSID)); PrivacyManager.setSetting(uid, PrivacyManager.cSettingUa, getValue(null, etUa)); finish(); // Refresh view if (uid == userId) { Intent intent = new Intent(ActivitySettings.this, ActivityMain.class); startActivity(intent); } else { Intent intent = new Intent(ActivitySettings.this, ActivityApp.class); intent.putExtra(ActivityApp.cUid, uid); intent.putExtra(ActivityApp.cAction, ActivityApp.cActionRefresh); startActivity(intent); } } private static String getValue(CheckBox check, EditText edit) { if (check != null && check.isChecked()) return PrivacyManager.cValueRandom; String value = edit.getText().toString().trim(); return ("".equals(value) ? null : value); } }
30,730
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XAccountManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XAccountManager.java
package biz.bokhorst.xprivacy; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.TimeUnit; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorDescription; import android.accounts.AuthenticatorException; import android.accounts.OnAccountsUpdateListener; import android.accounts.OperationCanceledException; import android.os.Binder; import android.os.Bundle; import android.util.Log; public class XAccountManager extends XHook { private Methods mMethod; private String mClassName; private static final String cClassName = "android.accounts.AccountManager"; private static final Map<OnAccountsUpdateListener, XOnAccountsUpdateListener> mListener = new WeakHashMap<OnAccountsUpdateListener, XOnAccountsUpdateListener>(); private XAccountManager(Methods method, String restrictionName) { super(restrictionName, method.name().replace("Srv_", ""), method.name()); mMethod = method; mClassName = "com.android.server.accounts.AccountManagerService"; } private XAccountManager(Methods method, String restrictionName, String className) { super(restrictionName, method.name(), null); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // public void addOnAccountsUpdatedListener(final OnAccountsUpdateListener listener, Handler handler, boolean updateImmediately) // public String blockingGetAuthToken(Account account, String authTokenType, boolean notifyAuthFailure) // public Account[] getAccounts() // public Account[] getAccountsByType(String type) // public Account[] getAccountsByTypeForPackage(String type, String packageName) // public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(final String type, final String[] features, AccountManagerCallback<Account[]> callback, Handler handler) // public AuthenticatorDescription[] getAuthenticatorTypes() // public AccountManagerFuture<Bundle> getAuthToken(final Account account, final String authTokenType, final Bundle options, final Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) // public AccountManagerFuture<Bundle> getAuthToken(final Account account, final String authTokenType, final boolean notifyAuthFailure, AccountManagerCallback<Bundle> callback, Handler handler) // public AccountManagerFuture<Bundle> getAuthToken(final Account account, final String authTokenType, final Bundle options, final boolean notifyAuthFailure, AccountManagerCallback<Bundle> callback, Handler handler) // public AccountManagerFuture<Bundle> getAuthTokenByFeatures(final String accountType, final String authTokenType, final String[] features, final Activity activity, final Bundle addAccountOptions, final Bundle getAuthTokenOptions, final AccountManagerCallback<Bundle> callback, final Handler handler) // public AccountManagerFuture<Boolean> hasFeatures(final Account account, final String[] features, AccountManagerCallback<Boolean> callback, Handler handler) // public void removeOnAccountsUpdatedListener(OnAccountsUpdateListener listener) // frameworks/base/core/java/android/accounts/AccountManager.java // http://developer.android.com/reference/android/accounts/AccountManager.html // @formatter:on // @formatter:off // public android.accounts.Account[] getAccounts(java.lang.String accountType) throws android.os.RemoteException; // public android.accounts.Account[] getAccountsAsUser(java.lang.String accountType, int userId) throws android.os.RemoteException; // public void getAccountsByFeatures(android.accounts.IAccountManagerResponse response, java.lang.String accountType, java.lang.String[] features) throws android.os.RemoteException; // public android.accounts.Account[] getAccountsForPackage(java.lang.String packageName, int uid) // public android.accounts.Account[] getSharedAccountsAsUser(int userId) throws android.os.RemoteException; // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.2_r1/com/android/server/accounts/AccountManagerService.java // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/android/accounts/IAccountManager.java // @formatter:on // @formatter:off private enum Methods { addOnAccountsUpdatedListener, blockingGetAuthToken, getAccounts, getAccountsByType, getAccountsByTypeForPackage, getAccountsByTypeAndFeatures, getAuthenticatorTypes, getAuthToken, getAuthTokenByFeatures, hasFeatures, removeOnAccountsUpdatedListener, Srv_getAccounts, Srv_getAccountsAsUser, Srv_getAccountsByFeatures, Srv_getAccountsForPackage, Srv_getSharedAccountsAsUser }; // @formatter:on public static List<XHook> getInstances(String className, boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (!cClassName.equals(className)) { if (className == null) className = cClassName; if (server) { listHook.add(new XAccountManager(Methods.Srv_getAccounts, PrivacyManager.cAccounts)); listHook.add(new XAccountManager(Methods.Srv_getAccountsAsUser, PrivacyManager.cAccounts)); listHook.add(new XAccountManager(Methods.Srv_getAccountsByFeatures, PrivacyManager.cAccounts)); listHook.add(new XAccountManager(Methods.Srv_getAccountsForPackage, PrivacyManager.cAccounts)); listHook.add(new XAccountManager(Methods.Srv_getSharedAccountsAsUser, PrivacyManager.cAccounts)); } else { listHook.add(new XAccountManager(Methods.addOnAccountsUpdatedListener, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.blockingGetAuthToken, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.getAccounts, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.getAccountsByType, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.getAccountsByTypeForPackage, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.getAccountsByTypeAndFeatures, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.getAuthenticatorTypes, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.getAuthToken, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.getAuthTokenByFeatures, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.hasFeatures, PrivacyManager.cAccounts, className)); listHook.add(new XAccountManager(Methods.removeOnAccountsUpdatedListener, null, className)); } } return listHook; } @Override @SuppressWarnings("unchecked") protected void before(XParam param) throws Throwable { switch (mMethod) { case addOnAccountsUpdatedListener: if (param.args.length > 0 && param.args[0] != null) if (isRestricted(param)) { int uid = Binder.getCallingUid(); OnAccountsUpdateListener listener = (OnAccountsUpdateListener) param.args[0]; XOnAccountsUpdateListener xListener; synchronized (mListener) { xListener = mListener.get(listener); if (xListener == null) { xListener = new XOnAccountsUpdateListener(listener, uid); mListener.put(listener, xListener); Util.log(this, Log.WARN, "Added count=" + mListener.size() + " uid=" + uid); } } param.args[0] = xListener; } break; case blockingGetAuthToken: case getAccounts: case getAccountsByType: case getAccountsByTypeForPackage: // Do nothing break; case getAccountsByTypeAndFeatures: if (param.args.length > 2 && param.args[2] != null) if (isRestrictedExtra(param, (String) param.args[0])) { AccountManagerCallback<Account[]> callback = (AccountManagerCallback<Account[]>) param.args[2]; param.args[2] = new XAccountManagerCallbackAccount(callback, Binder.getCallingUid()); } break; case getAuthenticatorTypes: // Do nothing break; case getAuthToken: if (param.args.length > 0) { Account account = (Account) param.args[0]; for (int i = 1; i < param.args.length; i++) if (param.args[i] instanceof AccountManagerCallback<?>) if (isRestrictedExtra(param, account == null ? null : account.name)) { AccountManagerCallback<Bundle> callback = (AccountManagerCallback<Bundle>) param.args[i]; param.args[i] = new XAccountManagerCallbackBundle(callback, Binder.getCallingUid()); } } break; case getAuthTokenByFeatures: if (param.args.length > 0) for (int i = 1; i < param.args.length; i++) if (param.args[i] instanceof AccountManagerCallback<?>) if (isRestrictedExtra(param, (String) param.args[0])) { AccountManagerCallback<Bundle> callback = (AccountManagerCallback<Bundle>) param.args[i]; param.args[i] = new XAccountManagerCallbackBundle(callback, Binder.getCallingUid()); } break; case hasFeatures: if (param.args.length > 0) { Account account = (Account) param.args[0]; for (int i = 1; i < param.args.length; i++) if (param.args[i] instanceof AccountManagerCallback<?>) if (isRestrictedExtra(param, account == null ? null : account.name)) { AccountManagerCallback<Boolean> callback = (AccountManagerCallback<Boolean>) param.args[i]; param.args[i] = new XAccountManagerCallbackBoolean(callback); } } break; case removeOnAccountsUpdatedListener: if (param.args.length > 0 && param.args[0] != null) synchronized (mListener) { OnAccountsUpdateListener listener = (OnAccountsUpdateListener) param.args[0]; XOnAccountsUpdateListener xListener = mListener.get(listener); if (xListener != null) { param.args[0] = xListener; Util.log(this, Log.WARN, "Removed count=" + mListener.size() + " uid=" + Binder.getCallingUid()); } } break; case Srv_getAccounts: case Srv_getAccountsAsUser: case Srv_getAccountsForPackage: // Do nothing break; case Srv_getAccountsByFeatures: if (param.args.length > 1 && (param.args[1] == null || param.args[1] instanceof String)) { if (isRestrictedExtra(param, (String) param.args[1])) param.setResult(null); } else { if (isRestricted(param)) param.setResult(null); } break; case Srv_getSharedAccountsAsUser: // Do nothing break; } } @Override @SuppressWarnings("unchecked") protected void after(XParam param) throws Throwable { int uid = Binder.getCallingUid(); switch (mMethod) { case addOnAccountsUpdatedListener: // Do nothing break; case blockingGetAuthToken: if (param.getResult() != null && param.args.length > 0 && param.args[0] != null) { Account account = (Account) param.args[0]; if (isRestrictedExtra(param, account == null ? null : account.name)) if (!isAccountAllowed(account, uid)) param.setResult(null); } break; case getAccounts: if (param.getResult() != null && isRestricted(param)) { Account[] accounts = (Account[]) param.getResult(); param.setResult(filterAccounts(accounts, uid)); } break; case getAccountsByType: case getAccountsByTypeForPackage: if (param.getResult() != null && param.args.length > 0) if (isRestrictedExtra(param, (String) param.args[0])) { Account[] accounts = (Account[]) param.getResult(); param.setResult(filterAccounts(accounts, uid)); } break; case getAccountsByTypeAndFeatures: if (param.getResult() != null && param.args.length > 0) if (isRestrictedExtra(param, (String) param.args[0])) { AccountManagerFuture<Account[]> future = (AccountManagerFuture<Account[]>) param.getResult(); param.setResult(new XFutureAccount(future, uid)); } break; case getAuthenticatorTypes: if (param.getResult() != null && isRestricted(param)) param.setResult(new AuthenticatorDescription[0]); break; case getAuthToken: if (param.getResult() != null && param.args.length > 0) { Account account = (Account) param.args[0]; if (isRestrictedExtra(param, account == null ? null : account.name)) { AccountManagerFuture<Bundle> future = (AccountManagerFuture<Bundle>) param.getResult(); param.setResult(new XFutureBundle(future, uid)); } } break; case getAuthTokenByFeatures: if (param.getResult() != null) if (isRestrictedExtra(param, (String) param.args[0])) { AccountManagerFuture<Bundle> future = (AccountManagerFuture<Bundle>) param.getResult(); param.setResult(new XFutureBundle(future, uid)); } break; case hasFeatures: if (param.getResult() != null && param.args.length > 0 && param.args[0] != null) { Account account = (Account) param.args[0]; if (isRestrictedExtra(param, account == null ? null : account.name)) if (!isAccountAllowed(account, uid)) param.setResult(new XFutureBoolean()); } break; case removeOnAccountsUpdatedListener: // Do nothing break; case Srv_getAccounts: case Srv_getAccountsAsUser: case Srv_getAccountsForPackage: case Srv_getSharedAccountsAsUser: // Filter account list String extra = null; if (mMethod == Methods.Srv_getAccounts || mMethod == Methods.Srv_getAccountsAsUser || mMethod == Methods.Srv_getAccountsForPackage) if (param.args.length > 0 && param.args[0] instanceof String) extra = (String) param.args[0]; if (param.getResult() instanceof Account[]) if (isRestrictedExtra(param, extra)) { Account[] accounts = (Account[]) param.getResult(); param.setResult(filterAccounts(accounts, uid)); } break; case Srv_getAccountsByFeatures: // Do nothing break; } } private Account[] filterAccounts(Account[] original, int uid) { List<Account> listAccount = new ArrayList<Account>(); for (Account account : original) if (isAccountAllowed(account, uid)) listAccount.add(account); return listAccount.toArray(new Account[0]); } public static boolean isAccountAllowed(Account account, int uid) { return isAccountAllowed(account.name, account.type, uid); } public static boolean isAccountAllowed(String accountName, String accountType, int uid) { try { boolean allowed = PrivacyManager.getSettingBool(-uid, Meta.cTypeAccountHash, accountName + accountType, false); boolean blacklist = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingBlacklist, false); if (blacklist) allowed = !allowed; return allowed; } catch (Throwable ex) { Util.bug(null, ex); return false; } } private class XFutureAccount implements AccountManagerFuture<Account[]> { private AccountManagerFuture<Account[]> mFuture; private int mUid; public XFutureAccount(AccountManagerFuture<Account[]> future, int uid) { mFuture = future; mUid = uid; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return mFuture.cancel(mayInterruptIfRunning); } @Override public Account[] getResult() throws OperationCanceledException, IOException, AuthenticatorException { Account[] account = mFuture.getResult(); return XAccountManager.this.filterAccounts(account, mUid); } @Override public Account[] getResult(long timeout, TimeUnit unit) throws OperationCanceledException, IOException, AuthenticatorException { Account[] account = mFuture.getResult(timeout, unit); return XAccountManager.this.filterAccounts(account, mUid); } @Override public boolean isCancelled() { return mFuture.isCancelled(); } @Override public boolean isDone() { return mFuture.isDone(); } } private class XFutureBoolean implements AccountManagerFuture<Boolean> { @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public Boolean getResult() throws OperationCanceledException, IOException, AuthenticatorException { return false; } @Override public Boolean getResult(long timeout, TimeUnit unit) throws OperationCanceledException, IOException, AuthenticatorException { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } } private class XFutureBundle implements AccountManagerFuture<Bundle> { private AccountManagerFuture<Bundle> mFuture; private int mUid; public XFutureBundle(AccountManagerFuture<Bundle> future, int uid) { mFuture = future; mUid = uid; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return mFuture.cancel(mayInterruptIfRunning); } @Override public Bundle getResult() throws OperationCanceledException, IOException, AuthenticatorException { Bundle bundle = mFuture.getResult(); String accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME); String accountType = bundle.getString(AccountManager.KEY_ACCOUNT_TYPE); if (isAccountAllowed(accountName, accountType, mUid)) return bundle; else throw new OperationCanceledException("XPrivacy"); } @Override public Bundle getResult(long timeout, TimeUnit unit) throws OperationCanceledException, IOException, AuthenticatorException { Bundle bundle = mFuture.getResult(timeout, unit); String accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME); String accountType = bundle.getString(AccountManager.KEY_ACCOUNT_TYPE); if (isAccountAllowed(accountName, accountType, mUid)) return bundle; else throw new OperationCanceledException("XPrivacy"); } @Override public boolean isCancelled() { return mFuture.isCancelled(); } @Override public boolean isDone() { return mFuture.isDone(); } } private class XOnAccountsUpdateListener implements OnAccountsUpdateListener { private OnAccountsUpdateListener mListener; private int mUid; public XOnAccountsUpdateListener(OnAccountsUpdateListener listener, int uid) { mListener = listener; mUid = uid; } @Override public void onAccountsUpdated(Account[] accounts) { mListener.onAccountsUpdated(XAccountManager.this.filterAccounts(accounts, mUid)); } } private class XAccountManagerCallbackAccount implements AccountManagerCallback<Account[]> { private AccountManagerCallback<Account[]> mCallback; private int mUid; public XAccountManagerCallbackAccount(AccountManagerCallback<Account[]> callback, int uid) { mCallback = callback; mUid = uid; } @Override public void run(AccountManagerFuture<Account[]> future) { mCallback.run(new XAccountManager.XFutureAccount(future, mUid)); } } private class XAccountManagerCallbackBundle implements AccountManagerCallback<Bundle> { private AccountManagerCallback<Bundle> mCallback; private int mUid; public XAccountManagerCallbackBundle(AccountManagerCallback<Bundle> callback, int uid) { mCallback = callback; mUid = uid; } @Override public void run(AccountManagerFuture<Bundle> future) { mCallback.run(new XAccountManager.XFutureBundle(future, mUid)); } } private class XAccountManagerCallbackBoolean implements AccountManagerCallback<Boolean> { private AccountManagerCallback<Boolean> mCallback; public XAccountManagerCallbackBoolean(AccountManagerCallback<Boolean> callback) { mCallback = callback; } @Override public void run(AccountManagerFuture<Boolean> future) { mCallback.run(new XAccountManager.XFutureBoolean()); } } }
19,502
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XUtilHook.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XUtilHook.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.util.Log; public class XUtilHook extends XHook { private XUtilHook(String methodName, String restrictionName) { super(restrictionName, methodName, null); } public String getClassName() { return Util.class.getName(); } // isXposedEnabled public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XUtilHook("isXposedEnabled", null)); return listHook; } @Override protected void before(XParam param) throws Throwable { Util.log(this, Log.INFO, param.method.getName() + "=true"); param.setResult(true); } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
766
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
PackageChange.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/PackageChange.java
package biz.bokhorst.xprivacy; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.util.Log; public class PackageChange extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { try { // Check uri Uri inputUri = intent.getData(); if (inputUri.getScheme().equals("package")) { // Get data int uid = intent.getIntExtra(Intent.EXTRA_UID, 0); int userId = Util.getUserId(uid); boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); boolean ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Util.log(null, Log.WARN, "Package change action=" + intent.getAction() + " replacing=" + replacing + " uid=" + uid); // Check action if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) { // Check privacy service if (PrivacyService.getClient() == null) return; // Get data ApplicationInfoEx appInfo = new ApplicationInfoEx(context, uid); String packageName = inputUri.getSchemeSpecificPart(); // Default deny new user apps if (appInfo.getPackageName().size() == 1) { if (replacing) PrivacyManager.clearPermissionCache(uid); else { // Delete existing restrictions PrivacyManager.deleteRestrictions(uid, null, true); PrivacyManager.deleteSettings(uid); PrivacyManager.deleteUsage(uid); PrivacyManager.clearPermissionCache(uid); // Apply template PrivacyManager.applyTemplate(uid, Meta.cTypeTemplate, null, true, true, false); // Enable on demand if (ondemand) PrivacyManager.setSetting(uid, PrivacyManager.cSettingOnDemand, Boolean.toString(true)); } } // Mark as new/changed PrivacyManager.setSetting(uid, PrivacyManager.cSettingState, Integer.toString(ApplicationInfoEx.STATE_ATTENTION)); // New/update notification boolean notify = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingNotify, true); if (notify) notify = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingNotify, true); if (!replacing || notify) { Intent resultIntent = new Intent(context, ActivityApp.class); resultIntent.putExtra(ActivityApp.cUid, uid); // Build pending intent PendingIntent pendingIntent = PendingIntent.getActivity(context, uid, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); // Build result intent settings Intent resultIntentSettings = new Intent(context, ActivityApp.class); resultIntentSettings.putExtra(ActivityApp.cUid, uid); resultIntentSettings.putExtra(ActivityApp.cAction, ActivityApp.cActionSettings); // Build pending intent settings PendingIntent pendingIntentSettings = PendingIntent.getActivity(context, uid - 10000, resultIntentSettings, PendingIntent.FLAG_UPDATE_CURRENT); // Build result intent clear Intent resultIntentClear = new Intent(context, ActivityApp.class); resultIntentClear.putExtra(ActivityApp.cUid, uid); resultIntentClear.putExtra(ActivityApp.cAction, ActivityApp.cActionClear); // Build pending intent clear PendingIntent pendingIntentClear = PendingIntent.getActivity(context, uid + 10000, resultIntentClear, PendingIntent.FLAG_UPDATE_CURRENT); // Title String title = String.format("%s %s %s", context.getString(replacing ? R.string.msg_update : R.string.msg_new), appInfo.getApplicationName(packageName), appInfo.getPackageVersionName(context, packageName)); if (!replacing) title = String.format("%s %s", title, context.getString(R.string.msg_applied)); // Build notification NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context); notificationBuilder.setSmallIcon(R.drawable.ic_launcher); notificationBuilder.setContentTitle(context.getString(R.string.app_name)); notificationBuilder.setContentText(title); notificationBuilder.setContentIntent(pendingIntent); notificationBuilder.setWhen(System.currentTimeMillis()); notificationBuilder.setAutoCancel(true); // Actions notificationBuilder.addAction(android.R.drawable.ic_menu_edit, context.getString(R.string.menu_app_settings), pendingIntentSettings); notificationBuilder.addAction(android.R.drawable.ic_menu_delete, context.getString(R.string.menu_clear), pendingIntentClear); // Notify Notification notification = notificationBuilder.build(); notificationManager.notify(appInfo.getUid(), notification); } } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) { // Check privacy service if (PrivacyService.getClient() == null) return; if (!replacing) { // Package removed notificationManager.cancel(uid); // Delete restrictions ApplicationInfoEx appInfo = new ApplicationInfoEx(context, uid); if (appInfo.getPackageName().size() == 0) { PrivacyManager.deleteRestrictions(uid, null, false); PrivacyManager.deleteSettings(uid); PrivacyManager.deleteUsage(uid); PrivacyManager.clearPermissionCache(uid); } } } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) { // Notify reboot required String packageName = inputUri.getSchemeSpecificPart(); if (packageName.equals(context.getPackageName())) { // Mark self as new/changed if (PrivacyService.getClient() != null) PrivacyManager.setSetting(uid, PrivacyManager.cSettingState, Integer.toString(ApplicationInfoEx.STATE_ATTENTION)); // Start package update Intent changeIntent = new Intent(); changeIntent.setClass(context, UpdateService.class); changeIntent.putExtra(UpdateService.cAction, UpdateService.cActionUpdated); context.startService(changeIntent); // Build notification NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context); notificationBuilder.setSmallIcon(R.drawable.ic_launcher); notificationBuilder.setContentTitle(context.getString(R.string.app_name)); notificationBuilder.setContentText(context.getString(R.string.msg_reboot)); notificationBuilder.setWhen(System.currentTimeMillis()); notificationBuilder.setAutoCancel(true); Notification notification = notificationBuilder.build(); // Notify notificationManager.notify(Util.NOTIFY_RESTART, notification); } } } } catch (Throwable ex) { Util.bug(null, ex); } } }
7,033
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
PrivacyProvider.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/PrivacyProvider.java
package biz.bokhorst.xprivacy; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.annotation.SuppressLint; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.UriMatcher; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.os.Binder; import android.os.Process; import android.util.Log; // This code is legacy and only used for updating to newer versions @SuppressWarnings("deprecation") @SuppressLint({ "DefaultLocale", "WorldReadableFiles", "Registered" }) public class PrivacyProvider extends ContentProvider { private static final String AUTHORITY = "biz.bokhorst.xprivacy.provider"; private static final String PREF_RESTRICTION = AUTHORITY; private static final String PREF_USAGE = AUTHORITY + ".usage"; private static final String PREF_SETTINGS = AUTHORITY + ".settings"; private static final String PATH_RESTRICTION = "restriction"; private static final String PATH_USAGE = "usage"; private static final String PATH_SETTINGS = "settings"; public static final Uri URI_RESTRICTION = Uri.parse("content://" + AUTHORITY + "/" + PATH_RESTRICTION); public static final Uri URI_USAGE = Uri.parse("content://" + AUTHORITY + "/" + PATH_USAGE); public static final Uri URI_SETTING = Uri.parse("content://" + AUTHORITY + "/" + PATH_SETTINGS); public static final String COL_UID = "Uid"; public static final String COL_RESTRICTION = "Restriction"; public static final String COL_RESTRICTED = "Restricted"; public static final String COL_METHOD = "Method"; public static final String COL_USED = "Used"; public static final String COL_SETTING = "Setting"; public static final String COL_VALUE = "Value"; private static final UriMatcher sUriMatcher; private static final int TYPE_RESTRICTION = 1; private static final int TYPE_USAGE = 2; private static final int TYPE_SETTING = 3; private static Object mFallbackRestrictionLock = new Object(); private static Object mFallbackSettingsLock = new Object(); private static int mFallbackRestrictionsUid = 0; private static long mFallbackRestrictionsTime = 0; private static long mFallbackSettingsTime = 0; private static SharedPreferencesEx mFallbackRestrictions = null; private static SharedPreferencesEx mFallbackSettings = null; private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(AUTHORITY, PATH_RESTRICTION, TYPE_RESTRICTION); sUriMatcher.addURI(AUTHORITY, PATH_USAGE, TYPE_USAGE); sUriMatcher.addURI(AUTHORITY, PATH_SETTINGS, TYPE_SETTING); } @Override public boolean onCreate() { try { convertRestrictions(getContext()); convertSettings(getContext()); fixFilePermissions(); } catch (Throwable ex) { Util.bug(null, ex); } return true; } @Override public String getType(Uri uri) { if (sUriMatcher.match(uri) == TYPE_RESTRICTION) return String.format("vnd.android.cursor.dir/%s.%s", AUTHORITY, PATH_RESTRICTION); else if (sUriMatcher.match(uri) == TYPE_USAGE) return String.format("vnd.android.cursor.dir/%s.%s", AUTHORITY, PATH_USAGE); else if (sUriMatcher.match(uri) == TYPE_SETTING) return String.format("vnd.android.cursor.dir/%s.%s", AUTHORITY, PATH_SETTINGS); throw new IllegalArgumentException(); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (sUriMatcher.match(uri) == TYPE_RESTRICTION && selectionArgs != null && selectionArgs.length >= 2) { // Query restrictions String restrictionName = selection; int uid = Integer.parseInt(selectionArgs[0]); boolean usage = Boolean.parseBoolean(selectionArgs[1]); String methodName = (selectionArgs.length >= 3 ? selectionArgs[2] : null); return queryRestrictions(uid, restrictionName, methodName, usage); } else if (sUriMatcher.match(uri) == TYPE_USAGE && selectionArgs != null && selectionArgs.length >= 1) { // Query usage String restrictionName = selection; int uid = Integer.parseInt(selectionArgs[0]); String methodName = (selectionArgs.length >= 2 ? selectionArgs[1] : null); return queryUsage(uid, restrictionName, methodName); } else if (sUriMatcher.match(uri) == TYPE_SETTING && selectionArgs == null) return querySettings(selection); throw new IllegalArgumentException(uri.toString()); } private Cursor queryRestrictions(final int uid, final String restrictionName, final String methodName, boolean usage) { MatrixCursor cursor = new MatrixCursor(new String[] { COL_UID, COL_RESTRICTION, COL_METHOD, COL_RESTRICTED }); // Build restriction list List<String> listRestrictionName; if (restrictionName == null) listRestrictionName = PrivacyManager.getRestrictions(); else { listRestrictionName = new ArrayList<String>(); listRestrictionName.add(restrictionName); } if (uid == 0) { // Process applications PackageManager pm = getContext().getPackageManager(); for (ApplicationInfo appInfo : pm.getInstalledApplications(PackageManager.GET_META_DATA)) { SharedPreferences prefs = getContext().getSharedPreferences(PREF_RESTRICTION + "." + appInfo.uid, Context.MODE_WORLD_READABLE); // Process restrictions for (String eRestrictionName : listRestrictionName) if (getRestricted(eRestrictionName, null, prefs)) { // Category cursor.addRow(new Object[] { appInfo.uid, eRestrictionName, null, true }); // Exceptions for (Hook md : PrivacyManager.getHooks(eRestrictionName, null)) { boolean restricted = getRestricted(eRestrictionName, md.getName(), prefs); if (!restricted || md.isDangerous()) cursor.addRow(new Object[] { appInfo.uid, eRestrictionName, md.getName(), restricted }); } } } } else { SharedPreferences prefs = getContext().getSharedPreferences(PREF_RESTRICTION + "." + uid, Context.MODE_WORLD_READABLE); // Process restrictions boolean restricted = false; if (methodName != null && methodName.equals("*")) { for (String eRestrictionName : listRestrictionName) { boolean eRestricted = getRestricted(eRestrictionName, null, prefs); cursor.addRow(new Object[] { uid, eRestrictionName, null, Boolean.toString(eRestricted) }); for (Hook md : PrivacyManager.getHooks(eRestrictionName, null)) { eRestricted = getRestricted(eRestrictionName, md.getName(), prefs); cursor.addRow(new Object[] { uid, eRestrictionName, md.getName(), Boolean.toString(eRestricted) }); } } } else { for (String eRestrictionName : listRestrictionName) { boolean eRestricted = getRestricted(eRestrictionName, methodName, prefs); cursor.addRow(new Object[] { uid, eRestrictionName, methodName, Boolean.toString(eRestricted) }); restricted = (restricted || eRestricted); } } // Update usage data if (usage && restrictionName != null && methodName != null && !methodName.equals("*")) { final boolean isRestricted = restricted; final long timeStamp = new Date().getTime(); mExecutor.execute(new Runnable() { public void run() { updateUsage(uid, restrictionName, methodName, isRestricted, timeStamp); } }); } } return cursor; } private static boolean getRestricted(String restrictionName, String methodName, SharedPreferences prefs) { // Check for restriction boolean restricted = prefs.getBoolean(getRestrictionPref(restrictionName), false); // Check for exception if (restricted && methodName != null) if (prefs.getBoolean(getExceptionPref(restrictionName, methodName), false)) restricted = false; return restricted; } private Cursor queryUsage(int uid, String restrictionName, String methodName) { MatrixCursor cursor = new MatrixCursor(new String[] { COL_UID, COL_RESTRICTION, COL_METHOD, COL_RESTRICTED, COL_USED }); List<String> listRestriction; if (restrictionName == null) listRestriction = PrivacyManager.getRestrictions(); else { listRestriction = new ArrayList<String>(); listRestriction.add(restrictionName); } if (uid == 0) { // All for (String eRestrictionName : PrivacyManager.getRestrictions()) { SharedPreferences prefs = getContext().getSharedPreferences(PREF_USAGE + "." + eRestrictionName, Context.MODE_PRIVATE); for (String prefName : prefs.getAll().keySet()) if (prefName.startsWith(COL_USED)) { String[] prefParts = prefName.split("\\."); int rUid = Integer.parseInt(prefParts[1]); String rMethodName = prefName.substring(prefParts[0].length() + 1 + prefParts[1].length() + 1); getUsage(rUid, eRestrictionName, rMethodName, cursor); } } } else { // Selected restrictions/methods for (String eRestrictionName : listRestriction) if (methodName == null) for (Hook md : PrivacyManager.getHooks(eRestrictionName, null)) getUsage(uid, eRestrictionName, md.getName(), cursor); else getUsage(uid, eRestrictionName, methodName, cursor); } return cursor; } private void getUsage(int uid, String restrictionName, String methodName, MatrixCursor cursor) { SharedPreferences prefs = getContext().getSharedPreferences(PREF_USAGE + "." + restrictionName, Context.MODE_PRIVATE); String values = prefs.getString(getUsagePref(uid, methodName), null); if (values != null) { String[] value = values.split(":"); long timeStamp = Long.parseLong(value[0]); boolean restricted = Boolean.parseBoolean(value[1]); cursor.addRow(new Object[] { uid, restrictionName, methodName, restricted, timeStamp }); } } private Cursor querySettings(String name) { SharedPreferences prefs = getContext().getSharedPreferences(PREF_SETTINGS, Context.MODE_WORLD_READABLE); MatrixCursor cursor = new MatrixCursor(new String[] { COL_SETTING, COL_VALUE }); if (name == null) for (String settingKey : prefs.getAll().keySet()) try { cursor.addRow(new Object[] { getSettingName(settingKey), prefs.getString(settingKey, null) }); } catch (Throwable ex) { // Legacy boolean } else cursor.addRow(new Object[] { name, prefs.getString(getSettingPref(name), null) }); return cursor; } @Override public Uri insert(Uri uri, ContentValues values) { // Check access enforcePermission(); throw new IllegalArgumentException(uri.toString()); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (sUriMatcher.match(uri) == TYPE_RESTRICTION) { // Check access enforcePermission(); // Get arguments String restrictionName = selection; int uid = values.getAsInteger(COL_UID); String methodName = values.getAsString(COL_METHOD); boolean restricted = Boolean.parseBoolean(values.getAsString(COL_RESTRICTED)); updateRestriction(getContext(), uid, restrictionName, methodName, !restricted); return 1; // rows } else if (sUriMatcher.match(uri) == TYPE_USAGE) { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // Get arguments int uid = values.getAsInteger(COL_UID); String restrictionName = values.getAsString(PrivacyProvider.COL_RESTRICTION); String methodName = values.getAsString(COL_METHOD); boolean restricted = false; if (values.containsKey(PrivacyProvider.COL_RESTRICTED)) restricted = values.getAsBoolean(PrivacyProvider.COL_RESTRICTED); long timeStamp = values.getAsLong(PrivacyProvider.COL_USED); Util.log(null, Log.INFO, String.format("Update usage data %d/%s/%s=%b", uid, restrictionName, methodName, restricted)); // Update usage data if (methodName != null) updateUsage(uid, restrictionName, methodName, restricted, timeStamp); return 1; } else if (sUriMatcher.match(uri) == TYPE_SETTING) { // Check access enforcePermission(); // Get arguments String settingName = selection; String value = values.getAsString(COL_VALUE); // Update setting updateSetting(settingName, value); return 1; } throw new IllegalArgumentException(uri.toString()); } private static void updateRestriction(Context context, int uid, String restrictionName, String methodName, boolean allowed) { // Update restriction SharedPreferences prefs = context.getSharedPreferences(PREF_RESTRICTION + "." + uid, Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor = prefs.edit(); if (methodName == null || !allowed) editor.putBoolean(getRestrictionPref(restrictionName), !allowed); if (methodName != null) editor.putBoolean(getExceptionPref(restrictionName, methodName), allowed); editor.commit(); setPrefFileReadable(PREF_RESTRICTION, uid); } private void updateUsage(final int uid, final String restrictionName, final String methodName, final boolean restricted, long timeStamp) { SharedPreferences prefs = getContext().getSharedPreferences(PREF_USAGE + "." + restrictionName, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); String prefName = getUsagePref(uid, methodName); String prefValue = String.format("%d:%b", timeStamp, restricted); editor.remove(prefName); editor.putString(prefName, prefValue); editor.commit(); } private void updateSetting(String name, String value) { SharedPreferences prefs = getContext().getSharedPreferences(PREF_SETTINGS, Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor = prefs.edit(); if (value == null) editor.remove(getSettingPref(name)); else editor.putString(getSettingPref(name), value); editor.commit(); setPrefFileReadable(PREF_SETTINGS); } @Override public int delete(Uri uri, String where, String[] selectionArgs) { // Check access enforcePermission(); if (sUriMatcher.match(uri) == TYPE_RESTRICTION) { int uid = Integer.parseInt(selectionArgs[0]); return deleteRestrictions(uid); } else if (sUriMatcher.match(uri) == TYPE_USAGE) { int uid = Integer.parseInt(selectionArgs[0]); return deleteUsage(uid); } else if (sUriMatcher.match(uri) == TYPE_SETTING) { int uid = Integer.parseInt(selectionArgs[0]); return deleteSettings(uid); } throw new IllegalArgumentException(uri.toString()); } private int deleteRestrictions(int uid) { int rows = 0; SharedPreferences prefs = getContext().getSharedPreferences(PREF_RESTRICTION + "." + uid, Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor = prefs.edit(); for (String pref : prefs.getAll().keySet()) { Util.log(null, Log.INFO, "Removed restriction=" + pref + " uid=" + uid); editor.remove(pref); rows++; } editor.commit(); setPrefFileReadable(PREF_RESTRICTION, uid); return rows; } private int deleteUsage(int uid) { int rows = 0; String sUid = Integer.toString(uid); for (String restrictionName : PrivacyManager.getRestrictions()) { SharedPreferences prefs = getContext().getSharedPreferences(PREF_USAGE + "." + restrictionName, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); for (String pref : prefs.getAll().keySet()) { String[] component = pref.split("\\."); if (uid == 0 || (component.length >= 2 && component[1].equals(sUid))) { Util.log(null, Log.INFO, "Removed usage=" + pref); editor.remove(pref); rows++; } } editor.commit(); } return rows; } private int deleteSettings(int uid) { int rows = 0; String sUid = Integer.toString(uid); SharedPreferences prefs = getContext().getSharedPreferences(PREF_SETTINGS, Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor = prefs.edit(); for (String pref : prefs.getAll().keySet()) { String[] component = pref.split("\\."); if (component.length >= 3 && component[2].equals(sUid)) { Util.log(null, Log.INFO, "Removed setting=" + pref + " uid=" + uid); editor.remove(pref); rows++; } } editor.commit(); setPrefFileReadable(PREF_SETTINGS); return rows; } // The following methods are used as fallback, when: // - there is no context (Java threads) // - the content provider cannot be queried (PackageManagerService) public static boolean getRestrictedFallback(XHook hook, int uid, String restrictionName, String methodName) { try { long now = new Date().getTime(); File file = new File(getPrefFileName(PREF_RESTRICTION, uid)); if (!file.exists()) Util.log(null, Log.INFO, "Not found file=" + file.getAbsolutePath()); synchronized (mFallbackRestrictionLock) { if (mFallbackRestrictions == null || mFallbackRestrictionsUid != uid) { // Initial load mFallbackRestrictions = new SharedPreferencesEx(file); mFallbackRestrictionsUid = uid; mFallbackRestrictionsTime = now; long ms = System.currentTimeMillis() - now; Util.log(null, Log.INFO, "Load fallback restrictions uid=" + uid + "/" + mFallbackRestrictionsUid + " " + ms + " ms"); } else if (mFallbackRestrictionsTime + PrivacyManager.cRestrictionCacheTimeoutMs < now) { // Check update mFallbackRestrictions.reload(); mFallbackRestrictionsUid = uid; mFallbackRestrictionsTime = now; long ms = System.currentTimeMillis() - now; Util.log(null, Log.INFO, "Reload fallback restrictions uid=" + uid + " " + ms + " ms"); } } return getRestricted(restrictionName, methodName, mFallbackRestrictions); } catch (Throwable ex) { Util.bug(hook, ex); return false; } } public static String getSettingFallback(String name, String defaultValue, boolean log) { try { long now = new Date().getTime(); File file = new File(getPrefFileName(PREF_SETTINGS)); if (!file.exists()) if (log) Util.log(null, Log.INFO, "Not found file=" + file.getAbsolutePath()); synchronized (mFallbackSettingsLock) { // Initial load if (mFallbackSettings == null) { mFallbackSettings = new SharedPreferencesEx(file); mFallbackSettingsTime = now; if (log) { long ms = System.currentTimeMillis() - now; Util.log(null, Log.INFO, "Load fallback settings uid=" + Binder.getCallingUid() + " " + ms + " ms"); } } // Get update if (mFallbackSettingsTime + PrivacyManager.cSettingCacheTimeoutMs < now) { mFallbackSettings.reload(); mFallbackSettingsTime = now; if (log) { long ms = System.currentTimeMillis() - now; Util.log(null, Log.INFO, "Reload fallback settings uid=" + Binder.getCallingUid() + " " + ms + " ms"); } } } return mFallbackSettings.getString(getSettingPref(name), defaultValue); } catch (Throwable ex) { if (log) Util.bug(null, ex); return defaultValue; } } public static void flush() { Util.log(null, Log.INFO, "Flush uid=" + Binder.getCallingUid()); synchronized (mFallbackRestrictionLock) { mFallbackRestrictions = null; } synchronized (mFallbackSettingsLock) { mFallbackSettings = null; } } // Helper methods private void enforcePermission() throws SecurityException { if (Binder.getCallingUid() != Process.myUid()) throw new SecurityException(); } private static String getPrefFileName(String preference) { return Util.getUserDataDirectory(Process.myUid()) + File.separator + "shared_prefs" + File.separator + preference + ".xml"; } private static String getPrefFileName(String preference, int uid) { return Util.getUserDataDirectory(uid) + File.separator + "shared_prefs" + File.separator + preference + "." + uid + ".xml"; } private static void setPrefFileReadable(String preference) { new File(getPrefFileName(preference)).setReadable(true, false); } private static void setPrefFileReadable(String preference, int uid) { new File(getPrefFileName(preference, uid)).setReadable(true, false); } public static void fixFilePermissions() { File folder = new File(Util.getUserDataDirectory(Process.myUid()) + File.separator + "shared_prefs"); folder.setReadable(true, false); File[] files = folder.listFiles(); if (files != null) for (File file : files) if (file.getName().startsWith("biz.bokhorst.xprivacy.provider.") && file.getName().endsWith(".xml") && !file.getName().contains(".usage.")) file.setReadable(true, false); } private static String getRestrictionPref(String restrictionName) { return String.format("%s.%s", COL_RESTRICTED, restrictionName); } private static String getExceptionPref(String restrictionName, String methodName) { return String.format("%s.%s.%s", COL_METHOD, restrictionName, methodName); } private static String getUsagePref(int uid, String methodName) { return String.format("%s.%d.%s", COL_USED, uid, methodName); } private static String getSettingPref(String settingName) { return String.format("%s.%s", COL_SETTING, settingName); } private static String getSettingName(String settingKey) { return settingKey.substring(COL_SETTING.length() + 1); } private static void convertRestrictions(Context context) throws IOException { File source = new File(Util.getUserDataDirectory(Process.myUid()) + File.separator + "shared_prefs" + File.separator + "biz.bokhorst.xprivacy.provider.xml"); File backup = new File(source.getAbsoluteFile() + ".orig"); if (source.exists() && !backup.exists()) { Util.log(null, Log.WARN, "Converting restrictions"); SharedPreferences prefs = context.getSharedPreferences(PREF_RESTRICTION, Context.MODE_WORLD_READABLE); for (String key : prefs.getAll().keySet()) { String[] component = key.split("\\."); if (key.startsWith(COL_RESTRICTED)) { String restrictionName = component[1]; String value = prefs.getString(key, null); List<String> listRestriction = new ArrayList<String>(Arrays.asList(value.split(","))); listRestriction.remove(0); for (String uid : listRestriction) updateRestriction(context, Integer.parseInt(uid), restrictionName, null, false); } else if (key.startsWith(COL_METHOD)) { int uid = Integer.parseInt(component[1]); String restrictionName = component[2]; String methodName = component[3]; boolean value = prefs.getBoolean(key, false); updateRestriction(context, uid, restrictionName, methodName, value); } else Util.log(null, Log.WARN, "Unknown key=" + key); } // Backup old file Util.log(null, Log.INFO, "Backup name=" + backup.getAbsolutePath()); Util.copy(source, backup); } } private static void convertSettings(Context context) throws IOException { if (new File(getPrefFileName(PREF_SETTINGS)).exists()) { SharedPreferences prefs = context.getSharedPreferences(PREF_SETTINGS, Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor = prefs.edit(); for (String key : prefs.getAll().keySet()) try { String value = prefs.getString(key, null); if (PrivacyManager.cValueRandomLegacy.equals(value)) editor.putString(key, PrivacyManager.cValueRandom); } catch (Throwable ex) { } editor.commit(); setPrefFileReadable(PREF_SETTINGS); } } private static void splitSettings(Context context) { File prefFile = new File(getPrefFileName(PREF_SETTINGS)); File migratedFile = new File(prefFile + ".migrated"); if (prefFile.exists() && !migratedFile.exists()) { Util.log(null, Log.WARN, "Splitting " + prefFile); SharedPreferences prefs = context.getSharedPreferences(PREF_SETTINGS, Context.MODE_WORLD_READABLE); for (String settingKey : prefs.getAll().keySet()) try { int uid = 0; String name = getSettingName(settingKey); String value = prefs.getString(settingKey, ""); // Decode setting String[] component = name.split("\\."); if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.")) { try { // name.uid.key uid = Integer.parseInt(component[1]); name = component[0]; for (int i = 2; i < component.length; i++) name += "." + component[i]; } catch (NumberFormatException ignored) { // Initial uid/name will be used } } else if (component.length > 1) { try { // name.x.y.z.uid uid = Integer.parseInt(component[component.length - 1]); name = component[0]; for (int i = 1; i < component.length - 1; i++) name += "." + component[i]; } catch (NumberFormatException ignored) { // Initial uid/name will be used } } SharedPreferences aprefs = context.getSharedPreferences(PREF_SETTINGS + "." + uid, Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor = aprefs.edit(); editor.putString(name, value); editor.commit(); } catch (Throwable ex) { // Legacy boolean Util.bug(null, ex); } prefFile.renameTo(migratedFile); } } // Migration public static void migrateLegacy(Context context) throws IOException { convertSettings(context); convertRestrictions(context); splitSettings(context); } public static List<PRestriction> migrateRestrictions(Context context, int uid) { List<PRestriction> listWork = new ArrayList<PRestriction>(); File prefFile = new File(getPrefFileName(PREF_RESTRICTION, uid)); File migratedFile = new File(prefFile + ".migrated"); if (prefFile.exists() && !migratedFile.exists()) { Util.log(null, Log.WARN, "Migrating " + prefFile); SharedPreferences prefs = context.getSharedPreferences(PREF_RESTRICTION + "." + uid, Context.MODE_WORLD_READABLE); // Process restrictions for (String restrictionName : PrivacyManager.getRestrictions()) if (getRestricted(restrictionName, null, prefs)) { // Category listWork.add(new PRestriction(uid, restrictionName, null, true)); // Exceptions for (Hook md : PrivacyManager.getHooks(restrictionName, null)) { boolean restricted = getRestricted(restrictionName, md.getName(), prefs); if (!restricted || md.isDangerous()) listWork.add(new PRestriction(uid, restrictionName, md.getName(), restricted)); } } } return listWork; } public static void finishMigrateRestrictions(int uid) { File prefFile = new File(getPrefFileName(PREF_RESTRICTION, uid)); File migratedFile = new File(prefFile + ".migrated"); prefFile.renameTo(migratedFile); } public static List<PSetting> migrateSettings(Context context, int uid) { // Process settings List<PSetting> listWork = new ArrayList<PSetting>(); File prefFile = new File(getPrefFileName(PREF_SETTINGS, uid)); File migratedFile = new File(prefFile + ".migrated"); if (prefFile.exists() && !migratedFile.exists()) { Util.log(null, Log.WARN, "Migrating " + prefFile); SharedPreferences prefs = context.getSharedPreferences(PREF_SETTINGS + "." + uid, Context.MODE_WORLD_READABLE); for (String name : prefs.getAll().keySet()) try { String value = prefs.getString(name, null); if (value != null && !"".equals(value)) { String type; if (name.startsWith("Account.") || name.startsWith("Application.") || name.startsWith("Contact.") || name.startsWith("Template.")) { int dot = name.indexOf('.'); type = name.substring(0, dot); name = name.substring(dot + 1); } else type = ""; listWork.add(new PSetting(uid, type, name, value)); } } catch (Throwable ex) { // Legacy boolean Util.bug(null, ex); } } return listWork; } public static void finishMigrateSettings(int uid) { File prefFile = new File(getPrefFileName(PREF_SETTINGS, uid)); File migratedFile = new File(prefFile + ".migrated"); prefFile.renameTo(migratedFile); } }
27,943
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XContextImpl.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XContextImpl.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; public class XContextImpl extends XHook { private Methods mMethod; private XContextImpl(Methods method, String restrictionName) { super(restrictionName, method.name(), null); mMethod = method; } public String getClassName() { return "android.app.ContextImpl"; } // @formatter:off // public PackageManager getPackageManager() // public Object getSystemService(String name) // frameworks/base/core/java/android/app/ContextImpl.java // @formatter:on private enum Methods { getPackageManager, getSystemService }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XContextImpl(Methods.getPackageManager, null)); listHook.add(new XContextImpl(Methods.getSystemService, null)); return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case getPackageManager: if (param.getResult() != null) XPrivacy.handleGetSystemService("PackageManager", param.getResult().getClass().getName(), getSecret()); break; case getSystemService: if (param.args.length > 0 && param.args[0] instanceof String && param.getResult() != null) { String name = (String) param.args[0]; Object instance = param.getResult(); XPrivacy.handleGetSystemService(name, instance.getClass().getName(), getSecret()); } break; } } }
1,537
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XApplication.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XApplication.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.app.Application; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Process; import android.util.Log; public class XApplication extends XHook { private Methods mMethod; private static boolean mReceiverInstalled = false; public static String cAction = "Action"; public static String cActionKillProcess = "Kill"; public static String cActionFlush = "Flush"; public static String ACTION_MANAGE_PACKAGE = "biz.bokhorst.xprivacy.ACTION_MANAGE_PACKAGE"; public static String PERMISSION_MANAGE_PACKAGES = "biz.bokhorst.xprivacy.MANAGE_PACKAGES"; public XApplication(Methods method, String restrictionName, String actionName) { super(restrictionName, method.name(), actionName); mMethod = method; } @Override public String getClassName() { return "android.app.Application"; } // public void onCreate() // frameworks/base/core/java/android/app/Application.java // http://developer.android.com/reference/android/app/Application.html private enum Methods { onCreate }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XApplication(Methods.onCreate, null, null)); return listHook; } @Override protected void before(XParam param) throws Throwable { // do nothing } @Override protected void after(XParam param) throws Throwable { switch (mMethod) { case onCreate: // Install receiver for package management if (PrivacyManager.isApplication(Process.myUid()) && !mReceiverInstalled) try { Application app = (Application) param.thisObject; if (app != null) { mReceiverInstalled = true; Util.log(this, Log.INFO, "Installing receiver uid=" + Process.myUid()); app.registerReceiver(new Receiver(app), new IntentFilter(ACTION_MANAGE_PACKAGE), PERMISSION_MANAGE_PACKAGES, null); } } catch (SecurityException ignored) { } catch (Throwable ex) { Util.bug(this, ex); } break; } } public static void manage(Context context, int uid, String action) { if (uid == 0) manage(context, null, action); else { String[] packageName = context.getPackageManager().getPackagesForUid(uid); if (packageName != null && packageName.length > 0) manage(context, packageName[0], action); else Util.log(null, Log.WARN, "No packages uid=" + uid + " action=" + action); } } public static void manage(Context context, String packageName, String action) { Util.log(null, Log.INFO, "Manage package=" + packageName + " action=" + action); if (packageName == null && XApplication.cActionKillProcess.equals(action)) { Util.log(null, Log.WARN, "Kill all"); return; } Intent manageIntent = new Intent(XApplication.ACTION_MANAGE_PACKAGE); manageIntent.putExtra(XApplication.cAction, action); if (packageName != null) manageIntent.setPackage(packageName); context.sendBroadcast(manageIntent); } private class Receiver extends BroadcastReceiver { public Receiver(Application app) { } @Override public void onReceive(Context context, Intent intent) { try { String action = intent.getExtras().getString(cAction); Util.log(null, Log.WARN, "Managing uid=" + Process.myUid() + " action=" + action); if (cActionKillProcess.equals(action)) android.os.Process.killProcess(Process.myPid()); else if (cActionFlush.equals(action)) { PrivacyManager.flush(); } else Util.log(null, Log.WARN, "Unknown management action=" + action); } catch (Throwable ex) { Util.bug(null, ex); } } } }
3,727
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
Meta.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/Meta.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import android.annotation.SuppressLint; import android.content.Intent; import android.content.res.Resources; import android.nfc.NfcAdapter; import android.os.Build; import android.provider.MediaStore; import android.provider.Telephony; import android.telephony.TelephonyManager; import android.util.Log; @SuppressLint("InlinedApi") public class Meta { private static boolean mAnnotated = false; private static List<Hook> mListHook = new ArrayList<Hook>(); public final static String cTypeAccount = "Account"; public final static String cTypeAccountHash = "AccountHash"; public final static String cTypeApplication = "Application"; public final static String cTypeContact = "Contact"; public final static String cTypeTemplate = "Template"; public final static String cTypeTemplateName = "TemplateName"; public final static String cTypeAddress = "Address"; public final static String cTypeAction = "Action"; public final static String cTypeCommand = "Command"; public final static String cTypeFilename = "Filename"; public final static String cTypeIPAddress = "IPAddress"; public final static String cTypeLibrary = "Library"; public final static String cTypeMethod = "Method"; public final static String cTypePermission = "Permission"; public final static String cTypeProc = "Proc"; public final static String cTypeTransaction = "Transaction"; public final static String cTypeUrl = "Url"; public static boolean isWhitelist(String type) { return (cTypeAddress.equals(type) || cTypeAction.equals(type) || cTypeCommand.equals(type) || cTypeFilename.equals(type) || cTypeIPAddress.equals(type) || cTypeLibrary.equals(type) || cTypeMethod.equals(type) || cTypePermission.equals(type) || cTypeProc.equals(type) || cTypeTransaction.equals(type) || cTypeUrl.equals(type)); } public static List<Hook> get() { // http://developer.android.com/reference/android/Manifest.permission.html if (mListHook.size() > 0) return mListHook; // @formatter:off mListHook.add(new Hook("accounts", "addOnAccountsUpdatedListener", "GET_ACCOUNTS", 5, null, null).notAOSP(19)); mListHook.add(new Hook("accounts", "blockingGetAuthToken", "USE_CREDENTIALS", 5, null, null).dangerous().unsafe()); mListHook.add(new Hook("accounts", "getAccounts", "GET_ACCOUNTS", 5, null, null).notAOSP(19)); mListHook.add(new Hook("accounts", "getAccountsByType", "GET_ACCOUNTS", 5, null, null).notAOSP(19)); mListHook.add(new Hook("accounts", "getAccountsByTypeAndFeatures", "GET_ACCOUNTS", 5, null, null).notAOSP(19)); mListHook.add(new Hook("accounts", "getAuthToken", "USE_CREDENTIALS", 5, null, null).unsafe().dangerous()); mListHook.add(new Hook("accounts", "getAuthTokenByFeatures", "MANAGE_ACCOUNTS", 5, null, null).unsafe().dangerous()); mListHook.add(new Hook("accounts", "hasFeatures", "GET_ACCOUNTS", 8, null, null).unsafe().dangerous()); mListHook.add(new Hook("accounts", "getAccountsByTypeForPackage", "GET_ACCOUNTS", 18, null, null).notAOSP(19)); mListHook.add(new Hook("accounts", "getTokenGoogle", "GET_ACCOUNTS", 1, null, null).unsafe().dangerous().optional()); mListHook.add(new Hook("accounts", "getTokenWithNotificationGoogle", "GET_ACCOUNTS", 1, null, null).unsafe().dangerous().optional()); mListHook.add(new Hook("accounts", "getAuthenticatorTypes", "GET_ACCOUNTS", 5, "1.99.24", null).unsafe().dangerous()); mListHook.add(new Hook("accounts", "getCurrentSync", "READ_SYNC_SETTINGS", 8, "1.99.24", null).notAOSP(19).dangerous()); mListHook.add(new Hook("accounts", "getCurrentSyncs", "READ_SYNC_SETTINGS", 11, "1.99.24", null).notAOSP(19).dangerous()); mListHook.add(new Hook("accounts", "getSyncAdapterTypes", "", 5, "1.99.24", null).unsafe().dangerous()); mListHook.add(new Hook("accounts", "Srv_getAccounts", "GET_ACCOUNTS", 19, "2.99", "getAccounts").AOSP(19)); mListHook.add(new Hook("accounts", "Srv_getAccountsAsUser", "GET_ACCOUNTS", 19, "2.99", null).AOSP(19)); mListHook.add(new Hook("accounts", "Srv_getAccountsByFeatures", "GET_ACCOUNTS", 19, "2.99", "getAccountsByTypeAndFeatures").AOSP(19)); mListHook.add(new Hook("accounts", "Srv_getAccountsForPackage", "GET_ACCOUNTS", 19, "3.5.6", null).AOSP(19)); mListHook.add(new Hook("accounts", "Srv_getSharedAccountsAsUser", "GET_ACCOUNTS", 19, "2.99", null).AOSP(19)); mListHook.add(new Hook("accounts", "Srv_getCurrentSyncs", "READ_SYNC_SETTINGS", 19, "2.99", "getCurrentSyncs").AOSP(19)); mListHook.add(new Hook("accounts", "Srv_getCurrentSyncsAsUser", "READ_SYNC_SETTINGS", 21, "3.5.6", null).AOSP(21)); mListHook.add(new Hook("browser", "BrowserProvider2", "com.android.browser.permission.READ_HISTORY_BOOKMARKS,GLOBAL_SEARCH", 1, null, null)); mListHook.add(new Hook("browser", "Downloads", "ACCESS_DOWNLOAD_MANAGER,ACCESS_DOWNLOAD_MANAGER_ADVANCED,ACCESS_ALL_DOWNLOADS", 1, "1.99.43", null).dangerous()); mListHook.add(new Hook("calendar", "CalendarProvider2", "READ_CALENDAR,WRITE_CALENDAR", 1, null, null)); mListHook.add(new Hook("calling", "sendDataMessage", "SEND_SMS", 4, null, null).notAOSP(19).whitelist(cTypeAddress).doNotify()); mListHook.add(new Hook("calling", "sendMultimediaMessage", "SEND_SMS", 21, "3.5.6", null).doNotify()); mListHook.add(new Hook("calling", "sendMultipartTextMessage", "SEND_SMS", 4, null, null).notAOSP(19).whitelist(cTypeAddress).doNotify()); mListHook.add(new Hook("calling", "sendTextMessage", "SEND_SMS", 4, null, null).notAOSP(19).whitelist(cTypeAddress).doNotify()); mListHook.add(new Hook("calling", "Srv_sendData", "SEND_SMS", 19, "2.99", "sendDataMessage").AOSP(19).whitelist(cTypeAddress).doNotify()); mListHook.add(new Hook("calling", "Srv_sendMultipartText", "SEND_SMS", 19, "2.99", "sendMultipartTextMessage").AOSP(19).whitelist(cTypeAddress).doNotify()); mListHook.add(new Hook("calling", "Srv_sendText", "SEND_SMS", 19, "2.99", "sendTextMessage").AOSP(19).whitelist(cTypeAddress).doNotify()); mListHook.add(new Hook("calling", TelephonyManager.ACTION_RESPOND_VIA_MESSAGE, "SEND_RESPOND_VIA_MESSAGE", 18, null, null).doNotify()); mListHook.add(new Hook("calling", Intent.ACTION_CALL, "CALL_PHONE", 10, null, null).doNotify()); mListHook.add(new Hook("calling", Intent.ACTION_DIAL, "", 10, "2.2.2", null).doNotify()); mListHook.add(new Hook("calling", Intent.ACTION_NEW_OUTGOING_CALL, "PROCESS_OUTGOING_CALLS", 10, "2.1.23", "phone/android.intent.action.NEW_OUTGOING_CALL").doNotify()); mListHook.add(new Hook("calling", "CallLogProvider", "READ_CALL_LOG,WRITE_CALL_LOG", 1, "2.1.23", "phone/CallLogProvider")); mListHook.add(new Hook("calling", "SIP.isApiSupported", "USE_SIP", 9, null, null).unsafe().doNotify()); mListHook.add(new Hook("calling", "SIP.isSipWifiOnly", "USE_SIP", 9, null, null).unsafe().doNotify()); mListHook.add(new Hook("calling", "SIP.isVoipSupported", "USE_SIP", 9, null, null).unsafe().doNotify()); mListHook.add(new Hook("calling", "SIP.newInstance", "USE_SIP", 9, null, null).unsafe().doNotify()); mListHook.add(new Hook("clipboard", "addPrimaryClipChangedListener", "", 11, null, null).notAOSP(19)); mListHook.add(new Hook("clipboard", "getPrimaryClip", "", 11, null, null).notAOSP(19).doNotify()); mListHook.add(new Hook("clipboard", "getPrimaryClipDescription", "", 11, null, null).notAOSP(19).doNotify()); mListHook.add(new Hook("clipboard", "getText", "", 10, null, null).notAOSP(19).doNotify()); mListHook.add(new Hook("clipboard", "hasPrimaryClip", "", 11, null, null).notAOSP(19).doNotify()); mListHook.add(new Hook("clipboard", "hasText", "", 10, null, null).notAOSP(19).doNotify()); mListHook.add(new Hook("clipboard", "Srv_addPrimaryClipChangedListener", "", 19, "2.99", "addPrimaryClipChangedListener").AOSP(19)); mListHook.add(new Hook("clipboard", "Srv_getPrimaryClip", "", 19, "2.99", "getPrimaryClip").AOSP(19).doNotify()); mListHook.add(new Hook("clipboard", "Srv_getPrimaryClipDescription", "", 19, "2.99", "getPrimaryClipDescription").AOSP(19).doNotify()); mListHook.add(new Hook("clipboard", "Srv_hasClipboardText", "", 19, "2.99", "hasText").AOSP(19).doNotify()); mListHook.add(new Hook("clipboard", "Srv_hasPrimaryClip", "", 19, "2.99", "hasPrimaryClip").AOSP(19).doNotify()); mListHook.add(new Hook("contacts", "contacts/contacts", "READ_CONTACTS,WRITE_CONTACTS", 1, null, null)); mListHook.add(new Hook("contacts", "contacts/data", "READ_CONTACTS,WRITE_CONTACTS", 1, null, null)); mListHook.add(new Hook("contacts", "contacts/people", "READ_CONTACTS,WRITE_CONTACTS", 1, "1.99.46", null)); mListHook.add(new Hook("contacts", "contacts/phone_lookup", "READ_CONTACTS,WRITE_CONTACTS", 1, null, null)); mListHook.add(new Hook("contacts", "contacts/profile", "READ_PROFILE,WRITE_PROFILE", 1, "1.99.38", null).dangerous()); mListHook.add(new Hook("contacts", "contacts/raw_contacts", "READ_CONTACTS,WRITE_CONTACTS", 1, null, null)); mListHook.add(new Hook("contacts", "ContactsProvider2", "READ_CONTACTS,WRITE_CONTACTS,READ_PROFILE,WRITE_PROFILE", 1, "1.99.38", null).dangerous()); mListHook.add(new Hook("contacts", "IccProvider", "READ_CONTACTS,WRITE_CONTACTS", 1, "1.99.38", null)); mListHook.add(new Hook("dictionary", "UserDictionary", "READ_USER_DICTIONARY", 1, null, null)); mListHook.add(new Hook("email", "EMailProvider", "com.android.email.permission.ACCESS_PROVIDER", 1, null, null)); mListHook.add(new Hook("email", "GMailProvider", "com.google.android.gm.permission.READ_CONTENT_PROVIDER", 8, "1.99.20", null)); mListHook.add(new Hook("identification", "%hostname", "", 1, null, null).unsafe()); mListHook.add(new Hook("identification", "%imei", "", 1, null, null).unsafe()); mListHook.add(new Hook("identification", "%macaddr", "", 1, null, null).unsafe()); mListHook.add(new Hook("identification", "%serialno", "", 1, null, null).unsafe()); mListHook.add(new Hook("identification", "%cid", "", 1, null, null).unsafe()); mListHook.add(new Hook("identification", "/proc", "", 1, "1.7", null).unsafe().dangerous().whitelist(cTypeProc)); mListHook.add(new Hook("identification", "/system/build.prop", "", 1, "1.9.9", null).unsafe().dangerous()); mListHook.add(new Hook("identification", "/sys/block/.../cid", "", 1, null, null).unsafe().dangerous()); mListHook.add(new Hook("identification", "/sys/class/.../cid", "", 1, null, null).unsafe().dangerous()); mListHook.add(new Hook("identification", "AdvertisingId", "", 1, null, null).unsafe().optional()); mListHook.add(new Hook("identification", "getString", "", 1, null, null).notAOSP(19)); mListHook.add(new Hook("identification", "InputDevice.getDescriptor", "", 16, "2.2.2", "getDescriptor").unsafe()); mListHook.add(new Hook("identification", "InputDevice.getName", "", 9, null, null).unsafe()); mListHook.add(new Hook("identification", "GservicesProvider", "com.google.android.providers.gsf.permission.READ_GSERVICES,com.google.android.providers.gsf.permission.WRITE_GSERVICES", 1, null, null).dangerous()); mListHook.add(new Hook("identification", "SERIAL", "", 1, null, null).restart().noUsageData()); mListHook.add(new Hook("identification", "USB.getDeviceId", "", 12, "2.1.7", null).unsafe()); mListHook.add(new Hook("identification", "USB.getDeviceName", "", 12, "2.1.7", null).unsafe()); mListHook.add(new Hook("identification", "USB.getSerialNumber", "", 20, "2.1.17", null).unsafe()); mListHook.add(new Hook("identification", "Srv_Android_ID", "", 19, "2.99", "getString").AOSP(19)); mListHook.add(new Hook("identification", "Cast.getDeviceId", "", 1, "3.5.11", null).unsafe()); mListHook.add(new Hook("identification", "Cast.getIpAddress", "", 1, "3.5.11", null).unsafe()); // java.net.NetworkInterface mListHook.add(new Hook("internet", "NetworkInterface.getByIndex", "INTERNET", 19, "2.2.2", null).unsafe()); mListHook.add(new Hook("internet", "NetworkInterface.getByInetAddress", "INTERNET", 1, "2.2.2", "getByInetAddress").unsafe()); mListHook.add(new Hook("internet", "NetworkInterface.getByName", "INTERNET", 1, "2.2.2", "getByName").unsafe().dangerous().whitelist(cTypeIPAddress)); mListHook.add(new Hook("internet", "NetworkInterface.getNetworkInterfaces", "INTERNET", 1, "2.2.2", "getNetworkInterfaces").unsafe()); mListHook.add(new Hook("internet", "inet", "INTERNET", 1, null, null).dangerous().restart().noUsageData()); mListHook.add(new Hook("internet", "inet_admin", "NET_ADMIN", 1, "2.1.1", null).dangerous().restart().noUsageData()); mListHook.add(new Hook("internet", "inet_bw", "READ_NETWORK_USAGE_HISTORY,MODIFY_NETWORK_ACCOUNTING", 1, "2.1.1", null).dangerous().restart().noUsageData()); mListHook.add(new Hook("internet", "inet_vpn", "NET_TUNNELING", 1, "2.1.1", null).dangerous().restart().noUsageData()); mListHook.add(new Hook("internet", "inet_mesh", "LOOP_RADIO", 1, "2.1.1", null).dangerous().restart().noUsageData()); // android.net.ConnectivityManager mListHook.add(new Hook("internet", "Connectivity.getActiveNetworkInfo", null, 1, "2.2.2", "getActiveNetworkInfo").unsafe().dangerous()); mListHook.add(new Hook("internet", "Connectivity.getAllNetworkInfo", null, 1, "2.2.2", "getAllNetworkInfo").unsafe()); mListHook.add(new Hook("internet", "Connectivity.getNetworkInfo", null, 1, "2.2.2", "getNetworkInfo").unsafe().dangerous()); // android.net.NetworkInfo mListHook.add(new Hook("internet", "NetworkInfo.getDetailedState", null, 1, "2.2.2", "getDetailedState").unsafe()); mListHook.add(new Hook("internet", "NetworkInfo.getState", null, 1, "2.2.2", "getState").unsafe()); mListHook.add(new Hook("internet", "NetworkInfo.isConnected", null, 1, "2.2.2", "isConnected").unsafe()); mListHook.add(new Hook("internet", "NetworkInfo.isConnectedOrConnecting", null, 1, "2.2.2", "isConnectedOrConnecting").unsafe()); // android.net.wifi.WifiManager mListHook.add(new Hook("internet", "WiFi.getConnectionInfo", null, 10, "2.2.2", "getConnectionInfo").notAOSP(19)); mListHook.add(new Hook("internet", "WiFi.Srv_getConnectionInfo", null, 10, "2.99", "WiFi.getConnectionInfo").AOSP(19)); // java.net.InetAddress mListHook.add(new Hook("internet", "InetAddress.getAllByName", "INTERNET", 1, null, null).unsafe().dangerous().whitelist(cTypeIPAddress)); mListHook.add(new Hook("internet", "InetAddress.getAllByNameOnNet", "INTERNET", 21, "3.5.6", null).unsafe().dangerous().whitelist(cTypeIPAddress)); mListHook.add(new Hook("internet", "InetAddress.getByAddress", "INTERNET", 1, null, null).unsafe().dangerous().whitelist(cTypeIPAddress)); mListHook.add(new Hook("internet", "InetAddress.getByName", "INTERNET", 1, null, null).unsafe().dangerous().whitelist(cTypeIPAddress)); mListHook.add(new Hook("internet", "InetAddress.getByNameOnNet", "INTERNET", 21, "3.5.6", null).unsafe().dangerous().whitelist(cTypeIPAddress)); // android.net.IpPrefix mListHook.add(new Hook("internet", "IpPrefix.getAddress", null, 21, "3.5.6", null).dangerous().unsafe()); mListHook.add(new Hook("internet", "IpPrefix.getRawAddress", null, 21, "3.5.6", null).dangerous().unsafe()); // android.net.LinkProperties mListHook.add(new Hook("internet", "LinkProperties.getAddresses", null, 19, "3.5.6", null).dangerous().unsafe()); mListHook.add(new Hook("internet", "LinkProperties.getAllAddresses", null, 19, "3.5.6", null).dangerous().unsafe()); mListHook.add(new Hook("internet", "LinkProperties.getAllLinkAddresses", null, 19, "3.5.6", null).dangerous().unsafe()); mListHook.add(new Hook("internet", "LinkProperties.getLinkAddresses", null, 19, "3.5.6", null).dangerous().unsafe()); mListHook.add(new Hook("internet", "LinkProperties.getStackedLinks", null, 19, "3.5.6", null).dangerous().unsafe()); mListHook.add(new Hook("internet", "connect", null, 1, "1.99.45", null).unsafe().dangerous().whitelist(cTypeIPAddress)); mListHook.add(new Hook("ipc", "Binder", "", 1, "2.1.21", null).notAOSP(19).dangerous().whitelist(cTypeTransaction)); mListHook.add(new Hook("location", "addGeofence", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 17, null, null).notAOSP(19)); mListHook.add(new Hook("location", "addGpsStatusListener", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 3, "2.1.17", null).notAOSP(19)); mListHook.add(new Hook("location", "addNmeaListener", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 5, null, null).notAOSP(19)); mListHook.add(new Hook("location", "addProximityAlert", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, null, null).notAOSP(19)); mListHook.add(new Hook("location", "getAllProviders", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.1.20", null).notAOSP(19).dangerous()); mListHook.add(new Hook("location", "getBestProvider", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.1.20", null).notAOSP(19).dangerous()); mListHook.add(new Hook("location", "getGpsStatus", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 3, "1.99.29", null).notAOSP(19)); mListHook.add(new Hook("location", "getLastKnownLocation", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, null, null).notAOSP(19)); mListHook.add(new Hook("location", "getProviders", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "1.99.1", null).notAOSP(19).dangerous()); mListHook.add(new Hook("location", "isProviderEnabled", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "1.99.1", null).notAOSP(19).dangerous()); mListHook.add(new Hook("location", "requestLocationUpdates", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, null, null).restart().notAOSP(19)); mListHook.add(new Hook("location", "requestSingleUpdate", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 9, null, null).restart().notAOSP(19)); mListHook.add(new Hook("location", "sendExtraCommand", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 3, null, null).notAOSP(19)); mListHook.add(new Hook("location", "Srv_requestGeofence", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 17, "2.99", "addGeofence").AOSP(19)); mListHook.add(new Hook("location", "Srv_addGpsStatusListener", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 3, "2.99", "addGpsStatusListener").AOSP(19)); mListHook.add(new Hook("location", "Srv_getAllProviders", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.99", "getAllProviders").AOSP(19).dangerous()); mListHook.add(new Hook("location", "Srv_getBestProvider", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.99", "getBestProvider").AOSP(19).dangerous()); mListHook.add(new Hook("location", "Srv_getProviders", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.99", "getProviders").AOSP(19).dangerous()); mListHook.add(new Hook("location", "Srv_isProviderEnabled", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.99", "isProviderEnabled").AOSP(19).dangerous()); mListHook.add(new Hook("location", "Srv_getLastLocation", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.99", "getLastKnownLocation").AOSP(19)); mListHook.add(new Hook("location", "Srv_requestLocationUpdates", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.99", "requestLocationUpdates").restart().AOSP(19)); mListHook.add(new Hook("location", "Srv_sendExtraCommand", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 3, "2.99", "sendExtraCommand").AOSP(19)); mListHook.add(new Hook("location", "Srv_addGpsMeasurementsListener", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 21, "3.5.6", null).AOSP(21)); mListHook.add(new Hook("location", "Srv_addGpsNavigationMessageListener", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 21, "3.5.6", null).AOSP(21)); mListHook.add(new Hook("location", "enableLocationUpdates", "CONTROL_LOCATION_UPDATES", 10, null, null).notAOSP(19)); mListHook.add(new Hook("location", "getAllCellInfo", "ACCESS_COARSE_UPDATES", 17, null, null).notAOSP(19)); mListHook.add(new Hook("location", "getCellLocation", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, null, null).notAOSP(19)); mListHook.add(new Hook("location", "getNeighboringCellInfo", "ACCESS_COARSE_UPDATES", 3, null, null).notAOSP(19)); mListHook.add(new Hook("location", "Srv_enableLocationUpdates", "CONTROL_LOCATION_UPDATES", 10, "2.99", "enableLocationUpdates").AOSP(19)); mListHook.add(new Hook("location", "Srv_enableLocationUpdatesForSubscriber", "CONTROL_LOCATION_UPDATES", 21, "3.5.6", null).AOSP(21)); mListHook.add(new Hook("location", "Srv_getAllCellInfo", "ACCESS_COARSE_UPDATES", 17, "2.99", "getAllCellInfo").AOSP(19)); mListHook.add(new Hook("location", "Srv_getCellLocation", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.99", "getCellLocation").AOSP(19)); mListHook.add(new Hook("location", "Srv_getNeighboringCellInfo", "ACCESS_COARSE_UPDATES", 3, "2.99", "getNeighboringCellInfo").AOSP(19)); mListHook.add(new Hook("location", "WiFi.getScanResults", "ACCESS_WIFI_STATE", 1, "2.2.2", "getScanResults").notAOSP(19).dangerous()); mListHook.add(new Hook("location", "WiFi.Srv_getScanResults", "ACCESS_WIFI_STATE", 1, "2.99", "WiFi.getScanResults").AOSP(19).dangerous()); mListHook.add(new Hook("location", "listen", "ACCESS_COARSE_LOCATION", 1, null, null).notAOSP(19)); mListHook.add(new Hook("location", "Srv_listen", "ACCESS_COARSE_LOCATION", 1, null, null).AOSP(19)); mListHook.add(new Hook("location", "GMS.addGeofences", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, null, null).unsafe().optional()); mListHook.add(new Hook("location", "GMS.getLastLocation", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, null, null).unsafe().optional()); mListHook.add(new Hook("location", "GMS.requestLocationUpdates", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, null, null).unsafe().optional()); mListHook.add(new Hook("location", "GMS.requestActivityUpdates", "com.google.android.gms.permission.ACTIVITY_RECOGNITION", 1, null, null).unsafe()); mListHook.add(new Hook("location", "GMS5.getLastLocation", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.99.26", null).unsafe().optional()); mListHook.add(new Hook("location", "GMS5.requestLocationUpdates", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.99.26", null).unsafe().optional()); mListHook.add(new Hook("location", "GMS5.requestActivityUpdates", "com.google.android.gms.permission.ACTIVITY_RECOGNITION", 1, "2.99.26", null).unsafe()); mListHook.add(new Hook("location", "GMS5.getCurrentPlace", "ACCESS_FINE_LOCATION", 1, "3.6.9", null).unsafe()); mListHook.add(new Hook("location", "MapV1.enableMyLocation", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.1.25", null).unsafe().optional()); mListHook.add(new Hook("location", "MapV2.getMyLocation", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.1.25", null).unsafe().optional()); mListHook.add(new Hook("location", "MapV2.getPosition", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.1.25", null).unsafe().optional()); mListHook.add(new Hook("location", "MapV2.setLocationSource", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.1.25", null).unsafe().optional()); mListHook.add(new Hook("location", "MapV2.setOnMapClickListener", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.1.25", null).unsafe().optional()); mListHook.add(new Hook("location", "MapV2.setOnMapLongClickListener", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.1.25", null).unsafe().optional()); mListHook.add(new Hook("location", "MapV2.setOnMyLocationChangeListener", "ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION", 1, "2.1.25", null).unsafe().optional()); mListHook.add(new Hook("media", "Audio.startRecording", "RECORD_AUDIO", 3, "2.2.3", "startRecording").unsafe().doNotify()); mListHook.add(new Hook("media", "Camera.setPreviewCallback", "CAMERA", 1, "2.99.21", "setPreviewCallback").unsafe().doNotify()); mListHook.add(new Hook("media", "Camera.setPreviewCallbackWithBuffer", "CAMERA", 8, "2.99.21", null).unsafe().doNotify()); mListHook.add(new Hook("media", "Camera.setPreviewDisplay", "CAMERA", 1, "2.99.21", null).unsafe().doNotify()); mListHook.add(new Hook("media", "Camera.setPreviewTexture", "CAMERA", 11, "2.99.21", null).unsafe().doNotify()); mListHook.add(new Hook("media", "Camera.setOneShotPreviewCallback", "CAMERA", 11, "2.99.21", null).unsafe().doNotify()); mListHook.add(new Hook("media", "Camera.startPreview", "CAMERA", 1, "2.2.3", "setPreviewCallback").unsafe().doNotify()); mListHook.add(new Hook("media", "Camera.takePicture", "CAMERA", 1, "2.2.3", "takePicture").unsafe().doNotify()); mListHook.add(new Hook("media", "MediaRecorder.start", "RECORD_AUDIO,RECORD_VIDEO", 1, "2.2.3", "setOutputFile").unsafe().doNotify()); mListHook.add(new Hook("media", "MediaRecorder.setOutputFile", "RECORD_AUDIO,RECORD_VIDEO", 1, "2.99.20", "setOutputFile").unsafe().doNotify()); mListHook.add(new Hook("media", "Camera.permission", "CAMERA", 1, "2.2.3", null).dangerous().doNotify()); mListHook.add(new Hook("media", "Record.Audio.permission", "RECORD_AUDIO", 3, "2.2.3", null).dangerous().doNotify()); mListHook.add(new Hook("media", "Record.Video.permission", "RECORD_VIDEO", 3, "2.2.3", null).dangerous().doNotify()); mListHook.add(new Hook("media", MediaStore.ACTION_IMAGE_CAPTURE, "", 3, null, null).doNotify()); mListHook.add(new Hook("media", MediaStore.ACTION_IMAGE_CAPTURE_SECURE, "", 17, null, null).doNotify()); mListHook.add(new Hook("media", MediaStore.ACTION_VIDEO_CAPTURE, "", 3, null, null).doNotify()); mListHook.add(new Hook("media", "Camera2.capture", "CAMERA", 20, null, null).unsafe().doNotify()); mListHook.add(new Hook("media", "Camera2.captureBurst", "CAMERA", 20, null, null).unsafe().doNotify()); mListHook.add(new Hook("media", "Camera2.setRepeatingRequest", "CAMERA", 20, null, null).unsafe().doNotify()); mListHook.add(new Hook("media", "Camera2.setRepeatingBurst", "CAMERA", 20, null, null).unsafe().doNotify()); mListHook.add(new Hook("messages", "getAllMessagesFromIcc", "RECEIVE_SMS", 10, null, null).notAOSP(19)); mListHook.add(new Hook("messages", "getCarrierConfigValues", "", 21, "3.5.6", null)); mListHook.add(new Hook("messages", "Srv_getAllMessagesFromIccEf", "RECEIVE_SMS", 19, "2.99", "getAllMessagesFromIcc").AOSP(19)); mListHook.add(new Hook("messages", "SmsProvider", "READ_SMS,WRITE_SMS", 1, null, null)); mListHook.add(new Hook("messages", "MmsProvider", "READ_SMS,WRITE_SMS", 1, null, null)); mListHook.add(new Hook("messages", "MmsSmsProvider", "READ_SMS,WRITE_SMS", 1, null, null)); mListHook.add(new Hook("messages", "VoicemailContentProvider", "com.android.voicemail.permission.READ_WRITE_ALL_VOICEMAIL", 1, null, null)); mListHook.add(new Hook("messages", Telephony.Sms.Intents.DATA_SMS_RECEIVED_ACTION, "RECEIVE_SMS", 1, null, null)); mListHook.add(new Hook("messages", Telephony.Sms.Intents.SMS_RECEIVED_ACTION, "RECEIVE_SMS", 1, null, null)); mListHook.add(new Hook("messages", Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION, "RECEIVE_WAP_PUSH", 1, null, null)); mListHook.add(new Hook("messages", Telephony.Sms.Intents.SMS_DELIVER_ACTION, "BROADCAST_SMS", 19, "2.2.2", null)); mListHook.add(new Hook("messages", Telephony.Sms.Intents.WAP_PUSH_DELIVER_ACTION, "BROADCAST_WAP_PUSH", 19, "2.2.2", null)); // android.bluetooth.BluetoothAdapter/BluetoothDevice mListHook.add(new Hook("network", "Bluetooth.getAddress", "BLUETOOTH", 5, "2.2.3", "getAddress").unsafe()); mListHook.add(new Hook("network", "Bluetooth.getBondedDevices", "BLUETOOTH", 5, "2.2.3", "getBondedDevices").unsafe()); mListHook.add(new Hook("network", "Bluetooth.Srv_getAddress", "BLUETOOTH", 5, "2.99", "getAddress").AOSP(19)); mListHook.add(new Hook("network", "Bluetooth.Srv_getName", "BLUETOOTH", 5, "2.99", null).AOSP(19)); // java.net.NetworkInterface mListHook.add(new Hook("network", "NetworkInterface.getHardwareAddress", "ACCESS_NETWORK_STATE", 9, "2.2.2", "getHardwareAddress").unsafe()); mListHook.add(new Hook("network", "NetworkInterface.getInetAddresses", "ACCESS_NETWORK_STATE", 9, "2.2.2", "getInetAddresses").unsafe()); mListHook.add(new Hook("network", "NetworkInterface.getInterfaceAddresses", "ACCESS_NETWORK_STATE", 9, "2.2.2", "getInterfaceAddresses").unsafe()); // android.net.wifi.WifiManager mListHook.add(new Hook("network", "WiFi.getConfiguredNetworks", "ACCESS_WIFI_STATE", 10, "2.2.2", "getConfiguredNetworks").notAOSP(19)); mListHook.add(new Hook("network", "WiFi.getConnectionInfo", "ACCESS_WIFI_STATE", 10, "2.2.2", "getConnectionInfo").notAOSP(19)); mListHook.add(new Hook("network", "WiFi.getDhcpInfo", "ACCESS_WIFI_STATE", 10, "2.2.2", "getDhcpInfo").notAOSP(19)); mListHook.add(new Hook("network", "WiFi.getScanResults", "ACCESS_WIFI_STATE", 10, "2.2.2", "getScanResults").notAOSP(19).dangerous()); mListHook.add(new Hook("network", "WiFi.getWifiApConfiguration", "ACCESS_WIFI_STATE", 10, "2.2.2", "getWifiApConfiguration").notAOSP(19)); mListHook.add(new Hook("network", "WiFi.Srv_getBatchedScanResults", "ACCESS_WIFI_STATE", 10, "2.99", null).AOSP(19).dangerous()); mListHook.add(new Hook("network", "WiFi.Srv_getConfiguredNetworks", "ACCESS_WIFI_STATE", 10, "2.99", "WiFi.getConfiguredNetworks").AOSP(19)); mListHook.add(new Hook("network", "WiFi.Srv_getConnectionInfo", "ACCESS_WIFI_STATE", 10, "2.99", "WiFi.getConnectionInfo").AOSP(19)); mListHook.add(new Hook("network", "WiFi.Srv_getDhcpInfo", "ACCESS_WIFI_STATE", 10, "2.99", "WiFi.getDhcpInfo").AOSP(19)); mListHook.add(new Hook("network", "WiFi.Srv_getScanResults", "ACCESS_WIFI_STATE", 10, "2.99", "WiFi.getScanResults").AOSP(19).dangerous()); mListHook.add(new Hook("network", "WiFi.Srv_getWifiApConfiguration", "ACCESS_WIFI_STATE", 10, "2.99", "WiFi.getWifiApConfiguration").AOSP(19)); mListHook.add(new Hook("network", "Srv_Default_DNS", "", 19, "2.99", "getString").AOSP(19).dangerous()); mListHook.add(new Hook("network", "Srv_WiFi_Country", "", 19, "2.99", "getString").AOSP(19).dangerous()); // android.net.NetworkInfo mListHook.add(new Hook("network", "NetworkInfo.getExtraInfo", null, 1, "2.2.2", "internet/getExtraInfo").unsafe()); mListHook.add(new Hook("nfc", "getNfcAdapter", "NFC", 14, null, null).unsafe()); mListHook.add(new Hook("nfc", "getDefaultAdapter", "NFC", 10, null, null).unsafe()); mListHook.add(new Hook("nfc", NfcAdapter.ACTION_ADAPTER_STATE_CHANGED, "NFC", 18, null, null)); mListHook.add(new Hook("nfc", NfcAdapter.ACTION_NDEF_DISCOVERED, "NFC", 10, null, null)); mListHook.add(new Hook("nfc", NfcAdapter.ACTION_TAG_DISCOVERED, "NFC", 10, null, null)); mListHook.add(new Hook("nfc", NfcAdapter.ACTION_TECH_DISCOVERED, "NFC", 10, null, null)); mListHook.add(new Hook("notifications", "android.service.notification.NotificationListenerService", "BIND_NOTIFICATION_LISTENER_SERVICE", 18, null, null).unsafe()); mListHook.add(new Hook("notifications", "com.google.android.c2dm.intent.REGISTRATION", "com.google.android.c2dm.permission.RECEIVE", 10, null, null).dangerous()); mListHook.add(new Hook("notifications", "com.google.android.c2dm.intent.RECEIVE", "com.google.android.c2dm.permission.RECEIVE", 10, null, null).dangerous()); mListHook.add(new Hook("overlay", "addView", "SYSTEM_ALERT_WINDOW", 1, null, null).unsafe().optional()); mListHook.add(new Hook("phone", "getDeviceId", "READ_PHONE_STATE", 10, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getGroupIdLevel1", "READ_PHONE_STATE", 18, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getIsimDomain", "READ_PRIVILEGED_PHONE_STATE", 14, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getIsimImpi", "READ_PRIVILEGED_PHONE_STATE", 14, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getIsimImpu", "READ_PRIVILEGED_PHONE_STATE", 14, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getLine1AlphaTag", "READ_PHONE_STATE", 10, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getLine1Number", "READ_PHONE_STATE", 10, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getMsisdn", "READ_PHONE_STATE", 14, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getSimSerialNumber", "READ_PHONE_STATE", 10, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getSubscriberId", "READ_PHONE_STATE", 10, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getVoiceMailAlphaTag", "READ_PHONE_STATE", 10, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "getVoiceMailNumber", "READ_PHONE_STATE", 10, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "Srv_getDeviceId", "READ_PHONE_STATE", 10, "2.99", "getDeviceId").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getGroupIdLevel1", "READ_PHONE_STATE", 18, "2.99", "getGroupIdLevel1").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getIsimDomain", "READ_PRIVILEGED_PHONE_STATE", 14, "2.99", "getIsimDomain").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getIsimImpi", "READ_PRIVILEGED_PHONE_STATE", 14, "2.99", "getIsimImpi").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getIsimImpu", "READ_PRIVILEGED_PHONE_STATE", 14, "2.99", "getIsimImpu").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getLine1AlphaTag", "READ_PHONE_STATE", 10, "2.99", "getLine1AlphaTag").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getLine1Number", "READ_PHONE_STATE", 10, "2.99", "getLine1Number").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getMsisdn", "READ_PHONE_STATE", 14, "2.99", "getMsisdn").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getIccSerialNumber", "READ_PHONE_STATE", 10, "2.99", "getSimSerialNumber").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getSubscriberId", "READ_PHONE_STATE", 10, "2.99", "getSubscriberId").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getVoiceMailAlphaTag", "READ_PHONE_STATE", 10, "2.99", "getVoiceMailAlphaTag").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getVoiceMailNumber", "READ_PHONE_STATE", 10, "2.99", "getVoiceMailNumber").AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getCompleteVoiceMailNumber", "READ_PHONE_STATE", 10, "2.99", null).AOSP(19).to(20)); mListHook.add(new Hook("phone", "Srv_getImei", "READ_PHONE_STATE", 21, "3.5.6", null).AOSP(21).obsolete()); mListHook.add(new Hook("phone", "Srv_getIsimIst", "READ_PRIVILEGED_PHONE_STATE", 21, "3.5.6", null).AOSP(21).obsolete()); mListHook.add(new Hook("phone", "Srv_getIsimPcscf", "READ_PRIVILEGED_PHONE_STATE", 21, "3.5.6", null).AOSP(21).obsolete()); mListHook.add(new Hook("phone", "Srv_getCdmaMdn", "MODIFY_PHONE_STATE", 21, "3.5.6", null).AOSP(21)); mListHook.add(new Hook("phone", "Srv_getCdmaMin", "MODIFY_PHONE_STATE", 21, "3.5.6", null).AOSP(21)); mListHook.add(new Hook("phone", "Srv_getLine1AlphaTagForDisplay", "READ_PHONE_STATE", 21, "3.5.6", null).AOSP(21).obsolete()); mListHook.add(new Hook("phone", "Srv_getLine1NumberForDisplay", "READ_PHONE_STATE", 21, "3.5.6", null).AOSP(21).obsolete()); mListHook.add(new Hook("phone", "Srv_getCompleteVoiceMailNumberForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getCompleteVoiceMailNumber").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getDeviceId5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getDeviceId").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getDeviceIdForPhone5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getDeviceId").AOSP(Build.VERSION_CODES.LOLLIPOP_MR1)); mListHook.add(new Hook("phone", "Srv_getDeviceIdForSubscriber5", "READ_PHONE_STATE", 21, "3.6.13", "Srv_getDeviceId").AOSP(Build.VERSION_CODES.LOLLIPOP).to(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getGroupIdLevel1ForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getGroupIdLevel1").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getIccSerialNumberForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getIccSerialNumber").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getImeiForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getImei").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getIsimDomain5", "READ_PRIVILEGED_PHONE_STATE", 21, "3.6.12", "Srv_getIsimDomain").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getIsimImpi5", "READ_PRIVILEGED_PHONE_STATE", 21, "3.6.12", "Srv_getIsimImpi").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getIsimImpu5", "READ_PRIVILEGED_PHONE_STATE", 21, "3.6.12", "Srv_getIsimImpu").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getIsimIst5", "READ_PRIVILEGED_PHONE_STATE", 21, "3.6.12", "Srv_getIsimIst").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getIsimPcscf5", "READ_PRIVILEGED_PHONE_STATE", 21, "3.6.12", "Srv_getIsimPcscf").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getLine1AlphaTagForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getLine1AlphaTagForDisplay").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getLine1NumberForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getLine1NumberForDisplay").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getMsisdnForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getMsisdn").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getNaiForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", null).AOSP(Build.VERSION_CODES.LOLLIPOP_MR1)); mListHook.add(new Hook("phone", "Srv_getSubscriberIdForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getSubscriberId").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getVoiceMailAlphaTagForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getVoiceMailAlphaTag").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "Srv_getVoiceMailNumberForSubscriber5", "READ_PHONE_STATE", 21, "3.6.12", "Srv_getVoiceMailNumber").AOSP(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook("phone", "listen", "READ_PHONE_STATE", 10, null, null).notAOSP(19)); mListHook.add(new Hook("phone", "Srv_listen", "READ_PHONE_STATE", 10, null, null).AOSP(19)); mListHook.add(new Hook("phone", "getNetworkCountryIso", "", 10, null, null).unsafe()); mListHook.add(new Hook("phone", "getNetworkOperator", "", 10, null, null).unsafe()); mListHook.add(new Hook("phone", "getNetworkOperatorName", "", 10, null, null).unsafe()); mListHook.add(new Hook("phone", "getSimCountryIso", "", 10, null, null).unsafe()); mListHook.add(new Hook("phone", "getSimOperator", "", 10, null, null).unsafe()); mListHook.add(new Hook("phone", "getSimOperatorName", "", 10, null, null).unsafe()); mListHook.add(new Hook("phone", TelephonyManager.ACTION_PHONE_STATE_CHANGED, "READ_PHONE_STATE", 10, null, null)); mListHook.add(new Hook("phone", "TelephonyProvider", "WRITE_APN_SETTINGS", 1, null, null)); mListHook.add(new Hook("phone", "Configuration.MCC", "", 1, "2.0", null).unsafe().noUsageData().noOnDemand()); mListHook.add(new Hook("phone", "Configuration.MNC", "", 1, "2.0", null).unsafe().noUsageData().noOnDemand()); mListHook.add(new Hook("sensors", "getDefaultSensor", "", 3, null, null).unsafe().dangerous()); mListHook.add(new Hook("sensors", "getSensorList", "", 3, null, null).unsafe().dangerous()); mListHook.add(new Hook("sensors", "registerListener", "", 3, "2.99.27", null).unsafe()); mListHook.add(new Hook("sensors", "acceleration", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "gravity", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "humidity", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "light", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "magnetic", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "motion", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "orientation", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "pressure", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "proximity", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "rotation", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "temperature", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "step", "", 3, null, null).unsafe()); mListHook.add(new Hook("sensors", "heartrate", "", 20, null, null).unsafe()); mListHook.add(new Hook("shell", "sh", "", 10, null, null).unsafe().dangerous().whitelist(cTypeCommand)); mListHook.add(new Hook("shell", "su", "", 10, null, null).unsafe().dangerous().whitelist(cTypeCommand)); mListHook.add(new Hook("shell", "exec", "", 10, null, null).unsafe().dangerous().whitelist(cTypeCommand)); mListHook.add(new Hook("shell", "load", "", 10, null, null).unsafe().dangerous().restart().whitelist(cTypeLibrary)); mListHook.add(new Hook("shell", "loadLibrary", "", 10, null, null).unsafe().dangerous().restart().whitelist(cTypeLibrary)); mListHook.add(new Hook("shell", "start", "", 10, null, null).unsafe().dangerous().whitelist(cTypeCommand)); mListHook.add(new Hook("storage", "media", "WRITE_MEDIA_STORAGE", 10, null, null).dangerous().restart().noUsageData()); mListHook.add(new Hook("storage", "sdcard", "READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE,ACCESS_ALL_EXTERNAL_STORAGE", 10, null, null).dangerous().restart().noUsageData()); mListHook.add(new Hook("storage", "mtp", "ACCESS_MTP", 10, "2.1.1", null).dangerous().restart().noUsageData()); mListHook.add(new Hook("storage", "getExternalStorageState", null, 10, null, null).unsafe().whitelist(cTypeFilename)); mListHook.add(new Hook("storage", "open", null, 1, "1.99.46", null).unsafe().dangerous().whitelist(cTypeFilename)); mListHook.add(new Hook("storage", "openAssetFileDescriptor", null, 3, "2.1.17", null).unsafe().dangerous().whitelist(cTypeFilename)); mListHook.add(new Hook("storage", "openFileDescriptor", null, 1, "2.1.17", null).unsafe().dangerous().whitelist(cTypeFilename)); mListHook.add(new Hook("storage", "openInputStream", null, 1, "2.1.17", null).unsafe().dangerous().whitelist(cTypeFilename)); mListHook.add(new Hook("storage", "openOutputStream", null, 1, "2.1.17", null).unsafe().dangerous().whitelist(cTypeFilename)); mListHook.add(new Hook("storage", "openTypedAssetFileDescriptor", null, 11, "2.1.17", null).unsafe().dangerous().whitelist(cTypeFilename)); mListHook.add(new Hook("storage", "openAssetFile", null, 5, "2.1.17", null).unsafe().dangerous().whitelist(cTypeFilename)); mListHook.add(new Hook("storage", "openFile", null, 5, "2.1.17", null).unsafe().dangerous().whitelist(cTypeFilename)); mListHook.add(new Hook("system", "getInstalledApplications", "", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "getInstalledPackages", "", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "getPackagesForUid", "", 1, "2.1.17", null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "getPackagesHoldingPermissions", "", 18, "1.99.1", null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "getPreferredActivities", "", 1, "1.99.44", null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "getPreferredPackages", "", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "queryBroadcastReceivers", "", 1, null, null).dangerous()); mListHook.add(new Hook("system", "queryContentProviders", "", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "queryIntentActivities", "", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "queryIntentActivityOptions", "", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "queryIntentContentProviders", "", 19, "1.99.1", null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "queryIntentServices", "", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getPackageInfo", "", 19, "2.99.30", null).AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getApplicationInfo", "", 19, "2.99.30", null).AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getInstalledApplications", "", 19, "2.99", "getInstalledApplications").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getInstalledPackages", "", 19, "2.99", "getInstalledPackages").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getPackagesForUid", "", 19, "2.99", "getPackagesForUid").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getPackagesHoldingPermissions", "", 19, "2.99", "getPackagesHoldingPermissions").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getPersistentApplications", "", 19, "2.99", null).AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getPreferredPackages", "", 19, "2.99", "getPreferredPackages").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_queryContentProviders", "", 19, "2.99", "queryContentProviders").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_queryIntentActivities", "", 19, "2.99", "queryIntentActivities").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_queryIntentActivityOptions", "", 19, "2.99", "queryIntentActivityOptions").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_queryIntentContentProviders", "", 19, "2.99", "queryIntentContentProviders").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_queryIntentReceivers", "", 19, "2.99", "queryBroadcastReceivers").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_queryIntentServices", "", 19, "2.99", "queryIntentServices").AOSP(19).dangerous()); mListHook.add(new Hook("system", "getInstalledProviders", "", 3, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "getInstalledProvidersForProfile", "", 21, "3.5.6", null).notAOSP(21).dangerous()); mListHook.add(new Hook("system", "Srv_getInstalledProviders", "", 3, "2.99", "getInstalledProviders").AOSP(19).to(19).dangerous()); mListHook.add(new Hook("system", "Srv_getInstalledProvidersForProfile", "", 3, "3.6.6", null).AOSP(21).dangerous()); mListHook.add(new Hook("system", "getRecentTasks", "GET_TASKS", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "getRunningAppProcesses", "", 3, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "getRunningServices", "", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "getRunningTasks", "GET_TASKS", 1, null, null).notAOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getRecentTasks", "GET_TASKS", 1, "2.99", "getRecentTasks").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getRunningAppProcesses", "", 3, "2.99", "getRunningAppProcesses").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getServices", "", 1, "2.99", "getRunningServices").AOSP(19).dangerous()); mListHook.add(new Hook("system", "Srv_getTasks", "GET_TASKS", 1, "2.99", "getRunningTasks").AOSP(19).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_ADDED, "", 1, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_REPLACED, "", 3, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_RESTARTED, "", 1, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_REMOVED, "", 1, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_CHANGED, "", 1, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_DATA_CLEARED, "", 3, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_FIRST_LAUNCH, "", 12, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_FULLY_REMOVED, "", 14, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_NEEDS_VERIFICATION, "", 14, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_PACKAGE_VERIFIED, "", 17, "2.2.2", null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE, "", 8, null, null).dangerous()); mListHook.add(new Hook("system", Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE, "", 8, null, null).dangerous()); mListHook.add(new Hook("system", "ApplicationsProvider", "", 1, null, null).to(18)); mListHook.add(new Hook("system", "checkPermission", "", 1, "2.1.24", null).AOSP(19).dangerous().whitelist(cTypePermission)); mListHook.add(new Hook("system", "checkUidPermission", "", 1, "2.1.24", null).AOSP(19).dangerous().whitelist(cTypePermission)); mListHook.add(new Hook("system", "IntentFirewall", "", 19, "2.2.2", null).AOSP(19).dangerous().whitelist(cTypeAction)); mListHook.add(new Hook("system", "queryAndAggregateUsageStats", null, 21, "3.5.6", null).notAOSP(21)); mListHook.add(new Hook("system", "queryConfigurations", null, 21, "3.5.6", null).notAOSP(21)); mListHook.add(new Hook("system", "queryEvents", null, 21, "3.5.6", null).notAOSP(21)); mListHook.add(new Hook("system", "queryUsageStats", null, 21, "3.5.6", null).notAOSP(21)); mListHook.add(new Hook("system", "Srv_queryConfigurationStats", null, 21, "3.5.6", null).AOSP(21)); mListHook.add(new Hook("system", "Srv_queryEvents", null, 21, "3.5.6", null).AOSP(21)); mListHook.add(new Hook("system", "Srv_queryUsageStats", null, 21, "3.5.6", null).AOSP(21)); mListHook.add(new Hook("view", "loadUrl", "", 1, "3.6.2", "false").unsafe().whitelist(cTypeUrl)); mListHook.add(new Hook("view", "postUrl", "", 1, "3.6.2", null).unsafe().whitelist(cTypeUrl)); mListHook.add(new Hook("view", "initUserAgentString", "", 3, "3.6.2", null).unsafe()); mListHook.add(new Hook("view", "getDefaultUserAgent", "", 17, null, null).unsafe()); mListHook.add(new Hook("view", "getUserAgent", "", 3, null, null).unsafe()); mListHook.add(new Hook("view", "getUserAgentString", "", 3, null, null).unsafe()); mListHook.add(new Hook("view", "setUserAgent", "", 3, null, null).unsafe()); mListHook.add(new Hook("view", "setUserAgentString", "", 3, null, null).unsafe()); mListHook.add(new Hook("view", Intent.ACTION_VIEW, "", 1, null, null).notAOSP(19).doNotify().whitelist(cTypeUrl)); mListHook.add(new Hook("view", "Srv_" + Intent.ACTION_VIEW, "", 19, "2.99", Intent.ACTION_VIEW).AOSP(19).doNotify().whitelist(cTypeUrl)); mListHook.add(new Hook("view", "GMS5.view", "", 1, "2.99.27", null).unsafe()); // AccountManager mListHook.add(new Hook(null, "removeOnAccountsUpdatedListener", "", 5, null, null)); // Activity mListHook.add(new Hook(null, "startActivities", "", 1, null, null).notAOSP(19)); mListHook.add(new Hook(null, "startActivity", "", 1, null, null).notAOSP(19)); mListHook.add(new Hook(null, "startActivityForResult", "", 1, null, null).notAOSP(19)); mListHook.add(new Hook(null, "startActivityFromChild", "", 1, null, null).notAOSP(19)); mListHook.add(new Hook(null, "startActivityFromFragment", "", 1, null, null).notAOSP(19)); mListHook.add(new Hook(null, "startActivityIfNeeded", "", 1, null, null).notAOSP(19)); mListHook.add(new Hook(null, "startNextMatchingActivity", "", 1, null, null).notAOSP(19)); // ActivityThread / MessageQueue mListHook.add(new Hook(null, "next", "", 1, null, null).notAOSP(19).optional()); mListHook.add(new Hook(null, "handleReceiver", "", 1, null, null).notAOSP(19).optional()); // ActivityManager(Service) mListHook.add(new Hook(null, "Srv_startActivities", "", 19, null, null).AOSP(19)); mListHook.add(new Hook(null, "Srv_startActivity", "", 19, null, null).AOSP(19)); mListHook.add(new Hook(null, "Srv_startActivityAsUser", "", 19, null, null).AOSP(19)); mListHook.add(new Hook(null, "Srv_startActivityAsCaller", "", 21, null, null).AOSP(21)); mListHook.add(new Hook(null, "Srv_startActivityAndWait", "", 19, null, null).AOSP(19)); mListHook.add(new Hook(null, "Srv_startActivityWithConfig", "", 19, null, null).AOSP(19)); mListHook.add(new Hook(null, "inputDispatchingTimedOut", "", 17, null, null)); mListHook.add(new Hook(null, "appNotResponding", "", 15, null, null).optional()); mListHook.add(new Hook(null, "systemReady", "", 15, null, null)); mListHook.add(new Hook(null, "finishBooting", "", 15, null, null)); mListHook.add(new Hook(null, "setLockScreenShown", "", 17, null, null).optional()); mListHook.add(new Hook(null, "goingToSleep", "", 16, null, null).to(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook(null, "wakingUp", "", 16, null, null).to(Build.VERSION_CODES.LOLLIPOP)); mListHook.add(new Hook(null, "updateSleepIfNeededLocked", "", Build.VERSION_CODES.LOLLIPOP_MR1, null, null)); mListHook.add(new Hook(null, "shutdown", "", 15, null, null)); mListHook.add(new Hook(null, "activityResumed", "", Build.VERSION_CODES.JELLY_BEAN_MR1, null, null)); mListHook.add(new Hook(null, "activityPaused", "", Build.VERSION_CODES.JELLY_BEAN_MR1, null, null)); // AppIndexApi mListHook.add(new Hook(null, "GMS5.viewEnd", "", 1, null, null)); // Application mListHook.add(new Hook(null, "onCreate", "", 1, null, null)); // AudioRecord mListHook.add(new Hook(null, "Audio.stop", "", 3, null, null)); // Binder mListHook.add(new Hook(null, "execTransact", "", 1, null, null).notAOSP(19)); mListHook.add(new Hook(null, "transact", "", 1, null, null).notAOSP(19)); // ClipboardManager/Service mListHook.add(new Hook(null, "removePrimaryClipChangedListener", "", 11, null, null).notAOSP(19)); mListHook.add(new Hook(null, "Srv_removePrimaryClipChangedListener", "", 11, null, null).AOSP(19)); // Content resolvers mListHook.add(new Hook(null, "query", "", 1, null, null).notAOSP(19)); mListHook.add(new Hook(null, "Srv_call", "", 1, null, null).AOSP(19)); mListHook.add(new Hook(null, "Srv_query", "", 1, null, null).AOSP(19)); // Camera mListHook.add(new Hook(null, "Camera.stopPreview", "", 1, null, null)); // ContextImpl mListHook.add(new Hook(null, "getPackageManager", "", 1, null, null).notAOSP(19)); // ContextImpl / Activity mListHook.add(new Hook(null, "getSystemService", "", 1, null, null).notAOSP(19)); // FusedLocationProviderApi // ActivityRecognitionApi mListHook.add(new Hook(null, "GMS5.removeLocationUpdates", "", 1, "2.99.26", null).optional()); mListHook.add(new Hook(null, "GMS5.removeActivityUpdates", "", 1, "2.99.26", null).optional()); // GoogleApiClient.Builder mListHook.add(new Hook(null, "GMS5.addConnectionCallbacks", "", 1, null, null).optional()); mListHook.add(new Hook(null, "GMS5.onConnected", "", 1, null, null)); // IntentFirewall mListHook.add(new Hook(null, "checkIntent", "", 19, null, null)); // LocationClient / ActivityRecognitionClient mListHook.add(new Hook(null, "GMS.removeActivityUpdates", "", 1, null, null)); mListHook.add(new Hook(null, "GMS.removeGeofences", "", 1, null, null).optional()); mListHook.add(new Hook(null, "GMS.removeLocationUpdates", "", 1, null, null).optional()); // LocationManager/Service mListHook.add(new Hook(null, "removeUpdates", "", 3, null, null).notAOSP(19)); mListHook.add(new Hook(null, "Srv_removeUpdates", "", 19, null, null).AOSP(19)); mListHook.add(new Hook(null, "Srv_removeGeofence", "", 19, null, null).AOSP(19)); mListHook.add(new Hook(null, "Srv_removeGpsStatusListener", "", 19, null, null).AOSP(19)); mListHook.add(new Hook(null, "Srv_removeGpsMeasurementsListener", "", 21, null, null).AOSP(21)); mListHook.add(new Hook(null, "Srv_removeGpsNavigationMessageListener", "", 21, null, null).AOSP(21)); mListHook.add(new Hook(null, "MapV1.disableMyLocation", "", 1, null, null).optional()); // MediaRecorder mListHook.add(new Hook(null, "MediaRecorder.prepare", "", 1, null, null)); mListHook.add(new Hook(null, "MediaRecorder.stop", "", 1, null, null)); // Resources mListHook.add(new Hook(null, "updateConfiguration", "", 1, null, null)); // TelephonyManager mListHook.add(new Hook(null, "disableLocationUpdates", "", 10, null, null).notAOSP(19)); mListHook.add(new Hook(null, "Srv_disableLocationUpdates", "", 19, null, null).AOSP(19)); mListHook.add(new Hook(null, "Srv_disableLocationUpdatesForSubscriber", "", 21, null, null).AOSP(21)); // UtilHook mListHook.add(new Hook(null, "isXposedEnabled", "", 15, null, null)); // WebView mListHook.add(new Hook(null, "WebView", "", 1, null, null)); mListHook.add(new Hook(null, "getSettings", "", 1, null, null)); // WindowManagerImpl mListHook.add(new Hook(null, "removeView", "", 1, null, null).optional()); mListHook.add(new Hook(null, "updateViewLayout", "", 1, null, null).optional()); // @formatter:on return mListHook; } public static void annotate(Resources resources) { if (mAnnotated) return; String self = Meta.class.getPackage().getName(); for (Hook hook : get()) if (hook.getRestrictionName() != null) { String name = hook.getRestrictionName() + "_" + hook.getName(); name = name.replace(".", "_").replace("/", "_").replace("%", "_").replace("-", "_"); int resId = resources.getIdentifier(name, "string", self); if (resId > 0) hook.annotate(resources.getString(resId)); else Util.log(null, Log.WARN, "Missing annotation hook=" + hook); } mAnnotated = true; } }
58,026
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XWifiManager.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XWifiManager.java
package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import android.net.DhcpInfo; import android.net.wifi.ScanResult; import android.net.wifi.SupplicantState; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.os.Binder; import android.os.Build; public class XWifiManager extends XHook { private Methods mMethod; private String mClassName; private static final String cClassName = "android.net.wifi.WifiManager"; private XWifiManager(Methods method, String restrictionName, String className) { super(restrictionName, method.name().replace("Srv_", ""), "WiFi." + method.name()); mMethod = method; mClassName = className; } public String getClassName() { return mClassName; } // @formatter:off // public List<WifiConfiguration> getConfiguredNetworks() // public WifiInfo getConnectionInfo() // public DhcpInfo getDhcpInfo() // public List<ScanResult> getScanResults() // public WifiConfiguration getWifiApConfiguration() // frameworks/base/wifi/java/android/net/wifi/WifiManager.java // frameworks/base/wifi/java/android/net/wifi/WifiInfo.java // frameworks/base/core/java/android/net/DhcpInfo.java // http://developer.android.com/reference/android/net/wifi/WifiManager.html // public java.util.List<android.net.wifi.BatchedScanResult> getBatchedScanResults(java.lang.String callingPackage) // public java.util.List<android.net.wifi.WifiConfiguration> getConfiguredNetworks() // public android.net.wifi.WifiInfo getConnectionInfo() // public android.net.DhcpInfo getDhcpInfo() // public java.util.List<android.net.wifi.ScanResult> getScanResults(java.lang.String callingPackage) // public android.net.wifi.WifiConfiguration getWifiApConfiguration() // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.4_r1/com/android/server/wifi/WifiService.java // http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/com/android/server/wifi/WifiServiceImpl.java // @formatter:on // @formatter:off private enum Methods { getConfiguredNetworks, getConnectionInfo, getDhcpInfo, getScanResults, getWifiApConfiguration, Srv_getBatchedScanResults, Srv_getConfiguredNetworks, Srv_getConnectionInfo, Srv_getDhcpInfo, Srv_getScanResults, Srv_getWifiApConfiguration }; // @formatter:on public static List<XHook> getInstances(String className, boolean server) { List<XHook> listHook = new ArrayList<XHook>(); if (!cClassName.equals(className)) { if (className == null) className = cClassName; String srvClassName; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) srvClassName = "com.android.server.wifi.WifiServiceImpl"; else srvClassName = "com.android.server.wifi.WifiService"; for (Methods wifi : Methods.values()) if (wifi.name().startsWith("Srv_")) { if (server) listHook.add(new XWifiManager(wifi, PrivacyManager.cNetwork, srvClassName)); } else listHook.add(new XWifiManager(wifi, PrivacyManager.cNetwork, className)); listHook.add(new XWifiManager(Methods.getScanResults, PrivacyManager.cLocation, className)); if (server) listHook.add(new XWifiManager(Methods.Srv_getScanResults, PrivacyManager.cLocation, srvClassName)); // This is to fake "offline", no permission required listHook.add(new XWifiManager(Methods.getConnectionInfo, PrivacyManager.cInternet, className)); if (server) listHook.add(new XWifiManager(Methods.Srv_getConnectionInfo, PrivacyManager.cInternet, srvClassName)); } return listHook; } @Override protected void before(XParam param) throws Throwable { // Do nothing } @Override @SuppressWarnings("rawtypes") protected void after(XParam param) throws Throwable { switch (mMethod) { case Srv_getBatchedScanResults: if (param.getResult() != null) if (isRestricted(param)) param.setResult(new ArrayList()); break; case getConfiguredNetworks: case Srv_getConfiguredNetworks: if (param.getResult() != null) if (isRestricted(param)) param.setResult(new ArrayList<WifiConfiguration>()); break; case getConnectionInfo: case Srv_getConnectionInfo: if (param.getResult() != null) if (isRestricted(param)) { WifiInfo result = (WifiInfo) param.getResult(); WifiInfo wInfo = WifiInfo.class.getConstructor(WifiInfo.class).newInstance(result); if (getRestrictionName().equals(PrivacyManager.cInternet)) { // Supplicant state try { Field fieldState = WifiInfo.class.getDeclaredField("mSupplicantState"); fieldState.setAccessible(true); fieldState.set(wInfo, SupplicantState.DISCONNECTED); } catch (Throwable ex) { Util.bug(this, ex); } } else { // BSSID try { Field fieldBSSID = WifiInfo.class.getDeclaredField("mBSSID"); fieldBSSID.setAccessible(true); fieldBSSID.set(wInfo, PrivacyManager.getDefacedProp(Binder.getCallingUid(), "MAC")); } catch (Throwable ex) { Util.bug(this, ex); } // IP address try { Field fieldIp = WifiInfo.class.getDeclaredField("mIpAddress"); fieldIp.setAccessible(true); fieldIp.set(wInfo, PrivacyManager.getDefacedProp(Binder.getCallingUid(), "InetAddress")); } catch (Throwable ex) { Util.bug(this, ex); } // MAC address try { Field fieldMAC = WifiInfo.class.getDeclaredField("mMacAddress"); fieldMAC.setAccessible(true); fieldMAC.set(wInfo, PrivacyManager.getDefacedProp(Binder.getCallingUid(), "MAC")); } catch (Throwable ex) { Util.bug(this, ex); } // SSID String ssid = (String) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "SSID"); try { Field fieldSSID = WifiInfo.class.getDeclaredField("mSSID"); fieldSSID.setAccessible(true); fieldSSID.set(wInfo, ssid); } catch (Throwable ex) { try { Field fieldWifiSsid = WifiInfo.class.getDeclaredField("mWifiSsid"); fieldWifiSsid.setAccessible(true); Object mWifiSsid = fieldWifiSsid.get(wInfo); if (mWifiSsid != null) { // public static WifiSsid // createFromAsciiEncoded(String // asciiEncoded) Method methodCreateFromAsciiEncoded = mWifiSsid.getClass().getDeclaredMethod( "createFromAsciiEncoded", String.class); fieldWifiSsid.set(wInfo, methodCreateFromAsciiEncoded.invoke(null, ssid)); } } catch (Throwable exex) { Util.bug(this, exex); } } } param.setResult(wInfo); } break; case getDhcpInfo: case Srv_getDhcpInfo: if (param.getResult() != null) if (isRestricted(param)) { DhcpInfo result = (DhcpInfo) param.getResult(); DhcpInfo dInfo = DhcpInfo.class.getConstructor(DhcpInfo.class).newInstance(result); dInfo.ipAddress = (Integer) PrivacyManager.getDefacedProp(Binder.getCallingUid(), "IPInt"); dInfo.gateway = dInfo.ipAddress; dInfo.dns1 = dInfo.ipAddress; dInfo.dns2 = dInfo.ipAddress; dInfo.serverAddress = dInfo.ipAddress; param.setResult(dInfo); } break; case getScanResults: case Srv_getScanResults: if (param.getResult() != null) if (isRestricted(param)) param.setResult(new ArrayList<ScanResult>()); break; case getWifiApConfiguration: case Srv_getWifiApConfiguration: if (param.getResult() != null) if (isRestricted(param)) param.setResult(null); break; } } }
7,602
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XAudioRecord.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/biz/bokhorst/xprivacy/XAudioRecord.java
package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; public class XAudioRecord extends XHook { private Methods mMethod; private XAudioRecord(Methods method, String restrictionName) { super(restrictionName, method.name(), "Audio." + method.name()); mMethod = method; } public String getClassName() { return "android.media.AudioRecord"; } // public void startRecording() // public void startRecording(MediaSyncEvent syncEvent) // public void stop() // frameworks/base/media/java/android/media/AudioRecord.java // http://developer.android.com/reference/android/media/AudioRecord.html private enum Methods { startRecording, stop }; public static List<XHook> getInstances() { List<XHook> listHook = new ArrayList<XHook>(); listHook.add(new XAudioRecord(Methods.startRecording, PrivacyManager.cMedia)); listHook.add(new XAudioRecord(Methods.stop, null)); return listHook; } @Override protected void before(XParam param) throws Throwable { switch (mMethod) { case startRecording: if (isRestricted(param)) param.setResult(null); break; case stop: if (isRestricted(param, PrivacyManager.cMedia, "Audio.startRecording")) param.setResult(null); break; } } @Override protected void after(XParam param) throws Throwable { // Do nothing } }
1,332
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
FastXmlSerializer.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/com/android/internal/util/FastXmlSerializer.java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.util; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; /** * This is a quick and dirty implementation of XmlSerializer that isn't horribly * painfully slow like the normal one. It only does what is needed for the * specific XML files being written with it. */ public class FastXmlSerializer implements XmlSerializer { private static final String ESCAPE_TABLE[] = new String[] { null, null, null, null, null, null, null, null, // 0-7 null, null, null, null, null, null, null, null, // 8-15 null, null, null, null, null, null, null, null, // 16-23 null, null, null, null, null, null, null, null, // 24-31 null, null, "&quot;", null, null, null, "&amp;", null, // 32-39 null, null, null, null, null, null, null, null, // 40-47 null, null, null, null, null, null, null, null, // 48-55 null, null, null, null, "&lt;", null, "&gt;", null, // 56-63 }; private static final int BUFFER_LEN = 8192; private static String sSpace = " "; private final char[] mText = new char[BUFFER_LEN]; private int mPos; private Writer mWriter; private OutputStream mOutputStream; private CharsetEncoder mCharset; private ByteBuffer mBytes = ByteBuffer.allocate(BUFFER_LEN); private boolean mIndent = false; private boolean mInTag; private int mNesting = 0; private boolean mLineStart = true; private void append(char c) throws IOException { int pos = mPos; if (pos >= (BUFFER_LEN-1)) { flush(); pos = mPos; } mText[pos] = c; mPos = pos+1; } private void append(String str, int i, final int length) throws IOException { if (length > BUFFER_LEN) { final int end = i + length; while (i < end) { int next = i + BUFFER_LEN; append(str, i, next<end ? BUFFER_LEN : (end-i)); i = next; } return; } int pos = mPos; if ((pos+length) > BUFFER_LEN) { flush(); pos = mPos; } str.getChars(i, i+length, mText, pos); mPos = pos + length; } private void append(char[] buf, int i, final int length) throws IOException { if (length > BUFFER_LEN) { final int end = i + length; while (i < end) { int next = i + BUFFER_LEN; append(buf, i, next<end ? BUFFER_LEN : (end-i)); i = next; } return; } int pos = mPos; if ((pos+length) > BUFFER_LEN) { flush(); pos = mPos; } System.arraycopy(buf, i, mText, pos, length); mPos = pos + length; } private void append(String str) throws IOException { append(str, 0, str.length()); } private void appendIndent(int indent) throws IOException { indent *= 4; if (indent > sSpace.length()) { indent = sSpace.length(); } append(sSpace, 0, indent); } private void escapeAndAppendString(final String string) throws IOException { final int N = string.length(); final char NE = (char)ESCAPE_TABLE.length; final String[] escapes = ESCAPE_TABLE; int lastPos = 0; int pos; for (pos=0; pos<N; pos++) { char c = string.charAt(pos); if (c >= NE) continue; String escape = escapes[c]; if (escape == null) continue; if (lastPos < pos) append(string, lastPos, pos-lastPos); lastPos = pos + 1; append(escape); } if (lastPos < pos) append(string, lastPos, pos-lastPos); } private void escapeAndAppendString(char[] buf, int start, int len) throws IOException { final char NE = (char)ESCAPE_TABLE.length; final String[] escapes = ESCAPE_TABLE; int end = start+len; int lastPos = start; int pos; for (pos=start; pos<end; pos++) { char c = buf[pos]; if (c >= NE) continue; String escape = escapes[c]; if (escape == null) continue; if (lastPos < pos) append(buf, lastPos, pos-lastPos); lastPos = pos + 1; append(escape); } if (lastPos < pos) append(buf, lastPos, pos-lastPos); } public XmlSerializer attribute(String namespace, String name, String value) throws IOException, IllegalArgumentException, IllegalStateException { append(' '); if (namespace != null) { append(namespace); append(':'); } append(name); append("=\""); escapeAndAppendString(value); append('"'); mLineStart = false; return this; } public void cdsect(String text) throws IOException, IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException(); } public void comment(String text) throws IOException, IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException(); } public void docdecl(String text) throws IOException, IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException(); } public void endDocument() throws IOException, IllegalArgumentException, IllegalStateException { flush(); } public XmlSerializer endTag(String namespace, String name) throws IOException, IllegalArgumentException, IllegalStateException { mNesting--; if (mInTag) { append(" />\n"); } else { if (mIndent && mLineStart) { appendIndent(mNesting); } append("</"); if (namespace != null) { append(namespace); append(':'); } append(name); append(">\n"); } mLineStart = true; mInTag = false; return this; } public void entityRef(String text) throws IOException, IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException(); } private void flushBytes() throws IOException { int position; if ((position = mBytes.position()) > 0) { mBytes.flip(); mOutputStream.write(mBytes.array(), 0, position); mBytes.clear(); } } public void flush() throws IOException { //Log.i("PackageManager", "flush mPos=" + mPos); if (mPos > 0) { if (mOutputStream != null) { CharBuffer charBuffer = CharBuffer.wrap(mText, 0, mPos); CoderResult result = mCharset.encode(charBuffer, mBytes, true); while (true) { if (result.isError()) { throw new IOException(result.toString()); } else if (result.isOverflow()) { flushBytes(); result = mCharset.encode(charBuffer, mBytes, true); continue; } break; } flushBytes(); mOutputStream.flush(); } else { mWriter.write(mText, 0, mPos); mWriter.flush(); } mPos = 0; } } public int getDepth() { throw new UnsupportedOperationException(); } public boolean getFeature(String name) { throw new UnsupportedOperationException(); } public String getName() { throw new UnsupportedOperationException(); } public String getNamespace() { throw new UnsupportedOperationException(); } public String getPrefix(String namespace, boolean generatePrefix) throws IllegalArgumentException { throw new UnsupportedOperationException(); } public Object getProperty(String name) { throw new UnsupportedOperationException(); } public void ignorableWhitespace(String text) throws IOException, IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException(); } public void processingInstruction(String text) throws IOException, IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException(); } public void setFeature(String name, boolean state) throws IllegalArgumentException, IllegalStateException { if (name.equals("http://xmlpull.org/v1/doc/features.html#indent-output")) { mIndent = true; return; } throw new UnsupportedOperationException(); } public void setOutput(OutputStream os, String encoding) throws IOException, IllegalArgumentException, IllegalStateException { if (os == null) throw new IllegalArgumentException(); if (true) { try { mCharset = Charset.forName(encoding).newEncoder(); } catch (IllegalCharsetNameException e) { throw (UnsupportedEncodingException) (new UnsupportedEncodingException( encoding).initCause(e)); } catch (UnsupportedCharsetException e) { throw (UnsupportedEncodingException) (new UnsupportedEncodingException( encoding).initCause(e)); } mOutputStream = os; } else { setOutput( encoding == null ? new OutputStreamWriter(os) : new OutputStreamWriter(os, encoding)); } } public void setOutput(Writer writer) throws IOException, IllegalArgumentException, IllegalStateException { mWriter = writer; } public void setPrefix(String prefix, String namespace) throws IOException, IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException(); } public void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException { throw new UnsupportedOperationException(); } public void startDocument(String encoding, Boolean standalone) throws IOException, IllegalArgumentException, IllegalStateException { append("<?xml version='1.0' encoding='utf-8' standalone='" + (standalone ? "yes" : "no") + "' ?>\n"); mLineStart = true; } public XmlSerializer startTag(String namespace, String name) throws IOException, IllegalArgumentException, IllegalStateException { if (mInTag) { append(">\n"); } if (mIndent) { appendIndent(mNesting); } mNesting++; append('<'); if (namespace != null) { append(namespace); append(':'); } append(name); mInTag = true; mLineStart = false; return this; } public XmlSerializer text(char[] buf, int start, int len) throws IOException, IllegalArgumentException, IllegalStateException { if (mInTag) { append(">"); mInTag = false; } escapeAndAppendString(buf, start, len); if (mIndent) { mLineStart = buf[start+len-1] == '\n'; } return this; } public XmlSerializer text(String text) throws IOException, IllegalArgumentException, IllegalStateException { if (mInTag) { append(">"); mInTag = false; } escapeAndAppendString(text); if (mIndent) { mLineStart = text.length() > 0 && (text.charAt(text.length()-1) == '\n'); } return this; } }
13,302
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
XmlUtils.java
/FileExtraction/Java_unseen/M66B_XPrivacy/src/com/android/internal/util/XmlUtils.java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.util; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ProtocolException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** {@hide} */ public class XmlUtils { public static void skipCurrentTag(XmlPullParser parser) throws XmlPullParserException, IOException { int outerDepth = parser.getDepth(); int type; while ((type=parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { } } public static final int convertValueToList(CharSequence value, String[] options, int defaultValue) { if (null != value) { for (int i = 0; i < options.length; i++) { if (value.equals(options[i])) return i; } } return defaultValue; } public static final boolean convertValueToBoolean(CharSequence value, boolean defaultValue) { boolean result = false; if (null == value) return defaultValue; if (value.equals("1") || value.equals("true") || value.equals("TRUE")) result = true; return result; } public static final int convertValueToInt(CharSequence charSeq, int defaultValue) { if (null == charSeq) return defaultValue; String nm = charSeq.toString(); // XXX This code is copied from Integer.decode() so we don't // have to instantiate an Integer! int value; int sign = 1; int index = 0; int len = nm.length(); int base = 10; if ('-' == nm.charAt(0)) { sign = -1; index++; } if ('0' == nm.charAt(index)) { // Quick check for a zero by itself if (index == (len - 1)) return 0; char c = nm.charAt(index + 1); if ('x' == c || 'X' == c) { index += 2; base = 16; } else { index++; base = 8; } } else if ('#' == nm.charAt(index)) { index++; base = 16; } return Integer.parseInt(nm.substring(index), base) * sign; } public static int convertValueToUnsignedInt(String value, int defaultValue) { if (null == value) { return defaultValue; } return parseUnsignedIntAttribute(value); } public static int parseUnsignedIntAttribute(CharSequence charSeq) { String value = charSeq.toString(); long bits; int index = 0; int len = value.length(); int base = 10; if ('0' == value.charAt(index)) { // Quick check for zero by itself if (index == (len - 1)) return 0; char c = value.charAt(index + 1); if ('x' == c || 'X' == c) { // check for hex index += 2; base = 16; } else { // check for octal index++; base = 8; } } else if ('#' == value.charAt(index)) { index++; base = 16; } return (int) Long.parseLong(value.substring(index), base); } /** * Flatten a Map into an output stream as XML. The map can later be * read back with readMapXml(). * * @param val The map to be flattened. * @param out Where to write the XML data. * * @see #writeMapXml(Map, String, XmlSerializer) * @see #writeListXml * @see #writeValueXml * @see #readMapXml */ public static final void writeMapXml(Map val, OutputStream out) throws XmlPullParserException, java.io.IOException { XmlSerializer serializer = new FastXmlSerializer(); serializer.setOutput(out, "utf-8"); serializer.startDocument(null, true); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); writeMapXml(val, null, serializer); serializer.endDocument(); } /** * Flatten a List into an output stream as XML. The list can later be * read back with readListXml(). * * @param val The list to be flattened. * @param out Where to write the XML data. * * @see #writeListXml(List, String, XmlSerializer) * @see #writeMapXml * @see #writeValueXml * @see #readListXml */ public static final void writeListXml(List val, OutputStream out) throws XmlPullParserException, java.io.IOException { XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(out, "utf-8"); serializer.startDocument(null, true); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); writeListXml(val, null, serializer); serializer.endDocument(); } /** * Flatten a Map into an XmlSerializer. The map can later be read back * with readThisMapXml(). * * @param val The map to be flattened. * @param name Name attribute to include with this list's tag, or null for * none. * @param out XmlSerializer to write the map into. * * @see #writeMapXml(Map, OutputStream) * @see #writeListXml * @see #writeValueXml * @see #readMapXml */ public static final void writeMapXml(Map val, String name, XmlSerializer out) throws XmlPullParserException, java.io.IOException { if (val == null) { out.startTag(null, "null"); out.endTag(null, "null"); return; } Set s = val.entrySet(); Iterator i = s.iterator(); out.startTag(null, "map"); if (name != null) { out.attribute(null, "name", name); } while (i.hasNext()) { Map.Entry e = (Map.Entry)i.next(); writeValueXml(e.getValue(), (String)e.getKey(), out); } out.endTag(null, "map"); } /** * Flatten a List into an XmlSerializer. The list can later be read back * with readThisListXml(). * * @param val The list to be flattened. * @param name Name attribute to include with this list's tag, or null for * none. * @param out XmlSerializer to write the list into. * * @see #writeListXml(List, OutputStream) * @see #writeMapXml * @see #writeValueXml * @see #readListXml */ public static final void writeListXml(List val, String name, XmlSerializer out) throws XmlPullParserException, java.io.IOException { if (val == null) { out.startTag(null, "null"); out.endTag(null, "null"); return; } out.startTag(null, "list"); if (name != null) { out.attribute(null, "name", name); } int N = val.size(); int i=0; while (i < N) { writeValueXml(val.get(i), null, out); i++; } out.endTag(null, "list"); } public static final void writeSetXml(Set val, String name, XmlSerializer out) throws XmlPullParserException, java.io.IOException { if (val == null) { out.startTag(null, "null"); out.endTag(null, "null"); return; } out.startTag(null, "set"); if (name != null) { out.attribute(null, "name", name); } for (Object v : val) { writeValueXml(v, null, out); } out.endTag(null, "set"); } /** * Flatten a byte[] into an XmlSerializer. The list can later be read back * with readThisByteArrayXml(). * * @param val The byte array to be flattened. * @param name Name attribute to include with this array's tag, or null for * none. * @param out XmlSerializer to write the array into. * * @see #writeMapXml * @see #writeValueXml */ public static final void writeByteArrayXml(byte[] val, String name, XmlSerializer out) throws XmlPullParserException, java.io.IOException { if (val == null) { out.startTag(null, "null"); out.endTag(null, "null"); return; } out.startTag(null, "byte-array"); if (name != null) { out.attribute(null, "name", name); } final int N = val.length; out.attribute(null, "num", Integer.toString(N)); StringBuilder sb = new StringBuilder(val.length*2); for (int i=0; i<N; i++) { int b = val[i]; int h = b>>4; sb.append(h >= 10 ? ('a'+h-10) : ('0'+h)); h = b&0xff; sb.append(h >= 10 ? ('a'+h-10) : ('0'+h)); } out.text(sb.toString()); out.endTag(null, "byte-array"); } /** * Flatten an int[] into an XmlSerializer. The list can later be read back * with readThisIntArrayXml(). * * @param val The int array to be flattened. * @param name Name attribute to include with this array's tag, or null for * none. * @param out XmlSerializer to write the array into. * * @see #writeMapXml * @see #writeValueXml * @see #readThisIntArrayXml */ public static final void writeIntArrayXml(int[] val, String name, XmlSerializer out) throws XmlPullParserException, java.io.IOException { if (val == null) { out.startTag(null, "null"); out.endTag(null, "null"); return; } out.startTag(null, "int-array"); if (name != null) { out.attribute(null, "name", name); } final int N = val.length; out.attribute(null, "num", Integer.toString(N)); for (int i=0; i<N; i++) { out.startTag(null, "item"); out.attribute(null, "value", Integer.toString(val[i])); out.endTag(null, "item"); } out.endTag(null, "int-array"); } /** * Flatten an object's value into an XmlSerializer. The value can later * be read back with readThisValueXml(). * * Currently supported value types are: null, String, Integer, Long, * Float, Double Boolean, Map, List. * * @param v The object to be flattened. * @param name Name attribute to include with this value's tag, or null * for none. * @param out XmlSerializer to write the object into. * * @see #writeMapXml * @see #writeListXml * @see #readValueXml */ public static final void writeValueXml(Object v, String name, XmlSerializer out) throws XmlPullParserException, java.io.IOException { String typeStr; if (v == null) { out.startTag(null, "null"); if (name != null) { out.attribute(null, "name", name); } out.endTag(null, "null"); return; } else if (v instanceof String) { out.startTag(null, "string"); if (name != null) { out.attribute(null, "name", name); } out.text(v.toString()); out.endTag(null, "string"); return; } else if (v instanceof Integer) { typeStr = "int"; } else if (v instanceof Long) { typeStr = "long"; } else if (v instanceof Float) { typeStr = "float"; } else if (v instanceof Double) { typeStr = "double"; } else if (v instanceof Boolean) { typeStr = "boolean"; } else if (v instanceof byte[]) { writeByteArrayXml((byte[])v, name, out); return; } else if (v instanceof int[]) { writeIntArrayXml((int[])v, name, out); return; } else if (v instanceof Map) { writeMapXml((Map)v, name, out); return; } else if (v instanceof List) { writeListXml((List)v, name, out); return; } else if (v instanceof Set) { writeSetXml((Set)v, name, out); return; } else if (v instanceof CharSequence) { // XXX This is to allow us to at least write something if // we encounter styled text... but it means we will drop all // of the styling information. :( out.startTag(null, "string"); if (name != null) { out.attribute(null, "name", name); } out.text(v.toString()); out.endTag(null, "string"); return; } else { throw new RuntimeException("writeValueXml: unable to write value " + v); } out.startTag(null, typeStr); if (name != null) { out.attribute(null, "name", name); } out.attribute(null, "value", v.toString()); out.endTag(null, typeStr); } /** * Read a HashMap from an InputStream containing XML. The stream can * previously have been written by writeMapXml(). * * @param in The InputStream from which to read. * * @return HashMap The resulting map. * * @see #readListXml * @see #readValueXml * @see #readThisMapXml * #see #writeMapXml */ public static final HashMap readMapXml(InputStream in) throws XmlPullParserException, java.io.IOException { XmlPullParser parser = Xml.newPullParser(); parser.setInput(in, null); return (HashMap)readValueXml(parser, new String[1]); } /** * Read an ArrayList from an InputStream containing XML. The stream can * previously have been written by writeListXml(). * * @param in The InputStream from which to read. * * @return ArrayList The resulting list. * * @see #readMapXml * @see #readValueXml * @see #readThisListXml * @see #writeListXml */ public static final ArrayList readListXml(InputStream in) throws XmlPullParserException, java.io.IOException { XmlPullParser parser = Xml.newPullParser(); parser.setInput(in, null); return (ArrayList)readValueXml(parser, new String[1]); } /** * Read a HashSet from an InputStream containing XML. The stream can * previously have been written by writeSetXml(). * * @param in The InputStream from which to read. * * @return HashSet The resulting set. * * @throws XmlPullParserException * @throws java.io.IOException * * @see #readValueXml * @see #readThisSetXml * @see #writeSetXml */ public static final HashSet readSetXml(InputStream in) throws XmlPullParserException, java.io.IOException { XmlPullParser parser = Xml.newPullParser(); parser.setInput(in, null); return (HashSet) readValueXml(parser, new String[1]); } /** * Read a HashMap object from an XmlPullParser. The XML data could * previously have been generated by writeMapXml(). The XmlPullParser * must be positioned <em>after</em> the tag that begins the map. * * @param parser The XmlPullParser from which to read the map data. * @param endTag Name of the tag that will end the map, usually "map". * @param name An array of one string, used to return the name attribute * of the map's tag. * * @return HashMap The newly generated map. * * @see #readMapXml */ public static final HashMap readThisMapXml(XmlPullParser parser, String endTag, String[] name) throws XmlPullParserException, java.io.IOException { HashMap map = new HashMap(); int eventType = parser.getEventType(); do { if (eventType == parser.START_TAG) { Object val = readThisValueXml(parser, name); if (name[0] != null) { //System.out.println("Adding to map: " + name + " -> " + val); map.put(name[0], val); } else { throw new XmlPullParserException( "Map value without name attribute: " + parser.getName()); } } else if (eventType == parser.END_TAG) { if (parser.getName().equals(endTag)) { return map; } throw new XmlPullParserException( "Expected " + endTag + " end tag at: " + parser.getName()); } eventType = parser.next(); } while (eventType != parser.END_DOCUMENT); throw new XmlPullParserException( "Document ended before " + endTag + " end tag"); } /** * Read an ArrayList object from an XmlPullParser. The XML data could * previously have been generated by writeListXml(). The XmlPullParser * must be positioned <em>after</em> the tag that begins the list. * * @param parser The XmlPullParser from which to read the list data. * @param endTag Name of the tag that will end the list, usually "list". * @param name An array of one string, used to return the name attribute * of the list's tag. * * @return HashMap The newly generated list. * * @see #readListXml */ public static final ArrayList readThisListXml(XmlPullParser parser, String endTag, String[] name) throws XmlPullParserException, java.io.IOException { ArrayList list = new ArrayList(); int eventType = parser.getEventType(); do { if (eventType == parser.START_TAG) { Object val = readThisValueXml(parser, name); list.add(val); //System.out.println("Adding to list: " + val); } else if (eventType == parser.END_TAG) { if (parser.getName().equals(endTag)) { return list; } throw new XmlPullParserException( "Expected " + endTag + " end tag at: " + parser.getName()); } eventType = parser.next(); } while (eventType != parser.END_DOCUMENT); throw new XmlPullParserException( "Document ended before " + endTag + " end tag"); } /** * Read a HashSet object from an XmlPullParser. The XML data could previously * have been generated by writeSetXml(). The XmlPullParser must be positioned * <em>after</em> the tag that begins the set. * * @param parser The XmlPullParser from which to read the set data. * @param endTag Name of the tag that will end the set, usually "set". * @param name An array of one string, used to return the name attribute * of the set's tag. * * @return HashSet The newly generated set. * * @throws XmlPullParserException * @throws java.io.IOException * * @see #readSetXml */ public static final HashSet readThisSetXml(XmlPullParser parser, String endTag, String[] name) throws XmlPullParserException, java.io.IOException { HashSet set = new HashSet(); int eventType = parser.getEventType(); do { if (eventType == parser.START_TAG) { Object val = readThisValueXml(parser, name); set.add(val); //System.out.println("Adding to set: " + val); } else if (eventType == parser.END_TAG) { if (parser.getName().equals(endTag)) { return set; } throw new XmlPullParserException( "Expected " + endTag + " end tag at: " + parser.getName()); } eventType = parser.next(); } while (eventType != parser.END_DOCUMENT); throw new XmlPullParserException( "Document ended before " + endTag + " end tag"); } /** * Read an int[] object from an XmlPullParser. The XML data could * previously have been generated by writeIntArrayXml(). The XmlPullParser * must be positioned <em>after</em> the tag that begins the list. * * @param parser The XmlPullParser from which to read the list data. * @param endTag Name of the tag that will end the list, usually "list". * @param name An array of one string, used to return the name attribute * of the list's tag. * * @return Returns a newly generated int[]. * * @see #readListXml */ public static final int[] readThisIntArrayXml(XmlPullParser parser, String endTag, String[] name) throws XmlPullParserException, java.io.IOException { int num; try { num = Integer.parseInt(parser.getAttributeValue(null, "num")); } catch (NullPointerException e) { throw new XmlPullParserException( "Need num attribute in byte-array"); } catch (NumberFormatException e) { throw new XmlPullParserException( "Not a number in num attribute in byte-array"); } int[] array = new int[num]; int i = 0; int eventType = parser.getEventType(); do { if (eventType == parser.START_TAG) { if (parser.getName().equals("item")) { try { array[i] = Integer.parseInt( parser.getAttributeValue(null, "value")); } catch (NullPointerException e) { throw new XmlPullParserException( "Need value attribute in item"); } catch (NumberFormatException e) { throw new XmlPullParserException( "Not a number in value attribute in item"); } } else { throw new XmlPullParserException( "Expected item tag at: " + parser.getName()); } } else if (eventType == parser.END_TAG) { if (parser.getName().equals(endTag)) { return array; } else if (parser.getName().equals("item")) { i++; } else { throw new XmlPullParserException( "Expected " + endTag + " end tag at: " + parser.getName()); } } eventType = parser.next(); } while (eventType != parser.END_DOCUMENT); throw new XmlPullParserException( "Document ended before " + endTag + " end tag"); } /** * Read a flattened object from an XmlPullParser. The XML data could * previously have been written with writeMapXml(), writeListXml(), or * writeValueXml(). The XmlPullParser must be positioned <em>at</em> the * tag that defines the value. * * @param parser The XmlPullParser from which to read the object. * @param name An array of one string, used to return the name attribute * of the value's tag. * * @return Object The newly generated value object. * * @see #readMapXml * @see #readListXml * @see #writeValueXml */ public static final Object readValueXml(XmlPullParser parser, String[] name) throws XmlPullParserException, java.io.IOException { int eventType = parser.getEventType(); do { if (eventType == parser.START_TAG) { return readThisValueXml(parser, name); } else if (eventType == parser.END_TAG) { throw new XmlPullParserException( "Unexpected end tag at: " + parser.getName()); } else if (eventType == parser.TEXT) { throw new XmlPullParserException( "Unexpected text: " + parser.getText()); } eventType = parser.next(); } while (eventType != parser.END_DOCUMENT); throw new XmlPullParserException( "Unexpected end of document"); } private static final Object readThisValueXml(XmlPullParser parser, String[] name) throws XmlPullParserException, java.io.IOException { final String valueName = parser.getAttributeValue(null, "name"); final String tagName = parser.getName(); //System.out.println("Reading this value tag: " + tagName + ", name=" + valueName); Object res; if (tagName.equals("null")) { res = null; } else if (tagName.equals("string")) { String value = ""; int eventType; while ((eventType = parser.next()) != parser.END_DOCUMENT) { if (eventType == parser.END_TAG) { if (parser.getName().equals("string")) { name[0] = valueName; //System.out.println("Returning value for " + valueName + ": " + value); return value; } throw new XmlPullParserException( "Unexpected end tag in <string>: " + parser.getName()); } else if (eventType == parser.TEXT) { value += parser.getText(); } else if (eventType == parser.START_TAG) { throw new XmlPullParserException( "Unexpected start tag in <string>: " + parser.getName()); } } throw new XmlPullParserException( "Unexpected end of document in <string>"); } else if ((res = readThisPrimitiveValueXml(parser, tagName)) != null) { // all work already done by readThisPrimitiveValueXml } else if (tagName.equals("int-array")) { parser.next(); res = readThisIntArrayXml(parser, "int-array", name); name[0] = valueName; //System.out.println("Returning value for " + valueName + ": " + res); return res; } else if (tagName.equals("map")) { parser.next(); res = readThisMapXml(parser, "map", name); name[0] = valueName; //System.out.println("Returning value for " + valueName + ": " + res); return res; } else if (tagName.equals("list")) { parser.next(); res = readThisListXml(parser, "list", name); name[0] = valueName; //System.out.println("Returning value for " + valueName + ": " + res); return res; } else if (tagName.equals("set")) { parser.next(); res = readThisSetXml(parser, "set", name); name[0] = valueName; //System.out.println("Returning value for " + valueName + ": " + res); return res; } else { throw new XmlPullParserException( "Unknown tag: " + tagName); } // Skip through to end tag. int eventType; while ((eventType = parser.next()) != parser.END_DOCUMENT) { if (eventType == parser.END_TAG) { if (parser.getName().equals(tagName)) { name[0] = valueName; //System.out.println("Returning value for " + valueName + ": " + res); return res; } throw new XmlPullParserException( "Unexpected end tag in <" + tagName + ">: " + parser.getName()); } else if (eventType == parser.TEXT) { throw new XmlPullParserException( "Unexpected text in <" + tagName + ">: " + parser.getName()); } else if (eventType == parser.START_TAG) { throw new XmlPullParserException( "Unexpected start tag in <" + tagName + ">: " + parser.getName()); } } throw new XmlPullParserException( "Unexpected end of document in <" + tagName + ">"); } private static final Object readThisPrimitiveValueXml(XmlPullParser parser, String tagName) throws XmlPullParserException, java.io.IOException { try { if (tagName.equals("int")) { return Integer.parseInt(parser.getAttributeValue(null, "value")); } else if (tagName.equals("long")) { return Long.valueOf(parser.getAttributeValue(null, "value")); } else if (tagName.equals("float")) { return new Float(parser.getAttributeValue(null, "value")); } else if (tagName.equals("double")) { return new Double(parser.getAttributeValue(null, "value")); } else if (tagName.equals("boolean")) { return Boolean.valueOf(parser.getAttributeValue(null, "value")); } else { return null; } } catch (NullPointerException e) { throw new XmlPullParserException("Need value attribute in <" + tagName + ">"); } catch (NumberFormatException e) { throw new XmlPullParserException( "Not a number in value attribute in <" + tagName + ">"); } } public static final void beginDocument(XmlPullParser parser, String firstElementName) throws XmlPullParserException, IOException { int type; while ((type=parser.next()) != parser.START_TAG && type != parser.END_DOCUMENT) { ; } if (type != parser.START_TAG) { throw new XmlPullParserException("No start tag found"); } if (!parser.getName().equals(firstElementName)) { throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() + ", expected " + firstElementName); } } public static final void nextElement(XmlPullParser parser) throws XmlPullParserException, IOException { int type; while ((type=parser.next()) != parser.START_TAG && type != parser.END_DOCUMENT) { ; } } public static boolean nextElementWithin(XmlPullParser parser, int outerDepth) throws IOException, XmlPullParserException { for (;;) { int type = parser.next(); if (type == XmlPullParser.END_DOCUMENT || (type == XmlPullParser.END_TAG && parser.getDepth() == outerDepth)) { return false; } if (type == XmlPullParser.START_TAG && parser.getDepth() == outerDepth + 1) { return true; } } } public static int readIntAttribute(XmlPullParser in, String name) throws IOException { final String value = in.getAttributeValue(null, name); try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new ProtocolException("problem parsing " + name + "=" + value + " as int"); } } public static void writeIntAttribute(XmlSerializer out, String name, int value) throws IOException { out.attribute(null, name, Integer.toString(value)); } public static long readLongAttribute(XmlPullParser in, String name, long defaultValue) { final String value = in.getAttributeValue(null, name); try { return Long.parseLong(value); } catch (NumberFormatException e) { return defaultValue; } } public static long readLongAttribute(XmlPullParser in, String name) throws IOException { final String value = in.getAttributeValue(null, name); try { return Long.parseLong(value); } catch (NumberFormatException e) { throw new ProtocolException("problem parsing " + name + "=" + value + " as long"); } } public static void writeLongAttribute(XmlSerializer out, String name, long value) throws IOException { out.attribute(null, name, Long.toString(value)); } public static boolean readBooleanAttribute(XmlPullParser in, String name) { final String value = in.getAttributeValue(null, name); return Boolean.parseBoolean(value); } public static void writeBooleanAttribute(XmlSerializer out, String name, boolean value) throws IOException { out.attribute(null, name, Boolean.toString(value)); } }
33,820
Java
.java
M66B/XPrivacy
2,074
527
71
2013-05-26T14:08:37Z
2019-09-05T19:16:53Z
ExampleUnitTest.java
/FileExtraction/Java_unseen/MasterGamesMG_ELFReader/app/src/test/java/com/mastergames/elfreader/ExampleUnitTest.java
package com.mastergames.elfreader; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
386
Java
.java
MasterGamesMG/ELFReader
14
4
0
2023-02-27T14:56:09Z
2023-02-28T22:54:56Z
MainActivity.java
/FileExtraction/Java_unseen/MasterGamesMG_ELFReader/app/src/main/java/com/mastergames/elfreader/MainActivity.java
package com.mastergames.elfreader; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; public class MainActivity extends AppCompatActivity { private EditText directoryOfFile; private Button readFile; private TextView archiveIsElf; private TextView architectureElf; private TextView elfEndian; private TextView elfABI; private TextView elfVersion; private TextView typeIsElfVersionABI; private TextView typeIsElf; private TextView typeIsElfPad; private Button clearOutputs; @SuppressLint("MissingInflatedId") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); directoryOfFile = findViewById(R.id.directoryoffile); readFile = findViewById(R.id.button_readfile); archiveIsElf = findViewById(R.id.isELForNot); architectureElf = findViewById(R.id.archictureiself); elfEndian = findViewById(R.id.elfEndian); elfABI = findViewById(R.id.elfAbi); elfVersion = findViewById(R.id.elfVersion); typeIsElf = findViewById(R.id.typeiself); clearOutputs = findViewById(R.id.clearoutput); readFile.setOnClickListener(new View.OnClickListener() { @SuppressLint("SetTextI18n") @Override public void onClick(View v) { try { // Open the .so file and create a FileInputStream String fileDirectory = directoryOfFile.getText().toString(); File file = new File(fileDirectory); FileInputStream fis = new FileInputStream(file); // Reading the first 52 bytes to get the ELF header byte[] header = new byte[52]; fis.read(header); // Get the ELF identifier String magic = new String(header, 0, 4); if (!magic.equals("\u007fELF")) { archiveIsElf.setText("EI_MAG : " + "Unknown"); } else { archiveIsElf.setText("EI_MAG : " + "0x7fELF (ELF)"); } // Get elf class (32-bit or 64-bit) int elfClass = header[4]; if (elfClass == 1) { architectureElf.setText("EI_CLASS : " + "ELFCLASS32 (32-bit)"); } else if (elfClass == 2) { architectureElf.setText("EI_CLASS : " + "ELFCLASS64 (64-bit)"); } else { architectureElf.setText("EI_CLASS : " + "ELFCLASSNONE (This class is invalid)"); } // Get data encoding int dataEncoding = header[5]; if (dataEncoding == 1) { elfEndian.setText("EI_DATA : " + "ELFDATA2LSB (Little-endian)"); } else if (dataEncoding == 2) { elfEndian.setText("EI_DATA : " + "ELFDATA2MSB (Big-endian)"); } else { elfEndian.setText("EI_DATA : " + "ELFDATANONE (Unknown data format)"); } // Get the ELF version int version = header[6]; if (version == 1) { elfVersion.setText("EI_VERSION : " + "EV_CURRENT (Current version)"); } else { elfVersion.setText("EI_VERSION : " + "EV_NONE (Invalid version)"); } // Get the value of the EI_OSABI byte osAbi = header[7]; String osAbiStr; switch (osAbi) { case 0: osAbiStr = "ELFOSABI_NONE/ELFOSABI_SYSV (UNIX System V ABI)"; break; case 1: osAbiStr = "ELFOSABI_HPUX (HP-UX ABI)"; break; case 2: osAbiStr = "ELFOSABI_NETBSD (NetBSD ABI)"; break; case 3: osAbiStr = "ELFOSABI_LINUX (Linux ABI)"; break; case 6: osAbiStr = "ELFOSABI_SOLARIS (Solaris ABI)"; break; case 8: osAbiStr = "ELFOSABI_IRIX (IRIX ABI)"; break; case 9: osAbiStr = "ELFOSABI_FREEBSD (FreeBSD ABI)"; break; case 10: osAbiStr = "ELFOSABI_TRU64 (TRU64 UNIX ABI)"; break; case 97: osAbiStr = "ELFOSABI_ARM (ARM architecture ABI)"; break; case (byte) 255: osAbiStr = "ELFOSABI_STANDALONE (Stand-alone (embedded) ABI)"; break; default: osAbiStr = "Unknown"; break; } elfABI.setText("EI_OSABI : " + osAbiStr); // Get ELF file type int type = header[16] + (header[17] << 8); String typeStr = ""; switch (type) { case 1: typeStr = "ET_REL (A Relocatable file)"; break; case 2: typeStr = "ET_EXEC (An Executable file)"; break; case 3: typeStr = "ET_DYN (A Shared object file)"; break; case 4: typeStr = "ET_CORE (A Core file)"; break; default: typeStr = "ET_NONE (An unknown type)"; break; } typeIsElf.setText("ET : " + typeStr); // Close FileInputStream fis.close(); } catch (FileNotFoundException e) { Toast.makeText(getApplicationContext(), "The file does not exist", Toast.LENGTH_LONG).show(); } catch (IOException e) { Toast.makeText(getApplicationContext(), "Failed to read the file", Toast.LENGTH_LONG).show(); } } }); clearOutputs.setOnClickListener(new View.OnClickListener() { @SuppressLint("SetTextI18n") @Override public void onClick(View v) { archiveIsElf.setText("EI_MAG : "); architectureElf.setText("EI_CLASS : "); elfEndian.setText("EI_DATA : "); elfVersion.setText("EI_VERSION : "); elfABI.setText("EI_OSABI : "); typeIsElf.setText("ET : "); } }); } }
7,841
Java
.java
MasterGamesMG/ELFReader
14
4
0
2023-02-27T14:56:09Z
2023-02-28T22:54:56Z
ExampleInstrumentedTest.java
/FileExtraction/Java_unseen/MasterGamesMG_ELFReader/app/src/androidTest/java/com/mastergames/elfreader/ExampleInstrumentedTest.java
package com.mastergames.elfreader; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.mastergames.elfreader", appContext.getPackageName()); } }
764
Java
.java
MasterGamesMG/ELFReader
14
4
0
2023-02-27T14:56:09Z
2023-02-28T22:54:56Z
ForwardsGraphTests.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/ForwardsGraphTests.java
package flow.twist.test.unit; import static flow.twist.config.AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults; import static flow.twist.config.AnalysisDirection.FORWARDS; import static flow.twist.test.util.selectors.TrackableSelectorFactory.taint; import static flow.twist.test.util.selectors.TrackableSelectorFactory.taintContains; import static flow.twist.test.util.selectors.UnitSelectorFactory.anyUnit; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitWithoutLabel; import org.junit.Ignore; import org.junit.Test; import flow.twist.SolverFactory; import flow.twist.test.util.AbstractTaintAnalysisTest; import flow.twist.test.util.AnalysisGraphVerifier; import flow.twist.test.util.AnalysisGraphVerifier.UnitNode; import flow.twist.test.util.selectors.TrackableSelector; import flow.twist.test.util.selectors.UnitSelector; public class ForwardsGraphTests extends AbstractTaintAnalysisTest { private UnitSelector forNameSelector = unitByLabel("forName"); @Override protected AnalysisGraphVerifier executeTaintAnalysis(String[] classNames) { AnalysisGraphVerifier verifier = new AnalysisGraphVerifier(); SolverFactory.runOneDirectionSolver(i2oSimpleClassForNameDefaults().direction(FORWARDS).reporter(verifier)); return verifier; } @Test public void aliasing() { AnalysisGraphVerifier verifier = runTest("java.lang.Aliasing"); UnitNode forName = verifier.find(unitInMethod("nameInput(", forNameSelector)); forName.pathTo(taint("$r3"), unitByLabel("return")); UnitNode forName2 = verifier.find(unitInMethod("nameInput2", forNameSelector)); forName2.pathTo(taint("$r2"), unitByLabel("return")); } @Test @Ignore("does not work without target for forName with classloader argument") public void beanInstantiator() { AnalysisGraphVerifier verifier = runTest("java.lang.BeanInstantiator"); UnitNode forNameSimple = verifier.find(unitInMethod("loadClass", unitByLabel("forName(java.lang.String)"))); forNameSimple.pathTo(taintContains("$r"), unitByLabel("return")); UnitNode forNameExtended = verifier.find(unitInMethod("loadClass", unitByLabel("forName(java.lang.String,"))); forNameExtended.pathTo(taintContains("$r"), unitByLabel("return")); } @Test @Ignore("does not work without target for forName with classloader argument") public void callerClassLoader() { AnalysisGraphVerifier verifier = runTest("java.lang.CallerClassLoader"); UnitNode forName = verifier.find(unitInMethod("problematicMethod", forNameSelector)); forName.pathTo(taint("$r0"), unitInMethod("leakingMethod", unitByLabel("return"))); UnitNode okForName = verifier.find(unitInMethod("okMethod", forNameSelector)); okForName.pathTo(taint("$r2"), unitByLabel("return")); } @Test public void checkPackageAccess() { AnalysisGraphVerifier verifier = runTest("java.lang.CheckPackageAccess"); UnitNode forName = verifier.find(unitInMethod("loadIt", forNameSelector)); forName.pathTo(taintContains("$r"), unitInMethod("wrapperWithCheck", unitByLabel("return"))); forName.pathTo(taintContains("$r"), unitInMethod("wrapperWithCheck(java.lang.String", unitByLabel("return"))); forName.pathTo(taintContains("$r"), unitInMethod("wrapperWithoutCheck", unitByLabel("return"))); forName.pathTo(taintContains("$r"), unitInMethod("wrapperWithoutCheck(java.lang.String", unitByLabel("return"))); } @Test public void classConstant() { AnalysisGraphVerifier verifier = runTest("java.lang.ClassConstant"); verifier.cannotFind(forNameSelector); } @Test public void classConstant2() { AnalysisGraphVerifier verifier = runTest("javax.management.remote.rmi.RMIConnectionImpl_Stub"); verifier.cannotFind(forNameSelector); } @Test public void classHierarchyHard() { AnalysisGraphVerifier verifier = runTest("java.lang.ClassHierarchyHard"); verifier.find(unitInMethod("invokeable", forNameSelector)).pathTo(taint("$r0"), unitByLabel("return")); verifier.find(unitInMethod("redundantInvokeable", forNameSelector)).pathTo(taint("$r0"), unitByLabel("return")); } @Test public void classInstanceCastedBeforeReturned() { AnalysisGraphVerifier verifier = runTest("java.lang.ClassInstanceCastedBeforeReturned"); verifier.cannotFind(unitInMethod("newInstance", unitByLabel("return"))); verifier.cannotFind(unitInMethod("explicitConstructor", unitByLabel("return"))); verifier.cannotFind(unitInMethod("allConstructors", unitByLabel("return"))); } @Test public void classInstanceReturned() { AnalysisGraphVerifier verifier = runTest("java.lang.ClassInstanceReturned"); verifier.find(unitInMethod("newInstance", forNameSelector)).pathTo(taint("result"), unitByLabel("return")); verifier.find(unitInMethod("explicitConstructor", forNameSelector)).pathTo(taint("result"), unitByLabel("return")); verifier.find(unitInMethod("allConstructors", forNameSelector)).pathTo(taint("result"), unitByLabel("return")); } @Test public void distinguishPaths() { AnalysisGraphVerifier verifier = runTest("java.lang.DistinguishPaths"); UnitNode forName = verifier.find(forNameSelector); forName.pathTo(taint("checkedResult"), unitInMethod("leakingMethod", unitByLabel("return"))); verifier.cannotFind(unitInMethod("okMethod", unitByLabel("return"))); } @Test public void exceptionalPath() { AnalysisGraphVerifier verifier = runTest("java.lang.ExceptionalPath"); UnitNode forName = verifier.find(forNameSelector); forName.pathTo(taint("$r0"), unitInMethod("test", unitByLabel("return"))); verifier.cannotFind(unitByLabel("return null")); verifier.cannotFind(unitByLabel("throw")); } @Test public void privateMethod() { AnalysisGraphVerifier verifier = runTest("java.lang.PrivateMethod"); verifier.find(forNameSelector).pathTo(taint("$r0"), unitInMethod("leakingMethod", unitByLabel("return"))); } @Test public void recursion() { AnalysisGraphVerifier verifier = runTest("java.lang.Recursion"); { UnitNode forName = verifier.find(unitInMethod("recursive(", forNameSelector)); forName.pathTo(taint("result"), unitByLabel("return result")); forName.pathTo(taint("recResult"), unitByLabel("return recResult")); } { TrackableSelector t = taint("$r0"); UnitNode forName = verifier.find(unitInMethod("recursiveA", forNameSelector)); UnitNode retAinB = forName.edge(t, unitByLabel("return $r0")).edge(t, unitInMethod("recursiveB", unitByLabel("return $r0"))); retAinB.edge(t, unitInMethod("recursiveA", unitByLabel("return $r0"))); UnitNode retBinB = retAinB.edge(t, unitInMethod("recursiveB", unitByLabel("return $r0"))); UnitNode retBinA = retBinB.edge(t, unitInMethod("recursiveA", unitByLabel("return $r0"))); retBinA.edge(t, unitInMethod("recursiveB", unitByLabel("return $r0"))); } } @Test public void returnEdgeMerge() { AnalysisGraphVerifier verifier = runTest("java.lang.ReturnEdgeMerge"); verifier.find(unitWithoutLabel("goto", unitByLabel("return result"))).assertIncomingEdges(3); } @Test public void recursionAndClassHierarchy() { AnalysisGraphVerifier verifier = runTest("java.lang.RecursionAndClassHierarchy", "java.lang.RecursionAndClassHierarchy$BaseInterface", "java.lang.RecursionAndClassHierarchy$SubClassA", "java.lang.RecursionAndClassHierarchy$SubClassB", "java.lang.RecursionAndClassHierarchy$SubClassC"); verifier.find(forNameSelector); // Just be happy that it terminates here. } @Test public void recursionClassAsParameter() { AnalysisGraphVerifier verifier = runTest("java.lang.RecursionClassAsParameter"); verifier.find(forNameSelector).pathTo(taint("c"), unitByLabel("return c")); } @Test public void validPathCheck() { AnalysisGraphVerifier verifier = runTest("java.lang.ValidPathCheck"); verifier.find(forNameSelector).pathTo(taint("$r0"), unitInMethod("a", unitByLabel("return"))); } @Test public void whiteboardGraph() { AnalysisGraphVerifier verifier = runTest("java.lang.WhiteboardGraph"); UnitNode forName = verifier.find(forNameSelector); forName.pathTo(taint("r2"), unitInMethod("notVulnerable", unitByLabel("return r2"))); verifier.cannotFind(unitInMethod("notVulnerable", unitByLabel("return r1"))); forName.pathTo(taint("r3"), unitInMethod("vulnerable", unitByLabel("return"))); } @Test public void javaUtil() { AnalysisGraphVerifier verifier = runTest("java.lang.JavaUtil", "java.util.HashMap", "java.util.Map", "java.lang.JavaUtil$CustomMapA", "java.lang.JavaUtil$CustomMapB"); verifier.cannotFind(unitInMethod("put", anyUnit())); } @Test public void impossiblePath() { AnalysisGraphVerifier verifier = runTest("java.lang.ImpossiblePath"); UnitNode forName = verifier.find(forNameSelector); forName.pathTo(taint("b"), unitByLabel("return")); } @Test public void throughGeneric() { AnalysisGraphVerifier verifier = runTest("generics.ForwardThroughGeneric"); verifier.find(forNameSelector).pathTo(taint("result"), unitInMethod("foo", unitByLabel("return"))); verifier.cannotFind(unitInMethod("$C", anyUnit())); } @Test public void outOfGeneric() { AnalysisGraphVerifier verifier = runTest("generics.ForwardOutOfGeneric"); verifier.find(forNameSelector).pathTo(taintContains("$r"), unitInMethod("clazz(", unitByLabel("return"))); verifier.cannotFind(unitInMethod("integer(", unitByLabel("return"))); verifier.find(forNameSelector).pathTo(taintContains("$r"), unitInMethod("object(", unitByLabel("return"))); } }
9,552
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
SimpleClassForNameI2OPathTests.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/SimpleClassForNameI2OPathTests.java
package flow.twist.test.unit; import static flow.twist.config.AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults; import java.util.Set; import flow.twist.SolverFactory; import flow.twist.path.Path; import flow.twist.pathchecker.FilterSingleDirectionReports; import flow.twist.reporter.CompositeReporter; import flow.twist.reporter.ResultForwardingReporter; import flow.twist.test.util.AbstractPathTests; import flow.twist.test.util.AnalysisGraphVerifier; import flow.twist.test.util.PathVerifier; import flow.twist.transformer.StoreDataTransformer; import flow.twist.transformer.path.MergeEqualSelectorStrategy; import flow.twist.transformer.path.PathBuilderResultTransformer; public class SimpleClassForNameI2OPathTests extends AbstractPathTests { @Override protected AnalysisGraphVerifier executeTaintAnalysis(String[] classNames) { AnalysisGraphVerifier verifier = new AnalysisGraphVerifier(); StoreDataTransformer<Set<Path>> dataStorage = new StoreDataTransformer<Set<Path>>(); CompositeReporter reporter = new CompositeReporter(verifier, new ResultForwardingReporter(new FilterSingleDirectionReports( new PathBuilderResultTransformer(dataStorage, new MergeEqualSelectorStrategy())))); SolverFactory.runInnerToOuterSolver(i2oSimpleClassForNameDefaults().reporter(reporter)); pathVerifier = new PathVerifier(dataStorage.getData()); return verifier; } }
1,389
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
I2OBiDiPathTests.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/I2OBiDiPathTests.java
package flow.twist.test.unit; import static flow.twist.config.AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults; import java.util.Set; import flow.twist.SolverFactory; import flow.twist.path.Path; import flow.twist.pathchecker.FilterSingleDirectionReports; import flow.twist.reporter.CompositeReporter; import flow.twist.reporter.ResultForwardingReporter; import flow.twist.test.util.AbstractPathTests; import flow.twist.test.util.AnalysisGraphVerifier; import flow.twist.test.util.PathVerifier; import flow.twist.transformer.StoreDataTransformer; import flow.twist.transformer.path.MergeEqualSelectorStrategy; import flow.twist.transformer.path.PathBuilderResultTransformer; public class I2OBiDiPathTests extends AbstractPathTests { @Override protected AnalysisGraphVerifier executeTaintAnalysis(String[] classNames) { AnalysisGraphVerifier verifier = new AnalysisGraphVerifier(); StoreDataTransformer<Set<Path>> dataStorage = new StoreDataTransformer<Set<Path>>(); CompositeReporter reporter = new CompositeReporter(verifier, new ResultForwardingReporter(new FilterSingleDirectionReports( new PathBuilderResultTransformer(dataStorage, new MergeEqualSelectorStrategy())))); SolverFactory.runBiDirectionSolver(i2oSimpleClassForNameDefaults().reporter(reporter)); pathVerifier = new PathVerifier(dataStorage.getData()); return verifier; } }
1,373
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
BackwardsGraphTests.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/BackwardsGraphTests.java
package flow.twist.test.unit; import static flow.twist.config.AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults; import static flow.twist.config.AnalysisDirection.BACKWARDS; import static flow.twist.test.util.selectors.TrackableSelectorFactory.taint; import static flow.twist.test.util.selectors.TrackableSelectorFactory.taintContains; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod; import org.junit.Ignore; import org.junit.Test; import flow.twist.SolverFactory; import flow.twist.test.util.AbstractTaintAnalysisTest; import flow.twist.test.util.AnalysisGraphVerifier; import flow.twist.test.util.AnalysisGraphVerifier.UnitNode; import flow.twist.test.util.selectors.UnitSelector; public class BackwardsGraphTests extends AbstractTaintAnalysisTest { private UnitSelector forNameSelector = unitByLabel("forName"); @Override protected AnalysisGraphVerifier executeTaintAnalysis(String[] classNames) { AnalysisGraphVerifier verifier = new AnalysisGraphVerifier(); SolverFactory.runOneDirectionSolver(i2oSimpleClassForNameDefaults().direction(BACKWARDS).reporter(verifier)); return verifier; } @Test public void aliasing() { AnalysisGraphVerifier verifier = runTest("java.lang.Aliasing"); UnitNode forName = verifier.find(unitInMethod("nameInput(", forNameSelector)); forName.pathTo(taint("name"), unitByLabel("@parameter0")); forName.pathTo(taint("name3"), unitByLabel("@parameter2")); UnitNode forName2 = verifier.find(unitInMethod("nameInput2", forNameSelector)); forName2.pathTo(taint("name"), unitByLabel("@parameter0")); } @Test @Ignore("does not work without target for forName with classloader argument") public void beanInstantiator() { AnalysisGraphVerifier verifier = runTest("java.lang.BeanInstantiator"); UnitNode forNameSimple = verifier.find(unitInMethod("loadClass", unitByLabel("forName(java.lang.String)"))); forNameSimple.pathTo(taint("className"), unitByLabel("@parameter0")); UnitNode forNameExtended = verifier.find(unitInMethod("loadClass", unitByLabel("forName(java.lang.String,"))); forNameExtended.pathTo(taint("className"), unitByLabel("@parameter0")); } @Test @Ignore("does not work without target for forName with classloader argument") public void callerClassLoader() { AnalysisGraphVerifier verifier = runTest("java.lang.CallerClassLoader"); UnitNode forName = verifier.find(unitInMethod("problematicMethod", forNameSelector)); forName.pathTo(taint("name"), unitInMethod("leakingMethod", unitByLabel("@parameter0"))); UnitNode okForName = verifier.find(unitInMethod("okMethod", forNameSelector)); okForName.pathTo(taint("name"), unitByLabel("@parameter0")); } @Test public void checkPackageAccess() { AnalysisGraphVerifier verifier = runTest("java.lang.CheckPackageAccess"); UnitNode forName = verifier.find(unitInMethod("loadIt", forNameSelector)); forName.pathTo(taint("n"), unitInMethod("wrapperWithoutCheck", unitByLabel("@parameter0"))); } @Test public void classHierarchyHard() { AnalysisGraphVerifier verifier = runTest("java.lang.ClassHierarchyHard"); verifier.find(unitInMethod("redundantInvokeable", forNameSelector)).pathTo(taintContains("red_className"), unitInMethod("redundantInvokeable", unitByLabel("@parameter0"))); verifier.find(unitInMethod("invokeable", forNameSelector)).pathTo(taintContains("inv_className"), unitInMethod("invokeable", unitByLabel("@parameter0"))); } @Test public void backwardsIntoThrow() { AnalysisGraphVerifier verifier = runTest("java.lang.BackwardsIntoThrow"); UnitNode forName = verifier.find(forNameSelector); forName.pathTo(taint("name"), unitInMethod("foo", unitByLabel("@parameter0"))); } @Test public void recursion() { AnalysisGraphVerifier verifier = runTest("java.lang.Recursion"); verifier.find(unitInMethod("recursive(", forNameSelector)).pathTo(taint("className"), unitByLabel("@parameter0")); UnitNode forName = verifier.find(unitInMethod("recursiveA", forNameSelector)); forName.pathTo(taint("className"), unitInMethod("recursiveA", unitByLabel("@parameter0"))); } @Test public void recursionAndClassHierarchy() { AnalysisGraphVerifier verifier = runTest("java.lang.RecursionAndClassHierarchy", "java.lang.RecursionAndClassHierarchy$BaseInterface", "java.lang.RecursionAndClassHierarchy$SubClassA", "java.lang.RecursionAndClassHierarchy$SubClassB", "java.lang.RecursionAndClassHierarchy$SubClassC"); verifier.find(forNameSelector); // Just be happy that it terminates here. } @Test public void stringConcatenation() { AnalysisGraphVerifier verifier = runTest("java.lang.StringConcatenation"); verifier.find(forNameSelector).pathTo(taint("name"), unitByLabel("@parameter0")); } @Test public void whiteboardGraph() { AnalysisGraphVerifier verifier = runTest("java.lang.WhiteboardGraph"); UnitNode forName = verifier.find(forNameSelector); forName.pathTo(taint("s3"), unitInMethod("notVulnerableWrapper", unitByLabel("@parameter0"))); forName.pathTo(taint("s3"), unitInMethod("vulnerable", unitByLabel("@parameter0"))); } @Test public void mergeTest() { AnalysisGraphVerifier verifier = runTest("java.lang.MergeTest"); verifier.find(unitInMethod("b(", forNameSelector)).pathTo(taint("className"), unitByLabel("@parameter0")); verifier.find(unitInMethod("c(", forNameSelector)).pathTo(taint("className"), unitByLabel("@parameter0")); } @Test public void throughGeneric() { AnalysisGraphVerifier verifier = runTest("generics.BackwardThroughGeneric"); verifier.cannotFind(forNameSelector); } @Test public void outOfGeneric() { AnalysisGraphVerifier verifier = runTest("generics.BackwardOutOfGeneric"); verifier.find(forNameSelector).pathTo(taint("name"), unitInMethod("string(", unitByLabel("@parameter0"))); verifier.cannotFind(unitInMethod("integer(", unitByLabel("@parameter0"))); verifier.find(forNameSelector).pathTo(taint("name"), unitInMethod("object(", unitByLabel("@parameter0"))); } @Test public void typeConversion() { AnalysisGraphVerifier verifier = runTest("type.TypeConversion"); verifier.cannotFind(forNameSelector); } @Test public void stringBuilderTest() { AnalysisGraphVerifier verifier = runTest("type.StringBuilderTest"); verifier.find(unitInMethod("leakStringBuilder", forNameSelector)).pathTo(taint("a"), unitByLabel("@parameter0")); verifier.find(unitInMethod("throughStringBuilder", forNameSelector)).pathTo(taint("a"), unitByLabel("@parameter0")); verifier.find(unitInMethod("trackStringBuilder", forNameSelector)).pathTo(taint("b"), unitByLabel("@parameter0")); } }
6,698
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
ForwardsFromCallablesPathTests.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/ForwardsFromCallablesPathTests.java
package flow.twist.test.unit; import static flow.twist.config.AnalysisConfigurationBuilder.forwardsFromAllParametersDefaults; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod; import java.util.Set; import org.junit.Test; import flow.twist.SolverFactory; import flow.twist.debugger.ClassNameFilter; import flow.twist.debugger.Debugger; import flow.twist.debugger.ShortConsoleDebugger; import flow.twist.path.Path; import flow.twist.reporter.CompositeReporter; import flow.twist.reporter.ResultForwardingReporter; import flow.twist.test.util.AbstractPathTests; import flow.twist.test.util.AnalysisGraphVerifier; import flow.twist.test.util.PathVerifier; import flow.twist.transformer.StoreDataTransformer; import flow.twist.transformer.path.MergeEqualSelectorStrategy; import flow.twist.transformer.path.PathBuilderResultTransformer; public class ForwardsFromCallablesPathTests extends AbstractPathTests { @Override protected AnalysisGraphVerifier executeTaintAnalysis(String[] classNames) { AnalysisGraphVerifier verifier = new AnalysisGraphVerifier(); StoreDataTransformer<Set<Path>> dataStorage = new StoreDataTransformer<Set<Path>>(); CompositeReporter reporter = new CompositeReporter(verifier, new ResultForwardingReporter(new PathBuilderResultTransformer(dataStorage, new MergeEqualSelectorStrategy()))); Debugger debugger = new Debugger(); debugger.addFilter(new ClassNameFilter(classNames)); debugger.registerListener(new ShortConsoleDebugger()); SolverFactory.runOneDirectionSolver(forwardsFromAllParametersDefaults(true).reporter(reporter).debugger(debugger)); pathVerifier = new PathVerifier(dataStorage.getData()); return verifier; } @Test public void recursion() { // for each sink two equal paths are generated because // of summary functions built for ZERO and the parameter runTest("java.lang.Recursion"); pathVerifier.totalPaths(6); pathVerifier.startsAt(unitInMethod("recursive(", unitByLabel("@parameter0"))).endsAt(unitInMethod("recursive(", unitByLabel("return"))) .times(3); pathVerifier.startsAt(unitInMethod("recursiveA(", unitByLabel("@parameter0"))).endsAt(unitInMethod("recursiveA(", unitByLabel("return"))) .times(3); } @Test public void recursionAndClassHierarchy() { // for each entry method two summaries are generated. One for the ZERO // case and one where the Parameter is tainted. The latter ones // disappear in the reported paths, due to recursion elimination in path // generation. Nevertheless, they result in equal taint paths reported // two times. runTest("java.lang.RecursionAndClassHierarchy", "java.lang.RecursionAndClassHierarchy$BaseInterface", "java.lang.RecursionAndClassHierarchy$SubClassA", "java.lang.RecursionAndClassHierarchy$SubClassB", "java.lang.RecursionAndClassHierarchy$SubClassC"); pathVerifier.totalPaths(8); } @Test public void combiningMultipleTargets() { runTest("callersensitive.CombiningMultipleTargets"); pathVerifier.totalPaths(1); } }
3,102
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
GenericCallerSensitiveI2OPathTests.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/GenericCallerSensitiveI2OPathTests.java
package flow.twist.test.unit; import static flow.twist.config.AnalysisConfigurationBuilder.i2oGenericCallerSensitiveDefaults; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod; import java.util.Set; import org.junit.Ignore; import org.junit.Test; import flow.twist.SolverFactory; import flow.twist.path.Path; import flow.twist.reporter.CompositeReporter; import flow.twist.reporter.ResultForwardingReporter; import flow.twist.test.util.AbstractPathTests; import flow.twist.test.util.AnalysisGraphVerifier; import flow.twist.test.util.PathVerifier; import flow.twist.transformer.StoreDataTransformer; import flow.twist.transformer.path.MergeEqualSelectorStrategy; import flow.twist.transformer.path.PathBuilderResultTransformer; public class GenericCallerSensitiveI2OPathTests extends AbstractPathTests { @Override protected AnalysisGraphVerifier executeTaintAnalysis(String[] classNames) { AnalysisGraphVerifier verifier = new AnalysisGraphVerifier(); StoreDataTransformer<Set<Path>> dataStorage = new StoreDataTransformer<Set<Path>>(); CompositeReporter reporter = new CompositeReporter(verifier, new ResultForwardingReporter(new PathBuilderResultTransformer(dataStorage, new MergeEqualSelectorStrategy()))); SolverFactory.runInnerToOuterSolver(i2oGenericCallerSensitiveDefaults().reporter(reporter)); pathVerifier = new PathVerifier(dataStorage.getData()); return verifier; } @Test public void callerSensitiveIntegrityAndConfidentiality() { runTest("callersensitive.IntegrityAndConfidentiality"); pathVerifier.startsAt(unitInMethod("foo(", unitByLabel("@parameter0"))).endsAt(unitByLabel("return")).once(); } @Test @Ignore("Current configuration filters sinks with one direction only") public void callerSensitiveIntegrity() { runTest("callersensitive.Integrity"); pathVerifier.startsAt(unitInMethod("foo(", unitByLabel("dangerous"))).endsAt(unitByLabel("@parameter0")).once(); } @Test @Ignore("Current configuration filters sinks with one direction only") public void callerSensitiveConfidentiality() { runTest("callersensitive.Confidentiality"); pathVerifier.startsAt(unitInMethod("foo(", unitByLabel("dangerous"))).endsAt(unitByLabel("return")).once(); } }
2,319
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
StateBasedPathTests.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/StateBasedPathTests.java
package flow.twist.test.unit; import static flow.twist.config.AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import flow.twist.SolverFactory; import flow.twist.reporter.CompositeReporter; import flow.twist.states.StateMachineBasedPathReporter; import flow.twist.states.StatePlotter; import flow.twist.test.util.AbstractPathTests; import flow.twist.test.util.AnalysisGraphVerifier; import flow.twist.test.util.PathVerifier; public class StateBasedPathTests extends AbstractPathTests { private StatePlotter statePlotter; @Rule public TestWatcher watcher = new TestWatcher() { @Override public void failed(Throwable e, Description description) { StringBuilder builder = new StringBuilder(); builder.append("tmp/"); builder.append(StateBasedPathTests.this.getClass().getSimpleName()); builder.append("_"); builder.append(description.getMethodName()); statePlotter.write(builder.toString() + "_states"); } }; @Override protected AnalysisGraphVerifier executeTaintAnalysis(String[] classNames) { AnalysisGraphVerifier verifier = new AnalysisGraphVerifier(); StateMachineBasedPathReporter vulnerablePathReporter = new StateMachineBasedPathReporter(); CompositeReporter reporter = new CompositeReporter(verifier, vulnerablePathReporter); SolverFactory.runInnerToOuterSolver(i2oSimpleClassForNameDefaults().reporter(reporter)); // SolverFactory.runBiDirectionSolver(reporter); pathVerifier = new PathVerifier(vulnerablePathReporter.getValidPaths()); statePlotter = new StatePlotter(vulnerablePathReporter); return verifier; } @Test public void decoratingClassHierarchyWithDifferentBehaviors() { runTest("java.lang.DecoratingClassHierarchyWithDifferentBehaviors", "java.lang.DecoratingClassHierarchyWithDifferentBehaviors$BaseInterface", "java.lang.DecoratingClassHierarchyWithDifferentBehaviors$SubClassA", "java.lang.DecoratingClassHierarchyWithDifferentBehaviors$SubClassB", "java.lang.DecoratingClassHierarchyWithDifferentBehaviors$SubClassC"); pathVerifier.totalPaths(2); pathVerifier.startsAt(unitInMethod("SubClassC", unitByLabel("@parameter0"))).endsAt(unitInMethod("SubClassC", unitByLabel("return"))).once(); pathVerifier.startsAt(unitInMethod("SubClassA", unitByLabel("@parameter1"))).endsAt(unitInMethod("SubClassA", unitByLabel("return"))).once(); } @Override @Ignore public void recursion() { } @Override @Ignore public void recursivePopState() { } }
2,758
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
AnalysisUtilTest.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/AnalysisUtilTest.java
package flow.twist.test.unit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Set; import org.junit.Test; import soot.RefType; import soot.Scene; import soot.SootMethod; import flow.twist.test.util.AbstractAnalysisTest; import flow.twist.util.AnalysisUtil; public class AnalysisUtilTest extends AbstractAnalysisTest { @Test public void assignableToSuperClass() { runAnalysis(new TestAnalysis("analysisutil.SubTypeTests") { @Override protected void executeAnalysis() { RefType typeA = Scene.v().getSootClass("analysisutil.SubTypeTests$A").getType(); RefType typeB = Scene.v().getSootClass("analysisutil.SubTypeTests$B").getType(); assertTrue(AnalysisUtil.isAssignable(typeB, typeA)); assertFalse(AnalysisUtil.isAssignable(typeA, typeB)); } }); } @Test public void assignableToInterface() { runAnalysis(new TestAnalysis("analysisutil.SubTypeTests") { @Override protected void executeAnalysis() { RefType typeI = Scene.v().getSootClass("analysisutil.SubTypeTests$I").getType(); RefType typeJ = Scene.v().getSootClass("analysisutil.SubTypeTests$J").getType(); assertTrue(AnalysisUtil.isAssignable(typeJ, typeI)); assertFalse(AnalysisUtil.isAssignable(typeI, typeJ)); } }); } @Test public void assignableToIdentity() { runAnalysis(new TestAnalysis("analysisutil.SubTypeTests") { @Override protected void executeAnalysis() { RefType typeA = Scene.v().getSootClass("analysisutil.SubTypeTests$A").getType(); RefType typeB = Scene.v().getSootClass("analysisutil.SubTypeTests$B").getType(); RefType typeI = Scene.v().getSootClass("analysisutil.SubTypeTests$I").getType(); RefType typeJ = Scene.v().getSootClass("analysisutil.SubTypeTests$J").getType(); assertTrue(AnalysisUtil.isAssignable(typeA, typeA)); assertTrue(AnalysisUtil.isAssignable(typeB, typeB)); assertTrue(AnalysisUtil.isAssignable(typeI, typeI)); assertTrue(AnalysisUtil.isAssignable(typeJ, typeJ)); } }); } @Test public void unassignableToDifferentHierarchy() { runAnalysis(new TestAnalysis("analysisutil.SubTypeTests") { @Override protected void executeAnalysis() { RefType typeA = Scene.v().getSootClass("analysisutil.SubTypeTests$A").getType(); RefType typeB = Scene.v().getSootClass("analysisutil.SubTypeTests$B").getType(); RefType typeI = Scene.v().getSootClass("analysisutil.SubTypeTests$I").getType(); RefType typeJ = Scene.v().getSootClass("analysisutil.SubTypeTests$J").getType(); assertFalse(AnalysisUtil.isAssignable(typeA, typeI)); assertFalse(AnalysisUtil.isAssignable(typeA, typeJ)); assertFalse(AnalysisUtil.isAssignable(typeB, typeI)); assertFalse(AnalysisUtil.isAssignable(typeB, typeJ)); } }); } @Test public void initDeclInInterface() { runAnalysis(new TestAnalysis("analysisutil.InitiallyDeclaredMethodTests") { @Override protected void executeAnalysis() { SootMethod method = Scene.v().getSootClass("analysisutil.InitiallyDeclaredMethodTests$A").getMethod("void inInterface()"); Set<SootMethod> set = AnalysisUtil.getInitialDeclaration(method); assertEquals(1, set.size()); assertTrue(set.iterator().next().toString().contains("$I")); } }); } @Test public void initDeclInInterfaceOfSupertype() { runAnalysis(new TestAnalysis("analysisutil.InitiallyDeclaredMethodTests") { @Override protected void executeAnalysis() { SootMethod method = Scene.v().getSootClass("analysisutil.InitiallyDeclaredMethodTests$B").getMethod("void inInterface()"); Set<SootMethod> set = AnalysisUtil.getInitialDeclaration(method); assertEquals(1, set.size()); assertTrue(set.iterator().next().toString().contains("$I")); } }); } @Test public void initDeclInExtendedInterfaceOfSupertype() { runAnalysis(new TestAnalysis("analysisutil.InitiallyDeclaredMethodTests") { @Override protected void executeAnalysis() { SootMethod method = Scene.v().getSootClass("analysisutil.InitiallyDeclaredMethodTests$C").getMethod("void inInterface()"); Set<SootMethod> set = AnalysisUtil.getInitialDeclaration(method); assertEquals(1, set.size()); assertTrue(set.iterator().next().toString().contains("$I")); } }); } @Test public void initDeclInSupertype() { runAnalysis(new TestAnalysis("analysisutil.InitiallyDeclaredMethodTests") { @Override protected void executeAnalysis() { SootMethod method = Scene.v().getSootClass("analysisutil.InitiallyDeclaredMethodTests$B").getMethod("void inSuperType()"); Set<SootMethod> set = AnalysisUtil.getInitialDeclaration(method); assertEquals(1, set.size()); assertTrue(set.iterator().next().toString().contains("$A")); } }); } @Test public void initDeclInSupertypeWithGap() { runAnalysis(new TestAnalysis("analysisutil.InitiallyDeclaredMethodTests") { @Override protected void executeAnalysis() { SootMethod method = Scene.v().getSootClass("analysisutil.InitiallyDeclaredMethodTests$E").getMethod("void inSuperType()"); Set<SootMethod> set = AnalysisUtil.getInitialDeclaration(method); assertEquals(1, set.size()); assertTrue(set.iterator().next().toString().contains("$A")); } }); } }
5,299
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
PathBuilderTest.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/transformer/path/PathBuilderTest.java
package flow.twist.test.unit.transformer.path; import static com.google.common.collect.Sets.newHashSet; import static flow.twist.test.util.TestTaint.setEqual; import static flow.twist.test.util.selectors.UnitSelectorFactory.specificUnit; import static flow.twist.trackable.Zero.ZERO; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import soot.SootMethod; import soot.Unit; import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import flow.twist.config.AnalysisConfiguration; import flow.twist.config.AnalysisContext; import flow.twist.path.Path; import flow.twist.reporter.Report; import flow.twist.reporter.TrackableGraphPlotter; import flow.twist.targets.AnalysisTarget; import flow.twist.test.util.PathVerifier; import flow.twist.test.util.PathVerifier.PathSelector; import flow.twist.test.util.TestTaint; import flow.twist.test.util.TestTaintPopFromStack; import flow.twist.test.util.TestTaintPushOnStack; import flow.twist.trackable.Trackable; import flow.twist.trackable.Zero; import flow.twist.transformer.path.MergeEqualSelectorStrategy; import flow.twist.transformer.path.PathBuilder; public class PathBuilderTest { private PathBuilder sut; private BiDiInterproceduralCFG<Unit, SootMethod> icfg; private AnalysisContext context; private Unit targetUnit; private Multimap<Unit, SootMethod> callSiteToDeclarationMapping; private TrackableGraphPlotter plotter; @Rule public TestWatcher watcher = new TestWatcher() { @Override public void failed(Throwable e, Description description) { StringBuilder builder = new StringBuilder(); builder.append("tmp/"); builder.append(PathBuilderTest.this.getClass().getSimpleName()); builder.append("_"); builder.append(description.getMethodName()); plotter.writeFile(builder.toString()); } }; @SuppressWarnings("unchecked") @Before public void setup() { plotter = new TrackableGraphPlotter(); sut = new PathBuilder(new MergeEqualSelectorStrategy()) { @Override protected Set<SootMethod> getInitialDeclaration(Unit callSite) { return newHashSet(callSiteToDeclarationMapping.get(callSite)); } }; callSiteToDeclarationMapping = HashMultimap.create(); icfg = mock(BiDiInterproceduralCFG.class); context = new AnalysisContext(new AnalysisConfiguration(Lists.<AnalysisTarget> newLinkedList(), null, null, null, null, null, null), icfg); targetUnit = mock(Unit.class); when(targetUnit.toString()).thenReturn("targetUnit"); } @Test public void trivialIntraproceduralPath() { TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); PathVerifier verifier = pathVerifierForReportAt(a2); verifier.totalPaths(1); verifier.startsAt(specificUnit(a1.sourceUnit)).contains(specificUnit(a2.sourceUnit)) .endsAt(specificUnit(targetUnit)).times(1); } @Test public void trivialInterproceduralPath() { Unit callSite = mock(Unit.class); TestTaint a1 = new TestTaintPushOnStack(ZERO, callSite, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); PathVerifier verifier = pathVerifierForReportAt(a2); verifier.totalPaths(1); PathSelector selector = verifier.startsAt(specificUnit(a1.sourceUnit)).contains(specificUnit(a2.sourceUnit)) .endsAt(specificUnit(targetUnit)); selector.times(1); selector.assertStack(callSite); } @Test public void invalidCallStack() { TestTaint a1 = new TestTaintPopFromStack(mock(Unit.class), ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); PathVerifier verifier = pathVerifierForReportAt(a2); verifier.totalPaths(0); } @Test public void loop() { TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint b1 = new TestTaint(a2, "b1"); TestTaint b2 = new TestTaint(b1, "b2"); TestTaint b3 = new TestTaint(b2, "b3"); a1.addNeighbor(b3); PathVerifier verifier = pathVerifierForReportAt(a3); verifier.totalPaths(1); verifier.startsAt(specificUnit(a1.sourceUnit)).doesNotContain(specificUnit(b2.sourceUnit)) .endsAt(specificUnit(targetUnit)).once(); } @Test public void branchAndJoin() { TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint b1 = new TestTaint(a1.sourceUnit, ZERO, "b1"); TestTaint b2 = new TestTaint(b1, "b2"); setEqual(a1, a2, b1, b2); a2.addNeighbor(b2); PathVerifier verifier = pathVerifierForReportAt(a2); verifier.totalPaths(1); verifier.startsAt(specificUnit(a1.sourceUnit)).endsAt(specificUnit(targetUnit)); } @Test public void callNotOnStack() { Unit callSite = mock(Unit.class); TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaintPopFromStack(callSite, a1, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint a4 = new TestTaintPushOnStack(a3, callSite, "a4"); PathVerifier verifier = pathVerifierForReportAt(a4); verifier.totalPaths(1); PathSelector selector = verifier.startsAt(specificUnit(a1.sourceUnit)).endsAt(specificUnit(targetUnit)); selector.once(); selector.assertStack(); } @Test public void testRecursiveHierarchy() { SootMethod initDeclMethod = mock(SootMethod.class); Unit callSiteA = mock(Unit.class); when(callSiteA.toString()).thenReturn("CallSiteA"); Unit callSiteD = mock(Unit.class); when(callSiteD.toString()).thenReturn("CallSiteD"); callSiteToDeclarationMapping.put(callSiteA, initDeclMethod); callSiteToDeclarationMapping.put(callSiteD, initDeclMethod); TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaintPushOnStack(a1, callSiteA, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint b1 = new TestTaintPushOnStack(a3, callSiteA, "b1"); a2.addNeighbor(b1); TestTaint c1 = new TestTaintPushOnStack(b1.sourceUnit, a3, callSiteD, "c1"); TestTaint d1 = new TestTaintPushOnStack(a2.sourceUnit, a1, callSiteD, "d1"); c1.addNeighbor(d1); TestTaint d2 = new TestTaint(c1, "d2"); TestTaint e1 = new TestTaintPushOnStack(d2, callSiteD, "e1"); c1.addNeighbor(e1); TestTaint f1 = new TestTaintPushOnStack(e1.sourceUnit, d2, callSiteA, "f1"); a2.addNeighbor(f1); PathVerifier verifierA = pathVerifierForReportAt(a3); verifierA.totalPaths(1); PathSelector selectorA = verifierA.startsAt(specificUnit(a1.sourceUnit)).endsAt(specificUnit(targetUnit)); selectorA.once(); selectorA.assertStack(callSiteA); PathVerifier verifierD = pathVerifierForReportAt(d2); verifierD.totalPaths(1); PathSelector selectorD = verifierD.startsAt(specificUnit(a1.sourceUnit)).endsAt(specificUnit(targetUnit)); selectorD.once(); selectorD.assertStack(callSiteD); } @Test public void multipleCallsToDifferentMethods() { Unit callSite1 = mock(Unit.class); when(callSite1.toString()).thenReturn("CallSite1"); Unit callSite2 = mock(Unit.class); when(callSite2.toString()).thenReturn("CallSite2"); callSiteToDeclarationMapping.put(callSite1, mock(SootMethod.class)); callSiteToDeclarationMapping.put(callSite2, mock(SootMethod.class)); TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaintPopFromStack(callSite1, a1, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint a4 = new TestTaintPushOnStack(a3, callSite1, "a4"); TestTaint a5 = new TestTaint(a4, "a5"); TestTaint a6 = new TestTaintPopFromStack(callSite2, a5, "a6"); a2.addNeighbor(a6); TestTaint a7 = new TestTaintPushOnStack(a4.sourceUnit, a3, callSite2, "a7"); TestTaint a8 = new TestTaint(a7, "a8"); PathVerifier verifier = pathVerifierForReportAt(a8); verifier.totalPaths(1); PathSelector selector = verifier.startsAt(specificUnit(a1.sourceUnit)).endsAt(specificUnit(targetUnit)); selector.once(); selector.assertStack(); } @Test public void multipleCallsToSameMethod() { SootMethod initDeclMethod = mock(SootMethod.class); Unit callSite1 = mock(Unit.class); when(callSite1.toString()).thenReturn("CallSite1"); Unit callSite2 = mock(Unit.class); when(callSite2.toString()).thenReturn("CallSite2"); callSiteToDeclarationMapping.put(callSite1, initDeclMethod); callSiteToDeclarationMapping.put(callSite2, initDeclMethod); TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaintPopFromStack(callSite1, a1, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint a4 = new TestTaintPushOnStack(a3, callSite1, "a4"); TestTaint a5 = new TestTaint(a4, "a5"); TestTaint a6 = new TestTaintPopFromStack(callSite2, a5, "a6"); a2.addNeighbor(a6); TestTaint a7 = new TestTaintPushOnStack(a4.sourceUnit, a3, callSite2, "a7"); TestTaint a8 = new TestTaint(a7, "a8"); PathVerifier verifier = pathVerifierForReportAt(a8); verifier.totalPaths(1); PathSelector selector = verifier.startsAt(specificUnit(a1.sourceUnit)).endsAt(specificUnit(targetUnit)); selector.once(); selector.assertStack(); } @Test public void joinAtReport() { TestTaint a1 = new TestTaint(Zero.ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint b1 = new TestTaint(a1.sourceUnit, Zero.ZERO, "b1"); TestTaint b2 = new TestTaint(a2.sourceUnit, b1, "b2"); a2.addNeighbor(b2); setEqual(a1, a2, b1, b2); PathVerifier verifierA = pathVerifierForReportAt(a2); verifierA.totalPaths(1); verifierA.startsAt(specificUnit(a1.sourceUnit)).endsAt(specificUnit(targetUnit)).once(); } @Test public void branchAtSink() { TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint b1 = new TestTaint(a1.sourceUnit, ZERO, "b1"); TestTaint b2 = new TestTaint(b1, "b2"); TestTaint b3 = new TestTaint(b2, "b3"); a1.addNeighbor(b3); setEqual(a1, a2, a3, b1, b2, b3); PathVerifier verifier = pathVerifierForReportAt(a3); verifier.totalPaths(1); verifier.startsAt(specificUnit(a1.sourceUnit)).endsAt(specificUnit(targetUnit)); } @Test public void multipleSinks() { TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint b1 = new TestTaint(ZERO, "b1"); TestTaint b2 = new TestTaint(a2.sourceUnit, b1, "b2"); TestTaint b3 = new TestTaint(a3.sourceUnit, b2, "b3"); a3.addNeighbor(b3); setEqual(a1, a2, b1, b2); setEqual(a3, b3); PathVerifier verifier = pathVerifierForReportAt(a3); verifier.totalPaths(2); verifier.startsAt(specificUnit(a1.sourceUnit)).contains(specificUnit(a3.sourceUnit)) .endsAt(specificUnit(targetUnit)).once(); verifier.startsAt(specificUnit(b1.sourceUnit)).contains(specificUnit(b3.sourceUnit)) .endsAt(specificUnit(targetUnit)).once(); } private PathVerifier pathVerifierForReportAt(Trackable t) { Report report = new Report(context, t, targetUnit); Set<Path> paths = sut.createPaths(report); plotter.reportTrackable(new Report(context, t, targetUnit)); return new PathVerifier(paths); } }
11,153
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
MergeEqualSelectorStrategyTest.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/unit/transformer/path/MergeEqualSelectorStrategyTest.java
package flow.twist.test.unit.transformer.path; import static com.google.common.collect.Iterables.size; import static flow.twist.test.util.TestTaint.setEqual; import static flow.twist.trackable.Zero.ZERO; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import soot.SootMethod; import soot.Unit; import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import flow.twist.config.AnalysisConfiguration; import flow.twist.config.AnalysisContext; import flow.twist.reporter.Report; import flow.twist.reporter.TrackableGraphPlotter; import flow.twist.targets.AnalysisTarget; import flow.twist.test.util.TestTaint; import flow.twist.trackable.Trackable; import flow.twist.trackable.Zero; import flow.twist.transformer.path.MergeEqualSelectorStrategy; public class MergeEqualSelectorStrategyTest { private MergeEqualSelectorStrategy sut = new MergeEqualSelectorStrategy(); private BiDiInterproceduralCFG<Unit, SootMethod> icfg; private AnalysisContext context; @Rule public TestWatcher watcher = new TestWatcher() { @Override public void failed(Throwable e, Description description) { StringBuilder builder = new StringBuilder(); builder.append("tmp/"); builder.append(MergeEqualSelectorStrategyTest.this.getClass().getSimpleName()); builder.append("_"); builder.append(description.getMethodName()); plotter.writeFile(builder.toString()); } }; TrackableGraphPlotter plotter; @Before public void setup() { plotter = new TrackableGraphPlotter(); icfg = mock(BiDiInterproceduralCFG.class); context = new AnalysisContext(new AnalysisConfiguration(Lists.<AnalysisTarget> newLinkedList(), null, null, null, null, null, null), icfg); } private Iterable<Trackable> exercise(Trackable t) { Iterable<Trackable> result = sut.firstIntroductionOf(t); plotter.reportTrackable(new Report(context, t, null)); return result; } @Test public void identity() { TestTaint a = new TestTaint(Zero.ZERO, "a"); TestTaint b = new TestTaint(a, "b"); assertElementsIdentical(newIdentitySet(b), exercise(b)); assertElementsIdentical(newIdentitySet(a), exercise(a)); } @Test public void joinTaintChain1() { TestTaint a1 = new TestTaint(Zero.ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint a3 = new TestTaint(Zero.ZERO, "a3"); a3.addNeighbor(a2); TestTaint.setEqual(a1, a2, a3); // assertElementsIdentical(newIdentitySet(a1, a3), exercise(a2)); assertElementsIdentical(newIdentitySet(a1, a3), exercise(a3)); } @Test public void branchTaintChain() { TestTaint a1 = new TestTaint(Zero.ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint a4 = new TestTaint(a2.sourceUnit, a1, "a4"); TestTaint.setEqual(a1, a2, a3, a4); assertElementsIdentical(newIdentitySet(a1), exercise(a3)); assertElementsIdentical(newIdentitySet(a1), exercise(a4)); } @Test public void joinTaintChain2() { TestTaint a = new TestTaint(Zero.ZERO, "a"); TestTaint d = new TestTaint(Zero.ZERO, "d"); TestTaint b1 = new TestTaint(a, "b1"); TestTaint b2 = new TestTaint(b1, "b2"); TestTaint b3 = new TestTaint(b2, "b3"); TestTaint c1 = new TestTaint(d, "c1"); TestTaint c2 = new TestTaint(c1, "c2"); TestTaint c3 = new TestTaint(c2, "c3"); TestTaint.setEqual(b1, b2, b3, c1, c2, c3); b3.addNeighbor(c3); assertElementsIdentical(newIdentitySet(b1, c1), exercise(b3)); // assertElementsIdentical(newIdentitySet(b1, c1), exercise(c3)); } @Test public void branchAndJoinTaintChain() { TestTaint a = new TestTaint(Zero.ZERO, "a"); TestTaint b1 = new TestTaint(a, "b1"); TestTaint b2 = new TestTaint(b1, "b2"); TestTaint b3 = new TestTaint(b2, "b3"); TestTaint c1 = new TestTaint(b1.sourceUnit, a, "c1"); TestTaint c2 = new TestTaint(c1, "c2"); TestTaint c3 = new TestTaint(c2, "c3"); TestTaint.setEqual(b1, b2, b3, c1, c2, c3); b3.addNeighbor(c3); Iterable<Trackable> actualForB3 = exercise(b3); assertEquals(1, size(actualForB3)); assertHasEqualTrackableWithSameSourceUnit(b1, actualForB3); Iterable<Trackable> actualForC3 = exercise(c3); assertEquals(1, size(actualForC3)); assertHasEqualTrackableWithSameSourceUnit(b1, actualForC3); } @Test public void branchAndJoinEqualTaintChain() { TestTaint a1 = new TestTaint(Zero.ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint b1 = new TestTaint(a2, "b1"); TestTaint b2 = new TestTaint(b1, "b2"); TestTaint b3 = new TestTaint(b2, "b3"); TestTaint c1 = new TestTaint(b1.sourceUnit, a2, "c1"); TestTaint c2 = new TestTaint(c1, "c2"); TestTaint c3 = new TestTaint(c2, "c3"); TestTaint.setEqual(a1, a2, b1, b2, b3, c1, c2, c3); b3.addNeighbor(c3); assertElementsIdentical(newIdentitySet(a1), exercise(b3)); assertElementsIdentical(newIdentitySet(a1), exercise(c3)); } @Test public void loop() { TestTaint a1 = new TestTaint(Zero.ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint b1 = new TestTaint(a3.sourceUnit, a2, "b1"); TestTaint b2 = new TestTaint(b1, "b2"); TestTaint b3 = new TestTaint(b2, "b3"); TestTaint.setEqual(a1, a2, a3, b1, b2, b3); a1.addNeighbor(b3); assertElementsIdentical(newIdentitySet(a1), exercise(a3)); } @Test public void joinAtReport() { TestTaint a1 = new TestTaint(Zero.ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint b1 = new TestTaint(a1.sourceUnit, Zero.ZERO, "b1"); TestTaint b2 = new TestTaint(a2.sourceUnit, b1, "b2"); a2.addNeighbor(b2); setEqual(a1, a2, b1, b2); Iterable<Trackable> actualForA2 = exercise(a2); assertEquals(1, size(actualForA2)); assertHasEqualTrackableWithSameSourceUnit(a1, actualForA2); Iterable<Trackable> actualForB2 = exercise(b2); assertEquals(1, size(actualForB2)); assertHasEqualTrackableWithSameSourceUnit(b1, actualForB2); } @Test public void branchAtSink() { TestTaint a1 = new TestTaint(ZERO, "a1"); TestTaint a2 = new TestTaint(a1, "a2"); TestTaint a3 = new TestTaint(a2, "a3"); TestTaint b1 = new TestTaint(a1.sourceUnit, ZERO, "b1"); TestTaint b2 = new TestTaint(b1, "b2"); TestTaint b3 = new TestTaint(b2, "b3"); a1.addNeighbor(b3); setEqual(a1, a2, a3, b1, b2, b3); assertElementsIdentical(newIdentitySet(a1), exercise(a3)); } private static <T> void assertElementsIdentical(Iterable<? extends T> expected, Iterable<? extends T> actual) { assertEquals(size(expected), size(actual)); for (T exp : expected) { boolean found = false; for (T act : actual) { if (exp == act) { found = true; break; } } if (!found) { fail("Expected: " + exp + "; actual: " + Joiner.on(",").join(actual).toString()); } } } private static void assertHasEqualTrackableWithSameSourceUnit(TestTaint expected, Iterable<Trackable> actual) { for (Trackable current : actual) { if (current.equals(expected) && current.sourceUnit == expected.sourceUnit) return; } fail(); } private static <T> Set<T> newIdentitySet(T... obj) { Set<T> result = Sets.newIdentityHashSet(); for (T o : obj) { result.add(o); } return result; } }
7,486
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
JdkAnalysis.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/jdk/JdkAnalysis.java
package flow.twist.test.jdk; import static flow.twist.config.AnalysisConfigurationBuilder.forwardsFromAllParametersDefaults; import static flow.twist.config.AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults; import java.io.File; import java.util.ArrayList; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import soot.G; import com.google.common.collect.Lists; import flow.twist.AbstractAnalysis; import flow.twist.SolverFactory; import flow.twist.config.AnalysisDirection; import flow.twist.pathchecker.FilterSingleDirectionReports; import flow.twist.reporter.ConsoleReporter; import flow.twist.reporter.ResultForwardingReporter; import flow.twist.states.StateMachineBasedPathReporter; import flow.twist.transformer.PathToConsole; import flow.twist.transformer.path.MergeEqualSelectorStrategy; import flow.twist.transformer.path.PathBuilderResultTransformer; import flow.twist.util.AnalysisUtil; public class JdkAnalysis { @Test public void forwards() { new AbstractTestAnalysis() { @Override protected void executeAnalysis() { SolverFactory.runOneDirectionSolver(i2oSimpleClassForNameDefaults().direction(AnalysisDirection.FORWARDS).reporter( new ConsoleReporter())); } }.execute(); } @Test public void backwards() { new AbstractTestAnalysis() { @Override protected void executeAnalysis() { SolverFactory.runOneDirectionSolver(i2oSimpleClassForNameDefaults().direction(AnalysisDirection.BACKWARDS).reporter( new ConsoleReporter())); } }.execute(); } @Test public void innerToOuterWithPathsOnly() { new AbstractTestAnalysis() { @Override protected void executeAnalysis() { SolverFactory.runInnerToOuterSolver(i2oSimpleClassForNameDefaults().reporter( new ResultForwardingReporter(new FilterSingleDirectionReports(new PathBuilderResultTransformer(new PathToConsole(), new MergeEqualSelectorStrategy()))))); } }.execute(); } @Test @Ignore("Does not scale for JDK yet") public void innerToOuterWithStates() { new AbstractTestAnalysis() { @Override protected void executeAnalysis() { SolverFactory.runInnerToOuterSolver(i2oSimpleClassForNameDefaults().reporter(new StateMachineBasedPathReporter())); } }.execute(); } @Test public void forwardsFromCallables() { new AbstractTestAnalysis() { @Override protected void executeAnalysis() { SolverFactory.runOneDirectionSolver(forwardsFromAllParametersDefaults(true).reporter( new ResultForwardingReporter(new PathBuilderResultTransformer(new PathToConsole(), new MergeEqualSelectorStrategy())))); } }.execute(); } // @Test // public void biDirectional() { // new AbstractTestAnalysis() { // @Override // protected void executeAnalysis() { // SolverFactory.runBiDirectionSolver(new VulnerablePathReporter()); // } // }.execute(); // } @Before public void setUp() throws Exception { String jrePath = System.getProperty("java.home"); jrePath = jrePath.substring(0, jrePath.lastIndexOf(File.separator)); AnalysisUtil.initRestrictedPackages(jrePath); } @After public void tearDown() throws Exception { try { } finally { G.reset(); } } private abstract static class AbstractTestAnalysis extends AbstractAnalysis { @Override protected ArrayList<String> createArgs() { String args = "-i java.lang. -allow-phantom-refs -f none -w -f none -p cg all-reachable:true -keep-line-number -pp"; ArrayList<String> argList = Lists.newArrayList(args.split(" ")); String javaHome = System.getProperty("java.home"); String libDir = javaHome + File.separator + "lib" + File.separator; argList.add("-cp"); argList.add(libDir + "jce.jar" + File.pathSeparator + libDir + "jsse.jar"); argList.add("-process-dir"); argList.add(libDir + "rt.jar"); return argList; } } }
3,858
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
AnalysisGraphVerifier.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/AnalysisGraphVerifier.java
package flow.twist.test.util; import static java.lang.String.format; import heros.solver.Pair; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.AssertionFailedError; import org.junit.Assert; import soot.SootMethod; import soot.Unit; import soot.util.IdentityHashSet; import com.google.common.base.Supplier; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import flow.twist.config.AnalysisContext; import flow.twist.reporter.IfdsReporter; import flow.twist.reporter.Report; import flow.twist.reporter.TrackableGraphPlotter; import flow.twist.test.util.selectors.TrackableSelector; import flow.twist.test.util.selectors.UnitSelector; import flow.twist.trackable.Trackable; public class AnalysisGraphVerifier implements IfdsReporter { private TrackableGraphPlotter debugPlotter; private Map<Unit, SootMethod> unit2Method = Maps.newHashMap(); private Multimap<Unit, Pair<Unit, Trackable>> successors = HashMultimap.create(); private Multimap<Unit, Trackable> trackablesAtUnit = Multimaps.newSetMultimap(new HashMap<Unit, Collection<Trackable>>(), new Supplier<Set<Trackable>>() { @Override public Set<Trackable> get() { return new IdentityHashSet<>(); } }); public AnalysisGraphVerifier() { // debugPlotter = new DebugPlotter(); debugPlotter = new TrackableGraphPlotter(); } @Override public void reportTrackable(Report report) { debugPlotter.reportTrackable(report); createEdges(report.context, report.trackable, report.targetUnit); } private void createEdges(AnalysisContext context, Trackable trackable, Unit unit) { unit2Method.put(unit, context.icfg.getMethodOf(unit)); for (Trackable neighbor : trackable.getSelfAndNeighbors()) { trackablesAtUnit.put(unit, neighbor); if (neighbor.sourceUnit == null) continue; if (successors.put(neighbor.sourceUnit, new Pair<Unit, Trackable>(unit, neighbor))) createEdges(context, neighbor.predecessor, neighbor.sourceUnit); } } @Override public void analysisFinished() { } public void writeDebugFile(String fileName) { System.out.println("Writing debug graph file for failed test: " + fileName); debugPlotter.writeFile(fileName); } public UnitNode find(UnitSelector selector) { for (Unit unit : unit2Method.keySet()) { if (selector.matches(unit2Method.get(unit), unit)) { return new UnitNode(unit); } } throw new AssertionFailedError(format("Unit not found: %s", selector)); } public void cannotFind(UnitSelector selector) { for (Unit unit : unit2Method.keySet()) { if (selector.matches(unit2Method.get(unit), unit)) { throw new AssertionFailedError(format("Unit found: %s", selector)); } } } public class UnitNode { private final Unit unit; public UnitNode(Unit unit) { this.unit = unit; } public UnitNode edge(TrackableSelector trackableSelector, UnitSelector unitSelector) { for (Pair<Unit, Trackable> successor : successors.get(unit)) { if (unitSelector.matches(unit2Method.get(successor.getO1()), successor.getO1()) && trackableSelector.matches(successor.getO2())) { return new UnitNode(successor.getO1()); } } throw new AssertionFailedError(format("No edge found from '%s' to '%s' with trackable matching '%s'", unit.toString(), unitSelector, trackableSelector.toString())); } public UnitNode pathTo(TrackableSelector trackableSelector, UnitSelector selector) { Set<Unit> visited = Sets.newHashSet(); List<Unit> worklist = Lists.newLinkedList(); worklist.add(unit); while (!worklist.isEmpty()) { Unit current = worklist.remove(0); if (visited.add(current)) { for (Pair<Unit, Trackable> successor : successors.get(current)) { if (selector.matches(unit2Method.get(successor.getO1()), successor.getO1()) && trackableSelector.matches(successor.getO2())) { return new UnitNode(successor.getO1()); } worklist.add(successor.getO1()); } } } throw new AssertionFailedError(format("There is no connection from '%s' to '%s' with the taint '%s' at the destination.", unit.toString(), selector, trackableSelector.toString())); } public void assertHasNot(TrackableSelector trackableSelector) { for (Pair<Unit, Trackable> successor : successors.get(unit)) { if (trackableSelector.matches(successor.getO2())) { throw new AssertionFailedError(format("There is a taint matching '%s' into unit '%s' that should not be there!", trackableSelector, unit)); } } } public void assertNoOutgoingEdges() { Assert.assertEquals(format("Unit '%s' has outgoing edges, but should have none.", unit), 0, successors.get(unit).size()); } public void assertIncomingEdges(int expected) { int actual = 0; for (Trackable t : trackablesAtUnit.get(unit)) { if (t.predecessor != null) actual++; } Assert.assertEquals(expected, actual); } } }
5,159
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
AbstractTaintAnalysisTest.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/AbstractTaintAnalysisTest.java
package flow.twist.test.util; import org.junit.Rule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; public abstract class AbstractTaintAnalysisTest extends AbstractAnalysisTest { @Rule public TestWatcher name = new TestWatcher() { @Override public void failed(Throwable e, Description description) { StringBuilder builder = new StringBuilder(); builder.append("tmp/"); builder.append(AbstractTaintAnalysisTest.this.getClass().getSimpleName()); builder.append("_"); builder.append(description.getMethodName()); verifier.writeDebugFile(builder.toString()); } }; private AnalysisGraphVerifier verifier; protected AnalysisGraphVerifier runTest(final String... classNames) { runAnalysis(new TestAnalysis(classNames) { @Override protected void executeAnalysis() { verifier = executeTaintAnalysis(classNames); } }); return verifier; } protected abstract AnalysisGraphVerifier executeTaintAnalysis(String[] classNames); }
996
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
AbstractAnalysisTest.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/AbstractAnalysisTest.java
package flow.twist.test.util; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import org.junit.After; import org.junit.Before; import soot.G; import flow.twist.AbstractAnalysis; import flow.twist.util.AnalysisUtil; public abstract class AbstractAnalysisTest { protected void runAnalysis(TestAnalysis analysis) { analysis.execute(); } @Before public void setUp() throws Exception { String jrePath = System.getProperty("java.home"); jrePath = jrePath.substring(0, jrePath.lastIndexOf(File.separator)); AnalysisUtil.initRestrictedPackages(jrePath); } @After public void tearDown() throws Exception { try { } finally { G.reset(); } } public static abstract class TestAnalysis extends AbstractAnalysis { private String[] classNames; public TestAnalysis(String... classNames) { this.classNames = classNames; } @Override protected ArrayList<String> createArgs() { String classPath = "bin"; String ARGS = "-no-bodies-for-excluded -p jb use-original-names:true -f none -cp " + classPath + " -pp -w -p cg all-reachable:true -keep-line-number "; ArrayList<String> argList = new ArrayList<String>(Arrays.asList(ARGS.split(" "))); for (String className : classNames) { argList.add("-i"); argList.add(className); } for (String className : classNames) { // argument class argList.add(className); } return argList; } } }
1,431
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
PathVerifier.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/PathVerifier.java
package flow.twist.test.util; import java.util.List; import java.util.Set; import org.junit.Assert; import soot.Unit; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import flow.twist.path.Path; import flow.twist.path.PathElement; import flow.twist.test.util.selectors.UnitSelector; public class PathVerifier { private Set<Path> paths; public PathVerifier(Set<Path> paths) { this.paths = paths; } public void totalPaths(int numberOfExpectedPaths) { Assert.assertEquals(numberOfExpectedPaths, paths.size()); } public Set<Path> getPaths() { return paths; } public PathSelector startsAt(UnitSelector selector) { List<Path> matchingPaths = Lists.newLinkedList(); for (Path path : paths) { Unit unit = path.getFirst(); if (selector.matches(path.context.icfg.getMethodOf(unit), unit)) { matchingPaths.add(path); } } return new PathSelector(matchingPaths); } public class PathSelector { private List<Path> paths; public PathSelector(List<Path> paths) { this.paths = paths; } public PathSelector endsAt(UnitSelector selector) { List<Path> matchingPaths = Lists.newLinkedList(); for (Path path : paths) { Unit unit = path.getLast(); if (selector.matches(path.context.icfg.getMethodOf(unit), unit)) { matchingPaths.add(path); } } return new PathSelector(matchingPaths); } public PathSelector contains(UnitSelector selector) { List<Path> matchingPaths = Lists.newLinkedList(); for (Path path : paths) { if (pathContains(selector, path)) { matchingPaths.add(path); } } return new PathSelector(matchingPaths); } private boolean pathContains(UnitSelector selector, Path path) { for (PathElement element : path) { if (selector.matches(path.context.icfg.getMethodOf(element.to), element.to)) { return true; } } return false; } public PathSelector doesNotContain(UnitSelector selector) { List<Path> matchingPaths = Lists.newLinkedList(); for (Path path : paths) { if (!pathContains(selector, path)) { matchingPaths.add(path); } } return new PathSelector(matchingPaths); } public void once() { Assert.assertEquals(1, paths.size()); } public void never() { Assert.assertEquals(0, paths.size()); } public void noOtherPaths() { Assert.assertEquals(paths.size(), PathVerifier.this.paths.size()); } public void times(int i) { Assert.assertEquals(i, paths.size()); } public void assertStack(Unit... callSites) { for (Path path : paths) { fj.data.List<Object> callStack = path.getCallStack(); Assert.assertTrue(Iterables.elementsEqual(callStack, Lists.newArrayList(callSites))); } } } }
2,733
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
TestTaintPopFromStack.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/TestTaintPopFromStack.java
package flow.twist.test.util; import soot.Unit; import flow.twist.trackable.PopFromStack; import flow.twist.trackable.Trackable; public class TestTaintPopFromStack extends TestTaint implements PopFromStack { public TestTaintPopFromStack(Unit callSite, Trackable predecessor, String identifier) { super(callSite, predecessor, identifier); } @Override public Unit getCallSite() { return sourceUnit; } }
415
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
TestTaint.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/TestTaint.java
package flow.twist.test.util; import static org.mockito.Mockito.mock; import java.util.Set; import org.mockito.Mockito; import soot.Unit; import com.google.common.collect.Sets; import flow.twist.trackable.Trackable; public class TestTaint extends Trackable { private Set<TestTaint> equalTaints = Sets.newIdentityHashSet(); private String identifier; public TestTaint(Unit unit, Trackable predecessor, String identifier) { super(unit, predecessor); this.identifier = identifier; } public TestTaint(Trackable predecessor, String identifier) { this(createUnitMock(identifier), predecessor, identifier); } protected static Unit createUnitMock(String identifier) { Unit mock = mock(Unit.class); Mockito.when(mock.toString()).thenReturn("unit(" + identifier + ")"); return mock; } @Override public Trackable cloneWithoutNeighborsAndPayload() { return null; } @Override public Trackable createAlias(Unit sourceUnits) { return null; } @Override public int hashCode() { return 0; } @Override public boolean equals(Object obj) { return equalTaints.contains(obj); } @Override public String toString() { return identifier; } public static void setEqual(TestTaint... taints) { Set<TestTaint> eq = Sets.newIdentityHashSet(); for (TestTaint t : taints) { eq.add(t); } for (TestTaint tt : taints) { tt.equalTaints = eq; } } }
1,389
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
AbstractPathTests.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/AbstractPathTests.java
package flow.twist.test.util; import static flow.twist.test.util.selectors.UnitSelectorFactory.anyUnit; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitWithoutLabel; import org.junit.Assert; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import flow.twist.test.util.PathVerifier.PathSelector; import flow.twist.util.MultipleAnalysisPlotter; public abstract class AbstractPathTests extends AbstractTaintAnalysisTest { protected PathVerifier pathVerifier; @Rule public TestWatcher watcher = new TestWatcher() { @Override public void failed(Throwable e, Description description) { StringBuilder builder = new StringBuilder(); builder.append("tmp/"); builder.append(AbstractPathTests.this.getClass().getSimpleName()); builder.append("_"); builder.append(description.getMethodName()); builder.append("_path"); MultipleAnalysisPlotter plotter = new MultipleAnalysisPlotter(); plotter.plotAnalysisResults(pathVerifier.getPaths(), "red"); plotter.writeFile(builder.toString()); } }; @Test public void aliasing() { runTest("java.lang.Aliasing"); pathVerifier.totalPaths(3); pathVerifier.startsAt(unitInMethod("nameInput(", unitByLabel("@parameter0"))).endsAt(unitByLabel("return")).once(); pathVerifier.startsAt(unitInMethod("nameInput(", unitByLabel("@parameter2"))).endsAt(unitByLabel("return")).once(); pathVerifier.startsAt(unitInMethod("nameInput2(", unitByLabel("@parameter0"))).endsAt(unitByLabel("return")).once(); } @Test public void backwardsIntoThrow() { runTest("java.lang.BackwardsIntoThrow"); pathVerifier.totalPaths(1); pathVerifier.startsAt(unitInMethod("foo", unitByLabel("@parameter0"))).endsAt(unitInMethod("foo", unitByLabel("return"))).once(); } @Test @Ignore("does not work without target for forName with classloader argument") public void beanInstantiator() { runTest("java.lang.BeanInstantiator"); pathVerifier.totalPaths(3); PathSelector path = pathVerifier.startsAt(unitInMethod("findClass", unitByLabel("@parameter0"))).endsAt( unitInMethod("findClass", unitByLabel("return"))); path.contains(unitWithoutLabel("goto", unitByLabel("forName(java.lang.String,boolean,java.lang.ClassLoader)"))).once(); path.contains(unitWithoutLabel("goto", unitByLabel("forName(java.lang.String)"))).once(); } @Test public void checkPackageAccess() { runTest("java.lang.CheckPackageAccess"); pathVerifier.totalPaths(1); pathVerifier.startsAt(unitInMethod("wrapperWithoutCheck(java.lang.String)", unitByLabel("@parameter0"))) .endsAt(unitInMethod("wrapperWithoutCheck(java.lang.String)", unitByLabel("return"))).contains(unitByLabel("forName")).once(); } @Test @Ignore("doPrivileged is native; we have no special handling yet") public void doPrivileged() { runTest("java.lang.DoPrivileged", "java.lang.DoPrivileged$1", "java.lang.DoPrivileged$2"); pathVerifier.totalPaths(2); pathVerifier.startsAt(unitInMethod("callable1", unitByLabel("@parameter0"))).endsAt(unitInMethod("callable1", unitByLabel("return"))).once(); pathVerifier.startsAt(unitInMethod("callable2", unitByLabel("@parameter0"))).endsAt(unitInMethod("callable2", unitByLabel("return"))).once(); } @Test public void classHierarchyHard() { runTest("java.lang.ClassHierarchyHard"); pathVerifier.totalPaths(2); pathVerifier.startsAt(unitInMethod("invokeable", unitByLabel("@parameter0"))).endsAt(unitInMethod("invokeable", unitByLabel("return"))) .once(); pathVerifier.startsAt(unitInMethod("redundantInvokeable", unitByLabel("@parameter0"))) .endsAt(unitInMethod("redundantInvokeable", unitByLabel("return"))).once(); } @Test public void classHierarchySimple() { runTest("java.lang.ClassHierarchySimple"); pathVerifier.totalPaths(1); pathVerifier.startsAt(unitInMethod("foo", unitByLabel("@parameter0"))).endsAt(unitInMethod("foo", unitByLabel("return"))) .contains(unitInMethod("$B: java.lang.Class test", unitByLabel("forName"))).once(); } @Test public void distinguishPaths() { runTest("java.lang.DistinguishPaths"); pathVerifier.totalPaths(1); pathVerifier.startsAt(unitInMethod("leakingMethod", unitByLabel("@parameter0"))).endsAt(unitInMethod("leakingMethod", unitByLabel("return"))) .once(); } @Test public void loop() { runTest("java.lang.Loop"); pathVerifier.startsAt(unitByLabel("@parameter0")).endsAt(unitByLabel("return")).times(1); } @Test @Ignore("not implemented") public void permissionCheckNotOnCallstack() { runTest("java.lang.PermissionCheckNotOnCallstack"); pathVerifier.totalPaths(0); } @Test public void permissionCheckNotOnAllPaths() { runTest("java.lang.PermissionCheckNotOnAllPaths"); pathVerifier.totalPaths(1); pathVerifier.startsAt(unitByLabel("@parameter0")).endsAt(unitByLabel("return")).doesNotContain(unitByLabel("name = className")).once(); } @Test public void recursion() { runTest("java.lang.Recursion"); pathVerifier.totalPaths(2); pathVerifier.startsAt(unitInMethod("recursive(", unitByLabel("@parameter0"))).endsAt(unitInMethod("recursive(", unitByLabel("return"))) .once(); pathVerifier.startsAt(unitInMethod("recursiveA(", unitByLabel("@parameter0"))).endsAt(unitInMethod("recursiveA(", unitByLabel("return"))) .once(); } @Test public void recursionAndClassHierarchy() { runTest("java.lang.RecursionAndClassHierarchy", "java.lang.RecursionAndClassHierarchy$BaseInterface", "java.lang.RecursionAndClassHierarchy$SubClassA", "java.lang.RecursionAndClassHierarchy$SubClassB", "java.lang.RecursionAndClassHierarchy$SubClassC"); pathVerifier.totalPaths(4); } @Test public void recursionAndClassAsParameter() { runTest("java.lang.RecursionClassAsParameter"); pathVerifier.totalPaths(1); } @Test public void sourceOnCallstack() { runTest("java.lang.SourceOnCallstack"); pathVerifier.totalPaths(1); pathVerifier.startsAt(unitInMethod("baz", unitByLabel("@parameter0"))).endsAt(unitInMethod("baz", unitByLabel("return"))) .contains(unitByLabel("forName")).once(); } @Test public void stringConcatenation() { runTest("java.lang.StringConcatenation"); pathVerifier.totalPaths(1); pathVerifier.startsAt(unitByLabel("@parameter0")).endsAt(unitByLabel("return")).contains(unitByLabel("forName")).once(); } @Test public void whileSwitch() { runTest("java.lang.Switch"); pathVerifier.totalPaths(5); } @Test public void validPathCheck() { runTest("java.lang.ValidPathCheck"); pathVerifier.totalPaths(1); pathVerifier.startsAt(unitInMethod("a(", unitByLabel("@parameter0"))).endsAt(unitInMethod("a(", unitByLabel("return"))) .doesNotContain(unitInMethod("e(", anyUnit())).once(); } @Test public void whiteboardGraph() { runTest("java.lang.WhiteboardGraph"); pathVerifier.totalPaths(1); PathSelector vulnerablePathSelector = pathVerifier.startsAt(unitInMethod("vulnerable", unitByLabel("@parameter0"))).endsAt( unitInMethod("vulnerable", unitByLabel("return"))); vulnerablePathSelector.once(); PathSelector notVulnerablePathSelector = pathVerifier.startsAt(unitInMethod("notVulnerable", unitByLabel("@parameter0"))).endsAt( unitInMethod("notVulnerable", unitByLabel("return"))); notVulnerablePathSelector.never(); } @Test public void impossiblePath() { runTest("java.lang.ImpossiblePath"); pathVerifier.startsAt(unitByLabel("@parameter0")).endsAt(unitByLabel("return")).once(); } @Test public void recursivePopState() { runTest("java.lang.RecursivePopState"); pathVerifier.totalPaths(1); } @Test public void multipleSinksInSameContext() { runTest("java.lang.MultipleSinksInSameContext"); pathVerifier.startsAt(unitByLabel("@parameter0")).endsAt(unitByLabel("return")).times(2); } @Test @Ignore("not implemented yet") public void combiningMultipleTargets() { runTest("callersensitive.CombiningMultipleTargets"); Assert.fail(); } @Test @Ignore("not implemented yet") public void parameterWithTaintedField() { runTest("typestate.ParameterWithTaintedField"); Assert.fail(); } }
8,280
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
TestTaintPushOnStack.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/TestTaintPushOnStack.java
package flow.twist.test.util; import soot.Unit; import flow.twist.trackable.PushOnStack; import flow.twist.trackable.Trackable; public class TestTaintPushOnStack extends TestTaint implements PushOnStack { private Unit callSite; public TestTaintPushOnStack(Unit sourceUnit, Trackable predecessor, Unit callSite, String identifier) { super(sourceUnit, predecessor, identifier); this.callSite = callSite; } public TestTaintPushOnStack(Trackable predecessor, Unit callSite, String identifier) { super(predecessor, identifier); this.callSite = callSite; } @Override public Unit getCallSite() { return callSite; } @Override public int getParameterIndex() { return 0; } }
696
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
UnitSelectorFactory.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
package flow.twist.test.util.selectors; import soot.SootMethod; import soot.Unit; public class UnitSelectorFactory { public static UnitSelector unitWithoutLabel(final String label, final UnitSelector selector) { return new UnitSelector() { @Override public boolean matches(SootMethod method, Unit unit) { return !unit.toString().contains(label) && selector.matches(method, unit); } @Override public String toString() { return "'" + selector.toString() + "' without '" + label + "'"; } }; } public static UnitSelector unitByLabel(final String label) { return new UnitSelector() { @Override public boolean matches(SootMethod method, Unit unit) { return unit.toString().contains(label); } @Override public String toString() { return label; } }; } public static UnitSelector unitInMethod(final String methodString, final UnitSelector selector) { return new UnitSelector() { @Override public boolean matches(SootMethod method, Unit unit) { return method.toString().contains(methodString) && selector.matches(method, unit); } @Override public String toString() { return "'" + selector.toString() + "' in '" + methodString + "'"; } }; } public static UnitSelector anyUnit() { return new UnitSelector() { @Override public boolean matches(SootMethod method, Unit unit) { return true; } @Override public String toString() { return "any unit"; } }; } public static UnitSelector specificUnit(final Unit specificUnit) { return new UnitSelector() { @Override public boolean matches(SootMethod method, Unit unit) { return unit == specificUnit; } @Override public String toString() { return "specific unit: " + specificUnit; } }; } }
1,792
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
TrackableSelector.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/selectors/TrackableSelector.java
package flow.twist.test.util.selectors; import flow.twist.trackable.Trackable; public interface TrackableSelector { boolean matches(Trackable trackable); }
158
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
TrackableSelectorFactory.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/selectors/TrackableSelectorFactory.java
package flow.twist.test.util.selectors; import flow.twist.trackable.Taint; import flow.twist.trackable.Trackable; public class TrackableSelectorFactory { public static TrackableSelector taintContains(final String name) { return new TrackableSelector() { @Override public boolean matches(Trackable trackable) { if (trackable instanceof Taint) { String taintString = ((Taint) trackable).value.toString(); if (taintString.contains(name)) { return true; } } return false; } @Override public String toString() { return ".*" + name + ".*"; } }; } public static TrackableSelector taint(final String name) { return new TrackableSelector() { @Override public boolean matches(Trackable trackable) { if (trackable instanceof Taint) { String taintString = ((Taint) trackable).value.toString(); if (taintString.equals(name)) { return true; } } return false; } @Override public String toString() { return name; } }; } public static TrackableSelector anyTaint() { return new TrackableSelector() { @Override public boolean matches(Trackable trackable) { return true; } @Override public String toString() { return "any Taint"; } }; } }
1,293
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
UnitSelector.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/test/flow/twist/test/util/selectors/UnitSelector.java
package flow.twist.test.util.selectors; import soot.SootMethod; import soot.Unit; public interface UnitSelector { boolean matches(SootMethod method, Unit unit); }
165
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
ActiveBodyVerifier.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/src/flow/twist/ActiveBodyVerifier.java
package flow.twist; import java.util.HashSet; import soot.SootMethod; import com.google.common.collect.Sets; public class ActiveBodyVerifier { private static HashSet<SootMethod> active = Sets.newHashSet(); private static HashSet<SootMethod> inactive = Sets.newHashSet(); public static void markActive(SootMethod m) { active.add(m); } public static void markInactive(SootMethod m) { inactive.add(m); } public static void assertActive(SootMethod m) { if (!active.contains(m)) throw new IllegalStateException(m + " was assumed to be active, but was not. Known to be inactive: " + inactive.contains(m)); } }
630
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
Main.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/src/flow/twist/Main.java
package flow.twist; import static flow.twist.config.AnalysisConfigurationBuilder.forwardsFromAllParametersDefaults; import static flow.twist.config.AnalysisConfigurationBuilder.i2oGenericCallerSensitiveDefaults; import static flow.twist.config.AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Set; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.VoidType; import soot.tagkit.AnnotationTag; import soot.tagkit.Tag; import soot.tagkit.VisibilityAnnotationTag; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import flow.twist.config.AnalysisConfigurationBuilder; import flow.twist.path.Path; import flow.twist.pathchecker.FilterSingleDirectionReports; import flow.twist.reporter.ResultForwardingReporter; import flow.twist.targets.GenericCallerSensitive; import flow.twist.transformer.StoreDataTransformer; import flow.twist.transformer.path.MergeEqualSelectorStrategy; import flow.twist.transformer.path.PathBuilderResultTransformer; import flow.twist.util.AnalysisUtil; import flow.twist.util.MultipleAnalysisPlotter; public class Main { public static void main(final String[] args) { new AbstractAnalysis() { @Override protected void executeAnalysis() { // executeMultipleAnalysis(); printCallerSensitiveStats(); MultipleAnalysisPlotter plotter = new MultipleAnalysisPlotter(); // Set<Path> validPaths = executeI2OForNameAnalysis(); // Set<Path> validPaths = executeBidiForNameAnalysis(); // Set<Path> validPaths = executeBidiCallerSensitiveAnalysis(); Set<Path> validPaths = executeForwardOnlyForNameAnalysis(); plotter.plotAnalysisResults(validPaths, "blue"); plotter.writeFile("analysisResults"); // SolverFactory.runInnerToOuterSolver(new ConsoleReporter()); // SolverFactory.runI2OOneDirectionSolver(AnalysisDirection.BACKWARDS, // new ConsoleReporter()); // executeSinkBySink(); // Debugger debugger = new Debugger(); // FanInFanOutDebugger fanInOut = new FanInFanOutDebugger(); // debugger.registerListener(fanInOut); // TabularViewer tabularViewer = new TabularViewer(debugger, // fanInOut); // SolverFactory.runOneDirectionSolver(AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults() // .direction(AnalysisDirection.FORWARDS).reporter(new // ConsoleReporter()).debugger(debugger)); // tabularViewer.dispose(); writeReportFile(validPaths); } private void writeReportFile(Set<Path> validPaths) { Multimap<SootMethod, Path> pathsBySink = HashMultimap.create(); for (Path path : validPaths) { pathsBySink.put(path.context.icfg.getMethodOf(path.getSink()), path); } try { FileWriter writer = new FileWriter(new File("report.csv")); for (SootMethod sink : pathsBySink.keySet()) { writer.write(String.format("%s;%d\n", sink.toString(), pathsBySink.get(sink).size())); } writer.close(); } catch (IOException e) { e.printStackTrace(); } } private void executeMultipleAnalysis() { AnalysisReporting.directory = new File("results/forName/bidi"); SolverFactory.runBiDirectionSolver(AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults().reporter( new ResultForwardingReporter(new PathBuilderResultTransformer(new StoreDataTransformer<Set<Path>>(), new MergeEqualSelectorStrategy())))); AnalysisReporting.directory = new File("results/forName/i2o-filtered"); SolverFactory.runInnerToOuterSolver(AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults().reporter( new ResultForwardingReporter(new FilterSingleDirectionReports(new PathBuilderResultTransformer( new StoreDataTransformer<Set<Path>>(), new MergeEqualSelectorStrategy()))))); AnalysisReporting.directory = new File("results/forName/i2o"); SolverFactory.runInnerToOuterSolver(AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults().reporter( new ResultForwardingReporter(new PathBuilderResultTransformer(new StoreDataTransformer<Set<Path>>(), new MergeEqualSelectorStrategy())))); AnalysisReporting.directory = new File("results/callersens/bidi"); SolverFactory.runBiDirectionSolver(AnalysisConfigurationBuilder.i2oGenericCallerSensitiveDefaults().reporter( new ResultForwardingReporter(new PathBuilderResultTransformer(new StoreDataTransformer<Set<Path>>(), new MergeEqualSelectorStrategy())))); AnalysisReporting.directory = new File("results/callersens/i2o-filtered"); SolverFactory.runInnerToOuterSolver(AnalysisConfigurationBuilder.i2oGenericCallerSensitiveDefaults().reporter( new ResultForwardingReporter(new FilterSingleDirectionReports(new PathBuilderResultTransformer( new StoreDataTransformer<Set<Path>>(), new MergeEqualSelectorStrategy()))))); AnalysisReporting.directory = new File("results/callersens/i2o"); SolverFactory.runInnerToOuterSolver(AnalysisConfigurationBuilder.i2oGenericCallerSensitiveDefaults().reporter( new ResultForwardingReporter(new PathBuilderResultTransformer(new StoreDataTransformer<Set<Path>>(), new MergeEqualSelectorStrategy())))); } private void printCallerSensitiveStats() { Set<SootMethod> methods = new GenericCallerSensitive().getSensitiveMethods(); System.out.println("Total caller sensitive methods: " + methods.size()); int integrityOnly = 0; int confidentialityOnly = 0; for (SootMethod m : methods) { boolean confidentiality = false; boolean integrity = false; if (!m.isStatic()) integrity = true; if (m.getParameterCount() > 0) integrity = true; if (!(m.getReturnType() instanceof VoidType)) confidentiality = true; if (confidentiality && !integrity) { confidentialityOnly++; System.out.println(m); } else if (integrity && !confidentiality) { integrityOnly++; System.out.println(m); } } System.out.println("Integrity only: " + integrityOnly); System.out.println("Confidentiality only: " + confidentialityOnly); int total = 0; for (SootClass cl : Scene.v().getClasses()) { for (SootMethod m : cl.getMethods()) { for (Tag tag : m.getTags()) { if (tag instanceof VisibilityAnnotationTag) { for (AnnotationTag annotation : ((VisibilityAnnotationTag) tag).getAnnotations()) { if (annotation.getType().equals("Lsun/reflect/CallerSensitive;")) { total++; if (methods.contains(m)) methods.remove(m); else System.out.println("Cross check found method not in AnalysisTarget: " + m); } } } } } } System.out.println("cross check: " + total); System.out.println(methods.size()); } private Set<Path> executeForwardOnlyForNameAnalysis() { StoreDataTransformer<Set<Path>> dataStorage = new StoreDataTransformer<Set<Path>>(); SolverFactory.runOneDirectionSolver(AnalysisConfigurationBuilder.forwardsFromAllParametersDefaults(false).reporter( new ResultForwardingReporter(new PathBuilderResultTransformer(dataStorage, new MergeEqualSelectorStrategy())))); return dataStorage.getData(); } private Set<Path> executeForwardOnlyCallerSensitiveAnalysis() { StoreDataTransformer<Set<Path>> dataStorage = new StoreDataTransformer<Set<Path>>(); SolverFactory.runOneDirectionSolver(forwardsFromAllParametersDefaults(true).reporter( new ResultForwardingReporter(new PathBuilderResultTransformer(dataStorage, new MergeEqualSelectorStrategy())))); return dataStorage.getData(); } private Set<Path> executeI2OForNameAnalysis() { StoreDataTransformer<Set<Path>> dataStorage = new StoreDataTransformer<Set<Path>>(); SolverFactory.runInnerToOuterSolver(AnalysisConfigurationBuilder.i2oSimpleClassForNameDefaults().reporter( new ResultForwardingReporter(new FilterSingleDirectionReports(new PathBuilderResultTransformer(dataStorage, new MergeEqualSelectorStrategy()))))); return dataStorage.getData(); } private Set<Path> executeBidiForNameAnalysis() { StoreDataTransformer<Set<Path>> dataStorage = new StoreDataTransformer<Set<Path>>(); SolverFactory.runBiDirectionSolver(i2oSimpleClassForNameDefaults().reporter( new ResultForwardingReporter(new PathBuilderResultTransformer(dataStorage, new MergeEqualSelectorStrategy())))); return dataStorage.getData(); } private Set<Path> executeBidiCallerSensitiveAnalysis() { StoreDataTransformer<Set<Path>> dataStorage = new StoreDataTransformer<Set<Path>>(); SolverFactory.runBiDirectionSolver(i2oGenericCallerSensitiveDefaults().reporter( new ResultForwardingReporter(new PathBuilderResultTransformer(dataStorage, new MergeEqualSelectorStrategy())))); return dataStorage.getData(); } // private void executeSinkBySink() { // AnalysisConfigurationBuilder configBuilder = // i2oGenericCallerSensitiveDefaults().direction(FORWARDS).reporter(new // ConsoleReporter()); // Set<Unit> seeds = new // SeedFactory.I2OSeedFactory().initialSeeds(configBuilder.build()); // int i = 0; // for (final Unit seed : seeds) { // System.out.println("==============="); // System.out.println("Seed: " + i + " / " + seeds.size()); // System.out.println("==============="); // // Set<Path> validPaths = executeWithTimeout(configBuilder, seed); // // System.out.println("Solvers finished"); // // if (!validPaths.isEmpty()) { // MultipleAnalysisPlotter plotter = new MultipleAnalysisPlotter(); // plotter.plotAnalysisResults(validPaths, "red"); // plotter.writeFile("analysisResults-" + i); // } // i++; // } // } // protected Set<Path> // executeWithTimeout(AnalysisConfigurationBuilder configBuilder, // final Unit seed) { // StoreDataTransformer<Set<Path>> dataStorage = new // StoreDataTransformer<Set<Path>>(); // SolverFactory.runInnerToOuterSolver(configBuilder.reporter( // new ResultForwardingReporter(new FilterSingleDirectionReports(new // PathBuilderResultTransformer(dataStorage, // new // MergeEqualSelectorStrategy())))).seedFactory(createSeedFactory(seed))); // return dataStorage.getData(); // } // // private void execute(AnalysisConfigurationBuilder configBuilder) // { // Debugger debugger = new Debugger(); // FanInFanOutDebugger fanInOut = new FanInFanOutDebugger(); // debugger.registerListener(fanInOut); // // TabularViewer tabularViewer = new TabularViewer(debugger, // // fanInOut); // SolverFactory.runOneDirectionSolver(configBuilder.debugger(debugger)); // // tabularViewer.dispose(); // } // protected SeedFactory createSeedFactory(final Unit seed) { // return new SeedFactory() { // @Override // public java.util.Set<Unit> initialSeeds(AnalysisConfiguration // config) { // return Sets.newHashSet(seed); // }; // }; // } @Override protected ArrayList<String> createArgs() { ArrayList<String> argList = new ArrayList<String>(Arrays.asList(args)); String jrePath = argList.remove(0); AnalysisUtil.initRestrictedPackages(jrePath); argList.add("-w"); argList.add("-f"); argList.add("none"); argList.add("-p"); argList.add("cg"); argList.add("all-reachable:true"); argList.add("-keep-line-number"); argList.add("-include-all"); argList.add("-allow-phantom-refs"); argList.add("-f"); argList.add("none"); argList.add("-pp"); return argList; } }.execute(); } }
11,722
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z
ReportMerger.java
/FileExtraction/Java_unseen/johanneslerch_FlowTwist/FlowTwist/src/flow/twist/ReportMerger.java
package flow.twist; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.TreeMap; import java.util.TreeSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class ReportMerger { public static void main(String[] args) throws IOException { TreeMap<String, TreeMap<File, Integer>> results = Maps.newTreeMap(); TreeSet<File> jres = Sets.newTreeSet(); File resultsDir = new File("results"); for (File jreDir : resultsDir.listFiles()) { jres.add(jreDir); File reportFile = new File(jreDir, "report.csv"); if (!reportFile.exists()) { System.out.println("No report file for " + jreDir); continue; } BufferedReader reader = new BufferedReader(new FileReader(reportFile)); String line = null; while ((line = reader.readLine()) != null) { String[] split = line.split(";"); TreeMap<File, Integer> innerMap = results.containsKey(split[0]) ? results.get(split[0]) : Maps.<File, Integer> newTreeMap(); innerMap.put(jreDir, Integer.parseInt(split[1])); results.put(split[0], innerMap); } reader.close(); } FileWriter writer = new FileWriter("report.csv"); writer.write(";");// no sink for (File jre : jres) { writer.write(jre.getName()); writer.write(";"); } writer.write("\n"); for (String sink : results.keySet()) { writer.write(sink); writer.write(";"); TreeMap<File, Integer> inner = results.get(sink); for (File jre : jres) { if (inner.containsKey(jre)) writer.write(String.valueOf(inner.get(jre))); writer.write(";"); } writer.write("\n"); } writer.close(); } }
1,711
Java
.java
johanneslerch/FlowTwist
9
4
0
2014-03-14T10:26:08Z
2015-02-13T09:54:39Z