# 16.5.安全等级

安全等级是内核实现的一个安全机制。当安全等级设置为正值时，内核会限制某些任务的执行；即使是超级用户（root）也无法进行这些操作。

安全等级机制限制了以下操作的能力：

* 取消某些文件标志，例如 `schg`（系统不可变标志）。
* 通过 **/dev/mem** 和 **/dev/kmem** 写入内核内存。
* 加载内核模块。
* 修改防火墙规则。

## 16.5.1. 安全等级定义

内核运行时有五个不同的安全等级。任何超级用户进程可以提升级别，但没有进程可以降低它。

安全等级定义如下：

* **-1** 永久不安全模式 - 始终在不安全模式下运行系统。这是默认初始值。
* **0** 不安全模式 - 可以关闭不可变标志和追加-only 标志。所有设备可以根据权限进行读写。
* **1** 安全模式 - 系统不可变和系统追加-only 标志不能关闭；不能为挂载的文件系统、**/dev/mem** 和 **/dev/kmem** 打开写入；**/dev/io**（如果平台支持）不能被打开；不能加载或卸载内核模块。不能使用 debug.kdb.enter sysctl 进入内核调试器。无法通过 `debug.kdb.panic`、`debug.kdb.panic_str` 等 sysctl 强制触发 panic 或陷阱。
* **2** 高安全模式 - 与安全模式相同，另外，磁盘不能被写入（除了通过 [mount(2)](https://man.freebsd.org/cgi/man.cgi?query=mount\&sektion=2\&format=html)）。这个级别防止通过卸载文件系统来篡改文件系统，但也会抑制在多用户系统中运行 [newfs(8)](https://man.freebsd.org/cgi/man.cgi?query=newfs\&sektion=8\&format=html)。
* **3** 网络安全模式 - 与高安全模式相同，另外，IP 包过滤规则（见 [ipfw(8)](https://man.freebsd.org/cgi/man.cgi?query=ipfw\&sektion=8\&format=html)、[ipfirewall(4)](https://man.freebsd.org/cgi/man.cgi?query=ipfirewall\&sektion=4\&format=html) 和 [pfctl(8)](https://man.freebsd.org/cgi/man.cgi?query=pfctl\&sektion=8\&format=html)）不能被更改，不能调整 [dummynet(4)](https://man.freebsd.org/cgi/man.cgi?query=dummynet\&sektion=4\&format=html) 或 [pf(4)](https://man.freebsd.org/cgi/man.cgi?query=pf\&sektion=4\&format=html) 配置。

> **技巧**
>
> 总结：在 FreeBSD 安全等级中，`永久不安全模式` 和 `不安全模式` 之间的关键区别是它们提供的安全性程度。`永久不安全模式` 完全解除所有安全限制，而 `不安全模式` 放松了一些限制，但仍然维持一定的控制和安全性。

## 16.5.2. 修改安全等级

要更改系统的安全等级，首先需要通过执行以下命令启用 `kern_securelevel_enable`：

```sh
# sysrc kern_securelevel_enable="YES"
```

然后设置 `kern_securelevel` 的值为所需的安全等级：

```sh
# sysrc kern_securelevel=2
```

要检查正在运行的系统的安全等级状态，可以执行以下命令：

```sh
# sysctl -n kern.securelevel
```

输出将包含当前的安全等级值。如果它大于 0，则至少启用了某些安全等级的保护措施。


---

# 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://book.bsdcn.org/hanbook/di-16-zhang-an-quan/16.5.-an-quan-deng-ji.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.
