initial upload

This commit is contained in:
kkb 2023-09-21 18:58:32 +02:00
parent a0aa9cc28e
commit f857f43df4
553 changed files with 46169 additions and 13 deletions

View file

@ -0,0 +1,57 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Microsoft.Extensions.Logging;
using Vaitr.Network;
namespace Insight.Agent.Network
{
public class AgentSession : TcpSession<IAgentMessage>
{
private readonly IEnumerable<IAgentMessageHandler<AgentSession>> _handlers;
public AgentSession(IEnumerable<IAgentMessageHandler<AgentSession>> handlers, ISerializer<IAgentMessage> serializer, ILogger<AgentSession> logger) : base(serializer, logger)
{
_handlers = handlers;
}
protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Agent ({ep?}) connected", RemoteEndPoint);
return default;
}
protected override ValueTask OnDisconnectedAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Agent ({ep?}) disconnected", RemoteEndPoint);
return default;
}
protected override ValueTask OnSentAsync(IPacketContext<IAgentMessage> context, CancellationToken cancellationToken)
{
return base.OnSentAsync(context, cancellationToken);
}
protected override async ValueTask OnReceivedAsync(IPacketContext<IAgentMessage> context, CancellationToken cancellationToken)
{
await base.OnReceivedAsync(context, cancellationToken);
foreach (var handler in _handlers)
{
try
{
await handler.HandleAsync(this, context.Packet, cancellationToken);
}
catch (Exception ex)
{
_logger.LogWarning("Agent ({ep?}) {ex}", RemoteEndPoint, ex.ToString());
}
}
}
protected override ValueTask OnHeartbeatAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Agent ({ep?}) Heartbeat", RemoteEndPoint);
return default;
}
}
}

View file

@ -0,0 +1,38 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Insight.Agent.Models;
using Insight.Agent.Services;
using Insight.Domain.Constants;
namespace Insight.Agent.Network.Handlers
{
public class AuthenticationHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is AuthenticationRequest)
{
Config? config = null;
try
{
config = await Configurator.ReadAsync<Config>(Configuration.DefaultConfig, cancellationToken).ConfigureAwait(false);
}
catch (Exception) { }
if (config is null)
{
config = new Config { Serial = Guid.NewGuid() };
await Configurator.WriteAsync(config, Configuration.DefaultConfig, cancellationToken).ConfigureAwait(false);
}
await sender.SendAsync(new Authentication
{
Serial = config.Serial ?? throw new InvalidDataException(nameof(config.Serial)),
Version = Configuration.Version,
Hostname = Configuration.Hostname
}, cancellationToken);
}
}
}
}

View file

@ -0,0 +1,111 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace Insight.Agent.Network.Handlers;
public class ConsoleHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is ConsoleQueryRequest consoleQueryRequest)
{
await OnConsoleQueryRequestAsync(sender, consoleQueryRequest, cancellationToken);
}
}
private async ValueTask OnConsoleQueryRequestAsync(AgentSession sender, ConsoleQueryRequest consoleQueryRequest, CancellationToken cancellationToken)
{
var result = await QueryScriptAsync(consoleQueryRequest.Query);
await sender.SendAsync(new ConsoleQuery
{
Id = consoleQueryRequest.Id,
HostId = consoleQueryRequest.HostId,
Query = consoleQueryRequest.Query,
Data = result.Data,
Errors = result.Errors,
HadErrors = result.HadErrors
}, cancellationToken);
}
private static async Task<QueryResult> QueryScriptAsync(string query)
{
var result = new QueryResult();
var errors = new List<string>();
try
{
using var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
runspace.SessionStateProxy.LanguageMode = PSLanguageMode.FullLanguage;
using var ps = PowerShell.Create(runspace);
ps.AddScript("Set-ExecutionPolicy unrestricted -Scope Process");
ps.AddScript(query);
ps.AddCommand("ConvertTo-Json"); // -Depth 10
result.Query = query;
var queryResult = await ps.InvokeAsync();
if (ps.HadErrors)
{
result.HadErrors = true;
errors.AddRange(ps.Streams.Error.Select(e => e.ToString()));
}
else
{
result.Data = queryResult[0].ToString();
//if (string.IsNullOrWhiteSpace(jsonString)) return result;
//if (jsonString.TrimStart().StartsWith("[")) // It's an array
//{
// result.IsArray = true;
// var deserialized = JsonSerializer.Deserialize<List<Dictionary<string, object?>>>(jsonString, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
// if (deserialized is null) return result;
// result.Data.AddRange(deserialized);
// //Console.WriteLine("Deserialized to List<Dictionary<string, object>>");
//}
//else
//{
// if (jsonString.TrimStart().StartsWith("{") is false) // It's an object
// {
// result.IsString = true;
// result.Data.Add(new Dictionary<string, object?> { { query, jsonString.Trim('"') } });
// }
// else
// {
// var deserialized = JsonSerializer.Deserialize<Dictionary<string, object?>>(jsonString, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
// if (deserialized is null) return result;
// result.Data.Add(deserialized);
// //Console.WriteLine("Deserialized to Dictionary<string, object>");
// }
//}
}
}
catch (Exception ex)
{
result.HadErrors = true;
errors.Add(ex.Message);
}
result.Errors = string.Join("\n", errors);
return result;
}
}
public class QueryResult
{
public bool HadErrors { get; set; }
public string? Query { get; set; }
public string? Data { get; set; }
public string? Errors { get; set; }
}

View file

@ -0,0 +1,178 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class DriveHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new DriveList();
result.AddRange(GetDrives());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<Drive> GetDrives()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select index, name, caption, model, manufacturer, serialNumber, size, status, interfacetype, firmwarerevision, deviceid, pnpdeviceid from win32_diskdrive")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_diskdrive");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var drives = new List<Drive>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var drive = new Drive();
var properties = @object.GetPropertyHashes();
drive.Index = @object.GetValue<uint>(properties, "index");
drive.Id = @object.GetValue<string>(properties, "deviceid")?.Trim();
drive.Name = @object.GetValue<string>(properties, "model")?.Trim();
drive.Manufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
drive.SerialNumber = @object.GetValue<string>(properties, "serialnumber")?.Trim();
drive.Size = @object.GetValue<ulong>(properties, "size");
drive.Status = @object.GetValue<string>(properties, "status")?.Trim();
drive.InterfaceType = @object.GetValue<string>(properties, "interfacetype")?.Trim();
drive.FirmwareRevision = @object.GetValue<string>(properties, "firmwarerevision")?.Trim();
drive.PNPDeviceID = @object.GetValue<string>(properties, "pnpdeviceid")?.Trim();
drive.Volumes = new List<Volume>();
var diskpartition = @object.GetRelated("win32_diskpartition");
using (diskpartition)
{
foreach (ManagementObject dp in diskpartition.Cast<ManagementObject>())
{
var volume = new Volume();
var dpProperties = dp.GetPropertyHashes();
volume.NumberOfBlocks = dp.GetValue<ulong>(dpProperties, "numberofblocks");
volume.BootPartition = dp.GetValue<bool>(dpProperties, "bootpartition");
volume.PrimaryPartition = dp.GetValue<bool>(dpProperties, "primarypartition");
volume.Size = dp.GetValue<ulong>(dpProperties, "size");
volume.Index = dp.GetValue<uint>(dpProperties, "index");
volume.Type = dp.GetValue<string>(dpProperties, "type")?.Trim();
volume.Bootable = dp.GetValue<bool>(dpProperties, "bootable");
volume.BlockSize = dp.GetValue<ulong>(dpProperties, "blocksize");
volume.StartingOffset = dp.GetValue<ulong>(dpProperties, "startingoffset");
var logicaldisk = dp.GetRelated("win32_logicaldisk");
using (logicaldisk)
{
foreach (ManagementObject ld in logicaldisk.Cast<ManagementObject>())
{
var ldProperties = ld.GetPropertyHashes();
volume.Id = ld.GetValue<string>(ldProperties, "deviceid")?.Trim();
volume.Name = ld.GetValue<string>(ldProperties, "volumename")?.Trim();
volume.SerialNumber = ld.GetValue<string>(ldProperties, "volumeserialnumber")?.Trim();
volume.DriveType = (DriveType)ld.GetValue<uint>(ldProperties, "drivetype");
volume.FileSystem = ld.GetValue<string>(ldProperties, "filesystem")?.Trim();
volume.Compressed = ld.GetValue<bool>(ldProperties, "compressed");
volume.Size = ld.GetValue<ulong>(ldProperties, "size");
volume.FreeSpace = ld.GetValue<ulong>(ldProperties, "freespace");
volume.ProviderName = ld.GetValue<string>(ldProperties, "providername")?.Trim();
}
}
drive.Volumes.Add(volume);
}
}
drives.Add(drive);
}
}
return drives;
}
private static List<Volume> GetVolumes()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select deviceid, volumename, volumeserialnumber, drivetype, filesystem, compressed, size, freeSpace, providername from win32_logicaldisk")
};
// per device query
// "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + driveDeviceId + "'} WHERE AssocClass=Win32_DiskDriveToDiskPartition"
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_logicaldisk");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var volumes = new List<Volume>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var volume = new Volume();
var properties = @object.GetPropertyHashes();
//volume.DeviceId = @object.GetValue<string>(properties, "deviceid")?.Trim();
//volume.VolumeName = @object.GetValue<string>(properties, "volumename")?.Trim();
//volume.VolumeSerialNumber = @object.GetValue<string>(properties, "volumeserialnumber")?.Trim();
volume.DriveType = (DriveType)@object.GetValue<uint>(properties, "drivetype");
volume.FileSystem = @object.GetValue<string>(properties, "filesystem")?.Trim();
volume.Compressed = @object.GetValue<bool>(properties, "compressed");
volume.Size = @object.GetValue<ulong>(properties, "size");
volume.FreeSpace = @object.GetValue<ulong>(properties, "freespace");
volume.ProviderName = @object.GetValue<string>(properties, "providername")?.Trim();
if (volume.Id is not null)
{
searcher.Query = new ObjectQuery("associators of {win32_logicaldisk.deviceid='" + volume.Id + "'} where assocclass=win32_logicaldisktopartition");
if (searcher.TryGet(out var collection2))
{
using (collection2)
{
foreach (ManagementObject @object2 in collection2)
{
var properties2 = @object2.GetPropertyHashes();
volume.Index = @object2.GetValue<uint>(properties2, "index");
//volume.DiskIndex = @object2.GetValue<uint>(properties2, "diskindex");
volume.Type = @object2.GetValue<string>(properties2, "type")?.Trim();
volume.Bootable = @object2.GetValue<bool>(properties2, "bootable");
volume.PrimaryPartition = @object2.GetValue<bool>(properties2, "primarypartition");
volume.BootPartition = @object2.GetValue<bool>(properties2, "bootpartition");
volume.BlockSize = @object2.GetValue<ulong>(properties2, "blocksize");
volume.NumberOfBlocks = @object2.GetValue<ulong>(properties2, "numberofblocks");
volume.StartingOffset = @object2.GetValue<ulong>(properties2, "startingoffset");
}
}
}
}
volumes.Add(volume);
}
}
return volumes;
}
}
}

View file

@ -0,0 +1,274 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Route = Insight.Agent.Messages.Route;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class InterfaceHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new InterfaceList();
result.AddRange(GetInterfaces());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<Interface> GetInterfaces()
{
if (NetworkInterface.GetIsNetworkAvailable() is false) return null;
if (NetworkInterface.GetAllNetworkInterfaces().Any() is false) return null;
var interfaces = new List<Interface>();
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
var ipProperties = ni.GetIPProperties();
var ipStatistics = ni.GetIPStatistics();
var @interface = new Interface
{
Mac = ni.GetPhysicalAddress().ToString(),
Name = ni.Name,
Description = ni.Description,
Type = ni.NetworkInterfaceType,
Speed = ni.Speed,
Status = ni.OperationalStatus,
Suffix = ipProperties.DnsSuffix,
Sent = ipStatistics.BytesSent,
Received = ipStatistics.BytesReceived,
IncomingPacketsDiscarded = ipStatistics.IncomingPacketsDiscarded,
IncomingPacketsWithErrors = ipStatistics.IncomingPacketsWithErrors,
IncomingUnknownProtocolPackets = ipStatistics.IncomingUnknownProtocolPackets,
OutgoingPacketsDiscarded = ipStatistics.OutgoingPacketsDiscarded,
OutgoingPacketsWithErrors = ipStatistics.OutgoingPacketsWithErrors
};
try
{
var propertiesV4 = ipProperties.GetIPv4Properties();
@interface.Index = uint.Parse(propertiesV4.Index.ToString());
@interface.Ipv4Mtu = propertiesV4.Mtu;
@interface.Ipv4Dhcp = propertiesV4.IsDhcpEnabled;
@interface.Ipv4Forwarding = propertiesV4.IsForwardingEnabled;
}
catch (Exception) { }
try
{
var propertiesV6 = ipProperties.GetIPv6Properties();
@interface.Index = uint.Parse(propertiesV6.Index.ToString());
@interface.Ipv6Mtu = propertiesV6.Mtu;
}
catch (Exception) { }
@interface.Gateways = GetAddresses(ipProperties.GatewayAddresses);
@interface.Addresses = GetAddresses(ipProperties.UnicastAddresses);
@interface.Dns = GetAddresses(ipProperties.DnsAddresses);
@interface.Dhcp = GetAddresses(ipProperties.DhcpServerAddresses);
if (@interface.Index.HasValue)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery($"select interfaceindex, guid, physicaladapter, manufacturer from win32_networkadapter where interfaceindex = {@interface.Index}")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery($"select * from win32_networkadapter where interfaceindex = {@interface.Index}");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
using (collection)
{
foreach (ManagementObject @object in collection)
{
var properties = @object.GetPropertyHashes();
@interface.Manufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
@interface.Guid = @object.GetValue<Guid>(properties, "guid");
@interface.Physical = @object.GetValue<bool>(properties, "physicaladapter");
break;
}
}
@interface.Routes = QueryInterfaceRoutes(@interface.Index.Value);
}
}
interfaces.Add(@interface);
}
return interfaces;
}
private static List<Route> QueryInterfaceRoutes(uint interfaceIndex)
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\standardcimv2"),
Query = new ObjectQuery($"select addressFamily, state, interfaceindex, routemetric, nexthop, destinationprefix from msft_netroute where interfaceindex = {interfaceIndex}")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery($"select * from msft_netroute where interfaceindex = {interfaceIndex}");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var routes = new List<Route>();
using (collection)
{
foreach (var @object in collection)
{
var route = new Route
{
InterfaceIndex = interfaceIndex
};
var properties = @object.GetPropertyHashes();
if (@object.TryGetValue<object>(properties, "routemetric", out var routemetric))
{
if (int.TryParse(routemetric?.ToString(), out var metric)) route.Metric = metric;
}
if (@object.TryGetValue<object>(properties, "nexthop", out var nexthop))
{
if (IPAddress.TryParse(nexthop?.ToString(), out var gateway)) route.Gateway = new IPAddress2(gateway);
}
if (@object.TryGetValue<object>(properties, "destinationprefix", out var destinationprefix))
{
var split = destinationprefix?.ToString()?.Split('/');
var cidrData = split?[1];
if (IPAddress.TryParse(split?[0], out var destination))
route.Destination = new IPAddress2(destination);
if (int.TryParse(cidrData, out var cidr))
{
var mask = ConvertCidr(cidr);
route.Mask = mask;
}
}
routes.Add(route);
}
}
return routes;
}
private static List<Unicast> GetAddresses(UnicastIPAddressInformationCollection unicastCollection)
{
var addresses = new List<Unicast>();
if (unicastCollection.Any() is false) return addresses;
foreach (var unicast in unicastCollection)
{
addresses.Add(new Unicast
{
IpAddress = new IPAddress2(unicast.Address),
AddressPreferredLifetime = unicast.AddressPreferredLifetime,
AddressValidLifetime = unicast.AddressValidLifetime,
DuplicateAddressDetectionState = unicast.DuplicateAddressDetectionState,
Ipv4Mask = new IPAddress2(unicast.IPv4Mask),
PrefixLength = unicast.PrefixLength,
PrefixOrigin = unicast.PrefixOrigin,
SuffixOrigin = unicast.SuffixOrigin,
DhcpLeaseLifetime = unicast.DhcpLeaseLifetime,
});
}
return addresses;
}
private static List<IPAddress2> GetAddresses(IPAddressCollection addressCollection)
{
var addresses = new List<IPAddress2>();
if (addressCollection.Any() is false) return addresses;
foreach (var address in addressCollection)
{
addresses.Add(new IPAddress2(address));
}
return addresses;
}
private static List<IPAddress2> GetAddresses(GatewayIPAddressInformationCollection addressCollection)
{
var addresses = new List<IPAddress2>();
if (addressCollection.Any() is false) return addresses;
foreach (var address in addressCollection)
{
addresses.Add(new IPAddress2(address.Address));
}
return addresses;
}
private static string? ConvertCidr(int cidr)
{
return cidr switch
{
0 => "0.0.0.0",
1 => "128.0.0.0",
2 => "192.0.0.0",
3 => "224.0.0.0",
4 => "240.0.0.0",
5 => "248.0.0.0",
6 => "252.0.0.0",
7 => "254.0.0.0",
8 => "255.0.0.0",
9 => "255.128.0.0",
10 => "255.192.0.0",
11 => "255.224.0.0",
12 => "255.240.0.0",
13 => "255.248.0.0",
14 => "255.252.0.0",
15 => "255.254.0.0",
16 => "255.255.0.0",
17 => "255.255.128.0",
18 => "255.255.192.0",
19 => "255.255.224.0",
20 => "255.255.240.0",
21 => "255.255.248.0",
22 => "255.255.252.0",
23 => "255.255.254.0",
24 => "255.255.255.0",
25 => "255.255.255.128",
26 => "255.255.255.192",
27 => "255.255.255.224",
28 => "255.255.255.240",
29 => "255.255.255.248",
30 => "255.255.255.252",
31 => "255.255.255.254",
32 => "255.255.255.255",
_ => null,
};
}
}
}

View file

@ -0,0 +1,86 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class MainboardHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
await sender.SendAsync(GetMainboard(), cancellationToken);
}
}
private static Mainboard GetMainboard()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select manufacturer, product, serialnumber from win32_baseboard")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_baseboard");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var mainboard = new Mainboard();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var properties = @object.GetPropertyHashes();
mainboard.Manufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
mainboard.Model = @object.GetValue<string>(properties, "product")?.Trim();
mainboard.Serial = @object.GetValue<string>(properties, "serialnumber")?.Trim();
break;
}
}
searcher.Query = new ObjectQuery("select manufacturer, serialnumber, smbiosbiosversion, releasedate from win32_bios");
if (searcher.TryGet(out var collection2) is false)
{
searcher.Query = new ObjectQuery("select * from win32_bios");
if (searcher.TryGet(out collection2) is false) return null;
}
using (collection2)
{
foreach (ManagementObject @object in collection2.Cast<ManagementObject>())
{
var properties = @object.GetPropertyHashes();
mainboard.BiosManufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
mainboard.Serial = @object.GetValue<string>(properties, "serialnumber")?.Trim();
mainboard.BiosVersion = @object.GetValue<string>(properties, "smbiosbiosversion")?.Trim();
if (@object.TryGetValue<object>(properties, "releasedate", out var releasedate))
{
mainboard.BiosDate = ManagementDateTimeConverter.ToDateTime(releasedate?.ToString());
}
break;
}
}
//Logger.LogWarning(JsonSerializer.Serialize(mainboard, new JsonSerializerOptions
//{
// WriteIndented= true
//}));
return mainboard;
}
}
}

View file

@ -0,0 +1,123 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class MemoryHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new MemoryList();
result.AddRange(GetMemory());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<Memory> GetMemory()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select tag, devicelocator, manufacturer, partnumber, serialnumber, capacity, speed, maxvoltage, configuredclockspeed, configuredvoltage from win32_physicalmemory")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_physicalmemory");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var memorysticks = new List<Memory>();
using (collection)
{
uint index = 0;
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var @memory = new Memory();
var properties = @object.GetPropertyHashes();
@memory.Index = index;
@memory.Tag = @object.GetValue<string>(properties, "tag")?.Trim();
@memory.Location = @object.GetValue<string>(properties, "devicelocator")?.Trim();
@memory.Manufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
@memory.Model = @object.GetValue<string>(properties, "partnumber")?.Trim();
@memory.Serial = @object.GetValue<string>(properties, "serialnumber")?.Trim();
@memory.Capacity = @object.GetValue<ulong>(properties, "capacity");
@memory.Speed = @object.GetValue<uint>(properties, "speed");
@memory.Voltage = @object.GetValue<uint>(properties, "maxvoltage");
@memory.ConfiguredSpeed = @object.GetValue<uint>(properties, "configuredclockspeed");
@memory.ConfiguredVoltage = @object.GetValue<uint>(properties, "configuredvoltage");
memorysticks.Add(@memory);
index++;
}
}
return memorysticks;
}
//private async ValueTask<Memory.Metric> GetMemoryMetricAsync(CancellationToken cancellationToken)
//{
// var metric = new Memory.Metric();
// using var searcher = new ManagementObjectSearcher
// {
// Scope = new ManagementScope(@"root\cimv2"),
// Query = new ObjectQuery("select totalphysicalmemory from win32_computersystem")
// };
// if (searcher.TryGet(out var collection) is false)
// {
// searcher.Query = new ObjectQuery("select * from win32_computersystem");
// if (searcher.TryGet(out collection) is false) return metric;
// }
// ulong capacity = 0;
// using (collection)
// {
// foreach (var @object in collection)
// {
// var properties = @object.GetPropertyHashes();
// if (@object.TryGetValue(properties, "totalphysicalmemory", out capacity))
// {
// capacity = capacity / 1024 / 1024;
// }
// break;
// }
// }
// if (MemoryAvailableCounter is null)
// {
// MemoryAvailableCounter = new PerformanceCounter
// {
// CategoryName = "Memory",
// CounterName = "Available MBytes"
// };
// metric.MemoryAvailable = MemoryAvailableCounter.NextValue();
// await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
// }
// metric.Timestamp = DateTime.Now;
// metric.MemoryAvailable = MemoryAvailableCounter.NextValue();
// metric.MemoryUsed = capacity - metric.MemoryAvailable;
// metric.MemoryUsagePercentage = metric.MemoryUsed / capacity * 100;
// metric.MemoryAvailablePercentage = 100 - metric.MemoryUsagePercentage;
// return metric;
//}
}
}

View file

@ -0,0 +1,91 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Microsoft.Win32;
using System.Management;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class OperationSystemHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
await sender.SendAsync(GetOperatingSystem(), cancellationToken);
}
}
private static OperationSystem GetOperatingSystem()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select caption, version, serialnumber, osarchitecture, installdate from win32_operatingsystem")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_operatingsystem");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var os = new OperationSystem();
using (collection)
{
foreach (ManagementObject @object in collection)
{
var properties = @object.GetPropertyHashes();
os.Name = @object.GetValue<string>(properties, "caption")?.Trim();
os.Version = @object.GetValue<string>(properties, "version")?.Trim();
os.SerialNumber = @object.GetValue<string>(properties, "serialnumber")?.Trim();
if (@object.TryGetValue<string>(properties, "osarchitecture", out var architecture))
{
if (architecture is not null && architecture.ToLower().Contains("64")) os.Architecture = Architecture.X64;
}
else
{
os.Architecture = Architecture.X86;
}
if (@object.TryGetValue<object>(properties, "installdate", out var installdate))
{
os.InstallDate = ManagementDateTimeConverter.ToDateTime(installdate?.ToString());
}
break;
}
}
using var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default);
using var key = registry.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey);
if (key is not null && key?.GetValue("UBR")?.ToString() is string buildNumber)
{
os.Version = $"{os.Version}.{buildNumber}";
}
searcher.Query = new ObjectQuery("select * from win32_portconnector");
if (searcher.TryGet(out var collection2) is false)
{
os.Virtual = true;
}
else
{
os.Virtual = false;
}
collection2.Dispose();
return os;
}
}
}

View file

@ -0,0 +1,60 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class PrinterHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new PrinterList();
result.AddRange(GetPrinters());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<Printer> GetPrinters()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select drivername, name, portname, location, comment from win32_printer")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_printer");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var printers = new List<Printer>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var printer = new Printer();
var properties = @object.GetPropertyHashes();
printer.Driver = @object.GetValue<string>(properties, "drivername")?.Trim();
printer.Name = @object.GetValue<string>(properties, "name")?.Trim();
printer.Port = @object.GetValue<string>(properties, "portname")?.Trim();
printer.Location = @object.GetValue<string>(properties, "location")?.Trim();
printer.Comment = @object.GetValue<string>(properties, "comment")?.Trim();
printers.Add(printer);
}
}
return printers;
}
}
}

View file

@ -0,0 +1,143 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class ProcessorHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new ProcessorList();
result.AddRange(GetProcessors());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<Processor> GetProcessors()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select deviceid, name, manufacturer, socketdesignation, version, processorid, l2cachesize, l3cachesize, currentclockspeed, maxclockspeed, numberofcores, numberoflogicalprocessors, virtualizationfirmwareenabled from win32_processor")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_processor");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var processors = new List<Processor>();
using (collection)
{
uint index = 0;
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var processor = new Processor();
var properties = @object.GetPropertyHashes();
processor.Index = index;
processor.DeviceId = @object.GetValue<string>(properties, "deviceid")?.Trim();
processor.Name = @object.GetValue<string>(properties, "name")?.Trim();
processor.Manufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
processor.Socket = @object.GetValue<string>(properties, "socketdesignation")?.Trim();
processor.Version = @object.GetValue<string>(properties, "version")?.Trim();
processor.SerialNumber = @object.GetValue<string>(properties, "processorid")?.Trim();
processor.CurrentSpeed = @object.GetValue<uint>(properties, "currentclockspeed");
processor.MaxSpeed = @object.GetValue<uint>(properties, "maxclockspeed");
processor.Cores = @object.GetValue<uint>(properties, "numberofcores");
processor.LogicalCores = @object.GetValue<uint>(properties, "numberoflogicalprocessors");
processor.Virtualization = @object.GetValue<bool>(properties, "virtualizationfirmwareenabled");
searcher.Query = new ObjectQuery("select level, maxcachesize from win32_cachememory");
if (searcher.TryGet(out var collection2) is false)
{
searcher.Query = new ObjectQuery("select * from win32_cachememory");
if (searcher.TryGet(out collection2) is false) throw new InvalidOperationException("WMI Collection NULL");
}
using (collection2)
{
foreach (ManagementObject @object2 in collection2.Cast<ManagementObject>())
{
var properties2 = @object2.GetPropertyHashes();
ProcessorCacheLevelEnum? cacheLevel = null;
cacheLevel = (ProcessorCacheLevelEnum?)@object2.GetValue<ushort>(properties2, "level");
if (cacheLevel is null) continue;
var installedSize = @object2.GetValue<uint>(properties2, "maxcachesize");
switch (cacheLevel)
{
case ProcessorCacheLevelEnum.L1:
{
processor.L1Size = installedSize;
break;
}
case ProcessorCacheLevelEnum.L2:
{
processor.L2Size = installedSize;
break;
}
case ProcessorCacheLevelEnum.L3:
{
processor.L3Size = installedSize;
break;
}
}
}
}
processors.Add(processor);
index++;
}
}
return processors;
}
private enum ProcessorCacheLevelEnum
{
L1 = 3,
L2 = 4,
L3 = 5,
}
//private async ValueTask<Processor.Metric?> GetProcessorMetricAsync(CancellationToken cancellationToken)
//{
// var metric = new Processor.Metric();
// if (ProcessorTimeCounter is null)
// {
// ProcessorTimeCounter = new PerformanceCounter
// {
// CategoryName = "Processor",
// CounterName = "% Processor Time",
// InstanceName = "_Total"
// };
// metric.ProcessorUsagePercentage = ProcessorTimeCounter.NextValue();
// await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
// }
// metric.Timestamp = DateTime.Now;
// metric.ProcessorUsagePercentage = ProcessorTimeCounter?.NextValue();
// return metric;
//}
}
}

View file

@ -0,0 +1,118 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
using System.ServiceProcess;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class ServiceHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new ServiceList();
result.AddRange(GetServices());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<Service> GetServices()
{
var services = new List<Service>();
var serviceControllers = ServiceController.GetServices()?.OrderBy(s => s.DisplayName)?.ToList();
if (serviceControllers is null || serviceControllers.Any() is false) throw new InvalidOperationException("SERVICE Collection NULL");
foreach (var sc in serviceControllers)
{
var status = sc.Status switch
{
ServiceControllerStatus.Stopped => Service.ServiceStatus.Stopped,
ServiceControllerStatus.StartPending => Service.ServiceStatus.StartPending,
ServiceControllerStatus.StopPending => Service.ServiceStatus.StopPending,
ServiceControllerStatus.Running => Service.ServiceStatus.Running,
ServiceControllerStatus.ContinuePending => Service.ServiceStatus.ContinuePending,
ServiceControllerStatus.PausePending => Service.ServiceStatus.PausePending,
ServiceControllerStatus.Paused => Service.ServiceStatus.Paused,
_ => Service.ServiceStatus.Unknown
};
var mode = sc.StartType switch
{
ServiceStartMode.Boot => Service.ServiceMode.Boot,
ServiceStartMode.System => Service.ServiceMode.System,
ServiceStartMode.Automatic => Service.ServiceMode.Automatic,
ServiceStartMode.Manual => Service.ServiceMode.Manual,
ServiceStartMode.Disabled => Service.ServiceMode.Disabled,
_ => Service.ServiceMode.Unknown,
};
var service = new Service
{
Name = sc.ServiceName?.Trim(),
Display = sc.DisplayName?.Trim(),
Status = status,
StartMode = mode
};
services.Add(service);
}
// additional infos
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("SELECT processid, name, description, pathname, startname, delayedautostart from win32_service")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_service");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var services2 = new List<Service>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var service2 = new Service();
var properties = @object.GetPropertyHashes();
service2.Name = @object.GetValue<string>(properties, "name")?.Trim();
service2.ProcessId = @object.GetValue<uint>(properties, "processid");
service2.Description = @object.GetValue<string>(properties, "description")?.Trim();
service2.PathName = @object.GetValue<string>(properties, "pathname")?.Trim();
service2.Account = @object.GetValue<string>(properties, "startname")?.Trim();
service2.Delay = @object.GetValue<bool>(properties, "delayedautostart");
services2.Add(service2);
}
}
if (services2.Any() is false) return services;
foreach (var svc in services)
{
var map = services2.Where(p => p.Name == svc.Name).FirstOrDefault();
if (map is null) continue;
svc.ProcessId = map.ProcessId;
svc.Description = map.Description;
svc.PathName = map.PathName;
svc.Account = map.Account;
svc.Delay = map.Delay;
}
return services.OrderBy(x => x.Name).ToList();
}
}
}

View file

@ -0,0 +1,252 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class SessionHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new SessionList();
result.AddRange(GetSessions());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<Session> GetSessions()
{
var query = NativeMethods.GetSessions();
var sessions = new List<Session>();
foreach (var s in NativeMethods.GetSessions())
{
sessions.Add(new Session
{
Sid = s.SessionId.ToString(),
User = s.Username,
Type = s.Workstation,
Status = s.State.ToString(),
Remote = s.IPAddress
});
}
return sessions;
}
private static partial class NativeMethods
{
//public const int WTS_CURRENT_SESSION = -1;
[DllImport("wtsapi32.dll")]
static extern int WTSEnumerateSessions(
nint pServer,
[MarshalAs(UnmanagedType.U4)] int iReserved,
[MarshalAs(UnmanagedType.U4)] int iVersion,
ref nint pSessionInfo,
[MarshalAs(UnmanagedType.U4)] ref int iCount);
[DllImport("Wtsapi32.dll")]
private static extern bool WTSQuerySessionInformation(
nint pServer,
int iSessionID,
WTS_INFO_CLASS oInfoClass,
out nint pBuffer,
out uint iBytesReturned);
[DllImport("wtsapi32.dll")]
static extern void WTSFreeMemory(
nint pMemory);
[StructLayout(LayoutKind.Sequential)]
private struct WTS_CLIENT_ADDRESS
{
public int iAddressFamily;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public byte[] bAddress;
}
[StructLayout(LayoutKind.Sequential)]
private struct WTS_SESSION_INFO
{
public int iSessionID;
[MarshalAs(UnmanagedType.LPStr)]
public string sWinsWorkstationName;
public WTS_CONNECTSTATE_CLASS oState;
}
[StructLayout(LayoutKind.Sequential)]
private struct WTS_CLIENT_DISPLAY
{
public int iHorizontalResolution;
public int iVerticalResolution;
//1 = The display uses 4 bits per pixel for a maximum of 16 colors.
//2 = The display uses 8 bits per pixel for a maximum of 256 colors.
//4 = The display uses 16 bits per pixel for a maximum of 2^16 colors.
//8 = The display uses 3-byte RGB values for a maximum of 2^24 colors.
//16 = The display uses 15 bits per pixel for a maximum of 2^15 colors.
public int iColorDepth;
}
public enum WTS_CONNECTSTATE_CLASS
{
WTSActive,
WTSConnected,
WTSConnectQuery,
WTSShadow,
WTSDisconnected,
WTSIdle,
WTSListen,
WTSReset,
WTSDown,
WTSInit
}
public enum WTS_INFO_CLASS
{
WTSInitialProgram,
WTSApplicationName,
WTSWorkingDirectory,
WTSOEMId,
WTSSessionId,
WTSUserName,
WTSWinStationName,
WTSDomainName,
WTSConnectState,
WTSClientBuildNumber,
WTSClientName,
WTSClientDirectory,
WTSClientProductId,
WTSClientHardwareId,
WTSClientAddress,
WTSClientDisplay,
WTSClientProtocolType,
WTSIdleTime,
WTSLogonTime,
WTSIncomingBytes,
WTSOutgoingBytes,
WTSIncomingFrames,
WTSOutgoingFrames,
WTSClientInfo,
WTSSessionInfo,
WTSConfigInfo,
WTSValidationInfo,
WTSSessionAddressV4,
WTSIsRemoteSession
}
public class WTSSession
{
public int SessionId { get; set; }
public WTS_CONNECTSTATE_CLASS State { get; set; }
public string? Workstation { get; set; }
public string? IPAddress { get; set; }
public string? Username { get; set; }
public int HorizontalResolution { get; set; }
public int VerticalResolution { get; set; }
public int ColorDepth { get; set; }
public string? ClientApplicationDirectory { get; set; }
}
public static IEnumerable<WTSSession> GetSessions()
{
var sessions = new List<WTSSession>();
var pServer = nint.Zero;
var pSessionInfo = nint.Zero;
try
{
var count = 0;
var sessionCount = WTSEnumerateSessions(pServer, 0, 1, ref pSessionInfo, ref count);
var dataSize = (long)Marshal.SizeOf(typeof(WTS_SESSION_INFO));
var current = (long)pSessionInfo;
if (sessionCount <= 0)
return sessions;
for (int i = 0; i < count; i++)
{
if (Marshal.PtrToStructure((nint)current, typeof(WTS_SESSION_INFO)) is not object sessionStructure)
continue;
var sessionInfo = (WTS_SESSION_INFO)sessionStructure;
current += dataSize;
var session = new WTSSession
{
SessionId = sessionInfo.iSessionID,
State = sessionInfo.oState,
Workstation = sessionInfo.sWinsWorkstationName,
};
var returned = (uint)0;
// get terminal user address
var address = nint.Zero;
var clientAddress = new WTS_CLIENT_ADDRESS();
if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientAddress, out address, out returned) == true)
{
if (Marshal.PtrToStructure(address, clientAddress.GetType()) is not object addressStructure)
break;
clientAddress = (WTS_CLIENT_ADDRESS)addressStructure;
session.IPAddress = clientAddress.bAddress[2] + "." + clientAddress.bAddress[3] + "." + clientAddress.bAddress[4] + "." + clientAddress.bAddress[5];
}
// get terminal user name
if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSUserName, out address, out returned) == true)
{
session.Username = Marshal.PtrToStringAnsi(address);
}
// get terminal user domain name
if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSDomainName, out address, out returned) == true)
{
session.Username = Marshal.PtrToStringAnsi(address) + @"\" + session.Username;
}
// get terminal user display informations
var clientDisplay = new WTS_CLIENT_DISPLAY();
if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientDisplay, out address, out returned) == true)
{
if (Marshal.PtrToStructure(address, clientDisplay.GetType()) is not object displayStructure)
break;
clientDisplay = (WTS_CLIENT_DISPLAY)displayStructure;
session.HorizontalResolution = clientDisplay.iHorizontalResolution;
session.VerticalResolution = clientDisplay.iVerticalResolution;
session.ColorDepth = clientDisplay.iColorDepth;
}
// get terminal user application directory
if (WTSQuerySessionInformation(pServer, sessionInfo.iSessionID, WTS_INFO_CLASS.WTSClientDirectory, out address, out returned) == true)
{
session.ClientApplicationDirectory = Marshal.PtrToStringAnsi(address);
}
sessions.Add(session);
}
}
catch (Exception)
{
throw;
}
finally
{
WTSFreeMemory(pSessionInfo);
}
return sessions;
}
}
}
}

View file

@ -0,0 +1,119 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Microsoft.Win32;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
internal class SoftwareHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var x64 = Task.Run(() => ApplicationRegistryQuery(RegistryView.Registry64), cancellationToken);
var x86 = Task.Run(() => ApplicationRegistryQuery(RegistryView.Registry32), cancellationToken);
await Task.WhenAll(x64, x86).ConfigureAwait(false);
var result = new ApplicationList();
result.AddRange(x64.Result);
result.AddRange(x86.Result.Where(p => result.All(app => p.Name != app.Name && p.Version != app.Version)));
await sender.SendAsync(result, cancellationToken);
}
}
private static IEnumerable<Application> ApplicationRegistryQuery(RegistryView registryView)
{
using var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView);
using var key = registry.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\", RegistryKeyPermissionCheck.ReadSubTree, RegistryRights.ReadKey);
if (key is null) throw new NullReferenceException(nameof(key));
var apps = new List<Application>();
var architecture = registryView switch
{
RegistryView.Registry32 => Architecture.X86,
_ => Architecture.X64
};
foreach (string name in key.GetSubKeyNames())
{
using var query = key.OpenSubKey(name);
if (query is null) continue;
var app = new Application
{
Architecture = architecture
};
if (query.GetValue("DisplayName")?.ToString()?.Trim() is string displayName && string.IsNullOrWhiteSpace(displayName) is false)
{
app.Name = displayName;
}
if (query.GetValue("Publisher")?.ToString()?.Trim() is string publisher && string.IsNullOrWhiteSpace(publisher) is false)
{
app.Publisher = publisher;
}
if (query.GetValue("DisplayVersion")?.ToString()?.Trim() is string version && string.IsNullOrWhiteSpace(version) is false)
{
app.Version = version;
}
if (query.GetValue("InstallLocation")?.ToString()?.Trim() is string location && string.IsNullOrWhiteSpace(location) is false)
{
app.Location = location;
}
if (query.GetValue("InstallSource")?.ToString()?.Trim() is string source && string.IsNullOrWhiteSpace(source) is false)
{
app.Source = source;
}
if (query.GetValue("UninstallString")?.ToString()?.Trim() is string uninstall && string.IsNullOrWhiteSpace(uninstall) is false)
{
app.Uninstall = uninstall;
}
if (app.Uninstall is null)
{
if (query.GetValue("UninstallString_Hidden")?.ToString()?.Trim() is string uninstall2 && string.IsNullOrWhiteSpace(uninstall2) is false)
{
app.Uninstall = uninstall2;
}
}
if (query.GetValue("InstallDate")?.ToString()?.Trim() is string installDate)
{
if (DateTime.TryParseExact(installDate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime valid))
{
app.InstallDate = valid;
}
if (app.InstallDate is null)
{
if (DateTime.TryParseExact(installDate, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime valid2))
{
app.InstallDate = valid2;
}
}
}
if (app.Name is not null)
{
apps.Add(app);
}
}
return apps;
}
}
}

View file

@ -0,0 +1,308 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
using static Insight.Agent.Messages.PhysicalDisk;
using static Insight.Agent.Messages.StoragePool;
using static Insight.Agent.Messages.VirtualDisk;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class StoragePoolHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new StoragePoolList();
result.AddRange(GetStoragePool());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<StoragePool> GetStoragePool()
{
if (Environment.OSVersion.Version.Major < 6 || Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor < 2)
{
throw new PlatformNotSupportedException();
}
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\microsoft\windows\storage"),
Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname, resiliencysettingnamedefault, isprimordial, isreadonly, isclustered, size, allocatedsize, logicalsectorsize, operationalstatus, healthstatus from msft_storagepool")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from msft_storagepool");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var pools = new List<StoragePool>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var pool = new StoragePool();
var properties = @object.GetPropertyHashes();
pool.UniqueId = @object.GetValue<string>(properties, "uniqueid")?.Trim();
pool.Name = @object.GetValue<string>(properties, "name")?.Trim();
pool.FriendlyName = @object.GetValue<string>(properties, "friendlyname")?.Trim();
if (@object.TryGetValue<ushort[]>(properties, "operationalstatus", out var operationals) && operationals is not null)
{
pool.States = operationals.Select(p => (StoragePool.OperationalState)p).ToList();
}
pool.Health = (StoragePool.HealthState)@object.GetValue<ushort>(properties, "healthstatus");
pool.RetireMissingPhysicalDisks = (RetireMissingPhysicalDisksEnum)@object.GetValue<ushort>(properties, "retiremissingphysicaldisks");
pool.Resiliency = @object.GetValue<string>(properties, "resiliencysettingnamedefault")?.Trim();
pool.IsPrimordial = @object.GetValue<bool>(properties, "isprimordial");
pool.IsReadOnly = @object.GetValue<bool>(properties, "isreadonly");
pool.IsClustered = @object.GetValue<bool>(properties, "isclustered");
pool.Size = @object.GetValue<ulong>(properties, "size");
pool.AllocatedSize = @object.GetValue<ulong>(properties, "allocatedsize");
pool.SectorSize = @object.GetValue<ulong>(properties, "logicalsectorsize");
if (@object.GetValue<string>(properties, "objectid") is string objectId)
{
pool.PhysicalDisks = QueryPhysicalDisksByStoragePool(objectId);
pool.VirtualDisks = QueryVirtualDisksByStoragePool(objectId);
}
pools.Add(pool);
}
}
return pools;
}
private static List<PhysicalDisk> GetPhysicalDisks()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\microsoft\windows\storage"),
Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname from msft_physicaldisk")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from msft_physicaldisk");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var disks = new List<PhysicalDisk>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var disk = new PhysicalDisk();
var properties = @object.GetPropertyHashes();
disk.UniqueId = @object.GetValue<string>(properties, "uniqueid")?.Trim();
disk.FriendlyName = @object.GetValue<string>(properties, "friendlyname")?.Trim();
disk.Manufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
disk.Model = @object.GetValue<string>(properties, "model")?.Trim();
disk.MediaType = @object.GetValue<ushort>(properties, "mediatype");
disk.BusType = @object.GetValue<ushort>(properties, "bustype");
if (@object.TryGetValue<ushort[]>(properties, "operationalstatus", out var operationals) && operationals is not null)
{
disk.States = operationals.Select(p => (PhysicalDisk.OperationalState)p).ToList();
}
disk.Health = (PhysicalDisk.HealthState)@object.GetValue<ushort>(properties, "healthstatus");
if (@object.TryGetValue<ushort[]>(properties, "supportedusages", out var supportedusages) && supportedusages is not null)
{
disk.SupportedUsages = supportedusages.Select(p => (SupportedUsagesEnum)p).ToList();
}
disk.Usage = @object.GetValue<ushort>(properties, "usage");
disk.PhysicalLocation = @object.GetValue<string>(properties, "physicallocation")?.Trim();
disk.SerialNumber = @object.GetValue<string>(properties, "serialnumber")?.Trim();
disk.FirmwareVersion = @object.GetValue<string>(properties, "firmwareversion")?.Trim();
disk.Size = @object.GetValue<ulong>(properties, "size");
disk.AllocatedSize = @object.GetValue<ulong>(properties, "allocatedsize");
disk.LogicalSectorSize = @object.GetValue<ulong>(properties, "logicalsectorsize");
disk.PhysicalSectorSize = @object.GetValue<ulong>(properties, "physicalsectorsize");
disk.VirtualDiskFootprint = @object.GetValue<ulong>(properties, "virtualdiskfootprint");
disks.Add(disk);
}
}
return disks;
}
private static List<VirtualDisk> GetVirtualDisks()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\microsoft\windows\storage"),
Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname, access, provisioningtype, physicaldiskredundancy, resiliencysettingname, isdeduplicationenabled, issnapshot, operationalstatus, healthstatus, size, allocatedsize, footprintonpool, readcachesize, writecachesize from msft_virtualdisk")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from msft_virtualdisk");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var disks = new List<VirtualDisk>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var disk = new VirtualDisk();
var properties = @object.GetPropertyHashes();
disk.UniqueId = @object.GetValue<string>(properties, "uniqueid")?.Trim();
disk.Name = @object.GetValue<string>(properties, "name")?.Trim();
disk.FriendlyName = @object.GetValue<string>(properties, "friendlyname")?.Trim();
disk.AccessType = (AccessTypeEnum)@object.GetValue<ushort>(properties, "access");
disk.ProvisioningType = (ProvisioningTypeEnum)@object.GetValue<ushort>(properties, "provisioningtype");
disk.PhysicalDiskRedundancy = @object.GetValue<ushort>(properties, "physicaldiskredundancy");
disk.ResiliencySettingName = @object.GetValue<string>(properties, "resiliencysettingname")?.Trim();
disk.Deduplication = @object.GetValue<bool>(properties, "isdeduplicationenabled");
disk.IsSnapshot = @object.GetValue<bool>(properties, "issnapshot");
if (@object.TryGetValue<ushort[]>(properties, "operationalstatus", out var operationals) && operationals is not null)
{
disk.States = operationals.Select(p => (VirtualDisk.OperationalState)p).ToList();
}
disk.Health = (VirtualDisk.HealthState)@object.GetValue<ushort>(properties, "healthstatus");
disk.Size = @object.GetValue<ulong>(properties, "size");
disk.AllocatedSize = @object.GetValue<ulong>(properties, "allocatedsize");
disk.FootprintOnPool = @object.GetValue<ulong>(properties, "footprintonpool");
disk.ReadCacheSize = @object.GetValue<ulong>(properties, "readcachesize");
disk.WriteCacheSize = @object.GetValue<ulong>(properties, "writecachesize");
disks.Add(disk);
}
}
return disks;
}
private static List<PhysicalDisk> QueryPhysicalDisksByStoragePool(string storagePoolObjectId)
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\microsoft\windows\storage"),
Query = new ObjectQuery("ASSOCIATORS OF {MSFT_StoragePool.ObjectId=\"" + Helpers.EscapeWql(storagePoolObjectId) + "\"} WHERE AssocClass = MSFT_StoragePoolToPhysicalDisk")
};
if (searcher.TryGet(out var collection) is false) throw new InvalidOperationException("WMI Collection NULL");
var disks = new List<PhysicalDisk>();
using (collection)
{
foreach (ManagementObject @object in collection)
{
var disk = new PhysicalDisk();
var properties = @object.GetPropertyHashes();
disk.UniqueId = @object.GetValue<string>(properties, "uniqueid")?.Trim();
disk.DeviceId = @object.GetValue<string>(properties, "deviceid")?.Trim();
disk.FriendlyName = @object.GetValue<string>(properties, "friendlyname")?.Trim();
disk.Manufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
disk.Model = @object.GetValue<string>(properties, "model")?.Trim();
disk.MediaType = @object.GetValue<ushort>(properties, "mediatype");
disk.BusType = @object.GetValue<ushort>(properties, "bustype");
if (@object.TryGetValue<ushort[]>(properties, "operationalstatus", out var operationals) && operationals is not null)
{
disk.States = operationals.Select(p => (PhysicalDisk.OperationalState)p).ToList();
}
disk.Health = (PhysicalDisk.HealthState)@object.GetValue<ushort>(properties, "healthstatus");
if (@object.TryGetValue<ushort[]>(properties, "supportedusages", out var supportedusages) && supportedusages is not null)
{
disk.SupportedUsages = supportedusages.Select(p => (SupportedUsagesEnum)p).ToList();
}
disk.Usage = @object.GetValue<ushort>(properties, "usage");
disk.PhysicalLocation = @object.GetValue<string>(properties, "physicallocation")?.Trim();
disk.SerialNumber = @object.GetValue<string>(properties, "serialnumber")?.Trim();
disk.FirmwareVersion = @object.GetValue<string>(properties, "firmwareversion")?.Trim();
disk.Size = @object.GetValue<ulong>(properties, "size");
disk.AllocatedSize = @object.GetValue<ulong>(properties, "allocatedsize");
disk.LogicalSectorSize = @object.GetValue<ulong>(properties, "logicalsectorsize");
disk.PhysicalSectorSize = @object.GetValue<ulong>(properties, "physicalsectorsize");
disk.VirtualDiskFootprint = @object.GetValue<ulong>(properties, "virtualdiskfootprint");
disks.Add(disk);
}
}
return disks;
}
private static List<VirtualDisk> QueryVirtualDisksByStoragePool(string storagePoolObjectId)
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\microsoft\windows\storage"),
Query = new ObjectQuery("ASSOCIATORS OF {MSFT_StoragePool.ObjectId=\"" + Helpers.EscapeWql(storagePoolObjectId) + "\"} WHERE AssocClass = MSFT_StoragePoolToVirtualDisk")
};
if (searcher.TryGet(out var collection) is false) throw new InvalidOperationException("WMI Collection NULL");
var disks = new List<VirtualDisk>();
using (collection)
{
foreach (ManagementObject @object in collection)
{
var disk = new VirtualDisk();
var properties = @object.GetPropertyHashes();
disk.UniqueId = @object.GetValue<string>(properties, "uniqueid")?.Trim();
disk.Name = @object.GetValue<string>(properties, "name")?.Trim();
disk.FriendlyName = @object.GetValue<string>(properties, "friendlyname")?.Trim();
disk.AccessType = (AccessTypeEnum)@object.GetValue<ushort>(properties, "access");
disk.ProvisioningType = (ProvisioningTypeEnum)@object.GetValue<ushort>(properties, "provisioningtype");
disk.PhysicalDiskRedundancy = @object.GetValue<ushort>(properties, "physicaldiskredundancy");
disk.ResiliencySettingName = @object.GetValue<string>(properties, "resiliencysettingname")?.Trim();
disk.Deduplication = @object.GetValue<bool>(properties, "isdeduplicationenabled");
disk.IsSnapshot = @object.GetValue<bool>(properties, "issnapshot");
if (@object.TryGetValue<ushort[]>(properties, "operationalstatus", out var operationals) && operationals is not null)
{
disk.States = operationals.Select(p => (VirtualDisk.OperationalState)p).ToList();
}
disk.Health = (VirtualDisk.HealthState)@object.GetValue<ushort>(properties, "healthstatus");
disk.Size = @object.GetValue<ulong>(properties, "size");
disk.AllocatedSize = @object.GetValue<ulong>(properties, "allocatedsize");
disk.FootprintOnPool = @object.GetValue<ulong>(properties, "footprintonpool");
disk.ReadCacheSize = @object.GetValue<ulong>(properties, "readcachesize");
disk.WriteCacheSize = @object.GetValue<ulong>(properties, "writecachesize");
disks.Add(disk);
}
}
return disks;
}
}
}

View file

@ -0,0 +1,175 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Microsoft.Win32;
using System.Collections;
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class SystemInfoHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
await sender.SendAsync(GetSystem(), cancellationToken);
}
}
private static SystemInfo GetSystem()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select lastbootuptime, localdatetime, numberofprocesses from win32_operatingsystem")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_operatingsystem");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var system = new SystemInfo();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var properties = @object.GetPropertyHashes();
if (@object.TryGetValue<object>(properties, "lastbootuptime", out var lastbootuptime))
{
system.LastBootUpTime = ManagementDateTimeConverter.ToDateTime(lastbootuptime?.ToString());
}
if (@object.TryGetValue<object>(properties, "localdatetime", out var localdatetime))
{
system.LocalDateTime = ManagementDateTimeConverter.ToDateTime(localdatetime?.ToString());
}
system.Processes = @object.GetValue<uint>(properties, "numberofprocesses");
break;
}
}
system.License = GetWindowsProductKeyFromRegistry();
return system;
}
private static string GetWindowsProductKeyFromRegistry()
{
var localKey =
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Environment.Is64BitOperatingSystem
? RegistryView.Registry64
: RegistryView.Registry32);
var registryKeyValue = localKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")?.GetValue("DigitalProductId");
if (registryKeyValue == null)
return "Failed to get DigitalProductId from registry";
var digitalProductId = (byte[])registryKeyValue;
localKey.Close();
var isWin8OrUp =
Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2
||
Environment.OSVersion.Version.Major > 6;
return GetWindowsProductKeyFromDigitalProductId(digitalProductId,
isWin8OrUp ? DigitalProductIdVersion.Windows8AndUp : DigitalProductIdVersion.UpToWindows7);
}
private static string GetWindowsProductKeyFromDigitalProductId(byte[] digitalProductId, DigitalProductIdVersion digitalProductIdVersion)
{
var productKey = digitalProductIdVersion == DigitalProductIdVersion.Windows8AndUp
? DecodeProductKeyWin8AndUp(digitalProductId)
: DecodeProductKey(digitalProductId);
return productKey;
}
private static string DecodeProductKey(byte[] digitalProductId)
{
const int keyStartIndex = 52;
const int keyEndIndex = keyStartIndex + 15;
var digits = new[]
{
'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R',
'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9',
};
const int decodeLength = 29;
const int decodeStringLength = 15;
var decodedChars = new char[decodeLength];
var hexPid = new ArrayList();
for (var i = keyStartIndex; i <= keyEndIndex; i++)
{
hexPid.Add(digitalProductId[i]);
}
for (var i = decodeLength - 1; i >= 0; i--)
{
// Every sixth char is a separator.
if ((i + 1) % 6 == 0)
{
decodedChars[i] = '-';
}
else
{
// Do the actual decoding.
var digitMapIndex = 0;
for (var j = decodeStringLength - 1; j >= 0; j--)
{
var byteValue = digitMapIndex << 8 | (byte)hexPid[j];
hexPid[j] = (byte)(byteValue / 24);
digitMapIndex = byteValue % 24;
decodedChars[i] = digits[digitMapIndex];
}
}
}
return new string(decodedChars);
}
private static string DecodeProductKeyWin8AndUp(byte[] digitalProductId)
{
var key = string.Empty;
const int keyOffset = 52;
var isWin8 = (byte)(digitalProductId[66] / 6 & 1);
digitalProductId[66] = (byte)(digitalProductId[66] & 0xf7 | (isWin8 & 2) * 4);
const string digits = "BCDFGHJKMPQRTVWXY2346789";
var last = 0;
for (var i = 24; i >= 0; i--)
{
var current = 0;
for (var j = 14; j >= 0; j--)
{
current = current * 256;
current = digitalProductId[j + keyOffset] + current;
digitalProductId[j + keyOffset] = (byte)(current / 24);
current = current % 24;
last = current;
}
key = digits[current] + key;
}
var keypart1 = key.Substring(1, last);
var keypart2 = key.Substring(last + 1, key.Length - (last + 1));
key = keypart1 + "N" + keypart2;
for (var i = 5; i < key.Length; i += 6)
{
key = key.Insert(i, "-");
}
return key;
}
private enum DigitalProductIdVersion
{
UpToWindows7,
Windows8AndUp
}
}
}

View file

@ -0,0 +1,130 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using WUApiLib;
using static Insight.Agent.Messages.Update;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class UpdateHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
await sender.SendAsync(GetUpdates(), cancellationToken);
}
}
private static UpdateList GetUpdates()
{
return new UpdateList
{
Installed = QueryInstalledUpdates(),
Pending = QueryPendingUpdates()
};
}
private static List<Update> QueryInstalledUpdates()
{
var updates = new List<Update>();
var session = new UpdateSessionClass();
var searcher = session.CreateUpdateSearcher();
searcher.Online = false;
var count = searcher.GetTotalHistoryCount();
var result = searcher.QueryHistory(0, count);
foreach (IUpdateHistoryEntry wupdate in result)
{
var update = new Update
{
Id = wupdate.UpdateIdentity.UpdateID,
Date = wupdate.Date,
Name = wupdate.Title,
Description = wupdate.Description,
Result = wupdate.ResultCode switch
{
OperationResultCode.orcNotStarted => OsUpdateResultCodeEnum.NotStarted,
OperationResultCode.orcInProgress => OsUpdateResultCodeEnum.InProgress,
OperationResultCode.orcSucceeded => OsUpdateResultCodeEnum.Succeeded,
OperationResultCode.orcSucceededWithErrors => OsUpdateResultCodeEnum.SucceededWithErrors,
OperationResultCode.orcFailed => OsUpdateResultCodeEnum.Failed,
OperationResultCode.orcAborted => OsUpdateResultCodeEnum.Aborted,
_ => null
},
SupportUrl = wupdate.SupportUrl,
};
try
{
var rx = new Regex(@"KB(\d+)");
update.Hotfix = rx.Match(wupdate.Title).Value;
}
catch (Exception)
{
}
updates.Add(update);
}
return updates;
}
private static List<Update> QueryPendingUpdates()
{
var updates = new List<Update>();
var session = new UpdateSessionClass();
var searcher = session.CreateUpdateSearcher();
searcher.Online = true;
var result = searcher.Search("IsInstalled=0");
foreach (IUpdate wupdate in result.Updates)
{
var update = new Update
{
Id = wupdate.Identity.UpdateID,
Type = wupdate.Type switch
{
UpdateType.utSoftware => OsUpdateTypeEnum.Software,
UpdateType.utDriver => OsUpdateTypeEnum.Driver,
_ => null
},
Date = wupdate.LastDeploymentChangeTime,
Name = wupdate.Title,
Description = wupdate.Description,
SupportUrl = wupdate.SupportUrl,
Size = wupdate.MaxDownloadSize,
IsDownloaded = wupdate.IsDownloaded,
CanRequestUserInput = wupdate.InstallationBehavior.CanRequestUserInput,
RebootBehavior = wupdate.InstallationBehavior.RebootBehavior switch
{
InstallationRebootBehavior.irbNeverReboots => OsUpdateRebootBehaviorEnum.NeverReboots,
InstallationRebootBehavior.irbAlwaysRequiresReboot => OsUpdateRebootBehaviorEnum.AlwaysRequiresReboot,
InstallationRebootBehavior.irbCanRequestReboot => OsUpdateRebootBehaviorEnum.CanRequestReboot,
_ => null
},
};
if (wupdate.KBArticleIDs.Count > 0)
{
foreach (var id in wupdate.KBArticleIDs)
{
update.Hotfix = $"KB{id}";
break;
}
}
updates.Add(update);
}
return updates;
}
}
}

View file

@ -0,0 +1,188 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class UserHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new UserList();
result.AddRange(GetUsers());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<User> GetUsers()
{
var users = QueryUsers();
var groups = GetGroups();
var usergrouping = QueryUserGroupMaps();
foreach (var u in users)
{
u.Groups = new List<Group>();
foreach (var ug in usergrouping.Where(ug => ug.UserDomain == u.Domain && ug.UserName == u.Name))
{
var grps = groups.Where(g => g.Domain == ug.GroupDomain && g.Name == ug.GroupName);
if (grps is not null)
{
u.Groups.AddRange(grps);
}
}
}
return users;
}
private static List<Group> GetGroups()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select sid, domain, name, description, localaccount from win32_group")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_group");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var groups = new List<Group>();
using (collection)
{
foreach (ManagementObject @object in collection)
{
var group = new Group();
var properties = @object.GetPropertyHashes();
group.Sid = @object.GetValue<string>(properties, "sid")?.Trim();
group.Domain = @object.GetValue<string>(properties, "domain")?.Trim();
group.Name = @object.GetValue<string>(properties, "name")?.Trim();
group.Description = @object.GetValue<string>(properties, "description")?.Trim();
group.LocalAccount = @object.GetValue<bool>(properties, "localaccount");
groups.Add(group);
}
}
return groups.OrderBy(x => x.Name)?.ToList();
}
private static List<User> QueryUsers()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select sid, name, fullname, description, domain, localaccount, disabled, lockout, status, passwordchangeable, passwordexpires, passwordrequired from win32_useraccount")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_useraccount");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var users = new List<User>();
using (collection)
{
foreach (ManagementObject @object in collection)
{
var user = new User();
var properties = @object.GetPropertyHashes();
user.Sid = @object.GetValue<string>(properties, "sid")?.Trim();
user.Name = @object.GetValue<string>(properties, "name")?.Trim();
user.FullName = @object.GetValue<string>(properties, "fullname")?.Trim();
user.Description = @object.GetValue<string>(properties, "description")?.Trim();
user.Domain = @object.GetValue<string>(properties, "domain")?.Trim();
user.LocalAccount = @object.GetValue<bool>(properties, "localaccount");
user.Disabled = @object.GetValue<bool>(properties, "disabled");
user.Lockout = @object.GetValue<bool>(properties, "lockout");
user.Status = @object.GetValue<string>(properties, "status")?.Trim();
user.PasswordChangeable = @object.GetValue<bool>(properties, "passwordchangeable");
user.PasswordExpires = @object.GetValue<bool>(properties, "passwordexpires");
user.PasswordRequired = @object.GetValue<bool>(properties, "passwordrequired");
users.Add(user);
}
}
return users;
}
private static List<UserGroupMap> QueryUserGroupMaps()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select groupcomponent, partcomponent from win32_groupuser")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_groupuser");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var usergroups = new List<UserGroupMap>();
using (collection)
{
foreach (ManagementObject @object in collection)
{
var usergroup = new UserGroupMap();
var properties = @object.GetPropertyHashes();
var raw = @object.GetValue<string>(properties, "groupcomponent");
var split = raw?.Split(".Domain=")[1]?.Split(",Name=");
if (split is not null && split.Length > 1)
{
usergroup.GroupDomain = split[0].TrimStart('"').TrimEnd('"');
usergroup.GroupName = split[1].TrimStart('"').TrimEnd('"');
}
raw = @object.GetValue<string>(properties, "partcomponent");
split = raw?.Split(".Domain=")[1]?.Split(",Name=");
if (split is not null && split.Length > 1)
{
usergroup.UserDomain = split[0].TrimStart('"').TrimEnd('"');
usergroup.UserName = split[1].TrimStart('"').TrimEnd('"');
}
usergroups.Add(usergroup);
}
}
return usergroups;
}
private class UserGroupMap
{
public string? GroupDomain { get; set; }
public string? GroupName { get; set; }
public string? UserDomain { get; set; }
public string? UserName { get; set; }
}
}
}

View file

@ -0,0 +1,64 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class VideocardHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new VideocardList();
result.AddRange(GetVideocards());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<Videocard> GetVideocards()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\cimv2"),
Query = new ObjectQuery("select deviceid, name, adapterram, driverdate, driverversion from win32_videocontroller")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from win32_videocontroller");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var videocards = new List<Videocard>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var videocard = new Videocard();
var properties = @object.GetPropertyHashes();
videocard.DeviceId = @object.GetValue<string>(properties, "deviceid")?.Trim();
videocard.Model = @object.GetValue<string>(properties, "name")?.Trim();
if (@object.TryGetValue<object>(properties, "driverdate", out var driverdate))
{
videocard.DriverDate = ManagementDateTimeConverter.ToDateTime(driverdate?.ToString());
}
videocard.DriverVersion = @object.GetValue<string>(properties, "driverversion")?.Trim();
videocards.Add(videocard);
}
}
return videocards;
}
}
}

View file

@ -0,0 +1,359 @@
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using System.Management;
using System.Runtime.Versioning;
using static Insight.Agent.Messages.VirtualMaschine;
using static Insight.Agent.Messages.VirtualMaschineConfiguration;
namespace Insight.Agent.Network.Handlers
{
[SupportedOSPlatform("windows")]
public class VirtualMaschineHandler : IAgentMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
{
if (message is GetInventory)
{
var result = new VirtualMaschineList();
result.AddRange(GetVirtualMaschines());
await sender.SendAsync(result, cancellationToken);
}
}
private static List<VirtualMaschine> GetVirtualMaschines()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\virtualization\v2"),
Query = new ObjectQuery("select * msvm_computersystem")
};
if (searcher.TryGet(out var computersystems) is false)
{
searcher.Query = new ObjectQuery("select * from msvm_computersystem");
if (searcher.TryGet(out computersystems) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var vms = new List<VirtualMaschine>();
using (computersystems)
{
foreach (ManagementObject cs in computersystems.Cast<ManagementObject>())
{
var vm = new VirtualMaschine();
var csProperties = cs.GetPropertyHashes();
var vmId = cs.GetValue<string>(csProperties, "name")?.Trim();
if (Guid.TryParse(vmId, out var vmGuid) is false) continue;
vm.Id = vmGuid;
vm.ProcessId = cs.GetValue<uint>(csProperties, "processid");
vm.Caption = cs.GetValue<string>(csProperties, "caption")?.Trim();
vm.Name = cs.GetValue<string>(csProperties, "elementname")?.Trim();
vm.Enabled = (EnabledEnum)cs.GetValue<ushort>(csProperties, "enabledstate");
vm.EnabledDefault = (EnabledDefaultEnum)cs.GetValue<ushort>(csProperties, "enableddefault");
vm.HealthState = (HealthStatusEnum)cs.GetValue<ushort>(csProperties, "healthstate");
vm.Status = cs.GetValue<string>(csProperties, "status")?.Trim();
vm.OnTime = cs.GetValue<ulong>(csProperties, "ontimeinmilliseconds");
vm.ReplicationMode = cs.GetValue<ushort>(csProperties, "replicationmode");
vm.ReplicationState = (ReplicationStateEnum)cs.GetValue<ushort>(csProperties, "replicationstate");
vm.ReplicationHealth = (ReplicationHealthEnum)cs.GetValue<ushort>(csProperties, "replicationhealth");
if (cs.TryGetValue<object>(csProperties, "installdate", out var installdate))
{
vm.InstallDate = ManagementDateTimeConverter.ToDateTime(installdate?.ToString());
}
if (cs.TryGetValue<object>(csProperties, "timeoflastconfigurationchange", out var timeoflastconfigurationchange))
{
vm.TimeOfLastConfigurationChange = ManagementDateTimeConverter.ToDateTime(timeoflastconfigurationchange?.ToString());
}
if (cs.TryGetValue<object>(csProperties, "timeoflaststatechange", out var timeoflaststatechange))
{
vm.TimeOfLastStateChange = ManagementDateTimeConverter.ToDateTime(timeoflaststatechange?.ToString());
}
if (cs.TryGetValue<object>(csProperties, "lastreplicationtime", out var lastreplicationtime))
{
vm.LastReplicationTime = ManagementDateTimeConverter.ToDateTime(lastreplicationtime?.ToString());
}
var summaryinformation = cs.GetRelated("msvm_summaryinformation");
using (summaryinformation)
{
foreach (ManagementObject si in summaryinformation.Cast<ManagementObject>())
{
var siProperties = si.GetPropertyHashes();
vm.Notes = si.GetValue<string>(siProperties, "Notes");
vm.ConfigurationVersion = si.GetValue<string>(siProperties, "Version");
vm.IntegrationServicesVersionState = (IntegrationServicesVersionStateEnum)si.GetValue<ushort>(siProperties, "IntegrationServicesVersionState");
vm.GuestOperatingSystem = si.GetValue<string>(siProperties, "GuestOperatingSystem");
vm.NumberOfProcessors = si.GetValue<ushort>(siProperties, "NumberOfProcessors");
vm.ProcessorLoad = si.GetValue<ushort>(siProperties, "ProcessorLoad");
vm.MemoryAvailable = si.GetValue<int>(siProperties, "MemoryAvailable");
vm.MemoryUsage = si.GetValue<ulong>(siProperties, "MemoryUsage");
}
}
var virtualSystemSettingData = cs.GetRelated("Msvm_VirtualSystemSettingData");
using (virtualSystemSettingData)
{
var configs = new List<VirtualMaschineConfiguration>();
foreach (ManagementObject vssd in virtualSystemSettingData.Cast<ManagementObject>())
{
var vmc = new VirtualMaschineConfiguration();
var vssdProperties = vssd.GetPropertyHashes();
var vmcId = vssd.GetValue<string>(vssdProperties, "ConfigurationID")?.Trim();
if (Guid.TryParse(vmcId, out var vmcGuid) is false) continue;
vmc.Id = vmcGuid.ToString();
vmc.Type = vssd.GetValue<string>(vssdProperties, "VirtualSystemType");
vmc.Name = vssd.GetValue<string>(vssdProperties, "ElementName");
if (vssd.TryGetValue<object>(vssdProperties, "CreationTime", out var creationtime))
{
vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(creationtime?.ToString());
}
vmc.Generation = vssd.GetValue<string>(vssdProperties, "VirtualSystemSubType");
vmc.Architecture = vssd.GetValue<string>(vssdProperties, "Architecture");
vmc.AutomaticStartupAction = (AutomaticStartupActionEnum)vssd.GetValue<uint>(vssdProperties, "AutomaticStartupAction");
vmc.AutomaticShutdownAction = (AutomaticShutdownActionEnum)vssd.GetValue<uint>(vssdProperties, "AutomaticShutdownAction");
vmc.AutomaticRecoveryAction = (AutomaticRecoveryActionEnum)vssd.GetValue<uint>(vssdProperties, "AutomaticRecoveryAction");
vmc.AutomaticSnapshotsEnabled = vssd.GetValue<bool>(vssdProperties, "AutomaticSnapshotsEnabled");
//if (vssd.TryGetValue<object>(vssdProperties, "AutomaticStartupActionDelay", out var automaticstartupactiondelay))
//{
// vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(automaticstartupactiondelay?.ToString());
//}
vmc.BaseBoardSerialNumber = vssd.GetValue<string>(vssdProperties, "BaseBoardSerialNumber");
vmc.BIOSGUID = vssd.GetValue<string>(vssdProperties, "BIOSGUID");
vmc.BIOSSerialNumber = vssd.GetValue<string>(vssdProperties, "BIOSSerialNumber");
vmc.BootOrder = vssd.GetValue<ushort[]>(vssdProperties, "BootOrder");
vmc.ConfigurationDataRoot = vssd.GetValue<string>(vssdProperties, "ConfigurationDataRoot");
vmc.ConfigurationFile = vssd.GetValue<string>(vssdProperties, "ConfigurationFile");
vmc.GuestStateDataRoot = vssd.GetValue<string>(vssdProperties, "GuestStateDataRoot");
vmc.GuestStateFile = vssd.GetValue<string>(vssdProperties, "GuestStateFile");
vmc.SnapshotDataRoot = vssd.GetValue<string>(vssdProperties, "SnapshotDataRoot");
vmc.SuspendDataRoot = vssd.GetValue<string>(vssdProperties, "SuspendDataRoot");
vmc.SwapFileDataRoot = vssd.GetValue<string>(vssdProperties, "SwapFileDataRoot");
vmc.SecureBootEnabled = vssd.GetValue<bool>(vssdProperties, "SecureBootEnabled");
vmc.IsAutomaticSnapshot = vssd.GetValue<bool>(vssdProperties, "IsAutomaticSnapshot");
vmc.Notes = vssd.GetValue<string[]>(vssdProperties, "Notes");
if (vssd.GetValue<string>(vssdProperties, "Parent") is string parent)
{
using var vmcp = new ManagementObject(parent);
vmcp.Get();
if (Guid.TryParse(vmcp["ConfigurationID"]?.ToString(), out var parentGuid) is false) continue;
vmc.ParentId = parentGuid.ToString();
}
//var storageallocationsettingdata = cs.GetRelated("Msvm_StorageAllocationSettingData");
//using (storageallocationsettingdata)
//{
//}
configs.Add(vmc);
}
vm.Configurations = configs.GroupBy(p => p.Id).Select(p => p.First()).ToList();
}
vms.Add(vm);
}
}
return vms;
}
private static List<VirtualMaschine> QueryVirtualMaschines0()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\virtualization\v2"),
Query = new ObjectQuery("select * msvm_computersystem")
};
if (searcher.TryGet(out var computersystems) is false)
{
searcher.Query = new ObjectQuery("select * from msvm_computersystem");
if (searcher.TryGet(out computersystems) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var vms = new List<VirtualMaschine>();
using (computersystems)
{
foreach (ManagementObject cs in computersystems.Cast<ManagementObject>())
{
var vm = new VirtualMaschine();
var csProperties = cs.GetPropertyHashes();
var vmId = cs.GetValue<string>(csProperties, "name")?.Trim();
if (Guid.TryParse(vmId, out var vmGuid) is false) continue;
vm.Id = vmGuid;
vm.ProcessId = cs.GetValue<uint>(csProperties, "processid");
vm.Caption = cs.GetValue<string>(csProperties, "caption")?.Trim();
vm.Name = cs.GetValue<string>(csProperties, "elementname")?.Trim();
vm.Enabled = (EnabledEnum)cs.GetValue<ushort>(csProperties, "enabledstate");
vm.EnabledDefault = (EnabledDefaultEnum)cs.GetValue<ushort>(csProperties, "enableddefault");
vm.HealthState = (HealthStatusEnum)cs.GetValue<ushort>(csProperties, "healthstate");
vm.Status = cs.GetValue<string>(csProperties, "status")?.Trim();
vm.OnTime = cs.GetValue<ulong>(csProperties, "ontimeinmilliseconds");
vm.ReplicationMode = cs.GetValue<ushort>(csProperties, "replicationmode");
vm.ReplicationState = (ReplicationStateEnum)cs.GetValue<ushort>(csProperties, "replicationstate");
vm.ReplicationHealth = (ReplicationHealthEnum)cs.GetValue<ushort>(csProperties, "replicationhealth");
if (cs.TryGetValue<object>(csProperties, "installdate", out var installdate))
{
vm.InstallDate = ManagementDateTimeConverter.ToDateTime(installdate?.ToString());
}
if (cs.TryGetValue<object>(csProperties, "timeoflastconfigurationchange", out var timeoflastconfigurationchange))
{
vm.TimeOfLastConfigurationChange = ManagementDateTimeConverter.ToDateTime(timeoflastconfigurationchange?.ToString());
}
if (cs.TryGetValue<object>(csProperties, "timeoflaststatechange", out var timeoflaststatechange))
{
vm.TimeOfLastStateChange = ManagementDateTimeConverter.ToDateTime(timeoflaststatechange?.ToString());
}
if (cs.TryGetValue<object>(csProperties, "lastreplicationtime", out var lastreplicationtime))
{
vm.LastReplicationTime = ManagementDateTimeConverter.ToDateTime(lastreplicationtime?.ToString());
}
var summaryinformation = cs.GetRelated("msvm_summaryinformation");
using (summaryinformation)
{
foreach (ManagementObject si in summaryinformation.Cast<ManagementObject>())
{
var siProperties = si.GetPropertyHashes();
vm.Notes = si.GetValue<string>(siProperties, "Notes");
vm.ConfigurationVersion = si.GetValue<string>(siProperties, "Version");
vm.IntegrationServicesVersionState = (IntegrationServicesVersionStateEnum)si.GetValue<ushort>(siProperties, "IntegrationServicesVersionState");
vm.GuestOperatingSystem = si.GetValue<string>(siProperties, "GuestOperatingSystem");
vm.NumberOfProcessors = si.GetValue<ushort>(siProperties, "NumberOfProcessors");
vm.ProcessorLoad = si.GetValue<ushort>(siProperties, "ProcessorLoad");
vm.MemoryAvailable = si.GetValue<int>(siProperties, "MemoryAvailable");
vm.MemoryUsage = si.GetValue<ulong>(siProperties, "MemoryUsage");
}
}
var virtualSystemSettingData = cs.GetRelated("Msvm_VirtualSystemSettingData");
using (virtualSystemSettingData)
{
var configs = new List<VirtualMaschineConfiguration>();
foreach (ManagementObject vssd in virtualSystemSettingData.Cast<ManagementObject>())
{
var vmc = new VirtualMaschineConfiguration();
var vssdProperties = vssd.GetPropertyHashes();
var vmcId = vssd.GetValue<string>(vssdProperties, "ConfigurationID")?.Trim();
if (Guid.TryParse(vmcId, out var vmcGuid) is false) continue;
vmc.Id = vmcGuid.ToString();
vmc.Type = vssd.GetValue<string>(vssdProperties, "VirtualSystemType");
vmc.Name = vssd.GetValue<string>(vssdProperties, "ElementName");
if (vssd.TryGetValue<object>(vssdProperties, "CreationTime", out var creationtime))
{
vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(creationtime?.ToString());
}
vmc.Generation = vssd.GetValue<string>(vssdProperties, "VirtualSystemSubType");
vmc.Architecture = vssd.GetValue<string>(vssdProperties, "Architecture");
vmc.AutomaticStartupAction = (AutomaticStartupActionEnum)vssd.GetValue<uint>(vssdProperties, "AutomaticStartupAction");
//if (vssd.TryGetValue<object>(vssdProperties, "AutomaticStartupActionDelay", out var automaticstartupactiondelay))
//{
// vmc.CreationTime = ManagementDateTimeConverter.ToDateTime(automaticstartupactiondelay?.ToString());
//}
vmc.AutomaticShutdownAction = (AutomaticShutdownActionEnum)vssd.GetValue<uint>(vssdProperties, "AutomaticShutdownAction");
vmc.AutomaticRecoveryAction = (AutomaticRecoveryActionEnum)vssd.GetValue<uint>(vssdProperties, "AutomaticRecoveryAction");
vmc.AutomaticSnapshotsEnabled = vssd.GetValue<bool>(vssdProperties, "AutomaticSnapshotsEnabled");
vmc.BaseBoardSerialNumber = vssd.GetValue<string>(vssdProperties, "BaseBoardSerialNumber");
vmc.BIOSGUID = vssd.GetValue<string>(vssdProperties, "BIOSGUID");
vmc.BIOSSerialNumber = vssd.GetValue<string>(vssdProperties, "BIOSSerialNumber");
vmc.BootOrder = vssd.GetValue<ushort[]>(vssdProperties, "BootOrder");
vmc.ConfigurationDataRoot = vssd.GetValue<string>(vssdProperties, "ConfigurationDataRoot");
vmc.ConfigurationFile = vssd.GetValue<string>(vssdProperties, "ConfigurationFile");
vmc.GuestStateDataRoot = vssd.GetValue<string>(vssdProperties, "GuestStateDataRoot");
vmc.GuestStateFile = vssd.GetValue<string>(vssdProperties, "GuestStateFile");
vmc.SnapshotDataRoot = vssd.GetValue<string>(vssdProperties, "SnapshotDataRoot");
vmc.SuspendDataRoot = vssd.GetValue<string>(vssdProperties, "SuspendDataRoot");
vmc.SwapFileDataRoot = vssd.GetValue<string>(vssdProperties, "SwapFileDataRoot");
vmc.SecureBootEnabled = vssd.GetValue<bool>(vssdProperties, "SecureBootEnabled");
vmc.IsAutomaticSnapshot = vssd.GetValue<bool>(vssdProperties, "IsAutomaticSnapshot");
vmc.Notes = vssd.GetValue<string[]>(vssdProperties, "Notes");
vmc.ParentId = vssd.GetValue<string>(vssdProperties, "Parent");
var storageallocationsettingdata = cs.GetRelated("Msvm_StorageAllocationSettingData");
using (storageallocationsettingdata)
{
}
configs.Add(vmc);
}
configs = configs.GroupBy(p => p.Id).Select(p => p.First()).ToList();
if (configs.Any(p => p.ParentId is not null))
{
foreach (var conf in configs.Where(p => p.ParentId is not null))
{
using var parent = new ManagementObject(conf.ParentId);
parent.Get();
if (Guid.TryParse(parent["ConfigurationID"]?.ToString(), out var parentGuid) && configs.FirstOrDefault(p => p.Id == parentGuid.ToString()) is VirtualMaschineConfiguration parentConfig)
{
conf.ParentId = parentGuid.ToString();
parentConfig.Childs ??= new List<VirtualMaschineConfiguration>();
parentConfig.Childs.Add(conf);
}
else
{
conf.ParentId = null;
}
}
}
vm.Configurations = configs.Where(p => p.ParentId is null).ToList();
}
vms.Add(vm);
}
}
return vms;
}
}
}