-
Notifications
You must be signed in to change notification settings - Fork 424
/
Win32Utils.cs
673 lines (613 loc) · 28.6 KB
/
Win32Utils.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
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
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 NtApiDotNet.Utilities.Memory;
using NtApiDotNet.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
namespace NtApiDotNet.Win32
{
/// <summary>
/// Utilities for Win32 APIs.
/// </summary>
public static class Win32Utils
{
private static bool IsValidMask(uint mask, uint valid_mask)
{
if (mask == 0)
{
return false;
}
// Filter out generic access etc.
if ((mask & ~valid_mask) != 0)
{
return false;
}
// Check if the mask only has a single bit set.
if ((mask & (mask - 1)) != 0)
{
return false;
}
return true;
}
private static void AddEnumToDictionary(Dictionary<uint, string> access, Type enumType, uint valid_mask, bool sdk_names)
{
Regex re = new Regex("([A-Z])");
foreach (uint mask in Enum.GetValues(enumType))
{
if (IsValidMask(mask, valid_mask))
{
string name = sdk_names ? NtSecurity.GetSDKName(enumType, mask)
: re.Replace(Enum.GetName(enumType, mask), " $1").Trim();
access.Add(mask, name);
}
}
}
private static string RemoveDevicePrefix(string win32_path)
{
if (win32_path.StartsWith(@"\\?\"))
{
if (win32_path.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase))
{
return @"\\" + win32_path.Substring(8);
}
else if (win32_path.Length >= 6)
{
if (NtFileUtils.GetDosPathType(win32_path.Substring(4)) == RtlPathType.DriveAbsolute)
{
return win32_path.Substring(4);
}
}
}
return win32_path;
}
/// <summary>
/// Get a mask dictionary for a type.
/// </summary>
/// <param name="access_type">The enumerated type to query for names.</param>
/// <param name="valid_access">The valid access.</param>
/// <returns>A dictionary mapping a mask value to a name.</returns>
public static Dictionary<uint, string> GetMaskDictionary(Type access_type, AccessMask valid_access)
{
return GetMaskDictionary(access_type, valid_access, false);
}
/// <summary>
/// Get a mask dictionary for a type.
/// </summary>
/// <param name="access_type">The enumerated type to query for names.</param>
/// <param name="valid_access">The valid access.</param>
/// <param name="sdk_names">Specify to get the SDK name instead of a formatting enumerated name.</param>
/// <returns>A dictionary mapping a mask value to a name.</returns>
public static Dictionary<uint, string> GetMaskDictionary(Type access_type, AccessMask valid_access, bool sdk_names)
{
Dictionary<uint, string> access = new Dictionary<uint, string>();
AddEnumToDictionary(access, access_type, valid_access.Access, sdk_names);
return access;
}
/// <summary>
/// Display the edit security dialog.
/// </summary>
/// <param name="hwnd">Parent window handle.</param>
/// <param name="handle">NT object to display the security.</param>
/// <param name="object_name">The name of the object to display.</param>
/// <param name="read_only">True to force the UI to read only.</param>
public static void EditSecurity(IntPtr hwnd, NtObject handle, string object_name, bool read_only)
{
Dictionary<uint, String> access = GetMaskDictionary(handle.NtType.AccessRightsType, handle.NtType.ValidAccess);
using (SecurityInformationImpl impl = new SecurityInformationImpl(object_name, handle, access,
handle.NtType.GenericMapping, read_only))
{
Win32NativeMethods.EditSecurity(hwnd, impl);
}
}
/// <summary>
/// Display the edit security dialog.
/// </summary>
/// <param name="hwnd">Parent window handle.</param>
/// <param name="name">The name of the object to display.</param>
/// <param name="sd">The security descriptor to display.</param>
/// <param name="type">The NT type of the object.</param>
public static void EditSecurity(IntPtr hwnd, string name, SecurityDescriptor sd, NtType type)
{
EditSecurity(hwnd, name, sd, type.AccessRightsType, type.ValidAccess, type.GenericMapping);
}
/// <summary>
/// Display the edit security dialog.
/// </summary>
/// <param name="hwnd">Parent window handle.</param>
/// <param name="name">The name of the object to display.</param>
/// <param name="sd">The security descriptor to display.</param>
/// <param name="access_type">An enumerated type for the access mask.</param>
/// <param name="generic_mapping">Generic mapping for the access rights.</param>
/// <param name="valid_access">Valid access mask for the access rights.</param>
public static void EditSecurity(IntPtr hwnd, string name, SecurityDescriptor sd,
Type access_type, AccessMask valid_access, GenericMapping generic_mapping)
{
Dictionary<uint, String> access = GetMaskDictionary(access_type, valid_access);
using (var impl = new SecurityInformationImpl(name, sd, access, generic_mapping))
{
Win32NativeMethods.EditSecurity(hwnd, impl);
}
}
/// <summary>
/// Define a new DOS device.
/// </summary>
/// <param name="flags">The dos device flags.</param>
/// <param name="device_name">The device name to define.</param>
/// <param name="target_path">The target path.</param>
public static void DefineDosDevice(DefineDosDeviceFlags flags, string device_name, string target_path)
{
if (!Win32NativeMethods.DefineDosDevice(flags, device_name, target_path))
{
throw new SafeWin32Exception();
}
}
/// <summary>
/// Get Windows INVALID_HANDLE_VALUE.
/// </summary>
public static IntPtr InvalidHandle { get => new IntPtr(-1); }
/// <summary>
/// Parse a command line into arguments.
/// </summary>
/// <param name="command_line">The parsed command line.</param>
/// <returns>The list of arguments.</returns>
public static string[] ParseCommandLine(string command_line)
{
if (string.IsNullOrWhiteSpace(command_line))
{
return new string[0];
}
using (var argv = Win32NativeMethods.CommandLineToArgvW(command_line, out int argc))
{
if (argv.IsInvalid)
{
throw new NtException(NtObjectUtils.MapDosErrorToStatus());
}
string[] ret = new string[argc];
for (int i = 0; i < argc; ++i)
{
ret[i] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(argv.DangerousGetHandle() + IntPtr.Size * i));
}
return ret;
}
}
/// <summary>
/// Get the image path from a command line.
/// </summary>
/// <param name="command_line">The command line to parse.</param>
/// <returns>The image path, returns the original command line if can't find a valid image path.</returns>
public static string GetImagePathFromCommandLine(string command_line)
{
command_line = command_line.Trim();
if (command_line.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && File.Exists(command_line))
{
return command_line;
}
string[] args = ParseCommandLine(command_line);
if (args.Length == 0)
{
return command_line;
}
if (command_line.StartsWith("\""))
{
return args[0];
}
for (int i = 0; i < args.Length; ++i)
{
string file = string.Join(" ", args.Take(i + 1));
if (File.Exists(file))
{
return file;
}
}
return command_line;
}
/// <summary>
/// Get Win32 path name for a file.
/// </summary>
/// <param name="file">The file to get the path from.</param>
/// <param name="flags">Flags for the path to return.</param>
/// <param name="throw_on_error">True to throw on error.</param>
/// <returns>The win32 path.</returns>
public static NtResult<string> GetWin32PathName(NtFile file, Win32PathNameFlags flags, bool throw_on_error)
{
StringBuilder builder = new StringBuilder(1000);
if (Win32NativeMethods.GetFinalPathNameByHandle(file.Handle, builder, builder.Capacity, flags) == 0)
{
return NtObjectUtils.MapDosErrorToStatus().CreateResultFromError<string>(throw_on_error);
}
return NtStatus.STATUS_SUCCESS.CreateResult(throw_on_error, () => RemoveDevicePrefix(builder.ToString()));
}
/// <summary>
/// Get Win32 path name for a file.
/// </summary>
/// <param name="file">The file to get the path from.</param>
/// <param name="flags">Flags for the path to return.</param>
/// <returns>The win32 path.</returns>
public static string GetWin32PathName(NtFile file, Win32PathNameFlags flags)
{
return GetWin32PathName(file, flags, true).Result;
}
/// <summary>
/// Format a message.
/// </summary>
/// <param name="module">The module containing the message.</param>
/// <param name="message_id">The ID of the message.</param>
/// <returns>The message. Empty string on error.</returns>
public static string FormatMessage(SafeLoadLibraryHandle module, uint message_id)
{
if (Win32NativeMethods.FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule
| FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
module.DangerousGetHandle(), message_id, 0, out SafeLocalAllocBuffer buffer, 0, IntPtr.Zero) > 0)
{
using (buffer)
{
return Marshal.PtrToStringUni(buffer.DangerousGetHandle()).Trim();
}
}
return string.Empty;
}
/// <summary>
/// Format a message.
/// </summary>
/// <param name="message_id">The ID of the message.</param>
/// <returns>The message. Empty string on error.</returns>
public static string FormatMessage(uint message_id)
{
return FormatMessage(SafeLoadLibraryHandle.Null, message_id);
}
internal static Win32Error GetLastWin32Error()
{
return (Win32Error)Marshal.GetLastWin32Error();
}
internal static NtResult<T> CreateWin32Result<T>(this bool result, bool throw_on_error, Func<T> create_func)
{
if (result)
{
return create_func().CreateResult();
}
return NtObjectUtils.MapDosErrorToStatus().CreateResultFromError<T>(throw_on_error);
}
internal static NtResult<T> CreateWin32Result<T>(this Win32Error result, bool throw_on_error, Func<T> create_func)
{
if (result == Win32Error.SUCCESS)
{
return create_func().CreateResult();
}
return result.CreateResultFromDosError<T>(throw_on_error);
}
internal static Win32Error GetLastWin32Error(this bool result)
{
if (result)
return Win32Error.SUCCESS;
return GetLastWin32Error();
}
internal static NtResult<T> CreateResultFromDosError<T>(bool throw_on_error)
{
return GetLastWin32Error().CreateResultFromDosError<T>(throw_on_error);
}
internal static NtStatus ToNtException(this bool result, bool throw_on_error)
{
return GetLastWin32Error(result).ToNtException(throw_on_error);
}
internal static NtStatus ToHresult(this Win32Error error)
{
return NtObjectUtils.BuildStatus(NtStatusSeverity.STATUS_SEVERITY_WARNING, false, false, NtStatusFacility.FACILITY_NTWIN32, (int)error);
}
/// <summary>
/// Open a file with the Win32 CreateFile API.
/// </summary>
/// <param name="filename">The filename to open.</param>
/// <param name="desired_access">The desired access.</param>
/// <param name="share_mode">The share mode.</param>
/// <param name="security_descriptor">Optional security descriptor.</param>
/// <param name="inherit_handle">True to set the handle as inheritable.</param>
/// <param name="creation_disposition">Creation disposition.</param>
/// <param name="flags_and_attributes">Flags and attributes.</param>
/// <param name="template_file">Optional template file.</param>
/// <param name="throw_on_error">True to throw on error.</param>
/// <returns>The opened file handle.</returns>
public static NtResult<NtFile> CreateFile(string filename,
FileAccessRights desired_access,
FileShareMode share_mode,
SecurityDescriptor security_descriptor,
bool inherit_handle,
CreateFileDisposition creation_disposition,
CreateFileFlagsAndAttributes flags_and_attributes,
NtFile template_file,
bool throw_on_error)
{
using (var resources = new DisposableList())
{
SECURITY_ATTRIBUTES sec_attr = null;
if (security_descriptor != null || inherit_handle)
{
sec_attr = new SECURITY_ATTRIBUTES();
sec_attr.bInheritHandle = inherit_handle;
sec_attr.lpSecurityDescriptor = security_descriptor == null ? SafeHGlobalBuffer.Null :
resources.AddResource(security_descriptor.ToSafeBuffer());
}
var handle = Win32NativeMethods.CreateFile(filename, desired_access,
share_mode, sec_attr, creation_disposition, flags_and_attributes,
template_file.GetHandle());
if (handle.IsInvalid)
{
return GetLastWin32Error().CreateResultFromDosError<NtFile>(throw_on_error);
}
return new NtFile(handle).CreateResult();
}
}
/// <summary>
/// Open a file with the Win32 CreateFile API.
/// </summary>
/// <param name="filename">The filename to open.</param>
/// <param name="desired_access">The desired access.</param>
/// <param name="share_mode">The share mode.</param>
/// <param name="security_descriptor">Optional security descriptor.</param>
/// <param name="inherit_handle">True to set the handle as inheritable.</param>
/// <param name="creation_disposition">Creation disposition.</param>
/// <param name="flags_and_attributes">Flags and attributes.</param>
/// <param name="template_file">Optional template file.</param>
/// <returns>The opened file handle.</returns>
public static NtFile CreateFile(string filename,
FileAccessRights desired_access,
FileShareMode share_mode,
SecurityDescriptor security_descriptor,
bool inherit_handle,
CreateFileDisposition creation_disposition,
CreateFileFlagsAndAttributes flags_and_attributes,
NtFile template_file)
{
return CreateFile(filename, desired_access, share_mode, security_descriptor, inherit_handle,
creation_disposition, flags_and_attributes, template_file, true).Result;
}
/// <summary>
/// Open a file with the Win32 CreateFile API.
/// </summary>
/// <param name="filename">The filename to open.</param>
/// <param name="desired_access">The desired access.</param>
/// <param name="share_mode">The share mode.</param>
/// <param name="creation_disposition">Creation disposition.</param>
/// <param name="flags_and_attributes">Flags and attributes.</param>
/// <param name="throw_on_error">True to throw on error.</param>
/// <returns>The opened file handle.</returns>
public static NtResult<NtFile> CreateFile(string filename,
FileAccessRights desired_access,
FileShareMode share_mode,
CreateFileDisposition creation_disposition,
CreateFileFlagsAndAttributes flags_and_attributes,
bool throw_on_error)
{
return CreateFile(filename, desired_access, share_mode, null, false,
creation_disposition, flags_and_attributes, null, throw_on_error);
}
/// <summary>
/// Open a file with the Win32 CreateFile API.
/// </summary>
/// <param name="filename">The filename to open.</param>
/// <param name="desired_access">The desired access.</param>
/// <param name="share_mode">The share mode.</param>
/// <param name="creation_disposition">Creation disposition.</param>
/// <param name="flags_and_attributes">Flags and attributes.</param>
/// <returns>The opened file handle.</returns>
public static NtFile CreateFile(string filename,
FileAccessRights desired_access,
FileShareMode share_mode,
CreateFileDisposition creation_disposition,
CreateFileFlagsAndAttributes flags_and_attributes)
{
return CreateFile(filename, desired_access, share_mode,
creation_disposition, flags_and_attributes, true).Result;
}
internal static SECURITY_CAPABILITIES CreateSecurityCapabilities(Sid package_sid, IEnumerable<Sid> capabilities, DisposableList resources)
{
SECURITY_CAPABILITIES caps = new SECURITY_CAPABILITIES
{
AppContainerSid = resources.AddResource(package_sid.ToSafeBuffer()).DangerousGetHandle()
};
if (capabilities.Any())
{
SidAndAttributes[] cap_sids = capabilities.Select(s => new SidAndAttributes()
{
Sid = resources.AddResource(s.ToSafeBuffer()).DangerousGetHandle(),
Attributes = GroupAttributes.Enabled
}).ToArray();
SafeHGlobalBuffer cap_buffer = resources.AddResource(new SafeHGlobalBuffer(Marshal.SizeOf(typeof(SidAndAttributes)) * cap_sids.Length));
cap_buffer.WriteArray(0, cap_sids, 0, cap_sids.Length);
caps.Capabilities = cap_buffer.DangerousGetHandle();
caps.CapabilityCount = cap_sids.Length;
}
return caps;
}
/// <summary>
/// Send key down events.
/// </summary>
/// <param name="key_codes">The key codes to send.</param>
public static void SendKeyDown(params VirtualKey[] key_codes)
{
INPUT[] inputs = key_codes.Select(k => new INPUT(k, false)).ToArray();
Win32NativeMethods.SendInput(inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
}
/// <summary>
/// Send key down events.
/// </summary>
/// <param name="key_codes">The key codes to send.</param>
public static void SendKeyUp(params VirtualKey[] key_codes)
{
INPUT[] inputs = key_codes.Select(k => new INPUT(k, true)).ToArray();
Win32NativeMethods.SendInput(inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
}
/// <summary>
/// Send key down then up events.
/// </summary>
/// <param name="key_codes">The key codes to send.</param>
/// <remarks>This will send all keys down first, then all up.</remarks>
public static void SendKeys(params VirtualKey[] key_codes)
{
SendKeyDown(key_codes);
SendKeyUp(key_codes);
}
/// <summary>
/// This creates a Window Station using the User32 API.
/// </summary>
/// <param name="name">The name of the Window Station.</param>
/// <returns>The Window Station.</returns>
public static NtWindowStation CreateWindowStation(string name)
{
var handle = Win32NativeMethods.CreateWindowStation(name, 0, WindowStationAccessRights.MaximumAllowed, null);
if (handle.IsInvalid)
throw new SafeWin32Exception();
return new NtWindowStation(handle);
}
/// <summary>
/// Create a remote thread.
/// </summary>
/// <param name="process">The process to create the thread in.</param>
/// <param name="security_descriptor">The thread security descriptor.</param>
/// <param name="inherit_handle">Whether the handle should be inherited.</param>
/// <param name="stack_size">The size of the stack. 0 for default.</param>
/// <param name="start_address">Start address for the thread.</param>
/// <param name="parameter">Parameter to pass to the thread.</param>
/// <param name="flags">The flags for the thread creation.</param>
/// <param name="throw_on_error">True to throw on error.</param>
/// <returns>The created thread.</returns>
/// <exception cref="NtException">Thrown on error.</exception>
public static NtResult<NtThread> CreateRemoteThread(
NtProcess process,
SecurityDescriptor security_descriptor,
bool inherit_handle,
long stack_size,
long start_address,
long parameter,
CreateThreadFlags flags,
bool throw_on_error)
{
if (process == null)
{
throw new ArgumentNullException(nameof(process));
}
using (var resources = new DisposableList())
{
SECURITY_ATTRIBUTES sec_attr = null;
if (security_descriptor != null || inherit_handle)
{
sec_attr = new SECURITY_ATTRIBUTES
{
bInheritHandle = inherit_handle,
lpSecurityDescriptor = security_descriptor == null ? SafeHGlobalBuffer.Null :
resources.AddResource(security_descriptor.ToSafeBuffer())
};
}
var handle = Win32NativeMethods.CreateRemoteThreadEx(process.GetHandle(),
sec_attr, new IntPtr(stack_size), new IntPtr(start_address),
new IntPtr(parameter), flags, SafeHGlobalBuffer.Null, null);
if (handle.IsInvalid)
{
return NtObjectUtils.CreateResultFromDosError<NtThread>(throw_on_error);
}
return new NtThread(handle).CreateResult();
}
}
/// <summary>
/// Create a remote thread.
/// </summary>
/// <param name="process">The process to create the thread in.</param>
/// <param name="security_descriptor">The thread security descriptor.</param>
/// <param name="inherit_handle">Whether the handle should be inherited.</param>
/// <param name="stack_size">The size of the stack. 0 for default.</param>
/// <param name="start_address">Start address for the thread.</param>
/// <param name="parameter">Parameter to pass to the thread.</param>
/// <param name="flags">The flags for the thread creation.</param>
/// <returns>The created thread.</returns>
/// <exception cref="NtException">Thrown on error.</exception>
public static NtThread CreateRemoteThread(
NtProcess process,
SecurityDescriptor security_descriptor,
bool inherit_handle,
long stack_size,
long start_address,
long parameter,
CreateThreadFlags flags)
{
return CreateRemoteThread(process, security_descriptor, inherit_handle,
stack_size, start_address, parameter, flags, true).Result;
}
/// <summary>
/// Create a remote thread.
/// </summary>
/// <param name="process">The process to create the thread in.</param>
/// <param name="start_address">Start address for the thread.</param>
/// <param name="parameter">Parameter to pass to the thread.</param>
/// <param name="flags">The flags for the thread creation.</param>
/// <returns>The created thread.</returns>
/// <exception cref="NtException">Thrown on error.</exception>
public static NtThread CreateRemoteThread(
NtProcess process,
long start_address,
long parameter,
CreateThreadFlags flags)
{
return CreateRemoteThread(process, null, false, 0, start_address, parameter, flags);
}
/// <summary>
/// Get a list of all console sessions.
/// </summary>
/// <param name="throw_on_error">True to throw on error.</param>
/// <returns>The list of console sessions.</returns>
public static NtResult<IEnumerable<ConsoleSession>> GetConsoleSessions(bool throw_on_error)
{
List<ConsoleSession> sessions = new List<ConsoleSession>();
IntPtr session_info = IntPtr.Zero;
int session_count = 0;
try
{
int level = 1;
if (!Win32NativeMethods.WTSEnumerateSessionsEx(IntPtr.Zero, ref level, 0, out session_info, out session_count))
{
return NtObjectUtils.MapDosErrorToStatus().CreateResultFromError<IEnumerable<ConsoleSession>>(throw_on_error);
}
sessions.AddRange(session_info.ReadArray<WTS_SESSION_INFO_1>(session_count).Select(w => new ConsoleSession(w)));
}
finally
{
if (session_info != IntPtr.Zero)
{
Win32NativeMethods.WTSFreeMemoryEx(WTS_TYPE_CLASS.WTSTypeSessionInfoLevel1,
session_info, session_count);
}
}
return sessions.AsReadOnly().CreateResult<IEnumerable<ConsoleSession>>();
}
/// <summary>
/// Get a list of all console sessions.
/// </summary>
/// <returns>The list of console sessions.</returns>
public static IEnumerable<ConsoleSession> GetConsoleSessions()
{
return GetConsoleSessions(true).Result;
}
/// <summary>
/// Write debug string to output.
/// </summary>
/// <param name="debug_str">The debug string to write.</param>
public static void WriteDebugString(string debug_str)
{
Win32NativeMethods.OutputDebugString(debug_str);
}
}
}