Blog | G5 Cyber Security

Secure Database Connections

TL;DR

Yes, your application can connect to a database without hardcoding or directly exposing passwords. Use environment variables and a configuration file to store connection details securely. Avoid storing sensitive information in version control.

How to Secure Database Connections

  1. Understand the Problem: Directly embedding database credentials (username, password) into your application code is a major security risk. If someone gains access to your codebase, they immediately have access to your database.
    • Risk of Exposure: Committing passwords to version control systems like Git exposes them even further.
    • Maintenance Issues: Changing credentials requires modifying the code and redeploying the application.
  2. Use Environment Variables: Store your database connection details as environment variables on your server.
    • Environment variables are system-level settings that can be accessed by your application at runtime. They’re separate from your code.
    • To set an environment variable (example for Linux/macOS):
      export DB_USER=your_username
      export DB_PASSWORD=your_password
      export DB_HOST=your_host
      export DB_NAME=your_database_name
  3. Create a Configuration File: Write a configuration file (e.g., config.py, settings.json) to read the environment variables.
    • This file will contain code that retrieves the values from the environment and makes them available to your application.
    • Python Example (config.py):
      import os
      
      def get_db_credentials():
        user = os.environ.get('DB_USER')
        password = os.environ.get('DB_PASSWORD')
        host = os.environ.get('DB_HOST')
        name = os.environ.get('DB_NAME')
        if not all([user, password, host, name]):
          raise ValueError("Missing database credentials in environment variables")
        return user, password, host, name
      
  4. Access Credentials in Your Application: Import the configuration file and use the function to retrieve the database credentials.
    • Python Example:
      from config import get_db_credentials
      
      try:
        user, password, host, name = get_db_credentials()
      except ValueError as e:
        print(f"Error loading database credentials: {e}")
        exit(1)
      
      # Now you can use user, password, host, and name to connect to your database.
      
  5. .gitignore File: Ensure that any files containing sensitive information (even temporary ones) are added to your .gitignore file before committing to version control.
    • This prevents accidental exposure of credentials in your repository.
    • Add the configuration file name (e.g., config.py) to your .gitignore file.
  6. Database User Permissions: Create a dedicated database user with limited privileges specifically for your application.
    • Avoid using the root or admin account for routine operations.
    • Grant only the necessary permissions (e.g., SELECT, INSERT, UPDATE) to the application’s user.
  7. Consider a Secrets Manager: For more complex deployments and enhanced security, use a dedicated secrets manager service (e.g., AWS Secrets Manager, HashiCorp Vault).
    • Secrets managers provide centralized storage, access control, and auditing for sensitive information.
Exit mobile version