实战-系统权限白名单授权

2024-05-25 14:58

本文主要是介绍实战-系统权限白名单授权,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

需求:

针对一些系统的应用或者第三方预置的应用,开机时默认授予权限,通知预置一个授权白名单文件,对文件内容的所有包名进行授权

预置授权文件

pms_sysapp_grant_permission_list.txt

com.gankao.gkwxhd

device/amlogic-o/u202/preinstall/preinstall.mk

PRODUCT_COPY_FILES += \$(LOCAL_PATH)/files/pms_sysapp_grant_permission_list.txt:system/etc/permissions/pms_sysapp_grant_permission_list.txt
方案1 ,增加一个FunPackageManagerUtil 类,在PackageManagerService.java 启动的时候,启动默认授权

frameworks/base / services/core/java/com/android/server/pm/PackageManagerService.java

public void systemReady() {// add for system app grant permission Sif (mFirstBoot) {FunPackageManagerUtil.slientGrantRuntimePermission(mContext, mPermissionManager);}// add for system app grant permission E
}

frameworks/base/services/core/java/com/android/server/pm/FunPackageManagerUtil.java

package com.android.server.pm;import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;import com.android.server.pm.permission.BasePermission;
import com.android.server.pm.permission.PermissionManagerInternal;
import android.content.pm.IPackageManager;
import android.app.AppGlobals;
import android.app.AppOpsManager;
import android.Manifest;
import com.android.internal.util.ArrayUtils;import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;public class FunPackageManagerUtil{private static String TAG = "FunPackageManagerUtil";private static final File GRANT_SYS_APP_LIST_SYSTEM = Environment.buildPath(Environment.getRootDirectory(), "etc", "permissions","pms_sysapp_grant_permission_list.txt");private static HashSet<String> sGrantSystemAppSet = new HashSet<String>();private static HashSet<String> sGrantPermissionSet = new HashSet<String>();private static  IPackageManager mIpm;private static  AppOpsManager mAppOpsManager;public static void slientGrantRuntimePermission(Context mContext,PermissionManagerInternal mPermissionManager){sGetGrantSystemAppFromFile(sGrantSystemAppSet, GRANT_SYS_APP_LIST_SYSTEM);PackageManager mPackageManager = mContext.getPackageManager();mIpm = AppGlobals.getPackageManager();mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);Iterator<String> it = sGrantSystemAppSet.iterator();Log.d(TAG, "sGrantSystemAppSet:");while (it.hasNext()) {sGrantPermissionSet.clear();String pkgName = it.next();Log.d(TAG, "pkgName="+pkgName);try {PackageInfo mPackageInfo =   mPackageManager.getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS);for (String permission : mPackageInfo.requestedPermissions){int status = mPackageManager.checkPermission(permission, pkgName);//final BasePermission bp = mSettings.mPermissions.get(permission);final BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(permission);if (status != PackageManager.PERMISSION_GRANTED && bp != null) {if (!bp.isRuntime() /*&& !bp.isDevelopment()*/) {Log.d(TAG, "Permission " + bp.getName() + " is not a changeable permission type");continue;}sGrantPermissionSet.add(permission);}}Log.e(TAG, " need grantRuntimePermission size:"+sGrantPermissionSet.size());for (String permission : sGrantPermissionSet) {mPackageManager.grantRuntimePermission(pkgName,permission, Process.myUserHandle());}if (checkInstallPackagesPermission(pkgName, mPackageInfo)) {Log.e(TAG, pkgName + " need grant INSTALL_PACKAGES permission");mAppOpsManager.setMode(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES,mPackageInfo.applicationInfo.uid, pkgName, AppOpsManager.MODE_ALLOWED);Log.e(TAG, "grant INSTALL_PACKAGES permission done");}} catch (Exception e) {//e.printStackTrace();Log.d(TAG, e.getMessage());}}}private static boolean checkInstallPackagesPermission(String packageName, PackageInfo mPackageInfo){int uid = mPackageInfo.applicationInfo.uid;//boolean permissionGranted = hasPermission(Manifest.permission.REQUEST_INSTALL_PACKAGES, uid);boolean permissionRequested = hasRequestedAppOpPermission(Manifest.permission.REQUEST_INSTALL_PACKAGES, packageName);int appOpMode = getAppOpMode(AppOpsManager.OP_REQUEST_INSTALL_PACKAGES, uid, packageName);return appOpMode != AppOpsManager.MODE_DEFAULT || permissionRequested;}private static int getAppOpMode(int appOpCode, int uid, String packageName) {return mAppOpsManager.checkOpNoThrow(appOpCode, uid, packageName);}private static boolean hasRequestedAppOpPermission(String permission, String packageName) {try {String[] packages = mIpm.getAppOpPermissionPackages(permission);return ArrayUtils.contains(packages, packageName);} catch (Exception exc) {Log.e(TAG, "PackageManager dead. Cannot get permission info");return false;}}private static boolean hasPermission(String permission, int uid) {try {int result = mIpm.checkUidPermission(permission, uid);return result == PackageManager.PERMISSION_GRANTED;} catch (Exception e) {Log.e(TAG, "PackageManager dead. Cannot get permission info");return false;}}/*** Get removable system app list from config file** @param resultSet*            Returned result list* @param file*            The config file*/private static void sGetGrantSystemAppFromFile(HashSet<String> resultSet, File file) {resultSet.clear();FileReader fr = null;BufferedReader br = null;try {if (file.exists()) {fr = new FileReader(file);} else {Log.d(TAG, "file in " + file + " does not exist!");return;}br = new BufferedReader(fr);String line;while ((line = br.readLine()) != null) {line = line.trim();if (!TextUtils.isEmpty(line)) {Log.d(TAG, "read line " + line);resultSet.add(line);}}Log.e(TAG,"GRANT_SYS_APP_LIST_SYSTEM size="+resultSet.size());} catch (Exception io) {Log.d(TAG, io.getMessage());} finally {try {if (br != null) {br.close();}if (fr != null) {fr.close();}} catch (IOException io) {Log.d(TAG, io.getMessage());}}}
}
方案2,在PackageInstaller 里面增加一个服务,进行授权

在AMS 中启动授权服务
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

 final void finishBooting() {startPermisionService();}
private void startPermisionService() {try{Log.d(TAG, "startPermisionService ...");Intent intent = new Intent();intent.setPackage("com.android.packageinstaller");intent.setAction("android.permission.PackagePermissionGrantService");mContext.startService(intent);}catch (Exception e){e.printStackTrace();}}

Background start not allowed

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

int getAppStartModeLocked() {if(packageName.equalsIgnoreCase("com.android.packageinstaller")){return ActivityManager.APP_START_MODE_NORMAL;}
}

PackageInstaller/src/com/android/packageinstaller/permission/service/PackagePermissionGrantService.java

package com.android.packageinstaller.permission.service;import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import android.os.Environment;import com.android.packageinstaller.permission.model.AppPermissionGroup;
import com.android.packageinstaller.permission.model.AppPermissions;
import com.android.packageinstaller.permission.model.Permission;
import com.android.packageinstaller.permission.utils.ArrayUtils;public class PackagePermissionGrantService extends Service {private static final  String TAG = "PackagePermission";private static final File GRANT_SYS_APP_LIST_SYSTEM = new File(Environment.getRootDirectory(),"/etc/permissions/pms_sysapp_grant_permission_list.txt");private static HashSet<String> sGrantSystemAppSet = new HashSet<String>();Permissionhandler handler;@Overridepublic void onCreate() {super.onCreate();Log.i(TAG, "onCreate OK");handler = new Permissionhandler();}@Overridepublic IBinder onBind(Intent arg0) {return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {handler.sendEmptyMessageDelayed(100,8000);return Service.START_NOT_STICKY;}@Overridepublic void onDestroy() {Log.e(TAG, " stop self onDestroy=");handler.removeCallbacksAndMessages(null);super.onDestroy();}class Permissionhandler extends Handler {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case 100:Log.e(TAG, "start grant permission");FunSlientGrantRuntimePermission();sendEmptyMessageDelayed(101,15000);break;case 101:stopSelf();break;}}}public void FunSlientGrantRuntimePermission(){sGetGrantSystemAppFromFile(sGrantSystemAppSet, GRANT_SYS_APP_LIST_SYSTEM);Iterator<String> it = sGrantSystemAppSet.iterator();while (it.hasNext()) {String pkgName = it.next();Log.d(TAG, "pkgName="+pkgName);slientGrantRuntimePermission(pkgName);}}public void slientGrantRuntimePermission(String packageName){PackageInfo packageInfo;try {Log.e(TAG, "PackageInfo for packageName="+ packageName);packageInfo =  getPackageManager().getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);} catch (PackageManager.NameNotFoundException e) {Log.e(TAG, "can't get PackageInfo for packageName="+ packageName);return;}AppPermissions mAppPermissions = new AppPermissions(this, packageInfo, null, false,new Runnable() {@Overridepublic void run() {stopSelf();}});Log.e(TAG, " AppPermissionGroup size==" + mAppPermissions.getPermissionGroups().size());if (mAppPermissions.getPermissionGroups().isEmpty()) {Log.e(TAG, "mAppPermissions size isEmpty");return;}for (AppPermissionGroup group : mAppPermissions.getPermissionGroups()) {String[] permissionsToGrant = null;final int permissionCount = group.getPermissions().size();for (int j = 0; j < permissionCount; j++) {final Permission permission = group.getPermissions().get(j);Log.e(TAG, "permissionName=" +permission.getName()+",isGranted="+ permission.isGranted());if (!permission.isGranted()) {permissionsToGrant = ArrayUtils.appendString(permissionsToGrant, permission.getName());Log.e(TAG, "permissionName=" + permission.getName());}}if (permissionsToGrant != null) {group.grantRuntimePermissions(false, permissionsToGrant);Log.i(TAG, "grantRuntimePermissions permissionsToGrant");}}}private static void sGetGrantSystemAppFromFile(HashSet<String> resultSet, File file) {resultSet.clear();FileReader fr = null;BufferedReader br = null;try {if (file.exists()) {fr = new FileReader(file);} else {Log.d(TAG, "file in " + file + " does not exist!");return;}br = new BufferedReader(fr);String line;while ((line = br.readLine()) != null) {line = line.trim();if (!TextUtils.isEmpty(line)) {Log.d(TAG, "read line " + line);resultSet.add(line);}}Log.e(TAG,"GRANT_SYS_APP_LIST_SYSTEM size="+resultSet.size());} catch (Exception io) {Log.d(TAG, io.getMessage());} finally {try {if (br != null) {br.close();}if (fr != null) {fr.close();}} catch (IOException io) {Log.d(TAG, io.getMessage());}}}
}

AndroidManifest.xml

<service android:name="com.android.permissioncontroller.permission.service.PackagePermissionGrantService">
<intent-filter android:priority="1"><action android:name="android.permission.PackagePermissionGrantService"/></intent-filter>
</service>

这篇关于实战-系统权限白名单授权的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1001828

相关文章

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

在不同系统间迁移Python程序的方法与教程

《在不同系统间迁移Python程序的方法与教程》本文介绍了几种将Windows上编写的Python程序迁移到Linux服务器上的方法,包括使用虚拟环境和依赖冻结、容器化技术(如Docker)、使用An... 目录使用虚拟环境和依赖冻结1. 创建虚拟环境2. 冻结依赖使用容器化技术(如 docker)1. 创

浅析如何使用Swagger生成带权限控制的API文档

《浅析如何使用Swagger生成带权限控制的API文档》当涉及到权限控制时,如何生成既安全又详细的API文档就成了一个关键问题,所以这篇文章小编就来和大家好好聊聊如何用Swagger来生成带有... 目录准备工作配置 Swagger权限控制给 API 加上权限注解查看文档注意事项在咱们的开发工作里,API

在Java中使用ModelMapper简化Shapefile属性转JavaBean实战过程

《在Java中使用ModelMapper简化Shapefile属性转JavaBean实战过程》本文介绍了在Java中使用ModelMapper库简化Shapefile属性转JavaBean的过程,对比... 目录前言一、原始的处理办法1、使用Set方法来转换2、使用构造方法转换二、基于ModelMapper

CentOS系统Maven安装教程分享

《CentOS系统Maven安装教程分享》本文介绍了如何在CentOS系统中安装Maven,并提供了一个简单的实际应用案例,安装Maven需要先安装Java和设置环境变量,Maven可以自动管理项目的... 目录准备工作下载并安装Maven常见问题及解决方法实际应用案例总结Maven是一个流行的项目管理工具

Java实战之自助进行多张图片合成拼接

《Java实战之自助进行多张图片合成拼接》在当今数字化时代,图像处理技术在各个领域都发挥着至关重要的作用,本文为大家详细介绍了如何使用Java实现多张图片合成拼接,需要的可以了解下... 目录前言一、图片合成需求描述二、图片合成设计与实现1、编程语言2、基础数据准备3、图片合成流程4、图片合成实现三、总结前

nginx-rtmp-module构建流媒体直播服务器实战指南

《nginx-rtmp-module构建流媒体直播服务器实战指南》本文主要介绍了nginx-rtmp-module构建流媒体直播服务器实战指南,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有... 目录1. RTMP协议介绍与应用RTMP协议的原理RTMP协议的应用RTMP与现代流媒体技术的关系2

C语言小项目实战之通讯录功能

《C语言小项目实战之通讯录功能》:本文主要介绍如何设计和实现一个简单的通讯录管理系统,包括联系人信息的存储、增加、删除、查找、修改和排序等功能,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录功能介绍:添加联系人模块显示联系人模块删除联系人模块查找联系人模块修改联系人模块排序联系人模块源代码如下

C#实现系统信息监控与获取功能

《C#实现系统信息监控与获取功能》在C#开发的众多应用场景中,获取系统信息以及监控用户操作有着广泛的用途,比如在系统性能优化工具中,需要实时读取CPU、GPU资源信息,本文将详细介绍如何使用C#来实现... 目录前言一、C# 监控键盘1. 原理与实现思路2. 代码实现二、读取 CPU、GPU 资源信息1.