Skip to content
KitploitKITPLOIT
HerramientasBlog
Enviar
HerramientasBlog
Enviar

¡Herramientas de Hacking, PenTest y Ciberseguridad para tu Arsenal de Seguridad!

Kitploit es un directorio de herramientas de hacking, ciberseguridad y pentesting. Descubre las últimas actualizaciones de proyectos para encontrar vulnerabilidades, analizar sistemas, automatizar pruebas y fortalecer tu seguridad.

··Feeds·Contacto·Privacidad·© 2026 Kitploit

Directorio de Herramientas

Categorías

Ver todas las categorías
Loading categories
detect-secrets — Una forma amigable para empresas de detectar y prevenir secretos en el código. | Kitploit
Herramientas/GitHubGitHub/yelp/detect-secrets
Análisis EstáticoAnálisis de CódigoDevSecOpsDetección de Secretos
GitHubyelp/detect-secrets

detect-secrets

Una forma amigable para empresas de detectar y prevenir secretos en el código.

Ver Repositorio
4.6k564hace 4 mesesRevisado por Kitploit

Más Populares

Ver todos →

Descubre las herramientas más usadas por nuestra comunidad.

Explora todas las herramientas

Explora nuestra colección de herramientas

Ver todas las herramientas →
Compartir

Build Status PyPI version Homebrew PRs Welcome AMF

detect-secrets

Acerca de

detect-secrets es un módulo con un nombre muy adecuado para (sorpresa, sorpresa) detectar secretos dentro de una base de código.

Sin embargo, a diferencia de otros paquetes similares que se centran únicamente en encontrar secretos, este paquete está diseñado pensando en el cliente empresarial: proporcionando una forma sistemática y compatible con versiones anteriores de:

  1. Prevenir que nuevos secretos entren en la base de código,
  2. Detectar si dichas prevenciones son explícitamente eludidas,
  3. Proporcionar una lista de verificación de secretos para rotar y migrar a un almacenamiento más seguro.

De esta manera, se crea una separación de intereses: aceptando que puede haber actualmente secretos ocultos en su gran repositorio (a esto lo llamamos línea base), pero evitando que este problema crezca, sin tener que lidiar con el esfuerzo potencialmente gigantesco de eliminar los secretos existentes.

Lo hace ejecutando salidas de diff periódicas contra declaraciones regex heurísticamente diseñadas, para identificar si se ha comprometido algún secreto nuevo. De esta manera, evita la sobrecarga de excavar en todo el historial de git, así como la necesidad de escanear todo el repositorio cada vez.

Para ver los cambios recientes, consulte CHANGELOG.md.

Si desea contribuir, consulte CONTRIBUTING.md.

Para documentación más detallada, consulte nuestra otra documentación.

Ejemplos

Inicio rápido:

Cree una línea base de posibles secretos encontrados actualmente en su repositorio git.```bash $ detect-secrets scan > .secrets.baseline

root@kitploit:~
o, para ejecutarlo desde un directorio diferente:```bash
$ detect-secrets -C /path/to/directory scan > /path/to/directory/.secrets.baseline

Escaneo de archivos no rastreados por git:```bash $ detect-secrets scan test_data/ --all-files > .secrets.baseline

root@kitploit:~
### Agregar nuevos secretos a la línea base:

Esto volverá a escanear tu base de código, y:

1. Actualizar/mejorar tu línea base para que sea compatible con la última versión,
2. Agregar cualquier nuevo secreto que encuentre a tu línea base,
3. Eliminar cualquier secreto que ya no esté en tu base de código

Esto también preservará cualquier secreto etiquetado que tengas.```bash
$ detect-secrets scan --baseline .secrets.baseline

Para líneas base anteriores a la versión 0.9, simplemente vuelva a crearla.

Alertar sobre secretos recién añadidos:

Escaneando solo archivos staged:```bash $ git diff --staged --name-only -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline

root@kitploit:~
**Escaneando Todos los Archivos Rastreados:**```bash
$ git ls-files -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline

Visualización de Todos los Plugins Habilitados:```bash

$ 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

root@kitploit:~
### Desactivando Plugins:```bash
$ detect-secrets scan --disable-plugin KeywordDetector --disable-plugin AWSKeyDetector

Si quieres ejecutar solo un plugin específico, puedes hacer:```bash $ detect-secrets scan --list-all-plugins |
grep -v 'BasicAuthDetector' |
sed "s#^#--disable-plugin #g" |
xargs detect-secrets scan test_data

root@kitploit:~
### Auditoría de una Línea Base:

Este es un paso opcional para etiquetar los resultados en tu línea base. Se puede usar para reducir tu
lista de secretos a migrar, o para configurar mejor tus complementos y mejorar su relación señal-ruido.```bash
$ detect-secrets audit .secrets.baseline

Uso en otros scripts de Python

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))

root@kitploit:~
**Configuración más avanzada:**```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')

Instalación```bash

$ pip install detect-secrets ✨🍰✨

root@kitploit:~
Instalar mediante [brew](https://brew.sh/):```bash
$ brew install detect-secrets

Uso

detect-secrets viene con tres herramientas diferentes, y a menudo hay confusión sobre cuál usar. Utilice esta práctica lista de verificación para ayudarle a decidir:

  1. ¿Desea agregar secretos a su línea base? Si es así, use detect-secrets scan.
  2. ¿Desea alertar sobre nuevos secretos que no estén en la línea base? Si es así, use detect-secrets-hook.
  3. ¿Está analizando la línea base en sí? Si es así, use detect-secrets audit.

Agregar secretos a la línea base```

$ 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

root@kitploit:~
### Bloqueando Secretos no en la Línea 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 esto como un hook de pre-commit. Una forma de hacerlo es utilizando el pre-commit framework:```yaml

.pre-commit-config.yaml

repos:

  • repo: https://github.com/Yelp/detect-secrets rev: v1.5.0 hooks:
    • id: detect-secrets args: ['--baseline', '.secrets.baseline'] exclude: package.lock.json
root@kitploit:~
#### Lista blanca en línea

Hay ocasiones en las que queremos excluir un falso positivo de bloquear un commit, sin crear
una línea base para hacerlo. Puede hacerlo agregando un comentario de la siguiente manera:```python
secret = "hunter2"      # pragma: allowlist secret

o```javascript // pragma: allowlist nextline secret const secret = "hunter2";

root@kitploit:~
### Auditoría de Secretos en 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.

Configuración

Esta herramienta funciona a través de un sistema de plugins y filtros.

  • Plugins encuentran secretos en el código
  • Filtros ignoran falsos positivos para aumentar la precisión del escaneo

Puedes ajustar ambos para adaptarlos a tus necesidades de precisión/recuperación.

Plugins

Existen tres estrategias diferentes que empleamos para intentar encontrar secretos en el código:

  1. Reglas basadas en expresiones regulares

    Son el tipo de plugin más común y funcionan bien con secretos bien estructurados. Estos secretos pueden ser opcionalmente verificados, lo que aumenta la precisión del escaneo. Sin embargo, depender únicamente de ellos puede afectar negativamente la recuperación de tu escaneo.

  2. Detector de entropía

    Busca cadenas con "apariencia de secreto" mediante diversas aproximaciones heurísticas. Esto es excelente para secretos no estructurados, pero puede requerir ajustes para adaptar la precisión del escaneo.

  3. Detector de palabras clave

    Ignora el valor del secreto y busca nombres de variables que suelen asociarse con la asignación de secretos mediante valores hardcodeados. Esto es excelente para cadenas con "apariencia no secreta" (por ejemplo, contraseñas le3tc0de), pero puede requerir ajustar los filtros para adaptar la precisión del escaneo.

¿Quieres encontrar un secreto que actualmente no detectamos? ¡También puedes desarrollar tu propio plugin (fácilmente) y usarlo con el motor! Para más información, consulta la documentación de plugins.

Filtros

detect-secrets incluye varios filtros integrados que pueden adaptarse a tus necesidades.

--exclude-lines

A veces, deseas poder permitir globalmente ciertas líneas en tu escaneo, si coinciden con un patrón específico. Puedes especificar una regla regex de la siguiente manera:```bash $ detect-secrets scan --exclude-lines 'password = (blah|fake)'

root@kitploit:~
O puedes especificar múltiples reglas regex de la siguiente manera:```bash
$ detect-secrets scan --exclude-lines 'password = blah' --exclude-lines 'password = fake'

--exclude-files

A veces, es posible que desees ignorar ciertos archivos en tu escaneo. Puedes especificar un patrón de expresión regular para hacerlo, y si el nombre del archivo coincide con este patrón de expresión regular, no será escaneado:```bash $ detect-secrets scan --exclude-files '.*.signature$'

root@kitploit:~
O puedes especificar múltiples patrones de regex de la siguiente manera:```bash
$ detect-secrets scan --exclude-files '.*\.signature$' --exclude-files '.*/i18n/.*'

--exclude-secrets

A veces, es posible que quieras ignorar ciertos valores secretos en tu escaneo. Puedes especificar una regla de expresión regular de la siguiente manera:```bash $ detect-secrets scan --exclude-secrets '(fakesecret|${.*})'

root@kitploit:~
O puedes especificar múltiples reglas regex de la siguiente manera:```bash
$ detect-secrets scan --exclude-secrets 'fakesecret' --exclude-secrets '\${.*})'

Lista blanca en línea

A veces, deseas aplicar una exclusión a una línea específica, en lugar de excluirla globalmente. Puedes hacerlo con la lista blanca en línea de la siguiente manera:```python API_KEY = 'this-will-ordinarily-be-detected-by-a-plugin' # pragma: allowlist secret

root@kitploit:~
Estos comentarios son compatibles con múltiples idiomas. p. ej.```java
const GoogleCredentialPassword = "something-secret-here";     //  pragma: allowlist secret

También puedes usar:```python

pragma: allowlist nextline secret

API_KEY = 'WillAlsoBeIgnored'

root@kitploit:~
Esta puede ser una forma conveniente de ignorar secretos, sin necesidad de regenerar toda la línea base nuevamente. Si necesitas buscar explícitamente estos secretos permitidos, también puedes hacerlo:```bash
$ detect-secrets scan --only-allowlisted

¿Quieres escribir más lógica personalizada para filtrar falsos positivos? Consulta cómo hacerlo en nuestra documentación de filtros.

Extensiones

wordlist

La bandera --exclude-secrets te permite especificar reglas regex para excluir valores secretos. Sin embargo, si quieres especificar una gran lista de palabras en su lugar, puedes usar la bandera --word-list.

Para usar esta función, asegúrate de instalar el paquete pyahocorasick, o simplemente usa:```bash $ pip install detect-secrets[word_list]

root@kitploit:~
Entonces, puedes usarlo de la siguiente manera:```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

Detector de Gibberish

El Detector de Gibberish es un modelo de ML simple, que intenta determinar si un valor secreto es realmente gibberish, bajo la suposición de que los valores secretos reales no son similares a palabras.

Para usar esta función, asegúrate de instalar el paquete gibberish-detector, o usa:```bash $ pip install detect-secrets[gibberish]

root@kitploit:~
Echa un vistazo al paquete [gibberish-detector](https://github.com/domanchi/gibberish-detector) para
obtener más información sobre cómo entrenar el modelo. Se incluirá un modelo pre-entrenado (inicializado mediante el procesamiento de RFCs) para facilitar su uso.

También puedes especificar tu propio modelo de la siguiente manera:```bash
$ detect-secrets scan --gibberish-model custom.model

Este no es un plugin predeterminado, ya que ignorará secretos como password.

Advertencias

Esto no pretende ser una solución infalible para evitar que los secretos ingresen al repositorio de código. Solo una educación adecuada de los desarrolladores puede lograrlo realmente. Este hook de pre-commit simplemente implementa varias heurísticas para intentar prevenir casos obvios de compromiso de secretos.

Cosas que no se evitarán:

  • Secretos de varias líneas
  • Contraseñas predeterminadas que no activen el KeywordDetector (por ejemplo, login = "hunter2")

FAQ

General

  • Se encontró la advertencia "Did not detect git repository." a pesar de estar en un repositorio git.

    Verifique si su versión de git es >= 1.8.5. Si no, actualícela e intente nuevamente. Más detalles aquí.

Windows

  • detect-secrets audit muestra "Not a valid baseline file!" después de crear la línea base.

    Asegúrese de que la codificación del archivo de su línea base sea UTF-8. Más detalles aquí.

Descargar herramienta