Search code examples
linuxcommand-linegdbenvironment-variablescommand-substitution

set environment variable in GDB from output of command


I am trying to exploit a buffer overflow in a challenge, the buffer gets it's value from an environment variable. In GDB I know that you can set environment variables using the command:

set environment username = test

However I need to pass the username variable special characters, so I need to do something like:

set environment username= $(echo -e '\xff\x4c......')

But that command doesn't get executed and the username variable contains literally what I wrote down, does anybody know a trick to pass special characters to an environment variable?


Solution

  • Well, if you really need to do it from GDB, here is one example:

    hello.c

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(int argc, char** argv) {
        printf("argv[1]=%s\n", argv[1]);
        printf("VAR=%s\n", getenv("VAR"));
        return 0;
    }
    

    Example:

    $ gcc -g -o hello hello.c
    $ gdb ./hello
    ...
    (gdb) set exec-wrapper bash -c 'exec env VAR="`echo myEnv`" "$@"' --
    (gdb) r myArg
    ...
    argv[1]=myArg
    VAR=myEnv
    

    Change VAR and echo myEnv to a variable and command you need.


    But note that setting VAR from shell before starting GDB also works:

    $ VAR=`echo Hey there` gdb ./hello
    ...
    (gdb) r myArg
    ...
    argv[1]=myArg
    VAR=Hey there