Skip to main content

Sensitive information in source code - API Key

Need

Secure storage and retrieval of sensitive information such as API keys

Context

  • Usage of PHP for server-side scripting and web development
  • Usage of Controller for handling and managing application logic and data flow

Description

Non compliant code

<?php
class SomeController extends Controller
{
public function someFunction()
{
$apiKey = '1234567890abcdef'; // API Key in plain text
// Rest of the code
}
}
?>

In the above code, the API key is hard-coded directly into the source code. This is a security vulnerability because anyone who has access to the source code will also have access to this sensitive information.

The API key is stored in the someFunction() method of the SomeController class. The API key is in plain text format, which means it's readable and accessible to anyone who can view the source code.

If an attacker gains access to the source code, they could potentially use this API key to carry out malicious activities. This could include making unauthorized API calls, exceeding rate limits, or even conducting more serious attacks such as data breaches or denial of service.

To avoid this vulnerability, sensitive information like API keys should never be hard-coded into the source code. Instead, they should be stored in a secure location such as environment variables, and accessed through secure methods.

Steps

  • Remove the API key from the source code.
  • Store the API key in a secure environment variable.
  • Access the API key in your code through the environment variable.
  • Ensure the environment variable is not logged or output in error messages or logs.

Compliant code

<?php
class SomeController extends Controller
{
public function someFunction()
{
$apiKey = env('API_KEY'); // API Key is now stored in an environment variable
// Rest of the code
}
}
?>

The API key was previously stored directly in the source code as a plain text string. This is a security vulnerability as it exposes the key to anyone who has access to the source code.

The fix involves removing the API key from the source code and storing it in an environment variable instead. The Laravel env() function is used to retrieve the value of the API key from the environment variable. This ensures that the API key is not exposed in the source code and can be securely managed separately from the codebase.

In your .env file, you should have a line that looks like this:

API_KEY=1234567890abcdef

This is where you store your actual API key. The .env file should not be included in your version control system. It should be in your .gitignore file to prevent it from being uploaded to your repository.

Remember to never output the value of the API key in error messages, logs, or any other user-facing messages, as this could expose the key.

References