Skip to content
Advertisement

assembly, how to use mprotect?

I am trying to make self modifying code in Linux. I thought it would works but didn’t.

section .data
section .text
global _start

_start:
    mov eax, 125 ;mprotect syscall number
    mov ebx, _start ; *addr
    mov ecx, 0x10000 ;page interval.
    mov edx, 7 ; rwx permission
    int 0x80
    jmp modify
target:
    mov eax, edx        
halt:
    mov ebx, 1
    mov eax, 1
    int 0x80
modify:
    mov ebx, [new]      
    mov [target], ebx   
    jmp target          
new:
    mov ebx, 0          

I used nasm on ubuntu 18.04.

INT 0x80 return value is -22 0xffffffea

I don’t know what is wrong.

Advertisement

Answer

Run your program under strace, like strace ./a.out to decode system call args and return values.

Probably your base address isn’t page-aligned, or the range includes some unmapped pages. You could round down to a page boundary with and ebx, -4096, or you could align _start by putting align 4096 before it.

Or instead of calling mprotect yourself, you could link your program with ld --omagic to make the text segment read+write+exec.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement