logo

Database

C Sharp X509certificate2 Privatekey Used

Description

Detects insecure handling of private keys in X509Certificate2 objects in C# code. When the PrivateKey property of an X509Certificate2 object is accessed directly, it can expose sensitive cryptographic material that should be protected. This poses a security risk as exposed private keys can be compromised and used to decrypt sensitive data or forge digital signatures.

Weakness:

313 - Insecure service configuration - Certificates

Category: Functionality Abuse

Detection Strategy

    • Check if the System.Security.Cryptography namespace is imported in the code

    • Look for direct access to the 'PrivateKey' property on X509Certificate2 objects

    • Verify that the object being accessed is an X509Certificate2 instance

    • Report a vulnerability when PrivateKey property access is found on an X509Certificate2 object

Vulnerable code example

using System.Security.Cryptography;

class UnsafeCertAccess {
    static void Main() {
        var cert = new X509Certificate2();
        var key = cert.PrivateKey;  // Vulnerable: Direct access to private key without security checks
    }
}

✅ Secure code example

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

class SafeCertAccess {
    static void Main() {
        try {
            // Use secure flag combination to protect key material
            var cert = new X509Certificate2("cert.pfx", "password", ...