Debian Codegraph @

dirsrvtests/tests/suites/password/pwp_history_test.py

raw
1 # --- BEGIN COPYRIGHT BLOCK ---
2 # Copyright (C) 2016 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 pytest
10 import time
11 import logging
12 import ldap
13 from lib389.tasks import *
14 from lib389.utils import ds_is_newer
15 from test389.topologies import topology_st
16 from lib389.idm.user import UserAccounts, TEST_USER_PROPERTIES
17 from lib389.idm.directorymanager import DirectoryManager
18 from lib389.idm.organizationalunit import OrganizationalUnits
19 from lib389.passwd import password_hash
20 from lib389.pwpolicy import PwPolicyManager
21 from lib389._constants import DEFAULT_SUFFIX
22
23 pytestmark = pytest.mark.tier1
24
25 logging.getLogger(__name__).setLevel(logging.DEBUG)
26 log = logging.getLogger(__name__)
27
28 USER_PWD = 'password'
29 USER_DN = f'uid=test_user_1000,ou=People,{DEFAULT_SUFFIX}'
30 SUBTREE_DN = f'ou=people,{DEFAULT_SUFFIX}'
31
32
33 def setup_pwp(inst, policy, pwp_mgr, history_count=3):
34 """ Setup global password policy """
35 dm = DirectoryManager(inst)
36 dm.rebind()
37
38 log.info(f'Configuring {policy} password policy with passwordInHistory={history_count}')
39
40 policy_props = {
41 'passwordHistory': 'on',
42 'passwordInHistory': str(history_count),
43 'passwordChange': 'on',
44 'passwordStorageScheme': 'CLEAR',
45 }
46
47 try:
48 if policy == 'global':
49 pwp_mgr.set_global_policy(policy_props)
50 elif policy == 'subtree':
51 pwp_mgr.create_subtree_policy(SUBTREE_DN, policy_props)
52 elif policy == 'user':
53 pwp_mgr.create_user_policy(USER_DN, policy_props)
54 else:
55 raise ValueError(f'Invalid type of password policy: {policy}')
56 except Exception as e:
57 log.fatal(f'Failed to configure {policy} password policy: {e}')
58 assert False
59
60
61 def modify_pwp(inst, policy, pwp_mgr, history_count):
62 """Modify password policy history count"""
63 dm = DirectoryManager(inst)
64 dm.rebind()
65
66 try:
67 if policy == 'global':
68 pwp_mgr.set_global_policy(properties={'passwordInHistory': str(history_count)})
69 elif policy == 'subtree':
70 policy_entry = pwp_mgr.get_pwpolicy_entry(SUBTREE_DN)
71 policy_entry.replace('passwordInHistory', str(history_count))
72 elif policy == 'user':
73 policy_entry = pwp_mgr.get_pwpolicy_entry(USER_DN)
74 policy_entry.replace('passwordInHistory', str(history_count))
75 else:
76 raise ValueError(f'Invalid type of password policy: {policy}')
77 log.info(f'Modified {policy} passwordInHistory to {history_count}.')
78 except ldap.LDAPError as e:
79 log.fatal(f'Failed to modify {policy} password policy (passwordInHistory to {history_count}): {str(e)}')
80 assert False
81 except Exception as e:
82 log.fatal(f'Failed to modify {policy} password policy: {str(e)}')
83 assert False
84
85
86 def change_password(user, password, success=True):
87 """Change password"""
88 if success:
89 try:
90 user.set('userpassword', password)
91 except ldap.LDAPError as e:
92 log.fatal(f'Failed to attempt to change password: {str(e)}')
93 log.fatal(f'password history: {str(user.get_attr_vals("passwordhistory"))}')
94 assert False
95 else:
96 try:
97 user.set('userpassword', password)
98 log.info(f'Incorrectly able to to set password to existing or recent password: {password}.')
99 log.fatal(f'password history: {str(user.get_attr_vals("passwordhistory"))}')
100 assert False
101 except ldap.CONSTRAINT_VIOLATION:
102 log.info('Password change correctly rejected')
103 except ldap.LDAPError as e:
104 log.fatal('Failed to attempt to change password: ' + str(e))
105 log.fatal(f'password history: {str(user.get_attr_vals("passwordhistory"))}')
106 assert False
107 time.sleep(0.5)
108
109
110 @pytest.fixture(scope="function")
111 def user(topology_st, request):
112 """Add and remove a test user"""
113
114 dm = DirectoryManager(topology_st.standalone)
115
116 # Add aci so users can change their own password
117 USER_ACI = '(targetattr="userpassword || passwordHistory")(version 3.0; acl "pwp test"; allow (all) userdn="ldap:///self";)'
118 ous = OrganizationalUnits(topology_st.standalone, DEFAULT_SUFFIX)
119 ou = ous.get('people')
120 ou.add('aci', USER_ACI)
121
122 # Create a user
123 users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
124 user = users.create_test_user()
125 user.set('userpassword', USER_PWD)
126 def fin():
127 dm.rebind()
128 user.delete()
129 ou.remove('aci', USER_ACI)
130 request.addfinalizer(fin)
131 return user
132
133
134 def test_history_is_not_overwritten(topology_st, user):
135 """Test that passwordHistory user attribute is not overwritten
136
137 :id: 1b311532-dd55-4072-88a9-1f960cb371bd
138 :setup: Standalone instance, a test user
139 :steps:
140 1. Configure password history policy as bellow:
141 passwordHistory: on
142 passwordInHistory: 3
143 2. Change the password 3 times
144 3. Try to change the password 2 more times to see
145 if it rewrites passwordHistory even on a failure attempt
146 4. Try to change the password to the initial value (it should be
147 still in history)
148 :expectedresults:
149 1. Password history policy should be configured successfully
150 2. Success
151 3. Password changes should be correctly rejected
152 with Constrant Violation error
153 4. Password change should be correctly rejected
154 with Constrant Violation error
155 """
156
157 topology_st.standalone.config.replace_many(('passwordHistory', 'on'),
158 ('passwordInHistory', '3'))
159 log.info('Configured password policy.')
160 time.sleep(1)
161
162 # Bind as the test user
163 user.rebind(USER_PWD)
164 time.sleep(.5)
165
166 # Change the password 3 times
167 user.set('userpassword', 'password1')
168 user.rebind('password1')
169 time.sleep(.5)
170 user.set('userpassword', 'password2')
171 user.rebind('password2')
172 time.sleep(.5)
173 user.set('userpassword', 'password3')
174 user.rebind('password3')
175 time.sleep(.5)
176
177 # Try to change the password 2 more times to see
178 # if it rewrites passwordHistory even on a failure attempt
179 with pytest.raises(ldap.CONSTRAINT_VIOLATION):
180 user.set('userpassword', 'password2')
181 time.sleep(.5)
182 with pytest.raises(ldap.CONSTRAINT_VIOLATION):
183 user.set('userpassword', 'password1')
184 time.sleep(.5)
185
186 # Try to change the password to the initial value (it should be still in history)
187 with pytest.raises(ldap.CONSTRAINT_VIOLATION):
188 user.set('userpassword', USER_PWD)
189
190
191 @pytest.mark.parametrize('policy',
192 [(pytest.param('global')),
193 (pytest.param('subtree')),
194 (pytest.param('user'))])
195 def test_basic(topology_st, user, policy):
196 """Test basic password policy history feature functionality with dynamic count reduction
197
198 :id: 83d74f7d-3036-4944-8839-1b40bbf265ff
199 :setup: Standalone instance, a test user
200 :steps:
201 1. Configure password history policy (global, subtree, or user-level) as below:
202 passwordHistory: on
203 passwordInHistory: 3
204 passwordChange: on
205 passwordStorageScheme: CLEAR
206 2. Attempt to change password to the same password (should fail)
207 3. Change password four times (password1, password2, password3, password4)
208 4. Check that we only have 3 passwords stored in history
209 5. Attempt to change the password to previous passwords in history (should all fail)
210 6. Reduce passwordInHistory from 3 to 2 (dynamic reduction)
211 7. Verify that last 2 passwords cannot be used and only 2 passwords stored in history
212 8. Verify that password1 can be used again (oldest password becomes available)
213 9. Reset password by Directory Manager (admin reset) to 'password-reset'
214 10. Try and change the password to the previous password before the reset (should fail)
215 11. Test passwordInHistory set to 0: current password still blocked, older passwords available
216 12. Set passwordInHistory back to 2: current password blocked, previously stored passwords available
217 :expectedresults:
218 1. Password history policy should be configured successfully for the specified policy type
219 2. Password change should be correctly rejected with Constraint Violation error
220 3. Password should be successfully changed four times
221 4. Exactly 3 passwords should be stored in history
222 5. Password changes should be correctly rejected with Constraint Violation error
223 6. Policy change should be successful, history count reduced
224 7. Only 2 passwords should remain in history, recent passwords still blocked
225 8. Oldest password (password1) should become available for reuse
226 9. Password should be successfully reset by admin
227 10. Password change should be correctly rejected with Constraint Violation error
228 11. When history count is 0: current password blocked, historical passwords allowed
229 12. When history count is restored: current password blocked, old passwords allowed
230 """
231 pwp_mgr = PwPolicyManager(topology_st.standalone)
232
233 # Configure password history policy and add a test user
234 setup_pwp(topology_st.standalone, policy, pwp_mgr)
235
236 # Bind as the test user
237 user.rebind(USER_PWD)
238
239 # Test that password history is enforced - Attempt to change password to the same password
240 change_password(user, USER_PWD, success=False)
241
242 # Keep changing password until we fill the password history (3)
243 for pwd in ['password1', 'password2', 'password3', 'password4']:
244 change_password(user, pwd, success=True)
245 user.rebind(pwd)
246 time.sleep(.5)
247 # Password history [password1, password2, password3], current password is "password4"
248
249 # Check that we only have 3 passwords stored in history
250 pwds = user.get_attr_vals('passwordHistory')
251 if len(pwds) != 3:
252 log.fatal(f'Incorrect number of passwords stored in history: {len(pwds)}')
253 log.error(f'password history: {pwds}')
254 assert False
255 else:
256 log.info('Correct number of passwords found in history.')
257
258 # Attempt to change the password to previous passwords
259 for pwd in ['password1', 'password2', 'password3']:
260 change_password(user, pwd, success=False)
261
262 # Change the history count to 2
263 modify_pwp(topology_st.standalone, policy, pwp_mgr, 2)
264 # Password history [password2, password3], current password is "password4"
265
266 # Verify that last 2 password cannot be used
267 user.rebind('password4')
268 for pwd in ['password2', 'password3']:
269 change_password(user, pwd, success=False)
270
271 # Verify that only 2 passwords are stored in history
272 pwds = user.get_attr_vals('passwordHistory')
273 if len(pwds) != 2:
274 log.fatal(f'Incorrect number of passwords stored in history: {len(pwds)}')
275 log.error(f'password history: {pwds}')
276 assert False
277 else:
278 log.info('Correct number of passwords found in history.')
279
280 # Verify password1 can be used again
281 change_password(user, 'password1', success=True)
282 # Password history [password3, password4], current password is "password1"
283
284 # Reset password by Directory Manager(admin reset)
285 dm = DirectoryManager(topology_st.standalone)
286 dm.rebind()
287 time.sleep(.5)
288 change_password(user, 'password-reset', success=True)
289 # Password history [password4, password1], current password is "password-reset"
290
291 # Try and change the password to the previous password before the reset
292 user.rebind('password-reset')
293 change_password(user, 'password1', success=False)
294
295 if ds_is_newer("1.4.1.2"):
296 # Test passwordInHistory to 0
297 modify_pwp(topology_st.standalone, policy, pwp_mgr, 0)
298 # Password history empty, current password is "password-reset"
299
300 # Verify current password still cannot be used
301 user.rebind('password-reset')
302 change_password(user, 'password-reset', success=False)
303
304 # Verify the older passwords in the entry (passwordhistory) can be used
305 change_password(user, 'password4', success=True)
306 change_password(user, 'password1', success=True)
307
308 # Need to make one successful update so history list is reset
309 user.set('userpassword', 'password5')
310
311 # Set the history count back to a positive value and make sure things still work
312 # as expected
313 modify_pwp(topology_st.standalone, policy, pwp_mgr, 2)
314 # Password history empty, current password is "password5"
315
316 # Verify current password still cannot be used
317 user.rebind('password5')
318 change_password(user, 'password5', success=False)
319
320 # Test that old password that was in history before changing the history count to 0 is not being checked
321 change_password(user, 'password4', success=True)
322 change_password(user, 'password1', success=True)
323
324 # Done
325 log.info('Test suite PASSED.')
326
327
328 def test_prehashed_pwd(topology_st):
329 """Test password history is updated with a pre-hashed password change
330
331 :id: 24d08663-f36a-44ab-8f02-b8a3f502925b
332 :setup: Standalone instance
333 :steps:
334 1. Configure password history policy as bellow:
335 passwordHistory: on
336 passwordChange: on
337 nsslapd-allow-hashed-passwords: on
338 2. Create ACI to allow users change their password
339 3. Add a test user
340 4. Attempt to change password using non hased value
341 5. Bind with non hashed value
342 6. Create a hash value for update
343 7. Update user password with hash value
344 8. Bind with hashed password cleartext
345 9. Check users passwordHistory
346
347 :expectedresults:
348 1. Password history policy should be configured successfully
349 2. ACI applied correctly
350 3. User successfully added
351 4. Password change accepted
352 5. Successful bind
353 6. Hash value created
354 7. Password change accepted
355 8. Successful bind
356 9. Users passwordHistory should contain 2 enteries
357 """
358
359 # Configure password history policy and add a test user
360 try:
361 topology_st.standalone.config.replace_many(('passwordHistory', 'on'),
362 ('passwordChange', 'on'),
363 ('nsslapd-allow-hashed-passwords', 'on'))
364 log.info('Configured password policy.')
365 except ldap.LDAPError as e:
366 log.fatal('Failed to configure password policy: ' + str(e))
367 assert False
368 time.sleep(1)
369
370 # Add aci so users can change their own password
371 USER_ACI = '(targetattr="userpassword || passwordHistory")(version 3.0; acl "pwp test"; allow (all) userdn="ldap:///self";)'
372 ous = OrganizationalUnits(topology_st.standalone, DEFAULT_SUFFIX)
373 ou = ous.get('people')
374 ou.add('aci', USER_ACI)
375
376 # Create user
377 users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
378 user = users.create(properties=TEST_USER_PROPERTIES)
379 user.set('userpassword', 'password')
380 user.rebind('password')
381
382 # Change user pwd to generate a history of 1 entry
383 user.replace('userpassword', 'password1')
384 user.rebind('password1')
385
386 #Create pwd hash
387 pwd_hash = password_hash('password2', scheme='PBKDF2_SHA256', bin_dir=topology_st.standalone.ds_paths.bin_dir)
388 #log.info(pwd_hash)
389
390 # Update user pwd hash
391 user.replace('userpassword', pwd_hash)
392 time.sleep(2)
393
394 # Bind with hashed password
395 user.rebind('password2')
396
397 # Check password history
398 pwds = user.get_attr_vals('passwordHistory')
399 if len(pwds) != 2:
400 log.fatal('Incorrect number of passwords stored in history: %d' %
401 len(pwds))
402 log.error('password history: ' + str(pwds))
403 assert False
404 else:
405 log.info('Correct number of passwords found in history.')
406
407 # Done
408 log.info('Test suite PASSED.')
409
410 if __name__ == '__main__':
411 # Run isolated
412 # -s for DEBUG mode
413 CURRENT_FILE = os.path.realpath(__file__)
414 pytest.main("-s %s" % CURRENT_FILE)