Search code examples
securitymemoryprogramming-languages

Can a program assign the memory directly?


Is there any really low level programming language that can get access the memory variable directly? For example, if I have a program have a variable i. Can anyone access the memory to change my program variable i to another value?


Solution

  • As an example of how to change the variable in a program from “the outside”, consider the use of a debugger. Example program:

    $ cat print_i.c
    #include <stdio.h>
    #include <unistd.h>
    
    int main (void) {
        int i = 42;
        for (;;) { (void) printf("i = %d\n", i); (void) sleep(3); }
        return 0;
    }
    $ gcc -g -o print_i print_i.c
    $ ./print_i
    i = 42
    i = 42
    i = 42
    …
    

    (The program prints the value of i every 3 seconds.)

    In another terminal, find the process id of the running program and attach the gdb debugger to it:

    
    $ ps | grep print_i
     1779  p1  S+     0:00.01 ./print_i
    $ gdb print_i 1779
    …
    (gdb) bt
    #0  0x90040df8 in mach_wait_until ()
    #1  0x90040bc4 in nanosleep ()
    #2  0x900409f0 in sleep ()
    #3  0x00002b8c in main () at print_i.c:6
    (gdb) up 3
    #3  0x00002b8c in main () at print_i.c:6
    6           for (;;) { (void) printf("i = %d\n", i); (void) sleep(3); }
    (gdb) set variable i = 666
    (gdb) continue
    

    Now the output of the program changes:

    …
    i = 42
    i = 42
    i = 666
    

    So, yes, it's possible to change the variable of a program from the “outside” if you have access to its memory. There are plenty of caveats here, e.g. one needs to locate where and how the variable is stored. Here it was easy because I compiled the program with debugging symbols. For an arbitrary program in an arbitrary language it's much more difficult, but still theoretically possible. Of course, if I weren't the owner of the running process, then a well-behaved operating system would not let me access its memory (without “hacking”), but that's a whole another question.