
기업 친화적인 코드 내 비밀 감지 및 방지 방법.
detect-secrets는 코드 베이스 내에서 (놀랍게도) 비밀(secret)을 탐지하기 위한 적절한 이름의 모듈입니다.
그러나 오직 비밀 찾기에만 초점을 맞춘 다른 유사 패키지와 달리, 이 패키지는 엔터프라이즈 클라이언트를 염두에 두고 설계되었습니다: 이전 버전과 호환되는 체계적인 수단을 제공합니다:
이런 방식으로, 관심사 분리를 만듭니다: 대규모 저장소에 현재 비밀이 숨어 있을 수 있다는 점을 인정하지만(이를 기준선(baseline) 이라고 합니다), 기존 비밀을 이동시키는 엄청난 노력을 들이지 않고 이 문제가 더 커지는 것을 방지합니다.
이는 주기적인 diff 출력을 경험적으로 작성된 정규식과 비교하여 새로운 비밀이 커밋되었는지 식별합니다. 이렇게 하면 모든 git 기록을 뒤질 필요가 없고 매번 전체 저장소를 스캔할 필요도 없습니다.
최근 변경 사항은 CHANGELOG.md를 참조하십시오.
기여하고 싶다면 CONTRIBUTING.md를 참조하십시오.
더 자세한 문서는 다른 문서를 확인하세요.
git 저장소에서 현재 발견된 잠재적 비밀의 기준선을 생성합니다.```bash $ detect-secrets scan > .secrets.baseline
또는, 다른 디렉토리에서 실행하려면:```bash
$ detect-secrets -C /path/to/directory scan > /path/to/directory/.secrets.baseline
git 추적되지 않는 파일 스캔:```bash $ detect-secrets scan test_data/ --all-files > .secrets.baseline
### 베이스라인에 새 비밀 추가:
코드베이스를 다시 스캔하여 다음을 수행합니다:
1. 베이스라인을 최신 버전과 호환되도록 업데이트/업그레이드합니다.
2. 발견된 모든 새 비밀을 베이스라인에 추가합니다.
3. 코드베이스에 더 이상 존재하지 않는 비밀을 제거합니다.
또한 레이블이 지정된 비밀은 유지됩니다.```bash
$ detect-secrets scan --baseline .secrets.baseline
버전 0.9보다 오래된 기준선은 그냥 다시 만드세요.
스테이징된 파일만 스캔:```bash $ git diff --staged --name-only -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline
**모든 추적된 파일 스캔 중:**```bash
$ git ls-files -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline
$ detect-secrets scan --list-all-plugins ArtifactoryDetector AWSKeyDetector AzureStorageKeyDetector BasicAuthDetector CloudantDetector DiscordBotTokenDetector GitHubTokenDetector GitLabTokenDetector Base64HighEntropyString HexHighEntropyString IbmCloudIamDetector IbmCosHmacDetector IPPublicDetector JwtTokenDetector KeywordDetector MailchimpDetector NpmDetector OpenAIDetector PrivateKeyDetector PypiTokenDetector SendGridDetector SlackDetector SoftlayerDetector SquareOAuthDetector StripeDetector TelegramBotTokenDetector TwilioKeyDetector
### 플러그인 비활성화:```bash
$ detect-secrets scan --disable-plugin KeywordDetector --disable-plugin AWSKeyDetector
오직 특정 플러그인을 실행하려면 다음을 수행하면 됩니다:```bash
$ detect-secrets scan --list-all-plugins |
grep -v 'BasicAuthDetector' |
sed "s#^#--disable-plugin #g" |
xargs detect-secrets scan test_data
### 베이스라인 감사:
이는 베이스라인의 결과에 레이블을 지정하는 선택적 단계입니다. 이를 통해 마이그레이션할 시크릿 체크리스트를 좁히거나, 신호 대 잡음비를 개선하기 위해 플러그인을 더 잘 구성하는 데 사용할 수 있습니다.```bash
$ detect-secrets audit .secrets.baseline
기본 사용:```python from detect_secrets import SecretsCollection from detect_secrets.settings import default_settings
secrets = SecretsCollection() with default_settings(): secrets.scan_file('test_data/config.ini')
import json print(json.dumps(secrets.json(), indent=2))
**고급 구성:**```python
from detect_secrets import SecretsCollection
from detect_secrets.settings import transient_settings
secrets = SecretsCollection()
with transient_settings({
# Only run scans with only these plugins.
# This format is the same as the one that is saved in the generated baseline.
'plugins_used': [
# Example of configuring a built-in plugin
{
'name': 'Base64HighEntropyString',
'limit': 5.0,
},
# Example of using a custom plugin
{
'name': 'HippoDetector',
'path': 'file:///Users/aaronloo/Documents/github/detect-secrets/testing/plugins.py',
},
],
# We can also specify whichever additional filters we want.
# This is an example of using the function `is_identified_by_ML_model` within the
# local file `./private-filters/example.py`.
'filters_used': [
{
'path': 'file://private-filters/example.py::is_identified_by_ML_model',
},
]
}) as settings:
# If we want to make any further adjustments to the created settings object (e.g.
# disabling default filters), we can do so as such.
settings.disable_filters(
'detect_secrets.filters.heuristic.is_prefixed_with_dollar_sign',
'detect_secrets.filters.heuristic.is_likely_id_string',
)
secrets.scan_file('test_data/config.ini')
$ pip install detect-secrets ✨🍰✨
[brew](https://brew.sh/)를 통해 설치:```bash
$ brew install detect-secrets
detect-secrets는 세 가지 도구를 제공하며, 어떤 것을 사용해야 할지 혼동이 있는 경우가 많습니다. 다음 편리한 체크리스트를 활용하여 결정하세요:
detect-secrets scan**을 사용하세요.detect-secrets-hook**을 사용하세요.detect-secrets audit**을 사용하세요.$ detect-secrets scan --help usage: detect-secrets scan [-h] [--string [STRING]] [--only-allowlisted] [--all-files] [--baseline FILENAME] [--force-use-all-plugins] [--slim] [--list-all-plugins] [-p PLUGIN] [--base64-limit [BASE64_LIMIT]] [--hex-limit [HEX_LIMIT]] [--disable-plugin DISABLE_PLUGIN] [-n | --only-verified] [--exclude-lines EXCLUDE_LINES] [--exclude-files EXCLUDE_FILES] [--exclude-secrets EXCLUDE_SECRETS] [--word-list WORD_LIST_FILE] [-f FILTER] [--disable-filter DISABLE_FILTER] [path [path ...]]
Scans a repository for secrets in code. The generated output is compatible
with detect-secrets-hook --baseline.
positional arguments: path Scans the entire codebase and outputs a snapshot of currently identified secrets.
optional arguments:
-h, --help show this help message and exit
--string [STRING] Scans an individual string, and displays configured
plugins' verdict.
--only-allowlisted Only scans the lines that are flagged with allowlist secret. This helps verify that individual exceptions
are indeed non-secrets.
scan options:
--all-files Scan all files recursively (as compared to only
scanning git tracked files).
--baseline FILENAME If provided, will update existing baseline by
importing settings from it.
--force-use-all-plugins
If a baseline is provided, detect-secrets will default
to loading the plugins specified by that baseline.
However, this may also mean it doesn't perform the
scan with the latest plugins. If this flag is
provided, it will always use the latest plugins
--slim Slim baselines are created with the intention of
minimizing differences between commits. However, they
are not compatible with the audit functionality, and
slim baselines will need to be remade to be audited.
plugin options: Configure settings for each secret scanning ruleset. By default, all plugins are enabled unless explicitly disabled.
--list-all-plugins Lists all plugins that will be used for the scan. -p PLUGIN, --plugin PLUGIN Specify path to custom secret detector plugin. --base64-limit [BASE64_LIMIT] Sets the entropy limit for high entropy strings. Value must be between 0.0 and 8.0, defaults to 4.5. --hex-limit [HEX_LIMIT] Sets the entropy limit for high entropy strings. Value must be between 0.0 and 8.0, defaults to 3.0. --disable-plugin DISABLE_PLUGIN Plugin class names to disable. e.g. Base64HighEntropyString
filter options: Configure settings for filtering out secrets after they are flagged by the engine.
-n, --no-verify Disables additional verification of secrets via network call. --only-verified Only flags secrets that can be verified. --exclude-lines EXCLUDE_LINES If lines match this regex, it will be ignored. --exclude-files EXCLUDE_FILES If filenames match this regex, it will be ignored. --exclude-secrets EXCLUDE_SECRETS If secrets match this regex, it will be ignored. --word-list WORD_LIST_FILE Text file with a list of words, if a secret contains a word in the list we ignore it. -f FILTER, --filter FILTER Specify path to custom filter. May be a python module path (e.g. detect_secrets.filters.common.is_invalid_file) or a local file path (e.g. file://path/to/file.py::function_name). --disable-filter DISABLE_FILTER Specify filter to disable. e.g. detect_secrets.filters.common.is_invalid_file
### 베이스라인에 없는 시크릿 차단```
$ detect-secrets-hook --help
usage: detect-secrets-hook [-h] [-v] [--version] [--baseline FILENAME]
[--list-all-plugins] [-p PLUGIN]
[--base64-limit [BASE64_LIMIT]]
[--hex-limit [HEX_LIMIT]]
[--disable-plugin DISABLE_PLUGIN]
[-n | --only-verified]
[--exclude-lines EXCLUDE_LINES]
[--exclude-files EXCLUDE_FILES]
[--exclude-secrets EXCLUDE_SECRETS]
[--word-list WORD_LIST_FILE] [-f FILTER]
[--disable-filter DISABLE_FILTER]
[filenames [filenames ...]]
positional arguments:
filenames Filenames to check.
optional arguments:
-h, --help show this help message and exit
-v, --verbose Verbose mode.
--version Display version information.
--json Print detect-secrets-hook output as JSON
--baseline FILENAME Explicitly ignore secrets through a baseline generated
by `detect-secrets scan`
plugin options:
Configure settings for each secret scanning ruleset. By default, all
plugins are enabled unless explicitly disabled.
--list-all-plugins Lists all plugins that will be used for the scan.
-p PLUGIN, --plugin PLUGIN
Specify path to custom secret detector plugin.
--base64-limit [BASE64_LIMIT]
Sets the entropy limit for high entropy strings. Value
must be between 0.0 and 8.0, defaults to 4.5.
--hex-limit [HEX_LIMIT]
Sets the entropy limit for high entropy strings. Value
must be between 0.0 and 8.0, defaults to 3.0.
--disable-plugin DISABLE_PLUGIN
Plugin class names to disable. e.g.
Base64HighEntropyString
filter options:
Configure settings for filtering out secrets after they are flagged by the
engine.
-n, --no-verify Disables additional verification of secrets via
network call.
--only-verified Only flags secrets that can be verified.
--exclude-lines EXCLUDE_LINES
If lines match this regex, it will be ignored.
--exclude-files EXCLUDE_FILES
If filenames match this regex, it will be ignored.
--exclude-secrets EXCLUDE_SECRETS
If secrets match this regex, it will be ignored.
-f FILTER, --filter FILTER
Specify path to custom filter. May be a python module
path (e.g.
detect_secrets.filters.common.is_invalid_file) or a
local file path (e.g.
file://path/to/file.py::function_name).
--disable-filter DISABLE_FILTER
Specify filter to disable. e.g.
detect_secrets.filters.common.is_invalid_file
이것을 pre-commit hook으로 설정하는 것을 권장합니다. 한 가지 방법은 pre-commit 프레임워크를 사용하는 것입니다:```yaml
repos:
#### 인라인 허용 목록
때로는 베이스라인을 생성하지 않고도 거짓 양성을 커밋 차단에서 제외하고 싶은 경우가 있습니다. 다음과 같이 주석을 추가하여 이를 수행할 수 있습니다:```python
secret = "hunter2" # pragma: allowlist secret
또는```javascript // pragma: allowlist nextline secret const secret = "hunter2";
### Baseline 내 비밀 감사```bash
$ detect-secrets audit --help
usage: detect-secrets audit [-h] [--diff] [--stats]
[--report] [--only-real | --only-false]
[--json]
filename [filename ...]
Auditing a baseline allows analysts to label results, and optimize plugins for
the highest signal-to-noise ratio for their environment.
positional arguments:
filename Audit a given baseline file to distinguish the difference
between false and true positives.
optional arguments:
-h, --help show this help message and exit
--diff Allows the comparison of two baseline files, in order to
effectively distinguish the difference between various plugin
configurations.
--stats Displays the results of an interactive auditing session which
have been saved to a baseline file.
--report Displays a report with the secrets detected
reporting:
Display a summary with all the findings and the made decisions. To be used with the report mode (--report).
--only-real Only includes real secrets in the report
--only-false Only includes false positives in the report
analytics:
Quantify the success of your plugins based on the labelled results in your
baseline. To be used with the statistics mode (--stats).
--json Outputs results in a machine-readable format.
이 도구는 플러그인과 필터 시스템을 통해 작동합니다.
정밀도/재현율 요구에 맞게 둘 다 조정할 수 있습니다.
코드에서 비밀을 찾기 위해 세 가지 전략을 사용합니다.
정규식 기반 규칙
이것은 가장 일반적인 플러그인 유형이며, 잘 구조화된 비밀에 잘 작동합니다. 이러한 비밀은 선택적으로 검증할 수 있으며, 이는 스캔 정밀도를 높입니다. 그러나 이에만 의존하면 스캔의 재현율에 부정적인 영향을 미칠 수 있습니다.
엔트로피 탐지기
다양한 휴리스틱 접근 방식을 통해 '비밀처럼 보이는' 문자열을 검색합니다. 이는 비구조화된 비밀에 탁월하지만, 스캔 정밀도를 조정하기 위해 튜닝이 필요할 수 있습니다.
키워드 탐지기
비밀 값을 무시하고, 하드코딩된 값으로 비밀을 할당하는 데 자주 사용되는 변수 이름을 검색합니다. 이는 '비밀로 보이지 않는' 문자열(예: le3tc0de 비밀번호)에 탁월하지만, 스캔 정밀도를 조정하기 위해 필터 튜닝이 필요할 수 있습니다.
현재 잡아내지 못하는 비밀을 찾고 싶으신가요? 자신만의 플러그인을 (쉽게) 개발하여 엔진과 함께 사용할 수도 있습니다! 자세한 내용은 플러그인 문서를 확인하세요.
detect-secrets는 여러 가지 내장 필터를 제공하여 필요에 맞게 사용할 수 있습니다.
때로는 특정 패턴과 일치하는 줄을 스캔에서 전역적으로 허용하고 싶을 수 있습니다. 다음과 같이 정규식 규칙을 지정할 수 있습니다.```bash $ detect-secrets scan --exclude-lines 'password = (blah|fake)'
또는 다음과 같이 여러 정규식 규칙을 지정할 수 있습니다:```bash
$ detect-secrets scan --exclude-lines 'password = blah' --exclude-lines 'password = fake'
때로는 스캔에서 특정 파일을 무시하고 싶을 수 있습니다. 이를 위해 정규식 패턴을 지정할 수 있으며, 파일 이름이 이 정규식 패턴과 일치하면 스캔되지 않습니다:```bash $ detect-secrets scan --exclude-files '.*.signature$'
혹은 여러 개의 정규식 패턴을 다음과 같이 지정할 수 있습니다:```bash
$ detect-secrets scan --exclude-files '.*\.signature$' --exclude-files '.*/i18n/.*'
때로는 스캔에서 특정 비밀 값을 무시하고 싶을 수 있습니다. 다음과 같이 regex 규칙을 지정할 수 있습니다:```bash $ detect-secrets scan --exclude-secrets '(fakesecret|${.*})'
또는 여러 정규식 규칙을 다음과 같이 지정할 수 있습니다:```bash
$ detect-secrets scan --exclude-secrets 'fakesecret' --exclude-secrets '\${.*})'
때로는 전체적으로 제외하지 않고 특정 줄에만 예외를 적용하고 싶을 수 있습니다. 이를 인라인 허용 목록을 사용하여 다음과 같이 할 수 있습니다:```python API_KEY = 'this-will-ordinarily-be-detected-by-a-plugin' # pragma: allowlist secret
이 주석들은 여러 언어로 지원됩니다. 예:```java
const GoogleCredentialPassword = "something-secret-here"; // pragma: allowlist secret
다음도 사용할 수 있습니다:```python
API_KEY = 'WillAlsoBeIgnored'
이는 전체 기준선을 다시 생성할 필요 없이 비밀을 무시하는 편리한 방법일 수 있습니다. 이러한 허용 목록에 등록된 비밀을 명시적으로 검색해야 하는 경우 다음을 수행할 수도 있습니다:```bash
$ detect-secrets scan --only-allowlisted
필터링 로직을 직접 작성하여 가양성을 더 많이 걸러내고 싶으신가요?
필터 문서에서 방법을 확인하세요.
--exclude-secrets 플래그를 사용하면 비밀 값을 제외할 정규식 규칙을 지정할 수 있습니다. 그러나 대신 큰 단어 목록을 지정하려면 --word-list 플래그를 사용할 수 있습니다.
이 기능을 사용하려면 pyahocorasick 패키지를 설치했는지 확인하거나, 간단히 다음을 사용하세요:```bash
$ pip install detect-secrets[word_list]
그런 다음, 다음과 같이 사용할 수 있습니다:```bash
$ cat wordlist.txt
not-a-real-secret
$ cat sample.ini
password = not-a-real-secret
# Will show results
$ detect-secrets scan sample.ini
# No results found
$ detect-secrets scan --word-list wordlist.txt
Gibberish Detector는 간단한 ML 모델로, 비밀 값이 실제로 무의미한 문자열인지 판단하려고 시도합니다. 실제 비밀 값은 단어와 유사하지 않다는 가정에 기반합니다.
이 기능을 사용하려면 gibberish-detector 패키지를 설치했는지 확인하거나, 다음을 사용하세요:```bash
$ pip install detect-secrets[gibberish]
Check out the [gibberish-detector](https://github.com/domanchi/gibberish-detector) 패키지를 확인하세요.
모델 훈련 방법에 대한 자세한 내용은 해당 패키지를 참조하십시오. 쉬운 사용을 위해 사전 훈련된 모델(RFC 처리로 시드됨)이 포함됩니다.
자체 모델을 다음과 같이 지정할 수도 있습니다:```bash
$ detect-secrets scan --gibberish-model custom.model
이것은 기본 플러그인이 아닙니다. 이는 password와 같은 비밀을 무시할 것이기 때문입니다.
이것은 비밀이 코드베이스에 들어가는 것을 방지하는 확실한 해결책으로 의도된 것이 아닙니다. 오직 적절한 개발자 교육만이 진정으로 그렇게 할 수 있습니다. 이 pre-commit 훅은 단지 비밀 커밋의 명백한 경우를 방지하기 위해 몇 가지 휴리스틱을 구현한 것입니다.
방지되지 않는 것들:
KeywordDetector를 트리거하지 않는 기본 비밀번호 (예: login = "hunter2")"Did not detect git repository." warning encountered, even though I'm in a git repo.
git 버전이 1.8.5 이상인지 확인하세요. 그렇지 않다면 업그레이드한 후 다시 시도하세요.
자세한 내용은 여기를 참조하세요.
detect-secrets audit displays "Not a valid baseline file!" after creating baseline.
기준 파일의 파일 인코딩이 UTF-8인지 확인하세요. 자세한 내용은 여기를 참조하세요.