Looking at Simple Encryptor reversing challenge on HackTheBox.

The story: flag storage server was hit by ransomware. We get the encrypted file and the compiled binary that encrypted it.

The files

After unzipping there are two files, encrypt and flag.enc.

$ file encrypt
encrypt: ELF 64-bit LSB pie executable, x86-64, ..., not stripped
$ ls -l flag.enc
-rw-r--r-- 1 htb htb 32 19. Jul 2022  flag.enc

encrypt Is not stripped, so function names like main are still in it. flag.enc is 32 bytes:

$ xxd -g 1 flag.enc
00000000: 5a 35 b1 62 00 f5 3e 12 c0 bd 8d 16 f0 fd 75 99  Z5.b..>.......u.
00000010: fa ef 39 9a 4b 96 21 a1 43 16 23 71 65 fb 27 4b  ..9.K.!.C.#qe.'K

At this point I didn’t know what these bytes are. That comes from the code.

Reading encrypt in Ghidra

I opened main in Ghidra. The variables have generic names like local_20 and local_38, and the loop was full of lines like this:

*(byte *)((long)local_20 + local_38) = *(byte *)((long)local_20 + local_38) ^ (byte)iVar1;

I had no idea what that does. It turned out to be buf[i] = buf[i] ^ rnd1: take the start address of the buffer, add i, and work on the byte at that address. Ghidra writes it this way because it doesn’t know the buffer is a byte array.

I renamed the variables and changed the type of the buffer to byte *. After that, main looks more readable :

flag_fp = fopen("flag","rb");
fseek(flag_fp,0,2);
size = ftell(flag_fp);
fseek(flag_fp,0,0);
buf = malloc(size);
fread(buf,size,1,flag_fp);
fclose(flag_fp);

now = time((time_t *)0x0);
seed = (uint)now;
srand(seed);

for (i = 0; i < (long)size; i = i + 1) {
  rnd1 = rand();
  buf[i] = buf[i] ^ (byte)rnd1;
  rnd2 = rand();
  rnd2 = rnd2 & 7;
  buf[i] = buf[i] << (sbyte)rnd2 | buf[i] >> 8 - (sbyte)rnd2;
}

enc_fp = fopen("flag.enc","wb");
fwrite(&seed,1,4,enc_fp);
fwrite(buf,1,size,enc_fp);
fclose(enc_fp);

Things matter here:

  1. The seed is the current time.
  2. Every byte is XORed with the lowest byte of one rand() value and then rotated left by a second rand() value. & 7 keeps the lowest 3 bits, so the rotation is between 0 and 7.
  3. fwrite(&seed,1,4,enc_fp) writes the seed into the file before the encrypted data. That’s 1 x 4 = 4 bytes.

Point 3 explains the file size:

flag.enc (32 bytes) = seed (4 bytes) + encrypted flag (28 bytes)

So the flag has 28 characters.

Finding the seed

The seed is the first 4 bytes of flag.enc:

$ xxd -g 1 -l 4 flag.enc
00000000: 5a 35 b1 62

x86 is little-endian, so the lowest byte is stored first. To get the number, you read the 4 bytes backwards:

in the file:   5a 35 b1 62
as a number:   0x62b1355a
$ printf "%d\n" 0x62b1355a
1655780698
$ date -u -d @1655780698
Di 21. Jun 03:04:58 UTC 2022

So the seed is 1655780698, a Unix timestamp. The flag was encrypted on 21 June 2022 at 03:04:58 UTC.

rand() with the same seed

rand() isn’t really random. After srand(seed) it always gives the same sequence. I checked that with a small program, using the seed from above:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    srand(1655780698);
    for (int i = 0; i < 4; i++)
        printf("%d\n", rand());
    return 0;
}

I ran it several times and always got:

2014390344    1st rand()
1469870660    2nd rand()
1982650619    3rd rand()
1625766133    4th rand()

These are exactly the numbers the encryptor got. The loop calls rand() twice for every byte, so they belong to the bytes like this:

byte 0:  rnd1 = 1st (2014390344)   rnd2 = 2nd (1469870660)
byte 1:  rnd1 = 3rd (1982650619)   rnd2 = 4th (1625766133)

Decrypting the first two bytes by hand

Both steps have to be undone in reverse order. The rotation was done last, so it is undone first:

encrypt:  XOR with rnd1,  then rotate left by rnd2
decrypt:  rotate right by rnd2,  then XOR with rnd1

If you do the XOR first, you get a wrong character.

Only part of each random number is used. From rnd1 only the lowest byte, which is the last two hex digits. From rnd2 only the lowest 3 bits (& 7).

Byte 0

The first encrypted byte comes right after the seed. It’s the 5th byte in the file: 00.

$ printf '%x\n' 2014390344      # 1st rand()
78112848                         # key = last byte = 0x48
$ echo $(( 1469870660 & 7 ))     # 2nd rand()
4                                # rotate by 4

0x00 is all zeros, so rotating it changes nothing. 0x00 ^ 0x48 = 0x48, which is H.

Byte 1

The 6th byte in the file: f5.

$ printf '%x\n' 1982650619      # 3rd rand()
762cd8fb                         # key = last byte = 0xfb
$ echo $(( 1625766133 & 7 ))     # 4th rand()
5                                # rotate by 5

For this one I had to write the bytes in binary. Each hex digit is 4 bits, with the weights 8 4 2 1. So f = 1111, 5 = 0101, and b = 1011.

0xf5                1111 0101
rotate right by 5   1010 1111    the last 5 bits (10101) move to the front
XOR with 0xfb     ^ 1111 1011
result              0101 0100    = 0x54 = 'T'

XOR gives 1 only where the two bits are different.

H and T, so it looks like the start of HTB{. At this point I knew the idea works on the real file.

The solver in C

The rest is the same thing for all 28 bytes. Putting a program going over 3 steps and checked each one against something I already knew:

  1. Read only the seed and print it. It printed 1655780698, same as by hand.
  2. Read the 28 encrypted bytes and print them as hex. Same as the xxd output after the seed.
  3. Add the decrypt loop.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

// rotate a byte right by k bits
static uint8_t ror8(uint8_t v, int k)
{
    return (uint8_t)((v >> k) | (v << (8 - k)));
}

int main(void)
{
    FILE *f = fopen("flag.enc", "rb");
    if (f == NULL) {
        perror("fopen");
        return 1;
    }

    // file size: jump to the end, get the position, jump back
    fseek(f, 0, SEEK_END);
    long size = ftell(f);
    fseek(f, 0, SEEK_SET);

    // first 4 bytes: the seed
    uint32_t seed;
    if (fread(&seed, 1, 4, f) != 4) {
        fprintf(stderr, "could not read seed\n");
        fclose(f);
        return 1;
    }

    // the rest: encrypted flag
    long len = size - 4;
    uint8_t *buf = malloc(len);
    if (buf == NULL) {
        perror("malloc");
        fclose(f);
        return 1;
    }
    if (fread(buf, 1, len, f) != (size_t)len) {
        fprintf(stderr, "could not read payload\n");
        free(buf);
        fclose(f);
        return 1;
    }
    fclose(f);

    // same seed, same rand() order as the encryptor
    srand(seed);
    for (long i = 0; i < len; i++) {
        int rnd1 = rand();
        int rnd2 = rand() & 7;
        buf[i] = ror8(buf[i], rnd2);        // undo the rotation
        buf[i] = buf[i] ^ (uint8_t)rnd1;    // undo the XOR
    }

    fwrite(buf, 1, len, stdout);
    printf("\n");

    free(buf);
    return 0;
}
$ gcc -Wall -Wextra solve.c -o solve
$ ./solve
HTB{REDACTED}

rand() is not the same in every C library. This only works with glibc on Linux, like the machine the encryptor ran on.

The same logic in objdump

Afterwards I tried to find the loop without Ghidra:

objdump -d -M intel --no-show-raw-insn --disassemble=main encrypt

Ghidra shows addresses with a base of 0x100000 and objdump doesn’t. So 00101350 in Ghidra is 1350 in objdump. These are the important lines of the loop:

1350:  call   rand@plt      # rnd1 = rand()
136c:  xor    ecx,eax       # buf[i] ^ rnd1
137d:  call   rand@plt      # rnd2 = rand()
1382:  and    eax,0x7       # rnd2 & 7
13b4:  rol    sil,cl        # rotate left

The compiler used a real rol instruction for the rotation. Ghidra turns it back into the << ... | >> ... expression.

objdump has no variable names, only stack slots like [rbp-0x30]. You have to work out from the code what each one is. The loop counter part:

1346:  mov  QWORD PTR [rbp-0x30],0x0     # set to 0
13bb:  add  QWORD PTR [rbp-0x30],0x1     # +1 at the end of each round
13c4:  cmp  rax,QWORD PTR [rbp-0x20]     # compare
13c8:  jl   1350                          # if less, back to the loop start

[rbp-0x30] starts at 0 and goes up by 1, so it’s i.

i is compared against [rbp-0x20] in the loop condition i < size, so that one is size. It’s 8 bytes (QWORD), which fits a size.

[rbp-0x18] is the buffer: i gets added to it and then one byte is read from that address. A Ghidra name local_XX is usually at [rbp-(XX-8)], so [rbp-0x18] is local_20, which I had renamed to buf.

The seed slot comes from the fwrite call. On x86-64 Linux the first function arguments go into rdi, rsi, rdx and rcx:

13e5:  lea  rax,[rbp-0x38]     # address of [rbp-0x38]
13e9:  mov  rcx,rdx            # 4th argument: the file
13ec:  mov  edx,0x4            # 3rd argument: 4
13f1:  mov  esi,0x1            # 2nd argument: 1
13f6:  mov  rdi,rax            # 1st argument: the address
13f9:  call fwrite@plt

This is fwrite(&seed, 1, 4, enc_fp), so [rbp-0x38] is the seed.