python-prctl-1.7/0000755000175000017500000000000013232713575014616 5ustar dennisdennis00000000000000python-prctl-1.7/_prctlmodule.c0000644000175000017500000005464113232713574017464 0ustar dennisdennis00000000000000/* * python-pctrl -- python interface to the prctl function * (c)2010-2018 Dennis Kaarsemaker * See COPYING for licensing details */ #include #if PY_MAJOR_VERSION >= 3 #define PyInt_FromLong PyLong_FromLong #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong #endif #include "securebits.h" #include #include #include /* New in 2.6.32, but named and implemented inconsistently. The linux * implementation has two ways of setting the policy to the default, and thus * needs an extra argument. We ignore the first argument and always call * PR_MCE_KILL_SET. This makes our implementation simpler and keeps the prctl * interface more consistent */ #ifdef PR_MCE_KILL #define PR_GET_MCE_KILL PR_MCE_KILL_GET #define PR_SET_MCE_KILL PR_MCE_KILL #endif /* New in 2.6.XX (Ubuntu 10.10) */ #define NOT_SET (-1) #ifdef PR_SET_PTRACER /* This one has no getter for some reason, but guard against that being fixed */ #ifndef PR_GET_PTRACER #define PR_GET_PTRACER NOT_SET /* Icky global variable to cache ptracer */ static int __cached_ptracer = NOT_SET; #endif #endif /* This function is not in Python.h, so define it here */ #if PY_MAJOR_VERSION < 3 void Py_GetArgcArgv(int*, char***); #else void Py_GetArgcArgv(int*, wchar_t***); #endif /* The prctl wrapper */ static PyObject * prctl_prctl(PyObject *self, PyObject *args) { long option = 0; long arg = 0; char *argstr = NULL; char name[17] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; int result; /* * Accept single int, two ints and int+string. That covers all current * prctl possibilities. int+string is required for (and only accepted for) * PR_SET_NAME */ if(!PyArg_ParseTuple(args, "l|l", &option, &arg)) { if(!PyArg_ParseTuple(args, "ls", &option, &argstr)) { return NULL; } if(option != PR_SET_NAME) { PyErr_SetString(PyExc_TypeError, "an integer is required"); return NULL; } PyErr_Clear(); } else { if(option == PR_SET_NAME) { PyErr_SetString(PyExc_TypeError, "a string is required"); return NULL; } } /* Validate the optional arguments */ switch(option) { #ifdef PR_CAPBSET_READ case(PR_CAPBSET_READ): case(PR_CAPBSET_DROP): if(!cap_valid(arg)) { PyErr_SetString(PyExc_ValueError, "Unknown capability"); return NULL; } break; #endif case(PR_SET_DUMPABLE): case(PR_SET_KEEPCAPS): /* Only 0 and 1 are allowed */ arg = arg ? 1 : 0; break; case(PR_SET_ENDIAN): if(arg != PR_ENDIAN_LITTLE && arg != PR_ENDIAN_BIG && arg != PR_ENDIAN_PPC_LITTLE) { PyErr_SetString(PyExc_ValueError, "Unknown endianness"); return NULL; } break; case(PR_SET_FPEMU): if(arg != PR_FPEMU_NOPRINT && arg != PR_FPEMU_SIGFPE) { PyErr_SetString(PyExc_ValueError, "Unknown floating-point emulation setting"); return NULL; } break; case(PR_SET_FPEXC): if(arg & ~(PR_FP_EXC_SW_ENABLE | PR_FP_EXC_DIV | PR_FP_EXC_OVF | PR_FP_EXC_UND | PR_FP_EXC_RES | PR_FP_EXC_INV | PR_FP_EXC_DISABLED | PR_FP_EXC_NONRECOV | PR_FP_EXC_ASYNC | PR_FP_EXC_PRECISE)) { PyErr_SetString(PyExc_ValueError, "Unknown floating-point exception mode"); return NULL; } break; #ifdef PR_MCE_KILL case(PR_SET_MCE_KILL): if(arg != PR_MCE_KILL_DEFAULT && arg != PR_MCE_KILL_EARLY && arg != PR_MCE_KILL_LATE) { PyErr_SetString(PyExc_ValueError, "Unknown memory corruption kill policy"); return NULL; } break; #endif case(PR_SET_NAME): if(strlen(argstr) > 16) { /* FIXME: warn */ } strncpy(name, argstr, 16); break; case(PR_SET_PDEATHSIG): if(arg < 0 || arg > SIGRTMAX) { PyErr_SetString(PyExc_ValueError, "Unknown signal"); return NULL; } break; #ifdef PR_SET_SECCOMP case(PR_SET_SECCOMP): #ifdef PR_SET_NO_NEW_PRIVS case(PR_SET_NO_NEW_PRIVS): #endif if(!arg) { PyErr_SetString(PyExc_ValueError, "Argument must be 1"); return NULL; } arg = 1; break; #endif #ifdef PR_SET_SECUREBITS case(PR_SET_SECUREBITS): if(arg & ~ ((1 << SECURE_NOROOT) | (1 << SECURE_NOROOT_LOCKED) | (1 << SECURE_NO_SETUID_FIXUP) | (1 << SECURE_NO_SETUID_FIXUP_LOCKED) | (1 << SECURE_KEEP_CAPS) | (1 << SECURE_KEEP_CAPS_LOCKED))) { PyErr_SetString(PyExc_ValueError, "Invalid securebits set"); return NULL; } break; #endif case(PR_SET_TIMING): if(arg != PR_TIMING_STATISTICAL && arg != PR_TIMING_TIMESTAMP) { PyErr_SetString(PyExc_ValueError, "Invalid timing constant"); return NULL; } break; #ifdef PR_SET_TSC case(PR_SET_TSC): if(arg != PR_TSC_ENABLE && arg != PR_TSC_SIGSEGV) { PyErr_SetString(PyExc_ValueError, "Invalid TSC setting"); return NULL; } break; #endif case(PR_SET_UNALIGN): if(arg != PR_UNALIGN_NOPRINT && arg != PR_UNALIGN_SIGBUS) { PyErr_SetString(PyExc_ValueError, "Invalid TSC setting"); return NULL; } break; } /* * Calling prctl * There are 3 basic call modes: * - Setters and getters for which the return value is the result * - Getters for which the result is placed in arg2 * - Getters and setters that deal with strings. * * This function takes care of all that and always returns Py_None for * settings or the result of a getter call as a PyInt or PyString. */ switch(option) { #ifdef PR_CAPBSET_READ case(PR_CAPBSET_READ): case(PR_CAPBSET_DROP): #endif #ifdef PR_SET_CHILD_SUBREAPER case(PR_SET_CHILD_SUBREAPER): #endif case(PR_SET_DUMPABLE): case(PR_GET_DUMPABLE): case(PR_SET_ENDIAN): case(PR_SET_FPEMU): case(PR_SET_FPEXC): case(PR_SET_KEEPCAPS): case(PR_GET_KEEPCAPS): #ifdef PR_MCE_KILL case(PR_GET_MCE_KILL): #endif #ifdef PR_GET_NO_NEW_PRIVS case(PR_GET_NO_NEW_PRIVS): case(PR_SET_NO_NEW_PRIVS): #endif case(PR_SET_PDEATHSIG): #if defined(PR_GET_PTRACER) && (PR_GET_PTRACER != NOT_SET) case(PR_GET_PTRACER): #endif #ifdef PR_SET_PTRACER case(PR_SET_PTRACER): #endif #ifdef PR_SET_SECCOMP case(PR_SET_SECCOMP): case(PR_GET_SECCOMP): #endif #ifdef PR_SET_SECUREBITS case(PR_SET_SECUREBITS): case(PR_GET_SECUREBITS): #endif #ifdef PR_GET_TIMERSLACK case(PR_GET_TIMERSLACK): case(PR_SET_TIMERSLACK): #endif case(PR_SET_TIMING): case(PR_GET_TIMING): #ifdef PR_SET_TSC case(PR_SET_TSC): #endif case(PR_SET_UNALIGN): result = prctl(option, arg, 0, 0, 0); if(result < 0) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } switch(option) { #ifdef PR_CAPBSET_READ case(PR_CAPBSET_READ): #endif case(PR_GET_DUMPABLE): case(PR_GET_KEEPCAPS): #ifdef PR_GET_SECCOMP case(PR_GET_SECCOMP): #endif case(PR_GET_TIMING): return PyBool_FromLong(result); #ifdef PR_MCE_KILL case(PR_GET_MCE_KILL): #endif #ifdef PR_GET_NO_NEW_PRIVS case(PR_GET_NO_NEW_PRIVS): #endif #if defined(PR_GET_PTRACER) && (PR_GET_PTRACER != NOT_SET) case(PR_GET_PTRACER): #endif #ifdef PR_GET_SECUREBITS case(PR_GET_SECUREBITS): #endif #ifdef PR_GET_TIMERSLACK case(PR_GET_TIMERSLACK): #endif return PyInt_FromLong(result); #if defined(PR_GET_PTRACER) && (PR_GET_PTRACER == NOT_SET) case(PR_SET_PTRACER): __cached_ptracer = arg; break; #endif } break; #ifdef PR_GET_CHILD_SUBREAPER case(PR_GET_CHILD_SUBREAPER): #endif case(PR_GET_ENDIAN): case(PR_GET_FPEMU): case(PR_GET_FPEXC): case(PR_GET_PDEATHSIG): #ifdef PR_GET_TSC case(PR_GET_TSC): #endif case(PR_GET_UNALIGN): #ifdef PR_GET_TID_ADDRESS case(PR_GET_TID_ADDRESS): #endif result = prctl(option, &arg, 0, 0, 0); if(result < 0) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } return PyInt_FromLong(arg); case(PR_SET_NAME): case(PR_GET_NAME): result = prctl(option, name, 0, 0, 0); if(result < 0) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } if(option == PR_GET_NAME) { return Py_BuildValue("s", name); } break; #if defined(PR_GET_PTRACER) && (PR_GET_PTRACER == NOT_SET) case(PR_GET_PTRACER): if(__cached_ptracer == NOT_SET) return PyInt_FromLong(getppid()); return PyInt_FromLong(__cached_ptracer); #endif #ifdef PR_MCE_KILL case(PR_SET_MCE_KILL): result = prctl(option, PR_MCE_KILL_SET, arg, 0, 0); if(result < 0) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } break; #endif default: PyErr_SetString(PyExc_ValueError, "Unknown prctl option"); return NULL; } /* None is returned by default */ Py_RETURN_NONE; } /* While not part of prctl, this complements PR_SET_NAME */ static int __real_argc = -1; static char **__real_argv = NULL; #if PY_MAJOR_VERSION < 3 #define _Py_GetArgcArgv Py_GetArgcArgv #else /* In python 3, Py_GetArgcArgv doesn't actually return the real argv, but an * encoded copy of it. We try to find the real one by going back from the start * of environ. */ static char * encode(wchar_t *wstr) { PyObject *unicodestr = NULL, *bytesstr = NULL; char *str = NULL; unicodestr = PyUnicode_FromWideChar(wstr, -1); if(!unicodestr) { PyErr_Clear(); return NULL; } bytesstr = PyUnicode_AsEncodedString(unicodestr, PyUnicode_GetDefaultEncoding(), "strict"); if(!bytesstr) { PyErr_Clear(); Py_XDECREF(unicodestr); return NULL; } str = PyBytes_AsString(bytesstr); Py_XDECREF(unicodestr); Py_XDECREF(bytesstr); return str; } static int _Py_GetArgcArgv(int* argc, char ***argv) { int i = 0; wchar_t **argv_w; char **buf = NULL , *arg0 = NULL, *ptr = 0, *limit = NULL; Py_GetArgcArgv(argc, &argv_w); buf = (char **)malloc((*argc + 1) * sizeof(char *)); buf[*argc] = NULL; /* Walk back from environ until you find argc-1 null-terminated strings. */ ptr = environ[0] - 1; limit = ptr - 8192; for(i=*argc-1; i >= 1; --i) { ptr--; while (*ptr && ptr-- > limit); if (ptr <= limit) { free(buf); return 0; } buf[i] = (ptr + 1); } /* Now try to find argv[0] */ arg0 = encode(argv_w[0]); if(!arg0) { free(buf); return 0; } ptr -= strlen(arg0); if(strcmp(ptr, arg0)) { free(buf); return 0; } buf[0] = ptr; *argv = buf; return 1; } #endif static PyObject * prctl_set_proctitle(PyObject *self, PyObject *args) { int argc = 0; char **argv; int len; char *title; if(!PyArg_ParseTuple(args, "s", &title)) { return NULL; } if(__real_argc > 0) { argc = __real_argc; argv = __real_argv; } else { _Py_GetArgcArgv(&argc, &argv); __real_argc = argc; __real_argv = argv; } if(argc <= 0) { PyErr_SetString(PyExc_RuntimeError, "Failed to locate argc/argv"); return NULL; } /* Determine up to where we can write */ len = (size_t)(argv[argc-1]) + strlen(argv[argc-1]) - (size_t)(argv[0]); strncpy(argv[0], title, len); if(strlen(title) < len) memset(argv[0] + strlen(title), 0, len - strlen(title)); Py_RETURN_NONE; } /* TODO: Add a getter? */ static PyObject * prctl_get_caps_flag(PyObject *list, cap_t caps, int flag) { int i; PyObject *ret, *item, *val; cap_flag_value_t value; if(list && !PySequence_Check(list)) { PyErr_SetString(PyExc_TypeError, "A sequence of integers is required"); return NULL; } ret = PyDict_New(); if(!list) return ret; for(i=0; i < PyList_Size(list); i++) { item = PyList_GetItem(list, i); if(!PyInt_Check(item)) { PyErr_SetString(PyExc_TypeError, "A sequence of integers is required"); return ret; /* Return the list so it can be freed */ } if(cap_get_flag(caps, PyInt_AsLong(item), flag, &value) == -1) { PyErr_SetFromErrno(PyExc_OSError); return ret; } val = PyBool_FromLong(value); PyDict_SetItem(ret, item, val); Py_XDECREF(val); } return ret; } static int prctl_set_caps_flag(PyObject *list, cap_t caps, int flag, cap_flag_value_t value) { int i; cap_value_t cap; PyObject *item; if(list && !PySequence_Check(list)) { PyErr_SetString(PyExc_TypeError, "A sequence of integers is required"); return 0; } if(!list) return 1; for(i=0; i < PyList_Size(list); i++) { item = PyList_GetItem(list, i); if(!PyInt_Check(item)) { PyErr_SetString(PyExc_TypeError, "A sequence of integers is required"); return 0; } cap = PyInt_AsLong(item); if(cap_set_flag(caps, flag, 1, &cap, value) == -1) { PyErr_SetFromErrno(PyExc_OSError); return 0; } } return 1; } static PyObject * prctl_get_caps(PyObject *self, PyObject *args) { PyObject *effective = NULL; PyObject *permitted = NULL; PyObject *inheritable = NULL; PyObject *effective_ = NULL; PyObject *permitted_ = NULL; PyObject *inheritable_ = NULL; PyObject *ret = NULL; PyObject *key = NULL; cap_t caps = NULL; if(!PyArg_ParseTuple(args, "O|OO", &effective, &permitted, &inheritable)) { return NULL; } caps = cap_get_proc(); if(!caps) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } effective_ = prctl_get_caps_flag(effective, caps, CAP_EFFECTIVE); if(PyErr_Occurred()) goto error; permitted_ = prctl_get_caps_flag(permitted, caps, CAP_PERMITTED); if(PyErr_Occurred()) goto error; inheritable_ = prctl_get_caps_flag(inheritable, caps, CAP_INHERITABLE); if(PyErr_Occurred()) goto error; /* Now build the dict */ ret = PyDict_New(); key = PyInt_FromLong(CAP_EFFECTIVE); PyDict_SetItem(ret, key, effective_); Py_XDECREF(key); key = PyInt_FromLong(CAP_PERMITTED); PyDict_SetItem(ret, key, permitted_); Py_XDECREF(key); key = PyInt_FromLong(CAP_INHERITABLE); PyDict_SetItem(ret, key, inheritable_); Py_XDECREF(key); error: cap_free(caps); Py_XDECREF(effective_); Py_XDECREF(permitted_); Py_XDECREF(inheritable_); return ret; } static PyObject * prctl_set_caps(PyObject *self, PyObject *args) { PyObject *effective_set = NULL; PyObject *permitted_set = NULL; PyObject *inheritable_set = NULL; PyObject *effective_clear = NULL; PyObject *permitted_clear = NULL; PyObject *inheritable_clear = NULL; cap_t caps = NULL; if(!PyArg_ParseTuple(args, "O|OOOOO", &effective_set, &permitted_set, &inheritable_set, &effective_clear, &permitted_clear, &inheritable_clear)) { return NULL; } caps = cap_get_proc(); if(!caps) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } if(!prctl_set_caps_flag(effective_set, caps, CAP_EFFECTIVE, CAP_SET)) return NULL; if(!prctl_set_caps_flag(permitted_set, caps, CAP_PERMITTED, CAP_SET)) return NULL; if(!prctl_set_caps_flag(inheritable_set, caps, CAP_INHERITABLE, CAP_SET)) return NULL; if(!prctl_set_caps_flag(effective_clear, caps, CAP_EFFECTIVE, CAP_CLEAR)) return NULL; if(!prctl_set_caps_flag(permitted_clear, caps, CAP_PERMITTED, CAP_CLEAR)) return NULL; if(!prctl_set_caps_flag(inheritable_clear, caps, CAP_INHERITABLE, CAP_CLEAR)) return NULL; if(cap_set_proc(caps) == -1) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } Py_RETURN_NONE; } #ifdef cap_to_name static PyObject * prctl_cap_to_name(PyObject *self, PyObject *args) { cap_value_t cap; char *name; PyObject *ret; if(!PyArg_ParseTuple(args, "i", &cap)){ return NULL; } name = cap_to_name(cap); if(!name) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } ret = Py_BuildValue("s", name+4); /* Exclude the cap_ prefix */ cap_free(name); return ret; } #endif static PyMethodDef PrctlMethods[] = { {"get_caps", prctl_get_caps, METH_VARARGS, "Get process capabilities"}, {"set_caps", prctl_set_caps, METH_VARARGS, "Set process capabilities"}, #ifdef cap_to_name {"cap_to_name", prctl_cap_to_name, METH_VARARGS, "Convert capability number to name"}, #endif {"prctl", prctl_prctl, METH_VARARGS, "Call prctl"}, {"set_proctitle", prctl_set_proctitle, METH_VARARGS, "Set the process title"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef prctlmodule = { PyModuleDef_HEAD_INIT, "_prctl", NULL, -1, PrctlMethods }; #endif /* These macros avoid tediously repeating a name 2 or 4 times */ #define namedconstant(x) PyModule_AddIntConstant(_prctl, #x, x) #define namedattribute(x) do{ \ PyModule_AddIntConstant(_prctl, "PR_GET_" #x, PR_GET_ ## x); \ PyModule_AddIntConstant(_prctl, "PR_SET_" #x, PR_SET_ ## x); \ } while(0) PyMODINIT_FUNC #if PY_MAJOR_VERSION < 3 init_prctl(void) #else PyInit__prctl(void) #endif { #if PY_MAJOR_VERSION < 3 PyObject *_prctl = Py_InitModule("_prctl", PrctlMethods); #else PyObject *_prctl = PyModule_Create(&prctlmodule); #endif /* Add the PR_* constants */ #ifdef PR_CAPBSET_READ namedconstant(PR_CAPBSET_READ); namedconstant(PR_CAPBSET_DROP); #endif namedattribute(DUMPABLE); namedattribute(ENDIAN); namedconstant(PR_ENDIAN_BIG); namedconstant(PR_ENDIAN_LITTLE); namedconstant(PR_ENDIAN_PPC_LITTLE); namedattribute(FPEMU); namedconstant(PR_FPEMU_NOPRINT); namedconstant(PR_FPEMU_SIGFPE); namedattribute(FPEXC); namedconstant(PR_FP_EXC_SW_ENABLE); namedconstant(PR_FP_EXC_DIV); namedconstant(PR_FP_EXC_OVF); namedconstant(PR_FP_EXC_UND); namedconstant(PR_FP_EXC_RES); namedconstant(PR_FP_EXC_INV); namedconstant(PR_FP_EXC_DISABLED); namedconstant(PR_FP_EXC_NONRECOV); namedconstant(PR_FP_EXC_ASYNC); namedconstant(PR_FP_EXC_PRECISE); namedattribute(KEEPCAPS); #ifdef PR_MCE_KILL namedattribute(MCE_KILL); namedconstant(PR_MCE_KILL_DEFAULT); namedconstant(PR_MCE_KILL_EARLY); namedconstant(PR_MCE_KILL_LATE); #endif namedattribute(NAME); namedattribute(PDEATHSIG); #ifdef PR_SET_PTRACER namedattribute(PTRACER); #endif #ifdef PR_SET_PTRACER_ANY namedconstant(PR_SET_PTRACER_ANY); #endif #ifdef PR_SET_CHILD_SUBREAPER namedattribute(CHILD_SUBREAPER); #endif #ifdef PR_SET_NO_NEW_PRIVS namedattribute(NO_NEW_PRIVS); #endif #ifdef PR_GET_SECCOMP namedattribute(SECCOMP); #endif #ifdef PR_GET_SECUREBITS namedattribute(SECUREBITS); #endif #ifdef PR_GET_TIMERSLACK namedattribute(TIMERSLACK); #endif namedattribute(TIMING); namedconstant(PR_TIMING_STATISTICAL); namedconstant(PR_TIMING_TIMESTAMP); #ifdef PR_SET_TSC namedattribute(TSC); namedconstant(PR_TSC_ENABLE); namedconstant(PR_TSC_SIGSEGV); #endif namedattribute(UNALIGN); namedconstant(PR_UNALIGN_NOPRINT); namedconstant(PR_UNALIGN_SIGBUS); #ifdef PR_GET_TID_ADDRESS namedconstant(PR_GET_TID_ADDRESS); #endif /* Add the CAP_* constants too */ namedconstant(CAP_EFFECTIVE); namedconstant(CAP_PERMITTED); namedconstant(CAP_INHERITABLE); namedconstant(CAP_CHOWN); namedconstant(CAP_DAC_OVERRIDE); namedconstant(CAP_DAC_READ_SEARCH); namedconstant(CAP_FOWNER); namedconstant(CAP_FSETID); namedconstant(CAP_KILL); namedconstant(CAP_SETGID); namedconstant(CAP_SETUID); namedconstant(CAP_SETPCAP); namedconstant(CAP_LINUX_IMMUTABLE); namedconstant(CAP_NET_BIND_SERVICE); namedconstant(CAP_NET_BROADCAST); namedconstant(CAP_NET_ADMIN); namedconstant(CAP_NET_RAW); namedconstant(CAP_IPC_LOCK); namedconstant(CAP_IPC_OWNER); namedconstant(CAP_SYS_MODULE); namedconstant(CAP_SYS_RAWIO); namedconstant(CAP_SYS_CHROOT); namedconstant(CAP_SYS_PTRACE); namedconstant(CAP_SYS_PACCT); namedconstant(CAP_SYS_ADMIN); namedconstant(CAP_SYS_BOOT); namedconstant(CAP_SYS_NICE); namedconstant(CAP_SYS_RESOURCE); namedconstant(CAP_SYS_TIME); namedconstant(CAP_SYS_TTY_CONFIG); namedconstant(CAP_MKNOD); namedconstant(CAP_LEASE); namedconstant(CAP_AUDIT_WRITE); namedconstant(CAP_AUDIT_CONTROL); #ifdef CAP_SETFCAP namedconstant(CAP_SETFCAP); #endif #ifdef CAP_MAC_OVERRIDE namedconstant(CAP_MAC_OVERRIDE); #endif #ifdef CAP_MAC_ADMIN namedconstant(CAP_MAC_ADMIN); #endif #ifdef CAP_SYSLOG namedconstant(CAP_SYSLOG); #endif #ifdef CAP_WAKE_ALARM namedconstant(CAP_WAKE_ALARM); #endif /* And the securebits constants */ namedconstant(SECURE_KEEP_CAPS); namedconstant(SECURE_NO_SETUID_FIXUP); namedconstant(SECURE_NOROOT); namedconstant(SECURE_KEEP_CAPS_LOCKED); namedconstant(SECURE_NO_SETUID_FIXUP_LOCKED); namedconstant(SECURE_NOROOT_LOCKED); namedconstant(SECBIT_KEEP_CAPS); namedconstant(SECBIT_NO_SETUID_FIXUP); namedconstant(SECBIT_NOROOT); namedconstant(SECBIT_KEEP_CAPS_LOCKED); namedconstant(SECBIT_NO_SETUID_FIXUP_LOCKED); namedconstant(SECBIT_NOROOT_LOCKED); #if PY_MAJOR_VERSION >= 3 return _prctl; #endif } python-prctl-1.7/docs/0000755000175000017500000000000013232713575015546 5ustar dennisdennis00000000000000python-prctl-1.7/docs/index.rst0000644000175000017500000007330413232713574017415 0ustar dennisdennis00000000000000======================================== Welcome to python-prctl's documentation! ======================================== The linux prctl function allows you to control specific characteristics of a process' behaviour. Usage of the function is fairly messy though, due to limitations in C and linux. This module provides a nice non-messy python(ic) interface. Most of the text in this documentation is based on text from the linux manpages :manpage:`prctl(2)` and :manpage:`capabilities(7)` Besides prctl, this library also wraps libcap for complete capability handling and allows you to set the process name as seen in ps and top. Downloading and installing ========================== Before you try to install python-prctl, you will need to install the following: * gcc * libc development headers * libcap development headers On Debian and Ubuntu, this is done as follows: .. code-block:: sh $ sudo apt-get install build-essential libcap-dev On Fedora and other RPM-based distributions: .. code-block:: sh $ sudo yum install gcc glibc-devel libcap-devel The latest stable version can be installed with distutils: .. code-block:: sh $ sudo easy_install python-prctl The latest development source for python-prctl can be downloaded from `GitHub `_. Installing is again done with distutils. .. code-block:: sh $ git clone http://github.com/seveas/python-prctl $ cd python-prctl $ python setup.py build $ sudo python setup.py install The prctl module is now ready to use. :mod:`prctl` -- Control process attributes ========================================== .. module:: prctl :platform: Linux (2.6.25 or newer) :synopsis: Control process attributes .. moduleauthor:: Dennis Kaarsemaker .. function:: set_child_subreaper(flag) When processes double-fork, they get implicitly re-parented to PID 1. Using this function, processes can mark themselves as service manager and will remain parent of any such processes they launch, becoming a sort of sub-init. They will then be responsible for handling :const:`~signal.SIGCHLD` and calling :func:`wait` in them. This is only available in linux 3.4 and newer .. function:: get_child_subreaper() Determine whether we are a sub-init. This is only available in linux 3.4 and newer .. function:: set_dumpable(flag) Set the state of the flag determining whether core dumps are produced for this process upon delivery of a signal whose default behavior is to produce a core dump. (Normally this flag is set for a process by default, but it is cleared when a set-user-ID or set-group-ID program is executed and also by various system calls that manipulate process UIDs and GIDs). .. function:: get_dumpable() Return the state of the dumpable flag. .. function:: set_endian(endianness) Set the endian-ness of the calling process. Valid values are :const:`~prctl.ENDIAN_BIG`, :const:`~prctl.ENDIAN_LITTLE` and :const:`~prctl.ENDIAN_PPC_LITTLE` (PowerPC pseudo little endian). .. note:: This function only works on PowerPC systems. An :exc:`OSError` is raised when called on other systems. .. function:: get_endian() Return the endian-ness of the calling process, see :func:`set_endian`. .. function:: set_fpemu(flag) Set floating-point emulation control flag. Pass :const:`~prctl.FPEMU_NOPRINT` to silently emulate fp operations accesses, or :const:`~prctl.FPEMU_SIGFPE` to not emulate fp operations and send :const:`~signal.SIGFPE` instead. .. note:: This function only works on ia64 systems. An :exc:`OSError` is raised when called on other systems. .. function:: get_fpemu() Get floating-point emulation control flag. See :func:`set_fpemu`. .. function:: set_fpexc(mode) Set floating-point exception mode. Pass :const:`FP_EXC_SW_ENABLE` to use FPEXC for FP exception, :const:`FP_EXC_DIV` for floating-point divide by zero, :const:`FP_EXC_OVF` for floating-point overflow, :const:`FP_EXC_UND` for floating-point underflow, :const:`FP_EXC_RES` for floating-point inexact result, :const:`FP_EXC_INV` for floating-point invalid operation, :const:`FP_EXC_DISABLED` for FP exceptions disabled, :const:`FP_EXC_NONRECOV` for async non-recoverable exception mode, :const:`FP_EXC_ASYNC` for async recoverable exception mode, :const:`FP_EXC_PRECISE` for precise exception mode. Modes can be combined with the :const:`|` operator. .. note:: This function only works on PowerPC systems. An :exc:`OSError` is raised when called on other systems. .. function:: get_fpexc() Return the floating-point exception mode as a bitmap of enabled modes. See :func:`set_fpexc`. .. function:: set_keepcaps(flag) Set the state of the thread's "keep capabilities" flag, which determines whether the thread's effective and permitted capability sets are cleared when a change is made to the thread's user IDs such that the thread's real UID, effective UID, and saved set-user-ID all become non-zero when at least one of them previously had the value 0. (By default, these credential sets are cleared). This value will be reset to :const:`False` on subsequent calls to :func:`execve`. .. function:: get_keepcaps() Return the current state of the calling thread's "keep capabilities" flag. .. function:: set_mce_kill(policy) Set the machine check memory corruption kill policy for the current thread. The policy can be early kill (:const:`MCE_KILL_EARLY`), late kill (:const:`MCE_KILL_LATE`), or the system-wide default (:const:`MCE_KILL_DEFAULT`). Early kill means that the task receives a :const:`SIGBUS` signal as soon as hardware memory corruption is detected inside its address space. In late kill mode, the process is only killed when it accesses a corrupted page. The policy is inherited by children. use the system-wide default. The system-wide default is defined by :file:`/proc/sys/vm/memory_failure_early_kill` This is only available in linux 2.6.32 and newer .. function:: get_mce_kill() Return the current per-process machine check kill policy. This is only available in linux 2.6.32 and newer .. function:: set_name(name) Set the process name for the calling process, the name can be up to 16 bytes long. This name is displayed in the output of :command:`ps` and :command:`top`. The initial value is the name of the executable. For python applications this will likely be :command:`python`. .. note:: Use :func:`set_proctitle` to set the name that's shown with :func:`ps aux` and :func:`top -c` .. function:: get_name() Return the (first 16 bytes of) the name for the calling process. .. function:: set_no_new_privs() Once this is set, no operation that can grant new privileges (such as execve'ing a setuid binary) will actually grant new privileges. This is only available in linux 3.5 and newer .. function:: get_no_new_privs() Get whether new privileges can be granted to this pid. This is only available in linux 3.5 and newer .. function:: set_proctitle(title) Set the process name for the calling process by overwriting the C-level :c:data:`**argv` variable. The original value of :c:data:`**argv` is then no longer visible. in :command:`ps`, :command:`proc`, or :file:`/proc/self/cmdline`. Names longer that what fits in :c:data:`**argv` will be silently truncated. To set a longer title, make your application accept bogus arguments and call the application with these arguments. .. note:: This function is not actually part of the standard :func:`pctrl` syscall, but was added because it nicely complements :func:`set_name`. .. function:: set_pdeathsig(signal) Set the parent death signal of the calling process (either a valid signal value from the :mod:`signal` module, or 0 to clear). This is the signal that the calling process will get when its parent dies. This value is cleared for the child of a :func:`fork`. .. warning:: The "parent" in this case is considered to be the thread that created this process. In other words, the signal will be sent when that thread terminates (via, for example, :func:`pthread_exit()`), rather than after all of the threads in the parent process terminate. .. function:: get_pdeathsig() Return the current value of the parent process death signal. See :func:`set_pdeathsig`. .. function:: set_ptracer(pid) Sets the top of the process tree that is allowed to use :func:`PTRACE` on the calling process, assuming other requirements are met (matching uid, wasn't setuid, etc). Use pid 0 to disallow all processes. For more details, see :file:`/etc/sysctl.d/10-ptrace.conf`. This is only available in linux 3.4 and newer .. function:: get_ptracer(pid) Returns the top of the process tree that is allowed to use :func:`PTRACE` on the calling process. See :func:`set_ptracer`. This is only available in linux 3.4 and newer .. function:: set_seccomp(mode) Set the secure computing mode for the calling thread. In the current implementation, mode must be :const:`True`. After the secure computing mode has been set to :const:`True`, the only system calls that the thread is permitted to make are :func:`read`, :func:`write`, :func:`_exit`, and :func:`sigreturn`. Other system calls result in the delivery of a :const:`~signal.SIGKILL` signal. Secure computing mode is useful for number-crunching applications that may need to execute untrusted byte code, perhaps obtained by reading from a pipe or socket. This operation is only available if the kernel is configured with :const:`CONFIG_SECCOMP` enabled. .. function:: get_seccomp() Return the secure computing mode of the calling thread. Not very useful for the current implementation, but may be useful for other possible future modes: if the caller is not in secure computing mode, this operation returns False; if the caller is in secure computing mode, then the :func:`prctl` call will cause a :const:`~signal.SIGKILL` signal to be sent to the process. This operation is only available if the kernel is configured with :const:`CONFIG_SECCOMP` enabled. .. function:: get_tid_address() Allows the process to obtain its own `clear_tid_address`, used when checkpointing/restoring processes. This is only available in linux 3.5 and newer .. function:: set_timerslack() Control the default "rounding" in nanoseconds that is used by :func:`select`, :func:`poll` and friends. The default value of the slack is 50 microseconds; this is significantly less than the kernels average timing error but still allows the kernel to group timers somewhat to preserve power behavior. This is only available in linux 2.6.28 and newer .. function:: get_timerslack(value) Return the current timing slack, see :func:`get_timing_slack` This is only available in linux 2.6.28 and newer .. function:: set_timing(flag) Set whether to use (normal, traditional) statistical process timing or accurate timestamp based process timing, by passing :const:`~prctl.TIMING_STATISTICAL` or :const:`~prctl.PR_TIMING_TIMESTAMP`. :const:`~prctl.TIMING_TIMESTAMP` is not currently implemented (attempting to set this mode will cause an :exc:`OSError`). .. function:: get_timing() Return which process timing method is currently in use. .. function:: set_tsc(flag) Set the state of the flag determining whether the timestamp counter can be read by the process. Pass :const:`~prctl.TSC_ENABLE` to allow it to be read, or :const:`~prctl.TSC_SIGSEGV` to generate a :const:`SIGSEGV` when the process tries to read the timestamp counter. .. note:: This function only works on x86 systems. An :exc:`OSError` is raised when called on other systems. .. function:: get_tsc() Return the state of the flag determining whether the timestamp counter can be read, see :func:`set_tsc`. .. function:: set_unalign(flag) Set unaligned access control flag. Pass :const:`~prctl.UNALIGN_NOPRINT` to silently fix up unaligned user accesses, or :const:`~prctl.UNALIGN_SIGBUS` to generate :const:`SIGBUS` on unaligned user access. .. note:: This function only works on ia64, parisc, PowerPC and Alpha systems. An :exc:`OSError` is raised when called on other systems. .. function:: get_unalign Return unaligned access control bits, see :func:`set_unalign`. .. function:: set_securebits(bitmap) Set the "securebits" flags of the calling thread. .. note:: It is not recommended to use this function directly, use the :attr:`~prctl.securebits` object instead. .. function:: get_securebits() Get the "securebits" flags of the calling thread. .. note:: As with :func:`set_securebits`, it is not recommended to use this function directly, use the :attr:`~prctl.securebits` object instead. .. function:: capbset_read(capability) Return whether the specified capability is in the calling thread's capability bounding set. The capability bounding set dictates whether the process can receive the capability through a file's permitted capability set on a subsequent call to :func:`execve`. An :exc:`OSError` will be raised when an invalid capability is specified. .. note:: It is not recommended to use this function directly, use the :attr:`~prctl.capbset` object instead. .. function:: capbset_drop(capability) If the calling thread has the :const:`~prctl.CAP_SETPCAP` capability, then drop the specified capability specified by from the calling thread's capability bounding set. Any children of the calling thread will inherit the newly reduced bounding set. An :exc:`OSError` will be raised if the calling thread does not have the :const:`~prctl.CAP_SETPCAP` capability or when the specified capability is invalid or when capabilities are not enabled in the kernel. .. note:: As with :func:`capbset_read`, it is not recommended to use this function directly, use the :attr:`~prctl.capbset` object instead. Capabilities and the capability bounding set ============================================ For the purpose of performing permission checks, traditional Unix implementations distinguish two categories of processes: privileged processes (whose effective user ID is 0, referred to as superuser or root), and unprivileged processes (whose effective UID is non-zero). Privileged processes bypass all kernel permission checks, while unprivileged processes are subject to full permission checking based on the process's credentials (usually: effective UID, effective GID, and supplementary group list). Starting with kernel 2.2, Linux divides the privileges traditionally associated with superuser into distinct units, known as capabilities, which can be independently enabled and disabled. Capabilities are a per-thread attribute. Each thread has three capability sets containing zero or more of the capabilities described below Permitted (the :attr:`~prctl.cap_permitted` object): This is a limiting superset for the effective capabilities that the thread may assume. It is also a limiting superset for the capabilities that may be added to the inheritable set by a thread that does not have the :attr:`setpcap` capability in its effective set. If a thread drops a capability from its permitted set, it can never re-acquire that capability (unless it :func:`execve` s either a set-user-ID-root program, or a program whose associated file capabilities grant that capability). Inheritable (the :attr:`~prctl.cap_inheritable` object): This is a set of capabilities preserved across an :func:`execve`. It provides a mechanism for a process to assign capabilities to the permitted set of the new program during an :func:`execve`. Effective (the :attr:`~prctl.cap_effective` object): This is the set of capabilities used by the kernel to perform permission checks for the thread. A child created via :func:`fork` inherits copies of its parent's capability sets. See below for a discussion of the treatment of capabilities during :func:`execve`. The :attr:`~prctl.capbset` object represents the current capability bounding set of the process. The capability bounding set dictates whether the process can receive the capability through a file's permitted capability set on a subsequent call to :func:`execve`. All attributes of :attr:`~prctl.capbset` are :const:`True` by default, unless a parent process already removed them from the bounding set. These four objects have a number of attributes, all of which are properties. For the capability bounding set and the effective capabilities, these can only be set to :const:`False`, this drops them from the corresponding set. All details about capabilities and capability bounding sets can be found in the :manpage:`capabilities(7)` manpage, on which most text below is based. These are the attributes (:class:`set` refers to each of the above objects): .. attribute:: set.audit_control Enable and disable kernel auditing; change auditing filter rules; retrieve auditing status and filtering rules. .. attribute:: set.audit_write Write records to kernel auditing log. .. attribute:: set.chown Make arbitrary changes to file UIDs and GIDs (see :manpage:`chown(2)`). .. attribute:: set.dac_override Bypass file read, write, and execute permission checks. (DAC is an abbreviation of "discretionary access control".) .. attribute:: set.dac_read_search Bypass file read permission checks and directory read and execute permission checks. .. attribute:: set.fowner * Bypass permission checks on operations that normally require the file system UID of the process to match the UID of the file (e.g., :func:`chmod`, :func:`utime`), excluding those operations covered by :attr:`dac_override` and :attr:`dac_read_search`. * Set extended file attributes (see :manpage:`chattr(1)`) on arbitrary files. * Set Access Control Lists (ACLs) on arbitrary files. * Ignore directory sticky bit on file deletion. * Specify :const:`O_NOATIME` for arbitrary files in :func:`open` and :func:`fcntl`. .. attribute:: set.fsetid Don't clear set-user-ID and set-group-ID permission bits when a file is modified; set the set-group-ID bit for a file whose GID does not match the file system or any of the supplementary GIDs of the calling process. .. attribute:: set.ipc_lock Lock memory (:func:`mlock`, :func:`mlockall`, :func:`mmap`, :func:`shmctl`). .. attribute:: set.ipc_owner Bypass permission checks for operations on System V IPC objects. .. attribute:: set.kill Bypass permission checks for sending signals (see :manpage:`kill(2)`). This includes use of the :func:`ioctl` :const:`KDSIGACCEPT` operation. .. attribute:: set.lease Establish leases on arbitrary files (see :manpage:`fcntl(2)`). .. attribute:: set.linux_immutable Set the :const:`FS_APPEND_FL` and :const:`FS_IMMUTABLE_FL` i-node flags (see :manpage:`chattr(1)`). .. attribute:: set.mac_admin Override Mandatory Access Control (MAC). Implemented for the Smack Linux Security Module (LSM). .. attribute:: set.mac_override Allow MAC configuration or state changes. Implemented for the Smack LSM. .. The above two were copied from the manpage, but they seem to be swapped. Hmm... .. attribute:: set.mknod Create special files using :func:`mknod`. .. attribute:: set.net_admin Perform various network-related operations (e.g., setting privileged socket options, enabling multicasting, interface configuration, modifying routing tables). .. attribute:: set.net_bind_service Bind a socket to Internet domain privileged ports (port numbers less than 1024). .. attribute:: set.net_broadcast (Unused) Make socket broadcasts, and listen to multicasts. .. attribute:: set.net_raw Use :const:`RAW` and :const:`PACKET` sockets. .. attribute:: set.setgid Make arbitrary manipulations of process GIDs and supplementary GID list; forge GID when passing socket credentials via Unix domain sockets. .. attribute:: set.setfcap Set file capabilities. .. attribute:: set.setpcap If file capabilities are not supported: grant or remove any capability in the caller's permitted capability set to or from any other process. (This property of :attr:`setpcap` is not available when the kernel is configured to support file capabilities, since :attr:`setpcap` has entirely different semantics for such kernels.) If file capabilities are supported: add any capability from the calling thread's bounding set to its inheritable set; drop capabilities from the bounding set (via :func:`~prctl.capbset_drop`); make changes to the securebits flags. .. attribute:: set.setuid Make arbitrary manipulations of process UIDs (:func:`setuid`, :func:`setreuid`, :func:`setresuid`, :func:`setfsuid`); make forged UID when passing socket credentials via Unix domain sockets. .. attribute:: set.syslog Allow configuring the kernel's syslog (printk behaviour). Before linux 2.6.38 the :attr:`sys_admin` capability was needed for this. This is only available in linux 2.6.38 and newer .. attribute:: set.sys_admin * Perform a range of system administration operations including: :func:`quotactl`, func:`mount`, :func:`umount`, :func:`swapon`, :func:`swapoff`, :func:`sethostname`, and :func:`setdomainname`. * Perform :const:`IPC_SET` and :const:`IPC_RMID` operations on arbitrary System V IPC objects. * Perform operations on trusted and security Extended Attributes (see :manpage:`attr(5)`). * Use :func:`lookup_dcookie`. * Use :func:`ioprio_set` to assign the :const:`IOPRIO_CLASS_RT` scheduling class. * Forge UID when passing socket credentials. * Exceed :file:`/proc/sys/fs/file-max`, the system-wide limit on the number of open files, in system calls that open files (e.g., :func:`accept`, :func:`execve`, :func:`open`, :func:`pipe`). * Employ :const:`CLONE_NEWNS` flag with :func:`clone` and :func:`unshare`. * Perform :const:`KEYCTL_CHOWN` and :const:`KEYCTL_SETPERM` :func:`keyctl` operations. .. attribute:: set.sys_boot Use :func:`reboot` and :func:`kexec_load`. .. attribute:: set.sys_chroot Use :func:`chroot`. .. attribute:: set.sys_module Load and unload kernel modules (see :manpage:`init_module(2)` and :manpage:`delete_module(2)`). .. attribute:: set.sys_nice * Raise process nice value (:func:`nice`, :func:`setpriority`) and change the nice value for arbitrary processes. * Set real-time scheduling policies for calling process, and set scheduling policies and priorities for arbitrary processes (:func:`sched_setscheduler`, :func:`sched_setparam`). * Set CPU affinity for arbitrary processes (:func:`sched_setaffinity`) * Set I/O scheduling class and priority for arbitrary processes (:func:`ioprio_set`). * Apply :func:`migrate_pages` to arbitrary processes and allow processes to be migrated to arbitrary nodes. * Apply :func:`move_pages` to arbitrary processes. * Use the :const:`MPOL_MF_MOVE_ALL` flag with :func:`mbind` and :func:`move_pages`. .. attribute:: set.sys_pacct Use :func:`acct`. .. attribute:: set.sys_ptrace Trace arbitrary processes using :func:`ptrace`. .. attribute:: set.sys_rawio Perform I/O port operations (:func:`iopl` and :func:`ioperm`); access :file:`/proc/kcore`. .. attribute:: set.sys_resource * Use reserved space on ext2 file systems. * Make :func:`ioctl` calls controlling ext3 journaling. * Override disk quota limits. * Increase resource limits (see :manpage:`setrlimit(2)`). * Override :const:`RLIMIT_NPROC` resource limit. * Raise :c:data:`msg_qbytes` limit for a System V message queue above the limit in :file:`/proc/sys/kernel/msgmnb` (see :manpage:`msgop(2)` and :manpage:`msgctl(2)`). .. attribute:: set.sys_time Set system clock (:func:`settimeofday`, :func:`stime`, :func:`adjtimex`); set real-time (hardware) clock. .. attribute:: set.sys_tty_config Use :func:`vhangup`. .. attribute:: set.wake_alarm Allow triggering something that will wake the system. This is only available in linux 3.0 and newer The four capabilities objects also have two additional methods, to make dropping many capabilities at the same time easier: .. function:: set.drop(cap [, ...]) Drop all capabilities given as arguments from the set. .. function:: set.limit(cap [, ...]) Drop all but the given capabilities from the set. These function accept both names of capabilities as given above and the :data:`CAP_` constants as defined in :file:`capabilities.h`. These constants are available as :attr:`prctl.CAP_SYS_ADMIN` et cetera. Capabilities and :func:`execve` =============================== During an :func:`execve`, the kernel calculates the new capabilities of the process using the following algorithm: * P'(permitted) = (P(inheritable) & F(inheritable)) | (F(permitted) & cap_bset) * P'(effective) = F(effective) ? P'(permitted) : 0 * P'(inheritable) = P(inheritable) [i.e., unchanged] Where: * P denotes the value of a thread capability set before the :func:`execve` * P' denotes the value of a capability set after the :func:`execve` * F denotes a file capability set * cap_bset is the value of the capability bounding set The downside of this is that you need to set file capabilities if you want to make applications capabilities-friendly via wrappers. For instance, to allow an http daemon to listen on port 80 without it needing root privileges, you could do the following: .. code-block:: python prctl.cap_inheritable.net_bind_service = True os.setuid(pwd.getpwnam('www-data').pw_uid) os.execve("/usr/sbin/httpd", ["/usr/sbin/httpd"], os.environ) This only works if :file:`/usr/sbin/httpd` has :attr:`CAP_NET_BIND_SOCK` in its inheritable and effective sets. You can do this with the :command:`setcap` tool shipped with libcap. .. code-block:: sh $ sudo setcap cap_net_bind_service=ie /usr/sbin/httpd $ getcap /usr/sbin/httpd /usr/sbin/httpd = cap_net_bind_service+ei Note that it only sets the capability in the inheritable set, so this capability is only granted if the program calling execve has it in its inheritable set too. The effective set of file capabilities does not exist in linux, it is a single bit that specifies whether capabilities in the permitted set are automatically raised in the effective set upon :func:`execve`. Establishing a capabilities-only environment with securebits ============================================================ With a kernel in which file capabilities are enabled, Linux implements a set of per-thread securebits flags that can be used to disable special handling of capabilities for UID 0 (root). The securebits flags are inherited by child processes. During an :func:`execve`, all of the flags are preserved, except :attr:`keep_caps` which is always cleared. These capabilities are available via :func:`get_securebits`, but are easier accessed via the :attr:`~prctl.securebits` object. This object has attributes tell you whether specific securebits are set, or unset. The following attributes are available: .. attribute:: securebits.keep_caps Setting this flag allows a thread that has one or more 0 UIDs to retain its capabilities when it switches all of its UIDs to a non-zero value. If this flag is not set, then such a UID switch causes the thread to lose all capabilities. This flag is always cleared on an :func:`execve`. .. attribute:: securebits.no_setuid_fixup Setting this flag stops the kernel from adjusting capability sets when the thread's effective and file system UIDs are switched between zero and non-zero values. (See the subsection Effect of User ID Changes on Capabilities in :manpage:`capabilities(7)`) .. attribute:: securebits.noroot If this bit is set, then the kernel does not grant capabilities when a set-user-ID-root program is executed, or when a process with an effective or real UID of 0 calls :func:`execve`. (See the subsection Capabilities and execution of programs by root in :manpage:`capabilities(7)`) .. attribute:: securebits.keep_caps_locked Like :attr:`keep_caps`, but irreversible .. attribute:: securebits.no_setuid_fixup_locked Like :attr:`no_setuid_fixup`, but irreversible .. attribute:: securebits.noroot_locked Like :attr:`noroot`, but irreversible :mod:`_prctl` -- Basic C wrapper around prctl ============================================= .. module:: _prctl :platform: Linux (2.6.25 or newer) :synopsis: Basic wrapper around prctl .. moduleauthor:: Dennis Kaarsemaker This is the lower level C module that wraps the :c:func:`prctl` syscall in a way that it is easy to call from a python module. It should not be used directly, applications and other libraries should use the functionality provided by the :mod:`prctl` module. This section of the documentation is meant for people who want to contribute to python-prctl. .. c:function:: static PyObject\* prctl_prctl(PyObject \*self, PyObject \*args) This is the :c:func:`prctl` wrapper. It accepts as argument either one or two :obj:`int` variables or an :obj:`int` and a :obj:`str`. The mandatory first int must be one of the :const:`PR_SET_*`, :const:`PR_GET_*`, or :const:`PR_CAPBSET_*` constants defined in :file:`sys/prctl.h`. The accepted values of the second argument depend on the first argument, see :manpage:`prctl(2)`. The function validates arguments, calls :c:func:`prctl` in the argument-specific way and returns the proper value, whether :func:`prctl` returns it as return value or stores it in one of the parameters. .. c:function:: static PyObject\* prctl_set_proctitle(PyObject \*self, PyObject \*args) Set the process title by mangling :data:`**argv`. Mandatory argument is a :obj:`str`. .. c:function:: PyMODINIT_FUNC init_prctl(void) Create the module instance and add all the relevant constants to the module. That means all :const:`PR_*`, :const:`CAP_*` and :const:`SECBIT_*` constants mentioned in :manpage:`prctl(2)` and :manpage:`capabilities(7)`. To avoid repeating yourself all the time, use the :c:macro:`namedconstant` and :c:macro:`namedattribute` macros when adding new values. .. toctree:: :maxdepth: 2 python-prctl-1.7/docs/conf.py0000644000175000017500000001430513232713574017047 0ustar dennisdennis00000000000000# -*- coding: utf-8 -*- # # python-prctl documentation build configuration file, created by # sphinx-quickstart on Wed Mar 10 23:08:02 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'python-prctl' copyright = u'2010-2018, Dennis Kaarsemaker' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.7' # The full version, including alpha/beta/rc tags. release = '1.7' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'python-prctldoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('README', 'python-prctl.tex', u'python-prctl Documentation', u'Dennis Kaarsemaker', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True python-prctl-1.7/docs/Makefile0000644000175000017500000000610213232713574017204 0ustar dennisdennis00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-prctl.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-prctl.qhc" latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." python-prctl-1.7/README0000644000175000017500000000205013232713574015472 0ustar dennisdennis00000000000000python-prctl -- Control process attributes through prctl ======================================================== The linux prctl function allows you to control specific characteristics of a process' behaviour. Usage of the function is fairly messy though, due to limitations in C and linux. This module provides a nice non-messy python(ic) interface. Besides prctl, this library also wraps libcap for complete capability handling and allows you to set the process name as seen in ps and top. See docs/index.rst for the documentation. An HTML version can be found on http://packages.python.org/python-prctl/ Quick install instructions ========================== Before installing python-prctl, you need GCC, libc headers and libcap headers. On Debian/Ubuntu: $ sudo apt-get install build-essential libcap-dev On fedora: $ sudo yum install gcc glibc-devel libcap-devel Stable version: $ sudo easy_install python-prctl Latest code: $ git clone http://github.com/seveas/python-prctl $ cd python-prctl $ python setup.py build $ sudo python setup.py install python-prctl-1.7/PKG-INFO0000644000175000017500000000122213232713575015710 0ustar dennisdennis00000000000000Metadata-Version: 1.1 Name: python-prctl Version: 1.7 Summary: Python(ic) interface to the linux prctl syscall Home-page: http://github.com/seveas/python-prctl Author: Dennis Kaarsemaker Author-email: dennis@kaarsemaker.net License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: C Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Security python-prctl-1.7/setup.py0000755000175000017500000000447113232713574016340 0ustar dennisdennis00000000000000#!/usr/bin/python from distutils.core import setup, Extension import glob import os import subprocess import sys # Check our environment # - Need to be on linux # - Need kernel 2.6.18+ # - Need python 2.4+ # - Need gcc # - Need C headers # - Need libcap headers if not sys.platform.startswith('linux'): sys.stderr.write("This module only works on linux\n") sys.exit(1) kvers = os.uname()[2] if kvers < '2.6.18' and not os.environ.get("PRCTL_SKIP_KERNEL_CHECK",False): sys.stderr.write("This module requires linux 2.6.18 or newer\n") sys.exit(1) if sys.version_info[:2] < (2,4): sys.stderr.write("This module requires python 2.4 or newer\n") sys.exit(1) exit = False try: subprocess.call(['gcc','-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) except: sys.stderr.write("You need to install gcc to build this module\n") sys.exit(1) sp = subprocess.Popen(['cpp'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sp.communicate('#include \n'.encode()) if sp.returncode: sys.stderr.write("You need to install libc development headers to build this module\n") exit = True sp = subprocess.Popen(['cpp'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sp.communicate('#include \n'.encode()) if sp.returncode: sys.stderr.write("You need to install libcap development headers to build this module\n") exit = True if exit: sys.exit(1) _prctl = Extension("_prctl", sources = ['_prctlmodule.c'], depends = ['securebits.h'], libraries = ['cap']) setup(name = "python-prctl", version = "1.7", author = "Dennis Kaarsemaker", author_email = "dennis@kaarsemaker.net", url = "http://github.com/seveas/python-prctl", description = "Python(ic) interface to the linux prctl syscall", py_modules = ["prctl"], ext_modules = [_prctl], classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: POSIX :: Linux', 'Programming Language :: C', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Security', ] ) python-prctl-1.7/securebits.h0000644000175000017500000000162713232713574017144 0ustar dennisdennis00000000000000/* Constants as defined in the kernel headers */ #define SECURE_NOROOT 0 #define SECURE_NOROOT_LOCKED 1 #define SECURE_NO_SETUID_FIXUP 2 #define SECURE_NO_SETUID_FIXUP_LOCKED 3 #define SECURE_KEEP_CAPS 4 #define SECURE_KEEP_CAPS_LOCKED 5 #define issecure_mask(X) (1 << (X)) #define SECUREBITS_DEFAULT 0x00000000 #define SECBIT_NOROOT (issecure_mask(SECURE_NOROOT)) #define SECBIT_NOROOT_LOCKED (issecure_mask(SECURE_NOROOT_LOCKED)) #define SECBIT_NO_SETUID_FIXUP (issecure_mask(SECURE_NO_SETUID_FIXUP)) #define SECBIT_NO_SETUID_FIXUP_LOCKED \ (issecure_mask(SECURE_NO_SETUID_FIXUP_LOCKED)) #define SECBIT_KEEP_CAPS (issecure_mask(SECURE_KEEP_CAPS)) #define SECBIT_KEEP_CAPS_LOCKED (issecure_mask(SECURE_KEEP_CAPS_LOCKED)) #define SECURE_ALL_BITS (issecure_mask(SECURE_NOROOT) | \ issecure_mask(SECURE_NO_SETUID_FIXUP) | \ issecure_mask(SECURE_KEEP_CAPS)) #define SECURE_ALL_LOCKS (SECURE_ALL_BITS << 1) python-prctl-1.7/prctl.py0000644000175000017500000001546013232713574016321 0ustar dennisdennis00000000000000# python-pctrl -- python interface to the prctl function # (c)2010-2018 Dennis Kaarsemaker # See COPYING for licensing details import _prctl # The C interface import sys # Python 3.x compatibility if sys.version_info[0] >= 3: basestring = str # Code generation functions def prctl_wrapper(option): def call_prctl(arg=0): return _prctl.prctl(option, arg) return call_prctl def capb_wrapper(cap): def getter(self): return _prctl.prctl(_prctl.PR_CAPBSET_READ, cap) def setter(self, value): if value: raise ValueError("Can only drop capabilities from the bounding set, not add new ones") _prctl.prctl(_prctl.PR_CAPBSET_DROP, cap) return property(getter, setter) def cap_wrapper(cap): def getter(self): return get_caps((cap, self.flag))[self.flag][cap] def setter(self, val): set_caps((cap, self.flag, val)) return property(getter, setter) def sec_wrapper(bit): def getter(self): return bool(_prctl.prctl(_prctl.PR_GET_SECUREBITS) & bit) def setter(self, value): bits = _prctl.prctl(_prctl.PR_GET_SECUREBITS) if value: bits |= bit else: bits &= ~(bit) _prctl.prctl(_prctl.PR_SET_SECUREBITS, bits) return property(getter, setter) # Wrap the capabilities, capability bounding set and securebits in an object _ALL_FLAG_NAMES = ('CAP_EFFECTIVE', 'CAP_INHERITABLE', 'CAP_PERMITTED') _ALL_CAP_NAMES = tuple(x for x in dir(_prctl) if x.startswith('CAP_') and x not in _ALL_FLAG_NAMES) ALL_FLAG_NAMES = list(x[4:].lower() for x in _ALL_FLAG_NAMES) ALL_CAP_NAMES = list(x[4:].lower() for x in _ALL_CAP_NAMES) ALL_CAPS = tuple(getattr(_prctl,x) for x in _ALL_CAP_NAMES) ALL_FLAGS = tuple(getattr(_prctl,x) for x in _ALL_FLAG_NAMES) class Capbset(object): __slots__ = ALL_CAP_NAMES def __init__(self): for name in _ALL_CAP_NAMES: friendly_name = name[4:].lower() setattr(self.__class__, friendly_name, capb_wrapper(getattr(_prctl, name))) def drop(self, *caps): for cap in _parse_caps_simple(caps): _prctl.prctl(_prctl.PR_CAPBSET_DROP, cap) def limit(self, *caps): for cap in [x for x in ALL_CAPS if x not in _parse_caps_simple(caps)]: _prctl.prctl(_prctl.PR_CAPBSET_DROP, cap) capbset = Capbset() class Capset(object): __slots__ = ALL_CAP_NAMES + ['flag'] def __init__(self, flag): self.flag = flag for name in _ALL_CAP_NAMES: friendly_name = name[4:].lower() setattr(self.__class__, friendly_name, cap_wrapper(getattr(_prctl, name))) def drop(self, *caps): set_caps((_parse_caps_simple(caps), self.flag, False)) def limit(self, *caps): set_caps(([x for x in ALL_CAPS if x not in _parse_caps_simple(caps)], self.flag, False)) cap_effective = Capset(_prctl.CAP_EFFECTIVE) cap_inheritable = Capset(_prctl.CAP_INHERITABLE) cap_permitted = Capset(_prctl.CAP_PERMITTED) class Securebits(object): __slots__ = [name[7:].lower() for name in dir(_prctl) if name.startswith('SECBIT_')] def __init__(self): for name in dir(_prctl): if name.startswith('SECBIT_'): friendly_name = name[7:].lower() setattr(self.__class__, friendly_name, sec_wrapper(getattr(_prctl, name))) securebits = Securebits() # Copy constants from _prctl and generate the functions self = sys.modules['prctl'] for name in dir(_prctl): if name.startswith('PR_GET') or name.startswith('PR_SET') and name != 'PR_SET_PTRACER_ANY' or name.startswith('PR_CAPBSET'): # Generate a function for this option val = getattr(_prctl, name) friendly_name = name.lower()[3:] setattr(self, friendly_name, prctl_wrapper(val)) elif name.startswith('PR_'): # Add the argument constants without PR_ prefix setattr(self, name[3:], getattr(_prctl, name)) elif name.startswith('CAP_') or name.startswith('SECBIT_') or name.startswith('SECURE_'): # Add CAP_*/SECBIT_*/SECURE_* constants verbatim. You shouldn't use them anyway, # use the capbset/securebits object setattr(self, name, getattr(_prctl, name)) def _parse_caps_simple(caps): ret = [] for cap in caps: if isinstance(cap, basestring): if 'CAP_' + cap.upper() in _ALL_CAP_NAMES: cap = 'CAP_' + cap.upper() elif cap not in _ALL_CAP_NAMES: raise ValueError("Unknown capability: %s" % cap) cap = getattr(_prctl, cap) elif cap not in ALL_CAPS: raise ValueError("Unknown capability: %s" % str(cap)) ret.append(cap) return ret def _parse_caps(has_value, *args): if has_value: new_args = {(_prctl.CAP_PERMITTED,True): [], (_prctl.CAP_INHERITABLE,True): [], (_prctl.CAP_EFFECTIVE,True): [], (_prctl.CAP_PERMITTED,False): [], (_prctl.CAP_INHERITABLE,False): [], (_prctl.CAP_EFFECTIVE,False): []} else: new_args = {_prctl.CAP_PERMITTED: [], _prctl.CAP_INHERITABLE: [], _prctl.CAP_EFFECTIVE: []} for arg in args: if has_value: caps, flags, value = arg else: caps, flags = arg # Accepted format: (cap|[cap,...], flag|[flag,...]) if not (hasattr(caps, '__iter__') or hasattr(caps, '__getitem__')): caps = [caps] caps = _parse_caps_simple(caps) if not (hasattr(flags, '__iter__') or hasattr(flags, '__getitem__')): flags = [flags] for cap in caps: for flag in flags: if has_value: new_args[(flag,value)].append(cap) else: new_args[flag].append(cap) if has_value: et = list(set(new_args[(_prctl.CAP_EFFECTIVE,True)])) pt = list(set(new_args[(_prctl.CAP_PERMITTED,True)])) it = list(set(new_args[(_prctl.CAP_INHERITABLE,True)])) ef = list(set(new_args[(_prctl.CAP_EFFECTIVE,False)])) pf = list(set(new_args[(_prctl.CAP_PERMITTED,False)])) if_ = list(set(new_args[(_prctl.CAP_INHERITABLE,False)])) return (et, pt, it, ef, pf, if_) else: e = list(set(new_args[_prctl.CAP_EFFECTIVE])) p = list(set(new_args[_prctl.CAP_PERMITTED])) i = list(set(new_args[_prctl.CAP_INHERITABLE])) return (e, p, i) def get_caps(*args): return _prctl.get_caps(*_parse_caps(False, *args)) def set_caps(*args): return _prctl.set_caps(*_parse_caps(True, *args)) # Functions copied directly, not part of the prctl interface set_proctitle = _prctl.set_proctitle # Delete the init-only things del self, friendly_name, name, prctl_wrapper, cap_wrapper, capb_wrapper, sec_wrapper del Capbset, Capset, Securebits, sys, val python-prctl-1.7/test_prctl.py0000644000175000017500000004123313232713574017355 0ustar dennisdennis00000000000000# python-pctrl -- python interface to the prctl function # (c)2010-2018 Dennis Kaarsemaker # See COPYING for licensing details import distutils.util import glob import os import re import signal import sys import subprocess import unittest so = '.so' try: import sysconfig so = sysconfig.get_config_var('SO') except ImportError: pass curdir = os.path.dirname(__file__) builddir = os.path.join(curdir, 'build', 'lib.%s-%s' % (distutils.util.get_platform(), sys.version[0:3])) # Always run from the builddir if not os.path.exists(builddir) or \ not os.path.exists(os.path.join(builddir, 'prctl.py')) or \ not os.path.exists(os.path.join(builddir, '_prctl' + so)) or \ int(os.path.getmtime(os.path.join(curdir, 'prctl.py'))) > int(os.path.getmtime(os.path.join(builddir, 'prctl.py'))) or \ os.path.getmtime(os.path.join(curdir, '_prctlmodule.c')) > os.path.getmtime(os.path.join(builddir, '_prctl' + so)): sys.stderr.write("Please build the extension first, using ./setup.py build\n") sys.exit(1) sys.path.insert(0, builddir) import prctl import _prctl def require(attr): def decorator(func): if not hasattr(prctl, attr) and not hasattr(_prctl, attr): return lambda *args, **kwargs: None return func return decorator class PrctlTest(unittest.TestCase): # There are architecture specific tests arch = os.uname()[4] # prctl behaviour differs when root, so you should test as root and non-root am_root = os.geteuid() == 0 def test_constants(self): """Test whether copying of constants works""" self.assertEqual(prctl.ENDIAN_LITTLE, _prctl.PR_ENDIAN_LITTLE) self.assertEqual(prctl.SECBIT_NOROOT, _prctl.SECBIT_NOROOT) self.assertEqual(prctl.CAP_SYS_ADMIN, _prctl.CAP_SYS_ADMIN) self.assertRaises(AttributeError, getattr, prctl, 'PR_ENDIAN_LITTLE') self.assertRaises(AttributeError, getattr, prctl, 'PR_CAPBSET_READ') self.assertRaises(AttributeError, getattr, prctl, 'CAPBSET_READ') self.assertEqual(prctl.SET_PTRACER_ANY, _prctl.PR_SET_PTRACER_ANY) @require('PR_CAPBSET_READ') def test_capbset(self): """Test the get_capbset/set_capbset functions""" self.assertEqual(prctl.capbset_read(prctl.CAP_FOWNER), True) if self.am_root: self.assertEqual(prctl.capbset_drop(prctl.CAP_FOWNER), None) self.assertEqual(prctl.capbset_read(prctl.CAP_FOWNER), False) else: self.assertRaises(OSError, prctl.capbset_drop, prctl.CAP_MKNOD) self.assertRaises(ValueError, prctl.capbset_read, 999) @require('PR_CAPBSET_READ') def test_capbset_object(self): """Test manipulation of the capability bounding set via the capbset object""" self.assertEqual(prctl.capbset.sys_admin, True) if self.am_root: prctl.capbset.kill = False self.assertEqual(prctl.capbset.kill, False) self.assertEqual(prctl.capbset.sys_admin, True) prctl.capbset.drop("setgid", prctl.CAP_SETGID) self.assertEqual(prctl.capbset.setgid, False) caps = list(prctl.ALL_CAPS) caps.remove(prctl.CAP_NET_RAW) prctl.capbset.limit(*caps) self.assertEqual(prctl.capbset.net_raw, False) self.assertEqual(prctl.capbset.net_broadcast, True) else: def set_false(): prctl.capbset.kill = False self.assertRaises(OSError, set_false) def set_true(): prctl.capbset.kill = True self.assertRaises(ValueError, set_true) def unknown_attr(): prctl.capbset.foo = 1 self.assertRaises(AttributeError, unknown_attr) @require('get_child_subreaper') def test_child_subreaper(self): self.assertEqual(prctl.get_child_subreaper(), 0) prctl.set_child_subreaper(1) self.assertEqual(prctl.get_child_subreaper(), 1) prctl.set_child_subreaper(0) def test_dumpable(self): """Test manipulation of the dumpable flag""" prctl.set_dumpable(True) self.assertEqual(prctl.get_dumpable(), True) prctl.set_dumpable(False) self.assertEqual(prctl.get_dumpable(), False) self.assertRaises(TypeError, prctl.get_dumpable, "42") def test_endian(self): """Test manipulation of the endianness setting""" if self.arch == 'powerpc': # FIXME untested prctl.set_endian(prctl.ENDIAN_BIG) self.assertEqual(prctl.get_endian(), prctl.ENDIAN_BIG) prctl.set_endian(prctl.ENDIAN_LITTLE) self.assertEqual(prctl.get_endian(), prctl.ENDIAN_LITTLE) self.assertRaises(ValueError, prctl.set_endian, 999) else: self.assertRaises(OSError, prctl.get_endian) self.assertRaises(OSError, prctl.set_endian) def test_fpemu(self): """Test manipulation of the fpemu setting""" if self.arch == 'ia64': # FIXME - untested prctl.set_fpemu(prctl.FPEMU_SIGFPE) self.assertEqual(prctl.get_fpemu(), prctl.FPEMU_SIGFPE) prctl.set_fpemu(prctl.FPEMU_NOPRINT) self.assertEqual(prctl.get_fpemu(), prctl.FPEMU_NOPRINT) self.assertRaises(ValueError, prctl.set_fpexc, 999) else: self.assertRaises(OSError, prctl.get_fpemu) self.assertRaises(OSError, prctl.set_fpemu, prctl.FPEMU_SIGFPE) def test_fpexc(self): """Test manipulation of the fpexc setting""" if self.arch == 'powerpc': # FIXME - untested prctl.set_fpexc(prctl.FP_EXC_SW_ENABLE) self.assertEqual(prctl.get_fpexc() & prctl.PR_FP_EXC_SW_ENABLE, prctl.PR_FP_EXC_SW_ENABLE) self.assertRaises(ValueError, prctl.set_fpexc, 999) else: self.assertRaises(OSError, prctl.get_fpexc) self.assertRaises(OSError, prctl.set_fpexc) def test_keepcaps(self): """Test manipulation of the keepcaps setting""" prctl.set_keepcaps(True) self.assertEqual(prctl.get_keepcaps(), True) prctl.set_keepcaps(False) self.assertEqual(prctl.get_keepcaps(), False) @require('set_mce_kill') def test_mce_kill(self): """Test the MCE_KILL setting""" fd = open('/proc/sys/vm/memory_failure_early_kill') current = int(fd.read().strip()) fd.close() prctl.set_mce_kill(prctl.MCE_KILL_EARLY) self.assertEqual(prctl.get_mce_kill(), prctl.MCE_KILL_EARLY) prctl.set_mce_kill(prctl.MCE_KILL_LATE) self.assertEqual(prctl.get_mce_kill(), prctl.MCE_KILL_LATE) prctl.set_mce_kill(prctl.MCE_KILL_DEFAULT) self.assertEqual(prctl.get_mce_kill(), prctl.MCE_KILL_DEFAULT) def test_name(self): """Test setting the process name""" name = prctl.get_name().swapcase() * 16 prctl.set_name(name) self.assertEqual(prctl.get_name(), name[:15]) @require('get_no_new_privs') def test_no_new_privs(self): """Test the no_new_privs function""" self.assertEqual(prctl.get_no_new_privs(), 0) pid = os.fork() if pid: self.assertEqual(os.waitpid(pid, 0)[1], 0) else: prctl.set_no_new_privs(1) self.assertEqual(prctl.get_no_new_privs(), 1) if os.geteuid() != 0: sp = subprocess.Popen(['ping', '-c1', 'localhost'], stderr=subprocess.PIPE) sp.communicate() self.assertNotEqual(sp.returncode, 0) os._exit(0) def test_proctitle(self): """Test setting the process title, including too long titles""" title = "This is a test!" prctl.set_proctitle(title) ps_output = subprocess.Popen(['ps', '-f', '-p', '%d' % os.getpid()], stdout=subprocess.PIPE).communicate()[0].decode('ascii') self.assertTrue(ps_output.strip().endswith(title)) # This should not segfault but truncate title2 = "And this is a test too! Don't segfault." prctl.set_proctitle(title2) ps_output = subprocess.Popen(['ps', '-f', '-p', '%d' % os.getpid()], stdout=subprocess.PIPE).communicate()[0].decode('ascii') self.assertTrue(ps_output.strip().endswith(title2[:len(title)])) def test_pdeathsig(self): """Test manipulation of the pdeathsig setting""" self.assertRaises(ValueError, prctl.set_pdeathsig, 999) self.assertEqual(prctl.get_pdeathsig(), 0) prctl.set_pdeathsig(signal.SIGINT) self.assertEqual(prctl.get_pdeathsig(), signal.SIGINT) @require('set_ptracer') def test_ptracer(self): """Test manipulation of the ptracer setting""" if not os.path.exists('/proc/sys/kernel/yama'): return self.assertEqual(prctl.get_ptracer(), os.getppid()) prctl.set_ptracer(1) self.assertEqual(prctl.get_ptracer(), 1) new_pid = os.fork() if new_pid: os.waitpid(new_pid, 0) else: os._exit(0) self.assertRaises(OSError, prctl.set_ptracer, new_pid) @require('get_seccomp') def test_seccomp(self): """Test manipulation of the seccomp setting""" self.assertEqual(prctl.get_seccomp(), False) result = os.fork() if result == 0: # In child prctl.set_seccomp(True) # This should kill ourselves open('/etc/resolv.conf') # If not, kill ourselves anyway sys.exit(0) else: pid, result = os.waitpid(result, 0) self.assertTrue(os.WIFSIGNALED(result)) self.assertEqual(os.WTERMSIG(result), signal.SIGKILL) @require('PR_GET_SECUREBITS') def test_securebits(self): """Test manipulation of the securebits flag""" self.assertEqual(prctl.get_securebits(), 0) if os.geteuid() == 0: prctl.set_securebits(prctl.SECBIT_KEEP_CAPS) self.assertEqual(prctl.get_securebits(), prctl.SECBIT_KEEP_CAPS) else: self.assertRaises(OSError, prctl.set_securebits, prctl.SECBIT_KEEP_CAPS) @require('PR_GET_SECUREBITS') def test_securebits_obj(self): """Test manipulation of the securebits via the securebits object""" self.assertEqual(prctl.securebits.noroot, False) if os.geteuid() == 0: prctl.securebits.noroot = True self.assertEqual(prctl.securebits.noroot, True) self.assertEqual(prctl.securebits.no_setuid_fixup, False) prctl.securebits.noroot_locked = True def set_false(): prctl.securebits.noroot = False self.assertRaises(OSError, set_false) else: def set_true(): prctl.securebits.noroot = True self.assertRaises(OSError, set_true) @require('get_timerslack') def test_timerslack(self): """Test manipulation of the timerslack value""" default = prctl.get_timerslack() prctl.set_timerslack(1000) self.assertEqual(prctl.get_timerslack(), 1000) prctl.set_timerslack(0) self.assertEqual(prctl.get_timerslack(), default) def test_timing(self): """Test manipulation of the timing setting""" self.assertRaises(OSError, prctl.set_timing, prctl.TIMING_TIMESTAMP); self.assertEqual(prctl.get_timing(), prctl.TIMING_STATISTICAL) prctl.set_timing(prctl.TIMING_STATISTICAL) self.assertEqual(prctl.get_timing(), prctl.TIMING_STATISTICAL) @require('set_tsc') def test_tsc(self): """Test manipulation of the timestamp counter flag""" if re.match('i.86|x86_64', self.arch): prctl.set_tsc(prctl.TSC_SIGSEGV) self.assertEqual(prctl.get_tsc(), prctl.TSC_SIGSEGV) prctl.set_tsc(prctl.TSC_ENABLE) self.assertEqual(prctl.get_tsc(), prctl.TSC_ENABLE) else: # FIXME untested self.assertRaises(OSError, prctl.get_tsc) self.assertRaises(OSError, prctl.set_tsc, prctl.TSC_ENABLE) def test_unalign(self): """Test manipulation of the unaligned access setting""" if self.arch in ('ia64', 'parisc', 'powerpc', 'alpha'): # FIXME untested prctl.set_unalign(prctl.UNALIGN_NOPRINT) self.assertEqual(prctl.get_unalign(), prctl.UNALIGN_NOPRINT) prctl.set_unalign(prctl.UNALIGN_SIGBUS) self.assertEqual(prctl.get_unalign(), prctl.UNALIGN_SIGBUS) else: self.assertRaises(OSError, prctl.get_unalign) self.assertRaises(OSError, prctl.set_unalign, prctl.UNALIGN_NOPRINT) def test_getcaps(self): """Test the get_caps function""" self.assertEqual(prctl.get_caps(), {prctl.CAP_EFFECTIVE: {}, prctl.CAP_INHERITABLE: {}, prctl.CAP_PERMITTED: {}}) self.assertEqual(prctl.get_caps((prctl.CAP_SYS_ADMIN, prctl.ALL_FLAGS),(prctl.CAP_NET_ADMIN, prctl.CAP_EFFECTIVE)), {prctl.CAP_EFFECTIVE: {prctl.CAP_SYS_ADMIN: self.am_root, prctl.CAP_NET_ADMIN: self.am_root}, prctl.CAP_INHERITABLE: {prctl.CAP_SYS_ADMIN: False}, prctl.CAP_PERMITTED: {prctl.CAP_SYS_ADMIN: self.am_root}}) self.assertEqual(prctl.get_caps(([prctl.CAP_SYS_ADMIN,prctl.CAP_NET_ADMIN], [prctl.CAP_EFFECTIVE,prctl.CAP_PERMITTED])), {prctl.CAP_EFFECTIVE: {prctl.CAP_SYS_ADMIN: self.am_root, prctl.CAP_NET_ADMIN: self.am_root}, prctl.CAP_INHERITABLE: {}, prctl.CAP_PERMITTED: {prctl.CAP_SYS_ADMIN: self.am_root, prctl.CAP_NET_ADMIN: self.am_root}}) self.assertRaises(KeyError, prctl.get_caps, (prctl.CAP_SYS_ADMIN,'abc')) def fail(): prctl.get_caps((1234,prctl.ALL_FLAGS)) self.assertRaises(ValueError, fail) def test_setcaps(self): """Test the setcaps function""" if self.am_root: prctl.set_caps((prctl.CAP_SETUID, prctl.ALL_FLAGS, True)) else: self.assertRaises(OSError, prctl.set_caps, (prctl.CAP_SETUID, prctl.ALL_FLAGS, True)) self.assertEqual(prctl.get_caps((prctl.CAP_SETUID, prctl.ALL_FLAGS)), {prctl.CAP_EFFECTIVE: {prctl.CAP_SETUID: self.am_root}, prctl.CAP_PERMITTED: {prctl.CAP_SETUID: self.am_root}, prctl.CAP_INHERITABLE: {prctl.CAP_SETUID: self.am_root}}) prctl.set_caps((prctl.CAP_SETUID, prctl.ALL_FLAGS, False)) self.assertEqual(prctl.get_caps((prctl.CAP_SETUID, prctl.ALL_FLAGS)), {prctl.CAP_EFFECTIVE: {prctl.CAP_SETUID: False}, prctl.CAP_PERMITTED: {prctl.CAP_SETUID: False}, prctl.CAP_INHERITABLE: {prctl.CAP_SETUID: False}}) self.assertRaises(OSError, prctl.set_caps, (prctl.CAP_SETUID, prctl.ALL_FLAGS, True)) capabilities = [x[4:].lower() for x in dir(_prctl) if x.startswith('CAP_')] @require('cap_to_name') def test_capabilities_objects(self): for cap in self.capabilities: if cap in ('all','effective','permitted','inheritable','setuid'): continue # This one now triggers EINVAL if cap == 'wake_alarm': continue self.assertEqual(getattr(prctl.cap_effective, cap), self.am_root) self.assertEqual(getattr(prctl.cap_permitted, cap), self.am_root) self.assertEqual(getattr(prctl.cap_inheritable, cap), False) for cap in ['dac_override','mac_override','net_raw']: if self.am_root: setattr(prctl.cap_effective, cap, False) setattr(prctl.cap_permitted, cap, False) setattr(prctl.cap_inheritable, cap, False) self.assertRaises(OSError, setattr, prctl.cap_effective, cap, True) self.assertRaises(OSError, setattr, prctl.cap_permitted, cap, True) if self.am_root: setattr(prctl.cap_inheritable, cap, True) else: self.assertRaises(OSError, setattr, prctl.cap_inheritable, cap, True) if self.am_root: prctl.cap_effective.drop('linux_immutable', 'sys_boot', 'sys_pacct') self.assertEqual(prctl.cap_effective.linux_immutable, False) self.assertEqual(prctl.cap_effective.sys_boot, False) self.assertEqual(prctl.cap_effective.sys_pacct, False) caps = list(prctl.ALL_CAPS) caps.remove(prctl.CAP_SYS_NICE) prctl.cap_effective.limit(*caps) self.assertEqual(prctl.cap_effective.sys_nice, False) @require('cap_to_name') def test_captoname(self): self.assertEqual(_prctl.cap_to_name(prctl.CAP_SYS_ADMIN), 'sys_admin') if __name__ == '__main__': unittest.main() python-prctl-1.7/MANIFEST.in0000644000175000017500000000011613232713574016351 0ustar dennisdennis00000000000000include securebits.h include test_prctl.py include docs/* include MANIFEST.in