C# - How to Authenticate with server dinamically - c#

I need to check if service "Advice" has its status running on said server. I made a method that does just that:
public static bool CheckServicesFromServer(string pServicos)
{
ServiceController service = new ServiceController();
List<string> Servicos = pServicos.Split(',').Select(p => p.Trim()).ToList();
if (Config.BaseLogin == BasesSistema.QualityLogin)
service.MachineName = "quality";
if (Config.BaseLogin == BasesSistema.TS02Login)
service.MachineName = "ts02";
if (Config.BaseLogin == BasesSistema.TS03Login)
service.MachineName = "ts03";
if (Config.BaseLogin == BasesSistema.LocalHost)
service.MachineName = Environment.MachineName;
try
{
foreach (var item in Servicos)
{
service.ServiceName = item;
if ((service.Status.Equals(ServiceControllerStatus.Stopped)) || (service.Status.Equals(ServiceControllerStatus.StopPending)))
{
File.AppendAllText(StatusLog.StatusLocation, "O servico " + service.ServiceName + " está parado. a Regra não será gerada.");
throw new Exception();
}
if (service.Status.Equals(ServiceControllerStatus.Running))
{
File.AppendAllText(StatusLog.StatusLocation, "O serviço " + service.ServiceName + "está rodando perfeitamente.");
}
}
}
catch (Exception e)
{
Log.WriteErrorLog(e.Message);
throw new Exception(e.Message);
}
return true;
}
The thing is, when I run the test, it says "Access Denied", and throws an exception. When I add my user (The user from the computer which is running the application) as an Adm at the server, it runs fine.
Is there a way to authenticate my computer so it can have permission to access the server and check its service status?

Thanks to Krik, I found the solution. It's as simple as addind this class:
using System;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Security.Permissions;
public class ImpersonateUser
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
private static IntPtr tokenHandle = new IntPtr(0);
private static WindowsImpersonationContext impersonatedUser;
// If you incorporate this code into a DLL, be sure to demand that it
// runs with FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void Impersonate(string domainName, string userName, string password)
{
//try
{
// Use the unmanaged LogonUser function to get the user token for
// the specified user, domain, and password.
const int LOGON32_PROVIDER_DEFAULT = 0;
// Passing this parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
tokenHandle = IntPtr.Zero;
// ---- Step - 1
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(
userName,
domainName,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref tokenHandle); // tokenHandle - new security token
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
// ---- Step - 2
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
// ---- Step - 3
{
impersonatedUser = newId.Impersonate();
}
}
}
// Stops impersonation
public void Undo()
{
impersonatedUser.Undo();
// Free the tokens.
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
internal void Impersonate()
{
throw new NotImplementedException();
}
}
And I Just had to call it like this:
public static bool CheckServicesFromServer(string pServicos)
{
ImpersonateUser Iu = new ImpersonateUser();
ServiceController service = new ServiceController();
List<string> Servicos = pServicos.Split(',').Select(p => p.Trim()).ToList();
if (Config.BaseLogin == BasesSistema.QualityLogin)
service.MachineName = "quality";
if (Config.BaseLogin == BasesSistema.TS02Login)
service.MachineName = "ts02";
if (Config.BaseLogin == BasesSistema.TS03Login)
service.MachineName = "ts03";
if (Config.BaseLogin == BasesSistema.LocalHost)
service.MachineName = Environment.MachineName;
Iu.Impersonate(Config.Dominio, Config.LoginMaster, Config.SenhaMaster);
try
{
foreach (var item in Servicos)
{
service.ServiceName = item;
if ((service.Status.Equals(ServiceControllerStatus.Stopped)) || (service.Status.Equals(ServiceControllerStatus.StopPending)))
{
Flag = true;
File.AppendAllText(StatusLog.StatusLocation, "O servico " + service.ServiceName + " está parado. a Regra não será gerada. <br />");
throw new Exception();
}
if (service.Status.Equals(ServiceControllerStatus.Running))
{
File.AppendAllText(StatusLog.StatusLocation, "O serviço " + service.ServiceName + " está rodando perfeitamente. <br />");
}
}
Iu.Undo();
}
catch
{
Iu.Undo();
Log.WriteErrorLog("Não é possível abrir o Gerenciador de Controle de Serviços no Computador '" + service.MachineName + "'. <br />");
return false;
}
return true;
}
My Config Class holds the information of the Domain, User and PassWord, and it worked perfectly.

Related

c# IDsObjectPickerCredentials fail

I have to set credentials to Active-Directory-Object-Picker (IDsObjectPicker) on c#.
But I can't force the IDsObjectPickerCredentials to work.
I've made same on c++ (msdn example) and it works good.
I used "headers" from here ComInterop.cs and StructsFlags.cs
Please tell me what I'm doing wrong. How to call IDsObjectPickerCredentials.SetCredentials
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Tulpep.ActiveDirectoryObjectPicker;
namespace cred
{
class Program
{
static void Main(string[] args)
{
string szTargetComputer = #"10.0.9.115";
string szUser = #"TST\test";
string szPassword = #"123qazWSX";
DSObjectPicker picker = new DSObjectPicker();
IDsObjectPicker ipicker = (IDsObjectPicker)picker;
int res = InitObjectPicker(ipicker, szTargetComputer);
if (res == (int)HRESULT.S_OK)
{
try
{
// !!! HERE !!!
IDsObjectPickerCredentials cred = (ipicker as IDsObjectPickerCredentials);
res = cred.SetCredentials(szUser, szPassword);
// c++ like variant
// res = InitCredentials(ipicker, szUser, szPassword);
if (res != (int)HRESULT.S_OK) Console.WriteLine("SetCredentials Fail : 0x{0}", res.ToString("X4")); // On Win32 I get 0x80070057 - looks like E_INVALIDARG
IntPtr hwndParent = Process.GetCurrentProcess().MainWindowHandle;
IDataObject dataObj = null;
int hresult = ipicker.InvokeDialog(hwndParent, out dataObj);
Console.WriteLine(hresult == (int)HRESULT.S_OK ? "OK" : "Cancel");
Console.ReadKey();
}
finally
{
Marshal.ReleaseComObject(ipicker);
}
}
}
[ComImport, Guid("E2D3EC9B-D041-445A-8F16-4748DE8FB1CF"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IDsObjectPickerCredentials
{
[PreserveSig()]
int SetCredentials(
[In, MarshalAs(UnmanagedType.LPWStr)] string szUserName,
[In, MarshalAs(UnmanagedType.LPWStr)] string szPassword);
}
static int InitObjectPicker(IDsObjectPicker ipicker, string szTargetComputer)
{
int res = (int)HRESULT.S_FALSE;
DSOP_SCOPE_INIT_INFO[] aScopeInit = new DSOP_SCOPE_INIT_INFO[1];
DSOP_INIT_INFO InitInfo = new DSOP_INIT_INFO();
aScopeInit[0].cbSize = (uint)Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO));
aScopeInit[0].flType =
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN |
DSOP_SCOPE_TYPE_FLAGS.DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN;
aScopeInit[0].FilterFlags.Uplevel.flBothModes =
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_COMPUTERS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_USERS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_BUILTIN_GROUPS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_INCLUDE_ADVANCED_VIEW;
aScopeInit[0].FilterFlags.flDownlevel =
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_COMPUTERS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_USERS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_BUILTIN_GROUPS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_WELL_KNOWN_PRINCIPALS |
DSOP_FILTER_FLAGS_FLAGS.DSOP_FILTER_INCLUDE_ADVANCED_VIEW;
IntPtr refScopeInitInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO)) * aScopeInit.Length);
try
{
// Marshal structs to pointers
for (int index = 0; index < aScopeInit.Length; index++)
{
Marshal.StructureToPtr(aScopeInit[index], (IntPtr)((int)refScopeInitInfo + index * Marshal.SizeOf(typeof(DSOP_SCOPE_INIT_INFO))), false);
}
InitInfo.cbSize = (uint)Marshal.SizeOf(typeof(DSOP_INIT_INFO));
InitInfo.cDsScopeInfos = (uint)aScopeInit.Length; //sizeof(aScopeInit)/sizeof(DSOP_SCOPE_INIT_INFO);
InitInfo.aDsScopeInfos = refScopeInitInfo;
InitInfo.flOptions = DSOP_INIT_INFO_FLAGS.DSOP_FLAG_MULTISELECT;
InitInfo.pwzTargetComputer = szTargetComputer;
res = ipicker.Initialize(ref InitInfo);
}
finally
{
Marshal.FreeHGlobal(refScopeInitInfo);
}
return res;
}
static int InitCredentials(IDsObjectPicker ipicker, string User, string Password)
{
IntPtr ptr = IntPtr.Zero;
Guid IID_IDsObjectPickerCredentials = new Guid("E2D3EC9B-D041-445A-8F16-4748DE8FB1CF");
IntPtr pIUnk = Marshal.GetIUnknownForObject(ipicker);
int hr = Marshal.QueryInterface(pIUnk, ref IID_IDsObjectPickerCredentials, out ptr);
if (hr == HRESULT.S_OK)
{
try
{
IDsObjectPickerCredentials cred = (IDsObjectPickerCredentials)Marshal.GetObjectForIUnknown(ptr);
hr = cred.SetCredentials(User, Password);
if (hr != HRESULT.S_OK)
{
System.Diagnostics.Debugger.Break(); // Fail
return (int)HRESULT.S_FALSE;
}
}
catch (Exception ex)
{
return (int)HRESULT.S_FALSE;
}
finally
{
Marshal.Release(ptr);
}
}
return (int)HRESULT.S_OK;
}
}
}
The IDsObjectPickerCredentials interface derives from the IDsObjectPicker. Your sample actually calls the Initialize method with a username and a password instead of SetCredentials.
Here is a correct declaration:
[ComImport, Guid("e2d3ec9b-d041-445a-8f16-4748de8fb1cf"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IDsObjectPickerCredentials
{
[PreserveSig]
int Initialize(ref DSOP_INIT_INFO pInitInfo);
[PreserveSig]
int InvokeDialog(IntPtr HWND, out IDataObject lpDataObject);
[PreserveSig]
int SetCredentials(string userName, string password);
}
Please note that instead of deriving from the IDsObjectPicker, the code replicates its methods, in the same order. This is necessary for .NET COM Interop.
You don't need that manual QueryInterface/Release calls, var cred = (IDsObjectPickerCredentials)iobjectpicker; is enough.
Also I found that the SetCredentials should be called before the Initialize method.

C# Access a local folder with admin account credentials

I have two user accounts in my computer
User 1 (regular user)
Admin
Now I have folder "e:\Folder1" for which only Admin account has full access. User ! cannot access the folder.
I have a WPF Application Where It would run only within the User 1 account. I want the user 1 to user the wpf application to access "Folder1".
I want to know how to do it using C#.
I tried the following it doesnt work.
NetworkCredential theNetworkCredential = new NetworkCredential(#"admin", "pass");
CredentialCache theNetCache = new CredentialCache();
theNetCache.Add(new Uri(#"E:\SDAVideo"), "Basic", theNetworkCredential);
string[] theFolders = Directory.GetDirectories(#"E:\SDAVideo");
Here is what I have tried.
Using following code I am able to get the Windows of Identity of Admin user account
SafeTokenHandle safeTokenHandle;
try
{
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser("admin", "", "pass",
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeTokenHandle);
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Debug.Write("\nLogonUser failed with error code : " + ret);
throw new System.ComponentModel.Win32Exception(ret);
}
using (safeTokenHandle)
{
Debug.Write("\nDid LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
Debug.Write("\nValue of Windows NT token: " + safeTokenHandle);
// Check the identity.
Debug.Write("\nBefore impersonation: "
+ WindowsIdentity.GetCurrent().Name);
Debug.Write("\nWriteAccess before: " + DirectoryHasPermission(#"E:\SDAVideo", WindowsIdentity.GetCurrent(), FileSystemRights.Write));
// Use the token handle returned by LogonUser.
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
{
// Check the identity.
Debug.Write("\nAfter impersonation: "
+ WindowsIdentity.GetCurrent().Name);
AccessFolder(WindowsIdentity.GetCurrent(), #"E:\SDAVideo");
//Debug.Write("\nWriteAccess after: " + DirectoryHasPermission(#"E:\SDAVideo", WindowsIdentity.GetCurrent(), FileSystemRights.Write));
}
// Releasing the context object stops the impersonation
// Check the identity.
Debug.Write("\nAfter closing the context: " + WindowsIdentity.GetCurrent().Name);
}
}
catch (Exception ex)
{
Debug.Write("\n1" + ex.ToString());
}
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
{
}
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
public static bool DirectoryHasPermission(string DirectoryPath, WindowsIdentity identity, FileSystemRights AccessRight)
{
//if (string.IsNullOrEmpty(DirectoryPath)) return false;
try
{
AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
//WindowsIdentity identity = WindowsIdentity.GetCurrent();
Debug.Write("\nUSER: " + identity.Name);
foreach (FileSystemAccessRule rule in rules)
{
if (identity.Groups.Contains(rule.IdentityReference))
{
if ((AccessRight & rule.FileSystemRights) == AccessRight)
{
if (rule.AccessControlType == AccessControlType.Allow)
return true;
}
}
}
}
catch (Exception ex)
{
Debug.Write("\n2 " + ex.ToString());
}
return false;
}
public static void AccessFolder(WindowsIdentity identity, string DirectoryPath)
{
try
{
Debug.Write("\nUSER: " + identity.Name);
DirectoryInfo myDirectoryInfo = new DirectoryInfo(DirectoryPath);
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(identity.Name, FileSystemRights.Write, AccessControlType.Allow));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
string pathString = System.IO.Path.Combine(DirectoryPath, "test.txt");
if (!System.IO.File.Exists(pathString))
{
using (System.IO.FileStream fs = System.IO.File.Create(pathString))
{
for (byte i = 0; i < 100; i++)
{
fs.WriteByte(i);
}
}
}
}
catch (Exception ex)
{
Debug.Write("\n3 " + ex.ToString());
}
}
Error I get as follows
System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.
System.InvalidOperationException: Method failed with unexpected error code 1346.
All of these failed, Only thing I am able to do is successfully get the Admin user windows identity.
Now with that I need to solve the two issues
1. How to check if app has write access using the windows identity of the admin
2. If so how to write something into the folder.
Try that:
using System;
using System.IO;
using System.Security.AccessControl;
namespace MyWpfApplication
{
public class AccessRules
{
private void SetAccessRuleForCurrentUser()
{
DirectoryInfo myDirectoryInfo = new DirectoryInfo(#"e:\Folder1");
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, FileSystemRights.Read, AccessControlType.Allow));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
}
}

Availability check of a network path with credentials

In C# I would like test the availability of a network path, what authentication needed. I am using the following function:
private bool TestDrive(string path,string userName,string domain, string password)
{
if (userName == "")
return true;
//else authentication needed
try
{
using (new CImpersonator(userName, domain, password))
{
using (FileStream fs = File.Create(path+"\\1.txt"))
{ }
File.Delete(path + "\\1.txt");
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public CImpersonator(
string userName,
string domainName,
string password,
bool checkUserName = true)
{
//Check if user exists
if (checkUserName && !CCheckUsername.UserExists(userName))
return;
this.ImpersonateValidUser(userName, domainName, password);
}
private void ImpersonateValidUser(
string userName,
string domain,
string password)
{
WindowsIdentity tempWindowsIdentity = null;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
try
{
if (RevertToSelf())
{
if (LogonUser(
userName,
domain,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref token) != 0)
{
if (DuplicateToken(token, (int)System.Management.ImpersonationLevel.Impersonate, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
_impersonationContext = tempWindowsIdentity.Impersonate();
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = (IntPtr)System.Diagnostics.Process.GetCurrentProcess().Id;
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ALL_ACCESS, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
retVal = LookupPrivilegeValue(null, SE_SYSTEMTIME_NAME, ref tp.Luid);
retVal = AdjustTokenPrivileges(token, false, ref tp, Marshal.SizeOf(typeof(TokPriv1Luid)), IntPtr.Zero, IntPtr.Zero);
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
}
}
The problem is that when I use this for test a network path in an another domain, then the TestDrive function returns false. Of course the domain, username and password are good, the user rights are good.
It is strange that the function works good, when I test it in the same domain.
Thank you for all ideas!
I would first try the following:
Folder.Exists(String Path);
This will however only work on a Path where you have read access, so if the network path isn't mapped with the credentials this method will return false, but you can use the above method and if it returns false, map the network path (this question answersthe how-to on that) with those different credentials
and then perform the:
Folder.Exists(String Path);
once more. Afterwards you can disconnect the network drive again.

Impersonation and DirectoryEntry

I am impersonating a user account successfully, but I am not able to use the impersonated account to bind to AD and pull down a DirectoryEntry.
The below code outputs:
Before impersonation I am: DOMAIN\user
After impersonation I am: DOMAIN\admin
Error: C:\Users\user\ADSI_Impersonation\bin\Debug\ADSI_Impersonation.exe
samaccountname:
My issue seems similar to:
How to use the System.DirectoryServices namespace in ASP.NET
I am obtaining a primary token. I understand that I need to use delegation to use the impersonated token on a remote computer. I confirmed that the account doesn't have the flag checked "Account is sensitive and cannot be delegated". I also confirmed that the Local Group Policy and Domain Group Policies are not preventing delegation:
Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment\
What am I missing?
Thanks!
using System;
using System.DirectoryServices;
using System.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Runtime.ConstrainedExecution;
namespace ADSI_Impersonation
{
class Program
{
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
static void Main(string[] args)
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
string userName = "admin#domain.com";
string password = "password";
Console.WriteLine("Before impersonation I am: " + WindowsIdentity.GetCurrent().Name);
SafeTokenHandle safeTokenHandle;
try
{
bool returnValue = LogonUser(userName, null, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeTokenHandle);
if (returnValue)
{
WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
}
else
{
Console.WriteLine("Unable to create impersonatedUser.");
return;
}
}
catch (Exception e)
{
Console.WriteLine("Authentication error.\r\n" + e.Message);
}
Console.WriteLine("After impersonation I am: " + WindowsIdentity.GetCurrent().Name);
string OU = "LDAP://dc=domain,dc=com";
DirectoryEntry entry = new DirectoryEntry(OU);
entry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher mySearcher = new DirectorySearcher();
mySearcher.SearchRoot = entry;
mySearcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
mySearcher.PropertiesToLoad.Add("cn");
mySearcher.PropertiesToLoad.Add("samaccountname");
string cn = "fistname mi. lastname";
string samaccountname = "";
try
{
// Create the LDAP query and send the request
mySearcher.Filter = "(cn=" + cn + ")";
SearchResultCollection searchresultcollection = mySearcher.FindAll();
DirectoryEntry ADentry = searchresultcollection[0].GetDirectoryEntry();
Console.WriteLine("samaccountname: " + ADentry.Properties["samaccountname"].Value.ToString());
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.WriteLine("samaccountname: " + samaccountname);
Console.ReadLine();
}
}
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
{
}
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
}
Many .NET APIs do not take your manual impersonation into consideration, such as the LDAP queries you noticed. Therefore, you need to use the overloading constructors of DirectoryEntry instead,
http://msdn.microsoft.com/en-us/library/bw8k1as4.aspx
http://msdn.microsoft.com/en-us/library/wh2h7eed.aspx
Error (0x80004005): Unspecified error
I had the some problem connecting to the remote windows authenticated with the error Error (0x80004005): Unspecified error. I resolved as follows:
//Define path
//This path uses the full path of user authentication
String path = string.Format("WinNT://{0}/{1},user", server_address, username);
DirectoryEntry deBase = null;
try
{
//Try to connect with secure connection
deBase = new DirectoryEntry(path, username, _passwd, AuthenticationTypes.Secure);
//Connection test
//After test define the deBase with the parent of user (root container)
object nativeObject = deBase.NativeObject;
deBase = deBase.Parent;
}
catch (Exception ex)
{
//If an error occurred try without Secure Connection
try
{
deBase = new DirectoryEntry(path, username, _passwd);
//Connection test
//After test define the deBase with the parent of user (root container)
object nativeObject = deBase.NativeObject;
deBase = deBase.Parent;
nativeObject = deBase.NativeObject;
}
catch (Exception ex2)
{
//If an error occurred throw the error
throw ex2;
}
}
Hope that helps.
Helvio Junior
www.helviojunior.com.br
Instead of
DirectoryEntry entry = new DirectoryEntry(OU);
try
DirectoryEntry entry = new DirectoryEntry(OU, null, null, AuthenticationTypes.FastBind | AuthenticationTypes.Secure);

C# Service Status On Remote Machine

I'm an expert programmer, so therefore, I don't have a clue as to WTH I'm doing :)
On a serious note; no, I'm not expert by any means. I do have a problem though, and don't know how to fix it. The good thing is, I (think I) know what the problem is, and I'm hoping someone here can help.
Here's the synopsis of the problem. I am creating a form in C# that will do some server and database administration task for me. I have a button that when clicked is supposed to return the service status of "x" service on "y" server. The status is printed on the screen to a textbox.
Here's my code:
private void button2_Click(object sender, EventArgs e)
{
string fs = "Service X Status = ";
string mr = "Service A Status = ";
string qp = "Service B Status = ";
string sp = "Spooler Service Status = ";
ServiceController fssc = new ServiceController("xService", "yServer");
ServiceController mrsc = new ServiceController("aService", "yServer");
ServiceController qpsc = new ServiceController("bService", "yServer");
ServiceController spsc = new ServiceController("Spooler", "yServer");
try
{
txtGtwySts.AppendText(sp + spsc.Status.ToString());
txtGtwySts.AppendText(Environment.NewLine);
txtGtwySts.AppendText(fs + fssc.Status.ToString());
txtGtwySts.AppendText(Environment.NewLine);
txtGtwySts.AppendText(mr + mrsc.Status.ToString());
txtGtwySts.AppendText(Environment.NewLine);
txtGtwySts.AppendText(qp + qpsc.Status.ToString());
}
catch (Exception crap)
{
string msg = "";
int i;
for (i = 0; i < crap.Message.Count(); i++)
{
msg += "Error # " + i + " Message: " + crap.Message + "\n";
}
MessageBox.Show(msg);
MessageBox.Show(i.ToString());
}
}
I get exceptions, basically saying: Cannot Open "Service" on "Server." Since this is a remote server, I'm assuming this is a credential/security problem. I do NOT, however, have any problems with the Spooler service.
My question is...How can I pass userID and password to this server so that it will authenticate or runas so I can check the status of these services, it that is the problem. If someone doesnt think its the problem, then please inform me where I've went wrong :)
Finally figured it out...
Created a new class, and is shown below:
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Security.Permissions;
public class ImpersonateUser
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
private static IntPtr tokenHandle = new IntPtr(0);
private static WindowsImpersonationContext impersonatedUser;
// If you incorporate this code into a DLL, be sure to demand that it
// runs with FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void Impersonate(string domainName, string userName, string password)
{
//try
{
// Use the unmanaged LogonUser function to get the user token for
// the specified user, domain, and password.
const int LOGON32_PROVIDER_DEFAULT = 0;
// Passing this parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
tokenHandle = IntPtr.Zero;
// ---- Step - 1
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(
userName,
domainName,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref tokenHandle); // tokenHandle - new security token
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
// ---- Step - 2
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
// ---- Step - 3
{
impersonatedUser = newId.Impersonate();
}
}
}
// Stops impersonation
public void Undo()
{
impersonatedUser.Undo();
// Free the tokens.
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
}
}
and the original code that I posted is wrapped by:
ImpersonateUser iu = new ImpersonateUser();
iu.Impersonate("[domain]","[username]","[password]");
// code you want to execute as impersonated user.....
iu.Undo();

Categories