
Un modo adatto alle aziende per rilevare e prevenire segreti nel codice.
detect-secrets è un modulo giustamente chiamato per (sorpresa, sorpresa) rilevare segreti all'interno di una base di codice.
Tuttavia, a differenza di altri pacchetti simili che si concentrano esclusivamente sulla ricerca di segreti, questo pacchetto è progettato pensando al cliente enterprise: fornendo un mezzo e sistematico per:
In questo modo, si crea una separazione delle responsabilità: accettando che possano esserci attualmente segreti nascosti nel vostro grande repository (questo è ciò che chiamiamo una baseline), ma impedendo che il problema diventi più grande, senza dover affrontare lo sforzo potenzialmente enorme di spostare i segreti esistenti.
Lo fa eseguendo output diff periodici rispetto a espressioni regex costruite euristicamente, per identificare se è stato commesso un nuovo segreto. In questo modo, evita l'overhead di scavare in tutta la storia di git, così come la necessità di scansionare l'intero repository ogni volta.
Per dare un'occhiata ai cambiamenti recenti, consultare CHANGELOG.md.
Se desideri contribuire, consulta CONTRIBUTING.md.
Per documentazione più dettagliata, dai un'occhiata alla nostra altra documentazione.
Crea una baseline dei potenziali segreti attualmente trovati nel tuo repository git.```bash $ detect-secrets scan > .secrets.baseline
oppure, per eseguirlo da una directory diversa:```bash
$ detect-secrets -C /path/to/directory scan > /path/to/directory/.secrets.baseline
Scansione dei file non tracciati da git:```bash $ detect-secrets scan test_data/ --all-files > .secrets.baseline
### Aggiunta di nuovi segreti alla baseline:
Questo eseguirà una nuova scansione del tuo codebase e:
1. Aggiorna/upgrade la tua baseline per renderla compatibile con l'ultima versione,
2. Aggiunge eventuali nuovi segreti trovati alla tua baseline,
3. Rimuove eventuali segreti non più presenti nel tuo codebase
Questo conserverà anche eventuali segreti etichettati che hai.```bash
$ detect-secrets scan --baseline .secrets.baseline
Per baseline più vecchie della versione 0.9, basta ricrearle.
Scansione solo dei file in staging:```bash $ git diff --staged --name-only -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline
**Scansione di tutti i file tracciati:**```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
### Disabilitazione dei Plugin:```bash
$ detect-secrets scan --disable-plugin KeywordDetector --disable-plugin AWSKeyDetector
Se vuoi solo eseguire un plugin specifico, puoi fare:```bash
$ detect-secrets scan --list-all-plugins |
grep -v 'BasicAuthDetector' |
sed "s#^#--disable-plugin #g" |
xargs detect-secrets scan test_data
### Verifica di una Baseline:
Questo è un passaggio opzionale per etichettare i risultati nella tua baseline. Può essere utilizzato per restringere la tua checklist di segreti da migrare, o per configurare meglio i tuoi plugin al fine di migliorare il rapporto segnale-rumore.```bash
$ detect-secrets audit .secrets.baseline
Uso base:```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))
**Configurazione più avanzata:**```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 ✨🍰✨
Installa tramite [brew](https://brew.sh/):```bash
$ brew install detect-secrets
detect-secrets viene fornito con tre diversi strumenti, e c'è spesso confusione su quale usare. Usa questa pratica checklist per aiutarti a decidere:
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
### Blocco dei segreti non in baseline```
$ 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
Raccomandiamo di impostarlo come hook pre-commit. Un modo per farlo è utilizzare il framework pre-commit:```yaml
repos:
#### Allowlist Inline
Ci sono momenti in cui vogliamo escludere un falso positivo dal bloccare un commit, senza creare una baseline per farlo. Puoi farlo aggiungendo un commento come:```python
secret = "hunter2" # pragma: allowlist secret
o```javascript // pragma: allowlist nextline secret const secret = "hunter2";
### Auditing dei segreti nella 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.
Questo strumento opera attraverso un sistema di plugin e filtri.
Puoi regolare entrambi per adattarli alle tue esigenze di precisione/richiamo.
Utilizziamo tre diverse strategie per cercare di trovare segreti nel codice:
Regole basate su Regex
Queste sono il tipo di plugin più comune e funzionano bene con segreti ben strutturati. Questi segreti possono opzionalmente essere verificati, il che aumenta la precisione della scansione. Tuttavia, dipendere esclusivamente da esse può influenzare negativamente il richiamo della tua scansione.
Rilevatore di Entropia
Cerca stringhe "dall'aspetto segreto" attraverso una varietà di approcci euristici. Questo è ottimo per segreti non strutturati, ma potrebbe richiedere un'ottimizzazione per regolare la precisione della scansione.
Rilevatore di Parole Chiave
Ignora il valore del segreto e cerca nomi di variabili spesso associati all'assegnazione di segreti con valori hard-coded. Questo è ottimo per stringhe "dall'aspetto non segreto" (ad es. password le3tc0de), ma potrebbe richiedere l'ottimizzazione dei filtri per regolare la precisione della scansione.
Vuoi trovare un segreto che attualmente non rileviamo? Puoi anche (facilmente) sviluppare il tuo plugin e usarlo con il motore! Per maggiori informazioni, consulta la documentazione dei plugin.
detect-secrets include diversi filtri integrati che potrebbero soddisfare le tue esigenze.
A volte, si desidera poter permettere globalmente certe righe nella scansione, se corrispondono a un pattern specifico. Puoi specificare una regola regex come segue:```bash $ detect-secrets scan --exclude-lines 'password = (blah|fake)'
Oppure puoi specificare più regole regex in questo modo:```bash
$ detect-secrets scan --exclude-lines 'password = blah' --exclude-lines 'password = fake'
A volte, potresti voler ignorare determinati file durante la scansione. Puoi specificare un pattern regex per farlo, e se il nome del file corrisponde a questo pattern regex, non verrà scansionato:```bash $ detect-secrets scan --exclude-files '.*.signature$'
Oppure puoi specificare più pattern regex in questo modo:```bash
$ detect-secrets scan --exclude-files '.*\.signature$' --exclude-files '.*/i18n/.*'
A volte, potresti voler ignorare determinati valori segreti nella tua scansione. Puoi specificare una regola regex in questo modo:```bash $ detect-secrets scan --exclude-secrets '(fakesecret|${.*})'
Oppure puoi specificare più regole regex come segue:```bash
$ detect-secrets scan --exclude-secrets 'fakesecret' --exclude-secrets '\${.*})'
A volte, si desidera applicare un'esclusione a una riga specifica, piuttosto che escluderla globalmente. È possibile farlo con l'allowlisting inline come segue:```python API_KEY = 'this-will-ordinarily-be-detected-by-a-plugin' # pragma: allowlist secret
Questi commenti sono supportati in più lingue. es.```java
const GoogleCredentialPassword = "something-secret-here"; // pragma: allowlist secret
Puoi anche usare:```python
API_KEY = 'WillAlsoBeIgnored'
Questo può essere un modo conveniente per ignorare i segreti, senza dover rigenerare l'intera
baseline. Se hai bisogno di cercare esplicitamente questi segreti consentiti, puoi anche farlo:```bash
$ detect-secrets scan --only-allowlisted
Vuoi scrivere più logica personalizzata per filtrare i falsi positivi? Scopri come fare nella nostra documentazione sui filtri.
Il flag --exclude-secrets permette di specificare regole regex per escludere valori segreti. Tuttavia,
se invece vuoi specificare una lunga lista di parole, puoi usare il flag --word-list.
Per utilizzare questa funzionalità, assicurati di installare il pacchetto pyahocorasick, o semplicemente usa:```bash
$ pip install detect-secrets[word_list]
Quindi, puoi usarlo in questo modo:```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
Il Gibberish Detector è un semplice modello di ML, che tenta di determinare se un valore segreto è effettivamente senza senso, partendo dal presupposto che i veri valori segreti non assomigliano a parole.
Per utilizzare questa funzionalità, assicurati di installare il pacchetto gibberish-detector, oppure usa:```bash
$ pip install detect-secrets[gibberish]
Dai un'occhiata al pacchetto [gibberish-detector](https://github.com/domanchi/gibberish-detector) per
maggiori informazioni su come addestrare il modello. Un modello pre-addestrato (inizializzato elaborando RFC) sarà
incluso per un uso facile.
Puoi anche specificare il tuo modello in questo modo:```bash
$ detect-secrets scan --gibberish-model custom.model
Questo non è un plugin predefinito, dato che ignorerà segreti come password.
Non è pensato per essere una soluzione infallibile per impedire che i segreti entrino nel codebase. Solo una corretta educazione degli sviluppatori può veramente raggiungere questo obiettivo. Questo hook pre-commit implementa semplicemente diverse euristiche per cercare di prevenire casi evidenti di commit di segreti.
Cose che non verranno impedite:
KeywordDetector (ad es. login = "hunter2")Avviso "Did not detect git repository." incontrato, anche se mi trovo in un repository git.
Controlla se la tua versione di git è >= 1.8.5. In caso contrario, aggiornala e riprova.
Maggiori dettagli qui.
detect-secrets audit mostra "Not a valid baseline file!" dopo aver creato la baseline.
Assicurati che la codifica del file della baseline sia UTF-8. Maggiori dettagli qui.