Debian Codegraph @

dirsrvtests/tests/suites/password/pwdPolicy_syntax_test.py

raw
1 # --- BEGIN COPYRIGHT BLOCK ---
2 # Copyright (C) 2026 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
11 import pytest
12 from lib389.tasks import *
13 from lib389.utils import *
14 from test389.topologies import topology_st
15 from lib389._constants import DEFAULT_SUFFIX, PASSWORD, DN_DM
16 from lib389.idm.domain import Domain
17 from lib389.idm.user import UserAccounts
18 from lib389.idm.organizationalunit import OrganizationalUnits
19 from lib389.pwpolicy import PwPolicyManager
20
21 pytestmark = pytest.mark.tier1
22
23 USER_DN = 'uid=user,ou=People,%s' % DEFAULT_SUFFIX
24 USER_RDN = 'user'
25 PEOPLE_DN = 'ou=people,%s' % DEFAULT_SUFFIX
26 USER_ACI = '(targetattr="userpassword")(version 3.0; acl "pwp test"; allow (all) userdn="ldap:///self";)'
27
28 logging.getLogger(__name__).setLevel(logging.INFO)
29 log = logging.getLogger(__name__)
30
31
32 @pytest.fixture(scope="module")
33 def password_policy(topology_st):
34 """Set global password policy"""
35
36 log.info('Enable global password policy. Check for syntax.')
37 topology_st.standalone.config.set('passwordCheckSyntax', 'on')
38 topology_st.standalone.config.set('nsslapd-pwpolicy-local', 'off')
39 topology_st.standalone.config.set('passwordMinCategories', '1')
40
41 # Add self user modification and anonymous aci
42 USER_SELF_MOD_ACI = '(targetattr="userpassword")(version 3.0; acl "pwp test"; allow (all) userdn="ldap:///self";)'
43 ANON_ACI = "(targetattr=\"*\")(version 3.0; acl \"Anonymous Read access\"; allow (read,search,compare) userdn = \"ldap:///anyone\";)"
44 suffix = Domain(topology_st.standalone, DEFAULT_SUFFIX)
45 suffix.add('aci', USER_SELF_MOD_ACI)
46 suffix.add('aci', ANON_ACI)
47
48
49 @pytest.fixture(scope="module")
50 def create_user(topology_st):
51 """Create the test user."""
52 users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
53 users.create(properties={
54 'uid': USER_RDN,
55 'cn': USER_RDN,
56 'sn': USER_RDN,
57 'uidNumber': '3000',
58 'gidNumber': '4000',
59 'homeDirectory': '/home/user',
60 'description': 'd_e_s_c',
61 'loginShell': USER_RDN,
62 'userPassword': PASSWORD
63 })
64
65
66 def setPolicy(inst, attr, value):
67 """Bind as Root DN, set policy, and then bind as user"""
68
69 inst.simple_bind_s(DN_DM, PASSWORD)
70
71 # Set the policy value
72 value = str(value)
73 inst.config.set(attr, value)
74
75 policy = inst.config.get_attr_val_utf8(attr)
76 assert policy == value
77
78
79 def resetPasswd(inst):
80 """Reset the user password for the next test"""
81
82 # First, bind as the ROOT DN so we can set the password
83 inst.simple_bind_s(DN_DM, PASSWORD)
84
85 # Now set the password
86 users = UserAccounts(inst, DEFAULT_SUFFIX)
87 user = users.get(USER_RDN)
88 user.reset_password(PASSWORD)
89
90
91 def tryPassword(inst, policy_attr, value, reset_value, pw_bad, pw_good, msg):
92 """Attempt to change the users password
93 inst: DirSrv Object
94 password: password
95 msg - error message if failure
96 """
97
98 setPolicy(inst, policy_attr, value)
99 inst.simple_bind_s(USER_DN, PASSWORD)
100 users = UserAccounts(inst, DEFAULT_SUFFIX)
101 user = users.get(USER_RDN)
102 try:
103 user.reset_password(pw_bad)
104 log.fatal('Invalid password was unexpectedly accepted (%s)' %
105 (policy_attr))
106 assert False
107 except ldap.CONSTRAINT_VIOLATION:
108 log.info('Invalid password correctly rejected by %s: %s' %
109 (policy_attr, msg))
110 pass
111 except ldap.LDAPError as e:
112 log.fatal("Failed to change password: " + str(e))
113 assert False
114
115 # Change password that is allowed
116 user.reset_password(pw_good)
117
118 # Reset for the next test
119 resetPasswd(inst)
120 setPolicy(inst, policy_attr, reset_value)
121
122
123 def setSubtreePolicy(inst, policy_entry, attr, value):
124 """Bind as Root DN and set an attribute on a subtree password policy entry."""
125
126 inst.simple_bind_s(DN_DM, PASSWORD)
127 value = str(value)
128 policy_entry.replace(attr, value)
129 policy = policy_entry.get_attr_val_utf8(attr)
130 assert policy == value
131
132
133 def tryPasswordSubtree(inst, policy_entry, policy_attr, value, reset_value, pw_bad, pw_good, msg):
134 """Like tryPassword but applies policy_attr on a local PwPolicyEntry."""
135
136 setSubtreePolicy(inst, policy_entry, policy_attr, value)
137 inst.simple_bind_s(USER_DN, PASSWORD)
138 users = UserAccounts(inst, DEFAULT_SUFFIX)
139 user = users.get(USER_RDN)
140 try:
141 user.reset_password(pw_bad)
142 log.fatal('Invalid password was unexpectedly accepted (%s)' %
143 (policy_attr))
144 assert False
145 except ldap.CONSTRAINT_VIOLATION:
146 log.info('Invalid password correctly rejected by subtree %s: %s' %
147 (policy_attr, msg))
148 pass
149 except ldap.LDAPError as e:
150 log.fatal("Failed to change password: " + str(e))
151 assert False
152
153 user.reset_password(pw_good)
154
155 resetPasswd(inst)
156 setSubtreePolicy(inst, policy_entry, policy_attr, reset_value)
157
158
159 def _run_password_syntax_checks(try_pw):
160 """Run the standard password syntax checks; try_pw matches tryPassword call shape."""
161
162 # Min Length
163 try_pw('passwordMinLength', 10, 2, 'passwd',
164 'password123', 'length too short')
165 # Min Digit
166 try_pw('passwordMinDigits', 2, 0, 'passwd',
167 'password123', 'does not contain minimum number of digits')
168 # Min Alphas
169 try_pw('passwordMinAlphas', 2, 0, 'p123456789',
170 'password123', 'does not contain minimum number of alphas')
171 # Max Repeats
172 try_pw('passwordMaxRepeats', 2, 0, 'passsword',
173 'password123', 'too many repeating characters')
174 # Min Specials
175 try_pw('passwordMinSpecials', 2, 0, 'passwd',
176 'password_#$',
177 'does not contain minimum number of special characters')
178 # Min Lowers
179 try_pw('passwordMinLowers', 2, 0, 'PASSWORD123',
180 'password123',
181 'does not contain minimum number of lowercase characters')
182 # Min Uppers
183 try_pw('passwordMinUppers', 2, 0, 'password',
184 'PASSWORD',
185 'does not contain minimum number of lowercase characters')
186 # Min 8-bit (non-ASCII UTF-8 bytes; high-bit bytes count toward num_8bit)
187 try_pw('passwordMin8Bit', 1, 0, 'Za12_ab_XY_9qM',
188 'Za12_ab_\u00fcXY_9qM#',
189 'does not contain minimum number of 8-bit characters')
190
191 if ds_is_newer('1.4.0.13'):
192 # Dictionary check
193 try_pw('passwordDictCheck', 'on', 'on', 'PASSWORD',
194 '13_#Kad472h', 'Password found in dictionary')
195
196 # Palindromes
197 try_pw('passwordPalindrome', 'on', 'on', 'Za12_#_21aZ',
198 '13_#Kad472h', 'Password is palindrome')
199
200 # Sequences
201 try_pw('passwordMaxSequence', 3, 0, 'Za1_1234',
202 '13_#Kad472h', 'Max monotonic sequence is not allowed')
203 try_pw('passwordMaxSequence', 3, 0, 'Za1_4321',
204 '13_#Kad472h', 'Max monotonic sequence is not allowed')
205 try_pw('passwordMaxSequence', 3, 0, 'Za1_abcd',
206 '13_#Kad472h', 'Max monotonic sequence is not allowed')
207 try_pw('passwordMaxSequence', 3, 0, 'Za1_dcba',
208 '13_#Kad472h', 'Max monotonic sequence is not allowed')
209
210 # Sequence Sets
211 try_pw('passwordMaxSeqSets', 2, 0, 'Za1_123--123',
212 '13_#Kad472h', 'Max monotonic sequence is not allowed')
213
214 # Max characters in a character class
215 try_pw('passwordMaxClassChars', 3, 0, 'Za1_9376',
216 '13_#Kad472h', 'Too may consecutive characters from the same class')
217 try_pw('passwordMaxClassChars', 3, 0, 'Za1_#$&!',
218 '13_#Kad472h', 'Too may consecutive characters from the same class')
219 try_pw('passwordMaxClassChars', 3, 0, 'Za1_ahtf',
220 '13_#Kad472h', 'Too may consecutive characters from the same class')
221 try_pw('passwordMaxClassChars', 3, 0, 'Za1_HTSE',
222 '13_#Kad472h', 'Too may consecutive characters from the same class')
223
224 # Bad words
225 try_pw('passwordBadWords', 'redhat', 'none', 'Za1_redhat',
226 '13_#Kad472h', 'Password contains a bad word')
227
228 # User Attributes
229 try_pw('passwordUserAttributes', 'description', 0, 'Za1_d_e_s_c',
230 '13_#Kad472h', 'Password found in user entry')
231
232
233 def test_basic(topology_st, create_user, password_policy):
234 """Ensure that on a password change, the policy syntax
235 is enforced correctly.
236
237 :id: e8de7029-7fa6-4e96-9eb6-4a121f4c8fb3
238 :customerscenario: True
239 :setup: Standalone instance, a test user,
240 global password policy with:
241 passwordCheckSyntax - on; nsslapd-pwpolicy-local - off;
242 passwordMinCategories - 1
243 :steps:
244 1. Run all syntax checks against cn=config (global policy), including
245 passwordMin8Bit using a UTF-8 password containing a Latin-1 letter.
246 2. Run the same checks against a subtree password policy on
247 ou=people,dc=example,dc=com (with passwordMinCategories 1 on the
248 subtree entry), then remove the subtree policy.
249 :expectedresults:
250 1. Each policy attribute behaves as documented for self-service password change.
251 2. Subtree policy enforcement matches global for every check; cleanup succeeds.
252 """
253
254 standalone = topology_st.standalone
255
256 ous = OrganizationalUnits(standalone, DEFAULT_SUFFIX)
257 ou = ous.get('people')
258 ou.add('aci', USER_ACI)
259
260 _run_password_syntax_checks(
261 lambda *args: tryPassword(standalone, *args))
262
263 log.info('\n\nRepeat syntax checks against subtree password policy at %s', PEOPLE_DN)
264 pwp = None
265 try:
266 pwp = PwPolicyManager(standalone)
267 pwp_entry = pwp.create_subtree_policy(
268 PEOPLE_DN,
269 {'passwordchange': 'on',
270 'passwordCheckSyntax': 'on',
271 'passwordMinCategories': '1'})
272 _run_password_syntax_checks(
273 lambda *args: tryPasswordSubtree(standalone, pwp_entry, *args))
274 finally:
275 standalone.simple_bind_s(DN_DM, PASSWORD)
276 if pwp is not None:
277 try:
278 pwp.delete_local_policy(PEOPLE_DN)
279 except ValueError:
280 pass
281 standalone.config.set('nsslapd-pwpolicy-local', 'off')
282
283
284 @pytest.mark.skipif(ds_is_older("1.4.1.18"), reason="Not implemented")
285 def test_config_set_few_user_attributes(topology_st, create_user, password_policy):
286 """Test that we can successfully set multiple values to passwordUserAttributes
287
288 :id: 188e0aee-6e29-4857-910c-27d5606f8c08
289 :setup: Standalone instance
290 :steps:
291 1. Set passwordUserAttributes to "description loginShell"
292 2. Verify passwordUserAttributes has the values
293 3. Verify passwordUserAttributes enforced the policy
294 :expectedresults:
295 1. Operation should be successful
296 2. Operation should be successful
297 3. Operation should be successful
298 """
299
300 standalone = topology_st.standalone
301 standalone.simple_bind_s(DN_DM, PASSWORD)
302 standalone.log.info('Set passwordUserAttributes to "description loginShell"')
303 standalone.config.set('passwordUserAttributes', 'description loginshell')
304 standalone.restart()
305
306 standalone.log.info("Verify passwordUserAttributes has the values")
307 user_attrs = standalone.config.get_attr_val_utf8('passwordUserAttributes')
308 assert "description" in user_attrs
309 assert "loginshell" in user_attrs
310 standalone.log.info("Reset passwordUserAttributes")
311 standalone.config.remove_all('passwordUserAttributes')
312
313 standalone.log.info("Verify passwordUserAttributes enforced the policy")
314 attributes = ['description, loginShell', 'description,loginShell', 'description loginShell']
315 values = ['Za1_d_e_s_c', f'Za1_{USER_RDN}', f'Za1_d_e_s_c{USER_RDN}']
316 for attr in attributes:
317 for value in values:
318 tryPassword(standalone, 'passwordUserAttributes', attr, 0, value,
319 '13_#Kad472h', 'Password found in user entry')
320
321
322 @pytest.mark.skipif(ds_is_older("1.4.1.18"), reason="Not implemented")
323 def test_config_set_few_bad_words(topology_st, create_user, password_policy):
324 """Test that we can successfully set multiple values to passwordBadWords
325
326 :id: 2977094c-921c-4b2f-af91-4c7a45ded48b
327 :setup: Standalone instance
328 :steps:
329 1. Set passwordBadWords to "fedora redhat"
330 2. Verify passwordBadWords has the values
331 3. Verify passwordBadWords enforced the policy
332 4. Set global passwordBadWords again (distinct from subtree list)
333 5. Add subtree password policy for ou=people with passwordBadWords "ubuntu debian"
334 6. Verify subtree passwordBadWords and enforcement (comma / space separated)
335 7. Remove subtree policy and restore nsslapd-pwpolicy-local
336 :expectedresults:
337 1. Operation should be successful
338 2. Operation should be successful
339 3. Operation should be successful
340 4. Operation should be successful
341 5. Operation should be successful
342 6. Operation should be successful
343 7. Cleanup succeeds
344 """
345
346 standalone = topology_st.standalone
347 standalone.simple_bind_s(DN_DM, PASSWORD)
348 standalone.log.info('Set passwordBadWords to "fedora redhat"')
349 standalone.config.set('passwordBadWords', 'fedora redhat')
350
351 standalone.log.info("Verify passwordBadWords has the values")
352 user_attrs = standalone.config.get_attr_val_utf8('passwordBadWords')
353 assert "fedora" in user_attrs
354 assert "redhat" in user_attrs
355 standalone.log.info("Reset passwordBadWords")
356 standalone.config.remove_all('passwordBadWords')
357
358 standalone.log.info("Verify passwordBadWords enforced the policy")
359 attributes = ['redhat, fedora', 'redhat,fedora', 'redhat fedora']
360 values = ['Za1_redhat_fedora', 'Za1_fedora', 'Za1_redhat']
361 for attr in attributes:
362 for value in values:
363 tryPassword(standalone, 'passwordBadWords', attr, 'none', value,
364 '13_#Kad472h', 'Password contains a bad word')
365
366 standalone.log.info(
367 '\n\nSubtree password policy at %s with passwordBadWords ubuntu debian '
368 '(distinct from global fedora/redhat)' % PEOPLE_DN)
369 standalone.simple_bind_s(DN_DM, PASSWORD)
370 standalone.config.set('passwordBadWords', 'fedora redhat')
371
372 # Test passwordBadWords using a local password policy
373 pwp = PwPolicyManager(standalone)
374 try:
375 pwp_entry = pwp.create_subtree_policy(
376 PEOPLE_DN,
377 {'passwordchange': 'on',
378 'passwordCheckSyntax': 'on',
379 'passwordBadWords': 'ubuntu debian'})
380
381 subtree_attrs = pwp_entry.get_attr_val_utf8('passwordBadWords')
382 assert 'ubuntu' in subtree_attrs.lower()
383 assert 'debian' in subtree_attrs.lower()
384 assert 'fedora' not in subtree_attrs.lower()
385 assert 'redhat' not in subtree_attrs.lower()
386
387 subtree_attr_variants = ['ubuntu, debian', 'ubuntu,debian', 'ubuntu debian']
388 subtree_values = ['Za1_ubuntu_debian', 'Za1_debian', 'Za1_ubuntu']
389 for attr in subtree_attr_variants:
390 for value in subtree_values:
391 tryPasswordSubtree(
392 standalone, pwp_entry, 'passwordBadWords', attr, 'none', value,
393 '13_#Kad472h',
394 'Password contains a bad word')
395 finally:
396 standalone.simple_bind_s(DN_DM, PASSWORD)
397 try:
398 pwp.delete_local_policy(PEOPLE_DN)
399 except ValueError:
400 pass
401 standalone.config.remove_all('passwordBadWords')
402 standalone.config.set('nsslapd-pwpolicy-local', 'off')
403
404
405 if __name__ == '__main__':
406 # Run isolated
407 # -s for DEBUG mode
408 CURRENT_FILE = os.path.realpath(__file__)
409 pytest.main("-s %s" % CURRENT_FILE)