Skillfade Logo

Passwords and Secrets, and Where To Find Them

⏳ 8 min read

Table of Contents

    Cybersecurity Illustration

    The neon rain lashes the windows, the city humming in electric tones beneath a sky full of drifted clouds. You jacked into the terminal, lines of code, glowing data streams, secrets waiting to be unearthed. Somewhere in this labyrinth of silicon and light, passwords brush past you like ghosts. You reach for them, sweaty palms on cold steel, chasing their phantom trails through layers of encryption, obfuscation, misdirection. Welcome to the edge of cyber-space.

    In the depths of server racks, in the folds of config files, in the breath between bytes, secrets live, tokens, keys, credentials. Some forged by humans, some generated by machines, all vulnerable. Newcomers stepping onto this stage should see not merely the code, but the danger, with each file, each variable, each assumed “secure” vault, there lies a chasm waiting to consume carelessness, vanity or wishful thinking.


    Why Passwords and Secrets are Everywhere

    Every system, every service, every device demands some kind of credential or secret. Web apps talk to databases, those connections need user names, passwords. APIs demand keys. Containers are configured to load secrets. Environments store variables. Cloud services offer credential stores, yet we often see insecure practices: secrets hard-coded in source code, exposed in public repos, shared in messages, left in logs.

    Attackers don’t need sophistication when you hand them the keys. A simple leakage, a git push with an API key, can let a stranger blast your infrastructure apart, manipulate data, spin up computational engines, incur crippling bills. The stakes are high.


    Where Secrets Hide: The Dark Corners in Plain Sight

    Here are some typical places where secrets end up, sometimes because of oversight, sometimes because systems grew messy.

    • Source code
      Hard-coded credentials, API keys, database URIs in code files. Especially in languages that handle strings plainly, Python, JavaScript, Java.

    • Configuration files
      .env files, .conf, config.json, settings.yml. These may contain secrets with lax file permissions, sometimes pushed to version control accidentally.

    • Environment variables
      Docker containers, CI/CD pipelines, deployment scripts often store secrets in environment variables. Misconfiguration may expose them to untrusted users.

    • Secret-management tools
      Tools like Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager. Proper use helps centralise management, but misconfigured policies or access rights defeat the purpose.

    • Cloud metadata services
      In cloud platforms a local metadata service may expose IAM roles or instance credentials. If an attacker accesses it (via SSRF for example), secrets leak.

    • Logs, backup files, snapshots
      Debug logs may record sensitive information. Old backups may include secrets no longer used, yet still valid. Snapshots may persist until destroyed.

    • Third-party libraries, plugins, dependencies
      Some include sample secrets or fallback credentials. Attack surfaces if dependencies bring in secrets by default or mistakenly.


    Actionable Strategies to Discover Secrets: Defensive and Offensive Views

    You should know both sides, how attackers find secrets, so you can protect yours.

    1. Scanning code for secrets

    Use automated tools to scan your codebase:

    bash
    # Requires git-rob, truffleHog or git-secrets
    git-secrets --scan
    trufflehog --regex --entropy true https://your.git.repo.url
    

    Warning: Scanning public repos is fine, scanning private data must abide by policies and legal boundaries.

    2. Grep through configuration

    bash
    grep -R --colour=always -E "(password|secret|token|apikey)" /path/to/project
    

    This reveals occurrences of words commonly used for credentials. False positives abound, but it’s a starting point.

    3. Checking environment variables

    In Bash:

    bash
    printenv | grep -E "(SECRET|TOKEN|KEY)"
    

    In PowerShell:

    powershell
    Get-ChildItem Env: | Where-Object { $_.Name -match "SECRET|TOKEN|KEY" }
    

    If variables include secrets in plaintext, that’s a red flag.

    4. Inspecting cloud metadata services (defensive awareness)

    Attackers may try SSRF to access e.g. http://169.254.169.254/ on AWS or Azure. Defend by disabling metadata access when not needed, using IAM roles with minimal privileges.

    5. Reviewing logs and backups

    Parse log files:

    bash
    grep -R -E "(password|passwd|token|key)" /var/log/*.log
    

    Archive files and snapshots should be audited, purged when obsolete.


    Securing Secrets: Best Practices for Cyber-Hygiene

    Knowing where secrets hide is only half the battle. Here’s what to do to protect them.

    • Use dedicated secrets managers. Let them handle rotation, access control, audits.

    • Encrypt secrets at rest, and ensure transport channels are secure (TLS). At rest: use vault encryption, cloud KMS services.

    • Adopt least privilege: limit who, and what, can access a secret. Don’t let entire development teams access production keys unless strictly necessary.

    • Use ephemeral credentials. If possible use short lived tokens, auto-rotated keys. Avoid eternal secrets.

    • Never commit secrets to version control. Use .gitignore for config files, use template files with placeholders.

    • Monitor for exposures. Use tools that scan public repos (e.g. GitHub secret scanning), alerts on abnormal access.

    • Rotate secrets regularly. Even if no breach, periodic change reduces the window of opportunity for attackers.


    A Practical Demo: Python Script Using Environment Variables Securely

    Here’s how you might load secrets safely in a Python application.

    python
    import os
    
    def get_database_credentials():
        db_user = os.getenv("DB_USER")
        db_password = os.getenv("DB_PASSWORD")
        if not db_user or not db_password:
            raise ValueError("Database credentials not found in environment")
        return db_user, db_password
    
    def connect():
        user, password = get_database_credentials()
        # Example: connecting securely using a library
        # Ensure that connection uses TLS, minimal privileges
        import psycopg2
        conn = psycopg2.connect(
            dbname="mydb",
            user=user,
            password=password,
            host="db.example.com",
            sslmode="require"
        )
        return conn
    

    Warning: Avoid printing secrets or logging them. In production do not expose stack traces that reveal secrets or configuration.


    Discovering Passwords and Secrets in Systems: A Hands-on Guide

    Aim

    To equip you with practical methods for locating, analysing and securing passwords and secrets in files, applications, environment variables and configuration settings.

    Learning outcomes

    By following this guide you will be able to:
    - Identify common locations where passwords and secrets are stored in projects or systems;
    - Use command-line tools to search for secrets in code or configuration files;
    - Extract secrets from environment variables and process memory;
    - Securely handle found secrets to reduce exposure risk.

    Prerequisites

    • A Unix-based system or Windows with PowerShell;
    • Basic familiarity with shell commands, Python or PowerShell scripts;
    • Access permissions to view relevant configuration files or process information;
    • A safe testing environment (e.g. virtual machine, container) so you do not expose real credentials.

    Step-by-step instructional guide

    1. Search configuration files and code repositories

    • Use grep (on Unix) or Select-String (on Windows) to find common secret-keywords such as password, secret, token, key.

    Example Bash command:

    bash
    grep ‐RInE "(password|secret|token|apikey)" /path/to/project
    

    Example PowerShell command:

    powershell
    Get-ChildItem ‐Recurse ‐Filter *.config,*.json,*.yaml |
      Select-String ‐Pattern "password","secret","token","apikey" |
      Format-List Path,LineNumber,Line
    
    • Check *.env files, appsettings.json, .ini, .yaml for clear-text secrets.

    2. Inspect environment variables

    • In Bash:
    bash
    printenv | grep ‐E "PASSWORD|SECRET|TOKEN|KEY"
    
    • In PowerShell:
    powershell
    Get-ChildItem Env: | Where-Object { $_.Name ‐match "PASSWORD|SECRET|TOKEN|KEY" }
    
    • Within Python scripts you may load values from os.environ:
    python
    import os
    
    for key in os.environ:
        if any(substr in key.upper() for substr in ("PASSWORD","SECRET","TOKEN","KEY")):
            print(f"{key}={os.environ[key]}")
    

    3. Search running processes and memory (where permitted)

    • Use ps aux or ps ‐ef (Unix) to list processes; examine arguments that contain secret-like parameters.

    Example Bash:

    bash
    ps aux | grep ‐E "(--password|, secret|--token)"
    
    • On Windows use PowerShell:
    powershell
    Get-Process | ForEach‐Object {
      $args = $_.StartInfo.Arguments
      if ($args ‐match "password|secret|token") {
        Write-Output "$($_.ProcessName): $args"
      }
    }
    
    • Use tools like strings against binary files or process memory dumps (only when you have authorisation) to find embedded secrets.

    4. Scan version control history

    • Secrets may have been committed and removed but still exist in history. Use tools such as git log ‐-all ‐-grep:
    bash
    git log ‐-all ‐-grep ‐E "(password|secret|token)" ‐-pretty="%h %s"
    
    • Use specialised tools like git-secrets or truffleHog to automate scanning repositories for high entropy strings or secret patterns.

    5. Mitigate risks once secrets found

    • Immediately rotate any found credentials.
    • Move secrets out of source code or configuration files into secure stores (e.g. HashiCorp Vault, AWS Secrets Manager).
    • Ensure environment variables are loaded from secure files with correct permission settings.
    • Remove hard-coded secrets and use parameterisation.

    Key actionable insights

    • Always search both current files and historical commits. Secrets often persist in history.
    • Use pattern matching carefully to reduce false positives; refining your regex helps.
    • Automate scanning in CI/CD pipelines to catch secrets before merge.
    • Proper file permissions (for .env, config files) are as important as detection.
    • Adopt secret-management tooling for safer usage in production.

    This guide gives you hands-on techniques for finding passwords and secrets in typical codebases or system environments and securing them properly.

    You stand at the threshold now, neon lights reflecting on hardened screens, knowing where the shadows lie, how to peer into corners safely, how to defend your own secrets. Keep vigilance, keep tools sharp, because in this cyber punk frontier, secrets are the currency, passwords are the keys, and knowledge, your best protection.