-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
♻️ Detect SeCreateGlobalPrivilege and move the shared memory stuff to…
… a separate assembly. This is mostly necessary so that the service can know which rights it has later on. Hopefully, ACL security stuff that is unimplemented in .NET Core won't be a problem…
- Loading branch information
Showing
15 changed files
with
275 additions
and
58 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> | ||
</PropertyGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,166 @@ | ||
using System.ComponentModel; | ||
using System.Diagnostics; | ||
using System.Runtime.CompilerServices; | ||
using System.Runtime.InteropServices; | ||
using System.Security; | ||
|
||
namespace Exo.Memory; | ||
|
||
[SuppressUnmanagedCodeSecurity] | ||
internal static unsafe class NativeMethods | ||
{ | ||
public const uint NtStatusBufferTooSmall = 0xC0000023; | ||
|
||
private const uint ReadControl = 0x00020000U; | ||
private const uint StandardRightsRead = ReadControl; | ||
private const uint TokenQuery = 0x0008; | ||
|
||
public const string SeCreateGlobalPrivilege = "SeCreateGlobalPrivilege"; | ||
|
||
public enum TokenInformationClass : uint | ||
{ | ||
TokenUser = 1, | ||
TokenGroups, | ||
TokenPrivileges, | ||
TokenOwner, | ||
TokenPrimaryGroup, | ||
TokenDefaultDacl, | ||
TokenSource, | ||
TokenType, | ||
TokenImpersonationLevel, | ||
TokenStatistics, | ||
TokenRestrictedSids, | ||
TokenSessionId, | ||
TokenGroupsAndPrivileges, | ||
TokenSessionReference, | ||
TokenSandBoxInert, | ||
TokenAuditPolicy, | ||
TokenOrigin, | ||
TokenElevationType, | ||
TokenLinkedToken, | ||
TokenElevation, | ||
TokenHasRestrictions, | ||
TokenAccessInformation, | ||
TokenVirtualizationAllowed, | ||
TokenVirtualizationEnabled, | ||
TokenIntegrityLevel, | ||
TokenUIAccess, | ||
TokenMandatoryPolicy, | ||
TokenLogonSid, | ||
TokenIsAppContainer, | ||
TokenCapabilities, | ||
TokenAppContainerSid, | ||
TokenAppContainerNumber, | ||
TokenUserClaimAttributes, | ||
TokenDeviceClaimAttributes, | ||
TokenRestrictedUserClaimAttributes, | ||
TokenRestrictedDeviceClaimAttributes, | ||
TokenDeviceGroups, | ||
TokenRestrictedDeviceGroups, | ||
TokenSecurityAttributes, | ||
TokenIsRestricted, | ||
TokenProcessTrustLevel, | ||
TokenPrivateNameSpace, | ||
TokenSingletonAttributes, | ||
TokenBnoIsolation, | ||
TokenChildProcessFlags, | ||
TokenIsLessPrivilegedAppContainer, | ||
TokenIsSandboxed, | ||
TokenIsAppSilo, | ||
TokenLoggingInformation, | ||
MaxTokenInfoClass, | ||
} | ||
|
||
public readonly struct LuidAndAttributes | ||
{ | ||
public readonly Luid Luid; | ||
public readonly PrivilegeAttributes Attributes; | ||
} | ||
|
||
public readonly struct Luid : IEquatable<Luid> | ||
{ | ||
public readonly uint LowPart; | ||
public readonly uint HighPart; | ||
|
||
public override bool Equals(object? obj) => obj is Luid luid && Equals(luid); | ||
public bool Equals(Luid other) => LowPart == other.LowPart && HighPart == other.HighPart; | ||
public override int GetHashCode() => HashCode.Combine(LowPart, HighPart); | ||
|
||
public static bool operator ==(Luid left, Luid right) => left.Equals(right); | ||
public static bool operator !=(Luid left, Luid right) => !(left == right); | ||
} | ||
|
||
[Flags] | ||
public enum PrivilegeAttributes : uint | ||
{ | ||
Disabled = 0x00000000, | ||
EnabledByDefault = 0x00000001, | ||
Enabled = 0x00000002, | ||
Removed = 0x00000004, | ||
UsedForAccess = 0x80000000, | ||
} | ||
|
||
[DllImport("advapi32", CharSet = CharSet.Unicode, EntryPoint = "LookupPrivilegeValueW", ExactSpelling = true, PreserveSig = true, SetLastError = true)] | ||
private static extern uint LookupPrivilegeValue(string? systemName, string name, Luid* privilege); | ||
|
||
[DllImport("advapi32", ExactSpelling = true, PreserveSig = true, SetLastError = true)] | ||
private static extern uint OpenProcessToken(nint processHandle, uint desiredAccess, out nint tokenHandle); | ||
|
||
[DllImport("ntdll", ExactSpelling = true, PreserveSig = true, SetLastError = false)] | ||
private static extern uint NtQueryInformationToken(nint tokenHandle, TokenInformationClass tokenInformationClass, void* tokenInformation, uint tokenInformationLength, uint* returnLength); | ||
|
||
[DllImport("ntdll", ExactSpelling = true, PreserveSig = true, SetLastError = false)] | ||
private static extern uint RtlNtStatusToDosError(uint status); | ||
|
||
[DllImport("kernel32", ExactSpelling = true, PreserveSig = true, SetLastError = true)] | ||
private static extern uint CloseHandle(nint handle); | ||
|
||
[DebuggerHidden] | ||
[StackTraceHidden] | ||
public static void ValidateNtStatus(uint status) | ||
{ | ||
if (status != 0) | ||
{ | ||
throw new Win32Exception((int)RtlNtStatusToDosError(status)); | ||
} | ||
} | ||
|
||
public static Luid GetPrivilegeValue(string privilegeName) | ||
{ | ||
ArgumentNullException.ThrowIfNull(privilegeName); | ||
|
||
Luid value = default; | ||
if (LookupPrivilegeValue(null, privilegeName, &value) == 0) | ||
{ | ||
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); | ||
} | ||
|
||
return value; | ||
} | ||
|
||
public static unsafe LuidAndAttributes[] GetProcessPrivileges() | ||
{ | ||
if (OpenProcessToken(Process.GetCurrentProcess().Handle, StandardRightsRead | TokenQuery, out nint tokenHandle) == 0) | ||
{ | ||
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); | ||
} | ||
try | ||
{ | ||
Span<byte> data = stackalloc byte[2048]; | ||
uint writtenLength = 0; | ||
uint result = NtQueryInformationToken(tokenHandle, TokenInformationClass.TokenPrivileges, Unsafe.AsPointer(ref data[0]), (uint)data.Length, &writtenLength); | ||
if (result != 0) | ||
{ | ||
Marshal.ThrowExceptionForHR((int)RtlNtStatusToDosError(result)); | ||
} | ||
return MemoryMarshal.Cast<byte, LuidAndAttributes>(data[..(int)writtenLength].Slice(4, (int)(Unsafe.As<byte, uint>(ref data[0]) * sizeof(LuidAndAttributes)))).ToArray(); | ||
} | ||
finally | ||
{ | ||
if (CloseHandle(tokenHandle) == 0) | ||
{ | ||
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
using System.IO.MemoryMappedFiles; | ||
using System.Security.Cryptography; | ||
|
||
namespace Exo.Memory; | ||
|
||
public sealed class SharedMemory : IDisposable | ||
{ | ||
private static readonly string DefaultPrefix = GetAcceptablePrefix(); | ||
|
||
private static string GetAcceptablePrefix() | ||
{ | ||
var seCreateGlobalPrivilege = NativeMethods.GetPrivilegeValue(NativeMethods.SeCreateGlobalPrivilege); | ||
foreach (var privilege in NativeMethods.GetProcessPrivileges()) | ||
{ | ||
if (privilege.Luid == seCreateGlobalPrivilege) return @"Global\"; | ||
} | ||
return @"Local\"; | ||
} | ||
|
||
public static SharedMemory Create(string prefix, ulong length) | ||
{ | ||
ArgumentNullException.ThrowIfNull(prefix); | ||
ArgumentOutOfRangeException.ThrowIfGreaterThan(length, (ulong)long.MaxValue); | ||
|
||
string name = string.Create | ||
( | ||
DefaultPrefix.Length + 32 + prefix.Length, | ||
prefix, | ||
static (span, prefix) => | ||
{ | ||
DefaultPrefix.CopyTo(span[..DefaultPrefix.Length]); | ||
prefix.CopyTo(span[DefaultPrefix.Length..]); | ||
RandomNumberGenerator.GetHexString(span[(DefaultPrefix.Length + prefix.Length)..], true); | ||
} | ||
); | ||
return new(name, MemoryMappedFile.CreateNew(name, (long)length, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None), length); | ||
} | ||
|
||
public static SharedMemory Open(string name, ulong length, MemoryMappedFileAccess access) | ||
{ | ||
ArgumentNullException.ThrowIfNull(name); | ||
ArgumentOutOfRangeException.ThrowIfGreaterThan(length, (ulong)long.MaxValue); | ||
|
||
return new(name, MemoryMappedFile.CreateOrOpen(name, (long)length, access), length); | ||
} | ||
|
||
private readonly string _name; | ||
private readonly MemoryMappedFile _file; | ||
private readonly ulong _length; | ||
|
||
private SharedMemory(string name, MemoryMappedFile file, ulong length) | ||
{ | ||
_name = name; | ||
_file = file; | ||
_length = length; | ||
} | ||
|
||
public void Dispose() => _file.Dispose(); | ||
|
||
public string Name => _name; | ||
public ulong Length => _length; | ||
|
||
public Stream CreateStream(MemoryMappedFileAccess access) => _file.CreateViewStream(0, (long)_length, access); | ||
public Stream CreateReadStream() => CreateStream(MemoryMappedFileAccess.Read); | ||
public Stream CreateWriteStream() => CreateStream(MemoryMappedFileAccess.Write); | ||
public MemoryMappedFileMemoryManager CreateMemoryManager(MemoryMappedFileAccess access) => new MemoryMappedFileMemoryManager(_file, 0, checked((int)Length), access); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
src/Exo/Ui/Exo.Settings.Ui/Converters/SharedMemoryToBitmapImageConverter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.