Workshop – Malware applications IonutPopescu Penetration Tester @ KPMG Romania http://www.kpmg.com/ro/en/Pages/default.aspx Administrator @ Romanian Security Team https://www.rstforums.com
Contents • About malware…………..………………………………………………………… • Malware examples………….…………………………………………………….. • Windows OS architecture…………………..……………………………………. • WinAPI function calls.…………………………………………………………….. • PE (Portable Executable) file format………...………………………………….. • Assembly & shellcodes ………………………………………………………...... • DLL Injection (why & how)……………………………………………………….. • API Hooking (why & how)………………………………………………………… • Malware classes: Java DriveBy, Stealer, Rootkit……..……………………….. • Malware analysis: static and dynamic………………………………………….. • Reverse engineering – Basics…………………………………………………... • Exploits: General information………………….………………………………… • Q/A and contact information……………………………………………………... These materials are intended for educational purposes only! I cannot be held responsible for any damage caused by information gained from this workshop!
About malware “Malware, short for malicious software, is software used to disrupt computer operation, gather sensitive information, or gain access to private computer systems. It can appear in the form of code, scripts, active content, and other software. 'Malware' is a general term used to refer to a variety of forms of hostile or intrusive software.” Virus – It is a generic term for malware that infects a system Worm – It has the ability to auto-copy to other systems Rootkit – It can hide itself from the process list, filesystem and registry Keylogger – It captures all the keys pressesd and sends them to the attacker Spyware – It steals personal information about victims Stealer – It steals passwords saved in web browsers or other apps Rogue-AV – It is a fake antivirus and it requests money for a fake disinfection Ransomware – It limits user access to files or PC until a payment is made Crypter – It can modify a detectable file to be undetected by the antivirus These notes are for classification only.
Day by day malware examples Stuxnetis a computer virus that was discovered in June 2010. It was designed to attack Siemens Step7 software running on a Windows operating system.Stuxnet almost ruined one-fifth of the Iranian nuclear centrifuge by spinning out of control while simultaneously replaying the recorded system values which shows the normal functioning centrifuge during the attack. Flameis modular computer malware discovered in 2012 that attacks computers running the Microsoft Windows operating system. The program is being used for targeted cyber espionage in Middle Eastern countries. The last of these stated in its report that it "is certainly the most sophisticated malware we encountered during our practice; arguably, it is the most complex malware ever found”. Confickeris a computer worm targeting the Microsoft Windows operating system that was first detected in November 2008. It uses flaws in Windows software and dictionary attacks on administrator passwords to propagate while forming a botnet, and has been unusually difficult to counter because of its combined use of many advanced malware techniques. CryptoLockeris a ransomware trojan which targets computers running Microsoft Windows and first surfaced in September 2013. A CryptoLocker attack may come from various sources; one such is disguised as a legitimate email attachment. When activated, the malware encrypts certain types of files stored on local and mounted network drives using RSA public-key cryptography, with the private key stored only on the malware's control servers. Zeusis Trojan horse computer malware that runs on computers running under versions of the Microsoft Windows operating system. While it is capable of being used to carry out many malicious and criminal tasks, it is often used to steal banking information by man-in-the-browser keystroke logging and form grabbing. It is also used to install the CryptoLocker ransomware. Rustockbotnet was a botnet that operated from around 2006 until March 2011. It consisted of computers running Microsoft Windows, and was capable of sending up to 25,000 spam messages per hour from an infected PC. At the height of its activities, it sent an average of 192 spam messages per compromised machine per minute. Advanced Persistent Threat (APT) is a set of stealthy and continuous hacking processes often orchestrated by human targeting a specific entity. APT usually targets organizations and or nations for business or political motives.
Windows kernel components The kernel mode in Windows is comprised of the Windows Executive, which includes the Executive Services, the kernel, and the hardware abstraction layer (HAL). The Windows executiveis the upper layer of Ntoskrnl.exe. (The kernel is the lower layer.)The executive provides core OS services. The executive contains major components such as various modules that manage I/O, objects, security, processes, inter-process communications (IPC), virtual memory, and window and graphics management. It also includes device driversfunctions. The kernel consists of a set of functions in Ntoskrnl.exe provides the most basic operating system services, such as thread scheduling, first-level interrupt handling, and deferred procedure calls. The kernel resides between the Executive Services and HAL layers. The other major job of the kernel is to abstract or isolate the executive and device drivers from variations between the hardware architectures supported by Windows. One of the crucial elements of the Windows design is its portability across a variety of hardware platforms. The hardware abstraction layer (HAL) is a key part of making this portability possible. The HAL is a loadable kernel-mode module (Hal.dll) enables the same operating system to run on different platforms with different processors. Also part of the kernel is the device drivers. Device drivers in Windows don't manipulate hardware directly, but rather they call functions in the HAL to interface with the hardware. ntoskrnl.exe(and ntkrnlpa.exe on systems with Physical Address Extension support) is the kernel image for the family of Microsoft Windows NT operating systems. It provides the kernel and executive layers of the Windows NT kernel space, and is responsible for various system services such as hardware virtualization, process and memory management, etc.
Windows userland library files MSVCRT.DLL is the Microsoft Visual C Run-Time Library for Visual C++. It provides programs compiled with these versions of Visual C++ a typical set of library functions required by C and C++ programs. These include string manipulation, memory allocation, C-style input/output calls, etc. USER32.DLL implements the Windows USER component that creates and manipulates the standard elements of the Windows user interface, such as the desktop, windows, and menus. It thus enables programs to implement a graphical user interface that matches the Windows look and feel. COMCTL32.DLL implements a wide variety of standard Windows controls, such as File Open, Save, and Save As dialogs, progress bars, and list views. It calls functions from both USER32.DLL and GDI32.DLL to create and manage the windows for these UI elements, place various graphic elements within them, and collect user input. KERNEL32.DLL exposes to applications most of the Win32 base APIs, such as memory management, input/output operations, process and thread creation, and synchronization functions. Many of these are implemented within KERNEL32.DLL by calling corresponding functions in the native API, exposed by NTDLL.DLL. NTDLL.DLL exports the Windows Native API. Most of the Native API calls are implemented in ntoskrnl.exe and are exposed to user mode by ntdll.dll. Some malware make use of the Native API to hide their presence from malware detection software. Nt or Zw are system calls declared in ntdll.dll and ntoskrnl.exe. When called from ntdll.dll in user mode, these groups are almost exactly the same; they trap into kernel mode and call the equivalent function in ntoskrnl.exe via the SSDT.
Windows 7 new library files Windows 7 introduces a new set of dll files containing exported functions of many well-known WIN32 APIs. All these filenames begins with 'api-ms-win-core' prefix, followed by the functions category name. For example, api-ms-win-core-localregistry-l1-1-0.dll contains the exported names for all Registry functions, api-ms-win-core-file-l1-1-0.dll contains the exported names for all file-related functions, api-ms-win-core-localization-l1-1-0.dll contains the exported names for all localization functions, and so on. When Windows loads the dll files, all the import entries of these api-ms-win-core Dlls are replaced with a call to a real function in Windows kernel. So here's our RegDeleteValueW example again: when loading a program into WinDbg, we can see that the jmp call now points to kernel32!RegDeleteValueW function. That's because during the loading of advapi32.dll, Windows automatically replace the import entry of API-MS-Win-Core-LocalRegistry-L1-1-0.RegDeleteValueW to the function address of RegDeleteValueW in kernel32. In previous versions of Windows, most of the kernel32 functions called to their corresponding functions in ntdll.dll. In Windows 7, most of the kernel functions call to their corresponding functions in kernelbase.dll, and the kernelbase dll is the one that makes the calls to ntdll.dll 75e5f307 eb05 jmp ADVAPI32!RegDeleteValueW+0xd (75e5f30e) 75e5f30e ff25b414e575 jmp dword ptr [ADVAPI32+0x14b4 (75e514b4)] ds:0023:75e514b4 = kernel32!RegDeleteValueW(758bd5af)
WinAPI function calls How a simple “fread” function call is made.
WinAPI function example Windows API Index: http://msdn.microsoft.com/en-us/library/windows/desktop/ff818516%28v=vs.85%29.aspx
Windows common processes SMSS.EXE - Session Manager Subsystem is a component of the Microsoft Windows NT family. It is executed during the startup process of those operating systems. At this time it: creates environment variable, starts the kernel and user modes of the Win32 subsystem, starts winlogon.exe, the Windows logon manager. WINLOGON.EXE - In computing, Winlogon is the component of Microsoft Windows operating systems that is responsible for handling the secure attention sequence, loading the user profile on logon, and optionally locking the computer when a screensaver is running (requiring another authentication step). CSRSS.EXE - Client/Server Runtime Subsystem provides the user mode side of the Win32 subsystem. When a user-mode process calls a function involving console windows, process/thread creation, or side-by-side support, instead of issuing a system call, the Win32 libraries (kernel32.dll, user32.dll, gdi32.dll) send an inter-process call to the CSRSS process which does most of the actual work without compromising the kernel. CSRSS is called along with winlogon.exe at Windows start-up. LSASS.EXE- Local Security Authority Subsystem Service is a process in Microsoft Windows operating systems that is responsible for enforcing the security policy on the system. It verifies users logging on to a Windows computer or server, handles password changes, and creates access tokens. Because lsass.exe is a crucial system file, its name is often faked by malware. The lsass.exe file used by Windows is located in the folder C:\Windows\System32. If it is running from any other location, that lsass.exe is most likely a virus, spyware, trojan or worm.
Windows Registry The Windows Registry is a hierarchical database that stores configuration settings and options on Microsoft Windows operating systems. It contains settings for low-level operating system components and for applications running on the platform that have opted to use the registry. The kernel, device drivers, services, SAM, user interface and third party applications can all make use of the registry.
PE File Format The Portable Executable (PE) format is a file format for executables, object code, DLLs, and others used in 32-bit and 64-bit versions of Windows operating systems. The PE format is a data structure that encapsulates the information necessary for the Windows OS loader to manage the wrapped executable code. This includes dynamic library references for linking, API export and import tables, resource management data and thread-local storage (TLS) data. On NT operating systems, the PE format is used for EXE, DLL, SYS (device driver), and other file types. A PE file consists of a number of headers and sections that tell the dynamic linker how to map the file into memory. An executable image consists of several different regions, each of which require different memory protection; so each section must be aligned to a page boundary.
MS-DOS Header MS-DOS header only, opened in a hex editor. Notable strings: it starts with “MZ” and it contains the following text: “This program cannot be run in DOS mode.”
PE Header MS-DOS header specifies (e_lfanew) the start of PE header.
PE imports table To parse the imports table, we need to iterate through all the functions with two pointers: one for the name of the function and the other for the address of the function.
Assembly & shellcode C code for a simple application and assembly code in OllyDbg.
DLL Injection Why? To execute code within other process, eg. Firefox.exe. In computer programming, DLL injection is a technique used for running code within the address space of another process by forcing it to load a dynamic-link library. DLL injection is often used by external programs to influence the behavior of another program in a way its authors did not anticipate or intend. For example, the injected code could hook system function calls, or read the contents of password textboxes, which cannot be done the usual way. A program used to inject arbitrary code into arbitrary processes is called DLL injector. There are various ways we can achieve that: - AppInit_DLLs - SetWindowsHookEx - CreateRemoteThread There are many reasons to do it. For example a malware author may want to hide the malicious activity by loading a DLL into a trusted process or may want to bypass security devices while on the other hand a person may want to extend the functionality of the original program
DLL Injection The Windows API actually offers a number of functions that allow us to attach and manipulate into other programs for debugging purposes. We'll leverage these methods to perform our DLL Injection. I've broken down DLL injection into four steps: - Attach to the process - Allocate Memory within the process - Copy the DLL or the DLL Path into the processes memory and determine appropriate memory addresses - Instruct the process to Execute your DLL LoadLibraryA() is a kernel32.dll function used to load DLLs, executables, and other supporting libraries at run time. It takes a filename as its only parameter and magically makes everything work. This means that we just need to allocate some memory for the path to our DLL providing the memory address where the path lies as a parameter.
DLL Injection Basic DLL Injection code example.
API Hooking Why? To monitor API calls from specific process, eg. Firefox.exe : ReadFile. In computer programming, the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a "hook". Hooking is used for many purposes, including debugging and extending functionality. Examples might include intercepting keyboard or mouse event messages before they reach an application, or intercepting operating system calls in order to monitor behavior or modify the function of an application or other component. It is also widely used in benchmarking programs, for example frame rate measuring in 3D games, where the output and input is done through hooking. Hooking can also be used by malicious code. For example, rootkits, pieces of software that try to make themselves invisible by faking the output of API calls that would otherwise reveal their existence, often use hooking techniques. A wallhack is another example of malicious behavior that can stem from hooking techniques. It is done by intercepting function calls in a computer game and altering what is shown to the player to allow them to gain an unfair advantage over other players. Detours is a general purpose function hooking library created by Microsoft Research. Detours intercepts Win32 functions by re-writing the in-memory code for target functions.
API Hooking The most common API hooking method is to replace first 5 bytes from a function code and jump to a new function. Some DLLs compiled with Visual C++ may allow hot patching.
API Hooking This code will jump to other function when “PR_Read” function call is made by Firefox.exe. It is important to restore the original bytes, call the original function and preserve the stack.
Antivirus Do not blindly trust that your antivirus is enough to protect you.
Java DriveBy Drive-by download means two things, each concerning the download of computer software from the Internet: - Downloads which a person authorized but without understanding the consequences (e.g. downloads which install an unknown or counterfeit executable program, ActiveX component, or Java applet). - Any download that happens without a person's knowledge, often a computer virus, spyware, malware, or crimeware. Drive-by downloads may happen when visiting a website, viewing an e-mail message or by clicking on a deceptive pop-up window.
Keylogger Keystroke logging, often referred to as keylogging or Keyboard Capturing, is the action of recording (or logging) the keys struck on a keyboard, typically in a covert manner so that the person using the keyboard is unaware that their actions are being monitored. It also has very legitimate uses in studies of human-computer interaction. There are numerous keylogging methods, ranging from hardware and software-based approaches to acoustic analysis.
Keylogger It determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState.
Keylogger WH_KEYBOARD_LL - Installs a hook procedure that monitors low-level keyboard input events.
Stealer Do not save passwords in the web browser! If you relly want to save them, use a master password.
Stealer Firefox passwords are saved in a simple SQLite database.
Crypter A crypter has two components: the builder, a GUI for users and a “stub”, a small program that will contain the encrypted malware. It reads itself, decrypts malware and loads it into memory.
Crypter Loading a PE file into memory and execute it is not really complicated: create a new process, load the PE file, align sections, set EAX to EntryPoint and start the process thread. Ok, it is.
Rootkit In this example, Rootkit revealer displays some files and registry keys hidden by a rootkit.
Rootkit System Service Descriptor Table (SSDT) is an internal dispatch table Microsoft Windows. Hooking SSDT calls is often used as a technique in both Windows rootkits and antivirus software.
Ransomware CryptoLocker is a ransomware trojan. A CryptoLocker attack may come from various sources; one such is disguised as a legitimate email attachment. When activated, the malware encrypts certain types of files stored on local and mounted network drives using RSA public-key cryptography, with the private key stored only on the malware's control servers.
Rogue security software Rogue-AV or Rogue security software is a Rogue that deceives or misleads users into paying money for fake or simulated removal of malware (so is a form of ransomware)—or it claims to get rid of, but instead introduces malware to the computer.
RAT (Remote Admin Tool) A remote administration tool (a RAT) is a piece of software that allows a remote "operator" to control a system as if he has physical access to that system. "RAT" software is usually associated with criminal or malicious activity. Such tools provide an operator the following capabilities: screen/camera capture, file management (download/upload/execute) and so on.
Virustotal VirusTotal is a free virus, malware and URL online scanning service. File checking is done with more than 40 antivirus solutions.
Anubis Anubis is a service for analyzing malware.
ResHacker Resource Hacker is a freeware utility to view, modify, rename, add, delete and extract resources in 32bit & 64bit Windows executables and resource files (*.res).
PE Explorer PE Explorer is the most feature-packed program for inspecting the inner workings of your own software, and more importantly, third party Windows applications and libraries for which you do not have source code.
PEID PEiD detects most common packers, cryptors and compilers for PE files. It can currently detect more than 470 different signatures in PE files.
VMWare Player Player is a desktop application that lets you create, configure, and run virtual machines. You can also use Player to download and run virtual appliances.