На мастер-классе будут рассматриваться современные методы противодействия анализу вредоносного ПО: «антиотладка», запуск в виртуальных машинах, трюки антидисассемблирования, упаковка и шифрование кода с использованием современных подходов и инструментов.
Для участия в мастер-классе вам понадобится ноутбук, виртуальная машина с Windows XP c установленными OllyDbg и дизассемблером.
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Современные технологии и инструменты анализа вредоносного ПО
1. СОВРЕМЕННЫЕ ТЕХНОЛОГИИ И ИНСТРУМЕНТЫ
АНАЛИЗА ВРЕДОНОСНОГО ПО
«ТЕХНИКИ ПРОТИВОДЕЙСТВИЯ АНАЛИЗУ
БИНАРНОГО КОГДА MALWARE»
ИВАН ПИСКУНОВ
23-24 мая 2017
2017
2. [ #WhoAme ]
• В индустрии безопасности более 9 лет
• Член сибирской CTF-команды CrazY geek$ (2008 - ..)
• Автор блога www.ipiskunov.blogspot.com
• Персональная колонка www.SecurityLab.ru «ИБ в
деталях»
• Цикл статей для ][акер «Реверсинг малвари для
начинающих»
• Курс «Этичный хакер» в школе программирования
для детей «Coddy School»
3. [ Intro ]
На мастер-классе будут рассматриваться современные
методы противодействия анализу вредоносного ПО:
• «антиотладка»,
• запуск в виртуальных машинах,
• трюки анти-дисассемблирования.
с использованием современных подходов и инструментов.
6. [ Anti-debugging ]
Все анти-отладочные приемы условно можно разделить на две
группы:
• Усложнение возможной отладки. Это прежде всего
обфускация кода, паковка/криптовка, использование
исключений, разделение кода на потоки/библиотеки,
мусорные функции и т.д.
• Обнаружение отладки. Происходит обнаружение самого
факта запуска отладчика: через созданные для этого функции
или через нахождения окна/процесса отладчика, нахождение
брекпоинтов (CC, проверка атрибутов доступа и др.), замеры
времени и т.д.
7. [ Anti-debugging ]
ОБЩИЕ МЕТОДЫ:
1. Windows API function
2. Manually checking «Flags»
3. Check system residue (key in reestr)
4. Program behavior
• Break points
• CheckSum
• Timing check
РЕЗУЛЬТАТЫ ПРОТИВОДЕЙСТВИЯ:
• Suspend
• Crash debug-program (exception)
• TSL Callback
• Crash debugger (The OutputDebugString Vulnerability)
• PE Heder Vulnerability
8. Antidebug
API calls
• IsDebuggerPresent - probably the most well-known technique and one of the easiest to bypass. This API checks
specific flag in PEB and returns TRUE/FALSE based on the result.
• CheckRemoteDebuggerPresent - same functionality as previous - simple bool function, straight use
• FindWindow - used to detect specific debuggers - for instance, OllyDbg window class is named “OLLYDBG” :) Other
popular debuggers classes checks include “WinDbgFrameClass”, “ID”, “Zeta Debugger”, “Rock Debugger” and
“ObsidianGUI”
• NtQueryObject - detection is based on “debug objects”. API queries for the list of existing objects and checks the
number of handles associated with any existing debug object
• NtQuerySystemInformation (ZwQuerySystemInformation) - similar to previous point - checks if debug object handle
exists and returns true if it’s the case
• NtSetInformationThread (ZwSetInformationThread) - the first anti-debugging API implemented by Windows. Class
HideThreadFromDebugger, when passed as an argument, can be used to prevent debuggers from receiving events
(include breakpoints and exiting the program) from any thread that has this API called on it.
• NtContinue and similar functions are used modify current context or load a new one in the current thread, which can
confuse debugger.
• CloseHandle and NtClose - a very cool technique based on the fact that call of ZwClose with invalid handle generates
STATUS_INVALID_HANDLE exception when the process is debugged.
• GenerateConsoleCtrlEvent - event-based detection. One vector is to invoke Ctrl-C signal and check for
EXCEPTION_CTL_C exception (which is true if the process is debugged)
• OutputDebugString with a valid ASCII strings - causes error when no debugger is present, otherwise passes normally.
Can also be used to exploit known weaknesses - for example, OllyDbg had known bug of not correct handling of
format strings and crashed with multiple “%s” input.
10. [ Anti-debugging ]
Maybe the simplest method is calling the IsDebuggerPresent function. This function detects if the calling process is being debugged by a user-
mode debugger. The code below represents an elementary protection example:
13. [ Anti-debugging ]
Flags
• Trap flag - controls tracing of a program. If it’s set, executing an instruction will raise
SINGLE_STEP exception. Example of usage: pushf / mov dword [esp], 0x100 / popf. Another
possible scenario might be tracing over SS (stack segment register) - debugger will not
break on those (e.g. push ss / pop ss) effectively stopping on the following instruction. In
other words, unset of trapflag won’t be possible after that, and if check is done here,
debugger will be detected.
• IsDebugged - second byte of PEB - this is what checked by IsDebuggerPresent(), however,
can also be checked directly.
• NtGlobalFlag - another field in PEB with offset 0x68/0xBC (x86/x64). A process that is
created by debugger will have 0x70 value (FLG_HEAP_ENABLE_TAIL_CHECK |
FLG_HEAP_ENABLE_FREE_CHECK | FLG_HEAP_VALIDATE_PARAMETERS) by default
• Heap flags - check of two flags located in heap: “Flags” and “ForceFlags”. Normally heap
location can be retrieved by GetProcessHeap() and/or from PEB structure. Exact
combination of flags depend on the OS (see more in details following links at the bottom)
18. Antidebug
Timing check
GetTickCount, GetLocalTime, GetSystemTime, timeGetTime,
NtQueryPerformanceCounter - typical timing functions which are used
to measure time needed to execute some function / instruction set. If
difference is more than fixed threshold, the process exits.
rdtsc - “Read Time Stamp Counter” asm instruction,technique is the
same as described above
19. [ Anti-debugging ]
# Замер времени выполнения команд
В системе есть довольно много способов измерения временных
промежутков. Если разница между TimeEnd и TimeStart меньше сотни, то
GetTickCount явно перехвачена. Поможет выявить это функция API
NtQueryInformationProcess в паре с API GetSystemTimeAsFileTime:
• команда RDTSC;
• API-функция GetTickCount;
• API-функция timeGetTime (из winmm.dll);
• API-функция QueryPerformanceCounter;
• API-функция GetSystemTimeAsFileTime;
• API-функция GetProcessTimes;
• API-функция KiGetTickCount (или вызов прерывания int 0x2A);
• API-функция NtQueryInformationProcess (ProcessInformationClass = ProcessTimes
(0x04);
• API-функция NtQueryInformationThread (ThreadInformationClass = ThreadTimes
(0x01);
• поля структуры KUSER_SHARED_DATA.
21. [ Anti-debugging ]
Rogue instructions (BreakPoints)
• INT3 - classic example (0xCC, 0xCD+0x03). Checks may include
comparison to xor’ed value, e.g. to 0x99 (0xCC ^ 0x55)
• Single-step - old trick to insert 0xF1 opcode to exploit SoftICE
debugging process by generating SINGLE_STEP exception.
• INT 2Dh - powerful interrupt technique which results in raising
breakpoint exception if the process is not debugged and in normal
execution if debugger is present.
• Stack Segment register - already described in “Trap flag” section -
due to incorrect execution of SS registers, it is possible to trick the
debugger setting the flag and check its value immediately.
22. [ Anti-debugging ]
BreakPoint (Точки останова)
Программные точки останова устанавливаются отладчиком путем инъекции
инструкции int 3h в код. Таким образом, методы обнаружения отладчика
основаны на вычислении контрольной суммы соответствующей функции.
Не существует универсального метода борьбы с такой защитой – хакеру
потребуется найти ту часть кода, которая отвечает за вычисление контрольной
суммы и заменить возвращаемые значения всех соответствующих переменных.
Аппаратные точки останова устанавливаются, используя специальные регистры
отладки: DR0-DR7. Используя их, разработчик может прервать выполнение
программы и передать управление отладчику. Защита от отладчика может быть
построена на проверке значений этих регистров или использовать более
активный подход и принудительно сбрасывать их значения, используя функцию
SetThreadContext, чтобы предотвратить отладку.
26. [ Anti-debugging ]
# Обработка исключений
Некоторые API-функции или команд процессора вызывают исключения, и,
если программа не запущена под отладчиком, то управление передается
заранее установленному обработчику исключений. Трюк в том, что если
запустить такую программу под отладчиком, то эти же самые функции или
исключений вызывать не смогут.
• точка заморозки (команда с опкодом 0xf1)
• API-функция DebugBreak (или DbgBreakPoint из ntdll.dll)
• API-функция RaiseException с некоторыми входными значениями
• флаг трассировки (trap flag)
28. [ Anti-disassembly ]
При реализации защиты от дизассемблирования используется множество
приемов, которые реализуются с целью запутать аналитика:
1.Шифрование критичного кода программы и дешифрация его самой
системой защиты перед передачей управления на него.
2.Скрытие команд передачи управления приводит к тому, что дизассемблер
не может построить граф передачи управления.
• Косвенная передача управления.
• Модификация адреса перехода в коде программы
3. Использование нестандартных способов передачи управления (jmp через
ret, ret и call через jmp)
4. Использование возможностей установки префикса сегментного регистра
перед некоторыми командами (pushf, pushfd, cld и др.). Дизассемблер не в
состоянии правильно распознать программу (db 3Eh, 2Eh, 90h = ds: cs: nop).
30. [ Anti-disassembly ]
This technique relies on changing a instruction, or a set of them, by equivalent ones. It can
be used to make the analysis process by a professional harder and also to bypass signatures.
Some examples are:
31. [ Anti-disassembly ]
1.Jump Instructions to a location with constant value
This is the most used trick by malware writers/anti-disassembly programs which create jumps into the same location +
1 or 2 bytes. It would lead to interpretation of completely different byte code by the system.
2.Jump Instructions to the Same target
IDA Pro usually follows this behavior where for a conditional instruction (jnz) it first disassembles the false branch of
the conditional instruction and then moves forward to the true part. From a malware POV since both the jz and jnz are
present it is similar to an unconditional jump
32. [ Anti-disassembly ]
With a little IDA Python knowledge, we can develop a script that allows malware analysts to easily NOP-out instructions
as they see fit. The following script establishes the hotkey ALT-N. Once this script is executed, whenever the user presses
ALT-N, IDA Pro will NOP-out the instruction that is currently at the cursor location. It will also conveniently advance the
cursor to the next instruction to facilitate easy NOP-outs of large blocks of code.
*Deobfuscator : Deobfuscation plugin for IDA - http://code.google.com/p/optimice/
33. [ Anti-virtual machine
techniques]
ОБЩИЕ ПРИНЦИПЫ:
Во-первых, любая виртуальная машина несет на своем борту какое-нибудь
специфическое оборудование. Это касается видеоадаптера, жесткого диска,
идентификатора процессора, версии BIOS, MAC-адреса сетевой карты.
Во-вторых, виртуальные машины оставляют следы в системе в виде
запущенных вспомогательных процессов, драйверов и других специфических
объектов.
В-третьих, если как следует покопаться в реестре виртуальной машины, там
можно найти много всяких интересных ключей, характерных только для
виртуальных машин.
Ну и в-четвертых, некоторые производители специально оставляют
возможности, позволяющие обнаружить их продукты.
34. [ Anti-virtual machine
techniques]
VM Fingerprints:
• Running Processes (eg. VMWare Tools)
• Registry entries that include "VMWare“
• VMWare specific I/O port
• Descriptor Table addresses (IDT, LDT, etc.)
• Default virtual machine hardware
• Common VM MAC addresses
36. [ Anti-virtual machine
techniques]
VMware tools is a software package users can install on their VMware virtual machines to increase their
functionality. For example, one thing it allows for is drag-and-drop functionality between the host and
guest, and vice versa. Competitors such as Oracle Virtualbox offers a similar package for their virtual
machines known as Virtualbox Guest Additions.
VMware Tools uses a special I/O port to communicate data to/from the host and virtual machine.
Malware takes advantage of this functionality and implements it using only a few lines of Assembly code.
37. [ Anti-virtual machine
techniques]
Check Descriptor Table Registers
There is one Local Descriptor Table Register (LDTR), one Global Descriptor Table Register (GDTR), and one
Interrupt Descriptor Table Register (IDTR) per CPU. These have to be moved to a different location when a
guest operating system is running to avoid conflicts with the host. Ocassionally, you’ll see malware check
for these by using the ASM instructions SLDT, SGDT, and SIDT to get the value of these registers.
38. [ Anti-virtual machine
techniques]
DLLScanning
This is perhaps one of the easiest identifiable anti-debug methods, where the malware scans its own
process to look for particular dynamic-link libraries (DLLs) that may be associated with analyst tools. The
targeted dlls here can be anything related to debuggers or tools that may inject special DLLs into the
malware’s process (i.e. sandboxes).
39. [ Anti-virtual machine
techniques]
Product ID check
Checking the Window Product ID found within the registry can yield clues to what kind of
System you are running. In the past, many Sandboxes used hardcoded product IDs in their
Operating System environment. While most Sandboxes and other automated analysis systems
use randomly generated product IDs, you can still occasionally find these checks.
40. [ Anti-virtual machine
techniques]
Timing based detection
“The Time Stamp Counter (TSC) is a 64-bit register present on all x86 processors since the Pentium. It counts the
number of cycles since reset”. If the code is being emulated then, there will be change in the time stamp between.
The Result in stored in EDX:EAX format Now the time difference in a real host machine would be usually less than 100,
but if the code is emulated the difference will be huge.
41. [Anti-Sandbox]
Sems tool is sent to malware sandbox like any other malware samples and waited until the
completion of analysis. Detected signatures can be seen in "File Operations" section of the
sandbox report hence sems drops separate .txt files for each findings.
42. [ VM Detect ]
In short, Virtual PC uses the "Invalid Opcode" mechanism as a backdoor.
The following code shows how to detect Virtual PC's presence:
43. [ VM Detect ]
The Intel x86 provides two instructions to allow you to carry I/O operations, these instructions are the "IN" and "OUT" instructions. These
two instructions are privileged instructions and cannot be used in a user-mode (while in protected mode) process unless the necessary
privileges are enabled, so using them in normal cases will cause an exception of the type: "EXCEPTION_PRIV_INSTRUCTION".
VMWare uses the "IN" instruction to read from a special port. This port does not effectively exist, however when VMWare is present, that
port will be the interface between the virtual machine and VMWare.
Here's the code:
44. [ Anti-virtual machine
techniques]
VirtualBox and VMware use default MAC addresses on virtual machines. The VirtualBox default address
uses the first three bytes 08:00:27. The VMware default address uses the first three bytes 00:0C:29,
00:1C:14, 00:50:56, or 00:05:69. Malware can detect these MAC addresses by requesting the following
registry key:
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlClass{4D36E972-E325-11CE-BFC1-
08002BE10318}0000NetworkAddress
45. [ Anti-VM Tricks]
ScoopyNG
ScoopyNG (http://www.trapkit.de/) is a free VMware detection tool that implements seven different checks for a virtual machine, as
follows:
46. [ Anti-VM Tricks]
There are also a number of undocumented features in VMware that can help mitigate anti-
VMware techniques. For example, placing the options in Listing into the virtual machine’s
.vmx file will make the virtual machine less detectable
.
48. [ Analysis Tools ]
Debug:
# OllyDbg (v2 preferences)
# WinDgb (kernel mode)
Disassembly:
# IDA Pro
# Hex-Rays
It’s a classic
49. [ Analysis Tools ]
# OllyDbg plugins
• Olly Advanced v1.27 — настройка обхода очень большого количества антиотладочных приемов,
настройка исправления большого количества ошибок, эксплуатируемых протекторами,
расширение функционала OllyDbg
• Anti-Debug Time - обход фич Timing Check
• ScyllaHide 1.2 - ScyllaHide is an open-source x64/x86 usermode Anti-Anti-Debug library. It hooks
various functions in usermode to hide debugging. This will stay usermode! For kernelmode hooks use
TitanHide.
• HideOD - HideOD is a plugin that bypasses several anti-debugging techniques commonly found in
malwares, hence facilitating the analyst's analysis.
• OllyExt — Anti-AntiDebug.
• Uberstealth — Anti-AntiDebug основанный на коде IdaStealth.
# IDA Pro plugins & Script
IDA Stealth: IDAStealth is a plugin which aims to hide the IDA debugger from most common anti-
debugging techniques. The plugin is composed of two files, the plugin itself and a dll which is injected
into the debuggee as soon as the debugger attaches to the process. The injected dll actually
implements most of the stealth techniques either by hooking system calls or by patching some flags in
the remote process.
60. [ Summary ]
Что происходит?
1. Усложнение техник противодействия анализу
2. Комбинирование различных техник (D + DA + VM + other)
3. Использование фич (above Vista, x64)
К чему приводит?
1. Усложнение анализа malware – кода (квалификация)
2. Увеличение времени на детектирование и выпуск сигнатур
Что ждет дальше?
1. Классификация методов = > база знаний, типовые сценарии
2. Автоматизация рутинных операций (plugins, script, etc)
61. [ Contacts ]
Иван Пискунов | Ivan Piskunov
E-mail: g14vano@gmail.com
Web: www.ipiskunov.blogspot.com