Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why data and stack segments are executable?

Tags:

I have just noticed that my simple program has its data and stack segments executable. I saw it in /proc/[pid]/maps, and simple code confirmed it.

For example:

; prog.asm section .data     code:   db 0xCC    ;int3  section .text global _start _start:     jmp    code      mov    rax, 60    ; sys_exit     mov    rdi, 0     syscall 

then

nasm -f elf64 prog.asm ld -o prog prog.o ./prog 

causes prog to execute int3 instruction.

Programs written in C and built with gcc have their data, stack and heap non-executable, so why those written in assembly behave in a different manner?

like image 635
witosx Avatar asked Oct 22 '11 23:10

witosx


People also ask

Why is the stack executable?

Executable stack is necessary in some cases such as GCC trampoline for nested functions. A trampoline is a small piece of code that is created at run time when the address of a nested function is taken. It normally resides on the stack, in the stack frame of the containing function.

Is the data segment executable?

The data segment is an area of memory that can be both read and written by the program; that is, it contains global variables. Similarly to the text segment, a portion of the executable file is copied to the data segment when a program is about to be executed. This portion is called the initialized data.

Is the stack executable?

To prevent stack-overflow exploits, the stack of a binary or shared library must be marked as not executable.

Which segment contains executable code of program?

The code segment, also known as text segment, contains executable code and is generally read-only and fixed size.


1 Answers

On modern Linux systems, the linker will mark stack/data non-executable IFF all objects that participate in the link have a special "marker" section .note.GNU-stack.

If you compile e.g. int foo() { return 1; } into assembly (with gcc -S foo.c), you'll see this:

    .section    .note.GNU-stack,"",@progbits 

For nasm, the syntax is shown in section 8.9.2 of the manual; you want something like this:

 section .note.GNU-stack noalloc noexec nowrite progbits 

Note

This has to be done for every .o file that goes into the executable. If any object file needs executable stack or data, then it's set for the entire segment.

like image 144
Employed Russian Avatar answered Sep 30 '22 20:09

Employed Russian