C# でのユーザーの偽装に問題があります。
何千もの例で使用されている既知の機能を偽装します。
using(Impersonator impClass = new Impersonator(_domain, _userName, _password)) ...
なりすましの後、私は実行します
System.Security.Principal.WindowsIdentity.GetCurrent().Name
正しい(偽装された)ユーザーを取得します。
そのため、なりすましは一般的に機能しています。
しかし、偽装後に実行空間 ( powershell ) を開くと、偽装前の古いユーザーが使用されています。
私が使用するコードの一部を次に示します。
using(Impersonator impClass = new Impersonator(_domain, _userName, _password))
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
logger.Debug("after imp windows: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
using (Pipeline pipeline = runspace.CreatePipeline())
{
List<Command> commandList = new List<Command>();
Command cmd = new Command("whoami");
commandList.Add(cmd);
foreach (Command command in commandList)
{
pipeline.Commands.AddScript(command.ToString()); pipeline.Commands.AddScript(command.ToString());
}
var res = pipeline.Invoke();
}
}
ログが言っていることは次のとおりです。
Windows ID: "impersonatedUser" <- 正しい
Powershell からの WhoAmI: "NotImpersonatedUser" <- 不正解
私は自分が間違っていることを本当に知りません。助けてください、もう何時間も無駄にしてしまいました...
これは私が使用している偽装クラスの一部です:
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);
}
}
}