TAMUQITS
asked on
Take ownership of a folder with C# 1.1
I need to be able to take control of a folder while using C#.
I have found an example using WMI in Win32 at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/takeownership_method_in_class_win32_directory.asp
There is an example of how to do it in .NET 2.0 at:
https://www.experts-exchange.com/questions/21823904/Take-ownership-of-a-folder.html
Can somebody provide an example of how to do this in .NET 1.0 or 1.1?
Thanks
I have found an example using WMI in Win32 at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/takeownership_method_in_class_win32_directory.asp
There is an example of how to do it in .NET 2.0 at:
https://www.experts-exchange.com/questions/21823904/Take-ownership-of-a-folder.html
Can somebody provide an example of how to do this in .NET 1.0 or 1.1?
Thanks
That code should work in 1.1 as well (except the using generics part)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks for the response. I added the code to my app and it runs up until "dir.Get()" and then it throws a "Access is denied." Exception.
I'm not sure where to start with this so I gave everybody full access to the test folder and I still get this message. That leads me to believe it is not an NTFS issue.
Details:
=== Access is denied ===
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessE xception: Access is denied.
=== The stack trace is ===
[UnauthorizedAccessExcepti on: Access is denied.]
System.Management.Manageme ntScope.In itializeGu ts(Object o) +47
System.Management.Manageme ntScope.In itialize() +187
System.Management.Manageme ntObject.I nitialize( Boolean getObject) +620
System.Management.Manageme ntObject.I nvokeMetho d(String methodName, Object[] args) +94
tamuq.ad.ADUser.renameProf ile() +360
tamuq.ad.ADUser.resetProfi le(Boolean deletArchivedProfiles) +170
ASP.editUser_resetProfile_ aspx.btnRe setProfile _Click(Obj ect Src, EventArgs E) in C:\UserMgmt\editUser_reset Profile.as px:37
System.Web.UI.WebControls. Button.OnC lick(Event Args e) +108
System.Web.UI.WebControls. Button.Sys tem.Web.UI .IPostBack EventHandl er.RaisePo stBackEven t(String eventArgument) +57
System.Web.UI.Page.RaisePo stBackEven t(IPostBac kEventHand ler sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePo stBackEven t(NameValu eCollectio n postData) +33
System.Web.UI.Page.Process RequestMai n() +1281
=== MORE INFO ===
When I tried to add a reference to the system.management.dll I got the error:
A reference to 'I:\WINDOWS\MICROSOFT.NET\ Framework\ v1.1.4322\ System.Man agement.dl l' could not be added. Error parsing application configuration file at line 11. Type '{http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/configuration}ReadOnlyConfigurationSe ctionData' is not found in Schema.
I'm not sure where to start with this so I gave everybody full access to the test folder and I still get this message. That leads me to believe it is not an NTFS issue.
Details:
=== Access is denied ===
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessE
=== The stack trace is ===
[UnauthorizedAccessExcepti
System.Management.Manageme
System.Management.Manageme
System.Management.Manageme
System.Management.Manageme
tamuq.ad.ADUser.renameProf
tamuq.ad.ADUser.resetProfi
ASP.editUser_resetProfile_
System.Web.UI.WebControls.
System.Web.UI.WebControls.
System.Web.UI.Page.RaisePo
System.Web.UI.Page.RaisePo
System.Web.UI.Page.Process
=== MORE INFO ===
When I tried to add a reference to the system.management.dll I got the error:
A reference to 'I:\WINDOWS\MICROSOFT.NET\
"A reference to 'I:\WINDOWS\MICROSOFT.NET\ Framework\ v1.1.4322\ System.Man agement.dl l' could not be added. Error parsing application configuration file at line 11. Type '{http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/configuration}ReadOnlyConfigurationSe ctionData' is not found in Schema."
sounds like you are having an app config problem for one ...
For the second bit .. what user are you running as (yourself?)
sounds like you are having an app config problem for one ...
For the second bit .. what user are you running as (yourself?)
ASKER
At this point in the App I've impersonated an admin account.
"sounds like you are having an app config problem for one ..."
Where would be a good place to start looking for a solution. Are you talking about machine.config, web.config or something else?
Thanks
"sounds like you are having an app config problem for one ..."
Where would be a good place to start looking for a solution. Are you talking about machine.config, web.config or something else?
Thanks
sounds like its having issues with an application block for your app.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
The Learned One I wasn't able to get the above code to work.
I modified it to compile but still no luck:
LogonUtility logon = new LogonUtility();
logon.ImpersonateUser(TQDe lAcct, TQDelPass);
System.Web.HttpContext.Cur rent.Trace .Warn("BBB 0");
System.Web.HttpContext.Cur rent.Trace .Warn("BBB 1");
////////////////////////// ////////// ////////// ///////
////////////////////////// ////////// ////////// ///////
//Define ManagementScope
ConnectionOptions options = new ConnectionOptions();
options.Username = TQDelAcct;
options.Password = TQDelPass;
//Define ManagementPath
ManagementPath path = new ManagementPath();
path.Server = @"\\mail\root\cimv2";
ManagementScope scope = new ManagementScope(profileSta rt, options);
string dirObject = String.Format("win32_Direc tory.Name= '{0}'", profileStart);
//Define ManagementObject
using (ManagementObject dir = new ManagementObject(dirObject , path, null))
{
System.Web.HttpContext.Cur rent.Trace .Warn("BBB 2");
dir.Get();
System.Web.HttpContext.Cur rent.Trace .Warn("BBB 3");
dir.InvokeMethod("TakeOwne rShip", null);
System.Web.HttpContext.Cur rent.Trace .Warn("BBB 4");
}
I'm going to open an MSDN ticket on this and once I get a solution I will post and award points
I modified it to compile but still no luck:
LogonUtility logon = new LogonUtility();
logon.ImpersonateUser(TQDe
System.Web.HttpContext.Cur
System.Web.HttpContext.Cur
//////////////////////////
//////////////////////////
//Define ManagementScope
ConnectionOptions options = new ConnectionOptions();
options.Username = TQDelAcct;
options.Password = TQDelPass;
//Define ManagementPath
ManagementPath path = new ManagementPath();
path.Server = @"\\mail\root\cimv2";
ManagementScope scope = new ManagementScope(profileSta
string dirObject = String.Format("win32_Direc
//Define ManagementObject
using (ManagementObject dir = new ManagementObject(dirObject
{
System.Web.HttpContext.Cur
dir.Get();
System.Web.HttpContext.Cur
dir.InvokeMethod("TakeOwne
System.Web.HttpContext.Cur
}
I'm going to open an MSDN ticket on this and once I get a solution I will post and award points
What is happening with that code?
Bob
Bob
ASKER
I submitted a ticket with MSDN and they provided me with the following class that did the trick.
It came in the form of a windows form app with the below namespaces. I believe you only need System since it imports all the .dlls but I'm a web guy so here is all of them
using System;
using System.Collections.Generic ;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServ ices;
public class ACLUtil
{
public enum SE_OBJECT_TYPE : uint
{
SE_UNKNOWN_OBJECT_TYPE = 0,
SE_FILE_OBJECT,
SE_SERVICE,
SE_PRINTER,
SE_REGISTRY_KEY,
SE_LMSHARE,
SE_KERNEL_OBJECT,
SE_WINDOW_OBJECT,
SE_DS_OBJECT,
SE_DS_OBJECT_ALL,
SE_PROVIDER_DEFINED_OBJECT ,
SE_WMIGUID_OBJECT,
SE_REGISTRY_WOW64_32KEY
}
[Flags]
public enum SECURITY_INFORMATION : uint
{
OWNER_SECURITY_INFORMATION = 0x00000001,
GROUP_SECURITY_INFORMATION = 0x00000002,
DACL_SECURITY_INFORMATION = 0x00000004,
SACL_SECURITY_INFORMATION = 0x00000008,
// Win2k only
PROTECTED_DACL_SECURITY_IN FORMATION = 0x80000000,
// Win2k only
PROTECTED_SACL_SECURITY_IN FORMATION = 0x40000000,
// Win2k only
UNPROTECTED_DACL_SECURITY_ INFORMATIO N = 0x20000000,
// Win2k only
UNPROTECTED_SACL_SECURITY_ INFORMATIO N = 0x10000000,
}
public const string SE_RESTORE_NAME = "SeRestorePrivilege";
[StructLayout(LayoutKind.S equential) ]
public struct LUID
{
public uint lowpart;
public uint highpart;
}
[StructLayout(LayoutKind.S equential) ]
public struct LUID_AND_ATTRIBUTES
{
public LUID pLuid;
public uint Attributes;
}
[StructLayout(LayoutKind.S equential) ]
public struct TOKEN_PRIVILEGES
{
public int PrivilegeCount;
public LUID_AND_ATTRIBUTES privileges;
}
[StructLayout(LayoutKind.S equential) ]
public struct TRUSTEE
{
public uint pMultipleTrustee;
public uint MultipleTrusteeOperation;
public uint TrusteeForm;
public uint TrusteeType;
public uint ptstrName;
}
[StructLayout(LayoutKind.S equential) ]
public struct EXPLICIT_ACCESS
{
public uint grfAccessPermissions;
public uint grfAccessMode;
public uint grfInheritance;
public TRUSTEE pTRUSTEE;
}
// Generic access rights extracted from WinNT.h
public const uint GENERIC_ALL = 0x10000000;
public const uint GENERIC_EXECUTE = 0x20000000;
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint SET_ACCESS = 2;
// Inheritance Flags
public const uint CONTAINER_INHERIT_ACE = 2;
public const uint OBJECT_INHERIT_ACE = 1;
// Error codes
public const int ERROR_SUCCESS = 0;
public const int ERROR_INSUFFICIENT_BUFFER = 122;
public const int ERROR_NONE_MAPPED = 1332;
private const uint MAXIMUM_ALLOWED = 0x02000000;
private const uint TOKEN_QUERY = 0x0008;
private const uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
private const uint SE_PRIVILEGE_ENABLED = 2;
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenThreadToken(
uint ThreadHandle,
uint DesiredAccess,
bool OpenAsSelf,
ref uint TokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(
uint ThreadHandle,
uint DesiredAccess,
ref uint TokenHandle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(uint handle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint GetCurrentThread();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint GetCurrentProcess();
public static uint GetCurrentToken(uint accessMask)
{
uint hToken = 0;
if (!OpenThreadToken(GetCurre ntThread() , accessMask, true, ref hToken))
{
if (!OpenProcessToken(GetCurr entProcess (), accessMask, ref hToken))
{
throw new Win32Exception(Marshal.Get LastWin32E rror());
//throw new ApplicationException("Open ProcessTok en failed with error code : " + Marshal.GetLastWin32Error( ).ToString ());
}
}
return hToken;
}
[DllImport("Kernel32.dll",
CallingConvention = CallingConvention.Winapi,
SetLastError = true)]
public static extern uint LocalFree(uint hMem);
[DllImport("Advapi32.dll",
EntryPoint = "BuildExplicitAccessWithNa meA",
CallingConvention = CallingConvention.Winapi,
SetLastError = true, CharSet = CharSet.Ansi)]
public static extern void BuildExplicitAccessWithNam e(
ref EXPLICIT_ACCESS ea,
IntPtr TrusteeName,
uint AccessPermissions,
uint AccessMode,
uint Inheritance);
[DllImport("Advapi32.dll",
EntryPoint = "SetEntriesInAclA",
CallingConvention = CallingConvention.Winapi,
SetLastError = true, CharSet = CharSet.Ansi)]
public static extern uint SetEntriesInAcl(
int CountofExplicitEntries,
ref EXPLICIT_ACCESS ea,
uint OldAcl,
ref uint NewAcl);
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Ansi)]
public static extern uint SetNamedSecurityInfo(
[MarshalAs(UnmanagedType.L PStr)] string pObjectName,
SE_OBJECT_TYPE ObjectType,
SECURITY_INFORMATION SecurityInfo,
IntPtr psidOwner,
uint psidGroup,
uint pDacl,
uint pSacl);
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Ansi)]
public static extern bool LookupAccountName(
[MarshalAs(UnmanagedType.L PStr)] string lpSystemName,
[MarshalAs(UnmanagedType.L PStr)] string lpAccountName,
IntPtr Sid,
ref int cbSid,
IntPtr DomainName,
ref int cbDomainName,
ref uint peUse
);
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Ansi)]
public static extern bool LookupPrivilegeValue(
[MarshalAs(UnmanagedType.L PStr)] string lpSystemName,
[MarshalAs(UnmanagedType.L PStr)] string lpName,
ref LUID Luid);
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true, CharSet = CharSet.Ansi)]
public static extern bool AdjustTokenPrivileges(
uint TokenHandle,
bool DisableAllPrivileges,
ref TOKEN_PRIVILEGES NewState,
int BufferLength,
uint PreviousState,
uint ReturnLength);
static bool AddFullControlToFolder(str ing FolderName, string[] accountNames, string ownerName)
{
int x;
int i;
bool bReturn;
bReturn = false;
x = accountNames.Length;
EXPLICIT_ACCESS[] ea = new EXPLICIT_ACCESS[x];
IntPtr[] accountNamePtrs = new IntPtr[x];
IntPtr sidPtr = IntPtr.Zero;
IntPtr domainNamePtr = IntPtr.Zero;
uint pDacl = 0;
uint hToken = 0;
try
{
int sidSize;
int domainNameSize;
bool bResult;
uint status;
uint eUse;
LUID luid = new LUID();
TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();
sidSize = 0;
domainNameSize = 0;
eUse = 0;
bResult = LookupAccountName(null, ownerName,
sidPtr, ref sidSize,
domainNamePtr, ref domainNameSize, ref eUse);
if (bResult == false &&
Marshal.GetLastWin32Error( ) != ERROR_INSUFFICIENT_BUFFER)
throw new ApplicationException("Look upAccountN ame failed with error code : " + Marshal.GetLastWin32Error( ).ToString ());
sidPtr = Marshal.AllocHGlobal(sidSi ze);
domainNamePtr = Marshal.AllocHGlobal(domai nNameSize) ;
bResult = LookupAccountName(null, ownerName,
sidPtr, ref sidSize,
domainNamePtr, ref domainNameSize, ref eUse);
if (bResult == false)
throw new ApplicationException("Look upAccountN ame failed with error code : " + Marshal.GetLastWin32Error( ).ToString ());
for (i = 0; i < x; i++)
{
accountNamePtrs[i] = Marshal.StringToHGlobalAns i(accountN ames[i]);
BuildExplicitAccessWithNam e(ref ea[i],
accountNamePtrs[i],
GENERIC_ALL,
SET_ACCESS,
CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE);
}
status = SetEntriesInAcl(x, ref ea[0], 0, ref pDacl);
if (status != ERROR_SUCCESS)
throw new ApplicationException("SetE ntriesInAc l failed with error code : " + status.ToString());
hToken = GetCurrentToken(TOKEN_QUER Y | TOKEN_ADJUST_PRIVILEGES);
bResult = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref luid);
if (bResult == false)
throw new ApplicationException("Look upPrivileg eValue failed with error code : " + Marshal.GetLastWin32Error( ).ToString ());
tp.PrivilegeCount = 1;
tp.privileges.pLuid = luid;
tp.privileges.Attributes = SE_PRIVILEGE_ENABLED;
bResult = AdjustTokenPrivileges(hTok en, false, ref tp, Marshal.SizeOf(tp), 0, 0);
if (bResult == false)
throw new ApplicationException("Adju stTokenPri vileges failed with error code : " + Marshal.GetLastWin32Error( ).ToString ());
status = SetNamedSecurityInfo(Folde rName, SE_OBJECT_TYPE.SE_FILE_OBJ ECT,
SECURITY_INFORMATION.DACL_ SECURITY_I NFORMATION |
SECURITY_INFORMATION.OWNER _SECURITY_ INFORMATIO N |
SECURITY_INFORMATION.PROTE CTED_DACL_ SECURITY_I NFORMATION ,
sidPtr,
0,
pDacl,
0);
if (status != ERROR_SUCCESS)
throw new ApplicationException("SetN amedSecuri tyInfo failed with error code : " + status.ToString());
bReturn = true;
}
finally
{
for (i = 0; i < x; i++)
{
if (accountNamePtrs[i] != IntPtr.Zero)
{
Marshal.FreeHGlobal(accoun tNamePtrs[ i]);
}
}
if (sidPtr != IntPtr.Zero)
Marshal.FreeHGlobal(sidPtr );
if (domainNamePtr != IntPtr.Zero)
Marshal.FreeHGlobal(domain NamePtr);
if (pDacl != 0)
LocalFree(pDacl);
if (hToken != 0)
CloseHandle(hToken);
}
return bReturn;
}
public static bool SetOwner(string FolderName, string ownerName, string adminAcct, string adminPass)
{
bool bReturn = false;
IntPtr sidPtr = IntPtr.Zero;
IntPtr domainNamePtr = IntPtr.Zero;
uint hToken = 0;
LogonUtility logon = new LogonUtility(); //custom class - used to access impersonation function
try
{
int sidSize;
int domainNameSize;
bool bResult;
uint status;
uint eUse;
LUID luid = new LUID();
TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();
sidSize = 0;
domainNameSize = 0;
eUse = 0;
bResult = LookupAccountName(
null, ownerName,
sidPtr, ref sidSize,
domainNamePtr, ref domainNameSize, ref eUse);
if (bResult == false && Marshal.GetLastWin32Error( ) != ERROR_INSUFFICIENT_BUFFER)
System.Web.HttpContext.Cur rent.Trace .Warn("1 LookupAccountName failed with error code : " + Marshal.GetLastWin32Error( ).ToString ());
sidPtr = Marshal.AllocHGlobal(sidSi ze);
domainNamePtr = Marshal.AllocHGlobal(domai nNameSize) ;
bResult = LookupAccountName(null, ownerName,
sidPtr, ref sidSize,
domainNamePtr, ref domainNameSize, ref eUse);
if (bResult == false)
System.Web.HttpContext.Cur rent.Trace .Warn("2 LookupAccountName failed with error code : " + Marshal.GetLastWin32Error( ).ToString ());
hToken = GetCurrentToken(TOKEN_QUER Y | TOKEN_ADJUST_PRIVILEGES);
bResult = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref luid);
if (bResult == false)
System.Web.HttpContext.Cur rent.Trace .Warn("3 LookupPrivilegeValue failed with error code : " + Marshal.GetLastWin32Error( ).ToString ());
tp.PrivilegeCount = 1;
tp.privileges.pLuid = luid;
tp.privileges.Attributes = SE_PRIVILEGE_ENABLED;
bResult = AdjustTokenPrivileges(hTok en, false, ref tp, Marshal.SizeOf(tp), 0, 0);
if (bResult == false)
System.Web.HttpContext.Cur rent.Trace .Warn("4 AdjustTokenPrivileges failed with error code : " + Marshal.GetLastWin32Error( ).ToString ());
logon.ImpersonateUser(admi nAcct, adminPass);//impersonate the admin account
status = SetNamedSecurityInfo(Folde rName, SE_OBJECT_TYPE.SE_FILE_OBJ ECT,
SECURITY_INFORMATION.OWNER _SECURITY_ INFORMATIO N, sidPtr, 0, 0, 0);
if (status != ERROR_SUCCESS)
{
System.Web.HttpContext.Cur rent.Trace .Warn("5 SetNamedSecurityInfo failed with error code : " + status.ToString());
}
else
bReturn = true;
}
finally
{
if (sidPtr != IntPtr.Zero)
Marshal.FreeHGlobal(sidPtr );
if (domainNamePtr != IntPtr.Zero)
Marshal.FreeHGlobal(domain NamePtr);
if (hToken != 0)
CloseHandle(hToken);
}
return bReturn;
}
/*
[STAThread]
static void Main(string[] args)
{
string[] accountNames = { "Administrators", "SYSTEM", "testuser" };
if (AddFullControlToFolder("C :\\TEST\\T EST", accountNames, "REDMOND\\prabagar"))
{
Console.WriteLine("Permiss ions set successfully");
}
else
Console.WriteLine("Unable to set permissions");
}
*/
}
It came in the form of a windows form app with the below namespaces. I believe you only need System since it imports all the .dlls but I'm a web guy so here is all of them
using System;
using System.Collections.Generic
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServ
public class ACLUtil
{
public enum SE_OBJECT_TYPE : uint
{
SE_UNKNOWN_OBJECT_TYPE = 0,
SE_FILE_OBJECT,
SE_SERVICE,
SE_PRINTER,
SE_REGISTRY_KEY,
SE_LMSHARE,
SE_KERNEL_OBJECT,
SE_WINDOW_OBJECT,
SE_DS_OBJECT,
SE_DS_OBJECT_ALL,
SE_PROVIDER_DEFINED_OBJECT
SE_WMIGUID_OBJECT,
SE_REGISTRY_WOW64_32KEY
}
[Flags]
public enum SECURITY_INFORMATION : uint
{
OWNER_SECURITY_INFORMATION
GROUP_SECURITY_INFORMATION
DACL_SECURITY_INFORMATION = 0x00000004,
SACL_SECURITY_INFORMATION = 0x00000008,
// Win2k only
PROTECTED_DACL_SECURITY_IN
// Win2k only
PROTECTED_SACL_SECURITY_IN
// Win2k only
UNPROTECTED_DACL_SECURITY_
// Win2k only
UNPROTECTED_SACL_SECURITY_
}
public const string SE_RESTORE_NAME = "SeRestorePrivilege";
[StructLayout(LayoutKind.S
public struct LUID
{
public uint lowpart;
public uint highpart;
}
[StructLayout(LayoutKind.S
public struct LUID_AND_ATTRIBUTES
{
public LUID pLuid;
public uint Attributes;
}
[StructLayout(LayoutKind.S
public struct TOKEN_PRIVILEGES
{
public int PrivilegeCount;
public LUID_AND_ATTRIBUTES privileges;
}
[StructLayout(LayoutKind.S
public struct TRUSTEE
{
public uint pMultipleTrustee;
public uint MultipleTrusteeOperation;
public uint TrusteeForm;
public uint TrusteeType;
public uint ptstrName;
}
[StructLayout(LayoutKind.S
public struct EXPLICIT_ACCESS
{
public uint grfAccessPermissions;
public uint grfAccessMode;
public uint grfInheritance;
public TRUSTEE pTRUSTEE;
}
// Generic access rights extracted from WinNT.h
public const uint GENERIC_ALL = 0x10000000;
public const uint GENERIC_EXECUTE = 0x20000000;
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint SET_ACCESS = 2;
// Inheritance Flags
public const uint CONTAINER_INHERIT_ACE = 2;
public const uint OBJECT_INHERIT_ACE = 1;
// Error codes
public const int ERROR_SUCCESS = 0;
public const int ERROR_INSUFFICIENT_BUFFER = 122;
public const int ERROR_NONE_MAPPED = 1332;
private const uint MAXIMUM_ALLOWED = 0x02000000;
private const uint TOKEN_QUERY = 0x0008;
private const uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
private const uint SE_PRIVILEGE_ENABLED = 2;
[DllImport("advapi32.dll",
private static extern bool OpenThreadToken(
uint ThreadHandle,
uint DesiredAccess,
bool OpenAsSelf,
ref uint TokenHandle);
[DllImport("advapi32.dll",
private static extern bool OpenProcessToken(
uint ThreadHandle,
uint DesiredAccess,
ref uint TokenHandle);
[DllImport("kernel32.dll",
public static extern bool CloseHandle(uint handle);
[DllImport("kernel32.dll",
private static extern uint GetCurrentThread();
[DllImport("kernel32.dll",
private static extern uint GetCurrentProcess();
public static uint GetCurrentToken(uint accessMask)
{
uint hToken = 0;
if (!OpenThreadToken(GetCurre
{
if (!OpenProcessToken(GetCurr
{
throw new Win32Exception(Marshal.Get
//throw new ApplicationException("Open
}
}
return hToken;
}
[DllImport("Kernel32.dll",
CallingConvention = CallingConvention.Winapi,
SetLastError = true)]
public static extern uint LocalFree(uint hMem);
[DllImport("Advapi32.dll",
EntryPoint = "BuildExplicitAccessWithNa
CallingConvention = CallingConvention.Winapi,
SetLastError = true, CharSet = CharSet.Ansi)]
public static extern void BuildExplicitAccessWithNam
ref EXPLICIT_ACCESS ea,
IntPtr TrusteeName,
uint AccessPermissions,
uint AccessMode,
uint Inheritance);
[DllImport("Advapi32.dll",
EntryPoint = "SetEntriesInAclA",
CallingConvention = CallingConvention.Winapi,
SetLastError = true, CharSet = CharSet.Ansi)]
public static extern uint SetEntriesInAcl(
int CountofExplicitEntries,
ref EXPLICIT_ACCESS ea,
uint OldAcl,
ref uint NewAcl);
[DllImport("Advapi32.dll",
public static extern uint SetNamedSecurityInfo(
[MarshalAs(UnmanagedType.L
SE_OBJECT_TYPE ObjectType,
SECURITY_INFORMATION SecurityInfo,
IntPtr psidOwner,
uint psidGroup,
uint pDacl,
uint pSacl);
[DllImport("Advapi32.dll",
public static extern bool LookupAccountName(
[MarshalAs(UnmanagedType.L
[MarshalAs(UnmanagedType.L
IntPtr Sid,
ref int cbSid,
IntPtr DomainName,
ref int cbDomainName,
ref uint peUse
);
[DllImport("Advapi32.dll",
public static extern bool LookupPrivilegeValue(
[MarshalAs(UnmanagedType.L
[MarshalAs(UnmanagedType.L
ref LUID Luid);
[DllImport("Advapi32.dll",
public static extern bool AdjustTokenPrivileges(
uint TokenHandle,
bool DisableAllPrivileges,
ref TOKEN_PRIVILEGES NewState,
int BufferLength,
uint PreviousState,
uint ReturnLength);
static bool AddFullControlToFolder(str
{
int x;
int i;
bool bReturn;
bReturn = false;
x = accountNames.Length;
EXPLICIT_ACCESS[] ea = new EXPLICIT_ACCESS[x];
IntPtr[] accountNamePtrs = new IntPtr[x];
IntPtr sidPtr = IntPtr.Zero;
IntPtr domainNamePtr = IntPtr.Zero;
uint pDacl = 0;
uint hToken = 0;
try
{
int sidSize;
int domainNameSize;
bool bResult;
uint status;
uint eUse;
LUID luid = new LUID();
TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();
sidSize = 0;
domainNameSize = 0;
eUse = 0;
bResult = LookupAccountName(null, ownerName,
sidPtr, ref sidSize,
domainNamePtr, ref domainNameSize, ref eUse);
if (bResult == false &&
Marshal.GetLastWin32Error(
throw new ApplicationException("Look
sidPtr = Marshal.AllocHGlobal(sidSi
domainNamePtr = Marshal.AllocHGlobal(domai
bResult = LookupAccountName(null, ownerName,
sidPtr, ref sidSize,
domainNamePtr, ref domainNameSize, ref eUse);
if (bResult == false)
throw new ApplicationException("Look
for (i = 0; i < x; i++)
{
accountNamePtrs[i] = Marshal.StringToHGlobalAns
BuildExplicitAccessWithNam
accountNamePtrs[i],
GENERIC_ALL,
SET_ACCESS,
CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE);
}
status = SetEntriesInAcl(x, ref ea[0], 0, ref pDacl);
if (status != ERROR_SUCCESS)
throw new ApplicationException("SetE
hToken = GetCurrentToken(TOKEN_QUER
bResult = LookupPrivilegeValue(null,
if (bResult == false)
throw new ApplicationException("Look
tp.PrivilegeCount = 1;
tp.privileges.pLuid = luid;
tp.privileges.Attributes = SE_PRIVILEGE_ENABLED;
bResult = AdjustTokenPrivileges(hTok
if (bResult == false)
throw new ApplicationException("Adju
status = SetNamedSecurityInfo(Folde
SECURITY_INFORMATION.DACL_
SECURITY_INFORMATION.OWNER
SECURITY_INFORMATION.PROTE
sidPtr,
0,
pDacl,
0);
if (status != ERROR_SUCCESS)
throw new ApplicationException("SetN
bReturn = true;
}
finally
{
for (i = 0; i < x; i++)
{
if (accountNamePtrs[i] != IntPtr.Zero)
{
Marshal.FreeHGlobal(accoun
}
}
if (sidPtr != IntPtr.Zero)
Marshal.FreeHGlobal(sidPtr
if (domainNamePtr != IntPtr.Zero)
Marshal.FreeHGlobal(domain
if (pDacl != 0)
LocalFree(pDacl);
if (hToken != 0)
CloseHandle(hToken);
}
return bReturn;
}
public static bool SetOwner(string FolderName, string ownerName, string adminAcct, string adminPass)
{
bool bReturn = false;
IntPtr sidPtr = IntPtr.Zero;
IntPtr domainNamePtr = IntPtr.Zero;
uint hToken = 0;
LogonUtility logon = new LogonUtility(); //custom class - used to access impersonation function
try
{
int sidSize;
int domainNameSize;
bool bResult;
uint status;
uint eUse;
LUID luid = new LUID();
TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();
sidSize = 0;
domainNameSize = 0;
eUse = 0;
bResult = LookupAccountName(
null, ownerName,
sidPtr, ref sidSize,
domainNamePtr, ref domainNameSize, ref eUse);
if (bResult == false && Marshal.GetLastWin32Error(
System.Web.HttpContext.Cur
sidPtr = Marshal.AllocHGlobal(sidSi
domainNamePtr = Marshal.AllocHGlobal(domai
bResult = LookupAccountName(null, ownerName,
sidPtr, ref sidSize,
domainNamePtr, ref domainNameSize, ref eUse);
if (bResult == false)
System.Web.HttpContext.Cur
hToken = GetCurrentToken(TOKEN_QUER
bResult = LookupPrivilegeValue(null,
if (bResult == false)
System.Web.HttpContext.Cur
tp.PrivilegeCount = 1;
tp.privileges.pLuid = luid;
tp.privileges.Attributes = SE_PRIVILEGE_ENABLED;
bResult = AdjustTokenPrivileges(hTok
if (bResult == false)
System.Web.HttpContext.Cur
logon.ImpersonateUser(admi
status = SetNamedSecurityInfo(Folde
SECURITY_INFORMATION.OWNER
if (status != ERROR_SUCCESS)
{
System.Web.HttpContext.Cur
}
else
bReturn = true;
}
finally
{
if (sidPtr != IntPtr.Zero)
Marshal.FreeHGlobal(sidPtr
if (domainNamePtr != IntPtr.Zero)
Marshal.FreeHGlobal(domain
if (hToken != 0)
CloseHandle(hToken);
}
return bReturn;
}
/*
[STAThread]
static void Main(string[] args)
{
string[] accountNames = { "Administrators", "SYSTEM", "testuser" };
if (AddFullControlToFolder("C
{
Console.WriteLine("Permiss
}
else
Console.WriteLine("Unable to set permissions");
}
*/
}
Nice class, but I don't see LogonUtility anywhere.
Bob
Bob
ASKER
I forgot about that one here it is:
////////////////////////// ////////// ////////// ////////// //
public class LogonUtility
{
private static string IMPERSONATED_USER;
private static string IMPERSONATED_PASS;
public LogonUtility()
{
IMPERSONATED_USER = IMPERSONATED_PASS = "";
}
public LogonUtility(string user, string pass)
{
IMPERSONATED_USER = user;
IMPERSONATED_PASS = pass;
}
//import LSA functions
[DllImport("advapi32.dll") ]
private static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken
);
[DllImport("advapi32.dll") ]
private static extern bool DuplicateToken(
IntPtr ExistingTokenHandle,
int ImpersonationLevel,
ref IntPtr DuplicateTokenHandle
);
[DllImport("kernel32.dll") ]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("advapi32.dll") ]
private static extern bool ImpersonateLoggedOnUser(In tPtr hToken);
[DllImport("kernel32.dll") ]
private static extern int GetLastError();
//enum impersonation levels an logon types
private enum SecurityImpersonationLevel
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
private enum LogonTypes
{
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEA RTEXT = 8,
LOGON32_LOGON_NEW_CREDENTI ALS = 9
}
public WindowsImpersonationContex t ImpersonateUser()
{
//define the handles
IntPtr existingTokenHandle = IntPtr.Zero;
IntPtr duplicateTokenHandle = IntPtr.Zero;
string domain = "yourDomain";
string username = IMPERSONATED_USER;
string password = IMPERSONATED_PASS;
bool isOkay = true;
try
{
//get a security token
isOkay = LogonUser(username, domain, password,
(int)LogonTypes.LOGON32_LO GON_INTERA CTIVE, (int)LogonTypes.LOGON32_PR OVIDER_DEF AULT,
ref existingTokenHandle);
if (!isOkay)
{
int lastWin32Error = Marshal.GetLastWin32Error( );
int lastError = GetLastError();
throw new Exception("LogonUser Failed: " + lastWin32Error + " - " + lastError);
}
// copy the token
isOkay = DuplicateToken(existingTok enHandle,
(int)SecurityImpersonation Level.Secu rityImpers onation,
ref duplicateTokenHandle);
if (!isOkay)
{
int lastWin32Error = Marshal.GetLastWin32Error( );
int lastError = GetLastError();
CloseHandle(existingTokenH andle);
throw new Exception("DuplicateToken Failed: " + lastWin32Error + " - " + lastError);
}
else
{
// create an identity from the token
WindowsIdentity newId = new WindowsIdentity(duplicateT okenHandle );
WindowsImpersonationContex t impersonatedUser = newId.Impersonate();
return impersonatedUser;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
//free all handles
if (existingTokenHandle != IntPtr.Zero)
{
CloseHandle(existingTokenH andle);
}
if (duplicateTokenHandle != IntPtr.Zero)
{
CloseHandle(duplicateToken Handle);
}
}
}
/// <summary>impersonates a user</summary>
/// <param name="sUsername">domain\na me of the user account</param>
/// <param name="sPassword">the user's password</param>
/// <returns>the new WindowsImpersonationContex t</returns >
public WindowsImpersonationContex t ImpersonateUser(String username, String password)
{
//define the handles
IntPtr existingTokenHandle = IntPtr.Zero;
IntPtr duplicateTokenHandle = IntPtr.Zero;
String domain;
if (username.IndexOf("\\") > 0)
{
//split domain and name
String[] splitUserName = username.Split('\\');
domain = splitUserName[0];
username = splitUserName[1];
}
else
{
//domain = String.Empty;
domain = "qatar";
}
bool isOkay = true;
try
{
//get a security token
isOkay = LogonUser(username, domain, password,
(int)LogonTypes.LOGON32_LO GON_INTERA CTIVE, (int)LogonTypes.LOGON32_PR OVIDER_DEF AULT,
ref existingTokenHandle);
if (!isOkay)
{
int lastWin32Error = Marshal.GetLastWin32Error( );
int lastError = GetLastError();
throw new Exception("LogonUser Failed: " + lastWin32Error + " - " + lastError);
}
// copy the token
isOkay = DuplicateToken(existingTok enHandle,
(int)SecurityImpersonation Level.Secu rityImpers onation,
ref duplicateTokenHandle);
if (!isOkay)
{
int lastWin32Error = Marshal.GetLastWin32Error( );
int lastError = GetLastError();
CloseHandle(existingTokenH andle);
throw new Exception("DuplicateToken Failed: " + lastWin32Error + " - " + lastError);
}
else
{
// create an identity from the token
WindowsIdentity newId = new WindowsIdentity(duplicateT okenHandle );
WindowsImpersonationContex t impersonatedUser = newId.Impersonate();
return impersonatedUser;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
//free all handles
if (existingTokenHandle != IntPtr.Zero)
{
CloseHandle(existingTokenH andle);
}
if (duplicateTokenHandle != IntPtr.Zero)
{
CloseHandle(duplicateToken Handle);
}
}
}
}
//////////////////////////
public class LogonUtility
{
private static string IMPERSONATED_USER;
private static string IMPERSONATED_PASS;
public LogonUtility()
{
IMPERSONATED_USER = IMPERSONATED_PASS = "";
}
public LogonUtility(string user, string pass)
{
IMPERSONATED_USER = user;
IMPERSONATED_PASS = pass;
}
//import LSA functions
[DllImport("advapi32.dll")
private static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken
);
[DllImport("advapi32.dll")
private static extern bool DuplicateToken(
IntPtr ExistingTokenHandle,
int ImpersonationLevel,
ref IntPtr DuplicateTokenHandle
);
[DllImport("kernel32.dll")
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("advapi32.dll")
private static extern bool ImpersonateLoggedOnUser(In
[DllImport("kernel32.dll")
private static extern int GetLastError();
//enum impersonation levels an logon types
private enum SecurityImpersonationLevel
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
private enum LogonTypes
{
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEA
LOGON32_LOGON_NEW_CREDENTI
}
public WindowsImpersonationContex
{
//define the handles
IntPtr existingTokenHandle = IntPtr.Zero;
IntPtr duplicateTokenHandle = IntPtr.Zero;
string domain = "yourDomain";
string username = IMPERSONATED_USER;
string password = IMPERSONATED_PASS;
bool isOkay = true;
try
{
//get a security token
isOkay = LogonUser(username, domain, password,
(int)LogonTypes.LOGON32_LO
ref existingTokenHandle);
if (!isOkay)
{
int lastWin32Error = Marshal.GetLastWin32Error(
int lastError = GetLastError();
throw new Exception("LogonUser Failed: " + lastWin32Error + " - " + lastError);
}
// copy the token
isOkay = DuplicateToken(existingTok
(int)SecurityImpersonation
ref duplicateTokenHandle);
if (!isOkay)
{
int lastWin32Error = Marshal.GetLastWin32Error(
int lastError = GetLastError();
CloseHandle(existingTokenH
throw new Exception("DuplicateToken Failed: " + lastWin32Error + " - " + lastError);
}
else
{
// create an identity from the token
WindowsIdentity newId = new WindowsIdentity(duplicateT
WindowsImpersonationContex
return impersonatedUser;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
//free all handles
if (existingTokenHandle != IntPtr.Zero)
{
CloseHandle(existingTokenH
}
if (duplicateTokenHandle != IntPtr.Zero)
{
CloseHandle(duplicateToken
}
}
}
/// <summary>impersonates a user</summary>
/// <param name="sUsername">domain\na
/// <param name="sPassword">the user's password</param>
/// <returns>the new WindowsImpersonationContex
public WindowsImpersonationContex
{
//define the handles
IntPtr existingTokenHandle = IntPtr.Zero;
IntPtr duplicateTokenHandle = IntPtr.Zero;
String domain;
if (username.IndexOf("\\") > 0)
{
//split domain and name
String[] splitUserName = username.Split('\\');
domain = splitUserName[0];
username = splitUserName[1];
}
else
{
//domain = String.Empty;
domain = "qatar";
}
bool isOkay = true;
try
{
//get a security token
isOkay = LogonUser(username, domain, password,
(int)LogonTypes.LOGON32_LO
ref existingTokenHandle);
if (!isOkay)
{
int lastWin32Error = Marshal.GetLastWin32Error(
int lastError = GetLastError();
throw new Exception("LogonUser Failed: " + lastWin32Error + " - " + lastError);
}
// copy the token
isOkay = DuplicateToken(existingTok
(int)SecurityImpersonation
ref duplicateTokenHandle);
if (!isOkay)
{
int lastWin32Error = Marshal.GetLastWin32Error(
int lastError = GetLastError();
CloseHandle(existingTokenH
throw new Exception("DuplicateToken Failed: " + lastWin32Error + " - " + lastError);
}
else
{
// create an identity from the token
WindowsIdentity newId = new WindowsIdentity(duplicateT
WindowsImpersonationContex
return impersonatedUser;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
//free all handles
if (existingTokenHandle != IntPtr.Zero)
{
CloseHandle(existingTokenH
}
if (duplicateTokenHandle != IntPtr.Zero)
{
CloseHandle(duplicateToken
}
}
}
}
Cool b-) Thanks :D
Bob
Bob
I am curious if they are saying the WMI methodology does not work. I am also curious of any code access implications for all of these pinvokes.
btw: you might want to "adjust" that logon utility class ... it has some problems (try the following)
LogonUtility foo = new LogonUtility("test", "test");
LogonUtility bar = new LogonUtility("test2", "test2");
foo.ImpersonateUser(); //logs in as test2
btw: you might want to "adjust" that logon utility class ... it has some problems (try the following)
LogonUtility foo = new LogonUtility("test", "test");
LogonUtility bar = new LogonUtility("test2", "test2");
foo.ImpersonateUser(); //logs in as test2