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

Copy
#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

Copy
#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.

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.