
Uma maneira amigável para empresas de detectar e prevenir segredos em código.
detect-secrets é um módulo com nome apropriado para (surpresa, surpresa) detectar segredos dentro de uma base de código.
No entanto, ao contrário de outros pacotes similares que focam apenas em encontrar segredos, este pacote foi projetado pensando no cliente empresarial: fornecendo um meio , sistemático de:
Dessa forma, você cria uma separação de preocupações: aceitando que pode atualmente haver segredos escondidos em seu grande repositório (isto é o que chamamos de baseline), mas impedindo que esse problema cresça, sem lidar com o esforço potencialmente gigantesco de remover os segredos existentes.
Ele faz isso executando saídas diff periódicas contra declarações regex heuristicamente criadas, para identificar se algum novo segredo foi commitado. Dessa forma, evita a sobrecarga de vasculhar todo o histórico do git, bem como a necessidade de escanear todo o repositório toda vez.
Para uma visão das mudanças recentes, consulte CHANGELOG.md.
Se você deseja contribuir, consulte CONTRIBUTING.md.
Para documentação mais detalhada, confira nossa outra documentação.
Crie uma baseline dos segredos potenciais atualmente encontrados em seu repositório git.```bash $ detect-secrets scan > .secrets.baseline
ou, para executá-lo a partir de um diretório diferente:```bash
$ detect-secrets -C /path/to/directory scan > /path/to/directory/.secrets.baseline
Escaneando arquivos não rastreados pelo git:```bash $ detect-secrets scan test_data/ --all-files > .secrets.baseline
### Adicionando Novos Segredos à Linha de Base:
Isso irá reexaminar sua base de código e:
1. Atualizar/melhorar sua linha de base para ser compatível com a versão mais recente,
2. Adicionar quaisquer novos segredos encontrados à sua linha de base,
3. Remover quaisquer segredos que não estejam mais em sua base de código
Isso também preservará quaisquer segredos rotulados que você tenha.```bash
$ detect-secrets scan --baseline .secrets.baseline
Para baselines mais antigos que a versão 0.9, apenas recrie-a.
Escaneando apenas arquivos em staged:```bash $ git diff --staged --name-only -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline
**Varrendo Todos os Arquivos Rastreados:**```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
### Desativando Plugins:```bash
$ detect-secrets scan --disable-plugin KeywordDetector --disable-plugin AWSKeyDetector
Se você quiser executar apenas um plugin específico, você pode fazer:```bash
$ detect-secrets scan --list-all-plugins |
grep -v 'BasicAuthDetector' |
sed "s#^#--disable-plugin #g" |
xargs detect-secrets scan test_data
### Auditando uma Linha de Base:
Este é um passo opcional para rotular os resultados na sua linha de base. Pode ser usado para reduzir sua lista de verificação de segredos a migrar, ou para configurar melhor seus plugins a fim de melhorar sua relação sinal-ruído.```bash
$ detect-secrets audit .secrets.baseline
Uso Básico:```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))
**Configuração Mais Avançada:**```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 ✨🍰✨
Instale via [brew](https://brew.sh/):```bash
$ brew install detect-secrets
detect-secrets vem com três ferramentas diferentes, e muitas vezes há confusão sobre qual
usar. Use esta útil lista de verificação para ajudá-lo a decidir:
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
### Bloqueando Segredos Fora da Linha de Base```
$ 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
Recomendamos configurar isso como um hook de pre-commit. Uma maneira de fazer isso é usando o pre-commit framework:```yaml
repos:
#### Lista de Permissões Inline
Há momentos em que queremos excluir um falso positivo de bloquear um commit, sem criar
uma linha de base para isso. Você pode fazer isso adicionando um comentário como este:```python
secret = "hunter2" # pragma: allowlist secret
ou```javascript // pragma: allowlist nextline secret const secret = "hunter2";
### Auditoria de Segredos na Linha de Base```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.
Esta ferramenta opera através de um sistema de plugins e filters.
Você pode ajustar ambos para atender às suas necessidades de precisão/revocação.
Existem três estratégias diferentes que empregamos para tentar encontrar segredos no código:
Regras Baseadas em Regex
Essas são o tipo mais comum de plugin e funcionam bem com segredos bem estruturados. Esses segredos podem opcionalmente ser verificados, o que aumenta a precisão da varredura. No entanto, depender exclusivamente deles pode afetar negativamente a revocação da sua varredura.
Detector de Entropia
Isso procura por strings "com aparência de segredo" através de uma variedade de abordagens heurísticas. Isso é ótimo para segredos não estruturados, mas pode exigir ajustes para calibrar a precisão da varredura.
Detector de Palavras-chave
Isso ignora o valor do segredo e procura por nomes de variáveis que são frequentemente associados a atribuir segredos com valores codificados. Isso é ótimo para strings "sem aparência de segredo" (por exemplo, senhas le3tc0de), mas pode exigir ajustes nos filters para calibrar a precisão da varredura.
Quer encontrar um segredo que atualmente não capturamos? Você também pode (facilmente) desenvolver seu próprio plugin e usá-lo com o mecanismo! Para mais informações, consulte a documentação de plugins.
O detect-secrets vem com vários filters integrados diferentes que podem atender às suas necessidades.
Às vezes, você deseja poder permitir globalmente certas linhas em sua varredura, se elas corresponderem a um padrão específico. Você pode especificar uma regra regex da seguinte forma:```bash $ detect-secrets scan --exclude-lines 'password = (blah|fake)'
Ou você pode especificar múltiplas regras regex da seguinte forma:```bash
$ detect-secrets scan --exclude-lines 'password = blah' --exclude-lines 'password = fake'
Às vezes, você pode querer ignorar certos arquivos em sua varredura. Você pode especificar um padrão regex para isso, e se o nome do arquivo corresponder a esse padrão regex, ele não será escaneado:```bash $ detect-secrets scan --exclude-files '.*.signature$'
Ou você pode especificar múltiplos padrões regex da seguinte forma:```bash
$ detect-secrets scan --exclude-files '.*\.signature$' --exclude-files '.*/i18n/.*'
Às vezes, você deseja ignorar certos valores secretos em sua varredura. Você pode especificar uma regra regex como:```bash $ detect-secrets scan --exclude-secrets '(fakesecret|${.*})'
Ou você pode especificar várias regras regex da seguinte forma:```bash
$ detect-secrets scan --exclude-secrets 'fakesecret' --exclude-secrets '\${.*})'
Às vezes, você deseja aplicar uma exclusão a uma linha específica, em vez de excluí-la globalmente. Você pode fazer isso com a permissão em linha da seguinte maneira:```python API_KEY = 'this-will-ordinarily-be-detected-by-a-plugin' # pragma: allowlist secret
Esses comentários são suportados em vários idiomas. p. ex.```java
const GoogleCredentialPassword = "something-secret-here"; // pragma: allowlist secret
Você também pode usar:```python
API_KEY = 'WillAlsoBeIgnored'
Esta pode ser uma maneira conveniente para você ignorar segredos, sem precisar regenerar toda a baseline novamente. Se você precisar pesquisar explicitamente por esses segredos na lista de permissões, você também pode fazer:```bash
$ detect-secrets scan --only-allowlisted
Quer escrever mais lógica personalizada para filtrar falsos positivos? Veja como fazer isso na nossa documentação de filtros.
A flag --exclude-secrets permite que você especifique regras regex para excluir valores secretos. No entanto,
se você quiser especificar uma grande lista de palavras, pode usar a flag --word-list.
Para usar este recurso, certifique-se de instalar o pacote pyahocorasick, ou simplesmente use:```bash
$ pip install detect-secrets[word_list]
Então, você pode usá-lo da seguinte forma:```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
O Gibberish Detector é um modelo de ML simples, que tenta determinar se um valor secreto é realmente absurdo, com a premissa de que valores secretos reais não se assemelham a palavras.
Para usar esta funcionalidade, instale o pacote gibberish-detector, ou use:```bash
$ pip install detect-secrets[gibberish]
Confira o pacote [gibberish-detector](https://github.com/domanchi/gibberish-detector) para mais informações sobre como treinar o modelo. Um modelo pré-treinado (inicializado processando RFCs) será incluído para facilitar o uso.
Você também pode especificar seu próprio modelo da seguinte forma:
``````bash
$ detect-secrets scan --gibberish-model custom.model
Este não é um plugin padrão, visto que ignorará segredos como password.
Este não é uma solução infalível para impedir que segredos entrem na base de código. Apenas uma educação adequada dos desenvolvedores pode realmente fazer isso. Este hook de pré-commit apenas implementa várias heurísticas para tentar prevenir casos óbvios de envio de segredos.
Coisas Que Não Serão Impedidas:
KeywordDetector (ex.: login = "hunter2")Aviso "Não foi detectado repositório git." encontrado, mesmo estando em um repositório git.
Verifique se a versão do seu git é >= 1.8.5. Caso contrário, atualize-a e tente novamente.
Mais detalhes aqui.
detect-secrets audit exibe "Not a valid baseline file!" após criar a baseline.
Certifique-se de que a codificação do arquivo da sua baseline seja UTF-8. Mais detalhes aqui.