Debian Codegraph @

dirsrvtests/tests/suites/plugins/pam_pta_test.py

raw
1 # --- BEGIN COPYRIGHT BLOCK ---
2 # Copyright (C) 2025 Red Hat, Inc.
3 # All rights reserved.
4 #
5 # License: GPL (version 3 or any later version).
6 # See LICENSE for details.
7 # --- END COPYRIGHT BLOCK ---
8
9 import pwd
10 import pytest
11 import os
12 import shutil
13 from lib389.utils import *
14 from test389.topologies import topology_st
15 from lib389._constants import DEFAULT_SUFFIX
16 from lib389.plugins import PAMPassThroughAuthPlugin, PAMPassThroughAuthConfigs
17 from lib389.idm.user import UserAccounts, DEFAULT_BASEDN_RDN
18
19 pytestmark = pytest.mark.tier2
20 pam_pta_ack = pytest.mark.skipif(not os.environ.get('PAM_PTA_ACK', False), reason="PAM PTA tests may damage system configuration.")
21
22 DEBUGGING = os.getenv('DEBUGGING', False)
23
24 logging.getLogger(__name__).setLevel(logging.DEBUG)
25 log = logging.getLogger(__name__)
26
27 PAM_PTA_PLUGIN_DN = 'cn=PAM Pass Through Auth,cn=plugins,cn=config'
28 PAM_PTA_MIGRATED_DN = "cn=default,cn=PAM Pass Through Auth,cn=plugins,cn=config"
29 PLUGIN_ENABLED = 'nsslapd-pluginEnabled'
30 SYSTEM_USER = 'pam_pta_user'
31 SYSTEM_PSWD = 'Secret123'
32
33 @pytest.fixture(scope='module')
34 def system_user():
35 """Create a local system user and yield its details."""
36
37 try:
38 user_info = pwd.getpwnam(SYSTEM_USER)
39 except KeyError:
40 log.info("Create system user, set password, add permissions")
41 subprocess.run(['sudo', 'useradd', '-m', SYSTEM_USER], check=True)
42 subprocess.run(['sudo', 'bash', '-c', f'echo "{SYSTEM_USER}:{SYSTEM_PSWD}" | chpasswd'], check=True)
43 subprocess.run(['sudo', 'setfacl', '-m', f'{SYSTEM_USER}:r--', '/etc/shadow'], check=True)
44 subprocess.run(['sudo', 'setfacl', '-m', 'dirsrv:r--', '/etc/shadow'], check=True)
45 user_info = pwd.getpwnam(SYSTEM_USER)
46
47 try:
48 yield user_info
49
50 finally:
51 try:
52 subprocess.run(['sudo', 'userdel', '-r', SYSTEM_USER], check=True)
53 except Exception as e:
54 log.warning("Failed to delete system user %s: %s", SYSTEM_USER, e)
55
56 @pytest.fixture(scope='module')
57 def ldap_user(topology_st, system_user):
58 """Create an LDAP user, matching the system user and yield its details."""
59
60 inst = topology_st.standalone
61 users = UserAccounts(inst, DEFAULT_SUFFIX)
62
63 user_props = {
64 'uid': system_user.pw_name,
65 'cn': system_user.pw_name,
66 'sn': 'whatever',
67 'uidNumber': str(system_user.pw_uid),
68 'gidNumber': str(system_user.pw_gid),
69 'homeDirectory': system_user.pw_dir,
70 }
71
72 log.info("Create ldap user (no password)")
73 user = users.create(properties=user_props)
74
75 try:
76 yield user
77
78 finally:
79 try:
80 user.delete()
81 except Exception as e:
82 log.warning("Failed to delete ldap user %s: %s", SYSTEM_USER, e)
83
84 @pytest.fixture(scope='module')
85 def pam_service_ldapserver(migrated_child_config):
86 """ Setup config for pamService:ldapserver """
87
88 pam_file = "/etc/pam.d/ldapserver"
89 backup_file = pam_file + ".bak"
90 required_lines = [
91 "auth required pam_unix.so",
92 "account required pam_unix.so"
93 ]
94
95 pam_file_exists = os.path.exists(pam_file)
96 try:
97 # Backup config if it exists
98 if pam_file_exists:
99 shutil.copy2(pam_file, backup_file)
100
101 # Add required lines
102 with open(pam_file, "w") as f:
103 for line in required_lines:
104 f.write(line + "\n")
105 os.chmod(pam_file, 0o644)
106
107 yield
108
109 except Exception as e:
110 if os.path.exists(backup_file):
111 # Restore backup on error
112 shutil.copy2(backup_file, pam_file)
113 pytest.fail(f"Test setup failed with {e}")
114
115 finally:
116 # Cleanup
117 if pam_file_exists and os.path.exists(backup_file):
118 shutil.copy2(backup_file, pam_file)
119 os.remove(backup_file)
120 elif not pam_file_exists:
121 os.remove(pam_file)
122
123 @pytest.fixture(scope='module')
124 def migrated_child_config(topology_st):
125 """Check child config entry 'cn=default...' exists, if not skip the test."""
126
127 inst = topology_st.standalone
128
129 try:
130 inst.getEntry(PAM_PTA_MIGRATED_DN, ldap.SCOPE_BASE, "(objectClass=*)")
131 print(f"{PAM_PTA_MIGRATED_DN} exists")
132 except ldap.NO_SUCH_OBJECT:
133 pytest.skip(f"Child config '{PAM_PTA_MIGRATED_DN}' does not exist. Skipping test.")
134
135 yield
136
137 @pam_pta_ack
138 def test_bind_default_config(topology_st, migrated_child_config, pam_service_ldapserver, ldap_user):
139 """Test PAM Passthrough Auth with default config.
140
141 :id: 6e2b16c9-04c8-4dd2-ad55-e8e9c92038dd
142 :setup: Standalone instance
143 :steps:
144 1. Enable TLS (default child config requires pamSecure=True)
145 2. Enable the plugin and restart the instance
146 3. Bind as ldap user
147 4. Check error logs for plugin message
148 :expectedresults:
149 1. Success
150 2. Success
151 3. Success
152 4. No plugin warning in logs
153 """
154 inst = topology_st.standalone
155 inst.enable_tls()
156
157 log.info("Enable PAM PTA plugin and restart server")
158 pta = PAMPassThroughAuthPlugin(inst)
159 pta.enable()
160
161 inst.restart()
162 entry = inst.getEntry(PAM_PTA_PLUGIN_DN, ldap.SCOPE_BASE, "(objectclass=*)", [PLUGIN_ENABLED])
163 assert entry.hasAttr(PLUGIN_ENABLED)
164 assert entry.getValue(PLUGIN_ENABLED).lower() == b'on'
165
166 log.info("Bind as user, default config")
167 try:
168 ldap_user.bind(SYSTEM_PSWD)
169 except:
170 pytest.fail("PTA - default config bind failed")
171
172 log.info("Verify there are no warnings in error logs")
173 assert not topology_st.standalone.ds_error_log.match('.*pam_passthru-plugin.*')
174
175 pta.disable()
176
177 @pam_pta_ack
178 def test_bind_excluded_suffix(topology_st, pam_service_ldapserver, ldap_user):
179 """Test PAM Passthrough Auth with excluded suffix (fallback to default config).
180
181 :id: ddbba223-7dcd-4604-9cfc-392ab053943e
182 :setup: Standalone instance
183 :steps:
184 1. Enable TLS (default child config requires pamSecure=True)
185 2. Enable the plugin and restart the instance
186 3. Create a config to exclude users suffix
187 4. Bind as ldap user
188 5. Add user password
189 6. Bind as ldap user
190 7. Check error logs for plugin message
191 :expectedresults:
192 1. Success
193 2. Success
194 3. Success
195 4. Bind should fail with invalid creds (no ldap passwd and not pta)
196 5. Success
197 6. Success
198 7. No plugin warning in logs
199 """
200 inst = topology_st.standalone
201 inst.enable_tls()
202 pta_config = "exclude"
203
204 log.info("Enable PAM PTA plugin and restart server")
205 pta = PAMPassThroughAuthPlugin(inst)
206 pta.enable()
207
208 inst.restart()
209 entry = inst.getEntry(PAM_PTA_PLUGIN_DN, ldap.SCOPE_BASE, "(objectclass=*)", [PLUGIN_ENABLED])
210 assert entry.hasAttr(PLUGIN_ENABLED)
211 assert entry.getValue(PLUGIN_ENABLED).lower() == b'on'
212
213 log.info("Create PAM PTA config to exclude users suffix")
214 pta_configs = PAMPassThroughAuthConfigs(inst)
215 pta_configs.create(properties={
216 'cn': pta_config,
217 'pamExcludeSuffix': f"{DEFAULT_BASEDN_RDN},{DEFAULT_SUFFIX}",
218 'pamFallback': 'FALSE',
219 'pamIDAttr': 'uid',
220 'pamMissingSuffix': 'ERROR',
221 'pamIDMapMethod': 'ENTRY',
222 'pamSecure': 'FALSE',
223 'pamService': 'system-auth'
224 })
225
226 log.info("Bind as user, excluded suffix, no passwd")
227 with pytest.raises(ldap.INVALID_CREDENTIALS):
228 ldap_user.bind(SYSTEM_PSWD)
229
230 LDAP_PWSD = "iamexcluded"
231 ldap_user.set('userpassword', LDAP_PWSD)
232 try:
233 log.info("Bind as user, excluded suffix, with passwd")
234 ldap_user.bind(LDAP_PWSD)
235 except:
236 pytest.fail("PTA - excluded suffix bind failed")
237
238 log.info("Verify there are no warnings in error logs")
239 assert not topology_st.standalone.ds_error_log.match('.*pam_passthru-plugin.*')
240
241 pta.disable()
242
243 @pam_pta_ack
244 def test_bind_included_suffix(topology_st, ldap_user):
245 """Test PAM Passthrough Auth with included suffix.
246
247 :id: d2b5366f-b36b-4251-b7ba-1c60546e75a8
248 :setup: Standalone instance
249 :steps:
250 1. Enable the plugin and restart the instance
251 2. Create a config to exclude users suffix, fallback=true
252 3. Set ldap user password
253 4. Bind as ldap user
254 5. Check error logs for plugin messages
255 :expectedresults:
256 1. Success
257 2. Success
258 3. SUccess
259 4. Success
260 5. No plugin warning in logs
261 """
262 inst = topology_st.standalone
263 pta_config = "included"
264
265 log.info("Enable PAM PTA plugin and restart server")
266 pta = PAMPassThroughAuthPlugin(inst)
267 pta.enable()
268 inst.restart()
269 entry = inst.getEntry(PAM_PTA_PLUGIN_DN, ldap.SCOPE_BASE, "(objectclass=*)", [PLUGIN_ENABLED])
270 assert entry.hasAttr(PLUGIN_ENABLED)
271 assert entry.getValue(PLUGIN_ENABLED).lower() == b'on'
272
273 log.info("Create PAM PTA config, include users suffix")
274 pta_configs = PAMPassThroughAuthConfigs(inst)
275 pta_configs.create(properties={
276 'cn': pta_config,
277 'pamIncludeSuffix': f"{DEFAULT_BASEDN_RDN},{DEFAULT_SUFFIX}",
278 'pamFallback': 'FALSE',
279 'pamIDAttr': 'uid',
280 'pamIDMapMethod': 'ENTRY',
281 'pamSecure': 'FALSE',
282 'pamService': 'system-auth'
283 })
284
285 log.info("Bind as user, included suffix")
286 try:
287 ldap_user.bind(SYSTEM_PSWD)
288 except:
289 pytest.fail("PTA - included suffix bind failed")
290
291 log.info("Verify there are no warnings in error logs")
292 assert not topology_st.standalone.ds_error_log.match('.*- pam_passthru-plugin -*.')
293
294 pta.disable()
295
296 if __name__ == '__main__':
297 # Run isolated
298 # -s for DEBUG mode
299 CURRENT_FILE = os.path.realpath(__file__)
300 pytest.main("-s %s" % CURRENT_FILE)