blob: b3f99076cedc853eda001b15763df1020b9951ef (
plain)
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
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
using Xunit;
namespace System
{
public static class AdminHelpers
{
/// <summary>
/// Runs the given command as sudo (for Unix).
/// </summary>
/// <param name="commandLine">The command line to run as sudo</param>
/// <returns> Returns the process exit code (0 typically means it is successful)</returns>
public static int RunAsSudo(string commandLine)
{
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = "sudo",
Arguments = commandLine
};
using (Process process = Process.Start(startInfo))
{
Assert.True(process.WaitForExit(30000));
return process.ExitCode;
}
}
public static unsafe bool IsProcessElevated()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
uint userId = Interop.Sys.GetEUid();
return(userId == 0);
}
IntPtr processHandle = Interop.Kernel32.GetCurrentProcess();
SafeAccessTokenHandle token;
if (!Interop.Advapi32.OpenProcessToken(processHandle, TokenAccessLevels.Read, out token))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "Open process token failed");
}
using (token)
{
Interop.Advapi32.TOKEN_ELEVATION elevation = new Interop.Advapi32.TOKEN_ELEVATION();
uint ignore;
if (!Interop.Advapi32.GetTokenInformation(
token,
Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenElevation,
&elevation,
(uint)sizeof(Interop.Advapi32.TOKEN_ELEVATION),
out ignore))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "Get token information failed");
}
return elevation.TokenIsElevated != Interop.BOOL.FALSE;
}
}
}
}
|