Debian Codegraph @

dirsrvtests/tests/suites/acl/misc_test.py

raw
1 """
2 # --- BEGIN COPYRIGHT BLOCK ---
3 # Copyright (C) 2020 RED Hat, Inc.
4 # All rights reserved.
5 #
6 # License: GPL (version 3 or any later version).
7 # See LICENSE for details.
8 # --- END COPYRIGHT BLOCK ----
9 """
10
11 import ldap
12 import logging
13 import os
14 import pytest
15
16 from lib389._constants import DEFAULT_SUFFIX, PW_DM, DN_DM, ReplicaRole
17 from lib389.idm.user import UserAccount, UserAccounts
18 from lib389._mapped_object import DSLdapObject
19 from lib389.idm.account import Accounts, Anonymous
20 from lib389.idm.organizationalunit import OrganizationalUnit, OrganizationalUnits
21 from lib389.idm.group import Group, Groups
22 from test389.topologies import topology_st as topo, create_topology
23 from lib389.idm.domain import Domain
24 from lib389.plugins import ACLPlugin
25 from lib389.tasks import ImportTask
26
27 pytestmark = pytest.mark.tier1
28
29 logging.getLogger(__name__).setLevel(logging.DEBUG)
30 log = logging.getLogger(__name__)
31
32 PEOPLE = "ou=PEOPLE,{}".format(DEFAULT_SUFFIX)
33 DYNGROUP = "cn=DYNGROUP,{}".format(PEOPLE)
34 CONTAINER_1_DELADD = "ou=Product Development,{}".format(DEFAULT_SUFFIX)
35 CONTAINER_2_DELADD = "ou=Accounting,{}".format(DEFAULT_SUFFIX)
36
37
38 @pytest.fixture(scope="function")
39 def aci_of_user(request, topo):
40 """
41 :param request:
42 :param topo:
43 """
44
45 # Add anonymous access aci
46 ACI_TARGET = "(targetattr != \"userpassword\")(target = \"ldap:///%s\")" % (DEFAULT_SUFFIX)
47 ACI_ALLOW = "(version 3.0; acl \"Anonymous Read access\"; allow (read,search,compare)"
48 ACI_SUBJECT = "(userdn=\"ldap:///anyone\");)"
49 ANON_ACI = ACI_TARGET + ACI_ALLOW + ACI_SUBJECT
50 suffix = Domain(topo.standalone, DEFAULT_SUFFIX)
51 try:
52 suffix.add('aci', ANON_ACI)
53 except ldap.TYPE_OR_VALUE_EXISTS:
54 pass
55
56 aci_list = suffix.get_attr_vals('aci')
57
58 def finofaci():
59 """
60 Removes and Restores ACIs after the test.
61 """
62 domain = Domain(topo.standalone, DEFAULT_SUFFIX)
63 domain.remove_all('aci')
64 for i in aci_list:
65 domain.add("aci", i)
66
67 request.addfinalizer(finofaci)
68
69
70 @pytest.fixture(scope="function")
71 def clean(request, topo):
72 """
73 :param request:
74 :param topo:
75 """
76 ous = OrganizationalUnits(topo.standalone, DEFAULT_SUFFIX)
77 try:
78 for i in ['Product Development', 'Accounting']:
79 ous.create(properties={'ou': i})
80 except ldap.ALREADY_EXISTS as eoor_eoor:
81 topo.standalone.log.info("Exception (expected): %s" % type(eoor_eoor).__name__)
82
83 def fin():
84 """
85 Deletes entries after the test.
86 """
87 for scope_scope in [CONTAINER_1_DELADD, CONTAINER_2_DELADD, PEOPLE]:
88 try:
89 DSLdapObject(topo.standalone, scope_scope).delete()
90 except ldap.ALREADY_EXISTS as eoor_eoor:
91 topo.standalone.log.info("Exception (expected): %s" % type(eoor_eoor).__name__)
92
93 request.addfinalizer(fin)
94
95
96 def test_accept_aci_in_addition_to_acl(topo, clean, aci_of_user):
97 """Misc Test 2 accept aci in addition to acl
98
99 :id: 8e9408fa-7db8-11e8-adaa-8c16451d917b
100 :setup: Standalone Instance
101 :steps:
102 1. Add test entry
103 2. Add ACI
104 3. User should follow ACI role
105 :expectedresults:
106 1. Entry should be added
107 2. Operation should succeed
108 3. Operation should succeed
109 """
110 uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn='ou=product development')
111 user = uas.create_test_user()
112 for i in [('mail', '[email protected]'), ('givenname', 'Anuj'), ('userPassword', PW_DM)]:
113 user.set(i[0], i[1])
114
115 aci_target = '(targetattr="givenname")'
116 aci_allow = ('(version 3.0; acl "Name of the ACI"; deny (read, search, compare, write)')
117 aci_subject = 'userdn="ldap:///anyone";)'
118 Domain(topo.standalone, CONTAINER_1_DELADD).add("aci", aci_target + aci_allow + aci_subject)
119
120 conn = Anonymous(topo.standalone).bind()
121 # aci will block targetattr=givenname to anyone
122 user = UserAccount(conn, user.dn)
123 with pytest.raises(AssertionError):
124 assert user.get_attr_val_utf8('givenname') == 'Anuj'
125 # aci will allow targetattr=uid to anyone
126 assert user.get_attr_val_utf8('uid') == 'test_user_1000'
127
128 for i in uas.list():
129 i.delete()
130
131
132 def test_more_then_40_acl_will_crash_slapd(topo, clean, aci_of_user):
133 """bug 334451 : more then 40 acl will crash slapd
134 superseded by Bug 772778 - acl cache overflown problem with > 200 acis
135
136 :id: 93a44c60-7db8-11e8-9439-8c16451d917b
137 :setup: Standalone Instance
138 :steps:
139 1. Add test entry
140 2. Add ACI
141 3. User should follow ACI role
142 :expectedresults:
143 1. Entry should be added
144 2. Operation should succeed
145 3. Operation should succeed
146 """
147 uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn='ou=Accounting')
148 user = uas.create_test_user()
149
150 aci_target = '(target ="ldap:///{}")(targetattr!="userPassword")'.format(CONTAINER_1_DELADD)
151 # more_then_40_acl_will not crash_slapd
152 for i in range(40):
153 aci_allow = '(version 3.0;acl "ACI_{}";allow (read, search, compare)'.format(i)
154 aci_subject = 'userdn="ldap:///anyone";)'
155 aci_body = aci_target + aci_allow + aci_subject
156 Domain(topo.standalone, CONTAINER_1_DELADD).add("aci", aci_body)
157 conn = Anonymous(topo.standalone).bind()
158 assert UserAccount(conn, user.dn).get_attr_val_utf8('uid') == 'test_user_1000'
159
160 for i in uas.list():
161 i.delete()
162
163 def test_search_access_should_not_include_read_access(topo, clean, aci_of_user):
164 """bug 345643
165 Misc Test 4 search access should not include read access
166
167 :id: 98ab173e-7db8-11e8-a309-8c16451d917b
168 :setup: Standalone Instance
169 :steps:
170 1. Add test entry
171 2. Add ACI
172 3. User should follow ACI role
173 :expectedresults:
174 1. Entry should be added
175 2. Operation should succeed
176 3. Operation should succeed
177 """
178 assert Domain(topo.standalone, DEFAULT_SUFFIX).present('aci')
179 Domain(topo.standalone, DEFAULT_SUFFIX)\
180 .replace("aci", [f'(target ="ldap:///{DEFAULT_SUFFIX}")(targetattr != "userPassword")'
181 '(version 3.0;acl "anonymous access";allow (search)'
182 '(userdn = "ldap:///anyone");)',
183 f'(target="ldap:///{DEFAULT_SUFFIX}") (targetattr = "*")(version 3.0; '
184 'acl "allow self write";allow(write) '
185 'userdn = "ldap:///self";)',
186 f'(target="ldap:///{DEFAULT_SUFFIX}") (targetattr = "*")(version 3.0; '
187 'acl "Allow all admin group"; allow(all) groupdn = "ldap:///cn=Directory '
188 'Administrators, {}";)'])
189
190 conn = Anonymous(topo.standalone).bind()
191 # search_access_should_not_include_read_access
192 suffix = Domain(conn, DEFAULT_SUFFIX)
193 with pytest.raises(Exception):
194 assert suffix.present('aci')
195
196
197 def test_only_allow_some_targetattr(topo, clean, aci_of_user):
198 """Misc Test 5 only allow some targetattr (1/2)
199
200 :id: 9d27f048-7db8-11e8-a71c-8c16451d917b
201 :setup: Standalone Instance
202 :steps:
203 1. Add test entry
204 2. Add ACI
205 3. User should follow ACI role
206 :expectedresults:
207 1. Entry should be added
208 2. Operation should succeed
209 3. Operation should succeed
210 """
211
212 uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=None)
213 for i in range(1, 3):
214 user = uas.create_test_user(uid=i, gid=i)
215 user.replace_many(('cn', 'Anuj1'), ('mail', '[email protected]'))
216
217 Domain(topo.standalone, DEFAULT_SUFFIX).\
218 replace("aci", '(target="ldap:///{}")(targetattr="mail||objectClass")'
219 '(version 3.0; acl "Test";allow (read,search,compare) '
220 '(userdn = "ldap:///anyone"); )'.format(DEFAULT_SUFFIX))
221
222 conn = Anonymous(topo.standalone).bind()
223 accounts = Accounts(conn, DEFAULT_SUFFIX)
224
225 # aci will allow only mail targetattr
226 assert len(accounts.filter('(mail=*)')) == 2
227 # aci will allow only mail targetattr
228 assert not accounts.filter('(cn=*)', scope=1)
229 # with root no , blockage
230 assert len(Accounts(topo.standalone, DEFAULT_SUFFIX).filter('(uid=*)', scope=1)) == 2
231
232 for i in uas.list():
233 i.delete()
234
235
236 def test_only_allow_some_targetattr_two(topo, clean, aci_of_user, request):
237 """Misc Test 6 only allow some targetattr (2/2)"
238
239 :id: a188239c-7db8-11e8-903e-8c16451d917b
240 :setup: Standalone Instance
241 :steps:
242 1. Add test entry
243 2. Add ACI
244 3. User should follow ACI role
245 :expectedresults:
246 1. Entry should be added
247 2. Operation should succeed
248 3. Operation should succeed
249 """
250 uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=None)
251 for i in range(5):
252 user = uas.create_test_user(uid=i, gid=i)
253 user.replace_many(('mail', '[email protected]'),
254 ('cn', 'Anuj'), ('userPassword', PW_DM))
255
256 user1 = uas.create_test_user()
257 user1.replace_many(('mail', '[email protected]'), ('userPassword', PW_DM))
258
259 Domain(topo.standalone, DEFAULT_SUFFIX).\
260 replace("aci", '(target="ldap:///{}") (targetattr="mail||objectClass")'
261 '(targetfilter="cn=Anuj") (version 3.0; acl "{}"; '
262 'allow (compare,read,search) '
263 '(userdn = "ldap:///anyone"); )'.format(DEFAULT_SUFFIX, request.node.name))
264
265 conn = UserAccount(topo.standalone, user.dn).bind(PW_DM)
266 # aci will allow only mail targetattr but only for cn=Anuj
267 account = Accounts(conn, DEFAULT_SUFFIX)
268 assert len(account.filter('(mail=*)', scope=1)) == 5
269 assert not account.filter('(cn=*)', scope=1)
270
271 for i in account.filter('(mail=*)'):
272 assert i.get_attr_val_utf8('mail') == '[email protected]'
273
274
275 conn = Anonymous(topo.standalone).bind()
276 # aci will allow only mail targetattr but only for cn=Anuj
277 account = Accounts(conn, DEFAULT_SUFFIX)
278 assert len(account.filter('(mail=*)', scope=1)) == 5
279 assert not account.filter('(cn=*)', scope=1)
280
281 for i in account.filter('(mail=*)'):
282 assert i.get_attr_val_utf8('mail') == '[email protected]'
283
284 # with root no blockage
285 assert len(Accounts(topo.standalone, DEFAULT_SUFFIX).filter('(mail=*)')) == 6
286
287 for i in uas.list():
288 i.delete()
289
290
291 def test_memberurl_needs_to_be_normalized(topo, clean, aci_of_user):
292 """Non-regression test for BUG 326000: MemberURL needs to be normalized
293
294 :id: a5d172e6-7db8-11e8-aca7-8c16451d917b
295 :setup: Standalone Instance
296 :steps:
297 1. Add test entry
298 2. Add ACI
299 3. User should follow ACI role
300 :expectedresults:
301 1. Entry should be added
302 2. Operation should succeed
303 3. Operation should succeed
304 """
305 ou_ou = OrganizationalUnit(topo.standalone, "ou=PEOPLE,{}".format(DEFAULT_SUFFIX))
306 ou_ou.set('aci', '(targetattr="*")'
307 '(version 3.0; acl "tester"; allow(all) '
308 'groupdn = "ldap:///cn =DYNGROUP,ou=PEOPLE, {}";)'.format(DEFAULT_SUFFIX))
309
310 groups = Groups(topo.standalone, DEFAULT_SUFFIX, rdn='ou=PEOPLE')
311 groups.create(properties={"cn": "DYNGROUP",
312 "description": "DYNGROUP",
313 'objectClass': 'groupOfURLS',
314 'memberURL': "ldap:///ou=PEOPLE,{}??sub?"
315 "(uid=test_user_2)".format(DEFAULT_SUFFIX)})
316
317 uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
318 for demo1 in [(1, "Entry to test rights on."), (2, "Member of DYNGROUP")]:
319 user = uas.create_test_user(uid=demo1[0], gid=demo1[0])
320 user.replace_many(('description', demo1[1]), ('userPassword', PW_DM))
321
322 ##with normal aci
323 conn = UserAccount(topo.standalone, uas.list()[1].dn).bind(PW_DM)
324 harry = UserAccount(conn, uas.list()[1].dn)
325 harry.add('sn', 'FRED')
326
327 ##with abnomal aci
328 dygrp = Group(topo.standalone, DYNGROUP)
329 dygrp.remove('memberurl', "ldap:///ou=PEOPLE,{}??sub?(uid=test_user_2)".format(DEFAULT_SUFFIX))
330 dygrp.add('memberurl', "ldap:///ou=PEOPLE,{}??sub?(uid=tesT_UsEr_2)".format(DEFAULT_SUFFIX))
331 harry.add('sn', 'Not FRED')
332
333 for i in uas.list():
334 i.delete()
335
336 def test_greater_than_200_acls_can_be_created(topo, clean, aci_of_user):
337 """Misc 10, check that greater than 200 ACLs can be created. Bug 624370
338
339 :id: ac020252-7db8-11e8-8652-8c16451d917b
340 :setup: Standalone Instance
341 :steps:
342 1. Add test entry
343 2. Add ACI
344 3. User should follow ACI role
345 :expectedresults:
346 1. Entry should be added
347 2. Operation should succeed
348 3. Operation should succeed
349 """
350 # greater_than_200_acls_can_be_created
351 uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
352 for i in range(200):
353 user = uas.create_test_user(uid=i, gid=i)
354 user.set('aci', '(targetattr = "description")'
355 '(version 3.0;acl "foo{}"; allow (read, search, compare)'
356 '(userdn="ldap:///anyone");)'.format(i))
357
358 assert user.\
359 get_attr_val_utf8('aci') == '(targetattr = "description")' \
360 '(version 3.0;acl "foo{}"; allow ' \
361 '(read, search, compare)' \
362 '(userdn="ldap:///anyone");)'.format(i)
363 for i in uas.list():
364 i.delete()
365
366
367 def test_server_bahaves_properly_with_very_long_attribute_names(topo, clean, aci_of_user):
368 """Make sure the server bahaves properly with very long attribute names. Bug 624453.
369
370 :id: b0d31942-7db8-11e8-a833-8c16451d917b
371 :setup: Standalone Instance
372 :steps:
373 1. Add test entry
374 2. Add ACI
375 3. User should follow ACI role
376 :expectedresults:
377 1. Entry should be added
378 2. Operation should succeed
379 3. Operation should succeed
380 """
381 users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
382 users.create_test_user()
383 users.list()[0].set('userpassword', PW_DM)
384
385 user = UserAccount(topo.standalone, 'uid=test_user_1000,ou=People,{}'.format(DEFAULT_SUFFIX))
386 with pytest.raises(ldap.INVALID_SYNTAX):
387 user.add("aci", "a" * 9000)
388
389
390 def test_do_bind_as_201_distinct_users(topo, clean, aci_of_user):
391 """Test bind as 201 distinct users
392
393 :id: c0060532-7db8-11e8-a124-8c16451d917b
394 :setup: Standalone Instance
395 :steps:
396 1. Add test entries
397 2. Increase the nsslapd-aclpb-max-selected-acls in cn=ACL Plugin,cn=plugins,cn=config
398 3. Restart the server
399 4. Do bind as 201 distinct users
400 :expectedresults:
401 1. Entries should be added
402 2. Operation should succeed
403 3. Operation should succeed
404 4. Operation should succeed
405 """
406 uas = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
407 for i in range(201):
408 user = uas.create_test_user(uid=i, gid=i)
409 user.set('userPassword', PW_DM)
410
411 users = uas.list()
412 for user in users:
413 user.bind(PW_DM)
414
415 ACLPlugin(topo.standalone).replace("nsslapd-aclpb-max-selected-acls", '220')
416 topo.standalone.restart()
417
418 users = uas.list()
419 for user in users:
420 user.bind(PW_DM)
421
422
423 def test_info_disclosure(request, topo):
424 """Test that a search returns 32 when base entry does not exist
425
426 :id: f6dec4c2-65a3-41e4-a4c0-146196863333
427 :setup: Standalone Instance
428 :steps:
429 1. Add aci
430 2. Add test user
431 3. Bind as user and search for non-existent entry
432 :expectedresults:
433 1. Success
434 2. Success
435 3. Error 32 is returned
436 """
437
438 ACI_TARGET = "(targetattr = \"*\")(target = \"ldap:///%s\")" % (DEFAULT_SUFFIX)
439 ACI_ALLOW = "(version 3.0; acl \"Read/Search permission for all users\"; allow (read,search)"
440 ACI_SUBJECT = "(userdn=\"ldap:///all\");)"
441 ACI = ACI_TARGET + ACI_ALLOW + ACI_SUBJECT
442
443 # Get current ACi's so we can restore them when we are done
444 suffix = Domain(topo.standalone, DEFAULT_SUFFIX)
445 preserved_acis = suffix.get_attr_vals_utf8('aci')
446
447 def finofaci():
448 domain = Domain(topo.standalone, DEFAULT_SUFFIX)
449 try:
450 domain.remove_all('aci')
451 domain.replace_values('aci', preserved_acis)
452 except:
453 pass
454 request.addfinalizer(finofaci)
455
456 # Remove aci's
457 suffix.remove_all('aci')
458
459 # Add test user
460 USER_DN = "uid=test,ou=people," + DEFAULT_SUFFIX
461 users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
462 users.create(properties={
463 'uid': 'test',
464 'cn': 'test',
465 'sn': 'test',
466 'uidNumber': '1000',
467 'gidNumber': '2000',
468 'homeDirectory': '/home/test',
469 'userPassword': PW_DM
470 })
471
472 # bind as user
473 conn = UserAccount(topo.standalone, USER_DN).bind(PW_DM)
474
475 # Search fo existing base DN
476 test = Domain(conn, DEFAULT_SUFFIX)
477 assert len(test.get_attr_vals_utf8_l('dc')) == 0
478
479 # Search for a non existent bases
480 subtree = Domain(conn, "ou=does_not_exist," + DEFAULT_SUFFIX)
481 assert len(subtree.get_attr_vals_utf8_l('objectclass')) == 0
482
483 subtree = Domain(conn, "ou=also does not exist,ou=does_not_exist," + DEFAULT_SUFFIX)
484 assert len(subtree.get_attr_vals_utf8_l('objectclass')) == 0
485
486 # Try ONE level search instead of BASE
487 assert len(Accounts(conn, "ou=does_not_exist," + DEFAULT_SUFFIX).filter("(objectclass=top)", scope=ldap.SCOPE_ONELEVEL)) == 0
488
489 # add aci
490 suffix.add('aci', ACI)
491
492 # Search for a non existent entry which should raise an exception
493 with pytest.raises(ldap.NO_SUCH_OBJECT):
494 conn = UserAccount(topo.standalone, USER_DN).bind(PW_DM)
495 subtree = Domain(conn, "ou=does_not_exist," + DEFAULT_SUFFIX)
496 subtree.get_attr_vals_utf8_l('objectclass')
497 with pytest.raises(ldap.NO_SUCH_OBJECT):
498 conn = UserAccount(topo.standalone, USER_DN).bind(PW_DM)
499 subtree = Domain(conn, "ou=also does not exist,ou=does_not_exist," + DEFAULT_SUFFIX)
500 subtree.get_attr_vals_utf8_l('objectclass')
501 with pytest.raises(ldap.NO_SUCH_OBJECT):
502 conn = UserAccount(topo.standalone, USER_DN).bind(PW_DM)
503 DN = "ou=also does not exist,ou=does_not_exist," + DEFAULT_SUFFIX
504 Accounts(conn, DN).filter("(objectclass=top)", scope=ldap.SCOPE_ONELEVEL, strict=True)
505
506
507 @pytest.fixture(scope="function")
508 def topo_fn(request):
509 """Function-scoped standalone instance that is removed after each test"""
510 topology = create_topology({ReplicaRole.STANDALONE: 1})
511
512 def fin():
513 if topology.standalone.exists():
514 topology.standalone.delete()
515 request.addfinalizer(fin)
516
517 return topology
518
519
520 def test_delete_aci_with_invalid_syntax(topo_fn, request):
521 """Verify that an ACI with invalid syntax can be deleted after being imported
522
523 :id: 7f3e8a9b-4c2d-4e5f-9a1b-2c3d4e5f6a7b
524 :setup: Standalone Instance
525 :steps:
526 1. Import an LDIF containing an ACI with invalid syntax
527 2. Attempt to delete the invalid ACI
528 :expectedresults:
529 1. Import should succeed
530 2. Delete operation should succeed without error
531 """
532 inst = topo_fn.standalone
533
534 invalid_aci = ('(targetattr ="fffff")(version 3.0;acl "Directory Administrators Group";'
535 'allow (all) (groupdn = "ldap:///cn=Directory Administrators, dc=example,dc=com");)')
536 valid_aci = ('(targetattr!="userPassword")(version 3.0; acl "Enable anonymous access"; '
537 'allow (read, search, compare) userdn="ldap:///anyone";)')
538
539 log.info("Create LDIF file with invalid ACI")
540 ldif_file = f'{inst.get_ldif_dir()}/invalid_aci_test.ldif'
541 with open(ldif_file, 'w') as f:
542 f.write(f"dn: {DEFAULT_SUFFIX}\n")
543 f.write("objectClass: top\n")
544 f.write("objectClass: domain\n")
545 f.write("dc: example\n")
546 f.write(f"aci: {valid_aci}\n")
547 f.write(f"aci: {invalid_aci}\n")
548 os.chmod(ldif_file, 0o777)
549
550 def fin():
551 if os.path.exists(ldif_file):
552 os.remove(ldif_file)
553 request.addfinalizer(fin)
554
555 log.info("Import LDIF with invalid ACI")
556 import_task = ImportTask(inst)
557 import_task.import_suffix_from_ldif(ldiffile=ldif_file, suffix=DEFAULT_SUFFIX)
558 import_task.wait()
559 assert import_task.get_exit_code() == 0, f"Import failed with exit code: {import_task.get_exit_code()}"
560
561 log.info("Delete the invalid ACI")
562 suffix = Domain(inst, DEFAULT_SUFFIX)
563 suffix.remove('aci', invalid_aci)
564
565 log.info("Verify the invalid ACI was removed")
566 assert invalid_aci not in suffix.get_attr_vals_utf8('aci')
567
568
569 if __name__ == "__main__":
570 CURRENT_FILE = os.path.realpath(__file__)
571 pytest.main("-s -v %s" % CURRENT_FILE)