SlideShare a Scribd company logo
1 of 61
СОВРЕМЕННЫЕ ТЕХНОЛОГИИ И ИНСТРУМЕНТЫ
АНАЛИЗА ВРЕДОНОСНОГО ПО
«ТЕХНИКИ ПРОТИВОДЕЙСТВИЯ АНАЛИЗУ
БИНАРНОГО КОГДА MALWARE»
ИВАН ПИСКУНОВ
23-24 мая 2017
2017
[ #WhoAme ]
• В индустрии безопасности более 9 лет
• Член сибирской CTF-команды CrazY geek$ (2008 - ..)
• Автор блога www.ipiskunov.blogspot.com
• Персональная колонка www.SecurityLab.ru «ИБ в
деталях»
• Цикл статей для ][акер «Реверсинг малвари для
начинающих»
• Курс «Этичный хакер» в школе программирования
для детей «Coddy School»
[ Intro ]
На мастер-классе будут рассматриваться современные
методы противодействия анализу вредоносного ПО:
• «антиотладка»,
• запуск в виртуальных машинах,
• трюки анти-дисассемблирования.
с использованием современных подходов и инструментов.
[ Agenda ]
[ Anti-reverse engineering ]:
#Anti-debugging
#Anti-disassembly
#Anti-virtual machine techniques
[ Agenda ]
[Tools]:
#IDA pro & OllyDBG
[Case]:
#Examples
[ Anti-debugging ]
Все анти-отладочные приемы условно можно разделить на две
группы:
• Усложнение возможной отладки. Это прежде всего
обфускация кода, паковка/криптовка, использование
исключений, разделение кода на потоки/библиотеки,
мусорные функции и т.д.
• Обнаружение отладки. Происходит обнаружение самого
факта запуска отладчика: через созданные для этого функции
или через нахождения окна/процесса отладчика, нахождение
брекпоинтов (CC, проверка атрибутов доступа и др.), замеры
времени и т.д.
[ 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
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.
[ Anti-debugging ]
[ 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:
[ Anti-debugging ]
[ Anti-debugging ]
[ 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)
[ Anti-debugging ]
[ Anti-debugging ]
Antidebug
Antidebug
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
[ 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.
[ Anti-debugging ]
Timing check
[ 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.
[ Anti-debugging ]
BreakPoint (Точки останова)
Программные точки останова устанавливаются отладчиком путем инъекции
инструкции int 3h в код. Таким образом, методы обнаружения отладчика
основаны на вычислении контрольной суммы соответствующей функции.
Не существует универсального метода борьбы с такой защитой – хакеру
потребуется найти ту часть кода, которая отвечает за вычисление контрольной
суммы и заменить возвращаемые значения всех соответствующих переменных.
Аппаратные точки останова устанавливаются, используя специальные регистры
отладки: DR0-DR7. Используя их, разработчик может прервать выполнение
программы и передать управление отладчику. Защита от отладчика может быть
построена на проверке значений этих регистров или использовать более
активный подход и принудительно сбрасывать их значения, используя функцию
SetThreadContext, чтобы предотвратить отладку.
[ Anti-debugging ]
[ Anti-debugging ]
Antidebug
[ Anti-debugging ]
# Обработка исключений
Некоторые API-функции или команд процессора вызывают исключения, и,
если программа не запущена под отладчиком, то управление передается
заранее установленному обработчику исключений. Трюк в том, что если
запустить такую программу под отладчиком, то эти же самые функции или
исключений вызывать не смогут.
• точка заморозки (команда с опкодом 0xf1)
• API-функция DebugBreak (или DbgBreakPoint из ntdll.dll)
• API-функция RaiseException с некоторыми входными значениями
• флаг трассировки (trap flag)
[ Anti-debugging ]
[ Anti-disassembly ]
При реализации защиты от дизассемблирования используется множество
приемов, которые реализуются с целью запутать аналитика:
1.Шифрование критичного кода программы и дешифрация его самой
системой защиты перед передачей управления на него.
2.Скрытие команд передачи управления приводит к тому, что дизассемблер
не может построить граф передачи управления.
• Косвенная передача управления.
• Модификация адреса перехода в коде программы
3. Использование нестандартных способов передачи управления (jmp через
ret, ret и call через jmp)
4. Использование возможностей установки префикса сегментного регистра
перед некоторыми командами (pushf, pushfd, cld и др.). Дизассемблер не в
состоянии правильно распознать программу (db 3Eh, 2Eh, 90h = ds: cs: nop).
[ Anti-disassembly ]
[ 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:
[ 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
[ 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/
[ Anti-virtual machine
techniques]
ОБЩИЕ ПРИНЦИПЫ:
Во-первых, любая виртуальная машина несет на своем борту какое-нибудь
специфическое оборудование. Это касается видеоадаптера, жесткого диска,
идентификатора процессора, версии BIOS, MAC-адреса сетевой карты.
Во-вторых, виртуальные машины оставляют следы в системе в виде
запущенных вспомогательных процессов, драйверов и других специфических
объектов.
В-третьих, если как следует покопаться в реестре виртуальной машины, там
можно найти много всяких интересных ключей, характерных только для
виртуальных машин.
Ну и в-четвертых, некоторые производители специально оставляют
возможности, позволяющие обнаружить их продукты.
[ 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
[ Anti-virtual machine
techniques]
Search Process in memory
[ 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.
[ 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.
[ 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).
[ 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.
[ 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.
[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.
[ 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:
[ 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:
[ 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
[ 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:
[ 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
.
[ Other techniques ]
Packers
Crypto
[ Analysis Tools ]
Debug:
# OllyDbg (v2 preferences)
# WinDgb (kernel mode)
Disassembly:
# IDA Pro
# Hex-Rays
It’s a classic 
[ 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.
[ Analysis Tools ]
OllyDBG plugins
[ Analysis Tools ]
IDA Pro plugins
[ Analysis Tools ]
IDA Pro plugins
Deobfuscator - Deobfuscation plugin for IDA
http://code.google.com/p/optimice/
[ Case ]
• VM (Windows XP)
• Samples (malw1, 2, 3)
• Tools
• Approach
Sample01 – Anti-disassembly
Sample02 – Anti-debug
Sample03 – Anti-VM
[Statistics]
[Statistics]
[Statistics]
[Statistics]
[Statistics]
[Statistics]
Суммарное использование техник противодействия
[ Summary ]
Что происходит?
1. Усложнение техник противодействия анализу
2. Комбинирование различных техник (D + DA + VM + other)
3. Использование фич (above Vista, x64)
К чему приводит?
1. Усложнение анализа malware – кода (квалификация)
2. Увеличение времени на детектирование и выпуск сигнатур
Что ждет дальше?
1. Классификация методов = > база знаний, типовые сценарии
2. Автоматизация рутинных операций (plugins, script, etc)
[ Contacts ]
Иван Пискунов | Ivan Piskunov
E-mail: g14vano@gmail.com
Web: www.ipiskunov.blogspot.com

More Related Content

What's hot

Reverse engineering20151112
Reverse engineering20151112Reverse engineering20151112
Reverse engineering20151112Bordeaux I
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special CasesCiklum Ukraine
 
FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!Vincent Claes
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Creating, obfuscating and analyzing malware JavaScript
Creating, obfuscating and analyzing malware JavaScriptCreating, obfuscating and analyzing malware JavaScript
Creating, obfuscating and analyzing malware JavaScriptKrzysztof Kotowicz
 
EXTENT-2016: Industry Practices of Advanced Program Analysis
EXTENT-2016: Industry Practices of Advanced Program AnalysisEXTENT-2016: Industry Practices of Advanced Program Analysis
EXTENT-2016: Industry Practices of Advanced Program AnalysisIosif Itkin
 

What's hot (14)

Reverse engineering20151112
Reverse engineering20151112Reverse engineering20151112
Reverse engineering20151112
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
groovy & grails - lecture 7
groovy & grails - lecture 7groovy & grails - lecture 7
groovy & grails - lecture 7
 
Verifikation - Metoder og Libraries
Verifikation - Metoder og LibrariesVerifikation - Metoder og Libraries
Verifikation - Metoder og Libraries
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!FreeRTOS Xilinx Vivado: Hello World!
FreeRTOS Xilinx Vivado: Hello World!
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Revealing ALLSTOCKER
Revealing ALLSTOCKERRevealing ALLSTOCKER
Revealing ALLSTOCKER
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Creating, obfuscating and analyzing malware JavaScript
Creating, obfuscating and analyzing malware JavaScriptCreating, obfuscating and analyzing malware JavaScript
Creating, obfuscating and analyzing malware JavaScript
 
EXTENT-2016: Industry Practices of Advanced Program Analysis
EXTENT-2016: Industry Practices of Advanced Program AnalysisEXTENT-2016: Industry Practices of Advanced Program Analysis
EXTENT-2016: Industry Practices of Advanced Program Analysis
 
Exception
ExceptionException
Exception
 

Similar to Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Piskunov

Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profilerIhor Bobak
 
Advanced Malware Analysis Training Session 4 - Anti-Analysis Techniques
Advanced Malware Analysis Training Session 4 - Anti-Analysis TechniquesAdvanced Malware Analysis Training Session 4 - Anti-Analysis Techniques
Advanced Malware Analysis Training Session 4 - Anti-Analysis Techniquessecurityxploded
 
Opencensus with prometheus and kubernetes
Opencensus with prometheus and kubernetesOpencensus with prometheus and kubernetes
Opencensus with prometheus and kubernetesJinwoong Kim
 
How to drive a malware analyst crazy
How to drive a malware analyst crazyHow to drive a malware analyst crazy
How to drive a malware analyst crazyMichael Boman
 
44CON London 2015 - How to drive a malware analyst crazy
44CON London 2015 - How to drive a malware analyst crazy44CON London 2015 - How to drive a malware analyst crazy
44CON London 2015 - How to drive a malware analyst crazy44CON
 
D Trace Support In My Sql Guide To Solving Reallife Performance Problems
D Trace Support In My Sql Guide To Solving Reallife Performance ProblemsD Trace Support In My Sql Guide To Solving Reallife Performance Problems
D Trace Support In My Sql Guide To Solving Reallife Performance ProblemsMySQLConference
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersJavan Rasokat
 
Integris Security - Hacking With Glue ℠
Integris Security - Hacking With Glue ℠Integris Security - Hacking With Glue ℠
Integris Security - Hacking With Glue ℠Integris Security LLC
 
how-to-bypass-AM-PPL
how-to-bypass-AM-PPLhow-to-bypass-AM-PPL
how-to-bypass-AM-PPLnitinscribd
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniqueAndrey Karpov
 
OpenCensus with Prometheus and Kubernetes
OpenCensus with Prometheus and KubernetesOpenCensus with Prometheus and Kubernetes
OpenCensus with Prometheus and KubernetesJinwoong Kim
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak PROIDEA
 
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...Garage4hackers.com
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Zeronights 2016 - Automating iOS blackbox security scanning
Zeronights 2016 - Automating iOS blackbox security scanningZeronights 2016 - Automating iOS blackbox security scanning
Zeronights 2016 - Automating iOS blackbox security scanningSynack
 
ZeroNights: Automating iOS blackbox security scanning
ZeroNights: Automating iOS blackbox security scanningZeroNights: Automating iOS blackbox security scanning
ZeroNights: Automating iOS blackbox security scanningMikhail Sosonkin
 

Similar to Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Piskunov (20)

Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
 
Anti Debugging
Anti DebuggingAnti Debugging
Anti Debugging
 
Advanced Malware Analysis Training Session 4 - Anti-Analysis Techniques
Advanced Malware Analysis Training Session 4 - Anti-Analysis TechniquesAdvanced Malware Analysis Training Session 4 - Anti-Analysis Techniques
Advanced Malware Analysis Training Session 4 - Anti-Analysis Techniques
 
Opencensus with prometheus and kubernetes
Opencensus with prometheus and kubernetesOpencensus with prometheus and kubernetes
Opencensus with prometheus and kubernetes
 
How to drive a malware analyst crazy
How to drive a malware analyst crazyHow to drive a malware analyst crazy
How to drive a malware analyst crazy
 
44CON London 2015 - How to drive a malware analyst crazy
44CON London 2015 - How to drive a malware analyst crazy44CON London 2015 - How to drive a malware analyst crazy
44CON London 2015 - How to drive a malware analyst crazy
 
D Trace Support In My Sql Guide To Solving Reallife Performance Problems
D Trace Support In My Sql Guide To Solving Reallife Performance ProblemsD Trace Support In My Sql Guide To Solving Reallife Performance Problems
D Trace Support In My Sql Guide To Solving Reallife Performance Problems
 
OWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA TestersOWASP ZAP Workshop for QA Testers
OWASP ZAP Workshop for QA Testers
 
Integris Security - Hacking With Glue ℠
Integris Security - Hacking With Glue ℠Integris Security - Hacking With Glue ℠
Integris Security - Hacking With Glue ℠
 
UVM TUTORIAL;
UVM TUTORIAL;UVM TUTORIAL;
UVM TUTORIAL;
 
how-to-bypass-AM-PPL
how-to-bypass-AM-PPLhow-to-bypass-AM-PPL
how-to-bypass-AM-PPL
 
PVS-Studio and static code analysis technique
PVS-Studio and static code analysis techniquePVS-Studio and static code analysis technique
PVS-Studio and static code analysis technique
 
OpenCensus with Prometheus and Kubernetes
OpenCensus with Prometheus and KubernetesOpenCensus with Prometheus and Kubernetes
OpenCensus with Prometheus and Kubernetes
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
 
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Zeronights 2016 - Automating iOS blackbox security scanning
Zeronights 2016 - Automating iOS blackbox security scanningZeronights 2016 - Automating iOS blackbox security scanning
Zeronights 2016 - Automating iOS blackbox security scanning
 
ZeroNights: Automating iOS blackbox security scanning
ZeroNights: Automating iOS blackbox security scanningZeroNights: Automating iOS blackbox security scanning
ZeroNights: Automating iOS blackbox security scanning
 

More from Ivan Piskunov

Электронная подпись и счет-фактуры в бухгалтерском учете
Электронная подпись и счет-фактуры в бухгалтерском учете Электронная подпись и счет-фактуры в бухгалтерском учете
Электронная подпись и счет-фактуры в бухгалтерском учете Ivan Piskunov
 
Особенности проведения аудита безопасности корпоративной IT-инфраструктуры_PH...
Особенности проведения аудита безопасности корпоративной IT-инфраструктуры_PH...Особенности проведения аудита безопасности корпоративной IT-инфраструктуры_PH...
Особенности проведения аудита безопасности корпоративной IT-инфраструктуры_PH...Ivan Piskunov
 
Человеческий фактор [без]опасного интернета
Человеческий фактор [без]опасного интернетаЧеловеческий фактор [без]опасного интернета
Человеческий фактор [без]опасного интернетаIvan Piskunov
 
Как сэкономить, вложив в информационную безопасность?
Как сэкономить, вложив в информационную безопасность? Как сэкономить, вложив в информационную безопасность?
Как сэкономить, вложив в информационную безопасность? Ivan Piskunov
 
Аудит ИБ как инструмент повышения эффективности вашего бизнеса
Аудит ИБ как инструмент повышения эффективности вашего бизнесаАудит ИБ как инструмент повышения эффективности вашего бизнеса
Аудит ИБ как инструмент повышения эффективности вашего бизнесаIvan Piskunov
 
Анти-фрод системы: правовые и технические аспекты, перспективы применения и ...
Анти-фрод системы:  правовые и технические аспекты, перспективы применения и ...Анти-фрод системы:  правовые и технические аспекты, перспективы применения и ...
Анти-фрод системы: правовые и технические аспекты, перспективы применения и ...Ivan Piskunov
 
Вопросы для интервью ISO 27001
Вопросы для интервью ISO 27001Вопросы для интервью ISO 27001
Вопросы для интервью ISO 27001Ivan Piskunov
 
ISO 27001 (v2013) Checklist
ISO 27001 (v2013) ChecklistISO 27001 (v2013) Checklist
ISO 27001 (v2013) ChecklistIvan Piskunov
 

More from Ivan Piskunov (10)

Электронная подпись и счет-фактуры в бухгалтерском учете
Электронная подпись и счет-фактуры в бухгалтерском учете Электронная подпись и счет-фактуры в бухгалтерском учете
Электронная подпись и счет-фактуры в бухгалтерском учете
 
Особенности проведения аудита безопасности корпоративной IT-инфраструктуры_PH...
Особенности проведения аудита безопасности корпоративной IT-инфраструктуры_PH...Особенности проведения аудита безопасности корпоративной IT-инфраструктуры_PH...
Особенности проведения аудита безопасности корпоративной IT-инфраструктуры_PH...
 
Человеческий фактор [без]опасного интернета
Человеческий фактор [без]опасного интернетаЧеловеческий фактор [без]опасного интернета
Человеческий фактор [без]опасного интернета
 
Как сэкономить, вложив в информационную безопасность?
Как сэкономить, вложив в информационную безопасность? Как сэкономить, вложив в информационную безопасность?
Как сэкономить, вложив в информационную безопасность?
 
Аудит ИБ как инструмент повышения эффективности вашего бизнеса
Аудит ИБ как инструмент повышения эффективности вашего бизнесаАудит ИБ как инструмент повышения эффективности вашего бизнеса
Аудит ИБ как инструмент повышения эффективности вашего бизнеса
 
Анти-фрод системы: правовые и технические аспекты, перспективы применения и ...
Анти-фрод системы:  правовые и технические аспекты, перспективы применения и ...Анти-фрод системы:  правовые и технические аспекты, перспективы применения и ...
Анти-фрод системы: правовые и технические аспекты, перспективы применения и ...
 
Вопросы для интервью ISO 27001
Вопросы для интервью ISO 27001Вопросы для интервью ISO 27001
Вопросы для интервью ISO 27001
 
ISO 27001 (v2013) Checklist
ISO 27001 (v2013) ChecklistISO 27001 (v2013) Checklist
ISO 27001 (v2013) Checklist
 
Scope of work IT DD
Scope of work IT DDScope of work IT DD
Scope of work IT DD
 
Scope of work IT DD
Scope of work IT DDScope of work IT DD
Scope of work IT DD
 

Recently uploaded

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 

Recently uploaded (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 

Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Piskunov

  • 1. СОВРЕМЕННЫЕ ТЕХНОЛОГИИ И ИНСТРУМЕНТЫ АНАЛИЗА ВРЕДОНОСНОГО ПО «ТЕХНИКИ ПРОТИВОДЕЙСТВИЯ АНАЛИЗУ БИНАРНОГО КОГДА MALWARE» ИВАН ПИСКУНОВ 23-24 мая 2017 2017
  • 2. [ #WhoAme ] • В индустрии безопасности более 9 лет • Член сибирской CTF-команды CrazY geek$ (2008 - ..) • Автор блога www.ipiskunov.blogspot.com • Персональная колонка www.SecurityLab.ru «ИБ в деталях» • Цикл статей для ][акер «Реверсинг малвари для начинающих» • Курс «Этичный хакер» в школе программирования для детей «Coddy School»
  • 3. [ Intro ] На мастер-классе будут рассматриваться современные методы противодействия анализу вредоносного ПО: • «антиотладка», • запуск в виртуальных машинах, • трюки анти-дисассемблирования. с использованием современных подходов и инструментов.
  • 4. [ Agenda ] [ Anti-reverse engineering ]: #Anti-debugging #Anti-disassembly #Anti-virtual machine techniques
  • 5. [ Agenda ] [Tools]: #IDA pro & OllyDBG [Case]: #Examples
  • 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 .
  • 47. [ Other techniques ] Packers Crypto
  • 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.
  • 50. [ Analysis Tools ] OllyDBG plugins
  • 51. [ Analysis Tools ] IDA Pro plugins
  • 52. [ Analysis Tools ] IDA Pro plugins Deobfuscator - Deobfuscation plugin for IDA http://code.google.com/p/optimice/
  • 53. [ Case ] • VM (Windows XP) • Samples (malw1, 2, 3) • Tools • Approach Sample01 – Anti-disassembly Sample02 – Anti-debug Sample03 – Anti-VM
  • 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