> For the complete documentation index, see [llms.txt](https://book.bsdcn.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.bsdcn.org/man/man9/priv.9.md).

# priv.9

`priv` — 内核权限检查 API

## 名称

`priv`

## 概要

```c
#include <sys/priv.h>
```

```c
int
priv_check(struct thread *td, int priv)

int
priv_check_cred(struct ucred *cred, int priv)
```

## 描述

`priv` 接口检查是否向传入的线程 `td` 或凭据 `cred` 授予了特定系统权限。此接口替代了现已移除的 suser(9) 权限检查接口。权限通常表示以下两类权利之一：管理系统特定组件的权利，或对特定策略或访问控制列表的豁免。调用者通过 `priv` 参数标识所需的权限。

### 权限策略

权限通常基于以下两种基本系统策略之一授予：超级用户策略，根据有效（或有时为实际）UID 值为 0 来授予权限；以及 jail(2) 策略，仅允许向 jail 中的进程授予某些权限。可用权限集还可能受 [mac(9)](/man/man9/mac.9.md) 中描述的 TrustedBSD MAC 框架影响。

## 实现说明

向代码路径添加新的权限检查时，首先检查 `sys/priv.h` 中当前权限的完整列表，查看是否已存在适用于所需权限类别的权限。只有在没有完全匹配的情况下，才应向权限列表添加新权限。由于权限号会编码到内核模块 ABI 中，因此不得更改权限常量，否则任何依赖权限的内核模块都需要重新编译。添加新权限时，务必确定是否应将其列在 `prison_priv_check` 中，该函数包含 jail(2) 中授予 root 用户的权限完整列表。

存在某些通用权限，如 `PRIV_DRIVER`，旨在供设备驱动程序使用，而不是添加新的驱动程序特定权限。

## 返回值

通常，成功返回 0，失败返回 `EPERM`。大多数 `priv` 的使用者会希望将失败的权限检查的错误代码直接返回到用户空间；少数使用者会希望将其转换为适合特定上下文的其他错误代码。

设计新 API 时，如果未授予权限，最好从调用中返回显式错误，而不是更改调用语义但返回成功。例如，stat(2) 所表现的行为——当权限不足时可选地将生成字段清零——是极不可取的，因为它会导致频繁的权限检查，且调用者无法判断是否发生了访问控制失败。

## 参见

[jail(2)](https://github.com/FreeBSD-Ask/freebsd-man-sc/tree/main/man2/jail.2.md), [dtrace\_priv(4)](/man/man4/dtrace_priv.4.md), [mac(9)](/man/man9/mac.9.md), [ucred(9)](/man/man9/ucred.9.md)

## 作者

`priv` API 和实现由 Robert Watson 在为 nCircle Network Security, Inc. 工作期间创建。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://book.bsdcn.org/man/man9/priv.9.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
