forked from hpsa/hpe-application-automation-tools-plugin
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathElevatedProcess.cs
245 lines (201 loc) · 9.42 KB
/
ElevatedProcess.cs
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/*
* Certain versions of software accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company.
* This software was acquired by Micro Focus on September 1, 2017, and is now offered by OpenText.
* Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.
* __________________________________________________________________
* MIT License
*
* Copyright 2012-2024 Open Text
*
* The only warranties for products and services of Open Text and
* its affiliates and licensors ("Open Text") are as may be set forth
* in the express warranty statements accompanying such products and services.
* Nothing herein should be construed as constituting an additional warranty.
* Open Text shall not be liable for technical or editorial errors or
* omissions contained herein. The information contained herein is subject
* to change without notice.
*
* Except as specifically indicated otherwise, this document contains
* confidential information and a valid license is required for possession,
* use or copying. If this work is provided to the U.S. Government,
* consistent with FAR 12.211 and 12.212, Commercial Computer Software,
* Computer Software Documentation, and Technical Data for Commercial Items are
* licensed to the U.S. Government under vendor's standard commercial license.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ___________________________________________________________________
*/
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
namespace HpToolsLauncher
{
[Serializable]
public class ElevatedProcessException : Exception
{
public ElevatedProcessException(string message) : base(message) { }
public ElevatedProcessException(string message, Exception innerException) : base(message, innerException) { }
}
public class ElevatedProcess : IDisposable
{
private readonly string _path;
private readonly string _arguments;
private readonly string _workDirectory;
private NativeProcess.PROCESS_INFORMATION _processInformation;
private const uint STILL_ACTIVE = 259;
private const uint INFINITE = 0xFFFFFFFF;
public ElevatedProcess(string path, string arguments, string workDirectory)
{
_path = path;
_arguments = arguments;
_workDirectory = workDirectory;
}
private int GetExitCode()
{
uint exitCode;
if (!NativeProcess.GetExitCodeProcess(_processInformation.hProcess, out exitCode))
{
return 0;
}
return (int)exitCode;
}
public int ExitCode
{
get
{
return GetExitCode();
}
}
public bool HasExited
{
get
{
return GetExitCode() != STILL_ACTIVE;
}
}
public void StartElevated()
{
Process process;
try
{
process = Process.GetProcessesByName("explorer").FirstOrDefault();
}
catch (InvalidOperationException e)
{
throw new ElevatedProcessException("An error has occurred while trying to find the 'explorer' process: ", e);
}
if (process == null)
{
throw new ElevatedProcessException("No process with the name 'explorer' found!");
}
// we can retrieve the token information from explorer
int explorerPid = process.Id;
// open the explorer process with the necessary flags
IntPtr hProcess = NativeProcess.OpenProcess(NativeProcess.ProcessAccessFlags.DuplicateHandle | NativeProcess.ProcessAccessFlags.QueryInformation, false, explorerPid);
if (hProcess == IntPtr.Zero)
{
throw new ElevatedProcessException("OpenProcess() failed with error code: " + Marshal.GetLastWin32Error());
}
IntPtr hUser;
// get the secondary token from the explorer process
if (!NativeProcess.OpenProcessToken(hProcess, NativeProcess.TOKEN_QUERY | NativeProcess.TOKEN_DUPLICATE | NativeProcess.TOKEN_ASSIGN_PRIMARY, out hUser))
{
NativeProcess.CloseHandle(hProcess);
throw new ElevatedProcessException("OpenProcessToken() failed with error code: " + Marshal.GetLastWin32Error());
}
IntPtr userToken;
// convert the secondary token to a primary token
if (!NativeProcess.DuplicateTokenEx(hUser, NativeProcess.MAXIMUM_ALLOWED, IntPtr.Zero, NativeProcess.SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
NativeProcess.TOKEN_TYPE.TokenPrimary, out userToken))
{
NativeProcess.CloseHandle(hUser);
NativeProcess.CloseHandle(hProcess);
throw new ElevatedProcessException("DuplicateTokenEx() failed with error code: " + Marshal.GetLastWin32Error());
}
// the explorer session id will be used in order to launch the given executable
uint sessionId;
if (!NativeProcess.ProcessIdToSessionId((uint)explorerPid, out sessionId))
{
throw new ElevatedProcessException("ProcessIdToSessionId() failed with error code: " + Marshal.GetLastWin32Error());
}
uint tokenInformationLen = (uint)Marshal.SizeOf(sessionId);
// set the session id
if (!NativeProcess.SetTokenInformation(userToken, NativeProcess.TOKEN_INFORMATION_CLASS.TokenSessionId, ref sessionId, tokenInformationLen))
{
NativeProcess.CloseHandle(hUser);
NativeProcess.CloseHandle(hProcess);
NativeProcess.CloseHandle(userToken);
throw new ElevatedProcessException("SetTokenInformation failed with: " + Marshal.GetLastWin32Error());
}
if (!NativeProcess.ImpersonateLoggedOnUser(userToken))
{
NativeProcess.CloseHandle(hUser);
NativeProcess.CloseHandle(hProcess);
NativeProcess.CloseHandle(userToken);
throw new ElevatedProcessException("ImpersonateLoggedOnUser failed with error code: " + Marshal.GetLastWin32Error());
}
// these handles are no longer needed
NativeProcess.CloseHandle(hUser);
NativeProcess.CloseHandle(hProcess);
NativeProcess.STARTUPINFO startupInfo = new NativeProcess.STARTUPINFO();
NativeProcess.PROCESS_INFORMATION pInfo = new NativeProcess.PROCESS_INFORMATION();
startupInfo.cb = Marshal.SizeOf(pInfo);
string commandLine = string.Format("{0} {1}", _path, _arguments);
IntPtr pEnv;
// create a new environment block for the process
if (!NativeProcess.CreateEnvironmentBlock(out pEnv, userToken, false))
{
throw new ElevatedProcessException("CreateEnvironmentBlock() failed with error code: " + Marshal.GetLastWin32Error());
}
// create the process with the retrieved token
if (!NativeProcess.CreateProcessAsUser(userToken, null, commandLine, IntPtr.Zero, IntPtr.Zero, false,
NativeProcess.CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT | NativeProcess.CreateProcessFlags.CREATE_SUSPENDED |
NativeProcess.CreateProcessFlags.CREATE_NO_WINDOW, pEnv, _workDirectory, ref startupInfo, out pInfo))
{
NativeProcess.CloseHandle(userToken);
if (pEnv != IntPtr.Zero)
{
NativeProcess.DestroyEnvironmentBlock(pEnv);
}
throw new ElevatedProcessException("CreateProcessAsUser() failed with error code: " + Marshal.GetLastWin32Error());
}
NativeProcess.ResumeThread(pInfo.hThread);
// the environment block can be destroyed now
if (pEnv != IntPtr.Zero)
{
NativeProcess.DestroyEnvironmentBlock(pEnv);
}
// save the process information
_processInformation = pInfo;
NativeProcess.RevertToSelf();
}
public void WaitForExit()
{
NativeProcess.WaitForSingleObject(_processInformation.hProcess, INFINITE);
}
public bool WaitForExit(int milliseconds)
{
NativeProcess.WaitForSingleObject(_processInformation.hProcess, (uint)milliseconds);
return HasExited;
}
public void Kill()
{
NativeProcess.TerminateProcess(_processInformation.hProcess, 0);
}
public void Dispose()
{
Close();
}
public void Close()
{
// close the handles before the object is destroyed
NativeProcess.CloseHandle(_processInformation.hProcess);
NativeProcess.CloseHandle(_processInformation.hThread);
}
}
}