The main purpose of this talk is to introduce DBI, delve deeper in this topic, demonstrate the power of this technique, and consider typical problems of its application for "industrial" tasks. Audience will get acquainted with DBI in general, will understand in which fields it is successfully applied, what are potential problems of this technique related to implementation of their own tool based on presented frameworks (Intel PIN and DynamoRIO), and see real examples of the technique used for heap-based bug detection in heavyweight programs along with dynamic malware analysis.
The (Memory) Safety Dance - SAS 2017 keynoteMarkDowd13
This presentation discusses defensive mitigations that have been introduced over the last several years and their effectiveness, and what it means for offensive research.
Stagefright affects over 90% of Android devices and will cause one of the largest security update. However, many news reports in Japan were flawed and caused confusions.
Installation of PC-Lint and its using in Visual Studio 2005PVS-Studio
The article is devoted to the first acquaintance with the PC-Lint 8.0 static analyzer of C++ code. The process of the tool installation and its initial setting is described.
Fuzzing 101 Webinar on Zero Day ManagementCodenomicon
In this webinar, we explore the process of zero-day vulnerability management from initial threat analysis to automated detection and remediation. We will demonstrate how easy it is to detect attack vectors and to quickly assess the reliability and security of those interfaces using general purpose fuzzing solutions. We will also show you how you can complement these solutions with known vulnerability data and do patch verification easily and cost-effectively. Finally, we will discuss how you can tailor your defenses to block zero day attacks, which is a key aspect of vulnerability management.
The (Memory) Safety Dance - SAS 2017 keynoteMarkDowd13
This presentation discusses defensive mitigations that have been introduced over the last several years and their effectiveness, and what it means for offensive research.
Stagefright affects over 90% of Android devices and will cause one of the largest security update. However, many news reports in Japan were flawed and caused confusions.
Installation of PC-Lint and its using in Visual Studio 2005PVS-Studio
The article is devoted to the first acquaintance with the PC-Lint 8.0 static analyzer of C++ code. The process of the tool installation and its initial setting is described.
Fuzzing 101 Webinar on Zero Day ManagementCodenomicon
In this webinar, we explore the process of zero-day vulnerability management from initial threat analysis to automated detection and remediation. We will demonstrate how easy it is to detect attack vectors and to quickly assess the reliability and security of those interfaces using general purpose fuzzing solutions. We will also show you how you can complement these solutions with known vulnerability data and do patch verification easily and cost-effectively. Finally, we will discuss how you can tailor your defenses to block zero day attacks, which is a key aspect of vulnerability management.
Inception: A reverse-engineer horror HistoryNelson Brito
Inception @ 2016 IBM Systems Technical University
Understanding reverse engineer using MS08-078. This presentation is an updated version of a previous series of presentations, which shows a practical methodology to perform a reverse engineering... The approach can be broader applied to any/most of the vulnerabilities targeting client-side applications.
For further details and informations, please, refer to:
- http://www.vimeo.com/nbrito
- https://www.slideshare.net/nbrito01/inception-support-slides
Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...Maksim Shudrak
Dynamic binary instrumentation (DBI) is a technique for analysing the behaviour of a binary application at runtime through the injection of instrumentation code. This instrumentation code is designed to be transparent towards the instrumented application and it executes as a part of the normal execution flow without significant runtime overhead. Moreover, there are no limitations for the instrumentation code - a user can implement even a complex logic to observe execution flow, memory layout, etc. Certainly, such a flexible and powerful technique can and should be used for malware analysis. However, while there are several open-source tools (PoCs) implemented on top of DBI frameworks, their application for malware analysis is very limited.
In the talk the author will discuss the pros and cons of malicious code instrumentation and his experience of how DBI can be used to perform investigation of sophisticated banking trojans such as Gootkit and EmbusteBot as well as dozens of other malicious samples in practice.
Moreover, the author will release a new tool for transparent and lightweight dynamic malware analysis and will demonstrate, using examples, how this tool can help researchers to easily reveal important behaviour details of sophisticated malicious samples. EmbusteBot (a new banking trojan from Brazil found and reported by the author in 2017) was investigated using only this tool without even starting a debugger or disassembler.
Pressentaion by Roelof Temmingh at blackhat USA in 2005.
This presentation is about the methodology behind the bidiblah tool. A tool developed by Roelof Temmingh which automates the foot-printing and discovery process.
Introduction to metasploit framework
01.History of metasploit
02.Metasploit Design and architecture
03.Metasploit Editions
04.Metasploit Interface
05.Basic commands and foot-printing modules
BriMor Labs Live Response Collection - OSDFCONBriMorLabs
Presentation by Brian Moran of BriMor Labs on the Live Response Collection given during the Basis Technology Open Source Digital Forensics Conference (OSDFCON) on October 28, 2015
Comment améliorer le quotidien des Développeurs PHP ?AFUP_Limoges
Conférence présentée lors du summer meetup de l'AFUP à Limoges le 19 juin 2018. Son objectif est de présenter plusieurs outils permettant de gagner rapidement en efficacité au quotidien.
Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...Mobodexter
BlackHat USA 2015 got recently concluded and we head a bunch of news around how BlackHat brought to light various security vulnerabilities in day-to-day life like ZigBee protocol, Device for stealing keyless cars & ATM card skimmers. However the presenters, who are also ethical hackers, also gave a bunch of tools to help software community to detect & prevent security holes in the hardware & software while the product is ready for release. We have reviewed all the presentations from the conference and give you here a list of Top 10 tools/utilities that helps in security vulnerability detection & prevention.
This presentation by Morris Kleiner (University of Minnesota), was made during the discussion “Competition and Regulation in Professions and Occupations” held at the Working Party No. 2 on Competition and Regulation on 10 June 2024. More papers and presentations on the topic can be found out at oe.cd/crps.
This presentation was uploaded with the author’s consent.
More Related Content
Similar to Exploring billion states of a program like a pro. How to cook your own fast and scalable DBI-based security tool. A case study.
Inception: A reverse-engineer horror HistoryNelson Brito
Inception @ 2016 IBM Systems Technical University
Understanding reverse engineer using MS08-078. This presentation is an updated version of a previous series of presentations, which shows a practical methodology to perform a reverse engineering... The approach can be broader applied to any/most of the vulnerabilities targeting client-side applications.
For further details and informations, please, refer to:
- http://www.vimeo.com/nbrito
- https://www.slideshare.net/nbrito01/inception-support-slides
Tricky sample? Hack it easy! Applying dynamic binary inastrumentation to ligh...Maksim Shudrak
Dynamic binary instrumentation (DBI) is a technique for analysing the behaviour of a binary application at runtime through the injection of instrumentation code. This instrumentation code is designed to be transparent towards the instrumented application and it executes as a part of the normal execution flow without significant runtime overhead. Moreover, there are no limitations for the instrumentation code - a user can implement even a complex logic to observe execution flow, memory layout, etc. Certainly, such a flexible and powerful technique can and should be used for malware analysis. However, while there are several open-source tools (PoCs) implemented on top of DBI frameworks, their application for malware analysis is very limited.
In the talk the author will discuss the pros and cons of malicious code instrumentation and his experience of how DBI can be used to perform investigation of sophisticated banking trojans such as Gootkit and EmbusteBot as well as dozens of other malicious samples in practice.
Moreover, the author will release a new tool for transparent and lightweight dynamic malware analysis and will demonstrate, using examples, how this tool can help researchers to easily reveal important behaviour details of sophisticated malicious samples. EmbusteBot (a new banking trojan from Brazil found and reported by the author in 2017) was investigated using only this tool without even starting a debugger or disassembler.
Pressentaion by Roelof Temmingh at blackhat USA in 2005.
This presentation is about the methodology behind the bidiblah tool. A tool developed by Roelof Temmingh which automates the foot-printing and discovery process.
Introduction to metasploit framework
01.History of metasploit
02.Metasploit Design and architecture
03.Metasploit Editions
04.Metasploit Interface
05.Basic commands and foot-printing modules
BriMor Labs Live Response Collection - OSDFCONBriMorLabs
Presentation by Brian Moran of BriMor Labs on the Live Response Collection given during the Basis Technology Open Source Digital Forensics Conference (OSDFCON) on October 28, 2015
Comment améliorer le quotidien des Développeurs PHP ?AFUP_Limoges
Conférence présentée lors du summer meetup de l'AFUP à Limoges le 19 juin 2018. Son objectif est de présenter plusieurs outils permettant de gagner rapidement en efficacité au quotidien.
Top 10 Software to Detect & Prevent Security Vulnerabilities from BlackHat US...Mobodexter
BlackHat USA 2015 got recently concluded and we head a bunch of news around how BlackHat brought to light various security vulnerabilities in day-to-day life like ZigBee protocol, Device for stealing keyless cars & ATM card skimmers. However the presenters, who are also ethical hackers, also gave a bunch of tools to help software community to detect & prevent security holes in the hardware & software while the product is ready for release. We have reviewed all the presentations from the conference and give you here a list of Top 10 tools/utilities that helps in security vulnerability detection & prevention.
This presentation by Morris Kleiner (University of Minnesota), was made during the discussion “Competition and Regulation in Professions and Occupations” held at the Working Party No. 2 on Competition and Regulation on 10 June 2024. More papers and presentations on the topic can be found out at oe.cd/crps.
This presentation was uploaded with the author’s consent.
Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...Orkestra
UIIN Conference, Madrid, 27-29 May 2024
James Wilson, Orkestra and Deusto Business School
Emily Wise, Lund University
Madeline Smith, The Glasgow School of Art
0x01 - Newton's Third Law: Static vs. Dynamic AbusersOWASP Beja
f you offer a service on the web, odds are that someone will abuse it. Be it an API, a SaaS, a PaaS, or even a static website, someone somewhere will try to figure out a way to use it to their own needs. In this talk we'll compare measures that are effective against static attackers and how to battle a dynamic attacker who adapts to your counter-measures.
About the Speaker
===============
Diogo Sousa, Engineering Manager @ Canonical
An opinionated individual with an interest in cryptography and its intersection with secure software development.
Acorn Recovery: Restore IT infra within minutesIP ServerOne
Introducing Acorn Recovery as a Service, a simple, fast, and secure managed disaster recovery (DRaaS) by IP ServerOne. A DR solution that helps restore your IT infra within minutes.
Have you ever wondered how search works while visiting an e-commerce site, internal website, or searching through other types of online resources? Look no further than this informative session on the ways that taxonomies help end-users navigate the internet! Hear from taxonomists and other information professionals who have first-hand experience creating and working with taxonomies that aid in navigation, search, and discovery across a range of disciplines.
Всем привет, меня зовут Максим Шудрак, я работаю cyber security researcherом в IBM Research Israel, мы занимаемся разработкой новых технологий для автоматизированного детектирования сложного вредоносного кода. Год назад я защитил диссертацию по поиску уязвимостей в исполняемом коде в Томском университете систем управления и радиоэлектроники. В свободное время я занимаюсь исследованием и разработкой утилит для анализа исполняемого кода, а также вношу вклад в разработку ДБИ фреймворка DynamoRIO.
Мой доклад будет построен следующим обрзаом: в начале мы рассмотрим, что такое динамическая бинарная инструментация в общем, как она работает, приведем описание и сравнение двух наиболее популярных фреймворков, а также рассмотрим возможные области применения этой технологии. Затем я подробно расскажу о своем опыте работы с этой технологией на примере разработки двух утилит для автоматизированного детектирования ошибок типа переполнения кучи и динамического анализа вредоносного кода. Покажу DEMO одной утилиты и расскажу о некоторых подводных камнях при работе с DBI.
Поехали. Динамическая бинарная инструментация или ДБИ это метод динамического анализа бинарных приложений путем внедрения инструментирующего кода. Звучит довольно просто, давайте посмотрим как это работает.
Итак представим что у нас есть бинарник и наш ДБИ фреймворк, который состоит из лаунчера и основной dll. На первом этапе это выглядит как классический инжект длл в приложение. Мы запускаем наш бинарник в приостановленном состоянии, инжектируем базовую длл фреймворка, перепесываем точку входа, чтобы передать управление на нашу core.dll. Потом мы возобновляем процесс, он запускается и передает управление в core.dll. Core.dll в свою очередь подгружает все необходимые для его функционирования библиотеки, вычисляет адрес первого блока приложения которое должно выполниться. Затем мы берем этот базовый блок, копируем его в кодовый кэш, инжектируем инструкции или целые функции в соответствии с тем, как нам нужно выполнить инструментацию и выполняем этот блок в кеше, затем вычисляем следующий базовый блок, выполняем его инструментацию, исполняем и т.д., до тех пор пока вся программа не выполнится. Безусловно это обобщенная схема, на практике за этапом 5 стоит ряд сложнейших технологий.
В моем докладе я бы хотел остановиться на двух самых популярных на сегодняшний день фреймворках DynamoRIO и Intel PIN. ДинамоРИО фреймворк поддерживаемый Google и ARM и Intel Pin поддерживаемый Intel. На мой взгляд DynamoRIO выгодно отличается от Intel PIN, он быстрее, распространяется под BSD-лицензией, поддерживает больше архитектур и гораздо более гибче с точки зрения используемой технологии. Однако Intel Pin гораздо проще с точки зрения разработки инструментирующий утилит и имеет больше примеров. Тоесть порог вхождение в него ниже.
Код обоих фреймворков построен на вызове callback-процедур в зависимости от определенного события, например исполнения нового базового блока или функции.
Инструментацию мы можем выполнять с разным уровнем так называемой гранулярности, мы можем инструментировать каждую инструкции, каждый базовый блок, каждый вызов функции или срабатывание определенного события, например загрузки модуля, исключения или системного вызова.
На сегодняшний день, ДБИ применяется в огромном количестве направлений, это поиск уязвимостей, тестирование и верификация программного обеспечения, обнаружение НДВ, динамический анализ вредоносного кода, реверс-инжиниринг, а также во многих других направлениях связанных с анализом качества программного обеспечения.
Рассмотрим один из вариантов применения ДБИ на примере поиска ошибок типа переполнения кучи в исполняемом коде.
В рамках работы с фреймворком Intel Pin, мною была разработана утилита WinHeap Explorer, которая как раз позволяет выполнять детектирование таких ошибок. Основными преимуществами этой утилиты по сравнению с аналогами является возможность выполнять частичную инструментацию ( я расскажу о ней далее), низкие накладные расходы, а также открытый исходный код под BSD - лицензией.
Я думаю присутствующим не нужно рассказывать об опасности ошибок типа переполнения кучи, однако на всякий случай я приведу пример. Представим что у нас есть вот такой вот код. У нас выделяется память с помощью malloc, затем выполняеться вызов CoCreateInstance с целью создать интерфейс для FileOpenDialog
, а затем на строчке 12 у нас есть переполнение буфера.
Такая ошибка чревата тем, что если 2 наших блока памяти выделяться один за другим, то есть существует достаточно приличная вероятность такого события. В таком случае у нас будет возможность выполнить так называемый vtable corruption или перезаписать таблицу виртуальных методов (vtable for pFileOpen на слайде).
Перезаписываем указатель на метод в pFileOpen, это позволит нам выполнить произвольный код в контексте уязвимого приложения. Конечно еще нужно, чтобы этот метод вызвался, но это уже не слишком сложно. Как вы видите у нас есть здесь выход за границы выделенной кучи.
Что если мы бы могли каким-либо образом запоминать размер выделенной кучи и сигнализировать в том случае, если программа выполняет запись за его пределами. Вот здесь нам может очень помочь DBI.
Итак представим что у нас есть 5 инструкций и 2 выделенных блока в куче.
Один блок доступный для чтения/записи, а второй уже освободился.
Представим что 2 наши инструкции корректно обращаются к памяти. А 2 другие пишут за границами выделенной памяти, а последняя обращается к уже освобожденному блоку памяти. Классический buffer overflow и use-after-free.
Что детектировать эти ошибки, пометим память до и после выделенного блока как redzone, а уже освобжденному блоку памяти присвоим специальный маркер.
Теперь если инструкция осуществляет доступ к redzone или к блоку помеченному как освобожденный, мы считаем такую ситуацию как ошибка.
И тем самым детектируем где у нас происходит оверфлоу или use-after-free. Звучит довольно просто, перейдем к реализации с помощью DBI.
Для того чтобы пометить каждый выделыемый блок памяти, нам нужно инструментировать API вызовы освобождения или выделения памяти, а также анализировать указатели каждой инструкции. Редзоны и статус каждого выделенного блока памяти будем хранить в куче. Все логично, и это будет работать. Но есть одна проблема.
Производительность просто ужасная, запуск повер-поинта длиться 12 минут
Это абсолютно неприемлимо, мы не сможем привязать фаззер или интегрировать нашу утилиту в процесс разработки. Окей, что мы можем сделать чтобы исправить эту ситуацию.
Во первых хранить все в хештейбл для нас слишком затратно. Заместо будем использовать теневую память. Куча выделяется с выравниванием в 8 байт, таким образом мы можем очень легко отразить, каждые восемь байт выделяемые в куче, на 1 байт в теневой памяти, используя простейшую арифметику, беря остаток от деления адреса на 8 и прибавляя его к базовому адресу по которому выделена теневая память. В этом же байте теневой памяти будем хранить и статус выделенного блока – доступен, освобожден или redzone.
Отлично далее. Я проанилизировал архитектуру выделения памяти в Windows и пришел к выводу, что нам не нужно инструментировать все функции, достаточно лишь инструменитровать Rtl вызовы в ntdll.dll. Все высокоуровневые функции, так или иначе будут использовать их для выделения памяти. Ну а они уже в свою очередь системный вызов в ядро.
Далее. Что можно сделать еще. Если мы проанализируем соотношение количества выполняемых инструкций в приложении и DLL, мы можем прийти к выводу, что очень много времени проводится в системных DLL, хотя нам их не нужно тестировать. На слайде приведено отношение, процент показывает соотношение количества выполненных инструкций в системных DLL к пользовательским.
К сожалению мы не можем просто не инструментировать код системных библиотек, однако мы можем добавить только те функции, которые действительно интересны с точки зрения анализа, например функции обработки строк, памяти и т.п.
Для этого я реализовал несколько скриптов на Pythonе, которые используют IDA, и которые позволяют составить список таких функций для WinHeap Explorer еще до начала анализа. Они сохраняются в базу, а затем в ходе тестирования WinHeap Explorer используют их для принятие решения об инструментации того или иного участка кода.
В результате удалось повысить производительность примерно в 70 раз и обогнать state-of-the-art утилиту в этой области DrMemory, разрабатываемую Google, в некоторых случаях на 70%.
Перейдем к следующему примеру. Анализ вредоносного кода.
Здесь я бы хотел показать пример применения технологии ДБИ для динамического анализа вредоносного кода.
Итак предположим у нас есть вирус, хорошо упакованный, обфусцированный и в котором есть механизмы защиты от отладки и API-хукинга. Мы не хотим заниматься ручным реверсингом этого семпла, но нам необходимо понять, что он делает. Традиционным подходом в таком случае будет использование различных утилит мониторинга операционной системы, например RegMon и SysMon, Wireshark для сети и т.д. Однако в такой ситуации мы сталкиваемся с так называемой проблемой называемой в Computer Science: Semantic Gap. Мы видим взаимодействие нашего семлпа с ОС, однако его внутренние механизмы попрежнему остаются для нас черным ящиком.
Хорошо, в таком случае мы можем использовать API-hooking и видеть каждый API - вызов, однако это очень известная техника, которая очень легко детектируется да и производительность и стабильность такого подхода вызывает вопросы.
Вот как раз для решения этой проблемы отличны подходит ДБИ. Мы можем выполнить инструментацию каждой экспортируемой функцией из подгружаемых семплом библиотек и печатать информацию в лог, каждый раз когда к ней происходит вызов.
Этот подход был реализован мною в утилите DrlTrace, построенной на базе DynamoRIO. Почему DynamoRIO, потому что основным принципом при разработке DynamoRIO являлась прозрачность по отношению к исполняемому коду. Это позволяет снизить потенциальный риск обнаружения утилиты малварью. Утилита доступна онлайн, лицензия BSD, работает в Windows,, Linux и под Android. Использовать её очень просто, достаточно одной команды, которая приведена на слайде.
Вот такой лог она будет генерировать в файл. Давайте посмотрим его на реальном примере.
Итак подведем итог. ДБИ это очень мощная технология, которая может использоваться во многих сфера информационной безопасности и если применять её правильно и использовать ряд оптимизаций рассмотренных в презентации, можно добиться отличных результатов, что и было продемонстрировано на примере двух утилит WinHeap Explorer и Dr.Ltrace.
Их можно скачать на github, спасибо за внимание, готовь ответить на вопросы.