# PicoCTF 2k13 - Core Decryption


$ mkdir decrypt
$ d decrypt
$ cp /problems/core_decrypt.tar .
$ tar xvf core_decrypt.tar
$ cat cryptor.c
#include <stdio.h>
#include <stdlib.h>

void swap(unsigned char* sbox, int i, int j) {
  unsigned char tmp;
  tmp = sbox[i];
  sbox[i] = sbox[j];
  sbox[j] = tmp;
}

void init_rc4(unsigned char* sbox, char* key, int keylen) {
  int i;
  for (i = 0; i < 256; i++) {
    sbox[i] = i;
  }
  unsigned char j,tmp;
  for (i = 0; i < 256; i++) {
    j = j + sbox[i] + key[i % keylen];
    swap(sbox,i,j);
  }
}

unsigned char next_prg(unsigned char* sbox, int *i, int *j) {
  i[0] = (i[0] + 1)&0xff;
  j[0] = (j[0] + sbox[i[0]])&0xff;
  swap(sbox,i[0],j[0]);
  return sbox[(sbox[i[0]] + sbox[j[0]])&0xff];
}

void crypt(FILE *inf, FILE *keyf, FILE *outf) {
  int uhoh;
  unsigned char sbox[256];
  int i,j;
  i = j = 0;
  char key[16];

  fread(key,1,16,keyf);
  init_rc4(sbox,key,16);

  unsigned char tmp;
  while (fread(&tmp,1,1,inf) > 0) {
    tmp ^= next_prg(sbox,&i,&j);
    fwrite(&tmp,1,1,outf);
  }
}

int usage(char* this) {
  printf("Usage: %s [input file] [outfile] [key file]\n",this);
  return -1;
}

int main(int argc, char** argv) {
  if (argc != 4) {
    return usage(argv[0]);
  }
  FILE *inf = fopen(argv[1],"r");
  FILE *outf = fopen(argv[2],"w");
  FILE *keyf = fopen(argv[3],"r");

  if (!(inf && outf && keyf)) {
    printf("Sorry, could not open all files for reading/writing\n");
    return -1;
  }
  crypt(inf,keyf,outf);
  fclose(inf);
  fclose(outf);
  fclose(keyf);
  return 0;
}
$ file ENCRYPTED
ENCRYPTED: data
$ file core.26474
core.26474: ELF 32-bit LSB core file Intel 80386, version 1 (SYSV), SVR4-style, from '/home/tyler/ppp/picoctf2013/problems/forensics/decryption_core/a.out keyfile.txt'
$ gdb cryptor core.26474
(gdb) info stack
#0  0x08048564 in swap (sbox=0xffffd17c "", i=-11652, j=16) at cryptor.c:7
#1  0x08048719 in crypt (inf=0x0, keyf=0xffffd17c, outf=0xf7ffda5c) at cryptor.c:42
#2  0x08048894 in main (argc=4, argv=0xffffd374) at cryptor.c:67
(gdb) frame 1
#1  0x08048719 in crypt (inf=0x0, keyf=0xffffd17c, outf=0xf7ffda5c) at cryptor.c:42
42     tmp ^= next_prg(sbox,&i,&j);
(gdb) info locals
(gdb) print /x &key
$1 = 0xffffd27c
(gdb) print /x key
$2 = {0xc5, 0xe4, 0x4c, 0x4, 0xbb, 0x2f, 0x5c, 0x10, 0xba, 0x75, 0x1b, 0xc3, 0x97, 0x4c, 0xdc, 0xdc}
$ python -c 'print "\xc5\xe4\x4c\x04\xbb\x2f\x5c\x10\xba\x75\x1b\xc3\x97\x4c\xdc\xdc"' > key
$ ./cryptor ENCRYPTED solution key
$ cat solution 
Well, assuming you're able to actually keep the secret keyfile safe, this is a legitimate way to encrypt files!
Your key is: astronomy_ceremony_times

No comments: