AKJ88
AKJ88

Reputation: 733

Still getting segmentation fault after calling mprotect in self-modifying assembly code

I'm trying to learn some stack overflow techniques and use shellcode in them. I was able to successfully use some basic shellcodes. Then I started working on using exeve in assembly and invoke ls -l with that, again successful. Now I am trying to use relative addressing and get rid of null values in my code. Because of that I tried a simple self-modifying code. I know code segment is read-only so I tried calling mprotect to make it writable. My code still doesn't work and I get segmentation fault at movb %al, 0x7(%esi). I really appreciate it if someone could give me some insight into the thing that is wrong in my code.

.text
.globl _start

_start:
  jmp StartPoint

  execvecall:
  popl %esi    # the address of string

  #calling mprotect to make the memory writable
  movl $0x7d, %eax
  movl %esi, %ebx
  movl $0x20, %ecx
  movl $7, %edx
  int $0x80

  xorl %eax, %eax

  movb %al, 0x7(%esi)  #putting zero for at the end of /bin/ls
  movb %al, 0xa(%esi)  #putting another zero at the end of -l

  #this part forms an array ending with for the second parameter of execve
  movl %esi, 0xb(%esi)
  movl %esi, %ebx
  addl $8, %ebx
  movl %ebx, 0xf(%esi)
  movl %eax, 0x13(%esi)

  movl %esi, %ebx
  leal 0xb(%esi), %ecx
  leal 0x13(%esi), %edx

  movb $11, %al
  int $0x80

StartPoint:
  call execvecall
SomeVarHere:
  .ascii "/bin/ls0-l0111122223333"

Upvotes: 2

Views: 864

Answers (1)

cadaniluk
cadaniluk

Reputation: 15229

man mprotect says:

The implementation may require that addr be a multiple of the page size as returned by sysconf().

This is apparently the case on your machine. Assuming you have 4 KiB pages (as on x86, no PSE), you can round the address down by executing

and $0xfffff000, %ebx

after

movl %esi, %ebx

when preparing to call mprotect.

Note that calling mprotect changes the protection for the whole page.

Upvotes: 5

Related Questions