John
John

Reputation: 13

Segmentation fault in mov instruction

rdi contains the address of a piece of code.I'm trying to implement XOR encoding to that code.When I run that code,the mov instruction causes segmentation fault.Can anyone help?

mov byte al,[rdi];   No errors
xor al,0x7f
mov byte [rdi],al;   Causes segmeation fault

Complete Code:

section .text
    global _start
    _start:
        call encrypt
    code:
        xor rax,rax
        xor rdx,rdx
        xor rcx,rcx
        xor rdx,rdx
        mov rdi,0x636e2f6e69622f2f
        shr rdi,0x8
        push rdi
        mov rdi,rsp
        mov rsi,0x6c2dffffffffffff
        shr rsi,0x30
        push rsi
        mov rsi,rsp
        mov rbx,0x702dffffffffffff
        shr rbx,0x30
        push rbx
        mov rbx,rsp
        mov rcx,0x30393039ffffffff
        shr rcx,0x20
        push rcx
        mov rcx,rsp
        mov rdx,0x652dffffffffffff
        shr rdx,0x20
        push rdx
        mov rdx,rsp
        xor r8,r8
        mov r8,0x68732f6e69622f2f
        shr r8,0x8
        push r8
        mov r8,rsp
        push r8
        push rdx
        push rcx
        push rbx
        push rsi
        push rdi
        mov rsi,rsp
        mov al,59
        syscall
    encrypt:
        pop rdi
        mov cl,0x8a
        mov bl,0
    loo:
        dec cl
        mov byte al,[rdi]
        xor al,0x7f
        mov byte [rdi],al  ;segfault occurs here
        inc rdi
        jne loo
        jmp code

Upvotes: 0

Views: 2324

Answers (1)

paxdiablo
paxdiablo

Reputation: 881403

rdi contains the address of a piece of code

Many systems provide protection from malicious code by actively preventing writes to code areas(a). For example, the code selector may point to a memory block which is marked read-only (unless you're running the code trying to modify it in some form of privileged mode).

You're almost certainly running into this protection mechanism in this case. How you solve it (assuming it's allowed) will depend on more details on your environment than you have currently provided (operation system, for example).

For example, under Linux, you can use mprotect to change protections for some address ranges in your virtual memory space.


(a) Some also stop you from executing data as if it was code which means that, even if you move the code to somewhere you can write, you may not be able to execute it.

Upvotes: 3

Related Questions