using System.Buffers.Binary;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
///
/// The ScriptWorker's Windows identity (Scripting:Worker:Identity, lmxopcua#780 design §6, owner decision §14 #5).
///
///
///
/// Why a restricted token and not a logon. Windows starts a process under a virtual account
/// (NT SERVICE\name) only when the Service Control Manager starts that service; a host cannot launch K + 1
/// short-lived children, each with its own nonce, pipe and Job Object, that way. A separate local user would need
/// a stored password and SeAssignPrimaryTokenPrivilege on the host account. Instead the host derives a
/// restricted token from its own (the Windows Service Hardening / browser-sandbox technique): every
/// privilege is removed, and the virtual account's SID is one of the token's restricting SIDs, so every
/// access check must pass twice — once for the host account and once for the restricting set
/// (). The worker can therefore reach only what BOTH the host account AND the worker
/// identity (or Everyone / BUILTIN\Users / RESTRICTED, which the runtime needs to load from
/// System32) may reach: in effect a standard user bounded by the host account, with no privileges.
///
///
/// The virtual account's SID is computable from its name (), so the identity works for ACLs
/// and the firewall rule whether or not the installer's anchor service exists; the anchor only makes the name
/// resolvable in ACL editors.
///
///
public static partial class ScriptWorkerIdentity
{
/// The installer's default virtual account name (the anchor service's name).
public const string DefaultServiceName = "OtOpcUaScriptWorker";
/// The installer's default identity, as configured.
public const string DefaultIdentity = @"NT SERVICE\" + DefaultServiceName;
/// Everyone.
public const string EveryoneSid = "S-1-1-0";
/// BUILTIN\Users.
public const string BuiltinUsersSid = "S-1-5-32-545";
/// NT AUTHORITY\RESTRICTED (the SID many system objects grant for restricted tokens).
public const string RestrictedSid = "S-1-5-12";
private const string ServicePrefix = @"NT SERVICE\";
///
/// The restricting SIDs of a worker token for : the identity itself, then
/// Everyone, BUILTIN\Users and RESTRICTED. Authenticated Users and the logon SID are
/// deliberately absent (the first is granted Modify on many data folders; the second reaches the host's own
/// processes in an interactive session).
///
/// The worker identity's SID string.
/// The restricting SID strings, identity first.
public static IReadOnlyList RestrictingSids(string workerSid) => [workerSid, EveryoneSid, BuiltinUsersSid, RestrictedSid];
///
/// The SID Windows assigns the virtual account NT SERVICE\:
/// S-1-5-80- followed by the SHA-1 of the upper-cased name in UTF-16LE, read as five little-endian
/// 32-bit values (the algorithm behind sc.exe showsid).
///
/// The service name (no NT SERVICE\ prefix).
/// The SID string.
public static string ServiceSid(string serviceName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(serviceName);
var hash = SHA1.HashData(Encoding.Unicode.GetBytes(serviceName.ToUpperInvariant()));
var sb = new StringBuilder("S-1-5-80");
for (var i = 0; i < 5; i++)
sb.Append('-').Append(BinaryPrimitives.ReadUInt32LittleEndian(hash.AsSpan(i * 4, 4)).ToString(CultureInfo.InvariantCulture));
return sb.ToString();
}
/// Resolves a configured identity to a SID string without touching the OS.
/// NT SERVICE\name or a SID string (S-1-…).
/// The SID string.
/// Why it was refused.
/// True when resolved.
public static bool TryResolveSid(string? identity, out string sid, out string? error)
{
sid = string.Empty;
error = null;
var value = identity?.Trim();
if (string.IsNullOrEmpty(value))
{
error = "no identity is set";
return false;
}
if (value.StartsWith(ServicePrefix, StringComparison.OrdinalIgnoreCase))
{
var name = value[ServicePrefix.Length..];
if (!ServiceNamePattern().IsMatch(name))
{
error = "the virtual account name must be 1–80 letters, digits, '_', '-' or '.'";
return false;
}
sid = ServiceSid(name);
return true;
}
if (SidPattern().IsMatch(value))
{
if (value is EveryoneSid or BuiltinUsersSid or RestrictedSid || value.StartsWith("S-1-5-32-", StringComparison.Ordinal)
|| value == "S-1-5-18" || value == "S-1-5-11")
{
error = "a well-known group or SYSTEM is not a worker identity; use a dedicated virtual account";
return false;
}
sid = value.ToUpperInvariant();
return true;
}
error = @"expected 'NT SERVICE\' (the installer's virtual account) or a SID string 'S-1-…'";
return false;
}
[GeneratedRegex(@"^[A-Za-z0-9_.\-]{1,80}$", RegexOptions.CultureInvariant)]
private static partial Regex ServiceNamePattern();
[GeneratedRegex(@"^[Ss]-1-\d+(-\d+){1,14}$", RegexOptions.CultureInvariant)]
private static partial Regex SidPattern();
}