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

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

相关文章

网页解析 lxml 库--实战

lxml库使用流程 lxml 是 Python 的第三方解析库,完全使用 Python 语言编写,它对 XPath表达式提供了良好的支 持,因此能够了高效地解析 HTML/XML 文档。本节讲解如何通过 lxml 库解析 HTML 文档。 pip install lxml lxm| 库提供了一个 etree 模块,该模块专门用来解析 HTML/XML 文档,下面来介绍一下 lxml 库

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

不懂推荐算法也能设计推荐系统

本文以商业化应用推荐为例,告诉我们不懂推荐算法的产品,也能从产品侧出发, 设计出一款不错的推荐系统。 相信很多新手产品,看到算法二字,多是懵圈的。 什么排序算法、最短路径等都是相对传统的算法(注:传统是指科班出身的产品都会接触过)。但对于推荐算法,多数产品对着网上搜到的资源,都会无从下手。特别当某些推荐算法 和 “AI”扯上关系后,更是加大了理解的难度。 但,不了解推荐算法,就无法做推荐系

基于人工智能的图像分类系统

目录 引言项目背景环境准备 硬件要求软件安装与配置系统设计 系统架构关键技术代码示例 数据预处理模型训练模型预测应用场景结论 1. 引言 图像分类是计算机视觉中的一个重要任务,目标是自动识别图像中的对象类别。通过卷积神经网络(CNN)等深度学习技术,我们可以构建高效的图像分类系统,广泛应用于自动驾驶、医疗影像诊断、监控分析等领域。本文将介绍如何构建一个基于人工智能的图像分类系统,包括环境

水位雨量在线监测系统概述及应用介绍

在当今社会,随着科技的飞速发展,各种智能监测系统已成为保障公共安全、促进资源管理和环境保护的重要工具。其中,水位雨量在线监测系统作为自然灾害预警、水资源管理及水利工程运行的关键技术,其重要性不言而喻。 一、水位雨量在线监测系统的基本原理 水位雨量在线监测系统主要由数据采集单元、数据传输网络、数据处理中心及用户终端四大部分构成,形成了一个完整的闭环系统。 数据采集单元:这是系统的“眼睛”,

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置

嵌入式QT开发:构建高效智能的嵌入式系统

摘要: 本文深入探讨了嵌入式 QT 相关的各个方面。从 QT 框架的基础架构和核心概念出发,详细阐述了其在嵌入式环境中的优势与特点。文中分析了嵌入式 QT 的开发环境搭建过程,包括交叉编译工具链的配置等关键步骤。进一步探讨了嵌入式 QT 的界面设计与开发,涵盖了从基本控件的使用到复杂界面布局的构建。同时也深入研究了信号与槽机制在嵌入式系统中的应用,以及嵌入式 QT 与硬件设备的交互,包括输入输出设

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

【区块链 + 人才服务】可信教育区块链治理系统 | FISCO BCOS应用案例

伴随着区块链技术的不断完善,其在教育信息化中的应用也在持续发展。利用区块链数据共识、不可篡改的特性, 将与教育相关的数据要素在区块链上进行存证确权,在确保数据可信的前提下,促进教育的公平、透明、开放,为教育教学质量提升赋能,实现教育数据的安全共享、高等教育体系的智慧治理。 可信教育区块链治理系统的顶层治理架构由教育部、高校、企业、学生等多方角色共同参与建设、维护,支撑教育资源共享、教学质量评估、