在 Android 文件系统中以明文形式存储敏感信息¶
ID: java/android/cleartext-storage-filesystem
Kind: problem
Security severity: 7.5
Severity: warning
Precision: medium
Tags:
- security
- external/cwe/cwe-312
Query suites:
- java-security-extended.qls
- java-security-and-quality.qls
具有适当权限的 Android 应用程序可以根据应用程序的需要将文件写入设备外部存储或应用程序内部存储。但是,不应以明文形式保存敏感信息。否则,root 设备中的任何进程或用户都可以访问它,或者可以通过链式漏洞泄露,例如通过暴露的组件意外访问私有存储。
建议¶
考虑使用 EncryptedFile
类来处理包含敏感数据的文件。或者,使用加密算法对要存储的敏感数据进行加密。
示例¶
在第一个示例中,敏感用户信息使用本地文件以明文形式存储。
在第二个和第三个例子中,代码在将敏感信息保存到文件系统之前对其进行了加密。
public void fileSystemStorageUnsafe(String name, String password) {
// BAD - sensitive data stored in cleartext
FileWriter fw = new FileWriter("some_file.txt");
fw.write(name + ":" + password);
fw.close();
}
public void filesystemStorageEncryptedFileSafe(Context context, String name, String password) {
// GOOD - the whole file is encrypted with androidx.security.crypto.EncryptedFile
File file = new File("some_file.txt");
String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
EncryptedFile encryptedFile = new EncryptedFile.Builder(
file,
context,
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
FileOutputStream encryptedOutputStream = encryptedFile.openFileOutput();
encryptedOutputStream.write(name + ":" + password);
}
public void fileSystemStorageSafe(String name, String password) {
// GOOD - sensitive data is encrypted using a custom method
FileWriter fw = new FileWriter("some_file.txt");
fw.write(name + ":" + encrypt(password));
fw.close();
}
private static String encrypt(String cleartext) {
// Use an encryption or strong hashing algorithm in the real world.
// The example below just returns a SHA-256 hash.
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(cleartext.getBytes(StandardCharsets.UTF_8));
String encoded = Base64.getEncoder().encodeToString(hash);
return encoded;
}
参考资料¶
Android 开发者:更安全地处理数据
Android 开发者:EncryptedFile
常见缺陷列表:CWE-312。