在 Python 中启用 seccomp 后如何干净地退出?

tam*_*ech 4 python seccomp

我在一个项目中通过 python-prctl 启用了 seccomp。我不太清楚如何干净地退出 - 结果总是被杀死。

我看到了一些使用 ctypes 或 ffi 尝试引用 libc 的示例,但是如果我希望它们带有 WIFEXITED,它们似乎也有同样的问题。

下面的示例代码。结果总是“我们被杀了”。

def main():
  pid = os.fork()
  if not pid:
    prctl.set_seccomp(True)
    os.write(0, 'Hi\n')

#    os._exit(0)
#    _exit(0)
#    sys._exit(0)
#    return
#    ?!@#(*!  What do?

  endpid, status = os.waitpid(pid, 0)
  print 'Child forked as %d and returned with %d' % (endpid, status)
  if not os.WIFEXITED(status):
    print 'Exitted abnormally'
    if os.WIFSIGNALED:
      if os.WTERMSIG(status) == signal.SIGKILL:
        print 'We were killed to death'
  else:
    print 'Returned with %d' % (os.WEXITSTATUS(status))
Run Code Online (Sandbox Code Playgroud)

快速更新,因为我忘记了 libc 的东西:

使用其中任何一个定义上面的 _exit() 仍然会导致终止。

# FFI Method
ffi = cffi.FFI()
# Use _exit, which avoids atexit(), etc
ffi.cdef('void _exit(int);')
libc = ffi.dlopen(None)
_exit = libc._exit
Run Code Online (Sandbox Code Playgroud)

.... 或者 ....

# ctypes method
libc = cdll.LoadLibrary('libc-2.18.so')
_exit = libc._exit
Run Code Online (Sandbox Code Playgroud)

tam*_*ech 5

有人帮我找到了这个答案:

In glibc up to version 2.3, the _exit() wrapper function invoked the kernel system
call of the same name.  Since glibc 2.3, the wrapper function invokes
exit_group(2), in order to terminate all of the threads in a process.
Run Code Online (Sandbox Code Playgroud)

由于 _exit 包装了 exit_group 并且 exit_group 不在 seccomp 过滤器中......它被杀死了。python 执行的 strace 显示了 exit_group 调用。