如何在Windows服务中模拟时调用net.pipe(命名管道)WCF服务

时间:2015-10-08 17:42:47

标签: .net windows wcf named-pipes impersonation

我在使用来自C#Windows服务的Windows模拟调用net.pipe上的WCF服务时出现问题。

背景

服务从队列中读取并创建子应用程序域,每个域运行特定模块,每个项目从队列中提取。我们将Windows服务称为“JobQueueAgent”,并将每个模块称为“Job”。我将继续使用这些术语。可以将作业配置为以指定用户身份运行。我们在作业的app域中使用模拟来完成此任务。 以下是服务中的逻辑和凭据流:

JobQueueAgent(Windows服务 - 主要用户)>>创建职位域>> 作业域(App Domain)>>模仿子用户>> 使用模拟>>在线程上运行作业 作业(模块 - 子用户)>>工作逻辑

“主要用户”和“子用户”都是具有“作为服务登录”权限的域帐户。

该服务在运行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调用失败。

以下是我在这种情况下遇到的例外情况:

  

未处理的异常:System.ComponentModel.Win32Exception:Access是   拒绝

     

服务器堆栈跟踪:at   System.ServiceModel.Channels.AppContainerInfo.GetCurrentProcessToken()   在   System.ServiceModel.Channels.AppContainerInfo.RunningInAppContainer()   在   System.ServiceModel.Channels.AppContainerInfo.get_IsRunningInAppContainer()   在System.ServiceModel.Channels.PipeSharedMemory.BuildPipeName(String   pipeGuid)

如果没有在模拟下运行,net.pipe会成功。将模拟用户添加到Administrators组时,net.pipe调用也会成功。这意味着用户在模仿时需要有一些特权来进行呼叫。在模仿时,我们无法确定用户进行net.pipe调用所需的策略,权限或访问权限。将用户设为管理员是不可接受的。

这是一个已知问题吗?用户需要成功的特定权利吗?我是否可以通过代码更改来解决此问题? Using WCF's net.pipe in a website with impersonate=true似乎表明由于NetworkService,这在ASP.NET应用程序中不起作用。不确定,但这不适用于此。

3 个答案:

答案 0 :(得分:4)

在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();
        }
    }
}

答案 1 :(得分:1)

啊,这就是问题所在:

  

服务器堆栈跟踪:at   System.ServiceModel.Channels.AppContainerInfo.GetCurrentProcessToken()

当您尝试打开管道时,系统会检查您是否在应用容器中。这涉及查询进程令牌,您假冒的用户无权执行此操作。

这对我来说似乎是个错误。您可以尝试与Microsoft打开付费支持案例,但无法保证他们愿意发布修补程序,或者他们能够尽快解决问题以满足您的需求。

所以我看到两个看似合理的解决方法:

  • 在模拟之前,更改进程访问令牌上的ACL以授予TOKEN_QUERY对新登录令牌的访问权限。我相信登录令牌将包含登录SID,因此这是最安全的选择,但是授予对用户帐户的访问权限应该不会太危险。据我所知,use PayPal\Api\object; 访问权限并未显示任何特别敏感的信息。

  • 您可以在子用户的上下文中启动子进程,而不是使用模拟。效率较低且不太方便,但这是解决问题的简单方法。

答案 2 :(得分:0)