15-堆内存隐私信息泄露缺陷
2025/1/1大约 2 分钟安全开发安全开发应用安全
堆内存隐私信息泄露缺陷 - 腾讯安全代码审计实战系列系列15
在应用程序中,敏感信息(如密码、密钥或个人身份信息)通常被存储为不可变的String
对象。在这种情况下,内存中的敏感数据可能会在不知不觉中泄露。由于String
对象是不可变的,它们不能直接被清除或覆盖,只能依赖垃圾收集器来清除内存中的数据。在垃圾收集器运行之前,如果发生内存转储或应用程序崩溃,这些数据就有可能泄露。
修复建议
- 使用可变的字符数组或字节数组来存储敏感信息,以便在使用之后能够直接清除或覆盖这些数据。
- 确保在敏感信息不再需要使用时,及时清除或覆盖其所占用的内存空间。
示例代码
// bad:使用String存储敏感信息,不可预测何时信息会被清除
public void processSensitiveInformation(byte[] secretData, byte[] encryptionKey, byte[] initializationVector) {
byte[] decryptedData = AESUtils.decrypt(secretData, encryptionKey, initializationVector);
String sensitiveInfo = new String(decryptedData); // 敏感信息以String形式存储
// 使用敏感信息
System.out.println("Processed: " + sensitiveInfo);
}
// good:使用char数组存储敏感信息,并及时清除
public void processSensitiveInformationSafely(byte[] secretData, byte[] encryptionKey, byte[] initializationVector) {
byte[] decryptedData = AESUtils.decrypt(secretData, encryptionKey, initializationVector);
char[] sensitiveInfo = new char[decryptedData.length];
for (int i = 0; i < decryptedData.length; i++) {
sensitiveInfo[i] = (char) decryptedData[i];
}
// 使用敏感信息
try {
System.out.println("Processed: " + new String(sensitiveInfo));
} finally {
Arrays.fill(sensitiveInfo, '\u0000'); // 使用完毕后清除信息
}
}