pax_global_header00006660000000000000000000000064113626736650014531gustar00rootroot0000000000000052 comment=6acd7d8eb48e3eb339240129438abf91679fd442 python-prctl-1.1.1/000077500000000000000000000000001136267366500141745ustar00rootroot00000000000000python-prctl-1.1.1/.gitignore000066400000000000000000000000461136267366500161640ustar00rootroot00000000000000build dist MANIFEST docs/_build *.pyc python-prctl-1.1.1/COPYING000066400000000000000000000013371136267366500152330ustar00rootroot00000000000000python-prctl - A python(ic) interface to the prctl syscall Copyright (C) 2010 Dennis Kaarsemaker This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . python-prctl-1.1.1/HACKING000066400000000000000000000006411136267366500151640ustar00rootroot00000000000000How to roll a release: Source preparation: - Bump version number in setup.py - Bump version number in debian/changelog - Tag the release - Push to github Packaging: - ./setup.py sdist - dpkg-buildpackage -rfakeroot - Upload tarballs and packages to kaarsemaker.net pypi: - dh clean - cd docs/_build/html - rm -f docs.zip && zip -r docs.zip * - Upload docs.zip to pypi - ./setup.py register python-prctl-1.1.1/MANIFEST.in000066400000000000000000000000721136267366500157310ustar00rootroot00000000000000include securebits.h include test_prctl.py include docs/* python-prctl-1.1.1/README000066400000000000000000000020501136267366500150510ustar00rootroot00000000000000python-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.1.1/_prctlmodule.c000066400000000000000000000371501136267366500170370ustar00rootroot00000000000000/* * python-pctrl -- python interface to the prctl function * (c)2010 Dennis Kaarsemaker #include "securebits.h" #include #include #include /* This function is not in Python.h, so define it here */ void Py_GetArgcArgv(int*, char***); /* 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) { case(PR_CAPBSET_READ): case(PR_CAPBSET_DROP): if(!cap_valid(arg)) { PyErr_SetString(PyExc_ValueError, "Unknown capability"); return NULL; } break; 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; 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; case(PR_SET_SECCOMP): if(!arg) { PyErr_SetString(PyExc_ValueError, "Argument must be 1"); return NULL; } arg = 1; break; 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; case(PR_SET_TIMING): if(arg != PR_TIMING_STATISTICAL && arg != PR_TIMING_TIMESTAMP) { PyErr_SetString(PyExc_ValueError, "Invalid timing constant"); return NULL; } break; case(PR_SET_TSC): if(arg != PR_TSC_ENABLE && arg != PR_TSC_SIGSEGV) { PyErr_SetString(PyExc_ValueError, "Invalid TSC setting"); return NULL; } break; 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) { case(PR_CAPBSET_READ): case(PR_CAPBSET_DROP): 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): case(PR_SET_PDEATHSIG): case(PR_SET_SECCOMP): case(PR_GET_SECCOMP): case(PR_SET_SECUREBITS): case(PR_GET_SECUREBITS): case(PR_SET_TIMING): case(PR_GET_TIMING): case(PR_SET_TSC): case(PR_SET_UNALIGN): result = prctl(option, arg, 0, 0, 0); if(result < 0) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } switch(option) { case(PR_CAPBSET_READ): case(PR_GET_DUMPABLE): case(PR_GET_KEEPCAPS): case(PR_GET_SECCOMP): case(PR_GET_TIMING): return PyBool_FromLong(result); case(PR_GET_SECUREBITS): return PyInt_FromLong(result); } break; case(PR_GET_ENDIAN): case(PR_GET_FPEMU): case(PR_GET_FPEXC): case(PR_GET_PDEATHSIG): case(PR_GET_TSC): case(PR_GET_UNALIGN): 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 PyString_FromString(name); } break; default: PyErr_SetString(PyExc_ValueError, "Unkown prctl option"); return NULL; } /* None is returned by default */ Py_RETURN_NONE; } /* While not part of prctl, this complements PR_SET_NAME */ static PyObject * prctl_set_proctitle(PyObject *self, PyObject *args) { int argc; char **argv; int len; char *title; if(!PyArg_ParseTuple(args, "s", &title)) { return NULL; } Py_GetArgcArgv(&argc, &argv); /* Determine up to where we can write */ len = (int)(argv[argc-1]) + strlen(argv[argc-1]) - (int)(argv[0]); strncpy(argv[0], title, len); memset(argv[0] + strlen(title), 0, len); 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; } 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 = PyString_FromString(name+4); /* Exclude the cap_ prefix */ cap_free(name); return ret; } static PyMethodDef PrctlMethods[] = { {"get_caps", prctl_get_caps, METH_VARARGS, "Get process capabilities"}, {"set_caps", prctl_set_caps, METH_VARARGS, "Set process capabilities"}, {"cap_to_name", prctl_cap_to_name, METH_VARARGS, "Convert capability number to name"}, {"prctl", prctl_prctl, METH_VARARGS, "Call prctl"}, {"set_proctitle", prctl_set_proctitle, METH_VARARGS, "Set the process title"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; /* 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 init_prctl(void) { PyObject *_prctl = Py_InitModule("_prctl", PrctlMethods); /* Add the PR_* constants */ namedconstant(PR_CAPBSET_READ); namedconstant(PR_CAPBSET_DROP); 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); namedattribute(NAME); namedattribute(PDEATHSIG); namedattribute(SECCOMP); namedattribute(SECUREBITS); namedattribute(TIMING); namedconstant(PR_TIMING_STATISTICAL); namedconstant(PR_TIMING_TIMESTAMP); namedattribute(TSC); namedconstant(PR_TSC_ENABLE); namedconstant(PR_TSC_SIGSEGV); namedattribute(UNALIGN); namedconstant(PR_UNALIGN_NOPRINT); namedconstant(PR_UNALIGN_SIGBUS); /* 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); namedconstant(CAP_SETFCAP); namedconstant(CAP_MAC_OVERRIDE); namedconstant(CAP_MAC_ADMIN); /* 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); } python-prctl-1.1.1/docs/000077500000000000000000000000001136267366500151245ustar00rootroot00000000000000python-prctl-1.1.1/docs/Makefile000066400000000000000000000061021136267366500165630ustar00rootroot00000000000000# 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.1.1/docs/conf.py000066400000000000000000000143001136267366500164210ustar00rootroot00000000000000# -*- 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, 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.0' # The full version, including alpha/beta/rc tags. release = '1.0' # 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.1.1/docs/index.rst000066400000000000000000000604751136267366500170010ustar00rootroot00000000000000======================================== 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_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(endiannes) 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 :keyword:`|` 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 threads's effective and permitted capability sets are cleared when a change is made to the threads's user IDs such that the threads'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:: set_name(flag) 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_proctitle(title) Set the process name for the calling process by overwriting the C-level :cdata:`**argv` variable. The original value of :cdata:`**argv` is then no longer visible. in :command:`ps`, :command:`proc`, or :file:`/proc/self/cmdline`. Names longer that what fits in :cdata:`**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 process 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`. .. function:: get_pdeathsig() Return the current value of the parent process death signal. See :func:`set_pdeathsig`. .. 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:: 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 unpriv‐ ileged processes are subject to full permission checking based on the process's credentials (usually: effective UID, effective GID, and sup‐ plementary 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 the :manpage:`capabilities(7)` manpage 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.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 :cdata:`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`. 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. 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 threads'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 :cfunc:`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. .. cfunction:: static PyObject\* prctl_prctl(PyObject \*self, PyObject \*args) This is the :cfunc:`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 :cfunc:`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. .. cfunction:: static PyObject\* prctl_set_proctitle(PyObject \*self, PyObject \*args) Set the process title by mangling :data:`**argv`. Mandatory argument is a :obj:`str`. .. cfunction:: 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:`SECURE_*` constants mentioned in :manpage:`prctl(2)` and :manpage:`capabilities(7)`. To avoid repeating yourself all the time, use the :cmacro:`namedconstant` and :cmacro:`namedattribute` macros when adding new values. .. toctree:: :maxdepth: 2 python-prctl-1.1.1/prctl.py000066400000000000000000000151441136267366500156770ustar00rootroot00000000000000# python-pctrl -- python interface to the prctl function # (c)2010 Dennis Kaarsemaker >sys.stderr, "This module only works on linux" sys.exit(1) kvers = os.uname()[2] if kvers < '2.6.26' and not os.environ.get("PRCTL_SKIP_KERNEL_CHECK",False): print >>sys.stderr, "This module requires linux 2.6.26 or newer" sys.exit(1) if sys.version_info[0] != 2 or sys.version_info[1] < 5: print >>sys.stderr, "This module requires python 2.5 or newer (but not 3.x)" sys.exit(1) exit = False try: subprocess.call(['gcc','-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) except: print >>sys.stderr, "You need to install gcc to build this module" exit = True sp = subprocess.Popen(['cpp'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sp.communicate('#include \n') if sp.returncode: print >>sys.stderr, "You need to install libc development headers to build this module" exit = True sp = subprocess.Popen(['cpp'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sp.communicate('#include \n') if sp.returncode: print >>sys.stderr, "You need to install libcap development headers to build this module" exit = True if exit: sys.exit(1) _prctl = Extension("_prctl", sources = ['_prctlmodule.c'], depends = ['securebits.h'], libraries = ['cap']) setup(name = "python-prctl", version = "1.1.1", 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 :: 2', 'Topic :: Security', ] ) python-prctl-1.1.1/test_prctl.py000066400000000000000000000332521136267366500167360ustar00rootroot00000000000000# python-pctrl -- python interface to the prctl function # (c)2010 Dennis Kaarsemaker 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')): print >>sys.stderr, "Please build the extension first, using ./setup.py build" sys.exit(1) sys.path.insert(0, builddir) import prctl import _prctl 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.assertEquals(prctl.ENDIAN_LITTLE, _prctl.PR_ENDIAN_LITTLE) self.assertEquals(prctl.SECURE_NOROOT, _prctl.SECURE_NOROOT) self.assertEquals(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') def test_capbset(self): """Test the get_capbset/set_capbset functions""" self.assertEquals(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) 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) 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) 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]) def test_proctitle(self): """Test setting the prcess 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] self.assertTrue(ps_output.strip().endswith(title)) # This should not segfault but truncate title2 = "And this is a test too!" prctl.set_proctitle(title2) ps_output = subprocess.Popen(['ps', '-f', '-p', '%d' % os.getpid()], stdout=subprocess.PIPE).communicate()[0] 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) 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) def test_securebits(self): """Test manipulation of the securebits flag""" self.assertEqual(prctl.get_securebits(), 0) if os.geteuid() == 0: prctl.set_securebits(1 << prctl.SECURE_KEEP_CAPS) self.assertEqual(prctl.get_securebits(), 1 << prctl.SECURE_KEEP_CAPS) else: self.assertRaises(OSError, prctl.set_securebits, 1 << prctl.SECURE_KEEP_CAPS) 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) def test_timing(self): """Test manipulation of the timing setting""" self.assertRaises(OSError, prctl.set_timing, prctl.TIMING_TIMESTAMP); self.assertEquals(prctl.get_timing(), prctl.TIMING_STATISTICAL) prctl.set_timing(prctl.TIMING_STATISTICAL) self.assertEquals(prctl.get_timing(), prctl.TIMING_STATISTICAL) def test_tsc(self): """Test manipulation of the timestamp counter flag""" if re.match('i.86', self.arch): prctl.set_tsc(prctl.TSC_SIGSEGV) self.assertEquals(prctl.get_tsc(), prctl.TSC_SIGSEGV) prctl.set_tsc(prctl.TSC_ENABLE) self.assertEquals(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 unalogned access setting""" if self.arch in ('ia64', 'parisc', 'powerpc', 'alpha'): # FIXME untested prctl.set_unalign(prctl.UNALIGN_NOPRINT) self.assertEquals(prctl.get_unalign(), prctl.UNALIGN_NOPRINT) prctl.set_unalign(prctl.UNALIGN_SIGBUS) self.assertEquals(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.assertEquals(prctl.get_caps(), {prctl.CAP_EFFECTIVE: {}, prctl.CAP_INHERITABLE: {}, prctl.CAP_PERMITTED: {}}) self.assertEquals(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.assertEquals(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_')] def test_capabilities_objects(self): for cap in self.capabilities: if cap in ('all','effective','permitted','inheritable','setuid'): continue self.assertEquals(getattr(prctl.cap_effective, cap), self.am_root) self.assertEquals(getattr(prctl.cap_permitted, cap), self.am_root) self.assertEquals(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) def test_captoname(self): self.assertEqual(_prctl.cap_to_name(prctl.CAP_SYS_ADMIN), 'sys_admin') if __name__ == '__main__': unittest.main()