CXX.SV.PRIVATE_KEY.UNENCRYPTED
Attempt to serialize private key in an unauthorized way
Klocwork reports a CXX.SV.PRIVATE_KEY.UNENCRYPTED defect when an unencrypted cipher is used to store a private key in a public key infrastructure (PKI) based authentication, which can lead to unauthorized access.
Vulnerability and risk
If a private key is stolen, this can compromise the authentication gained through PKI because an attacker can use the private key to digitally sign documents and pretend to be the authorized user.
Mitigation and prevention
We recommend using encryption techniques such as cipher or a non-empty password.
Vulnerable code example
#include <QOpcUaProvider>
#include <QOpcUaKeyPair>
#include <QFile>
int main()
{
// Generate RSA Key
QOpcUaKeyPair key;
key.generateRsaKey(QOpcUaKeyPair::RsaKeyStrength::Bits1024);
// Save private key to file
QByteArray keyData = key.privateKeyToByteArray(QOpcUaKeyPair::Cipher::Unencrypted, "password");
QFile keyFile("privateKey.pem");
keyFile.open(QFile::WriteOnly);
keyFile.write(keyData);
keyFile.close();
}
Klocwork reports a CXX.SV.PRIVATE_KEY.UNENCRYPTED defect on line 11, indicating, “Attempt to serialize private key in an unauthorized way. Consider encrypting with cipher.” In the QOpcUaKeyPair::privateKeyToByteArray
method, QOpcUaKeyPair::Cipher::Unencrypted
is passed, which means a private key is stored with unencrypted cipher and is prone to unauthorized access.
Fixed code example
#include <QOpcUaProvider>
#include <QOpcUaKeyPair>
#include <QFile>
int main()
{
// Generate RSA Key
QOpcUaKeyPair key;
key.generateRsaKey(QOpcUaKeyPair::RsaKeyStrength::Bits1024);
QByteArray keyData = key.privateKeyToByteArray(QOpcUaKeyPair::Cipher::Aes128Cbc, "K016w813");
QFile keyFile("privateKey.pem");
keyFile.open(QFile::WriteOnly);
keyFile.write(keyData);
keyFile.close();
}
Klocwork no longer reports a CXX.SV.PRIVATE_KEY.UNENCRYPTED defect because a cipher ("Aes128Cbc") and a password (“K016w813”) have been used on the private key for the required encryption.
Related checkers
External guidance
- CWE-311: Missing Encryption of Sensitive Data
- CWE-312: Cleartext Storage of Sensitive Information
- CWE-522: Insufficiently Protected Credentials
- DISA STIG version 4 and 5
- OWASP A2:2021 Cryptographic Failures
- STIG-ID:V-222551 (APSC-DV-001820): The application, when using PKI-based authentication, must enforce authorized access to the corresponding private key.
Security training
Application security training materials provided by Secure Code Warrior.
Extension
This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis and the PK.UNENC.SINK knowledge base for more information.