/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * dmex * */ namespace CustomBuildTool { /// /// Provides cryptographic and signature verification utilities for build artifacts. /// public static class BuildVerify { /// /// Maps build key names to their corresponding environment variable names for key and salt. /// public static readonly FrozenDictionary KeyName_Vars = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "canary", new("CANARY_BUILD_KEY", "CANARY_BUILD_S", "CANARY_BUILD_I") }, { "developer", new("DEVELOPER_BUILD_KEY", "DEVELOPER_BUILD_S", "DEVELOPER_BUILD_I") }, { "kph", new("KPH_BUILD_KEY", "KPH_BUILD_S", "KPH_BUILD_I") }, { "preview", new("PREVIEW_BUILD_KEY", "PREVIEW_BUILD_S", "PREVIEW_BUILD_I") }, { "release", new("RELEASE_BUILD_KEY", "RELEASE_BUILD_S", "RELEASE_BUILD_I") }, }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); public record BuildVerifyKeyPair(string Key, string Salt, string Iterations); /// /// Encrypts the specified file using the provided secret and salt, and writes the result to the output file. /// /// The path to the input file to encrypt. /// The path to the output encrypted file. /// The secret used for encryption. /// The salt value or key name for encryption. /// The iterations value or key name for encryption. /// True if encryption succeeds; otherwise, false. public static bool EncryptFile(string FileName, string OutFileName, ReadOnlySpan Secret, string Salt, string Iterations) { if (string.IsNullOrWhiteSpace(FileName) || string.IsNullOrWhiteSpace(OutFileName) || Secret.IsEmpty || string.IsNullOrWhiteSpace(Salt)) { Program.PrintColorMessage($"Unable to encrypt file: Invalid arguments.", ConsoleColor.Yellow); return false; } try { using (var fileStream = File.OpenRead(FileName)) { var encryptedBytes = Encrypt(fileStream, Secret, GetSalt(Salt), GetIterations(Iterations)); Utils.WriteAllBytes(OutFileName, encryptedBytes); } } catch (Exception e) { Program.PrintColorMessage($"Unable to encrypt file {Path.GetFileName(FileName)}: {e.Message}", ConsoleColor.Yellow); return false; } return true; } /// /// Decrypts the specified file using the provided secret and salt, and writes the result to the output file. /// /// The path to the input encrypted file. /// The path to the output decrypted file. /// The secret used for decryption. /// The salt value or key name for decryption. /// The iterations value or key name for encryption. /// True if decryption succeeds; otherwise, false. public static bool DecryptFile(string FileName, string OutFileName, ReadOnlySpan Secret, string Salt, string Iterations) { if (string.IsNullOrWhiteSpace(FileName) || string.IsNullOrWhiteSpace(OutFileName) || Secret.IsEmpty || string.IsNullOrWhiteSpace(Salt)) { Program.PrintColorMessage($"Unable to decrypt file: Invalid arguments.", ConsoleColor.Yellow); return false; } try { using (var fileStream = File.OpenRead(FileName)) { var decryptedBytes = Decrypt(fileStream, Secret, GetSalt(Salt), GetIterations(Iterations)); Utils.WriteAllBytes(OutFileName, decryptedBytes); } } catch (Exception e) { Program.PrintColorMessage($"Unable to decrypt file {Path.GetFileName(FileName)}: {e.Message}", ConsoleColor.Yellow); return false; } return true; } /// /// Computes the SHA256 hash of the specified file and returns it as a hexadecimal string. /// /// The path to the file to hash. /// The hexadecimal string of the file's hash, or an empty string if hashing fails. public static string HashFile(string FileName) { try { using (var fileStream = File.OpenRead(FileName)) { byte[] fileHash = SHA256.HashData(fileStream); return Convert.ToHexString(fileHash); } } catch (Exception e) { Program.PrintColorMessage($"Unable to hash file {Path.GetFileName(FileName)}: {e.Message}", ConsoleColor.Yellow); return null; } } /// /// Computes the SHA-256 hash of the specified byte array. /// /// The byte array to hash. /// A hexadecimal string representation of the computed hash, or null if an error occurs. public static string HashData(byte[] Source) { try { byte[] fileHash = SHA256.HashData(Source); return Convert.ToHexString(fileHash); } catch (Exception e) { Program.PrintColorMessage($"Unable to hash buffer: {e.Message}", ConsoleColor.Yellow); return null; } } /// /// Creates a signature file for the specified file using the given key name. /// /// The key name to use for signing. /// The path to the file to sign. /// If true, performs strict checks before creating the signature file. /// True if the signature file is created; otherwise, false. public static bool CreateSigFile(string KeyName, string FileName, bool StrictChecks) { if (string.IsNullOrWhiteSpace(KeyName)) { Program.PrintErrorMessage("CreateSigFile: KeyName is empty."); return false; } if (string.IsNullOrWhiteSpace(FileName)) { Program.PrintErrorMessage("CreateSigFile: FileName is empty."); return false; } try { if (!File.Exists(FileName)) { Program.PrintErrorMessage($"File missing: {FileName}"); return false; } string sigFileName = Path.ChangeExtension(FileName, ".sig"); if (!GetKeyMaterial(KeyName, out byte[] keyMaterial)) { if (StrictChecks) { Program.PrintColorMessage($"[GetKeyMaterial failed] ({KeyName})", ConsoleColor.Red); return false; } return true; } try { if (StrictChecks) { if (File.Exists(sigFileName) && Win32.GetFileSize(sigFileName) != 0) { Program.PrintColorMessage($"[Signature File Exists] ({sigFileName})", ConsoleColor.Red); return false; } } byte[] signature = SignFile(keyMaterial, FileName); Utils.WriteAllBytes(sigFileName, signature); } finally { CryptographicOperations.ZeroMemory(keyMaterial); } } catch (Exception e) { Program.PrintColorMessage($"Unable to create signature file {Path.GetFileName(FileName)}: {e}", ConsoleColor.Yellow); return false; } return true; } /// /// Creates a signature string for the specified file using the given key name. /// /// The key name to use for signing. /// The path to the file to sign. /// The hexadecimal string of the signature, or null if signing fails. public static string CreateSigString(string KeyName, string FileName) { if (!File.Exists(FileName)) return null; try { if (GetKeyMaterial(KeyName, out byte[] keyMaterial)) { try { byte[] signature = SignFile(keyMaterial, FileName); if (signature.Length != 0) { return Convert.ToHexString(signature); } } finally { CryptographicOperations.ZeroMemory(keyMaterial); } } } catch (Exception e) { Program.PrintColorMessage($"Unable to create signature string {Path.GetFileName(FileName)}: {e}", ConsoleColor.Yellow); } return null; } /// /// Encrypts the provided stream using the specified secret and salt. /// /// The input stream to encrypt. /// The secret used for encryption. /// The salt value for encryption. /// The iterations value for encryption. /// The encrypted byte array, or null if encryption fails. private static byte[] Encrypt(Stream Stream, ReadOnlySpan Secret, string Salt, int Iterations) { try { using (var aes = GetRijndael(Secret, Salt, Iterations)) using (var encryptor = aes.CreateEncryptor()) { int capacity = Stream.CanSeek ? aes.GetCiphertextLengthCbc((int)Stream.Length, PaddingMode.PKCS7) : 4096; using (var ms = new MemoryStream(capacity)) { using (var cryptoStream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write, leaveOpen: true)) { Stream.CopyTo(cryptoStream); cryptoStream.FlushFinalBlock(); } return ms.ToArray(); } } } catch (Exception e) { Program.PrintColorMessage($"[Encrypt-Exception]: {e.Message}", ConsoleColor.Red); } return null; } /// /// Decrypts data from the specified stream using AES with a key derived from the provided secret, salt, and /// iteration count. /// /// The stream containing the encrypted data. /// The secret used to derive the decryption key. /// The salt used in key derivation. /// The number of iterations for the key derivation function. /// A byte array containing the decrypted data, or null if decryption fails. private static byte[] Decrypt(Stream Stream, ReadOnlySpan Secret, string Salt, int Iterations) { try { using (var aes = GetRijndael(Secret, Salt, Iterations)) using (var decryptor = aes.CreateDecryptor()) { int capacity = Stream.CanSeek ? (int)Stream.Length : 4096; using (var ms = new MemoryStream(capacity)) { using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Write, leaveOpen: true)) { Stream.CopyTo(cryptoStream); cryptoStream.FlushFinalBlock(); } return ms.ToArray(); } } } catch (Exception e) { Program.PrintColorMessage($"[Decrypt-Exception]: {e.Message}", ConsoleColor.Red); } return null; } /// /// Decrypts a byte array using AES in CBC mode with a key derived from the specified secret, salt, and /// iteration count. /// /// The encrypted data to decrypt. /// The secret used to derive the decryption key. /// The salt used in key derivation. /// The number of iterations for the key derivation function. /// The decrypted byte array, or null if decryption fails. private static byte[] Decrypt(byte[] Bytes, ReadOnlySpan Secret, string Salt, int Iterations) { try { using (var aes = GetRijndael(Secret, Salt, Iterations)) { return aes.DecryptCbc(Bytes, aes.IV, PaddingMode.PKCS7); } } catch (Exception e) { Program.PrintColorMessage($"[Decrypt-Exception]: {e.Message}", ConsoleColor.Red); } return null; } private static byte[] Encrypt(byte[] Bytes, ReadOnlySpan Secret, string Salt, int Iterations) { try { using (var aes = GetRijndael(Secret, Salt, Iterations)) { return aes.EncryptCbc(Bytes, aes.IV, PaddingMode.PKCS7); } } catch (Exception e) { Program.PrintColorMessage($"[Encrypt-Exception]: {e.Message}", ConsoleColor.Red); } return null; } private static Aes GetRijndael(ReadOnlySpan Secret, string Salt, int Iterations) { ReadOnlySpan saltBytes = Convert.FromBase64String(Salt); Span keyMaterial = stackalloc byte[48]; Rfc2898DeriveBytes.Pbkdf2( Secret, saltBytes, keyMaterial, Iterations, HashAlgorithmName.SHA512 ); Aes aes = Aes.Create(); aes.Key = keyMaterial[..32].ToArray(); aes.IV = keyMaterial[32..48].ToArray(); CryptographicOperations.ZeroMemory(keyMaterial); return aes; } /// /// Signs the provided byte array using the specified key material. /// /// The private key material for signing. /// The data to sign. /// The signature byte array. private static byte[] Sign(byte[] KeyMaterial, byte[] Bytes) { byte[] buffer; using (CngKey cngkey = CngKey.Import(KeyMaterial, CngKeyBlobFormat.GenericPrivateBlob)) { if (cngkey.Algorithm == CngAlgorithm.ECDsaP256) { using (ECDsaCng ecdsa = new ECDsaCng(cngkey)) { buffer = ecdsa.SignData(Bytes, HashAlgorithmName.SHA256); } } else if (cngkey.Algorithm == CngAlgorithm.Rsa) { using (RSACng rsa = new RSACng(cngkey)) { buffer = rsa.SignData(Bytes, HashAlgorithmName.SHA512, RSASignaturePadding.Pss); } } else { throw new NotSupportedException($"Unsupported algorithm: {cngkey.Algorithm}"); } } return buffer; } /// /// Signs the contents of the specified file using the provided key material. /// /// The private key material for signing. /// The path to the file to sign. /// The signature byte array. private static byte[] SignFile(byte[] KeyMaterial, string FileName) { byte[] buffer; using (FileStream fileStream = File.OpenRead(FileName)) using (CngKey cngkey = CngKey.Import(KeyMaterial, CngKeyBlobFormat.GenericPrivateBlob)) { if (cngkey.Algorithm == CngAlgorithm.ECDsaP256) { using (ECDsaCng ecdsa = new ECDsaCng(cngkey)) { buffer = ecdsa.SignData(fileStream, HashAlgorithmName.SHA256); } } else if (cngkey.Algorithm == CngAlgorithm.Rsa) { using (RSACng rsa = new RSACng(cngkey)) { buffer = rsa.SignData(fileStream, HashAlgorithmName.SHA512, RSASignaturePadding.Pss); } } else { throw new NotSupportedException($"Unsupported algorithm: {cngkey.Algorithm}"); } } return buffer; } /// /// Attempts to extract the algorithm OID from a SubjectPublicKeyInfo ASN.1 blob. /// Returns "RSA", "ECDSA", or null if unknown. /// private static CngAlgorithmGroup GetPublicKeyAlgorithmOid(byte[] KeyBlob) { try { var reader = new System.Formats.Asn1.AsnReader(KeyBlob, System.Formats.Asn1.AsnEncodingRules.DER); var seq = reader.ReadSequence(); // SubjectPublicKeyInfo SEQUENCE var algId = seq.ReadSequence(); // AlgorithmIdentifier SEQUENCE var oid = algId.ReadObjectIdentifier(); // Common OIDs: // 1.2.840.10045.2.1 = ecPublicKey // 1.2.840.113549.1.1.1 = rsaEncryption if (string.Equals(oid, "1.2.840.10045.2.1", StringComparison.OrdinalIgnoreCase)) return CngAlgorithmGroup.ECDsa; if (string.Equals(oid, "1.2.840.113549.1.1.1", StringComparison.OrdinalIgnoreCase)) return CngAlgorithmGroup.Rsa; } catch { // Not a valid SubjectPublicKeyInfo or unknown format } return null; } /// /// Prints public key information for the provided key blob and format. /// /// The key blob containing the public key. /// The format of the key blob. public static void PrintCngPublicKeyInfo(byte[] KeyBlob, CngKeyBlobFormat KeyFormat) { // Try to detect if the blob is SubjectPublicKeyInfo (ASN.1 SEQUENCE starts with 0x30) bool isSubjectPublicKeyInfo = KeyBlob.Length > 0 && KeyBlob[0] == 0x30; if (isSubjectPublicKeyInfo) { var type = GetPublicKeyAlgorithmOid(KeyBlob); if (type == CngAlgorithmGroup.ECDsa) { using (ECDsa ecdsa = ECDsa.Create()) { ecdsa.ImportSubjectPublicKeyInfo(KeyBlob, out _); Program.PrintColorMessage("ECDSA Public Key (SubjectPublicKeyInfo)\n", ConsoleColor.Cyan); Program.PrintColorMessage($"{ecdsa.ExportSubjectPublicKeyInfoPem()}\n", ConsoleColor.White); } } else if (type == CngAlgorithmGroup.Rsa) { using (RSA rsa = RSA.Create()) { rsa.ImportSubjectPublicKeyInfo(KeyBlob, out _); Program.PrintColorMessage("RSA Public Key (SubjectPublicKeyInfo)\n", ConsoleColor.Cyan); Program.PrintColorMessage($"{rsa.ExportSubjectPublicKeyInfoPem()}\n", ConsoleColor.White); Program.PrintColorMessage($"{rsa.ExportRSAPublicKeyPem()}\n", ConsoleColor.White); } } else { throw new NotSupportedException($"Unsupported algorithm."); } } else { using (CngKey cngkey = CngKey.Import(KeyBlob, KeyFormat)) { if (cngkey.Algorithm == CngAlgorithm.ECDsaP256) { using (ECDsaCng ecdsa = new ECDsaCng(cngkey)) { Program.PrintColorMessage($"{ecdsa.ExportSubjectPublicKeyInfoPem()}\n", ConsoleColor.White); } } else if (cngkey.Algorithm == CngAlgorithm.Rsa) { using (RSACng rsa = new RSACng(cngkey)) { Program.PrintColorMessage($"{rsa.ExportSubjectPublicKeyInfoPem()}\n", ConsoleColor.White); Program.PrintColorMessage($"{rsa.ExportRSAPublicKeyPem()}\n", ConsoleColor.White); } } else { throw new NotSupportedException($"Unsupported algorithm: {cngkey.Algorithm}"); } } } } /// /// Gets the full path for the specified file, using environment variables or default locations. /// /// The file name to resolve. /// The resolved file path. private static string GetPath(string FileName) { if (Win32.GetEnvironmentVariable("BUILD_DRM", out string value)) { return Path.Join([value, FileName]); } // N.B. Local developers are instructed to put keys in this path. return Path.Join([Build.BuildWorkingFolder, "tools", "CustomSignTool", "Resources", FileName]); } /// /// Gets the salt value for the specified key name or returns the input if not found. /// /// The key name or salt value. /// The salt value. private static string GetSalt(string KeyNameOrSalt) { if (KeyName_Vars.TryGetValue(KeyNameOrSalt, out var vars)) { if (Win32.GetEnvironmentVariable(vars.Salt, out string salt)) { return salt; } string saltFile = GetPath($"{KeyNameOrSalt}.salt"); if (File.Exists(saltFile)) { return Utils.ReadFirstLine(saltFile); } } // Assume this is the salt itself... return KeyNameOrSalt; } /// /// Gets the iterations value for the specified key name or returns the input if not found. /// /// The key name or salt value. /// The salt value. private static int GetIterations(string KeyNameOrIterations) { if (KeyName_Vars.TryGetValue(KeyNameOrIterations, out var vars)) { if (Win32.GetEnvironmentVariable(vars.Iterations, out string iterations)) { return int.Parse(iterations); } string iterationsFile = GetPath($"{KeyNameOrIterations}.iterations"); if (File.Exists(iterationsFile)) { return int.Parse(Utils.ReadFirstLine(iterationsFile)); } } // Assume this is the iterations itself... return int.Parse(KeyNameOrIterations); } /// /// Retrieves the key material for the specified key name. /// /// The key name to retrieve material for. /// The output key material byte array. /// True if key material is found; otherwise, false. private static bool GetKeyMaterial(string KeyName, out byte[] KeyMaterial) { string fileName = GetPath($"{KeyName}"); if (File.Exists(fileName)) { using (var secret = Utils.ReadAllTextSecure(fileName)) { byte[] bytes = Utils.ReadAllBytes(GetPath($"{KeyName}.s")); KeyMaterial = Decrypt(bytes, secret.Span, GetSalt(KeyName), GetIterations(KeyName)); } return true; } else if (File.Exists(GetPath($"{KeyName}.key"))) { KeyMaterial = Utils.ReadAllBytes(GetPath($"{KeyName}.key")); return true; } else if (Win32.GetEnvironmentVariableSecure(KeyName_Vars[KeyName].Key, out SecureBuffer secret)) { using (secret) { byte[] bytes = Utils.ReadAllBytes(GetPath($"{KeyName}.s")); KeyMaterial = Decrypt(bytes, secret.Span, GetSalt(KeyName), GetIterations(KeyName)); } return true; } else { KeyMaterial = null; return false; } } //private static bool GetKeyMaterial(string KeyName, out byte[] KeyMaterial) //{ // if ( // Win32.GetEnvironmentVariable(KeyName_Vars[KeyName].Key, out string key) && // Win32.GetEnvironmentVariable(KeyName_Vars[KeyName].Value, out string value) && // Win32.GetEnvironmentVariable("KPH_BUILD_SALT", out string salt) // ) // { // if (Uri.TryCreate(value, UriKind.Absolute, out Uri result) && result.IsFile) // { // using (var fileStream = File.OpenRead(value)) // { // KeyMaterial = Decrypt(fileStream, key, salt); // } // } // else // { // byte[] bytes = Utils.ReadAllBytes(value); // KeyMaterial = Decrypt(bytes, key, salt); // } // // return true; // } // else if (Win32.GetEnvironmentVariable(KeyName_Vars[KeyName].Key, out string secret)) // { // if (Uri.TryCreate(secret, UriKind.Absolute, out Uri result) && result.IsFile) // { // using (var fileStream = File.OpenRead(secret)) // { // KeyMaterial = Decrypt(fileStream, secret, GetSalt(null)); // } // } // else // { // byte[] bytes = Utils.ReadAllBytes(GetPath($"{KeyName}.s")); // KeyMaterial = Decrypt(bytes, secret, GetSalt(null)); // } // // return true; // } // else if (File.Exists(GetPath($"{KeyName}.key"))) // { // KeyMaterial = Utils.ReadAllBytes(GetPath($"{KeyName}.key")); // return true; // } // else // { // KeyMaterial = null; // return false; // } //} } }