首页 > 系统相关 >【转】【C#】Windows服务运行exe程序

【转】【C#】Windows服务运行exe程序

时间:2024-11-13 18:45:44浏览次数:1  
标签:IntPtr process exe C# Windows int uint ref public

在“Windows服务”中,上述代码还是可以运行exe程序的,但是我们看不到。在“控制台应用程序”中,我们可以看到被执行的exe程序,但是到了“Windows服务”中,该exe变成了后台执行,无法与用户进行交互。
原因如下:
  默认情况下,服务是运行在session0下的,与普通的应用程序不在一个session,所以不能互动,但是我们可以利用函数“CreateProcessAsUser”来创建应用程序session下的进程,从而调用外部exe。
Windows服务(C#)显式运行外部exe程序源代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace SngjIPS_WindowsService
{
    class UserProcess
    {   #region Structures
        [StructLayout(LayoutKind.Sequential)]
        public struct SECURITY_ATTRIBUTES
        {
            public int Length;
            public IntPtr lpSecurityDescriptor;
            public bool bInheritHandle;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct STARTUPINFO
        {
            public int cb;
            public String lpReserved;
            public String lpDesktop;
            public String lpTitle;
            public uint dwX;
            public uint dwY;
            public uint dwXSize;
            public uint dwYSize;
            public uint dwXCountChars;
            public uint dwYCountChars;
            public uint dwFillAttribute;
            public uint dwFlags;
            public short wShowWindow;
            public short cbReserved2;
            public IntPtr lpReserved2;
            public IntPtr hStdInput;
            public IntPtr hStdOutput;
            public IntPtr hStdError;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct PROCESS_INFORMATION
        {
            public IntPtr hProcess;
            public IntPtr hThread;
            public uint dwProcessId;
            public uint dwThreadId;
        }
        #endregion
        #region Enumerations
        enum TOKEN_TYPE : int
        {
            TokenPrimary = 1,
            TokenImpersonation = 2
        }
        enum SECURITY_IMPERSONATION_LEVEL : int
        {
            SecurityAnonymous = 0,
            SecurityIdentification = 1,
            SecurityImpersonation = 2,
            SecurityDelegation = 3,
        }
        enum WTSInfoClass
        {
            InitialProgram,
            ApplicationName,
            WorkingDirectory,
            OEMId,
            SessionId,
            UserName,
            WinStationName,
            DomainName,
            ConnectState,
            ClientBuildNumber,
            ClientName,
            ClientDirectory,
            ClientProductId,
            ClientHardwareId,
            ClientAddress,
            ClientDisplay,
            ClientProtocolType
        }
        #endregion
        #region Constants
        public const int TOKEN_DUPLICATE = 0x0002;
        public const uint MAXIMUM_ALLOWED = 0x2000000;
        public const int CREATE_NEW_CONSOLE = 0x00000010;
        public const int IDLE_PRIORITY_CLASS = 0x40;
        public const int NORMAL_PRIORITY_CLASS = 0x20;
        public const int HIGH_PRIORITY_CLASS = 0x80;
        public const int REALTIME_PRIORITY_CLASS = 0x100;
        #endregion
        #region Win32 API Imports
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(IntPtr hSnapshot);
        [DllImport("kernel32.dll")]
        static extern uint WTSGetActiveConsoleSessionId();
        [DllImport("wtsapi32.dll", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
        static extern bool WTSQuerySessionInformation(System.IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);
        [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
        public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
            ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
            String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
        [DllImport("kernel32.dll")]
        static extern bool ProcessIdToSessionId(uint dwProcessId, ref uint pSessionId);
        [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
        public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,
            ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType,
            int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
        [DllImport("kernel32.dll")]
        static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
        [DllImport("advapi32", SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
        static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle);
        #endregion
        public static string GetCurrentActiveUser()
        {
            IntPtr hServer = IntPtr.Zero, state = IntPtr.Zero;
            uint bCount = 0;
            // obtain the currently active session id; every logged on user in the system has a unique session id  
            uint dwSessionId = WTSGetActiveConsoleSessionId();
            string domain = string.Empty, userName = string.Empty;
            if (WTSQuerySessionInformation(hServer, (int)dwSessionId, WTSInfoClass.DomainName, out state, out bCount))
            {
                domain = Marshal.PtrToStringAuto(state);
            }
            if (WTSQuerySessionInformation(hServer, (int)dwSessionId, WTSInfoClass.UserName, out state, out bCount))
            {
                userName = Marshal.PtrToStringAuto(state);
            }
            return string.Format("{0}\\{1}", domain, userName);
        }
        /// <summary>  
        /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt  
        /// </summary>  
        /// <param name="applicationName">The name of the application to launch</param>  
        /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param>  
        /// <returns></returns>  
        public static bool StartProcessAndBypassUAC(String applicationName, String command, out PROCESS_INFORMATION procInfo)
        {
            uint winlogonPid = 0;
            IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;
            procInfo = new PROCESS_INFORMATION();
            // obtain the currently active session id; every logged on user in the system has a unique session id  
            uint dwSessionId = WTSGetActiveConsoleSessionId();
            // obtain the process id of the winlogon process that is running within the currently active session  
            Process[] processes = Process.GetProcessesByName("winlogon");
            foreach (Process p in processes)
            {
                if ((uint)p.SessionId == dwSessionId)
                {
                    winlogonPid = (uint)p.Id;
                }
            }
            // obtain a handle to the winlogon process  
            hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);
            // obtain a handle to the access token of the winlogon process  
            if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hPToken))
            {
                CloseHandle(hProcess);
                return false;
            }
            // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser  
            // I would prefer to not have to use a security attribute variable and to just   
            // simply pass null and inherit (by default) the security attributes  
            // of the existing token. However, in C# structures are value types and therefore  
            // cannot be assigned the null value.  
            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
            sa.Length = Marshal.SizeOf(sa);
            // copy the access token of the winlogon process; the newly created token will be a primary token  
            if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
            {
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                return false;
            }
            // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning  
            // the window station has a desktop that is invisible and the process is incapable of receiving  
            // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user   
            // interaction with the new process.  
            STARTUPINFO si = new STARTUPINFO();
            si.cb = (int)Marshal.SizeOf(si);
            si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop  
            // flags that specify the priority and creation method of the process  
            int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
            // create a new process in the current user's logon session  
            bool result = CreateProcessAsUser(hUserTokenDup,        // client's access token  
                                            applicationName,        // file to execute  
                                            command,                // command line  
                                            ref sa,                 // pointer to process SECURITY_ATTRIBUTES  
                                            ref sa,                 // pointer to thread SECURITY_ATTRIBUTES  
                                            false,                  // handles are not inheritable  
                                            dwCreationFlags,        // creation flags  
                                            IntPtr.Zero,            // pointer to new environment block   
                                            null,                   // name of current directory   
                                            ref si,                 // pointer to STARTUPINFO structure  
                                            out procInfo            // receives information about new process  
                                            );
            // invalidate the handles  
            CloseHandle(hProcess);
            CloseHandle(hPToken);
            CloseHandle(hUserTokenDup);
            return result; // return the result  
        }
    }
 }

调用如下:

UserProcess.PROCESS_INFORMATION pInfo = new UserProcess.PROCESS_INFORMATION();
UserProcess.StartProcessAndBypassUAC("xxx.exe", string.Empty, out pInfo);

注意,该程序一定要写在“Windows服务”程序的代码中才有效,如果你把本程序代码写在“控制台应用程序”中运行是没有任何效果的。

原文地址:https://cognize.me/windowsservice/

标签:IntPtr,process,exe,C#,Windows,int,uint,ref,public
From: https://www.cnblogs.com/mqxs/p/18544559

相关文章

  • 大数据学习13之Scala基础语法(重点)
    1.简介        Scala是ScalableLanguage的简写,是一门多范式的编程语言。创始人为MartinOdersky马丁·奥德斯基。        Scala这个名字来源于ScalableLanguage(可伸缩的语言),它是一门基于JVM的多范式编程语言,通俗的说:Scala是一种运行在JVM上的......
  • CRUXEval: 代码推理、理解和执行的评估方法
    CRUXEval(CodeReasoning,Understanding,andeXecutionEvaluation)是一个在HumanEval上进行改进的benchmark。由800个Pythonfunction组成。paper:CRUXEval:ABenchmarkforCodeReasoning,UnderstandingandExecutionGitHub:cruxeval评估过程每个函数都带有一......
  • 用idea的docker插件生成镜像并推送到服务器
    准备这两个文件......
  • 告别头文件,编译效率提升 42%!C++ Modules 实战解析 | 干货推荐
    编者按:AlibabaCloudLinux(简称“Alinux”)是目前阿里云上占比第一的操作系统。2021年,龙蜥以Alinux产品为基础发布了AnolisOS8正式版。本文中,阿里云智能集团开发工程师李泽政以Alinux为操作环境,讲解模块相比传统头文件有哪些优势,并通过若干个例子,学习如何组织一个C++模......
  • starrycan的pwn学习记录1
    一.Introducation0x01简介CTF0x02什么是pwn”Pwn”是一个黑客语法的俚语词,是指攻破设备或者系统。发音类似“砰”,对黑客而言这就是成功实施黑客攻击的声音--砰的一声,被“黑”的电脑或手机就被你操纵了。CTF中的pwnCTF中的PWN主要是针对于二进制漏洞挖掘与利用,通常情况下选......
  • 如何将下载的mp4视频嵌入react应用程序?
    将下载的mp4视频嵌入React应用程序可以通过以下步骤实现:将下载的mp4视频文件放置在React应用程序的合适位置,例如在public文件夹下创建一个videos文件夹,并将视频文件放置其中。在React组件中引入视频文件,可以使用<video>标签来嵌入视频。在组件的render方法中,可以使用以下代码来......
  • COMP2011J - Object Oriented Programming
    Beijing-DublinInternationalCollegeCOMP2011J-ObjectOrientedProgrammingIndividualAssignment:DefenderAssignmentDetailsDuedate:6thofDecember2024Language:SolutionmustbecompletedinJavaGameDescriptionDefenderisaclassicarcadega......
  • AtCoder Beginner Contest 353 - VP 记录
    Preface这次比赛蛮简单的,就是黄题有点多,少了区分度。而且SigmaProblemAnotherSigmaProblemYetAnotherSigmaProblem是什么奇妙的题目名称?SigmaProblemAnotherSigmaProblemYetAnotherSigmaProblem\(\texttt{\scriptsizeYet\footnotesizeA......
  • ECMAScript 安全赋值运算符 (?=) 提案介绍及其 Polyfill
    本文介绍最新的ECMAScript安全赋值运算符提案以及相应的替代实现前言我们经常会跟try/catch打交道,但如果你写过Go或者Rust就会发现在这两种语言中是没有try/catch的,那么这些语言怎么进行错误捕获呢Go:Errorhandlingf,err:=os.Open("filename.ext")iferr......
  • Privilege Escalation(权限提升)
    PrivilegeEscalation(权限提升)WhattheShell?Whatisashellshell是我们与命令行环境(CLI)交互时使用的工具。换句话说,Linux中常见的bash或sh程序都是shell的例子,Windows上的cmd.exe和Powershell也是如此。简而言之,我们可以强制远程服务器向我们发送对服务......