# 应用沙箱

Android 平台利用基于 Linux 的用户保护来识别和隔离应用资源。这将应用彼此隔离，并保护应用和系统免受恶意应用的侵害。为此，Android 为每个 Android 应用分配一个唯一的用户 ID (UID)，并在其自己的进程中运行它。

![](/files/h80LyOgmTzlOx09fc8fd)

Android 使用 UID 来设置内核级的应用沙箱。内核通过分配给应用的标准 Linux 设施（如用户和组 ID）在进程级别强制执行应用和系统之间的安全性。默认情况下，应用无法相互交互，并且对操作系统的访问权限有限。沙箱简单、可审计，并且基于已有数十年历史的 UNIX 风格的进程和文件权限分离。

您可以通过查看 `/data/data` 文件夹中的文件系统权限来确认这一点

```bash
$ ls -la /data/data
drwx------  4 u0_a13    u0_a13    4096 2021-02-01 13:37 com.package1.app1
drwx------  6 u0_a163   u0_a163   4096 2021-02-01 13:39 com.package2.app2
```

由于应用沙箱位于内核中，此安全模型扩展到原生代码和操作系统应用程序。内核之上的所有软件，如操作系统库、应用框架、应用运行时和所有应用，都在应用沙箱内运行。

## 保护机制

Android 依靠多种保护机制来强制执行应用沙箱。这些强制措施是随着时间的推移而引入的，并显著增强了原始基于 UID 的自主访问控制 (DAC) 沙箱。以前的 Android 版本包括以下保护机制：

* 在 Android 5.0 中，[SELinux](https://www.redhat.com/en/topics/linux/what-is-selinux) 提供了系统和应用之间的强制访问控制 (MAC) 分离。但是，所有第三方应用都在同一个 SELinux 上下文中运行，因此应用间隔离主要由 UID DAC 强制执行。
* 在 Android 6.0 中，[SELinux](https://www.redhat.com/en/topics/linux/what-is-selinux) 沙箱扩展到跨物理用户边界隔离应用。此外，Android 还为应用数据设置了更安全的默认值：对于 `targetSdkVersion >= 24` 的应用，应用主目录的默认 DAC 权限从 `751` 更改为 `700`。这为私有应用数据提供了更安全的默认值（尽管应用可能会覆盖这些默认值）。
* 在 Android 8.0 中，所有应用都被设置为使用 [seccomp-bpf](https://www.kernel.org/doc/html/v4.16/userspace-api/seccomp_filter.html) 过滤器运行，该过滤器限制了允许应用使用的系统调用，从而加强了应用/内核边界。
* 在 Android 9 中，所有 `targetSdkVersion >= 28` 的非特权应用必须在单独的 [SELinux](https://www.redhat.com/en/topics/linux/what-is-selinux) 沙箱中运行，提供基于每个应用的 MAC。此保护机制改善了应用分离，防止覆盖安全默认值，并且（最重要的是）防止应用使其数据全局可访问。
* 在 Android 10 中，应用对文件系统的原始视图有限，无法直接访问 `/sdcard/DCIM` 等路径。但是，应用保留对其包特定路径的完全原始访问权限，如任何适用方法（如 `Context.getExternalFilesDir()`）返回的路径。

## 参考资料

* [Android 开源项目：应用沙箱](https://source.android.com/security/app-sandbox)
* [MSTG：Android - 平台概览](https://mobile-security.gitbook.io/mobile-security-testing-guide/android-testing-guide/0x05a-platform-overview#the-app-sandbox)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.cdxiaodong.life/android-ying-yong-an-quan/gai-shu/app-sandbox.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
