如何将RUNAS /NETONLY功能集成到(C#/.NET/WinForms)程序中?

28
我们的工作站不是我们的SQL Server所在域的成员(它们实际上根本不在任何域中-别问为什么)。
当我们使用SSMS或其他任何东西连接到SQL Server时,我们使用带有DOMAIN\user的RUNAS /NETONLY。然后我们输入密码,它会启动程序。(RUNAS /NETONLY不允许您在批处理文件中包含密码)。
因此,我有一个.NET WinForms应用程序需要SQL连接,并且用户必须通过运行具有RUNAS /NETONLY命令行的批处理文件来启动它,然后它启动EXE。
如果用户意外直接启动EXE,则无法连接到SQL Server。
右键单击该应用程序并使用“以管理员身份运行...”选项无效(可能是因为工作站实际上并不知道域)。
我正在寻找一种方法,使应用程序在启动任何重要内容之前在内部执行RUNAS /NETONLY功能。
请参阅此链接,了解RUNAS /NETONLY的工作原理:http://www.eggheadcafe.com/conversation.aspx?messageid=32443204&threadid=32442982 我想我将不得不使用LOGON_NETCREDENTIALS_ONLY和CreateProcessWithLogonW。

1
由于eggheadcafe链接不再有效,这里提供另一篇文章作为替代:http://www.pseale.com/pretend-youre-on-the-domain-with-runas-netonly - Saeb Amini
由于我们目前无法编辑答案(有太多待处理的编辑),我将更新链接到微软的一个描述RUNAS /NETONLY工作原理的页面:https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc771525(v=ws.11) - user8207463
7个回答

17

我知道这是一个旧帖子,但它非常有用。我的情况与Cade Roux完全相同,我想要/netonly样式的功能。

John Rasch的答案有效,只需进行一点修改!!!

添加以下常量(为了一致性,请在第102行左右):

private const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
然后将对LogonUser的调用更改为使用LOGON32_LOGON_NEW_CREDENTIALS而不是LOGON32_LOGON_INTERACTIVE

这是我所做的唯一更改,就能完美地使它工作了!!!谢谢John和Cade!!!

下面是完整修改后的代码,方便复制/粘贴:

namespace Tools
{
    #region Using directives.
    // ----------------------------------------------------------------------

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

    // ----------------------------------------------------------------------
    #endregion

    /////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// Impersonation of a user. Allows to execute code under another
    /// user context.
    /// Please note that the account that instantiates the Impersonator class
    /// needs to have the 'Act as part of operating system' privilege set.
    /// </summary>
    /// <remarks>   
    /// This class is based on the information in the Microsoft knowledge base
    /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158
    /// 
    /// Encapsulate an instance into a using-directive like e.g.:
    /// 
    ///     ...
    ///     using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
    ///     {
    ///         ...
    ///         [code that executes under the new context]
    ///         ...
    ///     }
    ///     ...
    /// 
    /// Please contact the author Uwe Keim (mailto:uwe.keim@zeta-software.de)
    /// for questions regarding this class.
    /// </remarks>
    public class Impersonator :
        IDisposable
    {
        #region Public methods.
        // ------------------------------------------------------------------

        /// <summary>
        /// Constructor. Starts the impersonation with the given credentials.
        /// Please note that the account that instantiates the Impersonator class
        /// needs to have the 'Act as part of operating system' privilege set.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        public Impersonator(
            string userName,
            string domainName,
            string password)
        {
            ImpersonateValidUser(userName, domainName, password);
        }

        // ------------------------------------------------------------------
        #endregion

        #region IDisposable member.
        // ------------------------------------------------------------------

        public void Dispose()
        {
            UndoImpersonation();
        }

        // ------------------------------------------------------------------
        #endregion

        #region P/Invoke.
        // ------------------------------------------------------------------

        [DllImport("advapi32.dll", SetLastError = true)]
        private 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)]
        private static extern int DuplicateToken(
            IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool CloseHandle(
            IntPtr handle);

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

        // ------------------------------------------------------------------
        #endregion

        #region Private member.
        // ------------------------------------------------------------------

        /// <summary>
        /// Does the actual impersonation.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        private void ImpersonateValidUser(
            string userName,
            string domain,
            string password)
        {
            WindowsIdentity tempWindowsIdentity = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUser(
                        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();
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CloseHandle(tokenDuplicate);
                }
            }
        }

        /// <summary>
        /// Reverts the impersonation.
        /// </summary>
        private void UndoImpersonation()
        {
            if (impersonationContext != null)
            {
                impersonationContext.Undo();
            }
        }

        private WindowsImpersonationContext impersonationContext = null;

        // ------------------------------------------------------------------
        #endregion
    }

    /////////////////////////////////////////////////////////////////////////
}

1
太棒了!这就是我喜欢 Stack Overflow 的原因! - Saeb Amini

7

我刚刚使用了ImpersonationContext做了类似的事情。它非常直观易用,对我来说完美地运行。

要以不同的用户身份运行,语法如下:

using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
    // code that executes under the new context...
}

这是这个类:

namespace Tools
{
    #region Using directives.
    // ----------------------------------------------------------------------

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

    // ----------------------------------------------------------------------
    #endregion

    /////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// Impersonation of a user. Allows to execute code under another
    /// user context.
    /// Please note that the account that instantiates the Impersonator class
    /// needs to have the 'Act as part of operating system' privilege set.
    /// </summary>
    /// <remarks>   
    /// This class is based on the information in the Microsoft knowledge base
    /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158
    /// 
    /// Encapsulate an instance into a using-directive like e.g.:
    /// 
    ///     ...
    ///     using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
    ///     {
    ///         ...
    ///         [code that executes under the new context]
    ///         ...
    ///     }
    ///     ...
    /// 
    /// Please contact the author Uwe Keim (mailto:uwe.keim@zeta-software.de)
    /// for questions regarding this class.
    /// </remarks>
    public class Impersonator :
        IDisposable
    {
        #region Public methods.
        // ------------------------------------------------------------------

        /// <summary>
        /// Constructor. Starts the impersonation with the given credentials.
        /// Please note that the account that instantiates the Impersonator class
        /// needs to have the 'Act as part of operating system' privilege set.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        public Impersonator(
            string userName,
            string domainName,
            string password)
        {
            ImpersonateValidUser(userName, domainName, password);
        }

        // ------------------------------------------------------------------
        #endregion

        #region IDisposable member.
        // ------------------------------------------------------------------

        public void Dispose()
        {
            UndoImpersonation();
        }

        // ------------------------------------------------------------------
        #endregion

        #region P/Invoke.
        // ------------------------------------------------------------------

        [DllImport("advapi32.dll", SetLastError = true)]
        private 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)]
        private static extern int DuplicateToken(
            IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern bool CloseHandle(
            IntPtr handle);

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

        // ------------------------------------------------------------------
        #endregion

        #region Private member.
        // ------------------------------------------------------------------

        /// <summary>
        /// Does the actual impersonation.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        private void ImpersonateValidUser(
            string userName,
            string domain,
            string password)
        {
            WindowsIdentity tempWindowsIdentity = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUser(
                        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();
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CloseHandle(tokenDuplicate);
                }
            }
        }

        /// <summary>
        /// Reverts the impersonation.
        /// </summary>
        private void UndoImpersonation()
        {
            if (impersonationContext != null)
            {
                impersonationContext.Undo();
            }
        }

        private WindowsImpersonationContext impersonationContext = null;

        // ------------------------------------------------------------------
        #endregion
    }

    /////////////////////////////////////////////////////////////////////////
}

我在自定义安装程序中使用了类似的代码 - 但是“作为操作系统的一部分”权限非常强大,系统管理员对将其授予普通用户表示了很多反对意见。当然,你的情况可能会有所不同。 - DJ.
这段代码只适用于本地登录 - 对于远程访问凭据(基本上只是SQL连接),您必须使用等效的/NETONLY标志,我现在正在努力确定它。 - Cade Roux
1
这个链接有点说明了区别:http://www.eggheadcafe.com/conversation.aspx?messageid=32443204&threadid=32442982 - 我可能需要创建一个新的进程。 - Cade Roux
不同的登录类型和提供程序可能会有所帮助:http://blogs.catalystss.com/blogs/jonathan_rupp/archive/2008/02/26/sometimes-impersonation-isn-t-enough.aspx。在原始情况下,本地计算机是同一个域的一部分,因此该解决方案可能不适用于此处。 - Jonathan Rupp
@Jonathan - 很好的观点,我正在使用这个来从同一域上的远程计算机中提取事件日志数据。 - John Rasch

4
我收集了这些有用的链接: http://www.developmentnow.com/g/36_2006_3_0_0_725350/Need-help-with-impersonation-please-.htm http://blrchen.spaces.live.com/blog/cns!572204F8C4F8A77A!251.entry 链接 http://msmvps.com/blogs/martinzugec/archive/2008/06/03/use-runas-from-non-domain-computer.aspx 结果是,我将不得不使用CreateProcessWithLogonWLOGON_NETCREDENTIALS_ONLY。我将尝试让程序检测是否已以这种方式启动,如果没有,则获取域凭据并启动自身。这样只会有一个自管理的EXE。

1
我知道这已经很老了,但前两个链接(developmentnow.com和blrchen.spaces.live.com)已经失效。 - chrnola
@chrnola 最后一个也坏了。 - user8207463

3

通过这里提供的非常有用的答案,我创建了下面这个简化的类,使用的API也在.NET Standard中可用:

public class Impersonator
{
    [DllImport("ADVAPI32.DLL", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool LogonUser(
        string lpszUsername,
        string lpszDomain,
        string lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        out SafeAccessTokenHandle phToken);

    public void RunAs(string domain, string username, string password, Action action)
    {
        using (var accessToken = GetUserAccessToken(domain, username, password))
        {
            WindowsIdentity.RunImpersonated(accessToken, action);
        }
    }

    private SafeAccessTokenHandle GetUserAccessToken(string domain, string username, string password)
    {
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_NETONLY = 9;

        bool isLogonSuccessful = LogonUser(username, domain, password, LOGON32_LOGON_NETONLY, LOGON32_PROVIDER_DEFAULT, out var safeAccessTokenHandle);
        if (!isLogonSuccessful)
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        return safeAccessTokenHandle;
    }
}

以下是使用方法:

这里是如何使用它:

_impersonator.RunAs(
    "DOMAIN",
    "Username",
    "Password",
    () =>
    {
        Console.WriteLine("code executed here runs as the specified user with /netonly");
    });

2
是的,真的很棒!! - Stef
也许你应该加上:Impersonator _impersonator = new Impersonator(); - user8207463

2

这段代码是我们用于启动具有提升权限的外部进程的RunAs类的一部分。将用户名和密码设为null将提示标准的UAC警告。当为用户名和密码传递值时,您实际上可以在没有UAC提示的情况下启动应用程序并获得提升的权限。

public static Process Elevated( string process, string args, string username, string password, string workingDirectory )
{
    if( process == null || process.Length == 0 ) throw new ArgumentNullException( "process" );

    process = Path.GetFullPath( process );
    string domain = null;
    if( username != null )
        username = GetUsername( username, out domain );
    ProcessStartInfo info = new ProcessStartInfo();
    info.UseShellExecute = false;
    info.Arguments = args;
    info.WorkingDirectory = workingDirectory ?? Path.GetDirectoryName( process );
    info.FileName = process;
    info.Verb = "runas";
    info.UserName = username;
    info.Domain = domain;
    info.LoadUserProfile = true;
    if( password != null )
    {
        SecureString ss = new SecureString();
        foreach( char c in password )
            ss.AppendChar( c );
        info.Password = ss;
    }

    return Process.Start( info );
}

private static string GetUsername( string username, out string domain ) 
{
    SplitUserName( username, out username, out domain );

    if( domain == null && username.IndexOf( '@' ) < 0 )
        domain = Environment.GetEnvironmentVariable( "USERDOMAIN" );
    return username;
}

ProcessStartInfo(因此Process.Start方法)没有任何等效的设置来运行AS / NETONLY,其中网络凭据仅用于网络连接,而不用于本地线程/进程权限。 - Cade Roux
真遗憾...你可能需要使用PInvoke和CreateProcess。 - Paul Alexander

0

我猜你不能只是在 SQL Server 中为应用程序添加一个用户,然后使用 SQL 身份验证而不是 Windows 身份验证吧?


不行。我确实希望访问此控制面板的用户是他们自己。这就像一个控制面板,显示了许多进程,并允许用户触发它们,查看结果等。 - Cade Roux
我的客户希望所有的SQL用户通过Windows身份验证进行认证。他们说这是为了审计。 - Walter Stabosz
@WalterStabosz 那么您的客户应该将他的计算机加入到Active Directory域中。如果他们已经这样做了,那么只需要在连接字符串中使用“Trusted_Connection”选项即可。另外一个选择是有时候可以通过使用计划任务来分配正确的用户来运行进程来解决这个问题。 - Joel Coehoorn
1
@JoelCoehoorn 应用程序用户和 OP 处于同一艘船上,“我们的工作站不是域成员,我们的 SQL Server 在其中”。我唯一能够从我们的某个非域工作站使用 Trusted_Connection 的方法是使用 runas /netonly。这些用户是为我的客户工作的承包商,他们的工作站没有连接到客户的域,但他们被赋予了客户域的 AD 凭据。#大型跨国IT - Walter Stabosz

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接