pam-python-1.0.7/0000755000215700017510000000000013541422776012533 5ustar rstuartitpam-python-1.0.7/Makefile.release0000644000215700017510000002167413541422776015624 0ustar rstuartit# # Do a release. # # This is file is identical for _all_ sourceforge projects I host. It is # designed to one thing: automate my sourceforce work flow. Be warned that # I will selfishly reject any patches that don't do that. # # It does the following: # # 1. Verifies the changelogs have been updated to a consistent version. # # 2. Updates the verison numbers and copyright dates in all source files. # # 3. Builds the source tarball. # # 4. Builds the debian source and binary packages. # # 5. If there is a .spec file, buids the rpm source and binary # packages. # # 6. Sends the released files (tarball, debian and rpm packages) to the # release area. # # 7. Sends the HTML file, and other files references by it, to the web # site. # # Copyright (c) 2013,2014,2015,2016,2017,2018,2019 Russell Stuart. # Licensed (at your choice) under GPLv2, or any later version, # or AGPL-3.0+, or any later version. # RELEASE_ME=$(shell sed -n '1s/ .*//p' ChangeLog.txt) RELEASE_PACKAGE_NAME=$(shell echo "$(RELEASE_ME)" | sed 's/-[^-]*$$//') RELEASE_VERSION=$(shell echo "$(RELEASE_ME)" | sed 's/.*-//') RELEASE_YEAR=$(shell date +%Y) RELEASE_MONTH=$(shell date +%b) RELEASE_DATE=$(shell date +%Y-%m-%d) RELEASE_DEBIAN_VERSION=$(shell sed -n 's/[^(]*(\([^)]*\)).*/\1/p;q' debian/changelog) RELEASE_DIR=release.tmp RELEASE_HTDOCS=$(RELEASE_DIR)/htdocs RELEASE_FILES=$(RELEASE_DIR)/$(RELEASE_PACKAGE_NAME)-$(RELEASE_DEBIAN_VERSION) .PHONY: release release: $(RELEASE_DIR)/release.stamp $(RELEASE_DIR)/release.stamp: $(RELEASE_SOURCES) @echo ME=$(RELEASE_ME) PACKAGE=$(RELEASE_PACKAGE_NAME) VERSION=$(RELEASE_VERSION) YEAR=$(RELEASE_YEAR) MONTH=$(RELEASE_MONTH) DATE=$(RELEASE_DATE) DEBIAN_VERSION=$(RELEASE_DEBIAN_VERSION) # # Ensure the Debian changelog matches this version. # debian_version="$(RELEASE_DEBIAN_VERSION)"; [ "$(RELEASE_PACKAGE_NAME)-$${debian_version%-*}" = "$(RELEASE_ME)" ] || \ { echo 1>&2 "debian/changelog: changelog is out of date."; exit 1; } $(MAKE) release-clean # # Check changes have reflected in mercurial. # ! hg status | grep '^?' || { echo "hg add hasn't been done" 1>&2; exit 1; } ! hg status | grep '^!' || { echo "hg rm hasn't been done" 1>&2; exit 1; } [ -z "$$(hg resolv --list | grep -v ^R)" ] || { echo "There are unresolved merge conflicts" 1>&2; exit 1; } # # Update all the version numbers and dates. # set -e; for f in $(wildcard *.1); do \ sed -i "s/^\([.].\" Copyright (c) \)2[0-9]*/\1$(RELEASE_YEAR)/" "$${f}"; \ sed -i "s/^\([.]TH [A-Z]* 1 \"\)[^\"]*\(\".*Version[ ]\+\)[1-9][0-9]*[.][0-9]\+/\1$(RELEASE_MONTH) $(RELEASE_YEAR)\2$(RELEASE_VERSION)/" "$${f}"; \ done set -e; for f in $$(find . -name "*.c" -o -name "*.h"); do \ sed -i "/$(RELEASE_YEAR)/!s/\(Copyright (c) [-0-9, ]*2[0-9]*\)\(,\? *Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" "$${f}"; \ sed -i "s/^\(static.*_version..[ ]*=[ ]*\"\)[^\"]*/\1$(RELEASE_VERSION)/" "$${f}"; \ sed -i "s/^\(static.*_date..[ ]*=[ ]*\"\)[^\"]*/\1$(RELEASE_DATE)/" "$${f}"; \ done set -e; for f in $$(find . -name "*.py"); do \ sed -i 's/^\(VERSION[ ]*=[ ]*"\)[^ "]*/\1$(RELEASE_VERSION)/' $${f}; \ sed -i 's/^\(VERSION[ ]*=[ ]*"[^ ]* \+\)[^"]*/\1$(RELEASE_DATE)/' $${f}; \ done set -e; for f in $$(find . -name "*.rst" -o -name "*.py" -o -name "Makefile*") README.txt; do \ sed -i "/$(RELEASE_YEAR)/!s/\(Copyright (c) [-0-9, ]*2[0-9]*\)\(,\? *Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" "$${f}"; \ done set -e; for f in $$(find . -name "setup.py"); do \ sed -i 's/^\([ ]*version="\)[0-9]\+[.][0-9.]\+/\1$(RELEASE_VERSION)/' "$${f}"; \ done ifneq ($(wildcard $(RELEASE_PACKAGE_NAME).spec),) sed -i "s/\(Version:[ ]\+\)[0-9]\+[.][0-9.]\+/\1$(RELEASE_VERSION)/" "$(RELEASE_PACKAGE_NAME).spec" endif ifneq ($(wildcard configure.ac),) sed -i "s/\(AC_INIT(\[\?$(RELEASE_PACKAGE_NAME)\]\?, *\[\?\)[0-9]\+[.][0-9.]\+/\1$(RELEASE_VERSION)/" configure.ac endif ifneq ($(wildcard doc/conf.py),) sed -i "/$(RELEASE_YEAR)/!s/^\( *copyright *= *u'[-0-9, ]*2[0-9]*\)\(,\?[ ]*Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" doc/conf.py sed -i "s/^\( *\(version\|release\) *= *u\?'\)[0-9]\+[.][0-9.]\+'/\1$(RELEASE_VERSION)'/" doc/conf.py endif sed -i "/$(RELEASE_YEAR)/!s/\(.* is copyright © [-0-9, ]*2[0-9]*\)\(,\?[ ]*Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" "$(RELEASE_PACKAGE_NAME).html" sed -i "s/$(RELEASE_PACKAGE_NAME)-[1-9][0-9]*[.][0-9]\+/$(RELEASE_ME)/g" "$(RELEASE_PACKAGE_NAME).html" sed -i "/$(RELEASE_YEAR)/!s/\(Copyright (c) [-0-9, ]*2[0-9]*\)\(,\? *Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" README.txt # # Do any custom stuff. # $(MAKE) release-customise # # Build the release source tarball. # (set -exv; d="$${PWD##*/}" && sd=$$(echo "$$d" | sed 's/\./[.]/g') && cd .. && tar cfz "$(RELEASE_PACKAGE_NAME)_$(RELEASE_VERSION).orig.tar.gz" --exclude="$${d}/debian" --exclude="$${d}/.hg*" --exclude-vcs --transform "s;^$${sd}\(/\|\$$\);$(RELEASE_ME)\1;" "$${d}") # # Insert the debian packates into the release. # DEBIAN_KERNEL_USE_CCACHE="yes" debuild --preserve-env --preserve-envvar="PATH" -k0xF5231C62E7843A8C -sa --lintian-opts --info --display-info --display-experimental mkdir -p "$(RELEASE_FILES)" rm ../$(RELEASE_PACKAGE_NAME)_$(RELEASE_DEBIAN_VERSION)_*.build set -xve; mv $$(sed -n '1,/^Files:/d;/^$$/q;s:.* :../:p' ../$(RELEASE_PACKAGE_NAME)_$(RELEASE_DEBIAN_VERSION)_*.changes) ../$(RELEASE_PACKAGE_NAME)_$(RELEASE_DEBIAN_VERSION)_*.changes $(RELEASE_FILES) mv "$(RELEASE_FILES)/$(RELEASE_PACKAGE_NAME)_$(RELEASE_VERSION).orig.tar.gz" "$(RELEASE_FILES)/$(RELEASE_ME).tar.gz" ifneq ($(wildcard $(RELEASE_PACKAGE_NAME).spec),) # # Build the RPM package. # mkdir -p "$(RELEASE_DIR)/rpm/BUILD" mkdir -p "$(RELEASE_DIR)/rpm/RPMS" mkdir -p "$(RELEASE_DIR)/rpm/SOURCES" mkdir -p "$(RELEASE_DIR)/rpm/SPECS" mkdir -p "$(RELEASE_DIR)/rpm/SRPMS" echo >"$(RELEASE_DIR)/rpm/rpmmacros" "%_topdir $(PWD)/$(RELEASE_DIR)/rpm" TAR_OPTIONS=--wildcards rpmbuild -ta --macros "/usr/lib/rpm/macros:/usr/lib/rpm/platform/$(shell dpkg-architecture -qDEB_HOST_GNU_CPU)-$(shell dpkg-architecture -qDEB_HOST_ARCH_OS)linux/macros:/usr/lib/rpm/platform/noarch-$(shell dpkg-architecture -qDEB_HOST_ARCH_OS)/macros:$(RELEASE_DIR)/rpm/rpmmacros" "$(RELEASE_FILES)/$(RELEASE_ME).tar.gz" mv "$(RELEASE_DIR)/rpm/SRPMS/$(RELEASE_ME)-1ras.src.rpm" "$(RELEASE_FILES)" mv "$(RELEASE_DIR)/rpm/RPMS"/*/"$(RELEASE_ME)-1ras".*."rpm" "$(RELEASE_FILES)" cp ChangeLog.txt "$(RELEASE_FILES)/README.txt" endif # # Build the htdocs directory as it will appear on the host. # mkdir -p "$(RELEASE_HTDOCS)" cp -a $(RELEASE_PACKAGE_NAME).html $(RELEASE_HTDOCS) set -e; for f in $$(sed -n 's,<\(a href\|img src\)="https\?://[^"]*"[^>]*>,,;ta;:a;s/.*<\(a href\|img src\)="\([^#/"][^#"]*\)"[^>]*>/\2@@@/g;T;s/@@@\([^@]\|@[^@]\|@@[^@]\)*$$//;s/@@@/ /g;p' "$(RELEASE_PACKAGE_NAME).html"); do \ f="$${f%/}"; \ [ ."$${f%%/*}" = ."$${f}" ] || mkdir -p "$(RELEASE_HTDOCS)/$${f%/*}"; \ case "$${f}" in \ *.[12345678].html) man2html <"$${f%.html}" | sed >"$(RELEASE_HTDOCS)/$${f}" '1,2d;7,8d;/^
/,/^Time: /d';; \ *) cp -a "$${f}" "$(RELEASE_HTDOCS)/$${f}";; \ esac; \ done ln -s "$(RELEASE_PACKAGE_NAME).html" "$(RELEASE_HTDOCS)/index.html" echo "Options +Indexes" >"$(RELEASE_HTDOCS)/.htaccess" # # Verify there is no rubbish lying wround. # ! hg status | grep '^?' || { echo '.hgignore: is missing some files' 1>&2; exit 1; } touch $@ .PHONY: release-customise release-customise:: .PHONY: release-upload release-upload: release-upload-htdocs release-upload-files .PHONY: release-upload-htdocs release-upload-htdocs: $(RELEASE_DIR)/release.stamp # # Send the files that a symlink'ed first, otherwise it fails on the # 1st send. # cd $(RELEASE_DIR); rsync -avPR $$(for f in $$(find htdocs -name index.html -type l); do ff=$$(readlink "$${f}"); echo $${f%/*}/$${ff}; done) rstuart,$(RELEASE_PACKAGE_NAME)@web.sourceforge.net:. rsync -avP --delete $(RELEASE_HTDOCS)/. rstuart,$(RELEASE_PACKAGE_NAME)@web.sourceforge.net:htdocs/. .PHONY: release-upload-files release-upload-files: $(RELEASE_DIR)/release.stamp rsync -avP --delete $(RELEASE_FILES) rstuart,$(RELEASE_PACKAGE_NAME)@frs.sourceforge.net:/home/frs/project/$(RELEASE_PACKAGE_NAME)/. .PHONY: release-clean release-clean: release-project-clean -[ "$(RELEASE_CLEAN_DONE)" = "yes" -o ! -d debian ] || RELEASE_CLEAN_DONE=yes debian/rules clean [ ! -d .pc ] || { quilt pop -a; rm -r .pc; } [ ! -f Makefile-automake ] || $(MAKE) maintainer-clean rm -rf $(RELEASE_DIR) "$(RELEASE_PACKAGE_NAME).1.html" rm -rf $$(find . -name "*.orig" -o -name ".*.sw?") .PHONY: release-tag release-tag: $(RELEASE_DIR)/release.stamp ! hg status | grep '^?' || { echo "hg add hasn't been done" 1>&2; exit 1; } ! hg status | grep '^!' || { echo "hg rm hasn't been done" 1>&2; exit 1; } [ -z "$$(hg resolv --list)" ] || { echo "There are unresolved merge conflicts" 1>&2; exit 1; } [ -z "$$(hg status)" ] || \ hg commit -m "Release $(RELEASE_PACKAGE_NAME)-$(RELEASE_DEBIAN_VERSION) - see ChangeLog.txt" hg tag "$(RELEASE_PACKAGE_NAME)-$(RELEASE_DEBIAN_VERSION)" .PHONY: release-project-clean release-project-clean:: pam-python-1.0.7/doc/0000755000215700017510000000000013541422776013300 5ustar rstuartitpam-python-1.0.7/doc/Makefile0000644000215700017510000000063413541422776014743 0ustar rstuartitPREFIX ?= /usr DOCDIR ?= $(PREFIX)/share/doc/pam_python .PHONY: build build: sphinx-build -b html -E . html rm -f html/index.html && ln -s pam_python.html html/index.html .PHONY: install install-doc install: install-doc install-doc: mkdir -p $(DESTDIR)$(DOCDIR)/html cp -a html/* $(DESTDIR)$(DOCDIR)/html mkdir -p $(DESTDIR)$(DOCDIR)/examples cp -a ../examples $(DESTDIR)$(DOCDIR)/. clean: rm -rf html pam-python-1.0.7/doc/pam_python.rst0000644000215700017510000004603113541422776016214 0ustar rstuartit************** |pam_python| ************** .. toctree:: :maxdepth: 2 .. topic:: Abstract |Pam_python| is a PAM module that runs the Python interpreter, and so allows PAM modules to be written in Python. :Author: Russell Stuart .. _intro: Introduction ============ The |pam_python| PAM module runs the Python source file (aka Python PAM module) it is given in the Python interpreter, making the PAM module API available to it. This document describes the how the PAM Module API is exposed to the Python PAM module. It does not describe how to use the API. You must read the |PMWG|_ to learn how to do that. To re-iterate: this document does not tell you how to write PAM modules, it only tells you how to access the PAM module API from Python. Writing PAM modules from Python incurs a large performance penalty and requires Python to be installed, so it is not the best option for writing modules that will be used widely. On the other hand memory allocation / corruption problems can not be caused by bad Python code, and a Python module is generally shorter and easier to write than its C equivalent. This makes it ideal for the system administrator who just wants to make use of the the PAM API for his own ends while minimising the risk of introducing memory corruption problems into every program using PAM. .. _configuring: Configuring PAM =============== Tell PAM to use a Python PAM module in the usual way: add a rule to your PAM configuration. The PAM administrators manual gives the syntax of a rule as:: service type control module-path module-arguments The first three parameters are the same for all PAM modules and so aren't any different for |pam_python|. The *module-path* is the path to pam_python.so. Like all paths PAM modules it is relative to the default PAM module directory so is usually just the string ``pam_python.so``. The first *module-argument* is the path to the Python PAM module. If it doesn't start with a / it is relative to the ``/lib/security``. All *module-arguments*, including the path name to the Python PAM module are passed to it. .. _module: Python PAM modules ================== When a PAM handle created by the applications call to PAM's :samp:`pam_start()` function first uses a Python PAM module, |pam_python| invokes it using Python's ``execfile`` function. The following variables are passed to the invoked module in its global namespace: .. data:: __builtins__ The usual Python ``__builtins__``. .. data:: __file__ The absolute path name to the Python PAM module. As described in the |PMWG|, PAM interacts with your module by calling methods you provide in it. Each ``type`` in the PAM configuration rules results in one or more methods being called. The Python PAM module must define the methods that will be called by each rule ``type`` it can be used with. Those methods are: .. function:: pam_sm_acct_mgmt(pamh, flags, args) The service module's implementation of PAM's :manpage:`pam_acct_mgmt(3)` interface. .. function:: pam_sm_authenticate(pamh, flags, args) The service module's implementation of PAM's :manpage:`pam_authenticate(3)` interface. .. function:: pam_sm_close_session(pamh, flags, args) The service module's implementation of PAM's :manpage:`pam_close_session(3)` interface. .. function:: pam_sm_chauthtok(pamh, flags, args) The service module's implementation of PAM's :manpage:`pam_chauthtok(3)` interface. .. function:: pam_sm_open_session(pamh, flags, args) The service module's implementation of PAM's :manpage:`pam_open_session(3)` interface. .. function:: pam_sm_setcred(pamh, flags, args) The service module's implementation of PAM's :manpage:`pam_setcred(3)` interface. The arguments and return value of all these methods are the same. The *pamh* parameter is an instance of the :class:`PamHandle` class. It is used to interact with PAM and is described in the next section. The remaining arguments are as described in the |PMWG|. All functions must return an integer, eg :const:`pamh.PAM_SUCCESS`. The valid return codes for each function are defined |PMWG|. If the Python method isn't present |pam_python| will return :const:`pamh.PAM_SYMBOL_ERR` to PAM; if the method doesn't return an integer or throws an exception :const:`pamh.PAM_SERVICE_ERR` is returned. There is one other method that in the Python PAM module that may be called by |pam_python|. It is optional: .. function:: pam_sm_end(pamh) If present this will be called when the application calls PAM's :manpage:`pam_end(3)` function. If not present nothing happens. The parameter *pamh* is the :class:`PamHandle` object. The return value is ignored. .. _pamhandle: The PamHandle Class =================== An instance of this class is automatically created for a Python PAM module when it is first referenced, (ie when it is ``execfile``'ed). It is the first argument to every Python method called by PAM. It is destroyed automatically when PAM's :c:func:`pam_end` is called, right after the ``execfile``'ed module is destroyed. If any method fails, or any access to a member fails a :exc:`PamHandle.exception` exception will be thrown. It contains the following members: .. data:: PAM_??? All the :const:`PAM_???` constants defined in the PAM include files version 1.1.1 are available. They are all read-only :class:`int`'s. .. data:: authtok The :const:`PAM_AUTHTOK` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_AUTHTOK)`, writing it results in a call :samp:`pam_set_item(PAM_AUTHTOK, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. .. data:: authtok_type The :const:`PAM_AUTHTOK_TYPE` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_AUTHTOK_TYPE)`, writing it results in a call :samp:`pam_set_item(PAM_AUTHTOK_TYPE, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. New in version 1.0.0. Only present if the version of PAM |pam_python| is compiled with supports it. .. data:: env This is a mapping representing the PAM environment. |pam_python| implements accesses and changes to it via the |pam-lib-func| :samp:`pam_getenv()`, :samp:`pam_putenv()` and :samp:`pam_getenvlist()`. The PAM environment only supports :class:`string` keys and values, and the keys may not be blank nor contain '='. .. data:: exception The exception raised by methods defined here if they fail. It is a subclass of :class:`StandardError`. Instances contain the member :const:`pam_result`, which is the error code returned by PAM. The description is the PAM error message. .. data:: libpam_version The version of PAM |pam_python| was compiled with. This is a :class:`string`. In version 0.1.0 of |pam_python| and prior this was an :class:`int` holding the version of PAM library loaded. Newer versions of PAM no longer export that value. .. data:: pamh The PAM handle, as read-only :class:`int`. Possibly useful during debugging. .. data:: py_initialized A read-only :class:`int`. If the Python interpreter was initialised before the |pam_python| module was created this is 0. Otherwise it is 1, meaning |pam_python| has called :c:func:`Py_Initialize` and will call :c:func:`Py_Finalize` when the last |pam_python| module is destroyed. .. data:: oldauthtok The :const:`PAM_OLDAUTHTOK` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_OLDAUTHTOK)`, writing it results in a call :samp:`pam_set_item(PAM_OLDAUTHTOK, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. .. data:: rhost The :const:`PAM_RHOST` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_RHOST)`, writing it results in a call :samp:`pam_set_item(PAM_RHOST, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. .. data:: ruser The :const:`PAM_RUSER` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_RUSER)`, writing it results in a call :samp:`pam_set_item(PAM_RUSER, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. .. data:: service The :const:`PAM_SERVICE` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_SERVICE)`, writing it results in a call :samp:`pam_set_item(PAM_SERVICE, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. .. data:: tty The :const:`PAM_TTY` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_TTY)`, writing it results in a call :samp:`pam_set_item(PAM_TTY, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. .. data:: user The :const:`PAM_USER` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_USER)`, writing it results in a call :samp:`pam_set_item(PAM_USER, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. .. data:: user_prompt The :const:`PAM_USER_PROMPT` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_USER_PROMPT)`, writing it results in a call :samp:`pam_set_item(PAM_USER_PROMPT, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. .. data:: xauthdata The :const:`PAM_XAUTHDATA` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_XAUTHDATA)`, writing it results in a call :samp:`pam_set_item(PAM_XAUTHDATA, value)`. Its value is a :class:`XAuthData` instance. When setting its value you don't have to use an actual :class:`XAuthData` instance, any class that contains a :class:`string` member :attr:`name` and a :class:`string` member :attr:`data` will do. New in version 1.0.0. Only present if the version of PAM |pam_python| is compiled with supports it. .. data:: xdisplay The :const:`PAM_XDISPLAY` PAM item. Reading this results in a call to the |pam-lib-func| :samp:`pam_get_item(PAM_XDISPLAY)`, writing it results in a call :samp:`pam_set_item(PAM_XDISPLAY, value)`. Its value will be either a :class:`string` or :const:`None` for the C value :c:macro:`NULL`. New in version 1.0.0. Only present if the version of PAM |pam_python| is compiled with supports it. The following methods are available: .. method:: PamHandle.Message(msg_style,msg) Creates an instance of the :class:`Message` class. The arguments become the instance members of the same name. This class is used to represent the C API's ``struct pam_message`` type. An instance has two members corresponding to the C structure members of the same name: :attr:`msg_style` an :class:`int` and :attr:`data` a :class:`string`. Instances are immutable. Instances of this class can be passed to the :meth:`conversation` method. .. method:: PamHandle.Response(resp,ret_code) Creates an instance of the :class:`Response` class. The arguments become the instance members of the same name. This class is used to represent the C API's ``struct pam_response`` type. An instance has two members corresponding to the C structure members of the same name: :attr:`resp` a :class:`string` and :attr:`ret_code` an :class:`int`. Instances are immutable. Instances of this class are returned by the :meth:`conversation` method. .. method:: PamHandle.XAuthData(name,data) Creates an instance of the :class:`XAuthData` class. The arguments become the instance members of the same name. This class is used to represent the C API's ``struct pam_xauth_data`` type. An instance has two members corresponding to the C structure members of the same name: :attr:`name` a :class:`string` and :attr:`data` also a :class:`string`. Instances are immutable. The :data:`xauthdata` member returns instances of this class and can be set to an instance of this class. .. method:: PamHandle.conversation(prompts) Calls the function defined by the PAM :c:macro:`PAM_CONV` item. The *prompts* argument is a :class:`Message` object or a :class:`list` of them. You don't have to pass an actual :class:`Message` object, any class that contains a :class:`string` member :attr:`msg` and a :class:`int` member :attr:`msg_style` will do. These members are used to initialise the ``struct pam_message`` members of the same name. It returns either a single :class:`Response` object if a single :class:`Message` was passed, or a :class:`list` of them of the same length as the :class:`list` passed. These :class:`Response` objects contain the data the user entered. .. method:: PamHandle.fail_delay(delay) This results in a call to the |pam-lib-func| :samp:`pam_fail_delay()`, which sets the maximum random delay after an authentication failure to *delay* milliseconds. .. method:: PamHandle.get_user([prompt]) This results in a call to the |pam-lib-func| :samp:`pam_get_user()`, which returns the current user name (a :class:`string`) or :const:`None` if :samp:`pam_get_user()` returns :c:macro:`NULL`. If not known it asks the PAM application for the user name, giving it the :class:`string` *prompt* parameter to prompt the user to enter it. .. method:: PamHandle.strerror(errnum) This results in a call to the |pam-lib-func| :samp:`pam_strerror()`, which returns a :class:`string` description of the :class:`int` PAM return value *errnum*. There is no interface provided for the |pam-lib-func|\s :samp:`pam_get_data()` and :samp:`pam_set_data()`. There are two reasons for this. Firstly those two methods are provided so C code can have private storage local to the PAM handle. A Python PAM Module can use own module name space to do the same job, and it's easier to do so. But more importantly it's safer because there is no type-safe way of providing access to the facility from Python. .. _diagnostics: Diagnostics, Debugging, Bugs ============================ The way |pam_python| operates will be foreign to most Python programmers. It embeds Python into existing programs, primarily ones written in C. This means things like debugging and diagnostics are done differently to a normal Python program. .. _return-values: Diagnostics ----------- If |pam_python| returns something other than :const:`PAM_SUCCESS` to PAM a message will be written to the ``syslog`` ``LOG_AUTHPRIV`` facility. The only exception to this is when |pam_python| is passing on the return value from a Python :meth:`pam_sm_...` entry point - nothing is logged in that case. So, if your Python PAM Module is failing in mysterious ways check the log file your system is configured to write ``LOG_AUTHPRIV`` entries to. Usually this is :file:`/var/log/syslog` or :file:`/var/log/auth.log`. The diagnostic or traceback Python would normally print to :attr:`sys.stderr` will be in there. The PAM result codes returned directly by |pam_python| are: .. data:: PAM_BUF_ERR Memory allocation failed. .. data:: PAM_MODULE_UNKNOWN The Python PAM module name wasn't supplied. .. data:: PAM_OPEN_ERR The Python PAM module could not be opened. .. data:: PAM_SERVICE_ERR A Python exception was thrown, unless it was because of a memory allocation failure. .. data:: PAM_SYMBOL_ERR A :meth:`pam_sm_...` called by PAM wasn't defined by the Python PAM module. .. _debugging: Debugging --------- If you have Python bindings for the PAM Application library then you can write test units in Python and use Pythons :mod:`pdb` module debug a Python PAM module. This is how |pam_python| was developed. I used `PyPAM `_ for the Python Application library bindings. Distributions often package it as ``python-pam``. To set breakpoints in :mod:`pdb` either wait until PAM has loaded your module, or :keyword:`import` it before you start debugging. .. _bugs: Bugs ---- There are several design decisions you may stumble across when using |pam_python|. One is that the Python PAM module is isolated from the rest of the Python environment. This differs from a :keyword:`import`'ed Python module, where regardless of how many times a module is imported there is only one copy that shares the one global name space. For example, if you :keyword:`import` your Python PAM module and then debug it as suggested above then there will be 2 copies of your Python PAM module in memory - the imported one and the one PAM is using. If the PAM module sets a global variable you won't see it in the :keyword:`import`'ed one. Indeed, obtaining any sort of handle to the module PAM is using is near impossible. This means the debugger can inspect variables in the module only when a breakpoint has one of the modules functions in its backtrace. There are a few of reasons for this. Firstly, the |PMWG| says this is the way it should be, so |pam_python| encourages it. Secondly, if a PAM application is using a Python PAM Module it's important the PAM module remains as near to invisible as possible to avoid conflicts. Finally, and most importantly, references to objects constructed by the Python PAM module must never leak. This is because the destructors to those objects are C functions that live in |pam_python|, and those destructors are called when all references to the objects are gone. When the application calls |pam-lib-func| :samp:`pam_end()` function |pam_python| is unloaded, and with it goes the destructor code. Should a reference to an object defined by |pam_python| exist after :samp:`pam_end()` returns the call to destructor will result in a jump to a non-existent address causing a ``SIGSEGV``. Another potential trap is the initialisation and finalisation of the Python interpreter itself. Calling the interpreter's finalisation routine while it is in use would I imagine be a big no-no. If |pam_python| has to initialise the interpreter (by calling :c:func:`Py_Initialize`) then it will call its finaliser :c:func:`Py_Finalize` when the last Python PAM module is destroyed. This is heuristic works in most scenarios. One example where is won't work is a sequence like:: start-python-pam-module; application-initialises-interpreter; stop-python-pam-module; application-stops-interpreter. The above is doomed to fail. .. _example: An example ========== This is one of the examples provided by the package: .. include:: pam_permit.py :literal: Assuming it and ``pam_python.so`` are in the directory ``/lib/security`` adding these rules to ``/etc/pam.conf`` would run it:: login account requisite pam_python.so pam_accept.py login auth requisite pam_python.so pam_accept.py login password requisite pam_python.so pam_accept.py login session requisite pam_python.so pam_accept.py .. |PMWG| replace:: PAM Module Writers Guide .. _PMWG: http://www.linux-pam.org/Linux-PAM-html/ .. |pam_python| replace:: `pam_python` .. |pam-lib-func| replace:: PAM library function pam-python-1.0.7/doc/conf.py0000644000215700017510000000037013541422776014577 0ustar rstuartitmaster_doc = 'pam_python' project = u'pam_python' copyright = u'2010,2014,2016,2019, Russell Stuart' version = '1.0.7' release = '1.0.7' extensions = ['sphinx.ext.intersphinx'] intersphinx_mapping = {'python': ('http://docs.python.org/2.7', None)} pam-python-1.0.7/doc/pam_permit.py0000644000215700017510000000113713541422776016011 0ustar rstuartit# # Duplicates pam_permit.c # DEFAULT_USER = "nobody" def pam_sm_authenticate(pamh, flags, argv): try: user = pamh.get_user(None) except pamh.exception, e: return e.pam_result if user == None: pam.user = DEFAULT_USER return pamh.PAM_SUCCESS def pam_sm_setcred(pamh, flags, argv): return pamh.PAM_SUCCESS def pam_sm_acct_mgmt(pamh, flags, argv): return pamh.PAM_SUCCESS def pam_sm_open_session(pamh, flags, argv): return pamh.PAM_SUCCESS def pam_sm_close_session(pamh, flags, argv): return pamh.PAM_SUCCESS def pam_sm_chauthtok(pamh, flags, argv): return pamh.PAM_SUCCESS pam-python-1.0.7/agpl-3.0.txt0000644000215700017510000010333012345724561014513 0ustar rstuartit GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . pam-python-1.0.7/pam-python.html0000644000215700017510000000601413541422776015516 0ustar rstuartit pam-python - write PAM modules in Python

Pam-python
Write PAM modules in Python

Pam-python is a PAM Module that runs the Python interpreter, thus allowing PAM Modules to be written in Python.

Documentation

There is a documentation page, some examples, a change log and a README.txt. The documentation page must be read in conjunction with the PAM Module Writers Guide.

Copyright and License

Pam-python is copyright © 2007-2012,2014,2016,2019 Russell Stuart. It is licensed under the GNU Affero General Public License.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

The copyright holders grant you an additional permission under Section 7 of the GNU Affero General Public License, version 3, exempting you from the requirement in Section 6 of the GNU General Public License, version 3, to accompany Corresponding Source with Installation Information for the Program or any work based on the Program. You are still required to comply with all other Section 6 requirements to provide Corresponding Source.

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 Affero General Public License for more details.

Downloading, Feedback & Contributing

Development for pam-python is hosted on Source forge:

 


Russell Stuart, 2014-May-29.

pam-python-1.0.7/examples/0000755000215700017510000000000013541422776014351 5ustar rstuartitpam-python-1.0.7/examples/pam_deny.py0000644000215700017510000000072013541422776016516 0ustar rstuartit# # Duplicates pam_deny.c # def pam_sm_authenticate(pamh, flags, argv): return pamh.PAM_AUTH_ERR def pam_sm_setcred(pamh, flags, argv): return pamh.PAM_CRED_UNAVAIL def pam_sm_acct_mgmt(pamh, flags, argv): return pamh.PAM_ACCT_EXPIRED def pam_sm_chauthtok(pamh, flags, argv): return pamh.PAM_AUTHTOK_ERR def pam_sm_open_session(pamh, flags, argv): return pamh.PAM_SYSTEM_ERR def pam_sm_close_session(pamh, flags, argv): return pamh.PAM_SYSTEM_ERR pam-python-1.0.7/examples/pam_nologin.py0000644000215700017510000000402513541422776017226 0ustar rstuartit# # Emulate what pam_nologin.c does. # import pwd # # Parse our command line. # def parse_args(pamh, argv): # # Parse the arguments. # nologin_file = "/etc/nologin" retval_when_nofile = pamh.PAM_IGNORE for arg in argv[1:]: if arg.starts_with("file="): nologin_file = arg[5:] elif arg == "successok": retval_when_nofile = pamh.PAM_SUCCESS return nologin_file, retval_when_nofile # # Check the /etc/nologin file. # def check_nologin(pamh, nologin_file, retval_when_nofile): # # Get the user name. # try: username = pamh.get_user() except pamh.exception: username = None if username == None: return pamh.PAM_USER_UNKNOWN # # Can we open the file? # try: handle = file(nologin_file, "r") except EnvironmentError: return retval_when_nofile # # Print the message. # try: try: msg = handle.read() except EnvironmentError: return pamh.PAM_SYSTEM_ERR finally: handle.close() # # Read the user's password entry so we can check if he is root. # Root can login regardless. # try: pwent = pwd.getpwnam(username) except KeyError: retval = pamh.PAM_USER_UNKNOWN msg_style = pamh.PAM_ERROR_MSG else: if pwent[2] == 0: # Is this root? retval = pamh.PAM_SUCCESS msg_style = pamh.PAM_TEXT_INFO else: retval = pamh.PAM_AUTH_ERR msg_style = pamh.PAM_ERROR_MSG # # Display the message # try: pamh.conversation(pamh.Message(msg_style, msg)) except pamh.exception: return pamh.PAM_SYSTEM_ERR return retval # # Entry points we handle. # def pam_sm_authenticate(pamh, flags, argv): nologin_file, retval_when_nofile = parse_args(pamh, argv) return check_nologin(pamh, nologin_file, retval_when_nofile) def pam_sm_setcred(pamh, flags, argv): nologin_file, retval_when_nofile = parse_args(pamh, argv) return retval_when_nofile def pam_sm_acct_mgmt(pamh, flags, argv): nologin_file, retval_when_nofile = parse_args(pamh, argv) return check_nologin(pamh, nologin_file, retval_when_nofile) pam-python-1.0.7/examples/pam_permit.py0000644000215700017510000000114013541422776017054 0ustar rstuartit# # Duplicates pam_permit.c # DEFAULT_USER = "nobody" def pam_sm_authenticate(pamh, flags, argv): try: user = pamh.get_user(None) except pamh.exception, e: return e.pam_result if user == None: pamh.user = DEFAULT_USER return pamh.PAM_SUCCESS def pam_sm_setcred(pamh, flags, argv): return pamh.PAM_SUCCESS def pam_sm_acct_mgmt(pamh, flags, argv): return pamh.PAM_SUCCESS def pam_sm_open_session(pamh, flags, argv): return pamh.PAM_SUCCESS def pam_sm_close_session(pamh, flags, argv): return pamh.PAM_SUCCESS def pam_sm_chauthtok(pamh, flags, argv): return pamh.PAM_SUCCESS pam-python-1.0.7/Makefile0000644000215700017510000000146213541422776014176 0ustar rstuartit.PHONY: all all: doc lib .PHONY: lib lib: $(MAKE) --directory src .PHONY: doc doc: $(MAKE) --directory doc .PHONY: test test: $(MAKE) --directory src $@ .PHONY: clean-pam_python clean-pam_python: rm -rf pam_python .PHONY: clean clean: clean-pam_python $(MAKE) --directory doc $@ $(MAKE) --directory src $@ .PHONY: install install: install-doc install-lib .PHONY: install-doc install-doc: clean-pam_python $(MAKE) --directory doc $@ .PHONY: install-lib install-lib: clean-pam_python $(MAKE) --directory src $@ RELEASE_SOURCES = \ ChangeLog.txt \ Makefile \ Makefile.release \ pam-python.html \ README.txt \ doc/pam_python.rst \ src/ctest.c \ src/Makefile \ src/pam_python.c \ src/setup.py \ src/test-pam_python.pam.in \ src/test.py include Makefile.release release-project-clean:: clean pam-python-1.0.7/README.txt0000644000215700017510000000433113541422776014232 0ustar rstuartitpam_python ========== pam_python is a PAM module that runs the Python interpreter and so allows PAM modules to be written in Python. There is extensive documentation shipped as reStructured text. The build system renders this in the standard Python HTML documentation style. All documentation is readable online at the home page: http://pam-python.sourceforge.net/ Dependencies ------------ Python >= 2.6, http://www.python.org pam >= 0.76, http://pam.sourceforge.net/ PyPAM (Debian package python-pam, needed for testing only) Building and Installing ----------------------- The build dependencies are: - Python2 development system, http://www.python.org - A POSIX system (make, unix shell, sed, etc). - The PAM development libraries, http://pam.sourceforge.net In addition the unit test requires: - sudo, http://www.sudo.ws/ - An account with root privileges. - PyPAM (for testing only) To build the re-distributable, in the directory containing this file run: make To install, in the directory containing this file run: make install To run the test suite, in the directory containing this file run: make test License ------- Copyright (c) 2007-2014,2016,2019 Russell Stuart. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The copyright holders grant you an additional permission under Section 7 of the GNU Affero General Public License, version 3, exempting you from the requirement in Section 6 of the GNU General Public License, version 3, to accompany Corresponding Source with Installation Information for the Program or any work based on the Program. You are still required to comply with all other Section 6 requirements to provide Corresponding Source. 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 Affero General Public License for more details. -- Russell Stuart 2014-May-29 pam-python-1.0.7/src/0000755000215700017510000000000013541422776013322 5ustar rstuartitpam-python-1.0.7/src/test.py0000644000215700017510000004662213541422776014665 0ustar rstuartit#!/usr/bin/python -W default # # This is the test script for libpython-pam. There aren't many stones # left unturned. # # Best run from the Makefile using the target 'test'. To run manually: # sudo ln -s $PWD/test-pam_python.pam /etc/pam.d # python test.py # sudo rm /etc/pam.d/test-pam_python.pam # import warnings; warnings.simplefilter('default') import os import sys TEST_PAM_MODULE = "test-pam_python.pam" TEST_PAM_USER = "root" # # A Fairly straight forward test harness. # def pam_sm_end(pamh): return test(pam_sm_end, pamh, None, None) def pam_sm_authenticate(pamh, flags, argv): return test(pam_sm_authenticate, pamh, flags, argv) def pam_sm_setcred(pamh, flags, argv): return test(pam_sm_setcred, pamh, flags, argv) def pam_sm_acct_mgmt(pamh, flags, argv): return test(pam_sm_acct_mgmt, pamh, flags, argv) def pam_sm_open_session(pamh, flags, argv): return test(pam_sm_open_session, pamh, flags, argv) def pam_sm_close_session(pamh, flags, argv): return test(pam_sm_close_session, pamh, flags, argv) def pam_sm_chauthtok(pamh, flags, argv): return test(pam_sm_chauthtok, pamh, flags, argv) def test(who, pamh, flags, argv): import test if not hasattr(test, "test_function"):# only true if not called via "main" return pamh.PAM_SUCCESS # normally happens only if run by ctest test_function = globals()[test.test_function.__name__] return test_function(test.test_results, who, pamh, flags, argv) def run_test(caller): import test test_name = caller.__name__[4:] sys.stdout.write("Testing " + test_name + " ") sys.stdout.flush() test.test_results = [] test.test_function = globals()["test_" + test_name] caller(test.test_results) sys.stdout.write("OK\n") def pam_conv(auth, query_list, userData=None): return query_list # # Verify the results match. # def assert_results(expected_results, results): for i in range(min(len(expected_results), len(results))): assert expected_results[i] == results[i], (i, expected_results[i], results[i]) if len(expected_results) < len(results): assert len(expected_results) == len(results), (i, results[len(expected_results)]) else: assert len(expected_results) == len(results), (i, expected_results[len(results)]) # # Test all the calls happen. # def test_basic_calls(results, who, pamh, flags, argv): results.append((who.func_name, flags, argv)) return pamh.PAM_SUCCESS def run_basic_calls(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) pam.acct_mgmt() pam.chauthtok() pam.open_session() pam.close_session() del pam me = os.path.join(os.getcwd(), __file__) expected_results = [ (pam_sm_authenticate.func_name, 0, [me]), (pam_sm_acct_mgmt.func_name, 0, [me, 'arg1', 'arg2']), (pam_sm_chauthtok.func_name, 16384, [me]), (pam_sm_chauthtok.func_name, 8192, [me]), (pam_sm_open_session.func_name, 0, [me]), (pam_sm_close_session.func_name, 0, [me]), (pam_sm_end.func_name, None, None)] assert_results(expected_results, results) # # Test all the constants are defined. # PAM_CONSTANTS = { # # Constants defined in _pam_types.h. The item constants are omitted. # "PAM_SUCCESS": 0, "PAM_OPEN_ERR": 1, "PAM_SYMBOL_ERR": 2, "PAM_SERVICE_ERR": 3, "PAM_SYSTEM_ERR": 4, "PAM_BUF_ERR": 5, "PAM_PERM_DENIED": 6, "PAM_AUTH_ERR": 7, "PAM_CRED_INSUFFICIENT": 8, "PAM_AUTHINFO_UNAVAIL": 9, "PAM_USER_UNKNOWN": 10, "PAM_MAXTRIES": 11, "PAM_NEW_AUTHTOK_REQD": 12, "PAM_ACCT_EXPIRED": 13, "PAM_SESSION_ERR": 14, "PAM_CRED_UNAVAIL": 15, "PAM_CRED_EXPIRED": 16, "PAM_CRED_ERR": 17, "PAM_NO_MODULE_DATA": 18, "PAM_CONV_ERR": 19, "PAM_AUTHTOK_ERR": 20, "PAM_AUTHTOK_RECOVER_ERR": 21, "PAM_AUTHTOK_RECOVERY_ERR": 21, "PAM_AUTHTOK_LOCK_BUSY": 22, "PAM_AUTHTOK_DISABLE_AGING": 23, "PAM_TRY_AGAIN": 24, "PAM_IGNORE": 25, "PAM_ABORT": 26, "PAM_AUTHTOK_EXPIRED": 27, "PAM_MODULE_UNKNOWN": 28, "PAM_BAD_ITEM": 29, "PAM_CONV_AGAIN": 30, "PAM_INCOMPLETE": 31, "PAM_SERVICE": 1, "PAM_USER": 2, "PAM_TTY": 3, "PAM_RHOST": 4, "PAM_CONV": 5, "PAM_AUTHTOK": 6, "PAM_OLDAUTHTOK": 7, "PAM_RUSER": 8, "PAM_USER_PROMPT": 9, "PAM_FAIL_DELAY": 10, "PAM_XDISPLAY": 11, "PAM_XAUTHDATA": 12, "PAM_AUTHTOK_TYPE": 13, "PAM_SILENT": 0x8000, "PAM_DISALLOW_NULL_AUTHTOK": 0x0001, "PAM_ESTABLISH_CRED": 0x0002, "PAM_DELETE_CRED": 0x0004, "PAM_REINITIALIZE_CRED": 0x0008, "PAM_REFRESH_CRED": 0x0010, "PAM_CHANGE_EXPIRED_AUTHTOK": 0x0020, "PAM_DATA_SILENT": 0x40000000, "PAM_PROMPT_ECHO_OFF": 1, "PAM_PROMPT_ECHO_ON": 2, "PAM_ERROR_MSG": 3, "PAM_TEXT_INFO": 4, "PAM_RADIO_TYPE": 5, "PAM_BINARY_PROMPT": 7, "PAM_MAX_NUM_MSG": 32, "PAM_MAX_MSG_SIZE": 512, "PAM_MAX_RESP_SIZE": 512, "_PAM_RETURN_VALUES": 32, # # Constants defined in pam_modules.h. The item constants are omitted. # "PAM_PRELIM_CHECK": 0x4000, "PAM_UPDATE_AUTHTOK": 0x2000, "PAM_DATA_REPLACE": 0x20000000, } def test_constants(results, who, pamh, flags, argv): results.append(who.func_name) if who != pam_sm_authenticate: return pamh.PAM_SUCCESS pam_constants = dict([ (var, getattr(pamh,var)) for var in dir(pamh) if var.startswith("PAM_") or var.startswith("_PAM_")]) results.append(pam_constants) try: pamh.PAM_SUCCESS = 1 results.append("Opps, pamh.PAM_SUCCESS = 1 worked!") except StandardError, e: results.append("except: %s" % e) return pamh.PAM_SUCCESS def run_constants(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) pam.close_session() del pam assert results[0] == pam_sm_authenticate.func_name, (results[0], pam_sm_authenticate.func_name) assert results[2] == "except: attribute 'PAM_SUCCESS' of 'PamHandle_type' objects is not writable", results[2] assert results[3] == pam_sm_close_session.func_name, (results[3], pam_sm_close_session.func_name) assert results[4] == pam_sm_end.func_name, (results[4], pam_sm_end.func_name) consts = results[1] for var in PAM_CONSTANTS.keys(): assert consts.has_key(var), var assert consts[var] == PAM_CONSTANTS[var], (var, consts[var], PAM_CONSTANTS[var]) for var in consts.keys(): assert PAM_CONSTANTS.has_key(var), var assert PAM_CONSTANTS[var] == consts[var], (var, PAM_CONSTANTS[var], consts[var]) assert len(results) == 5, len(results) # # Test the environment calls. # def test_environment(results, who, pamh, flags, argv): results.append(who.func_name) if who != pam_sm_acct_mgmt: return pamh.PAM_SUCCESS def test_exception(func): try: func() return str(None) except Exception, e: return e.__class__.__name__ + ": " + str(e) # # A few things to test here. First that PamEnv_as_mapping works. # results.append(len(pamh.env)) results.append(pamh.env["x1"]) pamh.env["yy"] = "y" results.append(pamh.env["yy"]) pamh.env["yy"] = "z" results.append(pamh.env["yy"]) def t(): pamh.env["yy"] = 1 results.append(test_exception(t)) del pamh.env["yy"] results.append(test_exception(lambda: pamh.env["yy"])) results.append(test_exception(lambda: pamh.env[1])) results.append(test_exception(lambda: pamh.env['a='])) results.append(test_exception(lambda: pamh.env[''])) # # Now the dict functions. # pamh.env["xx"] = "x" results.append("not in" in pamh.env) results.append("xx" in pamh.env) results.append(pamh.env.has_key("not in")) results.append(pamh.env.has_key("xx")) results.append(test_exception(lambda: pamh.env.__getitem__("not in"))) results.append(pamh.env.get("not in")) results.append(pamh.env.get("not in", "default")) results.append(pamh.env.get("xx")) results.append(pamh.env.get("xx", "default")) del pamh.env["x1"] results.append(pamh.env.items()) results.append(pamh.env.keys()) results.append(pamh.env.values()) return pamh.PAM_SUCCESS def run_environment(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) pam.putenv("x1=1") pam.putenv("x2=2") pam.putenv("x3=3") pam.acct_mgmt() pam.close_session() del pam expected_results = [ pam_sm_authenticate.func_name, pam_sm_acct_mgmt.func_name, 3, '1', 'y', 'z', 'TypeError: PAM environment value must be a string', "KeyError: 'yy'", 'TypeError: PAM environment key must be a string', "ValueError: PAM environment key can't contain '='", "ValueError: PAM environment key mustn't be 0 length", False, True, False, True, "KeyError: 'not in'", None, 'default', 'x', 'x', [('x2', '2'), ('x3', '3'), ('xx', 'x')], ['x2', 'x3', 'xx'], ['2', '3', 'x'], pam_sm_close_session.func_name, pam_sm_end.func_name] assert_results(expected_results, results) # # Test strerror(). # def test_strerror(results, who, pamh, flags, argv): results.append(who.func_name) if who != pam_sm_authenticate: return pamh.PAM_SUCCESS results.extend([(e, pamh.strerror(e).lower()) for e in (0, 1, 30, 31)]) return pamh.PAM_SUCCESS def run_strerror(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) del pam expected_results = [ pam_sm_authenticate.func_name, ( 0, 'success'), ( 1, 'failed to load module'), (30, 'conversation is waiting for event'), (31, 'application needs to call libpam again'), pam_sm_end.func_name] assert_results(expected_results, results) # # Test items. # def test_items(results, who, pamh, flags, argv): results.append(who.func_name) if not who in (pam_sm_open_session, pam_sm_close_session): return pamh.PAM_SUCCESS items = { "authtok": "authtok-module", "authtok_type": "authtok_type-module", "oldauthtok": "oldauthtok-module", "rhost": "rhost-module", "ruser": "ruser-module", "tty": "tty-module", "user_prompt": "user_prompt-module", "user": "user-module", "xdisplay": "xdisplay-module", } keys = items.keys() keys.sort() for key in keys: results.append((key, getattr(pamh, key))) value = items[key] if value != None: setattr(pamh, key, value) try: setattr(pamh, "tty", 1) results.append("%r = %r" % (key, value)) except StandardError, e: results.append("except: %s" % e) results.append(pamh.get_user("a prompt")) return pamh.PAM_SUCCESS def run_items(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) items = { 2: "user", 3: "tty", 4: "rhost", 8: "ruser", 9: "user_prompt", 11: "xdisplay", 13: "authtok_type"} items_list = items.keys() items_list.sort() for item in items_list: pam.set_item(item, items[item]) pam.open_session() pam.close_session() del pam expected_results = [ pam_sm_authenticate.func_name, pam_sm_open_session.func_name, ('authtok', None), ('authtok_type', 'authtok_type'), ('oldauthtok', None), ('rhost', 'rhost'), ('ruser', 'ruser'), ('tty', 'tty'), ('user', 'user'), ('user_prompt', 'user_prompt'), ('xdisplay', 'xdisplay'), 'except: PAM item PAM_TTY must be set to a string', 'user-module', pam_sm_close_session.func_name, ('authtok', 'authtok-module'), ('authtok_type', 'authtok_type-module'), ('oldauthtok', 'oldauthtok-module'), ('rhost', 'rhost-module'), ('ruser', 'ruser-module'), ('tty', 'tty-module'), ('user', 'user-module'), ('user_prompt', 'user_prompt-module'), ('xdisplay', 'xdisplay-module'), 'except: PAM item PAM_TTY must be set to a string', 'user-module', pam_sm_end.func_name] assert_results(expected_results, results) # # Test the xauthdata item. # def test_xauthdata(results, who, pamh, flags, argv): results.append(who.func_name) if not who in (pam_sm_open_session, pam_sm_close_session): return pamh.PAM_SUCCESS xauthdata0 = pamh.XAuthData("name-module", "data-module") pamh.xauthdata = xauthdata0 xauthdata1 = pamh.xauthdata results.append('name=%r, data=%r' % (xauthdata1.name, xauthdata1.data)) try: xauthdata2 = pamh.XAuthData(None, "x") results.append('pamh.XAuthData(%r, %r)' % (xauthdata2.name, xauthdata2.data)) except TypeError, e: results.append('except: %s' % e) try: xauthdata2 = pamh.XAuthData("x", 1) results.append('pamh.XAuthData(%r, %r)' % (xauthdata2.name, xauthdata2.data)) except TypeError, e: results.append('except: %s' % e) class XA: pass XA.name = "name-XA" XA.data = "data-XA" pamh.xauthdata = XA xauthdata2 = pamh.xauthdata results.append('name=%r, data=%r' % (xauthdata2.name, xauthdata2.data)) xa = XA() xa.name = "name-xa" xa.data = "data-xa" pamh.xauthdata = xa xauthdata4 = pamh.xauthdata results.append('name=%r, data=%r' % (xauthdata4.name, xauthdata4.data)) return pamh.PAM_SUCCESS def run_xauthdata(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) # # The PAM module doesn't support XAUTHDATA, so check what we can from the # module only. # pam.open_session() pam.close_session() del pam expected_results = [ pam_sm_authenticate.func_name, pam_sm_open_session.func_name, ("name='name-module', data='data-module'"), 'except: XAuthData() argument 1 must be string, not None', 'except: XAuthData() argument 2 must be string, not int', ("name='name-XA', data='data-XA'"), ("name='name-xa', data='data-xa'"), pam_sm_close_session.func_name, ("name='name-module', data='data-module'"), 'except: XAuthData() argument 1 must be string, not None', 'except: XAuthData() argument 2 must be string, not int', ("name='name-XA', data='data-XA'"), ("name='name-xa', data='data-xa'"), pam_sm_end.func_name] assert_results(expected_results, results) # # Test having no pam_sm_end. # def test_no_sm_end(results, who, pamh, flags, argv): results.append(who.func_name) global pam_sm_end del pam_sm_end return pamh.PAM_SUCCESS def run_no_sm_end(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) del pam expected_results = [pam_sm_authenticate.func_name] assert_results(expected_results, results) # # Test the conversation mechanism. # def test_conv(results, who, pamh, flags, argv): results.append(who.func_name) if who == pam_sm_end: return # # We must get rid of all references to pamh.Response objects. This instance # of the test.py module is running inside of libpam_python. That shared # library will be unloaded soon. Should a pamh.Response instance be # dealloc'ed after it is unloaded the now non-existant dealloc function will # be called, and a SIGSEGV will result. Normally instances would not leak, # but with the trickery we are performing with fake import's here they will # leak via the results variable unless we take special action. # def conv(convs): responses = pamh.conversation(convs) if type(responses) != type(()): return (responses.resp, responses.resp_retcode) return [(r.resp, r.resp_retcode) for r in responses] if who == pam_sm_authenticate: convs = [ pamh.Message(pamh.PAM_PROMPT_ECHO_OFF, "Prompt_echo_off"), pamh.Message(pamh.PAM_PROMPT_ECHO_ON, "Prompt_echo_on"), pamh.Message(pamh.PAM_ERROR_MSG, "Error_msg"), pamh.Message(pamh.PAM_TEXT_INFO, "Text_info")] if who == pam_sm_acct_mgmt: convs = pamh.Message(pamh.PAM_PROMPT_ECHO_OFF, "single") results.append(conv(convs)) return pamh.PAM_SUCCESS def run_conv(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) pam.acct_mgmt() del pam expected_results = [ pam_sm_authenticate.func_name, [('Prompt_echo_off', 1), ('Prompt_echo_on', 2), ('Error_msg', 3), ('Text_info', 4)], pam_sm_acct_mgmt.func_name, ('single', 1), pam_sm_end.func_name] assert_results(expected_results, results) # # Test pam error returns. # def test_pamerr(results, who, pamh, flags, argv): return results[-1] def run_pamerr(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) for err in range(0, PAM._PAM_RETURN_VALUES): results.append(err) try: pam.authenticate(0) except PAM.error, e: results[-1] = -e.args[1] del pam expected_results = [-r for r in range(PAM._PAM_RETURN_VALUES)] expected_results[25] = -6 assert_results(expected_results, results) # # Test fail_delay. # def test_fail_delay(results, who, pamh, flags, argv): pamh.fail_delay(10) return pamh.PAM_SUCCESS def run_fail_delay(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) del pam # # Test raising an exception. # def test_exceptions(results, who, pamh, flags, argv): if who != pam_sm_end: return pamh.PAM_SUCCESS # # Here we have use of a backdoor put into pam_python.c specifically # for testing raising exceptions. Oddly, normally PAM should never # return anything other than PAM_SUCCESS to anything pam_python.c # calls. # debug_magic = 0x4567abcd results.append(pamh._PAM_RETURN_VALUES) for err in range(pamh._PAM_RETURN_VALUES): try: pamh.strerror(debug_magic + err) results.append(err) except pamh.exception, e: results.append((-e.pam_result,)) return pamh.PAM_SUCCESS def run_exceptions(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) del pam expected_results = [results[0], 0] expected_results += [(-r,) for r in range(1, results[0])] assert_results(expected_results, results) # # Test absent entry point. # def test_absent(results, who, pamh, flags, argv): results.append(who.func_name) if who != pam_sm_authenticate: return pamh.PAM_SUCCESS global pam_sm_acct_mgmt; del pam_sm_acct_mgmt global pam_sm_setcred; del pam_sm_setcred global pam_sm_open_session; del pam_sm_open_session global pam_sm_close_session; del pam_sm_close_session global pam_sm_chauthtok; del pam_sm_chauthtok return pamh.PAM_SUCCESS def run_absent(results): pam = PAM.pam() pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv) pam.authenticate(0) funcs = ( pam.acct_mgmt, pam.setcred, pam.open_session, pam.close_session, pam.chauthtok ) for func in funcs: try: func(0) exception = None except Exception, e: exception = e results.append((exception.__class__.__name__, str(exception))) del pam expected_results = [ 'pam_sm_authenticate', ('error', "('Symbol not found', 2)"), ('error', "('Symbol not found', 2)"), ('error', "('Symbol not found', 2)"), ('error', "('Symbol not found', 2)"), ('error', "('Symbol not found', 2)"), ] assert_results(expected_results, results) # # Entry point. # def main(argv): run_test(run_basic_calls) run_test(run_constants) run_test(run_environment) run_test(run_strerror) run_test(run_items) run_test(run_xauthdata) run_test(run_no_sm_end) run_test(run_conv) run_test(run_pamerr) run_test(run_fail_delay) run_test(run_exceptions) run_test(run_absent) # # If run from Python run the test suite. Otherwse we are being used # as a real PAM module presumable from ctest, so just make every call # return success. # if __name__ == "__main__": import PAM main(sys.argv) pam-python-1.0.7/src/Makefile0000644000215700017510000000404213541422776014762 0ustar rstuartitall: ctest pam_python.so test-pam_python.pam WARNINGS=-Wall -Wextra -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wsign-compare -Waggregate-return -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Werror #WARNINGS=-Wunreachable-code # Gcc 4.1 .. 4.4 are too buggy to make this useful LIBDIR ?= /lib/security pam_python.so: pam_python.c setup.py Makefile @rm -f "$@" @[ ! -e build -o build/lib.*/$@ -nt setup.py -a build/lib.*/$@ -nt Makefile ] || rm -r build CFLAGS="$(WARNINGS) -I/usr/local/lib/ " ./setup.py build @#CFLAGS="-O0 $(WARNINGS)" ./setup.py build --debug @#CFLAGS="-O0 $(WARNINGS)" Py_DEBUG=1 ./setup.py build --debug ln -sf build/lib.*/$@ . .PHONY: install install-lib install: install-lib install-lib: mkdir -p $(DESTDIR)$(LIBDIR) cp build/lib.*/pam_python.so $(DESTDIR)$(LIBDIR) .PHONY: clean clean: rm -rf build ctest pam_python.so test-pam_python.pam test.pyc core [ ! -e /etc/pam.d/test-pam_python.pam ] || { s=$$([ $$(id -u) = 0 ] || echo sudo); $$s rm -f /etc/pam.d/test-pam_python.pam; } [ ! -e /etc/pam.d/test-pam_python-installed.pam ] || { s=$$([ $$(id -u) = 0 ] || echo sudo); $$s rm -f /etc/pam.d/test-pam_python-installed.pam; } .PHONY: ctest ctest: ctest.c Makefile gcc -O0 $(WARNINGS) -g -o $@ ctest.c -lpam test-pam_python.pam: test-pam_python.pam.in Makefile sed "s,\\\$$PWD,$$(pwd),g" "$@.in" >"$@.tmp" mv $@.tmp $@ /etc/pam.d/test-pam_python.pam: test-pam_python.pam s=$$([ $$(id -u) = 0 ] || echo sudo); $$s ln -sf $$(pwd)/test-pam_python.pam /etc/pam.d .PHONY: test test: pam_python.so ctest /etc/pam.d/test-pam_python.pam python test.py ./ctest test-pam_python-installed.pam: test-pam_python.pam.in Makefile sed "s,\\\$$PWD/pam-python.so,pam-python.so,;s,\\\$$PWD,$$(pwd),g" "$@.in" >"$@.tmp" mv $@.tmp $@ /etc/pam.d/test-pam_python-installed.pam: test-pam_python-installed.pam s=$$([ $$(id -u) = 0 ] || echo sudo); $$s ln -sf $$(pwd)/test-pam_python-installed.pam /etc/pam.d .PHONY: installed-test installed-test: ctest /etc/pam.d/test-pam_python-installed.pam python test.py ./ctest pam-python-1.0.7/src/ctest.c0000644000215700017510000000770113541422776014615 0ustar rstuartit/* * Best compiled & run using the Makefile target "test". To compile and run * manually: * gcc -O0 -g -Wall -o test -lpam test.c * sudo ln -s $PWD/test-pam_python.pam /etc/pam.d * ./ctest * sudo rm /etc/pam.d/test-pam_python.pam */ #define _GNU_SOURCE #ifdef __APPLE__ #include #else #include #endif #include #include #include #include #include struct walk_info { int libpam_python_seen; int python_seen; }; static int conv( int num_msg, const struct pam_message** msg, struct pam_response** resp, void *appdata_ptr) { int i; (void)appdata_ptr; *resp = malloc(num_msg * sizeof(**resp)); for (i = 0; i < num_msg; i += 1) { (*resp)[i].resp = strdup((*msg)[i].msg); (*resp)[i].resp_retcode = (*msg)[i].msg_style; } return 0; } static void call_pam( int* exit_status, const char* who, pam_handle_t* pamh, int (*func)(pam_handle_t*, int)) { int pam_result = (*func)(pamh, 0); if (pam_result == PAM_SUCCESS) return; fprintf( stderr, "%s failed: %d %s\n", who, pam_result, pam_strerror(pamh, pam_result)); *exit_status = 1; } #ifdef __APPLE__ static void walk_dlls(struct walk_info* walk_info) { int image_index; walk_info->libpam_python_seen = 0; walk_info->python_seen = 0; for (image_index = 0; image_index < _dyld_image_count(); image_index += 1) { const char* image_name = _dyld_get_image_name(image_index); if (strstr(image_name, "/pam_python.so") != 0) walk_info->libpam_python_seen = 1; if (strstr(image_name, "/libpython") != 0) walk_info->python_seen = 1; } } #else static int dl_walk(struct dl_phdr_info* info, size_t size, void* data) { struct walk_info* walk_info = data; (void)size; if (strstr(info->dlpi_name, "/pam_python.so") != 0) walk_info->libpam_python_seen = 1; if (strstr(info->dlpi_name, "/libpython") != 0) walk_info->python_seen = 1; return 0; } static void walk_dlls(struct walk_info* walk_info) { walk_info->libpam_python_seen = 0; walk_info->python_seen = 0; dl_iterate_phdr(dl_walk, walk_info); } #endif int main(int argc, char **argv) { int exit_status; struct pam_conv convstruct; pam_handle_t* pamh; struct walk_info walk_info_before; struct walk_info walk_info_after; (void)argc; (void)argv; if (access("/etc/pam.d/test-pam_python.pam", 0) != 0) { fprintf( stderr, "**WARNING**\n" " This test requires ./test-pam_python.pam configuration to be\n" " available to PAM But it doesn't appear to be in /etc/pam.d.\n" ); } printf("Testing calls from C"); fflush(stdout); convstruct.conv = conv; convstruct.appdata_ptr = 0; if (pam_start("test-pam_python.pam", "", &convstruct, &pamh) == -1) { fprintf(stderr, "pam_start failed\n"); exit(1); } exit_status = 0; call_pam(&exit_status, "pam_authenticate", pamh, pam_authenticate); call_pam(&exit_status, "pam_chauthtok", pamh, pam_chauthtok); call_pam(&exit_status, "pam_acct_mgmt", pamh, pam_acct_mgmt); call_pam(&exit_status, "pam_open_session", pamh, pam_open_session); call_pam(&exit_status, "pam_close_session", pamh, pam_close_session); walk_dlls(&walk_info_before); call_pam(&exit_status, "pam_end", pamh, pam_end); if (exit_status == 0) printf(" OK\n"); walk_dlls(&walk_info_after); printf("Testing dll load/unload "); if (!walk_info_before.libpam_python_seen) { fprintf(stderr, "It looks like pam_python.so wasn't loaded!\n"); exit_status = 1; } else if (!walk_info_before.python_seen) { fprintf(stderr, "It looks like libpythonX.Y.so wasn't loaded!\n"); exit_status = 1; } else if (walk_info_after.libpam_python_seen) { fprintf(stderr, "pam_python.so wasn't unloaded.\n"); exit_status = 1; } else if (walk_info_after.python_seen) { fprintf(stderr, "libpythonX.Y.so wasn't uloaded.\n"); exit_status = 1; } else printf("OK\n"); return exit_status; } pam-python-1.0.7/src/setup.py0000755000215700017510000000315413541422776015042 0ustar rstuartit#!/usr/bin/python -W default import warnings; warnings.simplefilter('default') import distutils.sysconfig import os import sys try: from setuptools import setup, Extension except ImportError: from distutils.core import setup, Extension long_description = """\ Embeds the Python interpreter into PAM \ so PAM modules can be written in Python""" classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)", "Natural Language :: English", "Operating System :: Unix", "Programming Language :: C", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Systems Administration :: Authentication/Directory"] if not os.environ.has_key("Py_DEBUG"): Py_DEBUG = [] else: Py_DEBUG = [('Py_DEBUG',1)] libpython_so = distutils.sysconfig.get_config_var('INSTSONAME') ext_modules = [ Extension( "pam_python", sources=["pam_python.c"], include_dirs = [], library_dirs=[], define_macros=[('LIBPYTHON_SO','"'+libpython_so+'"')] + Py_DEBUG, libraries=["pam","python%d.%d" % sys.version_info[:2]], ), ] setup( name="pam_python", version="1.0.7", description="Enabled PAM Modules to be written in Python", keywords="pam,embed,authentication,security", platforms="Unix", long_description=long_description, author="Russell Stuart", author_email="russell-pampython@stuart.id.au", url="http://pam-python.sourceforge.net/", license="AGPL-3.0", classifiers=classifiers, ext_modules=ext_modules, ) pam-python-1.0.7/src/test-pam_python.pam.in0000644000215700017510000000031412345724561017555 0ustar rstuartitauth required $PWD/pam_python.so $PWD/test.py account required $PWD/pam_python.so $PWD/test.py arg1 arg2 password required $PWD/pam_python.so $PWD/test.py session required $PWD/pam_python.so $PWD/test.py pam-python-1.0.7/src/pam_python.c0000644000215700017510000022347313541422776015657 0ustar rstuartit/* * Copyright (c) 2007-2012,2014,2016,2019 Russell Stuart * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * The copyright holders grant you an additional permission under Section 7 * of the GNU Affero General Public License, version 3, exempting you from * the requirement in Section 6 of the GNU General Public License, version 3, * to accompany Corresponding Source with Installation Information for the * Program or any work based on the Program. You are still required to * comply with all other Section 6 requirements to provide Corresponding * Source. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ #define PAM_SM_AUTH #define PAM_SM_ACCOUNT #define PAM_SM_SESSION #define PAM_SM_PASSWORD #include #ifndef __APPLE__ #include #include #else #include #include #define _PAM_RETURN_VALUES 30 // pam_types.h #endif #undef _POSIX_C_SOURCE #include #include #include #include #include #ifndef MODULE_NAME #define MODULE_NAME "libpam_python" #endif #ifndef DEFAULT_SECURITY_DIR #ifdef __APPLE__ #define DEFAULT_SECURITY_DIR "/usr/lib/pam/" #else #define DEFAULT_SECURITY_DIR "/lib/security/" #endif #endif #define PAMHANDLE_NAME "PamHandle" #define PAMHANDLEEXCEPTION_NAME "PamException" #define arr_size(x) (sizeof(x) / sizeof(*(x))) const char libpam_python_version[] = "1.0.3"; const char libpam_python_date[] = "2014-05-05"; #define PyCFunctionKwds_cast (PyCFunction)(Py_ssize_t) /* * Add typedef for Py_ssize_t if it you have an older python. */ #if (PY_VERSION_HEX < 0x02050000) typedef int Py_ssize_t; #endif /* * The python interpreter's shared library. */ static char libpython_so[] = LIBPYTHON_SO; /* * Initialise Python. How this should be done changed between versions. */ static void initialise_python(void) { #if PY_MAJOR_VERSION*100 + PY_MINOR_VERSION >= 204 Py_DontWriteBytecodeFlag = 1; Py_IgnoreEnvironmentFlag = 1; /* Py_IsolatedFlag = 1; Python3 only */ Py_NoSiteFlag = 1; Py_NoUserSiteDirectory = 1; Py_InitializeEx(0); #else size_t signum; struct sigaction oldsigaction[NSIG]; for (signum = 0; signum < arr_size(oldsigaction); signum += 1) sigaction(signum, 0, &oldsigaction[signum]); Py_Initialize(); for (signum = 0; signum < arr_size(oldsigaction); signum += 1) sigaction(signum, &oldsigaction[signum], 0); #endif } /* * The Py_XDECREF macro gives warnings. This function doesn't. */ static void py_xdecref(PyObject* object) { Py_XDECREF(object); } /* * Generic traverse function for heap objects. */ static int generic_traverse(PyObject* self, visitproc visitor, void* arg) { PyMemberDef* member; int member_visible; PyObject* object; int py_result; PyObject** slot; member = self->ob_type->tp_members; if (member == 0) return 0; /* * Loop for python visible and python non-visible members. */ for (member_visible = 0; member_visible < 2; member_visible += 1) { for (; member->name != 0; member += 1) { if (member->type != T_OBJECT && member->type != T_OBJECT_EX) continue; slot = (PyObject**)((char*)self + member->offset); object = *slot; if (object == 0) continue; py_result = visitor(object, arg); if (py_result != 0) return py_result; } member += 1; } return 0; } /* * Clear all slots in the object. */ static void clear_slot(PyObject** slot) { PyObject* object; object = *slot; if (object != 0) { *slot = 0; Py_DECREF(object); } } static int generic_clear(PyObject* self) { PyMemberDef* member; int member_visible; member = self->ob_type->tp_members; if (member == 0) return 0; /* * Loop for python visible and python non-visible members. */ for (member_visible = 0; member_visible < 2; member_visible += 1) { for (; member->name != 0; member += 1) { if (member->type != T_OBJECT && member->type != T_OBJECT_EX) continue; clear_slot((PyObject**)((char*)self + member->offset)); } member += 1; } return 0; } /* * A dealloc for all our objects. */ static void generic_dealloc(PyObject* self) { PyTypeObject* type = self->ob_type; if (PyObject_IS_GC(self)) PyObject_GC_UnTrack(self); if (type->tp_clear != 0) type->tp_clear(self); type->tp_free(self); } /* * The PamHandleObject - the object passed to all the python module's entry * points. */ typedef struct { PyObject_HEAD /* The Python Object Header */ void* dlhandle; /* dlopen() handle */ PyObject* env; /* pamh.env */ PyObject* exception; /* pamh.exception */ char* libpam_version; /* pamh.libpam_version */ PyTypeObject* message; /* pamh.Message */ PyObject* module; /* The Python Pam Module */ pam_handle_t* pamh; /* The pam handle */ PyObject* print_exception;/* traceback.print_exception */ int py_initialized; /* True if Py_initialize() called */ PyTypeObject* response; /* pamh.Response */ PyObject* syslogFile; /* A (the) SyslogFile instance */ PyTypeObject* xauthdata; /* pamh.XAuthData */ } PamHandleObject; /* * Forward declarations. */ static int call_python_handler( PyObject** result, PamHandleObject* pamHandle, PyObject* handler_function, const char* handler_name, int flags, int argc, const char** argv); /* * The SyslogfileObject. It emulates a Python file object (in that it has * a write method). It prints to stuff passed to write() on syslog. */ #define SYSLOGFILE_NAME "SyslogFile" typedef struct { PyObject_HEAD /* The Python Object Header */ char* buffer; /* Line buffer */ int size; /* Size of the buffer in bytes */ } SyslogFileObject; /* * Clear the SyslogFileObject for the garbage collector. */ static int SyslogFile_clear(PyObject* self) { SyslogFileObject* syslogFile = (SyslogFileObject*)self; PyMem_Free(syslogFile->buffer); syslogFile->buffer = 0; syslogFile->size = 0; return generic_clear(self); } /* * Emulate python's file.write(), but write to syslog. */ static PyObject* SyslogFile_write( PyObject* self, PyObject* args, PyObject* kwds) { SyslogFileObject* syslogFile = (SyslogFileObject*)self; const char* c; const char* data = 0; int len; const char* newline; PyObject* result = 0; static char* kwlist[] = {"data", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:write", kwlist, &data)) goto error_exit; if (syslogFile->buffer == 0) len = 0; else len = strlen(syslogFile->buffer); len += strlen(data) + 1; if (len > syslogFile->size) { const int new_size = len * 2; syslogFile->buffer = PyMem_Realloc(syslogFile->buffer, new_size); if (syslogFile->buffer == 0) { syslogFile->size = 0; goto error_exit; } if (syslogFile->size == 0) syslogFile->buffer[0] = '\0'; syslogFile->size = new_size; } strcat(syslogFile->buffer, data); for (c = syslogFile->buffer; *c != '\0'; c = newline + 1) { newline = strchr(c, '\n'); if (newline == 0) break; syslog(LOG_AUTHPRIV|LOG_ERR, "%.*s", (int)(newline - c), c); } if (c != syslogFile->buffer) strcpy(syslogFile->buffer, c); result = Py_None; Py_INCREF(result); error_exit: return result; } /* * Emulate python's file.flush(), but write to syslog. */ static void SyslogFile_flush(PyObject* self) { SyslogFileObject* syslogFile = (SyslogFileObject*)self; if (syslogFile->buffer != 0 && syslogFile->buffer[0] != '\0') { syslog(LOG_AUTHPRIV|LOG_ERR, "%s", syslogFile->buffer); syslogFile->buffer[0] = '\0'; } } static PyMethodDef SyslogFile_Methods[] = { { "write", PyCFunctionKwds_cast SyslogFile_write, METH_VARARGS|METH_KEYWORDS, 0 }, {0,0,0,0} /* Sentinal */ }; /* * Open syslog. */ static void syslog_open(const char* module_path) { openlog(module_path, LOG_CONS|LOG_PID, LOG_AUTHPRIV); } /* * Close syslog. */ static void syslog_close(void) { closelog(); } /* * Type to translate a Python Exception to a PAM error. */ static int syslog_python2pam(PyObject* exception_type) { if (exception_type == PyExc_MemoryError) return PAM_BUF_ERR; return PAM_SERVICE_ERR; } /* * Return the modules filename. */ static const char* get_module_path(PamHandleObject* pamHandle) { const char* result = PyModule_GetFilename(pamHandle->module); if (result != 0) return result; return MODULE_NAME; } /* * Print an exception to syslog. */ static int syslog_path_exception(const char* module_path, const char* errormsg) { PyObject* message = 0; PyObject* name = 0; PyObject* ptype = 0; PyObject* ptraceback = 0; PyObject* pvalue = 0; int pam_result = 0; PyObject* stype = 0; const char* str_name = 0; const char* str_message = 0; PyErr_Fetch(&ptype, &pvalue, &ptraceback); /* * We don't have a PamHandleObject, so we can't print a full traceback. * Just print the exception in some recognisable form, hopefully. */ syslog_open(module_path); if (PyClass_Check(ptype)) stype = PyObject_GetAttrString(ptype, "__name__"); else { stype = ptype; Py_INCREF(stype); } if (stype != 0) { name = PyObject_Str(stype); if (name != 0) str_name = PyString_AsString(name); } if (pvalue != 0) { message = PyObject_Str(pvalue); if (message != 0) str_message = PyString_AsString(message); } if (errormsg != 0 && str_name != 0 && str_message != 0) { syslog( LOG_AUTHPRIV|LOG_ERR, "%s - %s: %s", errormsg, str_name, str_message); } else if (str_name != 0 && str_message != 0) syslog(LOG_AUTHPRIV|LOG_ERR, "%s: %s", str_name, str_message); else if (errormsg != 0 && str_name != 0) syslog(LOG_AUTHPRIV|LOG_ERR, "%s - %s", errormsg, str_name); else if (errormsg != 0 && str_message != 0) syslog(LOG_AUTHPRIV|LOG_ERR, "%s - %s", errormsg, str_message); else if (errormsg != 0) syslog(LOG_AUTHPRIV|LOG_ERR, "%s", errormsg); else if (str_name != 0) syslog(LOG_AUTHPRIV|LOG_ERR, "%s", str_name); else if (str_message != 0) syslog(LOG_AUTHPRIV|LOG_ERR, "%s", str_message); pam_result = syslog_python2pam(ptype); py_xdecref(message); py_xdecref(name); py_xdecref(ptraceback); py_xdecref(ptype); py_xdecref(pvalue); py_xdecref(stype); syslog_close(); return pam_result; } /* * Print an exception to syslog, once we are initialised. */ static int syslog_exception(PamHandleObject* pamHandle, const char* errormsg) { return syslog_path_exception(get_module_path(pamHandle), errormsg); } /* * Print an message to syslog. */ static int syslog_path_vmessage( const char* module_path, const char* message, va_list ap) { syslog_open(module_path); vsyslog(LOG_AUTHPRIV|LOG_ERR, message, ap); syslog_close(); return PAM_SERVICE_ERR; } /* * Print an message to syslog. */ static int syslog_path_message( const char* module_path, const char* message, ...) { va_list ap; int result; va_start(ap, message); result = syslog_path_vmessage(module_path, message, ap); va_end(ap); return result; } /* * Print an message to syslog, once we are initialised. */ static int syslog_message(PamHandleObject* pamHandle, const char* message, ...) { va_list ap; int result; va_start(ap, message); result = syslog_path_vmessage(get_module_path(pamHandle), message, ap); va_end(ap); return result; } /* * Print a traceback to syslog. */ static int syslog_path_traceback( const char* module_path, PamHandleObject* pamHandle) { PyObject* args = 0; PyObject* ptraceback = 0; PyObject* ptype = 0; PyObject* pvalue = 0; PyObject* py_resultobj = 0; int pam_result; PyErr_Fetch(&ptype, &pvalue, &ptraceback); /* * If there isn't a traceback just log the exception. */ if (ptraceback == 0) { PyErr_Restore(ptype, pvalue, ptraceback); return syslog_path_exception(module_path, 0); } /* * Bit messy, this. The easiest way to print a traceback is to use * the traceback module, writing through a dummy file that actually * outputs to syslog. */ syslog_open(module_path); if (ptype == 0) { ptype = Py_None; Py_INCREF(ptype); } if (pvalue == 0) { pvalue = Py_None; Py_INCREF(pvalue); } args = Py_BuildValue( "OOOOO", ptype, pvalue, ptraceback, Py_None, pamHandle->syslogFile); if (args != 0) { py_resultobj = PyEval_CallObject(pamHandle->print_exception, args); if (py_resultobj != 0) SyslogFile_flush(pamHandle->syslogFile); } pam_result = syslog_python2pam(ptype); py_xdecref(args); py_xdecref(ptraceback); py_xdecref(ptype); py_xdecref(pvalue); py_xdecref(py_resultobj); syslog_close(); return pam_result; } /* * Print an message to syslog, once we are initialised. */ static int syslog_traceback(PamHandleObject* pamHandle) { return syslog_path_traceback(get_module_path(pamHandle), pamHandle); } /* * The PamMessage object - used in conversations. */ #define PAMMESSAGE_NAME "Message" typedef struct { PyObject_HEAD /* The Python Object header */ int msg_style; /* struct pam_message.msg_style */ PyObject* msg; /* struct pam_message.msg */ } PamMessageObject; static char PamMessage_doc[] = MODULE_NAME "." PAMHANDLE_NAME "." PAMMESSAGE_NAME "(msg_style, msg)\n" " Constructs an immutable object that can be passed to\n" " " MODULE_NAME "." PAMHANDLE_NAME ".conversation(). The parameters are\n" " assigned to readonly members of the same name. msg_style determines what\n" " is done (eg prompt for input, write a message), and msg is the prompt or\n" " message."; static PyMemberDef PamMessage_members[] = { { "msg_style", T_INT, offsetof(PamMessageObject, msg_style), READONLY, "What to do with the msg member, eg display it or use as a prompt.", }, { "msg", T_OBJECT_EX, offsetof(PamMessageObject, msg), READONLY, "The text to display to the user", }, {0,0,0,0,0}, /* End of Python visible members */ {0,0,0,0,0} /* Sentinal */ }; static PyObject* PamMessage_new( PyTypeObject* type, PyObject* args, PyObject* kwds) { int err; PyObject* msg = 0; int msg_style = 0; PamMessageObject* pamMessage = 0; PyObject* self = 0; static char* kwlist[] = {"msg_style", "msg", 0}; err = PyArg_ParseTupleAndKeywords( args, kwds, "iO!:Message", kwlist, &msg_style, &PyString_Type, &msg); if (!err) goto error_exit; pamMessage = (PamMessageObject*)type->tp_alloc(type, 0); if (pamMessage == 0) goto error_exit; pamMessage->msg_style = msg_style; pamMessage->msg = msg; Py_INCREF(pamMessage->msg); self = (PyObject*)pamMessage; pamMessage = 0; error_exit: py_xdecref((PyObject*)pamMessage); return self; } /* * The PamResponse object - used in conversations. */ #define PAMRESPONSE_NAME "Response" typedef struct { PyObject_HEAD /* The Python Object header */ PyObject* resp; /* struct pam_response.resp */ int resp_retcode; /* struct pam_response.resp_retcode */ } PamResponseObject; static char PamResponse_doc[] = MODULE_NAME "." PAMHANDLE_NAME "." PAMRESPONSE_NAME "(resp, resp_retcode)\n" " Constructs an immutable object that is returned by\n" " " MODULE_NAME "." PAMHANDLE_NAME ".conversation(). The parameters are\n" " assigned to readonly members of the same name. resp is the response from\n" " the user (if one was asked for), and resp_retcode says what it means."; static PyMemberDef PamResponse_members[] = { { "resp", T_OBJECT_EX, offsetof(PamResponseObject, resp), READONLY, "The response from the user.", }, { "resp_retcode", T_INT, offsetof(PamResponseObject, resp_retcode), READONLY, "The type of response.", }, {0,0,0,0,0}, /* End of Python visible members */ {0,0,0,0,0} /* Sentinal */ }; static PyObject* PamResponse_new( PyTypeObject* type, PyObject* args, PyObject* kwds) { int err; PyObject* resp = 0; int resp_retcode = 0; PamResponseObject* pamResponse = 0; PyObject* self = 0; static char* kwlist[] = {"resp", "resp_retcode", 0}; err = PyArg_ParseTupleAndKeywords( args, kwds, "Oi:Response", kwlist, &resp, &resp_retcode); if (!err) goto error_exit; if (resp != Py_None && !PyString_Check(resp)) { PyErr_SetString(PyExc_TypeError, "resp must be a string or None"); goto error_exit; } pamResponse = (PamResponseObject*)type->tp_alloc(type, 0); if (pamResponse == 0) goto error_exit; pamResponse->resp_retcode = resp_retcode; pamResponse->resp = resp; Py_INCREF(pamResponse->resp); self = (PyObject*)pamResponse; pamResponse = 0; error_exit: py_xdecref((PyObject*)pamResponse); return self; } /* * The PamXAuthData object - used by PAM_XAUTHDATA item. */ #define PAMXAUTHDATA_NAME "XAuthData" typedef struct { PyObject_HEAD /* The Python Object header */ PyObject* name; /* struct pam_xauth_data.name */ PyObject* data; /* struct pam_xauth_data.data */ } PamXAuthDataObject; static char PamXAuthData_doc[] = MODULE_NAME "." PAMHANDLE_NAME "." PAMXAUTHDATA_NAME "(name, data)\n" " Constructs an immutable object is returned by and can be passed to\n" " the " MODULE_NAME ".xauthdata property. The parameters are\n" " assigned to readonly members of the same name."; static PyMemberDef PamXAuthData_members[] = { { "data", T_OBJECT_EX, offsetof(PamXAuthDataObject, data), READONLY, "The value of the data item. A string or None.", }, { "name", T_OBJECT_EX, offsetof(PamXAuthDataObject, name), READONLY, "The name of the data item. A string or None.", }, {0,0,0,0,0}, /* End of Python visible members */ {0,0,0,0,0} /* Sentinal */ }; static PyObject* PamXAuthData_new( PyTypeObject* type, PyObject* args, PyObject* kwds) { int err; PyObject* name = 0; PyObject* data = 0; PamXAuthDataObject* pamXAuthData = 0; PyObject* self = 0; static char* kwlist[] = {"name", "data", 0}; err = PyArg_ParseTupleAndKeywords( args, kwds, "SS:XAuthData", kwlist, &name, &data); if (!err) goto error_exit; pamXAuthData = (PamXAuthDataObject*)type->tp_alloc(type, 0); if (pamXAuthData == 0) goto error_exit; pamXAuthData->name = name; Py_INCREF(pamXAuthData->name); pamXAuthData->data = data; Py_INCREF(pamXAuthData->data); self = (PyObject*)pamXAuthData; pamXAuthData = 0; error_exit: py_xdecref((PyObject*)pamXAuthData); return self; } /* * Check a PAM return value. If the function failed raise an exception * and return -1. */ static int check_pam_result(PamHandleObject* pamHandle, int pam_result) { if (pam_result == PAM_SUCCESS) return 0; if (!PyErr_Occurred()) { PyObject* ptype; PyObject* pvalue; PyObject* ptraceback; PyObject* error_code = 0; const char* error_string = pam_strerror(pamHandle->pamh, pam_result); PyErr_SetString(pamHandle->exception, error_string); PyErr_Fetch(&ptype, &pvalue, &ptraceback); PyErr_NormalizeException(&ptype, &pvalue, &ptraceback); error_code = PyInt_FromLong(pam_result); if (error_code != NULL) PyObject_SetAttrString(pvalue, "pam_result", error_code); PyErr_Restore(ptype, pvalue, ptraceback); py_xdecref(error_code); } return -1; } /* * Python getters / setters are used to manipulate PAM's items. */ static PyObject* PamHandle_get_item(PyObject* self, int item_type) { PamHandleObject* pamHandle = (PamHandleObject*)self; const char* value; PyObject* result = 0; int pam_result; pam_result = pam_get_item(pamHandle->pamh, item_type, (const void**)&value); if (check_pam_result(pamHandle, pam_result) == -1) goto error_exit; if (value != 0) result = PyString_FromString(value); else { result = Py_None; Py_INCREF(result); } error_exit: return result; } static int PamHandle_set_item( PyObject* self, int item_type, char* item_name, PyObject* pyValue) { PamHandleObject* pamHandle = (PamHandleObject*)self; int pam_result; int result = -1; char* value; char error_message[64]; if (pyValue == Py_None) value = 0; else { value = PyString_AsString(pyValue); if (value == 0) { snprintf( error_message, sizeof(error_message), "PAM item %s must be set to a string", item_name); PyErr_SetString(PyExc_TypeError, error_message); goto error_exit; } value = strdup(value); if (value == 0) { PyErr_NoMemory(); goto error_exit; } } pam_result = pam_set_item(pamHandle->pamh, item_type, value); if (pam_result == PAM_SUCCESS) value = 0; result = check_pam_result(pamHandle, pam_result); error_exit: if (value != 0) free(value); return result; } /* * The PAM Environment Object & its iterator. */ #define PAMENV_NAME "PamEnv" typedef struct { PyObject_HEAD /* The Python Object header */ PamHandleObject* pamHandle; /* The PamHandle that owns us */ PyTypeObject* pamEnvIter_type;/* A class for our iterators */ } PamEnvObject; static PyMemberDef PamEnv_Members[] = { {0,0,0,0,0}, /* End of Python visible members */ { "Iter", T_OBJECT_EX, offsetof(PamEnvObject, pamEnvIter_type), READONLY, "Iterator class for " PAMENV_NAME }, {0,0,0,0,0} /* Sentinel */ }; #define PAMENVITER_NAME "PamEnvIter" typedef struct { PyObject_HEAD PamEnvObject* env; /* The PamEnvObject we are iterating */ int pos; /* Nest position to return */ PyObject* (*get_entry)(const char* entry); /* What to return */ } PamEnvIterObject; static PyMemberDef PamEnvIter_Members[] = { {0,0,0,0,0}, /* End of Python visible members */ { "env", T_OBJECT_EX, offsetof(PamEnvIterObject, env), READONLY, "Dictionary to iterate" }, {0,0,0,0,0} /* Sentinel */ }; /* * Create a new iterator for a PamEnv. */ static PyObject* PamEnvIter_create( PamEnvObject* pamEnv, PyObject* (*get_entry)(const char* entry)) { PyTypeObject* type = pamEnv->pamEnvIter_type; PamEnvIterObject* pamEnvIter; PyObject* result = 0; pamEnvIter = (PamEnvIterObject*)type->tp_alloc(type, 0); if (pamEnvIter == 0) goto error_exit; pamEnvIter->env = pamEnv; Py_INCREF(pamEnvIter->env); pamEnvIter->get_entry = get_entry; pamEnvIter->pos = 0; result = (PyObject*)pamEnvIter; Py_INCREF(result); error_exit: py_xdecref((PyObject*)pamEnvIter); return result; } /* * Return the next object in the iteration. */ static PyObject* PamEnvIter_iternext(PyObject* self) { PamEnvIterObject* pamEnvIter = (PamEnvIterObject*)self; char** env; int i; PyObject* result; if (pamEnvIter->env == 0) goto error_exit; env = pam_getenvlist(pamEnvIter->env->pamHandle->pamh); if (env == 0) goto error_exit; for (i = 0; env[i] != 0 && i < pamEnvIter->pos; i += 1) continue; if (env[i] == 0) goto error_exit; result = pamEnvIter->get_entry(env[i]); if (result == 0) goto error_exit; pamEnvIter->pos += 1; return result; error_exit: clear_slot((PyObject**)&pamEnvIter->env); return 0; } /* * Return a python object for the key part. */ static PyObject* PamEnvIter_key_entry(const char* entry) { const char* equals; equals = strchr(entry, '='); if (equals == 0) return PyString_FromString(entry); return PyString_FromStringAndSize(entry, equals - entry); } /* * Return a python object for the value part. */ static PyObject* PamEnvIter_value_entry(const char* entry) { const char* equals; equals = strchr(entry, '='); if (equals == 0) return PyString_FromString(""); return PyString_FromString(equals + 1); } /* * Return a python object entire item. */ static PyObject* PamEnvIter_item_entry(const char* entry) { PyObject* key = 0; PyObject* result = 0; PyObject* tuple = 0; PyObject* value = 0; key = PamEnvIter_key_entry(entry); if (key == 0) goto error_exit; value = PamEnvIter_value_entry(entry); if (key == 0) goto error_exit; tuple = PyTuple_New(2); if (tuple == 0) goto error_exit; if (PyTuple_SetItem(tuple, 0, key) == -1) goto error_exit; key = 0; /* was stolen */ if (PyTuple_SetItem(tuple, 1, value) == -1) goto error_exit; value = 0; /* was stolen */ result = tuple; tuple = 0; error_exit: py_xdecref(key); py_xdecref(tuple); py_xdecref(value); return result; } /* * Create an iterator. */ static PyObject* PamEnv_iter(PyObject* self) { PamEnvObject* pamEnv = (PamEnvObject*)self; return PamEnvIter_create(pamEnv, PamEnvIter_key_entry); } /* * Get the value of a environment key. */ static const char* PamEnv_getkey(PyObject* key) { const char* result; if (!PyString_Check(key)) { PyErr_SetString(PyExc_TypeError, "PAM environment key must be a string"); return 0; } result = PyString_AS_STRING(key); if (*result == '\0') { PyErr_SetString( PyExc_ValueError, "PAM environment key mustn't be 0 length"); return 0; } if (strchr(result, '=') != 0) { PyErr_SetString(PyExc_ValueError, "PAM environment key can't contain '='"); return 0; } return result; } /* * Return the length. */ static Py_ssize_t PamEnv_mp_length(PyObject* self) { PamEnvObject* pamEnv = (PamEnvObject*)self; char** env; int length; env = pam_getenvlist(pamEnv->pamHandle->pamh); if (env == 0) return 0; for (length = 0; env[length] != 0; length += 1) continue; return length; } /* * Lookup a key returning its value. */ static PyObject* PamEnv_mp_subscript(PyObject* self, PyObject* key) { PamEnvObject* pamEnv = (PamEnvObject*)self; PyObject* result = 0; const char* key_str; const char* value; key_str = PamEnv_getkey(key); if (key_str == 0) goto error_exit; value = pam_getenv(pamEnv->pamHandle->pamh, key_str); if (value == 0) { PyErr_SetString(PyExc_KeyError, key_str); goto error_exit; } result = PyString_FromString(value); error_exit: return result; } /* * Assign a value to a key, or delete it. */ static int PamEnv_mp_assign(PyObject* self, PyObject* key, PyObject* value) { PamEnvObject* pamEnv = (PamEnvObject*)self; char* value_str = 0; int result = -1; const char* key_str; int pam_result; key_str = PamEnv_getkey(key); if (key_str == 0) goto error_exit; if (value == 0) value_str = (char*)key_str; else { if (!PyString_Check(value)) { PyErr_SetString( PyExc_TypeError, "PAM environment value must be a string"); goto error_exit; } value_str = malloc(PyString_Size(key) + 1 + PyString_Size(value) + 1); if (value_str == 0) { PyErr_NoMemory(); goto error_exit; } strcat(strcat(strcpy(value_str, key_str), "="), PyString_AS_STRING(value)); } pam_result = pam_putenv(pamEnv->pamHandle->pamh, value_str); if (pam_result != PAM_SUCCESS) // PAM_BAD_ITEM in Linux = PAM_BUF_ERR,PAM_SYSTEM_ERR { PyErr_SetString(PyExc_KeyError, key_str); goto error_exit; } if (check_pam_result(pamEnv->pamHandle, pam_result) == -1) goto error_exit; value_str = 0; result = 0; error_exit: if (value_str != key_str && value_str != 0) free(value_str); return result; } static PyMappingMethods PamEnv_as_mapping = { PamEnv_mp_length, /* mp_length */ PamEnv_mp_subscript, /* mp_subscript */ PamEnv_mp_assign, /* mp_ass_subscript */ }; /* * Check if a key is in the environment. */ static PyObject* PamEnv_has_key( PyObject* self, PyObject* args, PyObject* kwds) { PamEnvObject* pamEnv = (PamEnvObject*)self; PyObject* key; PyObject* result = 0; const char* key_str; const char* value_str; static char* kwlist[] = {"key", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:has_key", kwlist, &key)) goto error_exit; key_str = PamEnv_getkey(key); if (key_str == 0) goto error_exit; value_str = pam_getenv(pamEnv->pamHandle->pamh, key_str); result = value_str != 0 ? Py_True : Py_False; Py_INCREF(result); error_exit: return result; } /* * Lookup a key and return its value, throwing KeyError if the key * doesn't exist. */ static PyObject* PamEnv_getitem( PyObject* self, PyObject* args, PyObject* kwds) { PyObject* result = 0; PyObject* key; static char* kwlist[] = {"key", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:__getitem__", kwlist, &key)) goto error_exit; result = PamEnv_mp_subscript(self, key); error_exit: return result; } /* * Lookup a key and return its value, returning None or a default if it * doesn't exist. */ static PyObject* PamEnv_get( PyObject* self, PyObject* args, PyObject* kwds) { int err; PamEnvObject* pamEnv = (PamEnvObject*)self; PyObject* default_value = 0; PyObject* result = 0; PyObject* key; const char* key_str; const char* value_str; static char* kwlist[] = {"key", "default", NULL}; err = PyArg_ParseTupleAndKeywords( args, kwds, "O|O:get", kwlist, &key, &default_value); if (!err) goto error_exit; key_str = PamEnv_getkey(key); if (key_str == 0) goto error_exit; value_str = pam_getenv(pamEnv->pamHandle->pamh, key_str); if (value_str != 0) result = PyString_FromString(value_str); else { result = default_value != 0 ? default_value : Py_None; Py_INCREF(result); } error_exit: return result; } /* * Return all objects in the environment as a sequence. */ static PyObject* PamEnv_as_sequence( PyObject* self, PyObject* (*get_entry)(const char* entry)) { PamEnvObject* pamEnv = (PamEnvObject*)self; PyObject* list = 0; PyObject* result = 0; PyObject* entry = 0; char** env; int i; int length; env = pam_getenvlist(pamEnv->pamHandle->pamh); if (env == 0) length = 0; else { for (length = 0; env[length] != 0; length += 1) continue; } list = PyList_New(length); if (list == 0) goto error_exit; for (i = 0; env[i] != 0; i += 1) { entry = get_entry(env[i]); if (entry == 0) goto error_exit; if (PyList_SetItem(list, i, entry) == -1) goto error_exit; entry = 0; /* was stolen */ } result = list; list = 0; error_exit: py_xdecref(list); py_xdecref(entry); return result; } /* * Return all (key, value) pairs. */ static PyObject* PamEnv_items( PyObject* self, PyObject* args, PyObject* kwds) { static char* kwlist[] = {NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, ":items", kwlist)) return 0; return PamEnv_as_sequence(self, PamEnvIter_item_entry); } /* * An iterator for all (key, value) pairs. */ static PyObject* PamEnv_iteritems( PyObject* self, PyObject* args, PyObject* kwds) { PamEnvObject* pamEnv = (PamEnvObject*)self; static char* kwlist[] = {NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, ":iteritems", kwlist)) return 0; return PamEnvIter_create(pamEnv, PamEnvIter_item_entry); } /* * An iterator for the keys. */ static PyObject* PamEnv_iterkeys( PyObject* self, PyObject* args, PyObject* kwds) { PamEnvObject* pamEnv = (PamEnvObject*)self; static char* kwlist[] = {NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, ":iterkeys", kwlist)) return 0; return PamEnvIter_create(pamEnv, PamEnvIter_key_entry); } /* * An iterator for the values. */ static PyObject* PamEnv_itervalues( PyObject* self, PyObject* args, PyObject* kwds) { PamEnvObject* pamEnv = (PamEnvObject*)self; static char* kwlist[] = {NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, ":itervalues", kwlist)) return 0; return PamEnvIter_create(pamEnv, PamEnvIter_value_entry); } /* * Return all keys. */ static PyObject* PamEnv_keys( PyObject* self, PyObject* args, PyObject* kwds) { static char* kwlist[] = {NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, ":keys", kwlist)) return 0; return PamEnv_as_sequence(self, PamEnvIter_key_entry); } /* * Return all (key, value) pairs. */ static PyObject* PamEnv_values( PyObject* self, PyObject* args, PyObject* kwds) { static char* kwlist[] = {NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, ":values", kwlist)) return 0; return PamEnv_as_sequence(self, PamEnvIter_value_entry); } static PyMethodDef PamEnv_Methods[] = { {"__contains__", PyCFunctionKwds_cast PamEnv_has_key,METH_VARARGS|METH_KEYWORDS, 0}, {"__getitem__", PyCFunctionKwds_cast PamEnv_getitem,METH_VARARGS|METH_KEYWORDS, 0}, {"get", PyCFunctionKwds_cast PamEnv_get, METH_VARARGS|METH_KEYWORDS, 0}, {"has_key", PyCFunctionKwds_cast PamEnv_has_key,METH_VARARGS|METH_KEYWORDS, 0}, {"items", PyCFunctionKwds_cast PamEnv_items, METH_VARARGS|METH_KEYWORDS, 0}, {"iteritems", PyCFunctionKwds_cast PamEnv_iteritems,METH_VARARGS|METH_KEYWORDS, 0}, {"iterkeys", PyCFunctionKwds_cast PamEnv_iterkeys,METH_VARARGS|METH_KEYWORDS, 0}, {"itervalues", PyCFunctionKwds_cast PamEnv_itervalues,METH_VARARGS|METH_KEYWORDS, 0}, {"keys", PyCFunctionKwds_cast PamEnv_keys, METH_VARARGS|METH_KEYWORDS, 0}, {"values", PyCFunctionKwds_cast PamEnv_values, METH_VARARGS|METH_KEYWORDS, 0}, {0,0,0,0} /* Sentinel */ }; /* * Python Getter's for the constants. */ #define DECLARE_CONSTANT_GET_VALUE(x, v) \ static PyObject* PamHandle_Constant_ ## x(PyObject* object, void* closure) { \ object = object; \ closure = closure; \ return PyLong_FromLong(v); \ } #define DECLARE_CONSTANT_GET(x) \ static PyObject* PamHandle_Constant_ ## x(PyObject* object, void* closure) { \ object = object; \ closure = closure; \ return PyLong_FromLong(x); \ } #ifdef HAVE_PAM_FAIL_DELAY DECLARE_CONSTANT_GET_VALUE(HAVE_PAM_FAIL_DELAY, 1) #else DECLARE_CONSTANT_GET_VALUE(HAVE_PAM_FAIL_DELAY, 0) #endif DECLARE_CONSTANT_GET(PAM_ABORT) DECLARE_CONSTANT_GET(PAM_ACCT_EXPIRED) DECLARE_CONSTANT_GET(PAM_AUTH_ERR) DECLARE_CONSTANT_GET(PAM_AUTHINFO_UNAVAIL) DECLARE_CONSTANT_GET(PAM_AUTHTOK) DECLARE_CONSTANT_GET(PAM_AUTHTOK_DISABLE_AGING) DECLARE_CONSTANT_GET(PAM_AUTHTOK_ERR) DECLARE_CONSTANT_GET(PAM_AUTHTOK_EXPIRED) DECLARE_CONSTANT_GET(PAM_AUTHTOK_LOCK_BUSY) #ifdef PAM_AUTHTOK_RECOVERY_ERR DECLARE_CONSTANT_GET(PAM_AUTHTOK_RECOVERY_ERR) #endif #ifdef PAM_AUTHTOK_RECOVER_ERR DECLARE_CONSTANT_GET(PAM_AUTHTOK_RECOVER_ERR) #endif #ifdef PAM_AUTHTOK_TYPE DECLARE_CONSTANT_GET(PAM_AUTHTOK_TYPE) #endif #ifdef PAM_BAD_ITEM DECLARE_CONSTANT_GET(PAM_BAD_ITEM) #endif #ifdef PAM_BINARY_PROMPT DECLARE_CONSTANT_GET(PAM_BINARY_PROMPT) #endif DECLARE_CONSTANT_GET(PAM_BUF_ERR) DECLARE_CONSTANT_GET(PAM_CHANGE_EXPIRED_AUTHTOK) DECLARE_CONSTANT_GET(PAM_CONV) #ifdef PAM_CONV_AGAIN DECLARE_CONSTANT_GET(PAM_CONV_AGAIN) #endif DECLARE_CONSTANT_GET(PAM_CONV_ERR) DECLARE_CONSTANT_GET(PAM_CRED_ERR) DECLARE_CONSTANT_GET(PAM_CRED_EXPIRED) DECLARE_CONSTANT_GET(PAM_CRED_INSUFFICIENT) DECLARE_CONSTANT_GET(PAM_CRED_UNAVAIL) #ifdef PAM_DATA_REPLACE DECLARE_CONSTANT_GET(PAM_DATA_REPLACE) #endif #ifdef PAM_DATA_SILENT DECLARE_CONSTANT_GET(PAM_DATA_SILENT) #endif DECLARE_CONSTANT_GET(PAM_DELETE_CRED) DECLARE_CONSTANT_GET(PAM_DISALLOW_NULL_AUTHTOK) DECLARE_CONSTANT_GET(PAM_ERROR_MSG) DECLARE_CONSTANT_GET(PAM_ESTABLISH_CRED) #ifdef PAM_FAIL_DELAY DECLARE_CONSTANT_GET(PAM_FAIL_DELAY) #endif DECLARE_CONSTANT_GET(PAM_IGNORE) #ifdef PAM_INCOMPLETE DECLARE_CONSTANT_GET(PAM_INCOMPLETE) #endif DECLARE_CONSTANT_GET(PAM_MAX_MSG_SIZE) DECLARE_CONSTANT_GET(PAM_MAX_NUM_MSG) DECLARE_CONSTANT_GET(PAM_MAX_RESP_SIZE) DECLARE_CONSTANT_GET(PAM_MAXTRIES) DECLARE_CONSTANT_GET(PAM_MODULE_UNKNOWN) DECLARE_CONSTANT_GET(PAM_NEW_AUTHTOK_REQD) DECLARE_CONSTANT_GET(PAM_NO_MODULE_DATA) DECLARE_CONSTANT_GET(PAM_OLDAUTHTOK) DECLARE_CONSTANT_GET(PAM_OPEN_ERR) DECLARE_CONSTANT_GET(PAM_PERM_DENIED) DECLARE_CONSTANT_GET(PAM_PRELIM_CHECK) DECLARE_CONSTANT_GET(PAM_PROMPT_ECHO_OFF) DECLARE_CONSTANT_GET(PAM_PROMPT_ECHO_ON) #ifdef PAM_RADIO_TYPE DECLARE_CONSTANT_GET(PAM_RADIO_TYPE) #endif DECLARE_CONSTANT_GET(PAM_REFRESH_CRED) DECLARE_CONSTANT_GET(PAM_REINITIALIZE_CRED) DECLARE_CONSTANT_GET(_PAM_RETURN_VALUES) DECLARE_CONSTANT_GET(PAM_RHOST) DECLARE_CONSTANT_GET(PAM_RUSER) DECLARE_CONSTANT_GET(PAM_SERVICE) DECLARE_CONSTANT_GET(PAM_SERVICE_ERR) DECLARE_CONSTANT_GET(PAM_SESSION_ERR) DECLARE_CONSTANT_GET(PAM_SILENT) DECLARE_CONSTANT_GET(PAM_SUCCESS) DECLARE_CONSTANT_GET(PAM_SYMBOL_ERR) DECLARE_CONSTANT_GET(PAM_SYSTEM_ERR) DECLARE_CONSTANT_GET(PAM_TEXT_INFO) DECLARE_CONSTANT_GET(PAM_TRY_AGAIN) DECLARE_CONSTANT_GET(PAM_TTY) DECLARE_CONSTANT_GET(PAM_UPDATE_AUTHTOK) DECLARE_CONSTANT_GET(PAM_USER) DECLARE_CONSTANT_GET(PAM_USER_PROMPT) DECLARE_CONSTANT_GET(PAM_USER_UNKNOWN) #ifdef PAM_XAUTHDATA DECLARE_CONSTANT_GET(PAM_XAUTHDATA) #endif #ifdef PAM_XDISPLAY DECLARE_CONSTANT_GET(PAM_XDISPLAY) #endif #define CONSTANT_GETSET(x) {#x, PamHandle_Constant_ ## x, 0, 0, 0} #define MAKE_GETSET_ITEM(t) \ static PyObject* PamHandle_get_##t(PyObject* self, void* closure) \ { \ closure = closure; \ return PamHandle_get_item(self, PAM_##t); \ } \ static int PamHandle_set_##t(PyObject* self, PyObject* pyValue, void* closure) \ { \ closure = closure; \ return PamHandle_set_item(self, PAM_##t, "PAM_" #t, pyValue); \ } MAKE_GETSET_ITEM(AUTHTOK) #ifdef PAM_AUTHTOK_TYPE MAKE_GETSET_ITEM(AUTHTOK_TYPE) #endif MAKE_GETSET_ITEM(OLDAUTHTOK) MAKE_GETSET_ITEM(RHOST) MAKE_GETSET_ITEM(RUSER) MAKE_GETSET_ITEM(SERVICE) MAKE_GETSET_ITEM(TTY) MAKE_GETSET_ITEM(USER) MAKE_GETSET_ITEM(USER_PROMPT) #ifdef PAM_XDISPLAY MAKE_GETSET_ITEM(XDISPLAY) #endif #ifdef PAM_XAUTHDATA /* * The PAM_XAUTHDATA item doesn't take strings like the rest of them. * It wants a pam_xauth_data structure. */ static PyObject* PamHandle_get_XAUTHDATA(PyObject* self, void* closure) { PamHandleObject* pamHandle = (PamHandleObject*)self; PyObject* newargs = 0; PyObject* result = 0; int pam_result; struct pam_xauth_data* xauth_data = 0; closure = closure; pam_result = pam_get_item( pamHandle->pamh, PAM_XAUTHDATA, (const void**)&xauth_data); if (check_pam_result(pamHandle, pam_result) == -1) goto error_exit; if (xauth_data == 0) { result = Py_None; Py_INCREF(result); } else { newargs = Py_BuildValue( "s#s#", xauth_data->name, xauth_data->namelen, xauth_data->data, xauth_data->datalen); if (newargs == 0) goto error_exit; result = pamHandle->xauthdata->tp_new(pamHandle->xauthdata, newargs, 0); if (result == 0) goto error_exit; } error_exit: py_xdecref(newargs); return result; } static int PamHandle_set_XAUTHDATA( PyObject* self, PyObject* pyValue, void* closure) { PamHandleObject* pamHandle = (PamHandleObject*)self; PyObject* name = 0; PyObject* data = 0; int result = -1; const char* data_str; const char* name_str; int pam_result; struct pam_xauth_data xauth_data; closure = closure; xauth_data.name = 0; xauth_data.data = 0; /* * Get the name. */ name = PyObject_GetAttrString(pyValue, "name"); if (name == 0) goto error_exit; name_str = PyString_AsString(name); if (name_str == 0) { PyErr_SetString(PyExc_TypeError, "xauthdata.name must be a string"); goto error_exit; } xauth_data.name = strdup(name_str); if (xauth_data.name == 0) { PyErr_NoMemory(); goto error_exit; } xauth_data.namelen = PyString_GET_SIZE(name); /* * Get the data. */ data = PyObject_GetAttrString(pyValue, "data"); if (data == 0) goto error_exit; data_str = PyString_AsString(data); if (data_str == 0) { PyErr_SetString(PyExc_TypeError, "xauthdata.data must be a string"); goto error_exit; } xauth_data.data = strdup(data_str); if (xauth_data.data == 0) { PyErr_NoMemory(); goto error_exit; } xauth_data.datalen = PyString_GET_SIZE(data); /* * Set the item. If that worked PAM will have swallowed the strings inside * of it, so we must not free them. */ pam_result = pam_set_item(pamHandle->pamh, PAM_XAUTHDATA, &xauth_data); if (pam_result == PAM_SUCCESS) { xauth_data.name = 0; xauth_data.data = 0; } result = check_pam_result(pamHandle, pam_result); error_exit: py_xdecref(data); py_xdecref(name); if (xauth_data.name != 0) free(xauth_data.name); if (xauth_data.data != 0) free(xauth_data.data); return result; } #endif /* * Getters and setters. */ static PyGetSetDef PamHandle_Getset[] = { /* * Items. */ {"authtok", PamHandle_get_AUTHTOK, PamHandle_set_AUTHTOK, "Authentication token", 0}, #ifdef PAM_AUTHTOK_TYPE {"authtok_type",PamHandle_get_AUTHTOK_TYPE,PamHandle_set_AUTHTOK_TYPE,"XXX in the \"New XXX password:\" prompt", 0}, #endif {"oldauthtok", PamHandle_get_OLDAUTHTOK, PamHandle_set_OLDAUTHTOK, "Old authentication token", 0}, {"rhost", PamHandle_get_RHOST, PamHandle_set_RHOST, "Requesting host name", 0}, {"ruser", PamHandle_get_RUSER, PamHandle_set_RUSER, "Requesting user name", 0}, {"service", PamHandle_get_SERVICE, PamHandle_set_SERVICE, "Service (pam stack) name", 0}, {"tty", PamHandle_get_TTY, PamHandle_set_TTY, "Terminal name", 0}, {"user", PamHandle_get_USER, PamHandle_set_USER, "Authorized user name", 0}, {"user_prompt", PamHandle_get_USER_PROMPT, PamHandle_set_USER_PROMPT, "Prompt asking for users name", 0}, #ifdef PAM_XAUTHDATA {"xauthdata", PamHandle_get_XAUTHDATA, PamHandle_set_XAUTHDATA, "The name of the X display ($DISPLAY)", 0}, #endif #ifdef PAM_XDISPLAY {"xdisplay", PamHandle_get_XDISPLAY, PamHandle_set_XDISPLAY, "The name of the X display ($DISPLAY)", 0}, #endif /* * Constants. */ CONSTANT_GETSET(HAVE_PAM_FAIL_DELAY), CONSTANT_GETSET(PAM_ABORT), CONSTANT_GETSET(PAM_ACCT_EXPIRED), CONSTANT_GETSET(PAM_AUTH_ERR), CONSTANT_GETSET(PAM_AUTHINFO_UNAVAIL), CONSTANT_GETSET(PAM_AUTHTOK), CONSTANT_GETSET(PAM_AUTHTOK_DISABLE_AGING), CONSTANT_GETSET(PAM_AUTHTOK_ERR), CONSTANT_GETSET(PAM_AUTHTOK_EXPIRED), CONSTANT_GETSET(PAM_AUTHTOK_LOCK_BUSY), #ifdef PAM_AUTHTOK_RECOVERY_ERR CONSTANT_GETSET(PAM_AUTHTOK_RECOVERY_ERR), #endif #ifdef PAM_AUTHTOK_RECOVER_ERR CONSTANT_GETSET(PAM_AUTHTOK_RECOVER_ERR), #endif #ifdef PAM_AUTHTOK_TYPE CONSTANT_GETSET(PAM_AUTHTOK_TYPE), #endif #ifdef PAM_BAD_ITEM CONSTANT_GETSET(PAM_BAD_ITEM), #endif #ifdef PAM_BINARY_PROMPT CONSTANT_GETSET(PAM_BINARY_PROMPT), #endif CONSTANT_GETSET(PAM_BUF_ERR), CONSTANT_GETSET(PAM_CHANGE_EXPIRED_AUTHTOK), CONSTANT_GETSET(PAM_CONV), #ifdef PAM_CONV_AGAIN CONSTANT_GETSET(PAM_CONV_AGAIN), #endif CONSTANT_GETSET(PAM_CONV_ERR), CONSTANT_GETSET(PAM_CRED_ERR), CONSTANT_GETSET(PAM_CRED_EXPIRED), CONSTANT_GETSET(PAM_CRED_INSUFFICIENT), CONSTANT_GETSET(PAM_CRED_UNAVAIL), #ifdef PAM_DATA_REPLACE CONSTANT_GETSET(PAM_DATA_REPLACE), #endif #ifdef PAM_DATA_SILENT CONSTANT_GETSET(PAM_DATA_SILENT), #endif CONSTANT_GETSET(PAM_DELETE_CRED), CONSTANT_GETSET(PAM_DISALLOW_NULL_AUTHTOK), CONSTANT_GETSET(PAM_ERROR_MSG), CONSTANT_GETSET(PAM_ESTABLISH_CRED), #ifdef PAM_FAIL_DELAY CONSTANT_GETSET(PAM_FAIL_DELAY), #endif CONSTANT_GETSET(PAM_IGNORE), #ifdef PAM_INCOMPLETE CONSTANT_GETSET(PAM_INCOMPLETE), #endif CONSTANT_GETSET(PAM_MAX_MSG_SIZE), CONSTANT_GETSET(PAM_MAX_NUM_MSG), CONSTANT_GETSET(PAM_MAX_RESP_SIZE), CONSTANT_GETSET(PAM_MAXTRIES), CONSTANT_GETSET(PAM_MODULE_UNKNOWN), CONSTANT_GETSET(PAM_NEW_AUTHTOK_REQD), CONSTANT_GETSET(PAM_NO_MODULE_DATA), CONSTANT_GETSET(PAM_OLDAUTHTOK), CONSTANT_GETSET(PAM_OPEN_ERR), CONSTANT_GETSET(PAM_PERM_DENIED), CONSTANT_GETSET(PAM_PRELIM_CHECK), CONSTANT_GETSET(PAM_PROMPT_ECHO_OFF), CONSTANT_GETSET(PAM_PROMPT_ECHO_ON), #ifdef PAM_RADIO_TYPE CONSTANT_GETSET(PAM_RADIO_TYPE), #endif CONSTANT_GETSET(PAM_REFRESH_CRED), CONSTANT_GETSET(PAM_REINITIALIZE_CRED), CONSTANT_GETSET(_PAM_RETURN_VALUES), CONSTANT_GETSET(PAM_RHOST), CONSTANT_GETSET(PAM_RUSER), CONSTANT_GETSET(PAM_SERVICE), CONSTANT_GETSET(PAM_SERVICE_ERR), CONSTANT_GETSET(PAM_SESSION_ERR), CONSTANT_GETSET(PAM_SILENT), CONSTANT_GETSET(PAM_SUCCESS), CONSTANT_GETSET(PAM_SYMBOL_ERR), CONSTANT_GETSET(PAM_SYSTEM_ERR), CONSTANT_GETSET(PAM_TEXT_INFO), CONSTANT_GETSET(PAM_TRY_AGAIN), CONSTANT_GETSET(PAM_TTY), CONSTANT_GETSET(PAM_UPDATE_AUTHTOK), CONSTANT_GETSET(PAM_USER), CONSTANT_GETSET(PAM_USER_PROMPT), CONSTANT_GETSET(PAM_USER_UNKNOWN), #ifdef PAM_XAUTHDATA CONSTANT_GETSET(PAM_XAUTHDATA), #endif #ifdef PAM_XDISPLAY CONSTANT_GETSET(PAM_XDISPLAY), #endif {0,0,0,0,0} /* Sentinel */ }; /* * Convert a PamHandleObject.Message style object to a pam_message structure. */ static int PamHandle_conversation_2message( struct pam_message* message, PyObject* object) { PyObject* msg = 0; PyObject* msg_style = 0; int result = -1; msg_style = PyObject_GetAttrString(object, "msg_style"); if (msg_style == 0) goto error_exit; if (!PyInt_Check(msg_style) && !PyLong_Check(msg_style)) { PyErr_SetString(PyExc_TypeError, "message.msg_style must be an int"); goto error_exit; } message->msg_style = PyInt_AsLong(msg_style); msg = PyObject_GetAttrString(object, "msg"); if (msg == 0) goto error_exit; message->msg = PyString_AsString(msg); if (message->msg == 0) { PyErr_SetString(PyExc_TypeError, "message.msg must be a string"); goto error_exit; } result = 0; error_exit: py_xdecref(msg); py_xdecref(msg_style); return result; } /* * Convert a pam_response structure to a PamHandleObject.Response object. */ static PyObject* PamHandle_conversation_2response( PamHandleObject* pamHandle, struct pam_response* pam_response) { PyObject* newargs; PyObject* result = 0; newargs = Py_BuildValue("si", pam_response->resp, pam_response->resp_retcode); if (newargs == 0) goto error_exit; result = pamHandle->response->tp_new(pamHandle->response, newargs, 0); if (result == 0) goto error_exit; error_exit: py_xdecref(newargs); return result; } /* * Run a PAM "conversation". */ static PyObject* PamHandle_conversation( PyObject* self, PyObject* args, PyObject* kwds) { int err; PamHandleObject* pamHandle = (PamHandleObject*)self; PyObject* prompts = 0; PyObject* result_tuple = 0; struct pam_message* message_array = 0; struct pam_message** message_vector = 0; struct pam_response* response_array = 0; PyObject* result = 0; PyObject* response = 0; const struct pam_conv*conv; int prompt_count; int i; int pam_result; int prompts_is_sequence; int py_result; static char* kwlist[] = {"prompts", NULL}; err = PyArg_ParseTupleAndKeywords( args, kwds, "O:conversation", kwlist, &prompts); if (!err) goto error_exit; pam_result = pam_get_item(pamHandle->pamh, PAM_CONV, (const void**)&conv); if (check_pam_result(pamHandle, pam_result) == -1) goto error_exit; prompts_is_sequence = PySequence_Check(prompts); if (!prompts_is_sequence) prompt_count = 1; else { prompt_count = PySequence_Size(prompts); if (prompt_count == 0) { result = prompts; Py_INCREF(result); goto error_exit; } } message_array = PyMem_Malloc(prompt_count * sizeof(*message_array)); if (message_array == 0) { PyErr_NoMemory(); goto error_exit; } if (!prompts_is_sequence) { py_result = PamHandle_conversation_2message(message_array, prompts); if (py_result == -1) goto error_exit; } else { for (i = 0; i < prompt_count; i += 1) { PyObject* message = PySequence_ITEM(prompts, i); if (message == 0) goto error_exit; py_result = PamHandle_conversation_2message(&message_array[i], message); Py_DECREF(message); if (py_result == -1) goto error_exit; } } message_vector = PyMem_Malloc(prompt_count * sizeof(*message_vector)); if (message_vector == 0) { PyErr_NoMemory(); goto error_exit; } for (i = 0; i < prompt_count; i += 1) message_vector[i] = &message_array[i]; pam_result = conv->conv( prompt_count, (const struct pam_message**)message_vector, &response_array, conv->appdata_ptr); if (check_pam_result(pamHandle, pam_result) == -1) goto error_exit; if (!prompts_is_sequence) result = PamHandle_conversation_2response(pamHandle, response_array); else { result_tuple = PyTuple_New(prompt_count); if (result_tuple == 0) goto error_exit; for (i = 0; i < prompt_count; i += 1) { response = PamHandle_conversation_2response( pamHandle, &response_array[i]); if (response == 0) goto error_exit; if (PyTuple_SetItem(result_tuple, i, response) == -1) goto error_exit; response = 0; /* was stolen */ } result = result_tuple; result_tuple = 0; } error_exit: py_xdecref(response); py_xdecref(result_tuple); PyMem_Free(message_array); PyMem_Free(message_vector); if (response_array != 0) free(response_array); return result; } /* * Set the fail delay. */ static PyObject* PamHandle_fail_delay( PyObject* self, PyObject* args, PyObject* kwds) { int err; int micro_sec = 0; int pam_result; PyObject* result = 0; static char* kwlist[] = {"micro_sec", NULL}; err = PyArg_ParseTupleAndKeywords( args, kwds, "i:fail_delay", kwlist, µ_sec); if (!err) goto error_exit; #ifndef HAVE_PAM_FAIL_DELAY (void)self; #else { PamHandleObject* pamHandle = (PamHandleObject*)self; pam_result = pam_fail_delay(pamHandle->pamh, micro_sec); if (check_pam_result(pamHandle, pam_result) == -1) goto error_exit; } #endif result = Py_None; Py_INCREF(result); error_exit: return result; } /* * Get the user's name, promping if it isn't known. */ static PyObject* PamHandle_get_user( PyObject* self, PyObject* args, PyObject* kwds) { PamHandleObject* pamHandle = (PamHandleObject*)self; char* prompt = 0; PyObject* result = 0; int pam_result; const char* user = 0; static char* kwlist[] = {"prompt", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|z:get_user", kwlist, &prompt)) goto error_exit; pam_result = pam_get_user(pamHandle->pamh, &user, prompt); if (check_pam_result(pamHandle, pam_result) == -1) goto error_exit; if (user != 0) result = PyString_FromString(user); else { result = Py_None; Py_INCREF(result); } if (result == 0) goto error_exit; error_exit: return result; } /* * Set a PAM environment variable. */ static PyObject* PamHandle_strerror( PyObject* self, PyObject* args, PyObject* kwds) { PamHandleObject* pamHandle = (PamHandleObject*)self; const char* err; int errnum; PyObject* result = 0; const int debug_magic = 0x4567abcd; static char* kwlist[] = {"errnum", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "i:strerror", kwlist, &errnum)) goto error_exit; /* * A kludge so we can test exceptions. */ if (errnum >= debug_magic && errnum < debug_magic + _PAM_RETURN_VALUES) { if (check_pam_result(pamHandle, errnum - debug_magic) == -1) goto error_exit; } err = pam_strerror(pamHandle->pamh, errnum); if (err == 0) { result = Py_None; Py_INCREF(result); } else { result = PyString_FromString(err); if (result == 0) goto error_exit; } error_exit: return result; } static PyMethodDef PamHandle_Methods[] = { { "conversation", PyCFunctionKwds_cast PamHandle_conversation, METH_VARARGS|METH_KEYWORDS, MODULE_NAME "." PAMHANDLE_NAME "." "conversation(prompts)\n" " Ask the application to issue the prompts to the user and return the\n" " users responses. The 'prompts' can be one, or a list of\n" " " MODULE_NAME "." PAMHANDLE_NAME "." PAMMESSAGE_NAME " objects. The return value is one,\n" " or an array of " MODULE_NAME "." PAMHANDLE_NAME "." PAMRESPONSE_NAME " objects." }, { "fail_delay", PyCFunctionKwds_cast PamHandle_fail_delay, METH_VARARGS|METH_KEYWORDS, MODULE_NAME "." PAMHANDLE_NAME "." "fail_delay(micro_sec)\n" " Sets the amount of time a failed authenticate attempt should delay for\n" " in micro seconds. This amount reset to 0 after every authenticate\n" " attempt." }, { "get_user", PyCFunctionKwds_cast PamHandle_get_user, METH_VARARGS|METH_KEYWORDS, MODULE_NAME "." PAMHANDLE_NAME "." "getuser([prompt])\n" " If " PAMHANDLE_NAME ".user isn't None return it, otherwise ask the\n" " application to display the string 'prompt' and enter the user name. The\n" " user name (a string) is returned. It will be None if it isn't known." }, { "strerror", PyCFunctionKwds_cast PamHandle_strerror, METH_VARARGS|METH_KEYWORDS, MODULE_NAME "." PAMHANDLE_NAME "." "strerror(errnum)\n" " Return a string describing the pam error errnum." }, {0,0,0,0} /* Sentinel */ }; static PyMemberDef PamHandle_Members[] = { { "env", T_OBJECT_EX, offsetof(PamHandleObject, env), READONLY, "The PAM environment mapping." }, { "exception", T_OBJECT_EX, offsetof(PamHandleObject, exception), READONLY, "Exception raised when a call to PAM fails." }, { "libpam_version", T_STRING, offsetof(PamHandleObject, libpam_version), READONLY, "The runtime PAM version." }, { "Message", T_OBJECT, offsetof(PamHandleObject, message), READONLY, "Message class that can be passed to " MODULE_NAME "." PAMHANDLE_NAME ".conversation()" }, { "module", T_OBJECT, offsetof(PamHandleObject, module), READONLY, "The user module (ie you!)" }, { "pamh", T_LONG, offsetof(PamHandleObject, pamh), READONLY, "The PAM handle." }, { "py_initialized", T_INT, offsetof(PamHandleObject, py_initialized), READONLY, "True if Py_Initialize was called." }, { "Response", T_OBJECT, offsetof(PamHandleObject, response), READONLY, "Response class returned by " MODULE_NAME "." PAMHANDLE_NAME ".conversation()" }, { "XAuthData", T_OBJECT, offsetof(PamHandleObject, xauthdata), READONLY, "XAuthData class used by " MODULE_NAME "." PAMHANDLE_NAME ".xauthdata" }, {0,0,0,0,0}, /* End of Python visible members */ { "syslogFile", T_OBJECT, offsetof(PamHandleObject, syslogFile), READONLY, "File like object that writes to syslog" }, {0,0,0,0,0} /* Sentinal */ }; static char PamHandle_Doc[] = MODULE_NAME "." PAMHANDLE_NAME "\n" " A an instance of this class makes the PAM API available to the Python\n" " module. It is the first argument to every method PAM calls in the module."; static int pypam_initialize_count = 0; static void cleanup_pamHandle(pam_handle_t* pamh, void* data, int error_status) { PamHandleObject* pamHandle = (PamHandleObject*)data; void* dlhandle = pamHandle->dlhandle; PyObject* py_resultobj = 0; PyObject* handler_function = 0; int py_initialized; static const char* handler_name = "pam_sm_end"; (void)pamh; (void)error_status; handler_function = PyObject_GetAttrString(pamHandle->module, (char*)handler_name); if (handler_function == 0) PyErr_Restore(0, 0, 0); else { call_python_handler( &py_resultobj, pamHandle, handler_function, handler_name, 0, 0, 0); } py_xdecref(py_resultobj); py_xdecref(handler_function); py_initialized = pamHandle->py_initialized; Py_DECREF(pamHandle); if (py_initialized) { pypam_initialize_count -= 1; if (pypam_initialize_count == 0) Py_Finalize(); } dlclose(dlhandle); } /* * Find the module, and load it if we haven't see it before. Returns * PAM_SUCCESS if it worked, the PAM error code otherwise. */ static int load_user_module( PyObject** user_module, PamHandleObject* pamHandle, const char* module_path) { PyObject* builtins = 0; PyObject* module_dict = 0; FILE* module_fp = 0; char* user_module_name = 0; PyObject* py_resultobj = 0; char* dot; int pam_result; int py_result; /* * Open the file. */ module_fp = fopen(module_path, "r"); if (module_fp == 0) { syslog_path_message( module_path, "Can not open module: %s", strerror(errno)); pam_result = PAM_OPEN_ERR; goto error_exit; } /* * Create the new module. */ user_module_name = strrchr(module_path, '/'); if (user_module_name == 0) user_module_name = strdup(module_path); else user_module_name = strdup(user_module_name + 1); if (user_module_name == 0) { syslog_path_message(MODULE_NAME, "out of memory"); pam_result = PAM_BUF_ERR; goto error_exit; } dot = strrchr(user_module_name, '.'); if (dot != 0 && strcmp(dot, ".py") == 0) *dot = '\0'; *user_module = PyModule_New(user_module_name); if (*user_module == 0) { pam_result = syslog_path_exception( module_path, "PyModule_New(pamh.module.__file__) failed"); goto error_exit; } py_result = PyModule_AddStringConstant(*user_module, "__file__", (char*)module_path); if (py_result == -1) { pam_result = syslog_path_exception( module_path, "PyModule_AddStringConstant(pamh.module, '__file__', module_path) failed"); goto error_exit; } /* * Add __builtins__. */ if (!PyObject_HasAttrString(*user_module , "__builtins__")) { builtins = PyEval_GetBuiltins(); Py_INCREF(builtins); /* is stolen */ if (PyModule_AddObject(*user_module, "__builtins__", builtins) == -1) { pam_result = syslog_path_exception( module_path, "PyModule_AddObject(pamh.module, '__builtins__', builtins) failed"); goto error_exit; } builtins = 0; /* was borrowed */ } /* * Call it. */ module_dict = PyModule_GetDict(*user_module); py_resultobj = PyRun_FileExFlags( module_fp, module_path, Py_file_input, module_dict, module_dict, 1, 0); module_fp = 0; /* it was closed */ module_dict = 0; /* was borrowed */ /* * If that didn't work there was an exception. Errk! */ if (py_resultobj == 0) { pam_result = syslog_path_traceback(module_path, pamHandle); goto error_exit; } pam_result = PAM_SUCCESS; error_exit: py_xdecref(builtins); py_xdecref(module_dict); if (module_fp != 0) fclose(module_fp); if (user_module_name != 0) free(user_module_name); py_xdecref(py_resultobj); return pam_result; } /* * Create a new Python type on the heap. This differs from creating a static * type in non-obvious ways. */ static PyTypeObject* newHeapType( PyObject* module, /* Module declaring type (required) */ const char* name, /* tp_name (required) */ int basicsize, /* tp_basicsize (required) */ char* doc, /* tp_doc (optional) */ inquiry clear, /* tp_clear (optional) */ struct PyMethodDef* methods, /* tp_methods (optional) */ struct PyMemberDef* members, /* tp_members (optional) */ struct PyGetSetDef* getset, /* tp_getset (optional) */ newfunc new /* tp_new (optional) */ ) { PyObject* pyName = 0; PyTypeObject* result = 0; PyTypeObject* type = 0; pyName = PyString_FromString(name); if (pyName == 0) goto error_exit; type = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0); if (type == 0) goto error_exit; type->tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HEAPTYPE|Py_TPFLAGS_HAVE_GC; type->tp_basicsize = basicsize; type->tp_dealloc = generic_dealloc; if (doc != 0) { char *doc_string = PyMem_Malloc(strlen(doc)+1); if (doc_string == 0) { PyErr_NoMemory(); goto error_exit; } strcpy(doc_string, doc); type->tp_doc = doc_string; } type->tp_traverse = generic_traverse; type->tp_clear = clear != 0 ? clear : generic_clear; type->tp_methods = methods; type->tp_members = members; type->tp_getset = getset; type->tp_name = PyString_AsString(pyName); #if PY_VERSION_HEX < 0x02050000 ((PyHeapTypeObject*)type)->name = pyName; #else ((PyHeapTypeObject*)type)->ht_name = pyName; #endif pyName = 0; PyType_Ready(type); type->tp_new = new; if (PyDict_SetItemString(type->tp_dict, "__module__", module) == -1) goto error_exit; result = type; type = 0; error_exit: py_xdecref(pyName); py_xdecref((PyObject*)type); return result; } /* * Create a type and return an instance of that type. The newly created * type object is discarded. */ static PyObject* newSingletonObject( PyObject* module, /* Module declaring type (required) */ const char* name, /* tp_name (required) */ int basicsize, /* tp_basicsize (required) */ char* doc, /* tp_doc (optional) */ inquiry clear, /* tp_clear (optional) */ struct PyMethodDef* methods, /* tp_methods (optional) */ struct PyMemberDef* members, /* tp_members (optional) */ struct PyGetSetDef* getset /* tp_getset (optional) */ ) { PyObject* result = 0; PyTypeObject* type = 0; type = newHeapType( module, name, basicsize, doc, clear, methods, members, getset, 0); if (type != 0) result = type->tp_alloc(type, 0); py_xdecref((PyObject*)type); return result; } /* * Find the PamHandle object used by the pamh instance, creating one if it * doesn't exist. Returns a pam_result, which will be PAM_SUCCESS if it * works. */ static int get_pamHandle( PamHandleObject** result, pam_handle_t* pamh, const char** argv) { void* dlhandle = 0; int do_initialize; char* module_dir; char* module_path = 0; char* module_data_name = 0; PyObject* user_module = 0; PamEnvObject* pamEnv = 0; PamHandleObject* pamHandle = 0; PyObject* pamHandle_module = 0; SyslogFileObject* syslogFile = 0; PyObject* tracebackModule = 0; int pam_result; /* * Figure out where the module lives. */ if (argv == 0 || argv[0] == 0) { syslog_path_message(MODULE_NAME, "python module name not supplied"); pam_result = PAM_MODULE_UNKNOWN; goto error_exit; } if (argv[0][0] == '/') module_dir = ""; else module_dir = DEFAULT_SECURITY_DIR; module_path = malloc(strlen(module_dir) + strlen(argv[0]) + 1); if (module_path == 0) { syslog_path_message(MODULE_NAME, "out of memory"); pam_result = PAM_BUF_ERR; goto error_exit; } strcat(strcpy(module_path, module_dir), argv[0]); /* * See if we already exist. */ module_data_name = malloc(strlen(MODULE_NAME) + 1 + strlen(module_path) + 1); if (module_data_name == 0) { syslog_path_message(MODULE_NAME, "out of memory"); pam_result = PAM_BUF_ERR; goto error_exit; } strcat(strcat(strcpy(module_data_name, MODULE_NAME), "."), module_path); pam_result = pam_get_data(pamh, module_data_name, (void*)result); if (pam_result == PAM_SUCCESS) { (*result)->pamh = pamh; Py_INCREF(*result); goto error_exit; } /* * Initialize Python if required. */ dlhandle = dlopen(libpython_so, RTLD_NOW|RTLD_GLOBAL); if (dlhandle == 0) { pam_result = syslog_path_message( module_path, "Can't load python library %s: %s", libpython_so, dlerror()); goto error_exit; } do_initialize = pypam_initialize_count > 0 || !Py_IsInitialized(); if (do_initialize) { if (pypam_initialize_count == 0) initialise_python(); pypam_initialize_count += 1; } /* * Create a throw away module because heap types need one, apparently. */ pamHandle_module = PyModule_New((char*)module_data_name); if (pamHandle_module == 0) { pam_result = syslog_path_exception( module_path, "PyModule_New(module_data_name) failed"); goto error_exit; } /* * Create the type we use for our object. */ pamHandle = (PamHandleObject*)newSingletonObject( pamHandle_module, /* __module__ */ PAMHANDLE_NAME "_type", /* tp_name */ sizeof(PamHandleObject), /* tp_basicsize */ PamHandle_Doc, /* tp_doc */ 0, /* tp_clear */ PamHandle_Methods, /* tp_methods */ PamHandle_Members, /* tp_members */ PamHandle_Getset); /* tp_getset */ if (pamHandle == 0) { pam_result = syslog_path_exception(module_path, "Can't create pamh Object"); goto error_exit; } if (PyObject_IS_GC((PyObject*)pamHandle)) PyObject_GC_UnTrack(pamHandle); /* No refs are visible to python */ pamHandle->dlhandle = dlhandle; dlhandle = 0; pamHandle->libpam_version = __STRING(__LINUX_PAM__) "." __STRING(__LINUX_PAM_MINOR__); pamHandle->pamh = pamh; pamHandle->py_initialized = do_initialize; pamHandle->exception = PyErr_NewException( PAMHANDLE_NAME "." PAMHANDLEEXCEPTION_NAME, PyExc_StandardError, NULL); if (pamHandle->exception == NULL) goto error_exit; /* * Create the object we use to handle the PAM environment. */ pamEnv = (PamEnvObject*)newSingletonObject( pamHandle_module, /* __module__ */ PAMENV_NAME "_type", /* tp_name */ sizeof(PamEnvObject), /* tp_basicsize */ 0, /* tp_doc */ 0, /* tp_clear */ PamEnv_Methods, /* tp_methods */ PamEnv_Members, /* tp_members */ 0); /* tp_getset */ if (pamEnv == 0) { pam_result = syslog_path_exception(module_path, "Can't create pamh.env"); goto error_exit; } pamEnv->ob_type->tp_as_mapping = &PamEnv_as_mapping; pamEnv->ob_type->tp_iter = PamEnv_iter; pamEnv->pamHandle = pamHandle; pamEnv->pamEnvIter_type = newHeapType( pamHandle_module, /* __module__ */ PAMENVITER_NAME "_type", /* tp_name */ sizeof(PamEnvIterObject), /* tp_basicsize */ 0, /* tp_doc */ 0, /* tp_clear */ 0, /* tp_methods */ PamEnvIter_Members, /* tp_members */ 0, /* tp_getset */ 0); /* tp_new */ if (pamEnv->pamEnvIter_type == 0) goto error_exit; if (PyObject_IS_GC((PyObject*)pamEnv->pamEnvIter_type)) { /* * No refs are visible to python. */ PyObject_GC_UnTrack(pamEnv->pamEnvIter_type); } pamEnv->pamEnvIter_type->tp_iter = PyObject_SelfIter; pamEnv->pamEnvIter_type->tp_iternext = PamEnvIter_iternext; pamHandle->env = (PyObject*)pamEnv; pamEnv = 0; /* * Create the type for the PamMessageObject. */ pamHandle->message = newHeapType( pamHandle_module, /* __module__ */ PAMMESSAGE_NAME "_type", /* tp_name */ sizeof(PamMessageObject), /* tp_basicsize */ PamMessage_doc, /* tp_doc */ 0, /* tp_clear */ 0, /* tp_methods */ PamMessage_members, /* tp_members */ 0, /* tp_getset */ PamMessage_new); /* tp_new */ if (pamHandle->message == 0) { pam_result = syslog_path_exception( module_path, "Can't create pamh.Message"); goto error_exit; } /* * Create the type for the PamResponseObject. */ pamHandle->response = newHeapType( pamHandle_module, /* __module__ */ PAMRESPONSE_NAME "_type", /* tp_name */ sizeof(PamResponseObject), /* tp_basicsize */ PamResponse_doc, /* tp_doc */ 0, /* tp_clear */ 0, /* tp_methods */ PamResponse_members, /* tp_members */ 0, /* tp_getset */ PamResponse_new); /* tp_new */ if (pamHandle->response == 0) { pam_result = syslog_path_exception( module_path, "Can't create pamh.Response"); goto error_exit; } /* * Create the Syslogfile Type & Object. */ syslogFile = (SyslogFileObject*)newSingletonObject( pamHandle_module, /* __module__ */ SYSLOGFILE_NAME "_type", /* tp_name */ sizeof(SyslogFileObject), /* tp_basicsize */ 0, /* tp_doc */ SyslogFile_clear, /* tp_clear */ SyslogFile_Methods, /* tp_methods */ 0, /* tp_members */ 0); /* tp_getset */ if (syslogFile == 0) { pam_result = syslog_path_exception( module_path, "Can't create pamh.syslogFile"); goto error_exit; } syslogFile->buffer = 0; syslogFile->size = 0; pamHandle->syslogFile = (PyObject*)syslogFile; syslogFile = 0; /* * The traceback object. */ tracebackModule = PyImport_ImportModule("traceback"); if (tracebackModule == 0) { pam_result = syslog_path_exception( module_path, "PyImport_ImportModule('traceback') failed"); goto error_exit; } pamHandle->print_exception = PyObject_GetAttrString(tracebackModule, "print_exception"); if (pamHandle->print_exception == 0) { pam_result = syslog_path_exception( module_path, "PyObject_GetAttrString(traceback, 'print_exception') failed"); goto error_exit; } Py_INCREF(pamHandle->print_exception); /* Borrowed reference */ /* * Create the type for the PamXAuthDataObject. */ pamHandle->xauthdata = newHeapType( pamHandle_module, /* __module__ */ PAMXAUTHDATA_NAME "_type", /* tp_name */ sizeof(PamXAuthDataObject), /* tp_basicsize */ PamXAuthData_doc, /* tp_doc */ 0, /* tp_clear */ 0, /* tp_methods */ PamXAuthData_members, /* tp_members */ 0, /* tp_getset */ PamXAuthData_new); /* tp_new */ if (pamHandle->xauthdata == 0) { pam_result = syslog_path_exception( module_path, "Can't create pamh.XAuthData"); goto error_exit; } /* * Now we have error reporting set up import the module. */ pam_result = load_user_module(&user_module, pamHandle, module_path); if (pam_result != PAM_SUCCESS) goto error_exit; pamHandle->module = user_module; Py_INCREF(pamHandle->module); /* * That worked. Save a reference to it. */ Py_INCREF(pamHandle); pam_set_data(pamh, module_data_name, pamHandle, cleanup_pamHandle); *result = pamHandle; pamHandle = 0; error_exit: if (module_path != 0) free(module_path); if (module_data_name != 0) free(module_data_name); py_xdecref(user_module); py_xdecref((PyObject*)pamEnv); py_xdecref((PyObject*)pamHandle); py_xdecref(pamHandle_module); py_xdecref((PyObject*)syslogFile); py_xdecref(tracebackModule); return pam_result; } /* * Call the python handler. */ static int call_python_handler( PyObject** result, PamHandleObject* pamHandle, PyObject* handler_function, const char* handler_name, int flags, int argc, const char** argv) { PyObject* arg_object = 0; PyObject* argv_object = 0; PyObject* flags_object = 0; PyObject* handler_args = 0; PyObject* py_resultobj = 0; int i; int pam_result; if (!PyCallable_Check(handler_function)) { pam_result = syslog_message(pamHandle, "%s isn't a function.", handler_name); goto error_exit; } /* * Set up the arguments for the python function. If we aren't passed * argv then this is pam_sm_end() and it is only given pamh. */ if (argv == 0) handler_args = Py_BuildValue("(O)", pamHandle); else { flags_object = PyInt_FromLong(flags); if (flags_object == 0) { pam_result = syslog_exception(pamHandle, "PyInt_FromLong(flags) failed"); goto error_exit; } argv_object = PyList_New(argc); if (argv_object == 0) { pam_result = syslog_exception(pamHandle, "PyList_New(argc) failed"); goto error_exit; } for (i = 0; i < argc; i += 1) { arg_object = PyString_FromString(argv[i]); if (arg_object == 0) { pam_result = syslog_exception( pamHandle, "PyString_FromString(argv[i]) failed"); goto error_exit; } PyList_SET_ITEM(argv_object, i, arg_object); arg_object = 0; /* It was pinched by SET_ITEM */ } handler_args = Py_BuildValue("OOO", pamHandle, flags_object, argv_object); } if (handler_args == 0) { pam_result = syslog_exception( pamHandle, "handler_args = Py_BuildValue(...) failed"); goto error_exit; } /* * Call the Python handler function. */ py_resultobj = PyEval_CallObject(handler_function, handler_args); /* * Did it throw an exception? */ if (py_resultobj == 0) { pam_result = syslog_traceback(pamHandle); goto error_exit; } *result = py_resultobj; py_resultobj = 0; pam_result = PAM_SUCCESS; error_exit: py_xdecref(arg_object); py_xdecref(argv_object); py_xdecref(flags_object); py_xdecref(handler_args); py_xdecref(py_resultobj); return pam_result; } /* * Calls the Python method that will handle PAM's request to the module. */ static int call_handler( const char* handler_name, pam_handle_t* pamh, int flags, int argc, const char** argv) { PyObject* handler_function = 0; PamHandleObject* pamHandle = 0; PyObject* py_resultobj = 0; int pam_result; /* * Initialise Python, and get a copy of our object. */ pam_result = get_pamHandle(&pamHandle, pamh, argv); if (pam_result != PAM_SUCCESS) goto error_exit; /* * See if the function we have to call has been defined. */ handler_function = PyObject_GetAttrString(pamHandle->module, (char*)handler_name); if (handler_function == 0) { syslog_message(pamHandle, "%s() isn't defined.", handler_name); pam_result = PAM_SYMBOL_ERR; goto error_exit; } pam_result = call_python_handler( &py_resultobj, pamHandle, handler_function, handler_name, flags, argc, argv); if (pam_result != PAM_SUCCESS) goto error_exit; /* * It must return an integer. */ if (!PyInt_Check(py_resultobj) && !PyLong_Check(py_resultobj)) { pam_result = syslog_message( pamHandle, "%s() did not return an integer.", handler_name); goto error_exit; } pam_result = PyInt_AsLong(py_resultobj); error_exit: py_xdecref(handler_function); py_xdecref((PyObject*)pamHandle); py_xdecref(py_resultobj); return pam_result; } PAM_EXTERN int pam_sm_authenticate( pam_handle_t* pamh, int flags, int argc, const char** argv) { return call_handler("pam_sm_authenticate", pamh, flags, argc, argv); } PAM_EXTERN int pam_sm_setcred( pam_handle_t* pamh, int flags, int argc, const char** argv) { return call_handler("pam_sm_setcred", pamh, flags, argc, argv); } PAM_EXTERN int pam_sm_acct_mgmt( pam_handle_t* pamh, int flags, int argc, const char** argv) { return call_handler("pam_sm_acct_mgmt", pamh, flags, argc, argv); } PAM_EXTERN int pam_sm_open_session( pam_handle_t* pamh, int flags, int argc, const char** argv) { return call_handler("pam_sm_open_session", pamh, flags, argc, argv); } PAM_EXTERN int pam_sm_close_session( pam_handle_t* pamh, int flags, int argc, const char** argv) { return call_handler("pam_sm_close_session", pamh, flags, argc, argv); } PAM_EXTERN int pam_sm_chauthtok( pam_handle_t* pamh, int flags, int argc, const char** argv) { return call_handler("pam_sm_chauthtok", pamh, flags, argc, argv); } pam-python-1.0.7/ChangeLog.txt0000644000215700017510000000237413540402767015126 0ustar rstuartitpam-python-1.0.7 Wed, 18 Sep 2019 20:23:54 +1000 Bug: Local root exploit. pam-python-1.0.6 Sat, 27 Aug 2016 21:35:36 +1000 New: Update Makefile.release New: OSX support. Bug: Fix debian bug #833411. pam-python-1.0.5 Fri, 19 Feb 2016 19:29:38 +1000 New: Update Makefile.release Bug: Fix pam typeo in pam_accept.py. Thanks to AndrĂ© Caron for the bug report. pam-python-1.0.4 2014-05-04 New: Re-homed to sourceforge. New: Move to the AGPL-3.0. pam-python-1.0.3 2014-05-04 Bug: Make work with older versions of Python, courtesy of Thomas Kula. Bug: Call dlerror() where appropriate, courtesy of David MacKenzie. New: Linux-PAM-html has moved url's pam-python-1.0.2 2012-04-05 Bug: Get rid of build crap in source distribution. Bug: Fix doco grammar. pam-python-1.0.1 2010-12-13 Bug: Build test suit so libraries are loaded as needed. pam-python-1.0.0 2010-05-23 New: Documentation moved to Python 2.6 format, ie sphinx. New: Added additional members for the new PAM items: PAM_XDISPLAY, PAM_XAUTHTOK and PAM_AUTHTOK_TYPE. New: Added the PamXAuthData class. New: Added new PAM constants in PAM 1.1.1. pam-python-0.1.1 2009-08-05 New: Made to work with Python 2.5. pam-python-0.1.0 2007-12-05 New: Epoch.