
Python 환경, requirements 파일 및 종속성 트리를 감사하여 알려진 보안 취약점을 찾고 자동으로 수정할 수 있습니다.
pip-audit는 알려진 취약점이 있는 패키지를 검색하기 위해 Python 환경을 스캔하는 도구입니다. 이 도구는 취약점 보고서 소스로 PyPI JSON API를 통해 Python Packaging Advisory Database(https://github.com/pypa/advisory-database)를 사용합니다.
이 프로젝트는 Google의 지원을 받아 Trail of Bits가 부분적으로 유지 관리합니다. 이는 공식 Google 또는 Trail of Bits 제품이 아닙니다.
--fix)pip 캐시를 원활하게 재사용pip-audit는 Python 3.10 이상이 필요하며, pip를 통해 직접 설치할 수 있습니다:```bash
python -m pip install pip-audit
### 서드파티 패키지
`pip-audit`을 위한 여러 **서드파티** 패키지가 있습니다. 아래의 행렬과 배지에는 그중 일부가 나와 있습니다:
[](https://repology.org/project/python:pip-audit/versions)
[](https://repology.org/project/pip-audit/versions)
[][#conda-forge-package]
[][#conda-forge-package]
[#conda-forge-package]: https://anaconda.org/conda-forge/pip-audit
특히, `pip-audit`은 `conda`를 통해 설치할 수 있습니다:```bash
conda install -c conda-forge pip-audit
타사 패키지는 이 프로젝트에서 직접 지원되지 않습니다. 더 자세한 설치 지침은 패키지 관리자의 문서를 참조하세요.
pip-audit에는 공식 GitHub Action이 있습니다!
GitHub 마켓플레이스에서 설치하거나, 수동으로 CI에 추가할 수 있습니다:```yaml jobs: pip-audit: steps: - uses: pypa/[email protected] with: inputs: requirements.txt
자세한 내용과 사용 예시는 [액션 문서](https://github.com/pypa/gh-action-pip-audit/blob/main/README.md)를 참조하세요.
### `pre-commit` 지원
`pip-audit`은 [`pre-commit`](https://pre-commit.com/)을 지원합니다.
예를 들어, `pre-commit`을 통해 `pip-audit`을 사용하여 요구 사항 파일을 감사하는 경우:```yaml
- repo: https://github.com/pypa/pip-audit
rev: v2.10.1
hooks:
- id: pip-audit
args: ["-r", "requirements.txt"]
ci:
# Leave pip-audit to only run locally and not in CI
# pre-commit.ci does not allow network calls
skip: [pip-audit]
아래 문서화된 모든 pip-audit 인수를 전달할 수 있습니다.
pip-audit를 독립 실행형 프로그램으로 실행하거나 python -m을 통해 실행할 수 있습니다.```bash
pip-audit --help
python -m pip_audit --help
<!-- @begin-pip-audit-help@ -->```
usage: pip-audit [-h] [-V] [-l] [-r REQUIREMENT] [--locked] [-f FORMAT]
[-s SERVICE] [--osv-url OSV_URL] [-d] [-S]
[--desc [{on,off,auto}]] [--aliases [{on,off,auto}]]
[--cache-dir CACHE_DIR] [--progress-spinner {on,off}]
[--timeout TIMEOUT] [--path PATH] [-v] [--fix]
[--require-hashes] [--index-url INDEX_URL]
[--extra-index-url URL] [--skip-editable] [--no-deps]
[-o FILE] [--ignore-vuln ID] [--disable-pip]
[project_path]
audit the Python environment for dependencies with known vulnerabilities
positional arguments:
project_path audit a local Python project at the given path
(default: None)
options:
-h, --help show this help message and exit
-V, --version show program's version number and exit
-l, --local show only results for dependencies in the local
environment (default: False)
-r REQUIREMENT, --requirement REQUIREMENT
audit the given requirements file; this option can be
used multiple times (default: None)
--locked audit lock files from the local Python project. This
flag only applies to auditing from project paths
(default: False)
-f FORMAT, --format FORMAT
the format to emit audit results in (choices: columns,
json, cyclonedx-json, cyclonedx-xml, markdown)
(default: columns)
-s SERVICE, --vulnerability-service SERVICE
the vulnerability service to audit dependencies
against (choices: osv, pypi, esms) (default: pypi)
--osv-url OSV_URL URL to use for the OSV API instead of the default
(default: https://api.osv.dev/v1/query)
-d, --dry-run without `--fix`: collect all dependencies but do not
perform the auditing step; with `--fix`: perform the
auditing step but do not perform any fixes (default:
False)
-S, --strict fail the entire audit if dependency collection fails
on any dependency (default: False)
--desc [{on,off,auto}]
include a description for each vulnerability; `auto`
defaults to `on` for the `json` format. This flag has
no effect on the `cyclonedx-json` or `cyclonedx-xml`
formats. (default: auto)
--aliases [{on,off,auto}]
includes alias IDs for each vulnerability; `auto`
defaults to `on` for the `json` format. This flag has
no effect on the `cyclonedx-json` or `cyclonedx-xml`
formats. (default: auto)
--cache-dir CACHE_DIR
the directory to use as an HTTP cache for PyPI; uses
the `pip` HTTP cache by default (default: None)
--progress-spinner {on,off}
display a progress spinner (default: on)
--timeout TIMEOUT set the socket timeout (default: 15)
--path PATH restrict to the specified installation path for
auditing packages; this option can be used multiple
times (default: [])
-v, --verbose run with additional debug logging; supply multiple
times to increase verbosity (default: 0)
--fix automatically upgrade dependencies with known
vulnerabilities (default: False)
--require-hashes require a hash to check each requirement against, for
repeatable audits; this option is implied when any
package in a requirements file has a `--hash` option.
(default: False)
--index-url INDEX_URL
base URL of the Python Package Index; this should
point to a repository compliant with PEP 503 (the
simple repository API); this will be resolved by pip
if not specified (default: None)
--extra-index-url URL
extra URLs of package indexes to use in addition to
`--index-url`; should follow the same rules as
`--index-url` (default: [])
--skip-editable don't audit packages that are marked as editable
(default: False)
--no-deps don't perform any dependency resolution; requires all
requirements are pinned to an exact version (default:
False)
-o FILE, --output FILE
output results to the given file (default: stdout)
--ignore-vuln ID ignore a specific vulnerability by its vulnerability
ID; this option can be used multiple times (default:
[])
--disable-pip don't use `pip` for dependency resolution; this can
only be used with hashed requirements files or if the
`--no-deps` flag has been provided (default: False)
pip-audit는 사용자가 일부 플래그를 환경 변수로 대신 구성할 수 있도록 합니다.
완료 시, pip-audit는 상태를 나타내는 코드와 함께 종료됩니다.
현재 코드는 다음과 같습니다.
0: 알려진 취약점이 감지되지 않았습니다.1: 하나 이상의 알려진 취약점이 발견되었습니다.pip-audit의 종료 코드는 억제될 수 없습니다.
지원되는 대안은 Suppressing exit codes from pip-audit를 참조하십시오.
pip-audit는 --dry-run 플래그를 지원하며, 이를 통해 감사(또는 수정) 단계가 실제로 수행되는지 여부를 제어할 수 있습니다.
pip-audit --dry-run은 감사 단계를 건너뛰고 감사되었을 의존성의 수를 출력합니다.pip-audit --fix --dry-run은 감사 단계를 수행하고 수행되었을 수정 동작(예: 업그레이드되거나 건너뛰어질 의존성)을 출력합니다.현재 Python 환경에 대한 의존성 감사:```console $ pip-audit No known vulnerabilities found
주어진 요구사항 파일에 대한 종속성 감사:```console
$ pip-audit -r ./requirements.txt
No known vulnerabilities found
요구사항 파일의 종속성을 감사합니다(시스템 패키지 제외):```console $ pip-audit -r ./requirements.txt -l No known vulnerabilities found
로컬 Python 프로젝트의 종속성 감사:```console
$ pip-audit .
No known vulnerabilities found
로컬 Python 프로젝트의 잠금 파일을 감사합니다:```console $ pip-audit --locked . No known vulnerabilities found
`pip-audit`는 제공된 경로에서 다양한 Python "프로젝트" 파일을 검색합니다.
현재는 `pyproject.toml` 및 `pylock.*.toml`만 지원됩니다.
취약점이 있을 때 종속성을 감사합니다:```console
$ pip-audit
Found 2 known vulnerabilities in 1 package
Name Version ID Fix Versions
---- ------- -------------- ------------
Flask 0.5 PYSEC-2019-179 1.0
Flask 0.5 PYSEC-2018-66 0.12.3
별칭을 포함한 종속성 감사:```console $ pip-audit --aliases Found 2 known vulnerabilities in 1 package Name Version ID Fix Versions Aliases
Flask 0.5 PYSEC-2019-179 1.0 CVE-2019-1010083, GHSA-5wv5-4vpf-pj6m Flask 0.5 PYSEC-2018-66 0.12.3 CVE-2018-1000656, GHSA-562c-5r94-xh97
설명을 포함한 종속성 감사:```console
$ pip-audit --desc
Found 2 known vulnerabilities in 1 package
Name Version ID Fix Versions Description
---- ------- -------------- ------------ --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Flask 0.5 PYSEC-2019-179 1.0 The Pallets Project Flask before 1.0 is affected by: unexpected memory usage. The impact is: denial of service. The attack vector is: crafted encoded JSON data. The fixed version is: 1. NOTE: this may overlap CVE-2018-1000656.
Flask 0.5 PYSEC-2018-66 0.12.3 The Pallets Project flask version Before 0.12.3 contains a CWE-20: Improper Input Validation vulnerability in flask that can result in Large amount of memory usage possibly leading to denial of service. This attack appear to be exploitable via Attacker provides JSON data in incorrect encoding. This vulnerability appears to have been fixed in 0.12.3. NOTE: this may overlap CVE-2019-1010083.
JSON 형식의 종속성 감사:```console $ pip-audit -f json | python -m json.tool Found 2 known vulnerabilities in 1 package [ { "name": "flask", "version": "0.5", "vulns": [ { "id": "PYSEC-2019-179", "fix_versions": [ "1.0" ], "aliases": [ "CVE-2019-1010083", "GHSA-5wv5-4vpf-pj6m" ], "description": "The Pallets Project Flask before 1.0 is affected by: unexpected memory usage. The impact is: denial of service. The attack vector is: crafted encoded JSON data. The fixed version is: 1. NOTE: this may overlap CVE-2018-1000656." }, { "id": "PYSEC-2018-66", "fix_versions": [ "0.12.3" ], "aliases": [ "CVE-2018-1000656", "GHSA-562c-5r94-xh97" ], "description": "The Pallets Project flask version Before 0.12.3 contains a CWE-20: Improper Input Validation vulnerability in flask that can result in Large amount of memory usage possibly leading to denial of service. This attack appear to be exploitable via Attacker provides JSON data in incorrect encoding. This vulnerability appears to have been fixed in 0.12.3. NOTE: this may overlap CVE-2019-1010083." } ] }, { "name": "jinja2", "version": "3.0.2", "vulns": [] }, { "name": "pip", "version": "21.3.1", "vulns": [] }, { "name": "setuptools", "version": "57.4.0", "vulns": [] }, { "name": "werkzeug", "version": "2.0.2", "vulns": [] }, { "name": "markupsafe", "version": "2.0.1", "vulns": [] } ]
취약한 종속성을 감사하고 자동으로 업그레이드 시도:```console
$ pip-audit --fix
Found 2 known vulnerabilities in 1 package and fixed 2 vulnerabilities in 1 package
Name Version ID Fix Versions Applied Fix
----- ------- -------------- ------------ ----------------------------------------
flask 0.5 PYSEC-2019-179 1.0 Successfully upgraded flask (0.5 => 1.0)
flask 0.5 PYSEC-2018-66 0.12.3 Successfully upgraded flask (0.5 => 1.0)
pip-audit로 문제를 해결하셨나요? 이 섹션에 기여해 주세요!
pip-audit가 관련 없는 취약점 보고서를 표시합니다!완벽한 세상에서는 취약점 피드의 신호 대 잡음비가 무한할 것입니다. 모든 취약점 보고서가 (1) 정확하고 (2) 모든 의존성의 모든 사용에 적용 가능할 것입니다.
불행히도, 이 두 가지 모두 보장되지 않습니다. 취약점 피드는 관련 없거나 스팸 보고서로부터 자유롭지 않으며, 특정 의존성의 모든 사용이 모든 잠재적 취약점 클래스에 매핑되지는 않습니다.
만약 pip-audit 실행이 특정 애플리케이션이나 사용 사례에 실행 가능하지 않은 취약점 보고서를 생성하는 경우, --ignore-vuln ID 옵션을 사용하여 특정 취약점 보고서를 무시할 수 있습니다. --ignore-vuln은 별칭을 지원하므로, 해당 보고서에 PYSEC ID가 없는 경우 GHSA-xxx 또는 CVE-xxx ID를 PYSEC-xxx ID 대신 사용할 수 있습니다.
예를 들어, 다음은 pytest 사용자에게 잡음이 많은 취약점 보고서와 오탐(false positive)의 일반적인 원인인 GHSA-w596-4wvx-j9j6을 무시하는 방법입니다.```console
$ pip-audit --ignore-vuln GHSA-w596-4wvx-j9j6
The `--ignore-vuln ID` 옵션은 다른 모든 종속성 해결 및 감사 옵션과 함께 작동하므로, requirements 형식 입력이나 대체 취약점 피드 등에서도 정상적으로 작동합니다.
또한 여러 번 전달하여 여러 보고서를 무시할 수 있습니다:
```bash
pip-audit --ignore-vuln GHSA-... --ignore-vuln PYSEC-...
``````console
# Run the audit as normal, but exclude any reports that match these IDs
$ pip-audit --ignore-vuln CVE-XXX-YYYY --ignore-vuln CVE-ZZZ-AAAA
pip-audit이 예상보다 오래 걸립니다!사용 방법에 따라 pip-audit이 자체 의존성 해석을 수행해야 할 수 있으며, 이는 프로젝트에서 pip install이 걸리는 시간과 거의 비슷할 수 있습니다. 자세한 내용은 보안 모델을 참조하세요.
의존성 해석을 피하는 두 가지 옵션이 있습니다: 사전 설치된 환경을 감사하거나, 의존성이 이미 완전히 해결되었는지 확인하는 것입니다.
이미 pip-audit -r requirements.txt가 감사할 환경과 동등한 환경을 완전히 구성했다면, 간단히 재사용하면 됩니다:```console
$ pip-audit
$ pip-audit --local
또는 입력이 완전히 고정되어 있고 (선택적으로 해싱된 경우) `--no-deps` (해시 없이 고정됨) 또는 `--require-hashes` (해시 포함하여 고정됨) 옵션을 사용하여 `pip-audit`에 종속성 해결을 건너뛰도록 지시할 수 있습니다.
후자는 `pip`의 [해시 검증 모드](https://pip.pypa.io/en/stable/cli/pip_install/#hash-checking-mode)와 동일하며, 추가적인 무결성을 제공하므로 선호됩니다.```console
# fails if any dependency is not fully pinned
$ pip-audit --no-deps -r requirements.txt
# fails if any dependency is not fully pinned *or* is missing hashes
$ pip-audit --require-hashes -r requirements.txt
pip-audit이 제3자 인덱스에 인증할 수 없습니다!pip-audit은 --index-url 및 --extra-index-url을 지원하여 대체 또는 보조 패키지 인덱스를 구성합니다. pip과 마찬가지로.
인증되지 않은 상태에서는 이 인덱스들이 예상대로 작동합니다. 그러나 제3자 인덱스가 인증을 요구하는 경우, pip-audit은 일반적인 pip보다 몇 가지 추가 제한 사항이 있습니다:
대화형 인증은 지원되지 않습니다. 즉, pip-audit은 인덱스에 대한 사용자 이름/비밀번호를 묻지 않습니다.
pip의 keyring 인증은 지원되지만, 제한적으로 지원됩니다. pip-audit은 subprocess 키링 제공자를 사용하는데, 이는 감사가 격리된 가상 환경에서 수행되기 때문입니다. subprocess 제공자 자체는 추가 제한 사항(예: 필수 사용자 이름)을 따르며; pip의 문서에서 이에 대해 자세히 설명합니다.
위 사항에 추가로, 일부 제3자 인덱스에는 필수로 하드코딩된 사용자 이름이 있습니다. 예를 들어, Google Artifact Registry의 경우 하드코딩된 사용자 이름은 oauth2accesstoken입니다. 추가 컨텍스트는 #742 및 pip#11971를 참조하세요.
pipenv 프로젝트에 대해 실행하기pipenv는 requirements.txt 파일 대신 Pipfile 및 Pipfile.lock 파일을 사용하여 종속성을 추적하고 고정합니다. pip-audit은 Pipfile[.lock] 파일을 직접 처리할 수 없지만, 이를 pip-audit이 실행할 수 있는 지원되는 requirements.txt 파일로 변환할 수 있습니다. pipenv에는 종속성을 requirements.txt 파일로 변환하는 내장 명령이 있습니다 (v2022.4.8부터):```console
$ pipenv run pip-audit -r <(pipenv requirements)
### `pip-audit`에서 종료 코드 억제하기
`pip-audit`은 의도적으로 자체 종료 코드를 내부적으로 억제하는 것을 지원하지 않습니다.
실패한 `pip-audit` 호출의 종료 코드를 억제해야 하는 사용자는 표준 셸 관용구 중 하나를 사용할 수 있습니다:```bash
pip-audit || true
또는, 완전히 종료하려면:```bash pip-audit || exit 0
종료 코드를 명시적으로 캡처하고 처리할 수도 있습니다:```bash
pip-audit
exitcode="${?}"
# do something with ${exitcode}
처리해야 할 잠재적인 종료 코드 목록은 종료 코드를 참조하세요.
개발 워크플로우에서는 아직 해결되지 않은 취약점을 무시하고 릴리스 프로세스에서만 조사하고 싶을 수 있습니다. pip-audit는 수정되지 않은 취약점을 무시하는 것을 지원하지 않습니다. 그러나 JSON 형식으로 출력을 내보내고 외부에서 처리할 수 있습니다. 예를 들어, 감지된 취약점에 알려진 수정 버전이 있는 경우에만 0이 아닌 종료 코드로 종료하려면 jq를 사용하여 출력을 다음과 같이 처리할 수 있습니다:```shell
test -z "$(pip-audit -r requirements.txt --format=json 2>/dev/null | jq '.dependencies[].vulns[].fix_versions[]')"
이 방법을 사용하는 간단한 (그리고 비효율적인) 예는 다음과 같습니다:```shell
test -z "$(pip-audit -r requirements.txt --format=json 2>/dev/null | jq '.dependencies[].vulns[].fix_versions[]')" || pip-audit -r requirements.txt
which runs pip-audit as usual and exits with a non-zero code only if there are fixed versions for the known vulnerabilities.
이 섹션은 pip-audit을 사용할 때 할 수 있는 및 해서는 안 되는 보안 가정을 설명하기 위해 존재합니다.
TL;DR: pip install하지 않을 패키지는 pip audit하지 마십시오.
pip-audit은 알려진 취약점이 있는 패키지에 대해 Python 환경을 감사하는 도구입니다. "알려진 취약점"은 공개적으로 보고된 패키지의 결함으로, 수정되지 않으면 악의적인 행위자가 의도하지 않은 작업을 수행할 수 있습니다.
pip-audit은 알려진 취약점이 있을 때 이를 알려주고 업그레이드 방법을 제시하여 보호 할 수 있습니다. 예를 들어, 환경에 somepackage==1.2.3이 있는 경우 pip-audit은 1.2.4로 업그레이드해야 한다고 알려줄 수 있습니다.
pip-audit이 모든 Python 종속성을 완전히 해결하고 각각을 완전히 감사하거나 건너뛴 항목과 그 이유를 명시적으로 알리기 위해 최선을 다할 것이라고 가정할 수 있습니다.
pip-audit은 정적 코드 분석기가 아닙니다. 코드가 아닌 종속성 트리를 분석하며, 임의의 종속성 해결이 정적으로 발생한다고 보장할 수 없습니다. 그 이유를 이해하려면 Dustin Ingram의 Python 종속성 해결에 관한 훌륭한 게시물을 참조하십시오.
따라서: pip-audit이 악성 패키지로부터 방어해 줄 것이라고 가정해서는 안 됩니다. 특히 pip-audit -r INPUT을 pip-audit의 "더 안전한" 변형으로 취급하는 것은 올바르지 않습니다. 사실상 pip-audit -r INPUT은 pip install -r INPUT과 기능적으로 동일하며, 로컬 환경과의 충돌을 피하기 위해 약간의 비보안 격리가 추가된 것입니다.
pip-audit은 무엇보다도 Python 패키지를 위한 감사 도구입니다. pip-audit이 Python 패키지를 통해 노출될 수 있지만 패키지 자체의 일부가 아닌 "전이적" 취약점을 감지하거나 플래그를 지정할 것이라고 가정해서는 안 됩니다. 예를 들어, pip-audit의 취약점 정보 소스에는 인기 있는 Python 패키지가 사용할 수 있는 취약한 공유 라이브러리에 대한 권고가 포함될 가능성이 낮습니다. Python 패키지의 버전이 공유 라이브러리의 버전과 강하게 연결되어 있지 않기 때문입니다.
pip-audit은 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다.
pip-audit은 ISC 라이선스에 따라 라이선스가 부여된 resolvelib의 예제를 재사용 및 수정합니다.
자세한 내용은 기여 문서를 참조하십시오.
이 프로젝트와 상호 작용하는 모든 사람은 PSF 행동 강령을 준수해야 합니다.
| 플래그 | 환경 변수 대체 | 예시 |
|---|
--format | PIP_AUDIT_FORMAT | PIP_AUDIT_FORMAT=markdown |
--vulnerability-service | PIP_AUDIT_VULNERABILITY_SERVICE | PIP_AUDIT_VULNERABILITY_SERVICE=osv |
--desc | PIP_AUDIT_DESC | PIP_AUDIT_DESC=off |
--progress-spinner | PIP_AUDIT_PROGRESS_SPINNER | PIP_AUDIT_PROGRESS_SPINNER=off |
--output | PIP_AUDIT_OUTPUT | PIP_AUDIT_OUTPUT=/tmp/example |