如何在运行时检查android安全权限?

问题描述:

之前在 Android如何执行权限?中已问过此问题.尽管那里的讨论很好,但是问题仍然没有得到完全回答.

This question has been asked before at How does Android enforce permissions?. While the discussions there are good, the question is still not fully answered.

在开发环境中,当应用尝试执行需要在AndroidManifest.xml中未声明的权限的操作时,将引发异常.那么运行时系统如何实现运行时检查?

In the development environment, exceptions are thrown when the app tries to do something that requires permissions not declared in AndroidManifest.xml. So how does the run-time system implement the run-time checking?

我想这很可能是在核心框架中完成的,它可能需要也可能不需要本机代码的支持.但是我不知道AOSP中的哪些源代码文件与此相关.

I guess it's most likely done in the core framework, which may or may not need support from native code. But I don't know what source code files in AOSP are relevant to this.

Android使用许多标准的Linux(-kernel?)机制,尤其是在硬件限制方面.

Android uses a lot of the standard Linux(-kernel?) mechanisms especially when it comes to hardware restrictions.

每个应用程序都被分配一个新的唯一(Linux-)用户ID,并且每当创建应用程序进程时,系统都会使用该用户ID创建它.除非您删除该应用程序,否则ID永远不会更改.这意味着,为了访问较低的系统级别,您的应用将以特定用户的身份出现,并且与用户一起使用的每个(Linux-)许可系统也将适用于您的应用.

Every app gets assigned a new unique (Linux-)user id and whenever the app process is created the system creates it with that user id. The id will never change unless you remove the app. That means for accessing the lower system levels your app will appear as a certain user and every (Linux-)permission system that works with users will also apply to your app.

如果您在清单中请求WRITE_EXTERNAL_STORAGE,您的应用程序也将成为(Linux-)组(称为sdcard_rw)的成员,该组具有写入该存储的权限.文件系统的权限被强制为仅允许写入system用户(=所有者)和sdcard_rw组,其他任何人(= other)都只能读取.另请参见 Google是否阻止了将应用程序写入SD卡

If you request WRITE_EXTERNAL_STORAGE in the manifest your app will also become member of the (Linux-)group (called sdcard_rw) that has permissions to write to that storage. Permissions on the filesystem are enforced to only allow writing to the system user (=owner) and the sdcard_rw group, anyone else (=other) may only read. See also Is Google blocking apps writing to SD cards

这样做,除了设置应用程序启动后产生的进程的正确UID/GID之外,Android几乎不需要执行任何其他操作,而其他操作则在较低级别上进行.不属于某个组的应用程序根本无法访问某些硬件.

By doing that Android has to do pretty much nothing except for setting the correct UID/GIDs of the processes it spawns once the app starts and the rest is handled at lower levels. Apps that are not member of a certain group simply don't get access to certain hardware.

权限列表<>组映射: platform.xml

List of permission <> group mappings: platform.xml

还有一些(Android软件)限制基于您的应用程序的签名和/或仅通过查找您的应用程序请求的权限即可:

There are also some (Android software) restrictions that are based on either the signature of your app and / or simply by looking up the permissions your app requested: e.g. ContextImpl#checkPermission() - but those permissions have to be checked at every entrypoint to code that allows restricted actions.

人们不时发现例如以编程方式打开GPS,因为在某处缺少这样的检查.

From time to time people discover ways to e.g. turn on GPS programmatically because a check like that is missing somewhere.