The text of the presentation (for Google search and to get an idea about the contents:)

========================
Manipulating Memory for Fun & Profit
6 February 2013
Frédéric BOURLA
Chief Security Specialist
========================
# readelf prez
* Slides & talk in English.
* Native French speaker, so feel free to send me an email in French if case of question.
* Talk focused on Memory Manipulation, from both offensive and defensives angles.
* 1 round of 45’.
* Vast topic, lots of issues to address, and lots of slides so that the most technical of you can come back later to remember commands.
* Therefore some slides [specially the beginning] will be fast, but everything is summarized in demos.
* No need to take notes, the whole slides and demos will be published on High-Tech Bridge website.
========================
# readelf prez
* Despite its name, this talk will not deal with Total Recall or any other human memory manipulation based movie.
* Nor will it deal with classical binary exploitation, such as Stack based Buffer Overflows or Heap Spraying. I strongly advice to read corelanc0d3rs’ papers on corelan.be to learn more regarding Exploit Writing.
========================
Table of contents
0x00 - About me
0x01 - About this conference
0x02 - Memory introduction
0x03 - Memory manipulation from an offensive angle
0x04 - Memory manipulation from a defensive angle
0x05 - Conclusion
========================
# man mem
* RAM (Random Access Memory) is a temporary memory accessible by the CPU in order to hold all of the program code and data that is processed by the computer.
* It is called “random” because the system can directly access any of the memory cells anywhere on the RAM chip if it knows its row (i.e. “address”) and its column (i.e. “data bit”).
* It is much faster to access data in RAM than on the hard drive.
* CPU and OS determine how much and how the available memory will be used.
========================
# man mem
* In other words, most users do not have any control on memory, which makes RAM a target of choice.
* First systems were arbitrary limited to 640Kb RAM. Bill Gates once declared that “640K ought to be enough for anybody”.
* At this time it was far enough… But today the OS itself can consume 1 Gb. We therefore use much more memory.
* On a 32 bits Windows system, OS can directly address 2^32 cells, and is therefore mathematically limited to 4 Gb memory.
========================
# man mem
* Contrary to popular assumption, RAM can retain its content up to several minutes after a shutdown.
* Basically RAM is everywhere nowadays. Printers, fax, VoIP phones, GPS and smartphones are good examples.
* This provide some opportunities to security professionals [and also to bad guys]. Some points of this talk can be applied to various targets and may not be limited to Windows systems, even if since now we will deal with a classical Microsoft host.
========================
# man mem
* Upon process instantiation, the code is mapped in memory so that the CPU can read its instructions, and each process has his own virtual memory.
* OS relies on page table structures to map transparently each virtual memory address to physical memory.
* But most importantly, any program [including both its data and its instructions] must first be loaded into memory before being run by the processor.
========================
# man mem
* For example, FUD Trojans which highly rely on Packers & Crypters can be quickly uncovered through memory analysis.
* The same principle applies to OFTE. Memory Analysis can save your investigator's life, should you be facing a drive with On The Fly Encryption capabilities. To be efficient, transparent and usable, the [encrypted] key should be somewhere in memory.
========================
Table of contents
0x00 - About me
0x01 - About this conference
0x02 - Memory introduction
0x03 - Memory manipulation from an offensive angle
0x04 - Memory manipulation from a defensive angle
0x05 - Conclusion
========================
Post keylogging capacities
* A colleague just used your laptop to access a restricted page, and you regret you didn’t have time to run your favourite keylogger? :-]
========================
Post keylogging capacities
* No a problem, you may be able to browse the Internet browser’s memory to grab his credentials.
========================
Post keylogging capacities
* Besides this joke, have you ever wished you had saved your new email before a touchpad problem occurs and make you loose 30 minutes?
========================
Post keylogging capacities
* But you may not be obliged to restart writing everything from scratch if you browse the process memory shortly.
========================
Stars revelation
* In a pivoting attack, it can be very useful to reveal what’s behind the stars... Don’t forget, Windows remembers lots of passwords in behalf of users.
* Lots of tools do exist, such as Snadboy's Revelation. Unfortunately, most of them do not work against recent OS.
* BulletsPassView is one of the remaining tools which still works under Windows 7. There is even a 64 bits version.
* Anyway, it also does not work under Windows 8.
========================
Stars revelation
========================
Stars revelation
* Pillaging passwords often provide the keys of the kingdom.
========================
Memory Patching
* Memory Patching is the first stone to build a Crack or create a Keygen in the Warez world.
* It basically consists of locating and bypassing binary protections in memory in order to finally implement the trick in the targeted file.
========================
Memory Fuzzing
* Fuzz Testing, aka Fuzzing, consists in providing invalid, unexpected, or random data to the inputs of a monitored program to detect security issues [among others].
* General approach to Fuzzers:
========================
Memory Fuzzing
* Memory-oriented Fuzzing:
========================
Memory Fuzzing
* Here is an example from dbgHelp4j, a memory fuzzing project under development at High-Tech Bridge:
* To learn more, read Xavier ROUSSEL’s paper.
* This short demonstration shows how dbgHelp4j permits to identify rapidly an old buffer overflow in the CWD Command of Easy FTP Server v1.7.0.11.
========================
DLL Injection
* Another well-known memory abuse consists in injecting arbitrary code into the memory space of another process, for example through a CreateRemoteThread like function.
* Such an injection permits the attacker to benefit from the rights of the target process, and often to bypass firewalls.
* This also enable its author to hide himself from most users, as threads are not displayed in Windows Task Manager.
========================
DLL Injection
* Native task manager does not display current threads within a process.
========================
DLL Injection
* Here a DLL based Reverse Trojan is injected into IE memory space.
========================
DLL Injection
* Trojan reaches its C&C Server via HTTP through Internet Explorer [whose behaviour sounds right].
========================
DLL Injection
* From a Pivoting Attack point of view, DLL Injection is widely used during Privilege Escalation.
* There are a lot of tools, such as CacheDump, PWDump6, LSADump2 or PWDumpX.
* Most tools actually inject their nasty code into the Local Security Authority Subsystem (LSASS) to reach hashes.
* The latter is amazingly efficient and permits a user with administrative privileges to retrieve [either locally or remotely] the domain password cache, password hashes and LSA secrets from a Windows system.
========================
Process Memory Dump
* Some processes write sensitive data in memory in clear text format, or without relying on heavy encryption.
* Specific process memory dumps may allow an attacker to grab interesting data.
* Lots of tools do exist. One of the best ones is probably ProcDump, from Mark Russinovich.
* It’s a powerful command-line utility which primary purpose is to monitor applications for CPU spikes in order to generate a crash dump with the purpose of helping the developer to debug.
========================
Process Memory Dump
* It has plenty of amazing features. Anyway, here our goal is simply to dump the memory contents of a process to a file [without stopping the process of course].
* So lots of tools can also do the job, such as PMDump from NTSecurity.
* Sometimes we can find very sensitive information, such as usernames, computer names, IP addresses, and even passwords.
* This is for example the case if you dump the memory of PwSafe. Not all fields are encrypted in memory.
========================
Process Memory Dump
* For sure, password fields are not stored in memory in plaintext, but unfortunately other fields are. And sysadmin’s notes are often very juicy...
* There is hope to collect credentials, map network resources, identify services, ports, sudoers account, and so on.
* Even if the auditor is unlucky and does not grab passwords, he can still create a user list file for further dictionary attacks.
========================
Process Memory Dump
* Process Memory Dump files are quite light.
* During a Pivoting Attack in an Internal Penetration Test, it may worth a try to launch a memory dump against sensitive processes.
========================
Process Memory Dump
* Something as easy as parsing the process memdump for strings may reveal interesting stuff to a pentester.
========================
Process Memory Dump
* Here the Password Safe application permits an attacker to fingerprint the network, and to collect usernames, IP addresses and ports.
* Very useful to carry out further attacks.
========================
Process Memory Dump
* Here the network administration tool mRemote leaks internal path, IP address and TCP port of an SSH enabled server… As well as the username & password of a root account!
========================
Full Memory Dump
* If you have a good bandwidth and you are not so limited by the time, why not dumping the whole memory?
* An offline analysis of the whole memory dump may even reveal more important stuff. Even in the case of FDE, users may have opened sensitive TXT documents for example.
* You may add DumpIt to your toolkit. It is a one-click memory acquisition application for Windows released by MoonSols. It’s a great tool which combines win32dd and win64dd in one executable. It is fast, small, portable, free and ultra easy to use. Just run in to dump the physical memory in the current directory.
========================
Cold Boot Attacks
* It is a common belief that RAM looses its content as soon as the power is down.
* This is wrong, RAM is not immediately erased. It may take up to several minutes in a standard environment, even if the RAM is removed from the computer.
* And it may last much longer if you cool the DRAM chips. With a simple dusty spraying at -50°C, your RAM data can survive more that 10 minutes.
* If you cool the chips at -196°C with liquid nitrogen, data are hold for several hours without any power.
========================
Cold Boot Attacks
* It is then possible to plug the RAM in another system to dump their content to carry out an offline analysis.
* In particular, encryption tools deeply rely on RAM to store their keys. Therefore such attacks are mostly aimed to defeat FDE, such as BitLocker, FileVault, dm-crypt, and TrueCrypt.
* And even if there is some kinds of degradation in the memory contents, some algorithms can intelligently recover the keys.
* To know more, read the Princeton University's paper.
========================
DMA based attacks
* IEEE1394, aka FireWire, is a serial bus interface standard for high-speed communications and isochronous real-time data transfer.
* According to Wikipedia, it “supports DMA and memory-mapped devices, allowing data transfers to happen without loading the host CPU with interrupts and buffer-copy operations”.
* In other words, you can read [and write] in the target’s memory through its FireWire interface!
* This security problem is not new [2004], but still exists today as it relies in IEEE 1394 specifications.
========================
DMA based attacks
* A few years ago, attackers could use WinLockPwn. Today they have Inception tool, from ntropy.
* Inception is a physical memory manipulation and hacking tool which nicely exploits IEEE 1394 SBP-2 DMA [Serial Bus Protocol 2].
* The tool can unlock and escalate privileges to Administrator / Root on almost any powered on machine you have physical access to.
* The tool works over any interface that expands and can master the PCIe bus, such as FireWire, Thunderbolt, ExpressCard and PCMCIA (PC-Card).
========================
DMA based attacks
* It is initially made to attack computers that utilize FDE, such as BitLocker, FileVault, TrueCrypt or Pointsec.
* You just need a Linux / Mac OS X system and a target which provides a FireWire / Thunderbolt interface, or an ExpressCard / PCMCIA expansion port.
* There are for sure some limitations, such as the 4 GiB RAM bugs or the restrictions on OS X Lion targets [which disables DMA when the user is logged out as well as when the screen is locked if FileVault is enabled], but most often FireWire means P0wned.
========================
DMA based attacks
* Just a few lines to install on a your BackTrack:
* The short following demo of Inception exploits the FireWire interface of an up-to-date Windows 7 system to patch the msv1_0.dll file and unlock the running session.
========================
DMA based attacks
* This kind of DMA based attacks also permit to attack mounted encrypted volumes, such as a TrueCrypt archive.
* You can for example boot your attacking system with PassWare FireWire Memory Imager from Passware Kit Forensics, and search for AES keys in the target memory through FireWire.
* You can basically defeat BitLocker, TrueCrypt, FileVault2 & PGP encryption volumes.
* To know more: http://www.breaknenter.org/projects/inception/ http://support.microsoft.com/kb/2516445
========================
DMA based attacks
* The following slides illustrate an attack on a TrueCrypt volume created on an 8 Gb memory stick.
* First step was to backup the encrypted drive.
========================
DMA based attacks
* Then let’s begin the attack on a mounted volume when the user went.
========================
DMA based attacks
* Dump the physical memory of the target system through our favourite FireWire interface.
========================
DMA based attacks
* And attack the key material in memory…
========================
DMA based attacks
* The attack only last a couple of minutes.
========================
DMA based attacks
* And you should get an unencrypted raw volume.
========================
DMA based attacks
* You just have to fill a new memory stick with this raw image…
========================
DMA based attacks
* And that’s it ! Just plug your new device…
========================
DMA based attacks
* And enjoy your TrueCrypt less volume.
========================
Table of contents
0x00 - About me
0x01 - About this conference
0x02 - Memory introduction
0x03 - Memory manipulation from an offensive angle
0x04 - Memory manipulation from a defensive angle
0x05 - Conclusion
========================
Circumventing FDE
* Traditional Forensics approach faces problem with encryption, especially with FDE.
* If the investigator “pulls the plug” and creates a bit-for-bit image of the physical hard drive, he most probably destroys the best chance of recovering the plaintext data, as well as all common memory artefacts.
* With FDE, it is usually far better to make a bit-for-bit image of the logical device while the system is still running, even if underlines disk activities are generally not welcome… And even if we rely on an untrusted OS to present what is actually on the disk, therefore prone to anti-forensic techniques.
========================
Circumventing FDE
* If we begin by capturing the volatile memory, then we can potentially extract the cryptographic keys from the memory image to decrypt and analyse the disk image.
* The only one challenge usually consists in uniquely identifying key materials among gigabytes of other data.
* It is usually achieved with a mixed of entropy analysis [limited because of the short length of symmetrical keys and the randomness of other data, such as compressed files] and brute force attack [Known-Plaintext Attack, where the attacker has samples of both the plaintext and the ciphertext].
* To learn more: “RAM is Key - Extracting Disk Encryption Keys From Volatile Memory", by B. Kaplan and M. Geiger).
========================
Code Analysis via API Hooking
* A quick way to have an idea of what a binary does is to analyse its API calls.
* You can do it easily with APISpy32 for example, from Pietrek.
* You just need to populate a configuration file with the name of all the API [e.g. per a strings] you want to enable Hooking, and you get a nice malcode monitoring tool.
* Next slide shows common API use in malware.
========================
Code Analysis via API Hooking
Common API
Malware
URLDownloadToFile, FtpGetFile, FtpOpenFile
Dropper
CreateRemoteThread, NtWriteVirtualMemory,
LoadLibrary and similar (LoadLibraryA, LoadLibraryExA, LoadLibraryExW, etc.)
Injection
BeginPaint (to disable local screen changes when a VNC session is activated)
Zeus
Accept, Bind
Backdoor
Connect, CreateNamedPipe, ConnectNamedPipe, DisconnectNamedPipe
Dropper and Reverse Trojan
IsDebuggerPresent, CheckRemoteDebuggerPresent
Anti debugger
========================
Code Analysis via API Hooking
Common API
Malware
CryptCreateHash, CryptEncrypt, CryptGetHashParam
Encryption
DeviceIoControl, NtLoadDriver, NtOpenProcess
Rootkit
HttpOpenRequest, HttpSendRequest, InternetConnect
Exfiltration
ModifyExcuteProtectionSupport, EnableExecuteProtectionSupport, NtExecuteAddFileOptOutList
DEP
SetSfcFileException
Windows File Protection alteration
========================
Memory Forensics
* It is probably the best way to identify the most hidden evil code, such a Rootkits.
* And don't forget that some malware can live in memory without ever touching the hard disk. This is for example the case with MSF Meterpreter, which is injected into existing process memory.
* Stealth malware also work in that manner [mostly in targeted hacking against big companies].
* Hard disks are amazingly big today. Simply creating a raw image can take very long time... Sometimes several days. Analysing memory is much faster.
========================
Memory Forensics
* But there are also some minor drawbacks… Indeed, the memory image will only give us information on what was running at a particular time. We will not see the most visible piece of malcode if it was not running when we proceed with the imaging [unless some tracks remain in undeleted structures].
* And fore sure, to make an image of the memory we first need to run once a specific utility... Which will be loaded in the targeted memory! As a consequence, it is always possible to alter evidence [even if chances are really low with a light utility].
* Anyway, it definitely worth a try as a fast analysis can help you spot the evidence very quickly. :-]
========================
Memory Forensics
* Any kind of physical memory abstract could be usable, such as a Memory Dump, a Crash Dump, an hibernation file or a VMEM file for virtual machines.
========================
Memory Forensics
* Memory Forensics is a very huge project, as memory mappings differ from OS, SP and patch levels, and as vendors usually do not really document their internal memory structures.
* Nevertheless, it is mature and efficient since a few years. Nowadays, we are not limited anymore to ASCI and Unicode grep, and we can now rely on powerful tools which parse well known memory structures.
========================
Memory Forensics
* For sure, we are still facing challenging problems, and tools may be limited by Paging and Swapping which can prevent investigators from analysing the whole virtual address space of a specific process [unless they also dig into the pagefile.sys for example]…
* But it is still really effective for Malware Analysis!
* Besite commercial tools, free solutions do exist, such as Radare and Volatility. The later simply became impressing.
* Since last year, Volatility also support MAC systems.
========================
Memory Forensics
* Shall you need to carry out a Memory Forensics on a Windows, Linux, Mac or Android system, I strongly advise you to have a look on Volatility.
* It is basically a Python based tool for extracting digital artefacts from volatile memory [RAM] samples which offer an amazing visibility in the runtime state of the system.
* You can easily identify running processes and their DLL, Virtual Address Descriptor [VAD], System call tables [IDT, GDT, SSDT], environment variables, network connections, open handles to kernel and executive objects, and so on.
========================
Memory Forensics
* It can even be used to dump LM and NTLM hashes, as well as LSA secrets…
========================
Memory Forensics
* Well, for French targets there is a little bug [because of accents]... You will have to adapt a little bit the code:
========================
Memory Forensics
* But beside this, it is really efficient to track malcode. Let’s dig into a real example…
========================
Memory Forensics
* Heavy malware may be digitally signed by a trusted CA.
========================
Memory Forensics
* And may be really appear benign to your users.
========================
Memory Forensics
* Here it was an obfuscated .Net based Dropper.
========================
Memory Forensics
* Even if you manually find the embedded payload, nearly everything is packed to disturb Reverse Engineers.
========================
Memory Forensics
* The only one unencrypted payload was a kind of anti-restoring feature, which basically hooks specific API to prevent system administrators to remove the malware [e.g. by killing his task manager].
* And then? What’s next? We could spend lots of time in a Reverse Engineering phase, or analyse its behaviour in a sandbox [if the code doesn’t detect it]…
* …And we can simply see what’s happen in memory.
========================
Memory Forensics
* Just infect voluntarily your VM or your lab workstation.
* And use one of the good existing tools to dump the whole memory:
* Memory from Mandiant
* FTK Imager from AccessData
* FastDump from HB Gary
* DumpIt and Win32dd / Win64dd from Moonsols
* And of course your favourite FireWire interface
* Before using Volatility to dissect this memory dump.
========================
Memory Forensics
* Let’s begin to get basic information on our dump file.
========================
Memory Forensics
* The PSLIST command quickly show processes.
========================
Memory Forensics
* You can arrange them by tree view.
========================
Memory Forensics
* This process list can be quickly obtained by parsing a Kernel double chained list. Nevertheless, this list can be altered by malware, such as Rootkits, which therefore hide themselves from common system tools.
* A deep research can then be achieved, which consist in parsing the whole memory dump to locate EPROCESS structures. These Kernel structures do exist for each process, no matter what the double chained list [known as Process Control Block] is.
* A process listed in a PSCAN and not in a PSLIST often indicate a threat [mostly permitted via API Hooking].
========================
Memory Forensics
* The PSCAN is longer but may reveal hidden code.
========================
Memory Forensics
* Similarly, you can find processes which attempt to hide themselves on various process listings through the PSXVIEW command:
========================
Memory Forensics
* Several Volatility commands works in this way and offer a SCAN variant to try to recognize specific structures in memory, thus revealing hidden sockets and connections for example.
* For sure you may have [often quickly identified] false positives, as some process may gave been legitimately closed for example, thus letting some orphan EPROCESS data structures in RAM.
* Nevertheless, some process may still be really running, and therefore instantaneously reveal a serious security issue.
========================
Memory Forensics
* Established and recently closed connexions are also quickly revealed.
========================
Memory Forensics
* And you can also easily explore the registry, which is widely used by malcode writers for various purpose [e.g. to permit their code to survive reboot].
========================
Memory Forensics
* As well querying loaded drivers [often used by Rootkits].
========================
Memory Forensics
* You can even parse loaded libraries to detect API Hooking, also widely used by Rootkits. Here a trampoline has been placed in the wbemcomm DLL [to hook certain WMI queries].
========================
Memory Forensics
* You can extract suspicious file [through PID or offset] from the memory dump to carry out further investigation.
========================
Memory Forensics
* And quickly identify a Key Logger.
========================
Memory Forensics
* In fact, you can enumerate all opened files and even loaded DLL within a specific process… And drop them back on disk for investigation.
========================
Memory Forensics
* The dumped process may not be runable, but would still offer you a quite easy to understand code [at least you don't have anymore to unpack it]. For example: strings dumpedfile | egrep -i 'http|ftp|irc|\.exe'
* Even more powerful, you can rely on the MALFIND command to perform advanced search using Regex, Unicode or ANSI strings...
* And most importantly, it permits to quickly find hidden or injected code through the VAD tree inspection [very useful in case of DLL which may have been unlinked from the LDR lists by the malcode loader in order to avoid its detection].
========================
Memory Forensics
* Here the MALFIND command reveals that an arbitrary code was injected into the CRSS.exe system process.
========================
Memory Forensics
* We can quick parse MALFIND results to bring out running processes which were infected by such code injection.
========================
Memory Forensics
* Even powerful rootkits quickly draw your attention.
========================
Memory Forensics
* We can also use the Yara malware identification feature to directly scan for patterns inside a PID or within a specific memory segment. Here we see that an injected code inside the SVCHOST process established a connection to dexter.servequake.com:4444 via HTTP and download the 1234567890.functions resource.
========================
Memory Forensics
* For sure, the RAT payload is encrypted, but in a few minutes you identified the threat and dig quite deeply into the real problem.
========================
Memory Forensics
* You can now extract the guilty binary code along with the related memory segments and begin a classical malware analysis.
========================
Memory Forensics
* And if you like high-level view for your incident report, why not extend Volatility with Graphviz to make something more visual?
========================
Memory Forensics
* That’s it. I hope I have piqued your interest with one of the most important Forensics innovations of those last few years. The whole demo is attached here.
* To learn more: SANS Forensics 610 Training Course [GREM] https://www.volatilesystems.com/default/volatility http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx http://www.ualberta.ca/CNS/RESEARCH/LinuxClusters/mem.html http://www.tenouk.com/visualcplusmfc/visualcplusmfc20.html
========================
Table of contents
0x00 - About me
0x01 - About this conference
0x02 - Memory introduction
0x03 - Memory manipulation from an offensive angle
0x04 - Memory manipulation from a defensive angle
0x05 - Conclusion
========================
Conclusion
* I hope I have achieved my goal of opening the doors to a fascinating world which could easily allow security analysts to save lots of time during their recurrent duties…
* …And that you will see your own system [and the ones you asses] from a different angle.
* …And that you will now have the reflex of dumping the whole memory in case of incident.
* …And that you will reconsider security when the physical aspect in concerned. :-]

Malware samples are available for download by any responsible whitehat researcher. By downloading the samples, anyone waives all rights to claim punitive, incidental and consequential damages resulting from mishandling or self-infection.