Debian Codegraph @

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

raw
1 using Microsoft.Win32.SafeHandles;
2 using System;
3 using System.Collections;
4 using System.Collections.Generic;
5 using System.Linq;
6 using System.Runtime.InteropServices;
7 using System.Security.Principal;
8 using System.Text;
9
10 namespace Ansible.Privilege
11 {
12 internal class NativeHelpers
13 {
14 [StructLayout(LayoutKind.Sequential)]
15 public struct LUID
16 {
17 public UInt32 LowPart;
18 public Int32 HighPart;
19 }
20
21 [StructLayout(LayoutKind.Sequential)]
22 public struct LUID_AND_ATTRIBUTES
23 {
24 public LUID Luid;
25 public PrivilegeAttributes Attributes;
26 }
27
28 [StructLayout(LayoutKind.Sequential)]
29 public struct TOKEN_PRIVILEGES
30 {
31 public UInt32 PrivilegeCount;
32 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
33 public LUID_AND_ATTRIBUTES[] Privileges;
34 }
35 }
36
37 internal class NativeMethods
38 {
39 [DllImport("advapi32.dll", SetLastError = true)]
40 public static extern bool AdjustTokenPrivileges(
41 SafeNativeHandle TokenHandle,
42 [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges,
43 SafeMemoryBuffer NewState,
44 UInt32 BufferLength,
45 SafeMemoryBuffer PreviousState,
46 out UInt32 ReturnLength);
47
48 [DllImport("kernel32.dll")]
49 public static extern bool CloseHandle(
50 IntPtr hObject);
51
52 [DllImport("kernel32")]
53 public static extern SafeWaitHandle GetCurrentProcess();
54
55 [DllImport("advapi32.dll", SetLastError = true)]
56 public static extern bool GetTokenInformation(
57 SafeNativeHandle TokenHandle,
58 UInt32 TokenInformationClass,
59 SafeMemoryBuffer TokenInformation,
60 UInt32 TokenInformationLength,
61 out UInt32 ReturnLength);
62
63 [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
64 public static extern bool LookupPrivilegeName(
65 string lpSystemName,
66 ref NativeHelpers.LUID lpLuid,
67 StringBuilder lpName,
68 ref UInt32 cchName);
69
70 [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
71 public static extern bool LookupPrivilegeValue(
72 string lpSystemName,
73 string lpName,
74 out NativeHelpers.LUID lpLuid);
75
76 [DllImport("advapi32.dll", SetLastError = true)]
77 public static extern bool OpenProcessToken(
78 SafeHandle ProcessHandle,
79 TokenAccessLevels DesiredAccess,
80 out SafeNativeHandle TokenHandle);
81 }
82
83 internal class SafeMemoryBuffer : SafeHandleZeroOrMinusOneIsInvalid
84 {
85 public SafeMemoryBuffer() : base(true) { }
86 public SafeMemoryBuffer(int cb) : base(true)
87 {
88 base.SetHandle(Marshal.AllocHGlobal(cb));
89 }
90 public SafeMemoryBuffer(IntPtr handle) : base(true)
91 {
92 base.SetHandle(handle);
93 }
94 protected override bool ReleaseHandle()
95 {
96 Marshal.FreeHGlobal(handle);
97 return true;
98 }
99 }
100
101 internal class SafeNativeHandle : SafeHandleZeroOrMinusOneIsInvalid
102 {
103 public SafeNativeHandle() : base(true) { }
104 public SafeNativeHandle(IntPtr handle) : base(true) { this.handle = handle; }
105
106 protected override bool ReleaseHandle()
107 {
108 return NativeMethods.CloseHandle(handle);
109 }
110 }
111
112 public class Win32Exception : System.ComponentModel.Win32Exception
113 {
114 private string _msg;
115 public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { }
116 public Win32Exception(int errorCode, string message) : base(errorCode)
117 {
118 _msg = String.Format("{0} ({1}, Win32ErrorCode {2})", message, base.Message, errorCode);
119 }
120 public override string Message { get { return _msg; } }
121 public static explicit operator Win32Exception(string message) { return new Win32Exception(message); }
122 }
123
124 [Flags]
125 public enum PrivilegeAttributes : uint
126 {
127 Disabled = 0x00000000,
128 EnabledByDefault = 0x00000001,
129 Enabled = 0x00000002,
130 Removed = 0x00000004,
131 UsedForAccess = 0x80000000,
132 }
133
134 public class PrivilegeEnabler : IDisposable
135 {
136 private SafeHandle process;
137 private Dictionary<string, bool?> previousState;
138
139 /// <summary>
140 /// Temporarily enables the privileges specified and reverts once the class is disposed.
141 /// </summary>
142 /// <param name="strict">Whether to fail if any privilege failed to be enabled, if false then this will continue silently</param>
143 /// <param name="privileges">A list of privileges to enable</param>
144 public PrivilegeEnabler(bool strict, params string[] privileges)
145 {
146 if (privileges.Length > 0)
147 {
148 process = PrivilegeUtil.GetCurrentProcess();
149 Dictionary<string, bool?> newState = new Dictionary<string, bool?>();
150 for (int i = 0; i < privileges.Length; i++)
151 newState.Add(privileges[i], true);
152 try
153 {
154 previousState = PrivilegeUtil.SetTokenPrivileges(process, newState, strict);
155 }
156 catch (Win32Exception e)
157 {
158 throw new Win32Exception(e.NativeErrorCode, String.Format("Failed to enable privilege(s) {0}", String.Join(", ", privileges)));
159 }
160 }
161 }
162
163 public void Dispose()
164 {
165 // disables any privileges that were enabled by this class
166 if (previousState != null)
167 PrivilegeUtil.SetTokenPrivileges(process, previousState);
168 GC.SuppressFinalize(this);
169 }
170 ~PrivilegeEnabler() { this.Dispose(); }
171 }
172
173 public class PrivilegeUtil
174 {
175 private static readonly UInt32 TOKEN_PRIVILEGES = 3;
176
177 /// <summary>
178 /// Checks if the specific privilege constant is a valid privilege name
179 /// </summary>
180 /// <param name="name">The privilege constant (Se*Privilege) is valid</param>
181 /// <returns>true if valid, else false</returns>
182 public static bool CheckPrivilegeName(string name)
183 {
184 NativeHelpers.LUID luid;
185 if (!NativeMethods.LookupPrivilegeValue(null, name, out luid))
186 {
187 int errCode = Marshal.GetLastWin32Error();
188 if (errCode != 1313) // ERROR_NO_SUCH_PRIVILEGE
189 throw new Win32Exception(errCode, String.Format("LookupPrivilegeValue({0}) failed", name));
190 return false;
191 }
192 else
193 {
194 return true;
195 }
196 }
197
198 /// <summary>
199 /// Disables the privilege specified
200 /// </summary>
201 /// <param name="token">The process token to that contains the privilege to disable</param>
202 /// <param name="privilege">The privilege constant to disable</param>
203 /// <returns>The previous state that can be passed to SetTokenPrivileges to revert the action</returns>
204 public static Dictionary<string, bool?> DisablePrivilege(SafeHandle token, string privilege)
205 {
206 return SetTokenPrivileges(token, new Dictionary<string, bool?>() { { privilege, false } });
207 }
208
209 /// <summary>
210 /// Disables all the privileges
211 /// </summary>
212 /// <param name="token">The process token to that contains the privilege to disable</param>
213 /// <returns>The previous state that can be passed to SetTokenPrivileges to revert the action</returns>
214 public static Dictionary<string, bool?> DisableAllPrivileges(SafeHandle token)
215 {
216 return AdjustTokenPrivileges(token, null, false);
217 }
218
219 /// <summary>
220 /// Enables the privilege specified
221 /// </summary>
222 /// <param name="token">The process token to that contains the privilege to enable</param>
223 /// <param name="privilege">The privilege constant to enable</param>
224 /// <returns>The previous state that can be passed to SetTokenPrivileges to revert the action</returns>
225 public static Dictionary<string, bool?> EnablePrivilege(SafeHandle token, string privilege)
226 {
227 return SetTokenPrivileges(token, new Dictionary<string, bool?>() { { privilege, true } });
228 }
229
230 /// <summary>
231 /// Gets the status of all the privileges on the token specified
232 /// </summary>
233 /// <param name="token">The process token to get the privilege status on</param>
234 /// <returns>Dictionary where the key is the privilege constant and the value is the PrivilegeAttributes flags</returns>
235 public static Dictionary<String, PrivilegeAttributes> GetAllPrivilegeInfo(SafeHandle token)
236 {
237 SafeNativeHandle hToken = null;
238 if (!NativeMethods.OpenProcessToken(token, TokenAccessLevels.Query, out hToken))
239 throw new Win32Exception("OpenProcessToken() failed");
240
241 using (hToken)
242 {
243 UInt32 tokenLength = 0;
244 NativeMethods.GetTokenInformation(hToken, TOKEN_PRIVILEGES, new SafeMemoryBuffer(0), 0, out tokenLength);
245
246 NativeHelpers.LUID_AND_ATTRIBUTES[] privileges;
247 using (SafeMemoryBuffer privilegesPtr = new SafeMemoryBuffer((int)tokenLength))
248 {
249 if (!NativeMethods.GetTokenInformation(hToken, TOKEN_PRIVILEGES, privilegesPtr, tokenLength, out tokenLength))
250 throw new Win32Exception("GetTokenInformation() for TOKEN_PRIVILEGES failed");
251
252 NativeHelpers.TOKEN_PRIVILEGES privilegeInfo = (NativeHelpers.TOKEN_PRIVILEGES)Marshal.PtrToStructure(
253 privilegesPtr.DangerousGetHandle(), typeof(NativeHelpers.TOKEN_PRIVILEGES));
254 privileges = new NativeHelpers.LUID_AND_ATTRIBUTES[privilegeInfo.PrivilegeCount];
255 PtrToStructureArray(privileges, IntPtr.Add(privilegesPtr.DangerousGetHandle(), Marshal.SizeOf(privilegeInfo.PrivilegeCount)));
256 }
257
258 return privileges.ToDictionary(p => GetPrivilegeName(p.Luid), p => p.Attributes);
259 }
260 }
261
262 /// <summary>
263 /// Get a handle to the current process for use with the methods above
264 /// </summary>
265 /// <returns>SafeWaitHandle handle of the current process token</returns>
266 public static SafeWaitHandle GetCurrentProcess()
267 {
268 return NativeMethods.GetCurrentProcess();
269 }
270
271 /// <summary>
272 /// Removes a privilege from the token. This operation is irreversible
273 /// </summary>
274 /// <param name="token">The process token to that contains the privilege to remove</param>
275 /// <param name="privilege">The privilege constant to remove</param>
276 public static void RemovePrivilege(SafeHandle token, string privilege)
277 {
278 SetTokenPrivileges(token, new Dictionary<string, bool?>() { { privilege, null } });
279 }
280
281 /// <summary>
282 /// Do a bulk set of multiple privileges
283 /// </summary>
284 /// <param name="token">The process token to use when setting the privilege state</param>
285 /// <param name="state">A dictionary that contains the privileges to set, the key is the constant name and the value can be;
286 /// true - enable the privilege
287 /// false - disable the privilege
288 /// null - remove the privilege (this cannot be reversed)
289 /// </param>
290 /// <param name="strict">When true, will fail if one privilege failed to be set, otherwise it will silently continue</param>
291 /// <returns>The previous state that can be passed to SetTokenPrivileges to revert the action</returns>
292 public static Dictionary<string, bool?> SetTokenPrivileges(SafeHandle token, IDictionary state, bool strict = true)
293 {
294 NativeHelpers.LUID_AND_ATTRIBUTES[] privilegeAttr = new NativeHelpers.LUID_AND_ATTRIBUTES[state.Count];
295 int i = 0;
296
297 foreach (DictionaryEntry entry in state)
298 {
299 string key = (string)entry.Key;
300 NativeHelpers.LUID luid;
301 if (!NativeMethods.LookupPrivilegeValue(null, key, out luid))
302 throw new Win32Exception(String.Format("LookupPrivilegeValue({0}) failed", key));
303
304 PrivilegeAttributes attributes;
305 switch ((bool?)entry.Value)
306 {
307 case true:
308 attributes = PrivilegeAttributes.Enabled;
309 break;
310 case false:
311 attributes = PrivilegeAttributes.Disabled;
312 break;
313 default:
314 attributes = PrivilegeAttributes.Removed;
315 break;
316 }
317
318 privilegeAttr[i].Luid = luid;
319 privilegeAttr[i].Attributes = attributes;
320 i++;
321 }
322
323 return AdjustTokenPrivileges(token, privilegeAttr, strict);
324 }
325
326 private static Dictionary<string, bool?> AdjustTokenPrivileges(SafeHandle token, NativeHelpers.LUID_AND_ATTRIBUTES[] newState, bool strict)
327 {
328 bool disableAllPrivileges;
329 SafeMemoryBuffer newStatePtr;
330 NativeHelpers.LUID_AND_ATTRIBUTES[] oldStatePrivileges;
331 UInt32 returnLength;
332
333 if (newState == null)
334 {
335 disableAllPrivileges = true;
336 newStatePtr = new SafeMemoryBuffer(0);
337 }
338 else
339 {
340 disableAllPrivileges = false;
341
342 // Need to manually marshal the bytes requires for newState as the constant size
343 // of LUID_AND_ATTRIBUTES is set to 1 and can't be overridden at runtime, TOKEN_PRIVILEGES
344 // always contains at least 1 entry so we need to calculate the extra size if there are
345 // more than 1 LUID_AND_ATTRIBUTES entry
346 int tokenPrivilegesSize = Marshal.SizeOf(typeof(NativeHelpers.TOKEN_PRIVILEGES));
347 int luidAttrSize = 0;
348 if (newState.Length > 1)
349 luidAttrSize = Marshal.SizeOf(typeof(NativeHelpers.LUID_AND_ATTRIBUTES)) * (newState.Length - 1);
350 int totalSize = tokenPrivilegesSize + luidAttrSize;
351 byte[] newStateBytes = new byte[totalSize];
352
353 // get the first entry that includes the struct details
354 NativeHelpers.TOKEN_PRIVILEGES tokenPrivileges = new NativeHelpers.TOKEN_PRIVILEGES()
355 {
356 PrivilegeCount = (UInt32)newState.Length,
357 Privileges = new NativeHelpers.LUID_AND_ATTRIBUTES[1],
358 };
359 if (newState.Length > 0)
360 tokenPrivileges.Privileges[0] = newState[0];
361 int offset = StructureToBytes(tokenPrivileges, newStateBytes, 0);
362
363 // copy the remaining LUID_AND_ATTRIBUTES (if any)
364 for (int i = 1; i < newState.Length; i++)
365 offset += StructureToBytes(newState[i], newStateBytes, offset);
366
367 // finally create the pointer to the byte array we just created
368 newStatePtr = new SafeMemoryBuffer(newStateBytes.Length);
369 Marshal.Copy(newStateBytes, 0, newStatePtr.DangerousGetHandle(), newStateBytes.Length);
370 }
371
372 using (newStatePtr)
373 {
374 SafeNativeHandle hToken;
375 if (!NativeMethods.OpenProcessToken(token, TokenAccessLevels.Query | TokenAccessLevels.AdjustPrivileges, out hToken))
376 throw new Win32Exception("OpenProcessToken() failed with Query and AdjustPrivileges");
377
378 using (hToken)
379 {
380 if (!NativeMethods.AdjustTokenPrivileges(hToken, disableAllPrivileges, newStatePtr, 0, new SafeMemoryBuffer(0), out returnLength))
381 {
382 int errCode = Marshal.GetLastWin32Error();
383 if (errCode != 122) // ERROR_INSUFFICIENT_BUFFER
384 throw new Win32Exception(errCode, "AdjustTokenPrivileges() failed to get old state size");
385 }
386
387 using (SafeMemoryBuffer oldStatePtr = new SafeMemoryBuffer((int)returnLength))
388 {
389 bool res = NativeMethods.AdjustTokenPrivileges(hToken, disableAllPrivileges, newStatePtr, returnLength, oldStatePtr, out returnLength);
390 int errCode = Marshal.GetLastWin32Error();
391
392 // even when res == true, ERROR_NOT_ALL_ASSIGNED may be set as the last error code
393 // fail if we are running with strict, otherwise ignore those privileges
394 if (!res || ((strict && errCode != 0) || (!strict && !(errCode == 0 || errCode == 0x00000514))))
395 throw new Win32Exception(errCode, "AdjustTokenPrivileges() failed");
396
397 // Marshal the oldStatePtr to the struct
398 NativeHelpers.TOKEN_PRIVILEGES oldState = (NativeHelpers.TOKEN_PRIVILEGES)Marshal.PtrToStructure(
399 oldStatePtr.DangerousGetHandle(), typeof(NativeHelpers.TOKEN_PRIVILEGES));
400 oldStatePrivileges = new NativeHelpers.LUID_AND_ATTRIBUTES[oldState.PrivilegeCount];
401 PtrToStructureArray(oldStatePrivileges, IntPtr.Add(oldStatePtr.DangerousGetHandle(), Marshal.SizeOf(oldState.PrivilegeCount)));
402 }
403 }
404 }
405
406 return oldStatePrivileges.ToDictionary(p => GetPrivilegeName(p.Luid), p => (bool?)p.Attributes.HasFlag(PrivilegeAttributes.Enabled));
407 }
408
409 private static string GetPrivilegeName(NativeHelpers.LUID luid)
410 {
411 UInt32 nameLen = 0;
412 NativeMethods.LookupPrivilegeName(null, ref luid, null, ref nameLen);
413
414 StringBuilder name = new StringBuilder((int)(nameLen + 1));
415 if (!NativeMethods.LookupPrivilegeName(null, ref luid, name, ref nameLen))
416 throw new Win32Exception("LookupPrivilegeName() failed");
417
418 return name.ToString();
419 }
420
421 private static void PtrToStructureArray<T>(T[] array, IntPtr ptr)
422 {
423 IntPtr ptrOffset = ptr;
424 for (int i = 0; i < array.Length; i++, ptrOffset = IntPtr.Add(ptrOffset, Marshal.SizeOf(typeof(T))))
425 array[i] = (T)Marshal.PtrToStructure(ptrOffset, typeof(T));
426 }
427
428 private static int StructureToBytes<T>(T structure, byte[] array, int offset)
429 {
430 int size = Marshal.SizeOf(structure);
431 using (SafeMemoryBuffer structPtr = new SafeMemoryBuffer(size))
432 {
433 Marshal.StructureToPtr(structure, structPtr.DangerousGetHandle(), false);
434 Marshal.Copy(structPtr.DangerousGetHandle(), array, offset, size);
435 }
436
437 return size;
438 }
439 }
440 }
441