├── ChangeLog.txt
├── Makefile
├── Makefile.release
├── README.md
├── README.txt
├── agpl-3.0.txt
├── doc
├── Makefile
├── conf.py
├── pam_permit.py
└── pam_python.rst
├── examples
├── pam_deny.py
├── pam_nologin.py
└── pam_permit.py
├── pam-python.html
├── src
├── Makefile
├── build
│ ├── lib.linux-x86_64-2.6
│ │ └── pam_python.so
│ └── temp.linux-x86_64-2.6
│ │ └── pam_python.o
├── ctest
├── ctest.c
├── pam_python.c
├── pam_python.so
├── setup.py
├── test-pam_python.pam
├── test-pam_python.pam.in
└── test.py
└── utils
├── 2factor-with-PIN
├── README.md
├── auth.py
└── pam.d_sshd
└── 2factor-with-SMS
├── README.md
├── auth.py
├── pam.d_sshd
└── pam.d_sshd_original
/ChangeLog.txt:
--------------------------------------------------------------------------------
1 | pam-python-1.0.5 Fri, 19 Feb 2016 19:29:38 +1000
2 |
3 | New: Update Makefile.release
4 | Bug: Fix pam typeo in pam_accept.py. Thanks to André Caron
5 | for the bug report.
6 |
7 | pam-python-1.0.4 2014-05-04
8 |
9 | New: Re-homed to sourceforge.
10 | New: Move to the AGPL-3.0.
11 |
12 | pam-python-1.0.3 2014-05-04
13 |
14 | Bug: Make work with older versions of Python, courtesy of Thomas Kula.
15 | Bug: Call dlerror() where appropriate, courtesy of David MacKenzie.
16 | New: Linux-PAM-html has moved url's
17 |
18 | pam-python-1.0.2 2012-04-05
19 |
20 | Bug: Get rid of build crap in source distribution.
21 | Bug: Fix doco grammar.
22 |
23 | pam-python-1.0.1 2010-12-13
24 |
25 | Bug: Build test suit so libraries are loaded as needed.
26 |
27 | pam-python-1.0.0 2010-05-23
28 |
29 | New: Documentation moved to Python 2.6 format, ie sphinx.
30 | New: Added additional members for the new PAM items:
31 | PAM_XDISPLAY, PAM_XAUTHTOK and PAM_AUTHTOK_TYPE.
32 | New: Added the PamXAuthData class.
33 | New: Added new PAM constants in PAM 1.1.1.
34 |
35 | pam-python-0.1.1 2009-08-05
36 |
37 | New: Made to work with Python 2.5.
38 |
39 | pam-python-0.1.0 2007-12-05
40 |
41 | New: Epoch.
42 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: all
2 | all: doc lib
3 |
4 | .PHONY: lib
5 | lib:
6 | $(MAKE) --directory src
7 |
8 | .PHONY: doc
9 | doc:
10 | $(MAKE) --directory doc
11 |
12 | .PHONY: test
13 | test:
14 | $(MAKE) --directory src $@
15 |
16 | .PHONY: clean-pam_python
17 | clean-pam_python:
18 | rm -rf pam_python
19 |
20 | .PHONY: clean
21 | clean: clean-pam_python
22 | $(MAKE) --directory doc $@
23 | $(MAKE) --directory src $@
24 |
25 | .PHONY: install
26 | install: install-doc install-lib
27 |
28 | .PHONY: install-doc
29 | install-doc: clean-pam_python
30 | $(MAKE) --directory doc $@
31 |
32 | .PHONY: install-lib
33 | install-lib: clean-pam_python
34 | $(MAKE) --directory src $@
35 |
36 | RELEASE_SOURCES = \
37 | ChangeLog.txt \
38 | Makefile \
39 | Makefile.release \
40 | pam-python.html \
41 | README.txt \
42 | doc/pam_python.rst \
43 | src/ctest.c \
44 | src/Makefile \
45 | src/pam_python.c \
46 | src/setup.py \
47 | src/test-pam_python.pam.in \
48 | src/test.py
49 |
50 | include Makefile.release
51 |
52 | release-project-clean:: clean
53 |
--------------------------------------------------------------------------------
/Makefile.release:
--------------------------------------------------------------------------------
1 | #
2 | # Do a release. Does the following:
3 | #
4 | # 1. Verifies the changelogs have been updated to a consistent version.
5 | #
6 | # 2. Updates the verison numbers and copyright dates in all source files.
7 | #
8 | # 3. Builds the source tarball.
9 | #
10 | # 4. Builds the debian source and binary packages.
11 | #
12 | # 5. If there is a .spec file, buids the rpm source and binary
13 | # packages.
14 | #
15 | # 6. Sends the released files (tarball, debian and rpm packages) to the
16 | # release area.
17 | #
18 | # 7. Sends the HTML file, and other files references by it, to the web
19 | # site.
20 | #
21 | # Copyright (c) 2013,2014,2015,2016 Russell Stuart.
22 | # Licensed (at your choice) under GPLv2, or any later version,
23 | # or AGPL-3.0+, or any later version.
24 | #
25 | RELEASE_ME=$(shell sed -n '1s/ .*//p' ChangeLog.txt)
26 | RELEASE_PACKAGE_NAME=$(shell echo "$(RELEASE_ME)" | sed 's/-[^-]*$$//')
27 | RELEASE_VERSION=$(shell echo "$(RELEASE_ME)" | sed 's/.*-//')
28 | RELEASE_YEAR=$(shell date +%Y)
29 | RELEASE_MONTH=$(shell date +%b)
30 | RELEASE_DATE=$(shell date +%Y-%m-%d)
31 | RELEASE_DEBIAN_VERSION=$(shell sed -n 's/[^(]*(\([^)]*\)).*/\1/p;q' debian/changelog)
32 |
33 | RELEASE_DIR=release.tmp
34 | RELEASE_HTDOCS=$(RELEASE_DIR)/htdocs
35 | RELEASE_FILES=$(RELEASE_DIR)/$(RELEASE_PACKAGE_NAME)-$(RELEASE_DEBIAN_VERSION)
36 |
37 | .PHONY: release
38 | release: $(RELEASE_DIR)/release.stamp
39 | $(RELEASE_DIR)/release.stamp: $(RELEASE_SOURCES)
40 | @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)
41 | #
42 | # Ensure the Debian changelog matches this version.
43 | #
44 | debian_version="$(RELEASE_DEBIAN_VERSION)"; [ "$(RELEASE_PACKAGE_NAME)-$${debian_version%-*}" = "$(RELEASE_ME)" ] || \
45 | { echo 1>&2 "debian/changelog: changelog is out of date."; exit 1; }
46 | $(MAKE) release-clean
47 | #
48 | # Check changes have reflected in mercurial.
49 | #
50 | ! hg status | grep '^?' || { echo "hg add hasn't been done" 1>&2; exit 1; }
51 | ! hg status | grep '^!' || { echo "hg rm hasn't been done" 1>&2; exit 1; }
52 | [ -z "$$(hg resolv --list | grep -v ^R)" ] || { echo "There are unresolved merge conflicts" 1>&2; exit 1; }
53 |
54 | #
55 | # Update all the version numbers and dates.
56 | #
57 | set -e; for f in $(wildcard *.1); do \
58 | sed -i "s/^\([.].\" Copyright (c) \)2[0-9]*/\1$(RELEASE_YEAR)/" "$${f}"; \
59 | sed -i "s/^\([.]TH [A-Z]* 1 \"\)[^\"]*\(\".*Version[ ]\+\)[1-9][0-9]*[.][0-9]\+/\1$(RELEASE_MONTH) $(RELEASE_YEAR)\2$(RELEASE_VERSION)/" "$${f}"; \
60 | done
61 | set -e; for f in $$(find . -name "*.c" -o -name "*.h"); do \
62 | sed -i "/$(RELEASE_YEAR)/!s/\(Copyright (c) [-0-9, ]*2[0-9]*\)\(,\? *Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" "$${f}"; \
63 | sed -i "s/^\(static.*_version..[ ]*=[ ]*\"\)[^\"]*/\1$(RELEASE_VERSION)/" "$${f}"; \
64 | sed -i "s/^\(static.*_date..[ ]*=[ ]*\"\)[^\"]*/\1$(RELEASE_DATE)/" "$${f}"; \
65 | done
66 | set -e; for f in $$(find . -name "*.py"); do \
67 | sed -i 's/^\(VERSION[ ]*=[ ]*"\)[^ ]*/\1$(RELEASE_VERSION)/' $${f}; \
68 | sed -i 's/^\(VERSION[ ]*=[ ]*"[^ ]* \+\)[^"]*/\1$(RELEASE_DATE)/' $${f}; \
69 | done
70 | set -e; for f in $$(find . -name "*.rst" -o -name "*.py" -o -name "Makefile*") README.txt; do \
71 | sed -i "/$(RELEASE_YEAR)/!s/\(Copyright (c) [-0-9, ]*2[0-9]*\)\(,\? *Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" "$${f}"; \
72 | done
73 | set -e; for f in $$(find . -name "setup.py"); do \
74 | sed -i 's/^\([ ]*version="\)[0-9]\+[.][0-9.]\+/\1$(RELEASE_VERSION)/' "$${f}"; \
75 | done
76 | ifneq ($(wildcard $(RELEASE_PACKAGE_NAME).spec),)
77 | sed -i "s/\(Version:[ ]\+\)[0-9]\+[.][0-9.]\+/\1$(RELEASE_VERSION)/" "$(RELEASE_PACKAGE_NAME).spec"
78 | endif
79 | ifneq ($(wildcard configure.ac),)
80 | sed -i "s/\(AC_INIT(\[\?$(RELEASE_PACKAGE_NAME)\]\?, *\[\?\)[0-9]\+[.][0-9.]\+/\1$(RELEASE_VERSION)/" configure.ac
81 | endif
82 | ifneq ($(wildcard doc/conf.py),)
83 | sed -i "/$(RELEASE_YEAR)/!s/^\( *copyright *= *u'[-0-9, ]*2[0-9]*\)\(,\?[ ]*Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" doc/conf.py
84 | sed -i "s/^\( *\(version\|release\) *= *u\?'\)[0-9]\+[.][0-9.]\+'/\1$(RELEASE_VERSION)'/" doc/conf.py
85 | endif
86 | sed -i "/$(RELEASE_YEAR)/!s/\(.* is copyright © [-0-9, ]*2[0-9]*\)\(,\?[ ]*Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" "$(RELEASE_PACKAGE_NAME).html"
87 | sed -i "s/$(RELEASE_PACKAGE_NAME)-[1-9][0-9]*[.][0-9]\+/$(RELEASE_ME)/g" "$(RELEASE_PACKAGE_NAME).html"
88 | sed -i "/$(RELEASE_YEAR)/!s/\(Copyright (c) [-0-9, ]*2[0-9]*\)\(,\? *Russell Stuart\)/\1,$(RELEASE_YEAR)\2/" README.txt
89 | #
90 | # Do any custom stuff.
91 | #
92 | $(MAKE) release-customise
93 | #
94 | # Build the release source tarball.
95 | #
96 | (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}")
97 | #
98 | # Insert the debian packates into the release.
99 | #
100 | DEBIAN_KERNEL_USE_CCACHE="yes" debuild --preserve-env --preserve-envvar="PATH" -k0xE7843A8C -sa --lintian-opts --info --display-info --display-experimental
101 | mkdir -p "$(RELEASE_FILES)"
102 | rm ../$(RELEASE_PACKAGE_NAME)_$(RELEASE_DEBIAN_VERSION)_*.build
103 | 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)
104 | mv "$(RELEASE_FILES)/$(RELEASE_PACKAGE_NAME)_$(RELEASE_VERSION).orig.tar.gz" "$(RELEASE_FILES)/$(RELEASE_ME).tar.gz"
105 | ifneq ($(wildcard $(RELEASE_PACKAGE_NAME).spec),)
106 | #
107 | # Build the RPM package.
108 | #
109 | mkdir -p "$(RELEASE_DIR)/rpm/BUILD"
110 | mkdir -p "$(RELEASE_DIR)/rpm/RPMS"
111 | mkdir -p "$(RELEASE_DIR)/rpm/SOURCES"
112 | mkdir -p "$(RELEASE_DIR)/rpm/SPECS"
113 | mkdir -p "$(RELEASE_DIR)/rpm/SRPMS"
114 | echo >"$(RELEASE_DIR)/rpm/rpmmacros" "%_topdir $(PWD)/$(RELEASE_DIR)/rpm"
115 | 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"
116 | mv "$(RELEASE_DIR)/rpm/SRPMS/$(RELEASE_ME)-1ras.src.rpm" "$(RELEASE_FILES)"
117 | mv "$(RELEASE_DIR)/rpm/RPMS"/*/"$(RELEASE_ME)-1ras".*."rpm" "$(RELEASE_FILES)"
118 | cp ChangeLog.txt "$(RELEASE_FILES)/README.txt"
119 | endif
120 | #
121 | # Build the htdocs directory as it will appear on the host.
122 | #
123 | mkdir -p "$(RELEASE_HTDOCS)"
124 | cp -a $(RELEASE_PACKAGE_NAME).html $(RELEASE_HTDOCS)
125 | 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 \
126 | f="$${f%/}"; \
127 | [ ."$${f%%/*}" = ."$${f}" ] || mkdir -p "$(RELEASE_HTDOCS)/$${f%/*}"; \
128 | case "$${f}" in \
129 | *.[12345678].html) man2html <"$${f%.html}" | sed >"$(RELEASE_HTDOCS)/$${f}" '1,2d;7,8d;/^
/,/^Time: /d';; \
130 | *) cp -a "$${f}" "$(RELEASE_HTDOCS)/$${f}";; \
131 | esac; \
132 | done
133 | ln -s "$(RELEASE_PACKAGE_NAME).html" "$(RELEASE_HTDOCS)/index.html"
134 | echo "Options +Indexes" >"$(RELEASE_HTDOCS)/.htaccess"
135 | #
136 | # Verify there is no rubbish lying wround.
137 | #
138 | ! hg status | grep '^?' || { echo '.hgignore: is missing some files' 1>&2; exit 1; }
139 | touch $@
140 |
141 | .PHONY: release-customise
142 | release-customise::
143 |
144 | .PHONY: upload
145 | upload: upload-htdocs upload-files
146 |
147 | .PHONY: upload-htdocs
148 | upload-htdocs: $(RELEASE_DIR)/release.stamp
149 | #
150 | # Send the files that a symlink'ed first, otherwise it fails on the
151 | # 1st send.
152 | #
153 | 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:.
154 | rsync -avP --delete $(RELEASE_HTDOCS)/. rstuart,$(RELEASE_PACKAGE_NAME)@web.sourceforge.net:htdocs/.
155 |
156 | .PHONY: upload-files
157 | upload-files: $(RELEASE_DIR)/release.stamp
158 | rsync -avP --delete $(RELEASE_FILES) rstuart,$(RELEASE_PACKAGE_NAME)@frs.sourceforge.net:/home/frs/project/$(RELEASE_PACKAGE_NAME)/.
159 |
160 | .PHONY: release-clean
161 | release-clean: release-project-clean
162 | -[ "$(RELEASE_CLEAN_DONE)" = "yes" -o ! -d debian ] || RELEASE_CLEAN_DONE=yes debian/rules clean
163 | [ ! -f Makefile-automake ] || $(MAKE) maintainer-clean
164 | rm -rf $(RELEASE_DIR) "$(RELEASE_PACKAGE_NAME).1.html"
165 | rm -rf $$(find . -name "*.orig" -o -name ".*.sw?")
166 |
167 | .PHONY: release-tag
168 | release-tag: $(RELEASE_DIR)/release.stamp
169 | ! hg status | grep '^?' || { echo "hg add hasn't been done" 1>&2; exit 1; }
170 | ! hg status | grep '^!' || { echo "hg rm hasn't been done" 1>&2; exit 1; }
171 | [ -z "$$(hg resolv --list)" ] || { echo "There are unresolved merge conflicts" 1>&2; exit 1; }
172 | [ -z "$$(hg status)" ] || \
173 | hg commit -m "Release $(RELEASE_PACKAGE_NAME)-$(RELEASE_DEBIAN_VERSION) - see ChangeLog.txt"
174 | hg tag "$(RELEASE_PACKAGE_NAME)-$(RELEASE_DEBIAN_VERSION)"
175 |
176 |
177 | .PHONY: release-project-clean
178 | release-project-clean::
179 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pam-python-ipcpu
2 |
3 | Linux 的PAM模块,安装后可以调用python脚本执行PAM模块的相关逻辑。
4 |
5 | ##安装
6 |
7 | 编译依赖,依赖于pam、pam-devel模块
8 | ```
9 | yum install pam pam-devel -y
10 | ```
11 |
12 | 编译
13 | ```
14 | make lib
15 | ```
16 |
17 | 找到编译后的.so文件,拷贝到/lib64/security/目录
18 |
19 | ##使用
20 | 可以参照案例 utils/2factor-with-PIN/的相关内容
21 |
22 | 个人网站有详细的应用使用方法。
23 | http://www.ipcpu.com/2016/04/linux-pam-python/
24 |
--------------------------------------------------------------------------------
/README.txt:
--------------------------------------------------------------------------------
1 | pam_python
2 | ==========
3 |
4 | pam_python is a PAM module that runs the Python interpreter
5 | and so allows PAM modules to be written in Python.
6 |
7 | There is extensive documentation shipped as reStructured
8 | text. The build system renders this in the standard Python
9 | HTML documentation style.
10 |
11 | All documentation is readable online at the home page:
12 | http://pam-pathon.sourceforge.net/
13 |
14 |
15 | Dependencies
16 | ------------
17 |
18 | Python >= 2.6, http://www.python.org
19 | pam >= 0.76, http://pam.sourceforge.net/
20 |
21 |
22 | Building and Installing
23 | -----------------------
24 |
25 | The build dependencies are:
26 | - Python2 development system, http://www.python.org
27 | - A POSIX system (make, unix shell, sed, etc).
28 | - The PAM development libraries,
29 | http://pam.sourceforge.net
30 |
31 | In addition the unit test requires:
32 | - sudo, http://www.sudo.ws/
33 | - An account with root privileges.
34 |
35 | To build the re-distributable, in the directory containing
36 | this file run:
37 | make
38 |
39 | To install, in the directory containing this file run:
40 | make install
41 |
42 | To run the test suite, in the directory containing this file run:
43 | make test
44 |
45 |
46 | License
47 | -------
48 |
49 | Copyright (c) 2007-2014,2016 Russell Stuart.
50 |
51 | This program is free software: you can redistribute it and/or modify it
52 | under the terms of the GNU Affero General Public License as published by
53 | the Free Software Foundation, either version 3 of the License, or (at your
54 | option) any later version.
55 |
56 | The copyright holders grant you an additional permission under Section 7
57 | of the GNU Affero General Public License, version 3, exempting you from
58 | the requirement in Section 6 of the GNU General Public License, version 3,
59 | to accompany Corresponding Source with Installation Information for the
60 | Program or any work based on the Program. You are still required to
61 | comply with all other Section 6 requirements to provide Corresponding
62 | Source.
63 |
64 | This program is distributed in the hope that it will be useful,
65 | but WITHOUT ANY WARRANTY; without even the implied warranty of
66 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
67 | GNU Affero General Public License for more details.
68 |
69 |
70 | --
71 | Russell Stuart
72 | 2014-May-29
73 |
--------------------------------------------------------------------------------
/agpl-3.0.txt:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/doc/Makefile:
--------------------------------------------------------------------------------
1 | PREFIX ?= /usr
2 | DOCDIR ?= $(PREFIX)/share/doc/pam_python
3 |
4 | .PHONY: build
5 | build:
6 | sphinx-build -b html -E . html
7 | rm -f html/index.html && ln -s pam_python.html html/index.html
8 |
9 | .PHONY: install install-doc
10 | install: install-doc
11 | install-doc:
12 | mkdir -p $(DESTDIR)$(DOCDIR)/html
13 | cp -a html/* $(DESTDIR)$(DOCDIR)/html
14 | mkdir -p $(DESTDIR)$(DOCDIR)/examples
15 | cp -a ../examples $(DESTDIR)$(DOCDIR)/.
16 |
17 | clean:
18 | rm -rf html
19 |
--------------------------------------------------------------------------------
/doc/conf.py:
--------------------------------------------------------------------------------
1 | master_doc = 'pam_python'
2 | project = u'pam_python'
3 | copyright = u'2010,2014,2016, Russell Stuart'
4 | version = '1.0.5'
5 | release = '1.0.5'
6 | extensions = ['sphinx.ext.intersphinx']
7 | intersphinx_mapping = {'python': ('http://docs.python.org/2.7', None)}
8 |
--------------------------------------------------------------------------------
/doc/pam_permit.py:
--------------------------------------------------------------------------------
1 | #
2 | # Duplicates pam_permit.c
3 | #
4 | DEFAULT_USER = "nobody"
5 |
6 | def pam_sm_authenticate(pamh, flags, argv):
7 | try:
8 | user = pamh.get_user(None)
9 | except pamh.exception, e:
10 | return e.pam_result
11 | if user == None:
12 | pam.user = DEFAULT_USER
13 | return pamh.PAM_SUCCESS
14 |
15 | def pam_sm_setcred(pamh, flags, argv):
16 | return pamh.PAM_SUCCESS
17 |
18 | def pam_sm_acct_mgmt(pamh, flags, argv):
19 | return pamh.PAM_SUCCESS
20 |
21 | def pam_sm_open_session(pamh, flags, argv):
22 | return pamh.PAM_SUCCESS
23 |
24 | def pam_sm_close_session(pamh, flags, argv):
25 | return pamh.PAM_SUCCESS
26 |
27 | def pam_sm_chauthtok(pamh, flags, argv):
28 | return pamh.PAM_SUCCESS
29 |
--------------------------------------------------------------------------------
/doc/pam_python.rst:
--------------------------------------------------------------------------------
1 | **************
2 | |pam_python|
3 | **************
4 |
5 | .. toctree::
6 | :maxdepth: 2
7 |
8 | .. topic:: Abstract
9 |
10 | |Pam_python| is a PAM module that runs the Python interpreter, and so
11 | allows PAM modules to be written in Python.
12 |
13 | :Author: Russell Stuart
14 |
15 |
16 | .. _intro:
17 |
18 | Introduction
19 | ============
20 |
21 | The |pam_python| PAM module runs the Python source file (aka Python PAM
22 | module) it is given in the Python interpreter, making the PAM module API
23 | available to it. This document describes the how the PAM Module API is exposed
24 | to the Python PAM module. It does not describe how to use the API. You must read
25 | the |PMWG|_ to learn how to do that. To re-iterate: this
26 | document does not tell you how to write PAM modules, it only tells you how to
27 | access the PAM module API from Python.
28 |
29 | Writing PAM modules from Python incurs a large performance penalty and requires
30 | Python to be installed, so it is not the best option for writing modules that
31 | will be used widely. On the other hand memory allocation / corruption problems
32 | can not be caused by bad Python code, and a Python module is generally shorter
33 | and easier to write than its C equivalent. This makes it ideal for the system
34 | administrator who just wants to make use of the the PAM API for his own ends
35 | while minimising the risk of introducing memory corruption problems into every
36 | program using PAM.
37 |
38 |
39 | .. _configuring:
40 |
41 | Configuring PAM
42 | ===============
43 |
44 | Tell PAM to use a Python PAM module in the usual way: add a rule to your PAM
45 | configuration. The PAM administrators manual gives the syntax of a rule as::
46 |
47 | service type control module-path module-arguments
48 |
49 | The first three parameters are the same for all PAM modules and so aren't any
50 | different for |pam_python|. The *module-path* is the path to pam_python.so.
51 | Like all paths PAM modules it is relative to the default PAM module directory so
52 | is usually just the string ``pam_python.so``. The first *module-argument* is the
53 | path to the Python PAM module. If it doesn't start with a / it is relative to
54 | the ``/lib/security``. All *module-arguments*, including the path name to the
55 | Python PAM module are passed to it.
56 |
57 |
58 | .. _module:
59 |
60 | Python PAM modules
61 | ==================
62 |
63 | When a PAM handle created by the applications call to PAM's :samp:`pam_start()`
64 | function first uses a Python PAM module, |pam_python| invokes it using Python's
65 | ``execfile`` function. The following variables are passed to the invoked
66 | module in its global namespace:
67 |
68 |
69 | .. data:: __builtins__
70 |
71 | The usual Python ``__builtins__``.
72 |
73 |
74 | .. data:: __file__
75 |
76 | The absolute path name to the Python PAM module.
77 |
78 | As described in the |PMWG|, PAM interacts with your module by calling methods
79 | you provide in it. Each ``type`` in the PAM configuration rules results in one
80 | or more methods being called. The Python PAM module must define the methods that
81 | will be called by each rule ``type`` it can be used with. Those methods are:
82 |
83 |
84 | .. function:: pam_sm_acct_mgmt(pamh, flags, args)
85 |
86 | The service module's implementation of PAM's :manpage:`pam_acct_mgmt(3)` interface.
87 |
88 |
89 | .. function:: pam_sm_authenticate(pamh, flags, args)
90 |
91 | The service module's implementation of PAM's :manpage:`pam_authenticate(3)`
92 | interface.
93 |
94 |
95 | .. function:: pam_sm_close_session(pamh, flags, args)
96 |
97 | The service module's implementation of PAM's :manpage:`pam_close_session(3)`
98 | interface.
99 |
100 |
101 | .. function:: pam_sm_chauthtok(pamh, flags, args)
102 |
103 | The service module's implementation of PAM's :manpage:`pam_chauthtok(3)` interface.
104 |
105 |
106 | .. function:: pam_sm_open_session(pamh, flags, args)
107 |
108 | The service module's implementation of PAM's :manpage:`pam_open_session(3)`
109 | interface.
110 |
111 |
112 | .. function:: pam_sm_setcred(pamh, flags, args)
113 |
114 | The service module's implementation of PAM's :manpage:`pam_setcred(3)` interface.
115 |
116 | The arguments and return value of all these methods are the same. The *pamh*
117 | parameter is an instance of the :class:`PamHandle` class. It is used to interact
118 | with PAM and is described in the next section. The remaining arguments are as
119 | described in the |PMWG|. All functions must return an integer,
120 | eg :const:`pamh.PAM_SUCCESS`. The valid return codes for each function are
121 | defined |PMWG|. If the Python method isn't present
122 | |pam_python| will return :const:`pamh.PAM_SYMBOL_ERR` to PAM; if the method
123 | doesn't return an integer or throws an exception :const:`pamh.PAM_SERVICE_ERR`
124 | is returned.
125 |
126 | There is one other method that in the Python PAM module
127 | that may be called by |pam_python|.
128 | It is optional:
129 |
130 |
131 | .. function:: pam_sm_end(pamh)
132 |
133 | If present this will be called when the application calls PAM's
134 | :manpage:`pam_end(3)` function.
135 | If not present nothing happens.
136 | The parameter *pamh* is the :class:`PamHandle` object.
137 | The return value is ignored.
138 |
139 |
140 | .. _pamhandle:
141 |
142 | The PamHandle Class
143 | ===================
144 |
145 | An instance of this class is automatically created for a Python PAM module when
146 | it is first referenced, (ie when it is ``execfile``'ed). It is the first
147 | argument to every Python method called by PAM. It is destroyed automatically
148 | when PAM's :c:func:`pam_end` is called, right after the ``execfile``'ed
149 | module is destroyed. If any method fails, or any access to a member fails a
150 | :exc:`PamHandle.exception` exception will be thrown. It contains the following
151 | members:
152 |
153 |
154 | .. data:: PAM_???
155 |
156 | All the :const:`PAM_???` constants defined in the PAM include files
157 | version 1.1.1 are available. They are all read-only :class:`int`'s.
158 |
159 |
160 | .. data:: authtok
161 |
162 | The :const:`PAM_AUTHTOK` PAM item. Reading this results in a call
163 | to the |pam-lib-func| :samp:`pam_get_item(PAM_AUTHTOK)`, writing it
164 | results in a call :samp:`pam_set_item(PAM_AUTHTOK, value)`. Its
165 | value will be either a :class:`string` or :const:`None` for the C
166 | value :c:macro:`NULL`.
167 |
168 |
169 | .. data:: authtok_type
170 |
171 | The :const:`PAM_AUTHTOK_TYPE` PAM item. Reading this results in a call
172 | to the |pam-lib-func| :samp:`pam_get_item(PAM_AUTHTOK_TYPE)`, writing it
173 | results in a call :samp:`pam_set_item(PAM_AUTHTOK_TYPE, value)`. Its
174 | value will be either a :class:`string` or :const:`None` for the C
175 | value :c:macro:`NULL`.
176 | New in version 1.0.0.
177 | Only present if the version of PAM |pam_python| is compiled with supports it.
178 |
179 |
180 | .. data:: env
181 |
182 | This is a mapping representing the PAM environment. |pam_python| implements
183 | accesses and changes to it via the |pam-lib-func| :samp:`pam_getenv()`,
184 | :samp:`pam_putenv()` and :samp:`pam_getenvlist()`. The PAM environment
185 | only supports :class:`string` keys and values, and the keys may not be
186 | blank nor contain '='.
187 |
188 |
189 | .. data:: exception
190 |
191 | The exception raised by methods defined here if they fail. It is a
192 | subclass of :class:`StandardError`. Instances contain the member
193 | :const:`pam_result`, which is the error code returned by PAM. The
194 | description is the PAM error message.
195 |
196 |
197 | .. data:: libpam_version
198 |
199 | The version of PAM |pam_python| was compiled with. This is a
200 | :class:`string`. In version 0.1.0 of |pam_python| and prior this was an
201 | :class:`int` holding the version of PAM library loaded. Newer versions of
202 | PAM no longer export that value.
203 |
204 |
205 | .. data:: pamh
206 |
207 | The PAM handle, as read-only :class:`int`. Possibly useful during debugging.
208 |
209 |
210 | .. data:: py_initialized
211 |
212 | A read-only :class:`int`.
213 | If the Python interpreter was initialised
214 | before the |pam_python| module was created this is 0.
215 | Otherwise it is 1, meaning |pam_python| has called :c:func:`Py_Initialize`
216 | and will call :c:func:`Py_Finalize`
217 | when the last |pam_python| module is destroyed.
218 |
219 |
220 | .. data:: oldauthtok
221 |
222 | The :const:`PAM_OLDAUTHTOK` PAM item. Reading this results in a call
223 | to the |pam-lib-func| :samp:`pam_get_item(PAM_OLDAUTHTOK)`,
224 | writing it results in a call :samp:`pam_set_item(PAM_OLDAUTHTOK, value)`.
225 | Its value will be either a :class:`string` or :const:`None` for the
226 | C value :c:macro:`NULL`.
227 |
228 |
229 | .. data:: rhost
230 |
231 | The :const:`PAM_RHOST` PAM item. Reading this results in a call
232 | to the |pam-lib-func| :samp:`pam_get_item(PAM_RHOST)`,
233 | writing it results in a call :samp:`pam_set_item(PAM_RHOST, value)`.
234 | Its value will be either a :class:`string`
235 | or :const:`None` for the C value :c:macro:`NULL`.
236 |
237 |
238 | .. data:: ruser
239 |
240 | The :const:`PAM_RUSER` PAM item. Reading this results in a call
241 | to the |pam-lib-func| :samp:`pam_get_item(PAM_RUSER)`,
242 | writing it results in a call :samp:`pam_set_item(PAM_RUSER, value)`.
243 | Its value will be either a :class:`string`
244 | or :const:`None` for the C value :c:macro:`NULL`.
245 |
246 |
247 | .. data:: service
248 |
249 | The :const:`PAM_SERVICE` PAM item. Reading this results in a call
250 | to the |pam-lib-func| :samp:`pam_get_item(PAM_SERVICE)`,
251 | writing it results in a call :samp:`pam_set_item(PAM_SERVICE, value)`.
252 | Its value will be either a :class:`string`
253 | or :const:`None` for the C value :c:macro:`NULL`.
254 |
255 |
256 | .. data:: tty
257 |
258 | The :const:`PAM_TTY` PAM item. Reading this results in a call
259 | to the |pam-lib-func| :samp:`pam_get_item(PAM_TTY)`,
260 | writing it results in a call :samp:`pam_set_item(PAM_TTY, value)`.
261 | Its value will be either a :class:`string`
262 | or :const:`None` for the C value :c:macro:`NULL`.
263 |
264 |
265 | .. data:: user
266 |
267 | The :const:`PAM_USER` PAM item. Reading this results in a call
268 | to the |pam-lib-func| :samp:`pam_get_item(PAM_USER)`,
269 | writing it results in a call :samp:`pam_set_item(PAM_USER, value)`.
270 | Its value will be either a :class:`string`
271 | or :const:`None` for the C value :c:macro:`NULL`.
272 |
273 |
274 | .. data:: user_prompt
275 |
276 | The :const:`PAM_USER_PROMPT` PAM item. Reading this results in a call
277 | to the |pam-lib-func| :samp:`pam_get_item(PAM_USER_PROMPT)`,
278 | writing it results in a call :samp:`pam_set_item(PAM_USER_PROMPT, value)`.
279 | Its value will be either a :class:`string`
280 | or :const:`None` for the C value :c:macro:`NULL`.
281 |
282 |
283 | .. data:: xauthdata
284 |
285 | The :const:`PAM_XAUTHDATA` PAM item. Reading this results in a call
286 | to the |pam-lib-func| :samp:`pam_get_item(PAM_XAUTHDATA)`,
287 | writing it results in a call :samp:`pam_set_item(PAM_XAUTHDATA, value)`.
288 | Its value is a :class:`XAuthData` instance. When setting its value you
289 | don't have to use an actual :class:`XAuthData` instance,
290 | any class that contains a :class:`string` member :attr:`name`
291 | and a :class:`string` member :attr:`data` will do.
292 | New in version 1.0.0.
293 | Only present if the version of PAM |pam_python| is compiled with supports it.
294 |
295 |
296 | .. data:: xdisplay
297 |
298 | The :const:`PAM_XDISPLAY` PAM item. Reading this results in a call
299 | to the |pam-lib-func| :samp:`pam_get_item(PAM_XDISPLAY)`,
300 | writing it results in a call :samp:`pam_set_item(PAM_XDISPLAY, value)`.
301 | Its value will be either a :class:`string`
302 | or :const:`None` for the C value :c:macro:`NULL`.
303 | New in version 1.0.0.
304 | Only present if the version of PAM |pam_python| is compiled with supports it.
305 |
306 | The following methods are available:
307 |
308 |
309 | .. method:: PamHandle.Message(msg_style,msg)
310 |
311 | Creates an instance of the :class:`Message` class.
312 | The arguments become the instance members of the same name.
313 | This class is used to represent the C API's ``struct pam_message`` type.
314 | An instance has two members corresponding
315 | to the C structure members of the same name:
316 | :attr:`msg_style` an :class:`int`
317 | and :attr:`data` a :class:`string`.
318 | Instances are immutable.
319 | Instances of this class can be passed to the :meth:`conversation` method.
320 |
321 |
322 | .. method:: PamHandle.Response(resp,ret_code)
323 |
324 | Creates an instance of the :class:`Response` class.
325 | The arguments become the instance members of the same name.
326 | This class is used to represent the C API's ``struct pam_response`` type.
327 | An instance has two members
328 | corresponding to the C structure members of the same name:
329 | :attr:`resp` a :class:`string`
330 | and :attr:`ret_code` an :class:`int`.
331 | Instances are immutable.
332 | Instances of this class are returned by the :meth:`conversation` method.
333 |
334 |
335 | .. method:: PamHandle.XAuthData(name,data)
336 |
337 | Creates an instance of the :class:`XAuthData` class.
338 | The arguments become the instance members of the same name.
339 | This class is used to represent the C API's ``struct pam_xauth_data`` type.
340 | An instance has two members
341 | corresponding to the C structure members of the same name:
342 | :attr:`name` a :class:`string` and :attr:`data` also a :class:`string`.
343 | Instances are immutable.
344 | The :data:`xauthdata` member returns instances of this class and
345 | can be set to an instance of this class.
346 |
347 |
348 | .. method:: PamHandle.conversation(prompts)
349 |
350 | Calls the function defined by the PAM :c:macro:`PAM_CONV` item.
351 | The *prompts* argument is a :class:`Message` object
352 | or a :class:`list` of them.
353 | You don't have to pass an actual :class:`Message` object,
354 | any class that contains a :class:`string` member :attr:`msg`
355 | and a :class:`int` member :attr:`msg_style` will do.
356 | These members are used to initialise the ``struct pam_message``
357 | members of the same name. It returns either a single :class:`Response`
358 | object if a single :class:`Message` was passed,
359 | or a :class:`list` of them of the same length as the :class:`list` passed.
360 | These :class:`Response` objects contain the data the user entered.
361 |
362 |
363 | .. method:: PamHandle.fail_delay(delay)
364 |
365 | This results in a call to the |pam-lib-func| :samp:`pam_fail_delay()`,
366 | which sets the maximum random delay after an authentication failure
367 | to *delay* milliseconds.
368 |
369 |
370 | .. method:: PamHandle.get_user([prompt])
371 |
372 | This results in a call to the |pam-lib-func| :samp:`pam_get_user()`,
373 | which returns the current user name (a :class:`string`)
374 | or :const:`None` if :samp:`pam_get_user()` returns :c:macro:`NULL`.
375 | If not known it asks the PAM application for the user name,
376 | giving it the :class:`string` *prompt* parameter
377 | to prompt the user to enter it.
378 |
379 |
380 | .. method:: PamHandle.strerror(errnum)
381 |
382 | This results in a call to the |pam-lib-func| :samp:`pam_strerror()`,
383 | which returns a :class:`string` description of the :class:`int`
384 | PAM return value *errnum*.
385 |
386 | There is no interface provided for the |pam-lib-func|\s :samp:`pam_get_data()`
387 | and :samp:`pam_set_data()`. There are two reasons for this.
388 | Firstly those two methods are provided so C code can have private storage
389 | local to the PAM handle. A Python PAM Module can use own module name space
390 | to do the same job, and it's easier to do so. But more importantly it's
391 | safer because there is no type-safe way of providing access to the facility
392 | from Python.
393 |
394 |
395 | .. _diagnostics:
396 |
397 | Diagnostics, Debugging, Bugs
398 | ============================
399 |
400 | The way |pam_python| operates will be foreign to most Python programmers.
401 | It embeds Python into existing programs, primarily ones written in C.
402 | This means things like debugging and diagnostics
403 | are done differently to a normal Python program.
404 |
405 |
406 | .. _return-values:
407 |
408 | Diagnostics
409 | -----------
410 |
411 | If |pam_python| returns something other than :const:`PAM_SUCCESS` to PAM a
412 | message will be written to the ``syslog`` ``LOG_AUTHPRIV`` facility. The only
413 | exception to this is when |pam_python| is passing on the return value from
414 | a Python :meth:`pam_sm_...` entry point - nothing is logged in that case.
415 | So, if your Python PAM Module is failing in mysterious ways
416 | check the log file your system is configured to write
417 | ``LOG_AUTHPRIV`` entries to.
418 | Usually this is :file:`/var/log/syslog` or :file:`/var/log/auth.log`.
419 | The diagnostic or traceback Python would normally print to :attr:`sys.stderr`
420 | will be in there.
421 |
422 | The PAM result codes returned directly by |pam_python| are:
423 |
424 |
425 | .. data:: PAM_BUF_ERR
426 |
427 | Memory allocation failed.
428 |
429 |
430 | .. data:: PAM_MODULE_UNKNOWN
431 |
432 | The Python PAM module name wasn't supplied.
433 |
434 |
435 | .. data:: PAM_OPEN_ERR
436 |
437 | The Python PAM module could not be opened.
438 |
439 |
440 | .. data:: PAM_SERVICE_ERR
441 |
442 | A Python exception was thrown, unless it was because of a memory allocation
443 | failure.
444 |
445 |
446 | .. data:: PAM_SYMBOL_ERR
447 |
448 | A :meth:`pam_sm_...` called by PAM wasn't defined by the Python PAM module.
449 |
450 |
451 | .. _debugging:
452 |
453 | Debugging
454 | ---------
455 |
456 | If you have Python bindings for the PAM Application library then you can write
457 | test units in Python and use Pythons :mod:`pdb` module debug a Python PAM
458 | module. This is how |pam_python| was developed.
459 |
460 | I used `PyPAM `_ for the Python Application
461 | library bindings. Distributions often package it as ``python-pam``. To set
462 | breakpoints in :mod:`pdb` either wait until PAM has loaded your module, or
463 | :keyword:`import` it before you start debugging.
464 |
465 |
466 | .. _bugs:
467 |
468 | Bugs
469 | ----
470 |
471 | There are several design decisions you may stumble across when using
472 | |pam_python|. One is that the Python PAM module is isolated from the rest
473 | of the Python environment. This differs from a :keyword:`import`'ed Python module,
474 | where regardless of how many times a module is imported there is only one copy
475 | that shares the one global name space.
476 | For example, if you :keyword:`import` your Python PAM module
477 | and then debug it as suggested above then there will be 2
478 | copies of your Python PAM module in memory -
479 | the imported one and the one PAM is using.
480 | If the PAM module sets a global variable you won't see it in the
481 | :keyword:`import`'ed one. Indeed, obtaining any sort of handle to the module
482 | PAM is using is near impossible. This means the debugger can inspect variables
483 | in the module only when a breakpoint has one of the modules functions in its
484 | backtrace.
485 |
486 | There are a few of reasons for this. Firstly, the |PMWG| says
487 | this is the way it should be, so |pam_python| encourages it. Secondly, if a
488 | PAM application is using a Python PAM Module it's important the PAM module
489 | remains as near to invisible as possible to avoid conflicts. Finally, and most
490 | importantly, references to objects constructed by the Python PAM module must
491 | never leak. This is because the destructors to those objects are C functions
492 | that live in |pam_python|, and those destructors are called when all
493 | references to the objects are gone. When the application calls |pam-lib-func|
494 | :samp:`pam_end()` function |pam_python| is unloaded, and with it goes the
495 | destructor code. Should a reference to an object defined by |pam_python| exist
496 | after :samp:`pam_end()` returns the call to destructor
497 | will result in a jump to a non-existent address causing a ``SIGSEGV``.
498 |
499 | Another potential trap is the initialisation and finalisation of the Python
500 | interpreter itself. Calling the interpreter's finalisation routine while it is
501 | in use would I imagine be a big no-no. If |pam_python| has to initialise
502 | the interpreter (by calling :c:func:`Py_Initialize`) then it will call its
503 | finaliser :c:func:`Py_Finalize` when the last Python PAM module is destroyed.
504 | This is heuristic works in most scenarios. One example where is won't work is a
505 | sequence like::
506 |
507 | start-python-pam-module;
508 | application-initialises-interpreter;
509 | stop-python-pam-module;
510 | application-stops-interpreter.
511 |
512 | The above is doomed to fail.
513 |
514 |
515 | .. _example:
516 |
517 | An example
518 | ==========
519 |
520 | This is one of the examples provided by the package:
521 |
522 |
523 | .. include:: pam_permit.py
524 | :literal:
525 |
526 | Assuming it and ``pam_python.so`` are in the directory ``/lib/security`` adding
527 | these rules to ``/etc/pam.conf`` would run it::
528 |
529 | login account requisite pam_python.so pam_accept.py
530 | login auth requisite pam_python.so pam_accept.py
531 | login password requisite pam_python.so pam_accept.py
532 | login session requisite pam_python.so pam_accept.py
533 |
534 | .. |PMWG| replace:: PAM Module Writers Guide
535 |
536 | .. _PMWG: http://www.linux-pam.org/Linux-PAM-html/
537 |
538 | .. |pam_python| replace:: `pam_python`
539 |
540 | .. |pam-lib-func| replace:: PAM library function
541 |
--------------------------------------------------------------------------------
/examples/pam_deny.py:
--------------------------------------------------------------------------------
1 | #
2 | # Duplicates pam_deny.c
3 | #
4 | def pam_sm_authenticate(pamh, flags, argv):
5 | return pamh.PAM_AUTH_ERR
6 |
7 | def pam_sm_setcred(pamh, flags, argv):
8 | return pamh.PAM_CRED_UNAVAIL
9 |
10 | def pam_sm_acct_mgmt(pamh, flags, argv):
11 | return pamh.PAM_ACCT_EXPIRED
12 |
13 | def pam_sm_chauthtok(pamh, flags, argv):
14 | return pamh.PAM_AUTHTOK_ERR
15 |
16 | def pam_sm_open_session(pamh, flags, argv):
17 | return pamh.PAM_SYSTEM_ERR
18 |
19 | def pam_sm_close_session(pamh, flags, argv):
20 | return pamh.PAM_SYSTEM_ERR
21 |
--------------------------------------------------------------------------------
/examples/pam_nologin.py:
--------------------------------------------------------------------------------
1 | #
2 | # Emulate what pam_nologin.c does.
3 | #
4 | import pwd
5 |
6 | #
7 | # Parse our command line.
8 | #
9 | def parse_args(pamh, argv):
10 | #
11 | # Parse the arguments.
12 | #
13 | nologin_file = "/etc/nologin"
14 | retval_when_nofile = pamh.PAM_IGNORE
15 | for arg in argv[1:]:
16 | if arg.starts_with("file="):
17 | nologin_file = arg[5:]
18 | elif arg == "successok":
19 | retval_when_nofile = pamh.PAM_SUCCESS
20 | return nologin_file, retval_when_nofile
21 |
22 | #
23 | # Check the /etc/nologin file.
24 | #
25 | def check_nologin(pamh, nologin_file, retval_when_nofile):
26 | #
27 | # Get the user name.
28 | #
29 | try:
30 | username = pamh.get_user()
31 | except pamh.exception:
32 | username = None
33 | if username == None:
34 | return pamh.PAM_USER_UNKNOWN
35 | #
36 | # Can we open the file?
37 | #
38 | try:
39 | handle = file(nologin_file, "r")
40 | except EnvironmentError:
41 | return retval_when_nofile
42 | #
43 | # Print the message.
44 | #
45 | try:
46 | try:
47 | msg = handle.read()
48 | except EnvironmentError:
49 | return pamh.PAM_SYSTEM_ERR
50 | finally:
51 | handle.close()
52 | #
53 | # Read the user's password entry so we can check if he is root.
54 | # Root can login regardless.
55 | #
56 | try:
57 | pwent = pwd.getpwnam(username)
58 | except KeyError:
59 | retval = pamh.PAM_USER_UNKNOWN
60 | msg_style = pamh.PAM_ERROR_MSG
61 | else:
62 | if pwent[2] == 0: # Is this root?
63 | retval = pamh.PAM_SUCCESS
64 | msg_style = pamh.PAM_TEXT_INFO
65 | else:
66 | retval = pamh.PAM_AUTH_ERR
67 | msg_style = pamh.PAM_ERROR_MSG
68 | #
69 | # Display the message
70 | #
71 | try:
72 | pamh.conversation(pamh.Message(msg_style, msg))
73 | except pamh.exception:
74 | return pamh.PAM_SYSTEM_ERR
75 | return retval
76 |
77 | #
78 | # Entry points we handle.
79 | #
80 | def pam_sm_authenticate(pamh, flags, argv):
81 | nologin_file, retval_when_nofile = parse_args(pamh, argv)
82 | return check_nologin(pamh, nologin_file, retval_when_nofile)
83 |
84 | def pam_sm_setcred(pamh, flags, argv):
85 | nologin_file, retval_when_nofile = parse_args(pamh, argv)
86 | return retval_when_nofile
87 |
88 | def pam_sm_acct_mgmt(pamh, flags, argv):
89 | nologin_file, retval_when_nofile = parse_args(pamh, argv)
90 | return check_nologin(pamh, nologin_file, retval_when_nofile)
91 |
--------------------------------------------------------------------------------
/examples/pam_permit.py:
--------------------------------------------------------------------------------
1 | #
2 | # Duplicates pam_permit.c
3 | #
4 | DEFAULT_USER = "nobody"
5 |
6 | def pam_sm_authenticate(pamh, flags, argv):
7 | try:
8 | user = pamh.get_user(None)
9 | except pamh.exception, e:
10 | return e.pam_result
11 | if user == None:
12 | pamh.user = DEFAULT_USER
13 | return pamh.PAM_SUCCESS
14 |
15 | def pam_sm_setcred(pamh, flags, argv):
16 | return pamh.PAM_SUCCESS
17 |
18 | def pam_sm_acct_mgmt(pamh, flags, argv):
19 | return pamh.PAM_SUCCESS
20 |
21 | def pam_sm_open_session(pamh, flags, argv):
22 | return pamh.PAM_SUCCESS
23 |
24 | def pam_sm_close_session(pamh, flags, argv):
25 | return pamh.PAM_SUCCESS
26 |
27 | def pam_sm_chauthtok(pamh, flags, argv):
28 | return pamh.PAM_SUCCESS
29 |
--------------------------------------------------------------------------------
/pam-python.html:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 | pam-python - write PAM modules in Python
8 |
9 |
10 |
11 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | Pam-python
24 | Write PAM modules in Python
25 |
26 |
27 |
28 | Pam-python is a PAM Module that runs the Python interpreter,
29 | thus allowing PAM Modules to be written in Python.
30 |
31 |
32 | Documentation
33 |
34 |
35 | There is a
36 | documentation page,
37 | some examples, a
38 | change log and a
39 | README.txt.
40 | The documentation page must be read in conjunction with the
41 | PAM Module Writers Guide.
42 |
43 |
44 | Copyright and License
45 |
46 |
47 | Pam-python is copyright © 2007-2012,2014,2016 Russell Stuart.
48 | It is licensed under the GNU Affero General Public License.
49 |
50 |
51 |
52 | This program is free software: you can redistribute it and/or modify it
53 | under the terms of the GNU Affero General Public License as published by
54 | the Free Software Foundation, either version 3 of the License, or (at your
55 | option) any later version.
56 |
57 |
58 |
59 | The copyright holders grant you an additional permission under Section 7
60 | of the GNU Affero General Public License, version 3, exempting you from
61 | the requirement in Section 6 of the GNU General Public License, version 3,
62 | to accompany Corresponding Source with Installation Information for the
63 | Program or any work based on the Program. You are still required to
64 | comply with all other Section 6 requirements to provide Corresponding
65 | Source.
66 |
67 |
68 |
69 | This program is distributed in the hope that it will be useful,
70 | but WITHOUT ANY WARRANTY; without even the implied warranty of
71 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
72 | GNU Affero General Public License for more details.
73 |
74 |
75 | Downloading, Feedback & Contributing
76 |
77 |
78 | Development for pam-python is hosted on
79 | Source forge:
80 |
81 |
82 |
83 | -
84 | Download area,
85 | (.tar.gz, .deb).
86 |
87 | -
88 | Issue tracker,
89 | bugs, features or just questions.
90 |
91 | -
92 | Source repository.
93 |
94 | -
95 | Pam-python is part of Debian.
96 | Most Debian derived distribution can install using apt-get.
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 | Russell Stuart, 2014-May-29.
105 |
106 |
107 |
108 |
109 |
--------------------------------------------------------------------------------
/src/Makefile:
--------------------------------------------------------------------------------
1 | all: ctest pam_python.so test-pam_python.pam
2 |
3 | WARNINGS=-Wall -Wextra -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wsign-compare -Waggregate-return -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Werror
4 | #WARNINGS=-Wunreachable-code # Gcc 4.1 .. 4.4 are too buggy to make this useful
5 |
6 | LIBDIR ?= /lib64/security
7 |
8 | pam_python.so: pam_python.c setup.py Makefile
9 | @rm -f "$@"
10 | @[ ! -e build -o build/lib.*/$@ -nt setup.py -a build/lib.*/$@ -nt Makefile ] || rm -r build
11 | CFLAGS="$(WARNINGS)" ./setup.py build
12 | @#CFLAGS="-O0 $(WARNINGS)" ./setup.py build --debug
13 | @#CFLAGS="-O0 $(WARNINGS)" Py_DEBUG=1 ./setup.py build --debug
14 | ln -sf build/lib.*/$@ .
15 |
16 | .PHONY: install install-lib
17 | install: install-lib
18 | install-lib:
19 | mkdir -p $(DESTDIR)$(LIBDIR)
20 | cp build/lib.*/pam_python.so $(DESTDIR)$(LIBDIR)
21 |
22 | .PHONY: clean
23 | clean:
24 | rm -rf build ctest pam_python.so test-pam_python.pam test.pyc core
25 | [ ! -e /etc/pam.d/test-pam_python.pam ] || { s=$$([ $$(id -u) = 0 ] || echo sudo); $$s rm -f /etc/pam.d/test-pam_python.pam; }
26 |
27 | .PHONY: ctest
28 | ctest: ctest.c Makefile
29 | gcc -O0 $(WARNINGS) -g -o $@ ctest.c -lpam
30 |
31 | test-pam_python.pam: test-pam_python.pam.in Makefile
32 | sed "s,\\\$$PWD,$$(pwd),g" "$@.in" >"$@.tmp"
33 | mv $@.tmp $@
34 |
35 | /etc/pam.d/test-pam_python.pam: test-pam_python.pam
36 | s=$$([ $$(id -u) = 0 ] || echo sudo); $$s ln -sf $$(pwd)/test-pam_python.pam /etc/pam.d
37 |
38 | .PHONY: test
39 | test: pam_python.so ctest /etc/pam.d/test-pam_python.pam
40 | python test.py
41 | ./ctest
42 |
--------------------------------------------------------------------------------
/src/build/lib.linux-x86_64-2.6/pam_python.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ipcpu/pam-python-ipcpu/098bf3b399a2b988453a1fc3a90e16fe063bc527/src/build/lib.linux-x86_64-2.6/pam_python.so
--------------------------------------------------------------------------------
/src/build/temp.linux-x86_64-2.6/pam_python.o:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ipcpu/pam-python-ipcpu/098bf3b399a2b988453a1fc3a90e16fe063bc527/src/build/temp.linux-x86_64-2.6/pam_python.o
--------------------------------------------------------------------------------
/src/ctest:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ipcpu/pam-python-ipcpu/098bf3b399a2b988453a1fc3a90e16fe063bc527/src/ctest
--------------------------------------------------------------------------------
/src/ctest.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Best compiled & run using the Makefile target "test". To compile and run
3 | * manually:
4 | * gcc -O0 -g -Wall -o test -lpam test.c
5 | * sudo ln -s $PWD/test-pam_python.pam /etc/pam.d
6 | * ./ctest
7 | * sudo rm /etc/pam.d/test-pam_python.pam
8 | */
9 | #define _GNU_SOURCE
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 |
17 | struct walk_info {
18 | int libpam_python_seen;
19 | int python_seen;
20 | };
21 |
22 | static int conv(
23 | int num_msg, const struct pam_message** msg, struct pam_response** resp, void *appdata_ptr)
24 | {
25 | int i;
26 |
27 | appdata_ptr = appdata_ptr;
28 | *resp = malloc(num_msg * sizeof(**resp));
29 | for (i = 0; i < num_msg; i += 1)
30 | {
31 | (*resp)[i].resp = strdup((*msg)[i].msg);
32 | (*resp)[i].resp_retcode = (*msg)[i].msg_style;
33 | }
34 | return 0;
35 | }
36 |
37 | static void call_pam(
38 | int* exit_status, const char* who, pam_handle_t* pamh,
39 | int (*func)(pam_handle_t*, int))
40 | {
41 | int pam_result = (*func)(pamh, 0);
42 |
43 | if (pam_result == PAM_SUCCESS)
44 | return;
45 | fprintf(
46 | stderr, "%s failed: %d %s\n",
47 | who, pam_result, pam_strerror(pamh, pam_result));
48 | *exit_status = 1;
49 | }
50 |
51 | static int dl_walk(struct dl_phdr_info* info, size_t size, void* data)
52 | {
53 | struct walk_info* walk_info = data;
54 |
55 | size = size;
56 | if (strstr(info->dlpi_name, "/pam_python.so") != 0)
57 | walk_info->libpam_python_seen = 1;
58 | if (strstr(info->dlpi_name, "/libpython") != 0)
59 | walk_info->python_seen = 1;
60 | return 0;
61 | }
62 |
63 | static void walk_dlls(struct walk_info* walk_info)
64 | {
65 | walk_info->libpam_python_seen = 0;
66 | walk_info->python_seen = 0;
67 | dl_iterate_phdr(dl_walk, walk_info);
68 | }
69 |
70 | int main(int argc, char **argv)
71 | {
72 | int exit_status;
73 | struct pam_conv convstruct;
74 | pam_handle_t* pamh;
75 | struct walk_info walk_info_before;
76 | struct walk_info walk_info_after;
77 |
78 | argc = argc;
79 | argv = argv;
80 | if (access("/etc/pam.d/test-pam_python.pam", 0) != 0)
81 | {
82 | fprintf(
83 | stderr,
84 | "**WARNING**\n"
85 | " This test requires ./test-pam_python.pam configuration to be\n"
86 | " available to PAM But it doesn't appear to be in /etc/pam.d.\n"
87 | );
88 | }
89 | printf("Testing calls from C");
90 | fflush(stdout);
91 | convstruct.conv = conv;
92 | convstruct.appdata_ptr = 0;
93 | if (pam_start("test-pam_python.pam", "", &convstruct, &pamh) == -1)
94 | {
95 | fprintf(stderr, "pam_start failed\n");
96 | exit(1);
97 | }
98 | exit_status = 0;
99 | call_pam(&exit_status, "pam_authenticate", pamh, pam_authenticate);
100 | call_pam(&exit_status, "pam_chauthtok", pamh, pam_chauthtok);
101 | call_pam(&exit_status, "pam_acct_mgmt", pamh, pam_acct_mgmt);
102 | call_pam(&exit_status, "pam_open_session", pamh, pam_open_session);
103 | call_pam(&exit_status, "pam_close_session", pamh, pam_close_session);
104 | walk_dlls(&walk_info_before);
105 | call_pam(&exit_status, "pam_end", pamh, pam_end);
106 | if (exit_status == 0)
107 | printf(" OK\n");
108 | walk_dlls(&walk_info_after);
109 | printf("Testing dll load/unload ");
110 | if (!walk_info_before.libpam_python_seen)
111 | {
112 | fprintf(stderr, "It looks like pam_python.so wasn't loaded!\n");
113 | exit_status = 1;
114 | }
115 | else if (!walk_info_before.python_seen)
116 | {
117 | fprintf(stderr, "It looks like libpythonX.Y.so wasn't loaded!\n");
118 | exit_status = 1;
119 | }
120 | else if (walk_info_after.libpam_python_seen)
121 | {
122 | fprintf(stderr, "pam_python.so wasn't unloaded.\n");
123 | exit_status = 1;
124 | }
125 | else if (walk_info_after.python_seen)
126 | {
127 | fprintf(stderr, "libpythonX.Y.so wasn't uloaded.\n");
128 | exit_status = 1;
129 | }
130 | else
131 | printf("OK\n");
132 | return exit_status;
133 | }
134 |
--------------------------------------------------------------------------------
/src/pam_python.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2007-2012,2014,2016 Russell Stuart
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as published
6 | * by the Free Software Foundation, either version 3 of the License, or (at
7 | * your option) any later version.
8 | *
9 | * The copyright holders grant you an additional permission under Section 7
10 | * of the GNU Affero General Public License, version 3, exempting you from
11 | * the requirement in Section 6 of the GNU General Public License, version 3,
12 | * to accompany Corresponding Source with Installation Information for the
13 | * Program or any work based on the Program. You are still required to
14 | * comply with all other Section 6 requirements to provide Corresponding
15 | * Source.
16 | *
17 | * This program is distributed in the hope that it will be useful, but
18 | * WITHOUT ANY WARRANTY; without even the implied warranty of
19 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 | * Affero General Public License for more details.
21 | *
22 | * You should have received a copy of the GNU Affero General Public License
23 | * along with this program. If not, see .
24 | */
25 |
26 | #define PAM_SM_AUTH
27 | #define PAM_SM_ACCOUNT
28 | #define PAM_SM_SESSION
29 | #define PAM_SM_PASSWORD
30 |
31 | #include
32 | //#include
33 |
34 | #undef _POSIX_C_SOURCE
35 |
36 | #include
37 | #include
38 | #include
39 | #include
40 | #include
41 |
42 | #ifndef MODULE_NAME
43 | #define MODULE_NAME "libpam_python"
44 | #endif
45 |
46 | #ifndef DEFAULT_SECURITY_DIR
47 | #define DEFAULT_SECURITY_DIR "/lib64/security/"
48 | #endif
49 |
50 | #define PAMHANDLE_NAME "PamHandle"
51 |
52 | #define PAMHANDLEEXCEPTION_NAME "PamException"
53 |
54 | #define arr_size(x) (sizeof(x) / sizeof(*(x)))
55 |
56 | const char libpam_python_version[] = "1.0.3";
57 | const char libpam_python_date[] = "2014-05-05";
58 |
59 | /*
60 | * Add typedef for Py_ssize_t if it you have an older python.
61 | */
62 | #if (PY_VERSION_HEX < 0x02050000)
63 | typedef int Py_ssize_t;
64 | #endif
65 |
66 | /*
67 | * The python interpreter's shared library.
68 | */
69 | static char libpython_so[] = LIBPYTHON_SO;
70 |
71 | /*
72 | * Initialise Python. How this should be done changed between versions.
73 | */
74 | static void initialise_python(void)
75 | {
76 | #if PY_MAJOR_VERSION*100 + PY_MINOR_VERSION >= 204
77 | Py_InitializeEx(0);
78 | #else
79 | size_t signum;
80 | struct sigaction oldsigaction[NSIG];
81 |
82 | for (signum = 0; signum < arr_size(oldsigaction); signum += 1)
83 | sigaction(signum, 0, &oldsigaction[signum]);
84 | Py_Initialize();
85 | for (signum = 0; signum < arr_size(oldsigaction); signum += 1)
86 | sigaction(signum, &oldsigaction[signum], 0);
87 | #endif
88 | }
89 |
90 | /*
91 | * The Py_XDECREF macro gives warnings. This function doesn't.
92 | */
93 | static void py_xdecref(PyObject* object)
94 | {
95 | Py_XDECREF(object);
96 | }
97 |
98 | /*
99 | * Generic traverse function for heap objects.
100 | */
101 | static int generic_traverse(PyObject* self, visitproc visitor, void* arg)
102 | {
103 | PyMemberDef* member;
104 | int member_visible;
105 | PyObject* object;
106 | int py_result;
107 | PyObject** slot;
108 |
109 | member = self->ob_type->tp_members;
110 | if (member == 0)
111 | return 0;
112 | /*
113 | * Loop for python visible and python non-visible members.
114 | */
115 | for (member_visible = 0; member_visible < 2; member_visible += 1)
116 | {
117 | for (; member->name != 0; member += 1)
118 | {
119 | if (member->type != T_OBJECT && member->type != T_OBJECT_EX)
120 | continue;
121 | slot = (PyObject**)((char*)self + member->offset);
122 | object = *slot;
123 | if (object == 0)
124 | continue;
125 | py_result = visitor(object, arg);
126 | if (py_result != 0)
127 | return py_result;
128 | }
129 | member += 1;
130 | }
131 | return 0;
132 | }
133 |
134 | /*
135 | * Clear all slots in the object.
136 | */
137 | static void clear_slot(PyObject** slot)
138 | {
139 | PyObject* object;
140 |
141 | object = *slot;
142 | if (object != 0)
143 | {
144 | *slot = 0;
145 | Py_DECREF(object);
146 | }
147 | }
148 |
149 | static int generic_clear(PyObject* self)
150 | {
151 | PyMemberDef* member;
152 | int member_visible;
153 |
154 | member = self->ob_type->tp_members;
155 | if (member == 0)
156 | return 0;
157 | /*
158 | * Loop for python visible and python non-visible members.
159 | */
160 | for (member_visible = 0; member_visible < 2; member_visible += 1)
161 | {
162 | for (; member->name != 0; member += 1)
163 | {
164 | if (member->type != T_OBJECT && member->type != T_OBJECT_EX)
165 | continue;
166 | clear_slot((PyObject**)((char*)self + member->offset));
167 | }
168 | member += 1;
169 | }
170 | return 0;
171 | }
172 |
173 | /*
174 | * A dealloc for all our objects.
175 | */
176 | static void generic_dealloc(PyObject* self)
177 | {
178 | PyTypeObject* type = self->ob_type;
179 |
180 | if (PyObject_IS_GC(self))
181 | PyObject_GC_UnTrack(self);
182 | if (type->tp_clear != 0)
183 | type->tp_clear(self);
184 | type->tp_free(self);
185 | }
186 |
187 | /*
188 | * The PamHandleObject - the object passed to all the python module's entry
189 | * points.
190 | */
191 | typedef struct
192 | {
193 | PyObject_HEAD /* The Python Object Header */
194 | void* dlhandle; /* dlopen() handle */
195 | PyObject* env; /* pamh.env */
196 | PyObject* exception; /* pamh.exception */
197 | char* libpam_version; /* pamh.libpam_version */
198 | PyTypeObject* message; /* pamh.Message */
199 | PyObject* module; /* The Python Pam Module */
200 | pam_handle_t* pamh; /* The pam handle */
201 | PyObject* print_exception;/* traceback.print_exception */
202 | int py_initialized; /* True if Py_initialize() called */
203 | PyTypeObject* response; /* pamh.Response */
204 | PyObject* syslogFile; /* A (the) SyslogFile instance */
205 | PyTypeObject* xauthdata; /* pamh.XAuthData */
206 | } PamHandleObject;
207 |
208 | /*
209 | * Forward declarations.
210 | */
211 | static int call_python_handler(
212 | PyObject** result, PamHandleObject* pamHandle,
213 | PyObject* handler_function, const char* handler_name,
214 | int flags, int argc, const char** argv);
215 |
216 | /*
217 | * The SyslogfileObject. It emulates a Python file object (in that it has
218 | * a write method). It prints to stuff passed to write() on syslog.
219 | */
220 | #define SYSLOGFILE_NAME "SyslogFile"
221 | typedef struct
222 | {
223 | PyObject_HEAD /* The Python Object Header */
224 | char* buffer; /* Line buffer */
225 | int size; /* Size of the buffer in bytes */
226 | } SyslogFileObject;
227 |
228 | /*
229 | * Clear the SyslogFileObject for the garbage collector.
230 | */
231 | static int SyslogFile_clear(PyObject* self)
232 | {
233 | SyslogFileObject* syslogFile = (SyslogFileObject*)self;
234 |
235 | PyMem_Free(syslogFile->buffer);
236 | syslogFile->buffer = 0;
237 | syslogFile->size = 0;
238 | return generic_clear(self);
239 | }
240 |
241 | /*
242 | * Emulate python's file.write(), but write to syslog.
243 | */
244 | static PyObject* SyslogFile_write(
245 | PyObject* self, PyObject* args, PyObject* kwds)
246 | {
247 | SyslogFileObject* syslogFile = (SyslogFileObject*)self;
248 | const char* c;
249 | const char* data = 0;
250 | int len;
251 | const char* newline;
252 | PyObject* result = 0;
253 | static char* kwlist[] = {"data", NULL};
254 |
255 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:write", kwlist, &data))
256 | goto error_exit;
257 | if (syslogFile->buffer == 0)
258 | len = 0;
259 | else
260 | len = strlen(syslogFile->buffer);
261 | len += strlen(data) + 1;
262 | if (len > syslogFile->size)
263 | {
264 | const int new_size = len * 2;
265 | syslogFile->buffer = PyMem_Realloc(syslogFile->buffer, new_size);
266 | if (syslogFile->buffer == 0)
267 | {
268 | syslogFile->size = 0;
269 | goto error_exit;
270 | }
271 | if (syslogFile->size == 0)
272 | syslogFile->buffer[0] = '\0';
273 | syslogFile->size = new_size;
274 | }
275 | strcat(syslogFile->buffer, data);
276 | for (c = syslogFile->buffer; *c != '\0'; c = newline + 1) {
277 | newline = strchr(c, '\n');
278 | if (newline == 0)
279 | break;
280 | syslog(LOG_AUTHPRIV|LOG_ERR, "%.*s", (int)(newline - c), c);
281 | }
282 | if (c != syslogFile->buffer)
283 | strcpy(syslogFile->buffer, c);
284 | result = Py_None;
285 | Py_INCREF(result);
286 |
287 | error_exit:
288 | return result;
289 | }
290 |
291 | /*
292 | * Emulate python's file.flush(), but write to syslog.
293 | */
294 | static void SyslogFile_flush(PyObject* self)
295 | {
296 | SyslogFileObject* syslogFile = (SyslogFileObject*)self;
297 |
298 | if (syslogFile->buffer != 0 && syslogFile->buffer[0] != '\0')
299 | {
300 | syslog(LOG_AUTHPRIV|LOG_ERR, "%s", syslogFile->buffer);
301 | syslogFile->buffer[0] = '\0';
302 | }
303 | }
304 |
305 | static PyMethodDef SyslogFile_Methods[] =
306 | {
307 | {
308 | "write",
309 | (PyCFunction)SyslogFile_write,
310 | METH_VARARGS|METH_KEYWORDS,
311 | 0
312 | },
313 | {0,0,0,0} /* Sentinal */
314 | };
315 |
316 | /*
317 | * Open syslog.
318 | */
319 | static void syslog_open(const char* module_path)
320 | {
321 | openlog(module_path, LOG_CONS|LOG_PID, LOG_AUTHPRIV);
322 | }
323 |
324 | /*
325 | * Close syslog.
326 | */
327 | static void syslog_close(void)
328 | {
329 | closelog();
330 | }
331 |
332 | /*
333 | * Type to translate a Python Exception to a PAM error.
334 | */
335 | static int syslog_python2pam(PyObject* exception_type)
336 | {
337 | if (exception_type == PyExc_MemoryError)
338 | return PAM_BUF_ERR;
339 | return PAM_SERVICE_ERR;
340 | }
341 |
342 | /*
343 | * Return the modules filename.
344 | */
345 | static const char* get_module_path(PamHandleObject* pamHandle)
346 | {
347 | const char* result = PyModule_GetFilename(pamHandle->module);
348 | if (result != 0)
349 | return result;
350 | return MODULE_NAME;
351 | }
352 |
353 | /*
354 | * Print an exception to syslog.
355 | */
356 | static int syslog_path_exception(const char* module_path, const char* errormsg)
357 | {
358 | PyObject* message = 0;
359 | PyObject* name = 0;
360 | PyObject* ptype = 0;
361 | PyObject* ptraceback = 0;
362 | PyObject* pvalue = 0;
363 | int pam_result = 0;
364 | PyObject* stype = 0;
365 | const char* str_name = 0;
366 | const char* str_message = 0;
367 |
368 | PyErr_Fetch(&ptype, &pvalue, &ptraceback);
369 | /*
370 | * We don't have a PamHandleObject, so we can't print a full traceback.
371 | * Just print the exception in some recognisable form, hopefully.
372 | */
373 | syslog_open(module_path);
374 | if (PyClass_Check(ptype))
375 | stype = PyObject_GetAttrString(ptype, "__name__");
376 | else
377 | {
378 | stype = ptype;
379 | Py_INCREF(stype);
380 | }
381 | if (stype != 0)
382 | {
383 | name = PyObject_Str(stype);
384 | if (name != 0)
385 | str_name = PyString_AsString(name);
386 | }
387 | if (pvalue != 0)
388 | {
389 | message = PyObject_Str(pvalue);
390 | if (message != 0)
391 | str_message = PyString_AsString(message);
392 | }
393 | if (errormsg != 0 && str_name != 0 && str_message != 0)
394 | {
395 | syslog(
396 | LOG_AUTHPRIV|LOG_ERR, "%s - %s: %s",
397 | errormsg, str_name, str_message);
398 | }
399 | else if (str_name != 0 && str_message != 0)
400 | syslog(LOG_AUTHPRIV|LOG_ERR, "%s: %s", str_name, str_message);
401 | else if (errormsg != 0 && str_name != 0)
402 | syslog(LOG_AUTHPRIV|LOG_ERR, "%s - %s", errormsg, str_name);
403 | else if (errormsg != 0 && str_message != 0)
404 | syslog(LOG_AUTHPRIV|LOG_ERR, "%s - %s", errormsg, str_message);
405 | else if (errormsg != 0)
406 | syslog(LOG_AUTHPRIV|LOG_ERR, "%s", errormsg);
407 | else if (str_name != 0)
408 | syslog(LOG_AUTHPRIV|LOG_ERR, "%s", str_name);
409 | else if (str_message != 0)
410 | syslog(LOG_AUTHPRIV|LOG_ERR, "%s", str_message);
411 | pam_result = syslog_python2pam(ptype);
412 | py_xdecref(message);
413 | py_xdecref(name);
414 | py_xdecref(ptraceback);
415 | py_xdecref(ptype);
416 | py_xdecref(pvalue);
417 | py_xdecref(stype);
418 | syslog_close();
419 | return pam_result;
420 | }
421 |
422 | /*
423 | * Print an exception to syslog, once we are initialised.
424 | */
425 | static int syslog_exception(PamHandleObject* pamHandle, const char* errormsg)
426 | {
427 | return syslog_path_exception(get_module_path(pamHandle), errormsg);
428 | }
429 |
430 | /*
431 | * Print an message to syslog.
432 | */
433 | static int syslog_path_vmessage(
434 | const char* module_path, const char* message, va_list ap)
435 | {
436 | syslog_open(module_path);
437 | vsyslog(LOG_AUTHPRIV|LOG_ERR, message, ap);
438 | syslog_close();
439 | return PAM_SERVICE_ERR;
440 | }
441 |
442 | /*
443 | * Print an message to syslog.
444 | */
445 | static int syslog_path_message(
446 | const char* module_path, const char* message, ...)
447 | {
448 | va_list ap;
449 | int result;
450 |
451 | va_start(ap, message);
452 | result = syslog_path_vmessage(module_path, message, ap);
453 | va_end(ap);
454 | return result;
455 | }
456 |
457 | /*
458 | * Print an message to syslog, once we are initialised.
459 | */
460 | static int syslog_message(PamHandleObject* pamHandle, const char* message, ...)
461 | {
462 | va_list ap;
463 | int result;
464 |
465 | va_start(ap, message);
466 | result = syslog_path_vmessage(get_module_path(pamHandle), message, ap);
467 | va_end(ap);
468 | return result;
469 | }
470 |
471 | /*
472 | * Print a traceback to syslog.
473 | */
474 | static int syslog_path_traceback(
475 | const char* module_path, PamHandleObject* pamHandle)
476 | {
477 | PyObject* args = 0;
478 | PyObject* ptraceback = 0;
479 | PyObject* ptype = 0;
480 | PyObject* pvalue = 0;
481 | PyObject* py_resultobj = 0;
482 | int pam_result;
483 |
484 | PyErr_Fetch(&ptype, &pvalue, &ptraceback);
485 | /*
486 | * If there isn't a traceback just log the exception.
487 | */
488 | if (ptraceback == 0)
489 | {
490 | PyErr_Restore(ptype, pvalue, ptraceback);
491 | return syslog_path_exception(module_path, 0);
492 | }
493 | /*
494 | * Bit messy, this. The easiest way to print a traceback is to use
495 | * the traceback module, writing through a dummy file that actually
496 | * outputs to syslog.
497 | */
498 | syslog_open(module_path);
499 | if (ptype == 0)
500 | {
501 | ptype = Py_None;
502 | Py_INCREF(ptype);
503 | }
504 | if (pvalue == 0)
505 | {
506 | pvalue = Py_None;
507 | Py_INCREF(pvalue);
508 | }
509 | args = Py_BuildValue(
510 | "OOOOO", ptype, pvalue, ptraceback, Py_None, pamHandle->syslogFile);
511 | if (args != 0)
512 | {
513 | py_resultobj = PyEval_CallObject(pamHandle->print_exception, args);
514 | if (py_resultobj != 0)
515 | SyslogFile_flush(pamHandle->syslogFile);
516 | }
517 | pam_result = syslog_python2pam(ptype);
518 | py_xdecref(args);
519 | py_xdecref(ptraceback);
520 | py_xdecref(ptype);
521 | py_xdecref(pvalue);
522 | py_xdecref(py_resultobj);
523 | syslog_close();
524 | return pam_result;
525 | }
526 |
527 | /*
528 | * Print an message to syslog, once we are initialised.
529 | */
530 | static int syslog_traceback(PamHandleObject* pamHandle)
531 | {
532 | return syslog_path_traceback(get_module_path(pamHandle), pamHandle);
533 | }
534 |
535 | /*
536 | * The PamMessage object - used in conversations.
537 | */
538 | #define PAMMESSAGE_NAME "Message"
539 | typedef struct
540 | {
541 | PyObject_HEAD /* The Python Object header */
542 | int msg_style; /* struct pam_message.msg_style */
543 | PyObject* msg; /* struct pam_message.msg */
544 | } PamMessageObject;
545 |
546 | static char PamMessage_doc[] =
547 | MODULE_NAME "." PAMHANDLE_NAME "." PAMMESSAGE_NAME "(msg_style, msg)\n"
548 | " Constructs an immutable object that can be passed to\n"
549 | " " MODULE_NAME "." PAMHANDLE_NAME ".conversation(). The parameters are\n"
550 | " assigned to readonly members of the same name. msg_style determines what\n"
551 | " is done (eg prompt for input, write a message), and msg is the prompt or\n"
552 | " message.";
553 |
554 | static PyMemberDef PamMessage_members[] =
555 | {
556 | {
557 | "msg_style",
558 | T_INT,
559 | offsetof(PamMessageObject, msg_style),
560 | READONLY,
561 | "What to do with the msg member, eg display it or use as a prompt.",
562 | },
563 | {
564 | "msg",
565 | T_OBJECT_EX,
566 | offsetof(PamMessageObject, msg),
567 | READONLY,
568 | "The text to display to the user",
569 | },
570 | {0,0,0,0,0}, /* End of Python visible members */
571 | {0,0,0,0,0} /* Sentinal */
572 | };
573 |
574 | static PyObject* PamMessage_new(
575 | PyTypeObject* type, PyObject* args, PyObject* kwds)
576 | {
577 | int err;
578 | PyObject* msg = 0;
579 | int msg_style = 0;
580 | PamMessageObject* pamMessage = 0;
581 | PyObject* self = 0;
582 | static char* kwlist[] = {"msg_style", "msg", 0};
583 |
584 | err = PyArg_ParseTupleAndKeywords(
585 | args, kwds, "iO!:Message", kwlist,
586 | &msg_style, &PyString_Type, &msg);
587 | if (!err)
588 | goto error_exit;
589 | pamMessage = (PamMessageObject*)type->tp_alloc(type, 0);
590 | if (pamMessage == 0)
591 | goto error_exit;
592 | pamMessage->msg_style = msg_style;
593 | pamMessage->msg = msg;
594 | Py_INCREF(pamMessage->msg);
595 | self = (PyObject*)pamMessage;
596 | pamMessage = 0;
597 |
598 | error_exit:
599 | py_xdecref((PyObject*)pamMessage);
600 | return self;
601 | }
602 |
603 | /*
604 | * The PamResponse object - used in conversations.
605 | */
606 | #define PAMRESPONSE_NAME "Response"
607 | typedef struct
608 | {
609 | PyObject_HEAD /* The Python Object header */
610 | PyObject* resp; /* struct pam_response.resp */
611 | int resp_retcode; /* struct pam_response.resp_retcode */
612 | } PamResponseObject;
613 |
614 | static char PamResponse_doc[] =
615 | MODULE_NAME "." PAMHANDLE_NAME "." PAMRESPONSE_NAME "(resp, resp_retcode)\n"
616 | " Constructs an immutable object that is returned by\n"
617 | " " MODULE_NAME "." PAMHANDLE_NAME ".conversation(). The parameters are\n"
618 | " assigned to readonly members of the same name. resp is the response from\n"
619 | " the user (if one was asked for), and resp_retcode says what it means.";
620 |
621 | static PyMemberDef PamResponse_members[] =
622 | {
623 | {
624 | "resp",
625 | T_OBJECT_EX,
626 | offsetof(PamResponseObject, resp),
627 | READONLY,
628 | "The response from the user.",
629 | },
630 | {
631 | "resp_retcode",
632 | T_INT,
633 | offsetof(PamResponseObject, resp_retcode),
634 | READONLY,
635 | "The type of response.",
636 | },
637 | {0,0,0,0,0}, /* End of Python visible members */
638 | {0,0,0,0,0} /* Sentinal */
639 | };
640 |
641 | static PyObject* PamResponse_new(
642 | PyTypeObject* type, PyObject* args, PyObject* kwds)
643 | {
644 | int err;
645 | PyObject* resp = 0;
646 | int resp_retcode = 0;
647 | PamResponseObject* pamResponse = 0;
648 | PyObject* self = 0;
649 | static char* kwlist[] = {"resp", "resp_retcode", 0};
650 |
651 | err = PyArg_ParseTupleAndKeywords(
652 | args, kwds, "Oi:Response", kwlist,
653 | &resp, &resp_retcode);
654 | if (!err)
655 | goto error_exit;
656 | if (resp != Py_None && !PyString_Check(resp))
657 | {
658 | PyErr_SetString(PyExc_TypeError, "resp must be a string or None");
659 | goto error_exit;
660 | }
661 | pamResponse = (PamResponseObject*)type->tp_alloc(type, 0);
662 | if (pamResponse == 0)
663 | goto error_exit;
664 | pamResponse->resp_retcode = resp_retcode;
665 | pamResponse->resp = resp;
666 | Py_INCREF(pamResponse->resp);
667 | self = (PyObject*)pamResponse;
668 | pamResponse = 0;
669 |
670 | error_exit:
671 | py_xdecref((PyObject*)pamResponse);
672 | return self;
673 | }
674 |
675 | /*
676 | * The PamXAuthData object - used by PAM_XAUTHDATA item.
677 | */
678 | #define PAMXAUTHDATA_NAME "XAuthData"
679 | typedef struct
680 | {
681 | PyObject_HEAD /* The Python Object header */
682 | PyObject* name; /* struct pam_xauth_data.name */
683 | PyObject* data; /* struct pam_xauth_data.data */
684 | } PamXAuthDataObject;
685 |
686 | static char PamXAuthData_doc[] =
687 | MODULE_NAME "." PAMHANDLE_NAME "." PAMXAUTHDATA_NAME "(name, data)\n"
688 | " Constructs an immutable object is returned by and can be passed to\n"
689 | " the " MODULE_NAME ".xauthdata property. The parameters are\n"
690 | " assigned to readonly members of the same name.";
691 |
692 | static PyMemberDef PamXAuthData_members[] =
693 | {
694 | {
695 | "data",
696 | T_OBJECT_EX,
697 | offsetof(PamXAuthDataObject, data),
698 | READONLY,
699 | "The value of the data item. A string or None.",
700 | },
701 | {
702 | "name",
703 | T_OBJECT_EX,
704 | offsetof(PamXAuthDataObject, name),
705 | READONLY,
706 | "The name of the data item. A string or None.",
707 | },
708 | {0,0,0,0,0}, /* End of Python visible members */
709 | {0,0,0,0,0} /* Sentinal */
710 | };
711 |
712 | static PyObject* PamXAuthData_new(
713 | PyTypeObject* type, PyObject* args, PyObject* kwds)
714 | {
715 | int err;
716 | PyObject* name = 0;
717 | PyObject* data = 0;
718 | PamXAuthDataObject* pamXAuthData = 0;
719 | PyObject* self = 0;
720 | static char* kwlist[] = {"name", "data", 0};
721 |
722 | err = PyArg_ParseTupleAndKeywords(
723 | args, kwds, "SS:XAuthData", kwlist,
724 | &name, &data);
725 | if (!err)
726 | goto error_exit;
727 | pamXAuthData = (PamXAuthDataObject*)type->tp_alloc(type, 0);
728 | if (pamXAuthData == 0)
729 | goto error_exit;
730 | pamXAuthData->name = name;
731 | Py_INCREF(pamXAuthData->name);
732 | pamXAuthData->data = data;
733 | Py_INCREF(pamXAuthData->data);
734 | self = (PyObject*)pamXAuthData;
735 | pamXAuthData = 0;
736 |
737 | error_exit:
738 | py_xdecref((PyObject*)pamXAuthData);
739 | return self;
740 | }
741 |
742 | /*
743 | * Check a PAM return value. If the function failed raise an exception
744 | * and return -1.
745 | */
746 | static int check_pam_result(PamHandleObject* pamHandle, int pam_result)
747 | {
748 | if (pam_result == PAM_SUCCESS)
749 | return 0;
750 | if (!PyErr_Occurred())
751 | {
752 | PyObject* ptype;
753 | PyObject* pvalue;
754 | PyObject* ptraceback;
755 | PyObject* error_code = 0;
756 | const char* error_string = pam_strerror(pamHandle->pamh, pam_result);
757 |
758 | PyErr_SetString(pamHandle->exception, error_string);
759 | PyErr_Fetch(&ptype, &pvalue, &ptraceback);
760 | PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
761 | error_code = PyInt_FromLong(pam_result);
762 | if (error_code != NULL)
763 | PyObject_SetAttrString(pvalue, "pam_result", error_code);
764 | PyErr_Restore(ptype, pvalue, ptraceback);
765 | py_xdecref(error_code);
766 | }
767 | return -1;
768 | }
769 |
770 | /*
771 | * Python getters / setters are used to manipulate PAM's items.
772 | */
773 | static PyObject* PamHandle_get_item(PyObject* self, int item_type)
774 | {
775 | PamHandleObject* pamHandle = (PamHandleObject*)self;
776 | const char* value;
777 | PyObject* result = 0;
778 | int pam_result;
779 |
780 | pam_result = pam_get_item(pamHandle->pamh, item_type, (const void**)&value);
781 | if (check_pam_result(pamHandle, pam_result) == -1)
782 | goto error_exit;
783 | if (value != 0)
784 | result = PyString_FromString(value);
785 | else
786 | {
787 | result = Py_None;
788 | Py_INCREF(result);
789 | }
790 |
791 | error_exit:
792 | return result;
793 | }
794 |
795 | static int PamHandle_set_item(
796 | PyObject* self, int item_type, char* item_name, PyObject* pyValue)
797 | {
798 | PamHandleObject* pamHandle = (PamHandleObject*)self;
799 | int pam_result;
800 | int result = -1;
801 | char* value;
802 | char error_message[64];
803 |
804 | if (pyValue == Py_None)
805 | value = 0;
806 | else
807 | {
808 | value = PyString_AsString(pyValue);
809 | if (value == 0)
810 | {
811 | snprintf(
812 | error_message, sizeof(error_message),
813 | "PAM item %s must be set to a string", item_name);
814 | PyErr_SetString(PyExc_TypeError, error_message);
815 | goto error_exit;
816 | }
817 | value = strdup(value);
818 | if (value == 0)
819 | {
820 | PyErr_NoMemory();
821 | goto error_exit;
822 | }
823 | }
824 | pam_result = pam_set_item(pamHandle->pamh, item_type, value);
825 | if (pam_result == PAM_SUCCESS)
826 | value = 0;
827 | result = check_pam_result(pamHandle, pam_result);
828 |
829 | error_exit:
830 | if (value != 0)
831 | free(value);
832 | return result;
833 | }
834 |
835 | /*
836 | * The PAM Environment Object & its iterator.
837 | */
838 | #define PAMENV_NAME "PamEnv"
839 | typedef struct
840 | {
841 | PyObject_HEAD /* The Python Object header */
842 | PamHandleObject* pamHandle; /* The PamHandle that owns us */
843 | PyTypeObject* pamEnvIter_type;/* A class for our iterators */
844 | } PamEnvObject;
845 |
846 | static PyMemberDef PamEnv_Members[] =
847 | {
848 | {0,0,0,0,0}, /* End of Python visible members */
849 | {
850 | "Iter",
851 | T_OBJECT_EX,
852 | offsetof(PamEnvObject, pamEnvIter_type),
853 | READONLY,
854 | "Iterator class for " PAMENV_NAME
855 | },
856 | {0,0,0,0,0} /* Sentinel */
857 | };
858 |
859 | #define PAMENVITER_NAME "PamEnvIter"
860 | typedef struct
861 | {
862 | PyObject_HEAD
863 | PamEnvObject* env; /* The PamEnvObject we are iterating */
864 | int pos; /* Nest position to return */
865 | PyObject* (*get_entry)(const char* entry); /* What to return */
866 | } PamEnvIterObject;
867 |
868 | static PyMemberDef PamEnvIter_Members[] =
869 | {
870 | {0,0,0,0,0}, /* End of Python visible members */
871 | {
872 | "env",
873 | T_OBJECT_EX,
874 | offsetof(PamEnvIterObject, env),
875 | READONLY,
876 | "Dictionary to iterate"
877 | },
878 | {0,0,0,0,0} /* Sentinel */
879 | };
880 |
881 | /*
882 | * Create a new iterator for a PamEnv.
883 | */
884 | static PyObject* PamEnvIter_create(
885 | PamEnvObject* pamEnv, PyObject* (*get_entry)(const char* entry))
886 | {
887 | PyTypeObject* type = pamEnv->pamEnvIter_type;
888 | PamEnvIterObject* pamEnvIter;
889 | PyObject* result = 0;
890 |
891 | pamEnvIter = (PamEnvIterObject*)type->tp_alloc(type, 0);
892 | if (pamEnvIter == 0)
893 | goto error_exit;
894 | pamEnvIter->env = pamEnv;
895 | Py_INCREF(pamEnvIter->env);
896 | pamEnvIter->get_entry = get_entry;
897 | pamEnvIter->pos = 0;
898 | result = (PyObject*)pamEnvIter;
899 | Py_INCREF(result);
900 |
901 | error_exit:
902 | py_xdecref((PyObject*)pamEnvIter);
903 | return result;
904 | }
905 |
906 | /*
907 | * Return the next object in the iteration.
908 | */
909 | static PyObject* PamEnvIter_iternext(PyObject* self)
910 | {
911 | PamEnvIterObject* pamEnvIter = (PamEnvIterObject*)self;
912 | char** env;
913 | int i;
914 | PyObject* result;
915 |
916 | if (pamEnvIter->env == 0)
917 | goto error_exit;
918 | env = pam_getenvlist(pamEnvIter->env->pamHandle->pamh);
919 | if (env == 0)
920 | goto error_exit;
921 | for (i = 0; env[i] != 0 && i < pamEnvIter->pos; i += 1)
922 | continue;
923 | if (env[i] == 0)
924 | goto error_exit;
925 | result = pamEnvIter->get_entry(env[i]);
926 | if (result == 0)
927 | goto error_exit;
928 | pamEnvIter->pos += 1;
929 | return result;
930 |
931 | error_exit:
932 | clear_slot((PyObject**)&pamEnvIter->env);
933 | return 0;
934 | }
935 |
936 | /*
937 | * Return a python object for the key part.
938 | */
939 | static PyObject* PamEnvIter_key_entry(const char* entry)
940 | {
941 | const char* equals;
942 |
943 | equals = strchr(entry, '=');
944 | if (equals == 0)
945 | return PyString_FromString(entry);
946 | return PyString_FromStringAndSize(entry, equals - entry);
947 | }
948 |
949 | /*
950 | * Return a python object for the value part.
951 | */
952 | static PyObject* PamEnvIter_value_entry(const char* entry)
953 | {
954 | const char* equals;
955 |
956 | equals = strchr(entry, '=');
957 | if (equals == 0)
958 | return PyString_FromString("");
959 | return PyString_FromString(equals + 1);
960 | }
961 |
962 | /*
963 | * Return a python object entire item.
964 | */
965 | static PyObject* PamEnvIter_item_entry(const char* entry)
966 | {
967 | PyObject* key = 0;
968 | PyObject* result = 0;
969 | PyObject* tuple = 0;
970 | PyObject* value = 0;
971 |
972 | key = PamEnvIter_key_entry(entry);
973 | if (key == 0)
974 | goto error_exit;
975 | value = PamEnvIter_value_entry(entry);
976 | if (key == 0)
977 | goto error_exit;
978 | tuple = PyTuple_New(2);
979 | if (tuple == 0)
980 | goto error_exit;
981 | if (PyTuple_SetItem(tuple, 0, key) == -1)
982 | goto error_exit;
983 | key = 0; /* was stolen */
984 | if (PyTuple_SetItem(tuple, 1, value) == -1)
985 | goto error_exit;
986 | value = 0; /* was stolen */
987 | result = tuple;
988 | tuple = 0;
989 |
990 | error_exit:
991 | py_xdecref(key);
992 | py_xdecref(tuple);
993 | py_xdecref(value);
994 | return result;
995 | }
996 |
997 | /*
998 | * Create an iterator.
999 | */
1000 | static PyObject* PamEnv_iter(PyObject* self)
1001 | {
1002 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1003 |
1004 | return PamEnvIter_create(pamEnv, PamEnvIter_key_entry);
1005 | }
1006 |
1007 | /*
1008 | * Get the value of a environment key.
1009 | */
1010 | static const char* PamEnv_getkey(PyObject* key)
1011 | {
1012 | const char* result;
1013 |
1014 | if (!PyString_Check(key))
1015 | {
1016 | PyErr_SetString(PyExc_TypeError, "PAM environment key must be a string");
1017 | return 0;
1018 | }
1019 | result = PyString_AS_STRING(key);
1020 | if (*result == '\0')
1021 | {
1022 | PyErr_SetString(
1023 | PyExc_ValueError,
1024 | "PAM environment key mustn't be 0 length");
1025 | return 0;
1026 | }
1027 | if (strchr(result, '=') != 0)
1028 | {
1029 | PyErr_SetString(PyExc_ValueError, "PAM environment key can't contain '='");
1030 | return 0;
1031 | }
1032 | return result;
1033 | }
1034 |
1035 | /*
1036 | * Return the length.
1037 | */
1038 | static Py_ssize_t PamEnv_mp_length(PyObject* self)
1039 | {
1040 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1041 | char** env;
1042 | int length;
1043 |
1044 | env = pam_getenvlist(pamEnv->pamHandle->pamh);
1045 | if (env == 0)
1046 | return 0;
1047 | for (length = 0; env[length] != 0; length += 1)
1048 | continue;
1049 | return length;
1050 | }
1051 |
1052 | /*
1053 | * Lookup a key returning its value.
1054 | */
1055 | static PyObject* PamEnv_mp_subscript(PyObject* self, PyObject* key)
1056 | {
1057 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1058 | PyObject* result = 0;
1059 | const char* key_str;
1060 | const char* value;
1061 |
1062 | key_str = PamEnv_getkey(key);
1063 | if (key_str == 0)
1064 | goto error_exit;
1065 | value = pam_getenv(pamEnv->pamHandle->pamh, key_str);
1066 | if (value == 0)
1067 | {
1068 | PyErr_SetString(PyExc_KeyError, key_str);
1069 | goto error_exit;
1070 | }
1071 | result = PyString_FromString(value);
1072 |
1073 | error_exit:
1074 | return result;
1075 | }
1076 |
1077 | /*
1078 | * Assign a value to a key, or delete it.
1079 | */
1080 | static int PamEnv_mp_assign(PyObject* self, PyObject* key, PyObject* value)
1081 | {
1082 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1083 | char* value_str = 0;
1084 | int result = -1;
1085 | const char* key_str;
1086 | int pam_result;
1087 |
1088 | key_str = PamEnv_getkey(key);
1089 | if (key_str == 0)
1090 | goto error_exit;
1091 | if (value == 0)
1092 | value_str = (char*)key_str;
1093 | else
1094 | {
1095 | if (!PyString_Check(value))
1096 | {
1097 | PyErr_SetString(
1098 | PyExc_TypeError, "PAM environment value must be a string");
1099 | goto error_exit;
1100 | }
1101 | value_str = malloc(PyString_Size(key) + 1 + PyString_Size(value) + 1);
1102 | if (value_str == 0)
1103 | {
1104 | PyErr_NoMemory();
1105 | goto error_exit;
1106 | }
1107 | strcat(strcat(strcpy(value_str, key_str), "="), PyString_AS_STRING(value));
1108 | }
1109 | pam_result = pam_putenv(pamEnv->pamHandle->pamh, value_str);
1110 | if (pam_result == PAM_BAD_ITEM)
1111 | {
1112 | PyErr_SetString(PyExc_KeyError, key_str);
1113 | goto error_exit;
1114 | }
1115 | if (check_pam_result(pamEnv->pamHandle, pam_result) == -1)
1116 | goto error_exit;
1117 | value_str = 0;
1118 | result = 0;
1119 |
1120 | error_exit:
1121 | if (value_str != key_str && value_str != 0)
1122 | free(value_str);
1123 | return result;
1124 | }
1125 |
1126 | static PyMappingMethods PamEnv_as_mapping =
1127 | {
1128 | PamEnv_mp_length, /* mp_length */
1129 | PamEnv_mp_subscript, /* mp_subscript */
1130 | PamEnv_mp_assign, /* mp_ass_subscript */
1131 | };
1132 |
1133 | /*
1134 | * Check if a key is in the environment.
1135 | */
1136 | static PyObject* PamEnv_has_key(
1137 | PyObject* self, PyObject* args, PyObject* kwds)
1138 | {
1139 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1140 | PyObject* key;
1141 | PyObject* result = 0;
1142 | const char* key_str;
1143 | const char* value_str;
1144 | static char* kwlist[] = {"key", NULL};
1145 |
1146 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:has_key", kwlist, &key))
1147 | goto error_exit;
1148 | key_str = PamEnv_getkey(key);
1149 | if (key_str == 0)
1150 | goto error_exit;
1151 | value_str = pam_getenv(pamEnv->pamHandle->pamh, key_str);
1152 | result = value_str != 0 ? Py_True : Py_False;
1153 | Py_INCREF(result);
1154 |
1155 | error_exit:
1156 | return result;
1157 | }
1158 |
1159 | /*
1160 | * Lookup a key and return its value, throwing KeyError if the key
1161 | * doesn't exist.
1162 | */
1163 | static PyObject* PamEnv_getitem(
1164 | PyObject* self, PyObject* args, PyObject* kwds)
1165 | {
1166 | PyObject* result = 0;
1167 | PyObject* key;
1168 | static char* kwlist[] = {"key", NULL};
1169 |
1170 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:__getitem__", kwlist, &key))
1171 | goto error_exit;
1172 | result = PamEnv_mp_subscript(self, key);
1173 |
1174 | error_exit:
1175 | return result;
1176 | }
1177 |
1178 | /*
1179 | * Lookup a key and return its value, returning None or a default if it
1180 | * doesn't exist.
1181 | */
1182 | static PyObject* PamEnv_get(
1183 | PyObject* self, PyObject* args, PyObject* kwds)
1184 | {
1185 | int err;
1186 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1187 | PyObject* default_value = 0;
1188 | PyObject* result = 0;
1189 | PyObject* key;
1190 | const char* key_str;
1191 | const char* value_str;
1192 | static char* kwlist[] = {"key", "default", NULL};
1193 |
1194 | err = PyArg_ParseTupleAndKeywords(
1195 | args, kwds, "O|O:get", kwlist,
1196 | &key, &default_value);
1197 | if (!err)
1198 | goto error_exit;
1199 | key_str = PamEnv_getkey(key);
1200 | if (key_str == 0)
1201 | goto error_exit;
1202 | value_str = pam_getenv(pamEnv->pamHandle->pamh, key_str);
1203 | if (value_str != 0)
1204 | result = PyString_FromString(value_str);
1205 | else
1206 | {
1207 | result = default_value != 0 ? default_value : Py_None;
1208 | Py_INCREF(result);
1209 | }
1210 |
1211 | error_exit:
1212 | return result;
1213 | }
1214 |
1215 | /*
1216 | * Return all objects in the environment as a sequence.
1217 | */
1218 | static PyObject* PamEnv_as_sequence(
1219 | PyObject* self, PyObject* (*get_entry)(const char* entry))
1220 | {
1221 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1222 | PyObject* list = 0;
1223 | PyObject* result = 0;
1224 | PyObject* entry = 0;
1225 | char** env;
1226 | int i;
1227 | int length;
1228 |
1229 | env = pam_getenvlist(pamEnv->pamHandle->pamh);
1230 | if (env == 0)
1231 | length = 0;
1232 | else
1233 | {
1234 | for (length = 0; env[length] != 0; length += 1)
1235 | continue;
1236 | }
1237 | list = PyList_New(length);
1238 | if (list == 0)
1239 | goto error_exit;
1240 | for (i = 0; env[i] != 0; i += 1)
1241 | {
1242 | entry = get_entry(env[i]);
1243 | if (entry == 0)
1244 | goto error_exit;
1245 | if (PyList_SetItem(list, i, entry) == -1)
1246 | goto error_exit;
1247 | entry = 0; /* was stolen */
1248 | }
1249 | result = list;
1250 | list = 0;
1251 |
1252 | error_exit:
1253 | py_xdecref(list);
1254 | py_xdecref(entry);
1255 | return result;
1256 | }
1257 |
1258 | /*
1259 | * Return all (key, value) pairs.
1260 | */
1261 | static PyObject* PamEnv_items(
1262 | PyObject* self, PyObject* args, PyObject* kwds)
1263 | {
1264 | static char* kwlist[] = {NULL};
1265 |
1266 | if (!PyArg_ParseTupleAndKeywords(args, kwds, ":items", kwlist))
1267 | return 0;
1268 | return PamEnv_as_sequence(self, PamEnvIter_item_entry);
1269 | }
1270 |
1271 | /*
1272 | * An iterator for all (key, value) pairs.
1273 | */
1274 | static PyObject* PamEnv_iteritems(
1275 | PyObject* self, PyObject* args, PyObject* kwds)
1276 | {
1277 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1278 | static char* kwlist[] = {NULL};
1279 |
1280 | if (!PyArg_ParseTupleAndKeywords(args, kwds, ":iteritems", kwlist))
1281 | return 0;
1282 | return PamEnvIter_create(pamEnv, PamEnvIter_item_entry);
1283 | }
1284 |
1285 | /*
1286 | * An iterator for the keys.
1287 | */
1288 | static PyObject* PamEnv_iterkeys(
1289 | PyObject* self, PyObject* args, PyObject* kwds)
1290 | {
1291 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1292 | static char* kwlist[] = {NULL};
1293 |
1294 | if (!PyArg_ParseTupleAndKeywords(args, kwds, ":iterkeys", kwlist))
1295 | return 0;
1296 | return PamEnvIter_create(pamEnv, PamEnvIter_key_entry);
1297 | }
1298 |
1299 | /*
1300 | * An iterator for the values.
1301 | */
1302 | static PyObject* PamEnv_itervalues(
1303 | PyObject* self, PyObject* args, PyObject* kwds)
1304 | {
1305 | PamEnvObject* pamEnv = (PamEnvObject*)self;
1306 | static char* kwlist[] = {NULL};
1307 |
1308 | if (!PyArg_ParseTupleAndKeywords(args, kwds, ":itervalues", kwlist))
1309 | return 0;
1310 | return PamEnvIter_create(pamEnv, PamEnvIter_value_entry);
1311 | }
1312 |
1313 | /*
1314 | * Return all keys.
1315 | */
1316 | static PyObject* PamEnv_keys(
1317 | PyObject* self, PyObject* args, PyObject* kwds)
1318 | {
1319 | static char* kwlist[] = {NULL};
1320 |
1321 | if (!PyArg_ParseTupleAndKeywords(args, kwds, ":keys", kwlist))
1322 | return 0;
1323 | return PamEnv_as_sequence(self, PamEnvIter_key_entry);
1324 | }
1325 |
1326 | /*
1327 | * Return all (key, value) pairs.
1328 | */
1329 | static PyObject* PamEnv_values(
1330 | PyObject* self, PyObject* args, PyObject* kwds)
1331 | {
1332 | static char* kwlist[] = {NULL};
1333 |
1334 | if (!PyArg_ParseTupleAndKeywords(args, kwds, ":values", kwlist))
1335 | return 0;
1336 | return PamEnv_as_sequence(self, PamEnvIter_value_entry);
1337 | }
1338 |
1339 | static PyMethodDef PamEnv_Methods[] =
1340 | {
1341 | {"__contains__", (PyCFunction)PamEnv_has_key,METH_VARARGS|METH_KEYWORDS, 0},
1342 | {"__getitem__", (PyCFunction)PamEnv_getitem,METH_VARARGS|METH_KEYWORDS, 0},
1343 | {"get", (PyCFunction)PamEnv_get, METH_VARARGS|METH_KEYWORDS, 0},
1344 | {"has_key", (PyCFunction)PamEnv_has_key,METH_VARARGS|METH_KEYWORDS, 0},
1345 | {"items", (PyCFunction)PamEnv_items, METH_VARARGS|METH_KEYWORDS, 0},
1346 | {"iteritems", (PyCFunction)PamEnv_iteritems,METH_VARARGS|METH_KEYWORDS, 0},
1347 | {"iterkeys", (PyCFunction)PamEnv_iterkeys,METH_VARARGS|METH_KEYWORDS, 0},
1348 | {"itervalues", (PyCFunction)PamEnv_itervalues,METH_VARARGS|METH_KEYWORDS, 0},
1349 | {"keys", (PyCFunction)PamEnv_keys, METH_VARARGS|METH_KEYWORDS, 0},
1350 | {"values", (PyCFunction)PamEnv_values, METH_VARARGS|METH_KEYWORDS, 0},
1351 | {0,0,0,0} /* Sentinel */
1352 | };
1353 |
1354 | /*
1355 | * Python Getter's for the constants.
1356 | */
1357 | #define DECLARE_CONSTANT_GET_VALUE(x, v) \
1358 | static PyObject* PamHandle_Constant_ ## x(PyObject* object, void* closure) { \
1359 | object = object; \
1360 | closure = closure; \
1361 | return PyLong_FromLong(v); \
1362 | }
1363 |
1364 | #define DECLARE_CONSTANT_GET(x) \
1365 | static PyObject* PamHandle_Constant_ ## x(PyObject* object, void* closure) { \
1366 | object = object; \
1367 | closure = closure; \
1368 | return PyLong_FromLong(x); \
1369 | }
1370 |
1371 | #ifdef HAVE_PAM_FAIL_DELAY
1372 | DECLARE_CONSTANT_GET_VALUE(HAVE_PAM_FAIL_DELAY, 1)
1373 | #else
1374 | DECLARE_CONSTANT_GET_VALUE(HAVE_PAM_FAIL_DELAY, 0)
1375 | #endif
1376 | DECLARE_CONSTANT_GET(PAM_ABORT)
1377 | DECLARE_CONSTANT_GET(PAM_ACCT_EXPIRED)
1378 | DECLARE_CONSTANT_GET(PAM_AUTH_ERR)
1379 | DECLARE_CONSTANT_GET(PAM_AUTHINFO_UNAVAIL)
1380 | DECLARE_CONSTANT_GET(PAM_AUTHTOK)
1381 | DECLARE_CONSTANT_GET(PAM_AUTHTOK_DISABLE_AGING)
1382 | DECLARE_CONSTANT_GET(PAM_AUTHTOK_ERR)
1383 | DECLARE_CONSTANT_GET(PAM_AUTHTOK_EXPIRED)
1384 | DECLARE_CONSTANT_GET(PAM_AUTHTOK_LOCK_BUSY)
1385 | DECLARE_CONSTANT_GET(PAM_AUTHTOK_RECOVER_ERR)
1386 | #ifdef PAM_AUTHTOK_RECOVERY_ERR
1387 | DECLARE_CONSTANT_GET(PAM_AUTHTOK_RECOVERY_ERR)
1388 | #endif
1389 | #ifdef PAM_AUTHTOK_TYPE
1390 | DECLARE_CONSTANT_GET(PAM_AUTHTOK_TYPE)
1391 | #endif
1392 | DECLARE_CONSTANT_GET(PAM_BAD_ITEM)
1393 | DECLARE_CONSTANT_GET(PAM_BINARY_PROMPT)
1394 | DECLARE_CONSTANT_GET(PAM_BUF_ERR)
1395 | DECLARE_CONSTANT_GET(PAM_CHANGE_EXPIRED_AUTHTOK)
1396 | DECLARE_CONSTANT_GET(PAM_CONV)
1397 | DECLARE_CONSTANT_GET(PAM_CONV_AGAIN)
1398 | DECLARE_CONSTANT_GET(PAM_CONV_ERR)
1399 | DECLARE_CONSTANT_GET(PAM_CRED_ERR)
1400 | DECLARE_CONSTANT_GET(PAM_CRED_EXPIRED)
1401 | DECLARE_CONSTANT_GET(PAM_CRED_INSUFFICIENT)
1402 | DECLARE_CONSTANT_GET(PAM_CRED_UNAVAIL)
1403 | DECLARE_CONSTANT_GET(PAM_DATA_REPLACE)
1404 | DECLARE_CONSTANT_GET(PAM_DATA_SILENT)
1405 | DECLARE_CONSTANT_GET(PAM_DELETE_CRED)
1406 | DECLARE_CONSTANT_GET(PAM_DISALLOW_NULL_AUTHTOK)
1407 | DECLARE_CONSTANT_GET(PAM_ERROR_MSG)
1408 | DECLARE_CONSTANT_GET(PAM_ESTABLISH_CRED)
1409 | DECLARE_CONSTANT_GET(PAM_FAIL_DELAY)
1410 | DECLARE_CONSTANT_GET(PAM_IGNORE)
1411 | DECLARE_CONSTANT_GET(PAM_INCOMPLETE)
1412 | DECLARE_CONSTANT_GET(PAM_MAX_MSG_SIZE)
1413 | DECLARE_CONSTANT_GET(PAM_MAX_NUM_MSG)
1414 | DECLARE_CONSTANT_GET(PAM_MAX_RESP_SIZE)
1415 | DECLARE_CONSTANT_GET(PAM_MAXTRIES)
1416 | DECLARE_CONSTANT_GET(PAM_MODULE_UNKNOWN)
1417 | DECLARE_CONSTANT_GET(PAM_NEW_AUTHTOK_REQD)
1418 | DECLARE_CONSTANT_GET(PAM_NO_MODULE_DATA)
1419 | DECLARE_CONSTANT_GET(PAM_OLDAUTHTOK)
1420 | DECLARE_CONSTANT_GET(PAM_OPEN_ERR)
1421 | DECLARE_CONSTANT_GET(PAM_PERM_DENIED)
1422 | DECLARE_CONSTANT_GET(PAM_PRELIM_CHECK)
1423 | DECLARE_CONSTANT_GET(PAM_PROMPT_ECHO_OFF)
1424 | DECLARE_CONSTANT_GET(PAM_PROMPT_ECHO_ON)
1425 | DECLARE_CONSTANT_GET(PAM_RADIO_TYPE)
1426 | DECLARE_CONSTANT_GET(PAM_REFRESH_CRED)
1427 | DECLARE_CONSTANT_GET(PAM_REINITIALIZE_CRED)
1428 | DECLARE_CONSTANT_GET(_PAM_RETURN_VALUES)
1429 | DECLARE_CONSTANT_GET(PAM_RHOST)
1430 | DECLARE_CONSTANT_GET(PAM_RUSER)
1431 | DECLARE_CONSTANT_GET(PAM_SERVICE)
1432 | DECLARE_CONSTANT_GET(PAM_SERVICE_ERR)
1433 | DECLARE_CONSTANT_GET(PAM_SESSION_ERR)
1434 | DECLARE_CONSTANT_GET(PAM_SILENT)
1435 | DECLARE_CONSTANT_GET(PAM_SUCCESS)
1436 | DECLARE_CONSTANT_GET(PAM_SYMBOL_ERR)
1437 | DECLARE_CONSTANT_GET(PAM_SYSTEM_ERR)
1438 | DECLARE_CONSTANT_GET(PAM_TEXT_INFO)
1439 | DECLARE_CONSTANT_GET(PAM_TRY_AGAIN)
1440 | DECLARE_CONSTANT_GET(PAM_TTY)
1441 | DECLARE_CONSTANT_GET(PAM_UPDATE_AUTHTOK)
1442 | DECLARE_CONSTANT_GET(PAM_USER)
1443 | DECLARE_CONSTANT_GET(PAM_USER_PROMPT)
1444 | DECLARE_CONSTANT_GET(PAM_USER_UNKNOWN)
1445 | #ifdef PAM_XAUTHDATA
1446 | DECLARE_CONSTANT_GET(PAM_XAUTHDATA)
1447 | #endif
1448 | #ifdef PAM_XDISPLAY
1449 | DECLARE_CONSTANT_GET(PAM_XDISPLAY)
1450 | #endif
1451 |
1452 | #define CONSTANT_GETSET(x) {#x, PamHandle_Constant_ ## x, 0, 0, 0}
1453 |
1454 | #define MAKE_GETSET_ITEM(t) \
1455 | static PyObject* PamHandle_get_##t(PyObject* self, void* closure) \
1456 | { \
1457 | closure = closure; \
1458 | return PamHandle_get_item(self, PAM_##t); \
1459 | } \
1460 | static int PamHandle_set_##t(PyObject* self, PyObject* pyValue, void* closure) \
1461 | { \
1462 | closure = closure; \
1463 | return PamHandle_set_item(self, PAM_##t, "PAM_" #t, pyValue); \
1464 | }
1465 |
1466 | MAKE_GETSET_ITEM(AUTHTOK)
1467 | #ifdef PAM_AUTHTOK_TYPE
1468 | MAKE_GETSET_ITEM(AUTHTOK_TYPE)
1469 | #endif
1470 | MAKE_GETSET_ITEM(OLDAUTHTOK)
1471 | MAKE_GETSET_ITEM(RHOST)
1472 | MAKE_GETSET_ITEM(RUSER)
1473 | MAKE_GETSET_ITEM(SERVICE)
1474 | MAKE_GETSET_ITEM(TTY)
1475 | MAKE_GETSET_ITEM(USER)
1476 | MAKE_GETSET_ITEM(USER_PROMPT)
1477 | #ifdef PAM_XDISPLAY
1478 | MAKE_GETSET_ITEM(XDISPLAY)
1479 | #endif
1480 |
1481 | #ifdef PAM_XAUTHDATA
1482 | /*
1483 | * The PAM_XAUTHDATA item doesn't take strings like the rest of them.
1484 | * It wants a pam_xauth_data structure.
1485 | */
1486 | static PyObject* PamHandle_get_XAUTHDATA(PyObject* self, void* closure)
1487 | {
1488 | PamHandleObject* pamHandle = (PamHandleObject*)self;
1489 | PyObject* newargs = 0;
1490 | PyObject* result = 0;
1491 | int pam_result;
1492 | struct pam_xauth_data* xauth_data = 0;
1493 |
1494 | closure = closure;
1495 | pam_result = pam_get_item(
1496 | pamHandle->pamh, PAM_XAUTHDATA, (const void**)&xauth_data);
1497 | if (check_pam_result(pamHandle, pam_result) == -1)
1498 | goto error_exit;
1499 | if (xauth_data == 0)
1500 | {
1501 | result = Py_None;
1502 | Py_INCREF(result);
1503 | }
1504 | else
1505 | {
1506 | newargs = Py_BuildValue(
1507 | "s#s#",
1508 | xauth_data->name, xauth_data->namelen,
1509 | xauth_data->data, xauth_data->datalen);
1510 | if (newargs == 0)
1511 | goto error_exit;
1512 | result = pamHandle->xauthdata->tp_new(pamHandle->xauthdata, newargs, 0);
1513 | if (result == 0)
1514 | goto error_exit;
1515 | }
1516 |
1517 | error_exit:
1518 | py_xdecref(newargs);
1519 | return result;
1520 | }
1521 |
1522 | static int PamHandle_set_XAUTHDATA(
1523 | PyObject* self, PyObject* pyValue, void* closure)
1524 | {
1525 | PamHandleObject* pamHandle = (PamHandleObject*)self;
1526 | PyObject* name = 0;
1527 | PyObject* data = 0;
1528 | int result = -1;
1529 | const char* data_str;
1530 | const char* name_str;
1531 | int pam_result;
1532 | struct pam_xauth_data xauth_data;
1533 |
1534 | closure = closure;
1535 | xauth_data.name = 0;
1536 | xauth_data.data = 0;
1537 | /*
1538 | * Get the name.
1539 | */
1540 | name = PyObject_GetAttrString(pyValue, "name");
1541 | if (name == 0)
1542 | goto error_exit;
1543 | name_str = PyString_AsString(name);
1544 | if (name_str == 0)
1545 | {
1546 | PyErr_SetString(PyExc_TypeError, "xauthdata.name must be a string");
1547 | goto error_exit;
1548 | }
1549 | xauth_data.name = strdup(name_str);
1550 | if (xauth_data.name == 0)
1551 | {
1552 | PyErr_NoMemory();
1553 | goto error_exit;
1554 | }
1555 | xauth_data.namelen = PyString_GET_SIZE(name);
1556 | /*
1557 | * Get the data.
1558 | */
1559 | data = PyObject_GetAttrString(pyValue, "data");
1560 | if (data == 0)
1561 | goto error_exit;
1562 | data_str = PyString_AsString(data);
1563 | if (data_str == 0)
1564 | {
1565 | PyErr_SetString(PyExc_TypeError, "xauthdata.data must be a string");
1566 | goto error_exit;
1567 | }
1568 | xauth_data.data = strdup(data_str);
1569 | if (xauth_data.data == 0)
1570 | {
1571 | PyErr_NoMemory();
1572 | goto error_exit;
1573 | }
1574 | xauth_data.datalen = PyString_GET_SIZE(data);
1575 | /*
1576 | * Set the item. If that worked PAM will have swallowed the strings inside
1577 | * of it, so we must not free them.
1578 | */
1579 | pam_result = pam_set_item(pamHandle->pamh, PAM_XAUTHDATA, &xauth_data);
1580 | if (pam_result == PAM_SUCCESS)
1581 | {
1582 | xauth_data.name = 0;
1583 | xauth_data.data = 0;
1584 | }
1585 | result = check_pam_result(pamHandle, pam_result);
1586 |
1587 | error_exit:
1588 | py_xdecref(data);
1589 | py_xdecref(name);
1590 | if (xauth_data.name != 0)
1591 | free(xauth_data.name);
1592 | if (xauth_data.data != 0)
1593 | free(xauth_data.data);
1594 | return result;
1595 | }
1596 | #endif
1597 |
1598 | /*
1599 | * Getters and setters.
1600 | */
1601 | static PyGetSetDef PamHandle_Getset[] =
1602 | {
1603 | /*
1604 | * Items.
1605 | */
1606 | {"authtok", PamHandle_get_AUTHTOK, PamHandle_set_AUTHTOK, "Authentication token", 0},
1607 | #ifdef PAM_AUTHTOK_TYPE
1608 | {"authtok_type",PamHandle_get_AUTHTOK_TYPE,PamHandle_set_AUTHTOK_TYPE,"XXX in the \"New XXX password:\" prompt", 0},
1609 | #endif
1610 | {"oldauthtok", PamHandle_get_OLDAUTHTOK, PamHandle_set_OLDAUTHTOK, "Old authentication token", 0},
1611 | {"rhost", PamHandle_get_RHOST, PamHandle_set_RHOST, "Requesting host name", 0},
1612 | {"ruser", PamHandle_get_RUSER, PamHandle_set_RUSER, "Requesting user name", 0},
1613 | {"service", PamHandle_get_SERVICE, PamHandle_set_SERVICE, "Service (pam stack) name", 0},
1614 | {"tty", PamHandle_get_TTY, PamHandle_set_TTY, "Terminal name", 0},
1615 | {"user", PamHandle_get_USER, PamHandle_set_USER, "Authorized user name", 0},
1616 | {"user_prompt", PamHandle_get_USER_PROMPT, PamHandle_set_USER_PROMPT, "Prompt asking for users name", 0},
1617 | #ifdef PAM_XAUTHDATA
1618 | {"xauthdata", PamHandle_get_XAUTHDATA, PamHandle_set_XAUTHDATA, "The name of the X display ($DISPLAY)", 0},
1619 | #endif
1620 | #ifdef PAM_XDISPLAY
1621 | {"xdisplay", PamHandle_get_XDISPLAY, PamHandle_set_XDISPLAY, "The name of the X display ($DISPLAY)", 0},
1622 | #endif
1623 | /*
1624 | * Constants.
1625 | */
1626 | CONSTANT_GETSET(HAVE_PAM_FAIL_DELAY),
1627 | CONSTANT_GETSET(PAM_ABORT),
1628 | CONSTANT_GETSET(PAM_ACCT_EXPIRED),
1629 | CONSTANT_GETSET(PAM_AUTH_ERR),
1630 | CONSTANT_GETSET(PAM_AUTHINFO_UNAVAIL),
1631 | CONSTANT_GETSET(PAM_AUTHTOK),
1632 | CONSTANT_GETSET(PAM_AUTHTOK_DISABLE_AGING),
1633 | CONSTANT_GETSET(PAM_AUTHTOK_ERR),
1634 | CONSTANT_GETSET(PAM_AUTHTOK_EXPIRED),
1635 | CONSTANT_GETSET(PAM_AUTHTOK_LOCK_BUSY),
1636 | CONSTANT_GETSET(PAM_AUTHTOK_RECOVER_ERR),
1637 | #ifdef PAM_AUTHTOK_RECOVERY_ERR
1638 | CONSTANT_GETSET(PAM_AUTHTOK_RECOVERY_ERR),
1639 | #endif
1640 | #ifdef PAM_AUTHTOK_TYPE
1641 | CONSTANT_GETSET(PAM_AUTHTOK_TYPE),
1642 | #endif
1643 | CONSTANT_GETSET(PAM_BAD_ITEM),
1644 | CONSTANT_GETSET(PAM_BINARY_PROMPT),
1645 | CONSTANT_GETSET(PAM_BUF_ERR),
1646 | CONSTANT_GETSET(PAM_CHANGE_EXPIRED_AUTHTOK),
1647 | CONSTANT_GETSET(PAM_CONV),
1648 | CONSTANT_GETSET(PAM_CONV_AGAIN),
1649 | CONSTANT_GETSET(PAM_CONV_ERR),
1650 | CONSTANT_GETSET(PAM_CRED_ERR),
1651 | CONSTANT_GETSET(PAM_CRED_EXPIRED),
1652 | CONSTANT_GETSET(PAM_CRED_INSUFFICIENT),
1653 | CONSTANT_GETSET(PAM_CRED_UNAVAIL),
1654 | CONSTANT_GETSET(PAM_DATA_REPLACE),
1655 | CONSTANT_GETSET(PAM_DATA_SILENT),
1656 | CONSTANT_GETSET(PAM_DELETE_CRED),
1657 | CONSTANT_GETSET(PAM_DISALLOW_NULL_AUTHTOK),
1658 | CONSTANT_GETSET(PAM_ERROR_MSG),
1659 | CONSTANT_GETSET(PAM_ESTABLISH_CRED),
1660 | CONSTANT_GETSET(PAM_FAIL_DELAY),
1661 | CONSTANT_GETSET(PAM_IGNORE),
1662 | CONSTANT_GETSET(PAM_INCOMPLETE),
1663 | CONSTANT_GETSET(PAM_MAX_MSG_SIZE),
1664 | CONSTANT_GETSET(PAM_MAX_NUM_MSG),
1665 | CONSTANT_GETSET(PAM_MAX_RESP_SIZE),
1666 | CONSTANT_GETSET(PAM_MAXTRIES),
1667 | CONSTANT_GETSET(PAM_MODULE_UNKNOWN),
1668 | CONSTANT_GETSET(PAM_NEW_AUTHTOK_REQD),
1669 | CONSTANT_GETSET(PAM_NO_MODULE_DATA),
1670 | CONSTANT_GETSET(PAM_OLDAUTHTOK),
1671 | CONSTANT_GETSET(PAM_OPEN_ERR),
1672 | CONSTANT_GETSET(PAM_PERM_DENIED),
1673 | CONSTANT_GETSET(PAM_PRELIM_CHECK),
1674 | CONSTANT_GETSET(PAM_PROMPT_ECHO_OFF),
1675 | CONSTANT_GETSET(PAM_PROMPT_ECHO_ON),
1676 | CONSTANT_GETSET(PAM_RADIO_TYPE),
1677 | CONSTANT_GETSET(PAM_REFRESH_CRED),
1678 | CONSTANT_GETSET(PAM_REINITIALIZE_CRED),
1679 | CONSTANT_GETSET(_PAM_RETURN_VALUES),
1680 | CONSTANT_GETSET(PAM_RHOST),
1681 | CONSTANT_GETSET(PAM_RUSER),
1682 | CONSTANT_GETSET(PAM_SERVICE),
1683 | CONSTANT_GETSET(PAM_SERVICE_ERR),
1684 | CONSTANT_GETSET(PAM_SESSION_ERR),
1685 | CONSTANT_GETSET(PAM_SILENT),
1686 | CONSTANT_GETSET(PAM_SUCCESS),
1687 | CONSTANT_GETSET(PAM_SYMBOL_ERR),
1688 | CONSTANT_GETSET(PAM_SYSTEM_ERR),
1689 | CONSTANT_GETSET(PAM_TEXT_INFO),
1690 | CONSTANT_GETSET(PAM_TRY_AGAIN),
1691 | CONSTANT_GETSET(PAM_TTY),
1692 | CONSTANT_GETSET(PAM_UPDATE_AUTHTOK),
1693 | CONSTANT_GETSET(PAM_USER),
1694 | CONSTANT_GETSET(PAM_USER_PROMPT),
1695 | CONSTANT_GETSET(PAM_USER_UNKNOWN),
1696 | #ifdef PAM_XAUTHDATA
1697 | CONSTANT_GETSET(PAM_XAUTHDATA),
1698 | #endif
1699 | #ifdef PAM_XDISPLAY
1700 | CONSTANT_GETSET(PAM_XDISPLAY),
1701 | #endif
1702 | {0,0,0,0,0} /* Sentinel */
1703 | };
1704 |
1705 | /*
1706 | * Convert a PamHandleObject.Message style object to a pam_message structure.
1707 | */
1708 | static int PamHandle_conversation_2message(
1709 | struct pam_message* message, PyObject* object)
1710 | {
1711 | PyObject* msg = 0;
1712 | PyObject* msg_style = 0;
1713 | int result = -1;
1714 |
1715 | msg_style = PyObject_GetAttrString(object, "msg_style");
1716 | if (msg_style == 0)
1717 | goto error_exit;
1718 | if (!PyInt_Check(msg_style) && !PyLong_Check(msg_style))
1719 | {
1720 | PyErr_SetString(PyExc_TypeError, "message.msg_style must be an int");
1721 | goto error_exit;
1722 | }
1723 | message->msg_style = PyInt_AsLong(msg_style);
1724 | msg = PyObject_GetAttrString(object, "msg");
1725 | if (msg == 0)
1726 | goto error_exit;
1727 | message->msg = PyString_AsString(msg);
1728 | if (message->msg == 0)
1729 | {
1730 | PyErr_SetString(PyExc_TypeError, "message.msg must be a string");
1731 | goto error_exit;
1732 | }
1733 | result = 0;
1734 |
1735 | error_exit:
1736 | py_xdecref(msg);
1737 | py_xdecref(msg_style);
1738 | return result;
1739 | }
1740 |
1741 | /*
1742 | * Convert a pam_response structure to a PamHandleObject.Response object.
1743 | */
1744 | static PyObject* PamHandle_conversation_2response(
1745 | PamHandleObject* pamHandle, struct pam_response* pam_response)
1746 | {
1747 | PyObject* newargs;
1748 | PyObject* result = 0;
1749 |
1750 | newargs = Py_BuildValue("si", pam_response->resp, pam_response->resp_retcode);
1751 | if (newargs == 0)
1752 | goto error_exit;
1753 | result = pamHandle->response->tp_new(pamHandle->response, newargs, 0);
1754 | if (result == 0)
1755 | goto error_exit;
1756 |
1757 | error_exit:
1758 | py_xdecref(newargs);
1759 | return result;
1760 | }
1761 |
1762 | /*
1763 | * Run a PAM "conversation".
1764 | */
1765 | static PyObject* PamHandle_conversation(
1766 | PyObject* self, PyObject* args, PyObject* kwds)
1767 | {
1768 | int err;
1769 | PamHandleObject* pamHandle = (PamHandleObject*)self;
1770 | PyObject* prompts = 0;
1771 | PyObject* result_tuple = 0;
1772 | struct pam_message* message_array = 0;
1773 | struct pam_message** message_vector = 0;
1774 | struct pam_response* response_array = 0;
1775 | PyObject* result = 0;
1776 | PyObject* response = 0;
1777 | const struct pam_conv*conv;
1778 | int prompt_count;
1779 | int i;
1780 | int pam_result;
1781 | int prompts_is_sequence;
1782 | int py_result;
1783 | static char* kwlist[] = {"prompts", NULL};
1784 |
1785 | err = PyArg_ParseTupleAndKeywords(
1786 | args, kwds, "O:conversation", kwlist,
1787 | &prompts);
1788 | if (!err)
1789 | goto error_exit;
1790 | pam_result = pam_get_item(pamHandle->pamh, PAM_CONV, (const void**)&conv);
1791 | if (check_pam_result(pamHandle, pam_result) == -1)
1792 | goto error_exit;
1793 | prompts_is_sequence = PySequence_Check(prompts);
1794 | if (!prompts_is_sequence)
1795 | prompt_count = 1;
1796 | else
1797 | {
1798 | prompt_count = PySequence_Size(prompts);
1799 | if (prompt_count == 0)
1800 | {
1801 | result = prompts;
1802 | Py_INCREF(result);
1803 | goto error_exit;
1804 | }
1805 | }
1806 | message_array = PyMem_Malloc(prompt_count * sizeof(*message_array));
1807 | if (message_array == 0)
1808 | {
1809 | PyErr_NoMemory();
1810 | goto error_exit;
1811 | }
1812 | if (!prompts_is_sequence)
1813 | {
1814 | py_result = PamHandle_conversation_2message(message_array, prompts);
1815 | if (py_result == -1)
1816 | goto error_exit;
1817 | }
1818 | else
1819 | {
1820 | for (i = 0; i < prompt_count; i += 1)
1821 | {
1822 | PyObject* message = PySequence_ITEM(prompts, i);
1823 | if (message == 0)
1824 | goto error_exit;
1825 | py_result = PamHandle_conversation_2message(&message_array[i], message);
1826 | Py_DECREF(message);
1827 | if (py_result == -1)
1828 | goto error_exit;
1829 | }
1830 | }
1831 | message_vector = PyMem_Malloc(prompt_count * sizeof(*message_vector));
1832 | if (message_vector == 0)
1833 | {
1834 | PyErr_NoMemory();
1835 | goto error_exit;
1836 | }
1837 | for (i = 0; i < prompt_count; i += 1)
1838 | message_vector[i] = &message_array[i];
1839 | pam_result = conv->conv(
1840 | prompt_count, (const struct pam_message**)message_vector,
1841 | &response_array, conv->appdata_ptr);
1842 | if (check_pam_result(pamHandle, pam_result) == -1)
1843 | goto error_exit;
1844 | if (!prompts_is_sequence)
1845 | result = PamHandle_conversation_2response(pamHandle, response_array);
1846 | else
1847 | {
1848 | result_tuple = PyTuple_New(prompt_count);
1849 | if (result_tuple == 0)
1850 | goto error_exit;
1851 | for (i = 0; i < prompt_count; i += 1)
1852 | {
1853 | response = PamHandle_conversation_2response(
1854 | pamHandle, &response_array[i]);
1855 | if (response == 0)
1856 | goto error_exit;
1857 | if (PyTuple_SetItem(result_tuple, i, response) == -1)
1858 | goto error_exit;
1859 | response = 0; /* was stolen */
1860 | }
1861 | result = result_tuple;
1862 | result_tuple = 0;
1863 | }
1864 |
1865 | error_exit:
1866 | py_xdecref(response);
1867 | py_xdecref(result_tuple);
1868 | PyMem_Free(message_array);
1869 | PyMem_Free(message_vector);
1870 | if (response_array != 0)
1871 | free(response_array);
1872 | return result;
1873 | }
1874 |
1875 | /*
1876 | * Set the fail delay.
1877 | */
1878 | static PyObject* PamHandle_fail_delay(
1879 | PyObject* self, PyObject* args, PyObject* kwds)
1880 | {
1881 | int err;
1882 | PamHandleObject* pamHandle = (PamHandleObject*)self;
1883 | int micro_sec = 0;
1884 | int pam_result;
1885 | PyObject* result = 0;
1886 | static char* kwlist[] = {"micro_sec", NULL};
1887 |
1888 | err = PyArg_ParseTupleAndKeywords(
1889 | args, kwds, "i:fail_delay", kwlist,
1890 | µ_sec);
1891 | if (!err)
1892 | goto error_exit;
1893 | pam_result = pam_fail_delay(pamHandle->pamh, micro_sec);
1894 | if (check_pam_result(pamHandle, pam_result) == -1)
1895 | goto error_exit;
1896 | result = Py_None;
1897 | Py_INCREF(result);
1898 |
1899 | error_exit:
1900 | return result;
1901 | }
1902 |
1903 | /*
1904 | * Get the user's name, promping if it isn't known.
1905 | */
1906 | static PyObject* PamHandle_get_user(
1907 | PyObject* self, PyObject* args, PyObject* kwds)
1908 | {
1909 | PamHandleObject* pamHandle = (PamHandleObject*)self;
1910 | char* prompt = 0;
1911 | PyObject* result = 0;
1912 | int pam_result;
1913 | const char* user = 0;
1914 | static char* kwlist[] = {"prompt", NULL};
1915 |
1916 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "|z:get_user", kwlist, &prompt))
1917 | goto error_exit;
1918 | pam_result = pam_get_user(pamHandle->pamh, &user, prompt);
1919 | if (check_pam_result(pamHandle, pam_result) == -1)
1920 | goto error_exit;
1921 | if (user != 0)
1922 | result = PyString_FromString(user);
1923 | else
1924 | {
1925 | result = Py_None;
1926 | Py_INCREF(result);
1927 | }
1928 | if (result == 0)
1929 | goto error_exit;
1930 |
1931 | error_exit:
1932 | return result;
1933 | }
1934 |
1935 | /*
1936 | * Set a PAM environment variable.
1937 | */
1938 | static PyObject* PamHandle_strerror(
1939 | PyObject* self, PyObject* args, PyObject* kwds)
1940 | {
1941 | PamHandleObject* pamHandle = (PamHandleObject*)self;
1942 | const char* err;
1943 | int errnum;
1944 | PyObject* result = 0;
1945 | const int debug_magic = 0x4567abcd;
1946 | static char* kwlist[] = {"errnum", NULL};
1947 |
1948 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "i:strerror", kwlist, &errnum))
1949 | goto error_exit;
1950 | /*
1951 | * A kludge so we can test exceptions.
1952 | */
1953 | if (errnum >= debug_magic && errnum < debug_magic + _PAM_RETURN_VALUES)
1954 | {
1955 | if (check_pam_result(pamHandle, errnum - debug_magic) == -1)
1956 | goto error_exit;
1957 | }
1958 | err = pam_strerror(pamHandle->pamh, errnum);
1959 | if (err == 0)
1960 | {
1961 | result = Py_None;
1962 | Py_INCREF(result);
1963 | }
1964 | else
1965 | {
1966 | result = PyString_FromString(err);
1967 | if (result == 0)
1968 | goto error_exit;
1969 | }
1970 |
1971 | error_exit:
1972 | return result;
1973 | }
1974 |
1975 | static PyMethodDef PamHandle_Methods[] =
1976 | {
1977 | {
1978 | "conversation",
1979 | (PyCFunction)PamHandle_conversation,
1980 | METH_VARARGS|METH_KEYWORDS,
1981 | MODULE_NAME "." PAMHANDLE_NAME "." "conversation(prompts)\n"
1982 | " Ask the application to issue the prompts to the user and return the\n"
1983 | " users responses. The 'prompts' can be one, or a list of\n"
1984 | " " MODULE_NAME "." PAMHANDLE_NAME "." PAMMESSAGE_NAME " objects. The return value is one,\n"
1985 | " or an array of " MODULE_NAME "." PAMHANDLE_NAME "." PAMRESPONSE_NAME " objects."
1986 | },
1987 | {
1988 | "fail_delay",
1989 | (PyCFunction)PamHandle_fail_delay,
1990 | METH_VARARGS|METH_KEYWORDS,
1991 | MODULE_NAME "." PAMHANDLE_NAME "." "fail_delay(micro_sec)\n"
1992 | " Sets the amount of time a failed authenticate attempt should delay for\n"
1993 | " in micro seconds. This amount reset to 0 after every authenticate\n"
1994 | " attempt."
1995 | },
1996 | {
1997 | "get_user",
1998 | (PyCFunction)PamHandle_get_user,
1999 | METH_VARARGS|METH_KEYWORDS,
2000 | MODULE_NAME "." PAMHANDLE_NAME "." "getuser([prompt])\n"
2001 | " If " PAMHANDLE_NAME ".user isn't None return it, otherwise ask the\n"
2002 | " application to display the string 'prompt' and enter the user name. The\n"
2003 | " user name (a string) is returned. It will be None if it isn't known."
2004 | },
2005 | {
2006 | "strerror",
2007 | (PyCFunction)PamHandle_strerror,
2008 | METH_VARARGS|METH_KEYWORDS,
2009 | MODULE_NAME "." PAMHANDLE_NAME "." "strerror(errnum)\n"
2010 | " Return a string describing the pam error errnum."
2011 | },
2012 | {0,0,0,0} /* Sentinel */
2013 | };
2014 |
2015 | static PyMemberDef PamHandle_Members[] =
2016 | {
2017 | {
2018 | "env",
2019 | T_OBJECT_EX,
2020 | offsetof(PamHandleObject, env),
2021 | READONLY,
2022 | "The PAM environment mapping."
2023 | },
2024 | {
2025 | "exception",
2026 | T_OBJECT_EX,
2027 | offsetof(PamHandleObject, exception),
2028 | READONLY,
2029 | "Exception raised when a call to PAM fails."
2030 | },
2031 | {
2032 | "libpam_version",
2033 | T_STRING,
2034 | offsetof(PamHandleObject, libpam_version),
2035 | READONLY,
2036 | "The runtime PAM version."
2037 | },
2038 | {
2039 | "Message",
2040 | T_OBJECT,
2041 | offsetof(PamHandleObject, message),
2042 | READONLY,
2043 | "Message class that can be passed to " MODULE_NAME "." PAMHANDLE_NAME ".conversation()"
2044 | },
2045 | {
2046 | "module",
2047 | T_OBJECT,
2048 | offsetof(PamHandleObject, module),
2049 | READONLY,
2050 | "The user module (ie you!)"
2051 | },
2052 | {
2053 | "pamh",
2054 | T_LONG,
2055 | offsetof(PamHandleObject, pamh),
2056 | READONLY,
2057 | "The PAM handle."
2058 | },
2059 | {
2060 | "py_initialized",
2061 | T_INT,
2062 | offsetof(PamHandleObject, py_initialized),
2063 | READONLY,
2064 | "True if Py_Initialize was called."
2065 | },
2066 | {
2067 | "Response",
2068 | T_OBJECT,
2069 | offsetof(PamHandleObject, response),
2070 | READONLY,
2071 | "Response class returned by " MODULE_NAME "." PAMHANDLE_NAME ".conversation()"
2072 | },
2073 | {
2074 | "XAuthData",
2075 | T_OBJECT,
2076 | offsetof(PamHandleObject, xauthdata),
2077 | READONLY,
2078 | "XAuthData class used by " MODULE_NAME "." PAMHANDLE_NAME ".xauthdata"
2079 | },
2080 | {0,0,0,0,0}, /* End of Python visible members */
2081 | {
2082 | "syslogFile",
2083 | T_OBJECT,
2084 | offsetof(PamHandleObject, syslogFile),
2085 | READONLY,
2086 | "File like object that writes to syslog"
2087 | },
2088 | {0,0,0,0,0} /* Sentinal */
2089 | };
2090 |
2091 | static char PamHandle_Doc[] =
2092 | MODULE_NAME "." PAMHANDLE_NAME "\n"
2093 | " A an instance of this class makes the PAM API available to the Python\n"
2094 | " module. It is the first argument to every method PAM calls in the module.";
2095 |
2096 | static int pypam_initialize_count = 0;
2097 |
2098 | static void cleanup_pamHandle(pam_handle_t* pamh, void* data, int error_status)
2099 | {
2100 | PamHandleObject* pamHandle = (PamHandleObject*)data;
2101 | void* dlhandle = pamHandle->dlhandle;
2102 | PyObject* py_resultobj = 0;
2103 | PyObject* handler_function = 0;
2104 | int py_initialized;
2105 | static const char* handler_name = "pam_sm_end";
2106 |
2107 | pamh = pamh;
2108 | error_status = error_status;
2109 | handler_function =
2110 | PyObject_GetAttrString(pamHandle->module, (char*)handler_name);
2111 | if (handler_function == 0)
2112 | PyErr_Restore(0, 0, 0);
2113 | else
2114 | {
2115 | call_python_handler(
2116 | &py_resultobj, pamHandle, handler_function,
2117 | handler_name, 0, 0, 0);
2118 | }
2119 | py_xdecref(py_resultobj);
2120 | py_xdecref(handler_function);
2121 | py_initialized = pamHandle->py_initialized;
2122 | Py_DECREF(pamHandle);
2123 | if (py_initialized)
2124 | {
2125 | pypam_initialize_count -= 1;
2126 | if (pypam_initialize_count == 0)
2127 | Py_Finalize();
2128 | }
2129 | dlclose(dlhandle);
2130 | }
2131 |
2132 | /*
2133 | * Find the module, and load it if we haven't see it before. Returns
2134 | * PAM_SUCCESS if it worked, the PAM error code otherwise.
2135 | */
2136 | static int load_user_module(
2137 | PyObject** user_module, PamHandleObject* pamHandle,
2138 | const char* module_path)
2139 | {
2140 | PyObject* builtins = 0;
2141 | PyObject* module_dict = 0;
2142 | FILE* module_fp = 0;
2143 | char* user_module_name = 0;
2144 | PyObject* py_resultobj = 0;
2145 | char* dot;
2146 | int pam_result;
2147 | int py_result;
2148 |
2149 | /*
2150 | * Open the file.
2151 | */
2152 | module_fp = fopen(module_path, "r");
2153 | if (module_fp == 0)
2154 | {
2155 | syslog_path_message(
2156 | module_path, "Can not open module: %s",
2157 | strerror(errno));
2158 | pam_result = PAM_OPEN_ERR;
2159 | goto error_exit;
2160 | }
2161 | /*
2162 | * Create the new module.
2163 | */
2164 | user_module_name = strrchr(module_path, '/');
2165 | if (user_module_name == 0)
2166 | user_module_name = strdup(module_path);
2167 | else
2168 | user_module_name = strdup(user_module_name + 1);
2169 | if (user_module_name == 0)
2170 | {
2171 | syslog_path_message(MODULE_NAME, "out of memory");
2172 | pam_result = PAM_BUF_ERR;
2173 | goto error_exit;
2174 | }
2175 | dot = strrchr(user_module_name, '.');
2176 | if (dot != 0 || strcmp(dot, ".py") == 0)
2177 | *dot = '\0';
2178 | *user_module = PyModule_New(user_module_name);
2179 | if (*user_module == 0)
2180 | {
2181 | pam_result = syslog_path_exception(
2182 | module_path,
2183 | "PyModule_New(pamh.module.__file__) failed");
2184 | goto error_exit;
2185 | }
2186 | py_result =
2187 | PyModule_AddStringConstant(*user_module, "__file__", (char*)module_path);
2188 | if (py_result == -1)
2189 | {
2190 | pam_result = syslog_path_exception(
2191 | module_path,
2192 | "PyModule_AddStringConstant(pamh.module, '__file__', module_path) failed");
2193 | goto error_exit;
2194 | }
2195 | /*
2196 | * Add __builtins__.
2197 | */
2198 | if (!PyObject_HasAttrString(*user_module , "__builtins__"))
2199 | {
2200 | builtins = PyEval_GetBuiltins();
2201 | Py_INCREF(builtins); /* is stolen */
2202 | if (PyModule_AddObject(*user_module, "__builtins__", builtins) == -1)
2203 | {
2204 | pam_result = syslog_path_exception(
2205 | module_path,
2206 | "PyModule_AddObject(pamh.module, '__builtins__', builtins) failed");
2207 | goto error_exit;
2208 | }
2209 | builtins = 0; /* was borrowed */
2210 | }
2211 | /*
2212 | * Call it.
2213 | */
2214 | module_dict = PyModule_GetDict(*user_module);
2215 | py_resultobj = PyRun_FileExFlags(
2216 | module_fp, module_path, Py_file_input, module_dict, module_dict, 1, 0);
2217 | module_fp = 0; /* it was closed */
2218 | module_dict = 0; /* was borrowed */
2219 | /*
2220 | * If that didn't work there was an exception. Errk!
2221 | */
2222 | if (py_resultobj == 0)
2223 | {
2224 | pam_result = syslog_path_traceback(module_path, pamHandle);
2225 | goto error_exit;
2226 | }
2227 | pam_result = PAM_SUCCESS;
2228 |
2229 | error_exit:
2230 | py_xdecref(builtins);
2231 | py_xdecref(module_dict);
2232 | if (module_fp != 0)
2233 | fclose(module_fp);
2234 | if (user_module_name != 0)
2235 | free(user_module_name);
2236 | py_xdecref(py_resultobj);
2237 | return pam_result;
2238 | }
2239 |
2240 | /*
2241 | * Create a new Python type on the heap. This differs from creating a static
2242 | * type in non-obvious ways.
2243 | */
2244 | static PyTypeObject* newHeapType(
2245 | PyObject* module, /* Module declaring type (required) */
2246 | const char* name, /* tp_name (required) */
2247 | int basicsize, /* tp_basicsize (required) */
2248 | char* doc, /* tp_doc (optional) */
2249 | inquiry clear, /* tp_clear (optional) */
2250 | struct PyMethodDef* methods, /* tp_methods (optional) */
2251 | struct PyMemberDef* members, /* tp_members (optional) */
2252 | struct PyGetSetDef* getset, /* tp_getset (optional) */
2253 | newfunc new /* tp_new (optional) */
2254 | )
2255 | {
2256 | PyObject* pyName = 0;
2257 | PyTypeObject* result = 0;
2258 | PyTypeObject* type = 0;
2259 |
2260 | pyName = PyString_FromString(name);
2261 | if (pyName == 0)
2262 | goto error_exit;
2263 | type = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
2264 | if (type == 0)
2265 | goto error_exit;
2266 | type->tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HEAPTYPE|Py_TPFLAGS_HAVE_GC;
2267 | type->tp_basicsize = basicsize;
2268 | type->tp_dealloc = generic_dealloc;
2269 | if (doc != 0)
2270 | {
2271 | char *doc_string = PyMem_Malloc(strlen(doc)+1);
2272 | if (doc_string == 0)
2273 | {
2274 | PyErr_NoMemory();
2275 | goto error_exit;
2276 | }
2277 | strcpy(doc_string, doc);
2278 | type->tp_doc = doc_string;
2279 | }
2280 | type->tp_traverse = generic_traverse;
2281 | type->tp_clear = clear != 0 ? clear : generic_clear;
2282 | type->tp_methods = methods;
2283 | type->tp_members = members;
2284 | type->tp_getset = getset;
2285 | type->tp_name = PyString_AsString(pyName);
2286 | #if PY_VERSION_HEX < 0x02050000
2287 | ((PyHeapTypeObject*)type)->name = pyName;
2288 | #else
2289 | ((PyHeapTypeObject*)type)->ht_name = pyName;
2290 | #endif
2291 | pyName = 0;
2292 | PyType_Ready(type);
2293 | type->tp_new = new;
2294 | if (PyDict_SetItemString(type->tp_dict, "__module__", module) == -1)
2295 | goto error_exit;
2296 | result = type;
2297 | type = 0;
2298 |
2299 | error_exit:
2300 | py_xdecref(pyName);
2301 | py_xdecref((PyObject*)type);
2302 | return result;
2303 | }
2304 |
2305 | /*
2306 | * Create a type and return an instance of that type. The newly created
2307 | * type object is discarded.
2308 | */
2309 | static PyObject* newSingletonObject(
2310 | PyObject* module, /* Module declaring type (required) */
2311 | const char* name, /* tp_name (required) */
2312 | int basicsize, /* tp_basicsize (required) */
2313 | char* doc, /* tp_doc (optional) */
2314 | inquiry clear, /* tp_clear (optional) */
2315 | struct PyMethodDef* methods, /* tp_methods (optional) */
2316 | struct PyMemberDef* members, /* tp_members (optional) */
2317 | struct PyGetSetDef* getset /* tp_getset (optional) */
2318 | )
2319 | {
2320 | PyObject* result = 0;
2321 | PyTypeObject* type = 0;
2322 |
2323 | type = newHeapType(
2324 | module, name, basicsize, doc, clear, methods, members, getset, 0);
2325 | if (type != 0)
2326 | result = type->tp_alloc(type, 0);
2327 | py_xdecref((PyObject*)type);
2328 | return result;
2329 | }
2330 |
2331 | /*
2332 | * Find the PamHandle object used by the pamh instance, creating one if it
2333 | * doesn't exist. Returns a pam_result, which will be PAM_SUCCESS if it
2334 | * works.
2335 | */
2336 | static int get_pamHandle(
2337 | PamHandleObject** result, pam_handle_t* pamh, const char** argv)
2338 | {
2339 | void* dlhandle = 0;
2340 | int do_initialize;
2341 | char* module_dir;
2342 | char* module_path = 0;
2343 | char* module_data_name = 0;
2344 | PyObject* user_module = 0;
2345 | PamEnvObject* pamEnv = 0;
2346 | PamHandleObject* pamHandle = 0;
2347 | PyObject* pamHandle_module = 0;
2348 | SyslogFileObject* syslogFile = 0;
2349 | PyObject* tracebackModule = 0;
2350 | int pam_result;
2351 |
2352 | /*
2353 | * Figure out where the module lives.
2354 | */
2355 | if (argv == 0 || argv[0] == 0)
2356 | {
2357 | syslog_path_message(MODULE_NAME, "python module name not supplied");
2358 | pam_result = PAM_MODULE_UNKNOWN;
2359 | goto error_exit;
2360 | }
2361 | if (argv[0][0] == '/')
2362 | module_dir = "";
2363 | else
2364 | module_dir = DEFAULT_SECURITY_DIR;
2365 | module_path = malloc(strlen(module_dir) + strlen(argv[0]) + 1);
2366 | if (module_path == 0)
2367 | {
2368 | syslog_path_message(MODULE_NAME, "out of memory");
2369 | pam_result = PAM_BUF_ERR;
2370 | goto error_exit;
2371 | }
2372 | strcat(strcpy(module_path, module_dir), argv[0]);
2373 | /*
2374 | * See if we already exist.
2375 | */
2376 | module_data_name = malloc(strlen(MODULE_NAME) + 1 + strlen(module_path) + 1);
2377 | if (module_data_name == 0)
2378 | {
2379 | syslog_path_message(MODULE_NAME, "out of memory");
2380 | pam_result = PAM_BUF_ERR;
2381 | goto error_exit;
2382 | }
2383 | strcat(strcat(strcpy(module_data_name, MODULE_NAME), "."), module_path);
2384 | pam_result = pam_get_data(pamh, module_data_name, (void*)result);
2385 | if (pam_result == PAM_SUCCESS)
2386 | {
2387 | (*result)->pamh = pamh;
2388 | Py_INCREF(*result);
2389 | goto error_exit;
2390 | }
2391 | /*
2392 | * Initialize Python if required.
2393 | */
2394 | dlhandle = dlopen(libpython_so, RTLD_NOW|RTLD_GLOBAL);
2395 | if (dlhandle == 0)
2396 | {
2397 | pam_result = syslog_path_message(
2398 | module_path,
2399 | "Can't load python library %s: %s", libpython_so, dlerror());
2400 | goto error_exit;
2401 | }
2402 | do_initialize = pypam_initialize_count > 0 || !Py_IsInitialized();
2403 | if (do_initialize)
2404 | {
2405 | if (pypam_initialize_count == 0)
2406 | initialise_python();
2407 | pypam_initialize_count += 1;
2408 | }
2409 | /*
2410 | * Create a throw away module because heap types need one, apparently.
2411 | */
2412 | pamHandle_module = PyModule_New((char*)module_data_name);
2413 | if (pamHandle_module == 0)
2414 | {
2415 | pam_result = syslog_path_exception(
2416 | module_path,
2417 | "PyModule_New(module_data_name) failed");
2418 | goto error_exit;
2419 | }
2420 | /*
2421 | * Create the type we use for our object.
2422 | */
2423 | pamHandle = (PamHandleObject*)newSingletonObject(
2424 | pamHandle_module, /* __module__ */
2425 | PAMHANDLE_NAME "_type", /* tp_name */
2426 | sizeof(PamHandleObject), /* tp_basicsize */
2427 | PamHandle_Doc, /* tp_doc */
2428 | 0, /* tp_clear */
2429 | PamHandle_Methods, /* tp_methods */
2430 | PamHandle_Members, /* tp_members */
2431 | PamHandle_Getset); /* tp_getset */
2432 | if (pamHandle == 0)
2433 | {
2434 | pam_result = syslog_path_exception(module_path, "Can't create pamh Object");
2435 | goto error_exit;
2436 | }
2437 | if (PyObject_IS_GC((PyObject*)pamHandle))
2438 | PyObject_GC_UnTrack(pamHandle); /* No refs are visible to python */
2439 | pamHandle->dlhandle = dlhandle;
2440 | dlhandle = 0;
2441 | pamHandle->libpam_version =
2442 | __STRING(__LINUX_PAM__) "." __STRING(__LINUX_PAM_MINOR__);
2443 | pamHandle->pamh = pamh;
2444 | pamHandle->py_initialized = do_initialize;
2445 | pamHandle->exception = PyErr_NewException(
2446 | PAMHANDLE_NAME "." PAMHANDLEEXCEPTION_NAME, PyExc_StandardError, NULL);
2447 | if (pamHandle->exception == NULL)
2448 | goto error_exit;
2449 | /*
2450 | * Create the object we use to handle the PAM environment.
2451 | */
2452 | pamEnv = (PamEnvObject*)newSingletonObject(
2453 | pamHandle_module, /* __module__ */
2454 | PAMENV_NAME "_type", /* tp_name */
2455 | sizeof(PamEnvObject), /* tp_basicsize */
2456 | 0, /* tp_doc */
2457 | 0, /* tp_clear */
2458 | PamEnv_Methods, /* tp_methods */
2459 | PamEnv_Members, /* tp_members */
2460 | 0); /* tp_getset */
2461 | if (pamEnv == 0)
2462 | {
2463 | pam_result = syslog_path_exception(module_path, "Can't create pamh.env");
2464 | goto error_exit;
2465 | }
2466 | pamEnv->ob_type->tp_as_mapping = &PamEnv_as_mapping;
2467 | pamEnv->ob_type->tp_iter = PamEnv_iter;
2468 | pamEnv->pamHandle = pamHandle;
2469 | pamEnv->pamEnvIter_type = newHeapType(
2470 | pamHandle_module, /* __module__ */
2471 | PAMENVITER_NAME "_type", /* tp_name */
2472 | sizeof(PamEnvIterObject), /* tp_basicsize */
2473 | 0, /* tp_doc */
2474 | 0, /* tp_clear */
2475 | 0, /* tp_methods */
2476 | PamEnvIter_Members, /* tp_members */
2477 | 0, /* tp_getset */
2478 | 0); /* tp_new */
2479 | if (pamEnv->pamEnvIter_type == 0)
2480 | goto error_exit;
2481 | if (PyObject_IS_GC((PyObject*)pamEnv->pamEnvIter_type))
2482 | {
2483 | /*
2484 | * No refs are visible to python.
2485 | */
2486 | PyObject_GC_UnTrack(pamEnv->pamEnvIter_type);
2487 | }
2488 | pamEnv->pamEnvIter_type->tp_iter = PyObject_SelfIter;
2489 | pamEnv->pamEnvIter_type->tp_iternext = PamEnvIter_iternext;
2490 | pamHandle->env = (PyObject*)pamEnv;
2491 | pamEnv = 0;
2492 | /*
2493 | * Create the type for the PamMessageObject.
2494 | */
2495 | pamHandle->message = newHeapType(
2496 | pamHandle_module, /* __module__ */
2497 | PAMMESSAGE_NAME "_type", /* tp_name */
2498 | sizeof(PamMessageObject), /* tp_basicsize */
2499 | PamMessage_doc, /* tp_doc */
2500 | 0, /* tp_clear */
2501 | 0, /* tp_methods */
2502 | PamMessage_members, /* tp_members */
2503 | 0, /* tp_getset */
2504 | PamMessage_new); /* tp_new */
2505 | if (pamHandle->message == 0)
2506 | {
2507 | pam_result = syslog_path_exception(
2508 | module_path, "Can't create pamh.Message");
2509 | goto error_exit;
2510 | }
2511 | /*
2512 | * Create the type for the PamResponseObject.
2513 | */
2514 | pamHandle->response = newHeapType(
2515 | pamHandle_module, /* __module__ */
2516 | PAMRESPONSE_NAME "_type", /* tp_name */
2517 | sizeof(PamResponseObject), /* tp_basicsize */
2518 | PamResponse_doc, /* tp_doc */
2519 | 0, /* tp_clear */
2520 | 0, /* tp_methods */
2521 | PamResponse_members, /* tp_members */
2522 | 0, /* tp_getset */
2523 | PamResponse_new); /* tp_new */
2524 | if (pamHandle->response == 0)
2525 | {
2526 | pam_result = syslog_path_exception(
2527 | module_path,
2528 | "Can't create pamh.Response");
2529 | goto error_exit;
2530 | }
2531 | /*
2532 | * Create the Syslogfile Type & Object.
2533 | */
2534 | syslogFile = (SyslogFileObject*)newSingletonObject(
2535 | pamHandle_module, /* __module__ */
2536 | SYSLOGFILE_NAME "_type", /* tp_name */
2537 | sizeof(SyslogFileObject), /* tp_basicsize */
2538 | 0, /* tp_doc */
2539 | SyslogFile_clear, /* tp_clear */
2540 | SyslogFile_Methods, /* tp_methods */
2541 | 0, /* tp_members */
2542 | 0); /* tp_getset */
2543 | if (syslogFile == 0)
2544 | {
2545 | pam_result = syslog_path_exception(
2546 | module_path,
2547 | "Can't create pamh.syslogFile");
2548 | goto error_exit;
2549 | }
2550 | syslogFile->buffer = 0;
2551 | syslogFile->size = 0;
2552 | pamHandle->syslogFile = (PyObject*)syslogFile;
2553 | syslogFile = 0;
2554 | /*
2555 | * The traceback object.
2556 | */
2557 | tracebackModule = PyImport_ImportModule("traceback");
2558 | if (tracebackModule == 0)
2559 | {
2560 | pam_result = syslog_path_exception(
2561 | module_path,
2562 | "PyImport_ImportModule('traceback') failed");
2563 | goto error_exit;
2564 | }
2565 | pamHandle->print_exception =
2566 | PyObject_GetAttrString(tracebackModule, "print_exception");
2567 | if (pamHandle->print_exception == 0)
2568 | {
2569 | pam_result = syslog_path_exception(
2570 | module_path,
2571 | "PyObject_GetAttrString(traceback, 'print_exception') failed");
2572 | goto error_exit;
2573 | }
2574 | Py_INCREF(pamHandle->print_exception); /* Borrowed reference */
2575 | /*
2576 | * Create the type for the PamXAuthDataObject.
2577 | */
2578 | pamHandle->xauthdata = newHeapType(
2579 | pamHandle_module, /* __module__ */
2580 | PAMXAUTHDATA_NAME "_type", /* tp_name */
2581 | sizeof(PamXAuthDataObject), /* tp_basicsize */
2582 | PamXAuthData_doc, /* tp_doc */
2583 | 0, /* tp_clear */
2584 | 0, /* tp_methods */
2585 | PamXAuthData_members, /* tp_members */
2586 | 0, /* tp_getset */
2587 | PamXAuthData_new); /* tp_new */
2588 | if (pamHandle->xauthdata == 0)
2589 | {
2590 | pam_result = syslog_path_exception(
2591 | module_path, "Can't create pamh.XAuthData");
2592 | goto error_exit;
2593 | }
2594 | /*
2595 | * Now we have error reporting set up import the module.
2596 | */
2597 | pam_result = load_user_module(&user_module, pamHandle, module_path);
2598 | if (pam_result != PAM_SUCCESS)
2599 | goto error_exit;
2600 | pamHandle->module = user_module;
2601 | Py_INCREF(pamHandle->module);
2602 | /*
2603 | * That worked. Save a reference to it.
2604 | */
2605 | Py_INCREF(pamHandle);
2606 | pam_set_data(pamh, module_data_name, pamHandle, cleanup_pamHandle);
2607 | *result = pamHandle;
2608 | pamHandle = 0;
2609 |
2610 | error_exit:
2611 | if (module_path != 0)
2612 | free(module_path);
2613 | if (module_data_name != 0)
2614 | free(module_data_name);
2615 | py_xdecref(user_module);
2616 | py_xdecref((PyObject*)pamEnv);
2617 | py_xdecref((PyObject*)pamHandle);
2618 | py_xdecref(pamHandle_module);
2619 | py_xdecref((PyObject*)syslogFile);
2620 | py_xdecref(tracebackModule);
2621 | return pam_result;
2622 | }
2623 |
2624 | /*
2625 | * Call the python handler.
2626 | */
2627 | static int call_python_handler(
2628 | PyObject** result, PamHandleObject* pamHandle,
2629 | PyObject* handler_function, const char* handler_name,
2630 | int flags, int argc, const char** argv)
2631 | {
2632 | PyObject* arg_object = 0;
2633 | PyObject* argv_object = 0;
2634 | PyObject* flags_object = 0;
2635 | PyObject* handler_args = 0;
2636 | PyObject* py_resultobj = 0;
2637 | int i;
2638 | int pam_result;
2639 |
2640 | if (!PyCallable_Check(handler_function))
2641 | {
2642 | pam_result =
2643 | syslog_message(pamHandle, "%s isn't a function.", handler_name);
2644 | goto error_exit;
2645 | }
2646 | /*
2647 | * Set up the arguments for the python function. If we aren't passed
2648 | * argv then this is pam_sm_end() and it is only given pamh.
2649 | */
2650 | if (argv == 0)
2651 | handler_args = Py_BuildValue("(O)", pamHandle);
2652 | else
2653 | {
2654 | flags_object = PyInt_FromLong(flags);
2655 | if (flags_object == 0)
2656 | {
2657 | pam_result = syslog_exception(pamHandle, "PyInt_FromLong(flags) failed");
2658 | goto error_exit;
2659 | }
2660 | argv_object = PyList_New(argc);
2661 | if (argv_object == 0)
2662 | {
2663 | pam_result = syslog_exception(pamHandle, "PyList_New(argc) failed");
2664 | goto error_exit;
2665 | }
2666 | for (i = 0; i < argc; i += 1)
2667 | {
2668 | arg_object = PyString_FromString(argv[i]);
2669 | if (arg_object == 0)
2670 | {
2671 | pam_result = syslog_exception(
2672 | pamHandle,
2673 | "PyString_FromString(argv[i]) failed");
2674 | goto error_exit;
2675 | }
2676 | PyList_SET_ITEM(argv_object, i, arg_object);
2677 | arg_object = 0; /* It was pinched by SET_ITEM */
2678 | }
2679 | handler_args =
2680 | Py_BuildValue("OOO", pamHandle, flags_object, argv_object);
2681 | }
2682 | if (handler_args == 0)
2683 | {
2684 | pam_result = syslog_exception(
2685 | pamHandle,
2686 | "handler_args = Py_BuildValue(...) failed");
2687 | goto error_exit;
2688 | }
2689 | /*
2690 | * Call the Python handler function.
2691 | */
2692 | py_resultobj = PyEval_CallObject(handler_function, handler_args);
2693 | /*
2694 | * Did it throw an exception?
2695 | */
2696 | if (py_resultobj == 0)
2697 | {
2698 | pam_result = syslog_traceback(pamHandle);
2699 | goto error_exit;
2700 | }
2701 | *result = py_resultobj;
2702 | py_resultobj = 0;
2703 | pam_result = PAM_SUCCESS;
2704 |
2705 | error_exit:
2706 | py_xdecref(arg_object);
2707 | py_xdecref(argv_object);
2708 | py_xdecref(flags_object);
2709 | py_xdecref(handler_args);
2710 | py_xdecref(py_resultobj);
2711 | return pam_result;
2712 | }
2713 |
2714 | /*
2715 | * Calls the Python method that will handle PAM's request to the module.
2716 | */
2717 | static int call_handler(
2718 | const char* handler_name, pam_handle_t* pamh,
2719 | int flags, int argc, const char** argv)
2720 | {
2721 | PyObject* handler_function = 0;
2722 | PamHandleObject* pamHandle = 0;
2723 | PyObject* py_resultobj = 0;
2724 | int pam_result;
2725 |
2726 | /*
2727 | * Initialise Python, and get a copy of our object.
2728 | */
2729 | pam_result = get_pamHandle(&pamHandle, pamh, argv);
2730 | if (pam_result != PAM_SUCCESS)
2731 | goto error_exit;
2732 | /*
2733 | * See if the function we have to call has been defined.
2734 | */
2735 | handler_function =
2736 | PyObject_GetAttrString(pamHandle->module, (char*)handler_name);
2737 | if (handler_function == 0)
2738 | {
2739 | syslog_message(pamHandle, "%s() isn't defined.", handler_name);
2740 | pam_result = PAM_SYMBOL_ERR;
2741 | goto error_exit;
2742 | }
2743 | pam_result = call_python_handler(
2744 | &py_resultobj, pamHandle, handler_function, handler_name,
2745 | flags, argc, argv);
2746 | if (pam_result != PAM_SUCCESS)
2747 | goto error_exit;
2748 | /*
2749 | * It must return an integer.
2750 | */
2751 | if (!PyInt_Check(py_resultobj) && !PyLong_Check(py_resultobj))
2752 | {
2753 | pam_result = syslog_message(
2754 | pamHandle,
2755 | "%s() did not return an integer.", handler_name);
2756 | goto error_exit;
2757 | }
2758 | pam_result = PyInt_AsLong(py_resultobj);
2759 |
2760 | error_exit:
2761 | py_xdecref(handler_function);
2762 | py_xdecref((PyObject*)pamHandle);
2763 | py_xdecref(py_resultobj);
2764 | return pam_result;
2765 | }
2766 |
2767 |
2768 | PAM_EXTERN int pam_sm_authenticate(
2769 | pam_handle_t* pamh, int flags, int argc, const char** argv)
2770 | {
2771 | return call_handler("pam_sm_authenticate", pamh, flags, argc, argv);
2772 | }
2773 |
2774 | PAM_EXTERN int pam_sm_setcred(
2775 | pam_handle_t* pamh, int flags, int argc, const char** argv)
2776 | {
2777 | return call_handler("pam_sm_setcred", pamh, flags, argc, argv);
2778 | }
2779 |
2780 | PAM_EXTERN int pam_sm_acct_mgmt(
2781 | pam_handle_t* pamh, int flags, int argc, const char** argv)
2782 | {
2783 | return call_handler("pam_sm_acct_mgmt", pamh, flags, argc, argv);
2784 | }
2785 |
2786 | PAM_EXTERN int pam_sm_open_session(
2787 | pam_handle_t* pamh, int flags, int argc, const char** argv)
2788 | {
2789 | return call_handler("pam_sm_open_session", pamh, flags, argc, argv);
2790 | }
2791 |
2792 | PAM_EXTERN int pam_sm_close_session(
2793 | pam_handle_t* pamh, int flags, int argc, const char** argv)
2794 | {
2795 | return call_handler("pam_sm_close_session", pamh, flags, argc, argv);
2796 | }
2797 |
2798 | PAM_EXTERN int pam_sm_chauthtok(
2799 | pam_handle_t* pamh, int flags, int argc, const char** argv)
2800 | {
2801 | return call_handler("pam_sm_chauthtok", pamh, flags, argc, argv);
2802 | }
2803 |
--------------------------------------------------------------------------------
/src/pam_python.so:
--------------------------------------------------------------------------------
1 | build/lib.linux-x86_64-2.6/pam_python.so
--------------------------------------------------------------------------------
/src/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python -W default
2 | import warnings; warnings.simplefilter('default')
3 |
4 | import distutils.sysconfig
5 | import os
6 | import sys
7 |
8 | try:
9 | from setuptools import setup, Extension
10 | except ImportError:
11 | from distutils.core import setup, Extension
12 |
13 | long_description = """\
14 | Embeds the Python interpreter into PAM \
15 | so PAM modules can be written in Python"""
16 |
17 | classifiers = [
18 | "Development Status :: 4 - Beta",
19 | "Intended Audience :: Developers",
20 | "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
21 | "Natural Language :: English",
22 | "Operating System :: Unix",
23 | "Programming Language :: C",
24 | "Programming Language :: Python",
25 | "Topic :: Software Development :: Libraries :: Python Modules",
26 | "Topic :: System :: Systems Administration :: Authentication/Directory"]
27 |
28 | if not os.environ.has_key("Py_DEBUG"):
29 | Py_DEBUG = []
30 | else:
31 | Py_DEBUG = [('Py_DEBUG',1)]
32 |
33 | libpython_so = distutils.sysconfig.get_config_var('INSTSONAME')
34 | ext_modules = [
35 | Extension(
36 | "pam_python",
37 | sources=["pam_python.c"],
38 | include_dirs = [],
39 | library_dirs=[],
40 | define_macros=[('LIBPYTHON_SO','"'+libpython_so+'"')] + Py_DEBUG,
41 | libraries=["pam","python%d.%d" % sys.version_info[:2]],
42 | ), ]
43 |
44 | setup(
45 | name="pam_python",
46 | version="1.0.5",
47 | description="Enabled PAM Modules to be written in Python",
48 | keywords="pam,embed,authentication,security",
49 | platforms="Unix",
50 | long_description=long_description,
51 | author="Russell Stuart",
52 | author_email="russell-pampython@stuart.id.au",
53 | url="http://pam-python.sourceforge.net/",
54 | license="AGPL-3.0",
55 | classifiers=classifiers,
56 | ext_modules=ext_modules,
57 | )
58 |
--------------------------------------------------------------------------------
/src/test-pam_python.pam:
--------------------------------------------------------------------------------
1 | auth required /root/pam-python-1.0.5/src/pam_python.so /root/pam-python-1.0.5/src/test.py
2 | account required /root/pam-python-1.0.5/src/pam_python.so /root/pam-python-1.0.5/src/test.py arg1 arg2
3 | password required /root/pam-python-1.0.5/src/pam_python.so /root/pam-python-1.0.5/src/test.py
4 | session required /root/pam-python-1.0.5/src/pam_python.so /root/pam-python-1.0.5/src/test.py
5 |
--------------------------------------------------------------------------------
/src/test-pam_python.pam.in:
--------------------------------------------------------------------------------
1 | auth required $PWD/pam_python.so $PWD/test.py
2 | account required $PWD/pam_python.so $PWD/test.py arg1 arg2
3 | password required $PWD/pam_python.so $PWD/test.py
4 | session required $PWD/pam_python.so $PWD/test.py
5 |
--------------------------------------------------------------------------------
/src/test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python -W default
2 | #
3 | # This is the test script for libpython-pam. There aren't many stones
4 | # left unturned.
5 | #
6 | # Best run from the Makefile using the target 'test'. To run manually:
7 | # sudo ln -s $PWD/test-pam_python.pam /etc/pam.d
8 | # python test.py
9 | # sudo rm /etc/pam.d/test-pam_python.pam
10 | #
11 | import warnings; warnings.simplefilter('default')
12 | import os
13 | import sys
14 |
15 | TEST_PAM_MODULE = "test-pam_python.pam"
16 | TEST_PAM_USER = "root"
17 |
18 | #
19 | # A Fairly straight forward test harness.
20 | #
21 | def pam_sm_end(pamh):
22 | return test(pam_sm_end, pamh, None, None)
23 | def pam_sm_authenticate(pamh, flags, argv):
24 | return test(pam_sm_authenticate, pamh, flags, argv)
25 | def pam_sm_setcred(pamh, flags, argv):
26 | return test(pam_sm_setcred, pamh, flags, argv)
27 | def pam_sm_acct_mgmt(pamh, flags, argv):
28 | return test(pam_sm_acct_mgmt, pamh, flags, argv)
29 | def pam_sm_open_session(pamh, flags, argv):
30 | return test(pam_sm_open_session, pamh, flags, argv)
31 | def pam_sm_close_session(pamh, flags, argv):
32 | return test(pam_sm_close_session, pamh, flags, argv)
33 | def pam_sm_chauthtok(pamh, flags, argv):
34 | return test(pam_sm_chauthtok, pamh, flags, argv)
35 |
36 | def test(who, pamh, flags, argv):
37 | import test
38 | if not hasattr(test, "test_function"):# only true if not called via "main"
39 | return pamh.PAM_SUCCESS # normally happens only if run by ctest
40 | test_function = globals()[test.test_function.__name__]
41 | return test_function(test.test_results, who, pamh, flags, argv)
42 |
43 | def run_test(caller):
44 | import test
45 | test_name = caller.__name__[4:]
46 | sys.stdout.write("Testing " + test_name + " ")
47 | sys.stdout.flush()
48 | test.test_results = []
49 | test.test_function = globals()["test_" + test_name]
50 | caller(test.test_results)
51 | sys.stdout.write("OK\n")
52 |
53 | def pam_conv(auth, query_list, userData=None):
54 | return query_list
55 |
56 | #
57 | # Verify the results match.
58 | #
59 | def assert_results(expected_results, results):
60 | for i in range(min(len(expected_results), len(results))):
61 | assert expected_results[i] == results[i], (i, expected_results[i], results[i])
62 | if len(expected_results) < len(results):
63 | assert len(expected_results) == len(results), (i, results[len(expected_results)])
64 | else:
65 | assert len(expected_results) == len(results), (i, expected_results[len(results)])
66 |
67 | #
68 | # Test all the calls happen.
69 | #
70 | def test_basic_calls(results, who, pamh, flags, argv):
71 | results.append((who.func_name, flags, argv))
72 | return pamh.PAM_SUCCESS
73 |
74 | def run_basic_calls(results):
75 | pam = PAM.pam()
76 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
77 | pam.authenticate(0)
78 | pam.acct_mgmt()
79 | pam.chauthtok()
80 | pam.open_session()
81 | pam.close_session()
82 | del pam
83 | me = os.path.join(os.getcwd(), __file__)
84 | expected_results = [
85 | (pam_sm_authenticate.func_name, 0, [me]),
86 | (pam_sm_acct_mgmt.func_name, 0, [me, 'arg1', 'arg2']),
87 | (pam_sm_chauthtok.func_name, 16384, [me]),
88 | (pam_sm_chauthtok.func_name, 8192, [me]),
89 | (pam_sm_open_session.func_name, 0, [me]),
90 | (pam_sm_close_session.func_name, 0, [me]),
91 | (pam_sm_end.func_name, None, None)]
92 | assert_results(expected_results, results)
93 |
94 | #
95 | # Test all the constants are defined.
96 | #
97 | PAM_CONSTANTS = {
98 | #
99 | # Constants defined in _pam_types.h. The item constants are omitted.
100 | #
101 | "PAM_SUCCESS": 0,
102 | "PAM_OPEN_ERR": 1,
103 | "PAM_SYMBOL_ERR": 2,
104 | "PAM_SERVICE_ERR": 3,
105 | "PAM_SYSTEM_ERR": 4,
106 | "PAM_BUF_ERR": 5,
107 | "PAM_PERM_DENIED": 6,
108 | "PAM_AUTH_ERR": 7,
109 | "PAM_CRED_INSUFFICIENT": 8,
110 | "PAM_AUTHINFO_UNAVAIL": 9,
111 | "PAM_USER_UNKNOWN": 10,
112 | "PAM_MAXTRIES": 11,
113 | "PAM_NEW_AUTHTOK_REQD": 12,
114 | "PAM_ACCT_EXPIRED": 13,
115 | "PAM_SESSION_ERR": 14,
116 | "PAM_CRED_UNAVAIL": 15,
117 | "PAM_CRED_EXPIRED": 16,
118 | "PAM_CRED_ERR": 17,
119 | "PAM_NO_MODULE_DATA": 18,
120 | "PAM_CONV_ERR": 19,
121 | "PAM_AUTHTOK_ERR": 20,
122 | "PAM_AUTHTOK_RECOVER_ERR": 21,
123 | "PAM_AUTHTOK_RECOVERY_ERR": 21,
124 | "PAM_AUTHTOK_LOCK_BUSY": 22,
125 | "PAM_AUTHTOK_DISABLE_AGING": 23,
126 | "PAM_TRY_AGAIN": 24,
127 | "PAM_IGNORE": 25,
128 | "PAM_ABORT": 26,
129 | "PAM_AUTHTOK_EXPIRED": 27,
130 | "PAM_MODULE_UNKNOWN": 28,
131 | "PAM_BAD_ITEM": 29,
132 | "PAM_CONV_AGAIN": 30,
133 | "PAM_INCOMPLETE": 31,
134 | "PAM_SERVICE": 1,
135 | "PAM_USER": 2,
136 | "PAM_TTY": 3,
137 | "PAM_RHOST": 4,
138 | "PAM_CONV": 5,
139 | "PAM_AUTHTOK": 6,
140 | "PAM_OLDAUTHTOK": 7,
141 | "PAM_RUSER": 8,
142 | "PAM_USER_PROMPT": 9,
143 | "PAM_FAIL_DELAY": 10,
144 | "PAM_XDISPLAY": 11,
145 | "PAM_XAUTHDATA": 12,
146 | "PAM_AUTHTOK_TYPE": 13,
147 | "PAM_SILENT": 0x8000,
148 | "PAM_DISALLOW_NULL_AUTHTOK": 0x0001,
149 | "PAM_ESTABLISH_CRED": 0x0002,
150 | "PAM_DELETE_CRED": 0x0004,
151 | "PAM_REINITIALIZE_CRED": 0x0008,
152 | "PAM_REFRESH_CRED": 0x0010,
153 | "PAM_CHANGE_EXPIRED_AUTHTOK": 0x0020,
154 | "PAM_DATA_SILENT": 0x40000000,
155 | "PAM_PROMPT_ECHO_OFF": 1,
156 | "PAM_PROMPT_ECHO_ON": 2,
157 | "PAM_ERROR_MSG": 3,
158 | "PAM_TEXT_INFO": 4,
159 | "PAM_RADIO_TYPE": 5,
160 | "PAM_BINARY_PROMPT": 7,
161 | "PAM_MAX_NUM_MSG": 32,
162 | "PAM_MAX_MSG_SIZE": 512,
163 | "PAM_MAX_RESP_SIZE": 512,
164 | "_PAM_RETURN_VALUES": 32,
165 | #
166 | # Constants defined in pam_modules.h. The item constants are omitted.
167 | #
168 | "PAM_PRELIM_CHECK": 0x4000,
169 | "PAM_UPDATE_AUTHTOK": 0x2000,
170 | "PAM_DATA_REPLACE": 0x20000000,
171 | }
172 | def test_constants(results, who, pamh, flags, argv):
173 | results.append(who.func_name)
174 | if who != pam_sm_authenticate:
175 | return pamh.PAM_SUCCESS
176 | pam_constants = dict([
177 | (var, getattr(pamh,var))
178 | for var in dir(pamh)
179 | if var.startswith("PAM_") or var.startswith("_PAM_")])
180 | results.append(pam_constants)
181 | try:
182 | pamh.PAM_SUCCESS = 1
183 | results.append("Opps, pamh.PAM_SUCCESS = 1 worked!")
184 | except StandardError, e:
185 | results.append("except: %s" % e)
186 | return pamh.PAM_SUCCESS
187 |
188 | def run_constants(results):
189 | pam = PAM.pam()
190 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
191 | pam.authenticate(0)
192 | pam.close_session()
193 | del pam
194 | assert results[0] == pam_sm_authenticate.func_name, (results[0], pam_sm_authenticate.func_name)
195 | assert results[2] == "except: attribute 'PAM_SUCCESS' of 'PamHandle_type' objects is not writable", results[2]
196 | assert results[3] == pam_sm_close_session.func_name, (results[3], pam_sm_close_session.func_name)
197 | assert results[4] == pam_sm_end.func_name, (results[4], pam_sm_end.func_name)
198 | consts = results[1]
199 | for var in PAM_CONSTANTS.keys():
200 | assert consts.has_key(var), var
201 | assert consts[var] == PAM_CONSTANTS[var], (var, consts[var], PAM_CONSTANTS[var])
202 | for var in consts.keys():
203 | assert PAM_CONSTANTS.has_key(var), var
204 | assert PAM_CONSTANTS[var] == consts[var], (var, PAM_CONSTANTS[var], consts[var])
205 | assert len(results) == 5, len(results)
206 |
207 | #
208 | # Test the environment calls.
209 | #
210 | def test_environment(results, who, pamh, flags, argv):
211 | results.append(who.func_name)
212 | if who != pam_sm_acct_mgmt:
213 | return pamh.PAM_SUCCESS
214 | def test_exception(func):
215 | try:
216 | func()
217 | return str(None)
218 | except Exception, e:
219 | return e.__class__.__name__ + ": " + str(e)
220 | #
221 | # A few things to test here. First that PamEnv_as_mapping works.
222 | #
223 | results.append(len(pamh.env))
224 | results.append(pamh.env["x1"])
225 | pamh.env["yy"] = "y"
226 | results.append(pamh.env["yy"])
227 | pamh.env["yy"] = "z"
228 | results.append(pamh.env["yy"])
229 | def t(): pamh.env["yy"] = 1
230 | results.append(test_exception(t))
231 | del pamh.env["yy"]
232 | results.append(test_exception(lambda: pamh.env["yy"]))
233 | results.append(test_exception(lambda: pamh.env[1]))
234 | results.append(test_exception(lambda: pamh.env['a=']))
235 | results.append(test_exception(lambda: pamh.env['']))
236 | #
237 | # Now the dict functions.
238 | #
239 | pamh.env["xx"] = "x"
240 | results.append("not in" in pamh.env)
241 | results.append("xx" in pamh.env)
242 | results.append(pamh.env.has_key("not in"))
243 | results.append(pamh.env.has_key("xx"))
244 | results.append(test_exception(lambda: pamh.env.__getitem__("not in")))
245 | results.append(pamh.env.get("not in"))
246 | results.append(pamh.env.get("not in", "default"))
247 | results.append(pamh.env.get("xx"))
248 | results.append(pamh.env.get("xx", "default"))
249 | del pamh.env["x1"]
250 | results.append(pamh.env.items())
251 | results.append(pamh.env.keys())
252 | results.append(pamh.env.values())
253 | return pamh.PAM_SUCCESS
254 |
255 | def run_environment(results):
256 | pam = PAM.pam()
257 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
258 | pam.authenticate(0)
259 | pam.putenv("x1=1")
260 | pam.putenv("x2=2")
261 | pam.putenv("x3=3")
262 | pam.acct_mgmt()
263 | pam.close_session()
264 | del pam
265 | expected_results = [
266 | pam_sm_authenticate.func_name, pam_sm_acct_mgmt.func_name,
267 | 3, '1', 'y', 'z',
268 | 'TypeError: PAM environment value must be a string',
269 | "KeyError: 'yy'",
270 | 'TypeError: PAM environment key must be a string',
271 | "ValueError: PAM environment key can't contain '='",
272 | "ValueError: PAM environment key mustn't be 0 length",
273 | False, True, False, True,
274 | "KeyError: 'not in'",
275 | None, 'default', 'x', 'x',
276 | [('x2', '2'), ('x3', '3'), ('xx', 'x')],
277 | ['x2', 'x3', 'xx'],
278 | ['2', '3', 'x'],
279 | pam_sm_close_session.func_name, pam_sm_end.func_name]
280 | assert_results(expected_results, results)
281 |
282 | #
283 | # Test strerror().
284 | #
285 | def test_strerror(results, who, pamh, flags, argv):
286 | results.append(who.func_name)
287 | if who != pam_sm_authenticate:
288 | return pamh.PAM_SUCCESS
289 | results.extend([(e, pamh.strerror(e).lower()) for e in (0, 1, 30, 31)])
290 | return pamh.PAM_SUCCESS
291 |
292 | def run_strerror(results):
293 | pam = PAM.pam()
294 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
295 | pam.authenticate(0)
296 | del pam
297 | expected_results = [
298 | pam_sm_authenticate.func_name,
299 | ( 0, 'success'),
300 | ( 1, 'failed to load module'),
301 | (30, 'conversation is waiting for event'),
302 | (31, 'application needs to call libpam again'),
303 | pam_sm_end.func_name]
304 | assert_results(expected_results, results)
305 |
306 | #
307 | # Test items.
308 | #
309 | def test_items(results, who, pamh, flags, argv):
310 | results.append(who.func_name)
311 | if not who in (pam_sm_open_session, pam_sm_close_session):
312 | return pamh.PAM_SUCCESS
313 | items = {
314 | "authtok": "authtok-module",
315 | "authtok_type": "authtok_type-module",
316 | "oldauthtok": "oldauthtok-module",
317 | "rhost": "rhost-module",
318 | "ruser": "ruser-module",
319 | "tty": "tty-module",
320 | "user_prompt": "user_prompt-module",
321 | "user": "user-module",
322 | "xdisplay": "xdisplay-module",
323 | }
324 | keys = items.keys()
325 | keys.sort()
326 | for key in keys:
327 | results.append((key, getattr(pamh, key)))
328 | value = items[key]
329 | if value != None:
330 | setattr(pamh, key, value)
331 | try:
332 | setattr(pamh, "tty", 1)
333 | results.append("%r = %r" % (key, value))
334 | except StandardError, e:
335 | results.append("except: %s" % e)
336 | results.append(pamh.get_user("a prompt"))
337 | return pamh.PAM_SUCCESS
338 |
339 | def run_items(results):
340 | pam = PAM.pam()
341 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
342 | pam.authenticate(0)
343 | items = {
344 | 2: "user",
345 | 3: "tty",
346 | 4: "rhost",
347 | 8: "ruser",
348 | 9: "user_prompt",
349 | 11: "xdisplay",
350 | 13: "authtok_type"}
351 | items_list = items.keys()
352 | items_list.sort()
353 | for item in items_list:
354 | pam.set_item(item, items[item])
355 | pam.open_session()
356 | pam.close_session()
357 | del pam
358 | expected_results = [
359 | pam_sm_authenticate.func_name, pam_sm_open_session.func_name,
360 | ('authtok', None),
361 | ('authtok_type', 'authtok_type'),
362 | ('oldauthtok', None),
363 | ('rhost', 'rhost'),
364 | ('ruser', 'ruser'),
365 | ('tty', 'tty'),
366 | ('user', 'user'),
367 | ('user_prompt', 'user_prompt'),
368 | ('xdisplay', 'xdisplay'),
369 | 'except: PAM item PAM_TTY must be set to a string',
370 | 'user-module',
371 | pam_sm_close_session.func_name,
372 | ('authtok', 'authtok-module'),
373 | ('authtok_type', 'authtok_type-module'),
374 | ('oldauthtok', 'oldauthtok-module'),
375 | ('rhost', 'rhost-module'),
376 | ('ruser', 'ruser-module'),
377 | ('tty', 'tty-module'),
378 | ('user', 'user-module'),
379 | ('user_prompt', 'user_prompt-module'),
380 | ('xdisplay', 'xdisplay-module'),
381 | 'except: PAM item PAM_TTY must be set to a string',
382 | 'user-module',
383 | pam_sm_end.func_name]
384 | assert_results(expected_results, results)
385 |
386 | #
387 | # Test the xauthdata item.
388 | #
389 | def test_xauthdata(results, who, pamh, flags, argv):
390 | results.append(who.func_name)
391 | if not who in (pam_sm_open_session, pam_sm_close_session):
392 | return pamh.PAM_SUCCESS
393 | xauthdata0 = pamh.XAuthData("name-module", "data-module")
394 | pamh.xauthdata = xauthdata0
395 | xauthdata1 = pamh.xauthdata
396 | results.append('name=%r, data=%r' % (xauthdata1.name, xauthdata1.data))
397 | try:
398 | xauthdata2 = pamh.XAuthData(None, "x")
399 | results.append('pamh.XAuthData(%r, %r)' % (xauthdata2.name, xauthdata2.data))
400 | except TypeError, e:
401 | results.append('except: %s' % e)
402 | try:
403 | xauthdata2 = pamh.XAuthData("x", 1)
404 | results.append('pamh.XAuthData(%r, %r)' % (xauthdata2.name, xauthdata2.data))
405 | except TypeError, e:
406 | results.append('except: %s' % e)
407 | class XA: pass
408 | XA.name = "name-XA"
409 | XA.data = "data-XA"
410 | pamh.xauthdata = XA
411 | xauthdata2 = pamh.xauthdata
412 | results.append('name=%r, data=%r' % (xauthdata2.name, xauthdata2.data))
413 | xa = XA()
414 | xa.name = "name-xa"
415 | xa.data = "data-xa"
416 | pamh.xauthdata = xa
417 | xauthdata4 = pamh.xauthdata
418 | results.append('name=%r, data=%r' % (xauthdata4.name, xauthdata4.data))
419 | return pamh.PAM_SUCCESS
420 |
421 | def run_xauthdata(results):
422 | pam = PAM.pam()
423 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
424 | pam.authenticate(0)
425 | #
426 | # The PAM module doesn't support XAUTHDATA, so check what we can from the
427 | # module only.
428 | #
429 | pam.open_session()
430 | pam.close_session()
431 | del pam
432 | expected_results = [
433 | pam_sm_authenticate.func_name, pam_sm_open_session.func_name,
434 | ("name='name-module', data='data-module'"),
435 | 'except: XAuthData() argument 1 must be string, not None',
436 | 'except: XAuthData() argument 2 must be string, not int',
437 | ("name='name-XA', data='data-XA'"),
438 | ("name='name-xa', data='data-xa'"),
439 | pam_sm_close_session.func_name,
440 | ("name='name-module', data='data-module'"),
441 | 'except: XAuthData() argument 1 must be string, not None',
442 | 'except: XAuthData() argument 2 must be string, not int',
443 | ("name='name-XA', data='data-XA'"),
444 | ("name='name-xa', data='data-xa'"),
445 | pam_sm_end.func_name]
446 | assert_results(expected_results, results)
447 |
448 | #
449 | # Test having no pam_sm_end.
450 | #
451 | def test_no_sm_end(results, who, pamh, flags, argv):
452 | results.append(who.func_name)
453 | global pam_sm_end
454 | del pam_sm_end
455 | return pamh.PAM_SUCCESS
456 |
457 | def run_no_sm_end(results):
458 | pam = PAM.pam()
459 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
460 | pam.authenticate(0)
461 | del pam
462 | expected_results = [pam_sm_authenticate.func_name]
463 | assert_results(expected_results, results)
464 |
465 | #
466 | # Test the conversation mechanism.
467 | #
468 | def test_conv(results, who, pamh, flags, argv):
469 | results.append(who.func_name)
470 | if who == pam_sm_end:
471 | return
472 | #
473 | # We must get rid of all references to pamh.Response objects. This instance
474 | # of the test.py module is running inside of libpam_python. That shared
475 | # library will be unloaded soon. Should a pamh.Response instance be
476 | # dealloc'ed after it is unloaded the now non-existant dealloc function will
477 | # be called, and a SIGSEGV will result. Normally instances would not leak,
478 | # but with the trickery we are performing with fake import's here they will
479 | # leak via the results variable unless we take special action.
480 | #
481 | def conv(convs):
482 | responses = pamh.conversation(convs)
483 | if type(responses) != type(()):
484 | return (responses.resp, responses.resp_retcode)
485 | return [(r.resp, r.resp_retcode) for r in responses]
486 | if who == pam_sm_authenticate:
487 | convs = [
488 | pamh.Message(pamh.PAM_PROMPT_ECHO_OFF, "Prompt_echo_off"),
489 | pamh.Message(pamh.PAM_PROMPT_ECHO_ON, "Prompt_echo_on"),
490 | pamh.Message(pamh.PAM_ERROR_MSG, "Error_msg"),
491 | pamh.Message(pamh.PAM_TEXT_INFO, "Text_info")]
492 | if who == pam_sm_acct_mgmt:
493 | convs = pamh.Message(pamh.PAM_PROMPT_ECHO_OFF, "single")
494 | results.append(conv(convs))
495 | return pamh.PAM_SUCCESS
496 |
497 | def run_conv(results):
498 | pam = PAM.pam()
499 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
500 | pam.authenticate(0)
501 | pam.acct_mgmt()
502 | del pam
503 | expected_results = [
504 | pam_sm_authenticate.func_name,
505 | [('Prompt_echo_off', 1), ('Prompt_echo_on', 2), ('Error_msg', 3), ('Text_info', 4)],
506 | pam_sm_acct_mgmt.func_name,
507 | ('single', 1),
508 | pam_sm_end.func_name]
509 | assert_results(expected_results, results)
510 |
511 | #
512 | # Test pam error returns.
513 | #
514 | def test_pamerr(results, who, pamh, flags, argv):
515 | return results[-1]
516 |
517 | def run_pamerr(results):
518 | pam = PAM.pam()
519 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
520 | for err in range(0, PAM._PAM_RETURN_VALUES):
521 | results.append(err)
522 | try:
523 | pam.authenticate(0)
524 | except PAM.error, e:
525 | results[-1] = -e.args[1]
526 | del pam
527 | expected_results = [-r for r in range(PAM._PAM_RETURN_VALUES)]
528 | expected_results[25] = -6
529 | assert_results(expected_results, results)
530 |
531 | #
532 | # Test fail_delay.
533 | #
534 | def test_fail_delay(results, who, pamh, flags, argv):
535 | pamh.fail_delay(10)
536 | return pamh.PAM_SUCCESS
537 |
538 | def run_fail_delay(results):
539 | pam = PAM.pam()
540 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
541 | pam.authenticate(0)
542 | del pam
543 |
544 | #
545 | # Test raising an exception.
546 | #
547 | def test_exceptions(results, who, pamh, flags, argv):
548 | if who != pam_sm_end:
549 | return pamh.PAM_SUCCESS
550 | #
551 | # Here we have use of a backdoor put into pam_python.c specifically
552 | # for testing raising exceptions. Oddly, normally PAM should never
553 | # return anything other than PAM_SUCCESS to anything pam_python.c
554 | # calls.
555 | #
556 | debug_magic = 0x4567abcd
557 | results.append(pamh._PAM_RETURN_VALUES)
558 | for err in range(pamh._PAM_RETURN_VALUES):
559 | try:
560 | pamh.strerror(debug_magic + err)
561 | results.append(err)
562 | except pamh.exception, e:
563 | results.append((-e.pam_result,))
564 | return pamh.PAM_SUCCESS
565 |
566 | def run_exceptions(results):
567 | pam = PAM.pam()
568 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
569 | pam.authenticate(0)
570 | del pam
571 | expected_results = [results[0], 0]
572 | expected_results += [(-r,) for r in range(1, results[0])]
573 | assert_results(expected_results, results)
574 |
575 | #
576 | # Test absent entry point.
577 | #
578 | def test_absent(results, who, pamh, flags, argv):
579 | results.append(who.func_name)
580 | if who != pam_sm_authenticate:
581 | return pamh.PAM_SUCCESS
582 | global pam_sm_acct_mgmt; del pam_sm_acct_mgmt
583 | global pam_sm_setcred; del pam_sm_setcred
584 | global pam_sm_open_session; del pam_sm_open_session
585 | global pam_sm_close_session; del pam_sm_close_session
586 | global pam_sm_chauthtok; del pam_sm_chauthtok
587 | return pamh.PAM_SUCCESS
588 |
589 | def run_absent(results):
590 | pam = PAM.pam()
591 | pam.start(TEST_PAM_MODULE, TEST_PAM_USER, pam_conv)
592 | pam.authenticate(0)
593 | funcs = (
594 | pam.acct_mgmt,
595 | pam.setcred,
596 | pam.open_session,
597 | pam.close_session,
598 | pam.chauthtok
599 | )
600 | for func in funcs:
601 | try:
602 | func(0)
603 | exception = None
604 | except Exception, e:
605 | exception = e
606 | results.append((exception.__class__.__name__, str(exception)))
607 | del pam
608 | expected_results = [
609 | 'pam_sm_authenticate',
610 | ('error', "('Symbol not found', 2)"),
611 | ('error', "('Symbol not found', 2)"),
612 | ('error', "('Symbol not found', 2)"),
613 | ('error', "('Symbol not found', 2)"),
614 | ('error', "('Symbol not found', 2)"),
615 | ]
616 | assert_results(expected_results, results)
617 |
618 | #
619 | # Entry point.
620 | #
621 | def main(argv):
622 | run_test(run_basic_calls)
623 | run_test(run_constants)
624 | run_test(run_environment)
625 | run_test(run_strerror)
626 | run_test(run_items)
627 | run_test(run_xauthdata)
628 | run_test(run_no_sm_end)
629 | run_test(run_conv)
630 | run_test(run_pamerr)
631 | run_test(run_fail_delay)
632 | run_test(run_exceptions)
633 | run_test(run_absent)
634 |
635 | #
636 | # If run from Python run the test suite. Otherwse we are being used
637 | # as a real PAM module presumable from ctest, so just make every call
638 | # return success.
639 | #
640 | if __name__ == "__main__":
641 | import PAM
642 | main(sys.argv)
643 |
--------------------------------------------------------------------------------
/utils/2factor-with-PIN/README.md:
--------------------------------------------------------------------------------
1 | #HELP
2 |
3 | ##1.Add a comment with your account.
4 | ```
5 | usermod -c ',,555-555-5555,' youraccount
6 | ```
7 |
8 | you can check it in /etc/passwd
9 |
10 | ##2.put pam_python.so and auth.py
11 |
12 | put these files into directory /lib64/security/ .
13 |
14 | ##3.replace /etc/pam.d/sshd
15 |
16 | remember to backup you file.
17 |
18 | ##4.turn on ChallengeResponseAuthentication
19 |
20 | in file /etc/ssh/sshd_config,and then restart sshd server.
21 |
22 | ##5.test.
23 |
24 | ##6.preview
25 | ```
26 | [root@IPCPU-11 ~]# ssh ipcpu@192.168.110.11
27 | Enter Your PIN:
28 | Password:
29 | Last login: Mon Mar 21 00:04:37 2016 from 192.168.110.11
30 | [ipcpu@IPCPU-11 ~]$
31 | ```
32 | if the account have no PIN,you will get this
33 | ```
34 | [root@IPCPU-11 ~]# ssh root@192.168.110.11
35 | root@192.168.110.11's password:
36 | Permission denied, please try again.
37 | root@192.168.110.11's password:
38 | Permission denied, please try again.
39 | root@192.168.110.11's password:
40 | Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password,keyboard-interactive).
41 | ```
42 |
43 | ##7.the end.
44 |
--------------------------------------------------------------------------------
/utils/2factor-with-PIN/auth.py:
--------------------------------------------------------------------------------
1 | import random, string, hashlib, requests
2 | import pwd, syslog
3 |
4 |
5 | def auth_log(msg):
6 | """Send errors to default auth log"""
7 | ''' syslog.openlog(facility=syslog.LOG_AUTH)'''
8 | syslog.syslog("IPCPU-PAM-AUTH: " + msg)
9 | syslog.closelog()
10 |
11 |
12 | def get_user_number(user):
13 | """Extract user's phone number for pw entry"""
14 | try:
15 | comments = pwd.getpwnam(user).pw_gecos
16 | except KeyError: # Bad user name
17 | auth_log("No local user (%s) found." % user)
18 | return -1
19 |
20 | try:
21 | return comments.split(',')[2] # Return Office Phone
22 | except IndexError: # Bad comment section format
23 | auth_log("Invalid comment block for user %s. Phone number must be listed as Office Phone" % (user))
24 | return -1
25 |
26 |
27 | def pam_sm_authenticate(pamh, flags, argv):
28 | try:
29 | user = pamh.get_user()
30 | user_number = get_user_number(user)
31 | except pamh.exception, e:
32 | return e.pam_result
33 |
34 | if user is None or user_number == -1:
35 | msg = pamh.Message(pamh.PAM_ERROR_MSG, "Unable to send one time PIN.\nPlease contact your System Administrator")
36 | pamh.conversation(msg)
37 | return pamh.PAM_AUTH_ERR
38 | ###""return pamh.PAM_ABORT""
39 |
40 |
41 | for attempt in range(0,3): # 3 attempts to enter the one time PIN
42 | msg = pamh.Message(pamh.PAM_PROMPT_ECHO_OFF, "Enter Your PIN: ")
43 | resp = pamh.conversation(msg)
44 |
45 | if resp.resp == user_number:
46 | auth_log("user: " + user + " login successful with PIN.")
47 | return pamh.PAM_SUCCESS
48 | else:
49 | auth_log("user: " + user + " login failed with PIN.")
50 | continue
51 | return pamh.PAM_AUTH_ERR
52 |
53 | def pam_sm_setcred(pamh, flags, argv):
54 | return pamh.PAM_SUCCESS
55 |
56 | def pam_sm_acct_mgmt(pamh, flags, argv):
57 | return pamh.PAM_SUCCESS
58 |
59 | def pam_sm_open_session(pamh, flags, argv):
60 | return pamh.PAM_SUCCESS
61 |
62 | def pam_sm_close_session(pamh, flags, argv):
63 | return pamh.PAM_SUCCESS
64 |
65 | def pam_sm_chauthtok(pamh, flags, argv):
66 | return pamh.PAM_SUCCESS
67 |
--------------------------------------------------------------------------------
/utils/2factor-with-PIN/pam.d_sshd:
--------------------------------------------------------------------------------
1 | #%PAM-1.0
2 | auth requisite pam_python.so auth.py
3 | auth required pam_sepermit.so
4 | auth include password-auth
5 | account required pam_nologin.so
6 | account include password-auth
7 | password include password-auth
8 | # pam_selinux.so close should be the first session rule
9 | session required pam_selinux.so close
10 | session required pam_loginuid.so
11 | # pam_selinux.so open should only be followed by sessions to be executed in the user context
12 | session required pam_selinux.so open env_params
13 | session optional pam_keyinit.so force revoke
14 | session include password-auth
15 |
--------------------------------------------------------------------------------
/utils/2factor-with-SMS/README.md:
--------------------------------------------------------------------------------
1 | #HELP
2 |
3 | ##1.Add a comment with your account.
4 | ```
5 | usermod -c ',,555-555-5555,' youraccount
6 | ```
7 |
8 | you can check it in /etc/passwd
9 |
10 | ##2.put pam_python.so and stampauth.py
11 |
12 | put these files into directory /lib64/security/ .
13 |
14 | ##3.replace /etc/pam.d/sshd
15 |
16 | remember to backup you file.
17 |
18 | ##4.turn on ChallengeResponseAuthentication
19 |
20 | in file /etc/ssh/sshd_config,and then restart sshd server.
21 |
22 | ##5.test.
23 |
24 | ##6.preview
25 | ```
26 | [root@IPCPU-11 ~]# ssh ipcpu@192.168.110.11
27 | Enter Your PIN:
28 | Password:
29 | Last login: Mon Mar 21 00:04:37 2016 from 192.168.110.11
30 | [ipcpu@IPCPU-11 ~]$
31 | ```
32 | if the account have no PIN,you will get this
33 | ```
34 | [root@IPCPU-11 ~]# ssh root@192.168.110.11
35 | root@192.168.110.11's password:
36 | Permission denied, please try again.
37 | root@192.168.110.11's password:
38 | Permission denied, please try again.
39 | root@192.168.110.11's password:
40 | Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password,keyboard-interactive).
41 | ```
42 |
43 | ##7.the end.
44 |
--------------------------------------------------------------------------------
/utils/2factor-with-SMS/auth.py:
--------------------------------------------------------------------------------
1 | import random, string, hashlib, requests
2 | import pwd, syslog, json
3 | import urllib, urllib2
4 |
5 |
6 | def auth_log(msg):
7 | syslog.syslog("IPCPU-PAM-AUTH: " + msg)
8 |
9 |
10 | def get_user_number(user):
11 | try:
12 | comments = pwd.getpwnam(user).pw_gecos
13 | except KeyError: # Bad user name
14 | auth_log("No local user (%s) found." % user)
15 | return -1
16 |
17 | try:
18 | return comments.split(',')[2] # Return Office Phone
19 | except IndexError: # Bad comment section format
20 | auth_log("Invalid comment block for user %s. Phone number must be listed as Office Phone" % (user))
21 | return -1
22 |
23 | def genotp(length):
24 | chars=string.ascii_letters+string.digits
25 | return ''.join([random.choice(chars) for i in range(length)])
26 |
27 |
28 | def sendsms(mobile,content):
29 | url = 'http://sms.alibaba.com/smsapi'
30 | SMS_USER = 'alixixi'
31 | SMS_PASS = 'alixixi'
32 |
33 | param = {
34 | 'UserName': SMS_USER,
35 | 'UserPass': SMS_PASS,
36 | 'Mobile': mobile,
37 | 'Content' : content,
38 | }
39 |
40 | res = requests.post(url,data=param)
41 |
42 | def pam_sm_authenticate(pamh, flags, argv):
43 | try:
44 | user = pamh.get_user()
45 | user_number = get_user_number(user)
46 | user_otp = genotp(4)
47 | except pamh.exception, e:
48 | return e.pam_result
49 |
50 | try:
51 | sendsms(user_number,user_otp)
52 | except pamh.exception, e:
53 | return e.pam_result
54 |
55 |
56 | for attempt in range(0,3): # 3 attempts to enter the one time PIN
57 | msg = pamh.Message(pamh.PAM_PROMPT_ECHO_OFF, "Enter Your PIN: ")
58 | resp = pamh.conversation(msg)
59 |
60 | if resp.resp == user_otp:
61 | auth_log("user: " + user + " login successful with PIN.")
62 | return pamh.PAM_SUCCESS
63 | else:
64 | continue
65 | auth_log("user: " + user + " login failed with PIN.")
66 | return pamh.PAM_AUTH_ERR
67 |
68 |
69 | def pam_sm_setcred(pamh, flags, argv):
70 | return pamh.PAM_SUCCESS
71 |
72 | def pam_sm_acct_mgmt(pamh, flags, argv):
73 | return pamh.PAM_SUCCESS
74 |
75 | def pam_sm_open_session(pamh, flags, argv):
76 | return pamh.PAM_SUCCESS
77 |
78 | def pam_sm_close_session(pamh, flags, argv):
79 | return pamh.PAM_SUCCESS
80 |
81 | def pam_sm_chauthtok(pamh, flags, argv):
82 | return pamh.PAM_SUCCESS
83 |
--------------------------------------------------------------------------------
/utils/2factor-with-SMS/pam.d_sshd:
--------------------------------------------------------------------------------
1 | #%PAM-1.0
2 | auth requisite pam_python.so auth.py
3 | auth required pam_sepermit.so
4 | auth include password-auth
5 | account required pam_nologin.so
6 | account include password-auth
7 | password include password-auth
8 | # pam_selinux.so close should be the first session rule
9 | session required pam_selinux.so close
10 | session required pam_loginuid.so
11 | # pam_selinux.so open should only be followed by sessions to be executed in the user context
12 | session required pam_selinux.so open env_params
13 | session optional pam_keyinit.so force revoke
14 | session include password-auth
15 |
--------------------------------------------------------------------------------
/utils/2factor-with-SMS/pam.d_sshd_original:
--------------------------------------------------------------------------------
1 | #%PAM-1.0
2 | auth required pam_sepermit.so
3 | auth include password-auth
4 | account required pam_nologin.so
5 | account include password-auth
6 | password include password-auth
7 | # pam_selinux.so close should be the first session rule
8 | session required pam_selinux.so close
9 | session required pam_loginuid.so
10 | # pam_selinux.so open should only be followed by sessions to be executed in the user context
11 | session required pam_selinux.so open env_params
12 | session optional pam_keyinit.so force revoke
13 | session include password-auth
14 |
--------------------------------------------------------------------------------