Copying file to shared drive fails in ASP.net c# - c#

I have ASP.Net and C# application. I am uploading images to the site and store them in the C:\Images directory, which works fine. When I save images to the C:\Images folder and simultaneously copy (or some times move) to the shared drive, I use the shared drive physical address, which looks like \\192.xxx.x.xx\some folder\Images. This drive is mapped to the deployment server. I am using IIS hosting for the site.
The problem is with the shared drive copying. When I use the site from local machine (where the site is deployed) that copies the file to the shared drive. But when I use the site from another machine (other than the deployed server) that saves the image in C:\Images, but it won't copy the file to the shared drive.
Here's the code I'm using
**Loggedon method shows success in debug.
public static void CopytoNetwork(String Filename)
{
try
{
string updir = System.Configuration.ConfigurationManager.AppSettings["PhysicalPath"].ToString();
WindowsImpersonationContext impersonationContext = null;
IntPtr userHandle = IntPtr.Zero;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
String UserName = System.Configuration.ConfigurationManager.AppSettings["Server_UserName"].ToString();
String Password = System.Configuration.ConfigurationManager.AppSettings["server_Password"].ToString();
String DomainName = System.Configuration.ConfigurationManager.AppSettings["Server_Domain"].ToString();
bool loggedOn = LogonUser(UserName, DomainName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref userHandle);
try
{
File.Move(#"C:\Images\" + Filename, updir + "\\" + Filename);
}
catch (Exception)
{
}
finally
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
if (userHandle != IntPtr.Zero)
{
CloseHandle(userHandle);
}
}
}
catch (Exception)
{
}
}

You can set up an impersonated user class like this:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
public class ImpersonatedUser : IDisposable
{
IntPtr userHandle;
WindowsImpersonationContext impersonationContext;
public ImpersonatedUser(string user, string domain, string password)
{
userHandle = IntPtr.Zero;
bool loggedOn = LogonUser(
user,
domain,
password,
LogonType.Interactive,
LogonProvider.Default,
out userHandle);
if (!loggedOn)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Begin impersonating the user
impersonationContext = WindowsIdentity.Impersonate(userHandle);
}
public void Dispose()
{
if (userHandle != IntPtr.Zero)
{
CloseHandle(userHandle);
userHandle = IntPtr.Zero;
impersonationContext.Undo();
}
}
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
LogonType dwLogonType,
LogonProvider dwLogonProvider,
out IntPtr phToken
);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hHandle);
enum LogonType : int
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
NetworkCleartext = 8,
NewCredentials = 9,
}
enum LogonProvider : int
{
Default = 0,
}
}
When you need to do the file copying you do it like this:
using (new ImpersonatedUser(<UserName>, <UserDomainName>, <UserPassword>))
{
DoYourFileCopyLogic();
}

Related

C# Windows Service can't access to network drive [duplicate]

I need to be able to programmatically authenticate when trying to read and write files on a remote computer in a non-domain environment.
When you type a command into the Windows RUN prompt that is similar to \\targetComputer\C$\targetFolder or \\targetComputer\admin$, where the targetComputer is NOT on a domain, you will be prompted to enter a username and password. Once you enter the username and password, you have full access to the remote folder.
How can I accomplish this authentication programmatically in C#?
I've tried..
--Impersonation, but it appears to only work in a domain environment.
--CMDKEY.exe, but it also seems to only work in a domain environment.
There must be a way to do this, but I have searched high and low with no luck so far. Maybe I'm just looking for the wrong thing? I'm sure I'm not the first to have this question. Any help would be greatly appreciated.
Thanks!
EDIT :
I think I just found a different SO posting that answers my question: Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials
I will work with that for now and see where it gets me.
Thanks!
Impersonation works with Peer/LAN network as well. I got your typical home network with some machines on default "Workgroup" and some on a named one if I remembered doing it on the install.
Here is the code I use from my IIS server app to access files on my other computer (without having to have the same user and password on both machines involved, copied from somewhere and modified for my use):
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.ComponentModel;
/// <summary>
/// Class to impersonate another user. Requires user, pass and domain/computername
/// All code run after impersonationuser has been run will run as this user.
/// Remember to Dispose() afterwards.
/// </summary>
public class ImpersonateUser:IDisposable {
private WindowsImpersonationContext LastContext = null;
private IntPtr LastUserHandle = IntPtr.Zero;
#region User Impersonation api
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool ImpersonateLoggedOnUser(int Token);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool DuplicateToken(IntPtr token, int impersonationLevel, ref IntPtr duplication);
[DllImport("kernel32.dll")]
public static extern Boolean CloseHandle(IntPtr hObject);
public const int LOGON32_PROVIDER_DEFAULT = 0;
public const int LOGON32_PROVIDER_WINNT35 = 1;
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_LOGON_NETWORK = 3;
public const int LOGON32_LOGON_BATCH = 4;
public const int LOGON32_LOGON_SERVICE = 5;
public const int LOGON32_LOGON_UNLOCK = 7;
public const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;// Win2K or higher
public const int LOGON32_LOGON_NEW_CREDENTIALS = 9;// Win2K or higher
#endregion
public ImpersonateUser(string username, string domainOrComputerName, string password, int nm = LOGON32_LOGON_NETWORK) {
IntPtr userToken = IntPtr.Zero;
IntPtr userTokenDuplication = IntPtr.Zero;
bool loggedOn = false;
if (domainOrComputerName == null) domainOrComputerName = Environment.UserDomainName;
if (domainOrComputerName.ToLower() == "nt authority") {
loggedOn = LogonUser(username, domainOrComputerName, password, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, out userToken);
} else {
loggedOn = LogonUser(username, domainOrComputerName, password, nm, LOGON32_PROVIDER_DEFAULT, out userToken);
}
WindowsImpersonationContext _impersonationContext = null;
if (loggedOn) {
try {
// Create a duplication of the usertoken, this is a solution
// for the known bug that is published under KB article Q319615.
if (DuplicateToken(userToken, 2, ref userTokenDuplication)) {
// Create windows identity from the token and impersonate the user.
WindowsIdentity identity = new WindowsIdentity(userTokenDuplication);
_impersonationContext = identity.Impersonate();
} else {
// Token duplication failed!
// Use the default ctor overload
// that will use Mashal.GetLastWin32Error();
// to create the exceptions details.
throw new Win32Exception();
}
} finally {
// Close usertoken handle duplication when created.
if (!userTokenDuplication.Equals(IntPtr.Zero)) {
// Closes the handle of the user.
CloseHandle(userTokenDuplication);
userTokenDuplication = IntPtr.Zero;
}
// Close usertoken handle when created.
if (!userToken.Equals(IntPtr.Zero)) {
// Closes the handle of the user.
CloseHandle(userToken);
userToken = IntPtr.Zero;
}
}
} else {
// Logon failed!
// Use the default ctor overload that
// will use Mashal.GetLastWin32Error();
// to create the exceptions details.
throw new Win32Exception();
}
if (LastContext == null) LastContext = _impersonationContext;
}
public void Dispose() {
LastContext.Undo();
LastContext.Dispose();
}
}
The specific code I found out worked after a bit of trying was this:
using (var impersonation = new ImpersonateUser("OtherMachineUser", "OtherMachineName", "Password", LOGON32_LOGON_NEW_CREDENTIALS))
{
var files = System.IO.Directory.GetFiles("\\OtherMachineName\fileshare");
}

Accessing Third Party Network drive when using Azure Websites

I am having problems trying to read a file that is stored on a network drive when hosting my website/request on a azure website.
The code works testing on a local machine and it also works on a Dedicated server that we have with another client and have full control of but it gets the following error when we try to read the file.
Access to the path '\xxx.xxx.xxx.xxx\abc\abc.xml' is denied.
I wanted to know if Azure was locked down to prevent this behaviour that I didn't know about. Maybe ports closed or something.
The code I am using
if (impersonate.impersonateValidUser("username", "domain.com", "password"))
{
message = "impersonate ok";
if (!System.IO.File.Exists(file))
{
message = "no file";
impersonate.undoImpersonation();
}
using (StreamReader reader = File.OpenText(file))
{
message = "";
XmlSerializer deserializer = new XmlSerializer(typeof(TextModeSchema));
schema = (TextModeSchema)deserializer.Deserialize(reader);
reader.Close();
}
}
which is using a basic Impersonate class that we use in alot of places
public class Impersonate : IDisposable
{
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_LOGON_NETWORK = 3;
public const int LOGON32_LOGON_BATCH = 4;
public const int LOGON32_LOGON_SERVICE = 5;
public const int LOGON32_LOGON_UNLOCK = 7;
public const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
public const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
public const int LOGON32_PROVIDER_DEFAULT =0;
public const int LOGON32_PROVIDER_WINNT35 =1;
public const int LOGON32_PROVIDER_WINNT40 =2;
public const int LOGON32_PROVIDER_WINNT50 = 3;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
public bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
public void undoImpersonation()
{
impersonationContext.Undo();
}
public void Dispose()
{
impersonationContext.Undo();
GC.Collect();
}
}
If this is not allowed on azure, does anyone know of a way we can get around it without having to set up a full Virtual machine? I would like to keep with a azure website/webapp ideally.
Is this on a web role, worker role or a web application? I know that in case of a role, the remote host in your scenario has to be on the same private network than you role (It may also be true for a web app). Also, we had a similar scenario where we decided to use Azure Files which allows mounting shares on a role which you might want to try. http://blogs.msdn.com/b/windowsazurestorage/archive/2014/05/12/introducing-microsoft-azure-file-service.aspx

How to logon programmatically on a Windows machine

It is possible to use the logonuser function for logging onto a domain.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
I want to logon programatically from C# onto a windows machine which is not part of any domain. How to achieve this?
I am using the following Program to logon :
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
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);
internal void validateusercredentials(string username, string password, string hostname)
{
assert.isnotnull(username);
intptr tokenhandle = new intptr(0);
windowsidentity windowsid = null;
try
{
const int logon32_provider_default = 0;
const int logon32_logon_network = 3;
tokenhandle = intptr.zero;
bool success = logonuser(username, ".", password, logon32_logon_network,
logon32_provider_default, ref tokenhandle);
console.writeline("the return value of logon user is " + success);
if (!success)
{
int lastwindowserror = marshal.getlastwin32error();
if (lastwindowserror == error_logon_failure)
{
string message = string.format("invalid credentials supplied for user {0}", username);
console.writeline(lastwindowserror);
throw new invalidcredentialexception(message);
}
}
}
catch (exception e)
{
console.writeline(e.message);
trace.traceerror(e.message);
throw;
}
finally
{
if (tokenhandle != intptr.zero)
{
closehandle(tokenhandle);
}
if (windowsid != null)
{
windowsid.dispose();
windowsid = null;
}
}
}
If the machine is not part of your domain, you cannot use your domain credentials.
If you have a local account, you can instead use the local name of the computer as domain name and your local user and password as user and password.

connection one time to network Drive when Creating files with Impersonator

I have to create many files in Network drive with specified user.
I used this answer to connect different user
I use Impersonator Class :
public class Impersonator : IDisposable
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
[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 IntPtr token = IntPtr.Zero;
private WindowsImpersonationContext impersonated;
private readonly string _ErrMsg = "";
public bool IsImpersonating
{
get { return (token != IntPtr.Zero) && (impersonated != null); }
}
public string ErrMsg
{
get { return _ErrMsg; }
}
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public Impersonator(string userName, string password, string domain)
{
StopImpersonating();
bool loggedOn = LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token);
if (!loggedOn)
{
_ErrMsg = new System.ComponentModel.Win32Exception().Message;
return;
}
WindowsIdentity identity = new WindowsIdentity(token);
impersonated = identity.Impersonate();
}
private void StopImpersonating()
{
if (impersonated != null)
{
impersonated.Undo();
impersonated = null;
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
token = IntPtr.Zero;
}
}
public void Dispose()
{
StopImpersonating();
}
}
and the code :
using (Impersonator impersonator = new Impersonator("UserName", "UserPwd", "UserDomaine"))
{
if (!Directory.Exists("Z:\\")) // check if Network drive exist
{
NetworkDrive drive = new NetworkDrive
{
ShareName = #"\\IP\Partage",
LocalDrive = "Z",
Force = true
};
drive.MapDrive(#"UserDomaine\UserName", "UserPwd");
}
File.Create(#"Z:\Log\FileName.txt");
}
But in this case I found that the code Map the drive every time that I have to create a file or update it!! And I have a lot of work with this function.
There’s a solution to not map it every time?
I tried to Map the driver in with this user in opening of application but same problem.
I think you don't need to map the drive. After impersonating you can just create the file directly using the network drive and it will create the file as impersonated user.
using (Impersonator impersonator = new Impersonator("UserName", "UserPwd", "UserDomaine"))
{
File.Create(#"\\IP\Partage\Log\FileName.txt");
}
Try not to use Using block. declare Impersonator as global static variable.

Open a shared file under another user and domain?

I have a C# console application that needs to read a shared file on a machine in another domain.
When the application tries to access the file an exception occurs as the local user does not have permission to access the shared resource.
Currently I overcome this problem manually by open the shared folder from the run and put the username and password into the windows authentication dialog then run the application.
How can I do it programmatically?
a) p/invoke LogonUser with LOGON32_LOGON_NEW_CREDENTIALS and create a new WindowsIdentity with the new token, then use normal file access.
b) p/invoke WNetAddConnection3. Be advised that this makes your remote share accessible to every other process on your machine.
c) WMI via System.Management and CIM_DataFile; you won't even need p/invoke. System.Management lets you specify credentials for remote machine.
I used the point "a" as Anton suggested, I developed two versions for one class, the first one using the Win32 APIs, and the second uses the WindowsIdentity class.
Version 1:
class UserImpersonation : IDisposable
{
[DllImport("advapi32.dll")]
public static extern int LogonUser(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
WindowsImpersonationContext wic;
string _userName;
string _domain;
string _passWord;
public UserImpersonation(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
public bool ImpersonateValidUser()
{
WindowsIdentity wi;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUser(_userName, _domain, _passWord, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
wi = new WindowsIdentity(tokenDuplicate);
wic = wi.Impersonate();
if (wic != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
return false;
}
#region IDisposable Members
public void Dispose()
{
if (wic != null)
{
wic.Dispose();
}
RevertToSelf();
}
#endregion
}
Version2 (from MSDN with small changes):
class UserImpersonation2 : IDisposable
{
[DllImport("advapi32.dll")]
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 static extern bool CloseHandle(IntPtr handle);
WindowsImpersonationContext wic;
IntPtr tokenHandle;
string _userName;
string _domain;
string _passWord;
public UserImpersonation2(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
public bool ImpersonateValidUser()
{
bool returnValue = LogonUser(_userName, _domain, _passWord,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
return false;
}
Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
Console.WriteLine("Value of Windows NT token: " + tokenHandle);
// Check the identity.
Console.WriteLine("Before impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Use the token handle returned by LogonUser.
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
wic = newId.Impersonate();
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
return true;
}
#region IDisposable Members
public void Dispose()
{
if(wic!=null)
{
wic.Undo();
}
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
#endregion
}
How to use (both are the same):
const string file = #"\\machine\test\file.txt";
using (UserImpersonation user = new UserImpersonation("user", "domain", "password"))
{
if (user.ImpersonateValidUser())
{
StreamReader reader = new StreamReader(file);
Console.WriteLine(reader.ReadToEnd());
reader.Close();
}
}
From memory you'll need to use a Windows API call and login as a user on the other domain. See this link for an example.
Another idea could be to use the RunAs command line argument to read the file and save it into a file on your local domain/server.

Categories