<commit_before>using System;

using System.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Security;
using System.Security.Cryptography;
using System.Management;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;

namespace RocaCmTest
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 1)
            {
                System.Console.WriteLine("Usage1: RocaCmTest.exe ... test cert stores");
                System.Console.WriteLine("Usage2: RocaCmTest.exe <cert_file> ... test cert file");
                System.Console.WriteLine("Usage3: RocaCmTest.exe <directory> ... test directory");
                return;
            }

            int iTPMGenKeyFlag = -1; // -1 ... not done, 0 ... tested OK, 1 ... tested vulnerable
            int iTPMCertFlag = -1; // -1 ... not done, 0 ... tested OK, 1 ... tested vulnerable

            try
            {
                // Phase 1. Check TPM behavior
                Console.WriteLine("*** RocaCmTest tool will check for ROCA (CVE-2017-15361) vulnerability ***\n");
                System.Console.WriteLine("Usage1: RocaCmTest.exe ... test cert stores");
                System.Console.WriteLine("Usage2: RocaCmTest.exe <cert_file> ... test cert file");
                System.Console.WriteLine("Usage3: RocaCmTest.exe <directory> ... test directory");
                Console.WriteLine("\nStep 1: Try to generate RSA keypair using Platform Crypto Provider(TPM) and inspect it");
                
                // Detect TPM
                bool isTpmPresent = false;
                try
                {
                    // Create management class object
                    ManagementClass mc = new ManagementClass("/root/CIMv2/Security/MicrosoftTpm:Win32_Tpm");
                    //collection to store all management objects
                    ManagementObjectCollection moc = mc.GetInstances();
                    // Retrieve single instance of WMI management object
                    ManagementObjectCollection.ManagementObjectEnumerator moe = moc.GetEnumerator();
                    moe.MoveNext();
                    ManagementObject mo = (ManagementObject)moe.Current;

                    if (null == mo)
                    {
                        isTpmPresent = false;
                        Console.WriteLine("TPM is not detected");
                    }
                    else
                    {
                        isTpmPresent = true;
                        Console.WriteLine("TPM chip detected");
                    }
                }
                catch(Exception e)
                {
                    Console.WriteLine("TPM detection error: " + e.Message);
                }

                if (isTpmPresent)
                {
                    string containerName = "TestRoca_" + Guid.NewGuid().ToString();
                    string providerName = "Microsoft Platform Crypto Provider";
                    if (Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2))
                    {
                        try
                        {
                            // Win 8 and newer
                            CngKeyCreationParameters keyParams = new CngKeyCreationParameters();
                            keyParams.KeyUsage = CngKeyUsages.Signing;
                            keyParams.ExportPolicy = CngExportPolicies.None;
                            keyParams.KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey;
                            keyParams.Provider = new CngProvider(providerName);
                            keyParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

                            // Generate a key
                            CngKey cngKey = CngKey.Create(new CngAlgorithm("RSA"), containerName, keyParams);

                            // Display the key information to the console.  
                            Console.WriteLine("RSA Key generated successfully");

                            StringWriter sw = new StringWriter();
                            ExportPublicKeyCng(cngKey, sw);
                            
                            StringReader sr = new StringReader(sw.ToString());

                            // Check vulnerbility
                            ConsoleColor old_color = Console.ForegroundColor;
                            if (KeyIsVulnerable(sr))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Alert: TPM generated RSA key is vulnerable to ROCA (CVE-2017-15361)");
                                Console.ForegroundColor = old_color;
                                iTPMGenKeyFlag = 1;
                            }
                            else
                            {
                                Console.WriteLine("TPM generated RSA key is OK");
                                iTPMGenKeyFlag = 0;
                            }

                            // Delete the key
                            cngKey.Delete();
                        }
                        catch(Exception e)
                        {
                            Console.WriteLine("Error: " + e.Message);
                            Console.WriteLine("TPM RSA Key generation and check was not done. We continue with further checks.");
                        }
                    }
                    else
                    {
                        // We are on Win 7 or older
                        providerName = "Charismathics Smart Security Interface Platform Extended";

                        try
                        {
                            // Create the CspParameters object and set the key container name used to store the RSA key pair.  
                            CspParameters cp = new CspParameters(0x18);
                            cp.KeyContainerName = containerName;
                            cp.ProviderName = providerName;
                            cp.Flags = CspProviderFlags.UseNonExportableKey;

                            // Create a new instance of RSACryptoServiceProvider that accesses  
                            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, cp);

                            // Display the key information to the console.  
                            Console.WriteLine("RSA Key generated successfully");

                            // Export the key to PEM
                            StringWriter sw = new StringWriter();
                            ExportPublicKey(rsa, sw);

                            rsa.Clear();

                            // Get the key to string
                            StringReader sr = new StringReader(sw.ToString());
                            ConsoleColor old_color = Console.ForegroundColor;
                            if (KeyIsVulnerable(sr))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Alert: TPM generated RSA key is vulnerable to ROCA (CVE-2017-15361)");
                                Console.ForegroundColor = old_color;
                                iTPMGenKeyFlag = 1;
                            }
                            else
                            {
                                Console.WriteLine("TPM generated RSA key is OK");
                                iTPMGenKeyFlag = 0;
                            }

                            // Create the CspParameters object and set the key container name used to store the RSA key pair.  
                            CspParameters cp2 = new CspParameters(0x18);
                            cp2.KeyContainerName = containerName;
                            cp2.ProviderName = providerName;

                            // Create a new instance of RSACryptoServiceProvider that accesses  
                            // the key container.  
                            RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider(cp2);

                            // Delete the key entry in the container.  
                            rsa2.PersistKeyInCsp = false;

                            // Call Clear to release resources and delete the key from the container.  
                            rsa2.Clear();

                            Console.WriteLine("Key deleted");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Error: " + e.Message);
                            Console.WriteLine("TPM RSA Key generation and check was not done. We continue with further checks.");
                        }
                    }                   
                }
                else
                {
                    Console.WriteLine("No TPM found on this machine");
                }

                if (args.Length == 0)
                {
                    Console.WriteLine("Step 2: Validate all certificates in user & system stores");
                    int sum = 0;
                    if(PrintVulnerableResultStore(StoreLocation.CurrentUser))
                    {
                        sum++;
                    }
                    if(PrintVulnerableResultStore(StoreLocation.LocalMachine))
                    {
                        sum++;
                    }<commit_msg>Adding company name<commit_after>using System;

using System.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Security;
using System.Security.Cryptography;
using System.Management;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;

namespace RocaCmTest
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 1)
            {
                System.Console.WriteLine("Usage1: RocaCmTest.exe ... test cert stores");
                System.Console.WriteLine("Usage2: RocaCmTest.exe <cert_file> ... test cert file");
                System.Console.WriteLine("Usage3: RocaCmTest.exe <directory> ... test directory");
                return;
            }

            int iTPMGenKeyFlag = -1; // -1 ... not done, 0 ... tested OK, 1 ... tested vulnerable
            int iTPMCertFlag = -1; // -1 ... not done, 0 ... tested OK, 1 ... tested vulnerable

            try
            {
                // Phase 1. Check TPM behavior
                Console.WriteLine("------------------------------------------------------------------------");
                Console.WriteLine("--- Charismathics ROCA (CVE-2017-15361) Vulnerability Detection Tool ---");
                Console.WriteLine("------------------------------------------------------------------------");
                Console.WriteLine("");
                Console.WriteLine("Usage1: RocaCmTest.exe ... test cert stores");
                Console.WriteLine("Usage2: RocaCmTest.exe <cert_file> ... test cert file");
                Console.WriteLine("Usage3: RocaCmTest.exe <directory> ... test directory");
                Console.WriteLine("");
                Console.WriteLine("Step 1: Try to generate RSA keypair using Platform Crypto Provider(TPM) and inspect it");
                
                // Detect TPM
                bool isTpmPresent = false;
                try
                {
                    // Create management class object
                    ManagementClass mc = new ManagementClass("/root/CIMv2/Security/MicrosoftTpm:Win32_Tpm");
                    //collection to store all management objects
                    ManagementObjectCollection moc = mc.GetInstances();
                    // Retrieve single instance of WMI management object
                    ManagementObjectCollection.ManagementObjectEnumerator moe = moc.GetEnumerator();
                    moe.MoveNext();
                    ManagementObject mo = (ManagementObject)moe.Current;

                    if (null == mo)
                    {
                        isTpmPresent = false;
                        Console.WriteLine("TPM is not detected");
                    }
                    else
                    {
                        isTpmPresent = true;
                        Console.WriteLine("TPM chip detected");
                    }
                }
                catch(Exception e)
                {
                    Console.WriteLine("TPM detection error: " + e.Message);
                }

                if (isTpmPresent)
                {
                    string containerName = "TestRoca_" + Guid.NewGuid().ToString();
                    string providerName = "Microsoft Platform Crypto Provider";
                    if (Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2))
                    {
                        try
                        {
                            // Win 8 and newer
                            CngKeyCreationParameters keyParams = new CngKeyCreationParameters();
                            keyParams.KeyUsage = CngKeyUsages.Signing;
                            keyParams.ExportPolicy = CngExportPolicies.None;
                            keyParams.KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey;
                            keyParams.Provider = new CngProvider(providerName);
                            keyParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

                            // Generate a key
                            CngKey cngKey = CngKey.Create(new CngAlgorithm("RSA"), containerName, keyParams);

                            // Display the key information to the console.  
                            Console.WriteLine("RSA Key generated successfully");

                            StringWriter sw = new StringWriter();
                            ExportPublicKeyCng(cngKey, sw);
                            
                            StringReader sr = new StringReader(sw.ToString());

                            // Check vulnerbility
                            ConsoleColor old_color = Console.ForegroundColor;
                            if (KeyIsVulnerable(sr))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Alert: TPM generated RSA key is vulnerable to ROCA (CVE-2017-15361)");
                                Console.ForegroundColor = old_color;
                                iTPMGenKeyFlag = 1;
                            }
                            else
                            {
                                Console.WriteLine("TPM generated RSA key is OK");
                                iTPMGenKeyFlag = 0;
                            }

                            // Delete the key
                            cngKey.Delete();
                        }
                        catch(Exception e)
                        {
                            Console.WriteLine("Error: " + e.Message);
                            Console.WriteLine("TPM RSA Key generation and check was not done. We continue with further checks.");
                        }
                    }
                    else
                    {
                        // We are on Win 7 or older
                        providerName = "Charismathics Smart Security Interface Platform Extended";

                        try
                        {
                            // Create the CspParameters object and set the key container name used to store the RSA key pair.  
                            CspParameters cp = new CspParameters(0x18);
                            cp.KeyContainerName = containerName;
                            cp.ProviderName = providerName;
                            cp.Flags = CspProviderFlags.UseNonExportableKey;

                            // Create a new instance of RSACryptoServiceProvider that accesses  
                            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, cp);

                            // Display the key information to the console.  
                            Console.WriteLine("RSA Key generated successfully");

                            // Export the key to PEM
                            StringWriter sw = new StringWriter();
                            ExportPublicKey(rsa, sw);

                            rsa.Clear();

                            // Get the key to string
                            StringReader sr = new StringReader(sw.ToString());
                            ConsoleColor old_color = Console.ForegroundColor;
                            if (KeyIsVulnerable(sr))
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Alert: TPM generated RSA key is vulnerable to ROCA (CVE-2017-15361)");
                                Console.ForegroundColor = old_color;
                                iTPMGenKeyFlag = 1;
                            }
                            else
                            {
                                Console.WriteLine("TPM generated RSA key is OK");
                                iTPMGenKeyFlag = 0;
                            }

                            // Create the CspParameters object and set the key container name used to store the RSA key pair.  
                            CspParameters cp2 = new CspParameters(0x18);
                            cp2.KeyContainerName = containerName;
                            cp2.ProviderName = providerName;

                            // Create a new instance of RSACryptoServiceProvider that accesses  
                            // the key container.  
                            RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider(cp2);

                            // Delete the key entry in the container.  
                            rsa2.PersistKeyInCsp = false;

                            // Call Clear to release resources and delete the key from the container.  
                            rsa2.Clear();

                            Console.WriteLine("Key deleted");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Error: " + e.Message);
                            Console.WriteLine("TPM RSA Key generation and check was not done. We continue with further checks.");
                        }
                    }                   
                }
                else
                {
                    Console.WriteLine("No TPM found on this machine");
                }

                Console.WriteLine("");

                if (args.Length == 0)
                {
                    Console.WriteLine("Step 2: Validate all certificates in user & system stores");
                    int sum = 0;
                    if(PrintVulnerableResultStore(StoreLocation.CurrentUser))
                    {
                        sum++;
                    }
                    if(PrintVulnerableResultStore(StoreLocation.LocalMachine))
                    {
                        sum++;
                    }
{'fraction_non_alphanumeric': 0.07624230710543715, 'fraction_numerical': 0.008748283403692589, 'mean_word_length': 1.0205528722638988, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3904874', 'n_tokens_mistral': 4397, 'n_tokens_neox': 4012, 'n_words': 1056}