The document discusses exploiting vulnerabilities in the Windows registry and kernel to execute malicious code without detection. It describes how vulnerabilities in functions like RtlQueryRegistryValues and win32k.sys that improperly read registry values can be triggered to cause a buffer overflow and gain kernel code execution. The goal is to store malicious code in the registry and have it execute by exploiting these vulnerabilities during system startup before detection can occur.
The document discusses techniques used by malware to detect virtual machines and strategies to prevent such detection. It outlines several techniques malware uses to detect virtual machines, including hardware fingerprinting, registry checks, process/file checks, memory checks, timing analysis, and communication channel checks. It then discusses approaches used by popular virtual machines like VMware, VirtualBox, and VirtualPC. The document proposes developing a tool called VMDetectGuard that would monitor for calls and instructions used in detection and mask the virtual machine's identity by providing false information to tricks malware.
Detect Kernel-Mode Rootkits via Real Time Logging & Controlling Memory AccessIgor Korkin
The demo is here - https://www.youtube.com/watch?v=vi9TzLrO_pE
All details and source code are here - http://www.bit.ly/MemoryMonRWX
Modern malware and spyware platforms attack existing antivirus solutions and even Microsoft PatchGuard. To protect users and business systems new technologies developed by Intel and AMD CPUs may be applied. To deal with the new malware we propose monitoring and controlling access to the memory in real time using Intel VT-x with EPT. We have checked this concept by developing MemoryMonRWX, which is a bare-metal hypervisor. MemoryMonRWX is able to track and trap all types of memory access: read, write, and execute. MemoryMonRWX also has the following competitive advantages: fine-grained analysis, support of multi-core CPUs and 64-bit Windows 10. MemoryMonRWX is able to protect critical kernel memory areas even when PatchGuard has been disabled by malware. Its main innovative features are as follows: guaranteed interception of every memory access, resilience, and low performance degradation.
The document proposes an approach for automated defense against rootkit attacks through early detection and containment. It tracks dependencies between files and processes to automatically undo any damage caused by intrusions. The approach detects intrusions when malicious processes illegally access protected system zones. A prototype was developed demonstrating detection of a user-level rootkit, kernel-level rootkit, and stealth worm. Future work includes intrusion detection through system call and network anomalies.
This document discusses techniques that malware authors use to frustrate malware analysts, including inserting breakpoints, manipulating timing functions, exploiting Windows internals like debug flags and objects, anti-dumping methods, VM detection, and debugger-specific tricks. The author also announces a public malware repository and API called VXCage for sharing samples.
Halvar Flake: Why Johnny can’t tell if he is compromisedArea41
This document discusses the difficulty of determining if a computer system is compromised. It outlines several checks that could be done to verify control, such as verifying signatures on software binaries, firmware, and scripts. However, it finds that all of these checks ultimately fail due to issues like a lack of transparency, lack of standardization, and the potential for signing keys to be stolen without detection. It argues that fundamental changes are needed to infrastructure and practices to enable determining control, such as reducing the number of trusted code signing authorities, increasing transparency in software updates and signing processes, and reducing opacity in firmware and coprocessors.
This document summarizes several Windows registry keys and artifacts that can provide information about a user's digital activities. It describes keys that track recently opened files, installed applications, browser history and search terms, network connections, and more. Examining these locations can reveal details like the files and websites a user accessed, when they were accessed, and from where they originated.
How security broken? - Android internals and malware infection possibilitiesFFRI, Inc.
This document discusses security issues in the Android operating system and possibilities for malware infection. It begins by covering kernel-level protections like DEP and ASLR, which are not fully effective in Android due to issues like prelinking neutralizing ASLR. It then discusses the application layer, explaining Android application internals involving packages, permissions, and intent-based features like activities and broadcasts. Finally, it outlines the evolution of Android malware, characteristics like using intents and premium services, issues with anti-virus software's limited privileges, and how rooting breaks security by enabling malware to gain higher privileges.
Live Memory Forensics on Android devicesNikos Gkogkos
This presentation deals with some RAM forensics on the Android OS using the LiME tool for getting a RAM dump and the Volatility framework for the analysis part!
Protected Process Light will be Protected – MemoryRanger Fills the Gap AgainIgor Korkin
This document discusses Protected Process Light (PPL) and how it protects process memory on Windows. PPL adds a protection field to the EPROCESS structure that is set during process creation to mark a process as protected. When another process tries to open a protected process, Windows performs access checks using the protection levels to restrict access even for processes running with debug privileges. This helps prevent malware and other unauthorized processes from accessing sensitive memory of protected processes like LSASS.
Applying Memory Forensics to Rootkit DetectionIgor Korkin
Volatile memory dump and its analysis is an essential part of digital forensics. Among a number of various software and hardware approaches for memory dumping there are authors who point out that some of these approaches are not resilient to various anti-forensic techniques, and others that require a reboot or are highly platform dependent. New resilient tools have certain disadvantages such as low speed or vulnerability to rootkits which directly manipulate kernel structures e.g. page tables. A new memory forensic system – Malware Analysis System for Hidden Knotty Anomalies (MASHKA) is described in this paper. It is resilient to popular anti-forensic techniques. The system can be used for doing a wide range of memory forensics tasks. This paper describes how to apply the system for research and detection of kernel mode rootkits and also presents analysis of the most popular anti-rootkit tools.
Applying Memory Forensics to Rootkit Detection #adfsl #Virginia #USA
http://bit.ly/cdfsl_paper
http://bit.ly/cdfsl_slides
http://bit.ly/cdfsl_speech
The document discusses using a Trusted Platform Module (TPM) to securely store encryption keys for disk encryption on Linux. It describes configuring TPM to measure and seal an encryption key file using PCR registers. Modifications are made to initramfs and cryptroot scripts to support unsealing the key during boot without user input by using the TPM. While TPM provides secure storage, integrating it with Linux disk encryption requires additional configuration to get the key unsealed and passed to cryptsetup during early boot stages.
This document provides an overview of security features in UNIX and Linux operating systems. It discusses permissions, access control lists, mandatory access control, password hashing, system patching, sandboxing users and services, and other security concepts. The document aims to educate readers on basic and advanced security techniques available in UNIX/Linux to protect systems from threats.
Вячеслав Кабак "Microsoft Sysinternals-Useful Utilities"EPAM Systems
This document provides summaries of various system utilities from Sysinternals.com. It groups the utilities into categories such as File and Disk Utilities, Networking Utilities, Process Utilities, Security Utilities, System Information Utilities, and Miscellaneous Utilities. Key utilities are highlighted including PsTools, Process Monitor, Process Explorer, Autoruns, and BgInfo which provide information on processes, system activity in real-time, open files and registry keys, auto-starting programs, and system information for desktop backgrounds. The document serves as a reference guide to powerful free command line tools and applications that can help optimize, troubleshoot, and secure Windows systems.
Fermín J. Serna - Exploits & Mitigations: EMET [RootedCON 2010]RootedCON
Fermín J. Serna from Microsoft presented on exploits and mitigations. He discussed the history of exploits like stack overflows, heap overflows, and return oriented programming. He then covered mitigations introduced over time like GS, DEP, ASLR, SafeSEH, and SEHOP. Serna presented on the Enhanced Mitigation Experience Toolkit (EMET), including its current features like enabling DEP and a SEHOP-like implementation, as well as potential future features like EAT hardware breakpoint mitigation, stack pivot mitigation, and mandatory ASLR. He concluded by welcoming questions from the audience.
Android Mind Reading: Android Live Memory Analysis with LiME and VolatilityJoe Sylve
This document discusses acquiring and analyzing volatile memory from Android devices. It provides an overview of traditional Linux memory forensics and the challenges with analyzing Android memory. It introduces the tools LiME and Volatility for acquiring memory from a running Android device and then analyzing that memory image. It demonstrates how to use these tools to extract useful forensic artifacts like processes, network connections, and files.
Linux is well-suited for forensic investigations due to its free and open-source tools, flexible environment, and ability to access low-level interfaces. However, its tools are more complicated to use than commercial packages and typically lack technical support. Linux distributions use a directory tree with essential directories like /bin, /etc, /home, and /var. Important commands provide information on processes, network connections, and disk usage. The Linux boot process involves the BIOS, boot loader, kernel initialization, and starting of processes at designated run levels.
IDA Vulnerabilities and Bug Bounty by Masaaki ChidaCODE BLUE
IDA Pro is an advanced disassembler software and often used in vulnerability research and malware analysis. IDA Pro is used to analyse software behavior in detail, if there was a vulnerability and the user is attacked not only can it have impact in a social sense but also impact legal proceedings. In this presentation I will discuss the vulnerabilities found and attacks leveraging the vulnerabilities and Hex-rays's remediation process and dialogue I had with them.
http://codeblue.jp/en-speaker.html#MasaakiChida
Advanced Threats are rising in the Windows 10 environment, where sophisticated attack vectors are being used to evade threat detection tools and extract privileged data from the user. This talk presents a collection of tools and techniques developed after reverse engineering and playing with Windows interfaces, aim to evade detection system (A/V or A/C) and to escalate kernel privileges.
A Hypervisor IPS based on Hardware Assisted Virtualization TechnologyFFRI, Inc.
This document describes Viton, a hypervisor-based intrusion prevention system (IPS) developed by Fourteenforty Research Institute. Viton runs as a hypervisor using hardware-assisted virtualization technology to monitor the guest operating system for malicious activity. It protects persistent system resources by blocking all VMX instructions, monitoring registers like IDTR and MSR, and protecting read-only code sections of the kernel from modification. Viton aims to enforce immutability of critical system structures to detect rootkits and other malware running inside the guest OS.
The document discusses different approaches to detecting system compromise, including looking for rootkit side effects, signature-based scanning, and explicit compromise detection. It argues that modern malware need not use traditional rootkit techniques like hiding processes or sockets to achieve stealth. A demonstration of a "pretty stealthy backdoor" is presented that modifies only a few kernel data values without installing modules or hiding anything. The document proposes a classification of malware based on what operating system components it modifies and argues that type II malware modifying only data sections will be very difficult to detect.
Joanna Rutkowska Subverting Vista Kernelguestf1a032
The document discusses techniques for subverting the Windows Vista kernel protection mechanisms and loading unsigned code. It describes:
1) Forcing kernel drivers to page out to the pagefile by allocating large amounts of memory, then modifying the paged out code in the pagefile to inject shellcode without requiring a signature.
2) The concept of an undetectable "Blue Pill" malware that could install itself on-the-fly by exploiting AMD64 SVM virtualization extensions to move the operating system into a virtual machine controlled by a thin hypervisor.
3) Challenges of handling nested virtual machines to prevent detection when the system is already compromised by "Blue Pill" malware.
The document discusses system security and provides seven common sense rules for security. It covers account security, file permissions, data encryption, single user security, dialup modems, security tools, and an overview of viruses, trojans, and worms. Monitoring logs, using security scanning tools, and educating yourself on security best practices are emphasized as important ways to help secure systems.
The document discusses system security and provides seven common sense rules for security. It covers account security, file permissions, data encryption, single user security, dialup modems, security tools, and an overview of viruses, trojans, and worms. Monitoring logs, using security scanning tools, and educating yourself on security best practices are emphasized as important ways to help secure systems.
This document provides an overview of debugging and anti-debugging techniques on Windows. It discusses what debugging is, how programs run at the assembly level, and common anti-debugging tricks like API hooking and monitoring debug flags in process and thread data structures. The document also outlines techniques like inline hooking, SSDT hooking, and direct kernel object manipulation that can be used to bypass commercial anti-debugging tools and prevent a debugger from running normally.
The document provides an overview of reverse engineering concepts and techniques. It discusses reverse engineering jargon like zero-day attacks and rootkits. It covers analyzing software from both an attacker and defensive perspective through static and dynamic analysis. Tools discussed include IDA Pro, OllyDbg, Windbg, and Sysinternals utilities. Techniques like anti-debugging, anti-dumping, and code obfuscation used to hinder reverse engineering are also summarized. Specific malware examples like FATMAL and analyzing packed executables and memory are examined. The document concludes with resources for analyzing mobile threats on Android.
I prepared it when i started learning linux at KBFS. It explains why linux is less prone to virus and what kind of viruses affect linux. (final edit pending)
The document describes a procedure for using batch scripting and common tools to identify intrusions on a Microsoft Windows system. The script generates trending data by checking for unusual processes, services, accounts, files and connections. It analyzes the operating system version, registry entries, scheduled tasks, event logs and more. The final summary is a sample batch script that automates running various commands to collect security-related data and output it to log files for administrator review.
When it comes to actual, real-world, active malware detection there are surprisingly few choices. Most companies invest in one anti-virus vendor and when they suspect a compromise they simply wait for them to issue signatures.
If a company thinks they may be compromised but there is no AV signature, then what?
What if we could use basic python scripting to identify malware based on signatures we produce in real time? There are plenty of python tools, scripts and frameworks for malware identification including yara, pefile, nsrl hash db, pyemu, hachoir, volatility and pyew.
What if we could integrate these together into a system for centrally issuing
indicators of compromise? What if hosts we suspect as being compromised used this system to check themselves for compromise? Lets find out...
This document provides an overview of the key components and boot process of embedded Linux systems. It discusses that embedded Linux systems are typically built using cross-compilation on a host PC. The bootloader then initializes the target hardware and loads the operating system, including the Linux kernel, device tree, and root file system. The kernel mounts the root file system and executes the init process, which determines the runlevel and starts essential processes and services based on that runlevel.
Wonder walk in Rootkit Land by Himanshu KhokharOWASP Delhi
This document discusses user mode rootkits and provides examples of LD_PRELOAD and ptrace()-based rootkits. It begins with definitions of rootkits and describes different types including user mode and kernel mode. It then demonstrates an LD_PRELOAD rootkit that hijacks the strcmp() function and modifies its behavior. Another example hijacks the rand() function. The document notes that ptrace()-based rootkits can work on statically linked binaries but are more difficult to implement than LD_PRELOAD and not worth the effort.
The document discusses various operating system structures including batch, time-sharing, distributed, and network operating systems. It describes the layers of common operating system architectures like UNIX with the kernel providing core functions and systems programs interfacing with hardware. Finally, it analyzes hybrid operating system designs used by Linux, Solaris, Windows, iOS, and Android that combine aspects of monolithic and microkernel-based systems.
This document discusses reverse code engineering and the process involved. It provides an introduction by the speaker, Krishs Patil, who has a master's degree in computer application and is a computer programmer, reverser, and security researcher. The outline covers the reversing process, tools and techniques, reversing in different contexts, a lab demonstration, and defeating reverse engineering. It delves into the reversing process including defining scope, setting up environment, disassembling vs decompiling, program structure, and knowledge required. It also covers assembly language, system calls, portable executable files, and analysis tools. The overall document provides an in-depth overview of reverse engineering concepts, approaches, and skills needed.
System hacking is the way hackers get access to individual computers on a network. ... This course explains the main methods of system hacking—password cracking, privilege escalation, spyware installation, and keylogging—and the countermeasures IT security professionals can take to fight these attacks.
Yasser Ramzy Auda is an expert in cybersecurity with numerous certifications including CEH, CCIE, MCSE, VCP-NV, CISSP, and ITIL. He teaches the CEH certification course and provides hands-on training labs with virtual machines like Kali Linux, Metasploitable, Windows Server and more to allow students to conduct security assessments and penetration tests in a safe environment.
Esta apresentação é baseada em uma pesquisa que publiquei em 2015 que tratava de malware do tipo mach-o, e o aumento de visibilidade do macOS como novo alvo. Nesta nova pesquisa, a ideia é mostrar algumas dicas sobre internals, kernel e principais ameaças que o macOS vem enfrentando.
Penetration Testing and Intrusion Detection SystemBikrant Gautam
This document provides an overview of penetration testing techniques, including forms of cyber attacks like buffer overflows and SQL injection. It discusses using Metasploit and other commercial tools like Canvas to conduct network penetration testing. It also covers post-exploitation techniques such as password cracking, privilege escalation, and data exfiltration. The goal of a penetration test is to simulate a real attack to evaluate system defenses and identify vulnerabilities.
[Defcon Russia #29] Борис Савков - Bare-metal programming на примере Raspber...DefconRussia
Докладчик покажет, как с помощью bare-metal programming подружить Raspberry Pi с GPIO, памятью и Ethernet, и пояснит, кому и зачем это может понадобиться.
[Defcon Russia #29] Александр Ермолов - Safeguarding rootkits: Intel Boot Gua...DefconRussia
Intel Boot Guard — аппаратно поддержанная технология верификации подлинности BIOS, которую вендор компьютерной системы может встроить на этапе производства. Докладчик представит результаты анализа технологии, расскажет об её эволюции. Слушатели узнают, как годами клонируемая ошибка на производстве нескольких вендоров позволяет потенциальному злоумышленнику воспользоваться этой технологией для создания в системе неудаляемого (даже программатором!) скрытого руткита. Github: https://github.com/flothrone/bootguard
[Defcon Russia #29] Алексей Тюрин - Spring autobindingDefconRussia
В Spring MVC есть классная фича — autobinding. Но если пользоваться ей неправильно, могут появиться «незаметные» уязвимости, иногда с серьёзным импактом. Рассмотрим пару примеров, углубимся в тонкости появления autobinding-багов. Writeup [ENG]: http://agrrrdog.blogspot.ru/2017/03/autobinding-vulns-and-spring-mvc.html
[Defcon Russia #29] Михаил Клементьев - Обнаружение руткитов в GNU/LinuxDefconRussia
Руткиты в мире основанных на ядре Linux операционных систем уже не являются редкостью. Рассказ будет о том, как попытки в современных реалиях определить то, скомпрометирована ли система, привели к неожиданному результату.
[DCG 25] Александр Большев - Never Trust Your Inputs or How To Fool an ADC DefconRussia
Мы поговорим об общей проблеме валидации входных данных и качестве их обработки. Интерпретация входящих данных оказывает прямое влияние на решения, принимаемые в физической инфраструктуре: если какая-либо часть данных обрабатывается недостаточно аккуратно, это может повлиять на эффективность и безопасность процесса.
В этой беседе мы обсудим атаки на процесс обработки данных и природу концепции «never trust your inputs» в контексте информационно-физических систем (в общем смысле, то есть любых подобных систем). Для иллюстрации проблемы мы используем уязвимости аналого-цифровых преобразователей (АЦП), которые можно заставить выдавать поддельный цифровой сигнал с помощью изменения частоты и фазы входящего аналогового сигнала: ошибка масштабирования такого сигнала может вызывать целочисленное переполнение и дает возможность эксплуатировать уязвимости в логике PLC/встроенного ПО. Также мы покажем реальные примеры использования подобных уязвимостей и последствия этих нападений.
This document discusses Cisco IOS shellcoding and reverse engineering. It covers topics like Cisco IOS shellcodes that are image-independent by disassembling or interrupting hijacking. It also discusses Tcl shellcodes, Cisco IOS reverse engineering challenges including lack of modularity and APIs. The document details subsystems, registries, processes, command parser tree, debugging Cisco IOS, and magic numbers used in Cisco IOS.
This document discusses a password collection called W3@|cP@$s. It contains dictionaries of passwords gathered from multiple sources on the internet. The document provides statistics on the number and types of passwords collected, such as the frequency of different character sets and length distributions. It also describes the features of the collection, including the ability to filter passwords, count totals, and check sample passwords. The collection contains over 3.5 billion passwords gathered using automated bots to find password dumps from sites like pastebin.com.
This document discusses approaches for analyzing obfuscated code without symbols. It presents several techniques including identifying logging functions, searching for specific strings, using meta information like RTTI, analyzing the context of functions and their relationships, and considering properties of the overall program. A combination of techniques is recommended, prioritizing those most likely to apply, such as searching for strings, analyzing wrapper functions, and studying function call relationships.
The document describes a simulated hacking game scenario involving a compromised POS terminal infected with malware. It details the components of the botnet architecture including bot nodes, command and control infrastructure, and social media propagation. Diagrams show the network layout and communication channels. The document also examines the bot's components, capabilities, and protection mechanisms such as bytecode encryption and anti-debugging techniques. Hints are provided to help players progress in the game by bypassing defenses and achieving objectives over multiple days.
The document discusses using virtual machine techniques like GuestRPC and Backdoor I/O to conduct virtual denial of service attacks. It describes fuzzing the GuestRPC interface to discover bugs in systems like HGFS that could be exploited to cause memory leaks or crashes on the host machine. While vendors issue fixes, it notes that fully preventing abuse of these virtual machine behaviors is difficult and some techniques remain unfixed. It concludes with questions about using these kinds of attacks to bypass security systems on virtual machines.
Advanced cfg bypass on adobe flash player 18 defcon russia 23DefconRussia
This document describes an advanced technique to bypass Control Flow Guard (CFG) protections on Adobe Flash Player 18 and Windows 8.1. It details how the researchers were able to generate indirect call instructions in just-in-time (JIT) compiled Flash code to redirect execution to controlled addresses, bypassing CFG. This was done by manipulating parameters passed between functions to influence the JIT compiler's code generation and produce the desired indirect call opcodes. The technique allowed full control-flow hijacking on the protected systems.
Andrey Belenko, Alexey Troshichev - Внутреннее устройство и безопасность iClo...DefconRussia
Расскажу где и как iCloud Keychain хранит пароли, и какие потенциальные риски это несёт. Apple утверждает, что пароли надежно защищены, и даже её сотрудники не могут получить к ним доступ. Чтобы это подтвердить или опровергнуть, необходимо разобраться с внутренним устройством iCloud Keychain, чем мы и займемся.
Sergey Belov - Покажите нам Impact! Доказываем угрозу в сложных условияхDefconRussia
Все шире и шире получают распространение bugbounty программы - программы вознаграждения за уязвимости различных вендоров. И порой при поиске уязвимостей находятся места, которые явно небезопасны (например - self XSS), но доказать от них угрозу сложно. Но чем крупнее (хотя, скорее адекватнее) вендор, тем они охотнее обсуждают и просят показать угрозу от сообщенной уязвимости, и при успехе – вознаграждают 8). Мой доклад – подборка таких сложных ситуаций и рассказ, как же можно доказать угрозу.
3. What do you think when you hear this term?
Rustock
TDSS/Alureon
ZeroAccess
Carberp
4. What do you think when you hear this term?
Rustock
TDSS/Alureon
ZeroAccess
Carberp
My talk about another: rootkits for the target
attacks
5. The purpose of malicious code puts certain requirements over it
In general, the requirements are persistence and activity hiding, but
also there is some special cases
Case #1: rootkits for the mass-spreading malware
Prevent active infection curing by the popular anti-virus software
Case #2: rootkits for the target attacks
Prevent active infection detection even by the professional during
forensic analysis
The main subject of this talk
6. Specific requirements dictate the necessity of the
specific technical solutions
All rootkits listed above in the case #1 and all
known «cyber-weapon» stuff are very easy
detectable
We need to design something fundamentally new
that will be good enough for the case #2
But first - let's look at the common rootkit detection
scenarios for better understanding of the task
7. In order to be working the malicious code must get execution
somehow
System service installation or using of the less obvious auto-run
capabilities (documented or not) of OS
▪ TDL 2, Rustock, Srizbi, Stuxnet, Duqu
Infection of the existing executable file
▪ TDL 3, ZeroAccess, Virut
OS booting control (modification of the boot code, partition table or
playing with the UEFI boot drivers and services)
▪ TDL 4, Mebroot, Olmarik, Rovnix, UEFI rootkit by @snare
8. Apart from getting the execution rootkits also have
to hide the evidences of their work (we're still
talking about rootkits?)
Hidden objects and resources of the operating
system make the rootkit detection more easy
How exactly?
9. Step 1: collect the database (like name/path + hash) of interesting
resources (files, system registry, boot sectors) inside the environment
of presumably infected by rootkit OS
Step 2: collect the same database but with the mounting of the target
OS system volume inside the environment of clear and trusted OS
Step 3: diff of the two databases will show us the resources that were
hidden or locked by the rootkit inside the environment of the target OS
Reliability is close to 100% in the absence of implementation errors
Very hard for to bypass such detection
I'm using this method successfully in the different practical cases
13. The malicious code also can have nothing to hide (because not
only rootkits are useful)
Developers can masquerade the malicious module as a legitimate
program component (from OS or 3-rd party software)
Actually, such case is much more harder for investigation and
detection than “true rootkit”, that hides any files/processes/registry
keys/etc.
But we still can compare collected resources database with the
some reference
Good system administrator always knows, exactly what software
and drivers are installed on his servers and workstations. Find
something extraneous among known components and data is a
much than possible
14. So, for these reasons our ideal rootkit for target attacks is strictly
prohibited to use:
All the regular ways of auto-run
Existing files modification and new files creation
Interfere in the process of OS booting with the modification of MBR, VBR,
NTFS $Boot and so on.
But where should we store the malicious code and how to pass
execution into it?
Maybe, firmware infection is the most obvious way?
Yes: that’s a powerful technology and it can solve our tasks
No: in practice – very expensive, depends on the specific hardware and
have a lot of other limitations
15. Let’s store malicious code inside some REG_BINARY
or REG_SZ system registry value!
16. The main goal: Windows system registry – is the millions of keys and
values
There is no any complete documentation on all of these
Usually, the forensic analysis is limited by checking only a small part of
registry keys (that stores critical system settings and known auto-run
locations)
The main problem: how to execute a code, that located inside a
system registry value?
Of course, the Windows haven’t any regular capabilities for that
But some registry keys can contain the data that very interesting and
sensitive itself
Also, there are a lot of code and program components that read something
from the system registry, and, of course, such code can have vulnerabilities
17. What interesting is kept in the system registry?
Settings, users password hashes, certificates and secret/public keys
Maybe, anything else?
18. Windows ACPI driver stores a copy of the DSDT table (that was read
from the firmware) inside a system registry
sometimes this feature is used by enthusiasts to fix the hardware vendor
bugs
DSDT – is the part of ACPI specification, this table stores machine-
independent subprograms, that are interpreting by ACPI driver in the
occurrence of different power events
ACPI spec 4.0a, «5.2 ACPI System Description Tables»
DSDT had already got under the attention of researchers
«Implementing and Detecting an ACPI BIOS Rootkit» (John Heasman, Black
Hat 2006)
I propose to modify the copy of DSDT inside the system registry, but not
inside the firmware
19. DSDT can contain data objects and control methods
They forming a hierarchical ACPI namespace
Control methods are represented in the form of an AML byte-
code (ACPI Machine Language), in which compiles the programs
written in ASL (ACPI Source Language)
Compilers and disassemblers are available in toolkits from Intel and
Microsoft
It’s possible to browse ACPI namespace and debug the AML code
with the acpikd extension for WinDbg
AML byte-code interpreter located inside the operating system
ACPI driver (ACPI.sys on Windows)
20. ASL provides a lot of capabilities for working with the hardware
resources
OperationRegion directive (ACPI spec 4.0a, «18.5.89 Declare Operation
Region») can give the access to the different memory regions
21. Example: ASL code that writes 0x1337 into the
physical memory at 0x80000000
22. Write ASL program, that generates the malicious machine code
directly into the physical memory, and then – patches OS kernel
for redirecting control flow to the generated code
Read DSDT contents from the system registry
Add written program into the code of some control method, that
will be called during OS startup
Write modified DSDT back into the system registry
PROFFIT!
At the next reboot modified control method code will be interpreted
by ACPI driver and after that – our malicious code will be generated
and executed
23. ASL code can work only with the physical memory, so, for accessing to
the virtual memory we need to make the address translation manually
Windows stores PDE/PTE tables at the constant virtual addresses
0xC0300000/0xC0000000 (for x86)
Then we should find the address of the some kernel mode code to
patch, the using of hardcoded address is possible
Will work on NT 5.x
Will not work NT 6.x because there is a kernel-mode ASLR
… but it’s better to modify the code, that located in the SystemCallPad
field of the _KUSER_SHARED_DATA structure
This structure located at the executable memory page with the constant
address 0xffdf0000 (at least – up to NT 6.1 including)
The end of this page can be used to store the malicious code
25. Unfortunately, considered DSDT modification works
fine only on the NT 5.x and gives the strange BSoD
on the NT 6.x:
26. The reason – KeBugCheckEx call inside the ACPI.sys
27. ACPI!MapPhysMem calls the
AmlpValidateFirmwareMemoryAddress function, that checks the
physical address from the OperationRegion for belonging to the I/O
ports addresses ranges
If the control method code trying to read or write something different
(executable images that mapped to the memory, kernel structures and so
on) – ACPI.sys drops the system into the BSoD
ACPI.sys reads the information about the allowed memory regions
from the special keys of the system registry, that located in
HARDWAREDESCRIPTIONSystemMultifunctionAdapter
This key is not a permanent – it’s creating during the operating system
startup
PnP driver puts I/O memory information inside it during the hardware
resources enumeration and initialization
28. Well… we can try to put fake I/O memory information into the
system registry and corrupt the hive binary structure somehow
to prevent the system to modify data
Also, the possible way is exploring the other ACPI features
Already done by Alex Ionescu: «ACPI 5.0 Rootkit Attacks Against
Windows 8»
One more variant: to find the vulnerability in the AML byte-code
interpreter code
But stop, out primary task – is executing of the code, that is
located inside the system registry. Let’s leave ACPI and find
some different way
29. Do you remember the local privileges escalation
vulnerability CVE-2010-4398 (MS11-010)?
The another one vulnerability in the win32k.sys
Incorrect usage of the RtlQueryRegistryValues kernel
function causes stack-based buffer overflow during
reading the registry value contents
Because the RtlQueryRegistryValues – is really
overcomplicated
Seems that even the Windows developers don’t know all
the documented features of the some kernel functions
30. The RtlQueryRegistryValues has a lot of options and different
data reading modes
The most interesting stuff located in the
RTL_QUERY_REGISTRY_TABLE structure, that must be passed
to the RtlQueryRegistryValues as an argument
31. The Flags field can contain the RTL_QUERY_REGISTRY_DIRECT flag:
The MSDN quote about this flag: «The QueryRoutine member is not used
(and must be NULL), and the EntryContext points to the buffer to store the
value»
From the type of the value, that you’re reading, depends on how
exactly the data will be written into the buffer
REG_SZ, REG_EXPAND_SZ: «EntryContext must point to an initialized
UNICODE_STRING structure»
Non-string data with size <=sizeof(ULONG): «The value is stored in the
memory location specified by EntryContext»
Non-string data with size >sizeof(ULONG): «The buffer pointed to
by EntryContext must begin with a signed LONG value. The magnitude of
the value must specify the size, in bytes, of the buffer»
32. The usage of the RtlQueryRegistryValues causes the BoF when:
The code is trying to read REG_DWORD or REG_SZ value with the
RTL_QUERY_REGISTRY_DIRECT flag but without the correct type
value in the DefaultType field
… and buffer, that pointed by the EntryContext field, has a non-zero
DWORD at the beginning (for example – when the EntryContext
points to the initialized UNICODE_STRING structure)
… and attacker can replace the reading value (REG_DWORD or
REG_SZ) by malicious one, that has a REG_BINARY type
Result –100% controllable overflow with the trivial
exploitation!
Number of overwritten bytes – is the first DWORD value from the
EntryContext pointed buffer
33. Simple PoC for the CVE-2010-4398 as a .REG file:
35. Of course, Microsoft has released a path for the CVE-2011-4398
That patch also adds some improvements and mitigations for the
RtlQueryRegistryValues function:
The RTL_QUERY_REGISTRY_TYPECHECK flag has been added, if it is
specified – the RtlQueryRegistryValues will return an error in case of the
zero DefaultType field
In Windows 8 the RTL_QUERY_REGISTRY_DIRECT flag works only for the
trusted registry keys (that can’t be overwritten under limited user account)
But these improvements will not make the already written code more
secure
On Windows 7 we still have a good LPE vector
… and local-admin-to-ring0 on Windows 8
36. Even reverse engineering of the vulnerabilities that
were already fixed can give you a valuable
experience
As a result of the patched vulnerabilities discovery
it’s possible to obtain a new attack vector and a
"template" of the vulnerable code, that can be used
to find new zero-day vulnerabilities
Let’s try to find zero-day vulnerabilities that are
similar to the CVE-2010-4398
38. Fuzzing? Static dataflow analysis? Symbolic execution?
Keep it simple. IDA, win32k.sys and one hour of the time!
39. Some interesting piece of code in win32k.sys:
40. The win32!bInitializeEUDC function unsafely reading the
«FontLink» value (REG_DWORD) of the
«SoftwareMicrosoftWindows NTCurrentVersion» key
No DefaultType specified, EntryContext pointed buffer – is
uninitialized stack variable with the non-zero value
We can trigger the vulnerability by replacing these values with
the REG_BINARY one
41. Yes, it drops a system into the BSoD and we can
control the EIP value
42. Vulnerable function takes the execution from the NtUserInitialize
system call handler. Windows kernel is using this system call for the
per-session initialization of the Win32 subsystem
So, the vulnerability can be triggered during the system boot, all that we
need – is just put the malicious value into the system registry
43. There is a DEP and ASLR in the NT 6.x kernels, and we need to bypass
them absolutely blindly without any pre-interaction with the OS
Good thing – there is no stack cookies in win32!bInitializeEUDC
Exploit should not violate the normal execution flow and global state
of the OS kernel, if it will – BSoD and unbootable OS
Need to restore overwritten stack frames and correctly pass the execution
from the shellcode back to the win32k.sys
Overflow happens too close to the bottom of the stack, we have only
about 70 bytes for the shellcode
It’s not possible to do the spray or something, because we can’t interact
with the OS at the exploitation stage, all that we have – is the data that
overwrites the stack
44. A little fail: I haven’t got the ROP chain with the short enough length
for DEP/ASLR bypass inside the Windows kernel environment (and it
seems that nobody has)
The shortest what I know – has a 68 bytes length without the shellcode
See the «Bypassing Windows 7 kernel ASLR» by Stéfan LE BERRE
Compromise solution – to disable the DEP inside the Windows boot
loader configuration
… and enable it for the user-mode processes back when the shellcode has
been successfully executed
There is no way to disable ASLR
But it seems that it’s not a very critical for the vulnerability that I’m talking
about
45. I’m using the JMP ESP that is located at the constant address
inside the KUSER_SHARED_DATA for defeating the kernel ASLR
70 bytes is a pretty enough for the egg-hunting stage 1
shellcode, that locates and executes stage 2 shellcode in the
kernel-space virtual memory by the binary signature lookup
Stage 2 shellcode is originally located inside some another registry
value – Windows kernel maps the big parts of the registry hives in
the virtual memory
Also, in stage 1 shellcode I’m finding an address of the
MmIsAddressValid kernel function
Stage 1 shellcode is obtaining the kernel image base from the _KPCR
structure (we can access it via FS segment register)
47. For the OS code execution state normalization the stage 2
shellcode must perform some operations, that weren’t executed
in the win32k.sys code because of the buffer overflow
It sets the WIN32_PROCESS_FLAGS flag inside the Win32 Process
Information structure (W32PROCESS) for the current process
It finds the address of the non-exportable function
win32k!UserInitialize and calls it manually
Then, the stage 2 shellcode loads, initializes and runs the ring 0
payload
After that, the stage 2 shellcode sets the return address and ESP
values in order to return the execution of the current system
call back to the system calls manager (nt!_KiFastCallEntry) with
the STATUS_SUCCESS return value
48. Regular Windows kernel mode driver PE image
Is also stored inside the system registry value
It hides itself from the modern anti-rootkits
In order to avoid unknown executable code detection it moves itself in the
memory over discardable sections of some default Windows drivers
It installs the kernel mode network backdoor
Undetectable NDIS miniport level hooks allows to monitor the incoming
network traffic on all of the interfaces
When network backdoor finds the magic sequence in the traffic – it injects
meterpreter/bind_tcp payload (from the Metasploit framework) for
execution into the WINLOGON.EXE user mode process
50. Check out the rootkit source code on GitHub!
github.com/Cr4sh/WindowsRegistryRootkit
51. I’m not reported about these win32k.sys vulnerability into the
Microsoft
Not very critical vulnerability because of the strange practical use-cases
Vulnerable systems – all the NT 6.x (up to the Windows 8), for x86 and
x64
Seems that stable exploitation of vulnerability in the
win32!bInitializeEUDC function is impossible on the x64 Windows
version
The win32k!bInitializeEUDC function have the stack cookies on
Windows x64 because of the stack frames elimination
Impossible to exploit such cases completely blindly, without the pre-
interaction with the OS