Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathUACHelper.cs
More file actions
740 lines (634 loc) · 28.6 KB
/
Copy pathUACHelper.cs
File metadata and controls
740 lines (634 loc) · 28.6 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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using Microsoft.Win32.TaskScheduler;
using UACHelper.Helpers;
using UACHelper.Native.ComInterop;
using UACHelper.Native.Enums;
using UACHelper.Native.Methods;
using UACHelper.Native.Structures;
using UACHelper.Properties;
using IServiceProvider = UACHelper.Native.ComInterop.IServiceProvider;
namespace UACHelper
{
/// <summary>
/// Contains properties about the current state of the application as well as providing methods to get information
/// about other processes and starting new ones.
/// </summary>
// ReSharper disable once HollowTypeName
public static class UACHelper
{
private static WindowsIdentity _currentUserIdentity;
private static WindowsIdentity CachedOwner
{
get => _currentUserIdentity ?? (_currentUserIdentity = Owner);
}
/// <summary>
/// Returns a <see cref="NTAccount" /> object containing information about the current desktop owner
/// </summary>
public static NTAccount DesktopOwner
{
get => GetProcessDesktopOwner(Process.GetCurrentProcess());
}
/// <summary>
/// A <see cref="bool" /> value indicating if the user that owns this process is a member of the 'Administrators'
/// group
/// </summary>
public static bool IsAdministrator
{
get
{
if (!IsUACEnable)
{
return IsElevated;
}
if (CachedOwner == null)
{
return false;
}
if (IsElevated)
{
return true;
}
var elevationType = Tokens.GetTokenElevationType(CachedOwner.Token);
return elevationType == TokenElevationType.Full ||
elevationType == TokenElevationType.Limited;
}
}
/// <summary>
/// A <see cref="bool" /> value indicating if the user that owns this process also owns the desktop session
/// </summary>
public static bool IsDesktopOwner
{
get => CachedOwner.User?.Equals(
(SecurityIdentifier) DesktopOwner.Translate(typeof(SecurityIdentifier))
) ==
true;
}
/// <summary>
/// A <see cref="bool" /> value indicating if the current process has full administrative rights
/// </summary>
public static bool IsElevated
{
get => CachedOwner != null &&
new WindowsPrincipal(CachedOwner).IsInRole(WindowsBuiltInRole.Administrator);
}
/// <summary>
/// A <see cref="bool" /> value indicating if the UAC vitalization is enable on this machine
/// </summary>
public static bool IsUACEnable
{
get
{
if (AAMSettings.IsEnable)
{
return true;
}
if (IsUACSupported && IsVirtualized)
{
return true;
}
return false;
}
}
/// <summary>
/// A <see cref="bool" /> value indicating if UAC virtualization is supported on the current machine
/// </summary>
public static bool IsUACSupported
{
get => Environment.OSVersion.Version.Major >= 6;
}
/// <summary>
/// A <see cref="Boolean" /> value indicating if the current process started under UAC virtualization
/// </summary>
public static bool IsVirtualized
{
get => Tokens.GetTokenElevationType(CachedOwner.Token) != TokenElevationType.Default;
}
/// <summary>
/// Returns a <see cref="WindowsIdentity" /> object containing information about the current process owner
/// </summary>
public static WindowsIdentity Owner
{
get => WindowsIdentity.GetCurrent();
}
/// <summary>
/// Checks a file and retrieve the expected <see cref="RunLevel" /> for it to start
/// </summary>
/// <param name="applicationAddress">Address of the file or the executable</param>
/// <param name="reason">A value showing the reason of this conclusion</param>
/// <returns>A value indicating the expected run level</returns>
/// <exception cref="NotSupportedException">This method is only supported on Windows Vista+</exception>
public static RunLevel GetExpectedRunLevel(string applicationAddress, out RunLevelConclusionReason reason)
{
try
{
uint pdwFlags = 0;
var errorCode = Kernel.CheckElevation(
applicationAddress,
ref pdwFlags,
IntPtr.Zero,
out var runLevel,
out reason
);
if (errorCode == 0) // ERROR_SUCCESS
{
return runLevel;
}
var exception = new Win32Exception(errorCode);
switch (errorCode)
{
case 2: // ERROR_FILE_NOT_FOUND
throw new FileNotFoundException(exception.Message, applicationAddress, exception);
case 3: // ERROR_PATH_NOT_FOUND
throw new DirectoryNotFoundException(exception.Message, exception);
case 5: // ERROR_ACCESS_DENIED
throw new UnauthorizedAccessException(exception.Message, exception);
case 8: // ERROR_NOT_ENOUGH_MEMORY
case 14: // ERROR_OUTOFMEMORY
throw new InsufficientMemoryException(exception.Message, exception);
case 15: // ERROR_INVALID_DRIVE
throw new DriveNotFoundException(exception.Message, exception);
default:
throw exception;
}
}
catch (EntryPointNotFoundException e)
{
throw new NotSupportedException(Resources.Error_This_method_is_not_supported_in_current_environment, e);
}
}
/// <summary>
/// Checks a file and retrieve the expected <see cref="RunLevel" /> for it to start
/// </summary>
/// <param name="applicationAddress">Address of the file or the executable</param>
/// <returns>A value indicating the expected run level</returns>
/// <exception cref="NotSupportedException">This method is only supported on Windows Vista+</exception>
public static RunLevel GetExpectedRunLevel(string applicationAddress)
{
return GetExpectedRunLevel(applicationAddress, out _);
}
/// <summary>
/// Returns a <see cref="NTAccount" /> object containing information about the desktop owner of a specific
/// <see cref="Process" />
/// </summary>
/// <param name="process"><see cref="Process" /> to get information about</param>
/// <exception cref="NotSupportedException">This method is not supported in current environment.</exception>
/// <returns>A newly created <see cref="NTAccount" /> object</returns>
public static NTAccount GetProcessDesktopOwner(Process process)
{
try
{
var sessionId = process.SessionId;
if (
WindowsTerminal.QuerySessionInformation(
IntPtr.Zero,
sessionId,
WindowsTerminalInfoClass.UserName,
out var buffer,
out var bufferSize
) &&
bufferSize > 0)
{
var accountName = Marshal.PtrToStringUni(buffer);
WindowsTerminal.FreeMemory(buffer);
if (accountName != null)
{
if (
WindowsTerminal.QuerySessionInformation(
IntPtr.Zero,
sessionId,
WindowsTerminalInfoClass.DomainName,
out buffer,
out bufferSize
) &&
bufferSize > 0)
{
var domainName = Marshal.PtrToStringUni(buffer);
WindowsTerminal.FreeMemory(buffer);
return new NTAccount(domainName, accountName);
}
return new NTAccount(accountName);
}
}
return new NTAccount(@"SYSTEM");
}
catch (EntryPointNotFoundException e)
{
throw new NotSupportedException(Resources.Error_This_method_is_not_supported_in_current_environment, e);
}
}
/// <summary>
/// Returns a <see cref="WindowsIdentity" /> object containing information about the owner of a specific
/// <see cref="Process" />
/// </summary>
/// <param name="process">
/// <see cref="Process" /> to be used for creating the corresponding <see cref="WindowsIdentity" />
/// object
/// </param>
/// <returns>A newly created <see cref="WindowsIdentity" /> object</returns>
public static WindowsIdentity GetProcessOwner(Process process)
{
if (!AdvancedAPI.OpenProcessToken(
process.Handle,
TokenAccessLevels.Query | TokenAccessLevels.Duplicate,
out var token))
{
throw new Win32Exception();
}
using (token)
{
return new WindowsIdentity(token.DangerousGetHandle());
}
}
/// <summary>
/// Indicates if the passed <see cref="Process" /> started with elevated privileges
/// </summary>
/// <param name="process">The <see cref="Process" /> to get information about</param>
/// <returns>A <see cref="Boolean" /> indicating if the <see cref="Process" /> in-fact started with elevated privileges</returns>
/// <exception cref="NotSupportedException">This method is only supported on Windows Vista+</exception>
/// <exception cref="InvalidOperationException">This method needs administrative access rights</exception>
public static bool IsProcessElevated(Process process)
{
if (!IsUACSupported)
{
throw new NotSupportedException();
}
if (!IsElevated)
{
throw new InvalidOperationException(Resources.Error_AccessDenied);
}
var processIdentity = GetProcessOwner(process);
try
{
var tokenElevation = Tokens.GetTokenElevationType(processIdentity.Token);
if (tokenElevation == TokenElevationType.Limited)
{
return false;
}
if (tokenElevation == TokenElevationType.Full)
{
return true;
}
}
catch (NotSupportedException)
{
// XP possibility. We can't open other user's processes. And no UAC.
// So we can assume that the process we manages to open is owned by same use and also started with highest available privileges.
return IsAdministrator;
}
// Do we have a Default elevation type? Then the process elevation status depends directly
// to the owner user being a member of the Administrative group.
return new WindowsPrincipal(processIdentity).IsInRole(WindowsBuiltInRole.Administrator);
}
/// <summary>
/// Starts a new <see cref="Process" /> with the start info provided and with the same rights as the mentioned
/// <see cref="Process" />
/// </summary>
/// <param name="process">The <see cref="Process" /> to copy rights from</param>
/// <param name="startInfo">Contains the information about the <see cref="Process" /> to be started</param>
/// <returns>Returns the newly started <see cref="Process" /></returns>
/// <exception cref="InvalidOperationException">This method needs administrative access rights.-or-UAC is not enable</exception>
/// <exception cref="NotSupportedException">Current version of Windows does not meets the needs of this method</exception>
public static Process StartAndCopyProcessPermission(Process process, ProcessStartInfo startInfo)
{
if (!string.IsNullOrWhiteSpace(startInfo.UserName))
{
throw new InvalidOperationException(Resources.Error_StartWithUsername);
}
if (!IsElevated)
{
throw new InvalidOperationException(Resources.Error_AccessDenied);
}
Tokens.EnablePrivilegeOnProcess(Process.GetCurrentProcess(), SecurityEntities.SeImpersonatePrivilege);
using (var primaryToken = Tokens.DuplicatePrimaryToken(process))
{
var lockTaken = false;
try
{
Monitor.Enter(startInfo, ref lockTaken);
var unicode = Environment.OSVersion.Platform == PlatformID.Win32NT;
var creationFlags = startInfo.CreateNoWindow
? ProcessCreationFlags.CreateNoWindow
: ProcessCreationFlags.None;
if (unicode)
{
creationFlags |= ProcessCreationFlags.UnicodeEnvironment;
}
var commandLine = IOPath.BuildCommandLine(startInfo.FileName, startInfo.Arguments);
var workingDirectory = string.IsNullOrEmpty(startInfo.WorkingDirectory)
? Environment.CurrentDirectory
: startInfo.WorkingDirectory;
var startupInfo = StartupInfo.GetOne();
var gcHandle = new GCHandle();
try
{
gcHandle =
GCHandle.Alloc(
IOPath.EnvironmentBlockToByteArray(startInfo.EnvironmentVariables, unicode),
GCHandleType.Pinned);
var environmentPtr = gcHandle.AddrOfPinnedObject();
var logonFlags = startInfo.LoadUserProfile ? LogonFlags.LogonWithProfile : LogonFlags.None;
ProcessInformation processInfo;
bool processCreationResult;
if (IsUACSupported) // Vista +
{
processCreationResult = AdvancedAPI.CreateProcessWithTokenW(primaryToken, logonFlags,
null,
commandLine,
creationFlags, environmentPtr, workingDirectory, ref startupInfo, out processInfo);
}
else
{
Tokens.EnablePrivilegeOnProcess(Process.GetCurrentProcess(),
SecurityEntities.SeIncreaseQuotaPrivilege);
processCreationResult = AdvancedAPI.CreateProcessAsUserW(primaryToken, null,
commandLine, IntPtr.Zero,
IntPtr.Zero, false, creationFlags, environmentPtr, workingDirectory, ref startupInfo,
out processInfo);
}
if (!processCreationResult)
{
throw new Win32Exception();
}
SafeNativeHandle.CloseHandle(processInfo.Thread);
SafeNativeHandle.CloseHandle(processInfo.Process);
if (processInfo.ProcessId <= 0)
{
throw new InvalidOperationException(Resources.Error_Unknown);
}
return Process.GetProcessById(processInfo.ProcessId);
}
catch (EntryPointNotFoundException e)
{
throw new NotSupportedException(
Resources.Error_This_method_is_not_supported_in_current_environment, e);
}
finally
{
if (gcHandle.IsAllocated)
{
gcHandle.Free();
}
}
}
finally
{
if (lockTaken)
{
Monitor.Exit(startInfo);
}
}
}
}
/// <summary>
/// Starts a new <see cref="Process" /> with the start info provided directly by Windows Explorer (Usually as limited)
/// </summary>
/// <param name="startInfo">Contains the information about the <see cref="Process" /> to be started</param>
/// <exception cref="NotSupportedException">This operation is not available in this environment.</exception>
/// <exception cref="InvalidOperationException">Failed to start application.</exception>
public static void StartByShell(ShellStartInfo startInfo)
{
var emptyObject = new object();
object shellWindows = null;
object desktopWindow = null;
object desktopBrowser = null;
object desktopView = null;
object backgroundFolderView = null;
object applicationDispatch = null;
var shellWindowsType = Type.GetTypeFromCLSID(ComClassId.ShellWindowsServer, false);
if (shellWindowsType == null)
{
throw new NotSupportedException("This operation is not available in this environment.");
}
try
{
shellWindows = Activator.CreateInstance(shellWindowsType);
desktopWindow = ((IShellWindows) shellWindows).FindWindowSW(
ref emptyObject,
ref emptyObject,
ShellWindowsClass.Desktop,
out var _,
ShellWindowsFindOptions.NeedDispatch
);
((IServiceProvider) desktopWindow).QueryService(
ServiceProviderServiceId.TopLevelBrowser,
typeof(IShellBrowser).GUID,
out desktopBrowser
);
((IShellBrowser) desktopBrowser).QueryActiveShellView(out desktopView);
((IShellView) desktopView).GetItemObject(
ShellViewGetItemObject.Background,
typeof(IDispatch).GUID,
out backgroundFolderView
);
applicationDispatch = ((IShellFolderViewDual) backgroundFolderView).Application;
var showFlags = new object();
switch (startInfo.WindowStyle)
{
case ProcessWindowStyle.Normal:
showFlags = ShellDispatchExecuteShowFlags.Normal;
break;
case ProcessWindowStyle.Hidden:
showFlags = ShellDispatchExecuteShowFlags.Hidden;
break;
case ProcessWindowStyle.Minimized:
showFlags = ShellDispatchExecuteShowFlags.Minimized;
break;
case ProcessWindowStyle.Maximized:
showFlags = ShellDispatchExecuteShowFlags.Maximized;
break;
}
((IShellDispatch2) applicationDispatch).ShellExecute(
startInfo.Address,
startInfo.Arguments,
startInfo.WorkingDirectory,
startInfo.Verb ?? emptyObject,
showFlags
);
}
catch (Exception e)
{
throw new InvalidOperationException("Failed to start application.", e);
}
finally
{
if (applicationDispatch != null)
{
Marshal.ReleaseComObject(applicationDispatch);
}
if (backgroundFolderView != null)
{
Marshal.ReleaseComObject(backgroundFolderView);
}
if (desktopView != null)
{
Marshal.ReleaseComObject(desktopView);
}
if (desktopBrowser != null)
{
Marshal.ReleaseComObject(desktopBrowser);
}
if (desktopWindow != null)
{
Marshal.ReleaseComObject(desktopWindow);
}
if (shellWindows != null)
{
Marshal.ReleaseComObject(shellWindows);
}
}
}
/// <summary>
/// Starts a new elevated <see cref="Process" /> with the start info provided
/// </summary>
/// <param name="startInfo">Contains the information about the <see cref="Process" /> to be started</param>
/// <returns>Returns the newly started <see cref="Process" /></returns>
/// <exception cref="NotSupportedException">
/// Can not use CreateProcess to start in elevated mode.-or-Can not use custom
/// verbs to start in elevated mode.
/// </exception>
/// <exception cref="InvalidOperationException">UAC is not enable</exception>
public static Process StartElevated(ProcessStartInfo startInfo)
{
if (!string.IsNullOrWhiteSpace(startInfo.UserName))
{
throw new InvalidOperationException(
Resources.Error_StartWithUsername);
}
if (IsElevated)
{
return Process.Start(startInfo);
}
if (!IsUACEnable && IsUACSupported)
{
throw new InvalidOperationException(Resources.Error_StartElevatedFailed_UACDisable);
}
if (startInfo.UseShellExecute == false)
{
throw new NotSupportedException(Resources.Error_StartElevatedFailed_NoShellExecute);
}
if (!string.IsNullOrWhiteSpace(startInfo.Verb) && startInfo.Verb.ToLower().Trim() != @"runas")
{
throw new NotSupportedException(Resources.Error_StartElevatedFailed_CustomVerbs);
}
startInfo.Verb = @"runas";
return Process.Start(startInfo);
}
/// <summary>
/// Starts a new <see cref="Process" /> with the start info provided and with the limited access rights
/// </summary>
/// <param name="startInfo">Contains the information about the <see cref="Process" /> to be started</param>
/// <returns>Returns the newly started <see cref="Process" /></returns>
public static Process StartLimited(ProcessStartInfo startInfo)
{
if (!string.IsNullOrWhiteSpace(startInfo.UserName))
{
throw new InvalidOperationException(
Resources.Error_StartWithUsername);
}
if (!IsElevated)
{
return Process.Start(startInfo);
}
var sessionOwner = (SecurityIdentifier) DesktopOwner.Translate(typeof(SecurityIdentifier));
foreach (var process in Process.GetProcesses())
{
try
{
var processIdentity = GetProcessOwner(process);
if (processIdentity.User?.Equals(sessionOwner) == true) // Same Terminal Session
{
var elevationType = Tokens.GetTokenElevationType(processIdentity.Token);
if (elevationType == TokenElevationType.Limited ||
elevationType == TokenElevationType.Default &&
!new WindowsPrincipal(processIdentity).IsInRole(WindowsBuiltInRole.Administrator))
{
return StartAndCopyProcessPermission(process, startInfo);
}
}
}
catch
{
// ignored
}
}
throw new InvalidOperationException(Resources.Error_StartLimitedFailed);
}
/// <summary>
/// Starts a new process with the task info provided and with the limited access rights
/// </summary>
/// <param name="taskStartInfo">Contains the information about the process to be started</param>
/// <exception cref="NotSupportedException">This method is only supported on Windows Vista+</exception>
public static void StartLimitedTask(TaskStartInfo taskStartInfo)
{
if (!IsElevated)
{
Process.Start(new ProcessStartInfo(taskStartInfo.Address, taskStartInfo.Arguments)
{
WorkingDirectory = taskStartInfo.WorkingDirectory
});
}
if (!IsUACSupported)
{
throw new NotSupportedException();
}
bool? success;
using (var taskService = new TaskService())
{
var name = "UACHelper.TemporaryTask.{" + Guid.NewGuid() + "}";
using (var newTask = taskService.NewTask())
{
newTask.Actions.Add(new ExecAction(taskStartInfo.Address, taskStartInfo.Arguments,
taskStartInfo.WorkingDirectory));
newTask.Principal.DisplayName = DesktopOwner.Value;
newTask.Principal.UserId = DesktopOwner.Translate(typeof(SecurityIdentifier)).Value;
newTask.Settings.ExecutionTimeLimit = TimeSpan.Zero;
var runningTask =
taskService.RootFolder.RegisterTaskDefinition(name, newTask)
.RunEx(TaskRunFlags.IgnoreConstraints, 0, string.Empty);
Thread.Sleep(1000);
success = runningTask?.State == TaskState.Running;
}
taskService.RootFolder.DeleteTask(name, false);
}
if (success != true)
{
throw new InvalidOperationException(Resources.Error_StartLimitedFailed);
}
}
/// <summary>
/// Starts a new <see cref="Process" /> with the start info provided and with the same rights as the current active
/// shell process
/// </summary>
/// <param name="startInfo">Contains the information about the <see cref="Process" /> to be started</param>
/// <returns>Returns the newly started <see cref="Process" /></returns>
/// <exception cref="InvalidOperationException">Can not find the current Shell Window</exception>
public static Process StartWithShell(ProcessStartInfo startInfo)
{
if (!string.IsNullOrWhiteSpace(startInfo.UserName))
{
throw new InvalidOperationException(
Resources.Error_StartWithUsername);
}
if (!IsElevated && (!IsAdministrator || !IsUACEnable))
{
return Process.Start(startInfo);
}
var shellWindow = User.GetShellWindow();
if (shellWindow == IntPtr.Zero)
{
throw new InvalidOperationException(Resources.Error_NoShellWindow);
}
if (User.GetWindowThreadProcessId(shellWindow, out var shellProcessId) == 0 || shellProcessId == 0)
{
throw new Win32Exception();
}
return StartAndCopyProcessPermission(Process.GetProcessById((int) shellProcessId), startInfo);
}
}
}
You can’t perform that action at this time.
