Search code examples
c#nas

Connection to NAS Server with Read/Write Check. Impersonation Fails


I'am working on a program which has to check if there is a connection to the NAS and if it's possible to write and read data from it. Checking the connection is not a problem.

I'am running on a Windows Server 2012 and know the credentials from the NAS. I tried impersonating with those credentials but this did not work. I'am always getting the same error. The user name or password is incorrect. But when I connection with the windows explorer with the same credentials it works.

This is my DLL Import and the necessary variables

[DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain,
    String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

// Variables
private IntPtr m_Token;
private WindowsImpersonationContext m_Context = null;
private string m_Domain;
private string m_Password;
private string m_Username;

m_Domain is different to the local domain

This is the actual Impersonation

            m_Token = IntPtr.Zero;
            bool logonSuccessfull = LogonUser(
               m_Username,
               m_Domain,
               m_Password,
               (int)LOGON32_TYPE_NETWORK,
               (int)LOGON32_PROVIDER_WINNT50,
               ref m_Token);
            if (logonSuccessfull == false)
            {
                int error = Marshal.GetLastWin32Error();
                throw new Win32Exception(error);
            }
            WindowsIdentity identity = new WindowsIdentity(m_Token);
            m_Context = identity.Impersonate();

LOGON32_TYPE_NETWORK is equal to 3, LOGON32_PROVIDER_WINNT50 is equal to 3

This code is executed with administrator rights.

This is the error which gets thrown:

System.ComponentModel.Win32Exception (0x80004005): The user name or password is incorrect

This error get's thrown at

if (logonSuccessfull == false)
{
     int error = Marshal.GetLastWin32Error();
     throw new Win32Exception(error);
}

Is there another way? Or do have to use other LogonType's or LogonProvider?

These I have also tried but also did not work for me.

private const int LOGON32_PROVIDER_DEFAULT = 0;
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_TYPE_NEW_CREDENTIALS = 9;

When using the LOGON32_TYPE_NEW_CREDENTIALS it doesn't throw an error but the impersonated user does not change at all.


Solution

  • I could solve the isse by using the Network Credentials and by using the mpr.dll

    [DllImport("mpr.dll")]
    private static extern int WNetAddConnection2(NetResource netResource,
         string password, string username, int flags);
    [DllImport("mpr.dll")]
         private static extern int WNetCancelConnection2(string name, int flags, bool force);
    [StructLayout(LayoutKind.Sequential)]
    public class NetResource
    {
      public ResourceScope Scope;
      public ResourceType ResourceType;
      public ResourceDisplaytype DisplayType;
      public int Usage;
      public string LocalName;
      public string RemoteName;
      public string Comment;
      public string Provider;
    }
    public enum ResourceScope : int
    {
      Connected = 1,
      GlobalNetwork,
      Remembered,
      Recent,
      Context
    };
    
    public enum ResourceType : int
    {
      Any = 0,
      Disk = 1,
      Print = 2,
      Reserved = 8,
    }
    
    public enum ResourceDisplaytype : int
    {
      Generic = 0x0,
      Domain = 0x01,
      Server = 0x02,
      Share = 0x03,
      File = 0x04,
      Group = 0x05,
      Network = 0x06,
      Root = 0x07,
      Shareadmin = 0x08,
      Directory = 0x09,
      Tree = 0x0a,
      Ndscontainer = 0x0b
    }
    
    void ConnectToNas(string username, string password, string networkName){
         NetworkCredential cred = new NetworkCredential(username, password);
    
         var netResource = new NetResource
         {
              Scope = ResourceScope.GlobalNetwork,
              ResourceType = ResourceType.Disk,
              DisplayType = ResourceDisplaytype.Share,
              RemoteName = networkName
         };
    
         var result = WNetAddConnection2(netResource, credentials.Password,userName,0);
    
         if (result != 0)
         {
              throw new Win32Exception(result, "Error while connection to NAS");
         }
    }
    
    

    For closing the connection:

    void CloseConnection(string networkName){
         WNetCancelConnection2(networkName, 0, true);
    }
    

    With this way I was able to connect to the NAS and check if it's readable and writeable by writing a file to it, reading it and afterwards deleting it.