0

Is it possible to impersonate an administrator in Vista/Windows 7 setting user name, login and password in the code?

My scenario: A lot of users (without local admin rigths) will execute a C# program; the C# program copy a file to C:\Windows\. I want the program to use the credentials of an administrator to do the copy without getting the "Access denied" message and without typing the credentials in the UAC prompt.

I've tried these two approaches:

  • Include a manifest with requireAdministrator or highestAvailable. The user would be prompted for the credentials so this doesn't work.
  • Impersonating using the good old LogonUser from advapi32.dll API. I've done it and works like a charm ... but only in Windows XP.

Is this possible?

EDIT

A lot of interest on why Am I doing such a horrible thing. I'm editing to include a couple of my comments explaining why I need this.

we can't create a scheduled task in each user computer. This is a one time thing: send an email to all users asking them to execute a .exe file in a network folder (or attaching the .exe). That's the whole point: avoid doing it computer by computer.

Come on guys! I know this isn't rigth, but that is the scenario. The normal and correct way would take us 2 months on the corporate procedure. The general manager asked us to find a way to do that in a week for business reasons. This is not about some virus or attack... this is a silly task for changing the outdated wallpaper with the one with the pretty new sales "mantra".

daniloquio
  • 3,822
  • 2
  • 36
  • 56
  • I would make a scheduled task for this that other users can run. – Jeremy Holovacs May 20 '13 at 20:15
  • 3
    ..or fix the C# program so it does not need to do this copy? – Martin James May 20 '13 at 20:17
  • @JeremyHolovacs we can't create a scheduled task in each user computer. This is a one time thing: send an email to all users asking them to execute a .exe file in a network folder (or attaching the .exe). That's the whole point: avoid doing it computer by computer. – daniloquio May 20 '13 at 20:19
  • 2
    Don't you find a small contradiction between *A lot of users (without local admin rigths)* and *copy a file to "C:\Windows\"*. I can see how malware will like your efforts! – oleksii May 20 '13 at 20:19
  • Why not make this an AD script to run on start then? – Jeremy Holovacs May 20 '13 at 20:21
  • Why do you need to copy a file into `C:\Windows`? – qJake May 20 '13 at 20:21
  • If you include the admin username and password in the program, you are giving it to the users, as well. If you somehow *need* to do this (and I bet you don't/shouldn't), you should do it with a service that handles the dangerous part, after being handed the task by the user program. – Andrew Barber May 20 '13 at 20:23
  • Come on guys! I know this isn't rigth, but that is the scenario. The normal and correct way would take us 2 months on the corporate procedure. The general manager asked us to find a way to do that in a week for business reasons. This is not about some virus or attack... this is a silly task for changing the outdated wallpaper with the one with the pretty new sales mantra. – daniloquio May 20 '13 at 20:24
  • @JeremyHolovacs that is the normal 2 months long corporate procedure (see my previous comment). – daniloquio May 20 '13 at 20:24
  • @SpikeX please look at my previous long comment. – daniloquio May 20 '13 at 20:27
  • 2
    Why do you need to put a file into `C:\Windows` in order to change a wallpaper!? Just put the file in the user's appdata somewhere (where it's writable without administrator permissions!), and set the wallpaper to be that file. Wallpapers don't need to be stored in `C:\Windows` in order to be used. See this answer for how to set a wallpaper programmatically with C#: http://stackoverflow.com/questions/1061678/change-desktop-wallpaper-using-code-in-net – qJake May 20 '13 at 20:30
  • @SpikeX that is not an option for us because of the global policy for the active directory; we just can't touch that. The current wallpaper is being taken from C:\windows\ so change the wallpaper file in there is our only chance to avoid a very long process. – daniloquio May 20 '13 at 20:38
  • Unless you want to be responsible for a potential security vulnerability on each of these machines (where you're going to be giving out the administrator username/password), I would highly recommend that you tell your superiors that this is not possible and to find another, more correct solution, such as storing the wallpaper in a user-writable location, or performing this maintenance off-hours when IT staff can sign on as an administrator and update the wallpaper (this can also be automated). – qJake May 20 '13 at 20:42
  • 1
    So you're going to circumvent security to update your wallpaper? And you have apparently crippled access to appdata by global policy? Really: The correct answer is to go through normal corp policy or uncripple your access through GP. – Reacher Gilt May 20 '13 at 20:52
  • @ReacherGilt Look guys, I'm done talking about the wallpaper. I asked a very specific question and only got a -1 for it. You would need a lot of additional information to make an informed opinion of my workplace's policies, environment or practices. Please focus on the question, like you are supposed to. Thanks. – daniloquio May 20 '13 at 21:30
  • @daniloquio the way you are trying to solve this is a **bad solution**, however *we would need a lot of additional information to make an informed opinion* on what would be a better solution to your problem. – Scott Chamberlain May 20 '13 at 21:32
  • 1
    [FAQ: Why can’t I bypass the UAC prompt?](http://blogs.msdn.com/b/aaron_margosis/archive/2007/06/29/faq-why-can-t-i-bypass-the-uac-prompt.aspx) – Bill_Stewart May 21 '13 at 02:14
  • @Bill_Stewart Thanks, great read. This seems to be impossible to do on Vista or W7. It would be great to just say **sudo make me a sandwish and then copy this thing to system folder** jeje http://xkcd.com/149/ – daniloquio May 21 '13 at 13:33
  • @daniloquio There is a sudo similar command, it's [runas](http://technet.microsoft.com/en-us/library/cc771525%28v=ws.10%29.aspx). However (like with sudo) you must tell the user running the command the password. – Scott Chamberlain May 21 '13 at 13:36
  • Note that [runas can't start an elevated process](http://msdn.microsoft.com/en-us/library/bb756922.aspx). – Bill_Stewart May 21 '13 at 14:11
  • @daniloquio I really do appreciate the situation you're in, and I'm sure it seems like people are ganging up on you. Maybe the best of all possible outcomes is that you get some talking points to bring back to your managers. – Reacher Gilt May 21 '13 at 15:25
  • @ReacherGilt actually my bosses are ok. We already created a request for doing this the slow way so they know it can take 1 or 2 months. They asked me to try doing it faster so I tried (with no luck). I think this is interesting: the internet (SO included) is full of unconclusive answers to this question. – daniloquio May 21 '13 at 16:04

2 Answers2

3

You said you are just changing the wallpaper of the users, the correct approach would be a two step process and it can be entirely done with Group Policy.

Step 1: Have a one time per-machine startup script to copy the background from a network share to the local windows directory.

Step 2: Update the users wallpaper to the new corporate wallpaper. (The reg keys you will need to update are in HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\, specifically Wallpaper and WallpaperStyle)

If the new wallpaper will have the same name as the old wallpaper you can remove Step 2.


If you really MUST do it your way, here is a solution based off of the answer to this question that I used for my own tasks.

Add the following NativeMethods class to your code.

using System;
using System.Runtime.InteropServices;

/// <summary>
/// Implements P/Invoke Interop calls to the operating system.
/// </summary>
internal static class NativeMethods
{
    /// <summary>
    /// The type of logon operation to perform.
    /// </summary>
    internal enum LogonType : int
    {
        /// <summary>
        /// This logon type is intended for users who will be interactively
        /// using the computer, such as a user being logged on by a
        /// terminal server, remote shell, or similar process.
        /// This logon type has the additional expense of caching logon
        /// information for disconnected operations; therefore, it is
        /// inappropriate for some client/server applications, such as a
        /// mail server.
        /// </summary>
        Interactive = 2,

        /// <summary>
        /// This logon type is intended for high performance servers to
        /// authenticate plaintext passwords.
        /// The LogonUser function does not cache credentials for this
        /// logon type.
        /// </summary>
        Network = 3,

        /// <summary>
        /// This logon type is intended for batch servers, where processes
        /// may be executing on behalf of a user without their direct
        /// intervention.  This type is also for higher performance servers
        /// that process many plaintext authentication attempts at a time,
        /// such as mail or Web servers.
        /// The LogonUser function does not cache credentials for this
        /// logon type.
        /// </summary>
        Batch = 4,

        /// <summary>
        /// Indicates a service-type logon.  The account provided must have
        /// the service privilege enabled.
        /// </summary>
        Service = 5,

        /// <summary>
        /// This logon type is for GINA DLLs that log on users who will be
        /// interactively using the computer.
        /// This logon type can generate a unique audit record that shows
        /// when the workstation was unlocked.
        /// </summary>
        Unlock = 7,

        /// <summary>
        /// This logon type preserves the name and password in the
        /// authentication package, which allows the server to make
        /// connections to other network servers while impersonating the
        /// client.  A server can accept plaintext credentials from a
        /// client, call LogonUser, verify that the user can access the
        /// system across the network, and still communicate with other
        /// servers.
        /// NOTE: Windows NT:  This value is not supported.
        /// </summary>
        NetworkCleartext = 8,

        /// <summary>
        /// This logon type allows the caller to clone its current token
        /// and specify new credentials for outbound connections.  The new
        /// logon session has the same local identifier but uses different
        /// credentials for other network connections.
        /// NOTE: This logon type is supported only by the
        /// LOGON32_PROVIDER_WINNT50 logon provider.
        /// NOTE: Windows NT:  This value is not supported.
        /// </summary>
        NewCredentials = 9
    }

    /// <summary>
    /// Specifies the logon provider.
    /// </summary>
    internal enum LogonProvider : int
    {
        /// <summary>
        /// Use the standard logon provider for the system.
        /// The default security provider is negotiate, unless you pass
        /// NULL for the domain name and the user name is not in UPN format.
        /// In this case, the default provider is NTLM.
        /// NOTE: Windows 2000/NT:   The default security provider is NTLM.
        /// </summary>
        Default = 0,

        /// <summary>
        /// Use this provider if you'll be authenticating against a Windows
        /// NT 3.51 domain controller (uses the NT 3.51 logon provider).
        /// </summary>
        WinNT35 = 1,

        /// <summary>
        /// Use the NTLM logon provider.
        /// </summary>
        WinNT40 = 2,

        /// <summary>
        /// Use the negotiate logon provider.
        /// </summary>
        WinNT50 = 3
    }

    /// <summary>
    /// The type of logon operation to perform.
    /// </summary>
    internal enum SecurityImpersonationLevel : int
    {
        /// <summary>
        /// The server process cannot obtain identification information
        /// about the client, and it cannot impersonate the client.  It is
        /// defined with no value given, and thus, by ANSI C rules,
        /// defaults to a value of zero.
        /// </summary>
        Anonymous = 0,

        /// <summary>
        /// The server process can obtain information about the client,
        /// such as security identifiers and privileges, but it cannot
        /// impersonate the client.  This is useful for servers that export
        /// their own objects, for example, database products that export
        /// tables and views.  Using the retrieved client-security
        /// information, the server can make access-validation decisions
        /// without being able to use other services that are using the
        /// client's security context.
        /// </summary>
        Identification = 1,

        /// <summary>
        /// The server process can impersonate the client's security
        /// context on its local system.  The server cannot impersonate the
        /// client on remote systems.
        /// </summary>
        Impersonation = 2,

        /// <summary>
        /// The server process can impersonate the client's security
        /// context on remote systems.
        /// NOTE: Windows NT:  This impersonation level is not supported.
        /// </summary>
        Delegation = 3
    }

    /// <summary>
    /// Logs on the user.
    /// </summary>
    /// <param name="userName">Name of the user.</param>
    /// <param name="domain">The domain.</param>
    /// <param name="password">The password.</param>
    /// <param name="logonType">Type of the logon.</param>
    /// <param name="logonProvider">The logon provider.</param>
    /// <param name="token">The token.</param>
    /// <returns>True if the function succeeds, false if the function fails.
    /// To get extended error information, call GetLastError.</returns>
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool LogonUser(
        string userName,
        string domain,
        string password,
        LogonType logonType,
        LogonProvider logonProvider,
        out IntPtr token);

    /// <summary>
    /// Duplicates the token.
    /// </summary>
    /// <param name="existingTokenHandle">The existing token
    /// handle.</param>
    /// <param name="securityImpersonationLevel">The security impersonation
    /// level.</param>
    /// <param name="duplicateTokenHandle">The duplicate token
    /// handle.</param>
    /// <returns>True if the function succeeds, false if the function fails.
    /// To get extended error information, call GetLastError.</returns>
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool DuplicateToken(
        IntPtr existingTokenHandle,
        SecurityImpersonationLevel securityImpersonationLevel,
        out IntPtr duplicateTokenHandle);

    /// <summary>
    /// Closes the handle.
    /// </summary>
    /// <param name="handle">The handle.</param>
    /// <returns>True if the function succeeds, false if the function fails.
    /// To get extended error information, call GetLastError.</returns>
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool CloseHandle(IntPtr handle);
}

Here is the implementation to be used in code.

    IntPtr token;

    if (!NativeMethods.LogonUser(
        this.userName,
        this.domain,
        this.password,
        NativeMethods.LogonType.NewCredentials,
        NativeMethods.LogonProvider.Default,
        out token))
    {
        throw new Win32Exception();
    }

    try
    {
        IntPtr tokenDuplicate;

        if (!NativeMethods.DuplicateToken(
            token,
            NativeMethods.SecurityImpersonationLevel.Impersonation,
            out tokenDuplicate))
        {
            throw new Win32Exception();
        }

        try
        {
            using (WindowsImpersonationContext impersonationContext =
                new WindowsIdentity(tokenDuplicate).Impersonate())
            {
                //Copy your file to the windows directory here.

                impersonationContext.Undo();
                return;
            }
        }
        finally
        {
            if (tokenDuplicate != IntPtr.Zero)
            {
                if (!NativeMethods.CloseHandle(tokenDuplicate))
                {
                    // Uncomment if you need to know this case.
                    ////throw new Win32Exception();
                }
            }
        }
    }
    finally
    {
        if (token != IntPtr.Zero)
        {
            if (!NativeMethods.CloseHandle(token))
            {
                // Uncomment if you need to know this case.
                ////throw new Win32Exception();
            }
        }
    }
Community
  • 1
  • 1
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • -1 This doesn't answer my question. I asked a very specific question and it wasn't about wallpapers. Additionally, we can't do something like this because we don't have control over the Group Policy. – daniloquio May 20 '13 at 21:18
  • 1
    Yes, but you are falling in to the [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)! You are focused too much on fixing your attempted solution to the problem instead of just finding a different solution to the problem and using that instead. If you updated your original question to explain WHY you need to copy files to the windows directory you can get better answers. Can you explain why you can't just push this out as a Group Policy change? This situation is the EXACT thing group policy was invented for. – Scott Chamberlain May 20 '13 at 21:24
  • Because what we need will affect the users on three countries. Group policy is managed by a team located in another continent and managing 120+ countries. We can send our users an application that changes the location of a file; we can't change group policy. Please trust me: I reviewed all our posibilities and I came here to check if one of them is possible from a TECHNICAL point of view. – daniloquio May 20 '13 at 21:36
  • Sigh, I know i will regret this but take a look at [this question and answer](http://stackoverflow.com/questions/2563724/accessing-password-protected-network-drives-in-windows-in-c) It shows how to do impersonation when talking to a network drive. In principal, the same thing would work when talking to a local drive while still inside the impersonation context. – Scott Chamberlain May 20 '13 at 22:41
  • +1 Thanks. This is the LogonUser thing I already tried but using NewCredentials instead of Interactive. I tried but it didn't work. This seems to be impossible by design. – daniloquio May 21 '13 at 13:53
  • Did you do the `DuplicateToken` step? Not doing that is what was making my code not work when I was trying to copy from a network drive. – Scott Chamberlain May 21 '13 at 13:57
  • Yes I'm using http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User and it implements the DuplicateToken step. My code works on XP but it doesn't work on vista/w7. – daniloquio May 21 '13 at 14:01
  • One last suggestion to try, while impersonating try connecting to the network path `\\localhost\C$\Windows` if that does not work, I am out of ideas. (also is the user you are typing in to the impersonation credentials different than the logged on user and has administrative access? if you are typing your own credentials in, it may not work) – Scott Chamberlain May 21 '13 at 14:04
  • I got the "you were not connected because a duplicate name exists on the network ... change the computer name" error. No luck... – daniloquio May 21 '13 at 14:12
3

As others have said, your workaround breaks several best practices, and "just need to get it done now" is a bad time to break best practices as history has shown. So a couple of recommendations that you should do first:

  • Make a brand new account for this
  • Give that account the bare minimum permissions required
  • Give that account a very short (< 1 week) timeout

This will at least guarantee someone a year from now can't stumble on the program and have admin rights everywhere. Now with a program like this it may only take a day, but it has already been pointed out the futility of security with things like this.

Given that, I found a post talking about a breaking change in LogonUser. It calls for changing your DllImport code from:

[DllImport("advapi32.dll", SetLastError = true)]
private extern static bool LogonUser(
    string pszUsername, string pszDomain, string pszPassword,
    int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

To:

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

See if that is able to solve your "Only works on Windows XP" problem.

Now that you have a solution for the programming issue, you really need to talk with your company to figure out why your corporate policy has defanged your IT department to the point where deploying a new wallpaper takes 2 months. These kind of issues may fester to the point where bad practices can no longer be fixed since the timeline to do so is so drawn out. (Oh that service account has a three year old password and is a domain admin, well fixing it would require a lot of paperwork...)

Guvante
  • 18,775
  • 1
  • 33
  • 64