Debian Codegraph @

lib/ansible/module_utils/csharp/Ansible.Become.cs

raw
1 using Microsoft.Win32.SafeHandles;
2 using System;
3 using System.Collections;
4 using System.Collections.Generic;
5 using System.IO;
6 using System.Linq;
7 using System.Runtime.InteropServices;
8 using System.Security.AccessControl;
9 using System.Security.Principal;
10 using System.Text;
11 using Ansible.AccessToken;
12 using Ansible.Process;
13
14 namespace Ansible.Become
15 {
16 internal class NativeHelpers
17 {
18 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
19 public struct KERB_S4U_LOGON
20 {
21 public UInt32 MessageType;
22 public UInt32 Flags;
23 public LSA_UNICODE_STRING ClientUpn;
24 public LSA_UNICODE_STRING ClientRealm;
25 }
26
27 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
28 public struct LSA_STRING
29 {
30 public UInt16 Length;
31 public UInt16 MaximumLength;
32 [MarshalAs(UnmanagedType.LPStr)] public string Buffer;
33
34 public static implicit operator string(LSA_STRING s)
35 {
36 return s.Buffer;
37 }
38
39 public static implicit operator LSA_STRING(string s)
40 {
41 if (s == null)
42 s = "";
43
44 LSA_STRING lsaStr = new LSA_STRING
45 {
46 Buffer = s,
47 Length = (UInt16)s.Length,
48 MaximumLength = (UInt16)(s.Length + 1),
49 };
50 return lsaStr;
51 }
52 }
53
54 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
55 public struct LSA_UNICODE_STRING
56 {
57 public UInt16 Length;
58 public UInt16 MaximumLength;
59 public IntPtr Buffer;
60 }
61
62 [StructLayout(LayoutKind.Sequential)]
63 public struct SECURITY_LOGON_SESSION_DATA
64 {
65 public UInt32 Size;
66 public Luid LogonId;
67 public LSA_UNICODE_STRING UserName;
68 public LSA_UNICODE_STRING LogonDomain;
69 public LSA_UNICODE_STRING AuthenticationPackage;
70 public SECURITY_LOGON_TYPE LogonType;
71 }
72
73 [StructLayout(LayoutKind.Sequential)]
74 public struct TOKEN_SOURCE
75 {
76 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public char[] SourceName;
77 public Luid SourceIdentifier;
78 }
79
80 public enum SECURITY_LOGON_TYPE
81 {
82 System = 0, // Used only by the System account
83 Interactive = 2,
84 Network,
85 Batch,
86 Service,
87 Proxy,
88 Unlock,
89 NetworkCleartext,
90 NewCredentials,
91 RemoteInteractive,
92 CachedInteractive,
93 CachedRemoteInteractive,
94 CachedUnlock
95 }
96
97 [Flags]
98 public enum ProcessChildProcessPolicyFlags
99 {
100 None = 0x0,
101 NoChildProcessCreation = 0x1,
102 AuditNoChildProcessCreation = 0x2,
103 AllowSecureProcessCreation = 0x4,
104 }
105 }
106
107 internal class NativeMethods
108 {
109 public const int ProcessChildProcessPolicy = 13;
110
111 [DllImport("advapi32.dll", SetLastError = true)]
112 public static extern bool AllocateLocallyUniqueId(
113 out Luid Luid);
114
115 [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
116 public static extern bool CreateProcessWithTokenW(
117 SafeNativeHandle hToken,
118 LogonFlags dwLogonFlags,
119 [MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName,
120 StringBuilder lpCommandLine,
121 Process.NativeHelpers.ProcessCreationFlags dwCreationFlags,
122 Process.SafeMemoryBuffer lpEnvironment,
123 [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory,
124 Process.NativeHelpers.STARTUPINFOEX lpStartupInfo,
125 out Process.NativeHelpers.PROCESS_INFORMATION lpProcessInformation);
126
127 [DllImport("kernel32.dll")]
128 public static extern UInt32 GetCurrentThreadId();
129
130 [DllImport("kernel32.dll", SetLastError = true)]
131 public static extern bool GetProcessMitigationPolicy(
132 SafeNativeHandle hProcess,
133 int MitigationPolicy,
134 ref NativeHelpers.ProcessChildProcessPolicyFlags lpBuffer,
135 IntPtr dwLength);
136
137 [DllImport("user32.dll", SetLastError = true)]
138 public static extern NoopSafeHandle GetProcessWindowStation();
139
140 [DllImport("user32.dll", SetLastError = true)]
141 public static extern NoopSafeHandle GetThreadDesktop(
142 UInt32 dwThreadId);
143
144 [DllImport("secur32.dll", SetLastError = true)]
145 public static extern UInt32 LsaDeregisterLogonProcess(
146 IntPtr LsaHandle);
147
148 [DllImport("secur32.dll", SetLastError = true)]
149 public static extern UInt32 LsaFreeReturnBuffer(
150 IntPtr Buffer);
151
152 [DllImport("secur32.dll", SetLastError = true)]
153 public static extern UInt32 LsaGetLogonSessionData(
154 ref Luid LogonId,
155 out SafeLsaMemoryBuffer ppLogonSessionData);
156
157 [DllImport("secur32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
158 public static extern UInt32 LsaLogonUser(
159 SafeLsaHandle LsaHandle,
160 NativeHelpers.LSA_STRING OriginName,
161 LogonType LogonType,
162 UInt32 AuthenticationPackage,
163 IntPtr AuthenticationInformation,
164 UInt32 AuthenticationInformationLength,
165 IntPtr LocalGroups,
166 NativeHelpers.TOKEN_SOURCE SourceContext,
167 out SafeLsaMemoryBuffer ProfileBuffer,
168 out UInt32 ProfileBufferLength,
169 out Luid LogonId,
170 out SafeNativeHandle Token,
171 out IntPtr Quotas,
172 out UInt32 SubStatus);
173
174 [DllImport("secur32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
175 public static extern UInt32 LsaLookupAuthenticationPackage(
176 SafeLsaHandle LsaHandle,
177 NativeHelpers.LSA_STRING PackageName,
178 out UInt32 AuthenticationPackage);
179
180 [DllImport("advapi32.dll")]
181 public static extern UInt32 LsaNtStatusToWinError(
182 UInt32 Status);
183
184 [DllImport("secur32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
185 public static extern UInt32 LsaRegisterLogonProcess(
186 NativeHelpers.LSA_STRING LogonProcessName,
187 out SafeLsaHandle LsaHandle,
188 out IntPtr SecurityMode);
189 }
190
191 internal class SafeLsaHandle : SafeHandleZeroOrMinusOneIsInvalid
192 {
193 public SafeLsaHandle() : base(true) { }
194
195 protected override bool ReleaseHandle()
196 {
197 UInt32 res = NativeMethods.LsaDeregisterLogonProcess(handle);
198 return res == 0;
199 }
200 }
201
202 internal class SafeLsaMemoryBuffer : SafeHandleZeroOrMinusOneIsInvalid
203 {
204 public SafeLsaMemoryBuffer() : base(true) { }
205
206 protected override bool ReleaseHandle()
207 {
208 UInt32 res = NativeMethods.LsaFreeReturnBuffer(handle);
209 return res == 0;
210 }
211 }
212
213 internal class NoopSafeHandle : SafeHandle
214 {
215 public NoopSafeHandle() : base(IntPtr.Zero, false) { }
216 public override bool IsInvalid { get { return false; } }
217
218 protected override bool ReleaseHandle() { return true; }
219 }
220
221 [Flags]
222 public enum LogonFlags
223 {
224 None = 0x00000000,
225 WithProfile = 0x00000001,
226 NetcredentialsOnly = 0x00000002
227 }
228
229 public class BecomeUtil
230 {
231 private static List<string> SERVICE_SIDS = new List<string>()
232 {
233 "S-1-5-18", // NT AUTHORITY\SYSTEM
234 "S-1-5-19", // NT AUTHORITY\LocalService
235 "S-1-5-20" // NT AUTHORITY\NetworkService
236 };
237 private static int WINDOWS_STATION_ALL_ACCESS = 0x000F037F;
238 private static int DESKTOP_RIGHTS_ALL_ACCESS = 0x000F01FF;
239 private static bool _getProcessMitigationPolicySupported = true;
240
241 public static Result CreateProcessAsUser(string username, string password, string command)
242 {
243 return CreateProcessAsUser(username, password, LogonFlags.WithProfile, LogonType.Interactive,
244 null, command, null, null, "");
245 }
246
247 public static Result CreateProcessAsUser(string username, string password, LogonFlags logonFlags, LogonType logonType,
248 string lpApplicationName, string lpCommandLine, string lpCurrentDirectory, IDictionary environment,
249 string stdin)
250 {
251 byte[] stdinBytes;
252 if (String.IsNullOrEmpty(stdin))
253 stdinBytes = new byte[0];
254 else
255 {
256 if (!stdin.EndsWith(Environment.NewLine))
257 stdin += Environment.NewLine;
258 stdinBytes = new UTF8Encoding(false).GetBytes(stdin);
259 }
260 return CreateProcessAsUser(username, password, logonFlags, logonType, lpApplicationName, lpCommandLine,
261 lpCurrentDirectory, environment, stdinBytes);
262 }
263
264 /// <summary>
265 /// Creates a process as another user account. This method will attempt to run as another user with the
266 /// highest possible permissions available. The main privilege required is the SeDebugPrivilege, without
267 /// this privilege you can only run as a local or domain user if the username and password is specified.
268 /// </summary>
269 /// <param name="username">The username of the runas user</param>
270 /// <param name="password">The password of the runas user</param>
271 /// <param name="logonFlags">LogonFlags to control how to logon a user when the password is specified</param>
272 /// <param name="logonType">Controls what type of logon is used, this only applies when the password is specified</param>
273 /// <param name="lpApplicationName">The name of the executable or batch file to executable</param>
274 /// <param name="lpCommandLine">The command line to execute, typically this includes lpApplication as the first argument</param>
275 /// <param name="lpCurrentDirectory">The full path to the current directory for the process, null will have the same cwd as the calling process</param>
276 /// <param name="environment">A dictionary of key/value pairs to define the new process environment</param>
277 /// <param name="stdin">Bytes sent to the stdin pipe</param>
278 /// <returns>Ansible.Process.Result object that contains the command output and return code</returns>
279 public static Result CreateProcessAsUser(string username, string password, LogonFlags logonFlags, LogonType logonType,
280 string lpApplicationName, string lpCommandLine, string lpCurrentDirectory, IDictionary environment, byte[] stdin)
281 {
282 // While we use STARTUPINFOEX having EXTENDED_STARTUPINFO_PRESENT causes a parameter validation error
283 Process.NativeHelpers.ProcessCreationFlags creationFlags = Process.NativeHelpers.ProcessCreationFlags.CREATE_UNICODE_ENVIRONMENT;
284 Process.NativeHelpers.PROCESS_INFORMATION pi = new Process.NativeHelpers.PROCESS_INFORMATION();
285 Process.NativeHelpers.STARTUPINFOEX si = new Process.NativeHelpers.STARTUPINFOEX();
286 si.startupInfo.dwFlags = Process.NativeHelpers.StartupInfoFlags.USESTDHANDLES;
287
288 SafeFileHandle stdoutRead, stdoutWrite, stderrRead, stderrWrite, stdinRead, stdinWrite;
289 ProcessUtil.CreateStdioPipes(si, out stdoutRead, out stdoutWrite, out stderrRead, out stderrWrite,
290 out stdinRead, out stdinWrite);
291 FileStream stdinStream = new FileStream(stdinWrite, FileAccess.Write);
292
293 // $null from PowerShell ends up as an empty string, we need to convert back as an empty string doesn't
294 // make sense for these parameters
295 if (lpApplicationName == "")
296 lpApplicationName = null;
297
298 if (lpCurrentDirectory == "")
299 lpCurrentDirectory = null;
300
301 // A user may have 2 tokens, 1 limited and 1 elevated. GetUserTokens will return both token to ensure
302 // we don't close one of the pairs while the process is still running. If the process tries to retrieve
303 // one of the pairs and the token handle is closed then it will fail with ERROR_NO_SUCH_LOGON_SESSION.
304 List<SafeNativeHandle> userTokens = GetUserTokens(username, password, logonType);
305 try
306 {
307 using (Process.SafeMemoryBuffer lpEnvironment = ProcessUtil.CreateEnvironmentPointer(environment))
308 {
309 bool launchSuccess = false;
310 StringBuilder commandLine = new StringBuilder(lpCommandLine);
311 foreach (SafeNativeHandle token in userTokens)
312 {
313 // GetUserTokens could return null if an elevated token could not be retrieved.
314 if (token == null)
315 continue;
316
317 if (NativeMethods.CreateProcessWithTokenW(token, logonFlags, lpApplicationName,
318 commandLine, creationFlags, lpEnvironment, lpCurrentDirectory, si, out pi))
319 {
320 launchSuccess = true;
321 break;
322 }
323 }
324
325 if (!launchSuccess)
326 throw new Process.Win32Exception("CreateProcessWithTokenW() failed");
327 }
328 return ProcessUtil.WaitProcess(stdoutRead, stdoutWrite, stderrRead, stderrWrite, stdinStream, stdin,
329 pi.hProcess);
330 }
331 finally
332 {
333 userTokens.Where(t => t != null).ToList().ForEach(t => t.Dispose());
334 }
335 }
336
337 private static List<SafeNativeHandle> GetUserTokens(string username, string password, LogonType logonType)
338 {
339 List<SafeNativeHandle> userTokens = new List<SafeNativeHandle>();
340
341 SafeNativeHandle systemToken = null;
342 bool impersonated = false;
343 string becomeSid = username;
344 if (logonType != LogonType.NewCredentials)
345 {
346 // If prefixed with .\, we are becoming a local account, strip the prefix
347 if (username.StartsWith(".\\"))
348 username = username.Substring(2);
349
350 NTAccount account = new NTAccount(username);
351 becomeSid = ((SecurityIdentifier)account.Translate(typeof(SecurityIdentifier))).Value;
352
353 // Grant access to the current Windows Station and Desktop to the become user
354 GrantAccessToWindowStationAndDesktop(account);
355
356 // Try and impersonate a SYSTEM token, we need a SYSTEM token to either become a well known service
357 // account or have administrative rights on the become access token.
358 // If we ultimately are becoming the SYSTEM account we want the token with the most privileges available.
359 // https://github.com/ansible/ansible/issues/71453
360 bool usedForProcess = becomeSid == "S-1-5-18";
361 systemToken = GetPrimaryTokenForUser(new SecurityIdentifier("S-1-5-18"),
362 new List<string>() { "SeTcbPrivilege" }, usedForProcess);
363 if (systemToken != null)
364 {
365 try
366 {
367 TokenUtil.ImpersonateToken(systemToken);
368 impersonated = true;
369 }
370 catch (Process.Win32Exception) { } // We tried, just rely on current user's permissions.
371 }
372 }
373
374 // We require impersonation if becoming a service sid or becoming a user without a password
375 if (!impersonated && (SERVICE_SIDS.Contains(becomeSid) || String.IsNullOrEmpty(password)))
376 throw new Exception("Failed to get token for NT AUTHORITY\\SYSTEM required for become as a service account or an account without a password");
377
378 try
379 {
380 if (becomeSid == "S-1-5-18")
381 userTokens.Add(systemToken);
382 // Cannot use String.IsEmptyOrNull() as an empty string is an account that doesn't have a pass.
383 // We only use S4U if no password was defined or it was null
384 else if (!SERVICE_SIDS.Contains(becomeSid) && password == null && logonType != LogonType.NewCredentials)
385 {
386 // If no password was specified, try and duplicate an existing token for that user or use S4U to
387 // generate one without network credentials
388 SecurityIdentifier sid = new SecurityIdentifier(becomeSid);
389 SafeNativeHandle becomeToken = GetPrimaryTokenForUser(sid);
390 if (becomeToken != null)
391 {
392 userTokens.Add(GetElevatedToken(becomeToken));
393 userTokens.Add(becomeToken);
394 }
395 else
396 {
397 becomeToken = GetS4UTokenForUser(sid, logonType);
398 userTokens.Add(null);
399 userTokens.Add(becomeToken);
400 }
401 }
402 else
403 {
404 string domain = null;
405 switch (becomeSid)
406 {
407 case "S-1-5-19":
408 logonType = LogonType.Service;
409 domain = "NT AUTHORITY";
410 username = "LocalService";
411 break;
412 case "S-1-5-20":
413 logonType = LogonType.Service;
414 domain = "NT AUTHORITY";
415 username = "NetworkService";
416 break;
417 default:
418 // Trying to become a local or domain account
419 if (username.Contains(@"\"))
420 {
421 string[] userSplit = username.Split(new char[1] { '\\' }, 2);
422 domain = userSplit[0];
423 username = userSplit[1];
424 }
425 else if (!username.Contains("@"))
426 domain = ".";
427 break;
428 }
429
430 SafeNativeHandle hToken = TokenUtil.LogonUser(username, domain, password, logonType,
431 LogonProvider.Default);
432
433 // Get the elevated token for a local/domain accounts only
434 if (!SERVICE_SIDS.Contains(becomeSid))
435 userTokens.Add(GetElevatedToken(hToken));
436 userTokens.Add(hToken);
437 }
438 }
439 finally
440 {
441 if (impersonated)
442 TokenUtil.RevertToSelf();
443 }
444
445 return userTokens;
446 }
447
448 private static SafeNativeHandle GetPrimaryTokenForUser(
449 SecurityIdentifier sid,
450 List<string> requiredPrivileges = null,
451 bool usedForProcess = false)
452 {
453 // According to CreateProcessWithTokenW we require a token with
454 // TOKEN_QUERY, TOKEN_DUPLICATE and TOKEN_ASSIGN_PRIMARY
455 // Also add in TOKEN_IMPERSONATE so we can get an impersonated token
456 TokenAccessLevels dwAccess = TokenAccessLevels.Query |
457 TokenAccessLevels.Duplicate |
458 TokenAccessLevels.AssignPrimary |
459 TokenAccessLevels.Impersonate;
460
461 SafeNativeHandle userToken = null;
462 int privilegeCount = 0;
463
464 // If we are using this token for the process, we need to check the
465 // process mitigation policy allows child processes to be created.
466 var processFilter = usedForProcess
467 ? (Func<System.Diagnostics.Process, SafeNativeHandle, bool>)((p, t) =>
468 {
469 return GetProcessChildProcessPolicyFlags(t) == NativeHelpers.ProcessChildProcessPolicyFlags.None;
470 })
471 : ((p, t) => true);
472
473 foreach (SafeNativeHandle hToken in TokenUtil.EnumerateUserTokens(sid, dwAccess, processFilter))
474 {
475 // Filter out any Network logon tokens, using become with that is useless when S4U
476 // can give us a Batch logon
477 NativeHelpers.SECURITY_LOGON_TYPE tokenLogonType = GetTokenLogonType(hToken);
478 if (tokenLogonType == NativeHelpers.SECURITY_LOGON_TYPE.Network)
479 continue;
480
481 List<string> actualPrivileges = TokenUtil.GetTokenPrivileges(hToken).Select(x => x.Name).ToList();
482
483 // If the token has less or the same number of privileges than the current token, skip it.
484 if (usedForProcess && privilegeCount >= actualPrivileges.Count)
485 continue;
486
487 // Check that the required privileges are on the token
488 if (requiredPrivileges != null)
489 {
490 int missing = requiredPrivileges.Where(x => !actualPrivileges.Contains(x)).Count();
491 if (missing > 0)
492 continue;
493 }
494
495 // Duplicate the token to convert it to a primary token with the access level required.
496 try
497 {
498 userToken = TokenUtil.DuplicateToken(hToken, TokenAccessLevels.MaximumAllowed,
499 SecurityImpersonationLevel.Anonymous, TokenType.Primary);
500 privilegeCount = actualPrivileges.Count;
501 }
502 catch (Process.Win32Exception)
503 {
504 continue;
505 }
506
507 // If we don't care about getting the token with the most privileges, escape the loop as we already
508 // have a token.
509 if (!usedForProcess)
510 break;
511 }
512
513 return userToken;
514 }
515
516 private static SafeNativeHandle GetS4UTokenForUser(SecurityIdentifier sid, LogonType logonType)
517 {
518 NTAccount becomeAccount = (NTAccount)sid.Translate(typeof(NTAccount));
519 string[] userSplit = becomeAccount.Value.Split(new char[1] { '\\' }, 2);
520 string domainName = userSplit[0];
521 string username = userSplit[1];
522 bool domainUser = domainName.ToLowerInvariant() != Environment.MachineName.ToLowerInvariant();
523
524 NativeHelpers.LSA_STRING logonProcessName = "ansible";
525 SafeLsaHandle lsaHandle;
526 IntPtr securityMode;
527 UInt32 res = NativeMethods.LsaRegisterLogonProcess(logonProcessName, out lsaHandle, out securityMode);
528 if (res != 0)
529 throw new Process.Win32Exception((int)NativeMethods.LsaNtStatusToWinError(res), "LsaRegisterLogonProcess() failed");
530
531 using (lsaHandle)
532 {
533 NativeHelpers.LSA_STRING packageName = domainUser ? "Kerberos" : "MICROSOFT_AUTHENTICATION_PACKAGE_V1_0";
534 UInt32 authPackage;
535 res = NativeMethods.LsaLookupAuthenticationPackage(lsaHandle, packageName, out authPackage);
536 if (res != 0)
537 throw new Process.Win32Exception((int)NativeMethods.LsaNtStatusToWinError(res),
538 String.Format("LsaLookupAuthenticationPackage({0}) failed", (string)packageName));
539
540 int usernameLength = username.Length * sizeof(char);
541 int domainLength = domainName.Length * sizeof(char);
542 int authInfoLength = (Marshal.SizeOf(typeof(NativeHelpers.KERB_S4U_LOGON)) + usernameLength + domainLength);
543 IntPtr authInfo = Marshal.AllocHGlobal((int)authInfoLength);
544 try
545 {
546 IntPtr usernamePtr = IntPtr.Add(authInfo, Marshal.SizeOf(typeof(NativeHelpers.KERB_S4U_LOGON)));
547 IntPtr domainPtr = IntPtr.Add(usernamePtr, usernameLength);
548
549 // KERB_S4U_LOGON has the same structure as MSV1_0_S4U_LOGON (local accounts)
550 NativeHelpers.KERB_S4U_LOGON s4uLogon = new NativeHelpers.KERB_S4U_LOGON
551 {
552 MessageType = 12, // KerbS4ULogon
553 Flags = 0,
554 ClientUpn = new NativeHelpers.LSA_UNICODE_STRING
555 {
556 Length = (UInt16)usernameLength,
557 MaximumLength = (UInt16)usernameLength,
558 Buffer = usernamePtr,
559 },
560 ClientRealm = new NativeHelpers.LSA_UNICODE_STRING
561 {
562 Length = (UInt16)domainLength,
563 MaximumLength = (UInt16)domainLength,
564 Buffer = domainPtr,
565 },
566 };
567 Marshal.StructureToPtr(s4uLogon, authInfo, false);
568 Marshal.Copy(username.ToCharArray(), 0, usernamePtr, username.Length);
569 Marshal.Copy(domainName.ToCharArray(), 0, domainPtr, domainName.Length);
570
571 Luid sourceLuid;
572 if (!NativeMethods.AllocateLocallyUniqueId(out sourceLuid))
573 throw new Process.Win32Exception("AllocateLocallyUniqueId() failed");
574
575 NativeHelpers.TOKEN_SOURCE tokenSource = new NativeHelpers.TOKEN_SOURCE
576 {
577 SourceName = "ansible\0".ToCharArray(),
578 SourceIdentifier = sourceLuid,
579 };
580
581 // Only Batch or Network will work with S4U, prefer Batch but use Network if asked
582 LogonType lsaLogonType = logonType == LogonType.Network
583 ? LogonType.Network
584 : LogonType.Batch;
585 SafeLsaMemoryBuffer profileBuffer;
586 UInt32 profileBufferLength;
587 Luid logonId;
588 SafeNativeHandle hToken;
589 IntPtr quotas;
590 UInt32 subStatus;
591
592 res = NativeMethods.LsaLogonUser(lsaHandle, logonProcessName, lsaLogonType, authPackage,
593 authInfo, (UInt32)authInfoLength, IntPtr.Zero, tokenSource, out profileBuffer, out profileBufferLength,
594 out logonId, out hToken, out quotas, out subStatus);
595 if (res != 0)
596 throw new Process.Win32Exception((int)NativeMethods.LsaNtStatusToWinError(res),
597 String.Format("LsaLogonUser() failed with substatus {0}", subStatus));
598
599 profileBuffer.Dispose();
600 return hToken;
601 }
602 finally
603 {
604 Marshal.FreeHGlobal(authInfo);
605 }
606 }
607 }
608
609 private static SafeNativeHandle GetElevatedToken(SafeNativeHandle hToken)
610 {
611 TokenElevationType tet = TokenUtil.GetTokenElevationType(hToken);
612 // We already have the best token we can get, no linked token is really available.
613 if (tet != TokenElevationType.Limited)
614 return null;
615
616 SafeNativeHandle linkedToken = TokenUtil.GetTokenLinkedToken(hToken);
617 TokenStatistics tokenStats = TokenUtil.GetTokenStatistics(linkedToken);
618
619 // We can only use a token if it's a primary one (we had the SeTcbPrivilege set)
620 if (tokenStats.TokenType == TokenType.Primary)
621 return linkedToken;
622 else
623 return null;
624 }
625
626 private static NativeHelpers.ProcessChildProcessPolicyFlags GetProcessChildProcessPolicyFlags(SafeNativeHandle processHandle)
627 {
628 // Because this is only used to check the policy, we ignore any
629 // errors and pretend that the policy is None.
630 NativeHelpers.ProcessChildProcessPolicyFlags policy = NativeHelpers.ProcessChildProcessPolicyFlags.None;
631
632 if (_getProcessMitigationPolicySupported)
633 {
634 try
635 {
636 if (NativeMethods.GetProcessMitigationPolicy(
637 processHandle,
638 NativeMethods.ProcessChildProcessPolicy,
639 ref policy,
640 (IntPtr)4))
641 {
642 return policy;
643 }
644 }
645 catch (EntryPointNotFoundException)
646 {
647 // If the function is not available, we won't try to call it again
648 _getProcessMitigationPolicySupported = false;
649 }
650 }
651
652 return policy;
653 }
654
655 private static NativeHelpers.SECURITY_LOGON_TYPE GetTokenLogonType(SafeNativeHandle hToken)
656 {
657 TokenStatistics stats = TokenUtil.GetTokenStatistics(hToken);
658
659 SafeLsaMemoryBuffer sessionDataPtr;
660 UInt32 res = NativeMethods.LsaGetLogonSessionData(ref stats.AuthenticationId, out sessionDataPtr);
661 if (res != 0)
662 // Default to Network, if we weren't able to get the actual type treat it as an error and assume
663 // we don't want to run a process with the token
664 return NativeHelpers.SECURITY_LOGON_TYPE.Network;
665
666 using (sessionDataPtr)
667 {
668 NativeHelpers.SECURITY_LOGON_SESSION_DATA sessionData = (NativeHelpers.SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(
669 sessionDataPtr.DangerousGetHandle(), typeof(NativeHelpers.SECURITY_LOGON_SESSION_DATA));
670 return sessionData.LogonType;
671 }
672 }
673
674 private static void GrantAccessToWindowStationAndDesktop(IdentityReference account)
675 {
676 GrantAccess(account, NativeMethods.GetProcessWindowStation(), WINDOWS_STATION_ALL_ACCESS);
677 GrantAccess(account, NativeMethods.GetThreadDesktop(NativeMethods.GetCurrentThreadId()), DESKTOP_RIGHTS_ALL_ACCESS);
678 }
679
680 private static void GrantAccess(IdentityReference account, NoopSafeHandle handle, int accessMask)
681 {
682 GenericSecurity security = new GenericSecurity(false, ResourceType.WindowObject, handle, AccessControlSections.Access);
683 security.AddAccessRule(new GenericAccessRule(account, accessMask, AccessControlType.Allow));
684 security.Persist(handle, AccessControlSections.Access);
685 }
686
687 private class GenericSecurity : NativeObjectSecurity
688 {
689 public GenericSecurity(bool isContainer, ResourceType resType, SafeHandle objectHandle, AccessControlSections sectionsRequested)
690 : base(isContainer, resType, objectHandle, sectionsRequested) { }
691 public new void Persist(SafeHandle handle, AccessControlSections includeSections) { base.Persist(handle, includeSections); }
692 public new void AddAccessRule(AccessRule rule) { base.AddAccessRule(rule); }
693 public override Type AccessRightType { get { throw new NotImplementedException(); } }
694 public override AccessRule AccessRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited,
695 InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
696 { throw new NotImplementedException(); }
697 public override Type AccessRuleType { get { return typeof(AccessRule); } }
698 public override AuditRule AuditRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited,
699 InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
700 { throw new NotImplementedException(); }
701 public override Type AuditRuleType { get { return typeof(AuditRule); } }
702 }
703
704 private class GenericAccessRule : AccessRule
705 {
706 public GenericAccessRule(IdentityReference identity, int accessMask, AccessControlType type) :
707 base(identity, accessMask, false, InheritanceFlags.None, PropagationFlags.None, type)
708 { }
709 }
710 }
711 }