using System.Diagnostics; using System.Net.NetworkInformation; using System.Security.Cryptography; using System.Text; using Azaion.CommonSecurity.DTO; namespace Azaion.CommonSecurity.Services; public interface IHardwareService { HardwareInfo GetHardware(); } public class HardwareService : IHardwareService { private const string WIN32_GET_HARDWARE_COMMAND = "powershell -Command \"" + "Get-CimInstance -ClassName Win32_Processor | Select-Object -ExpandProperty Name | Write-Output; " + "Get-CimInstance -ClassName Win32_VideoController | Select-Object -ExpandProperty Name | Write-Output; " + "Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -ExpandProperty TotalVisibleMemorySize | Write-Output" + "\""; private const string UNIX_GET_HARDWARE_COMMAND = "/bin/bash -c \"free -g | grep Mem: | awk '{print $2}' && " + "lscpu | grep 'Model name:' | cut -d':' -f2 && " + "lspci | grep VGA | cut -d':' -f3\""; public HardwareInfo GetHardware() { try { var output = RunCommand(Environment.OSVersion.Platform == PlatformID.Win32NT ? WIN32_GET_HARDWARE_COMMAND : UNIX_GET_HARDWARE_COMMAND); var lines = output .Replace("TotalVisibleMemorySize=", "") .Replace("Name=", "") .Replace(" ", " ") .Trim() .Split(['\n', '\r'], StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .ToArray(); if (lines.Length < 3) throw new Exception("Can't get hardware info"); var hardwareInfo = new HardwareInfo { CPU = lines[0], GPU = lines[1], Memory = lines[2], MacAddress = GetMacAddress() }; return hardwareInfo; } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } } private string GetMacAddress() { var macAddress = NetworkInterface .GetAllNetworkInterfaces() .Where(nic => nic.OperationalStatus == OperationalStatus.Up) .Select(nic => nic.GetPhysicalAddress().ToString()) .FirstOrDefault(); return macAddress ?? string.Empty; } private string RunCommand(string command) { try { using var process = new Process(); process.StartInfo.FileName = Environment.OSVersion.Platform == PlatformID.Unix ? "/bin/bash" : "cmd.exe"; process.StartInfo.Arguments = Environment.OSVersion.Platform == PlatformID.Unix ? $"-c \"{command}\"" : $"/c {command}"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.Start(); var result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return result.Trim(); } catch { return string.Empty; } } private static string ToHash(string str) => Convert.ToBase64String(SHA384.HashData(Encoding.UTF8.GetBytes(str))); }