Connecting to a UNC share from a web application

Ask a Question related to ASP.NET Security, Design and Development.

  1. #1

    Default Connecting to a UNC share from a web application

    Basically I want to do the following:

    DirectoryInfo baseDirInfo = new DirectoryInfo(@"\\server2\files");
    FileInfo[] aFileInfos = baseDirInfo.GetFiles();
    string ss = "";
    foreach (FileInfo fileInfo in aFileInfos){
    ss += fileInfo.Name;
    }


    But I need a way to supply the username and password – otherwise I’m not
    allowed to access the share.

    Info:
    The web application has anonymous access
    No domain
    A local user is created on server2
    This user has access to share d:\files on server2

    Rasmus Guest

  2. Similar Questions and Discussions

    1. Weird issue connecting to WinXP share
      Let me preface this by saying I am a newbie to Linux, though not to computers. Forgive me for any abuse of Linux-specific terminology. I'm trying...
    2. Problem with asp.net application locate on network share
      Hi all, I have an asp.net application (framework 1.1 sp1) on windows server 2003. When the document root is locate in local that's all ok... but...
    3. ASPNET Account Security Problem - Running a Web Application over a network share
      All, If anyone has been following my trials over the last week see(Setting up a Web Application on IIS 5.1 and ASP.Net Security Problems). I'm...
    4. Running ASP.NET application from network share
      The problem is the same with running apps across domain boundaries (app domain, not NT domain). You are creating what, in essence, is a distributed...
    5. 30 second delay connecting with XP Professional to Windows 2003 file share w/ AD
      I have a small office network connected via a Dell Power Connect switch and Cat 5 cabling throughout. I can connect to my Windows 2003 Server file...
  3. #2

    Default Re: Connecting to a UNC share from a web application

    On Thu, 6 Jan 2005 07:59:06 -0800, Rasmus <Rasmus@nospam.nospam> wrote:

    ¤ Basically I want to do the following:
    ¤
    ¤ DirectoryInfo baseDirInfo = new DirectoryInfo(@"\\server2\files");
    ¤ FileInfo[] aFileInfos = baseDirInfo.GetFiles();
    ¤ string ss = "";
    ¤ foreach (FileInfo fileInfo in aFileInfos){
    ¤ ss += fileInfo.Name;
    ¤ }
    ¤
    ¤
    ¤ But I need a way to supply the username and password – otherwise I’m not
    ¤ allowed to access the share.
    ¤
    ¤ Info:
    ¤ The web application has anonymous access
    ¤ No domain
    ¤ A local user is created on server2
    ¤ This user has access to share d:\files on server2

    Take a look at the below link concerning delegation scenarios:

    [url]http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsent7/html/vxconaspnetdelegation.asp[/url]


    Paul ~~~ [email]pclement@ameritech.net[/email]
    Microsoft MVP (Visual Basic)
    Paul Clement Guest

  4. #3

    Default Re: Connecting to a UNC share from a web application

    Thank you for the reply.

    I've tried the approach from
    [url]http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemSecurityPrincipalWindowsIdentityClassIm personateTopic.asp[/url]

    But keep getting "Error: [1326] Logon failure: unknown user name or bad
    password."

    I'm trying to connect to a XP with a shared folder

    Rasmus Guest

  5. #4

    Default Re: Connecting to a UNC share from a web application

    Server name: server2
    unc: \\server2\junk
    username: test
    password: pass

    More info on what i can do and not:

    In cmd window:
    net use x: \\server2\junk /user:server2\test pass

    this will map the unc to drive x - and everything works fine.

    But using the same username password in the code snippet from
    [url]http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemSecurityPrincipalWindowsIdentityClassIm personateTopic.asp[/url]

    I get:
    Enter the name of the domain on which to log on: \\server2\junk
    Enter the login of a user on \\apollo6\ros that you wish to impersonate:
    server2\test
    Enter the password for server2\test: pass
    LogonUser called.
    LogonUser failed with error code : 1326

    Error: [1326] Logon failure: unknown user name or bad password.


    Exception occurred. Access is denied




    please help
    Rasmus Guest

  6. #5

    Default Re: Connecting to a UNC share from a web application

    Hello,

    I think you may try impersonate in ASP.NET. This can make your ASP.NET app
    act as a designed user and use this user's permission to access network
    share. This can be implement with either asp.net config file or code. For
    details, you may refer to:

    How to implement impersonation in an ASP.NET application
    [url]http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q306158[/url]

    Luke

    [MSFT] Guest

  7. #6

    Default Re: Connecting to a UNC share from a web application

    Hello,

    Thanks for the reply. But i still cant get it to work. with the following
    code:



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

    namespace nws
    {
    /// <summary>
    /// Summary description for WebForm2.
    /// </summary>
    public class WebForm2 : System.Web.UI.Page
    {
    public const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_PROVIDER_DEFAULT = 0;

    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 void Page_Load(Object s, EventArgs e) {
    if(impersonateValidUser("test", "server2", "pass")) {
    Response.Write("HURRA");
    //Insert your code that runs under the security context of a specific
    user here.
    undoImpersonation();
    }
    else {
    Response.Write("BUMMER");
    //Your impersonation failed. Therefore, include a fail-safe mechanism
    here.
    }
    }

    private 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_INTERACTIVE,
    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;
    }

    private void undoImpersonation() {
    impersonationContext.Undo();
    }


    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    //
    InitializeComponent();
    base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    }
    }

    Rasmus Guest

  8. #7

    Default Re: Connecting to a UNC share from a web application

    On Thu, 6 Jan 2005 12:53:01 -0800, Rasmus <Rasmus@nospam.nospam> wrote:

    ¤ Thank you for the reply.
    ¤
    ¤ I've tried the approach from
    ¤ [url]http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemSecurityPrincipalWindowsIdentityClassIm personateTopic.asp[/url]
    ¤
    ¤ But keep getting "Error: [1326] Logon failure: unknown user name or bad
    ¤ password."
    ¤
    ¤ I'm trying to connect to a XP with a shared folder

    Assuming here that you're using a local account and that it exists on both machines and has the same
    password?


    Paul ~~~ [email]pclement@ameritech.net[/email]
    Microsoft MVP (Visual Basic)
    Paul Clement Guest

  9. #8

    Default Re: Connecting to a UNC share from a web application

    Hi Paul,

    No i did not have the test user on both machines. I tried it and it still
    did not work.
    I noticed this in the code comment:
    "This sample can be run only on Windows XP. "

    The client in my case is a windows server 2003 - could that be the cause?
    Rasmus Guest

  10. #9

    Default Re: Connecting to a UNC share from a web application

    On Fri, 7 Jan 2005 08:07:05 -0800, Rasmus <Rasmus@nospam.nospam> wrote:

    ¤ Hi Paul,
    ¤
    ¤ No i did not have the test user on both machines. I tried it and it still
    ¤ did not work.
    ¤ I noticed this in the code comment:
    ¤ "This sample can be run only on Windows XP. "
    ¤
    ¤ The client in my case is a windows server 2003 - could that be the cause?

    Have you tried changing the Anonymous account under which the web application is running (it's
    probably IUSR_machinename, which can't be delegated) and then just using the standard impersonation
    (web.config setting for your ASP.NET app)? If this works then it would eliminate the need for the
    impersonation code you've written.

    In any event, for delegation to function properly, the local account must exist on both machines and
    have the same password.

    I'm not sure what impact Windows Server 2003 would have in this configuration. It's a more secure OS
    that was designed to operate in a domain based environment.


    Paul ~~~ [email]pclement@ameritech.net[/email]
    Microsoft MVP (Visual Basic)
    Paul Clement Guest

  11. #10

    Default Re: Connecting to a UNC share from a web application

    It seems there is no problem with the code. As Paul suggested, have you
    checked the anonymous access in the IIS security setting? Also, how did you
    set the authentication in web.config?

    Luke

    [MSFT] Guest

  12. #11

    Default Re: Connecting to a UNC share from a web application

    Anonymous is checked and user is IUSR_<Machine name>

    Web config:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>

    <system.web>

    <!-- DYNAMIC DEBUG COMPILATION
    Set compilation debug="true" to enable ASPX debugging. Otherwise,
    setting this value to
    false will improve runtime performance of this application.
    Set compilation debug="true" to insert debugging symbols (.pdb
    information)
    into the compiled page. Because this creates a larger file that
    executes
    more slowly, you should set this value to true only when debugging
    and to
    false at all other times. For more information, refer to the
    documentation about
    debugging ASP.NET files.
    -->
    <compilation
    defaultLanguage="c#"
    debug="true"
    />

    <!-- CUSTOM ERROR MESSAGES
    Set customErrors mode="On" or "RemoteOnly" to enable custom error
    messages, "Off" to disable.
    Add <error> tags for each of the errors you want to handle.

    "On" Always display custom (friendly) messages.
    "Off" Always display detailed ASP.NET error information.
    "RemoteOnly" Display custom (friendly) messages only to users not
    running
    on the local Web server. This setting is recommended for security
    purposes, so
    that you do not display application detail information to remote
    clients.
    -->
    <customErrors
    mode="RemoteOnly"
    />

    <!-- AUTHENTICATION
    This section sets the authentication policies of the application.
    Possible modes are "Windows",
    "Forms", "Passport" and "None"

    "None" No authentication is performed.
    "Windows" IIS performs authentication (Basic, Digest, or
    Integrated Windows) according to
    its settings for the application. Anonymous access must be
    disabled in IIS.
    "Forms" You provide a custom form (Web page) for users to enter
    their credentials, and then
    you authenticate them in your application. A user credential
    token is stored in a cookie.
    "Passport" Authentication is performed via a centralized
    authentication service provided
    by Microsoft that offers a single logon and core profile services
    for member sites.
    -->
    <authentication mode="None" />

    <!-- AUTHORIZATION
    This section sets the authorization policies of the application.
    You can allow or deny access
    to application resources by user or role. Wildcards: "*" mean
    everyone, "?" means anonymous
    (unauthenticated) users.
    -->

    <authorization>
    <allow users="*" /> <!-- Allow all users -->
    <!-- <allow users="[comma separated list of users]"
    roles="[comma separated list of roles]"/>
    <deny users="[comma separated list of users]"
    roles="[comma separated list of roles]"/>
    -->
    </authorization>

    <!-- APPLICATION-LEVEL TRACE LOGGING
    Application-level tracing enables trace log output for every page
    within an application.
    Set trace enabled="true" to enable application trace logging. If
    pageOutput="true", the
    trace information will be displayed at the bottom of each page.
    Otherwise, you can view the
    application trace log by browsing the "trace.axd" page from your
    web application
    root.
    -->
    <trace
    enabled="false"
    requestLimit="10"
    pageOutput="false"
    traceMode="SortByTime"
    localOnly="true"
    />

    <!-- SESSION STATE SETTINGS
    By default ASP.NET uses cookies to identify which requests belong
    to a particular session.
    If cookies are not available, a session can be tracked by adding a
    session identifier to the URL.
    To disable cookies, set sessionState cookieless="true".
    -->
    <sessionState
    mode="InProc"
    stateConnectionString="tcpip=127.0.0.1:42424"
    sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
    cookieless="false"
    timeout="20"
    />

    <!-- GLOBALIZATION
    This section sets the globalization settings of the application.
    -->
    <globalization
    requestEncoding="utf-8"
    responseEncoding="utf-8"
    />

    </system.web>

    </configuration>

    Rasmus Guest

  13. #12

    Default Re: Connecting to a UNC share from a web application

    I guess the root of your problems is in the following quote from the Platform
    SDK:
    "The LogonUser function attempts to log a user on to the local computer. The
    local computer is the computer from which LogonUser was called. You cannot
    use LogonUser to log on to a remote computer."

    So my suggestions are:

    1. Try use "." instead of domain name when calling LogonUser - that might
    solve the problem of ivalid user or password.

    2. LogonUser can't be used at all (as I understood from other discussions)
    to solve the problem of accessing shared resources on other computers. To
    solve that problem you have to configure delegation on all computers
    involved.

    3. Or am I mistaken?..

    "Rasmus" wrote:
    > Anonymous is checked and user is IUSR_<Machine name>
    >
    > Web config:
    > <?xml version="1.0" encoding="utf-8" ?>
    > <configuration>
    >
    > <system.web>
    >
    > <!-- DYNAMIC DEBUG COMPILATION
    > Set compilation debug="true" to enable ASPX debugging. Otherwise,
    > setting this value to
    > false will improve runtime performance of this application.
    > Set compilation debug="true" to insert debugging symbols (.pdb
    > information)
    > into the compiled page. Because this creates a larger file that
    > executes
    > more slowly, you should set this value to true only when debugging
    > and to
    > false at all other times. For more information, refer to the
    > documentation about
    > debugging ASP.NET files.
    > -->
    > <compilation
    > defaultLanguage="c#"
    > debug="true"
    > />
    >
    > <!-- CUSTOM ERROR MESSAGES
    > Set customErrors mode="On" or "RemoteOnly" to enable custom error
    > messages, "Off" to disable.
    > Add <error> tags for each of the errors you want to handle.
    >
    > "On" Always display custom (friendly) messages.
    > "Off" Always display detailed ASP.NET error information.
    > "RemoteOnly" Display custom (friendly) messages only to users not
    > running
    > on the local Web server. This setting is recommended for security
    > purposes, so
    > that you do not display application detail information to remote
    > clients.
    > -->
    > <customErrors
    > mode="RemoteOnly"
    > />
    >
    > <!-- AUTHENTICATION
    > This section sets the authentication policies of the application.
    > Possible modes are "Windows",
    > "Forms", "Passport" and "None"
    >
    > "None" No authentication is performed.
    > "Windows" IIS performs authentication (Basic, Digest, or
    > Integrated Windows) according to
    > its settings for the application. Anonymous access must be
    > disabled in IIS.
    > "Forms" You provide a custom form (Web page) for users to enter
    > their credentials, and then
    > you authenticate them in your application. A user credential
    > token is stored in a cookie.
    > "Passport" Authentication is performed via a centralized
    > authentication service provided
    > by Microsoft that offers a single logon and core profile services
    > for member sites.
    > -->
    > <authentication mode="None" />
    >
    > <!-- AUTHORIZATION
    > This section sets the authorization policies of the application.
    > You can allow or deny access
    > to application resources by user or role. Wildcards: "*" mean
    > everyone, "?" means anonymous
    > (unauthenticated) users.
    > -->
    >
    > <authorization>
    > <allow users="*" /> <!-- Allow all users -->
    > <!-- <allow users="[comma separated list of users]"
    > roles="[comma separated list of roles]"/>
    > <deny users="[comma separated list of users]"
    > roles="[comma separated list of roles]"/>
    > -->
    > </authorization>
    >
    > <!-- APPLICATION-LEVEL TRACE LOGGING
    > Application-level tracing enables trace log output for every page
    > within an application.
    > Set trace enabled="true" to enable application trace logging. If
    > pageOutput="true", the
    > trace information will be displayed at the bottom of each page.
    > Otherwise, you can view the
    > application trace log by browsing the "trace.axd" page from your
    > web application
    > root.
    > -->
    > <trace
    > enabled="false"
    > requestLimit="10"
    > pageOutput="false"
    > traceMode="SortByTime"
    > localOnly="true"
    > />
    >
    > <!-- SESSION STATE SETTINGS
    > By default ASP.NET uses cookies to identify which requests belong
    > to a particular session.
    > If cookies are not available, a session can be tracked by adding a
    > session identifier to the URL.
    > To disable cookies, set sessionState cookieless="true".
    > -->
    > <sessionState
    > mode="InProc"
    > stateConnectionString="tcpip=127.0.0.1:42424"
    > sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
    > cookieless="false"
    > timeout="20"
    > />
    >
    > <!-- GLOBALIZATION
    > This section sets the globalization settings of the application.
    > -->
    > <globalization
    > requestEncoding="utf-8"
    > responseEncoding="utf-8"
    > />
    >
    > </system.web>
    >
    > </configuration>
    >
    vetplakh Guest

  14. #13

    Default Re: Connecting to a UNC share from a web application

    Thank you for the suggestions.

    I just can’t seem to understand why, when I have all the necessary login
    information (UNC, username and password), I cannot retrieve the files and
    folders on the UNC share.

    Rasmus Guest

Posting Permissions

  • You may not post new threads
  • You may post replies
  • You may not post attachments
  • You may not edit your posts

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139