Debian Codegraph @

test/support/windows-integration/plugins/modules/win_whoami.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2017, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 #Requires -Module Ansible.ModuleUtils.Legacy
7 #Requires -Module Ansible.ModuleUtils.CamelConversion
8
9 $ErrorActionPreference = "Stop"
10
11 $params = Parse-Args $args -supports_check_mode $true
12 $_remote_tmp = Get-AnsibleParam $params "_ansible_remote_tmp" -type "path" -default $env:TMP
13
14 $session_util = @'
15 using System;
16 using System.Collections;
17 using System.Collections.Generic;
18 using System.Linq;
19 using System.Runtime.InteropServices;
20 using System.Security.Principal;
21 using System.Text;
22
23 namespace Ansible
24 {
25 public class SessionInfo
26 {
27 // SECURITY_LOGON_SESSION_DATA
28 public UInt64 LogonId { get; internal set; }
29 public Sid Account { get; internal set; }
30 public string LoginDomain { get; internal set; }
31 public string AuthenticationPackage { get; internal set; }
32 public SECURITY_LOGON_TYPE LogonType { get; internal set; }
33 public string LoginTime { get; internal set; }
34 public string LogonServer { get; internal set; }
35 public string DnsDomainName { get; internal set; }
36 public string Upn { get; internal set; }
37 public ArrayList UserFlags { get; internal set; }
38
39 // TOKEN_STATISTICS
40 public SECURITY_IMPERSONATION_LEVEL ImpersonationLevel { get; internal set; }
41 public TOKEN_TYPE TokenType { get; internal set; }
42
43 // TOKEN_GROUPS
44 public ArrayList Groups { get; internal set; }
45 public ArrayList Rights { get; internal set; }
46
47 // TOKEN_MANDATORY_LABEL
48 public Sid Label { get; internal set; }
49
50 // TOKEN_PRIVILEGES
51 public Hashtable Privileges { get; internal set; }
52 }
53
54 public class Win32Exception : System.ComponentModel.Win32Exception
55 {
56 private string _msg;
57 public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { }
58 public Win32Exception(int errorCode, string message) : base(errorCode)
59 {
60 _msg = String.Format("{0} ({1}, Win32ErrorCode {2})", message, base.Message, errorCode);
61 }
62 public override string Message { get { return _msg; } }
63 public static explicit operator Win32Exception(string message) { return new Win32Exception(message); }
64 }
65
66 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
67 public struct LSA_UNICODE_STRING
68 {
69 public UInt16 Length;
70 public UInt16 MaximumLength;
71 public IntPtr buffer;
72 }
73
74 [StructLayout(LayoutKind.Sequential)]
75 public struct LUID
76 {
77 public UInt32 LowPart;
78 public Int32 HighPart;
79 }
80
81 [StructLayout(LayoutKind.Sequential)]
82 public struct SECURITY_LOGON_SESSION_DATA
83 {
84 public UInt32 Size;
85 public LUID LogonId;
86 public LSA_UNICODE_STRING Username;
87 public LSA_UNICODE_STRING LoginDomain;
88 public LSA_UNICODE_STRING AuthenticationPackage;
89 public SECURITY_LOGON_TYPE LogonType;
90 public UInt32 Session;
91 public IntPtr Sid;
92 public UInt64 LoginTime;
93 public LSA_UNICODE_STRING LogonServer;
94 public LSA_UNICODE_STRING DnsDomainName;
95 public LSA_UNICODE_STRING Upn;
96 public UInt32 UserFlags;
97 public LSA_LAST_INTER_LOGON_INFO LastLogonInfo;
98 public LSA_UNICODE_STRING LogonScript;
99 public LSA_UNICODE_STRING ProfilePath;
100 public LSA_UNICODE_STRING HomeDirectory;
101 public LSA_UNICODE_STRING HomeDirectoryDrive;
102 public UInt64 LogoffTime;
103 public UInt64 KickOffTime;
104 public UInt64 PasswordLastSet;
105 public UInt64 PasswordCanChange;
106 public UInt64 PasswordMustChange;
107 }
108
109 [StructLayout(LayoutKind.Sequential)]
110 public struct LSA_LAST_INTER_LOGON_INFO
111 {
112 public UInt64 LastSuccessfulLogon;
113 public UInt64 LastFailedLogon;
114 public UInt32 FailedAttemptCountSinceLastSuccessfulLogon;
115 }
116
117 public enum TOKEN_TYPE
118 {
119 TokenPrimary = 1,
120 TokenImpersonation
121 }
122
123 public enum SECURITY_IMPERSONATION_LEVEL
124 {
125 SecurityAnonymous,
126 SecurityIdentification,
127 SecurityImpersonation,
128 SecurityDelegation
129 }
130
131 public enum SECURITY_LOGON_TYPE
132 {
133 System = 0, // Used only by the System account
134 Interactive = 2,
135 Network,
136 Batch,
137 Service,
138 Proxy,
139 Unlock,
140 NetworkCleartext,
141 NewCredentials,
142 RemoteInteractive,
143 CachedInteractive,
144 CachedRemoteInteractive,
145 CachedUnlock
146 }
147
148 [Flags]
149 public enum TokenGroupAttributes : uint
150 {
151 SE_GROUP_ENABLED = 0x00000004,
152 SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002,
153 SE_GROUP_INTEGRITY = 0x00000020,
154 SE_GROUP_INTEGRITY_ENABLED = 0x00000040,
155 SE_GROUP_LOGON_ID = 0xC0000000,
156 SE_GROUP_MANDATORY = 0x00000001,
157 SE_GROUP_OWNER = 0x00000008,
158 SE_GROUP_RESOURCE = 0x20000000,
159 SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010,
160 }
161
162 [Flags]
163 public enum UserFlags : uint
164 {
165 LOGON_OPTIMIZED = 0x4000,
166 LOGON_WINLOGON = 0x8000,
167 LOGON_PKINIT = 0x10000,
168 LOGON_NOT_OPTMIZED = 0x20000,
169 }
170
171 [StructLayout(LayoutKind.Sequential)]
172 public struct SID_AND_ATTRIBUTES
173 {
174 public IntPtr Sid;
175 public UInt32 Attributes;
176 }
177
178 [StructLayout(LayoutKind.Sequential)]
179 public struct LUID_AND_ATTRIBUTES
180 {
181 public LUID Luid;
182 public UInt32 Attributes;
183 }
184
185 [StructLayout(LayoutKind.Sequential)]
186 public struct TOKEN_GROUPS
187 {
188 public UInt32 GroupCount;
189 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
190 public SID_AND_ATTRIBUTES[] Groups;
191 }
192
193 [StructLayout(LayoutKind.Sequential)]
194 public struct TOKEN_MANDATORY_LABEL
195 {
196 public SID_AND_ATTRIBUTES Label;
197 }
198
199 [StructLayout(LayoutKind.Sequential)]
200 public struct TOKEN_STATISTICS
201 {
202 public LUID TokenId;
203 public LUID AuthenticationId;
204 public UInt64 ExpirationTime;
205 public TOKEN_TYPE TokenType;
206 public SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
207 public UInt32 DynamicCharged;
208 public UInt32 DynamicAvailable;
209 public UInt32 GroupCount;
210 public UInt32 PrivilegeCount;
211 public LUID ModifiedId;
212 }
213
214 [StructLayout(LayoutKind.Sequential)]
215 public struct TOKEN_PRIVILEGES
216 {
217 public UInt32 PrivilegeCount;
218 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
219 public LUID_AND_ATTRIBUTES[] Privileges;
220 }
221
222 public class AccessToken : IDisposable
223 {
224 public enum TOKEN_INFORMATION_CLASS
225 {
226 TokenUser = 1,
227 TokenGroups,
228 TokenPrivileges,
229 TokenOwner,
230 TokenPrimaryGroup,
231 TokenDefaultDacl,
232 TokenSource,
233 TokenType,
234 TokenImpersonationLevel,
235 TokenStatistics,
236 TokenRestrictedSids,
237 TokenSessionId,
238 TokenGroupsAndPrivileges,
239 TokenSessionReference,
240 TokenSandBoxInert,
241 TokenAuditPolicy,
242 TokenOrigin,
243 TokenElevationType,
244 TokenLinkedToken,
245 TokenElevation,
246 TokenHasRestrictions,
247 TokenAccessInformation,
248 TokenVirtualizationAllowed,
249 TokenVirtualizationEnabled,
250 TokenIntegrityLevel,
251 TokenUIAccess,
252 TokenMandatoryPolicy,
253 TokenLogonSid,
254 TokenIsAppContainer,
255 TokenCapabilities,
256 TokenAppContainerSid,
257 TokenAppContainerNumber,
258 TokenUserClaimAttributes,
259 TokenDeviceClaimAttributes,
260 TokenRestrictedUserClaimAttributes,
261 TokenRestrictedDeviceClaimAttributes,
262 TokenDeviceGroups,
263 TokenRestrictedDeviceGroups,
264 TokenSecurityAttributes,
265 TokenIsRestricted,
266 MaxTokenInfoClass
267 }
268
269 public IntPtr hToken = IntPtr.Zero;
270
271 [DllImport("kernel32.dll")]
272 private static extern IntPtr GetCurrentProcess();
273
274 [DllImport("advapi32.dll", SetLastError = true)]
275 private static extern bool OpenProcessToken(
276 IntPtr ProcessHandle,
277 TokenAccessLevels DesiredAccess,
278 out IntPtr TokenHandle);
279
280 [DllImport("advapi32.dll", SetLastError = true)]
281 private static extern bool GetTokenInformation(
282 IntPtr TokenHandle,
283 TOKEN_INFORMATION_CLASS TokenInformationClass,
284 IntPtr TokenInformation,
285 UInt32 TokenInformationLength,
286 out UInt32 ReturnLength);
287
288 public AccessToken(TokenAccessLevels tokenAccessLevels)
289 {
290 IntPtr currentProcess = GetCurrentProcess();
291 if (!OpenProcessToken(currentProcess, tokenAccessLevels, out hToken))
292 throw new Win32Exception("OpenProcessToken() for current process failed");
293 }
294
295 public IntPtr GetTokenInformation<T>(out T tokenInformation, TOKEN_INFORMATION_CLASS tokenClass)
296 {
297 UInt32 tokenLength = 0;
298 GetTokenInformation(hToken, tokenClass, IntPtr.Zero, 0, out tokenLength);
299
300 IntPtr infoPtr = Marshal.AllocHGlobal((int)tokenLength);
301
302 if (!GetTokenInformation(hToken, tokenClass, infoPtr, tokenLength, out tokenLength))
303 throw new Win32Exception(String.Format("GetTokenInformation() data for {0} failed", tokenClass.ToString()));
304
305 tokenInformation = (T)Marshal.PtrToStructure(infoPtr, typeof(T));
306 return infoPtr;
307 }
308
309 public void Dispose()
310 {
311 GC.SuppressFinalize(this);
312 }
313
314 ~AccessToken() { Dispose(); }
315 }
316
317 public class LsaHandle : IDisposable
318 {
319 [Flags]
320 public enum DesiredAccess : uint
321 {
322 POLICY_VIEW_LOCAL_INFORMATION = 0x00000001,
323 POLICY_VIEW_AUDIT_INFORMATION = 0x00000002,
324 POLICY_GET_PRIVATE_INFORMATION = 0x00000004,
325 POLICY_TRUST_ADMIN = 0x00000008,
326 POLICY_CREATE_ACCOUNT = 0x00000010,
327 POLICY_CREATE_SECRET = 0x00000020,
328 POLICY_CREATE_PRIVILEGE = 0x00000040,
329 POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080,
330 POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100,
331 POLICY_AUDIT_LOG_ADMIN = 0x00000200,
332 POLICY_SERVER_ADMIN = 0x00000400,
333 POLICY_LOOKUP_NAMES = 0x00000800,
334 POLICY_NOTIFICATION = 0x00001000
335 }
336
337 public IntPtr handle = IntPtr.Zero;
338
339 [DllImport("advapi32.dll", SetLastError = true)]
340 private static extern uint LsaOpenPolicy(
341 LSA_UNICODE_STRING[] SystemName,
342 ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
343 DesiredAccess AccessMask,
344 out IntPtr PolicyHandle);
345
346 [DllImport("advapi32.dll", SetLastError = true)]
347 private static extern uint LsaClose(
348 IntPtr ObjectHandle);
349
350 [DllImport("advapi32.dll", SetLastError = false)]
351 private static extern int LsaNtStatusToWinError(
352 uint Status);
353
354 [StructLayout(LayoutKind.Sequential)]
355 public struct LSA_OBJECT_ATTRIBUTES
356 {
357 public int Length;
358 public IntPtr RootDirectory;
359 public IntPtr ObjectName;
360 public int Attributes;
361 public IntPtr SecurityDescriptor;
362 public IntPtr SecurityQualityOfService;
363 }
364
365 public LsaHandle(DesiredAccess desiredAccess)
366 {
367 LSA_OBJECT_ATTRIBUTES lsaAttr;
368 lsaAttr.RootDirectory = IntPtr.Zero;
369 lsaAttr.ObjectName = IntPtr.Zero;
370 lsaAttr.Attributes = 0;
371 lsaAttr.SecurityDescriptor = IntPtr.Zero;
372 lsaAttr.SecurityQualityOfService = IntPtr.Zero;
373 lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
374 LSA_UNICODE_STRING[] system = new LSA_UNICODE_STRING[1];
375 system[0].buffer = IntPtr.Zero;
376
377 uint res = LsaOpenPolicy(system, ref lsaAttr, desiredAccess, out handle);
378 if (res != 0)
379 throw new Win32Exception(LsaNtStatusToWinError(res), "LsaOpenPolicy() failed");
380 }
381
382 public void Dispose()
383 {
384 if (handle != IntPtr.Zero)
385 {
386 LsaClose(handle);
387 handle = IntPtr.Zero;
388 }
389 GC.SuppressFinalize(this);
390 }
391
392 ~LsaHandle() { Dispose(); }
393 }
394
395 public class Sid
396 {
397 public string SidString { get; internal set; }
398 public string DomainName { get; internal set; }
399 public string AccountName { get; internal set; }
400 public SID_NAME_USE SidType { get; internal set; }
401
402 public enum SID_NAME_USE
403 {
404 SidTypeUser = 1,
405 SidTypeGroup,
406 SidTypeDomain,
407 SidTypeAlias,
408 SidTypeWellKnownGroup,
409 SidTypeDeletedAccount,
410 SidTypeInvalid,
411 SidTypeUnknown,
412 SidTypeComputer,
413 SidTypeLabel,
414 SidTypeLogon,
415 }
416
417 [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
418 private static extern bool LookupAccountSid(
419 string lpSystemName,
420 [MarshalAs(UnmanagedType.LPArray)]
421 byte[] Sid,
422 StringBuilder lpName,
423 ref UInt32 cchName,
424 StringBuilder ReferencedDomainName,
425 ref UInt32 cchReferencedDomainName,
426 out SID_NAME_USE peUse);
427
428 public Sid(IntPtr sidPtr)
429 {
430 SecurityIdentifier sid;
431 try
432 {
433 sid = new SecurityIdentifier(sidPtr);
434 }
435 catch (Exception e)
436 {
437 throw new ArgumentException(String.Format("Failed to cast IntPtr to SecurityIdentifier: {0}", e));
438 }
439
440 SetSidInfo(sid);
441 }
442
443 public Sid(SecurityIdentifier sid)
444 {
445 SetSidInfo(sid);
446 }
447
448 public override string ToString()
449 {
450 return SidString;
451 }
452
453 private void SetSidInfo(SecurityIdentifier sid)
454 {
455 byte[] sidBytes = new byte[sid.BinaryLength];
456 sid.GetBinaryForm(sidBytes, 0);
457
458 StringBuilder lpName = new StringBuilder();
459 UInt32 cchName = 0;
460 StringBuilder referencedDomainName = new StringBuilder();
461 UInt32 cchReferencedDomainName = 0;
462 SID_NAME_USE peUse;
463 LookupAccountSid(null, sidBytes, lpName, ref cchName, referencedDomainName, ref cchReferencedDomainName, out peUse);
464
465 lpName.EnsureCapacity((int)cchName);
466 referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
467
468 SidString = sid.ToString();
469 if (!LookupAccountSid(null, sidBytes, lpName, ref cchName, referencedDomainName, ref cchReferencedDomainName, out peUse))
470 {
471 int lastError = Marshal.GetLastWin32Error();
472
473 if (lastError != 1332 && lastError != 1789) // Fails to lookup Logon Sid
474 {
475 throw new Win32Exception(lastError, String.Format("LookupAccountSid() failed for SID: {0} {1}", sid.ToString(), lastError));
476 }
477 else if (SidString.StartsWith("S-1-5-5-"))
478 {
479 AccountName = String.Format("LogonSessionId_{0}", SidString.Substring(8));
480 DomainName = "NT AUTHORITY";
481 SidType = SID_NAME_USE.SidTypeLogon;
482 }
483 else
484 {
485 AccountName = null;
486 DomainName = null;
487 SidType = SID_NAME_USE.SidTypeUnknown;
488 }
489 }
490 else
491 {
492 AccountName = lpName.ToString();
493 DomainName = referencedDomainName.ToString();
494 SidType = peUse;
495 }
496 }
497 }
498
499 public class SessionUtil
500 {
501 [DllImport("secur32.dll", SetLastError = false)]
502 private static extern uint LsaFreeReturnBuffer(
503 IntPtr Buffer);
504
505 [DllImport("secur32.dll", SetLastError = false)]
506 private static extern uint LsaEnumerateLogonSessions(
507 out UInt64 LogonSessionCount,
508 out IntPtr LogonSessionList);
509
510 [DllImport("secur32.dll", SetLastError = false)]
511 private static extern uint LsaGetLogonSessionData(
512 IntPtr LogonId,
513 out IntPtr ppLogonSessionData);
514
515 [DllImport("advapi32.dll", SetLastError = false)]
516 private static extern int LsaNtStatusToWinError(
517 uint Status);
518
519 [DllImport("advapi32", SetLastError = true)]
520 private static extern uint LsaEnumerateAccountRights(
521 IntPtr PolicyHandle,
522 IntPtr AccountSid,
523 out IntPtr UserRights,
524 out UInt64 CountOfRights);
525
526 [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
527 private static extern bool LookupPrivilegeName(
528 string lpSystemName,
529 ref LUID lpLuid,
530 StringBuilder lpName,
531 ref UInt32 cchName);
532
533 private const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001;
534 private const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002;
535 private const UInt32 STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034;
536 private const UInt32 STATUS_ACCESS_DENIED = 0xC0000022;
537
538 public static SessionInfo GetSessionInfo()
539 {
540 AccessToken accessToken = new AccessToken(TokenAccessLevels.Query);
541
542 // Get Privileges
543 Hashtable privilegeInfo = new Hashtable();
544 TOKEN_PRIVILEGES privileges;
545 IntPtr privilegesPtr = accessToken.GetTokenInformation(out privileges, AccessToken.TOKEN_INFORMATION_CLASS.TokenPrivileges);
546 LUID_AND_ATTRIBUTES[] luidAndAttributes = new LUID_AND_ATTRIBUTES[privileges.PrivilegeCount];
547 try
548 {
549 PtrToStructureArray(luidAndAttributes, privilegesPtr.ToInt64() + Marshal.SizeOf(privileges.PrivilegeCount));
550 }
551 finally
552 {
553 Marshal.FreeHGlobal(privilegesPtr);
554 }
555 foreach (LUID_AND_ATTRIBUTES luidAndAttribute in luidAndAttributes)
556 {
557 LUID privLuid = luidAndAttribute.Luid;
558 UInt32 privNameLen = 0;
559 StringBuilder privName = new StringBuilder();
560 LookupPrivilegeName(null, ref privLuid, null, ref privNameLen);
561 privName.EnsureCapacity((int)(privNameLen + 1));
562 if (!LookupPrivilegeName(null, ref privLuid, privName, ref privNameLen))
563 throw new Win32Exception("LookupPrivilegeName() failed");
564
565 string state = "disabled";
566 if ((luidAndAttribute.Attributes & SE_PRIVILEGE_ENABLED) == SE_PRIVILEGE_ENABLED)
567 state = "enabled";
568 if ((luidAndAttribute.Attributes & SE_PRIVILEGE_ENABLED_BY_DEFAULT) == SE_PRIVILEGE_ENABLED_BY_DEFAULT)
569 state = "enabled-by-default";
570 privilegeInfo.Add(privName.ToString(), state);
571 }
572
573 // Get Current Process LogonSID, User Rights and Groups
574 ArrayList userRights = new ArrayList();
575 ArrayList userGroups = new ArrayList();
576 TOKEN_GROUPS groups;
577 IntPtr groupsPtr = accessToken.GetTokenInformation(out groups, AccessToken.TOKEN_INFORMATION_CLASS.TokenGroups);
578 SID_AND_ATTRIBUTES[] sidAndAttributes = new SID_AND_ATTRIBUTES[groups.GroupCount];
579 LsaHandle lsaHandle = null;
580 // We can only get rights if we are an admin
581 if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
582 lsaHandle = new LsaHandle(LsaHandle.DesiredAccess.POLICY_LOOKUP_NAMES);
583 try
584 {
585 PtrToStructureArray(sidAndAttributes, groupsPtr.ToInt64() + IntPtr.Size);
586 foreach (SID_AND_ATTRIBUTES sidAndAttribute in sidAndAttributes)
587 {
588 TokenGroupAttributes attributes = (TokenGroupAttributes)sidAndAttribute.Attributes;
589 if (attributes.HasFlag(TokenGroupAttributes.SE_GROUP_ENABLED) && lsaHandle != null)
590 {
591 ArrayList rights = GetAccountRights(lsaHandle.handle, sidAndAttribute.Sid);
592 foreach (string right in rights)
593 {
594 // Includes both Privileges and Account Rights, only add the ones with Logon in the name
595 // https://msdn.microsoft.com/en-us/library/windows/desktop/bb545671(v=vs.85).aspx
596 if (!userRights.Contains(right) && right.Contains("Logon"))
597 userRights.Add(right);
598 }
599 }
600 // Do not include the Logon SID in the groups category
601 if (!attributes.HasFlag(TokenGroupAttributes.SE_GROUP_LOGON_ID))
602 {
603 Hashtable groupInfo = new Hashtable();
604 Sid group = new Sid(sidAndAttribute.Sid);
605 ArrayList groupAttributes = new ArrayList();
606 foreach (TokenGroupAttributes attribute in Enum.GetValues(typeof(TokenGroupAttributes)))
607 {
608 if (attributes.HasFlag(attribute))
609 {
610 string attributeName = attribute.ToString().Substring(9);
611 attributeName = attributeName.Replace('_', ' ');
612 attributeName = attributeName.First().ToString().ToUpper() + attributeName.Substring(1).ToLower();
613 groupAttributes.Add(attributeName);
614 }
615 }
616 // Using snake_case here as I can't generically convert all dict keys in PS (see Privileges)
617 groupInfo.Add("sid", group.SidString);
618 groupInfo.Add("domain_name", group.DomainName);
619 groupInfo.Add("account_name", group.AccountName);
620 groupInfo.Add("type", group.SidType);
621 groupInfo.Add("attributes", groupAttributes);
622 userGroups.Add(groupInfo);
623 }
624 }
625 }
626 finally
627 {
628 Marshal.FreeHGlobal(groupsPtr);
629 if (lsaHandle != null)
630 lsaHandle.Dispose();
631 }
632
633 // Get Integrity Level
634 Sid integritySid = null;
635 TOKEN_MANDATORY_LABEL mandatoryLabel;
636 IntPtr mandatoryLabelPtr = accessToken.GetTokenInformation(out mandatoryLabel, AccessToken.TOKEN_INFORMATION_CLASS.TokenIntegrityLevel);
637 Marshal.FreeHGlobal(mandatoryLabelPtr);
638 integritySid = new Sid(mandatoryLabel.Label.Sid);
639
640 // Get Token Statistics
641 TOKEN_STATISTICS tokenStats;
642 IntPtr tokenStatsPtr = accessToken.GetTokenInformation(out tokenStats, AccessToken.TOKEN_INFORMATION_CLASS.TokenStatistics);
643 Marshal.FreeHGlobal(tokenStatsPtr);
644
645 SessionInfo sessionInfo = GetSessionDataForLogonSession(tokenStats.AuthenticationId);
646 sessionInfo.Groups = userGroups;
647 sessionInfo.Label = integritySid;
648 sessionInfo.ImpersonationLevel = tokenStats.ImpersonationLevel;
649 sessionInfo.TokenType = tokenStats.TokenType;
650 sessionInfo.Privileges = privilegeInfo;
651 sessionInfo.Rights = userRights;
652 return sessionInfo;
653 }
654
655 private static ArrayList GetAccountRights(IntPtr lsaHandle, IntPtr sid)
656 {
657 UInt32 res;
658 ArrayList rights = new ArrayList();
659 IntPtr userRightsPointer = IntPtr.Zero;
660 UInt64 countOfRights = 0;
661
662 res = LsaEnumerateAccountRights(lsaHandle, sid, out userRightsPointer, out countOfRights);
663 if (res != 0 && res != STATUS_OBJECT_NAME_NOT_FOUND)
664 throw new Win32Exception(LsaNtStatusToWinError(res), "LsaEnumerateAccountRights() failed");
665 else if (res != STATUS_OBJECT_NAME_NOT_FOUND)
666 {
667 LSA_UNICODE_STRING[] userRights = new LSA_UNICODE_STRING[countOfRights];
668 PtrToStructureArray(userRights, userRightsPointer.ToInt64());
669 rights = new ArrayList();
670 foreach (LSA_UNICODE_STRING right in userRights)
671 rights.Add(Marshal.PtrToStringUni(right.buffer));
672 }
673
674 return rights;
675 }
676
677 private static SessionInfo GetSessionDataForLogonSession(LUID logonSession)
678 {
679 uint res;
680 UInt64 count = 0;
681 IntPtr luidPtr = IntPtr.Zero;
682 SessionInfo sessionInfo = null;
683 UInt64 processDataId = ConvertLuidToUint(logonSession);
684
685 res = LsaEnumerateLogonSessions(out count, out luidPtr);
686 if (res != 0)
687 throw new Win32Exception(LsaNtStatusToWinError(res), "LsaEnumerateLogonSessions() failed");
688 Int64 luidAddr = luidPtr.ToInt64();
689
690 try
691 {
692 for (UInt64 i = 0; i < count; i++)
693 {
694 IntPtr dataPointer = IntPtr.Zero;
695 res = LsaGetLogonSessionData(luidPtr, out dataPointer);
696 if (res == STATUS_ACCESS_DENIED) // Non admins won't be able to get info for session's that are not their own
697 {
698 luidPtr = new IntPtr(luidPtr.ToInt64() + Marshal.SizeOf(typeof(LUID)));
699 continue;
700 }
701 else if (res != 0)
702 throw new Win32Exception(LsaNtStatusToWinError(res), String.Format("LsaGetLogonSessionData() failed {0}", res));
703
704 SECURITY_LOGON_SESSION_DATA sessionData = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(dataPointer, typeof(SECURITY_LOGON_SESSION_DATA));
705 UInt64 sessionDataid = ConvertLuidToUint(sessionData.LogonId);
706
707 if (sessionDataid == processDataId)
708 {
709 ArrayList userFlags = new ArrayList();
710 UserFlags flags = (UserFlags)sessionData.UserFlags;
711 foreach (UserFlags flag in Enum.GetValues(typeof(UserFlags)))
712 {
713 if (flags.HasFlag(flag))
714 {
715 string flagName = flag.ToString().Substring(6);
716 flagName = flagName.Replace('_', ' ');
717 flagName = flagName.First().ToString().ToUpper() + flagName.Substring(1).ToLower();
718 userFlags.Add(flagName);
719 }
720 }
721
722 sessionInfo = new SessionInfo()
723 {
724 AuthenticationPackage = Marshal.PtrToStringUni(sessionData.AuthenticationPackage.buffer),
725 DnsDomainName = Marshal.PtrToStringUni(sessionData.DnsDomainName.buffer),
726 LoginDomain = Marshal.PtrToStringUni(sessionData.LoginDomain.buffer),
727 LoginTime = ConvertIntegerToDateString(sessionData.LoginTime),
728 LogonId = ConvertLuidToUint(sessionData.LogonId),
729 LogonServer = Marshal.PtrToStringUni(sessionData.LogonServer.buffer),
730 LogonType = sessionData.LogonType,
731 Upn = Marshal.PtrToStringUni(sessionData.Upn.buffer),
732 UserFlags = userFlags,
733 Account = new Sid(sessionData.Sid)
734 };
735 break;
736 }
737 luidPtr = new IntPtr(luidPtr.ToInt64() + Marshal.SizeOf(typeof(LUID)));
738 }
739 }
740 finally
741 {
742 LsaFreeReturnBuffer(new IntPtr(luidAddr));
743 }
744
745 if (sessionInfo == null)
746 throw new Exception(String.Format("Could not find the data for logon session {0}", processDataId));
747 return sessionInfo;
748 }
749
750 private static string ConvertIntegerToDateString(UInt64 time)
751 {
752 if (time == 0)
753 return null;
754 if (time > (UInt64)DateTime.MaxValue.ToFileTime())
755 return null;
756
757 DateTime dateTime = DateTime.FromFileTime((long)time);
758 return dateTime.ToString("o");
759 }
760
761 private static UInt64 ConvertLuidToUint(LUID luid)
762 {
763 UInt32 low = luid.LowPart;
764 UInt64 high = (UInt64)luid.HighPart;
765 high = high << 32;
766 UInt64 uintValue = (high | (UInt64)low);
767 return uintValue;
768 }
769
770 private static void PtrToStructureArray<T>(T[] array, Int64 pointerAddress)
771 {
772 Int64 pointerOffset = pointerAddress;
773 for (int i = 0; i < array.Length; i++, pointerOffset += Marshal.SizeOf(typeof(T)))
774 array[i] = (T)Marshal.PtrToStructure(new IntPtr(pointerOffset), typeof(T));
775 }
776
777 public static IEnumerable<T> GetValues<T>()
778 {
779 return Enum.GetValues(typeof(T)).Cast<T>();
780 }
781 }
782 }
783 '@
784
785 $original_tmp = $env:TMP
786 $env:TMP = $_remote_tmp
787 Add-Type -TypeDefinition $session_util
788 $env:TMP = $original_tmp
789
790 $session_info = [Ansible.SessionUtil]::GetSessionInfo()
791
792 Function Convert-Value($value) {
793 $new_value = $value
794 if ($value -is [System.Collections.ArrayList]) {
795 $new_value = [System.Collections.ArrayList]@()
796 foreach ($list_value in $value) {
797 $new_list_value = Convert-Value -value $list_value
798 [void]$new_value.Add($new_list_value)
799 }
800 } elseif ($value -is [Hashtable]) {
801 $new_value = @{}
802 foreach ($entry in $value.GetEnumerator()) {
803 $entry_value = Convert-Value -value $entry.Value
804 # manually convert Sid type entry to remove the SidType prefix
805 if ($entry.Name -eq "type") {
806 $entry_value = $entry_value.Replace("SidType", "")
807 }
808 $new_value[$entry.Name] = $entry_value
809 }
810 } elseif ($value -is [Ansible.Sid]) {
811 $new_value = @{
812 sid = $value.SidString
813 account_name = $value.AccountName
814 domain_name = $value.DomainName
815 type = $value.SidType.ToString().Replace("SidType", "")
816 }
817 } elseif ($value -is [Enum]) {
818 $new_value = $value.ToString()
819 }
820
821 return ,$new_value
822 }
823
824 $result = @{
825 changed = $false
826 }
827
828 $properties = [type][Ansible.SessionInfo]
829 foreach ($property in $properties.DeclaredProperties) {
830 $property_name = $property.Name
831 $property_value = $session_info.$property_name
832 $snake_name = Convert-StringToSnakeCase -string $property_name
833
834 $result.$snake_name = Convert-Value -value $property_value
835 }
836
837 Exit-Json -obj $result