Debian Codegraph @

dirsrvtests/tests/suites/ldapi/ldapi_test.py

raw
1 # --- BEGIN COPYRIGHT BLOCK ---
2 # Copyright (C) 2022 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 logging
10 import pytest
11 import os
12 import subprocess
13 from lib389._constants import DEFAULT_SUFFIX, DN_DM, PASSWORD
14 from lib389.idm.directorymanager import DirectoryManager
15 from lib389.idm.user import UserAccounts
16 from lib389.ldapi import LDAPIMapping, LDAPIFixedMapping
17 from test389.topologies import topology_st as topo
18 from lib389.tasks import LDAPIMappingReloadTask
19
20 log = logging.getLogger(__name__)
21
22 if os.geteuid() != 0:
23 pytest.skip("Must be root to run LDAPI tests")
24
25 # Common constants
26 LDAPI_AUTH_CONTAINER = "cn=auto_bind,cn=config"
27 DEFAULT_PASSWORD = "5ecret_137"
28
29
30 @pytest.fixture(scope="function")
31 def ldapi_config(topo):
32 """Configure LDAPI settings and return socket path"""
33 topo.standalone.config.set('nsslapd-accesslog-logbuffering', 'off')
34 topo.standalone.config.set('nsslapd-ldapilisten', 'on')
35 topo.standalone.config.set('nsslapd-ldapiautobind', 'on')
36 topo.standalone.config.set('nsslapd-ldapiDNMappingBase', LDAPI_AUTH_CONTAINER)
37 topo.standalone.config.set('nsslapd-ldapimaptoentries', 'on')
38 topo.standalone.config.set('nsslapd-ldapiuidnumbertype', 'uidNumber')
39 topo.standalone.config.set('nsslapd-ldapigidnumbertype', 'gidNumber')
40
41 ldapi_socket_raw = topo.standalone.config.get_attr_val_utf8('nsslapd-ldapifilepath')
42 ldapi_socket = ldapi_socket_raw.replace('/', '%2F')
43
44 return ldapi_socket
45
46
47 def create_os_user(username, uid, password=DEFAULT_PASSWORD):
48 """Helper to create OS user"""
49 subprocess.run(['useradd', '-u', str(uid), '-p', password, username],
50 check=False)
51 return username
52
53
54 def cleanup_os_user(username):
55 """Helper to cleanup OS user"""
56 try:
57 subprocess.run(['userdel', '-r', username], check=False)
58 except:
59 pass
60
61
62 def ldapsearch_ldapi(ldapi_socket, user=None):
63 """Helper to build ldapsearch command for LDAPI"""
64 cmd = f'ldapsearch -b \'\' -s base -Y EXTERNAL -H ldapi://{ldapi_socket}'
65 if user:
66 return f'su {user} -c "{cmd}"'
67 return cmd
68
69
70 @pytest.fixture(scope="function")
71 def os_user_factory(request):
72 """Factory fixture to create and cleanup OS users"""
73 users = []
74
75 def _create_user(username, uid, password=DEFAULT_PASSWORD):
76 create_os_user(username, uid, password)
77 users.append(username)
78 return username
79
80 yield _create_user
81
82 # Cleanup
83 for user in users:
84 cleanup_os_user(user)
85
86
87 @pytest.fixture(scope="function")
88 def ldap_user_factory(topo):
89 """Factory fixture to create LDAP users with common properties"""
90 users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
91
92 def _create_ldap_user(uid, uidnumber, gidnumber, **extra_props):
93 """Create LDAP user with standard properties"""
94 properties = {
95 'uid': uid,
96 'cn': uid,
97 'sn': uid,
98 'uidNumber': str(uidnumber),
99 'gidNumber': str(gidnumber),
100 'userpassword': PASSWORD,
101 'homeDirectory': f'/home/{uid}'
102 }
103 properties.update(extra_props)
104 return users.create(properties=properties)
105
106 return _create_ldap_user
107
108
109 def test_ldapi_authdn_attr_rewrite(topo, ldapi_config, os_user_factory, ldap_user_factory):
110 """Test LDAPI Authentication DN mapping feature
111
112 :id: e8d68979-4b3d-4e2d-89ed-f9bad827718c
113 :setup: Standalone Instance
114 :steps:
115 1. Set LDAPI configuration
116 2. Create LDAP users
117 3. Create OS users
118 4. Create entries under cn=config for auto bind subtree and mapping entry
119 5. Do an LDAPI ldapsearch as the OS user
120 6. OS user was mapped expected LDAP entry
121 7. Do search using root & LDAPI
122 :expectedresults:
123 1. Success
124 2. Success
125 3. Success
126 4. Success
127 5. Success
128 6. Success
129 7. Success
130 """
131
132 LINUX_USER = "ldapi_test_lib389_user"
133 LINUX_USER2 = "ldapi_test_lib389_user2"
134 LINUX_USER3 = "ldapi_test_lib389_user3"
135 LDAP_ENTRY_DN = f"uid=test_ldapi,ou=people,{DEFAULT_SUFFIX}"
136 LDAP_ENTRY_DN2 = f"uid=test_ldapi2,ou=people,{DEFAULT_SUFFIX}"
137 LDAP_ENTRY_DN3 = f"uid=test_ldapi3,ou=people,{DEFAULT_SUFFIX}"
138
139 # Create LDAP users
140 ldap_user_factory('test_ldapi', 2020, 2020, description='userdesc')
141 ldap_user_factory('test_ldapi2', 2021, 2021, description='userdesc')
142 ldap_user_factory('test_ldapi3', 2023, 2023, description='userdesc')
143
144 # Create OS users
145 os_user_factory(LINUX_USER, 5001)
146 os_user_factory(LINUX_USER2, 5002)
147
148 # Create some mapping entries
149 ldapi_mapping = LDAPIMapping(topo.standalone, LDAPI_AUTH_CONTAINER)
150 ldapi_mapping.create_mapping(name='entry_map1', username='dummy1',
151 ldap_dn=f'uid=dummy1,{DEFAULT_SUFFIX}')
152 ldapi_mapping.create_mapping(name='entry_map2', username=LINUX_USER,
153 ldap_dn=LDAP_ENTRY_DN)
154 ldapi_mapping.create_mapping(name='entry_map3', username='dummy2',
155 ldap_dn=f'uid=dummy3,{DEFAULT_SUFFIX}')
156
157 # Restart server for config to take effect, and clear the access log
158 topo.standalone.deleteAccessLogs(restart=True)
159
160 # Bind as OS user using ldapsearch
161 os.system(ldapsearch_ldapi(ldapi_config, LINUX_USER))
162
163 # Check access log
164 assert topo.standalone.ds_access_log.match(f'.*AUTOBIND dn="{LDAP_ENTRY_DN}".*')
165
166 # Bind as Root DN just to make sure it still works
167 assert os.system(ldapsearch_ldapi(ldapi_config)) == 0
168 assert topo.standalone.ds_access_log.match(f'.*AUTOBIND dn="{DN_DM}".*')
169
170 # Create some fixed mapping
171 ldapi_fixed_mapping = LDAPIFixedMapping(topo.standalone, LDAPI_AUTH_CONTAINER)
172 ldapi_fixed_mapping.create_mapping("fixed", "5002", "5002", ldap_dn=LDAP_ENTRY_DN2)
173 topo.standalone.deleteAccessLogs(restart=True)
174
175 # Bind as OS user using ldapsearch
176 os.system(ldapsearch_ldapi(ldapi_config, LINUX_USER2))
177
178 # Check access log
179 assert topo.standalone.ds_access_log.match(f'.*AUTOBIND dn="{LDAP_ENTRY_DN2}".*')
180
181 # Add 3rd user, and test reload task
182 os_user_factory(LINUX_USER3, 5003)
183 ldapi_fixed_mapping.create_mapping("reload", "5003", "5003", ldap_dn=LDAP_ENTRY_DN3)
184
185 reload_task = LDAPIMappingReloadTask(topo.standalone).create()
186 reload_task.wait(timeout=20)
187
188 os.system(ldapsearch_ldapi(ldapi_config, LINUX_USER3))
189 assert topo.standalone.ds_access_log.match(f'.*AUTOBIND dn="{LDAP_ENTRY_DN3}".*')
190
191
192 @pytest.mark.parametrize("lock_state,expected_autobind", [
193 ("locked", False), # Locked account should NOT autobind
194 ("nonexistent", False), # Non-existent entry should NOT autobind
195 ])
196 def test_ldapi_for_bad_accounts(topo, ldapi_config, os_user_factory, ldap_user_factory,
197 lock_state, expected_autobind):
198 """Test LDAPI memory leaks with locked/non-existent accounts
199
200 :id: c0f5cce9-d62e-441d-9e6f-5b67dc0a4e69
201 :setup: Standalone Instance with LDAPI configured
202 :steps:
203 1. Create LDAP user (or not, if testing non-existent)
204 2. Lock account if testing locked state
205 3. Create OS user
206 4. Create LDAPI mapping
207 5. Restart server
208 6. Try LDAPI bind as OS user
209 7. Verify expected behavior
210 :expectedresults:
211 1. Success
212 2. Success
213 3. Success
214 4. Success
215 5. Success
216 6. Success
217 7. No AUTOBIND for locked/non-existent
218 """
219
220 LINUX_USER = f"ldapi_{lock_state}_user"
221 LDAP_UID = f"test_{lock_state}"
222 LDAP_ENTRY_DN = f"uid={LDAP_UID},ou=people,{DEFAULT_SUFFIX}"
223 OS_UID = 6001 if lock_state == "locked" else 6002
224
225 # Create OS user
226 os_user_factory(LINUX_USER, OS_UID)
227
228 if lock_state == "locked":
229 # Create LDAP user and lock it
230 user = ldap_user_factory(LDAP_UID, OS_UID, OS_UID)
231 user.replace('nsAccountLock', 'true')
232
233 # Create mapping (to locked account or non-existent entry)
234 ldapi_mapping = LDAPIMapping(topo.standalone, LDAPI_AUTH_CONTAINER)
235 ldapi_mapping.create_mapping(name=f'{lock_state}_map',
236 username=LINUX_USER,
237 ldap_dn=LDAP_ENTRY_DN)
238
239 # Restart and clear logs
240 if lock_state == "nonexistent":
241 topo.standalone.deleteErrorLogs()
242 topo.standalone.deleteAccessLogs(restart=True)
243
244 # Try LDAPI bind as OS user
245 os.system(ldapsearch_ldapi(ldapi_config, LINUX_USER))
246
247 # Verify expected behavior
248 autobind_match = topo.standalone.ds_access_log.match(f'.*AUTOBIND dn="{LDAP_ENTRY_DN}".*')
249
250 if expected_autobind:
251 assert autobind_match, f"Expected AUTOBIND for {lock_state}"
252 else:
253 assert not autobind_match, f"Unexpected AUTOBIND for {lock_state} account"
254
255 # Additional check for non-existent entry
256 if lock_state == "nonexistent":
257 assert topo.standalone.ds_error_log.match('.*LDAPI auth mapping.*does not exist.*')
258
259
260 def test_ldapi_locked_root_account(topo, ldapi_config, ldap_user_factory, request):
261 """Test LDAPI with locked root account
262
263 This tests the memory leak fix for ldapi.c:348-354 where root_dn
264 is not freed when root account is locked.
265
266 :id: 5c07605e-ec94-4b62-8344-87ac4ab9ba6b
267 :setup: Standalone Instance with LDAPI configured
268 :steps:
269 1. Create a new LDAP user to serve as root DN
270 2. Change root DN configuration to this user
271 3. Rebind as the new root DN
272 4. Lock the root DN entry
273 5. Try to bind as system root using LDAPI
274 6. Verify no AUTOBIND (account is locked)
275 7. Restore original root DN
276 :expectedresults:
277 1. Success
278 2. Success
279 3. Success
280 4. Success
281 5. Fail
282 6. Success
283 7. Success
284 """
285
286 test_root_dn = f'uid=test_rootdn,ou=people,{DEFAULT_SUFFIX}'
287
288 def fin():
289 # Cleanup: restore original root DN
290 try:
291 # First unlock the test root user so we can authenticate with it
292 from lib389._mapped_object import DSLdapObject
293 try:
294 root_user = DSLdapObject(topo.standalone, dn=test_root_dn)
295 root_user.remove('nsAccountLock', 'true')
296 # Rebind as unlocked test root
297 dm = DirectoryManager(topo.standalone, test_root_dn)
298 dm.bind(PASSWORD)
299 except:
300 pass
301
302 # Restore original root DN
303 topo.standalone.config.replace('nsslapd-rootdn', DN_DM)
304 topo.standalone.restart()
305 except Exception as e:
306 log.error(f"Cleanup failed: {e}")
307 request.addfinalizer(fin)
308
309 # Create a new LDAP user to use as root DN
310 root_user = ldap_user_factory('test_rootdn', 7001, 7001)
311
312 # Change root DN to this user (while still unlocked)
313 topo.standalone.config.replace('nsslapd-rootdn', root_user.dn)
314
315 # Rebind as the new root DN
316 dm = DirectoryManager(topo.standalone, root_user.dn)
317 dm.bind(PASSWORD)
318
319 # Lock the root account
320 root_user.replace('nsAccountLock', 'true')
321
322 # Try to bind as system root using LDAPI (should fail - account is locked)
323 os.system(ldapsearch_ldapi(ldapi_config))
324
325 # Verify NO AUTOBIND in access log (root account is locked)
326 assert not topo.standalone.ds_access_log.match(f'.*AUTOBIND dn="{root_user.dn}".*'), \
327 "Root DN should not autobind when locked"
328
329
330 if __name__ == '__main__':
331 # Run isolated
332 # -s for DEBUG mode
333 CURRENT_FILE = os.path.realpath(__file__)
334 pytest.main(["-s", CURRENT_FILE])