diff --git a/Source/NETworkManager.Converters/IPScannerOSToStringConverter.cs b/Source/NETworkManager.Converters/IPScannerOSToStringConverter.cs
new file mode 100644
index 0000000000..2e1113a5a0
--- /dev/null
+++ b/Source/NETworkManager.Converters/IPScannerOSToStringConverter.cs
@@ -0,0 +1,72 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using NETworkManager.Localization.Resources;
+using NETworkManager.Models.Network;
+
+namespace NETworkManager.Converters;
+
+///
+/// Text and tooltip of the OS column of the IP Scanner: the Windows version if it was read (more precise), otherwise
+/// the guess from the TTL of the ping reply (see ).
+///
+public sealed class IPScannerOSToStringConverter : IMultiValueConverter
+{
+ ///
+ /// Gets the text or tooltip of the OS column.
+ ///
+ ///
+ /// [0] , [1] hops (), [2] the ping is running, [3] the guess was
+ /// enabled for the scan, [4] (null if not read), [5] the Windows host information
+ /// is still read.
+ ///
+ ///
+ ///
+ /// "ToolTip" to get the tooltip (version of Windows, or the hops of the guess), "Copy" for the clipboard (empty
+ /// without value).
+ ///
+ ///
+ /// Text ("..." while running, "-/-" without value) or tooltip (null without value).
+ public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
+ {
+ if (values is not { Length: 6 })
+ return null;
+
+ var osGuess = values[3] is true && values[0] is IPScannerOSGuess value ? value : IPScannerOSGuess.None;
+ var hops = values[1] is int hopsValue ? hopsValue : 0;
+ var isPingPending = values[3] is true && values[2] is true;
+ var windows = values[4] as WindowsHostInfo;
+ var isWindowsPending = values[5] is true;
+
+ var isToolTip = parameter as string == "ToolTip";
+
+ if (!string.IsNullOrEmpty(windows?.OS))
+ {
+ if (!isToolTip)
+ return windows.OS;
+
+ // E.g. "Pro, 10.0.26200.6584"
+ return string.IsNullOrEmpty(windows.Edition)
+ ? windows.Version?.ToString()
+ : $"{windows.Edition}, {windows.Version}";
+ }
+
+ if (osGuess != IPScannerOSGuess.None)
+ return isToolTip
+ ? string.Format(Strings.OSGuessBasedOnTheTTLXHops, hops)
+ : IPScannerOSGuessToStringConverter.ToLocalizedString(osGuess);
+
+ if (isToolTip)
+ return null;
+
+ if (parameter as string == "Copy")
+ return string.Empty;
+
+ return isPingPending || isWindowsPending ? "..." : "-/-";
+ }
+
+ public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
+ {
+ throw new NotImplementedException();
+ }
+}
diff --git a/Source/NETworkManager.Converters/IPScannerStatusToolTipConverter.cs b/Source/NETworkManager.Converters/IPScannerStatusToolTipConverter.cs
index 02d6e98d09..623fa75ef2 100644
--- a/Source/NETworkManager.Converters/IPScannerStatusToolTipConverter.cs
+++ b/Source/NETworkManager.Converters/IPScannerStatusToolTipConverter.cs
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
-using System.Net.NetworkInformation;
using System.Windows.Data;
using NETworkManager.Localization;
using NETworkManager.Localization.Resources;
@@ -11,8 +10,8 @@
namespace NETworkManager.Converters;
///
-/// Convert a result of the IP Scanner to the tooltip of its status icon: ping status with time and TTL, open ports,
-/// NetBIOS name and workgroup / domain - or whether the host answered a probe.
+/// Convert a result of the IP Scanner to a tooltip: the open ports (Open ports column), or whether the host answered
+/// a probe (status icons in the headers of the row details).
///
public sealed class IPScannerStatusToolTipConverter : IValueConverter
{
@@ -25,8 +24,8 @@ public sealed class IPScannerStatusToolTipConverter : IValueConverter
/// Convert a result of the IP Scanner to the tooltip of its status icon.
///
///
- /// , ports (), , or the
- /// of a host with the probe as .
+ /// Ports (), or the of a host with the probe
+ /// as .
///
///
/// Probe as name of (e.g. "ICMP").
@@ -36,18 +35,6 @@ public object Convert(object value, Type targetType, object parameter, CultureIn
{
switch (value)
{
- // Success (2 ms, TTL 64) / Timed out
- case PingInfo pingInfo:
- var status = ResourceTranslator.Translate(ResourceIdentifier.IPStatus, pingInfo.Status);
-
- if (pingInfo.Status != IPStatus.Success)
- return status;
-
- var time = Models.Network.Ping.TimeToString(pingInfo.Status, pingInfo.Time);
-
- // No TTL for IPv6
- return pingInfo.TTL > 0 ? $"{status} ({time}, {Strings.TTL} {pingInfo.TTL})" : $"{status} ({time})";
-
// Open: 22 (ssh), 80 (http) / No open ports found! (closed or timed out - the ports that are not open may
// be hidden, see IPScanner.GetShownPorts)
case List ports:
@@ -64,16 +51,6 @@ public object Convert(object value, Type targetType, object parameter, CultureIn
return $"{ResourceTranslator.Translate(ResourceIdentifier.PortState, PortState.Open)}: {list}";
- // Yes (PC01, WORKGROUP) / No
- case NetBIOSInfo netBIOSInfo:
- if (!netBIOSInfo.IsReachable)
- return Strings.No;
-
- var names = new[] { netBIOSInfo.ComputerName, netBIOSInfo.GroupName }
- .Where(x => !string.IsNullOrEmpty(x)).ToList();
-
- return names.Count == 0 ? Strings.Yes : $"{Strings.Yes} ({string.Join(", ", names)})";
-
// Answered / No answer
case IPScannerDetectionMethod detectedBy:
return Enum.TryParse(parameter as string, out var method) &&
diff --git a/Source/NETworkManager.Converters/PortOpenToStringConverter.cs b/Source/NETworkManager.Converters/PortOpenToStringConverter.cs
deleted file mode 100644
index e35fb6663f..0000000000
--- a/Source/NETworkManager.Converters/PortOpenToStringConverter.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-using System;
-using System.Globalization;
-using System.Windows.Data;
-using NETworkManager.Localization;
-using NETworkManager.Models.Network;
-
-namespace NETworkManager.Converters;
-
-///
-/// Convert a that indicates if a port is open to a translated or wise versa.
-///
-public sealed class PortOpenToStringConverter : IValueConverter
-{
- ///
- /// Convert a that indicates if a port is open to a translated .
- ///
- /// Port up as .
- ///
- ///
- ///
- /// Translated .
- public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
- {
- return value is not bool portState
- ? "-/-"
- : ResourceTranslator.Translate(ResourceIdentifier.PortState, portState ? PortState.Open : PortState.Closed);
- }
-
- ///
- /// !!! Method not implemented !!!
- ///
- ///
- ///
- ///
- ///
- ///
- public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
- {
- throw new NotImplementedException();
- }
-}
\ No newline at end of file
diff --git a/Source/NETworkManager.Converters/WindowsHostInfoToStringConverter.cs b/Source/NETworkManager.Converters/WindowsHostInfoToStringConverter.cs
new file mode 100644
index 0000000000..90d5cdac7f
--- /dev/null
+++ b/Source/NETworkManager.Converters/WindowsHostInfoToStringConverter.cs
@@ -0,0 +1,96 @@
+using System;
+using System.Globalization;
+using System.Windows.Data;
+using NETworkManager.Localization.Resources;
+using NETworkManager.Models.Network;
+using NETworkManager.Utilities;
+
+namespace NETworkManager.Converters;
+
+///
+/// Converts a value of the of an IP Scanner host to a for the
+/// result and the row details, "-/-" if there is none. The value is selected with the converter parameter:
+/// OS, Edition, Version, Role, ComputerName, Domain,
+/// Description, TimeOffset, Users (one per line, the error if they could not be read),
+/// SMB (dialect), SMBSigning (required / not required), Error (message of the NetApi error).
+///
+public sealed class WindowsHostInfoToStringConverter : IValueConverter
+{
+ ///
+ /// Text without a value: "-/-" (default), empty for Copy.
+ ///
+ public string NoValue { get; set; } = "-/-";
+
+ public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ var text = value is WindowsHostInfo info ? GetValue(info, parameter as string) : null;
+
+ return string.IsNullOrEmpty(text) ? NoValue : text;
+ }
+
+ ///
+ /// Gets a value of the Windows host information as text.
+ ///
+ /// Windows host information.
+ /// Name of the value, see .
+ /// Value, empty if there is none.
+ public static string GetValue(WindowsHostInfo info, string name)
+ {
+ return name switch
+ {
+ "OS" => info.OS,
+ "Edition" => info.Edition,
+ "Version" => info.Version?.ToString(),
+ "Role" => RoleToLocalizedString(info.Role),
+ "ComputerName" => info.ComputerName,
+ "Domain" => info.Domain,
+ "Description" => info.Description,
+ "TimeOffset" => info.TimeOffset is { } offset ? DateTimeHelper.TimeSpanToOffsetString(offset) : null,
+ "Users" => info.Users != null
+ ? string.Join(Environment.NewLine, info.Users)
+ : GetErrorMessage(info.UsersError),
+ "SMB" => info.SMB?.Dialect,
+ "SMBSigning" => info.SMB == null
+ ? null
+ : info.SMB.SigningRequired
+ ? Strings.Required
+ : Strings.NotRequired,
+ "Error" => GetErrorMessage(info.Error),
+ _ => null
+ };
+ }
+
+ ///
+ /// Gets the message of an error of the NetApi requests (of Windows, or the credentials were not tried).
+ ///
+ private static string GetErrorMessage(int error)
+ {
+ return error switch
+ {
+ WindowsHostInfo.ErrorLogonSkipped => Strings.WindowsLogonSkippedMessage,
+ WindowsHostInfo.ErrorLogonNotChecked => Strings.WindowsLogonNotCheckedMessage,
+ _ => WindowsHostInfo.GetErrorMessage(error)
+ };
+ }
+
+ ///
+ /// Gets the translated role of a Windows host, empty if unknown.
+ ///
+ /// Role.
+ /// Translated role.
+ public static string RoleToLocalizedString(WindowsHostRole role)
+ {
+ return role switch
+ {
+ WindowsHostRole.Workstation => Strings.Workstation,
+ WindowsHostRole.Server => Strings.Server,
+ WindowsHostRole.DomainController => Strings.DomainController,
+ _ => string.Empty
+ };
+ }
+
+ public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ throw new NotImplementedException();
+ }
+}
diff --git a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs
index 59c6116441..b9b02ec7bc 100644
--- a/Source/NETworkManager.Localization/Resources/Strings.Designer.cs
+++ b/Source/NETworkManager.Localization/Resources/Strings.Designer.cs
@@ -1491,6 +1491,24 @@ public static string BeaconInterval {
}
}
+ ///
+ /// Looks up a localized string similar to Beta.
+ ///
+ public static string Beta {
+ get {
+ return ResourceManager.GetString("Beta", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Beta: this feature is tested publicly and may change. Please report problems on GitHub..
+ ///
+ public static string BetaFeatureMessage {
+ get {
+ return ResourceManager.GetString("BetaFeatureMessage", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Bit Calculator.
///
@@ -3811,6 +3829,15 @@ public static string DomainCannotBeQueriedViaRDAPTryWhois {
}
}
+ ///
+ /// Looks up a localized string similar to Domain controller.
+ ///
+ public static string DomainController {
+ get {
+ return ResourceManager.GetString("DomainController", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Domain name.
///
@@ -4019,6 +4046,15 @@ public static string EditGroupDots {
}
}
+ ///
+ /// Looks up a localized string similar to Edition.
+ ///
+ public static string Edition {
+ get {
+ return ResourceManager.GetString("Edition", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Edit OID profile.
///
@@ -4958,24 +4994,6 @@ public static string Experience {
}
}
- ///
- /// Looks up a localized string similar to Experimental.
- ///
- public static string Experimental {
- get {
- return ResourceManager.GetString("Experimental", resourceCulture);
- }
- }
-
- ///
- /// Looks up a localized string similar to Experimental features.
- ///
- public static string ExperimentalFeatures {
- get {
- return ResourceManager.GetString("ExperimentalFeatures", resourceCulture);
- }
- }
-
///
/// Looks up a localized string similar to Explorer (Win+E).
///
@@ -5883,7 +5901,7 @@ public static string HelpMessage_AdjustThreadsAutomatically {
///
///Only the PowerShell consoles configured in the PowerShell settings are modified. Both Windows PowerShell and PWSH (PowerShell 7 and higher) are supported.
///
- ///Click in the upper right corner on the help / documentation button (left [rest of string was truncated]";.
+ ///Click in the upper right corner on the help / documentation button ( [rest of string was truncated]";.
///
public static string HelpMessage_ApplyThemeToPowerShellConsole {
get {
@@ -5993,15 +6011,6 @@ public static string HelpMessage_CustomPublicIPv6AddressAPI {
}
}
- ///
- /// Looks up a localized string similar to Enable experimental features to test new functions. These are not yet complete, contain bugs, can crash the application and may change again until release..
- ///
- public static string HelpMessage_ExperimentalFeatures {
- get {
- return ResourceManager.GetString("HelpMessage_ExperimentalFeatures", resourceCulture);
- }
- }
-
///
/// Looks up a localized string similar to Find hosts in a local subnet that don't answer the ping, a port or NetBIOS (e.g. a firewall drops everything) by their entry in the neighbor table (ARP / NDP). To reach a host in a local subnet, Windows has to resolve its MAC address first, and a host answers this request even if its firewall drops everything else. No additional packets are sent, except to check an entry from earlier traffic again. Hosts behind a router can't be found this way. Only decides if a host is up - the MAC address and vendor are s [rest of string was truncated]";.
///
@@ -6038,6 +6047,15 @@ public static string HelpMessage_MaximumNumberOfBackups {
}
}
+ ///
+ /// Looks up a localized string similar to Logon failures with the Windows credentials of a profile / group / tab on hosts outside the domain of the credentials (e.g. in a trusted domain) before they are rejected and not used for the other hosts. A logon failure on a host in the domain of the credentials, or with credentials without domain, rejects them right away. The failures are counted per account for all tabs until NETworkManager is closed. A domain controller may count one failed logon twice (Kerberos, then NTLM): keep this value below half of [rest of string was truncated]";.
+ ///
+ public static string HelpMessage_MaxLogonFailures {
+ get {
+ return ResourceManager.GetString("HelpMessage_MaxLogonFailures", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Number of consecutive failed pings (timeouts) required before a "Host is down" notification is shown. Higher values reduce noise from flapping hosts..
///
@@ -6221,6 +6239,15 @@ public static string HelpMessage_ReadWebPages {
}
}
+ ///
+ /// Looks up a localized string similar to Read the Windows host information of every reachable host over SMB (TCP port 445): with the port scan and port 445 in its list only for hosts with port 445 open, otherwise for every found host. Without credentials (SMB / NTLM negotiation, no logon): operating system and build, computer name, domain and the time offset. With credentials (NetApi): role (workstation, server, domain controller), description and workgroup; logged-on users and the patch level (remote registry) need admin rights on the host. The u [rest of string was truncated]";.
+ ///
+ public static string HelpMessage_ReadWindowsHostInformation {
+ get {
+ return ResourceManager.GetString("HelpMessage_ReadWindowsHostInformation", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Show the MAC address and vendor of every found host: read from the neighbor table (ARP / NDP) for hosts in a local subnet, otherwise from the NetBIOS answer (if NetBIOS is enabled). Doesn't find hosts - a host that doesn't answer the ping, a port or NetBIOS is only found with "Find hosts in the local subnet"..
///
@@ -6293,6 +6320,15 @@ public static string HelpMessage_UseCustomThemes {
}
}
+ ///
+ /// Looks up a localized string similar to Windows credentials for the Windows host information of this tab (also for repeated scans and Rescan), replacing the ones of the profile / group. They are not saved and are discarded when the tab is closed. Without credentials, the user running NETworkManager is used..
+ ///
+ public static string HelpMessage_WindowsCredentialsOfTheTab {
+ get {
+ return ResourceManager.GetString("HelpMessage_WindowsCredentialsOfTheTab", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Help translate the project on Transifex..
///
@@ -7752,6 +7788,15 @@ public static string LogFileName {
}
}
+ ///
+ /// Looks up a localized string similar to Logged-on users.
+ ///
+ public static string LoggedOnUsers {
+ get {
+ return ResourceManager.GetString("LoggedOnUsers", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Log mode.
///
@@ -7932,6 +7977,15 @@ public static string MaximumNumberOfHopsReached {
}
}
+ ///
+ /// Looks up a localized string similar to Max. logon failures.
+ ///
+ public static string MaxLogonFailures {
+ get {
+ return ResourceManager.GetString("MaxLogonFailures", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Max. concurrent port threads.
///
@@ -7941,6 +7995,15 @@ public static string MaxPortThreads {
}
}
+ ///
+ /// Looks up a localized string similar to Max. concurrent Windows host information threads.
+ ///
+ public static string MaxWindowsThreads {
+ get {
+ return ResourceManager.GetString("MaxWindowsThreads", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to mDNS.
///
@@ -8770,6 +8833,15 @@ public static string NotificationSuccessThreshold {
}
}
+ ///
+ /// Looks up a localized string similar to Not required.
+ ///
+ public static string NotRequired {
+ get {
+ return ResourceManager.GetString("NotRequired", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Not set.
///
@@ -9112,6 +9184,15 @@ public static string OpenWebsite {
}
}
+ ///
+ /// Looks up a localized string similar to Operating system.
+ ///
+ public static string OperatingSystem {
+ get {
+ return ResourceManager.GetString("OperatingSystem", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Options.
///
@@ -9139,6 +9220,15 @@ public static string Organization {
}
}
+ ///
+ /// Looks up a localized string similar to OS.
+ ///
+ public static string OS {
+ get {
+ return ResourceManager.GetString("OS", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to OS (guess).
///
@@ -9808,7 +9898,7 @@ public static string Profile {
///
/// Looks up a localized string similar to Profile files are encrypted on disk using AES with a key size of 256 bits and a block size of 128 bits in CBC mode. The encryption key is derived from a master password using Rfc2898DeriveBytes (PBKDF2) with 1,000,000 iterations. At runtime, passwords are stored as SecureString once the profile file is loaded. For some functions, the password must be converted to a normal string and remains unencrypted in memory until the garbage collector cleans them up.
///
- ///First make a backup copy of your profile files befo [rest of string was truncated]";.
+ ///First make a backup copy of your profile files be [rest of string was truncated]";.
///
public static string ProfileEncryptionDisclaimer {
get {
@@ -10437,6 +10527,15 @@ public static string ReadingWebPagesIsDisabled {
}
}
+ ///
+ /// Looks up a localized string similar to Reading Windows host information is disabled!.
+ ///
+ public static string ReadingWindowsHostInformationIsDisabled {
+ get {
+ return ResourceManager.GetString("ReadingWindowsHostInformationIsDisabled", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Read the SNMP system information.
///
@@ -10455,6 +10554,15 @@ public static string ReadWebPages {
}
}
+ ///
+ /// Looks up a localized string similar to Read Windows host information.
+ ///
+ public static string ReadWindowsHostInformation {
+ get {
+ return ResourceManager.GetString("ReadWindowsHostInformation", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Realm.
///
@@ -11715,6 +11823,15 @@ public static string ReportOnGitHub {
}
}
+ ///
+ /// Looks up a localized string similar to Required.
+ ///
+ public static string Required {
+ get {
+ return ResourceManager.GetString("Required", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Rescan.
///
@@ -12106,6 +12223,15 @@ public static string RloginPort {
}
}
+ ///
+ /// Looks up a localized string similar to Role.
+ ///
+ public static string Role {
+ get {
+ return ResourceManager.GetString("Role", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Roles.
///
@@ -12565,6 +12691,24 @@ public static string Scan {
}
}
+ ///
+ /// Looks up a localized string similar to Scan as.
+ ///
+ public static string ScanAs {
+ get {
+ return ResourceManager.GetString("ScanAs", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Scan as....
+ ///
+ public static string ScanAsDots {
+ get {
+ return ResourceManager.GetString("ScanAsDots", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Scan for NetBIOS.
///
@@ -13059,6 +13203,15 @@ public static string SettingsResetExclamationMark {
}
}
+ ///
+ /// Looks up a localized string similar to Set Windows credentials....
+ ///
+ public static string SetWindowsCredentialsDots {
+ get {
+ return ResourceManager.GetString("SetWindowsCredentialsDots", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Several profiles are named "{0}", select one!.
///
@@ -13329,6 +13482,24 @@ public static string Slogan {
}
}
+ ///
+ /// Looks up a localized string similar to SMB.
+ ///
+ public static string SMB {
+ get {
+ return ResourceManager.GetString("SMB", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to SMB signing.
+ ///
+ public static string SMBSigning {
+ get {
+ return ResourceManager.GetString("SMBSigning", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to SNMP.
///
@@ -14356,6 +14527,15 @@ public static string TimeMSToWaitBetweenEachPing {
}
}
+ ///
+ /// Looks up a localized string similar to Time offset.
+ ///
+ public static string TimeOffset {
+ get {
+ return ResourceManager.GetString("TimeOffset", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Timeout.
///
@@ -15334,6 +15514,33 @@ public static string Windows {
}
}
+ ///
+ /// Looks up a localized string similar to Windows credentials.
+ ///
+ public static string WindowsCredentials {
+ get {
+ return ResourceManager.GetString("WindowsCredentials", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Windows credentials of this tab ({0}).
+ ///
+ public static string WindowsCredentialsOfThisTabX {
+ get {
+ return ResourceManager.GetString("WindowsCredentialsOfThisTabX", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Windows credentials of "{0}" ({1}).
+ ///
+ public static string WindowsCredentialsOfX {
+ get {
+ return ResourceManager.GetString("WindowsCredentialsOfX", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to Windows DNS settings.
///
@@ -15352,6 +15559,42 @@ public static string WindowsFirewallSettings {
}
}
+ ///
+ /// Looks up a localized string similar to The logon with the Windows credentials "{0}" failed (wrong username or password?). To protect the account from being locked out, they are not used for the other hosts and the next scans of this tab. Set them again with Set Windows credentials... in the options, or open a new tab after correcting the profile / group..
+ ///
+ public static string WindowsLogonFailedMessage {
+ get {
+ return ResourceManager.GetString("WindowsLogonFailedMessage", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Not tried: the Windows credentials were still being checked on another host (protection against an account lockout)..
+ ///
+ public static string WindowsLogonNotCheckedMessage {
+ get {
+ return ResourceManager.GetString("WindowsLogonNotCheckedMessage", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Not tried: the Windows credentials were rejected on another host, or by this host in an earlier scan (protection against an account lockout)..
+ ///
+ public static string WindowsLogonSkippedMessage {
+ get {
+ return ResourceManager.GetString("WindowsLogonSkippedMessage", resourceCulture);
+ }
+ }
+
+ ///
+ /// Looks up a localized string similar to Workstation.
+ ///
+ public static string Workstation {
+ get {
+ return ResourceManager.GetString("Workstation", resourceCulture);
+ }
+ }
+
///
/// Looks up a localized string similar to WPS.
///
diff --git a/Source/NETworkManager.Localization/Resources/Strings.resx b/Source/NETworkManager.Localization/Resources/Strings.resx
index bcfccfd993..7debb8294a 100644
--- a/Source/NETworkManager.Localization/Resources/Strings.resx
+++ b/Source/NETworkManager.Localization/Resources/Strings.resx
@@ -2003,6 +2003,9 @@ Profile files are not affected!
Max. concurrent port threads
+
+ Max. concurrent Windows host information threads
+
PowerShell
@@ -3782,15 +3785,6 @@ Try again in a few seconds.
Application
-
- Enable experimental features to test new functions. These are not yet complete, contain bugs, can crash the application and may change again until release.
-
-
- Experimental features
-
-
- Experimental
-
Run command...
@@ -5357,4 +5351,103 @@ Do you want to start the scan?
SNMP version and credentials of "{0}"IP Scanner: the tab uses the SNMP version and credentials of a profile or group, {0} is its name.
+
+ Read Windows host information
+
+
+ Read the Windows host information of every reachable host over SMB (TCP port 445): with the port scan and port 445 in its list only for hosts with port 445 open, otherwise for every found host. Without credentials (SMB / NTLM negotiation, no logon): operating system and build, computer name, domain and the time offset. With credentials (NetApi): role (workstation, server, domain controller), description and workgroup; logged-on users and the patch level (remote registry) need admin rights on the host. The user running NETworkManager is used, or the Windows credentials of the profile / group the tab was opened with. Every host that answers on port 445 receives a logon with these credentials (NTLM if it is asked by its IP address) - only scan networks you trust.
+
+
+ Windows credentials of "{0}" ({1})
+ IP Scanner: the tab uses the Windows credentials of a profile or group, {0} is its name, {1} the user (e.g. CORP\admin).
+
+
+ Operating system
+
+
+ Edition
+ Edition of Windows, e.g. Pro or Enterprise
+
+
+ Role
+ Role of a Windows host: workstation, server or domain controller
+
+
+ Workstation
+ Role of a Windows host (client)
+
+
+ Domain controller
+
+
+ Time offset
+ Time of the host minus the local time
+
+
+ Logged-on users
+
+
+ SMB
+
+
+ Reading Windows host information is disabled!
+
+
+ The logon with the Windows credentials "{0}" failed (wrong username or password?). To protect the account from being locked out, they are not used for the other hosts and the next scans of this tab. Set them again with Set Windows credentials... in the options, or open a new tab after correcting the profile / group.
+ {0} is the user (e.g. CORP\admin)
+
+
+ Not tried: the Windows credentials were rejected on another host, or by this host in an earlier scan (protection against an account lockout).
+
+
+ Not tried: the Windows credentials were still being checked on another host (protection against an account lockout).
+
+
+ Windows credentials
+
+
+ Scan as...
+ IP Scanner: scan a profile with other Windows credentials
+
+
+ Windows credentials of this tab ({0})
+ IP Scanner: the tab uses Windows credentials entered for it (not saved), {0} is the user (e.g. CORP\admin).
+
+
+ Windows credentials for the Windows host information of this tab (also for repeated scans and Rescan), replacing the ones of the profile / group. They are not saved and are discarded when the tab is closed. Without credentials, the user running NETworkManager is used.
+
+
+ Scan as
+ IP Scanner: title of the dialog to scan a profile with other Windows credentials
+
+
+ SMB signing
+ Whether the SMB server of a host requires signed messages
+
+
+ Required
+
+
+ Not required
+
+
+ OS
+ Column of the IP Scanner: operating system (Windows version or guess from the TTL)
+
+
+ Set Windows credentials...
+ IP Scanner: options menu, Windows credentials of the tab (not saved)
+
+
+ Max. logon failures
+
+
+ Logon failures with the Windows credentials of a profile / group / tab on hosts outside the domain of the credentials (e.g. in a trusted domain) before they are rejected and not used for the other hosts. A logon failure on a host in the domain of the credentials, or with credentials without domain, rejects them right away. The failures are counted per account for all tabs until NETworkManager is closed. A domain controller may count one failed logon twice (Kerberos, then NTLM): keep this value below half of the account lockout threshold of your domain.
+
+
+ Beta
+
+
+ Beta: this feature is tested publicly and may change. Please report problems on GitHub.
+
\ No newline at end of file
diff --git a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs
index 6eebe414cb..7c938be4df 100644
--- a/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs
+++ b/Source/NETworkManager.Models/Export/ExportManager.IPScannerHostInfo.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
@@ -67,8 +68,17 @@ private static List GetFields(IPScannerHostInfo info, IPScannerResu
var netBIOSInfo = GetNetBIOSInfo(info, options);
var certificate = GetWebCertificate(info, options);
+ // Windows host information: null (empty values) if disabled, "" if the host had none
+ var windows = options.WindowsEnabled ? info.Windows : null;
+
string IfEnabled(bool isEnabled, string value) => isEnabled ? value : null;
+ string IfWindows(Func value) =>
+ options.WindowsEnabled ? windows == null ? string.Empty : value(windows) ?? string.Empty : null;
+
+ // Number / bool like WebStatusCode / WebCertificateSelfSigned: null without a value
+ object IfWindowsValue(Func value) => windows == null ? null : value(windows);
+
return
[
new(nameof(IPScannerHostInfo.IsReachable), info.IsReachable),
@@ -119,7 +129,24 @@ private static List GetFields(IPScannerHostInfo info, IPScannerResu
new(nameof(IPScannerHostInfo.PreviousMACAddress), info.PreviousMACAddress),
// SNMPv3 error of the host (e.g. "AuthenticationFailed"), empty without
new(nameof(IPScannerHostInfo.SNMPError),
- IfEnabled(options.SNMPEnabled, info.HasSNMPError ? info.SNMPError.ToString() : string.Empty), true)
+ IfEnabled(options.SNMPEnabled, info.HasSNMPError ? info.SNMPError.ToString() : string.Empty), true),
+ // Windows host information (SMB / NTLM, NetApi)
+ new("WindowsOS", IfWindows(x => x.OS), true),
+ new("WindowsEdition", IfWindows(x => x.Edition), true),
+ new("WindowsVersion", IfWindows(x => x.Version?.ToString())),
+ new("WindowsRole", IfWindows(x => x.Role == WindowsHostRole.Unknown ? string.Empty : x.Role.ToString())),
+ new("WindowsComputerName", IfWindows(x => x.ComputerName), true),
+ new("WindowsDomain", IfWindows(x => x.Domain), true),
+ // Seconds (time of the host minus the local time)
+ new("WindowsTimeOffset",
+ IfWindowsValue(x => x.TimeOffset is { } offset ? Math.Round(offset.TotalSeconds, 3) : null)),
+ new("WindowsUsers", IfWindows(x => x.Users == null ? string.Empty : string.Join("; ", x.Users)), true),
+ new("WindowsDescription", IfWindows(x => x.Description), true),
+ // Win32 error of the NetApi requests (e.g. 5 = access denied, 1326 = wrong username or password)
+ new("WindowsError", IfWindowsValue(x => x.Error == 0 ? null : x.Error)),
+ new("SMBDialect", IfWindows(x => x.SMB?.Dialect)),
+ new("SMBSigningRequired", IfWindowsValue(x => x.SMB?.SigningRequired)),
+ new("SMBServerGuid", IfWindows(x => x.SMB?.ServerGuid.ToString()))
];
}
@@ -147,7 +174,8 @@ private static void CreateCsv(IEnumerable collection, IPScann
var value = field.Value is List ports
? string.Join(";", ports.Select(port =>
$"{port.Port}/{port.LookupInfo.Protocol}/{port.LookupInfo.Service}/{port.LookupInfo.Description}/{port.State}"))
- : $"{field.Value}";
+ // Invariant: a decimal comma would split the column (e.g. WindowsTimeOffset)
+ : Convert.ToString(field.Value, CultureInfo.InvariantCulture);
return field.IsQuoted ? CsvHelper.QuoteString(value) : value;
})));
@@ -166,7 +194,7 @@ private static IEnumerable GetFieldNames()
new NetBIOSInfo(IPAddress.None));
return GetFields(placeholder, new IPScannerResultOptions(false, false, false, false, false, false, false, false,
- false)).Select(x => x.Name);
+ false, false)).Select(x => x.Name);
}
///
diff --git a/Source/NETworkManager.Models/Network/IPScanner.cs b/Source/NETworkManager.Models/Network/IPScanner.cs
index 0c0b589a30..e646b05618 100644
--- a/Source/NETworkManager.Models/Network/IPScanner.cs
+++ b/Source/NETworkManager.Models/Network/IPScanner.cs
@@ -1,12 +1,14 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
+using log4net;
using NETworkManager.Models.Lookup;
using NETworkManager.Utilities;
@@ -20,6 +22,20 @@ public sealed class IPScanner(IPScannerOptions options)
{
#region Variables
+ private static readonly ILog Log = LogManager.GetLogger(typeof(IPScanner));
+
+ // The port scan checks TCP 445 (SMB): the Windows host information is only read for hosts with 445 open
+ private readonly bool _isSMBPortScanned =
+ options.PortScanEnabled && options.PortScanPorts.Contains(SMBInfoResolver.SMBPort);
+
+ // Network logon with the Windows credentials of the profile / group (null: the user running the application) and
+ // the error if it could not be created (every host gets it instead of using another user)
+ private WindowsLogon _windowsLogon;
+ private int _windowsLogonError;
+
+ // Checks the credentials on one host before the others use them (account lockout), null without credentials
+ private WindowsLogonGate _windowsLogonGate;
+
///
/// Time between the start of two hosts during the ramp-up, see . With the
/// default settings the first 128 hosts are started within ~1.3 s instead of at the same moment (~11 connection
@@ -138,6 +154,27 @@ public void ScanAsync(IEnumerable<(IPAddress ipAddress, string hostname)> hosts,
_hostRoles = IPScannerHostRoleHelper.GetRoles(networkInterfaces);
_neighborCache = new IPScannerNeighborCache(_hostRoles);
+ // Network logon for the NetApi requests of the Windows host information, once per scan
+ if (options.WindowsEnabled && options.WindowsCredentials != null)
+ {
+ // Of the tab (all its scans), otherwise for this scan
+ _windowsLogonGate = options.WindowsLogonGate ?? new WindowsLogonGate(options.WindowsCredentials);
+ _windowsLogonGate.StartScan(options.WindowsMaxLogonFailures);
+
+ try
+ {
+ _windowsLogon = WindowsLogon.Create(options.WindowsCredentials);
+ }
+ catch (Exception ex)
+ {
+ Log.Warn($"Could not log on with the Windows credentials of the profile / group " +
+ $"({options.WindowsCredentials}), the NetApi requests are skipped.", ex);
+
+ // Not a wrong password (the logon doesn't check it)
+ _windowsLogonError = GetWin32Error(ex);
+ }
+ }
+
var hostParallelOptions = new ParallelOptions
{
CancellationToken = cancellationToken,
@@ -200,6 +237,11 @@ await ScanHostAsync(host.ipAddress, portScanParallelOptions, networkInterfaces,
}
finally
{
+ // A NetApi call that exceeded the timeout may still run, the thread keeps its impersonation token
+ _windowsLogon?.Dispose();
+
+ _windowsLogonGate?.LogScanSummary();
+
OnScanComplete(new ScanCompleteArgs(isCanceled, exception));
}
});
@@ -268,24 +310,51 @@ await _neighborCache.WasReachableBeforeAsync(ipAddress, cancellationToken)
// Probes that answered so far
var detectedBy = IPScannerDetectionMethod.None;
- // The title of the web page is read for the found host (when the port scan is finished)
+ // The title of the web page and the Windows host information are read for the found host (when the port scan
+ // is finished)
var isWebPagePending = false;
+ var isWindowsPending = false;
+
+ // DNS hostname of the host (empty if none or disabled) - the NetApi requests use it to connect by name
+ var dnsHostname = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
IPScannerHostInfo hostInfo = null;
+ var isWindowsStarted = false;
+
+ // Windows host information of a found host - as soon as the result of TCP 445 is known if the port scan
+ // checks it (not after the other probes, e.g. SNMP or a long port list), otherwise right away
+ void StartWindows()
+ {
+ if (!isWindowsPending || isWindowsStarted || (_isSMBPortScanned && ports == null))
+ return;
+
+ isWindowsStarted = true;
+
+ if (IsSMBPortOpenOrNotScanned(ports))
+ enrichTask = Task.WhenAll(enrichTask,
+ UpdateWindowsAsync(ipAddress, hostInfo, dnsHostname.Task, cancellationToken));
+ else
+ OnHostUpdated(new IPScannerHostUpdatedArgs(hostInfo, x => x.IsWindowsPending = false));
+ }
+
// The host answered (the first probe, or its neighbor entry): it is up - raise it as found with the results so
- // far and start the lookups (DNS, MAC address, mDNS)
+ // far and start the lookups (DNS, MAC address, mDNS, Windows)
void RaiseHostFound()
{
hostInfo = CreateHostInfo(ipAddress, detectedBy, pingInfo, ports, netBIOSInfo, snmpInfo, isSNMPFinished);
isWebPagePending = hostInfo.IsWebPagePending;
+ isWindowsPending = hostInfo.IsWindowsPending;
_hostsUp.Increment();
OnHostFound(new IPScannerHostFoundArgs(hostInfo));
OnProgressChanged();
- enrichTask = EnrichAsync(ipAddress, hostInfo, DateTime.UtcNow, networkInterfaces, cancellationToken);
+ enrichTask = EnrichAsync(ipAddress, hostInfo, DateTime.UtcNow, networkInterfaces, dnsHostname,
+ cancellationToken);
+
+ StartWindows();
}
try
@@ -396,6 +465,9 @@ void RaiseHostFound()
if (update != null)
OnHostUpdated(new IPScannerHostUpdatedArgs(hostInfo, update));
+ // E.g. the port scan finished
+ StartWindows();
+
continue;
}
@@ -447,7 +519,7 @@ await _neighborCache.IsNeighborAsync(ipAddress, wasNeighborReachableBefore, canc
// An unreachable host doesn't need a new snapshot of the neighbor table - the table is only read
// if it was not read yet (e.g. a host that blocks ICMP still has an ARP entry from the ping)
enrichTask = EnrichAsync(ipAddress, hostInfo, DateTime.MinValue, networkInterfaces,
- cancellationToken);
+ dnsHostname, cancellationToken);
}
}
@@ -520,6 +592,7 @@ private IPScannerHostInfo CreateHostInfo(IPAddress ipAddress, IPScannerDetection
DetectedBy = detectedBy,
Role = IPScannerHostRoleHelper.GetRole(_hostRoles, ipAddress),
IsPingPending = pingInfo == null && options.ICMPEnabled,
+ IsOSGuessEnabled = options.OSGuessEnabled,
// Lookups of every shown host and requests to reachable hosts, started after the host was found (see
// EnrichAsync, ScanHostAsync)
IsDNSPending = options.ResolveHostname,
@@ -532,6 +605,7 @@ private IPScannerHostInfo CreateHostInfo(IPAddress ipAddress, IPScannerDetection
SNMPError = snmpInfo?.Error ?? SNMPV3ErrorCode.None,
IsWebPagePending = isReachable && options.WebPageEnabled &&
(ports == null ? options.PortScanEnabled : GetWebPorts(ports).Count > 0),
+ IsWindowsPending = isReachable && options.WindowsEnabled && (ports == null || IsSMBPortOpenOrNotScanned(ports)),
IsPortScanPending = ports == null,
IsNetBIOSPending = netBIOSInfo == null
};
@@ -547,14 +621,29 @@ private IPScannerHostInfo CreateHostInfo(IPAddress ipAddress, IPScannerDetection
/// Result of the host, already raised in .
/// Time the host answered, if it is unreachable.
/// Local network interfaces (for the MAC address lookup).
+ /// Completed with the DNS hostname (empty if none or disabled).
/// Token to monitor for cancellation requests.
private async Task EnrichAsync(IPAddress ipAddress, IPScannerHostInfo host, DateTime discoveredAt,
- List networkInterfaces, CancellationToken cancellationToken)
+ List networkInterfaces, TaskCompletionSource dnsHostnameResult,
+ CancellationToken cancellationToken)
{
async Task UpdateHostnameAsync()
{
- var dnsHostname = await DNSClient.GetInstance().ResolvePtrOrEmptyAsync(ipAddress, cancellationToken)
- .ConfigureAwait(false);
+ string dnsHostname;
+
+ try
+ {
+ dnsHostname = await DNSClient.GetInstance().ResolvePtrOrEmptyAsync(ipAddress, cancellationToken)
+ .ConfigureAwait(false);
+ }
+ catch
+ {
+ // Also on cancellation / an error, nothing waits for a hostname that never comes
+ dnsHostnameResult.TrySetResult(string.Empty);
+ throw;
+ }
+
+ dnsHostnameResult.TrySetResult(dnsHostname ?? string.Empty);
// Also without a hostname, so the placeholder is replaced
OnHostUpdated(new IPScannerHostUpdatedArgs(host, x =>
@@ -594,6 +683,9 @@ async Task UpdateMACAddressAsync()
// Requests sent to the host (e.g. mDNS) only for reachable hosts
var isReachable = discoveredAt != DateTime.MinValue;
+ if (!options.ResolveHostname)
+ dnsHostnameResult.TrySetResult(string.Empty);
+
// The lookups don't depend on each other - run them concurrently, the host is finished after the slowest one
// instead of after all of them
await Task.WhenAll(
@@ -646,6 +738,289 @@ private async Task UpdateWebPageAsync(IPAddress ipAddress, IPScannerHostInfo hos
}));
}
+ ///
+ /// Gets the Win32 error of an exception of the Windows logon / NetApi requests.
+ ///
+ /// Exception.
+ /// Error of a , otherwise ERROR_GEN_FAILURE (31).
+ private static int GetWin32Error(Exception ex)
+ {
+ const int errorGenFailure = 31;
+
+ return ex is Win32Exception win32Exception ? win32Exception.NativeErrorCode : errorGenFailure;
+ }
+
+ ///
+ /// Checks if the Windows host information is read for a found host: with the port scan and TCP 445 in its
+ /// ports only if 445 is open, otherwise for every found host (the SMB request tells if 445 is open).
+ ///
+ ///
+ /// All probed ports (empty if the port scan is disabled; null while it runs, only if it doesn't check 445).
+ ///
+ /// True if the Windows host information is read.
+ private bool IsSMBPortOpenOrNotScanned(List ports)
+ {
+ if (!_isSMBPortScanned)
+ return true;
+
+ return ports.Any(x => x.Port == SMBInfoResolver.SMBPort && x.State == PortState.Open);
+ }
+
+ ///
+ /// Reads the Windows host information of a host and raises it as : the SMB / NTLM
+ /// values (no credentials), then - if the host answered on TCP 445 - the NetApi values with the credentials of
+ /// the scan.
+ ///
+ /// IP address of the host.
+ /// Result of the host, already raised in .
+ /// DNS hostname of the host (empty if none or disabled).
+ /// Token to monitor for cancellation requests.
+ private async Task UpdateWindowsAsync(IPAddress ipAddress, IPScannerHostInfo host, Task dnsHostname,
+ CancellationToken cancellationToken)
+ {
+ var smbInfo = await SMBInfoResolver.ResolveAsync(ipAddress, options.WindowsTimeout, cancellationToken)
+ .ConfigureAwait(false);
+
+ WindowsNetApiInfo netApiInfo = null;
+
+ // No SMB answer: no NetApi requests (they would wait for the SMB / RPC timeouts)
+ if (smbInfo != null)
+ {
+ // Without credentials of the scan: the logon of the user running the application (no stored password)
+ var isGated = _windowsLogonGate?.IsGated(smbInfo.NTLM) ?? true;
+
+ var target = GetWindowsTarget(ipAddress, await dnsHostname.ConfigureAwait(false), smbInfo.NTLM,
+ isGated);
+
+ netApiInfo = await ResolveNetApiAsync(ipAddress.ToString(), target, smbInfo.NTLM, cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ var windowsInfo = smbInfo == null ? null : new WindowsHostInfo(smbInfo, netApiInfo);
+
+ // Also without an answer, so the placeholder is replaced
+ OnHostUpdated(new IPScannerHostUpdatedArgs(host, x =>
+ {
+ x.Windows = windowsInfo;
+ x.IsWindowsPending = false;
+ }));
+ }
+
+ ///
+ /// Gets the name the NetApi requests connect to: the DNS hostname if it is the DNS name the host itself sends in
+ /// the NTLM challenge (the full name - a stale PTR record or a computer with the same name in another domain
+ /// could resolve to another host, which would get the credentials and show its values), so Kerberos can be
+ /// used; otherwise the IP address (NTLM only), e.g. for a computer in a workgroup (no DNS domain). A host that is
+ /// not gated by the lockout protection (workgroup computer, local account) always gets the IP address: with a
+ /// hostname, Kerberos would first ask the domain controller of the credentials for a ticket - a wrong password
+ /// would count there for every such host, in parallel.
+ ///
+ /// IP address of the host.
+ /// DNS hostname (empty if none).
+ /// NTLM challenge of the host, null if none.
+ ///
+ /// The host is gated by the lockout protection, or the scan has no credentials (see
+ /// ).
+ ///
+ /// Hostname or IP address.
+ public static string GetWindowsTarget(IPAddress ipAddress, string dnsHostname, NTLMChallengeInfo ntlm,
+ bool isGated)
+ {
+ if (!isGated || string.IsNullOrEmpty(dnsHostname) || string.IsNullOrEmpty(ntlm?.DNSComputerName) ||
+ !ntlm.DNSComputerName.Contains('.'))
+ return ipAddress.ToString();
+
+ var hostname = dnsHostname.TrimEnd('.');
+
+ return string.Equals(hostname, ntlm.DNSComputerName.TrimEnd('.'), StringComparison.OrdinalIgnoreCase)
+ ? hostname
+ : ipAddress.ToString();
+ }
+
+ ///
+ /// Runs the blocking NetApi requests of a host on its own thread (max.
+ /// at the same time in all scans, see
+ /// ) with the network logon of the scan, waits at most the timeout.
+ ///
+ /// IP address of the host (if the hostname can't be found).
+ /// Hostname or IP address to connect to, see .
+ /// NTLM challenge of the host (domain for the lockout protection), null if none.
+ /// Token to monitor for cancellation requests.
+ /// NetApi information, with after the timeout.
+ private async Task ResolveNetApiAsync(string ipAddress, string target, NTLMChallengeInfo ntlm,
+ CancellationToken cancellationToken)
+ {
+ if (_windowsLogonError != 0)
+ return WindowsNetApiInfo.FromError(_windowsLogonError);
+
+ var timeout = TimeSpan.FromMilliseconds(options.WindowsTimeout);
+
+ // Credentials: checked on one host before the others use them (a wrong password must not lock the account)
+ var decision = _windowsLogonGate == null
+ ? WindowsLogonGate.Decision.Proceed
+ : await _windowsLogonGate.WaitAsync(ntlm, ipAddress, timeout * 2, cancellationToken).ConfigureAwait(false);
+
+ switch (decision)
+ {
+ case WindowsLogonGate.Decision.Skip:
+ return WindowsNetApiInfo.FromError(WindowsHostInfo.ErrorLogonSkipped);
+ // Never contacted: not the timeout of the host
+ case WindowsLogonGate.Decision.Timeout:
+ return WindowsNetApiInfo.FromError(WindowsHostInfo.ErrorLogonNotChecked);
+ }
+
+ // The host checks the credentials: its result is reported when the call returns - also after the timeout of
+ // the host, so the next host doesn't check them while this logon is still running (a late logon failure in
+ // the domain still rejects them)
+ // A host that is not gated reports its own logon failure (skipped in the next scans)
+ var isUngated = _windowsLogonGate != null && !_windowsLogonGate.IsGated(ntlm);
+
+ // A gated host that uses the accepted credentials reports a logon failure in their domain (e.g. the password
+ // was changed during the scan): rejected for the hosts that didn't start yet
+ Action onCallCompleted = _windowsLogonGate == null
+ ? null
+ : decision == WindowsLogonGate.Decision.Check
+ ? x => _windowsLogonGate.Report(ntlm, ipAddress, x)
+ : isUngated
+ ? x => _windowsLogonGate.ReportUngated(ntlm, ipAddress, x)
+ : x => _windowsLogonGate.ReportAccepted(ntlm, ipAddress, x);
+
+ // Local account (".\admin"): logged on with the computer name of the host ("PC01\admin"), so only the host
+ // checks it (not gated, the computer name is known)
+ var hostCredentials = isUngated ? options.WindowsCredentials.ForHost(ntlm.NetBIOSComputerName) : null;
+
+ return await ResolveNetApiWithLogonAsync(ipAddress, target, timeout, hostCredentials, onCallCompleted,
+ cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Runs the blocking NetApi requests of a host, see .
+ ///
+ ///
+ /// Credentials of a local account for this host (logged on for this call), null for the logon of the scan.
+ ///
+ ///
+ /// Called once with the result of the call when it is known (the NetApi values were read before the remote
+ /// registry, or the call returned - also after the timeout), null if it was not started (canceled while waiting
+ /// for a slot); optional.
+ ///
+ private async Task ResolveNetApiWithLogonAsync(string ipAddress, string target,
+ TimeSpan timeout, WindowsCredentials hostCredentials, Action onCallCompleted,
+ CancellationToken cancellationToken)
+ {
+ // Every path reports through Complete, exactly once (the lockout protection releases its turn): the NetApi
+ // values (the registry doesn't change the logon), the result of the call, or why it didn't run
+ var isCompleted = 0;
+
+ void Complete(WindowsNetApiInfo info)
+ {
+ if (Interlocked.Exchange(ref isCompleted, 1) == 0)
+ onCallCompleted?.Invoke(info);
+ }
+
+ // All slots are taken by calls that wait for Windows (e.g. hosts that don't answer RPC)
+ bool isSlotFree;
+
+ try
+ {
+ isSlotFree = await WindowsNetApiSlots.Shared
+ .WaitAsync(options.MaxWindowsThreads, timeout, cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ Complete(null);
+ throw;
+ }
+
+ if (!isSlotFree)
+ {
+ var info = WindowsNetApiInfo.FromError(WindowsHostInfo.ErrorTimeout);
+
+ Complete(info);
+
+ return info;
+ }
+
+ var logon = _windowsLogon;
+
+ // Values of the NetApi before the remote registry is read: kept if the registry exceeds the timeout
+ WindowsNetApiInfo netApiRead = null;
+
+ void OnNetApiRead(WindowsNetApiInfo info)
+ {
+ Volatile.Write(ref netApiRead, info);
+
+ Complete(info);
+ }
+
+ var task = Task.Factory.StartNew(() =>
+ {
+ WindowsNetApiInfo result = null;
+ WindowsLogon hostLogon = null;
+
+ // The requests were sent with the logon (impersonated) and returned: only then the result can be a failed
+ // logon - otherwise (e.g. the logon was disposed, the local logon failed, an exception of the call) the
+ // lockout protection gets no result
+ var isSent = false;
+ var isException = false;
+
+ try
+ {
+ WindowsNetApiInfo Resolve()
+ {
+ isSent = true;
+
+ var info = WindowsNetApiResolver.Resolve(target, OnNetApiRead);
+
+ // The hostname can't be found (e.g. no forward lookup zone): the IP address (NTLM)
+ return target != ipAddress && info.Error is 53 or 67 or 1214 or 1231
+ ? WindowsNetApiResolver.Resolve(ipAddress, OnNetApiRead)
+ : info;
+ }
+
+ // Local logon, no network: an error is not a failed logon at the host (e.g. invalid username)
+ if (hostCredentials != null)
+ logon = hostLogon = WindowsLogon.Create(hostCredentials);
+
+ result = logon != null ? logon.Run(Resolve) : Resolve();
+
+ return result;
+ }
+ catch (Exception ex)
+ {
+ // E.g. the logon was disposed by the end of the scan while the call waited for a slot (not sent). Not a
+ // failed logon: the host reports it as an error code, never as an exception (e.g. an exception after
+ // NetServerGetInfo succeeded must not reject correct credentials)
+ Log.Debug($"NetApi requests to {target} failed (sent: {isSent}).", ex);
+
+ isException = true;
+ result = WindowsNetApiInfo.FromError(GetWin32Error(ex));
+
+ return result;
+ }
+ finally
+ {
+ hostLogon?.Dispose();
+
+ WindowsNetApiSlots.Shared.Release();
+
+ // Not sent or an exception: not decided, the next host checks them (the row shows the error)
+ Complete(isSent && !isException ? result : null);
+ }
+ }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
+
+ try
+ {
+ return await task.WaitAsync(timeout, cancellationToken).ConfigureAwait(false);
+ }
+ catch (TimeoutException)
+ {
+ // The call keeps its thread (and slot) until Windows returns, its result is only reported (see
+ // onCallCompleted). The NetApi values if only the remote registry is still read (without patch level).
+ return Volatile.Read(ref netApiRead) ?? WindowsNetApiInfo.FromError(WindowsHostInfo.ErrorTimeout);
+ }
+ }
+
///
/// Resolves the MAC address of a host from the neighbor table (ARP/NDP) or the local network interfaces,
/// and its vendor.
diff --git a/Source/NETworkManager.Models/Network/IPScannerHostInfo.cs b/Source/NETworkManager.Models/Network/IPScannerHostInfo.cs
index e3ebaa5b0b..b5e4fd2dad 100644
--- a/Source/NETworkManager.Models/Network/IPScannerHostInfo.cs
+++ b/Source/NETworkManager.Models/Network/IPScannerHostInfo.cs
@@ -1,4 +1,5 @@
-using System.Collections.Generic;
+using System;
+using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
@@ -112,9 +113,53 @@ internal set
OnPropertyChanged();
OnPropertyChanged(nameof(OSGuess));
OnPropertyChanged(nameof(OSGuessHops));
+ OnPropertyChanged(nameof(OSName));
+ OnPropertyChanged(nameof(IsOSPending));
}
}
+ ///
+ /// The operating system is guessed from the TTL in the scan of the host (the OS column shows the guess). Default
+ /// on, set by the scan.
+ ///
+ public bool IsOSGuessEnabled
+ {
+ get;
+ internal set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ OnPropertyChanged(nameof(OSName));
+ OnPropertyChanged(nameof(IsOSPending));
+ }
+ } = true;
+
+ ///
+ /// Name of a guessed operating system as shown in the OS column (translated, set by the application - this
+ /// project has no translations), for sorting; the name of the value by default.
+ ///
+ public static Func OSGuessToString { get; set; } = x => x.ToString();
+
+ ///
+ /// Operating system for sorting the OS column (as shown): the Windows version if it was read, otherwise the
+ /// guess from the TTL (if enabled), empty if neither is known.
+ ///
+ public string OSName => HasWindowsOS
+ ? WindowsOS
+ : !IsOSGuessEnabled || OSGuess == IPScannerOSGuess.None
+ ? string.Empty
+ : OSGuessToString(OSGuess);
+
+ ///
+ /// The operating system is not known yet, but a source (Windows host information, ping for the guess) is still
+ /// running.
+ ///
+ public bool IsOSPending => string.IsNullOrEmpty(OSName) &&
+ (IsWindowsPending || (IsOSGuessEnabled && IsPingPending));
+
///
/// Operating system guessed from the TTL of the ping reply (see ),
/// without a ping reply (or TTL, e.g. IPv6).
@@ -207,10 +252,32 @@ internal set
return;
field = value;
+
+ // Computed once (sorting / search read them often)
+ var openPorts = value?.Where(x => x.State == PortState.Open).Select(x => x.Port).ToList() ?? [];
+ _openPorts = string.Join(", ", openPorts);
+ _openPortCount = openPorts.Count;
+
OnPropertyChanged();
+ OnPropertyChanged(nameof(OpenPorts));
+ OnPropertyChanged(nameof(OpenPortCount));
}
}
+ ///
+ /// Open ports, comma-separated in the order of the ports (e.g. "22, 80, 443"), empty if none.
+ ///
+ public string OpenPorts => _openPorts;
+
+ // Cache of OpenPorts / OpenPortCount, set with Ports
+ private string _openPorts = string.Empty;
+ private int _openPortCount;
+
+ ///
+ /// Number of open ports (sorting of the open ports).
+ ///
+ public int OpenPortCount => _openPortCount;
+
///
/// NetBIOS information about the host.
///
@@ -227,6 +294,8 @@ internal set
OnPropertyChanged(nameof(Hostname));
OnPropertyChanged(nameof(MACAddress));
OnPropertyChanged(nameof(Vendor));
+ OnPropertyChanged(nameof(Domain));
+ OnPropertyChanged(nameof(IsDomainPending));
}
}
@@ -245,6 +314,8 @@ internal set
OnPropertyChanged();
OnPropertyChanged(nameof(OSGuess));
OnPropertyChanged(nameof(OSGuessHops));
+ OnPropertyChanged(nameof(OSName));
+ OnPropertyChanged(nameof(IsOSPending));
}
}
@@ -280,6 +351,7 @@ internal set
OnPropertyChanged();
OnPropertyChanged(nameof(IsHostnamePending));
OnPropertyChanged(nameof(IsMACAddressPending));
+ OnPropertyChanged(nameof(IsDomainPending));
}
}
@@ -356,7 +428,7 @@ internal set
///
/// Ends the lookups that are still running when the scan was canceled or failed (their results never arrive):
- /// DNS hostname, MAC address, mDNS hostname and web page show no value instead of "...", and
+ /// DNS hostname, MAC address, mDNS hostname, web page and Windows show no value instead of "...", and
/// / no longer wait for NetBIOS. The probes that decide if
/// the host is up (ping, ports, NetBIOS, SNMP) stay pending ("..." = not finished). Call it on the thread that
/// owns the host (UI thread).
@@ -367,6 +439,7 @@ public void EndPendingLookups()
IsNeighborMACAddressPending = false;
IsMDNSPending = false;
IsWebPagePending = false;
+ IsWindowsPending = false;
_areLookupsEnded = true;
@@ -585,6 +658,99 @@ internal set
///
public bool HasSNMPError => SNMPError != SNMPV3ErrorCode.None;
+ ///
+ /// Windows host information (SMB / NTLM without credentials, NetApi with the credentials of the scan), null if
+ /// it was not read (yet) or the host didn't answer on TCP 445.
+ ///
+ public WindowsHostInfo Windows
+ {
+ get;
+ internal set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+
+ // Computed once (sorting / search of the OS and Logged-on users columns read them often)
+ _windowsOS = value?.OS ?? string.Empty;
+ _windowsUsers = value?.Users is { } users ? string.Join(", ", users) : string.Empty;
+
+ OnPropertyChanged();
+ OnPropertyChanged(nameof(WindowsOS));
+ OnPropertyChanged(nameof(HasWindowsOS));
+ OnPropertyChanged(nameof(OSName));
+ OnPropertyChanged(nameof(IsOSPending));
+ OnPropertyChanged(nameof(WindowsDomain));
+ OnPropertyChanged(nameof(Domain));
+ OnPropertyChanged(nameof(IsDomainPending));
+ OnPropertyChanged(nameof(WindowsTimeOffset));
+ OnPropertyChanged(nameof(IsWindowsTimeOffsetLarge));
+ OnPropertyChanged(nameof(WindowsUsers));
+ OnPropertyChanged(nameof(HasWindowsError));
+ }
+ }
+
+ ///
+ /// The NetApi requests of the Windows host information failed (e.g. access denied, wrong password) or were not
+ /// sent (credentials rejected on another host).
+ ///
+ public bool HasWindowsError => Windows is { Error: not 0 };
+
+ ///
+ /// Name of the Windows version (e.g. "Windows 11 25H2"), empty if not known.
+ ///
+ public string WindowsOS => _windowsOS;
+
+ // Cache of WindowsOS, set with Windows
+ private string _windowsOS = string.Empty;
+
+ ///
+ /// The Windows version is known (shown in the OS column instead of the guess from the TTL).
+ ///
+ public bool HasWindowsOS => !string.IsNullOrEmpty(WindowsOS);
+
+ ///
+ /// Domain or workgroup of the Windows host, empty if not known.
+ ///
+ public string WindowsDomain => Windows?.Domain ?? string.Empty;
+
+ ///
+ /// Domain or workgroup of the host for the Domain column: of the Windows host information, otherwise the
+ /// workgroup / domain of the NetBIOS answer, empty if neither is known.
+ ///
+ public string Domain => !string.IsNullOrEmpty(WindowsDomain)
+ ? WindowsDomain
+ : NetBIOSInfo is { IsReachable: true } ? NetBIOSInfo.GroupName ?? string.Empty : string.Empty;
+
+ ///
+ /// The domain is not known yet, but a source (Windows host information, NetBIOS) is still running.
+ ///
+ public bool IsDomainPending => string.IsNullOrEmpty(Domain) && (IsWindowsPending || IsNetBIOSPending);
+
+ ///
+ /// Time of the host minus the local time, null if not known.
+ ///
+ public TimeSpan? WindowsTimeOffset => Windows?.TimeOffset;
+
+ ///
+ /// Max. time offset of Kerberos (default of the domain policy): a larger offset breaks the logon in a domain.
+ ///
+ public static readonly TimeSpan MaxKerberosTimeOffset = TimeSpan.FromMinutes(5);
+
+ ///
+ /// The time offset is larger than the Kerberos limit (highlighted in the result).
+ ///
+ public bool IsWindowsTimeOffsetLarge => WindowsTimeOffset?.Duration() > MaxKerberosTimeOffset;
+
+ ///
+ /// Logged-on users, comma-separated (empty if none or not read).
+ ///
+ public string WindowsUsers => _windowsUsers;
+
+ // Cache of WindowsUsers, set with Windows
+ private string _windowsUsers = string.Empty;
+
///
/// Indicates whether the DNS hostname (PTR) is still resolved ( is a placeholder).
///
@@ -654,6 +820,25 @@ internal set
}
}
+ ///
+ /// Indicates whether the Windows host information is still read, or the port scan it needs is still running
+ /// ( is a placeholder).
+ ///
+ public bool IsWindowsPending
+ {
+ get;
+ internal set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ OnPropertyChanged(nameof(IsDomainPending));
+ OnPropertyChanged(nameof(IsOSPending));
+ }
+ }
+
///
/// Indicates whether the SNMP request is still running (,
/// , are placeholders).
@@ -760,6 +945,7 @@ public void CopyFrom(IPScannerHostInfo source)
IsReachable = source.IsReachable;
DetectedBy = source.DetectedBy;
Role = source.Role;
+ IsOSGuessEnabled = source.IsOSGuessEnabled;
PingInfo = source.PingInfo;
IsAnyPortOpen = source.IsAnyPortOpen;
Ports = source.Ports;
@@ -781,10 +967,12 @@ public void CopyFrom(IPScannerHostInfo source)
SNMPDescription = source.SNMPDescription;
SNMPLocation = source.SNMPLocation;
SNMPError = source.SNMPError;
+ Windows = source.Windows;
IsDNSPending = source.IsDNSPending;
IsNeighborMACAddressPending = source.IsNeighborMACAddressPending;
IsMDNSPending = source.IsMDNSPending;
IsWebPagePending = source.IsWebPagePending;
+ IsWindowsPending = source.IsWindowsPending;
// A rescan restarts the lookups (or a canceled one restores the ended state)
_areLookupsEnded = source._areLookupsEnded;
diff --git a/Source/NETworkManager.Models/Network/IPScannerOptions.cs b/Source/NETworkManager.Models/Network/IPScannerOptions.cs
index 26dc4a68f8..5b6fa9ec4c 100644
--- a/Source/NETworkManager.Models/Network/IPScannerOptions.cs
+++ b/Source/NETworkManager.Models/Network/IPScannerOptions.cs
@@ -16,6 +16,13 @@ public record IPScannerOptions
///
public required int MaxPortThreads { get; init; }
+ ///
+ /// Max. number of hosts whose NetApi requests run at the same time, in all scans of the application (the calls
+ /// are blocking and keep their thread after the timeout until Windows returns), see
+ /// .
+ ///
+ public required int MaxWindowsThreads { get; init; }
+
///
/// Ping the host.
///
@@ -130,6 +137,36 @@ public record IPScannerOptions
///
public required int SNMPTimeout { get; init; }
+ ///
+ /// Read the Windows host information of reachable hosts (SMB / NTLM without credentials, NetApi with the
+ /// credentials below), see and .
+ ///
+ public required bool WindowsEnabled { get; init; }
+
+ ///
+ /// Windows credentials of the profile / group the tab was opened with for the NetApi requests, null for the user
+ /// running the application (there are no Windows credentials in the settings).
+ ///
+ public WindowsCredentials WindowsCredentials { get; init; }
+
+ ///
+ /// Lockout protection of the , kept by the tab for all its scans (accepted /
+ /// rejected state, a check that is still running; the logon failures are counted per account for all tabs), so
+ /// repeated scans don't lock the account. Null: a new one for the scan.
+ ///
+ public WindowsLogonGate WindowsLogonGate { get; init; }
+
+ ///
+ /// Timeout in milliseconds of the SMB request and of the NetApi requests of a host.
+ ///
+ public required int WindowsTimeout { get; init; }
+
+ ///
+ /// Max. logon failures with the on hosts of other domains before they are
+ /// rejected, see .
+ ///
+ public required int WindowsMaxLogonFailures { get; init; }
+
///
/// Include unreachable IP addresses in the result.
///
diff --git a/Source/NETworkManager.Models/Network/IPScannerResultOptions.cs b/Source/NETworkManager.Models/Network/IPScannerResultOptions.cs
index d838269e62..1fbb6b3189 100644
--- a/Source/NETworkManager.Models/Network/IPScannerResultOptions.cs
+++ b/Source/NETworkManager.Models/Network/IPScannerResultOptions.cs
@@ -13,6 +13,7 @@
/// The mDNS hostname was resolved.
/// The title of the web pages was read.
/// The SNMP system information was read.
+/// The Windows host information was read.
public sealed record IPScannerResultOptions(
bool ICMPEnabled,
bool OSGuessEnabled,
@@ -22,7 +23,8 @@ public sealed record IPScannerResultOptions(
bool ResolveMACAddress,
bool MDNSEnabled,
bool WebPageEnabled,
- bool SNMPEnabled)
+ bool SNMPEnabled,
+ bool WindowsEnabled)
{
///
/// Creates the result options from the options of a scan.
@@ -30,7 +32,17 @@ public sealed record IPScannerResultOptions(
/// Options of the scan.
public IPScannerResultOptions(IPScannerOptions options)
: this(options.ICMPEnabled, options.OSGuessEnabled, options.ResolveHostname, options.PortScanEnabled, options.NetBIOSEnabled, options.ResolveMACAddress,
- options.MDNSEnabled, options.WebPageEnabled, options.SNMPEnabled)
+ options.MDNSEnabled, options.WebPageEnabled, options.SNMPEnabled, options.WindowsEnabled)
{
}
+
+ ///
+ /// The OS column is shown: the guess from the TTL (needs the ping) or the Windows version.
+ ///
+ public bool IsOSShown => (ICMPEnabled && OSGuessEnabled) || WindowsEnabled;
+
+ ///
+ /// The Domain column is shown: domain / workgroup of the Windows host information or of the NetBIOS answer.
+ ///
+ public bool IsDomainShown => WindowsEnabled || NetBIOSEnabled;
}
diff --git a/Source/NETworkManager.Models/Network/MDNSResolver.cs b/Source/NETworkManager.Models/Network/MDNSResolver.cs
index f5d8bb7103..7e41ed262b 100644
--- a/Source/NETworkManager.Models/Network/MDNSResolver.cs
+++ b/Source/NETworkManager.Models/Network/MDNSResolver.cs
@@ -6,6 +6,7 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using NETworkManager.Utilities;
namespace NETworkManager.Models.Network;
@@ -152,7 +153,7 @@ public static string ParsePTRResponse(byte[] response, ushort id)
// export fail
var name = ReadName(response, ref dataOffset) ?? string.Empty;
- return new string([.. name.Where(x => !char.IsControl(x))]);
+ return StringHelper.RemoveControlCharacters(name);
}
offset += dataLength;
diff --git a/Source/NETworkManager.Models/Network/SMBInfo.cs b/Source/NETworkManager.Models/Network/SMBInfo.cs
new file mode 100644
index 0000000000..4034821549
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/SMBInfo.cs
@@ -0,0 +1,57 @@
+using System;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Information a host reveals in the SMB negotiation without credentials, see .
+///
+/// Negotiated SMB dialect, e.g. "3.1.1".
+/// The server requires signed messages.
+/// GUID of the SMB server (stable per host, e.g. for known devices).
+///
+/// Time of the host in UTC (of the negotiate response, otherwise of the NTLM challenge), null if the host didn't
+/// send it.
+///
+///
+/// Time of the host minus the local time (corrected by half the round trip time), null without
+/// .
+///
+/// Values of the NTLM challenge, null if the host didn't send one (e.g. NTLM disabled).
+public sealed record SMBInfo(
+ string Dialect,
+ bool SigningRequired,
+ Guid ServerGuid,
+ DateTime? SystemTime,
+ TimeSpan? TimeOffset,
+ NTLMChallengeInfo NTLM);
+
+///
+/// Values of an NTLM challenge (sent by the host before any credentials are checked), see
+/// . Strings are empty if the host didn't send them.
+///
+/// Version of the operating system (major.minor.build), null if not sent.
+/// NetBIOS name of the computer, e.g. "CLIENT01".
+///
+/// NetBIOS name of the domain, e.g. "CORP" (the computer name if it is not in a domain).
+///
+/// DNS name of the computer, e.g. "client01.corp.example.com".
+/// DNS name of the domain, e.g. "corp.example.com" (the computer name if not in a domain).
+/// DNS name of the forest, e.g. "example.com".
+/// Time of the host in UTC, null if not sent.
+public sealed record NTLMChallengeInfo(
+ Version Version,
+ string NetBIOSComputerName,
+ string NetBIOSDomainName,
+ string DNSComputerName,
+ string DNSDomainName,
+ string DNSTreeName,
+ DateTime? Timestamp)
+{
+ ///
+ /// The computer is in a domain: the NetBIOS domain name is not its own computer name (a computer in a
+ /// workgroup sends its own name as domain).
+ ///
+ public bool IsDomainMember => !string.IsNullOrEmpty(NetBIOSDomainName) &&
+ !string.Equals(NetBIOSDomainName, NetBIOSComputerName,
+ StringComparison.OrdinalIgnoreCase);
+}
diff --git a/Source/NETworkManager.Models/Network/SMBInfoResolver.cs b/Source/NETworkManager.Models/Network/SMBInfoResolver.cs
new file mode 100644
index 0000000000..25ecf69c25
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/SMBInfoResolver.cs
@@ -0,0 +1,517 @@
+using System;
+using System.Buffers.Binary;
+using System.Diagnostics;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using NETworkManager.Utilities;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Reads what a host reveals in the SMB negotiation on TCP port 445 without credentials: an SMB2 NEGOTIATE
+/// (dialect, signing, server GUID, system time) and a SESSION_SETUP with an NTLM NEGOTIATE message,
+/// whose CHALLENGE answer contains the version of the operating system (major.minor.build), the computer and
+/// domain names and the time of the host. The connection is closed after the challenge: no credentials are sent and
+/// no logon is attempted (no failed logon on the host). Exception-free: null if the host doesn't answer or the
+/// answer is invalid.
+///
+public static class SMBInfoResolver
+{
+ ///
+ /// TCP port of SMB.
+ ///
+ public const int SMBPort = 445;
+
+ // Max. size of an answer (NBT session header length), larger answers are invalid for a negotiate / session setup
+ private const int MaxMessageSize = 64 * 1024;
+
+ private const int HeaderSize = 64;
+
+ private const ushort CommandNegotiate = 0x0000;
+ private const ushort CommandSessionSetup = 0x0001;
+
+ private const uint StatusSuccess = 0x00000000;
+ private const uint StatusMoreProcessingRequired = 0xC0000016;
+
+ // Dialects of the negotiate request: 2.0.2, 2.1, 3.0, 3.0.2, 3.1.1 (3.1.1 needs the preauth integrity context)
+ private static readonly ushort[] Dialects = [0x0202, 0x0210, 0x0300, 0x0302, 0x0311];
+
+ // NTLMSSP signature "NTLMSSP\0"
+ private static readonly byte[] NTLMSSPSignature = "NTLMSSP\0"u8.ToArray();
+
+ private const uint NTLMSSP_NEGOTIATE_UNICODE = 0x00000001;
+ private const uint NTLMSSP_REQUEST_TARGET = 0x00000004;
+ private const uint NTLMSSP_NEGOTIATE_NTLM = 0x00000200;
+ private const uint NTLMSSP_NEGOTIATE_ALWAYS_SIGN = 0x00008000;
+ private const uint NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY = 0x00080000;
+ private const uint NTLMSSP_NEGOTIATE_TARGET_INFO = 0x00800000;
+ private const uint NTLMSSP_NEGOTIATE_VERSION = 0x02000000;
+ private const uint NTLMSSP_NEGOTIATE_128 = 0x20000000;
+ private const uint NTLMSSP_NEGOTIATE_56 = 0x80000000;
+
+ ///
+ /// Reads the SMB information of a host.
+ ///
+ /// IP address of the host.
+ /// Timeout in milliseconds for the connection and both requests.
+ /// Token to monitor for cancellation requests.
+ /// SMB information, null if the host didn't answer the negotiate request or the answer is invalid.
+ public static async Task ResolveAsync(IPAddress ipAddress, int timeout,
+ CancellationToken cancellationToken)
+ {
+ using var timeoutCts = new CancellationTokenSource(timeout);
+ using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
+
+ try
+ {
+ using var socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
+
+ // Close with a reset (no TIME_WAIT sockets on large scans, see PortProbe)
+ socket.LingerState = new LingerOption(true, 0);
+ socket.NoDelay = true;
+
+ // Refused / no answer as SocketError instead of an exception (hosts without SMB, see SocketOperation)
+ using var connectArgs = new SocketAsyncEventArgs();
+ connectArgs.RemoteEndPoint = new IPEndPoint(ipAddress, SMBPort);
+
+ var connectTask = SocketOperation.RunAsync(connectArgs, socket.ConnectAsync);
+
+ SocketError socketError;
+
+ await using (linkedCts.Token.Register(() => Socket.CancelConnectAsync(connectArgs)))
+ {
+ socketError = await connectTask.ConfigureAwait(false);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (socketError != SocketError.Success)
+ return null;
+
+ await using var stream = new NetworkStream(socket, false);
+
+ // Negotiate: dialect, signing, GUID, time (the round trip time corrects the time offset)
+ var sentAt = DateTime.UtcNow;
+ var stopwatch = Stopwatch.StartNew();
+
+ await WriteMessageAsync(stream, CreateNegotiateRequest(Guid.NewGuid(), RandomNumberGenerator.GetBytes(32)),
+ linkedCts.Token).ConfigureAwait(false);
+
+ var negotiateResponse = await ReadMessageAsync(stream, linkedCts.Token).ConfigureAwait(false);
+
+ // Local time when the host answered: the middle of the round trip
+ var negotiateTime = sentAt + stopwatch.Elapsed / 2;
+
+ var negotiate = ParseNegotiateResponse(negotiateResponse);
+
+ if (negotiate == null)
+ return null;
+
+ // Session setup with an NTLM negotiate message: the answer contains the challenge (no logon)
+ NTLMChallengeInfo ntlm = null;
+ var sessionSetupTime = DateTime.MinValue;
+
+ try
+ {
+ var sessionSetupSent = stopwatch.Elapsed;
+
+ await WriteMessageAsync(stream, CreateSessionSetupRequest(), linkedCts.Token).ConfigureAwait(false);
+
+ var sessionSetupResponse = await ReadMessageAsync(stream, linkedCts.Token).ConfigureAwait(false);
+
+ sessionSetupTime = sentAt + (sessionSetupSent + stopwatch.Elapsed) / 2;
+
+ ntlm = ParseSessionSetupResponse(sessionSetupResponse);
+ }
+ catch (Exception) when (!cancellationToken.IsCancellationRequested)
+ {
+ // No challenge (e.g. NTLM disabled, the host closed the connection or the timeout): negotiate values only
+ }
+
+ // Time of the host and the local time when it was sent: of the negotiate response, otherwise of the NTLM
+ // challenge (its own round trip, not the one of the negotiate request)
+ var (systemTime, localTime) = negotiate.SystemTime != null
+ ? (negotiate.SystemTime, negotiateTime)
+ : (ntlm?.Timestamp, sessionSetupTime);
+
+ return new SMBInfo(negotiate.Dialect, negotiate.SigningRequired, negotiate.ServerGuid, systemTime,
+ systemTime - localTime, ntlm);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception)
+ {
+ // Refused, timeout, closed connection, invalid answer
+ return null;
+ }
+ }
+
+ #region Requests
+
+ ///
+ /// Creates an SMB2 NEGOTIATE request (dialects 2.0.2 - 3.1.1 with the preauth integrity context of
+ /// 3.1.1).
+ ///
+ /// GUID of the client.
+ /// Salt of the preauth integrity context (32 bytes).
+ /// SMB2 message (without the 4 byte session header).
+ public static byte[] CreateNegotiateRequest(Guid clientGuid, byte[] salt)
+ {
+ // Body: 36 bytes + dialects, the negotiate context is 8 byte aligned (relative to the SMB2 header)
+ var dialectsEnd = HeaderSize + 36 + Dialects.Length * 2;
+ var contextOffset = (dialectsEnd + 7) & ~7;
+ var contextDataLength = 2 + 2 + 2 + salt.Length;
+
+ var message = new byte[contextOffset + 8 + contextDataLength];
+ var span = message.AsSpan();
+
+ WriteHeader(span, CommandNegotiate, 0);
+
+ var body = span[HeaderSize..];
+ BinaryPrimitives.WriteUInt16LittleEndian(body, 36); // StructureSize
+ BinaryPrimitives.WriteUInt16LittleEndian(body[2..], (ushort)Dialects.Length);
+ BinaryPrimitives.WriteUInt16LittleEndian(body[4..], 0x0001); // SecurityMode: signing enabled
+ clientGuid.TryWriteBytes(body[12..]);
+ BinaryPrimitives.WriteUInt32LittleEndian(body[28..], (uint)contextOffset); // NegotiateContextOffset
+ BinaryPrimitives.WriteUInt16LittleEndian(body[32..], 1); // NegotiateContextCount
+
+ for (var i = 0; i < Dialects.Length; i++)
+ BinaryPrimitives.WriteUInt16LittleEndian(body[(36 + i * 2)..], Dialects[i]);
+
+ // SMB2_PREAUTH_INTEGRITY_CAPABILITIES: SHA-512 with a salt
+ var context = span[contextOffset..];
+ BinaryPrimitives.WriteUInt16LittleEndian(context, 0x0001); // ContextType
+ BinaryPrimitives.WriteUInt16LittleEndian(context[2..], (ushort)contextDataLength);
+ BinaryPrimitives.WriteUInt16LittleEndian(context[8..], 1); // HashAlgorithmCount
+ BinaryPrimitives.WriteUInt16LittleEndian(context[10..], (ushort)salt.Length);
+ BinaryPrimitives.WriteUInt16LittleEndian(context[12..], 0x0001); // SHA-512
+ salt.CopyTo(context[14..]);
+
+ return message;
+ }
+
+ ///
+ /// Creates an SMB2 SESSION_SETUP request with an NTLM NEGOTIATE message (in an SPNEGO token).
+ ///
+ /// SMB2 message (without the 4 byte session header).
+ public static byte[] CreateSessionSetupRequest()
+ {
+ var securityBuffer = CreateSPNEGONegTokenInit(CreateNTLMNegotiateMessage());
+
+ const int bufferOffset = HeaderSize + 24;
+
+ var message = new byte[bufferOffset + securityBuffer.Length];
+ var span = message.AsSpan();
+
+ WriteHeader(span, CommandSessionSetup, 1);
+
+ var body = span[HeaderSize..];
+ BinaryPrimitives.WriteUInt16LittleEndian(body, 25); // StructureSize
+ body[3] = 0x01; // SecurityMode: signing enabled
+ BinaryPrimitives.WriteUInt16LittleEndian(body[12..], bufferOffset); // SecurityBufferOffset
+ BinaryPrimitives.WriteUInt16LittleEndian(body[14..], (ushort)securityBuffer.Length);
+
+ securityBuffer.CopyTo(span[bufferOffset..]);
+
+ return message;
+ }
+
+ ///
+ /// Writes an SMB2 header (sync, no session).
+ ///
+ private static void WriteHeader(Span span, ushort command, ulong messageId)
+ {
+ span[0] = 0xFE;
+ span[1] = (byte)'S';
+ span[2] = (byte)'M';
+ span[3] = (byte)'B';
+ BinaryPrimitives.WriteUInt16LittleEndian(span[4..], HeaderSize); // StructureSize
+ BinaryPrimitives.WriteUInt16LittleEndian(span[6..], 1); // CreditCharge
+ BinaryPrimitives.WriteUInt16LittleEndian(span[12..], command);
+ BinaryPrimitives.WriteUInt16LittleEndian(span[14..], 1); // CreditRequest
+ BinaryPrimitives.WriteUInt64LittleEndian(span[24..], messageId);
+ }
+
+ ///
+ /// Creates an NTLM NEGOTIATE message (no domain / workstation, with version).
+ ///
+ private static byte[] CreateNTLMNegotiateMessage()
+ {
+ var message = new byte[40];
+ var span = message.AsSpan();
+
+ NTLMSSPSignature.CopyTo(span);
+ BinaryPrimitives.WriteUInt32LittleEndian(span[8..], 1); // MessageType: NEGOTIATE
+ BinaryPrimitives.WriteUInt32LittleEndian(span[12..],
+ NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_NTLM |
+ NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY |
+ NTLMSSP_NEGOTIATE_TARGET_INFO | NTLMSSP_NEGOTIATE_VERSION | NTLMSSP_NEGOTIATE_128 |
+ NTLMSSP_NEGOTIATE_56);
+
+ // Domain / workstation fields (16 bytes) empty, version 10.0 with NTLM revision 15
+ span[32] = 10;
+ span[39] = 0x0F;
+
+ return message;
+ }
+
+ ///
+ /// Wraps an NTLM message in an SPNEGO NegTokenInit (GSS-API initial context token).
+ ///
+ private static byte[] CreateSPNEGONegTokenInit(byte[] ntlmMessage)
+ {
+ // OID 1.3.6.1.4.1.311.2.2.10 (NTLMSSP)
+ byte[] ntlmOID = [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0A];
+ // OID 1.3.6.1.5.5.2 (SPNEGO)
+ byte[] spnegoOID = [0x06, 0x06, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x02];
+
+ var mechTypes = DER(0xA0, DER(0x30, ntlmOID));
+ var mechToken = DER(0xA2, DER(0x04, ntlmMessage));
+ var negTokenInit = DER(0xA0, DER(0x30, [.. mechTypes, .. mechToken]));
+
+ return DER(0x60, [.. spnegoOID, .. negTokenInit]);
+ }
+
+ ///
+ /// Encodes a DER element (tag, length, value).
+ ///
+ private static byte[] DER(byte tag, byte[] value)
+ {
+ byte[] length = value.Length switch
+ {
+ < 0x80 => [(byte)value.Length],
+ <= 0xFF => [0x81, (byte)value.Length],
+ _ => [0x82, (byte)(value.Length >> 8), (byte)value.Length]
+ };
+
+ return [tag, .. length, .. value];
+ }
+
+ #endregion
+
+ #region Responses
+
+ ///
+ /// Values of an SMB2 NEGOTIATE response.
+ ///
+ /// Negotiated dialect, e.g. "3.1.1".
+ /// The server requires signed messages.
+ /// GUID of the server.
+ /// Time of the server in UTC, null if not set.
+ public sealed record NegotiateResponse(string Dialect, bool SigningRequired, Guid ServerGuid, DateTime? SystemTime);
+
+ ///
+ /// Parses an SMB2 NEGOTIATE response.
+ ///
+ /// SMB2 message (without the 4 byte session header).
+ /// Values, null if it is not a successful negotiate response.
+ public static NegotiateResponse ParseNegotiateResponse(ReadOnlySpan message)
+ {
+ if (!IsResponse(message, CommandNegotiate, StatusSuccess) || message.Length < HeaderSize + 64)
+ return null;
+
+ var body = message[HeaderSize..];
+
+ if (BinaryPrimitives.ReadUInt16LittleEndian(body) != 65)
+ return null;
+
+ var securityMode = BinaryPrimitives.ReadUInt16LittleEndian(body[2..]);
+ var dialect = BinaryPrimitives.ReadUInt16LittleEndian(body[4..]);
+
+ return new NegotiateResponse(FormatDialect(dialect), (securityMode & 0x0002) != 0,
+ new Guid(body.Slice(8, 16)), FromFileTime(BinaryPrimitives.ReadInt64LittleEndian(body[40..])));
+ }
+
+ ///
+ /// Parses an SMB2 SESSION_SETUP response that contains an NTLM CHALLENGE message.
+ ///
+ /// SMB2 message (without the 4 byte session header).
+ /// Values of the challenge, null if there is none (e.g. NTLM disabled).
+ public static NTLMChallengeInfo ParseSessionSetupResponse(ReadOnlySpan message)
+ {
+ if (!IsResponse(message, CommandSessionSetup, StatusMoreProcessingRequired) ||
+ message.Length < HeaderSize + 8)
+ return null;
+
+ var body = message[HeaderSize..];
+
+ int offset = BinaryPrimitives.ReadUInt16LittleEndian(body[4..]);
+ int length = BinaryPrimitives.ReadUInt16LittleEndian(body[6..]);
+
+ if (offset < HeaderSize + 8 || offset + length > message.Length)
+ return null;
+
+ // The NTLM message is in the SPNEGO answer (NegTokenResp), found by its signature
+ var securityBuffer = message.Slice(offset, length);
+ var index = securityBuffer.IndexOf(NTLMSSPSignature);
+
+ return index < 0 ? null : ParseNTLMChallenge(securityBuffer[index..]);
+ }
+
+ ///
+ /// Parses an NTLM CHALLENGE message: version (if sent) and the values of the target info.
+ ///
+ /// NTLM message, starting with the signature (may be followed by other data).
+ /// Values, null if it is not a challenge message.
+ public static NTLMChallengeInfo ParseNTLMChallenge(ReadOnlySpan message)
+ {
+ if (message.Length < 48 || !message[..8].SequenceEqual(NTLMSSPSignature) ||
+ BinaryPrimitives.ReadUInt32LittleEndian(message[8..]) != 2)
+ return null;
+
+ var flags = BinaryPrimitives.ReadUInt32LittleEndian(message[20..]);
+
+ int targetInfoLength = BinaryPrimitives.ReadUInt16LittleEndian(message[40..]);
+ var targetInfoOffset = BinaryPrimitives.ReadUInt32LittleEndian(message[44..]);
+
+ // Version (8 bytes after the target info fields), only if negotiated and the payload starts after it
+ Version version = null;
+
+ if ((flags & NTLMSSP_NEGOTIATE_VERSION) != 0 && message.Length >= 56 &&
+ (targetInfoLength == 0 || targetInfoOffset >= 56) && message[48] != 0)
+ version = new Version(message[48], message[49], BinaryPrimitives.ReadUInt16LittleEndian(message[50..]));
+
+ string nbComputer = string.Empty, nbDomain = string.Empty, dnsComputer = string.Empty,
+ dnsDomain = string.Empty, dnsTree = string.Empty;
+ DateTime? timestamp = null;
+
+ if (targetInfoLength > 0 && targetInfoOffset + (ulong)targetInfoLength <= (ulong)message.Length)
+ {
+ var targetInfo = message.Slice((int)targetInfoOffset, targetInfoLength);
+
+ // AV_PAIR list: id, length, value; ends with MsvAvEOL
+ while (targetInfo.Length >= 4)
+ {
+ var id = BinaryPrimitives.ReadUInt16LittleEndian(targetInfo);
+ int length = BinaryPrimitives.ReadUInt16LittleEndian(targetInfo[2..]);
+
+ if (id == 0 || targetInfo.Length < 4 + length)
+ break;
+
+ var value = targetInfo.Slice(4, length);
+
+ switch (id)
+ {
+ case 1:
+ nbComputer = ToString(value);
+ break;
+ case 2:
+ nbDomain = ToString(value);
+ break;
+ case 3:
+ dnsComputer = ToString(value);
+ break;
+ case 4:
+ dnsDomain = ToString(value);
+ break;
+ case 5:
+ dnsTree = ToString(value);
+ break;
+ case 7 when length == 8:
+ timestamp = FromFileTime(BinaryPrimitives.ReadInt64LittleEndian(value));
+ break;
+ }
+
+ targetInfo = targetInfo[(4 + length)..];
+ }
+ }
+
+ return new NTLMChallengeInfo(version, nbComputer, nbDomain, dnsComputer, dnsDomain, dnsTree, timestamp);
+ }
+
+ ///
+ /// Formats an SMB2 dialect, e.g. 0x0311 -> "3.1.1", 0x0210 -> "2.1".
+ ///
+ public static string FormatDialect(ushort dialect)
+ {
+ var major = (dialect >> 8) & 0xF;
+ var minor = (dialect >> 4) & 0xF;
+ var patch = dialect & 0xF;
+
+ return patch == 0 ? $"{major}.{minor}" : $"{major}.{minor}.{patch}";
+ }
+
+ ///
+ /// The message is an SMB2 response of the command with the status.
+ ///
+ private static bool IsResponse(ReadOnlySpan message, ushort command, uint status)
+ {
+ return message.Length >= HeaderSize &&
+ message[0] == 0xFE && message[1] == 'S' && message[2] == 'M' && message[3] == 'B' &&
+ BinaryPrimitives.ReadUInt32LittleEndian(message[8..]) == status &&
+ BinaryPrimitives.ReadUInt16LittleEndian(message[12..]) == command &&
+ (BinaryPrimitives.ReadUInt32LittleEndian(message[16..]) & 0x00000001) != 0; // SMB2_FLAGS_SERVER_TO_REDIR
+ }
+
+ ///
+ /// Converts a FILETIME to UTC, null if it is not set or invalid.
+ ///
+ private static DateTime? FromFileTime(long fileTime)
+ {
+ if (fileTime <= 0)
+ return null;
+
+ try
+ {
+ return DateTime.FromFileTimeUtc(fileTime);
+ }
+ catch (ArgumentOutOfRangeException)
+ {
+ return null;
+ }
+ }
+
+ ///
+ /// Decodes a UTF-16 value of the target info without control characters.
+ ///
+ private static string ToString(ReadOnlySpan value)
+ {
+ return StringHelper.RemoveControlCharacters(Encoding.Unicode.GetString(value));
+ }
+
+ #endregion
+
+ #region Transport
+
+ ///
+ /// Writes an SMB2 message with the 4 byte session header (direct TCP transport: zero byte + 24 bit length).
+ ///
+ private static async Task WriteMessageAsync(Stream stream, byte[] message, CancellationToken cancellationToken)
+ {
+ var packet = new byte[4 + message.Length];
+ packet[1] = (byte)(message.Length >> 16);
+ packet[2] = (byte)(message.Length >> 8);
+ packet[3] = (byte)message.Length;
+ message.CopyTo(packet, 4);
+
+ await stream.WriteAsync(packet, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Reads an SMB2 message (without the 4 byte session header).
+ ///
+ private static async Task ReadMessageAsync(Stream stream, CancellationToken cancellationToken)
+ {
+ var header = new byte[4];
+ await stream.ReadExactlyAsync(header, cancellationToken).ConfigureAwait(false);
+
+ var length = (header[1] << 16) | (header[2] << 8) | header[3];
+
+ if (header[0] != 0 || length is < HeaderSize or > MaxMessageSize)
+ throw new InvalidDataException("Invalid SMB session header.");
+
+ var message = new byte[length];
+ await stream.ReadExactlyAsync(message, cancellationToken).ConfigureAwait(false);
+
+ return message;
+ }
+
+ #endregion
+}
diff --git a/Source/NETworkManager.Models/Network/SNMPSystemInfoResolver.cs b/Source/NETworkManager.Models/Network/SNMPSystemInfoResolver.cs
index 3a1e2a3779..1371a1b2c8 100644
--- a/Source/NETworkManager.Models/Network/SNMPSystemInfoResolver.cs
+++ b/Source/NETworkManager.Models/Network/SNMPSystemInfoResolver.cs
@@ -7,6 +7,7 @@
using Lextm.SharpSnmpLib;
using Lextm.SharpSnmpLib.Messaging;
using Lextm.SharpSnmpLib.Security;
+using NETworkManager.Utilities;
namespace NETworkManager.Models.Network;
@@ -275,8 +276,6 @@ private static string GetValue(ISnmpData data)
return string.Empty;
// Control characters (e.g. line breaks in sysDescr) are shown as spaces, several spaces as one
- var value = new string([.. octetString.ToString().Select(x => char.IsControl(x) ? ' ' : x)]);
-
- return string.Join(' ', value.Split(' ', StringSplitOptions.RemoveEmptyEntries));
+ return StringHelper.ReplaceControlCharactersWithSpace(octetString.ToString());
}
}
diff --git a/Source/NETworkManager.Models/Network/SocketOperation.cs b/Source/NETworkManager.Models/Network/SocketOperation.cs
index 36982365b9..b37a441d4f 100644
--- a/Source/NETworkManager.Models/Network/SocketOperation.cs
+++ b/Source/NETworkManager.Models/Network/SocketOperation.cs
@@ -9,7 +9,8 @@ namespace NETworkManager.Models.Network;
/// methods (e.g. ), these report the result as
/// instead of throwing an exception for every refused connection, timeout or
/// unreachable host. A scan has thousands of these, and every exception is slow with a debugger attached
-/// (the whole application lags). Used by and .
+/// (the whole application lags). Used by , and
+/// .
///
internal static class SocketOperation
{
diff --git a/Source/NETworkManager.Models/Network/WebPageResolver.cs b/Source/NETworkManager.Models/Network/WebPageResolver.cs
index b339a88a6e..e8c2dd3026 100644
--- a/Source/NETworkManager.Models/Network/WebPageResolver.cs
+++ b/Source/NETworkManager.Models/Network/WebPageResolver.cs
@@ -7,6 +7,7 @@
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
+using NETworkManager.Utilities;
namespace NETworkManager.Models.Network;
@@ -260,8 +261,7 @@ public static string ParseRealm(IEnumerable headerValues)
/// Cleaned value.
public static string CleanHeaderValue(string value)
{
- var withoutControlCharacters = new string([.. (value ?? string.Empty).Where(x => !char.IsControl(x))]);
- var cleaned = WhitespaceRegex().Replace(withoutControlCharacters, " ").Trim();
+ var cleaned = WhitespaceRegex().Replace(StringHelper.RemoveControlCharacters(value), " ").Trim();
return cleaned.Length > MaxTitleLength ? cleaned[..MaxTitleLength] + "..." : cleaned;
}
@@ -334,7 +334,7 @@ public static string ParseTitle(string html)
var title = WhitespaceRegex().Replace(WebUtility.HtmlDecode(match.Groups[1].Value), " ").Trim();
// Control characters (e.g. from a broken page) are not shown
- title = new string([.. title.Where(x => !char.IsControl(x))]);
+ title = StringHelper.RemoveControlCharacters(title);
return title.Length > MaxTitleLength ? title[..MaxTitleLength] + "..." : title;
}
diff --git a/Source/NETworkManager.Models/Network/WindowsCredentials.cs b/Source/NETworkManager.Models/Network/WindowsCredentials.cs
new file mode 100644
index 0000000000..d10523408b
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/WindowsCredentials.cs
@@ -0,0 +1,55 @@
+using System.Security;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Windows credentials of a profile / group as kept by an IP Scanner tab for the Windows host information. The
+/// password stays protected (): it is only copied to unmanaged memory for the logon of a
+/// scan, never converted to a managed string.
+///
+/// Username (also "DOMAIN\user" or "user@domain" with an empty domain).
+/// Domain, "." for a local account of the host or empty.
+/// Password.
+public sealed record WindowsCredentials(string Username, string Domain, SecureString Password)
+{
+ ///
+ /// User as shown in the IP Scanner (e.g. "CORP\admin"), without the password.
+ ///
+ public string DisplayName
+ {
+ get
+ {
+ // As used for the logon (e.g. not "CORP\CORP\admin" for "CORP\admin" with the domain "CORP")
+ var (username, domain) = WindowsLogon.SplitUsername(Username, Domain);
+
+ return domain == null ? username : $@"{domain}\{username}";
+ }
+ }
+
+ ///
+ /// Local account of the scanned hosts ("." as domain, e.g. ".\admin").
+ ///
+ public bool IsLocalAccount => WindowsLogon.SplitUsername(Username, Domain).domain == ".";
+
+ ///
+ /// Gets the credentials of a local account for one host: its computer name as domain (e.g. "PC01\admin"
+ /// instead of ".\admin"), so the host checks them with its own accounts - never passed to a domain controller.
+ ///
+ /// NetBIOS name of the host (of its NTLM challenge).
+ /// Credentials for the host (same password), null if they are not a local account.
+ public WindowsCredentials ForHost(string computerName)
+ {
+ if (!IsLocalAccount || string.IsNullOrEmpty(computerName))
+ return null;
+
+ return new WindowsCredentials(WindowsLogon.SplitUsername(Username, Domain).username, computerName, Password);
+ }
+
+ ///
+ /// Without the password.
+ ///
+ public override string ToString()
+ {
+ return DisplayName;
+ }
+}
diff --git a/Source/NETworkManager.Models/Network/WindowsHostInfo.cs b/Source/NETworkManager.Models/Network/WindowsHostInfo.cs
new file mode 100644
index 0000000000..e62b826ccc
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/WindowsHostInfo.cs
@@ -0,0 +1,294 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Windows host information of the IP Scanner: what the host reveals without credentials in the SMB negotiation
+/// () and what is read with the NetApi / remote registry with the credentials of the scan
+/// (). The values for the result combine both (the more precise one first).
+///
+/// SMB / NTLM information, null if the host didn't answer on TCP 445.
+/// NetApi information, null if it was not read (no SMB answer).
+public sealed record WindowsHostInfo(SMBInfo SMB, WindowsNetApiInfo NetApi)
+{
+ ///
+ /// Win32 error of a request that timed out (ERROR_TIMEOUT).
+ ///
+ public const int ErrorTimeout = 1460;
+
+ ///
+ /// Error of a host whose NetApi requests were not sent: the credentials were rejected on another host (wrong
+ /// username or password), see . Not a Win32 error.
+ ///
+ public const int ErrorLogonSkipped = -1;
+
+ ///
+ /// Error of a host whose NetApi requests were not sent: it waited longer than the timeout while the credentials
+ /// were checked on other hosts, see . Not a Win32 error.
+ ///
+ public const int ErrorLogonNotChecked = -2;
+
+ ///
+ /// Win32 error of a logon type that is not granted on the host (ERROR_LOGON_TYPE_NOT_GRANTED, e.g. "Deny
+ /// access to this computer from the network"): checked by the host after the domain controller accepted the
+ /// password.
+ ///
+ public const int ErrorLogonTypeNotGranted = 1385;
+
+ ///
+ /// Win32 errors of a logon that is not allowed for the account: account restriction (e.g. Protected Users with
+ /// NTLM), logon hours, workstation, logon type not granted. No failed logon is counted for them (checked after
+ /// the password, or the password was not checked).
+ ///
+ private static readonly HashSet LogonNotAllowedErrors = [1327, 1328, 1329, ErrorLogonTypeNotGranted];
+
+ ///
+ /// Win32 errors of NetApi requests whose logon was not decided: the host (or its SMB / RPC service) can't be
+ /// reached, the connection was closed, the domain controller of the host can't be reached or NTLM is blocked -
+ /// no domain controller checked the password. Every other error may be a failed logon (e.g. a Kerberos / SSPI
+ /// error of a wrong password), see .
+ ///
+ private static readonly HashSet LogonNotDecidedErrors =
+ [
+ 50, // ERROR_NOT_SUPPORTED
+ 53, // ERROR_BAD_NETPATH
+ 59, // ERROR_UNEXP_NET_ERR
+ 64, // ERROR_NETNAME_DELETED
+ 67, // ERROR_BAD_NET_NAME
+ 121, // ERROR_SEM_TIMEOUT
+ 1214, // ERROR_INVALID_NETNAME
+ 1225, // ERROR_CONNECTION_REFUSED
+ 1231, // ERROR_NETWORK_UNREACHABLE
+ 1232, // ERROR_HOST_UNREACHABLE
+ 1236, // ERROR_CONNECTION_ABORTED
+ 1311, // ERROR_NO_LOGON_SERVERS
+ ErrorTimeout,
+ 1722, // RPC_S_SERVER_UNAVAILABLE
+ 1726, // RPC_S_CALL_FAILED
+ 1727, // RPC_S_CALL_FAILED_DNE
+ 1753, // EPT_S_NOT_REGISTERED
+ 1788, // ERROR_TRUSTED_DOMAIN_FAILURE
+ 1789, // ERROR_TRUSTED_RELATIONSHIP_FAILURE
+ 1937, // ERROR_NTLM_BLOCKED
+ 2102, // NERR_WkstaNotStarted
+ 2114 // NERR_ServerNotStarted
+ ];
+
+ ///
+ /// Version of Windows: of the registry (with patch level), otherwise of the NTLM challenge (major.minor.build),
+ /// null if none is known (or it has no build, e.g. Samba).
+ ///
+ public Version Version => NetApi?.Registry?.Version ?? (SMB?.NTLM?.Version is { Build: > 0 } version ? version : null);
+
+ ///
+ /// Role of the host (NetApi), unknown if it was not read.
+ ///
+ public WindowsHostRole Role => NetApi?.Role ?? WindowsHostRole.Unknown;
+
+ ///
+ /// The host is a server (incl. domain controller): of the role, otherwise of the installation type of the
+ /// registry, null if unknown.
+ ///
+ public bool? IsServer => Role switch
+ {
+ WindowsHostRole.Server or WindowsHostRole.DomainController => true,
+ WindowsHostRole.Workstation => false,
+ _ => NetApi?.Registry?.IsServer
+ };
+
+ ///
+ /// Name of the operating system, e.g. "Windows 11 25H2" (the display version of the registry for a build that
+ /// is not known yet), empty if not known.
+ ///
+ public string OS
+ {
+ get
+ {
+ var name = WindowsVersionHelper.GetName(Version, IsServer);
+
+ if (name == null)
+ return string.Empty;
+
+ var displayVersion = NetApi?.Registry?.DisplayVersion;
+
+ // Newer Windows 11 build than the list: e.g. "Windows 11 (build 27000)" -> "Windows 11 26H1". Not for other
+ // unknown builds: the display version of a server (e.g. 24H2 for Server 2025) doesn't name the release, a
+ // name without "Server" would look like a client - they keep the build
+ return !string.IsNullOrEmpty(displayVersion) && Version != null &&
+ name == $"Windows 11 (build {Version.Build})"
+ ? $"Windows 11 {displayVersion}"
+ : name;
+ }
+ }
+
+ ///
+ /// Edition (registry), e.g. "Pro" or "Datacenter", empty if not read.
+ ///
+ public string Edition => WindowsNetApiResolver.GetEditionName(NetApi?.Registry?.EditionID);
+
+ ///
+ /// The host is in a domain (NTLM challenge, otherwise NetApi), null if unknown.
+ ///
+ public bool? IsDomainMember => SMB?.NTLM != null ? SMB.NTLM.IsDomainMember : NetApi?.IsDomainMember;
+
+ ///
+ /// Domain (DNS name, otherwise NetBIOS name) or workgroup of the host, empty if not known.
+ ///
+ public string Domain
+ {
+ get
+ {
+ var ntlm = SMB?.NTLM;
+
+ if (IsDomainMember == true)
+ {
+ if (!string.IsNullOrEmpty(ntlm?.DNSDomainName))
+ return ntlm.DNSDomainName;
+
+ if (!string.IsNullOrEmpty(ntlm?.NetBIOSDomainName))
+ return ntlm.NetBIOSDomainName;
+ }
+
+ // A computer in a workgroup sends its own name as domain in the challenge - the workgroup is only known
+ // from the NetApi
+ return NetApi?.Workgroup ?? string.Empty;
+ }
+ }
+
+ ///
+ /// Computer name of the host (DNS name, otherwise NetBIOS name of the NTLM challenge), empty if not known.
+ ///
+ public string ComputerName => !string.IsNullOrEmpty(SMB?.NTLM?.DNSComputerName)
+ ? SMB.NTLM.DNSComputerName
+ : SMB?.NTLM?.NetBIOSComputerName ?? string.Empty;
+
+ ///
+ /// Time of the host minus the local time, null if not known.
+ ///
+ public TimeSpan? TimeOffset => SMB?.TimeOffset;
+
+ ///
+ /// Logged-on users, null if they could not be read (see ).
+ ///
+ public IReadOnlyList Users => NetApi?.Users;
+
+ ///
+ /// Description of the computer, empty if none.
+ ///
+ public string Description => NetApi?.Description ?? string.Empty;
+
+ ///
+ /// Win32 error of the NetApi (0 if it succeeded or was not read).
+ ///
+ public int Error => NetApi?.Error ?? 0;
+
+ ///
+ /// Win32 error of the logged-on users (0 if they were read or the NetApi was not read).
+ ///
+ public int UsersError => NetApi?.UsersError ?? 0;
+
+ ///
+ /// Checks if a Win32 error of the NetApi requests is a logon that is not allowed for the account (e.g. on this
+ /// host or at this time): no failed logon at the domain controller, but the password is not proven either
+ /// (except ).
+ ///
+ /// Win32 error.
+ /// True if the logon is not allowed.
+ public static bool IsLogonNotAllowed(int error)
+ {
+ return LogonNotAllowedErrors.Contains(error);
+ }
+
+ ///
+ /// Checks if a Win32 error of the NetApi requests shows that the logon was not decided (host, network, RPC or
+ /// the domain controller of the host not reachable). The lockout protection counts every other error as a
+ /// failed logon, so an unknown error of a wrong password can't let the next hosts try it.
+ ///
+ /// Win32 error.
+ /// True if no domain controller checked the password.
+ public static bool IsLogonNotDecided(int error)
+ {
+ return LogonNotDecidedErrors.Contains(error);
+ }
+
+ ///
+ /// Gets the message of a Win32 error (of Windows, in the language of the system). NetApi errors (NERR_*,
+ /// 2100 - 2999, e.g. 2114 "The Server service is not started.") are read from netmsg.dll, they are not
+ /// in the messages of the system.
+ ///
+ /// Win32 error.
+ ///
+ /// Message, empty for 0, and (translated
+ /// by the caller).
+ ///
+ public static string GetErrorMessage(int error)
+ {
+ if (error is 0 or ErrorLogonSkipped or ErrorLogonNotChecked)
+ return string.Empty;
+
+ if (error is >= NERR_BASE and <= MAX_NERR && GetNetApiMessage(error) is { Length: > 0 } message)
+ return message;
+
+ return new Win32Exception(error).Message;
+ }
+
+ #region NetApi messages
+
+ private const int NERR_BASE = 2100;
+ private const int MAX_NERR = 2999;
+
+ private const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
+ private const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
+ private const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800;
+
+ // netmsg.dll as data file, loaded once (IntPtr.Zero if it can't be loaded, e.g. not on Windows)
+ private static readonly Lazy NetMsgModule = new(() =>
+ {
+ try
+ {
+ return LoadLibraryEx("netmsg.dll", IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE);
+ }
+ catch (Exception)
+ {
+ return IntPtr.Zero;
+ }
+ });
+
+ ///
+ /// Gets the message of a NetApi error from netmsg.dll, null if it is not known.
+ ///
+ private static string GetNetApiMessage(int error)
+ {
+ var module = NetMsgModule.Value;
+
+ if (module == IntPtr.Zero)
+ return null;
+
+ try
+ {
+ var buffer = new StringBuilder(512);
+
+ var length = FormatMessage(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS, module,
+ (uint)error, 0, buffer, buffer.Capacity, IntPtr.Zero);
+
+ return length > 0 ? buffer.ToString().Trim() : null;
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ }
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "LoadLibraryExW")]
+ private static extern IntPtr LoadLibraryEx(string lpLibFileName, IntPtr hFile, uint dwFlags);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "FormatMessageW")]
+ private static extern int FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId,
+ StringBuilder lpBuffer, int nSize, IntPtr arguments);
+
+ #endregion
+}
diff --git a/Source/NETworkManager.Models/Network/WindowsLogon.cs b/Source/NETworkManager.Models/Network/WindowsLogon.cs
new file mode 100644
index 0000000000..5b087937c2
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/WindowsLogon.cs
@@ -0,0 +1,102 @@
+using System;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Security.Principal;
+using Microsoft.Win32.SafeHandles;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Network logon with other Windows credentials, like runas /netonly: LogonUser with
+/// LOGON32_LOGON_NEW_CREDENTIALS creates a token that is a copy of the current user locally and uses the
+/// credentials only for outgoing network connections (SMB / RPC). No privileges or admin rights are needed. The
+/// credentials are not checked by the logon: a wrong password is reported by the host (e.g.
+/// ERROR_LOGON_FAILURE). Unlike WNetAddConnection2, no SMB session of the user is created or
+/// changed (no conflict with mapped drives).
+///
+public sealed class WindowsLogon : IDisposable
+{
+ private const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
+ private const int LOGON32_PROVIDER_WINNT50 = 3;
+
+ private readonly SafeAccessTokenHandle _token;
+
+ private WindowsLogon(SafeAccessTokenHandle token)
+ {
+ _token = token;
+ }
+
+ ///
+ /// Creates the network logon. The password is copied to unmanaged memory for the call only (zeroed and freed
+ /// afterwards), it is never converted to a managed string.
+ ///
+ /// Credentials.
+ /// Logon, dispose it when it is no longer used.
+ /// The logon failed (e.g. invalid username).
+ public static WindowsLogon Create(WindowsCredentials credentials)
+ {
+ var (username, domain) = SplitUsername(credentials.Username, credentials.Domain);
+
+ var password = credentials.Password != null
+ ? Marshal.SecureStringToGlobalAllocUnicode(credentials.Password)
+ : Marshal.StringToHGlobalUni(string.Empty);
+
+ try
+ {
+ if (!LogonUser(username, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50,
+ out var token))
+ throw new Win32Exception(Marshal.GetLastWin32Error());
+
+ return new WindowsLogon(token);
+ }
+ finally
+ {
+ Marshal.ZeroFreeGlobalAllocUnicode(password);
+ }
+ }
+
+ ///
+ /// Runs a (blocking) function with the network logon on the current thread. Never use it around an
+ /// await: the impersonation belongs to the thread.
+ ///
+ /// Function, e.g. NetApi calls to a host.
+ /// Result.
+ /// Result of the function.
+ public T Run(Func func)
+ {
+ return WindowsIdentity.RunImpersonated(_token, func);
+ }
+
+ ///
+ /// Splits the username into user and domain for LogonUser: "DOMAIN\user" uses the domain of the
+ /// username (also if a domain is set - "DOMAIN\user" as user would always fail), "user@domain" (UPN) needs no
+ /// domain (null), otherwise the domain (null if empty).
+ ///
+ /// Username.
+ /// Domain, may be empty.
+ /// Username and domain (null for a UPN or without domain).
+ public static (string username, string domain) SplitUsername(string username, string domain)
+ {
+ username ??= string.Empty;
+
+ var index = username.IndexOf('\\');
+
+ if (index > 0)
+ return (username[(index + 1)..], username[..index]);
+
+ // UPN (user@domain): LogonUser takes it as it is, the domain must be null
+ if (username.Contains('@'))
+ return (username, null);
+
+ return (username, string.IsNullOrEmpty(domain) ? null : domain);
+ }
+
+ public void Dispose()
+ {
+ _token.Dispose();
+ }
+
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "LogonUserW")]
+ private static extern bool LogonUser(string lpszUsername, string lpszDomain, IntPtr lpszPassword,
+ int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);
+}
diff --git a/Source/NETworkManager.Models/Network/WindowsLogonGate.cs b/Source/NETworkManager.Models/Network/WindowsLogonGate.cs
new file mode 100644
index 0000000000..5368d461dd
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/WindowsLogonGate.cs
@@ -0,0 +1,710 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Cryptography;
+using System.Threading;
+using System.Threading.Tasks;
+using log4net;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Protects the account of the Windows credentials of a scan from being locked out. With a wrong password, every
+/// host in a domain makes the domain controller count a failed logon - a /24 with many Windows hosts would reach the
+/// lockout threshold in seconds. The credentials are checked on one host first (the others wait); only if they are
+/// accepted, the hosts run in parallel:
+///
+/// Accepted (success, access denied = logged on without rights, or a logon type the host doesn't grant
+/// after the password was checked) on a Windows host in the domain of the credentials: all hosts run, the logon
+/// failures of the account are reset (like the domain controller does). A success on a host of another domain,
+/// on a host that is not Windows or with credentials without domain proves nothing - a host that maps a failed
+/// logon to guest (e.g. a NAS with map to guest = bad user outside the domain, or a Samba / NAS member
+/// of the domain with map to guest = bad password) or a local account with the same name also answer a
+/// wrong password: only this host uses them, the next host checks them.
+/// Logon failure on a host in the domain of the credentials (the domain controller checked them), any
+/// logon failure if the credentials have no domain (e.g. "admin"), or the max. logon failures (setting) on hosts
+/// of other domains: rejected, the remaining hosts are not tried. Also after they were accepted: a logon
+/// failure on a host in their domain while the hosts run (e.g. the password was changed or the account locked
+/// during the scan) rejects them for the hosts that didn't start yet.
+/// Errors that show the logon was not decided (timeout, host / RPC / domain controller of the host not
+/// reachable, see ) or a logon failure on a computer of
+/// another domain: the next host checks. Every other error counts as a logon failure (e.g. a Kerberos / SSPI
+/// error of a wrong password that is not known as one).
+///
+/// Hosts whose logon can't count at a domain controller are not gated: computers in a workgroup and local accounts
+/// ("." or the computer name as domain; "." is logged on with the computer name of each host, see
+/// ) - a failure there only affects the host itself. Only a host whose
+/// computer and domain name are known from its NTLM challenge.
+///
+/// Per account (e.g. "CORP\admin", also "corp.example.com\admin" = "admin@corp.example.com") for all gates
+/// (tabs) until the application is closed, like the domain controller counts them: one host checks them at a
+/// time, the logon failures are counted, and a rejected password stays rejected - a new gate (e.g. another tab
+/// of the same profile) with it starts rejected. A new gate with another password (e.g. corrected in the
+/// profile) or with credentials the user entered (also unchanged, e.g. after the account was unlocked) checks
+/// them again.
+///
+///
+public sealed class WindowsLogonGate
+{
+ private static readonly ILog Log = LogManager.GetLogger(typeof(WindowsLogonGate));
+
+ ///
+ /// State of each account for all gates of the application, see .
+ ///
+ private static readonly ConcurrentDictionary Accounts =
+ new(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// Random key of the password fingerprints (), new for every start of the
+ /// application - the fingerprints only exist in memory.
+ ///
+ private static readonly byte[] FingerprintKey = RandomNumberGenerator.GetBytes(32);
+
+ ///
+ /// State of an account, shared by all its gates.
+ ///
+ private sealed class AccountState
+ {
+ ///
+ /// One host of all gates of the account checks the credentials at a time.
+ ///
+ public readonly SemaphoreSlim Turn = new(1, 1);
+
+ ///
+ /// Fingerprints of the rejected passwords: a new gate with one of them starts rejected (locked by the
+ /// state).
+ ///
+ public readonly HashSet RejectedPasswords = new(StringComparer.Ordinal);
+
+ ///
+ /// Logon failures of the account (reset by an accept in the domain).
+ ///
+ public int LogonFailures;
+ }
+
+ ///
+ /// What a host does with the credentials.
+ ///
+ public enum Decision
+ {
+ ///
+ /// Use them (accepted, or not gated). Don't call ; call
+ /// (gated) or (not gated) with the result.
+ ///
+ Proceed,
+
+ ///
+ /// Use them and check them: call with the result (also on an error / cancellation).
+ ///
+ Check,
+
+ ///
+ /// Don't use them, they were rejected on another host.
+ ///
+ Skip,
+
+ ///
+ /// Not used: the host waited longer than the timeout for its turn (another host is still checking them).
+ ///
+ Timeout
+ }
+
+ private enum State
+ {
+ Unchecked,
+ Accepted,
+ Rejected
+ }
+
+ // Order: _lock, then _accountState (never the other way)
+ private readonly Lock _lock = new();
+
+ // Of the account (shared with its other gates): its turn, rejected passwords and logon failures
+ private readonly AccountState _accountState;
+ private readonly SemaphoreSlim _turn;
+
+ // Keyed hash of the password of the credentials, see GetPasswordFingerprint
+ private readonly string _passwordFingerprint;
+
+ // Account as used for the logon (e.g. "CORP\admin") for the log, never the password
+ private readonly string _account;
+
+ private readonly string _domain;
+ private readonly bool _isLocalAccount;
+
+ // UPN (user@suffix): resolved by a domain controller of the host, also with a suffix that is not a domain name
+ private readonly bool _isUpn;
+
+ // Hosts of the scan that were not tried (rejected / waited longer than the timeout), for the log of the scan
+ private int _skippedHosts;
+ private int _timedOutHosts;
+
+ private State _state;
+
+ // Completed when the credentials are accepted / rejected (new when a scan checks them again): hosts of other
+ // domains wait for it first, see WaitAsync
+ private TaskCompletionSource _decided = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ // Max. logon failures on hosts of other domains (setting of the scan, see StartScan), 1 until a scan started
+ private int _maxLogonFailures = 1;
+
+ // Hosts that are not gated and rejected the credentials themselves (e.g. a workgroup computer): not tried again
+ private readonly HashSet _rejectedHosts = new(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// Creates the gate for the credentials of a scan (kept by the tab for all its scans).
+ ///
+ /// Credentials of the scan.
+ ///
+ /// The user entered the credentials (e.g. Set Windows credentials..., Scan as..., also unchanged): checked
+ /// again also if their password was rejected before. Otherwise (e.g. of a profile) a rejected password starts
+ /// rejected.
+ ///
+ public WindowsLogonGate(WindowsCredentials credentials, bool isEnteredByUser = false)
+ {
+ var (username, domain) = WindowsLogon.SplitUsername(credentials.Username, credentials.Domain);
+
+ // UPN (user@corp.example.com): the domain is the suffix
+ if (domain == null && username.Contains('@'))
+ {
+ domain = username[(username.LastIndexOf('@') + 1)..];
+ _isUpn = true;
+ }
+
+ _domain = domain ?? string.Empty;
+ _isLocalAccount = _domain == ".";
+
+ _account = credentials.DisplayName;
+
+ _accountState = Accounts.GetOrAdd(GetAccountKey(username, _domain), _ => new AccountState());
+ _turn = _accountState.Turn;
+ _passwordFingerprint = GetPasswordFingerprint(credentials.Password);
+
+ lock (_accountState)
+ {
+ if (isEnteredByUser)
+ _accountState.RejectedPasswords.Remove(_passwordFingerprint);
+ else if (_accountState.RejectedPasswords.Contains(_passwordFingerprint))
+ {
+ _state = State.Rejected;
+ _decided.TrySetResult();
+ }
+ }
+ }
+
+ ///
+ /// Gets the key of an account: "domain\user" (the suffix of a UPN as domain, so "admin@corp.example.com" is
+ /// "corp.example.com\admin"), the user without domain.
+ ///
+ /// Username as used for the logon (without the domain of "DOMAIN\user").
+ /// Domain (also of a UPN), empty if none.
+ /// Key, compared ignoring the case.
+ private static string GetAccountKey(string username, string domain)
+ {
+ if (username.Contains('@'))
+ username = username[..username.LastIndexOf('@')];
+
+ return string.IsNullOrEmpty(domain) ? username : $@"{domain}\{username}";
+ }
+
+ ///
+ /// Gets a keyed hash (HMAC-SHA256, random key per start of the application) of a password, to know if a
+ /// password was rejected without keeping it. The password is only copied to a pinned buffer that is zeroed right
+ /// away.
+ ///
+ /// Password, null for an empty one.
+ /// Fingerprint (Base64).
+ private static string GetPasswordFingerprint(SecureString password)
+ {
+ if (password == null || password.Length == 0)
+ return Convert.ToBase64String(HMACSHA256.HashData(FingerprintKey, ReadOnlySpan.Empty));
+
+ var length = password.Length * 2;
+ var buffer = GC.AllocateArray(length, pinned: true);
+ var unmanaged = Marshal.SecureStringToGlobalAllocUnicode(password);
+
+ try
+ {
+ Marshal.Copy(unmanaged, buffer, 0, length);
+
+ return Convert.ToBase64String(HMACSHA256.HashData(FingerprintKey, buffer));
+ }
+ finally
+ {
+ CryptographicOperations.ZeroMemory(buffer);
+ Marshal.ZeroFreeGlobalAllocUnicode(unmanaged);
+ }
+ }
+
+ ///
+ /// Rejects the credentials (called in the lock): also for the other gates of the account with this password.
+ ///
+ private void SetRejected()
+ {
+ _state = State.Rejected;
+ _decided.TrySetResult();
+
+ lock (_accountState)
+ _accountState.RejectedPasswords.Add(_passwordFingerprint);
+ }
+
+ ///
+ /// Raised once when the credentials are rejected - also after the scan was completed (a check that exceeded the
+ /// timeout reports its result when Windows returns). Raised on the thread of the report.
+ ///
+ public event EventHandler Rejected;
+
+ ///
+ /// The credentials were rejected (wrong username or password).
+ ///
+ public bool IsRejected
+ {
+ get
+ {
+ lock (_lock)
+ return _state == State.Rejected;
+ }
+ }
+
+ ///
+ /// Starts a scan with the gate (kept by the tab for all its scans): credentials accepted in an earlier scan are
+ /// checked again (e.g. the password was changed or expired since then), the logon failures and a rejection are
+ /// kept (also a rejection of the password in another gate of the account since then).
+ ///
+ ///
+ /// Max. logon failures on hosts of other domains before the credentials are rejected (setting, min. 1).
+ ///
+ public void StartScan(int maxLogonFailures)
+ {
+ State state;
+
+ lock (_lock)
+ {
+ _maxLogonFailures = Math.Max(1, maxLogonFailures);
+
+ if (_state == State.Accepted)
+ {
+ _state = State.Unchecked;
+ _decided = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ }
+
+ UpdateFromAccount();
+
+ state = _state;
+ }
+
+ Interlocked.Exchange(ref _skippedHosts, 0);
+ Interlocked.Exchange(ref _timedOutHosts, 0);
+
+ if (state == State.Rejected)
+ Log.Info($"Windows credentials \"{_account}\" were rejected before (in an earlier scan or another tab), " +
+ "they are not used for the domain hosts of this scan (lockout protection).");
+ else
+ Log.Info($"Scan with the Windows credentials \"{_account}\": checked on one host first (lockout " +
+ $"protection, max. {_maxLogonFailures} logon failure(s) on hosts of other domains, " +
+ $"{Volatile.Read(ref _accountState.LogonFailures)} counted for the account).");
+ }
+
+ ///
+ /// Logs the hosts of the scan that didn't use the credentials (rejected, or waited longer than the timeout for
+ /// the check on another host) - once per scan instead of per host.
+ ///
+ public void LogScanSummary()
+ {
+ var skipped = Volatile.Read(ref _skippedHosts);
+ var timedOut = Volatile.Read(ref _timedOutHosts);
+
+ if (skipped > 0)
+ Log.Info($"{skipped} host(s) didn't use the Windows credentials \"{_account}\": rejected (lockout " +
+ "protection).");
+
+ if (timedOut > 0)
+ Log.Info($"{timedOut} host(s) didn't use the Windows credentials \"{_account}\": waited longer than " +
+ "the timeout while they were checked on another host (lockout protection).");
+ }
+
+ ///
+ /// Name of a host for the log: IP address, computer name and domain of the NTLM challenge (e.g. "10.0.0.5
+ /// (CLIENT01, domain CORP)", "10.0.2.1 (PC01, workgroup)").
+ ///
+ private static string GetHostName(string host, NTLMChallengeInfo ntlm)
+ {
+ if (string.IsNullOrEmpty(ntlm?.NetBIOSComputerName))
+ return $"{host} (no NTLM computer name)";
+
+ return ntlm.IsDomainMember
+ ? $"{host} ({ntlm.NetBIOSComputerName}, domain {ntlm.NetBIOSDomainName})"
+ : $"{host} ({ntlm.NetBIOSComputerName}, workgroup)";
+ }
+
+ ///
+ /// Win32 error for the log, e.g. "1326 (The user name or password is incorrect.)".
+ ///
+ private static string GetError(int error)
+ {
+ return $"{error} ({WindowsHostInfo.GetErrorMessage(error)})";
+ }
+
+ ///
+ /// Checks if the logon to a host can count at a domain controller: not for a local account and not for a
+ /// computer in a workgroup (known from the NTLM challenge; without challenge or without its computer / domain
+ /// name it is unknown, so it is gated).
+ ///
+ /// NTLM challenge of the host, null if none.
+ /// True if the host is gated.
+ public bool IsGated(NTLMChallengeInfo ntlm)
+ {
+ // E.g. a challenge without (or with a truncated) target info: empty names are no workgroup computer and no
+ // computer of a local account - also not for ".": the logon needs the computer name of the host
+ if (ntlm == null || string.IsNullOrEmpty(ntlm.NetBIOSComputerName) ||
+ string.IsNullOrEmpty(ntlm.NetBIOSDomainName))
+ return true;
+
+ // Local account: logged on with the computer name of the host
+ if (_isLocalAccount)
+ return false;
+
+ // Local account of the host (its computer name as domain)
+ if (string.Equals(_domain, ntlm.NetBIOSComputerName, StringComparison.OrdinalIgnoreCase))
+ return false;
+
+ return ntlm.IsDomainMember;
+ }
+
+ ///
+ /// Checks if a host is in the domain of the credentials (NetBIOS or DNS name), or in the forest whose root domain
+ /// is the domain of the credentials (DNS name, e.g. the UPN suffix "example.com" of a host in
+ /// "corp.example.com"): a domain controller of the forest checks the logon.
+ ///
+ /// NTLM challenge of the host, null if none.
+ /// True if the domain controller of the credentials checks the logon.
+ public bool IsInDomain(NTLMChallengeInfo ntlm)
+ {
+ return ntlm != null && !string.IsNullOrEmpty(_domain) &&
+ (string.Equals(_domain, ntlm.NetBIOSDomainName, StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(_domain, ntlm.DNSDomainName, StringComparison.OrdinalIgnoreCase) ||
+ string.Equals(_domain, ntlm.DNSTreeName, StringComparison.OrdinalIgnoreCase));
+ }
+
+ ///
+ /// Checks if a success on a host proves the password for all hosts: a Windows host (build of the NTLM challenge;
+ /// Samba / NAS devices send none or 0 and may log a wrong password on as guest) in the domain of the
+ /// credentials, or for a UPN any Windows member of a domain (it passes the UPN to its domain controller, also
+ /// with a suffix that is not the name of the domain, e.g. "admin@company.com" for "corp.local").
+ ///
+ /// NTLM challenge of the host, null if none.
+ /// True if the host decides for all hosts.
+ private bool CanAccept(NTLMChallengeInfo ntlm)
+ {
+ return ntlm?.Version is { Build: > 0 } && (IsInDomain(ntlm) || (_isUpn && ntlm.IsDomainMember));
+ }
+
+ ///
+ /// Waits until the host can use the credentials: right away if it is not gated or they were accepted, otherwise
+ /// until it is its turn to check them (one host at a time) or they were rejected.
+ ///
+ /// NTLM challenge of the host, null if none.
+ /// IP address of the host (a host that is not gated is skipped after its own logon failure).
+ /// Max. time to wait for the turn (a slow host checking them doesn't stall the scan).
+ /// Token to monitor for cancellation requests.
+ /// What the host does with the credentials.
+ public async Task WaitAsync(NTLMChallengeInfo ntlm, string host, TimeSpan timeout,
+ CancellationToken cancellationToken)
+ {
+ // Not gated (workgroup computer, local account): independent of a rejection by the domain hosts (e.g. the
+ // local admin of workgroup computers), but not tried again after its own logon failure (its account would
+ // count the wrong password in every scan). Call ReportUngated with the result.
+ if (!IsGated(ntlm))
+ {
+ bool isRejectedHost;
+
+ lock (_lock)
+ isRejectedHost = _rejectedHosts.Contains(host);
+
+ if (!isRejectedHost)
+ return Decision.Proceed;
+
+ Log.Debug($"Windows credentials \"{_account}\" not used for {GetHostName(host, ntlm)}: the host " +
+ "rejected them in an earlier scan (lockout protection).");
+
+ return Decision.Skip;
+ }
+
+ var decision = GetDecision();
+
+ // A host of another domain (or without challenge) waits up to half of the timeout for a host in the domain of
+ // the credentials to decide: a domain that is not trusted fails also with a correct password - the first
+ // hosts of the scan must not reject them before a host of their domain checked them. Not for credentials
+ // without domain (no host is in their domain).
+ if (decision == null && !string.IsNullOrEmpty(_domain) && !IsInDomain(ntlm) && !CanAccept(ntlm))
+ {
+ Task decided;
+
+ lock (_lock)
+ decided = _decided.Task;
+
+ var grace = timeout / 2;
+
+ await Task.WhenAny(decided, Task.Delay(grace, cancellationToken)).ConfigureAwait(false);
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ decision = GetDecision();
+ timeout -= grace;
+ }
+
+ if (decision == null)
+ {
+ if (!await _turn.WaitAsync(timeout, cancellationToken).ConfigureAwait(false))
+ {
+ decision = GetDecision() ?? Decision.Timeout;
+ }
+ else
+ {
+ // Another host may have decided while this one waited
+ decision = GetDecision();
+
+ if (decision == null)
+ {
+ Log.Debug($"Windows credentials \"{_account}\" are checked on {GetHostName(host, ntlm)}, the " +
+ "other hosts wait (lockout protection).");
+
+ return Decision.Check;
+ }
+
+ _turn.Release();
+ }
+ }
+
+ switch (decision)
+ {
+ case Decision.Skip:
+ Interlocked.Increment(ref _skippedHosts);
+ break;
+ case Decision.Timeout:
+ Interlocked.Increment(ref _timedOutHosts);
+ break;
+ }
+
+ return decision.Value;
+ }
+
+ ///
+ /// Reports the result of a host that checked the credentials () and lets the next
+ /// host check them if it didn't decide.
+ ///
+ /// NTLM challenge of the host, null if none.
+ /// IP address of the host (for the log).
+ /// Result of the NetApi requests, null if they didn't run (e.g. canceled).
+ public void Report(NTLMChallengeInfo ntlm, string host, WindowsNetApiInfo info)
+ {
+ var isRejected = false;
+
+ // Logged outside the lock
+ Action log = null;
+ var hostName = GetHostName(host, ntlm);
+
+ try
+ {
+ if (info == null)
+ {
+ log = () => Log.Debug($"Windows credentials \"{_account}\" not checked on {hostName} (canceled, " +
+ "or the requests were not sent), the next host checks them.");
+ return;
+ }
+
+ lock (_lock)
+ {
+ if (_state != State.Unchecked)
+ return;
+
+ // Access denied (logged on, but without rights) or a logon type the host doesn't grant (checked after
+ // the password, e.g. "Deny access to this computer from the network" on a domain controller): the
+ // credentials are correct. Only proven by a host in their domain: another host may have logged on as
+ // guest or with a local account of the same name, also with a wrong password (only this host used them,
+ // the next host checks them)
+ if (info.Error is 0 or 5 or WindowsHostInfo.ErrorLogonTypeNotGranted)
+ {
+ // A Windows host in their domain (or a Windows member of a domain for a UPN) doesn't log a wrong
+ // password of a domain account on as guest
+ if (CanAccept(ntlm))
+ {
+ _state = State.Accepted;
+ _decided.TrySetResult();
+
+ // A successful logon resets the failures at the domain controller (badPwdCount)
+ Interlocked.Exchange(ref _accountState.LogonFailures, 0);
+
+ log = () => Log.Info($"Windows credentials \"{_account}\" accepted on {hostName} (Windows " +
+ $"host of their domain, error {GetError(info.Error)}): the other hosts " +
+ "use them.");
+ }
+ else
+ {
+ var where = IsInDomain(ntlm) || (_isUpn && ntlm?.IsDomainMember == true)
+ ? "not a Windows host"
+ : "not in their domain";
+
+ log = () => Log.Info($"Windows credentials \"{_account}\" logged on to {hostName} (error " +
+ $"{GetError(info.Error)}), but {where} - not proven (e.g. guest, local " +
+ "account): the next host checks them (lockout protection).");
+ }
+
+ return;
+ }
+
+ // Only an error that shows that no domain controller checked them, or a logon that is not allowed for
+ // the account (e.g. logon hours, Protected Users with NTLM - no failed logon), lets the next host check
+ // them, every other error may be a wrong password
+ if (WindowsHostInfo.IsLogonNotDecided(info.Error) || WindowsHostInfo.IsLogonNotAllowed(info.Error))
+ {
+ log = WindowsHostInfo.IsLogonNotAllowed(info.Error)
+ ? () => Log.Info($"Logon of \"{_account}\" to {hostName} not allowed: error " +
+ $"{GetError(info.Error)} - no logon failure counted, the next host checks " +
+ "the credentials.")
+ : () => Log.Debug($"Windows credentials \"{_account}\" not checked on {hostName}: error " +
+ $"{GetError(info.Error)}, the next host checks them.");
+ return;
+ }
+
+ var logonFailures = Interlocked.Increment(ref _accountState.LogonFailures);
+ var isInDomain = IsInDomain(ntlm);
+
+ // Without a domain (e.g. "admin"), the host's domain controller may have checked them
+ if (isInDomain || string.IsNullOrEmpty(_domain) || logonFailures >= _maxLogonFailures)
+ {
+ SetRejected();
+ isRejected = true;
+ }
+
+ var reason = isInDomain
+ ? "a logon failure in their domain"
+ : string.IsNullOrEmpty(_domain)
+ ? "a logon failure without domain (the domain controller of the host may count it)"
+ : $"{logonFailures} of max. {_maxLogonFailures} logon failure(s) on hosts of other domains";
+
+ log = () =>
+ {
+ Log.Warn($"Logon of \"{_account}\" failed on {hostName}: error {GetError(info.Error)} " +
+ $"(logon failure {logonFailures} of the account).");
+
+ if (isRejected)
+ Log.Warn($"Windows credentials \"{_account}\" rejected after {reason}: not used for the " +
+ "other hosts and the next scans of the tab (lockout protection).");
+ else
+ Log.Info($"Windows credentials \"{_account}\": {reason}, the next host checks them.");
+ };
+ }
+ }
+ finally
+ {
+ _turn.Release();
+
+ log?.Invoke();
+ }
+
+ // Outside the lock (the handler may read the state)
+ if (isRejected)
+ Rejected?.Invoke(this, EventArgs.Empty);
+ }
+
+ ///
+ /// Reports the result of a gated host that used the accepted credentials (): a
+ /// logon failure on a host in their domain, or on a host that could accept them (, e.g.
+ /// a domain member for a UPN), rejects them for the hosts that didn't start yet (e.g. the password was changed
+ /// or the account locked during the scan). Failures on hosts of other domains are expected also with a correct
+ /// password (e.g. a domain that is not trusted).
+ ///
+ /// NTLM challenge of the host, null if none.
+ /// IP address of the host (for the log).
+ /// Result of the NetApi requests, null if they didn't run (e.g. canceled).
+ public void ReportAccepted(NTLMChallengeInfo ntlm, string host, WindowsNetApiInfo info)
+ {
+ if (info == null || info.Error is 0 or 5 or WindowsHostInfo.ErrorLogonTypeNotGranted ||
+ WindowsHostInfo.IsLogonNotDecided(info.Error) || WindowsHostInfo.IsLogonNotAllowed(info.Error) ||
+ !(IsInDomain(ntlm) || CanAccept(ntlm)))
+ return;
+
+ int logonFailures;
+
+ lock (_lock)
+ {
+ // Rejected already (e.g. by another host of the scan)
+ if (_state == State.Rejected)
+ return;
+
+ logonFailures = Interlocked.Increment(ref _accountState.LogonFailures);
+
+ SetRejected();
+ }
+
+ var hostName = GetHostName(host, ntlm);
+
+ Log.Warn($"Logon of \"{_account}\" failed on {hostName}: error {GetError(info.Error)} (logon failure " +
+ $"{logonFailures} of the account).");
+ Log.Warn($"Windows credentials \"{_account}\" rejected after a logon failure in their domain while the hosts " +
+ "used them (e.g. the password was changed or the account locked during the scan): not used for the " +
+ "hosts that didn't start yet and the next scans of the tab (lockout protection).");
+
+ Rejected?.Invoke(this, EventArgs.Empty);
+ }
+
+ ///
+ /// Reports the result of a host that is not gated ( false, ):
+ /// after a logon failure (every error except success, access denied and the errors of
+ /// / ), the
+ /// host is skipped in the next scans.
+ ///
+ /// NTLM challenge of the host (for the log).
+ /// IP address of the host.
+ /// Result of the NetApi requests, null if they didn't run (e.g. canceled).
+ public void ReportUngated(NTLMChallengeInfo ntlm, string host, WindowsNetApiInfo info)
+ {
+ if (info == null || info.Error is 0 or 5 || WindowsHostInfo.IsLogonNotAllowed(info.Error) ||
+ WindowsHostInfo.IsLogonNotDecided(info.Error))
+ return;
+
+ lock (_lock)
+ _rejectedHosts.Add(host);
+
+ Log.Warn($"Logon of \"{_account}\" failed on {GetHostName(host, ntlm)}: error {GetError(info.Error)} - " +
+ "workgroup computer / local account (not checked by a domain controller), the host is not tried " +
+ "again in the next scans of the tab (lockout protection).");
+ }
+
+ ///
+ /// Takes a rejection of the password by another gate of the account (called in the lock): e.g. another tab
+ /// checked them while this gate waited for the turn of the account.
+ ///
+ private void UpdateFromAccount()
+ {
+ if (_state == State.Rejected)
+ return;
+
+ lock (_accountState)
+ {
+ if (!_accountState.RejectedPasswords.Contains(_passwordFingerprint))
+ return;
+ }
+
+ _state = State.Rejected;
+ _decided.TrySetResult();
+ }
+
+ private Decision? GetDecision()
+ {
+ lock (_lock)
+ {
+ UpdateFromAccount();
+
+ return _state switch
+ {
+ State.Accepted => Decision.Proceed,
+ State.Rejected => Decision.Skip,
+ _ => null
+ };
+ }
+ }
+}
diff --git a/Source/NETworkManager.Models/Network/WindowsNetApiInfo.cs b/Source/NETworkManager.Models/Network/WindowsNetApiInfo.cs
new file mode 100644
index 0000000000..4319643e03
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/WindowsNetApiInfo.cs
@@ -0,0 +1,79 @@
+using System;
+using System.Collections.Generic;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Role of a Windows host (server type of NetServerGetInfo).
+///
+public enum WindowsHostRole
+{
+ ///
+ /// Not known (not read or access denied).
+ ///
+ Unknown,
+
+ ///
+ /// Workstation (client).
+ ///
+ Workstation,
+
+ ///
+ /// Server.
+ ///
+ Server,
+
+ ///
+ /// Domain controller.
+ ///
+ DomainController
+}
+
+///
+/// Information of a Windows host read with the NetApi (SMB / RPC, with the credentials of the scan), see
+/// .
+///
+///
+/// Win32 error of the first request (NetServerGetInfo), 0 if it succeeded - e.g. 5 (access denied), 1326
+/// (wrong username or password). Nothing else is read after an error.
+///
+/// Role of the host.
+/// The host is in a domain (null if not known).
+/// Description of the computer (empty if none).
+/// Workgroup or NetBIOS domain name (empty if not read).
+/// Logged-on users ("DOMAIN\user"), null if they could not be read.
+/// Win32 error of the logged-on users (e.g. 5: needs admin rights), 0 if read.
+/// Version of the remote registry, null if it could not be read (admin rights, service).
+public sealed record WindowsNetApiInfo(
+ int Error,
+ WindowsHostRole Role,
+ bool? IsDomainMember,
+ string Description,
+ string Workgroup,
+ IReadOnlyList Users,
+ int UsersError,
+ WindowsRegistryVersion Registry)
+{
+ ///
+ /// Creates the result of a request that failed.
+ ///
+ /// Win32 error.
+ public static WindowsNetApiInfo FromError(int error)
+ {
+ return new WindowsNetApiInfo(error, WindowsHostRole.Unknown, null, string.Empty, string.Empty, null, error,
+ null);
+ }
+}
+
+///
+/// Version of Windows from the remote registry (HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion).
+///
+/// Version with the patch level (update build revision), e.g. 10.0.26200.6584.
+/// Display version, e.g. "25H2" (empty for older versions).
+/// Edition, e.g. "Professional" or "ServerStandard".
+/// Installation type is a server (null if not set).
+public sealed record WindowsRegistryVersion(
+ Version Version,
+ string DisplayVersion,
+ string EditionID,
+ bool? IsServer);
diff --git a/Source/NETworkManager.Models/Network/WindowsNetApiResolver.cs b/Source/NETworkManager.Models/Network/WindowsNetApiResolver.cs
new file mode 100644
index 0000000000..4357aee979
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/WindowsNetApiResolver.cs
@@ -0,0 +1,345 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Runtime.InteropServices;
+using Microsoft.Win32;
+using NETworkManager.Utilities;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Reads the information of a Windows host with the NetApi (RPC over SMB, TCP 445) with the credentials of the
+/// calling thread (the user running the application, or a ):
+///
+/// NetServerGetInfo level 101: role (workstation / server / domain controller), domain member,
+/// description - any authenticated user.
+/// NetWkstaGetInfo level 100: workgroup / NetBIOS domain name.
+/// NetWkstaUserEnum level 1: logged-on users - admin rights on the host.
+/// Remote registry (only if the users could be read = admin rights): build with patch level, display
+/// version (e.g. 25H2) and edition - needs the Remote Registry service (disabled by default on clients).
+///
+/// The calls are blocking and can't be canceled (SMB / RPC timeouts of 20 s and more): run them on a limited number
+/// of threads with a timeout (see ).
+///
+public static class WindowsNetApiResolver
+{
+ private const int NERR_Success = 0;
+ private const int ERROR_MORE_DATA = 234;
+ private const int MAX_PREFERRED_LENGTH = -1;
+
+ // Server type flags (SV_TYPE_*)
+ private const int SV_TYPE_WORKSTATION = 0x00000001;
+ private const int SV_TYPE_DOMAIN_CTRL = 0x00000008;
+ private const int SV_TYPE_DOMAIN_BAKCTRL = 0x00000010;
+ private const int SV_TYPE_DOMAIN_MEMBER = 0x00000100;
+ private const int SV_TYPE_SERVER_NT = 0x00008000;
+
+ private const string CurrentVersionKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
+
+ ///
+ /// Reads the information of a host (blocking).
+ ///
+ /// DNS hostname or IP address of the host.
+ ///
+ /// Called with the values of the NetApi before the remote registry is read (it can be slow, e.g. a service that
+ /// is started on demand), so a caller with a timeout can keep them; optional.
+ ///
+ /// Information, with the Win32 error if the first request failed.
+ public static WindowsNetApiInfo Resolve(string host, Action onNetApiRead = null)
+ {
+ var server = $@"\\{ToServerName(host)}";
+
+ var (error, role, isDomainMember, description) = GetServerInfo(server);
+
+ if (error != NERR_Success)
+ return WindowsNetApiInfo.FromError(error);
+
+ var workgroup = GetWorkgroup(server);
+
+ var (users, usersError) = GetUsers(server);
+
+ var info = new WindowsNetApiInfo(NERR_Success, role, isDomainMember, description, workgroup, users,
+ usersError, null);
+
+ // The registry needs admin rights like the users - not tried without them (one RPC connection less)
+ if (usersError != NERR_Success)
+ return info;
+
+ onNetApiRead?.Invoke(info);
+
+ var registry = GetRegistryVersion(ToServerName(host));
+
+ return registry == null ? info : info with { Registry = registry };
+ }
+
+ ///
+ /// Converts an IPv6 address to its UNC name (e.g. "fe80--1s4.ipv6-literal.net"), other hosts are returned as
+ /// they are.
+ ///
+ /// DNS hostname or IP address.
+ /// Name for UNC paths / NetApi calls.
+ public static string ToServerName(string host)
+ {
+ if (IPAddress.TryParse(host, out var ipAddress) && ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
+ return ipAddress.ToString().Replace(':', '-').Replace('%', 's') + ".ipv6-literal.net";
+
+ return host;
+ }
+
+ ///
+ /// Gets the role of a host from its server type flags.
+ ///
+ /// Server type (SV_TYPE_* flags).
+ /// Role.
+ public static WindowsHostRole GetRole(int type)
+ {
+ if ((type & (SV_TYPE_DOMAIN_CTRL | SV_TYPE_DOMAIN_BAKCTRL)) != 0)
+ return WindowsHostRole.DomainController;
+
+ if ((type & SV_TYPE_SERVER_NT) != 0)
+ return WindowsHostRole.Server;
+
+ return (type & SV_TYPE_WORKSTATION) != 0 ? WindowsHostRole.Workstation : WindowsHostRole.Unknown;
+ }
+
+ ///
+ /// Filters the logged-on users: no computer accounts ("NAME$") and no virtual accounts of the desktop window
+ /// manager / font driver ("DWM-1", "UMFD-0"), each user once ("DOMAIN\user"), sorted.
+ ///
+ /// Username and logon domain of the entries.
+ /// Users.
+ public static List FilterUsers(IEnumerable<(string username, string domain)> entries)
+ {
+ return entries
+ .Where(x => !string.IsNullOrEmpty(x.username) && !x.username.EndsWith('$') &&
+ !x.username.StartsWith("DWM-", StringComparison.OrdinalIgnoreCase) &&
+ !x.username.StartsWith("UMFD-", StringComparison.OrdinalIgnoreCase))
+ .Select(x => string.IsNullOrEmpty(x.domain) ? x.username : $@"{x.domain}\{x.username}")
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .Order(StringComparer.OrdinalIgnoreCase)
+ .ToList();
+ }
+
+ ///
+ /// Gets the edition for display, e.g. "Professional" -> "Pro", "ServerDatacenter" -> "Datacenter".
+ ///
+ /// EditionID of the registry.
+ /// Edition, empty if none.
+ public static string GetEditionName(string editionID)
+ {
+ if (string.IsNullOrEmpty(editionID))
+ return string.Empty;
+
+ return editionID switch
+ {
+ "Core" or "CoreSingleLanguage" or "CoreCountrySpecific" => "Home",
+ "Professional" => "Pro",
+ "ProfessionalWorkstation" => "Pro for Workstations",
+ "ProfessionalEducation" => "Pro Education",
+ "EnterpriseS" => "Enterprise LTSC",
+ "IoTEnterpriseS" => "IoT Enterprise LTSC",
+ _ when editionID.StartsWith("Server", StringComparison.Ordinal) && editionID.Length > 6 =>
+ editionID[6..] switch
+ {
+ "StandardEval" => "Standard (Evaluation)",
+ "DatacenterEval" => "Datacenter (Evaluation)",
+ "AzureEdition" => "Datacenter: Azure Edition",
+ var x => x
+ },
+ _ => editionID
+ };
+ }
+
+ #region NetApi
+
+ private static (int error, WindowsHostRole role, bool? isDomainMember, string description) GetServerInfo(
+ string server)
+ {
+ var error = NetServerGetInfo(server, 101, out var buffer);
+
+ try
+ {
+ if (error != NERR_Success)
+ return (error, WindowsHostRole.Unknown, null, string.Empty);
+
+ var info = Marshal.PtrToStructure(buffer);
+
+ var role = GetRole(info.sv101_type);
+
+ return (NERR_Success, role,
+ role == WindowsHostRole.DomainController || (info.sv101_type & SV_TYPE_DOMAIN_MEMBER) != 0,
+ // A description with several lines on one line
+ StringHelper.ReplaceControlCharactersWithSpace(info.sv101_comment));
+ }
+ finally
+ {
+ if (buffer != IntPtr.Zero)
+ NetApiBufferFree(buffer);
+ }
+ }
+
+ private static string GetWorkgroup(string server)
+ {
+ var error = NetWkstaGetInfo(server, 100, out var buffer);
+
+ try
+ {
+ return error == NERR_Success
+ ? Clean(Marshal.PtrToStructure(buffer).wki100_langroup)
+ : string.Empty;
+ }
+ finally
+ {
+ if (buffer != IntPtr.Zero)
+ NetApiBufferFree(buffer);
+ }
+ }
+
+ private static (List users, int error) GetUsers(string server)
+ {
+ var entries = new List<(string, string)>();
+ var resumeHandle = 0;
+ int error;
+
+ do
+ {
+ error = NetWkstaUserEnum(server, 1, out var buffer, MAX_PREFERRED_LENGTH, out var entriesRead, out _,
+ ref resumeHandle);
+
+ try
+ {
+ if (error is not (NERR_Success or ERROR_MORE_DATA))
+ return (null, error);
+
+ var size = Marshal.SizeOf();
+
+ for (var i = 0; i < entriesRead; i++)
+ {
+ var info = Marshal.PtrToStructure(buffer + i * size);
+
+ entries.Add((Clean(info.wkui1_username), Clean(info.wkui1_logon_domain)));
+ }
+ }
+ finally
+ {
+ if (buffer != IntPtr.Zero)
+ NetApiBufferFree(buffer);
+ }
+ } while (error == ERROR_MORE_DATA);
+
+ return (FilterUsers(entries), NERR_Success);
+ }
+
+ #endregion
+
+ #region Registry
+
+ ///
+ /// Reads the version from the remote registry, null if it can't be read (no admin rights, service stopped /
+ /// disabled).
+ ///
+ private static WindowsRegistryVersion GetRegistryVersion(string server)
+ {
+ try
+ {
+ using var baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, server);
+ using var key = baseKey.OpenSubKey(CurrentVersionKey);
+
+ if (key == null || !int.TryParse(key.GetValue("CurrentBuild") as string ?? key.GetValue("CurrentBuildNumber") as string,
+ out var build))
+ return null;
+
+ // Windows 10 and later: CurrentMajor/MinorVersionNumber (CurrentVersion is "6.3" for compatibility)
+ int major, minor;
+
+ if (key.GetValue("CurrentMajorVersionNumber") is int majorValue &&
+ key.GetValue("CurrentMinorVersionNumber") is int minorValue)
+ {
+ major = majorValue;
+ minor = minorValue;
+ }
+ else if (Version.TryParse(key.GetValue("CurrentVersion") as string, out var currentVersion))
+ {
+ major = currentVersion.Major;
+ minor = currentVersion.Minor;
+ }
+ else
+ {
+ return null;
+ }
+
+ var ubr = key.GetValue("UBR") is int ubrValue ? ubrValue : 0;
+
+ var installationType = key.GetValue("InstallationType") as string;
+
+ return new WindowsRegistryVersion(new Version(major, minor, build, ubr),
+ Clean(key.GetValue("DisplayVersion") as string), Clean(key.GetValue("EditionID") as string),
+ string.IsNullOrEmpty(installationType)
+ ? null
+ : installationType.StartsWith("Server", StringComparison.OrdinalIgnoreCase));
+ }
+ catch (Exception)
+ {
+ return null;
+ }
+ }
+
+ #endregion
+
+ ///
+ /// Trims a value and removes control characters, empty for null.
+ ///
+ private static string Clean(string value)
+ {
+ return StringHelper.RemoveControlCharacters(value).Trim();
+ }
+
+ #region P/Invoke
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct SERVER_INFO_101
+ {
+ public int sv101_platform_id;
+ [MarshalAs(UnmanagedType.LPWStr)] public string sv101_name;
+ public int sv101_version_major;
+ public int sv101_version_minor;
+ public int sv101_type;
+ [MarshalAs(UnmanagedType.LPWStr)] public string sv101_comment;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct WKSTA_INFO_100
+ {
+ public int wki100_platform_id;
+ [MarshalAs(UnmanagedType.LPWStr)] public string wki100_computername;
+ [MarshalAs(UnmanagedType.LPWStr)] public string wki100_langroup;
+ public int wki100_ver_major;
+ public int wki100_ver_minor;
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct WKSTA_USER_INFO_1
+ {
+ [MarshalAs(UnmanagedType.LPWStr)] public string wkui1_username;
+ [MarshalAs(UnmanagedType.LPWStr)] public string wkui1_logon_domain;
+ [MarshalAs(UnmanagedType.LPWStr)] public string wkui1_oth_domains;
+ [MarshalAs(UnmanagedType.LPWStr)] public string wkui1_logon_server;
+ }
+
+ [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
+ private static extern int NetServerGetInfo(string servername, int level, out IntPtr bufptr);
+
+ [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
+ private static extern int NetWkstaGetInfo(string servername, int level, out IntPtr bufptr);
+
+ [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
+ private static extern int NetWkstaUserEnum(string servername, int level, out IntPtr bufptr, int prefmaxlen,
+ out int entriesread, out int totalentries, ref int resumeHandle);
+
+ [DllImport("netapi32.dll")]
+ private static extern int NetApiBufferFree(IntPtr buffer);
+
+ #endregion
+}
diff --git a/Source/NETworkManager.Models/Network/WindowsNetApiSlots.cs b/Source/NETworkManager.Models/Network/WindowsNetApiSlots.cs
new file mode 100644
index 0000000000..350bf1dae3
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/WindowsNetApiSlots.cs
@@ -0,0 +1,105 @@
+using System;
+using System.Diagnostics;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Slots for the blocking NetApi requests of the IP Scanner, shared by all scans of the application (tabs, repeated
+/// scans): a call that exceeds the timeout keeps its slot until Windows returns - also after its scan is completed -
+/// so blocked calls can't pile up. Like a semaphore, but the max. number of slots is passed with every request: a
+/// changed setting applies to the next request, also while calls of an earlier scan with another limit are still
+/// running (a lower limit lets no new call start until enough of them returned).
+///
+public sealed class WindowsNetApiSlots
+{
+ ///
+ /// Slots of all scans of the application.
+ ///
+ public static WindowsNetApiSlots Shared { get; } = new();
+
+ private readonly Lock _lock = new();
+ private int _used;
+
+ // Completed when a slot is released, then replaced: wakes up all waiting requests, they check the limit again
+ private TaskCompletionSource _released = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ ///
+ /// Number of slots in use (calls that are running, also after their timeout).
+ ///
+ public int Used
+ {
+ get
+ {
+ lock (_lock)
+ return _used;
+ }
+ }
+
+ ///
+ /// Waits for a free slot. Release it with when the call returned.
+ ///
+ /// Max. number of slots in use (incl. this one), at least 1.
+ /// Max. time to wait.
+ /// Token to monitor for cancellation requests.
+ /// True if a slot was taken, false after the timeout.
+ public async Task WaitAsync(int maxSlots, TimeSpan timeout, CancellationToken cancellationToken)
+ {
+ maxSlots = Math.Max(1, maxSlots);
+
+ var stopwatch = Stopwatch.StartNew();
+
+ while (true)
+ {
+ Task released;
+
+ lock (_lock)
+ {
+ if (_used < maxSlots)
+ {
+ _used++;
+
+ return true;
+ }
+
+ released = _released.Task;
+ }
+
+ var remaining = timeout - stopwatch.Elapsed;
+
+ if (remaining <= TimeSpan.Zero)
+ return false;
+
+ try
+ {
+ await released.WaitAsync(remaining, cancellationToken).ConfigureAwait(false);
+ }
+ catch (TimeoutException)
+ {
+ return false;
+ }
+ }
+ }
+
+ ///
+ /// Releases a slot taken with .
+ ///
+ public void Release()
+ {
+ TaskCompletionSource released;
+
+ lock (_lock)
+ {
+ if (_used == 0)
+ throw new InvalidOperationException("No slot is in use.");
+
+ _used--;
+
+ released = _released;
+ _released = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ }
+
+ released.SetResult();
+ }
+}
diff --git a/Source/NETworkManager.Models/Network/WindowsVersionHelper.cs b/Source/NETworkManager.Models/Network/WindowsVersionHelper.cs
new file mode 100644
index 0000000000..de23e00d2c
--- /dev/null
+++ b/Source/NETworkManager.Models/Network/WindowsVersionHelper.cs
@@ -0,0 +1,103 @@
+using System;
+using System.Collections.Generic;
+
+namespace NETworkManager.Models.Network;
+
+///
+/// Name of a Windows version from its version number (major.minor.build), e.g. 10.0.26200 -> "Windows 11 25H2".
+/// Windows 10 / 11 and Windows Server 2016 and later all report 10.0, only the build tells them apart. Some builds
+/// are shared by a client and a server version (e.g. 26100: Windows 11 24H2 / Server 2025) - the role of the host
+/// decides, if known.
+///
+public static class WindowsVersionHelper
+{
+ ///
+ /// Builds of Windows 10 / 11 / Server 2016 and later: client name, server name (null if there is only one of
+ /// them).
+ ///
+ private static readonly Dictionary Builds = new()
+ {
+ { 10240, ("Windows 10 1507", null) },
+ { 10586, ("Windows 10 1511", null) },
+ { 14393, ("Windows 10 1607", "Windows Server 2016") },
+ { 15063, ("Windows 10 1703", null) },
+ { 16299, ("Windows 10 1709", "Windows Server 1709") },
+ { 17134, ("Windows 10 1803", "Windows Server 1803") },
+ { 17763, ("Windows 10 1809", "Windows Server 2019") },
+ { 18362, ("Windows 10 1903", "Windows Server 1903") },
+ { 18363, ("Windows 10 1909", "Windows Server 1909") },
+ { 19041, ("Windows 10 2004", "Windows Server 2004") },
+ { 19042, ("Windows 10 20H2", "Windows Server 20H2") },
+ { 19043, ("Windows 10 21H1", null) },
+ { 19044, ("Windows 10 21H2", null) },
+ { 19045, ("Windows 10 22H2", null) },
+ { 20348, (null, "Windows Server 2022") },
+ { 22000, ("Windows 11 21H2", null) },
+ { 22621, ("Windows 11 22H2", null) },
+ { 22631, ("Windows 11 23H2", null) },
+ { 25398, (null, "Windows Server 23H2") },
+ { 26100, ("Windows 11 24H2", "Windows Server 2025") },
+ { 26200, ("Windows 11 25H2", null) },
+ { 26300, ("Windows 11 26H2", null) },
+ // Only on new devices with new chips (e.g. Snapdragon X2), existing PCs get 26H2
+ { 28000, ("Windows 11 26H1", null) }
+ };
+
+ ///
+ /// Gets the name of a Windows version.
+ ///
+ /// Version (major.minor.build).
+ ///
+ /// The host is a server (incl. domain controller), false for a workstation, null if unknown (a build of a client
+ /// and a server version gets both names).
+ ///
+ /// Name, null if the version is not a known Windows version (e.g. Samba, which reports build 0).
+ public static string GetName(Version version, bool? isServer)
+ {
+ // Samba and other SMB servers report a Windows version without build
+ if (version == null || version.Build <= 0)
+ return null;
+
+ if (version.Major == 10 && version.Minor == 0)
+ {
+ if (Builds.TryGetValue(version.Build, out var names))
+ return Choose(names.Client, names.Server, isServer);
+
+ // Unknown build (e.g. a newer release): Windows 11 from build 22000 for a workstation - not if the role is
+ // unknown (usual without credentials), it could be a newer Windows Server
+ return version.Build >= 22000 && isServer == false
+ ? $"Windows 11 (build {version.Build})"
+ : $"Windows (build {version.Build})";
+ }
+
+ // Windows Vista / Server 2008 and later: earlier versions (XP, Server 2003) only know SMB1, the version is read
+ // over SMB2 only
+ return (version.Major, version.Minor) switch
+ {
+ (6, 0) => Choose("Windows Vista", "Windows Server 2008", isServer),
+ (6, 1) => Choose("Windows 7", "Windows Server 2008 R2", isServer),
+ (6, 2) => Choose("Windows 8", "Windows Server 2012", isServer),
+ (6, 3) => Choose("Windows 8.1", "Windows Server 2012 R2", isServer),
+ _ => null
+ };
+ }
+
+ ///
+ /// Chooses the client or server name by the role, both if the role is unknown.
+ ///
+ private static string Choose(string client, string server, bool? isServer)
+ {
+ if (client == null)
+ return server;
+
+ if (server == null)
+ return client;
+
+ return isServer switch
+ {
+ true => server,
+ false => client,
+ null => $"{client} / {server.Replace("Windows ", string.Empty)}"
+ };
+ }
+}
diff --git a/Source/NETworkManager.Profiles/Application/IPScanner.cs b/Source/NETworkManager.Profiles/Application/IPScanner.cs
index d836a0f771..5b027db1af 100644
--- a/Source/NETworkManager.Profiles/Application/IPScanner.cs
+++ b/Source/NETworkManager.Profiles/Application/IPScanner.cs
@@ -41,6 +41,37 @@ public static SNMPSecureCredentials GetSNMPCredentials(ProfileInfo profile, Grou
return null;
}
+ ///
+ /// Gets the Windows credentials of a profile for the Windows host information of the IP Scanner: its own (if
+ /// used), otherwise the ones of its group (if used), otherwise null (the user running the application). There are
+ /// no Windows credentials in the settings.
+ ///
+ /// Profile the tab is opened with.
+ /// Credentials, null if neither the profile nor its group uses credentials.
+ public static WindowsCredentials GetWindowsCredentials(ProfileInfo profile)
+ {
+ return GetWindowsCredentials(profile, ProfileManager.GetGroupByName(profile.Group));
+ }
+
+ ///
+ /// Gets the Windows credentials of a profile and its group, see .
+ ///
+ /// Profile.
+ /// Group of the profile, null if it can't be found.
+ /// Credentials (copy of the password), null if neither the profile nor its group uses credentials.
+ public static WindowsCredentials GetWindowsCredentials(ProfileInfo profile, GroupInfo group)
+ {
+ if (profile.IPScanner_UseWindowsCredentials)
+ return new WindowsCredentials(profile.IPScanner_WindowsUsername ?? string.Empty,
+ profile.IPScanner_WindowsDomain ?? string.Empty, profile.IPScanner_WindowsPassword?.Copy());
+
+ if (group is { IPScanner_UseWindowsCredentials: true })
+ return new WindowsCredentials(group.IPScanner_WindowsUsername ?? string.Empty,
+ group.IPScanner_WindowsDomain ?? string.Empty, group.IPScanner_WindowsPassword?.Copy());
+
+ return null;
+ }
+
///
/// Creates the credentials of the values of a profile or group (copies of the passwords, a change of the profile
/// doesn't change an open tab).
diff --git a/Source/NETworkManager.Profiles/GroupInfo.cs b/Source/NETworkManager.Profiles/GroupInfo.cs
index 2124632e87..d3a961b220 100644
--- a/Source/NETworkManager.Profiles/GroupInfo.cs
+++ b/Source/NETworkManager.Profiles/GroupInfo.cs
@@ -51,6 +51,10 @@ public GroupInfo(GroupInfo group) : this(group.Name)
IPScanner_SNMPAuth = group.IPScanner_SNMPAuth;
IPScanner_SNMPPrivacyProvider = group.IPScanner_SNMPPrivacyProvider;
IPScanner_SNMPPriv = group.IPScanner_SNMPPriv;
+ IPScanner_UseWindowsCredentials = group.IPScanner_UseWindowsCredentials;
+ IPScanner_WindowsUsername = group.IPScanner_WindowsUsername;
+ IPScanner_WindowsDomain = group.IPScanner_WindowsDomain;
+ IPScanner_WindowsPassword = group.IPScanner_WindowsPassword;
// Port Scanner
PortScanner_OverridePorts = group.PortScanner_OverridePorts;
@@ -217,6 +221,17 @@ public GroupInfo(GroupInfo group) : this(group.Name)
[XmlIgnore] public SecureString IPScanner_SNMPPriv { get; set; }
+ ///
+ /// Use the Windows credentials below for the Windows host information of the IP Scanner instead of the user
+ /// running the application (a profile before its group), see
+ /// .
+ ///
+ public bool IPScanner_UseWindowsCredentials { get; set; }
+
+ public string IPScanner_WindowsUsername { get; set; }
+ public string IPScanner_WindowsDomain { get; set; }
+ [XmlIgnore] public SecureString IPScanner_WindowsPassword { get; set; }
+
public bool PortScanner_OverridePorts { get; set; }
///
diff --git a/Source/NETworkManager.Profiles/GroupInfoSerializable.cs b/Source/NETworkManager.Profiles/GroupInfoSerializable.cs
index dd63f97750..42ca59d9a0 100644
--- a/Source/NETworkManager.Profiles/GroupInfoSerializable.cs
+++ b/Source/NETworkManager.Profiles/GroupInfoSerializable.cs
@@ -33,6 +33,11 @@ public GroupInfoSerializable(GroupInfo profileGroup) : base(profileGroup)
///
public new string IPScanner_SNMPPriv { get; set; }
+ ///
+ /// Override the default IP Scanner Windows password to make it serializable.
+ ///
+ public new string IPScanner_WindowsPassword { get; set; }
+
///
/// Override the default remote desktop password to make it serializable.
///
diff --git a/Source/NETworkManager.Profiles/ProfileFileData.cs b/Source/NETworkManager.Profiles/ProfileFileData.cs
index bc399638d0..735d4d3dad 100644
--- a/Source/NETworkManager.Profiles/ProfileFileData.cs
+++ b/Source/NETworkManager.Profiles/ProfileFileData.cs
@@ -113,6 +113,9 @@ public List GroupsSerializable
IPScanner_SNMPPriv = p.IPScanner_SNMPPriv != null
? Utilities.SecureStringHelper.ConvertToString(p.IPScanner_SNMPPriv)
: string.Empty,
+ IPScanner_WindowsPassword = p.IPScanner_WindowsPassword != null
+ ? Utilities.SecureStringHelper.ConvertToString(p.IPScanner_WindowsPassword)
+ : string.Empty,
RemoteDesktop_Password = p.RemoteDesktop_Password != null
? Utilities.SecureStringHelper.ConvertToString(p.RemoteDesktop_Password)
: string.Empty,
@@ -138,6 +141,9 @@ public List GroupsSerializable
IPScanner_SNMPPriv = g.IPScanner_SNMPPriv != null
? Utilities.SecureStringHelper.ConvertToString(g.IPScanner_SNMPPriv)
: string.Empty,
+ IPScanner_WindowsPassword = g.IPScanner_WindowsPassword != null
+ ? Utilities.SecureStringHelper.ConvertToString(g.IPScanner_WindowsPassword)
+ : string.Empty,
RemoteDesktop_Password = g.RemoteDesktop_Password != null
? Utilities.SecureStringHelper.ConvertToString(g.RemoteDesktop_Password)
: string.Empty,
@@ -176,6 +182,9 @@ public List GroupsSerializable
IPScanner_SNMPPriv = !string.IsNullOrEmpty(ps.IPScanner_SNMPPriv)
? Utilities.SecureStringHelper.ConvertToSecureString(ps.IPScanner_SNMPPriv)
: null,
+ IPScanner_WindowsPassword = !string.IsNullOrEmpty(ps.IPScanner_WindowsPassword)
+ ? Utilities.SecureStringHelper.ConvertToSecureString(ps.IPScanner_WindowsPassword)
+ : null,
RemoteDesktop_Password = !string.IsNullOrEmpty(ps.RemoteDesktop_Password)
? Utilities.SecureStringHelper.ConvertToSecureString(ps.RemoteDesktop_Password)
: null,
@@ -201,6 +210,9 @@ public List GroupsSerializable
IPScanner_SNMPPriv = !string.IsNullOrEmpty(gs.IPScanner_SNMPPriv)
? Utilities.SecureStringHelper.ConvertToSecureString(gs.IPScanner_SNMPPriv)
: null,
+ IPScanner_WindowsPassword = !string.IsNullOrEmpty(gs.IPScanner_WindowsPassword)
+ ? Utilities.SecureStringHelper.ConvertToSecureString(gs.IPScanner_WindowsPassword)
+ : null,
RemoteDesktop_Password = !string.IsNullOrEmpty(gs.RemoteDesktop_Password)
? Utilities.SecureStringHelper.ConvertToSecureString(gs.RemoteDesktop_Password)
: null,
diff --git a/Source/NETworkManager.Profiles/ProfileInfo.cs b/Source/NETworkManager.Profiles/ProfileInfo.cs
index 1c2e463fd2..78966fad7c 100644
--- a/Source/NETworkManager.Profiles/ProfileInfo.cs
+++ b/Source/NETworkManager.Profiles/ProfileInfo.cs
@@ -67,6 +67,10 @@ public ProfileInfo(ProfileInfo profile)
IPScanner_SNMPAuth = profile.IPScanner_SNMPAuth;
IPScanner_SNMPPrivacyProvider = profile.IPScanner_SNMPPrivacyProvider;
IPScanner_SNMPPriv = profile.IPScanner_SNMPPriv;
+ IPScanner_UseWindowsCredentials = profile.IPScanner_UseWindowsCredentials;
+ IPScanner_WindowsUsername = profile.IPScanner_WindowsUsername;
+ IPScanner_WindowsDomain = profile.IPScanner_WindowsDomain;
+ IPScanner_WindowsPassword = profile.IPScanner_WindowsPassword;
// Port Scanner
PortScanner_Enabled = profile.PortScanner_Enabled;
@@ -345,6 +349,17 @@ public ProfileInfo(ProfileInfo profile)
[XmlIgnore] public SecureString IPScanner_SNMPPriv { get; set; }
+ ///
+ /// Use the Windows credentials below for the Windows host information of the IP Scanner instead of the user
+ /// running the application (a profile before its group), see
+ /// .
+ ///
+ public bool IPScanner_UseWindowsCredentials { get; set; }
+
+ public string IPScanner_WindowsUsername { get; set; }
+ public string IPScanner_WindowsDomain { get; set; }
+ [XmlIgnore] public SecureString IPScanner_WindowsPassword { get; set; }
+
public bool PortScanner_Enabled { get; set; }
public bool PortScanner_InheritHost { get; set; } = true;
public string PortScanner_Host { get; set; }
diff --git a/Source/NETworkManager.Profiles/ProfileInfoSerializable.cs b/Source/NETworkManager.Profiles/ProfileInfoSerializable.cs
index 2e684433ef..2437da5e5e 100644
--- a/Source/NETworkManager.Profiles/ProfileInfoSerializable.cs
+++ b/Source/NETworkManager.Profiles/ProfileInfoSerializable.cs
@@ -34,6 +34,11 @@ public ProfileInfoSerializable(ProfileInfo profile) : base(profile)
///
public new string IPScanner_SNMPPriv { get; set; }
+ ///
+ /// Override the default IP Scanner Windows password to make it serializable.
+ ///
+ public new string IPScanner_WindowsPassword { get; set; }
+
///
/// Override the default remote desktop password to make it serializable.
///
diff --git a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs
index 811786e00f..9510cc5c14 100644
--- a/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs
+++ b/Source/NETworkManager.Settings/GlobalStaticConfiguration.cs
@@ -107,7 +107,6 @@ public static class GlobalStaticConfiguration
// Settings: Update
public static bool Update_CheckForUpdatesAtStartup => true;
public static bool Update_CheckForPreReleases => false;
- public static bool Experimental_EnableExperimentalFeatures => false;
// Settings: Profiles
public static bool Profiles_IsDailyBackupEnabled => true;
@@ -160,6 +159,7 @@ public static class GlobalStaticConfiguration
public static int IPScanner_PortScanAttempts => 1;
public static int IPScanner_MaxHostThreads => 128;
public static int IPScanner_MaxPortThreads => 16;
+ public static int IPScanner_MaxWindowsThreads => 16;
public static bool IPScanner_NetBIOSEnabled => true;
public static int IPScanner_NetBIOSTimeout => 2000;
public static bool IPScanner_ARPEnabled => true;
@@ -173,6 +173,9 @@ public static class GlobalStaticConfiguration
public static SNMPVersion IPScanner_SNMPVersion => SNMPVersion.V2C;
public static string IPScanner_SNMPCommunity => "public";
public static int IPScanner_SNMPTimeout => 2000;
+ public static bool IPScanner_WindowsEnabled => false;
+ public static int IPScanner_WindowsTimeout => 5000;
+ public static int IPScanner_WindowsMaxLogonFailures => 2;
public static bool IPScanner_ExpandHostView => false;
public static AutoRefreshTimeInfo IPScanner_AutoRefreshTime =>
diff --git a/Source/NETworkManager.Settings/SettingsInfo.cs b/Source/NETworkManager.Settings/SettingsInfo.cs
index 2b1c134448..fb066d7d30 100644
--- a/Source/NETworkManager.Settings/SettingsInfo.cs
+++ b/Source/NETworkManager.Settings/SettingsInfo.cs
@@ -608,19 +608,6 @@ public bool Update_CheckForPreReleases
}
} = GlobalStaticConfiguration.Update_CheckForPreReleases;
- public bool Experimental_EnableExperimentalFeatures
- {
- get;
- set
- {
- if (value == field)
- return;
-
- field = value;
- OnPropertyChanged();
- }
- } = GlobalStaticConfiguration.Experimental_EnableExperimentalFeatures;
-
// Profiles
public string Profiles_FolderLocation
@@ -1597,6 +1584,45 @@ public int IPScanner_SNMPTimeout
}
} = GlobalStaticConfiguration.IPScanner_SNMPTimeout;
+ public bool IPScanner_WindowsEnabled
+ {
+ get;
+ set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ }
+ } = GlobalStaticConfiguration.IPScanner_WindowsEnabled;
+
+ public int IPScanner_WindowsTimeout
+ {
+ get;
+ set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ }
+ } = GlobalStaticConfiguration.IPScanner_WindowsTimeout;
+
+ public int IPScanner_WindowsMaxLogonFailures
+ {
+ get;
+ set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ }
+ } = GlobalStaticConfiguration.IPScanner_WindowsMaxLogonFailures;
+
public ObservableCollection IPScanner_CustomCommands
{
get;
@@ -1637,6 +1663,19 @@ public int IPScanner_MaxPortThreads
}
} = GlobalStaticConfiguration.IPScanner_MaxPortThreads;
+ public int IPScanner_MaxWindowsThreads
+ {
+ get;
+ set
+ {
+ if (value == field)
+ return;
+
+ field = value;
+ OnPropertyChanged();
+ }
+ } = GlobalStaticConfiguration.IPScanner_MaxWindowsThreads;
+
public string IPScanner_ExportFilePath
{
get;
diff --git a/Source/NETworkManager.Tests/Network/ExportManagerIPScannerTests.cs b/Source/NETworkManager.Tests/Network/ExportManagerIPScannerTests.cs
index d5316b198d..e95dbeba69 100644
--- a/Source/NETworkManager.Tests/Network/ExportManagerIPScannerTests.cs
+++ b/Source/NETworkManager.Tests/Network/ExportManagerIPScannerTests.cs
@@ -22,9 +22,11 @@ public class ExportManagerIPScannerTests
"NetBIOSIPAddress,NetBIOSComputerName,NetBIOSUserName,NetBIOSGroupName,NetBIOSMACAddress,NetBIOSVendor," +
"MACAddress,Vendor,DNSHostname,DetectedBy,OSGuess,Role,MDNSHostname,WebTitle,WebURL,SNMPName,SNMPDescription," +
"SNMPLocation,WebStatusCode,WebServer,WebPoweredBy,WebRealm,WebRedirectURL,WebCertificateSubject," +
- "WebCertificateIssuer,WebCertificateNotAfter,WebCertificateSelfSigned,Change,PreviousMACAddress,SNMPError";
+ "WebCertificateIssuer,WebCertificateNotAfter,WebCertificateSelfSigned,Change,PreviousMACAddress,SNMPError," +
+ "WindowsOS,WindowsEdition,WindowsVersion,WindowsRole,WindowsComputerName,WindowsDomain,WindowsTimeOffset," +
+ "WindowsUsers,WindowsDescription,WindowsError,SMBDialect,SMBSigningRequired,SMBServerGuid";
- private static readonly IPScannerResultOptions AllEnabled = new(true, true, true, true, true, true, true, true, true);
+ private static readonly IPScannerResultOptions AllEnabled = new(true, true, true, true, true, true, true, true, true, true);
private static string Export(ExportFileType fileType, params IPScannerHostInfo[] hosts)
{
@@ -93,6 +95,74 @@ public void Json_WebPageWithoutPortScan_Empty()
Assert.Equal(JTokenType.Null, host["WebURL"]!.Type);
}
+ private static IPScannerHostInfo CreateWindowsHost()
+ {
+ var host = CreateHost();
+
+ var ntlm = new NTLMChallengeInfo(new Version(10, 0, 26200), "CLIENT01", "CORP", "client01.corp.example.com",
+ "corp.example.com", "example.com", null);
+ var smb = new SMBInfo("3.1.1", true, Guid.Parse("8c5b6f4e-3d2a-4b1c-9e8f-7a6b5c4d3e2f"), DateTime.UtcNow,
+ TimeSpan.FromSeconds(-185.5), ntlm);
+ var netApi = new WindowsNetApiInfo(0, WindowsHostRole.Workstation, true, "Reception, 1st floor", "CORP",
+ [@"CORP\alice", @"CORP\bob"], 0, null);
+
+ // The value is set by the scan (internal setter)
+ typeof(IPScannerHostInfo).GetProperty(nameof(IPScannerHostInfo.Windows))!
+ .SetValue(host, new WindowsHostInfo(smb, netApi));
+
+ return host;
+ }
+
+ [Fact]
+ public void Json_WindowsValues()
+ {
+ var host = (JObject)JArray.Parse(Export(ExportFileType.Json, CreateWindowsHost())).Single();
+
+ Assert.Equal("Windows 11 25H2", (string)host["WindowsOS"]);
+ Assert.Equal("10.0.26200", (string)host["WindowsVersion"]);
+ Assert.Equal("Workstation", (string)host["WindowsRole"]);
+ Assert.Equal("corp.example.com", (string)host["WindowsDomain"]);
+ Assert.Equal(-185.5, (double)host["WindowsTimeOffset"]);
+ Assert.Equal(JTokenType.Boolean, host["SMBSigningRequired"]!.Type);
+ Assert.Equal(@"CORP\alice; CORP\bob", (string)host["WindowsUsers"]);
+ Assert.Equal(JTokenType.Null, host["WindowsError"]!.Type);
+ Assert.Equal("3.1.1", (string)host["SMBDialect"]);
+ Assert.Equal("8c5b6f4e-3d2a-4b1c-9e8f-7a6b5c4d3e2f", (string)host["SMBServerGuid"]);
+ }
+
+ [Fact]
+ public void Json_WindowsDisabled_Empty()
+ {
+ var options = AllEnabled with { WindowsEnabled = false };
+
+ var host = (JObject)JArray.Parse(Export(ExportFileType.Json, options, CreateWindowsHost())).Single();
+
+ Assert.Equal(JTokenType.Null, host["WindowsOS"]!.Type);
+ Assert.Equal(JTokenType.Null, host["SMBServerGuid"]!.Type);
+ }
+
+ [Fact]
+ public void Csv_WindowsValues_OneValuePerColumn()
+ {
+ // The description contains a comma (quoted), the time offset has a decimal point in every culture
+ var culture = System.Globalization.CultureInfo.CurrentCulture;
+
+ try
+ {
+ System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
+
+ var row = Export(ExportFileType.Csv, CreateWindowsHost()).Split(Environment.NewLine)[1];
+
+ Assert.Contains("\"Reception, 1st floor\"", row);
+ Assert.Contains(",-185.5,", row);
+ Assert.Equal(CsvHeader.Split(',').Length, row.Replace("\"Reception, 1st floor\"", "x").Split(',').Length);
+ }
+ finally
+ {
+ System.Globalization.CultureInfo.CurrentCulture = culture;
+ }
+ }
+
[Fact]
public void Json_SameKeysAsCsv()
{
diff --git a/Source/NETworkManager.Tests/Network/IPScannerHostInfoTests.cs b/Source/NETworkManager.Tests/Network/IPScannerHostInfoTests.cs
index 3790891359..167adc11a5 100644
--- a/Source/NETworkManager.Tests/Network/IPScannerHostInfoTests.cs
+++ b/Source/NETworkManager.Tests/Network/IPScannerHostInfoTests.cs
@@ -35,6 +35,8 @@ public void Clone_CopiesAllValues()
var type when type.IsEnum => Enum.GetValues(type).Cast