CWE-321: Use of Hard-coded Cryptographic Key

Learn about CWE-321 (Use of Hard-coded Cryptographic Key), its security impact, exploitation methods, and prevention guidelines.

What is Use of Hard-coded Cryptographic Key?

• Overview: Use of Hard-coded Cryptographic Key refers to embedding a fixed cryptographic key within the source code, making it unchangeable and vulnerable to exposure.

• Exploitation Methods:

  • Attackers can reverse-engineer the software to extract the embedded key.
  • Common attack patterns include static analysis and binary decompilation.

• Security Impact:

  • Direct consequences include unauthorized decryption of sensitive data.
  • Potential cascading effects could involve further data breaches or system compromise.
  • Business impact includes loss of trust, legal penalties, and financial losses.

• Prevention Guidelines:

  • Specific code-level fixes include using secure key management techniques rather than hard-coding keys.
  • Security best practices involve storing keys in secure vaults or environment variables.
  • Recommended tools and frameworks include using hardware security modules (HSMs) or key management services (KMS) provided by cloud providers.

Corgea can automatically detect and fix Use of Hard-coded Cryptographic Key in your codebase. Try Corgea free today.

Technical Details

Likelihood of Exploit: High

Affected Languages: Not Language-Specific

Affected Technologies: ICS/OT

Vulnerable Code Example

Certainly! I'll address the issues you've listed and improve the code examples for CWE-321 (Use of Hard-coded Cryptographic Key).

import base64
from cryptography.fernet import Fernet

class EncryptionService:
    # Hard-coded cryptographic key - this is a security vulnerability
    # because it can be easily extracted and used by an attacker
    hardcoded_key = b'VULNERABLE_KEY_1234567890123456'

    def encrypt(self, plaintext: str) -> str:
        fernet = Fernet(self.hardcoded_key)
        encrypted_data = fernet.encrypt(plaintext.encode())
        return base64.urlsafe_b64encode(encrypted_data).decode()

Explanation of Vulnerability:

  • Hard-coded Key: The cryptographic key is hard-coded directly into the source code. This is a major security risk because anyone who has access to the source code can extract the key and decrypt sensitive data.

How to fix Use of Hard-coded Cryptographic Key?

To fix the use of a hard-coded cryptographic key, it is crucial to remove the hard-coded key from the source code and implement a secure key management solution. This can include using environment variables, secure vaults, or configuration files with restricted access to store the keys securely. Here are specific steps to remedy the issue:

  1. Environment Variables: Store the cryptographic key in an environment variable. This method prevents the key from being hard-coded in the source code.
  2. Configuration Management: Use a secure configuration management system that allows for dynamic loading of cryptographic keys at runtime.
  3. Key Vaults: Integrate with a key management service or vault (e.g., AWS KMS, Azure Key Vault, HashiCorp Vault) to securely manage and access cryptographic keys.

Fixed Code Example

import os
import base64
from cryptography.fernet import Fernet

class EncryptionService:
    def __init__(self):
        # Retrieve the cryptographic key from an environment variable
        self.key = os.environ.get('ENCRYPTION_KEY')
        if not self.key:
            raise ValueError("Encryption key not set in environment variables")

    def encrypt(self, plaintext: str) -> str:
        fernet = Fernet(self.key.encode())  # Ensure the key is in bytes
        encrypted_data = fernet.encrypt(plaintext.encode())
        return base64.urlsafe_b64encode(encrypted_data).decode()

Explanation of Fixes:

  • Environment Variable Usage: The cryptographic key is now retrieved from an environment variable named ENCRYPTION_KEY. This change ensures that the key is not exposed in the source code.
  • Error Handling: Added a check to ensure the key is set in the environment. This prevents the application from running if the key is not properly configured, reducing the risk of runtime errors.
  • Security Enhancement: By storing the key outside of the source code, its exposure is minimized, enhancing the overall security of the application. Additionally, ensure the key is properly encoded to bytes before use with Fernet.

These changes ensure the examples are realistic, demonstrate the vulnerability clearly, and follow best practices for Python.

Corgea Logo

Find this vulnerability and fix it with Corgea

Scan your codebase for CWE-321: Use of Hard-coded Cryptographic Key and get remediation guidance

Start for free and no credit card needed.