Skip to content

CWE-313: Cleartext Storage in a File or on Disk - Remediation Guide

In short CWE-313 is sensitive data, such as PII, stored in cleartext in a file or on disk, where unauthorized users can retrieve it easily. Prevent it by omitting sensitive data that is not needed, masking values, and using strong encryption for anything that must be stored.

CWE-313: Cleartext Storage in a File or on Disk involves the unsafe practice of storing sensitive data, such as Personally Identifiable Information (PII), in cleartext within files or on disk. This vulnerability allows unauthorized users to access or retrieve sensitive information easily. This article outlines the risks associated with PII exposure through CWE-313 and offers strategies for remediation, with coding examples in Java, JavaScript, and Python.

  1. Data Theft: Unauthorized access to files or disks can lead directly to the theft of PII.

  2. Identity Theft: Exposed PII can be used by malicious actors to impersonate victims.

  3. Financial Fraud: Access to sensitive information like bank details can result in unauthorized transactions and financial losses.

  1. Reputational Damage: A data breach can severely damage an organization’s reputation, leading to loss of customer trust and business.

  2. Regulatory Penalties: Non-compliance with data protection regulations (e.g., GDPR, HIPAA) could result in hefty fines and legal actions.

  3. Operational Interruptions: Addressing the aftermath of a breach involves considerable resources, which can divert focus from core business operations.

Effective remediation for CWE-313 involves ensuring that sensitive data is not stored in cleartext. Techniques include omitting unnecessary sensitive data, masking data, and using strong encryption methods.

Whenever possible, sensitive data should not be written to disk.

Java
public class User {
private String username;
// Avoid writing sensitive information like social security numbers to disk
}
Javascript
function saveUser(username) {
// Only save non-sensitive information; avoid writing personal details to disk
console.log("Saving user: " + username);
}
Python
class User:
def __init__(self, username):
self.username = username
# Ensure that sensitive PII is not written to disk

If sensitive data must be stored, ensure it is adequately masked or anonymized.

Java
public String maskSocialSecurityNumber(String ssn) {
return "XXX-XX-" + ssn.substring(ssn.length() - 4);
}
Javascript
function maskSSN(ssn) {
return 'XXX-XX-' + ssn.slice(-4);
}
Python
def mask_ssn(ssn):
return 'XXX-XX-' + ssn[-4:]

Encrypt sensitive data before it is written to disk to protect it from unauthorized access.

Java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
public class EncryptionUtility {
// secretKey is supplied by the caller, sourced from your KMS or secret store
public static String encrypt(String data, SecretKey secretKey) throws Exception {
byte[] iv = new byte[12];
new SecureRandom().nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new GCMParameterSpec(128, iv));
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
byte[] payload = ByteBuffer.allocate(iv.length + encrypted.length).put(iv).put(encrypted).array();
return java.util.Base64.getEncoder().encodeToString(payload);
}
}
Javascript
const crypto = require('crypto');
// key: 32-byte Buffer loaded from your KMS or secret store
function encrypt(data, key) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
const encrypted = Buffer.concat([cipher.update(data, 'utf8'), cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
}
Python
from cryptography.fernet import Fernet
# key: Fernet key loaded from your secret store, never generated per call
def encrypt(data, key):
cipher = Fernet(key)
encrypted = cipher.encrypt(data.encode())
return encrypted.decode()

HoundDog.ai’s Privacy Code Scanner (hounddog scan) records sensitive data written to files and other storage sinks, and reports a risky dataflow when that data reaches a storage sink marked risky. It identifies sensitive data elements in source code and traces them through assignments, transformations, string interpolations, and function calls to the sinks they reach.

  • Sensitive data types. The scanner ships with over 100 data element definitions covering common PII, PHI, CHD, PIFI, and secret data (tags PII, PHI, CHD, PIFI, SECRET); the full list is in the scanner’s data-elements.md. A finding names the data element involved, such as Email or Social Security Number.

  • Sinks. The Files sink is marked safe by default, so sensitive data written to a file is recorded and appears in the Datamap but is not flagged as risky. Set the sink to risky under Scanner Rules to have those writes flagged. CWE-313 is attached to several storage and cloud data sinks, including AWS S3, AWS DynamoDB, Azure Blob Storage, and SQL Database, which are also safe by default.

  • Languages. Dataflows are reported for Python, JavaScript, TypeScript, Java, C#/.NET, and Go. Other supported languages are scanned for data elements only and produce no dataflows. See Supported Languages.

  • Sanitization. When AI dataflow reviews are enabled, each dataflow is reviewed with its code and trace in context, including any sanitization logic (masking, hashing, encryption, redaction) applied before the data reaches the sink. Dataflows where the data is effectively sanitized are marked as false positives.

To run a scan, see the quickstart. For how data elements and data sinks are defined and customized, see the scanner rules reference.

Addressing CWE-313 requires careful handling of how and where sensitive data is stored. By implementing data omission, masking, and encryption strategies, organizations can mitigate the risk of unauthorized data access and comply with stringent privacy regulations, thereby safeguarding both their customers and their operational integrity.