Solved

Create a Directory on network Shared Drive impersonating a service account using C# asp.net

Posted on 2008-10-16
15
2,379 Views
Last Modified: 2013-12-17
How can I Create a Directory on network Shared Drive impersonating a service account using C# asp.net. My web.config identity impersonate tag is set to true and no username and password is provided for security reasons. So I am just impersonating the code where I am accessing the network resources. It would be great if I could get a working code. Thanks.
0
Comment
Question by:nk_kanikaram
  • 8
  • 7
15 Comments
 
LVL 13

Expert Comment

by:TechTiger007
ID: 22732999
Here is a sample that moves file from one path to another, you can build on the same code to create directory in network path

http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_2.0/Q_23120865.html?sfQueryTermInfo=1+creat+folder+imperson
0
 

Author Comment

by:nk_kanikaram
ID: 22733153
Could I please get the C# equivalent code for the same.
0
 
LVL 13

Assisted Solution

by:TechTiger007
TechTiger007 earned 500 total points
ID: 22734419
Here is a sample in C#.
The full source code is available as zip file download it and use the required part of the code

http://csharptuning.blogspot.com/2007/06/impersonation-in-c.html
0
 

Author Comment

by:nk_kanikaram
ID: 22734958
Thanks for the response. I am doing the following, but still i am getting the Access denied error message.I have looked at the folder security and granted fullcontrol to the root folder underwhich i am trying to create the new folder. Am I missing something here.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.IO;

public partial class RunAs_Impersonator : System.Web.UI.Page
{
    public const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_PROVIDER_DEFAULT = 0;
    IntPtr tokenHandle;
    IntPtr dupeTokenHandle;
    WindowsImpersonationContext impersonatedUser;

    [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);

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public void ImpersonateStart(string Domain, string userName, string Password)
    {
        try
        {
            tokenHandle = IntPtr.Zero;
            int returnValue = LogonUserA(userName, Domain, Password, 2, 0, ref tokenHandle);
            if (returnValue == 0)
            {
                int ret = Marshal.GetLastWin32Error();
                throw new System.ComponentModel.Win32Exception(ret);
            }
            WindowsIdentity newId = new WindowsIdentity(tokenHandle);
            impersonatedUser = newId.Impersonate();
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public void ImpersonateStop()
    {
        impersonatedUser.Undo();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            ImpersonateStart("userDomain", "userName", "userPassword");
            if (Directory.Exists(@"\\serverName\ExistingFolderwithpermissions"))// the "userName" account has modify permissions on this folder
            {
                //This line of code throws exception "Access denied to the \\serverName\ExistingFolderwithpermissions\NewFolder path."
                Directory.CreateDirectory(@"\\serverName\ExistingFolderwithpermissions\NewFolder");
            }
            ImpersonateStop();
        }
        catch (Exception ex)
        {
            ImpersonateStop();
        }
    }
}
0
 
LVL 13

Expert Comment

by:TechTiger007
ID: 22735133
does this user id that you are using to impersonate have permission on the folder?

is impersonation successful? did it throw any exception?

0
 

Author Comment

by:nk_kanikaram
ID: 22735260
Yes, the user has access to @"\\serverName\ExistingFolderwithpermissions". The code passed the impersonation. But fails on Creating the directory. Just for testing purposes, I replaced the CreateDirectory Code with following to view files under the same root folder and had no issues viewing the files.

            ImpersonateStart("userDomain", "userName", "userPassword");
            DirectoryInfo dirInfo = new DirectoryInfo(@"\\serverName\ExistingFolderwithpermissions");
            FileInfo[] files = dirInfo.GetFiles();
            DirectoryInfo[] directories = dirInfo.GetDirectories();
            foreach (DirectoryInfo dir in directories)
            {
                Response.Write(dir.FullName + "<br/>");
            }
            foreach (FileInfo file in files)
            {
                Response.Write(file.FullName + "<br/>");
            }
           ImpersonateStop();
0
 
LVL 13

Assisted Solution

by:TechTiger007
TechTiger007 earned 500 total points
ID: 22735345
If you are able to see the list of files that means the user have got read access to the folder. To create another folder user should have "Modify" privilege on it having "Write" privilege wont be enough. Does the user have Modify privilege on the folder?

Try out with giving full access for the user if Modify didnt work.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:nk_kanikaram
ID: 22735435
The user has full control, read & execute, modify, write permissions on the folder. Also, I have checked all of the advanced permissions for this user on the folder(like create files, folders, write, append data etc.) . And also made sure that the folder is shared.
0
 
LVL 13

Assisted Solution

by:TechTiger007
TechTiger007 earned 500 total points
ID: 22738498
Let me confirm
1. User has got modify permission on the physical folder of the shared folder on the machine
2. User has got full access on the share permissions. (folder permissions and share permissions are different)
3. Both machines are in same domain
4. User is part of the domain
5. User impersonation succeeds

above are conditions that should satisfy.
I think we did not check the permission for user in the share. what do you say?
0
 

Author Comment

by:nk_kanikaram
ID: 22741152
Yes, I have double checked all the 5 points mentioned, all the permissions are set for the user on the shared folder, user is part of the domain, impersonation succeeds, machines are in the same domain etc.,
I Tried to run the same code from the server itself and surprisingly it failed even on the server.
Seems like Directory.CreateDirectory(@"\\serverName\ExistingFolderwithpermissions\NewFolder"); fails with UNC path. Same code works fine with physical path. ie Directory.CreateDirectory(@"C:\ExistingFolderwithpermissions\NewFolder");

0
 
LVL 13

Assisted Solution

by:TechTiger007
TechTiger007 earned 500 total points
ID: 22741418
try to impersonate with your user account once and check if you are able to create folder

may be I am asking again but just to confirm, is this what you did?
Right click on the folder that is shared
Select "Share and Security" option or "Share" option (depends on the OS)
In the pop up window, select security tab
click on permissions
give full permission for the user

0
 

Accepted Solution

by:
nk_kanikaram earned 0 total points
ID: 22757796
looks like its working now. I am using the code below. No need to set the permissions for the impersonation user on the root folder. Looks like the code adds the impersonating user to the newly created folder's security tab users list but with no permissions set for this user on the folder.

        string tempRoot = @"\\serverName\ExistingFolderwithpermissions\NewFolder";
        if (LogonUser("userName", "userDomain", "userPassword",
            8, // LOGON32_LOGON_NETWORK_CLEARTEXT    
            0, // LOGON32_PROVIDER_DEFAULT    
            out token))
        {
            wi = new WindowsIdentity(token);
            WindowsImpersonationContext wic = wi.Impersonate();
            try
            {
                Directory.CreateDirectory(tempRoot);
            }
            catch (UnauthorizedAccessException uae)
            {
                string msg = uae.StackTrace;
            }
            wic.Undo();
            CloseHandle(token);
        }
        else
        {
        }
0
 
LVL 13

Expert Comment

by:TechTiger007
ID: 22760481
Thats good to hear.
0
 

Author Comment

by:nk_kanikaram
ID: 22760525
Thanks a ton for your help.
0
 
LVL 13

Expert Comment

by:TechTiger007
ID: 22760751
You are welcome :-)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

A Change in PHP Behavior with Session Write Short Circuit (http://php.net/manual/en/book.session.php#116217) (Winter 2014)** With the release of PHP 5.6 the session handler changed in a way that many think should be considered a bug.  See the note …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video teaches viewers how to create their own website using cPanel and Wordpress. Tutorial walks users through how to set up their own domain name from tools like Domain Registrar, Hosting Account, and Wordpress. More specifically, the order in…
This video teaches users how to migrate an existing Wordpress website to a new domain.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now