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

2cmtqfgy  于 2022-10-22  发布在  C#
关注(0)|答案(7)|浏览(79)

我们的工作站不是SQL Server所在域的成员。(它们实际上根本不在域中-不要问)。
当我们使用SSMS或任何东西连接到SQL Server时,我们将RUNAS/NETONLY与DOMAIN\user一起使用。然后我们输入密码,它就会启动程序。(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_ONLYCreateProcessWithLogonW

jm2pwxwz

jm2pwxwz1#

我知道这是一个旧线程,但它非常有用。我和Cade Roux的情况完全一样,因为我想要/网络风格的功能。

John Rasch的答案只需稍作修改就可以了

添加以下常量(为一致性,请围绕第102行):

private const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

然后将调用更改为LogonUser,以使用LOGON32_LOGON_NEW_CREDENTIALS而不是LOGON32_LOGON_INTERACTIVE
这是我唯一需要做的改变,让它完美运行!!!谢谢约翰和凯德!!!
以下是为便于复制/粘贴而修改的完整代码:

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
    }

    /////////////////////////////////////////////////////////////////////////
}
vmdwslir

vmdwslir2#

我刚刚用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
    }

    /////////////////////////////////////////////////////////////////////////
}
ffvjumwh

ffvjumwh3#

我收集了这些有用的链接:
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
i1 j2 k1 l
http://msmvps.com/blogs/martinzugec/archive/2008/06/03/use-runas-from-non-domain-computer.aspx
事实证明,我将不得不使用LOGON_NETCREDENTIALS_ONLYCreateProcessWithLogonW。我将看看是否可以让程序检测到它是否以这种方式启动,如果没有,则收集域凭据并自行启动。这样,只有一个自我管理的EXE。

ycl3bljg

ycl3bljg4#

此代码是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;
}
7xllpg7q

7xllpg7q5#

使用这里非常有用的答案,我创建了下面的简化类,它使用了.NET标准中提供的API:

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");
    });
qyswt5oh

qyswt5oh6#

我想你不能只为应用程序添加一个用户到sqlserver,然后使用sql身份验证而不是windows身份验证吗?

eiee3dmh

eiee3dmh7#

对于.NET Core,WindowsImpersonationContextWindowsIdentity.Impersonate()不可用。
这里有一个链接,指向.NETCore的类似解决方案。WindowsImpersonationContext & Impersonate() not found in ASP.Core

相关问题