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

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

相关文章

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

Linux系统中卸载与安装JDK的详细教程

《Linux系统中卸载与安装JDK的详细教程》本文详细介绍了如何在Linux系统中通过Xshell和Xftp工具连接与传输文件,然后进行JDK的安装与卸载,安装步骤包括连接Linux、传输JDK安装包... 目录1、卸载1.1 linux删除自带的JDK1.2 Linux上卸载自己安装的JDK2、安装2.1

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

MyBatis 动态 SQL 优化之标签的实战与技巧(常见用法)

《MyBatis动态SQL优化之标签的实战与技巧(常见用法)》本文通过详细的示例和实际应用场景,介绍了如何有效利用这些标签来优化MyBatis配置,提升开发效率,确保SQL的高效执行和安全性,感... 目录动态SQL详解一、动态SQL的核心概念1.1 什么是动态SQL?1.2 动态SQL的优点1.3 动态S

Pandas使用SQLite3实战

《Pandas使用SQLite3实战》本文主要介绍了Pandas使用SQLite3实战,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1 环境准备2 从 SQLite3VlfrWQzgt 读取数据到 DataFrame基础用法:读

Linux系统之主机网络配置方式

《Linux系统之主机网络配置方式》:本文主要介绍Linux系统之主机网络配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、查看主机的网络参数1、查看主机名2、查看IP地址3、查看网关4、查看DNS二、配置网卡1、修改网卡配置文件2、nmcli工具【通用

Linux系统之dns域名解析全过程

《Linux系统之dns域名解析全过程》:本文主要介绍Linux系统之dns域名解析全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、dns域名解析介绍1、DNS核心概念1.1 区域 zone1.2 记录 record二、DNS服务的配置1、正向解析的配置

Python实战之屏幕录制功能的实现

《Python实战之屏幕录制功能的实现》屏幕录制,即屏幕捕获,是指将计算机屏幕上的活动记录下来,生成视频文件,本文主要为大家介绍了如何使用Python实现这一功能,希望对大家有所帮助... 目录屏幕录制原理图像捕获音频捕获编码压缩输出保存完整的屏幕录制工具高级功能实时预览增加水印多平台支持屏幕录制原理屏幕

Linux系统中配置静态IP地址的详细步骤

《Linux系统中配置静态IP地址的详细步骤》本文详细介绍了在Linux系统中配置静态IP地址的五个步骤,包括打开终端、编辑网络配置文件、配置IP地址、保存并重启网络服务,这对于系统管理员和新手都极具... 目录步骤一:打开终端步骤二:编辑网络配置文件步骤三:配置静态IP地址步骤四:保存并关闭文件步骤五:重

最新Spring Security实战教程之Spring Security安全框架指南

《最新SpringSecurity实战教程之SpringSecurity安全框架指南》SpringSecurity是Spring生态系统中的核心组件,提供认证、授权和防护机制,以保护应用免受各种安... 目录前言什么是Spring Security?同类框架对比Spring Security典型应用场景传统