1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 
5 //
6 // This file defines many COM dual interfaces which are legacy and,
7 // cannot be changed.  Tolerate possible obsoletion.
8 //
9 #pragma warning disable CS0618 // Type or member is obsolete
10 
11 namespace System.DirectoryServices.AccountManagement
12 {
13     using System.Runtime.InteropServices;
14     using System;
15     using System.Security;
16     using System.Security.Permissions;
17     using System.Text;
18 
19     internal class Constants
20     {
Constants()21         private Constants() { }
22         internal static Byte[] GUID_USERS_CONTAINER_BYTE = new Byte[] { 0xa9, 0xd1, 0xca, 0x15, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };
23         internal static Byte[] GUID_COMPUTRS_CONTAINER_BYTE = new Byte[] { 0xaa, 0x31, 0x28, 0x25, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };
24         internal static Byte[] GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE = new Byte[] { 0x22, 0xb7, 0x0c, 0x67, 0xd5, 0x6e, 0x4e, 0xfb, 0x91, 0xe9, 0x30, 0x0f, 0xca, 0x3d, 0xc1, 0xaa };
25     }
26 
27     internal class SafeNativeMethods
28     {
29         // To stop the compiler from autogenerating a constructor for this class
SafeNativeMethods()30         private SafeNativeMethods() { }
31 
32         [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThreadId", CharSet = CharSet.Unicode)]
GetCurrentThreadId()33         static extern public int GetCurrentThreadId();
34 
35         [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaNtStatusToWinError", CharSet = CharSet.Unicode)]
LsaNtStatusToWinError(int ntStatus)36         static extern public int LsaNtStatusToWinError(int ntStatus);
37     }
38 
39     internal class UnsafeNativeMethods
40     {
41         // To stop the compiler from autogenerating a constructor for this class
UnsafeNativeMethods()42         private UnsafeNativeMethods() { }
43 
44         [DllImport(ExternDll.Activeds, ExactSpelling = true, EntryPoint = "ADsOpenObject", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
IntADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject)45         private static extern int IntADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject)46         public static int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject)
47         {
48             try
49             {
50                 return IntADsOpenObject(path, userName, password, flags, ref iid, out ppObject);
51             }
52             catch (EntryPointNotFoundException)
53             {
54                 throw new InvalidOperationException(SR.AdsiNotInstalled);
55             }
56         }
57 
58         //
59         // ADSI Interopt
60         //
61 
62         internal enum ADS_PASSWORD_ENCODING_ENUM
63         {
64             ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0,
65             ADS_PASSWORD_ENCODE_CLEAR = 1
66         }
67 
68         internal enum ADS_OPTION_ENUM
69         {
70             ADS_OPTION_SERVERNAME = 0,
71             ADS_OPTION_REFERRALS = 1,
72             ADS_OPTION_PAGE_SIZE = 2,
73             ADS_OPTION_SECURITY_MASK = 3,
74             ADS_OPTION_MUTUAL_AUTH_STATUS = 4,
75             ADS_OPTION_QUOTA = 5,
76             ADS_OPTION_PASSWORD_PORTNUMBER = 6,
77             ADS_OPTION_PASSWORD_METHOD = 7,
78             ADS_OPTION_ACCUMULATIVE_MODIFICATION = 8,
79             ADS_OPTION_SKIP_SID_LOOKUP = 9
80         }
81 
82         [ComImport, Guid("7E99C0A2-F935-11D2-BA96-00C04FB6D0D1"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
83         public interface IADsDNWithBinary
84         {
85             object BinaryValue { get; set; }
86             string DNString { get; set; }
87         }
88 
89         [ComImport, Guid("9068270b-0939-11D1-8be1-00c04fd8d503"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
90         public interface IADsLargeInteger
91         {
92             int HighPart { get; set; }
93             int LowPart { get; set; }
94         }
95 
96         [ComImport, Guid("927971f5-0939-11d1-8be1-00c04fd8d503")]
97         public class ADsLargeInteger
98         {
99         }
100 
101         [ComImport, Guid("46f14fda-232b-11d1-a808-00c04fd8d5a8"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
102         public interface IAdsObjectOptions
103         {
104             [return: MarshalAs(UnmanagedType.Struct)]
GetOption( [In] int option)105             Object GetOption(
106                 [In]
107                 int option);
108 
PutOption( [In] int option, [In, MarshalAs(UnmanagedType.Struct)] Object vProp)109             void PutOption(
110                 [In]
111                 int option,
112                 [In, MarshalAs(UnmanagedType.Struct)]
113                 Object vProp);
114         }
115 
116         [ComImport, Guid("FD8256D0-FD15-11CE-ABC4-02608C9E7553"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
117         public interface IADs
118         {
119             string Name
120             {
121                 [return: MarshalAs(UnmanagedType.BStr)]
122                 get;
123             }
124 
125             string Class
126             {
127                 [return: MarshalAs(UnmanagedType.BStr)]
128                 get;
129             }
130 
131             string GUID
132             {
133                 [return: MarshalAs(UnmanagedType.BStr)]
134                 get;
135             }
136 
137             string ADsPath
138             {
139                 [return: MarshalAs(UnmanagedType.BStr)]
140                 get;
141             }
142 
143             string Parent
144             {
145                 [return: MarshalAs(UnmanagedType.BStr)]
146                 get;
147             }
148 
149             string Schema
150             {
151                 [return: MarshalAs(UnmanagedType.BStr)]
152                 get;
153             }
154 
GetInfo()155             void GetInfo();
156 
SetInfo()157             void SetInfo();
158 
159             [return: MarshalAs(UnmanagedType.Struct)]
Get( [In, MarshalAs(UnmanagedType.BStr)] string bstrName)160             Object Get(
161                 [In, MarshalAs(UnmanagedType.BStr)]
162                 string bstrName);
163 
Put( [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In, MarshalAs(UnmanagedType.Struct)] Object vProp)164             void Put(
165                 [In, MarshalAs(UnmanagedType.BStr)]
166                 string bstrName,
167                 [In, MarshalAs(UnmanagedType.Struct)]
168                 Object vProp);
169 
170             [return: MarshalAs(UnmanagedType.Struct)]
GetEx( [In, MarshalAs(UnmanagedType.BStr)] String bstrName)171             Object GetEx(
172                 [In, MarshalAs(UnmanagedType.BStr)]
173                 String bstrName);
174 
PutEx( [In, MarshalAs(UnmanagedType.U4)] int lnControlCode, [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In, MarshalAs(UnmanagedType.Struct)] Object vProp)175             void PutEx(
176                 [In, MarshalAs(UnmanagedType.U4)]
177                 int lnControlCode,
178                 [In, MarshalAs(UnmanagedType.BStr)]
179                 string bstrName,
180                 [In, MarshalAs(UnmanagedType.Struct)]
181                 Object vProp);
182 
GetInfoEx( [In, MarshalAs(UnmanagedType.Struct)] Object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved)183             void GetInfoEx(
184                 [In, MarshalAs(UnmanagedType.Struct)]
185                 Object vProperties,
186                 [In, MarshalAs(UnmanagedType.U4)]
187                 int lnReserved);
188         }
189 
190         [ComImport, Guid("27636b00-410f-11cf-b1ff-02608c9e7553"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
191         public interface IADsGroup
192         {
193             string Name
194             {
195                 [return: MarshalAs(UnmanagedType.BStr)]
196                 get;
197             }
198 
199             string Class
200             {
201                 [return: MarshalAs(UnmanagedType.BStr)]
202                 get;
203             }
204 
205             string GUID
206             {
207                 [return: MarshalAs(UnmanagedType.BStr)]
208                 get;
209             }
210 
211             string ADsPath
212             {
213                 [return: MarshalAs(UnmanagedType.BStr)]
214                 get;
215             }
216 
217             string Parent
218             {
219                 [return: MarshalAs(UnmanagedType.BStr)]
220                 get;
221             }
222 
223             string Schema
224             {
225                 [return: MarshalAs(UnmanagedType.BStr)]
226                 get;
227             }
228 
GetInfo()229             void GetInfo();
230 
SetInfo()231             void SetInfo();
232 
233             [return: MarshalAs(UnmanagedType.Struct)]
Get( [In, MarshalAs(UnmanagedType.BStr)] string bstrName)234             Object Get(
235                 [In, MarshalAs(UnmanagedType.BStr)]
236                 string bstrName);
237 
Put( [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In, MarshalAs(UnmanagedType.Struct)] Object vProp)238             void Put(
239                 [In, MarshalAs(UnmanagedType.BStr)]
240                 string bstrName,
241                 [In, MarshalAs(UnmanagedType.Struct)]
242                 Object vProp);
243 
244             [return: MarshalAs(UnmanagedType.Struct)]
GetEx( [In, MarshalAs(UnmanagedType.BStr)] String bstrName)245             Object GetEx(
246                 [In, MarshalAs(UnmanagedType.BStr)]
247                 String bstrName);
248 
PutEx( [In, MarshalAs(UnmanagedType.U4)] int lnControlCode, [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In, MarshalAs(UnmanagedType.Struct)] Object vProp)249             void PutEx(
250                 [In, MarshalAs(UnmanagedType.U4)]
251                 int lnControlCode,
252                 [In, MarshalAs(UnmanagedType.BStr)]
253                 string bstrName,
254                 [In, MarshalAs(UnmanagedType.Struct)]
255                 Object vProp);
256 
GetInfoEx( [In, MarshalAs(UnmanagedType.Struct)] Object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved)257             void GetInfoEx(
258                 [In, MarshalAs(UnmanagedType.Struct)]
259                 Object vProperties,
260                 [In, MarshalAs(UnmanagedType.U4)]
261                 int lnReserved);
262 
263             string Description
264             {
265                 [return: MarshalAs(UnmanagedType.BStr)]
266                 get;
267                 [param: MarshalAs(UnmanagedType.BStr)]
268                 set;
269             }
270 
Members()271             IADsMembers Members();
272 
IsMember([In, MarshalAs(UnmanagedType.BStr)] string bstrMember)273             bool IsMember([In, MarshalAs(UnmanagedType.BStr)] string bstrMember);
274 
Add([In, MarshalAs(UnmanagedType.BStr)] string bstrNewItem)275             void Add([In, MarshalAs(UnmanagedType.BStr)] string bstrNewItem);
276 
Remove([In, MarshalAs(UnmanagedType.BStr)] string bstrItemToBeRemoved)277             void Remove([In, MarshalAs(UnmanagedType.BStr)] string bstrItemToBeRemoved);
278         }
279 
280         [ComImport, Guid("451a0030-72ec-11cf-b03b-00aa006e0975"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
281         public interface IADsMembers
282         {
283             int Count
284             {
285                 [return: MarshalAs(UnmanagedType.U4)]
286                 get;
287             }
288 
289             object _NewEnum
290             {
291                 [return: MarshalAs(UnmanagedType.Interface)]
292                 get;
293             }
294 
295             object Filter
296             {
297                 [return: MarshalAs(UnmanagedType.Struct)]
298                 get;
299                 [param: MarshalAs(UnmanagedType.Struct)]
300                 set;
301             }
302         }
303 
304         [ComImport, Guid("080d0d78-f421-11d0-a36e-00c04fb950dc")]
305         public class Pathname
306         {
307         }
308 
309         [ComImport, Guid("d592aed4-f420-11d0-a36e-00c04fb950dc"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
310         public interface IADsPathname
311         {
Set( [In, MarshalAs(UnmanagedType.BStr)] string bstrADsPath, [In, MarshalAs(UnmanagedType.U4)] int lnSetType )312             void Set(
313                 [In, MarshalAs(UnmanagedType.BStr)] string bstrADsPath,
314                 [In, MarshalAs(UnmanagedType.U4)]  int lnSetType
315                 );
316 
SetDisplayType( [In, MarshalAs(UnmanagedType.U4)] int lnDisplayType )317             void SetDisplayType(
318                 [In, MarshalAs(UnmanagedType.U4)] int lnDisplayType
319                 );
320 
321             [return: MarshalAs(UnmanagedType.BStr)]
Retrieve( [In, MarshalAs(UnmanagedType.U4)] int lnFormatType )322             string Retrieve(
323                 [In, MarshalAs(UnmanagedType.U4)] int lnFormatType
324                 );
325 
326             [return: MarshalAs(UnmanagedType.U4)]
GetNumElements()327             int GetNumElements();
328 
329             [return: MarshalAs(UnmanagedType.BStr)]
330             string
GetElement( [In, MarshalAs(UnmanagedType.U4)] int lnElementIndex )331             GetElement(
332                 [In, MarshalAs(UnmanagedType.U4)]  int lnElementIndex
333                 );
334 
AddLeafElement( [In, MarshalAs(UnmanagedType.BStr)] string bstrLeafElement )335             void AddLeafElement(
336                 [In, MarshalAs(UnmanagedType.BStr)] string bstrLeafElement
337                 );
338 
RemoveLeafElement()339             void RemoveLeafElement();
340 
341             [return: MarshalAs(UnmanagedType.Struct)]
CopyPath()342             Object CopyPath();
343 
344             [return: MarshalAs(UnmanagedType.BStr)]
GetEscapedElement( [In, MarshalAs(UnmanagedType.U4)] int lnReserved, [In, MarshalAs(UnmanagedType.BStr)] string bstrInStr )345             string GetEscapedElement(
346                 [In, MarshalAs(UnmanagedType.U4)] int lnReserved,
347                 [In, MarshalAs(UnmanagedType.BStr)] string bstrInStr
348                 );
349 
350             int EscapedMode
351             {
352                 [return: MarshalAs(UnmanagedType.U4)]
353                 get;
354                 [param: MarshalAs(UnmanagedType.U4)]
355                 set;
356             }
357         }
358 
359         //
360         // DSInteropt
361         //
362 
363         /*
364         typedef enum
365         {
366           DsRole_RoleStandaloneWorkstation,
367           DsRole_RoleMemberWorkstation,
368           DsRole_RoleStandaloneServer,
369           DsRole_RoleMemberServer,
370           DsRole_RoleBackupDomainController,
371           DsRole_RolePrimaryDomainController,
372           DsRole_WorkstationWithSharedAccountDomain,
373           DsRole_ServerWithSharedAccountDomain,
374           DsRole_MemberWorkstationWithSharedAccountDomain,
375           DsRole_MemberServerWithSharedAccountDomain
376         }DSROLE_MACHINE_ROLE;
377         */
378 
379         public enum DSROLE_MACHINE_ROLE
380         {
381             DsRole_RoleStandaloneWorkstation,
382             DsRole_RoleMemberWorkstation,
383             DsRole_RoleStandaloneServer,
384             DsRole_RoleMemberServer,
385             DsRole_RoleBackupDomainController,
386             DsRole_RolePrimaryDomainController,
387             DsRole_WorkstationWithSharedAccountDomain,
388             DsRole_ServerWithSharedAccountDomain,
389             DsRole_MemberWorkstationWithSharedAccountDomain,
390             DsRole_MemberServerWithSharedAccountDomain
391         }
392 
393         /*
394         typedef enum
395         {
396           DsRolePrimaryDomainInfoBasic,
397           DsRoleUpgradeStatus,
398           DsRoleOperationState,
399           DsRolePrimaryDomainInfoBasicEx
400         }DSROLE_PRIMARY_DOMAIN_INFO_LEVEL;
401         */
402 
403         public enum DSROLE_PRIMARY_DOMAIN_INFO_LEVEL
404         {
405             DsRolePrimaryDomainInfoBasic = 1,
406             DsRoleUpgradeStatus = 2,
407             DsRoleOperationState = 3,
408             DsRolePrimaryDomainInfoBasicEx = 4
409         }
410 
411         /*
412          typedef struct _DSROLE_PRIMARY_DOMAIN_INFO_BASIC {
413          DSROLE_MACHINE_ROLE MachineRole;
414          ULONG Flags;
415          LPWSTR DomainNameFlat;
416          LPWSTR DomainNameDns;
417          LPWSTR DomainForestName;
418          GUID DomainGuid;
419          } DSROLE_PRIMARY_DOMAIN_INFO_BASIC,  *PDSROLE_PRIMARY_DOMAIN_INFO_BASIC;
420          */
421 
422         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
423         public sealed class DSROLE_PRIMARY_DOMAIN_INFO_BASIC
424         {
425             public DSROLE_MACHINE_ROLE MachineRole;
426             public uint Flags;
427             [MarshalAs(UnmanagedType.LPWStr)]
428             public string DomainNameFlat;
429             [MarshalAs(UnmanagedType.LPWStr)]
430             public string DomainNameDns;
431             [MarshalAs(UnmanagedType.LPWStr)]
432             public string DomainForestName;
433             public Guid DomainGuid = new Guid();
434         }
435 
436         /*
437         DWORD DsRoleGetPrimaryDomainInformation(
438           LPCWSTR lpServer,
439           DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
440           PBYTE* Buffer
441         ); */
442 
443         [DllImport("dsrole.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)]
DsRoleGetPrimaryDomainInformation( [MarshalAs(UnmanagedType.LPTStr)] string lpServer, [In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel, out IntPtr Buffer)444         public static extern int DsRoleGetPrimaryDomainInformation(
445             [MarshalAs(UnmanagedType.LPTStr)] string lpServer,
446             [In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
447             out IntPtr Buffer);
448 
449         /*typedef struct _DOMAIN_CONTROLLER_INFO {
450             LPTSTR DomainControllerName;
451             LPTSTR DomainControllerAddress;
452             ULONG DomainControllerAddressType;
453             GUID DomainGuid;
454             LPTSTR DomainName;
455             LPTSTR DnsForestName;
456             ULONG Flags;
457             LPTSTR DcSiteName;
458             LPTSTR ClientSiteName;
459         } DOMAIN_CONTROLLER_INFO, *PDOMAIN_CONTROLLER_INFO; */
460         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
461         public sealed class DomainControllerInfo
462         {
463             public string DomainControllerName = null;
464             public string DomainControllerAddress = null;
465             public int DomainControllerAddressType = 0;
466             public Guid DomainGuid = new Guid();
467             public string DomainName = null;
468             public string DnsForestName = null;
469             public int Flags = 0;
470             public string DcSiteName = null;
471             public string ClientSiteName = null;
472         }
473 
474         /*
475         void DsRoleFreeMemory(
476           PVOID Buffer
477         );
478         */
479         [DllImport("dsrole.dll")]
DsRoleFreeMemory( [In] IntPtr buffer)480         public static extern int DsRoleFreeMemory(
481             [In] IntPtr buffer);
482 
483         /*DWORD DsGetDcName(
484             LPCTSTR ComputerName,
485             LPCTSTR DomainName,
486             GUID* DomainGuid,
487             LPCTSTR SiteName,
488             ULONG Flags,
489             PDOMAIN_CONTROLLER_INFO* DomainControllerInfo
490         );*/
491         [DllImport("logoncli.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)]
DsGetDcName( [In] string computerName, [In] string domainName, [In] IntPtr domainGuid, [In] string siteName, [In] int flags, [Out] out IntPtr domainControllerInfo)492         public static extern int DsGetDcName(
493             [In] string computerName,
494             [In] string domainName,
495             [In] IntPtr domainGuid,
496             [In] string siteName,
497             [In] int flags,
498             [Out] out IntPtr domainControllerInfo);
499 
500         /* typedef struct _WKSTA_INFO_100 {
501                 DWORD wki100_platform_id;
502                 LMSTR wki100_computername;
503                 LMSTR wki100_langroup;
504                 DWORD wki100_ver_major;
505                 DWORD wki100_ver_minor;
506         } WKSTA_INFO_100, *PWKSTA_INFO_100; */
507         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
508         public sealed class WKSTA_INFO_100
509         {
510             public int wki100_platform_id = 0;
511             public string wki100_computername = null;
512             public string wki100_langroup = null;
513             public int wki100_ver_major = 0;
514             public int wki100_ver_minor = 0;
515         };
516 
517         [DllImport("wkscli.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "NetWkstaGetInfo", CharSet = CharSet.Unicode)]
NetWkstaGetInfo(string server, int level, ref IntPtr buffer)518         public static extern int NetWkstaGetInfo(string server, int level, ref IntPtr buffer);
519 
520         [DllImport("netutils.dll")]
NetApiBufferFree( [In] IntPtr buffer)521         public static extern int NetApiBufferFree(
522             [In] IntPtr buffer);
523 
524         //
525         // SID
526         //
527 
528         [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertSidToStringSidW", CharSet = CharSet.Unicode)]
ConvertSidToStringSid(IntPtr sid, ref string stringSid)529         public static extern bool ConvertSidToStringSid(IntPtr sid, ref string stringSid);
530 
531         [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertStringSidToSidW", CharSet = CharSet.Unicode)]
ConvertStringSidToSid(string stringSid, ref IntPtr sid)532         public static extern bool ConvertStringSidToSid(string stringSid, ref IntPtr sid);
533 
534         [DllImport("advapi32.dll")]
GetLengthSid(IntPtr sid)535         public static extern int GetLengthSid(IntPtr sid);
536 
537         [DllImport("advapi32.dll", SetLastError = true)]
IsValidSid(IntPtr sid)538         public static extern bool IsValidSid(IntPtr sid);
539 
540         [DllImport("advapi32.dll")]
GetSidIdentifierAuthority(IntPtr sid)541         public static extern IntPtr GetSidIdentifierAuthority(IntPtr sid);
542 
543         [DllImport("advapi32.dll")]
GetSidSubAuthority(IntPtr sid, int index)544         public static extern IntPtr GetSidSubAuthority(IntPtr sid, int index);
545 
546         [DllImport("advapi32.dll")]
GetSidSubAuthorityCount(IntPtr sid)547         public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid);
548 
549         [DllImport("advapi32.dll")]
EqualDomainSid(IntPtr pSid1, IntPtr pSid2, ref bool equal)550         public static extern bool EqualDomainSid(IntPtr pSid1, IntPtr pSid2, ref bool equal);
551 
552         [DllImport("advapi32.dll", SetLastError = true)]
CopySid(int destinationLength, IntPtr pSidDestination, IntPtr pSidSource)553         public static extern bool CopySid(int destinationLength, IntPtr pSidDestination, IntPtr pSidSource);
554 
555         [DllImport("kernel32.dll")]
LocalFree(IntPtr ptr)556         public static extern IntPtr LocalFree(IntPtr ptr);
557 
558         [DllImport("Credui.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "CredUIParseUserNameW", CharSet = CharSet.Unicode)]
CredUIParseUserName( string pszUserName, StringBuilder pszUser, System.UInt32 ulUserMaxChars, StringBuilder pszDomain, System.UInt32 ulDomainMaxChars )559         public static extern int CredUIParseUserName(
560                                                                                         string pszUserName,
561                                                                                         StringBuilder pszUser,
562                                                                                         System.UInt32 ulUserMaxChars,
563                                                                                         StringBuilder pszDomain,
564                                                                                         System.UInt32 ulDomainMaxChars
565                                                                                         );
566 
567         // These contants were taken from the wincred.h file
568         public const int CRED_MAX_USERNAME_LENGTH = 514;
569         public const int CRED_MAX_DOMAIN_TARGET_LENGTH = 338;
570 
571         /*
572         BOOL LookupAccountSid(
573           LPCTSTR lpSystemName,
574           PSID lpSid,
575           LPTSTR lpName,
576           LPDWORD cchName,
577           LPTSTR lpReferencedDomainName,
578           LPDWORD cchReferencedDomainName,
579           PSID_NAME_USE peUse
580         );
581 
582         */
583 
584         [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "LookupAccountSidW", CharSet = CharSet.Unicode)]
LookupAccountSid( string computerName, IntPtr sid, StringBuilder name, ref int nameLength, StringBuilder domainName, ref int domainNameLength, ref int usage)585         public static extern bool LookupAccountSid(
586                                         string computerName,
587                                         IntPtr sid,
588                                         StringBuilder name,
589                                         ref int nameLength,
590                                         StringBuilder domainName,
591                                         ref int domainNameLength,
592                                         ref int usage);
593 
594         //
595         // AuthZ functions
596         //
597 
598         internal sealed class AUTHZ_RM_FLAG
599         {
AUTHZ_RM_FLAG()600             private AUTHZ_RM_FLAG() { }
601             public static int AUTHZ_RM_FLAG_NO_AUDIT = 0x1;
602             public static int AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION = 0x2;
603             public static int AUTHZ_VALID_RM_INIT_FLAGS = (AUTHZ_RM_FLAG_NO_AUDIT | AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION);
604         }
605 
606         [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeResourceManager", CharSet = CharSet.Unicode)]
AuthzInitializeResourceManager( int flags, IntPtr pfnAccessCheck, IntPtr pfnComputeDynamicGroups, IntPtr pfnFreeDynamicGroups, string name, out IntPtr rm )607         static extern public bool AuthzInitializeResourceManager(
608                                         int flags,
609                                         IntPtr pfnAccessCheck,
610                                         IntPtr pfnComputeDynamicGroups,
611                                         IntPtr pfnFreeDynamicGroups,
612                                         string name,
613                                         out IntPtr rm
614                                         );
615 
616         /*
617         BOOL WINAPI AuthzInitializeContextFromSid(
618             DWORD Flags,
619             PSID UserSid,
620             AUTHZ_RESOURCE_MANAGER_HANDLE AuthzResourceManager,
621             PLARGE_INTEGER pExpirationTime,
622             LUID Identifier,
623             PVOID DynamicGroupArgs,
624             PAUTHZ_CLIENT_CONTEXT_HANDLE pAuthzClientContext
625         );
626         */
627         [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeContextFromSid", CharSet = CharSet.Unicode)]
AuthzInitializeContextFromSid( int Flags, IntPtr UserSid, IntPtr AuthzResourceManager, IntPtr pExpirationTime, LUID Identitifier, IntPtr DynamicGroupArgs, out IntPtr pAuthzClientContext )628         static extern public bool AuthzInitializeContextFromSid(
629                                         int Flags,
630                                         IntPtr UserSid,
631                                         IntPtr AuthzResourceManager,
632                                         IntPtr pExpirationTime,
633                                         LUID Identitifier,
634                                         IntPtr DynamicGroupArgs,
635                                         out IntPtr pAuthzClientContext
636                                         );
637 
638         /*
639                 [DllImport("authz.dll", SetLastError=true, CallingConvention=CallingConvention.StdCall, EntryPoint="AuthzInitializeContextFromToken", CharSet=CharSet.Unicode)]
640                 static extern public bool AuthzInitializeContextFromToken(
641                                                 int Flags,
642                                                 IntPtr TokenHandle,
643                                                 IntPtr AuthzResourceManager,
644                                                 IntPtr pExpirationTime,
645                                                 LUID Identitifier,
646                                                 IntPtr DynamicGroupArgs,
647                                                 out IntPtr pAuthzClientContext
648                                                 );
649         */
650         [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzGetInformationFromContext", CharSet = CharSet.Unicode)]
AuthzGetInformationFromContext( IntPtr hAuthzClientContext, int InfoClass, int BufferSize, out int pSizeRequired, IntPtr Buffer )651         static extern public bool AuthzGetInformationFromContext(
652                                         IntPtr hAuthzClientContext,
653                                         int InfoClass,
654                                         int BufferSize,
655                                         out int pSizeRequired,
656                                         IntPtr Buffer
657                                         );
658 
659         [DllImport("authz.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeContext", CharSet = CharSet.Unicode)]
AuthzFreeContext( IntPtr AuthzClientContext )660         static extern public bool AuthzFreeContext(
661                                         IntPtr AuthzClientContext
662                                         );
663 
664         [DllImport("authz.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeResourceManager", CharSet = CharSet.Unicode)]
AuthzFreeResourceManager( IntPtr rm )665         static extern public bool AuthzFreeResourceManager(
666                                         IntPtr rm
667                                         );
668 
669         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
670         public struct LUID
671         {
672             public int low;
673             public int high;
674         }
675 
676         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
677         public sealed class TOKEN_GROUPS
678         {
679             public int groupCount = 0;
680             public IntPtr groups = IntPtr.Zero;
681         }
682 
683         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
684         public sealed class SID_AND_ATTR
685         {
686             public IntPtr pSid = IntPtr.Zero;
687             public int attrs = 0;
688         }
689 
690         //
691         // Token
692         //
693 
694         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
695         public sealed class TOKEN_USER
696         {
697             public SID_AND_ATTR sidAndAttributes = new SID_AND_ATTR();
698         }
699 
700         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
701         public sealed class SID_IDENTIFIER_AUTHORITY
702         {
703             public byte b1 = 0;
704             public byte b2 = 0;
705             public byte b3 = 0;
706             public byte b4 = 0;
707             public byte b5 = 0;
708             public byte b6 = 0;
709         }
710 
711         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
712         public sealed class LSA_OBJECT_ATTRIBUTES
713         {
714             public int length = 0;
715             public IntPtr rootDirectory = IntPtr.Zero;
716             public IntPtr objectName = IntPtr.Zero;
717             public int attributes = 0;
718             public IntPtr securityDescriptor = IntPtr.Zero;
719             public IntPtr securityQualityOfService = IntPtr.Zero;
720         }
721 
722         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
723         public sealed class POLICY_ACCOUNT_DOMAIN_INFO
724         {
725             public LSA_UNICODE_STRING domainName = new LSA_UNICODE_STRING();
726             public IntPtr domainSid = IntPtr.Zero;
727         }
728 
729         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
730         public sealed class LSA_UNICODE_STRING
731         {
732             public ushort length = 0;
733             public ushort maximumLength = 0;
734             public IntPtr buffer = IntPtr.Zero;
735         }
736 
737         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
738         public sealed class LSA_UNICODE_STRING_Managed
739         {
740             public ushort length = 0;
741             public ushort maximumLength = 0;
742             public string buffer;
743         }
744 
745         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
746         public sealed class LSA_TRANSLATED_NAME
747         {
748             public int use = 0;
749             public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING();
750             public int domainIndex = 0;
751         }
752 
753         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
754         public sealed class LSA_REFERENCED_DOMAIN_LIST
755         {
756             // To stop the compiler from autogenerating a constructor for this class
LSA_REFERENCED_DOMAIN_LIST()757             private LSA_REFERENCED_DOMAIN_LIST() { }
758 
759             public int entries = 0;
760             public IntPtr domains = IntPtr.Zero;
761         }
762 
763         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
764         public sealed class LSA_TRUST_INFORMATION
765         {
766             public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING();
767             private IntPtr _pSid = IntPtr.Zero;
768         }
769 
770         [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenThreadToken", CharSet = CharSet.Unicode)]
OpenThreadToken( IntPtr threadHandle, int desiredAccess, bool openAsSelf, ref IntPtr tokenHandle )771         static extern public bool OpenThreadToken(
772                                         IntPtr threadHandle,
773                                         int desiredAccess,
774                                         bool openAsSelf,
775                                         ref IntPtr tokenHandle
776                                         );
777 
778         [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenProcessToken", CharSet = CharSet.Unicode)]
OpenProcessToken( IntPtr processHandle, int desiredAccess, ref IntPtr tokenHandle )779         static extern public bool OpenProcessToken(
780                                         IntPtr processHandle,
781                                         int desiredAccess,
782                                         ref IntPtr tokenHandle
783                                         );
784 
785         [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "CloseHandle", CharSet = CharSet.Unicode)]
CloseHandle(IntPtr handle)786         static extern public bool CloseHandle(IntPtr handle);
787 
788         [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThread", CharSet = CharSet.Unicode)]
GetCurrentThread()789         static extern public IntPtr GetCurrentThread();
790 
791         [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentProcess", CharSet = CharSet.Unicode)]
GetCurrentProcess()792         static extern public IntPtr GetCurrentProcess();
793 
794         [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetTokenInformation", CharSet = CharSet.Unicode)]
GetTokenInformation( IntPtr tokenHandle, int tokenInformationClass, IntPtr buffer, int bufferSize, ref int returnLength )795         static extern public bool GetTokenInformation(
796                                         IntPtr tokenHandle,
797                                         int tokenInformationClass,
798                                         IntPtr buffer,
799                                         int bufferSize,
800                                         ref int returnLength
801                                         );
802 
803         [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaOpenPolicy", CharSet = CharSet.Unicode)]
LsaOpenPolicy( IntPtr lsaUnicodeString, IntPtr lsaObjectAttributes, int desiredAccess, ref IntPtr policyHandle)804         static extern public int LsaOpenPolicy(
805                                         IntPtr lsaUnicodeString,
806                                         IntPtr lsaObjectAttributes,
807                                         int desiredAccess,
808                                         ref IntPtr policyHandle);
809 
810         [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaQueryInformationPolicy", CharSet = CharSet.Unicode)]
LsaQueryInformationPolicy( IntPtr policyHandle, int policyInformationClass, ref IntPtr buffer )811         static extern public int LsaQueryInformationPolicy(
812                                         IntPtr policyHandle,
813                                         int policyInformationClass,
814                                         ref IntPtr buffer
815                                         );
816 
817         [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaLookupSids", CharSet = CharSet.Unicode)]
LsaLookupSids( IntPtr policyHandle, int count, IntPtr[] sids, out IntPtr referencedDomains, out IntPtr names )818         public static extern int LsaLookupSids(
819                                         IntPtr policyHandle,
820                                         int count,
821                                         IntPtr[] sids,
822                                         out IntPtr referencedDomains,
823                                         out IntPtr names
824                                         );
825 
826         [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaFreeMemory", CharSet = CharSet.Unicode)]
LsaFreeMemory(IntPtr buffer)827         static extern public int LsaFreeMemory(IntPtr buffer);
828 
829         [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaClose", CharSet = CharSet.Unicode)]
LsaClose(IntPtr policyHandle)830         static extern public int LsaClose(IntPtr policyHandle);
831 
832         //
833         // Impersonation
834         //
835 
836         [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "LogonUserW", CharSet = CharSet.Unicode)]
LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken)837         static extern public int LogonUser(
838                                     string lpszUsername,
839                                     string lpszDomain,
840                                     string lpszPassword,
841                                     int dwLogonType,
842                                     int dwLogonProvider,
843                                     ref IntPtr phToken);
844 
845         [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ImpersonateLoggedOnUser", CharSet = CharSet.Unicode)]
ImpersonateLoggedOnUser(IntPtr hToken)846         static extern public int ImpersonateLoggedOnUser(IntPtr hToken);
847 
848         [DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "RevertToSelf", CharSet = CharSet.Unicode)]
RevertToSelf()849         static extern public int RevertToSelf();
850 
851         public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
852             FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
853             FORMAT_MESSAGE_FROM_STRING = 0x00000400,
854             FORMAT_MESSAGE_FROM_HMODULE = 0x00000800,
855             FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
856             FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000,
857             FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF;
858 
859         [DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
FormatMessageW(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr arguments)860         public static extern int FormatMessageW(int dwFlags, IntPtr lpSource, int dwMessageId,
861                                                 int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr arguments);
862     }
863 }
864 
865