我们的工作站不是我们的SQL Server所在域的成员。 (他们根本不在某个域上 - 不要问)。
当我们使用SSMS或任何东西连接到SQL Server时,我们将RUNAS / NETONLY与DOMAIN \ user一起使用。然后我们输入密码并启动程序。 (RUNAS / NETONLY不允许您在批处理文件中包含密码)。
所以我有一个需要SQL连接的.NET WinForms应用程序,用户必须通过运行具有RUNAS / NETONLY命令行的批处理文件启动它,然后启动EXE。
如果用户意外直接启动EXE,则无法连接到SQL Server。
右键单击应用程序并使用“运行方式...”选项不起作用(可能是因为工作站并不真正了解域名)。
我正在寻找一种方法让应用程序在内部启动之前执行RUNAS / NETONLY功能。
有关RUNAS / NETONLY如何运作的说明,请参阅此链接:http://www.eggheadcafe.com/conversation.aspx?messageid=32443204&threadid=32442982
我想我必须LOGON_NETCREDENTIALS_ONLY
使用CreateProcessWithLogonW
答案 0 :(得分:11)
我知道这是一个旧线程,但它非常有用。我有与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 :(得分:6)
我只是使用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
}
/////////////////////////////////////////////////////////////////////////
}
答案 2 :(得分:3)
我收集了这些有用的链接:
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://geekswithblogs.net/khanna/archive/2005/02/09/22430.aspx
http://msmvps.com/blogs/martinzugec/archive/2008/06/03/use-runas-from-non-domain-computer.aspx
事实证明,我将不得不将LOGON_NETCREDENTIALS_ONLY
与CreateProcessWithLogonW
一起使用。我将看看我是否可以检测程序是否以这种方式启动,如果没有,则收集域凭据并启动自身。这样只会有一个自我管理的EXE。
答案 3 :(得分:2)
此代码是RunAs类的一部分,我们用它来启动具有提升的特权的外部进程。为用户名&amp;传递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;
}
答案 4 :(得分:0)
我想您不能只是将应用程序的用户添加到sql server然后使用sql身份验证而不是Windows身份验证?
答案 5 :(得分:0)
在这里使用非常有用的答案,我创建了以下简化的类,该类使用.NET Standard中也可用的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");
});