-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurityUtilities.cs
More file actions
86 lines (79 loc) · 2.69 KB
/
Copy pathSecurityUtilities.cs
File metadata and controls
86 lines (79 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Security.Principal;
namespace IoMonitor
{
/// <summary>
/// Helper methods for interacting with the current Windows security context.
/// </summary>
internal static class SecurityUtilities
{
/// <summary>
/// Returns true when the current process is running as an Administrator.
/// </summary>
public static bool IsAdministrator()
{
try
{
using var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
/// <summary>
/// Attempts to enable SeDebugPrivilege for the current process.
/// </summary>
public static bool EnableDebugPrivilege()
{
try
{
IntPtr processHandle = NativeMethods.GetCurrentProcess();
if (!NativeMethods.OpenProcessToken(
processHandle,
NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY,
out var token))
{
return false;
}
try
{
if (!NativeMethods.LookupPrivilegeValue(null, "SeDebugPrivilege", out var luid))
{
return false;
}
var tp = new NativeMethods.TOKEN_PRIVILEGES
{
PrivilegeCount = 1,
Privileges = new[]
{
new NativeMethods.LUID_AND_ATTRIBUTES
{
Luid = luid,
Attributes = NativeMethods.SE_PRIVILEGE_ENABLED
}
}
};
bool result = NativeMethods.AdjustTokenPrivileges(
token,
disableAllPrivileges: false,
ref tp,
bufferLength: 0,
previousState: IntPtr.Zero,
returnLength: IntPtr.Zero);
return result;
}
finally
{
NativeMethods.CloseHandle(token);
}
}
catch
{
return false;
}
}
}
}