Debian Codegraph @

dirsrvtests/tests/suites/logging/security_basic_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 ldap
10 import json
11 import logging
12 import pytest
13 import os
14 import re
15 import signal
16 import subprocess
17 import time
18 from lib389._constants import DEFAULT_SUFFIX, PASSWORD, DN_DM
19 from test389.topologies import topology_st as topo
20 from lib389.idm.user import UserAccount, UserAccounts
21 from lib389.dirsrv_log import DirsrvSecurityLog
22 from lib389.utils import ensure_str
23 from lib389.idm.domain import Domain
24 from lib389.idm.account import Anonymous
25 from lib389.config import CertmapLegacy
26 from lib389.nss_ssl import NssSsl
27
28
29 log = logging.getLogger(__name__)
30
31 DN = "uid=security,ou=people," + DEFAULT_SUFFIX
32 DN_NO_ENTRY = "uid=fredSomething,ou=people," + DEFAULT_SUFFIX
33 DN_NO_BACKEND = "uid=not_there,o=nope," + DEFAULT_SUFFIX
34 DN_QUOATED = "uid=\"cn=mark\",ou=people," + DEFAULT_SUFFIX
35 DN_QUOATED_ESCAPED = "uid=cn\\3dmark,ou=people," + DEFAULT_SUFFIX
36 DN_LONG = "uid=" + ("z" * 520) + ",ou=people," + DEFAULT_SUFFIX
37 DN_LONG_TRUNCATED = "uid=" + ("z" * 508) + "..."
38 RDN_TEST_USER = 'testuser'
39 RDN_TEST_USER_WRONG = 'testuser_wrong'
40
41
42 @pytest.fixture
43 def setup_test(topo, request):
44 """Disable log buffering"""
45 topo.standalone.config.set('nsslapd-securitylog-logbuffering', 'off')
46
47 """Add a test user"""
48 users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
49 try:
50 users.create(properties={
51 'uid': 'security',
52 'cn': 'security',
53 'sn': 'security',
54 'uidNumber': '3000',
55 'gidNumber': '4000',
56 'homeDirectory': '/home/security',
57 'description': 'test security logging with this user',
58 'userPassword': PASSWORD
59 })
60 except ldap.ALREADY_EXISTS:
61 pass
62
63
64 def check_log(inst, event_id, msg, dn=None, bind_method=None):
65 """Check the security log
66 """
67 time.sleep(1) # give a little time to flush to disk
68
69 security_log = DirsrvSecurityLog(inst)
70 log_lines = security_log.readlines()
71 for line in log_lines:
72 if re.match(r'[ \t]', line):
73 # Skip log title lines
74 continue
75
76 event = json.loads(line)
77 found = False
78 if event['event'] == event_id and event['msg'] == msg:
79 if dn is not None:
80 if event['dn'] == dn.lower():
81 found = True
82 if bind_method is not None:
83 if event['bind_method'] == bind_method:
84 found = True
85
86 if not found and (dn is not None or bind_method is not None):
87 continue
88 else:
89 # Found it
90 return
91
92 assert False
93
94
95 @pytest.fixture(scope="module")
96 def big_file():
97 TEMP_BIG_FILE = ''
98 for x in range(1048576):
99 TEMP_BIG_FILE += '+'
100
101 return TEMP_BIG_FILE
102
103
104 def test_invalid_binds(topo, setup_test):
105 """Test the various bind scenarios that should be logged in the security log
106
107 :id: b82e3fb9-f1af-4a75-8d96-5e5d284f31c5
108 :setup: Standalone Instance
109 :steps:
110 1. Test successful bind is logged
111 2. Test bad password is logged
112 3. Test no such entry is logged
113 4. Test no such entry is logged (quoated dn)
114 5. Test no such entry is logged (truncated dn)
115 6. Test no such backend is logged
116 7. Test account lockout is logged
117 :expectedresults:
118 1. Success
119 2. Success
120 3. Success
121 4. Success
122 5. Success
123 6. Success
124 7. Success
125 """
126
127 inst = topo.standalone
128 user_entry = UserAccount(inst, DN)
129
130 # Delete the previous securty logs
131 inst.deleteSecurityLogs()
132
133 # Good bind
134 user_entry.bind(PASSWORD)
135 check_log(inst, "BIND_SUCCESS", "", DN)
136
137 # Bad password
138 with pytest.raises(ldap.INVALID_CREDENTIALS):
139 user_entry.bind("wrongpassword")
140 check_log(inst, "BIND_FAILED", "INVALID_PASSWORD", DN)
141
142 # No_such_entry
143 with pytest.raises(ldap.INVALID_CREDENTIALS):
144 UserAccount(inst, DN_NO_ENTRY).bind(PASSWORD)
145 check_log(inst, "BIND_FAILED", "NO_SUCH_ENTRY", DN_NO_ENTRY)
146
147 # No_such_entry (quoted)
148 with pytest.raises(ldap.INVALID_CREDENTIALS):
149 UserAccount(inst, DN_QUOATED).bind(PASSWORD)
150 check_log(inst, "BIND_FAILED", "NO_SUCH_ENTRY", DN_QUOATED_ESCAPED)
151
152 # No such entry (truncated dn)
153 with pytest.raises(ldap.INVALID_CREDENTIALS):
154 UserAccount(inst, DN_LONG).bind(PASSWORD)
155 check_log(inst, "BIND_FAILED", "NO_SUCH_ENTRY", DN_LONG_TRUNCATED)
156
157 # No_such_backend
158 with pytest.raises(ldap.INVALID_CREDENTIALS):
159 UserAccount(inst, DN_NO_BACKEND).bind(PASSWORD)
160 check_log(inst, "BIND_FAILED", "NO_SUCH_ENTRY", DN_NO_BACKEND)
161
162
163 def test_authorization(topo, setup_test):
164 """Test the authorization event by performing a modification that the user
165 is not allowed to do.
166
167 :id: 17a62670-f86d-4b39-9ee7-e7d36b973ec8
168 :setup: Standalone Instance
169 :steps:
170 1. Bind as a unprivileged user
171 2. Attempt to modify restricted resource
172 3. Security authorization event is logged
173 :expectedresults:
174 1. Success
175 2. Should fail
176 3. Success
177 """
178 inst = topo.standalone
179
180 # Delete the previous security logs
181 inst.deleteSecurityLogs()
182
183 # Bind as a user
184 user_entry = UserAccount(inst, DN)
185 user_conn = user_entry.bind(PASSWORD)
186
187 # Try modifying a restricted resource
188 suffix = Domain(user_conn, DEFAULT_SUFFIX)
189 with pytest.raises(ldap.INSUFFICIENT_ACCESS):
190 suffix.replace('description', 'not allowed')
191
192 # Check that an authorization event was logged
193 check_log(inst, "AUTHZ_ERROR", f"target_dn=({DEFAULT_SUFFIX})")
194
195
196 def test_account_lockout(topo, setup_test):
197 """Test that account locked message is displayed correctly
198
199 :id: b70494f0-7d8e-4d90-8265-9d009bbb08b4
200 :setup: Standalone Instance
201 :steps:
202 1. Configure account lockout
203 2. Bind using the wrong password until the account is locked
204 3. Check for account lockout event
205 :expectedresults:
206 1. Success
207 2. Success
208 3. Success
209 """
210 inst = topo.standalone
211
212 # Delete the previous security logs
213 inst.deleteSecurityLogs()
214
215 # Configure account lockout
216 inst.config.set('passwordlockout', 'on')
217 inst.config.set('passwordMaxFailure', '2')
218
219 # Force entry to get locked out
220 user_entry = UserAccount(inst, DN)
221 with pytest.raises(ldap.INVALID_CREDENTIALS):
222 user_entry.bind("wrong")
223 with pytest.raises(ldap.INVALID_CREDENTIALS):
224 user_entry.bind("wrong")
225 with pytest.raises(ldap.CONSTRAINT_VIOLATION):
226 # Should fail with good or bad password
227 user_entry.bind(PASSWORD)
228
229 # Check that an account locked event was logged for this DN
230 check_log(inst, "BIND_FAILED", "ACCOUNT_LOCKED", DN)
231
232
233 def test_tcp_events(topo, setup_test):
234 """Trigger a TCP_ERROR event that should be logged in the security log
235
236 :id: 2f653508-89ae-4325-9fed-a2c4ab304149
237 :setup: Standalone Instance
238 :steps:
239 1. Start ldapmodify in its interactive mode
240 2. Get the pid of ldapmodify
241 3. Kill ldapmodify
242 4. Check that a TCP_ERROR is in the security log
243 :expectedresults:
244 1. Success
245 2. Success
246 3. Success
247 4. Success
248 """
249
250 inst = topo.standalone
251
252 # Delete the previous security logs
253 inst.deleteSecurityLogs()
254
255 # Start interactive ldapamodfy command
256 ldap_cmd = ['ldapmodify', '-x', '-D', DN_DM, '-w', PASSWORD,
257 '-H', f'ldap://{inst.host}:{inst.port}']
258 subprocess.Popen(ldap_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
259 time.sleep(3) # need some time for ldapmodify to actually launch
260
261 # Get ldapmodify pid
262 result = subprocess.check_output(['pidof','ldapmodify'])
263 ldapmodify_pid = ensure_str(result)
264
265 # Kill ldapmodify and check the log
266 os.kill(int(ldapmodify_pid), signal.SIGKILL)
267 check_log(inst, "TCP_ERROR", "Bad Ber Tag or uncleanly closed connection - B1")
268
269
270 def test_tcp_events_maxbersize(topo, setup_test, big_file):
271 """Trigger a TCP_ERROR event B2 that should be logged in the security log
272
273 :id: 85e5ac23-4288-4e55-b8c3-1f8f39e95c2b
274 :setup: Standalone Instance
275 :testype: Non-functional
276 :subtype1: Security
277 :subtype2: Penetration
278 :subsystemteam: sst_idm_ds
279 :steps:
280 1. Create test user
281 1. Set maxbersize attribute to a small value (20KiB)
282 3. Add the big value to instance
283 4. Check that a TCP_ERROR is in the security log
284 :expectedresults:
285 1. Success
286 2. Success
287 3. Success
288 4. Success
289 """
290
291 inst = topo.standalone
292 user_entry = UserAccount(inst, DN)
293
294 # Delete the previous security logs
295 inst.deleteSecurityLogs()
296
297 log.info("Set nsslapd-maxbersize to 20K")
298 inst.config.set('nsslapd-maxbersize', '20480')
299 inst.restart()
300
301 log.info('Try to add attribute with a big value to instance - expect to FAIL')
302 with pytest.raises(ldap.SERVER_DOWN):
303 user_entry.add('jpegphoto', big_file)
304
305 log.info('Check security log')
306 check_log(inst, "TCP_ERROR", "Ber Too Big (nsslapd-maxbersize) - B2")
307
308 # restart the instance so it won't break next tests
309 inst.restart()
310
311
312 def test_anonymous_bind(topo, setup_test):
313 """Test that anonymous bind message is displayed correctly
314
315 :id: 0df3c6c1-e93a-4baf-88c6-825c1d4d9b8e
316 :setup: Standalone Instance
317 :steps:
318 1. Bind anonymously
319 2. Check for account lockout event
320 :expectedresults:
321 1. Success
322 2. Success
323 """
324
325 inst = topo.standalone
326
327 # Delete the previous securty logs
328 inst.deleteSecurityLogs()
329
330 Anonymous(inst).bind()
331 check_log(inst, "BIND_SUCCESS", "ANONYMOUS_BIND")
332
333
334 def test_cert_map_failed_event(topo, setup_test):
335 """Trigger a CERT_MAP_FAILED event that should be logged in the security log.
336 Also test that BIND_SUCCESS works with TLSCLIENTAUTH
337
338 :id: eb0c638b-4a30-4108-b38b-e75e55ccb6c8
339 :setup: Standalone Instance
340 :steps:
341 1. Enable TLS
342 2. Create a user
343 3. Create User certificates - one is for the new user, another one is free
344 4. Turn on the certmap.
345 5. Check that EXTERNAL is listed in supported mechns.
346 6. Restart to allow certmaps to be re-read
347 7. Attempt a bind with TLS external with the correct credentials
348 8. Now attempt a bind with TLS external with a wrong cert
349 :expectedresults:
350 1. Success
351 2. Success
352 3. Success
353 4. Success
354 5. Success
355 6. Success
356 7. Securotylog should display BIND_SUCCESS works with TLSCLIENTAUTH
357 8. Securotylog should display BIND_FAILED works with CERT_MAP_FAILED
358 """
359
360 inst = topo.standalone
361
362 inst.enable_tls()
363
364 users = UserAccounts(inst, DEFAULT_SUFFIX)
365 user = users.create(properties={
366 'uid': RDN_TEST_USER,
367 'cn' : RDN_TEST_USER,
368 'sn' : RDN_TEST_USER,
369 'uidNumber' : '1000',
370 'gidNumber' : '2000',
371 'homeDirectory' : f'/home/{RDN_TEST_USER}'
372 })
373
374 ssca_dir = inst.get_ssca_dir()
375 ssca = NssSsl(dbpath=ssca_dir)
376 ssca.create_rsa_user(RDN_TEST_USER)
377 ssca.create_rsa_user(RDN_TEST_USER_WRONG)
378
379 # Get the details of where the key and crt are.
380 tls_locs = ssca.get_rsa_user(RDN_TEST_USER)
381 tls_locs_wrong = ssca.get_rsa_user(RDN_TEST_USER_WRONG)
382
383 user.enroll_certificate(tls_locs['crt_der_path'])
384
385 # Turn on the certmap.
386 cm = CertmapLegacy(inst)
387 certmaps = cm.list()
388 certmaps['default']['DNComps'] = ''
389 certmaps['default']['FilterComps'] = ['cn']
390 certmaps['default']['VerifyCert'] = 'off'
391 cm.set(certmaps)
392
393 # Check that EXTERNAL is listed in supported mechns.
394 assert(inst.rootdse.supports_sasl_external())
395
396 # Restart to allow certmaps to be re-read: Note, we CAN NOT use post_open
397 # here, it breaks on auth. see lib389/__init__.py
398 inst.restart(post_open=False)
399
400 # Delete the previous securty logs
401 inst.deleteSecurityLogs()
402
403 # Attempt a bind with TLS external
404 inst.open(saslmethod='EXTERNAL', connOnly=True, certdir=ssca_dir, userkey=tls_locs['key'], usercert=tls_locs['crt'])
405 inst.restart()
406 check_log(inst, "BIND_SUCCESS", "", bind_method="TLSCLIENTAUTH")
407
408 # Now attempt a bind with TLS external with a wrong cert
409 with pytest.raises(ldap.INVALID_CREDENTIALS):
410 inst.open(saslmethod='EXTERNAL', connOnly=True, certdir=ssca_dir, userkey=tls_locs_wrong['key'], usercert=tls_locs_wrong['crt'])
411 check_log(inst, "BIND_FAILED", "CERT_MAP_FAILED")
412
413
414 if __name__ == '__main__':
415 # Run isolated
416 # -s for DEBUG mode
417 CURRENT_FILE = os.path.realpath(__file__)
418 pytest.main(["-s", CURRENT_FILE])