Powershell에서 Active Directory 사용자를 어떻게 가장합니까?
-
08-06-2019 - |
문제
Exchange 2007에서 사서함 등을 생성하기 위해 웹 인터페이스(ASP.NET/C#)를 통해 powershell 명령을 실행하려고 합니다.Visual Studio(Cassini)를 사용하여 페이지를 실행하면 페이지가 올바르게 로드됩니다.그러나 IIS(v5.1)에서 실행하면 "알 수 없는 사용자 이름 또는 잘못된 암호"라는 오류가 발생합니다.제가 발견한 가장 큰 문제는 Powershell이 Active Directory 계정 대신 ASPNET으로 로그인되었다는 것입니다.Powershell 세션을 다른 Active Directory 계정으로 강제로 인증하려면 어떻게 해야 하나요?
기본적으로 지금까지 내가 가지고 있는 스크립트는 다음과 같습니다.
RunspaceConfiguration rc = RunspaceConfiguration.Create();
PSSnapInException snapEx = null;
rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapEx);
Runspace runspace = RunspaceFactory.CreateRunspace(rc);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
using (pipeline)
{
pipeline.Commands.AddScript("Get-Mailbox -identity 'user.name'");
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
if (pipeline.Error != null && pipeline.Error.Count > 0)
{
foreach (object item in pipeline.Error.ReadToEnd())
resultString += "Error: " + item.ToString() + "\n";
}
runspace.Close();
foreach (PSObject obj in results)
resultString += obj.ToString();
}
return resultString;
해결책 3
Exchange 2007에서는 보안상의 이유로 사용자를 가장하는 것을 허용하지 않습니다.즉, 현재로서는 사용자를 가장하여 사서함을 만드는 것이 불가능합니다.이 문제를 해결하기 위해 이메일 계정 생성 등의 권한이 있는 AD 사용자로 실행되는 웹 서비스를 만들었습니다.그런 다음 이 웹 서비스에 액세스하여 powershell에 액세스할 수 있습니다.이는 잠재적으로 큰 보안 허점이 될 수 있으므로 필요한 보안을 추가하는 것을 잊지 마십시오.
다른 팁
다음은 사용자를 가장하는 데 사용하는 클래스입니다.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace orr.Tools
{
#region Using directives.
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
}
}
ASP.NET 앱에서는 올바른 권한이 있는 유효한 AD 계정을 가장해야 합니다.
패치가 필요할 수도 있습니다.
에서: http://support.microsoft.com/kb/943937
응용 프로그램은 사용자를 가장 한 다음 Exchange Server 2007 환경에서 Windows PowerShell 명령을 실행할 수 없습니다.
이 문제를 해결하려면 Exchange Server 2007 서비스 팩 1의 업데이트 롤업 1을 설치하십시오.
MSDN 블로그의 이 기사에서는 이를 수행하는 방법을 보여 주는 것 같습니다. 아직 시도할 수는 없지만 시도하게 되면 알려 드리겠습니다.