Secure storage of confidential information
# settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mydatabasepassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
In this code, the credentials for the database are stored directly in the source code. This is a security vulnerability because anyone who has access to this source code would also have access to the database. The password is in plain text and not encrypted or hashed in any way. This means that if the source code is ever exposed, the database could be easily compromised.
This is a common mistake made by developers because it is easy and convenient to store credentials directly in the code. However, it is a serious security risk and should be avoided. Instead, credentials should be stored in a separate configuration file or environment variables that are not included in the source code. They should also be encrypted or hashed to provide an additional layer of security.
# settings.py
import os
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.getenv('DATABASE_NAME'),
'USER': os.getenv('DATABASE_USER'),
'PASSWORD': os.getenv('DATABASE_PASSWORD'),
'HOST': os.getenv('DATABASE_HOST'),
'PORT': os.getenv('DATABASE_PORT'),
}
}
The above code fixes the vulnerability by removing the hard-coded credentials from the source code and replacing them with environment variables.
The
os.getenv
function is used to retrieve the values of the environment variables. These variables are
DATABASE_NAME
,
DATABASE_USER
,
DATABASE_PASSWORD
,
DATABASE_HOST
, and
DATABASE_PORT
.
These environment variables should be set in the environment where your application is running. The exact method to set these variables depends on your operating system and the way you are running your application.
For example, in a Unix-based system, you can set environment variables in the terminal like this:
export DATABASE_NAME=mydatabase
export DATABASE_USER=mydatabaseuser
export DATABASE_PASSWORD=mydatabasepassword
export DATABASE_HOST=localhost
export DATABASE_PORT=5432
.gitignore
file to ensure they are not included in the version control system.
# .gitignore
DATABASE_NAME
DATABASE_USER
DATABASE_PASSWORD
DATABASE_HOST
DATABASE_PORT