如何在模拟 Windows 服务时调用 net.pipe(命名管道)WCF 服务
How to call net.pipe (named pipe) WCF services while impersonating in a Windows Service
我在使用来自 C# Windows 服务的 Windows 模拟通过 net.pipe 调用 WCF 服务时遇到问题。
背景
该服务从队列中读取并创建子应用程序域,每个子应用程序域 运行根据从队列中拉出的项目创建一个特定模块。我们将 Windows 服务称为“JobQueueAgent”,每个模块称为“作业”。我将继续使用这些术语。可以将作业配置为 运行 作为指定用户。我们在作业的应用程序域内使用模拟来完成此操作。
以下是服务中的逻辑和凭证流程:
JobQueueAgent(Windows 服务 – 主要用户)>> 创建作业域 >>
工作域(应用域)>> 模拟子用户>>
运行 线程上的作业与模拟 >>
作业(模块 – 子用户)>> 作业逻辑
“主用户”和“子用户”都是具有“作为服务登录”权限的域帐户。
服务 运行s 在虚拟服务器 运行ning Windows Server 2012 R2 上。
以下是我使用的C#模拟代码:
namespace JobQueue.WindowsServices
{
using System;
using System.ComponentModel;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Permissions;
using System.Security.Principal;
internal sealed class ImpersonatedIdentity : IDisposable
{
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public ImpersonatedIdentity(NetworkCredential credential)
{
if (credential == null) throw new ArgumentNullException("credential");
if (LogonUser(credential.UserName, credential.Domain, credential.Password, 5, 0, out _handle))
{
_context = WindowsIdentity.Impersonate(_handle);
}
else
{
throw new AuthenticationException("Impersonation failed.", newWin32Exception(Marshal.GetLastWin32Error()));
}
}
~ImpersonatedIdentity()
{
Dispose();
}
public void Dispose()
{
if (_handle != IntPtr.Zero)
{
CloseHandle(_handle);
_handle = IntPtr.Zero;
}
if (_context != null)
{
_context.Undo();
_context.Dispose();
_context = null;
}
GC.SuppressFinalize(this);
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool LogonUser(string userName, string domain, string password, int logonType,int logonProvider, out IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
private IntPtr _handle = IntPtr.Zero;
private WindowsImpersonationContext _context;
}
}
问题
某些作业需要对服务器上的另一个 Windows 服务 运行 进行 net.pipe WCF 服务调用。 net.pipe 调用在模拟 运行ning 时失败。
这是我在这种情况下遇到的异常:
Unhandled Exception: System.ComponentModel.Win32Exception: Access is
denied
Server stack trace: at
System.ServiceModel.Channels.AppContainerInfo.GetCurrentProcessToken()
at
System.ServiceModel.Channels.AppContainerInfo.RunningInAppContainer()
at
System.ServiceModel.Channels.AppContainerInfo.get_IsRunningInAppContainer()
at System.ServiceModel.Channels.PipeSharedMemory.BuildPipeName(String
pipeGuid)
net.pipe 未在模拟下 运行ning 时成功。当模拟用户被添加到管理员组时,net.pipe 调用也会成功。这意味着用户需要一些特权才能在模拟状态下进行呼叫。我们无法确定用户在模拟时进行 net.pipe 调用需要什么策略、权限或访问权限。让用户成为管理员是不可接受的。
这是一个已知问题吗?用户是否需要特定的权利才能成功?我可以更改代码来解决此问题吗? Using WCF's net.pipe in a website with impersonate=true 似乎表明由于网络服务,这在 ASP.NET 应用程序中不起作用。不确定,但这不应该适用于此。
如果没有提升(管理员)权限,这似乎是不可能的。
不过,这里描述的双工合同可能是关键。
Client on non-admin user can't communicate using net.pipe with services
啊,问题来了:
Server stack trace: at
System.ServiceModel.Channels.AppContainerInfo.GetCurrentProcessToken()
当您尝试打开管道时,系统会检查您是否在应用程序容器中。这涉及查询进程令牌,您正在模拟的用户无权执行此操作。
这对我来说似乎是一个错误。您可以尝试向 Microsoft 提交付费支持案例,但不能保证他们愿意发布修补程序或能够尽快解决问题以满足您的需求。
所以我看到了两个可行的解决方法:
在模拟之前,更改进程访问令牌上的 ACL 以授予 TOKEN_QUERY
对新登录令牌的访问权限。我相信登录令牌将包含一个登录 SID,因此这将是最安全的选择,但授予用户帐户访问权限应该不会太危险。据我所知,TOKEN_QUERY
访问权限不会泄露任何特别敏感的信息。
您可以在子用户的上下文中启动子进程,而不是使用模拟。效率较低,也不太方便,但这是解决问题的简单方法。
在 Microsoft 支持的帮助下,我能够通过修改线程标识的访问权限来解决此问题(Harry Johnston 在另一个答案中提出的建议)。这是我现在使用的模拟代码:
using System;
using System.ComponentModel;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Authentication;
using System.Security.Permissions;
using System.Security.Principal;
internal sealed class ImpersonatedIdentity : IDisposable
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public ImpersonatedIdentity(NetworkCredential credential)
{
if (credential == null) throw new ArgumentNullException(nameof(credential));
_processIdentity = WindowsIdentity.GetCurrent();
var tokenSecurity = new TokenSecurity(new SafeTokenHandleRef(_processIdentity.Token), AccessControlSections.Access);
if (!LogonUser(credential.UserName, credential.Domain, credential.Password, 5, 0, out _token))
{
throw new AuthenticationException("Impersonation failed.", new Win32Exception(Marshal.GetLastWin32Error()));
}
_threadIdentity = new WindowsIdentity(_token);
tokenSecurity.AddAccessRule(new AccessRule<TokenRights>(_threadIdentity.User, TokenRights.TOKEN_QUERY, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow));
tokenSecurity.ApplyChanges();
_context = _threadIdentity.Impersonate();
}
~ImpersonatedIdentity()
{
Dispose();
}
public void Dispose()
{
if (_processIdentity != null)
{
_processIdentity.Dispose();
_processIdentity = null;
}
if (_token != IntPtr.Zero)
{
CloseHandle(_token);
_token = IntPtr.Zero;
}
if (_context != null)
{
_context.Undo();
_context.Dispose();
_context = null;
}
GC.SuppressFinalize(this);
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, out IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
private WindowsIdentity _processIdentity;
private WindowsIdentity _threadIdentity;
private IntPtr _token = IntPtr.Zero;
private WindowsImpersonationContext _context;
[Flags]
private enum TokenRights
{
TOKEN_QUERY = 8
}
private class TokenSecurity : ObjectSecurity<TokenRights>
{
public TokenSecurity(SafeHandle safeHandle, AccessControlSections includeSections)
: base(false, ResourceType.KernelObject, safeHandle, includeSections)
{
_safeHandle = safeHandle;
}
public void ApplyChanges()
{
Persist(_safeHandle);
}
private readonly SafeHandle _safeHandle;
}
private class SafeTokenHandleRef : SafeHandle
{
public SafeTokenHandleRef(IntPtr handle)
: base(IntPtr.Zero, false)
{
SetHandle(handle);
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
}
protected override bool ReleaseHandle()
{
throw new NotImplementedException();
}
}
}
我在使用来自 C# Windows 服务的 Windows 模拟通过 net.pipe 调用 WCF 服务时遇到问题。
背景
该服务从队列中读取并创建子应用程序域,每个子应用程序域 运行根据从队列中拉出的项目创建一个特定模块。我们将 Windows 服务称为“JobQueueAgent”,每个模块称为“作业”。我将继续使用这些术语。可以将作业配置为 运行 作为指定用户。我们在作业的应用程序域内使用模拟来完成此操作。 以下是服务中的逻辑和凭证流程:
JobQueueAgent(Windows 服务 – 主要用户)>> 创建作业域 >> 工作域(应用域)>> 模拟子用户>> 运行 线程上的作业与模拟 >> 作业(模块 – 子用户)>> 作业逻辑
“主用户”和“子用户”都是具有“作为服务登录”权限的域帐户。
服务 运行s 在虚拟服务器 运行ning Windows Server 2012 R2 上。
以下是我使用的C#模拟代码:
namespace JobQueue.WindowsServices
{
using System;
using System.ComponentModel;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Permissions;
using System.Security.Principal;
internal sealed class ImpersonatedIdentity : IDisposable
{
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public ImpersonatedIdentity(NetworkCredential credential)
{
if (credential == null) throw new ArgumentNullException("credential");
if (LogonUser(credential.UserName, credential.Domain, credential.Password, 5, 0, out _handle))
{
_context = WindowsIdentity.Impersonate(_handle);
}
else
{
throw new AuthenticationException("Impersonation failed.", newWin32Exception(Marshal.GetLastWin32Error()));
}
}
~ImpersonatedIdentity()
{
Dispose();
}
public void Dispose()
{
if (_handle != IntPtr.Zero)
{
CloseHandle(_handle);
_handle = IntPtr.Zero;
}
if (_context != null)
{
_context.Undo();
_context.Dispose();
_context = null;
}
GC.SuppressFinalize(this);
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool LogonUser(string userName, string domain, string password, int logonType,int logonProvider, out IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
private IntPtr _handle = IntPtr.Zero;
private WindowsImpersonationContext _context;
}
}
问题
某些作业需要对服务器上的另一个 Windows 服务 运行 进行 net.pipe WCF 服务调用。 net.pipe 调用在模拟 运行ning 时失败。
这是我在这种情况下遇到的异常:
Unhandled Exception: System.ComponentModel.Win32Exception: Access is denied
Server stack trace: at System.ServiceModel.Channels.AppContainerInfo.GetCurrentProcessToken() at System.ServiceModel.Channels.AppContainerInfo.RunningInAppContainer() at System.ServiceModel.Channels.AppContainerInfo.get_IsRunningInAppContainer() at System.ServiceModel.Channels.PipeSharedMemory.BuildPipeName(String pipeGuid)
net.pipe 未在模拟下 运行ning 时成功。当模拟用户被添加到管理员组时,net.pipe 调用也会成功。这意味着用户需要一些特权才能在模拟状态下进行呼叫。我们无法确定用户在模拟时进行 net.pipe 调用需要什么策略、权限或访问权限。让用户成为管理员是不可接受的。
这是一个已知问题吗?用户是否需要特定的权利才能成功?我可以更改代码来解决此问题吗? Using WCF's net.pipe in a website with impersonate=true 似乎表明由于网络服务,这在 ASP.NET 应用程序中不起作用。不确定,但这不应该适用于此。
如果没有提升(管理员)权限,这似乎是不可能的。
不过,这里描述的双工合同可能是关键。
Client on non-admin user can't communicate using net.pipe with services
啊,问题来了:
Server stack trace: at System.ServiceModel.Channels.AppContainerInfo.GetCurrentProcessToken()
当您尝试打开管道时,系统会检查您是否在应用程序容器中。这涉及查询进程令牌,您正在模拟的用户无权执行此操作。
这对我来说似乎是一个错误。您可以尝试向 Microsoft 提交付费支持案例,但不能保证他们愿意发布修补程序或能够尽快解决问题以满足您的需求。
所以我看到了两个可行的解决方法:
在模拟之前,更改进程访问令牌上的 ACL 以授予
TOKEN_QUERY
对新登录令牌的访问权限。我相信登录令牌将包含一个登录 SID,因此这将是最安全的选择,但授予用户帐户访问权限应该不会太危险。据我所知,TOKEN_QUERY
访问权限不会泄露任何特别敏感的信息。您可以在子用户的上下文中启动子进程,而不是使用模拟。效率较低,也不太方便,但这是解决问题的简单方法。
在 Microsoft 支持的帮助下,我能够通过修改线程标识的访问权限来解决此问题(Harry Johnston 在另一个答案中提出的建议)。这是我现在使用的模拟代码:
using System;
using System.ComponentModel;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Authentication;
using System.Security.Permissions;
using System.Security.Principal;
internal sealed class ImpersonatedIdentity : IDisposable
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public ImpersonatedIdentity(NetworkCredential credential)
{
if (credential == null) throw new ArgumentNullException(nameof(credential));
_processIdentity = WindowsIdentity.GetCurrent();
var tokenSecurity = new TokenSecurity(new SafeTokenHandleRef(_processIdentity.Token), AccessControlSections.Access);
if (!LogonUser(credential.UserName, credential.Domain, credential.Password, 5, 0, out _token))
{
throw new AuthenticationException("Impersonation failed.", new Win32Exception(Marshal.GetLastWin32Error()));
}
_threadIdentity = new WindowsIdentity(_token);
tokenSecurity.AddAccessRule(new AccessRule<TokenRights>(_threadIdentity.User, TokenRights.TOKEN_QUERY, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow));
tokenSecurity.ApplyChanges();
_context = _threadIdentity.Impersonate();
}
~ImpersonatedIdentity()
{
Dispose();
}
public void Dispose()
{
if (_processIdentity != null)
{
_processIdentity.Dispose();
_processIdentity = null;
}
if (_token != IntPtr.Zero)
{
CloseHandle(_token);
_token = IntPtr.Zero;
}
if (_context != null)
{
_context.Undo();
_context.Dispose();
_context = null;
}
GC.SuppressFinalize(this);
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, out IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
private WindowsIdentity _processIdentity;
private WindowsIdentity _threadIdentity;
private IntPtr _token = IntPtr.Zero;
private WindowsImpersonationContext _context;
[Flags]
private enum TokenRights
{
TOKEN_QUERY = 8
}
private class TokenSecurity : ObjectSecurity<TokenRights>
{
public TokenSecurity(SafeHandle safeHandle, AccessControlSections includeSections)
: base(false, ResourceType.KernelObject, safeHandle, includeSections)
{
_safeHandle = safeHandle;
}
public void ApplyChanges()
{
Persist(_safeHandle);
}
private readonly SafeHandle _safeHandle;
}
private class SafeTokenHandleRef : SafeHandle
{
public SafeTokenHandleRef(IntPtr handle)
: base(IntPtr.Zero, false)
{
SetHandle(handle);
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero || handle == new IntPtr(-1); }
}
protected override bool ReleaseHandle()
{
throw new NotImplementedException();
}
}
}