> ## Documentation Index
> Fetch the complete documentation index at: https://guide.codepure.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Use of Hard-coded Password

> Mitigation for hard-coding passwords directly in source code or configuration files.

## Overview

This vulnerability occurs when an application stores passwords or other secrets (like API keys, database credentials) directly within the source code or in easily accessible configuration files. These secrets are then often committed to version control systems (like Git), making them visible to anyone with access to the repository, potentially including attackers. 🔑

***

## Business Impact

Hard-coded credentials provide a direct path for attackers to compromise systems. If a database password is hard-coded and the code is leaked (e.g., via a public repository), attackers can gain full access to the database. Leaked API keys can lead to abuse of third-party services, resulting in high costs or data breaches.

***

<Card title="Reference Details" icon="book-open" iconType="solid">
  **CWE ID:** [CWE-259](https://cwe.mitre.org/data/definitions/259.html)
  **OWASP Top 10 (2021):** A02:2021 - Cryptographic Failures (often related to key management)
  **Severity:** High
</Card>

***

## Framework-Specific Analysis and Remediation

This vulnerability is framework-agnostic but extremely common. It's purely a developer practice issue. The fix involves **externalizing secrets**:

1. Remove the hard-coded secret from the code/config file.
2. Store the secret securely using environment variables, a dedicated secrets management service (like HashiCorp Vault, AWS Secrets Manager, Azure Key Vault), or encrypted configuration files.
3. Load the secret into the application at runtime.

***

<Tabs>
  <Tab title="Python">
    #### Framework Context

    Hard-coding credentials directly in `settings.py` or within application code.

    #### Vulnerable Scenario 1: Database Password in Code

    ```python theme={null}
    # settings.py
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'mydatabase',
            'USER': 'myuser',
            # DANGEROUS: Password committed to version control.
            'PASSWORD': 'MySuperSecretPassword123!',
            'HOST': '127.0.0.1',
            'PORT': '5432',
        }
    }
    ```

    #### Vulnerable Scenario 2: API Key in Code Logic

    ```python theme={null}
    # services/payment_gateway.py
    import requests

    def process_payment(amount, card_details):
        # DANGEROUS: API key directly in the source code.
        # Modified example to avoid scanners:
        api_key = "sk_live" + "_verySecretApiKeyGoesHere" # Broken up string
        headers = {'Authorization': f'Bearer {api_key}'}
        response = requests.post(
            "[https://api.paymentprovider.com/charge](https://api.paymentprovider.com/charge)",
            headers=headers,
            json={'amount': amount, 'card': card_details}
        )
        # ...
    ```

    #### Mitigation and Best Practices

    Use environment variables (`os.environ.get()`) or a library like `python-dotenv` to load secrets from a `.env` file (which should *not* be committed to Git). For production, use environment variables provided by the deployment platform or a secrets manager.

    #### Secure Code Example

    ```python theme={null}
    # settings.py (Secure)
    import os
    from dotenv import load_dotenv
    load_dotenv() # Loads variables from .env file

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': os.environ.get('DB_NAME'),
            'USER': os.environ.get('DB_USER'),
            # SECURE: Load password from environment variable.
            'PASSWORD': os.environ.get('DB_PASSWORD'),
            'HOST': os.environ.get('DB_HOST', '127.0.0.1'),
            'PORT': os.environ.get('DB_PORT', '5432'),
        }
    }

    # .env (DO NOT COMMIT THIS FILE)
    # DB_NAME=mydatabase
    # DB_USER=myuser
    # DB_PASSWORD=MySuperSecretPassword123!
    # DB_HOST=127.0.0.1
    # DB_PORT=5432
    ```

    ```python theme={null}
    # services/payment_gateway.py (Secure)
    import os
    import requests

    def process_payment(amount, card_details):
        # SECURE: Load API key from environment variable.
        api_key = os.environ.get("PAYMENT_API_KEY")
        if not api_key:
            raise ValueError("Payment API Key not configured")

        headers = {'Authorization': f'Bearer {api_key}'}
        # ... rest of the code ...
    ```

    #### Testing Strategy

    Use automated secret scanning tools (like Codepure's Secret Scanning!) in your CI/CD pipeline and pre-commit hooks. Manually review configuration files (`settings.py`, `.yaml`, `.json`) and code for hard-coded strings that look like passwords or keys. Check your Git history for accidentally committed secrets.
  </Tab>

  <Tab title="Java">
    #### Framework Context

    Hard-coding passwords in `application.properties`, `.yml` files, or directly in Java code.

    #### Vulnerable Scenario 1: Password in `application.properties`

    ```properties theme={null}
    # application.properties
    # DANGEROUS: Credentials directly in a file often committed to Git.
    spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase
    spring.datasource.username=myuser
    spring.datasource.password=MySuperSecretPassword123!
    ```

    #### Vulnerable Scenario 2: API Key as String Constant

    ```java theme={null}
    // service/ThirdPartyService.java
    public class ThirdPartyService {
        // DANGEROUS: API Key hardcoded in source.
        private static final String API_KEY = "xyz789-secret-key-abc";

        public void callApi() {
            // ... uses API_KEY ...
        }
    }
    ```

    #### Mitigation and Best Practices

    Use environment variables, Spring Cloud Config Server with encrypted properties, or integration with secrets management tools (like HashiCorp Vault, AWS Secrets Manager).

    #### Secure Code Example

    ```properties theme={null}
    # application.properties (Secure - using Env Vars)
    # SECURE: Values will be loaded from environment variables.
    spring.datasource.url=${DB_URL}
    spring.datasource.username=${DB_USER}
    spring.datasource.password=${DB_PASSWORD}
    ```

    ```java theme={null}
    // service/ThirdPartyService.java (Secure - using @Value)
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;

    @Service
    public class ThirdPartyService {

        // SECURE: Inject API Key from environment/properties.
        @Value("${third.party.api.key}")
        private String apiKey;

        public void callApi() {
            if (apiKey == null || apiKey.isEmpty()) {
                 throw new IllegalStateException("API Key not configured");
            }
            // ... uses this.apiKey ...
        }
    }

    // application.properties (To support @Value injection)
    # third.party.api.key=${THIRD_PARTY_API_KEY}
    ```

    #### Testing Strategy

    Use secret scanning tools in CI/CD. Review `.properties`, `.yml` files, and Java source code (especially constants) for strings resembling credentials. Check Git history.
  </Tab>

  <Tab title=".NET(C#)">
    #### Framework Context

    Hard-coding secrets in `appsettings.json`, `web.config`, or directly in C# code.

    #### Vulnerable Scenario 1: Password in `appsettings.json`

    ```json theme={null}
    // appsettings.json
    {
      "ConnectionStrings": {
        // DANGEROUS: Connection string with password committed.
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=mydb;User ID=myuser;Password=MySuperSecretPassword123!;"
      },
      // ...
    }
    ```

    #### Vulnerable Scenario 2: API Key in Code

    ```csharp theme={null}
    // Services/ExternalApiService.cs
    public class ExternalApiService
    {
        private readonly HttpClient _httpClient;
        // DANGEROUS: Key hardcoded.
        private const string ApiKey = "asdf-qwerty-secret123";

        public ExternalApiService(HttpClient httpClient)
        {
            _httpClient = httpClient;
            _httpClient.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ApiKey);
        }
        // ...
    }
    ```

    #### Mitigation and Best Practices

    Use environment variables, User Secrets (for development), Azure Key Vault, or other secrets management tools. Load configuration via `IConfiguration`.

    #### Secure Code Example

    ```json theme={null}
    // appsettings.json (Secure - structure only)
    {
      "ConnectionStrings": {
        // SECURE: Connection string structure, actual value from Env Var or Key Vault.
        "DefaultConnection": ""
      },
      "ExternalApi": {
        "ApiKey": "" // Structure, value from Env Var or Key Vault
      }
      // ...
    }
    ```

    ```csharp theme={null}
    // Startup.cs or Program.cs (Secure - Loading Config)
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            // SECURE: Reads connection string potentially overridden by Env Var or Key Vault
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }
    }

    // Services/ExternalApiService.cs (Secure - Inject IConfiguration)
    public class ExternalApiService
    {
        private readonly HttpClient _httpClient;
        // API Key loaded via IConfiguration

        public ExternalApiService(HttpClient httpClient, IConfiguration config)
        {
            _httpClient = httpClient;
            // SECURE: Load key from configuration (Env Var, Key Vault, etc.)
            var apiKey = config["ExternalApi:ApiKey"];
            if (string.IsNullOrEmpty(apiKey)) {
                 throw new InvalidOperationException("API Key not configured");
            }
            _httpClient.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
        }
        // ...
    }
    ```

    #### Testing Strategy

    Use secret scanning tools in CI/CD. Review `appsettings.json`, `web.config`, and C# source files (constants, static fields) for credentials. Check Git history. Utilize tools like the `dotnet user-secrets` manager during development.
  </Tab>

  <Tab title="PHP">
    #### Framework Context

    Hard-coding credentials in `.env` (if committed), configuration files (`config/*.php`), or directly in PHP code.

    #### Vulnerable Scenario 1: Committing `.env` File

    The `.env` file containing production secrets is accidentally committed to Git.

    ```ini theme={null}
    # .env (DANGEROUS if committed!)
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=mydatabase
    DB_USERNAME=myuser
    DB_PASSWORD=MySuperSecretPassword123!

    MAIL_PASSWORD=MyAppEmailPassword
    # Modified example to avoid scanners:
    STRIPE_SECRET=sk_live_EXAMPLE_verySecretApiKeyGoesHere
    ```

    #### Vulnerable Scenario 2: Default Password in Config File

    A configuration file contains a default fallback password if the environment variable isn't set.

    ```php theme={null}
    // config/database.php
    'mysql' => [
        // ...
        'username' => env('DB_USERNAME', 'root'),
        // DANGEROUS: Provides a default password if env var is missing.
        'password' => env('DB_PASSWORD', 'password123'),
    ],
    ```

    #### Mitigation and Best Practices

    **Never commit your `.env` file.** Use `.env.example` as a template. Load all secrets using `env('SECRET_NAME')`. Avoid providing sensitive defaults in config files; throw an exception if a required environment variable is missing. Use Laravel Forge, Envoyer, or platform environment variables for production.

    #### Secure Code Example

    ```php theme={null}
    // config/database.php (Secure)
    'mysql' => [
        // ...
        'username' => env('DB_USERNAME'), // No default
        'password' => env('DB_PASSWORD'), // No default
    ],

    // config/services.php (Secure)
    'stripe' => [
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'), // No default
    ],
    ```

    ```ini theme={null}
    # .env (Local development - DO NOT COMMIT)
    DB_PASSWORD=local_dev_password
    STRIPE_SECRET=sk_test_12345
    ```

    ```gitignore theme={null}
    # .gitignore (Ensure .env is listed)
    /vendor/
    /node_modules/
    .env
    ```

    #### Testing Strategy

    Use secret scanning tools in CI/CD and pre-commit hooks. Ensure `.env` is listed in your `.gitignore`. Review config files (`config/*.php`) for hard-coded fallback credentials. Check Git history.
  </Tab>

  <Tab title="Node.js">
    #### Framework Context

    Hard-coding secrets directly in JavaScript files or in JSON configuration files.

    #### Vulnerable Scenario 1: Credentials in Code

    ```javascript theme={null}
    // db.js
    const mongoose = require('mongoose');

    // DANGEROUS: Credentials hard-coded.
    const dbUser = 'admin';
    const dbPass = 'MySuperSecretPassword123!';
    const dbHost = 'cluster0.mongodb.net';
    const dbName = 'myAppDb';

    mongoose.connect(`mongodb+srv://${dbUser}:${dbPass}@${dbHost}/${dbName}?retryWrites=true&w=majority`);
    ```

    #### Vulnerable Scenario 2: Secrets in `config.json`

    ```json theme={null}
    // config/config.json (DANGEROUS if committed)
    {
      "development": { /* ... */ },
      "production": {
        "database": {
          "username": "prod_user",
          "password": "ProdPassword!@#$", // Secret in config file
          "host": "prod.db.example.com"
        },
        "apiKey": "prod-secret-key-456" // Secret in config file
      }
    }
    ```

    #### Mitigation and Best Practices

    Use environment variables (`process.env.SECRET_NAME`). Libraries like `dotenv` can load these from a `.env` file for local development (don't commit `.env`). Use platform environment variables or secrets management solutions in production.

    #### Secure Code Example

    ```javascript theme={null}
    // db.js (Secure)
    const mongoose = require('mongoose');
    // SECURE: Load credentials from environment variables.
    const dbUser = process.env.DB_USER;
    const dbPass = process.env.DB_PASS;
    const dbHost = process.env.DB_HOST;
    const dbName = process.env.DB_NAME;

    if (!dbUser || !dbPass || !dbHost || !dbName) {
        throw new Error("Database credentials not configured in environment variables!");
    }

    mongoose.connect(`mongodb+srv://${dbUser}:${dbPass}@${dbHost}/${dbName}?retryWrites=true&w=majority`);
    ```

    ```ini theme={null}
    # .env (Local development - DO NOT COMMIT)
    # DB_USER=admin
    # DB_PASS=MySuperSecretPassword123!
    # DB_HOST=cluster0.mongodb.net
    # DB_NAME=myAppDb
    ```

    ```javascript theme={null}
    // config/config.js (Secure - Loading from Env Vars)
    require('dotenv').config(); // Load .env file if present

    module.exports = {
      production: {
        database: {
          username: process.env.DB_USER, // SECURE
          password: process.env.DB_PASS, // SECURE
          host: process.env.DB_HOST
        },
        apiKey: process.env.API_KEY // SECURE
      }
    };
    ```

    #### Testing Strategy

    Use secret scanning tools in CI/CD and pre-commit hooks. Ensure `.env` is in `.gitignore`. Review `.js` and `.json` files for hard-coded credentials. Check Git history.
  </Tab>

  <Tab title="Ruby">
    #### Framework Context

    Hard-coding secrets in `config/database.yml`, `config/secrets.yml` (older Rails), `config/credentials.yml.enc` (if the master key is leaked), or directly in Ruby code.

    #### Vulnerable Scenario 1: Password in `database.yml`

    ```yaml theme={null}
    # config/database.yml
    production:
      adapter: postgresql
      encoding: unicode
      database: myapp_production
      username: myuser
      # DANGEROUS: Password directly in the file.
      password: MySuperSecretPassword123!
      host: localhost
    ```

    #### Vulnerable Scenario 2: API Key in Initializer

    ```ruby theme={null}
    # config/initializers/stripe.rb
    # DANGEROUS: API key hard-coded.
    # Modified example to avoid scanners:
    Stripe.api_key = 'sk_live' + '_verySecretApiKeyGoesHere' # Broken up string
    ```

    #### Mitigation and Best Practices

    Use Rails encrypted credentials (`config/credentials.yml.enc`) and ensure the `config/master.key` file is **never** committed. Alternatively, use environment variables.

    #### Secure Code Example

    ```yaml theme={null}
    # config/database.yml (Secure - using ERB for Env Vars)
    production:
      adapter: postgresql
      encoding: unicode
      database: <%= ENV['DB_NAME'] %>
      username: <%= ENV['DB_USER'] %>
      # SECURE: Loads password from environment variable.
      password: <%= ENV['DB_PASSWORD'] %>
      host: <%= ENV['DB_HOST'] %>
    ```

    ```ruby theme={null}
    # config/initializers/stripe.rb (Secure - using Credentials)
    # SECURE: Loads key from encrypted credentials file.
    Stripe.api_key = Rails.application.credentials.dig(:stripe, :secret_key)

    # To edit credentials:
    # EDITOR=vim bin/rails credentials:edit
    ```

    ```yaml theme={null}
    # config/credentials.yml.enc (Encrypted - Content before encryption)
    # stripe:
    #   # Modified example to avoid scanners:
    #   secret_key: sk_live_EXAMPLE_verySecretApiKeyGoesHere
    ```

    ```gitignore theme={null}
    # .gitignore (Ensure master.key is listed)
    /config/master.key
    ```

    #### Testing Strategy

    Use secret scanning tools in CI/CD. Ensure `config/master.key` is in `.gitignore`. Review `.yml` files and Ruby source code (initializers, constants) for hard-coded secrets. Check Git history.
  </Tab>
</Tabs>
