1
0
mirror of https://github.com/samba-team/samba.git synced 2025-01-03 01:18:10 +03:00

PEP8: fix E128: continuation line under-indented for visual indent

Signed-off-by: Joe Guo <joeg@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>
Reviewed-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
This commit is contained in:
Joe Guo 2018-07-30 18:16:12 +12:00 committed by Douglas Bagnall
parent bbb9f57603
commit 5d532543ab
117 changed files with 2223 additions and 2135 deletions

View File

@ -158,7 +158,7 @@ unicodePwd:: """ + base64.b64encode(u"\"P@ssw0rd\"".encode('utf-16-le')).decode(
print("BindTest (no domain) with: " + self.username) print("BindTest (no domain) with: " + self.username)
try: try:
ldb_user4 = samba.tests.connect_samdb(host, credentials=creds_user4, ldb_user4 = samba.tests.connect_samdb(host, credentials=creds_user4,
lp=lp, ldap_only=True) lp=lp, ldap_only=True)
except: except:
self.fail("Failed to connect without the domain set") self.fail("Failed to connect without the domain set")

View File

@ -62,25 +62,25 @@ class MatchRulesTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(self.ldb, self.ou) m.dn = Dn(self.ldb, self.ou)
m["otherWellKnownObjects"] = MessageElement("B:32:00000000000000000000000000000001:OU=o1,%s" % self.ou, m["otherWellKnownObjects"] = MessageElement("B:32:00000000000000000000000000000001:OU=o1,%s" % self.ou,
FLAG_MOD_ADD, "otherWellKnownObjects") FLAG_MOD_ADD, "otherWellKnownObjects")
self.ldb.modify(m) self.ldb.modify(m)
m = Message() m = Message()
m.dn = Dn(self.ldb, "OU=o1,%s" % self.ou) m.dn = Dn(self.ldb, "OU=o1,%s" % self.ou)
m["otherWellKnownObjects"] = MessageElement("B:32:00000000000000000000000000000002:OU=o2,OU=o1,%s" % self.ou, m["otherWellKnownObjects"] = MessageElement("B:32:00000000000000000000000000000002:OU=o2,OU=o1,%s" % self.ou,
FLAG_MOD_ADD, "otherWellKnownObjects") FLAG_MOD_ADD, "otherWellKnownObjects")
self.ldb.modify(m) self.ldb.modify(m)
m = Message() m = Message()
m.dn = Dn(self.ldb, "OU=o2,OU=o1,%s" % self.ou) m.dn = Dn(self.ldb, "OU=o2,OU=o1,%s" % self.ou)
m["otherWellKnownObjects"] = MessageElement("B:32:00000000000000000000000000000003:OU=o3,OU=o2,OU=o1,%s" % self.ou, m["otherWellKnownObjects"] = MessageElement("B:32:00000000000000000000000000000003:OU=o3,OU=o2,OU=o1,%s" % self.ou,
FLAG_MOD_ADD, "otherWellKnownObjects") FLAG_MOD_ADD, "otherWellKnownObjects")
self.ldb.modify(m) self.ldb.modify(m)
m = Message() m = Message()
m.dn = Dn(self.ldb, "OU=o3,OU=o2,OU=o1,%s" % self.ou) m.dn = Dn(self.ldb, "OU=o3,OU=o2,OU=o1,%s" % self.ou)
m["otherWellKnownObjects"] = MessageElement("B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou, m["otherWellKnownObjects"] = MessageElement("B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou,
FLAG_MOD_ADD, "otherWellKnownObjects") FLAG_MOD_ADD, "otherWellKnownObjects")
self.ldb.modify(m) self.ldb.modify(m)
# Create OU for users and groups # Create OU for users and groups
@ -276,68 +276,68 @@ class MatchRulesTests(samba.tests.TestCase):
def test_u1_member_of_g4(self): def test_u1_member_of_g4(self):
# Search without transitive match must return 0 results # Search without transitive match must return 0 results
res1 = self.ldb.search("cn=g4,%s" % self.ou_groups, res1 = self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member=cn=u1,%s" % self.ou_users) expression="member=cn=u1,%s" % self.ou_users)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search("cn=u1,%s" % self.ou_users, res1 = self.ldb.search("cn=u1,%s" % self.ou_users,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="memberOf=cn=g4,%s" % self.ou_groups) expression="memberOf=cn=g4,%s" % self.ou_groups)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
# Search with transitive match must return 1 results # Search with transitive match must return 1 results
res1 = self.ldb.search("cn=g4,%s" % self.ou_groups, res1 = self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users) expression="member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g4,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g4,%s" % self.ou_groups).lower())
res1 = self.ldb.search("cn=u1,%s" % self.ou_users, res1 = self.ldb.search("cn=u1,%s" % self.ou_users,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="memberOf:1.2.840.113556.1.4.1941:=cn=g4,%s" % self.ou_groups) expression="memberOf:1.2.840.113556.1.4.1941:=cn=g4,%s" % self.ou_groups)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=u1,%s" % self.ou_users).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=u1,%s" % self.ou_users).lower())
def test_g1_member_of_g4(self): def test_g1_member_of_g4(self):
# Search without transitive match must return 0 results # Search without transitive match must return 0 results
res1 = self.ldb.search("cn=g4,%s" % self.ou_groups, res1 = self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member=cn=g1,%s" % self.ou_groups) expression="member=cn=g1,%s" % self.ou_groups)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search("cn=g1,%s" % self.ou_groups, res1 = self.ldb.search("cn=g1,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="memberOf=cn=g4,%s" % self.ou_groups) expression="memberOf=cn=g4,%s" % self.ou_groups)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
# Search with transitive match must return 1 results # Search with transitive match must return 1 results
res1 = self.ldb.search("cn=g4,%s" % self.ou_groups, res1 = self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member:1.2.840.113556.1.4.1941:=cn=g1,%s" % self.ou_groups) expression="member:1.2.840.113556.1.4.1941:=cn=g1,%s" % self.ou_groups)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g4,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g4,%s" % self.ou_groups).lower())
res1 = self.ldb.search("cn=g1,%s" % self.ou_groups, res1 = self.ldb.search("cn=g1,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="memberOf:1.2.840.113556.1.4.1941:=cn=g4,%s" % self.ou_groups) expression="memberOf:1.2.840.113556.1.4.1941:=cn=g4,%s" % self.ou_groups)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g1,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g1,%s" % self.ou_groups).lower())
def test_u1_groups(self): def test_u1_groups(self):
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=cn=u1,%s" % self.ou_users) expression="member=cn=u1,%s" % self.ou_users)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g1,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g1,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_users, res1 = self.ldb.search(self.ou_users,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=cn=u1,%s" % self.ou_users) expression="member=cn=u1,%s" % self.ou_users)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users) expression="member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users)
self.assertEqual(len(res1), 4) self.assertEqual(len(res1), 4)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list)
@ -346,25 +346,25 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_users, res1 = self.ldb.search(self.ou_users,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users) expression="member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
def test_u2_groups(self): def test_u2_groups(self):
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=cn=u2,%s" % self.ou_users) expression="member=cn=u2,%s" % self.ou_users)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g2,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g2,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_users, res1 = self.ldb.search(self.ou_users,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=cn=u2,%s" % self.ou_users) expression="member=cn=u2,%s" % self.ou_users)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=cn=u2,%s" % self.ou_users) expression="member:1.2.840.113556.1.4.1941:=cn=u2,%s" % self.ou_users)
self.assertEqual(len(res1), 3) self.assertEqual(len(res1), 3)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list)
@ -372,63 +372,63 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_users, res1 = self.ldb.search(self.ou_users,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=cn=u2,%s" % self.ou_users) expression="member:1.2.840.113556.1.4.1941:=cn=u2,%s" % self.ou_users)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
def test_u3_groups(self): def test_u3_groups(self):
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=cn=u3,%s" % self.ou_users) expression="member=cn=u3,%s" % self.ou_users)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g3,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g3,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_users, res1 = self.ldb.search(self.ou_users,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=cn=u3,%s" % self.ou_users) expression="member=cn=u3,%s" % self.ou_users)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=cn=u3,%s" % self.ou_users) expression="member:1.2.840.113556.1.4.1941:=cn=u3,%s" % self.ou_users)
self.assertEqual(len(res1), 2) self.assertEqual(len(res1), 2)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g3,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g3,%s" % self.ou_groups).lower() in dn_list)
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_users, res1 = self.ldb.search(self.ou_users,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=cn=u3,%s" % self.ou_users) expression="member:1.2.840.113556.1.4.1941:=cn=u3,%s" % self.ou_users)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
def test_u4_groups(self): def test_u4_groups(self):
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=cn=u4,%s" % self.ou_users) expression="member=cn=u4,%s" % self.ou_users)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g4,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g4,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_users, res1 = self.ldb.search(self.ou_users,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=cn=u4,%s" % self.ou_users) expression="member=cn=u4,%s" % self.ou_users)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=cn=u4,%s" % self.ou_users) expression="member:1.2.840.113556.1.4.1941:=cn=u4,%s" % self.ou_users)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g4,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g4,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_users, res1 = self.ldb.search(self.ou_users,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=cn=u4,%s" % self.ou_users) expression="member:1.2.840.113556.1.4.1941:=cn=u4,%s" % self.ou_users)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
def test_extended_dn_u1(self): def test_extended_dn_u1(self):
res1 = self.ldb.search("cn=u1,%s" % self.ou_users, res1 = self.ldb.search("cn=u1,%s" % self.ou_users,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="objectClass=*", expression="objectClass=*",
attrs=['objectSid', 'objectGUID']) attrs=['objectSid', 'objectGUID'])
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("cn=u1,%s" % self.ou_users).lower()) self.assertEqual(str(res1[0].dn).lower(), ("cn=u1,%s" % self.ou_users).lower())
@ -436,20 +436,20 @@ class MatchRulesTests(samba.tests.TestCase):
guid = self.ldb.schema_format_value("objectGUID", res1[0]['objectGUID'][0]) guid = self.ldb.schema_format_value("objectGUID", res1[0]['objectGUID'][0])
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=<SID=%s>" % sid) expression="member=<SID=%s>" % sid)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g1,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g1,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=<GUID=%s>" % guid) expression="member=<GUID=%s>" % guid)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g1,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g1,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=<SID=%s>" % sid) expression="member:1.2.840.113556.1.4.1941:=<SID=%s>" % sid)
self.assertEqual(len(res1), 4) self.assertEqual(len(res1), 4)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list)
@ -458,8 +458,8 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="member:1.2.840.113556.1.4.1941:=<SID=%s>" % sid) expression="member:1.2.840.113556.1.4.1941:=<SID=%s>" % sid)
self.assertEqual(len(res1), 4) self.assertEqual(len(res1), 4)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list)
@ -468,8 +468,8 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid) expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid)
self.assertEqual(len(res1), 4) self.assertEqual(len(res1), 4)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list)
@ -478,8 +478,8 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid) expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid)
self.assertEqual(len(res1), 4) self.assertEqual(len(res1), 4)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g1,%s" % self.ou_groups).lower() in dn_list)
@ -489,9 +489,9 @@ class MatchRulesTests(samba.tests.TestCase):
def test_extended_dn_u2(self): def test_extended_dn_u2(self):
res1 = self.ldb.search("cn=u2,%s" % self.ou_users, res1 = self.ldb.search("cn=u2,%s" % self.ou_users,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="objectClass=*", expression="objectClass=*",
attrs=['objectSid', 'objectGUID']) attrs=['objectSid', 'objectGUID'])
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("cn=u2,%s" % self.ou_users).lower()) self.assertEqual(str(res1[0].dn).lower(), ("cn=u2,%s" % self.ou_users).lower())
@ -499,20 +499,20 @@ class MatchRulesTests(samba.tests.TestCase):
guid = self.ldb.schema_format_value("objectGUID", res1[0]['objectGUID'][0]) guid = self.ldb.schema_format_value("objectGUID", res1[0]['objectGUID'][0])
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=<SID=%s>" % sid) expression="member=<SID=%s>" % sid)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g2,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g2,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=<GUID=%s>" % guid) expression="member=<GUID=%s>" % guid)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g2,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g2,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=<SID=%s>" % sid) expression="member:1.2.840.113556.1.4.1941:=<SID=%s>" % sid)
self.assertEqual(len(res1), 3) self.assertEqual(len(res1), 3)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list)
@ -520,8 +520,8 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="member:1.2.840.113556.1.4.1941:=<SID=%s>" % sid) expression="member:1.2.840.113556.1.4.1941:=<SID=%s>" % sid)
self.assertEqual(len(res1), 3) self.assertEqual(len(res1), 3)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list)
@ -529,8 +529,8 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid) expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid)
self.assertEqual(len(res1), 3) self.assertEqual(len(res1), 3)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list)
@ -538,8 +538,8 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid) expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid)
self.assertEqual(len(res1), 3) self.assertEqual(len(res1), 3)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g2,%s" % self.ou_groups).lower() in dn_list)
@ -548,9 +548,9 @@ class MatchRulesTests(samba.tests.TestCase):
def test_extended_dn_u3(self): def test_extended_dn_u3(self):
res1 = self.ldb.search("cn=u3,%s" % self.ou_users, res1 = self.ldb.search("cn=u3,%s" % self.ou_users,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="objectClass=*", expression="objectClass=*",
attrs=['objectSid', 'objectGUID']) attrs=['objectSid', 'objectGUID'])
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("cn=u3,%s" % self.ou_users).lower()) self.assertEqual(str(res1[0].dn).lower(), ("cn=u3,%s" % self.ou_users).lower())
@ -558,14 +558,14 @@ class MatchRulesTests(samba.tests.TestCase):
guid = self.ldb.schema_format_value("objectGUID", res1[0]['objectGUID'][0]) guid = self.ldb.schema_format_value("objectGUID", res1[0]['objectGUID'][0])
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=<SID=%s>" % sid) expression="member=<SID=%s>" % sid)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g3,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g3,%s" % self.ou_groups).lower())
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member=<GUID=%s>" % guid) expression="member=<GUID=%s>" % guid)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=g3,%s" % self.ou_groups).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=g3,%s" % self.ou_groups).lower())
@ -586,16 +586,16 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid) expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid)
self.assertEqual(len(res1), 2) self.assertEqual(len(res1), 2)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g3,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g3,%s" % self.ou_groups).lower() in dn_list)
self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g4,%s" % self.ou_groups).lower() in dn_list)
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid) expression="member:1.2.840.113556.1.4.1941:=<GUID=%s>" % guid)
self.assertEqual(len(res1), 2) self.assertEqual(len(res1), 2)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=g3,%s" % self.ou_groups).lower() in dn_list) self.assertTrue(("CN=g3,%s" % self.ou_groups).lower() in dn_list)
@ -656,28 +656,28 @@ class MatchRulesTests(samba.tests.TestCase):
def test_object_dn_binary(self): def test_object_dn_binary(self):
res1 = self.ldb.search(self.ou_computers, res1 = self.ldb.search(self.ou_computers,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="msDS-RevealedUsers=B:8:01010101:cn=c3,%s" % self.ou_computers) expression="msDS-RevealedUsers=B:8:01010101:cn=c3,%s" % self.ou_computers)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=c2,%s" % self.ou_computers).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=c2,%s" % self.ou_computers).lower())
res1 = self.ldb.search(self.ou_computers, res1 = self.ldb.search(self.ou_computers,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="msDS-RevealedUsers=B:8:01010101:cn=c3,%s" % self.ou_computers) expression="msDS-RevealedUsers=B:8:01010101:cn=c3,%s" % self.ou_computers)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=c2,%s" % self.ou_computers).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=c2,%s" % self.ou_computers).lower())
res1 = self.ldb.search(self.ou_computers, res1 = self.ldb.search(self.ou_computers,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="msDS-RevealedUsers:1.2.840.113556.1.4.1941:=B:8:01010101:cn=c3,%s" % self.ou_computers) expression="msDS-RevealedUsers:1.2.840.113556.1.4.1941:=B:8:01010101:cn=c3,%s" % self.ou_computers)
self.assertEqual(len(res1), 2) self.assertEqual(len(res1), 2)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=c1,%s" % self.ou_computers).lower() in dn_list) self.assertTrue(("CN=c1,%s" % self.ou_computers).lower() in dn_list)
self.assertTrue(("CN=c2,%s" % self.ou_computers).lower() in dn_list) self.assertTrue(("CN=c2,%s" % self.ou_computers).lower() in dn_list)
res1 = self.ldb.search(self.ou_computers, res1 = self.ldb.search(self.ou_computers,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="msDS-RevealedUsers:1.2.840.113556.1.4.1941:=B:8:01010101:cn=c3,%s" % self.ou_computers) expression="msDS-RevealedUsers:1.2.840.113556.1.4.1941:=B:8:01010101:cn=c3,%s" % self.ou_computers)
self.assertEqual(len(res1), 2) self.assertEqual(len(res1), 2)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=c1,%s" % self.ou_computers).lower() in dn_list) self.assertTrue(("CN=c1,%s" % self.ou_computers).lower() in dn_list)
@ -685,28 +685,28 @@ class MatchRulesTests(samba.tests.TestCase):
def test_one_way_links(self): def test_one_way_links(self):
res1 = self.ldb.search(self.ou, res1 = self.ldb.search(self.ou,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="addressBookRoots2=cn=c1,%s" % self.ou_computers) expression="addressBookRoots2=cn=c1,%s" % self.ou_computers)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=e2,%s" % self.ou).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=e2,%s" % self.ou).lower())
res1 = self.ldb.search(self.ou, res1 = self.ldb.search(self.ou,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="addressBookRoots2=cn=c1,%s" % self.ou_computers) expression="addressBookRoots2=cn=c1,%s" % self.ou_computers)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("CN=e2,%s" % self.ou).lower()) self.assertEqual(str(res1[0].dn).lower(), ("CN=e2,%s" % self.ou).lower())
res1 = self.ldb.search(self.ou, res1 = self.ldb.search(self.ou,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="addressBookRoots2:1.2.840.113556.1.4.1941:=cn=c1,%s" % self.ou_computers) expression="addressBookRoots2:1.2.840.113556.1.4.1941:=cn=c1,%s" % self.ou_computers)
self.assertEqual(len(res1), 2) self.assertEqual(len(res1), 2)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=e1,%s" % self.ou).lower() in dn_list) self.assertTrue(("CN=e1,%s" % self.ou).lower() in dn_list)
self.assertTrue(("CN=e2,%s" % self.ou).lower() in dn_list) self.assertTrue(("CN=e2,%s" % self.ou).lower() in dn_list)
res1 = self.ldb.search(self.ou, res1 = self.ldb.search(self.ou,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="addressBookRoots2:1.2.840.113556.1.4.1941:=cn=c1,%s" % self.ou_computers) expression="addressBookRoots2:1.2.840.113556.1.4.1941:=cn=c1,%s" % self.ou_computers)
self.assertEqual(len(res1), 2) self.assertEqual(len(res1), 2)
dn_list = [str(res.dn).lower() for res in res1] dn_list = [str(res.dn).lower() for res in res1]
self.assertTrue(("CN=e1,%s" % self.ou).lower() in dn_list) self.assertTrue(("CN=e1,%s" % self.ou).lower() in dn_list)
@ -714,8 +714,8 @@ class MatchRulesTests(samba.tests.TestCase):
def test_not_linked_attrs(self): def test_not_linked_attrs(self):
res1 = self.ldb.search(self.base_dn, res1 = self.ldb.search(self.base_dn,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="wellKnownObjects=B:32:aa312825768811d1aded00c04fd8d5cd:CN=computers,%s" % self.base_dn) expression="wellKnownObjects=B:32:aa312825768811d1aded00c04fd8d5cd:CN=computers,%s" % self.base_dn)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), self.base_dn.lower()) self.assertEqual(str(res1[0].dn).lower(), self.base_dn.lower())
@ -732,24 +732,24 @@ class MatchRulesTests(samba.tests.TestCase):
def test_subtree(self): def test_subtree(self):
res1 = self.ldb.search(self.ou, res1 = self.ldb.search(self.ou,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="otherWellKnownObjects=B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou) expression="otherWellKnownObjects=B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou)
self.assertEqual(len(res1), 1) self.assertEqual(len(res1), 1)
self.assertEqual(str(res1[0].dn).lower(), ("OU=o3,OU=o2,OU=o1,%s" % self.ou).lower()) self.assertEqual(str(res1[0].dn).lower(), ("OU=o3,OU=o2,OU=o1,%s" % self.ou).lower())
res1 = self.ldb.search(self.ou, res1 = self.ldb.search(self.ou,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="otherWellKnownObjects=B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou) expression="otherWellKnownObjects=B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search(self.ou, res1 = self.ldb.search(self.ou,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="otherWellKnownObjects:1.2.840.113556.1.4.1941:=B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou) expression="otherWellKnownObjects:1.2.840.113556.1.4.1941:=B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search(self.ou, res1 = self.ldb.search(self.ou,
scope=SCOPE_ONELEVEL, scope=SCOPE_ONELEVEL,
expression="otherWellKnownObjects:1.2.840.113556.1.4.1941:=B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou) expression="otherWellKnownObjects:1.2.840.113556.1.4.1941:=B:32:00000000000000000000000000000004:OU=o4,OU=o3,OU=o2,OU=o1,%s" % self.ou)
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
def test_unknown_oid(self): def test_unknown_oid(self):
@ -769,49 +769,58 @@ class MatchRulesTests(samba.tests.TestCase):
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
def test_nul_text(self): def test_nul_text(self):
self.assertRaises(TypeError, lambda: self.ldb.search("cn=g4,%s" % self.ou_groups, self.assertRaises(TypeError,
scope=SCOPE_BASE, lambda: self.ldb.search("cn=g4,%s" % self.ou_groups,
expression="\00member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users)) scope=SCOPE_BASE,
self.assertRaises(TypeError, lambda: self.ldb.search("cn=g4,%s" % self.ou_groups, expression="\00member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users))
scope=SCOPE_BASE, self.assertRaises(TypeError,
expression="member:1.2.840\00.113556.1.4.1941:=cn=u1,%s" % self.ou_users)) lambda: self.ldb.search("cn=g4,%s" % self.ou_groups,
self.assertRaises(TypeError, lambda: self.ldb.search("cn=g4,%s" % self.ou_groups, scope=SCOPE_BASE,
scope=SCOPE_BASE, expression="member:1.2.840\00.113556.1.4.1941:=cn=u1,%s" % self.ou_users))
expression="member:1.2.840.113556.1.4.1941:=cn=u1\00,%s" % self.ou_users)) self.assertRaises(TypeError,
self.assertRaises(LdbError, lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups, lambda: self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users)) expression="member:1.2.840.113556.1.4.1941:=cn=u1\00,%s" % self.ou_users))
self.assertRaises(LdbError, lambda: self.ldb.search("cn=g4,%s" % self.ou_groups, self.assertRaises(LdbError,
scope=SCOPE_BASE, lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups,
expression="member:1.2.840.113556.1.4.1941:")) scope=SCOPE_BASE,
expression="member:1.2.840.113556.1.4.1941:=cn=u1,%s" % self.ou_users))
self.assertRaises(LdbError,
lambda: self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE,
expression="member:1.2.840.113556.1.4.1941:"))
res1 = self.ldb.search("cn=g4,%s" % self.ou_groups, res1 = self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member:1.2.840.113556.1.4.1941:=") expression="member:1.2.840.113556.1.4.1941:=")
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search("cn=g4,%s" % self.ou_groups, res1 = self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member=") expression="member=")
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search("cn=g4,%s" % self.ou_groups, res1 = self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member:1.2.840.113556.1.4.1941:=nonexistent") expression="member:1.2.840.113556.1.4.1941:=nonexistent")
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
res1 = self.ldb.search("cn=g4,%s" % self.ou_groups, res1 = self.ldb.search("cn=g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member=nonexistent") expression="member=nonexistent")
self.assertEqual(len(res1), 0) self.assertEqual(len(res1), 0)
self.assertRaises(LdbError, lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups, self.assertRaises(LdbError,
scope=SCOPE_BASE, lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups,
expression="member:1.2.840.113556.1.4.1941:cn=u1,%s" % self.ou_users)) scope=SCOPE_BASE,
self.assertRaises(LdbError, lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups, expression="member:1.2.840.113556.1.4.1941:cn=u1,%s" % self.ou_users))
scope=SCOPE_BASE, self.assertRaises(LdbError,
expression="member:1.2.840.113556.1.4.1941:=cn=u1")) lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups,
self.assertRaises(LdbError, lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups, scope=SCOPE_BASE,
scope=SCOPE_BASE, expression="member:1.2.840.113556.1.4.1941:=cn=u1"))
expression="member:1.2.840.113556.1.4.1941:=cn=")) self.assertRaises(LdbError,
self.assertRaises(LdbError, lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups, lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups,
scope=SCOPE_BASE, scope=SCOPE_BASE,
expression="member::=cn=u1,%s" % self.ou_users)) expression="member:1.2.840.113556.1.4.1941:=cn="))
self.assertRaises(LdbError,
lambda: self.ldb.search("cn=\00g4,%s" % self.ou_groups,
scope=SCOPE_BASE,
expression="member::=cn=u1,%s" % self.ou_users))
def test_misc_matches(self): def test_misc_matches(self):
res1 = self.ldb.search(self.ou_groups, res1 = self.ldb.search(self.ou_groups,

View File

@ -159,12 +159,12 @@ class SimpleLdb(LdbBaseTest):
def test_search_scope_base_empty_db(self): def test_search_scope_base_empty_db(self):
l = ldb.Ldb(self.url(), flags=self.flags()) l = ldb.Ldb(self.url(), flags=self.flags())
self.assertEqual(len(l.search(ldb.Dn(l, "dc=foo1"), self.assertEqual(len(l.search(ldb.Dn(l, "dc=foo1"),
ldb.SCOPE_BASE)), 0) ldb.SCOPE_BASE)), 0)
def test_search_scope_onelevel_empty_db(self): def test_search_scope_onelevel_empty_db(self):
l = ldb.Ldb(self.url(), flags=self.flags()) l = ldb.Ldb(self.url(), flags=self.flags())
self.assertEqual(len(l.search(ldb.Dn(l, "dc=foo1"), self.assertEqual(len(l.search(ldb.Dn(l, "dc=foo1"),
ldb.SCOPE_ONELEVEL)), 0) ldb.SCOPE_ONELEVEL)), 0)
def test_delete(self): def test_delete(self):
l = ldb.Ldb(self.url(), flags=self.flags()) l = ldb.Ldb(self.url(), flags=self.flags())
@ -1873,7 +1873,7 @@ class BadIndexTests(LdbBaseTest):
# Now set this to unique index, but forget to check the result # Now set this to unique index, but forget to check the result
try: try:
self.ldb.add({"dn": "@ATTRIBUTES", self.ldb.add({"dn": "@ATTRIBUTES",
"y": "UNIQUE_INDEX"}) "y": "UNIQUE_INDEX"})
self.fail() self.fail()
except ldb.LdbError: except ldb.LdbError:
pass pass
@ -1903,7 +1903,7 @@ class BadIndexTests(LdbBaseTest):
# Now set this to unique index, but forget to check the result # Now set this to unique index, but forget to check the result
try: try:
self.ldb.add({"dn": "@ATTRIBUTES", self.ldb.add({"dn": "@ATTRIBUTES",
"y": "UNIQUE_INDEX"}) "y": "UNIQUE_INDEX"})
except ldb.LdbError: except ldb.LdbError:
pass pass
@ -2767,7 +2767,7 @@ class LdbResultTests(LdbBaseTest):
# This should not turn up until the transaction is concluded # This should not turn up until the transaction is concluded
res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG", res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG",
scope=ldb.SCOPE_BASE) scope=ldb.SCOPE_BASE)
self.assertEqual(len(res11), 0) self.assertEqual(len(res11), 0)
os.write(w2, b"search") os.write(w2, b"search")
@ -2779,7 +2779,7 @@ class LdbResultTests(LdbBaseTest):
# This should now turn up, as the transaction is over # This should now turn up, as the transaction is over
res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG", res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG",
scope=ldb.SCOPE_BASE) scope=ldb.SCOPE_BASE)
self.assertEqual(len(res11), 1) self.assertEqual(len(res11), 1)
self.assertFalse(found11) self.assertFalse(found11)
@ -2839,7 +2839,7 @@ class LdbResultTests(LdbBaseTest):
# This should not turn up until the transaction is concluded # This should not turn up until the transaction is concluded
res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG", res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG",
scope=ldb.SCOPE_BASE) scope=ldb.SCOPE_BASE)
self.assertEqual(len(res11), 0) self.assertEqual(len(res11), 0)
os.write(w2, b"search") os.write(w2, b"search")
@ -2851,7 +2851,7 @@ class LdbResultTests(LdbBaseTest):
# removed the read lock, but for ldb_tdb that happened as soon # removed the read lock, but for ldb_tdb that happened as soon
# as we called the first res.next() # as we called the first res.next()
res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG", res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG",
scope=ldb.SCOPE_BASE) scope=ldb.SCOPE_BASE)
self.assertEqual(len(res11), 0) self.assertEqual(len(res11), 0)
# These results are all collected at the first next(res) call # These results are all collected at the first next(res) call
@ -2867,7 +2867,7 @@ class LdbResultTests(LdbBaseTest):
# This should now turn up, as the transaction is over and all # This should now turn up, as the transaction is over and all
# read locks are gone # read locks are gone
res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG", res11 = self.l.search(base="OU=OU11,DC=SAMBA,DC=ORG",
scope=ldb.SCOPE_BASE) scope=ldb.SCOPE_BASE)
self.assertEqual(len(res11), 1) self.assertEqual(len(res11), 1)
self.assertTrue(found) self.assertTrue(found)

View File

@ -1311,11 +1311,11 @@ class RejectSubDBIndex(LdbBaseTest):
def test_try_subdb_index(self): def test_try_subdb_index(self):
try: try:
self.l.add({"dn": "@INDEXLIST", self.l.add({"dn": "@INDEXLIST",
"@IDX_LMDB_SUBDB": [b"1"], "@IDX_LMDB_SUBDB": [b"1"],
"@IDXONE": [b"1"], "@IDXONE": [b"1"],
"@IDXONE": [b"1"], "@IDXONE": [b"1"],
"@IDXGUID": [b"objectUUID"], "@IDXGUID": [b"objectUUID"],
"@IDX_DN_GUID": [b"GUID"], "@IDX_DN_GUID": [b"GUID"],
}) })
except ldb.LdbError as e: except ldb.LdbError as e:
code = e.args[0] code = e.args[0]

View File

@ -19,7 +19,7 @@ parser = optparse.OptionParser("%s <BINDING> [path]" % sys.argv[0])
sambaopts = options.SambaOptions(parser) sambaopts = options.SambaOptions(parser)
parser.add_option_group(sambaopts) parser.add_option_group(sambaopts)
parser.add_option("--createkey", type="string", metavar="KEYNAME", parser.add_option("--createkey", type="string", metavar="KEYNAME",
help="create a key") help="create a key")
opts, args = parser.parse_args() opts, args = parser.parse_args()

View File

@ -140,7 +140,7 @@ class Ldb(_Ldb):
try: try:
res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[], res = self.search(base=dn, scope=ldb.SCOPE_SUBTREE, attrs=[],
expression="(|(objectclass=user)(objectclass=computer))") expression="(|(objectclass=user)(objectclass=computer))")
except ldb.LdbError as error: except ldb.LdbError as error:
(errno, estr) = error.args (errno, estr) = error.args
if errno == ldb.ERR_NO_SUCH_OBJECT: if errno == ldb.ERR_NO_SUCH_OBJECT:
@ -173,8 +173,8 @@ class Ldb(_Ldb):
# Delete the 'visible' records, and the invisble 'deleted' records (if # Delete the 'visible' records, and the invisble 'deleted' records (if
# this DB supports it) # this DB supports it)
for msg in self.search(basedn, ldb.SCOPE_SUBTREE, for msg in self.search(basedn, ldb.SCOPE_SUBTREE,
"(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
[], controls=["show_deleted:0", "show_recycled:0"]): [], controls=["show_deleted:0", "show_recycled:0"]):
try: try:
self.delete(msg.dn, ["relax:0"]) self.delete(msg.dn, ["relax:0"])
except ldb.LdbError as error: except ldb.LdbError as error:
@ -184,8 +184,8 @@ class Ldb(_Ldb):
raise raise
res = self.search(basedn, ldb.SCOPE_SUBTREE, res = self.search(basedn, ldb.SCOPE_SUBTREE,
"(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))", "(&(|(objectclass=*)(distinguishedName=*))(!(distinguishedName=@BASEINFO)))",
[], controls=["show_deleted:0", "show_recycled:0"]) [], controls=["show_deleted:0", "show_recycled:0"])
assert len(res) == 0 assert len(res) == 0
# delete the specials # delete the specials
@ -271,7 +271,7 @@ def check_all_substituted(text):
var_end = text.find("}", var_start) var_end = text.find("}", var_start)
raise Exception("Not all variables substituted: %s" % raise Exception("Not all variables substituted: %s" %
text[var_start:var_end+1]) text[var_start:var_end+1])
def read_and_sub_file(file_name, subst_vars): def read_and_sub_file(file_name, subst_vars):
@ -336,7 +336,7 @@ def import_bundled_package(modulename, location, source_tree_container,
""" """
if in_source_tree(): if in_source_tree():
extra_path = os.path.join(source_tree_topdir(), source_tree_container, extra_path = os.path.join(source_tree_topdir(), source_tree_container,
location) location)
if not extra_path in sys.path: if not extra_path in sys.path:
sys.path.insert(0, extra_path) sys.path.insert(0, extra_path)
sys.modules[modulename] = __import__(modulename) sys.modules[modulename] = __import__(modulename)
@ -356,8 +356,8 @@ def ensure_third_party_module(modulename, location):
__import__(modulename) __import__(modulename)
except ImportError: except ImportError:
import_bundled_package(modulename, location, import_bundled_package(modulename, location,
source_tree_container="third_party", source_tree_container="third_party",
namespace="samba.third_party") namespace="samba.third_party")
def dn_from_dns_name(dnsdomain): def dn_from_dns_name(dnsdomain):

View File

@ -106,7 +106,7 @@ class dbcheck(object):
self.name_map = {} self.name_map = {}
try: try:
res = samdb.search(base="CN=DnsAdmins,CN=Users,%s" % samdb.domain_dn(), scope=ldb.SCOPE_BASE, res = samdb.search(base="CN=DnsAdmins,CN=Users,%s" % samdb.domain_dn(), scope=ldb.SCOPE_BASE,
attrs=["objectSid"]) attrs=["objectSid"])
dnsadmins_sid = ndr_unpack(security.dom_sid, res[0]["objectSid"][0]) dnsadmins_sid = ndr_unpack(security.dom_sid, res[0]["objectSid"][0])
self.name_map['DnsAdmins'] = str(dnsadmins_sid) self.name_map['DnsAdmins'] = str(dnsadmins_sid)
except ldb.LdbError as e5: except ldb.LdbError as e5:
@ -195,7 +195,7 @@ class dbcheck(object):
res = self.samdb.search(scope=ldb.SCOPE_BASE, res = self.samdb.search(scope=ldb.SCOPE_BASE,
base="@SAMBA_DSDB", base="@SAMBA_DSDB",
attrs=["compatibleFeatures", attrs=["compatibleFeatures",
"requiredFeatures"]) "requiredFeatures"])
if "compatibleFeatures" in res[0]: if "compatibleFeatures" in res[0]:
self.compatibleFeatures = res[0]["compatibleFeatures"] self.compatibleFeatures = res[0]["compatibleFeatures"]
if "requiredFeatures" in res[0]: if "requiredFeatures" in res[0]:
@ -463,7 +463,7 @@ newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname) m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
if nval != '': if nval != '':
m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD,
attrname) attrname)
if self.do_modify(m, ["relax:0", "show_recycled:1"], if self.do_modify(m, ["relax:0", "show_recycled:1"],
"Failed to normalise attribute %s" % attrname, "Failed to normalise attribute %s" % attrname,
@ -767,7 +767,7 @@ newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
m.dn = obj.dn m.dn = obj.dn
m['value'] = ldb.MessageElement(forward_vals, ldb.FLAG_MOD_REPLACE, forward_attr) m['value'] = ldb.MessageElement(forward_vals, ldb.FLAG_MOD_REPLACE, forward_attr)
if self.do_modify(m, ["local_oid:%s:1" % dsdb.DSDB_CONTROL_DBCHECK_FIX_DUPLICATE_LINKS], if self.do_modify(m, ["local_oid:%s:1" % dsdb.DSDB_CONTROL_DBCHECK_FIX_DUPLICATE_LINKS],
"Failed to fix duplicate links in attribute '%s'" % forward_attr): "Failed to fix duplicate links in attribute '%s'" % forward_attr):
self.report("Fixed duplicate links in attribute '%s'" % (forward_attr)) self.report("Fixed duplicate links in attribute '%s'" % (forward_attr))
duplicate_cache_key = "%s:%s" % (str(obj.dn), forward_attr) duplicate_cache_key = "%s:%s" % (str(obj.dn), forward_attr)
assert duplicate_cache_key in self.duplicate_link_cache assert duplicate_cache_key in self.duplicate_link_cache
@ -1142,9 +1142,9 @@ newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
missing_forward_links, missing_error_count = \ missing_forward_links, missing_error_count = \
self.find_missing_forward_links_from_backlinks(obj, self.find_missing_forward_links_from_backlinks(obj,
attrname, syntax_oid, attrname, syntax_oid,
reverse_link_name, reverse_link_name,
unique_dict) unique_dict)
error_count += missing_error_count error_count += missing_error_count
forward_links = [dn for dn in unique_dict.values()] forward_links = [dn for dn in unique_dict.values()]
@ -1186,7 +1186,7 @@ newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
if guid is None: if guid is None:
error_count += 1 error_count += 1
self.err_missing_dn_GUID_component(obj.dn, attrname, val, dsdb_dn, self.err_missing_dn_GUID_component(obj.dn, attrname, val, dsdb_dn,
"missing GUID") "missing GUID")
continue continue
guidstr = str(misc.GUID(guid)) guidstr = str(misc.GUID(guid))
@ -1839,9 +1839,9 @@ newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
nmsg.dn = dn nmsg.dn = dn
nmsg[attr] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, attr) nmsg[attr] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, attr)
if self.do_modify(nmsg, ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK_MODIFY_RO_REPLICA, if self.do_modify(nmsg, ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK_MODIFY_RO_REPLICA,
"local_oid:1.3.6.1.4.1.7165.4.3.14:0", "local_oid:1.3.6.1.4.1.7165.4.3.14:0",
"local_oid:1.3.6.1.4.1.7165.4.3.25:0"], "local_oid:1.3.6.1.4.1.7165.4.3.25:0"],
"Failed to fix attribute %s" % attr): "Failed to fix attribute %s" % attr):
self.report("Fixed attribute '%s' of '%s'\n" % (attr, dn)) self.report("Fixed attribute '%s' of '%s'\n" % (attr, dn))

View File

@ -141,7 +141,7 @@ class SOARecord(dnsserver.DNS_RPC_RECORD):
class SRVRecord(dnsserver.DNS_RPC_RECORD): class SRVRecord(dnsserver.DNS_RPC_RECORD):
def __init__(self, target, port, priority=0, weight=100, serial=1, ttl=900, def __init__(self, target, port, priority=0, weight=100, serial=1, ttl=900,
rank=dnsp.DNS_RANK_ZONE, node_flag=0): rank=dnsp.DNS_RANK_ZONE, node_flag=0):
super(SRVRecord, self).__init__() super(SRVRecord, self).__init__()
self.wType = dnsp.DNS_TYPE_SRV self.wType = dnsp.DNS_TYPE_SRV
self.dwFlags = rank | node_flag self.dwFlags = rank | node_flag
@ -160,7 +160,7 @@ class SRVRecord(dnsserver.DNS_RPC_RECORD):
class TXTRecord(dnsserver.DNS_RPC_RECORD): class TXTRecord(dnsserver.DNS_RPC_RECORD):
def __init__(self, slist, serial=1, ttl=900, rank=dnsp.DNS_RANK_ZONE, def __init__(self, slist, serial=1, ttl=900, rank=dnsp.DNS_RANK_ZONE,
node_flag=0): node_flag=0):
super(TXTRecord, self).__init__() super(TXTRecord, self).__init__()
self.wType = dnsp.DNS_TYPE_TXT self.wType = dnsp.DNS_TYPE_TXT
self.dwFlags = rank | node_flag self.dwFlags = rank | node_flag

View File

@ -62,7 +62,7 @@ def drsuapi_connect(server, lp, creds):
def sendDsReplicaSync(drsuapiBind, drsuapi_handle, source_dsa_guid, def sendDsReplicaSync(drsuapiBind, drsuapi_handle, source_dsa_guid,
naming_context, req_option): naming_context, req_option):
"""Send DS replica sync request. """Send DS replica sync request.
:param drsuapiBind: a drsuapi Bind object :param drsuapiBind: a drsuapi Bind object

View File

@ -100,8 +100,8 @@ class VersionOptions(optparse.OptionGroup):
def __init__(self, parser): def __init__(self, parser):
optparse.OptionGroup.__init__(self, parser, "Version Options") optparse.OptionGroup.__init__(self, parser, "Version Options")
self.add_option("-V", "--version", action="callback", self.add_option("-V", "--version", action="callback",
callback=self._display_version, callback=self._display_version,
help="Display version number") help="Display version number")
def _display_version(self, option, opt_str, arg, parser): def _display_version(self, option, opt_str, arg, parser):
import samba import samba
@ -136,30 +136,30 @@ class CredentialsOptions(optparse.OptionGroup):
self.machine_pass = False self.machine_pass = False
optparse.OptionGroup.__init__(self, parser, self.section) optparse.OptionGroup.__init__(self, parser, self.section)
self._add_option("--simple-bind-dn", metavar="DN", action="callback", self._add_option("--simple-bind-dn", metavar="DN", action="callback",
callback=self._set_simple_bind_dn, type=str, callback=self._set_simple_bind_dn, type=str,
help="DN to use for a simple bind") help="DN to use for a simple bind")
self._add_option("--password", metavar="PASSWORD", action="callback", self._add_option("--password", metavar="PASSWORD", action="callback",
help="Password", type=str, callback=self._set_password) help="Password", type=str, callback=self._set_password)
self._add_option("-U", "--username", metavar="USERNAME", self._add_option("-U", "--username", metavar="USERNAME",
action="callback", type=str, action="callback", type=str,
help="Username", callback=self._parse_username) help="Username", callback=self._parse_username)
self._add_option("-W", "--workgroup", metavar="WORKGROUP", self._add_option("-W", "--workgroup", metavar="WORKGROUP",
action="callback", type=str, action="callback", type=str,
help="Workgroup", callback=self._parse_workgroup) help="Workgroup", callback=self._parse_workgroup)
self._add_option("-N", "--no-pass", action="callback", self._add_option("-N", "--no-pass", action="callback",
help="Don't ask for a password", help="Don't ask for a password",
callback=self._set_no_password) callback=self._set_no_password)
self._add_option("-k", "--kerberos", metavar="KERBEROS", self._add_option("-k", "--kerberos", metavar="KERBEROS",
action="callback", type=str, action="callback", type=str,
help="Use Kerberos", callback=self._set_kerberos) help="Use Kerberos", callback=self._set_kerberos)
self._add_option("", "--ipaddress", metavar="IPADDRESS", self._add_option("", "--ipaddress", metavar="IPADDRESS",
action="callback", type=str, action="callback", type=str,
help="IP address of server", help="IP address of server",
callback=self._set_ipaddress) callback=self._set_ipaddress)
self._add_option("-P", "--machine-pass", self._add_option("-P", "--machine-pass",
action="callback", action="callback",
help="Use stored machine account password", help="Use stored machine account password",
callback=self._set_machine_pass) callback=self._set_machine_pass)
self._add_option("--krb5-ccache", metavar="KRB5CCNAME", self._add_option("--krb5-ccache", metavar="KRB5CCNAME",
action="callback", type=str, action="callback", type=str,
help="Kerberos Credentials cache", help="Kerberos Credentials cache",

View File

@ -118,7 +118,7 @@ class gp_sec_ext(gp_inf_ext):
def list(self, rootpath): def list(self, rootpath):
return os.path.join(rootpath, return os.path.join(rootpath,
"MACHINE/Microsoft/Windows NT/SecEdit/GptTmpl.inf") "MACHINE/Microsoft/Windows NT/SecEdit/GptTmpl.inf")
def listmachpol(self, rootpath): def listmachpol(self, rootpath):
return os.path.join(rootpath, "Machine/Registry.pol") return os.path.join(rootpath, "Machine/Registry.pol")

View File

@ -402,7 +402,7 @@ class gp_inf_ext(gp_ext):
def get_dc_hostname(creds, lp): def get_dc_hostname(creds, lp):
net = Net(creds=creds, lp=lp) net = Net(creds=creds, lp=lp)
cldap_ret = net.finddc(domain=lp.get('realm'), flags=(nbt.NBT_SERVER_LDAP | cldap_ret = net.finddc(domain=lp.get('realm'), flags=(nbt.NBT_SERVER_LDAP |
nbt.NBT_SERVER_DS)) nbt.NBT_SERVER_DS))
return cldap_ret.pdc_dns_name return cldap_ret.pdc_dns_name
''' Fetch a list of GUIDs for applicable GPOs ''' ''' Fetch a list of GUIDs for applicable GPOs '''
@ -464,7 +464,7 @@ def apply_gp(lp, creds, test_ldb, logger, store, gp_extensions):
check_refresh_gpo_list(dc_hostname, lp, creds, gpos) check_refresh_gpo_list(dc_hostname, lp, creds, gpos)
except: except:
logger.error('Failed downloading gpt cache from \'%s\' using SMB' \ logger.error('Failed downloading gpt cache from \'%s\' using SMB' \
% dc_hostname) % dc_hostname)
return return
for gpo_obj in gpos: for gpo_obj in gpos:
@ -485,7 +485,7 @@ def apply_gp(lp, creds, test_ldb, logger, store, gp_extensions):
ext.parse(ext.list(path), test_ldb, gp_db, lp) ext.parse(ext.list(path), test_ldb, gp_db, lp)
except Exception as e: except Exception as e:
logger.error('Failed to parse gpo %s for extension %s' % \ logger.error('Failed to parse gpo %s for extension %s' % \
(guid, str(ext))) (guid, str(ext)))
logger.error('Message was: ' + str(e)) logger.error('Message was: ' + str(e))
store.cancel() store.cancel()
continue continue

View File

@ -121,7 +121,7 @@ def shorten_vertex_names(vertices, suffix=',...', aggressive=False):
break break
else: else:
vmap = dict((k, v.replace(',CN=Servers,', ',**,', 1)) vmap = dict((k, v.replace(',CN=Servers,', ',**,', 1))
for k, v in vmap.items()) for k, v in vmap.items())
replacements.append(('**', 'CN=Servers')) replacements.append(('**', 'CN=Servers'))
for v in vmap.values(): for v in vmap.values():
@ -129,7 +129,7 @@ def shorten_vertex_names(vertices, suffix=',...', aggressive=False):
break break
else: else:
vmap = dict((k, v.replace('CN=NTDS Settings,', '*,', 1)) vmap = dict((k, v.replace('CN=NTDS Settings,', '*,', 1))
for k, v in vmap.items()) for k, v in vmap.items())
replacements.append(('*', 'CN=NTDS Settings')) replacements.append(('*', 'CN=NTDS Settings'))
return vmap, replacements return vmap, replacements

View File

@ -42,12 +42,12 @@ class IDmapDB(samba.Ldb):
url = lp.private_path("idmap.ldb") url = lp.private_path("idmap.ldb")
super(IDmapDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir, super(IDmapDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir,
session_info=session_info, credentials=credentials, flags=flags, session_info=session_info, credentials=credentials, flags=flags,
options=options) options=options)
def connect(self, url=None, flags=0, options=None): def connect(self, url=None, flags=0, options=None):
super(IDmapDB, self).connect(url=self.lp.private_path(url), flags=flags, super(IDmapDB, self).connect(url=self.lp.private_path(url), flags=flags,
options=options) options=options)
def increment_xid(self): def increment_xid(self):
"""Increment xidNumber, if not present it create and assign it to the lowerBound """Increment xidNumber, if not present it create and assign it to the lowerBound

View File

@ -227,7 +227,7 @@ class DCJoinContext(object):
creds.set_kerberos_state(ctx.creds.get_kerberos_state()) creds.set_kerberos_state(ctx.creds.get_kerberos_state())
machine_samdb = SamDB(url="ldap://%s" % ctx.server, machine_samdb = SamDB(url="ldap://%s" % ctx.server,
session_info=system_session(), session_info=system_session(),
credentials=creds, lp=ctx.lp) credentials=creds, lp=ctx.lp)
except: except:
pass pass
else: else:
@ -235,10 +235,10 @@ class DCJoinContext(object):
if token_res[0]["tokenGroups"][0] \ if token_res[0]["tokenGroups"][0] \
== res[0]["objectSID"][0]: == res[0]["objectSID"][0]:
raise DCJoinException("Not removing account %s which " raise DCJoinException("Not removing account %s which "
"looks like a Samba DC account " "looks like a Samba DC account "
"matching the password we already have. " "matching the password we already have. "
"To override, remove secrets.ldb and secrets.tdb" "To override, remove secrets.ldb and secrets.tdb"
% ctx.samname) % ctx.samname)
ctx.del_noerror(res[0].dn, recursive=True) ctx.del_noerror(res[0].dn, recursive=True)
@ -256,13 +256,13 @@ class DCJoinContext(object):
res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(), res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname), expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname),
attrs=[]) attrs=[])
if res: if res:
raise DCJoinException("Not removing account %s which looks like " raise DCJoinException("Not removing account %s which looks like "
"a Samba DNS service account but does not " "a Samba DNS service account but does not "
"have servicePrincipalName=%s" % "have servicePrincipalName=%s" %
(ldb.binary_encode("dns-%s" % ctx.myname), (ldb.binary_encode("dns-%s" % ctx.myname),
ldb.binary_encode("dns/%s" % ctx.dnshostname))) ldb.binary_encode("dns/%s" % ctx.dnshostname)))
def cleanup_old_join(ctx, force=False): def cleanup_old_join(ctx, force=False):
@ -656,15 +656,15 @@ class DCJoinContext(object):
# TODO Is this supposed to be for the schema partition too? # TODO Is this supposed to be for the schema partition too?
expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.domaindns_zone) expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.domaindns_zone)
domain = (ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, domain = (ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
attrs=[], attrs=[],
base=ctx.samdb.get_partitions_dn(), base=ctx.samdb.get_partitions_dn(),
expression=expr), ctx.domaindns_zone) expression=expr), ctx.domaindns_zone)
expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.forestdns_zone) expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.forestdns_zone)
forest = (ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, forest = (ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
attrs=[], attrs=[],
base=ctx.samdb.get_partitions_dn(), base=ctx.samdb.get_partitions_dn(),
expression=expr), ctx.forestdns_zone) expression=expr), ctx.forestdns_zone)
for part, zone in (domain, forest): for part, zone in (domain, forest):
if zone not in ctx.nc_list: if zone not in ctx.nc_list:
@ -847,16 +847,16 @@ class DCJoinContext(object):
smbconf = ctx.lp.configfile smbconf = ctx.lp.configfile
presult = provision(ctx.logger, system_session(), smbconf=smbconf, presult = provision(ctx.logger, system_session(), smbconf=smbconf,
targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm, targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
rootdn=ctx.root_dn, domaindn=ctx.base_dn, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
schemadn=ctx.schema_dn, configdn=ctx.config_dn, schemadn=ctx.schema_dn, configdn=ctx.config_dn,
serverdn=ctx.server_dn, domain=ctx.domain_name, serverdn=ctx.server_dn, domain=ctx.domain_name,
hostname=ctx.myname, domainsid=ctx.domsid, hostname=ctx.myname, domainsid=ctx.domsid,
machinepass=ctx.acct_pass, serverrole="active directory domain controller", machinepass=ctx.acct_pass, serverrole="active directory domain controller",
sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid, sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend, use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend,
plaintext_secrets=ctx.plaintext_secrets, plaintext_secrets=ctx.plaintext_secrets,
backend_store=ctx.backend_store backend_store=ctx.backend_store
) )
print("Provision OK for domain DN %s" % presult.domaindn) print("Provision OK for domain DN %s" % presult.domaindn)
ctx.local_samdb = presult.samdb ctx.local_samdb = presult.samdb
@ -942,19 +942,19 @@ class DCJoinContext(object):
repl = ctx.create_replicator(repl_creds, binding_options) repl = ctx.create_replicator(repl_creds, binding_options)
repl.replicate(ctx.schema_dn, source_dsa_invocation_id, repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
destination_dsa_guid, schema=True, rodc=ctx.RODC, destination_dsa_guid, schema=True, rodc=ctx.RODC,
replica_flags=ctx.replica_flags) replica_flags=ctx.replica_flags)
repl.replicate(ctx.config_dn, source_dsa_invocation_id, repl.replicate(ctx.config_dn, source_dsa_invocation_id,
destination_dsa_guid, rodc=ctx.RODC, destination_dsa_guid, rodc=ctx.RODC,
replica_flags=ctx.replica_flags) replica_flags=ctx.replica_flags)
if not ctx.subdomain: if not ctx.subdomain:
# Replicate first the critical object for the basedn # Replicate first the critical object for the basedn
if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY: if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
print("Replicating critical objects from the base DN of the domain") print("Replicating critical objects from the base DN of the domain")
ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
repl.replicate(ctx.base_dn, source_dsa_invocation_id, repl.replicate(ctx.base_dn, source_dsa_invocation_id,
destination_dsa_guid, rodc=ctx.RODC, destination_dsa_guid, rodc=ctx.RODC,
replica_flags=ctx.domain_replica_flags) replica_flags=ctx.domain_replica_flags)
ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
repl.replicate(ctx.base_dn, source_dsa_invocation_id, repl.replicate(ctx.base_dn, source_dsa_invocation_id,
destination_dsa_guid, rodc=ctx.RODC, destination_dsa_guid, rodc=ctx.RODC,
@ -973,11 +973,11 @@ class DCJoinContext(object):
if ctx.RODC: if ctx.RODC:
repl.replicate(ctx.acct_dn, source_dsa_invocation_id, repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
destination_dsa_guid, destination_dsa_guid,
exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True) exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id, repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
destination_dsa_guid, destination_dsa_guid,
exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True) exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
elif ctx.rid_manager_dn != None: elif ctx.rid_manager_dn != None:
# Try and get a RID Set if we can. This is only possible against the RID Master. Warn otherwise. # Try and get a RID Set if we can. This is only possible against the RID Master. Warn otherwise.
try: try:
@ -1061,7 +1061,7 @@ class DCJoinContext(object):
binding_options = "sign" binding_options = "sign"
dns_conn = dnsserver.dnsserver("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options), dns_conn = dnsserver.dnsserver("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
ctx.lp, ctx.creds) ctx.lp, ctx.creds)
name_found = True name_found = True
@ -1519,10 +1519,10 @@ def join_clone(logger=None, server=None, creds=None, lp=None,
return ctx return ctx
def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None, def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None,
netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None, netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False, netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False,
dns_backend=None, plaintext_secrets=False, dns_backend=None, plaintext_secrets=False,
backend_store=None): backend_store=None):
"""Join as a DC.""" """Join as a DC."""
ctx = DCJoinContext(logger, server, creds, lp, site, netbios_name, ctx = DCJoinContext(logger, server, creds, lp, site, netbios_name,
targetdir, parent_domain, machinepass, use_ntvfs, targetdir, parent_domain, machinepass, use_ntvfs,
@ -1696,14 +1696,14 @@ class DCCloneAndRenameContext(DCCloneContext):
# do the provision with the new/renamed domain DN values # do the provision with the new/renamed domain DN values
presult = provision(ctx.logger, system_session(), presult = provision(ctx.logger, system_session(),
targetdir=ctx.targetdir, samdb_fill=FILL_DRS, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
realm=ctx.new_realm, lp=non_global_lp, realm=ctx.new_realm, lp=non_global_lp,
rootdn=ctx.rename_dn(ctx.root_dn), domaindn=ctx.new_base_dn, rootdn=ctx.rename_dn(ctx.root_dn), domaindn=ctx.new_base_dn,
schemadn=ctx.rename_dn(ctx.schema_dn), schemadn=ctx.rename_dn(ctx.schema_dn),
configdn=ctx.rename_dn(ctx.config_dn), configdn=ctx.rename_dn(ctx.config_dn),
domain=ctx.new_domain_name, domainsid=ctx.domsid, domain=ctx.new_domain_name, domainsid=ctx.domsid,
serverrole="active directory domain controller", serverrole="active directory domain controller",
dns_backend=ctx.dns_backend) dns_backend=ctx.dns_backend)
print("Provision OK for renamed domain DN %s" % presult.domaindn) print("Provision OK for renamed domain DN %s" % presult.domaindn)
ctx.local_samdb = presult.samdb ctx.local_samdb = presult.samdb

View File

@ -34,9 +34,9 @@ class PlainHelpFormatter(optparse.IndentedHelpFormatter):
paragraphs = description.split('\n') paragraphs = description.split('\n')
wrapped_paragraphs = [ wrapped_paragraphs = [
textwrap.fill(p, textwrap.fill(p,
desc_width, desc_width,
initial_indent=indent, initial_indent=indent,
subsequent_indent=indent) subsequent_indent=indent)
for p in paragraphs] for p in paragraphs]
result = "\n".join(wrapped_paragraphs) + "\n" result = "\n".join(wrapped_paragraphs) + "\n"
return result return result

View File

@ -58,7 +58,7 @@ def netcmd_finddc(lp, creds, realm=None):
if realm is None: if realm is None:
realm = lp.get('realm') realm = lp.get('realm')
cldap_ret = net.finddc(domain=realm, cldap_ret = net.finddc(domain=realm,
flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE) flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
return cldap_ret.pdc_dns_name return cldap_ret.pdc_dns_name
@ -67,5 +67,5 @@ def netcmd_get_domain_infos_via_cldap(lp, creds, address=None):
DC with the specified address''' DC with the specified address'''
net = Net(creds=creds, lp=lp) net = Net(creds=creds, lp=lp)
cldap_ret = net.finddc(address=address, cldap_ret = net.finddc(address=address,
flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS) flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS)
return cldap_ret return cldap_ret

View File

@ -421,7 +421,7 @@ class cmd_computer_list(Command):
creds = credopts.get_credentials(lp, fallback_machine=True) creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
filter = "(sAMAccountType=%u)" % (dsdb.ATYPE_WORKSTATION_TRUST) filter = "(sAMAccountType=%u)" % (dsdb.ATYPE_WORKSTATION_TRUST)

View File

@ -57,7 +57,7 @@ class cmd_dbcheck(Command):
takes_options = [ takes_options = [
Option("--scope", dest="scope", default="SUB", Option("--scope", dest="scope", default="SUB",
help="Pass search scope that builds DN list. Options: SUB, ONE, BASE"), help="Pass search scope that builds DN list. Options: SUB, ONE, BASE"),
Option("--fix", dest="fix", default=False, action='store_true', Option("--fix", dest="fix", default=False, action='store_true',
help='Fix any errors found'), help='Fix any errors found'),
Option("--yes", action='callback', callback=process_yes, Option("--yes", action='callback', callback=process_yes,
@ -65,9 +65,9 @@ class cmd_dbcheck(Command):
Option("--cross-ncs", dest="cross_ncs", default=False, action='store_true', Option("--cross-ncs", dest="cross_ncs", default=False, action='store_true',
help="cross naming context boundaries"), help="cross naming context boundaries"),
Option("-v", "--verbose", dest="verbose", action="store_true", default=False, Option("-v", "--verbose", dest="verbose", action="store_true", default=False,
help="Print more details of checking"), help="Print more details of checking"),
Option("-q", "--quiet", action="store_true", default=False, Option("-q", "--quiet", action="store_true", default=False,
help="don't print details of checking"), help="don't print details of checking"),
Option("--attrs", dest="attrs", default=None, help="list of attributes to check (space separated)"), Option("--attrs", dest="attrs", default=None, help="list of attributes to check (space separated)"),
Option("--reindex", dest="reindex", default=False, action="store_true", help="force database re-index"), Option("--reindex", dest="reindex", default=False, action="store_true", help="force database re-index"),
Option("--force-modules", dest="force_modules", default=False, action="store_true", help="force loading of Samba modules and ignore the @MODULES record (for very old databases)"), Option("--force-modules", dest="force_modules", default=False, action="store_true", help="force loading of Samba modules and ignore the @MODULES record (for very old databases)"),
@ -154,7 +154,7 @@ class cmd_dbcheck(Command):
else: else:
error_count = chk.check_database(DN=DN, scope=search_scope, error_count = chk.check_database(DN=DN, scope=search_scope,
controls=controls, attrs=attrs) controls=controls, attrs=attrs)
except: except:
if started_transaction: if started_transaction:
samdb.transaction_cancel() samdb.transaction_cancel()

View File

@ -68,9 +68,9 @@ class cmd_delegation_show(Command):
(cleanedaccount, realm, domain) = _get_user_realm_domain(accountname) (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname)
res = sam.search(expression="sAMAccountName=%s" % res = sam.search(expression="sAMAccountName=%s" %
ldb.binary_encode(cleanedaccount), ldb.binary_encode(cleanedaccount),
scope=ldb.SCOPE_SUBTREE, scope=ldb.SCOPE_SUBTREE,
attrs=["userAccountControl", "msDS-AllowedToDelegateTo"]) attrs=["userAccountControl", "msDS-AllowedToDelegateTo"])
if len(res) == 0: if len(res) == 0:
raise CommandError("Unable to find account name '%s'" % accountname) raise CommandError("Unable to find account name '%s'" % accountname)
assert(len(res) == 1) assert(len(res) == 1)
@ -80,9 +80,9 @@ class cmd_delegation_show(Command):
self.outf.write("Account-DN: %s\n" % str(res[0].dn)) self.outf.write("Account-DN: %s\n" % str(res[0].dn))
self.outf.write("UF_TRUSTED_FOR_DELEGATION: %s\n" self.outf.write("UF_TRUSTED_FOR_DELEGATION: %s\n"
% bool(uac & dsdb.UF_TRUSTED_FOR_DELEGATION)) % bool(uac & dsdb.UF_TRUSTED_FOR_DELEGATION))
self.outf.write("UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: %s\n" % self.outf.write("UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: %s\n" %
bool(uac & dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION)) bool(uac & dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION))
if allowed is not None: if allowed is not None:
for a in allowed: for a in allowed:
@ -190,8 +190,8 @@ class cmd_delegation_for_any_protocol(Command):
flag = dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION flag = dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
try: try:
sam.toggle_userAccountFlags(search_filter, flag, sam.toggle_userAccountFlags(search_filter, flag,
flags_str="Trusted-to-Authenticate-for-Delegation", flags_str="Trusted-to-Authenticate-for-Delegation",
on=on, strict=True) on=on, strict=True)
except Exception as err: except Exception as err:
raise CommandError(err) raise CommandError(err)
@ -242,8 +242,8 @@ class cmd_delegation_add_service(Command):
msg = ldb.Message() msg = ldb.Message()
msg.dn = res[0].dn msg.dn = res[0].dn
msg["msDS-AllowedToDelegateTo"] = ldb.MessageElement([principal], msg["msDS-AllowedToDelegateTo"] = ldb.MessageElement([principal],
ldb.FLAG_MOD_ADD, ldb.FLAG_MOD_ADD,
"msDS-AllowedToDelegateTo") "msDS-AllowedToDelegateTo")
try: try:
sam.modify(msg) sam.modify(msg)
except Exception as err: except Exception as err:
@ -296,8 +296,8 @@ class cmd_delegation_del_service(Command):
msg = ldb.Message() msg = ldb.Message()
msg.dn = res[0].dn msg.dn = res[0].dn
msg["msDS-AllowedToDelegateTo"] = ldb.MessageElement([principal], msg["msDS-AllowedToDelegateTo"] = ldb.MessageElement([principal],
ldb.FLAG_MOD_DELETE, ldb.FLAG_MOD_DELETE,
"msDS-AllowedToDelegateTo") "msDS-AllowedToDelegateTo")
try: try:
sam.modify(msg) sam.modify(msg)
except Exception as err: except Exception as err:

View File

@ -123,7 +123,7 @@ def zone_notify_level_string(notify_level):
def dp_flags_string(dp_flags): def dp_flags_string(dp_flags):
bitmap_defs = [ 'DNS_DP_AUTOCREATED', 'DNS_DP_LEGACY', 'DNS_DP_DOMAIN_DEFAULT', bitmap_defs = [ 'DNS_DP_AUTOCREATED', 'DNS_DP_LEGACY', 'DNS_DP_DOMAIN_DEFAULT',
'DNS_DP_FOREST_DEFAULT', 'DNS_DP_ENLISTED', 'DNS_DP_DELETED' ] 'DNS_DP_FOREST_DEFAULT', 'DNS_DP_ENLISTED', 'DNS_DP_DELETED' ]
return bitmap_string(dnsserver, bitmap_defs, dp_flags) return bitmap_string(dnsserver, bitmap_defs, dp_flags)
@ -986,7 +986,7 @@ class cmd_update_record(Command):
dns_conn = dns_connect(server, self.lp, self.creds) dns_conn = dns_connect(server, self.lp, self.creds)
rec_match = dns_record_match(dns_conn, server, zone, name, record_type, rec_match = dns_record_match(dns_conn, server, zone, name, record_type,
olddata) olddata)
if not rec_match: if not rec_match:
raise CommandError('Record or zone does not exist.') raise CommandError('Record or zone does not exist.')

View File

@ -514,28 +514,28 @@ class cmd_domain_provision(Command):
backend_store = get_default_backend_store() backend_store = get_default_backend_store()
try: try:
result = provision(self.logger, result = provision(self.logger,
session, smbconf=smbconf, targetdir=targetdir, session, smbconf=smbconf, targetdir=targetdir,
samdb_fill=samdb_fill, realm=realm, domain=domain, samdb_fill=samdb_fill, realm=realm, domain=domain,
domainguid=domain_guid, domainsid=domain_sid, domainguid=domain_guid, domainsid=domain_sid,
hostname=host_name, hostname=host_name,
hostip=host_ip, hostip6=host_ip6, hostip=host_ip, hostip6=host_ip6,
sitename=site, ntdsguid=ntds_guid, sitename=site, ntdsguid=ntds_guid,
invocationid=invocationid, adminpass=adminpass, invocationid=invocationid, adminpass=adminpass,
krbtgtpass=krbtgtpass, machinepass=machinepass, krbtgtpass=krbtgtpass, machinepass=machinepass,
dns_backend=dns_backend, dns_forwarder=dns_forwarder, dns_backend=dns_backend, dns_forwarder=dns_forwarder,
dnspass=dnspass, root=root, nobody=nobody, dnspass=dnspass, root=root, nobody=nobody,
users=users, users=users,
serverrole=server_role, dom_for_fun_level=dom_for_fun_level, serverrole=server_role, dom_for_fun_level=dom_for_fun_level,
backend_type=ldap_backend_type, backend_type=ldap_backend_type,
ldapadminpass=ldapadminpass, ol_mmr_urls=ol_mmr_urls, slapd_path=slapd_path, ldapadminpass=ldapadminpass, ol_mmr_urls=ol_mmr_urls, slapd_path=slapd_path,
useeadb=eadb, next_rid=next_rid, lp=lp, use_ntvfs=use_ntvfs, useeadb=eadb, next_rid=next_rid, lp=lp, use_ntvfs=use_ntvfs,
use_rfc2307=use_rfc2307, skip_sysvolacl=False, use_rfc2307=use_rfc2307, skip_sysvolacl=False,
ldap_backend_extra_port=ldap_backend_extra_port, ldap_backend_extra_port=ldap_backend_extra_port,
ldap_backend_forced_uri=ldap_backend_forced_uri, ldap_backend_forced_uri=ldap_backend_forced_uri,
nosync=ldap_backend_nosync, ldap_dryrun_mode=ldap_dryrun_mode, nosync=ldap_backend_nosync, ldap_dryrun_mode=ldap_dryrun_mode,
base_schema=base_schema, base_schema=base_schema,
plaintext_secrets=plaintext_secrets, plaintext_secrets=plaintext_secrets,
backend_store=backend_store) backend_store=backend_store)
except ProvisioningError as e: except ProvisioningError as e:
raise CommandError("Provision failed", e) raise CommandError("Provision failed", e)
@ -809,8 +809,8 @@ class cmd_domain_demote(Command):
ntds_guid = samdb.get_ntds_GUID() ntds_guid = samdb.get_ntds_GUID()
msg = samdb.search(base=str(samdb.get_config_basedn()), msg = samdb.search(base=str(samdb.get_config_basedn()),
scope=ldb.SCOPE_SUBTREE, expression="(objectGUID=%s)" % ntds_guid, scope=ldb.SCOPE_SUBTREE, expression="(objectGUID=%s)" % ntds_guid,
attrs=['options']) attrs=['options'])
if len(msg) == 0 or "options" not in msg[0]: if len(msg) == 0 or "options" not in msg[0]:
raise CommandError("Failed to find options on %s" % ntds_guid) raise CommandError("Failed to find options on %s" % ntds_guid)
@ -870,14 +870,14 @@ class cmd_domain_demote(Command):
raise CommandError("Error while sending a DsReplicaSync for partition '%s'" % str(part), string) raise CommandError("Error while sending a DsReplicaSync for partition '%s'" % str(part), string)
try: try:
remote_samdb = SamDB(url="ldap://%s" % server, remote_samdb = SamDB(url="ldap://%s" % server,
session_info=system_session(), session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
self.errf.write("Changing userControl and container\n") self.errf.write("Changing userControl and container\n")
res = remote_samdb.search(base=str(remote_samdb.domain_dn()), res = remote_samdb.search(base=str(remote_samdb.domain_dn()),
expression="(&(objectClass=user)(sAMAccountName=%s$))" % expression="(&(objectClass=user)(sAMAccountName=%s$))" %
netbios_name.upper(), netbios_name.upper(),
attrs=["userAccountControl"]) attrs=["userAccountControl"])
dc_dn = res[0].dn dc_dn = res[0].dn
uac = int(str(res[0]["userAccountControl"])) uac = int(str(res[0]["userAccountControl"]))
@ -954,8 +954,8 @@ class cmd_domain_demote(Command):
msg.dn = dc_dn msg.dn = dc_dn
msg["userAccountControl"] = ldb.MessageElement("%d" % uac, msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
ldb.FLAG_MOD_REPLACE, ldb.FLAG_MOD_REPLACE,
"userAccountControl") "userAccountControl")
remote_samdb.modify(msg) remote_samdb.modify(msg)
@ -980,8 +980,8 @@ class cmd_domain_demote(Command):
msg.dn = dc_dn msg.dn = dc_dn
msg["userAccountControl"] = ldb.MessageElement("%d" % uac, msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
ldb.FLAG_MOD_REPLACE, ldb.FLAG_MOD_REPLACE,
"userAccountControl") "userAccountControl")
remote_samdb.modify(msg) remote_samdb.modify(msg)
raise CommandError("Error while renaming %s to %s" % (str(dc_dn), str(newdn)), e) raise CommandError("Error while renaming %s to %s" % (str(dc_dn), str(newdn)), e)
@ -1032,7 +1032,7 @@ class cmd_domain_demote(Command):
"CN=NTFRS Subscriptions"): "CN=NTFRS Subscriptions"):
try: try:
remote_samdb.delete(ldb.Dn(remote_samdb, remote_samdb.delete(ldb.Dn(remote_samdb,
"%s,%s" % (s, str(newdn)))) "%s,%s" % (s, str(newdn))))
except ldb.LdbError as l: except ldb.LdbError as l:
pass pass
@ -1059,10 +1059,10 @@ class cmd_domain_level(Command):
metavar="URL", dest="H"), metavar="URL", dest="H"),
Option("-q", "--quiet", help="Be quiet", action="store_true"), # unused Option("-q", "--quiet", help="Be quiet", action="store_true"), # unused
Option("--forest-level", type="choice", choices=["2003", "2008", "2008_R2", "2012", "2012_R2"], Option("--forest-level", type="choice", choices=["2003", "2008", "2008_R2", "2012", "2012_R2"],
help="The forest function level (2003 | 2008 | 2008_R2 | 2012 | 2012_R2)"), help="The forest function level (2003 | 2008 | 2008_R2 | 2012 | 2012_R2)"),
Option("--domain-level", type="choice", choices=["2003", "2008", "2008_R2", "2012", "2012_R2"], Option("--domain-level", type="choice", choices=["2003", "2008", "2008_R2", "2012", "2012_R2"],
help="The domain function level (2003 | 2008 | 2008_R2 | 2012 | 2012_R2)") help="The domain function level (2003 | 2008 | 2008_R2 | 2012 | 2012_R2)")
] ]
takes_args = ["subcommand"] takes_args = ["subcommand"]
@ -1072,21 +1072,21 @@ class cmd_domain_level(Command):
creds = credopts.get_credentials(lp, fallback_machine=True) creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
domain_dn = samdb.domain_dn() domain_dn = samdb.domain_dn()
res_forest = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(), res_forest = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(),
scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"]) scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
assert len(res_forest) == 1 assert len(res_forest) == 1
res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE, res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
attrs=["msDS-Behavior-Version", "nTMixedDomain"]) attrs=["msDS-Behavior-Version", "nTMixedDomain"])
assert len(res_domain) == 1 assert len(res_domain) == 1
res_dc_s = samdb.search("CN=Sites,%s" % samdb.get_config_basedn(), res_dc_s = samdb.search("CN=Sites,%s" % samdb.get_config_basedn(),
scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)", scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)",
attrs=["msDS-Behavior-Version"]) attrs=["msDS-Behavior-Version"])
assert len(res_dc_s) >= 1 assert len(res_dc_s) >= 1
# default values, since "msDS-Behavior-Version" does not exist on Windows 2000 AD # default values, since "msDS-Behavior-Version" does not exist on Windows 2000 AD
@ -1209,13 +1209,13 @@ class cmd_domain_level(Command):
m = ldb.Message() m = ldb.Message()
m.dn = ldb.Dn(samdb, domain_dn) m.dn = ldb.Dn(samdb, domain_dn)
m["nTMixedDomain"] = ldb.MessageElement("0", m["nTMixedDomain"] = ldb.MessageElement("0",
ldb.FLAG_MOD_REPLACE, "nTMixedDomain") ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
samdb.modify(m) samdb.modify(m)
# Under partitions # Under partitions
m = ldb.Message() m = ldb.Message()
m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") + ",CN=Partitions,%s" % samdb.get_config_basedn()) m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") + ",CN=Partitions,%s" % samdb.get_config_basedn())
m["nTMixedDomain"] = ldb.MessageElement("0", m["nTMixedDomain"] = ldb.MessageElement("0",
ldb.FLAG_MOD_REPLACE, "nTMixedDomain") ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
try: try:
samdb.modify(m) samdb.modify(m)
except ldb.LdbError as e: except ldb.LdbError as e:
@ -1233,7 +1233,7 @@ class cmd_domain_level(Command):
# Under partitions # Under partitions
m = ldb.Message() m = ldb.Message()
m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup")
+ ",CN=Partitions,%s" % samdb.get_config_basedn()) + ",CN=Partitions,%s" % samdb.get_config_basedn())
m["msDS-Behavior-Version"]= ldb.MessageElement( m["msDS-Behavior-Version"]= ldb.MessageElement(
str(new_level_domain), ldb.FLAG_MOD_REPLACE, str(new_level_domain), ldb.FLAG_MOD_REPLACE,
"msDS-Behavior-Version") "msDS-Behavior-Version")
@ -1297,13 +1297,13 @@ class cmd_domain_passwordsettings_show(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
domain_dn = samdb.domain_dn() domain_dn = samdb.domain_dn()
res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE, res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength", attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength",
"minPwdAge", "maxPwdAge", "lockoutDuration", "lockoutThreshold", "minPwdAge", "maxPwdAge", "lockoutDuration", "lockoutThreshold",
"lockOutObservationWindow"]) "lockOutObservationWindow"])
assert(len(res) == 1) assert(len(res) == 1)
try: try:
pwd_props = int(res[0]["pwdProperties"][0]) pwd_props = int(res[0]["pwdProperties"][0])
@ -1366,24 +1366,24 @@ class cmd_domain_passwordsettings_set(Command):
metavar="URL", dest="H"), metavar="URL", dest="H"),
Option("-q", "--quiet", help="Be quiet", action="store_true"), # unused Option("-q", "--quiet", help="Be quiet", action="store_true"), # unused
Option("--complexity", type="choice", choices=["on","off","default"], Option("--complexity", type="choice", choices=["on","off","default"],
help="The password complexity (on | off | default). Default is 'on'"), help="The password complexity (on | off | default). Default is 'on'"),
Option("--store-plaintext", type="choice", choices=["on","off","default"], Option("--store-plaintext", type="choice", choices=["on","off","default"],
help="Store plaintext passwords where account have 'store passwords with reversible encryption' set (on | off | default). Default is 'off'"), help="Store plaintext passwords where account have 'store passwords with reversible encryption' set (on | off | default). Default is 'off'"),
Option("--history-length", Option("--history-length",
help="The password history length (<integer> | default). Default is 24.", type=str), help="The password history length (<integer> | default). Default is 24.", type=str),
Option("--min-pwd-length", Option("--min-pwd-length",
help="The minimum password length (<integer> | default). Default is 7.", type=str), help="The minimum password length (<integer> | default). Default is 7.", type=str),
Option("--min-pwd-age", Option("--min-pwd-age",
help="The minimum password age (<integer in days> | default). Default is 1.", type=str), help="The minimum password age (<integer in days> | default). Default is 1.", type=str),
Option("--max-pwd-age", Option("--max-pwd-age",
help="The maximum password age (<integer in days> | default). Default is 43.", type=str), help="The maximum password age (<integer in days> | default). Default is 43.", type=str),
Option("--account-lockout-duration", Option("--account-lockout-duration",
help="The the length of time an account is locked out after exeeding the limit on bad password attempts (<integer in mins> | default). Default is 30 mins.", type=str), help="The the length of time an account is locked out after exeeding the limit on bad password attempts (<integer in mins> | default). Default is 30 mins.", type=str),
Option("--account-lockout-threshold", Option("--account-lockout-threshold",
help="The number of bad password attempts allowed before locking out the account (<integer> | default). Default is 0 (never lock out).", type=str), help="The number of bad password attempts allowed before locking out the account (<integer> | default). Default is 0 (never lock out).", type=str),
Option("--reset-account-lockout-after", Option("--reset-account-lockout-after",
help="After this time is elapsed, the recorded number of attempts restarts from zero (<integer> | default). Default is 30.", type=str), help="After this time is elapsed, the recorded number of attempts restarts from zero (<integer> | default). Default is 30.", type=str),
] ]
def run(self, H=None, min_pwd_age=None, max_pwd_age=None, def run(self, H=None, min_pwd_age=None, max_pwd_age=None,
quiet=False, complexity=None, store_plaintext=None, history_length=None, quiet=False, complexity=None, store_plaintext=None, history_length=None,
@ -1394,7 +1394,7 @@ class cmd_domain_passwordsettings_set(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
domain_dn = samdb.domain_dn() domain_dn = samdb.domain_dn()
msgs = [] msgs = []
@ -1420,7 +1420,7 @@ class cmd_domain_passwordsettings_set(Command):
if complexity is not None or store_plaintext is not None: if complexity is not None or store_plaintext is not None:
m["pwdProperties"] = ldb.MessageElement(str(pwd_props), m["pwdProperties"] = ldb.MessageElement(str(pwd_props),
ldb.FLAG_MOD_REPLACE, "pwdProperties") ldb.FLAG_MOD_REPLACE, "pwdProperties")
if history_length is not None: if history_length is not None:
if history_length == "default": if history_length == "default":
@ -1432,7 +1432,7 @@ class cmd_domain_passwordsettings_set(Command):
raise CommandError("Password history length must be in the range of 0 to 24!") raise CommandError("Password history length must be in the range of 0 to 24!")
m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len), m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len),
ldb.FLAG_MOD_REPLACE, "pwdHistoryLength") ldb.FLAG_MOD_REPLACE, "pwdHistoryLength")
msgs.append("Password history length changed!") msgs.append("Password history length changed!")
if min_pwd_length is not None: if min_pwd_length is not None:
@ -1445,7 +1445,7 @@ class cmd_domain_passwordsettings_set(Command):
raise CommandError("Minimum password length must be in the range of 0 to 14!") raise CommandError("Minimum password length must be in the range of 0 to 14!")
m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len), m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len),
ldb.FLAG_MOD_REPLACE, "minPwdLength") ldb.FLAG_MOD_REPLACE, "minPwdLength")
msgs.append("Minimum password length changed!") msgs.append("Minimum password length changed!")
if min_pwd_age is not None: if min_pwd_age is not None:
@ -1461,7 +1461,7 @@ class cmd_domain_passwordsettings_set(Command):
min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7)) min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7))
m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks), m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks),
ldb.FLAG_MOD_REPLACE, "minPwdAge") ldb.FLAG_MOD_REPLACE, "minPwdAge")
msgs.append("Minimum password age changed!") msgs.append("Minimum password age changed!")
if max_pwd_age is not None: if max_pwd_age is not None:
@ -1480,7 +1480,7 @@ class cmd_domain_passwordsettings_set(Command):
max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7)) max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7))
m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks), m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks),
ldb.FLAG_MOD_REPLACE, "maxPwdAge") ldb.FLAG_MOD_REPLACE, "maxPwdAge")
msgs.append("Maximum password age changed!") msgs.append("Maximum password age changed!")
if account_lockout_duration is not None: if account_lockout_duration is not None:
@ -1499,7 +1499,7 @@ class cmd_domain_passwordsettings_set(Command):
account_lockout_duration_ticks = -int(account_lockout_duration * (60 * 1e7)) account_lockout_duration_ticks = -int(account_lockout_duration * (60 * 1e7))
m["lockoutDuration"] = ldb.MessageElement(str(account_lockout_duration_ticks), m["lockoutDuration"] = ldb.MessageElement(str(account_lockout_duration_ticks),
ldb.FLAG_MOD_REPLACE, "lockoutDuration") ldb.FLAG_MOD_REPLACE, "lockoutDuration")
msgs.append("Account lockout duration changed!") msgs.append("Account lockout duration changed!")
if account_lockout_threshold is not None: if account_lockout_threshold is not None:
@ -1509,7 +1509,7 @@ class cmd_domain_passwordsettings_set(Command):
account_lockout_threshold = int(account_lockout_threshold) account_lockout_threshold = int(account_lockout_threshold)
m["lockoutThreshold"] = ldb.MessageElement(str(account_lockout_threshold), m["lockoutThreshold"] = ldb.MessageElement(str(account_lockout_threshold),
ldb.FLAG_MOD_REPLACE, "lockoutThreshold") ldb.FLAG_MOD_REPLACE, "lockoutThreshold")
msgs.append("Account lockout threshold changed!") msgs.append("Account lockout threshold changed!")
if reset_account_lockout_after is not None: if reset_account_lockout_after is not None:
@ -1528,7 +1528,7 @@ class cmd_domain_passwordsettings_set(Command):
reset_account_lockout_after_ticks = -int(reset_account_lockout_after * (60 * 1e7)) reset_account_lockout_after_ticks = -int(reset_account_lockout_after * (60 * 1e7))
m["lockOutObservationWindow"] = ldb.MessageElement(str(reset_account_lockout_after_ticks), m["lockOutObservationWindow"] = ldb.MessageElement(str(reset_account_lockout_after_ticks),
ldb.FLAG_MOD_REPLACE, "lockOutObservationWindow") ldb.FLAG_MOD_REPLACE, "lockOutObservationWindow")
msgs.append("Duration to reset account lockout after changed!") msgs.append("Duration to reset account lockout after changed!")
if max_pwd_age and max_pwd_age > 0 and min_pwd_age >= max_pwd_age: if max_pwd_age and max_pwd_age > 0 and min_pwd_age >= max_pwd_age:
@ -1649,7 +1649,7 @@ class cmd_domain_classicupgrade(Command):
try: try:
try: try:
samba.ntacls.setntacl(lp, tmpfile.name, samba.ntacls.setntacl(lp, tmpfile.name,
"O:S-1-5-32G:S-1-5-32", "S-1-5-32", "native") "O:S-1-5-32G:S-1-5-32", "S-1-5-32", "native")
eadb = False eadb = False
except Exception: except Exception:
# FIXME: Don't catch all exceptions here # FIXME: Don't catch all exceptions here
@ -1848,7 +1848,7 @@ class DomainTrustCommand(Command):
nbt.NBT_SERVER_FOREST_ROOT: "FOREST_ROOT", nbt.NBT_SERVER_FOREST_ROOT: "FOREST_ROOT",
} }
server_type_string = self.generic_bitmap_to_string(flag_map, server_type_string = self.generic_bitmap_to_string(flag_map,
remote_info.server_type, names_only=True) remote_info.server_type, names_only=True)
self.outf.write("RemoteDC Netbios[%s] DNS[%s] ServerType[%s]\n" % ( self.outf.write("RemoteDC Netbios[%s] DNS[%s] ServerType[%s]\n" % (
remote_info.pdc_name, remote_info.pdc_name,
remote_info.pdc_dns_name, remote_info.pdc_dns_name,
@ -2109,10 +2109,11 @@ class cmd_domain_trust_list(DomainTrustCommand):
raise self.LocalRuntimeError(self, error, "failed to connect netlogon server") raise self.LocalRuntimeError(self, error, "failed to connect netlogon server")
try: try:
local_netlogon_trusts = local_netlogon.netr_DsrEnumerateDomainTrusts(local_server, local_netlogon_trusts = \
netlogon.NETR_TRUST_FLAG_IN_FOREST | local_netlogon.netr_DsrEnumerateDomainTrusts(local_server,
netlogon.NETR_TRUST_FLAG_OUTBOUND | netlogon.NETR_TRUST_FLAG_IN_FOREST |
netlogon.NETR_TRUST_FLAG_INBOUND) netlogon.NETR_TRUST_FLAG_OUTBOUND |
netlogon.NETR_TRUST_FLAG_INBOUND)
except RuntimeError as error: except RuntimeError as error:
if self.check_runtime_error(error, werror.WERR_RPC_S_PROCNUM_OUT_OF_RANGE): if self.check_runtime_error(error, werror.WERR_RPC_S_PROCNUM_OUT_OF_RANGE):
# TODO: we could implement a fallback to lsa.EnumTrustDom() # TODO: we could implement a fallback to lsa.EnumTrustDom()
@ -2169,8 +2170,10 @@ class cmd_domain_trust_show(DomainTrustCommand):
lsaString = lsa.String() lsaString = lsa.String()
lsaString.string = domain lsaString.string = domain
try: try:
local_tdo_full = local_lsa.QueryTrustedDomainInfoByName(local_policy, local_tdo_full = \
lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) local_lsa.QueryTrustedDomainInfoByName(local_policy,
lsaString,
lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
local_tdo_info = local_tdo_full.info_ex local_tdo_info = local_tdo_full.info_ex
local_tdo_posix = local_tdo_full.posix_offset local_tdo_posix = local_tdo_full.posix_offset
except NTSTATUSError as error: except NTSTATUSError as error:
@ -2180,8 +2183,10 @@ class cmd_domain_trust_show(DomainTrustCommand):
raise self.LocalRuntimeError(self, error, "QueryTrustedDomainInfoByName(FULL_INFO) failed") raise self.LocalRuntimeError(self, error, "QueryTrustedDomainInfoByName(FULL_INFO) failed")
try: try:
local_tdo_enctypes = local_lsa.QueryTrustedDomainInfoByName(local_policy, local_tdo_enctypes = \
lsaString, lsa.LSA_TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES) local_lsa.QueryTrustedDomainInfoByName(local_policy,
lsaString,
lsa.LSA_TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES)
except NTSTATUSError as error: except NTSTATUSError as error:
if self.check_runtime_error(error, ntstatus.NT_STATUS_INVALID_PARAMETER): if self.check_runtime_error(error, ntstatus.NT_STATUS_INVALID_PARAMETER):
error = None error = None
@ -2190,7 +2195,7 @@ class cmd_domain_trust_show(DomainTrustCommand):
if error is not None: if error is not None:
raise self.LocalRuntimeError(self, error, raise self.LocalRuntimeError(self, error,
"QueryTrustedDomainInfoByName(SUPPORTED_ENCRYPTION_TYPES) failed") "QueryTrustedDomainInfoByName(SUPPORTED_ENCRYPTION_TYPES) failed")
local_tdo_enctypes = lsa.TrustDomainInfoSupportedEncTypes() local_tdo_enctypes = lsa.TrustDomainInfoSupportedEncTypes()
local_tdo_enctypes.enc_types = 0 local_tdo_enctypes.enc_types = 0
@ -2198,8 +2203,10 @@ class cmd_domain_trust_show(DomainTrustCommand):
try: try:
local_tdo_forest = None local_tdo_forest = None
if local_tdo_info.trust_attributes & lsa.LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE: if local_tdo_info.trust_attributes & lsa.LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE:
local_tdo_forest = local_lsa.lsaRQueryForestTrustInformation(local_policy, local_tdo_forest = \
lsaString, lsa.LSA_FOREST_TRUST_DOMAIN_INFO) local_lsa.lsaRQueryForestTrustInformation(local_policy,
lsaString,
lsa.LSA_FOREST_TRUST_DOMAIN_INFO)
except RuntimeError as error: except RuntimeError as error:
if self.check_runtime_error(error, ntstatus.NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE): if self.check_runtime_error(error, ntstatus.NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE):
error = None error = None
@ -2458,47 +2465,55 @@ class cmd_domain_trust_create(DomainTrustCommand):
try: try:
lsaString.string = local_trust_info.domain_name.string lsaString.string = local_trust_info.domain_name.string
local_old_netbios = local_lsa.QueryTrustedDomainInfoByName(local_policy, local_old_netbios = \
lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) local_lsa.QueryTrustedDomainInfoByName(local_policy,
lsaString,
lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
raise CommandError("TrustedDomain %s already exist'" % lsaString.string) raise CommandError("TrustedDomain %s already exist'" % lsaString.string)
except NTSTATUSError as error: except NTSTATUSError as error:
if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND): if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND):
raise self.LocalRuntimeError(self, error, raise self.LocalRuntimeError(self, error,
"QueryTrustedDomainInfoByName(%s, FULL_INFO) failed" % ( "QueryTrustedDomainInfoByName(%s, FULL_INFO) failed" % (
lsaString.string)) lsaString.string))
try: try:
lsaString.string = local_trust_info.netbios_name.string lsaString.string = local_trust_info.netbios_name.string
local_old_dns = local_lsa.QueryTrustedDomainInfoByName(local_policy, local_old_dns = \
lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) local_lsa.QueryTrustedDomainInfoByName(local_policy,
lsaString,
lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
raise CommandError("TrustedDomain %s already exist'" % lsaString.string) raise CommandError("TrustedDomain %s already exist'" % lsaString.string)
except NTSTATUSError as error: except NTSTATUSError as error:
if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND): if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND):
raise self.LocalRuntimeError(self, error, raise self.LocalRuntimeError(self, error,
"QueryTrustedDomainInfoByName(%s, FULL_INFO) failed" % ( "QueryTrustedDomainInfoByName(%s, FULL_INFO) failed" % (
lsaString.string)) lsaString.string))
if remote_trust_info: if remote_trust_info:
try: try:
lsaString.string = remote_trust_info.domain_name.string lsaString.string = remote_trust_info.domain_name.string
remote_old_netbios = remote_lsa.QueryTrustedDomainInfoByName(remote_policy, remote_old_netbios = \
lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) remote_lsa.QueryTrustedDomainInfoByName(remote_policy,
lsaString,
lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
raise CommandError("TrustedDomain %s already exist'" % lsaString.string) raise CommandError("TrustedDomain %s already exist'" % lsaString.string)
except NTSTATUSError as error: except NTSTATUSError as error:
if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND): if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND):
raise self.RemoteRuntimeError(self, error, raise self.RemoteRuntimeError(self, error,
"QueryTrustedDomainInfoByName(%s, FULL_INFO) failed" % ( "QueryTrustedDomainInfoByName(%s, FULL_INFO) failed" % (
lsaString.string)) lsaString.string))
try: try:
lsaString.string = remote_trust_info.netbios_name.string lsaString.string = remote_trust_info.netbios_name.string
remote_old_dns = remote_lsa.QueryTrustedDomainInfoByName(remote_policy, remote_old_dns = \
lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO) remote_lsa.QueryTrustedDomainInfoByName(remote_policy,
lsaString,
lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
raise CommandError("TrustedDomain %s already exist'" % lsaString.string) raise CommandError("TrustedDomain %s already exist'" % lsaString.string)
except NTSTATUSError as error: except NTSTATUSError as error:
if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND): if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND):
raise self.RemoteRuntimeError(self, error, raise self.RemoteRuntimeError(self, error,
"QueryTrustedDomainInfoByName(%s, FULL_INFO) failed" % ( "QueryTrustedDomainInfoByName(%s, FULL_INFO) failed" % (
lsaString.string)) lsaString.string))
try: try:
@ -2592,10 +2607,11 @@ class cmd_domain_trust_create(DomainTrustCommand):
if remote_trust_info: if remote_trust_info:
self.outf.write("Creating remote TDO.\n") self.outf.write("Creating remote TDO.\n")
current_request = { "location": "remote", "name": "CreateTrustedDomainEx2"} current_request = { "location": "remote", "name": "CreateTrustedDomainEx2"}
remote_tdo_handle = remote_lsa.CreateTrustedDomainEx2(remote_policy, remote_tdo_handle = \
remote_trust_info, remote_lsa.CreateTrustedDomainEx2(remote_policy,
remote_auth_info, remote_trust_info,
lsa.LSA_TRUSTED_DOMAIN_ALL_ACCESS) remote_auth_info,
lsa.LSA_TRUSTED_DOMAIN_ALL_ACCESS)
self.outf.write("Remote TDO created.\n") self.outf.write("Remote TDO created.\n")
if enc_types: if enc_types:
self.outf.write("Setting supported encryption types on remote TDO.\n") self.outf.write("Setting supported encryption types on remote TDO.\n")
@ -2642,19 +2658,21 @@ class cmd_domain_trust_create(DomainTrustCommand):
# this triggers netr_GetForestTrustInformation to the remote domain # this triggers netr_GetForestTrustInformation to the remote domain
# and lsaRSetForestTrustInformation() locally, but new top level # and lsaRSetForestTrustInformation() locally, but new top level
# names are disabled by default. # names are disabled by default.
local_forest_info = local_netlogon.netr_DsRGetForestTrustInformation(local_netlogon_info.dc_unc, local_forest_info = \
remote_lsa_info.dns_domain.string, local_netlogon.netr_DsRGetForestTrustInformation(local_netlogon_info.dc_unc,
netlogon.DS_GFTI_UPDATE_TDO) remote_lsa_info.dns_domain.string,
netlogon.DS_GFTI_UPDATE_TDO)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "netr_DsRGetForestTrustInformation() failed") raise self.LocalRuntimeError(self, error, "netr_DsRGetForestTrustInformation() failed")
try: try:
# here we try to enable all top level names # here we try to enable all top level names
local_forest_collision = local_lsa.lsaRSetForestTrustInformation(local_policy, local_forest_collision = \
remote_lsa_info.dns_domain, local_lsa.lsaRSetForestTrustInformation(local_policy,
lsa.LSA_FOREST_TRUST_DOMAIN_INFO, remote_lsa_info.dns_domain,
local_forest_info, lsa.LSA_FOREST_TRUST_DOMAIN_INFO,
0) local_forest_info,
0)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "lsaRSetForestTrustInformation() failed") raise self.LocalRuntimeError(self, error, "lsaRSetForestTrustInformation() failed")
@ -2669,19 +2687,21 @@ class cmd_domain_trust_create(DomainTrustCommand):
# this triggers netr_GetForestTrustInformation to our domain. # this triggers netr_GetForestTrustInformation to our domain.
# and lsaRSetForestTrustInformation() remotely, but new top level # and lsaRSetForestTrustInformation() remotely, but new top level
# names are disabled by default. # names are disabled by default.
remote_forest_info = remote_netlogon.netr_DsRGetForestTrustInformation(remote_netlogon_dc_unc, remote_forest_info = \
local_lsa_info.dns_domain.string, remote_netlogon.netr_DsRGetForestTrustInformation(remote_netlogon_dc_unc,
netlogon.DS_GFTI_UPDATE_TDO) local_lsa_info.dns_domain.string,
netlogon.DS_GFTI_UPDATE_TDO)
except RuntimeError as error: except RuntimeError as error:
raise self.RemoteRuntimeError(self, error, "netr_DsRGetForestTrustInformation() failed") raise self.RemoteRuntimeError(self, error, "netr_DsRGetForestTrustInformation() failed")
try: try:
# here we try to enable all top level names # here we try to enable all top level names
remote_forest_collision = remote_lsa.lsaRSetForestTrustInformation(remote_policy, remote_forest_collision = \
local_lsa_info.dns_domain, remote_lsa.lsaRSetForestTrustInformation(remote_policy,
lsa.LSA_FOREST_TRUST_DOMAIN_INFO, local_lsa_info.dns_domain,
remote_forest_info, lsa.LSA_FOREST_TRUST_DOMAIN_INFO,
0) remote_forest_info,
0)
except RuntimeError as error: except RuntimeError as error:
raise self.RemoteRuntimeError(self, error, "lsaRSetForestTrustInformation() failed") raise self.RemoteRuntimeError(self, error, "lsaRSetForestTrustInformation() failed")
@ -2693,9 +2713,9 @@ class cmd_domain_trust_create(DomainTrustCommand):
self.outf.write("Validating outgoing trust...\n") self.outf.write("Validating outgoing trust...\n")
try: try:
local_trust_verify = local_netlogon.netr_LogonControl2Ex(local_netlogon_info.dc_unc, local_trust_verify = local_netlogon.netr_LogonControl2Ex(local_netlogon_info.dc_unc,
netlogon.NETLOGON_CONTROL_TC_VERIFY, netlogon.NETLOGON_CONTROL_TC_VERIFY,
2, 2,
remote_lsa_info.dns_domain.string) remote_lsa_info.dns_domain.string)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "NETLOGON_CONTROL_TC_VERIFY failed") raise self.LocalRuntimeError(self, error, "NETLOGON_CONTROL_TC_VERIFY failed")
@ -2722,10 +2742,11 @@ class cmd_domain_trust_create(DomainTrustCommand):
if remote_trust_info.trust_direction & lsa.LSA_TRUST_DIRECTION_OUTBOUND: if remote_trust_info.trust_direction & lsa.LSA_TRUST_DIRECTION_OUTBOUND:
self.outf.write("Validating incoming trust...\n") self.outf.write("Validating incoming trust...\n")
try: try:
remote_trust_verify = remote_netlogon.netr_LogonControl2Ex(remote_netlogon_dc_unc, remote_trust_verify = \
netlogon.NETLOGON_CONTROL_TC_VERIFY, remote_netlogon.netr_LogonControl2Ex(remote_netlogon_dc_unc,
2, netlogon.NETLOGON_CONTROL_TC_VERIFY,
local_lsa_info.dns_domain.string) 2,
local_lsa_info.dns_domain.string)
except RuntimeError as error: except RuntimeError as error:
raise self.RemoteRuntimeError(self, error, "NETLOGON_CONTROL_TC_VERIFY failed") raise self.RemoteRuntimeError(self, error, "NETLOGON_CONTROL_TC_VERIFY failed")
@ -2825,7 +2846,7 @@ class cmd_domain_trust_delete(DomainTrustCommand):
try: try:
lsaString.string = domain lsaString.string = domain
local_tdo_info = local_lsa.QueryTrustedDomainInfoByName(local_policy, local_tdo_info = local_lsa.QueryTrustedDomainInfoByName(local_policy,
lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX) lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX)
except NTSTATUSError as error: except NTSTATUSError as error:
if self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND): if self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND):
raise CommandError("Failed to find trust for domain '%s'" % domain) raise CommandError("Failed to find trust for domain '%s'" % domain)
@ -2863,8 +2884,10 @@ class cmd_domain_trust_delete(DomainTrustCommand):
try: try:
lsaString.string = local_lsa_info.dns_domain.string lsaString.string = local_lsa_info.dns_domain.string
remote_tdo_info = remote_lsa.QueryTrustedDomainInfoByName(remote_policy, remote_tdo_info = \
lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX) remote_lsa.QueryTrustedDomainInfoByName(remote_policy,
lsaString,
lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX)
except NTSTATUSError as error: except NTSTATUSError as error:
if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND): if not self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND):
raise self.RemoteRuntimeError(self, error, "QueryTrustedDomainInfoByName(%s)" % ( raise self.RemoteRuntimeError(self, error, "QueryTrustedDomainInfoByName(%s)" % (
@ -2883,9 +2906,10 @@ class cmd_domain_trust_delete(DomainTrustCommand):
if local_tdo_info is not None: if local_tdo_info is not None:
try: try:
lsaString.string = local_tdo_info.domain_name.string lsaString.string = local_tdo_info.domain_name.string
local_tdo_handle = local_lsa.OpenTrustedDomainByName(local_policy, local_tdo_handle = \
lsaString, local_lsa.OpenTrustedDomainByName(local_policy,
security.SEC_STD_DELETE) lsaString,
security.SEC_STD_DELETE)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "OpenTrustedDomainByName(%s)" % ( raise self.LocalRuntimeError(self, error, "OpenTrustedDomainByName(%s)" % (
lsaString.string)) lsaString.string))
@ -2896,9 +2920,10 @@ class cmd_domain_trust_delete(DomainTrustCommand):
if remote_tdo_info is not None: if remote_tdo_info is not None:
try: try:
lsaString.string = remote_tdo_info.domain_name.string lsaString.string = remote_tdo_info.domain_name.string
remote_tdo_handle = remote_lsa.OpenTrustedDomainByName(remote_policy, remote_tdo_handle = \
lsaString, remote_lsa.OpenTrustedDomainByName(remote_policy,
security.SEC_STD_DELETE) lsaString,
security.SEC_STD_DELETE)
except RuntimeError as error: except RuntimeError as error:
raise self.RemoteRuntimeError(self, error, "OpenTrustedDomainByName(%s)" % ( raise self.RemoteRuntimeError(self, error, "OpenTrustedDomainByName(%s)" % (
lsaString.string)) lsaString.string))
@ -2967,8 +2992,10 @@ class cmd_domain_trust_validate(DomainTrustCommand):
try: try:
lsaString = lsa.String() lsaString = lsa.String()
lsaString.string = domain lsaString.string = domain
local_tdo_info = local_lsa.QueryTrustedDomainInfoByName(local_policy, local_tdo_info = \
lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX) local_lsa.QueryTrustedDomainInfoByName(local_policy,
lsaString,
lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX)
except NTSTATUSError as error: except NTSTATUSError as error:
if self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND): if self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND):
raise CommandError("trusted domain object does not exist for domain [%s]" % domain) raise CommandError("trusted domain object does not exist for domain [%s]" % domain)
@ -2986,10 +3013,11 @@ class cmd_domain_trust_validate(DomainTrustCommand):
raise self.LocalRuntimeError(self, error, "failed to connect netlogon server") raise self.LocalRuntimeError(self, error, "failed to connect netlogon server")
try: try:
local_trust_verify = local_netlogon.netr_LogonControl2Ex(local_server, local_trust_verify = \
netlogon.NETLOGON_CONTROL_TC_VERIFY, local_netlogon.netr_LogonControl2Ex(local_server,
2, netlogon.NETLOGON_CONTROL_TC_VERIFY,
local_tdo_info.domain_name.string) 2,
local_tdo_info.domain_name.string)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "NETLOGON_CONTROL_TC_VERIFY failed") raise self.LocalRuntimeError(self, error, "NETLOGON_CONTROL_TC_VERIFY failed")
@ -3015,10 +3043,11 @@ class cmd_domain_trust_validate(DomainTrustCommand):
try: try:
server = local_trust_verify.trusted_dc_name.replace('\\', '') server = local_trust_verify.trusted_dc_name.replace('\\', '')
domain_and_server = "%s\\%s" % (local_tdo_info.domain_name.string, server) domain_and_server = "%s\\%s" % (local_tdo_info.domain_name.string, server)
local_trust_rediscover = local_netlogon.netr_LogonControl2Ex(local_server, local_trust_rediscover = \
netlogon.NETLOGON_CONTROL_REDISCOVER, local_netlogon.netr_LogonControl2Ex(local_server,
2, netlogon.NETLOGON_CONTROL_REDISCOVER,
domain_and_server) 2,
domain_and_server)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "NETLOGON_CONTROL_REDISCOVER failed") raise self.LocalRuntimeError(self, error, "NETLOGON_CONTROL_REDISCOVER failed")
@ -3044,10 +3073,11 @@ class cmd_domain_trust_validate(DomainTrustCommand):
raise self.RemoteRuntimeError(self, error, "failed to connect netlogon server") raise self.RemoteRuntimeError(self, error, "failed to connect netlogon server")
try: try:
remote_trust_verify = remote_netlogon.netr_LogonControl2Ex(remote_server, remote_trust_verify = \
netlogon.NETLOGON_CONTROL_TC_VERIFY, remote_netlogon.netr_LogonControl2Ex(remote_server,
2, netlogon.NETLOGON_CONTROL_TC_VERIFY,
local_lsa_info.dns_domain.string) 2,
local_lsa_info.dns_domain.string)
except RuntimeError as error: except RuntimeError as error:
raise self.RemoteRuntimeError(self, error, "NETLOGON_CONTROL_TC_VERIFY failed") raise self.RemoteRuntimeError(self, error, "NETLOGON_CONTROL_TC_VERIFY failed")
@ -3073,10 +3103,11 @@ class cmd_domain_trust_validate(DomainTrustCommand):
try: try:
server = remote_trust_verify.trusted_dc_name.replace('\\', '') server = remote_trust_verify.trusted_dc_name.replace('\\', '')
domain_and_server = "%s\\%s" % (local_lsa_info.dns_domain.string, server) domain_and_server = "%s\\%s" % (local_lsa_info.dns_domain.string, server)
remote_trust_rediscover = remote_netlogon.netr_LogonControl2Ex(remote_server, remote_trust_rediscover = \
netlogon.NETLOGON_CONTROL_REDISCOVER, remote_netlogon.netr_LogonControl2Ex(remote_server,
2, netlogon.NETLOGON_CONTROL_REDISCOVER,
domain_and_server) 2,
domain_and_server)
except RuntimeError as error: except RuntimeError as error:
raise self.RemoteRuntimeError(self, error, "NETLOGON_CONTROL_REDISCOVER failed") raise self.RemoteRuntimeError(self, error, "NETLOGON_CONTROL_REDISCOVER failed")
@ -3529,8 +3560,10 @@ class cmd_domain_trust_namespaces(DomainTrustCommand):
try: try:
lsaString = lsa.String() lsaString = lsa.String()
lsaString.string = domain lsaString.string = domain
local_tdo_info = local_lsa.QueryTrustedDomainInfoByName(local_policy, local_tdo_info = \
lsaString, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX) local_lsa.QueryTrustedDomainInfoByName(local_policy,
lsaString,
lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX)
except NTSTATUSError as error: except NTSTATUSError as error:
if self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND): if self.check_runtime_error(error, ntstatus.NT_STATUS_OBJECT_NAME_NOT_FOUND):
raise CommandError("trusted domain object does not exist for domain [%s]" % domain) raise CommandError("trusted domain object does not exist for domain [%s]" % domain)
@ -3569,18 +3602,20 @@ class cmd_domain_trust_namespaces(DomainTrustCommand):
# this triggers netr_GetForestTrustInformation to the remote domain # this triggers netr_GetForestTrustInformation to the remote domain
# and lsaRSetForestTrustInformation() locally, but new top level # and lsaRSetForestTrustInformation() locally, but new top level
# names are disabled by default. # names are disabled by default.
fresh_forest_info = local_netlogon.netr_DsRGetForestTrustInformation(local_netlogon_info.dc_unc, fresh_forest_info = \
local_tdo_info.domain_name.string, local_netlogon.netr_DsRGetForestTrustInformation(local_netlogon_info.dc_unc,
netlogon_update_tdo) local_tdo_info.domain_name.string,
netlogon_update_tdo)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "netr_DsRGetForestTrustInformation() failed") raise self.LocalRuntimeError(self, error, "netr_DsRGetForestTrustInformation() failed")
try: try:
fresh_forest_collision = local_lsa.lsaRSetForestTrustInformation(local_policy, fresh_forest_collision = \
local_tdo_info.domain_name, local_lsa.lsaRSetForestTrustInformation(local_policy,
lsa.LSA_FOREST_TRUST_DOMAIN_INFO, local_tdo_info.domain_name,
fresh_forest_info, lsa.LSA_FOREST_TRUST_DOMAIN_INFO,
lsa_update_check) fresh_forest_info,
lsa_update_check)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "lsaRSetForestTrustInformation() failed") raise self.LocalRuntimeError(self, error, "lsaRSetForestTrustInformation() failed")
@ -3593,7 +3628,8 @@ class cmd_domain_trust_namespaces(DomainTrustCommand):
try: try:
lsaString = lsa.String() lsaString = lsa.String()
lsaString.string = local_tdo_info.domain_name.string lsaString.string = local_tdo_info.domain_name.string
stored_forest_info = local_lsa.lsaRQueryForestTrustInformation(local_policy, stored_forest_info = \
local_lsa.lsaRQueryForestTrustInformation(local_policy,
lsaString, lsaString,
lsa.LSA_FOREST_TRUST_DOMAIN_INFO) lsa.LSA_FOREST_TRUST_DOMAIN_INFO)
except RuntimeError as error: except RuntimeError as error:
@ -3612,9 +3648,10 @@ class cmd_domain_trust_namespaces(DomainTrustCommand):
try: try:
lsaString = lsa.String() lsaString = lsa.String()
lsaString.string = local_tdo_info.domain_name.string lsaString.string = local_tdo_info.domain_name.string
local_forest_info = local_lsa.lsaRQueryForestTrustInformation(local_policy, local_forest_info = \
lsaString, local_lsa.lsaRQueryForestTrustInformation(local_policy,
lsa.LSA_FOREST_TRUST_DOMAIN_INFO) lsaString,
lsa.LSA_FOREST_TRUST_DOMAIN_INFO)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "lsaRQueryForestTrustInformation() failed") raise self.LocalRuntimeError(self, error, "lsaRQueryForestTrustInformation() failed")
@ -3807,9 +3844,9 @@ class cmd_domain_trust_namespaces(DomainTrustCommand):
try: try:
update_forest_collision = local_lsa.lsaRSetForestTrustInformation(local_policy, update_forest_collision = local_lsa.lsaRSetForestTrustInformation(local_policy,
local_tdo_info.domain_name, local_tdo_info.domain_name,
lsa.LSA_FOREST_TRUST_DOMAIN_INFO, lsa.LSA_FOREST_TRUST_DOMAIN_INFO,
update_forest_info, 0) update_forest_info, 0)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "lsaRSetForestTrustInformation() failed") raise self.LocalRuntimeError(self, error, "lsaRSetForestTrustInformation() failed")
@ -3822,8 +3859,8 @@ class cmd_domain_trust_namespaces(DomainTrustCommand):
lsaString = lsa.String() lsaString = lsa.String()
lsaString.string = local_tdo_info.domain_name.string lsaString.string = local_tdo_info.domain_name.string
stored_forest_info = local_lsa.lsaRQueryForestTrustInformation(local_policy, stored_forest_info = local_lsa.lsaRQueryForestTrustInformation(local_policy,
lsaString, lsaString,
lsa.LSA_FOREST_TRUST_DOMAIN_INFO) lsa.LSA_FOREST_TRUST_DOMAIN_INFO)
except RuntimeError as error: except RuntimeError as error:
raise self.LocalRuntimeError(self, error, "lsaRQueryForestTrustInformation() failed") raise self.LocalRuntimeError(self, error, "lsaRQueryForestTrustInformation() failed")
@ -3876,7 +3913,7 @@ This command expunges tombstones from the database."""
if len(ncs) == 0: if len(ncs) == 0:
res = samdb.search(expression="", base="", scope=ldb.SCOPE_BASE, res = samdb.search(expression="", base="", scope=ldb.SCOPE_BASE,
attrs=["namingContexts"]) attrs=["namingContexts"])
ncs = [] ncs = []
for nc in res[0]["namingContexts"]: for nc in res[0]["namingContexts"]:
@ -4288,7 +4325,7 @@ class cmd_domain_functional_prep(Command):
domain_dn = samdb.domain_dn() domain_dn = samdb.domain_dn()
infrastructure_dn = "CN=Infrastructure," + domain_dn infrastructure_dn = "CN=Infrastructure," + domain_dn
master = get_fsmo_roleowner(samdb, infrastructure_dn, master = get_fsmo_roleowner(samdb, infrastructure_dn,
'infrastructure') 'infrastructure')
if own_dn != master: if own_dn != master:
raise CommandError("This server is not the infrastructure master.") raise CommandError("This server is not the infrastructure master.")

View File

@ -76,16 +76,16 @@ class cmd_dsacl_set(Command):
Option("--action", type="choice", choices=["allow", "deny"], Option("--action", type="choice", choices=["allow", "deny"],
help="""Deny or allow access"""), help="""Deny or allow access"""),
Option("--objectdn", help="DN of the object whose SD to modify", Option("--objectdn", help="DN of the object whose SD to modify",
type="string"), type="string"),
Option("--trusteedn", help="DN of the entity that gets access", Option("--trusteedn", help="DN of the entity that gets access",
type="string"), type="string"),
Option("--sddl", help="An ACE or group of ACEs to be added on the object", Option("--sddl", help="An ACE or group of ACEs to be added on the object",
type="string"), type="string"),
] ]
def find_trustee_sid(self, samdb, trusteedn): def find_trustee_sid(self, samdb, trusteedn):
res = samdb.search(base=trusteedn, expression="(objectClass=*)", res = samdb.search(base=trusteedn, expression="(objectClass=*)",
scope=SCOPE_BASE) scope=SCOPE_BASE)
assert(len(res) == 1) assert(len(res) == 1)
return ndr_unpack( security.dom_sid,res[0]["objectSid"][0]) return ndr_unpack( security.dom_sid,res[0]["objectSid"][0])
@ -100,7 +100,7 @@ class cmd_dsacl_set(Command):
def read_descriptor(self, samdb, object_dn): def read_descriptor(self, samdb, object_dn):
res = samdb.search(base=object_dn, scope=SCOPE_BASE, res = samdb.search(base=object_dn, scope=SCOPE_BASE,
attrs=["nTSecurityDescriptor"]) attrs=["nTSecurityDescriptor"])
# we should theoretically always have an SD # we should theoretically always have an SD
assert(len(res) == 1) assert(len(res) == 1)
desc = res[0]["nTSecurityDescriptor"][0] desc = res[0]["nTSecurityDescriptor"][0]
@ -108,7 +108,7 @@ class cmd_dsacl_set(Command):
def get_domain_sid(self, samdb): def get_domain_sid(self, samdb):
res = samdb.search(base=samdb.domain_dn(), res = samdb.search(base=samdb.domain_dn(),
expression="(objectClass=*)", scope=SCOPE_BASE) expression="(objectClass=*)", scope=SCOPE_BASE)
return ndr_unpack( security.dom_sid,res[0]["objectSid"][0]) return ndr_unpack( security.dom_sid,res[0]["objectSid"][0])
def add_ace(self, samdb, object_dn, new_ace): def add_ace(self, samdb, object_dn, new_ace):
@ -145,7 +145,7 @@ class cmd_dsacl_set(Command):
return self.usage() return self.usage()
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
cars = {'change-rid' : GUID_DRS_CHANGE_RID_MASTER, cars = {'change-rid' : GUID_DRS_CHANGE_RID_MASTER,
'change-pdc' : GUID_DRS_CHANGE_PDC, 'change-pdc' : GUID_DRS_CHANGE_PDC,
'change-infrastructure' : GUID_DRS_CHANGE_INFR_MASTER, 'change-infrastructure' : GUID_DRS_CHANGE_INFR_MASTER,

View File

@ -53,7 +53,7 @@ class cmd_forest_show(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
domain_dn = samdb.domain_dn() domain_dn = samdb.domain_dn()
object_dn = "%s,%s" % (self.objectdn, domain_dn) object_dn = "%s,%s" % (self.objectdn, domain_dn)
@ -103,7 +103,7 @@ class cmd_forest_set(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
domain_dn = samdb.domain_dn() domain_dn = samdb.domain_dn()
object_dn = "%s,%s" % (self.objectdn, domain_dn) object_dn = "%s,%s" % (self.objectdn, domain_dn)

View File

@ -72,8 +72,8 @@ def transfer_dns_role(outf, sambaopts, credopts, role, samdb):
if 'fSMORoleOwner' in res[0]: if 'fSMORoleOwner' in res[0]:
try: try:
master_guid = str(misc.GUID(ldb.Dn(samdb, master_guid = str(misc.GUID(ldb.Dn(samdb,
res[0]['fSMORoleOwner'][0].decode('utf8')) res[0]['fSMORoleOwner'][0].decode('utf8'))
.get_extended_component('GUID'))) .get_extended_component('GUID')))
master_owner = str(ldb.Dn(samdb, res[0]['fSMORoleOwner'][0].decode('utf8'))) master_owner = str(ldb.Dn(samdb, res[0]['fSMORoleOwner'][0].decode('utf8')))
except LdbError as e3: except LdbError as e3:
(num, msg) = e3.args (num, msg) = e3.args
@ -231,7 +231,7 @@ class cmd_fsmo_seize(Command):
help="Force seizing of role without attempting to transfer.", help="Force seizing of role without attempting to transfer.",
action="store_true"), action="store_true"),
Option("--role", type="choice", choices=["rid", "pdc", "infrastructure", Option("--role", type="choice", choices=["rid", "pdc", "infrastructure",
"schema", "naming", "domaindns", "forestdns", "all"], "schema", "naming", "domaindns", "forestdns", "all"],
help="""The FSMO role to seize or transfer.\n help="""The FSMO role to seize or transfer.\n
rid=RidAllocationMasterRole\n rid=RidAllocationMasterRole\n
schema=SchemaMasterRole\n schema=SchemaMasterRole\n
@ -443,7 +443,7 @@ class cmd_fsmo_show(Command):
creds = credopts.get_credentials(lp, fallback_machine=True) creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
domain_dn = samdb.domain_dn() domain_dn = samdb.domain_dn()
forest_dn = samba.dn_from_dns_name(samdb.forest_dns_name()) forest_dn = samba.dn_from_dns_name(samdb.forest_dns_name())
@ -489,7 +489,7 @@ class cmd_fsmo_transfer(Command):
Option("-H", "--URL", help="LDB URL for database or target server", Option("-H", "--URL", help="LDB URL for database or target server",
type=str, metavar="URL", dest="H"), type=str, metavar="URL", dest="H"),
Option("--role", type="choice", choices=["rid", "pdc", "infrastructure", Option("--role", type="choice", choices=["rid", "pdc", "infrastructure",
"schema", "naming", "domaindns", "forestdns", "all"], "schema", "naming", "domaindns", "forestdns", "all"],
help="""The FSMO role to seize or transfer.\n help="""The FSMO role to seize or transfer.\n
rid=RidAllocationMasterRole\n rid=RidAllocationMasterRole\n
schema=SchemaMasterRole\n schema=SchemaMasterRole\n

View File

@ -418,7 +418,7 @@ class cmd_list(Command):
takes_options = [ takes_options = [
Option("-H", "--URL", help="LDB URL for database or target server", Option("-H", "--URL", help="LDB URL for database or target server",
type=str, metavar="URL", dest="H") type=str, metavar="URL", dest="H")
] ]
def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None): def run(self, username, H=None, sambaopts=None, credopts=None, versionopts=None):
@ -480,7 +480,7 @@ class cmd_list(Command):
secdesc = ndr_unpack(security.descriptor, secdesc_ndr) secdesc = ndr_unpack(security.descriptor, secdesc_ndr)
except Exception: except Exception:
self.outf.write("Failed to fetch gpo object with nTSecurityDescriptor %s\n" % self.outf.write("Failed to fetch gpo object with nTSecurityDescriptor %s\n" %
g['dn']) g['dn'])
continue continue
try: try:
@ -630,9 +630,9 @@ class cmd_setlink(Command):
takes_options = [ takes_options = [
Option("-H", help="LDB URL for database or target server", type=str), Option("-H", help="LDB URL for database or target server", type=str),
Option("--disable", dest="disabled", default=False, action='store_true', Option("--disable", dest="disabled", default=False, action='store_true',
help="Disable policy"), help="Disable policy"),
Option("--enforce", dest="enforced", default=False, action='store_true', Option("--enforce", dest="enforced", default=False, action='store_true',
help="Enforce policy") help="Enforce policy")
] ]
def run(self, container_dn, gpo, H=None, disabled=False, enforced=False, def run(self, container_dn, gpo, H=None, disabled=False, enforced=False,

View File

@ -89,12 +89,12 @@ Example3 adds a new RFC2307 enabled group for NIS domain samdom and GID 12345 (b
Option("-H", "--URL", help="LDB URL for database or target server", type=str, Option("-H", "--URL", help="LDB URL for database or target server", type=str,
metavar="URL", dest="H"), metavar="URL", dest="H"),
Option("--groupou", Option("--groupou",
help="Alternative location (without domainDN counterpart) to default CN=Users in which new user object will be created", help="Alternative location (without domainDN counterpart) to default CN=Users in which new user object will be created",
type=str), type=str),
Option("--group-scope", type="choice", choices=["Domain", "Global", "Universal"], Option("--group-scope", type="choice", choices=["Domain", "Global", "Universal"],
help="Group scope (Domain | Global | Universal)"), help="Group scope (Domain | Global | Universal)"),
Option("--group-type", type="choice", choices=["Security", "Distribution"], Option("--group-type", type="choice", choices=["Security", "Distribution"],
help="Group type (Security | Distribution)"), help="Group type (Security | Distribution)"),
Option("--description", help="Group's description", type=str), Option("--description", help="Group's description", type=str),
Option("--mail-address", help="Group's email address", type=str), Option("--mail-address", help="Group's email address", type=str),
Option("--notes", help="Groups's notes", type=str), Option("--notes", help="Groups's notes", type=str),
@ -123,8 +123,8 @@ Example3 adds a new RFC2307 enabled group for NIS domain samdom and GID 12345 (b
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
samdb.newgroup(groupname, groupou=groupou, grouptype = gtype, samdb.newgroup(groupname, groupou=groupou, grouptype = gtype,
description=description, mailaddress=mail_address, notes=notes, description=description, mailaddress=mail_address, notes=notes,
gidnumber=gid_number, nisdomain=nis_domain) gidnumber=gid_number, nisdomain=nis_domain)
except Exception as e: except Exception as e:
# FIXME: catch more specific exception # FIXME: catch more specific exception
raise CommandError('Failed to create group "%s"' % groupname, e) raise CommandError('Failed to create group "%s"' % groupname, e)
@ -239,7 +239,7 @@ Example2 shows how to add a single user account, User2, to the supergroup AD gro
credentials=creds, lp=lp) credentials=creds, lp=lp)
groupmembers = listofmembers.split(',') groupmembers = listofmembers.split(',')
samdb.add_remove_group_members(groupname, groupmembers, samdb.add_remove_group_members(groupname, groupmembers,
add_members_operation=True) add_members_operation=True)
except Exception as e: except Exception as e:
# FIXME: catch more specific exception # FIXME: catch more specific exception
raise CommandError('Failed to add members "%s" to group "%s"' % ( raise CommandError('Failed to add members "%s" to group "%s"' % (
@ -290,7 +290,7 @@ Example2 shows how to remove a single user account, User2, from the supergroup A
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
samdb.add_remove_group_members(groupname, listofmembers.split(","), samdb.add_remove_group_members(groupname, listofmembers.split(","),
add_members_operation=False) add_members_operation=False)
except Exception as e: except Exception as e:
# FIXME: Catch more specific exception # FIXME: Catch more specific exception
raise CommandError('Failed to remove members "%s" from group "%s"' % (listofmembers, groupname), e) raise CommandError('Failed to remove members "%s" from group "%s"' % (listofmembers, groupname), e)
@ -323,12 +323,12 @@ class cmd_group_list(Command):
creds = credopts.get_credentials(lp, fallback_machine=True) creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
domain_dn = samdb.domain_dn() domain_dn = samdb.domain_dn()
res = samdb.search(domain_dn, scope=ldb.SCOPE_SUBTREE, res = samdb.search(domain_dn, scope=ldb.SCOPE_SUBTREE,
expression=("(objectClass=group)"), expression=("(objectClass=group)"),
attrs=["samaccountname", "grouptype"]) attrs=["samaccountname", "grouptype"])
if (len(res) == 0): if (len(res) == 0):
return return

View File

@ -87,13 +87,13 @@ class LDAPBase(object):
if self.two_domains and not self.quiet: if self.two_domains and not self.quiet:
self.outf.write("\n* Place-holders for %s:\n" % self.host) self.outf.write("\n* Place-holders for %s:\n" % self.host)
self.outf.write(4*" " + "${DOMAIN_DN} => %s\n" % self.outf.write(4*" " + "${DOMAIN_DN} => %s\n" %
self.base_dn) self.base_dn)
self.outf.write(4*" " + "${DOMAIN_NETBIOS} => %s\n" % self.outf.write(4*" " + "${DOMAIN_NETBIOS} => %s\n" %
self.domain_netbios) self.domain_netbios)
self.outf.write(4*" " + "${SERVER_NAME} => %s\n" % self.outf.write(4*" " + "${SERVER_NAME} => %s\n" %
self.server_names) self.server_names)
self.outf.write(4*" " + "${DOMAIN_NAME} => %s\n" % self.outf.write(4*" " + "${DOMAIN_NAME} => %s\n" %
self.domain_name) self.domain_name)
def find_domain_sid(self): def find_domain_sid(self):
res = self.ldb.search(base=self.base_dn, expression="(objectClass=*)", scope=SCOPE_BASE) res = self.ldb.search(base=self.base_dn, expression="(objectClass=*)", scope=SCOPE_BASE)
@ -103,7 +103,7 @@ class LDAPBase(object):
""" """
""" """
res = self.ldb.search(base="OU=Domain Controllers,%s" % self.base_dn, res = self.ldb.search(base="OU=Domain Controllers,%s" % self.base_dn,
scope=SCOPE_SUBTREE, expression="(objectClass=computer)", attrs=["cn"]) scope=SCOPE_SUBTREE, expression="(objectClass=computer)", attrs=["cn"])
assert len(res) > 0 assert len(res) > 0
srv = [] srv = []
for x in res: for x in res:
@ -112,7 +112,7 @@ class LDAPBase(object):
def find_netbios(self): def find_netbios(self):
res = self.ldb.search(base="CN=Partitions,%s" % self.config_dn, res = self.ldb.search(base="CN=Partitions,%s" % self.config_dn,
scope=SCOPE_SUBTREE, attrs=["nETBIOSName"]) scope=SCOPE_SUBTREE, attrs=["nETBIOSName"])
assert len(res) > 0 assert len(res) > 0
for x in res: for x in res:
if "nETBIOSName" in x.keys(): if "nETBIOSName" in x.keys():
@ -497,8 +497,8 @@ class LDAPObject(object):
# #
# May contain DOMAIN_NETBIOS and SERVER_NAME # May contain DOMAIN_NETBIOS and SERVER_NAME
self.servername_attributes = [ "distinguishedName", "name", "CN", "sAMAccountName", "dNSHostName", self.servername_attributes = [ "distinguishedName", "name", "CN", "sAMAccountName", "dNSHostName",
"servicePrincipalName", "rIDSetReferences", "serverReference", "serverReferenceBL", "servicePrincipalName", "rIDSetReferences", "serverReference", "serverReferenceBL",
"msDS-IsDomainFor", "interSiteTopologyGenerator",] "msDS-IsDomainFor", "interSiteTopologyGenerator",]
self.servername_attributes = [x.upper() for x in self.servername_attributes] self.servername_attributes = [x.upper() for x in self.servername_attributes]
# #
self.netbios_attributes = [ "servicePrincipalName", "CN", "distinguishedName", "nETBIOSName", "name",] self.netbios_attributes = [ "servicePrincipalName", "CN", "distinguishedName", "nETBIOSName", "name",]
@ -793,10 +793,10 @@ class LDAPBundel(object):
raise raise
try: try:
object2 = LDAPObject(connection=other.con, object2 = LDAPObject(connection=other.con,
dn=other.dn_list[index], dn=other.dn_list[index],
summary=other.summary, summary=other.summary,
filter_list=self.filter_list, filter_list=self.filter_list,
outf=self.outf, errf=self.errf) outf=self.outf, errf=self.errf)
except LdbError as e1: except LdbError as e1:
(enum, estr) = e1.args (enum, estr) = e1.args
if enum == ERR_NO_SUCH_OBJECT: if enum == ERR_NO_SUCH_OBJECT:
@ -893,27 +893,27 @@ class cmd_ldapcmp(Command):
takes_options = [ takes_options = [
Option("-w", "--two", dest="two", action="store_true", default=False, Option("-w", "--two", dest="two", action="store_true", default=False,
help="Hosts are in two different domains"), help="Hosts are in two different domains"),
Option("-q", "--quiet", dest="quiet", action="store_true", default=False, Option("-q", "--quiet", dest="quiet", action="store_true", default=False,
help="Do not print anything but relay on just exit code"), help="Do not print anything but relay on just exit code"),
Option("-v", "--verbose", dest="verbose", action="store_true", default=False, Option("-v", "--verbose", dest="verbose", action="store_true", default=False,
help="Print all DN pairs that have been compared"), help="Print all DN pairs that have been compared"),
Option("--sd", dest="descriptor", action="store_true", default=False, Option("--sd", dest="descriptor", action="store_true", default=False,
help="Compare nTSecurityDescriptor attibutes only"), help="Compare nTSecurityDescriptor attibutes only"),
Option("--sort-aces", dest="sort_aces", action="store_true", default=False, Option("--sort-aces", dest="sort_aces", action="store_true", default=False,
help="Sort ACEs before comparison of nTSecurityDescriptor attribute"), help="Sort ACEs before comparison of nTSecurityDescriptor attribute"),
Option("--view", dest="view", default="section", Option("--view", dest="view", default="section",
help="Display mode for nTSecurityDescriptor results. Possible values: section or collision."), help="Display mode for nTSecurityDescriptor results. Possible values: section or collision."),
Option("--base", dest="base", default="", Option("--base", dest="base", default="",
help="Pass search base that will build DN list for the first DC."), help="Pass search base that will build DN list for the first DC."),
Option("--base2", dest="base2", default="", Option("--base2", dest="base2", default="",
help="Pass search base that will build DN list for the second DC. Used when --two or when compare two different DNs."), help="Pass search base that will build DN list for the second DC. Used when --two or when compare two different DNs."),
Option("--scope", dest="scope", default="SUB", Option("--scope", dest="scope", default="SUB",
help="Pass search scope that builds DN list. Options: SUB, ONE, BASE"), help="Pass search scope that builds DN list. Options: SUB, ONE, BASE"),
Option("--filter", dest="filter", default="", Option("--filter", dest="filter", default="",
help="List of comma separated attributes to ignore in the comparision"), help="List of comma separated attributes to ignore in the comparision"),
Option("--skip-missing-dn", dest="skip_missing_dn", action="store_true", default=False, Option("--skip-missing-dn", dest="skip_missing_dn", action="store_true", default=False,
help="Skip report and failure due to missing DNs in one server or another"), help="Skip report and failure due to missing DNs in one server or another"),
] ]
def run(self, URL1, URL2, def run(self, URL1, URL2,
@ -993,7 +993,7 @@ class cmd_ldapcmp(Command):
if b1 == b2: if b1 == b2:
if not quiet: if not quiet:
self.outf.write("\n* Result for [%s]: SUCCESS\n" % self.outf.write("\n* Result for [%s]: SUCCESS\n" %
context) context)
else: else:
if not quiet: if not quiet:
self.outf.write("\n* Result for [%s]: FAILURE\n" % context) self.outf.write("\n* Result for [%s]: FAILURE\n" % context)

View File

@ -174,7 +174,7 @@ def make_pso_ldb_msg(outf, samdb, pso_dn, create, lockout_threshold=None,
if create: if create:
ldb_oper = ldb.FLAG_MOD_ADD ldb_oper = ldb.FLAG_MOD_ADD
m["msDS-objectClass"] = ldb.MessageElement("msDS-PasswordSettings", m["msDS-objectClass"] = ldb.MessageElement("msDS-PasswordSettings",
ldb_oper, "objectClass") ldb_oper, "objectClass")
else: else:
ldb_oper = ldb.FLAG_MOD_REPLACE ldb_oper = ldb.FLAG_MOD_REPLACE
@ -252,14 +252,14 @@ def check_pso_constraints(min_pwd_length=None, history_length=None,
# the same args are used for both create and set commands # the same args are used for both create and set commands
pwd_settings_options = [ pwd_settings_options = [
Option("--complexity", type="choice", choices=["on", "off"], Option("--complexity", type="choice", choices=["on", "off"],
help="The password complexity (on | off)."), help="The password complexity (on | off)."),
Option("--store-plaintext", type="choice", choices=["on", "off"], Option("--store-plaintext", type="choice", choices=["on", "off"],
help="Store plaintext passwords where account have " help="Store plaintext passwords where account have "
"'store passwords with reversible encryption' set (on | off)."), "'store passwords with reversible encryption' set (on | off)."),
Option("--history-length", Option("--history-length",
help="The password history length (<integer>).", type=int), help="The password history length (<integer>).", type=int),
Option("--min-pwd-length", Option("--min-pwd-length",
help="The minimum password length (<integer>).", type=int), help="The minimum password length (<integer>).", type=int),
Option("--min-pwd-age", Option("--min-pwd-age",
help=("The minimum password age (<integer in days>). " help=("The minimum password age (<integer in days>). "
"Default is domain setting."), type=int), "Default is domain setting."), type=int),
@ -336,7 +336,7 @@ class cmd_domain_pwdsettings_pso_create(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
try: try:
precedence = int(precedence) precedence = int(precedence)
@ -374,9 +374,9 @@ class cmd_domain_pwdsettings_pso_create(Command):
# lookup the current domain password-settings # lookup the current domain password-settings
res = samdb.search(samdb.domain_dn(), scope=ldb.SCOPE_BASE, res = samdb.search(samdb.domain_dn(), scope=ldb.SCOPE_BASE,
attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength", attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength",
"minPwdAge", "maxPwdAge", "lockoutDuration", "minPwdAge", "maxPwdAge", "lockoutDuration",
"lockoutThreshold", "lockOutObservationWindow"]) "lockoutThreshold", "lockOutObservationWindow"])
assert(len(res) == 1) assert(len(res) == 1)
# use the domain settings for any missing arguments # use the domain settings for any missing arguments
@ -473,7 +473,7 @@ class cmd_domain_pwdsettings_pso_set(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
# sanity-check the PSO exists # sanity-check the PSO exists
pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb)) pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb))
@ -549,7 +549,7 @@ class cmd_domain_pwdsettings_pso_delete(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb)) pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb))
# sanity-check the PSO exists # sanity-check the PSO exists
@ -587,7 +587,7 @@ class cmd_domain_pwdsettings_pso_list(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
res = samdb.search(pso_container(samdb), scope=ldb.SCOPE_SUBTREE, res = samdb.search(pso_container(samdb), scope=ldb.SCOPE_SUBTREE,
attrs=['name', 'msDS-PasswordSettingsPrecedence'], attrs=['name', 'msDS-PasswordSettingsPrecedence'],
@ -634,7 +634,7 @@ class cmd_domain_pwdsettings_pso_show(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb)) pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb))
check_pso_valid(samdb, pso_dn, psoname) check_pso_valid(samdb, pso_dn, psoname)
@ -664,7 +664,7 @@ class cmd_domain_pwdsettings_pso_show_user(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
show_pso_for_user(self.outf, samdb, username) show_pso_for_user(self.outf, samdb, username)
@ -700,7 +700,7 @@ class cmd_domain_pwdsettings_pso_apply(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb)) pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb))
# sanity-check the PSO exists # sanity-check the PSO exists
@ -760,7 +760,7 @@ class cmd_domain_pwdsettings_pso_unapply(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb)) pso_dn = "CN=%s,%s" % (psoname, pso_container(samdb))
# sanity-check the PSO exists # sanity-check the PSO exists

View File

@ -111,7 +111,7 @@ class cmd_schema_attribute_modify(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
schema_dn = samdb.schema_dn() schema_dn = samdb.schema_dn()
# For now we make assumptions about the CN # For now we make assumptions about the CN
@ -154,7 +154,7 @@ class cmd_schema_attribute_show(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
schema_dn = samdb.schema_dn() schema_dn = samdb.schema_dn()
@ -229,7 +229,7 @@ class cmd_schema_attribute_show_oc(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
schema_dn = samdb.schema_dn() schema_dn = samdb.schema_dn()
@ -239,9 +239,9 @@ class cmd_schema_attribute_show_oc(Command):
'(|(mustContain={0})(systemMustContain={0})))'.format(attribute) '(|(mustContain={0})(systemMustContain={0})))'.format(attribute)
may_res = samdb.search(base=schema_dn, scope=ldb.SCOPE_SUBTREE, may_res = samdb.search(base=schema_dn, scope=ldb.SCOPE_SUBTREE,
expression=may_filt, attrs=['cn']) expression=may_filt, attrs=['cn'])
must_res = samdb.search(base=schema_dn, scope=ldb.SCOPE_SUBTREE, must_res = samdb.search(base=schema_dn, scope=ldb.SCOPE_SUBTREE,
expression=must_filt, attrs=['cn']) expression=must_filt, attrs=['cn'])
self.outf.write('--- MAY contain ---\n') self.outf.write('--- MAY contain ---\n')
for msg in may_res: for msg in may_res:
@ -279,7 +279,7 @@ class cmd_schema_objectclass_show(Command):
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
schema_dn = samdb.schema_dn() schema_dn = samdb.schema_dn()

View File

@ -123,7 +123,7 @@ class cmd_spn_add(Command):
tab.append(name) tab.append(name)
msg.dn = res[0].dn msg.dn = res[0].dn
msg["servicePrincipalName"] = ldb.MessageElement(tab, flag, msg["servicePrincipalName"] = ldb.MessageElement(tab, flag,
"servicePrincipalName") "servicePrincipalName")
if not found: if not found:
sam.modify(msg) sam.modify(msg)
else: else:
@ -173,8 +173,8 @@ class cmd_spn_delete(Command):
for r in res: for r in res:
listUser = "%s\n%s" % (listUser, str(r.dn)) listUser = "%s\n%s" % (listUser, str(r.dn))
raise CommandError("More than one user has the spn %s " raise CommandError("More than one user has the spn %s "
"and no specific user was specified, list of users" "and no specific user was specified, list of users"
" with this spn:%s" % (name, listUser)) " with this spn:%s" % (name, listUser))
else: else:
result=res[0] result=res[0]
@ -189,7 +189,7 @@ class cmd_spn_delete(Command):
flag = ldb.FLAG_MOD_REPLACE flag = ldb.FLAG_MOD_REPLACE
msg.dn = result.dn msg.dn = result.dn
msg["servicePrincipalName"] = ldb.MessageElement(tab, flag, msg["servicePrincipalName"] = ldb.MessageElement(tab, flag,
"servicePrincipalName") "servicePrincipalName")
sam.modify(msg) sam.modify(msg)
else: else:
raise CommandError("Service principal %s not affected" % name) raise CommandError("Service principal %s not affected" % name)

View File

@ -201,9 +201,9 @@ class cmd_testparm(Command):
# this is totally ugly, a real `quick' hack # this is totally ugly, a real `quick' hack
for s in lp.services(): for s in lp.services():
if (self.allow_access(lp.get("hosts deny"), lp.get("hosts allow"), cname, if (self.allow_access(lp.get("hosts deny"), lp.get("hosts allow"), cname,
caddr) and caddr) and
self.allow_access(lp.get("hosts deny", s), lp.get("hosts allow", s), self.allow_access(lp.get("hosts deny", s), lp.get("hosts allow", s),
cname, caddr)): cname, caddr)):
logger.info("Allow connection from %s (%s) to %s", cname, caddr, s) logger.info("Allow connection from %s (%s) to %s", cname, caddr, s)
else: else:
logger.info("Deny connection from %s (%s) to %s", cname, caddr, s) logger.info("Deny connection from %s (%s) to %s", cname, caddr, s)

View File

@ -479,13 +479,13 @@ class cmd_user_list(Command):
creds = credopts.get_credentials(lp, fallback_machine=True) creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
domain_dn = samdb.domain_dn() domain_dn = samdb.domain_dn()
res = samdb.search(domain_dn, scope=ldb.SCOPE_SUBTREE, res = samdb.search(domain_dn, scope=ldb.SCOPE_SUBTREE,
expression=("(&(objectClass=user)(userAccountControl:%s:=%u))" expression=("(&(objectClass=user)(userAccountControl:%s:=%u))"
% (ldb.OID_COMPARATOR_AND, dsdb.UF_NORMAL_ACCOUNT)), % (ldb.OID_COMPARATOR_AND, dsdb.UF_NORMAL_ACCOUNT)),
attrs=["samaccountname"]) attrs=["samaccountname"])
if (len(res) == 0): if (len(res) == 0):
return return
@ -554,7 +554,7 @@ Example3 shows how to enable a user in the domain against a local LDAP server.
creds = credopts.get_credentials(lp, fallback_machine=True) creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
try: try:
samdb.enable_account(filter) samdb.enable_account(filter)
except Exception as msg: except Exception as msg:
@ -593,7 +593,7 @@ class cmd_user_disable(Command):
creds = credopts.get_credentials(lp, fallback_machine=True) creds = credopts.get_credentials(lp, fallback_machine=True)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
try: try:
samdb.disable_account(filter) samdb.disable_account(filter)
except Exception as msg: except Exception as msg:
@ -659,7 +659,7 @@ Example4 shows how to set the account expiration so that it will never expire.
creds = credopts.get_credentials(lp) creds = credopts.get_credentials(lp)
samdb = SamDB(url=H, session_info=system_session(), samdb = SamDB(url=H, session_info=system_session(),
credentials=creds, lp=lp) credentials=creds, lp=lp)
try: try:
samdb.setexpiry(filter, days*24*3600, no_expiry_req=noexpiry) samdb.setexpiry(filter, days*24*3600, no_expiry_req=noexpiry)

View File

@ -181,7 +181,7 @@ class ProvisionNames(object):
def find_provision_key_parameters(samdb, secretsdb, idmapdb, paths, smbconf, def find_provision_key_parameters(samdb, secretsdb, idmapdb, paths, smbconf,
lp): lp):
"""Get key provision parameters (realm, domain, ...) from a given provision """Get key provision parameters (realm, domain, ...) from a given provision
:param samdb: An LDB object connected to the sam.ldb file :param samdb: An LDB object connected to the sam.ldb file
@ -213,19 +213,19 @@ def find_provision_key_parameters(samdb, secretsdb, idmapdb, paths, smbconf,
# That's a bit simplistic but it's ok as long as we have only 3 # That's a bit simplistic but it's ok as long as we have only 3
# partitions # partitions
current = samdb.search(expression="(objectClass=*)", current = samdb.search(expression="(objectClass=*)",
base="", scope=ldb.SCOPE_BASE, base="", scope=ldb.SCOPE_BASE,
attrs=["defaultNamingContext", "schemaNamingContext", attrs=["defaultNamingContext", "schemaNamingContext",
"configurationNamingContext","rootDomainNamingContext", "configurationNamingContext","rootDomainNamingContext",
"namingContexts"]) "namingContexts"])
names.configdn = current[0]["configurationNamingContext"][0] names.configdn = current[0]["configurationNamingContext"][0]
names.schemadn = current[0]["schemaNamingContext"][0] names.schemadn = current[0]["schemaNamingContext"][0]
if not (ldb.Dn(samdb, basedn) == (ldb.Dn(samdb, if not (ldb.Dn(samdb, basedn) == (ldb.Dn(samdb,
current[0]["defaultNamingContext"][0].decode('utf8')))): current[0]["defaultNamingContext"][0].decode('utf8')))):
raise ProvisioningError(("basedn in %s (%s) and from %s (%s)" raise ProvisioningError(("basedn in %s (%s) and from %s (%s)"
"is not the same ..." % (paths.samdb, "is not the same ..." % (paths.samdb,
str(current[0]["defaultNamingContext"][0].decode('utf8')), str(current[0]["defaultNamingContext"][0].decode('utf8')),
paths.smbconf, basedn))) paths.smbconf, basedn)))
names.domaindn=current[0]["defaultNamingContext"][0] names.domaindn=current[0]["defaultNamingContext"][0]
names.rootdn=current[0]["rootDomainNamingContext"][0] names.rootdn=current[0]["rootDomainNamingContext"][0]
@ -248,7 +248,7 @@ def find_provision_key_parameters(samdb, secretsdb, idmapdb, paths, smbconf,
# default site name # default site name
res3 = samdb.search(expression="(objectClass=site)", res3 = samdb.search(expression="(objectClass=site)",
base="CN=Sites," + names.configdn, scope=ldb.SCOPE_ONELEVEL, attrs=["cn"]) base="CN=Sites," + names.configdn, scope=ldb.SCOPE_ONELEVEL, attrs=["cn"])
names.sitename = str(res3[0]["cn"]) names.sitename = str(res3[0]["cn"])
# dns hostname and server dn # dns hostname and server dn
@ -266,16 +266,16 @@ def find_provision_key_parameters(samdb, secretsdb, idmapdb, paths, smbconf,
# invocation id/objectguid # invocation id/objectguid
res5 = samdb.search(expression="(objectClass=*)", res5 = samdb.search(expression="(objectClass=*)",
base="CN=NTDS Settings,%s" % str(names.serverdn), base="CN=NTDS Settings,%s" % str(names.serverdn),
scope=ldb.SCOPE_BASE, scope=ldb.SCOPE_BASE,
attrs=["invocationID", "objectGUID"]) attrs=["invocationID", "objectGUID"])
names.invocation = str(ndr_unpack(misc.GUID, res5[0]["invocationId"][0])) names.invocation = str(ndr_unpack(misc.GUID, res5[0]["invocationId"][0]))
names.ntdsguid = str(ndr_unpack(misc.GUID, res5[0]["objectGUID"][0])) names.ntdsguid = str(ndr_unpack(misc.GUID, res5[0]["objectGUID"][0]))
# domain guid/sid # domain guid/sid
res6 = samdb.search(expression="(objectClass=*)", base=basedn, res6 = samdb.search(expression="(objectClass=*)", base=basedn,
scope=ldb.SCOPE_BASE, attrs=["objectGUID", scope=ldb.SCOPE_BASE, attrs=["objectGUID",
"objectSid","msDS-Behavior-Version" ]) "objectSid","msDS-Behavior-Version" ])
names.domainguid = str(ndr_unpack(misc.GUID, res6[0]["objectGUID"][0])) names.domainguid = str(ndr_unpack(misc.GUID, res6[0]["objectGUID"][0]))
names.domainsid = ndr_unpack( security.dom_sid, res6[0]["objectSid"][0]) names.domainsid = ndr_unpack( security.dom_sid, res6[0]["objectSid"][0])
names.forestsid = ndr_unpack( security.dom_sid, res6[0]["objectSid"][0]) names.forestsid = ndr_unpack( security.dom_sid, res6[0]["objectSid"][0])
@ -371,8 +371,10 @@ def update_provision_usn(samdb, low, high, id, replace=False):
tab.append("%s-%s;%s" % (low, high, id)) tab.append("%s-%s;%s" % (low, high, id))
delta = ldb.Message() delta = ldb.Message()
delta.dn = ldb.Dn(samdb, "@PROVISION") delta.dn = ldb.Dn(samdb, "@PROVISION")
delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, delta[LAST_PROVISION_USN_ATTRIBUTE] = \
ldb.FLAG_MOD_REPLACE, LAST_PROVISION_USN_ATTRIBUTE) ldb.MessageElement(tab,
ldb.FLAG_MOD_REPLACE,
LAST_PROVISION_USN_ATTRIBUTE)
entry = samdb.search(expression='provisionnerID=*', entry = samdb.search(expression='provisionnerID=*',
base="@PROVISION", scope=ldb.SCOPE_BASE, base="@PROVISION", scope=ldb.SCOPE_BASE,
attrs=["provisionnerID"]) attrs=["provisionnerID"])
@ -398,8 +400,10 @@ def set_provision_usn(samdb, low, high, id):
delta = ldb.Message() delta = ldb.Message()
delta.dn = ldb.Dn(samdb, "@PROVISION") delta.dn = ldb.Dn(samdb, "@PROVISION")
delta[LAST_PROVISION_USN_ATTRIBUTE] = ldb.MessageElement(tab, delta[LAST_PROVISION_USN_ATTRIBUTE] = \
ldb.FLAG_MOD_ADD, LAST_PROVISION_USN_ATTRIBUTE) ldb.MessageElement(tab,
ldb.FLAG_MOD_ADD,
LAST_PROVISION_USN_ATTRIBUTE)
samdb.add(delta) samdb.add(delta)
@ -428,8 +432,8 @@ def get_last_provision_usn(sam):
""" """
try: try:
entry = sam.search(expression="%s=*" % LAST_PROVISION_USN_ATTRIBUTE, entry = sam.search(expression="%s=*" % LAST_PROVISION_USN_ATTRIBUTE,
base="@PROVISION", scope=ldb.SCOPE_BASE, base="@PROVISION", scope=ldb.SCOPE_BASE,
attrs=[LAST_PROVISION_USN_ATTRIBUTE, "provisionnerID"]) attrs=[LAST_PROVISION_USN_ATTRIBUTE, "provisionnerID"])
except ldb.LdbError as e1: except ldb.LdbError as e1:
(ecode, emsg) = e1.args (ecode, emsg) = e1.args
if ecode == ldb.ERR_NO_SUCH_OBJECT: if ecode == ldb.ERR_NO_SUCH_OBJECT:
@ -508,7 +512,7 @@ def check_install(lp, session_info, credentials):
if lp.get("realm") == "": if lp.get("realm") == "":
raise Exception("Realm empty") raise Exception("Realm empty")
samdb = Ldb(lp.samdb_url(), session_info=session_info, samdb = Ldb(lp.samdb_url(), session_info=session_info,
credentials=credentials, lp=lp) credentials=credentials, lp=lp)
if len(samdb.search("(cn=Administrator)")) != 1: if len(samdb.search("(cn=Administrator)")) != 1:
raise ProvisioningError("No administrator account found") raise ProvisioningError("No administrator account found")
@ -774,7 +778,7 @@ def make_smbconf(smbconf, hostname, domain, realm, targetdir,
if serverrole == "active directory domain controller": if serverrole == "active directory domain controller":
shares["sysvol"] = os.path.join(lp.get("state directory"), "sysvol") shares["sysvol"] = os.path.join(lp.get("state directory"), "sysvol")
shares["netlogon"] = os.path.join(shares["sysvol"], realm.lower(), shares["netlogon"] = os.path.join(shares["sysvol"], realm.lower(),
"scripts") "scripts")
else: else:
global_settings["passdb backend"] = "samba_dsdb" global_settings["passdb backend"] = "samba_dsdb"
@ -906,11 +910,11 @@ def secretsdb_self_join(secretsdb, domain,
:param machinepass: Machine password :param machinepass: Machine password
""" """
attrs = ["whenChanged", attrs = ["whenChanged",
"secret", "secret",
"priorSecret", "priorSecret",
"priorChanged", "priorChanged",
"krb5Keytab", "krb5Keytab",
"privateKeytab"] "privateKeytab"]
if realm is not None: if realm is not None:
if dnsdomain is None: if dnsdomain is None:
@ -943,8 +947,8 @@ def secretsdb_self_join(secretsdb, domain,
# but we don't delete the old record that we are about to modify, # but we don't delete the old record that we are about to modify,
# because that would delete the keytab and previous password. # because that would delete the keytab and previous password.
res = secretsdb.search(base="cn=Primary Domains", attrs=attrs, res = secretsdb.search(base="cn=Primary Domains", attrs=attrs,
expression=("(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(distinguishedName=%s)))" % (domain, realm, str(domainsid), str(msg.dn))), expression=("(&(|(flatname=%s)(realm=%s)(objectSid=%s))(objectclass=primaryDomain)(!(distinguishedName=%s)))" % (domain, realm, str(domainsid), str(msg.dn))),
scope=ldb.SCOPE_ONELEVEL) scope=ldb.SCOPE_ONELEVEL)
for del_msg in res: for del_msg in res:
secretsdb.delete(del_msg.dn) secretsdb.delete(del_msg.dn)
@ -1025,13 +1029,13 @@ def setup_secretsdb(paths, session_info, backend_credentials, lp):
backend_credentials.authentication_requested()): backend_credentials.authentication_requested()):
if backend_credentials.get_bind_dn() is not None: if backend_credentials.get_bind_dn() is not None:
setup_add_ldif(secrets_ldb, setup_add_ldif(secrets_ldb,
setup_path("secrets_simple_ldap.ldif"), { setup_path("secrets_simple_ldap.ldif"), {
"LDAPMANAGERDN": backend_credentials.get_bind_dn(), "LDAPMANAGERDN": backend_credentials.get_bind_dn(),
"LDAPMANAGERPASS_B64": b64encode(backend_credentials.get_password()).decode('utf8') "LDAPMANAGERPASS_B64": b64encode(backend_credentials.get_password()).decode('utf8')
}) })
else: else:
setup_add_ldif(secrets_ldb, setup_add_ldif(secrets_ldb,
setup_path("secrets_sasl_ldap.ldif"), { setup_path("secrets_sasl_ldap.ldif"), {
"LDAPADMINUSER": backend_credentials.get_username(), "LDAPADMINUSER": backend_credentials.get_username(),
"LDAPADMINREALM": backend_credentials.get_realm(), "LDAPADMINREALM": backend_credentials.get_realm(),
"LDAPADMINPASS_B64": b64encode(backend_credentials.get_password()).decode('utf8') "LDAPADMINPASS_B64": b64encode(backend_credentials.get_password()).decode('utf8')
@ -1130,9 +1134,9 @@ def setup_samdb_rootdse(samdb, names):
def setup_self_join(samdb, admin_session_info, names, fill, machinepass, def setup_self_join(samdb, admin_session_info, names, fill, machinepass,
dns_backend, dnspass, domainsid, next_rid, invocationid, dns_backend, dnspass, domainsid, next_rid, invocationid,
policyguid, policyguid_dc, policyguid, policyguid_dc,
domainControllerFunctionality, ntdsguid=None, dc_rid=None): domainControllerFunctionality, ntdsguid=None, dc_rid=None):
"""Join a host to its own domain.""" """Join a host to its own domain."""
assert isinstance(invocationid, str) assert isinstance(invocationid, str)
if ntdsguid is not None: if ntdsguid is not None:
@ -1188,7 +1192,7 @@ def setup_self_join(samdb, admin_session_info, names, fill, machinepass,
# Setup fSMORoleOwner entries to point at the newly created DC entry # Setup fSMORoleOwner entries to point at the newly created DC entry
setup_modify_ldif(samdb, setup_modify_ldif(samdb,
setup_path("provision_self_join_modify_config.ldif"), { setup_path("provision_self_join_modify_config.ldif"), {
"CONFIGDN": names.configdn, "CONFIGDN": names.configdn,
"SCHEMADN": names.schemadn, "SCHEMADN": names.schemadn,
"DEFAULTSITE": names.sitename, "DEFAULTSITE": names.sitename,
@ -1268,8 +1272,8 @@ def create_default_gpo(sysvolpath, dnsdomain, policyguid, policyguid_dc):
def setup_samdb(path, session_info, provision_backend, lp, names, def setup_samdb(path, session_info, provision_backend, lp, names,
logger, fill, serverrole, schema, am_rodc=False, logger, fill, serverrole, schema, am_rodc=False,
plaintext_secrets=False, backend_store=None): plaintext_secrets=False, backend_store=None):
"""Setup a complete SAM Database. """Setup a complete SAM Database.
:note: This will wipe the main SAM database file! :note: This will wipe the main SAM database file!
@ -1277,9 +1281,9 @@ def setup_samdb(path, session_info, provision_backend, lp, names,
# Also wipes the database # Also wipes the database
setup_samdb_partitions(path, logger=logger, lp=lp, setup_samdb_partitions(path, logger=logger, lp=lp,
provision_backend=provision_backend, session_info=session_info, provision_backend=provision_backend, session_info=session_info,
names=names, serverrole=serverrole, plaintext_secrets=plaintext_secrets, names=names, serverrole=serverrole, plaintext_secrets=plaintext_secrets,
backend_store=backend_store) backend_store=backend_store)
# Load the database, but don's load the global schema and don't connect # Load the database, but don's load the global schema and don't connect
# quite yet # quite yet
@ -1316,10 +1320,10 @@ def setup_samdb(path, session_info, provision_backend, lp, names,
def fill_samdb(samdb, lp, names, logger, policyguid, def fill_samdb(samdb, lp, names, logger, policyguid,
policyguid_dc, fill, adminpass, krbtgtpass, machinepass, dns_backend, policyguid_dc, fill, adminpass, krbtgtpass, machinepass, dns_backend,
dnspass, invocationid, ntdsguid, serverrole, am_rodc=False, dnspass, invocationid, ntdsguid, serverrole, am_rodc=False,
dom_for_fun_level=None, schema=None, next_rid=None, dc_rid=None, dom_for_fun_level=None, schema=None, next_rid=None, dc_rid=None,
backend_store=None): backend_store=None):
if next_rid is None: if next_rid is None:
next_rid = 1000 next_rid = 1000
@ -1359,7 +1363,7 @@ def fill_samdb(samdb, lp, names, logger, policyguid,
samdb.set_opaque_integer("domainFunctionality", domainFunctionality) samdb.set_opaque_integer("domainFunctionality", domainFunctionality)
samdb.set_opaque_integer("forestFunctionality", forestFunctionality) samdb.set_opaque_integer("forestFunctionality", forestFunctionality)
samdb.set_opaque_integer("domainControllerFunctionality", samdb.set_opaque_integer("domainControllerFunctionality",
domainControllerFunctionality) domainControllerFunctionality)
samdb.set_domain_sid(str(names.domainsid)) samdb.set_domain_sid(str(names.domainsid))
samdb.set_invocation_id(invocationid) samdb.set_invocation_id(invocationid)
@ -1419,7 +1423,7 @@ def fill_samdb(samdb, lp, names, logger, policyguid,
# Now register this container in the root of the forest # Now register this container in the root of the forest
msg = ldb.Message(ldb.Dn(samdb, names.domaindn)) msg = ldb.Message(ldb.Dn(samdb, names.domaindn))
msg["subRefs"] = ldb.MessageElement(names.configdn , ldb.FLAG_MOD_ADD, msg["subRefs"] = ldb.MessageElement(names.configdn , ldb.FLAG_MOD_ADD,
"subRefs") "subRefs")
samdb.invocation_id = invocationid samdb.invocation_id = invocationid
@ -1476,7 +1480,7 @@ def fill_samdb(samdb, lp, names, logger, policyguid,
logger.info("Modifying display specifiers and extended rights") logger.info("Modifying display specifiers and extended rights")
setup_modify_ldif(samdb, setup_modify_ldif(samdb,
setup_path("provision_configuration_modify.ldif"), { setup_path("provision_configuration_modify.ldif"), {
"CONFIGDN": names.configdn, "CONFIGDN": names.configdn,
"DISPLAYSPECIFIERS_DESCRIPTOR": protected2_descr "DISPLAYSPECIFIERS_DESCRIPTOR": protected2_descr
}) })
@ -1498,7 +1502,7 @@ def fill_samdb(samdb, lp, names, logger, policyguid,
}) })
logger.info("Modifying computers container") logger.info("Modifying computers container")
setup_modify_ldif(samdb, setup_modify_ldif(samdb,
setup_path("provision_computers_modify.ldif"), { setup_path("provision_computers_modify.ldif"), {
"DOMAINDN": names.domaindn}) "DOMAINDN": names.domaindn})
logger.info("Setting up sam.ldb data") logger.info("Setting up sam.ldb data")
infrastructure_desc = b64encode(get_domain_infrastructure_descriptor(names.domainsid)).decode('utf8') infrastructure_desc = b64encode(get_domain_infrastructure_descriptor(names.domainsid)).decode('utf8')
@ -1554,21 +1558,21 @@ def fill_samdb(samdb, lp, names, logger, policyguid,
logger.info("Setting up self join") logger.info("Setting up self join")
setup_self_join(samdb, admin_session_info, names=names, fill=fill, setup_self_join(samdb, admin_session_info, names=names, fill=fill,
invocationid=invocationid, invocationid=invocationid,
dns_backend=dns_backend, dns_backend=dns_backend,
dnspass=dnspass, dnspass=dnspass,
machinepass=machinepass, machinepass=machinepass,
domainsid=names.domainsid, domainsid=names.domainsid,
next_rid=next_rid, next_rid=next_rid,
dc_rid=dc_rid, dc_rid=dc_rid,
policyguid=policyguid, policyguid=policyguid,
policyguid_dc=policyguid_dc, policyguid_dc=policyguid_dc,
domainControllerFunctionality=domainControllerFunctionality, domainControllerFunctionality=domainControllerFunctionality,
ntdsguid=ntdsguid) ntdsguid=ntdsguid)
ntds_dn = "CN=NTDS Settings,%s" % names.serverdn ntds_dn = "CN=NTDS Settings,%s" % names.serverdn
names.ntdsguid = samdb.searchone(basedn=ntds_dn, names.ntdsguid = samdb.searchone(basedn=ntds_dn,
attribute="objectGUID", expression="", scope=ldb.SCOPE_BASE) attribute="objectGUID", expression="", scope=ldb.SCOPE_BASE)
assert isinstance(names.ntdsguid, str) assert isinstance(names.ntdsguid, str)
return samdb return samdb
@ -1583,10 +1587,10 @@ def set_dir_acl(path, acl, lp, domsid, use_ntvfs, passdb, service=SYSVOL_SERVICE
for root, dirs, files in os.walk(path, topdown=False): for root, dirs, files in os.walk(path, topdown=False):
for name in files: for name in files:
setntacl(lp, os.path.join(root, name), acl, domsid, setntacl(lp, os.path.join(root, name), acl, domsid,
use_ntvfs=use_ntvfs, skip_invalid_chown=True, passdb=passdb, service=service) use_ntvfs=use_ntvfs, skip_invalid_chown=True, passdb=passdb, service=service)
for name in dirs: for name in dirs:
setntacl(lp, os.path.join(root, name), acl, domsid, setntacl(lp, os.path.join(root, name), acl, domsid,
use_ntvfs=use_ntvfs, skip_invalid_chown=True, passdb=passdb, service=service) use_ntvfs=use_ntvfs, skip_invalid_chown=True, passdb=passdb, service=service)
def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp, use_ntvfs, passdb): def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp, use_ntvfs, passdb):
@ -1604,7 +1608,7 @@ def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp, use_ntvfs, p
# Set ACL for GPO root folder # Set ACL for GPO root folder
root_policy_path = os.path.join(sysvol, dnsdomain, "Policies") root_policy_path = os.path.join(sysvol, dnsdomain, "Policies")
setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid), setntacl(lp, root_policy_path, POLICIES_ACL, str(domainsid),
use_ntvfs=use_ntvfs, skip_invalid_chown=True, passdb=passdb, service=SYSVOL_SERVICE) use_ntvfs=use_ntvfs, skip_invalid_chown=True, passdb=passdb, service=SYSVOL_SERVICE)
res = samdb.search(base="CN=Policies,CN=System,%s"%(domaindn), res = samdb.search(base="CN=Policies,CN=System,%s"%(domaindn),
attrs=["cn", "nTSecurityDescriptor"], attrs=["cn", "nTSecurityDescriptor"],
@ -1620,7 +1624,7 @@ def set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp, use_ntvfs, p
def setsysvolacl(samdb, netlogon, sysvol, uid, gid, domainsid, dnsdomain, def setsysvolacl(samdb, netlogon, sysvol, uid, gid, domainsid, dnsdomain,
domaindn, lp, use_ntvfs): domaindn, lp, use_ntvfs):
"""Set the ACL for the sysvol share and the subfolders """Set the ACL for the sysvol share and the subfolders
:param samdb: An LDB object on the SAM db :param samdb: An LDB object on the SAM db
@ -1758,7 +1762,7 @@ def check_dir_acl(path, acl, lp, domainsid, direct_db_access):
def check_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp, def check_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp,
direct_db_access): direct_db_access):
"""Set ACL on the sysvol/<dnsname>/Policies folder and the policy """Set ACL on the sysvol/<dnsname>/Policies folder and the policy
folders beneath. folders beneath.
@ -1792,7 +1796,7 @@ def check_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp,
def checksysvolacl(samdb, netlogon, sysvol, domainsid, dnsdomain, domaindn, def checksysvolacl(samdb, netlogon, sysvol, domainsid, dnsdomain, domaindn,
lp): lp):
"""Set the ACL for the sysvol share and the subfolders """Set the ACL for the sysvol share and the subfolders
:param samdb: An LDB object on the SAM db :param samdb: An LDB object on the SAM db
@ -1837,7 +1841,7 @@ def checksysvolacl(samdb, netlogon, sysvol, domainsid, dnsdomain, domaindn,
# Check acls on Policy folder and policies folders # Check acls on Policy folder and policies folders
check_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp, check_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp,
direct_db_access) direct_db_access)
def interface_ips_v4(lp): def interface_ips_v4(lp):
@ -1895,15 +1899,15 @@ def provision_fill(samdb, secrets_ldb, logger, names, paths,
samdb.transaction_start() samdb.transaction_start()
try: try:
samdb = fill_samdb(samdb, lp, names, logger=logger, samdb = fill_samdb(samdb, lp, names, logger=logger,
schema=schema, schema=schema,
policyguid=policyguid, policyguid_dc=policyguid_dc, policyguid=policyguid, policyguid_dc=policyguid_dc,
fill=samdb_fill, adminpass=adminpass, krbtgtpass=krbtgtpass, fill=samdb_fill, adminpass=adminpass, krbtgtpass=krbtgtpass,
invocationid=invocationid, machinepass=machinepass, invocationid=invocationid, machinepass=machinepass,
dns_backend=dns_backend, dnspass=dnspass, dns_backend=dns_backend, dnspass=dnspass,
ntdsguid=ntdsguid, serverrole=serverrole, ntdsguid=ntdsguid, serverrole=serverrole,
dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc,
next_rid=next_rid, dc_rid=dc_rid, next_rid=next_rid, dc_rid=dc_rid,
backend_store=backend_store) backend_store=backend_store)
# Set up group policies (domain policy and domain controller # Set up group policies (domain policy and domain controller
# policy) # policy)
@ -1927,9 +1931,9 @@ def provision_fill(samdb, secrets_ldb, logger, names, paths,
logger.info("Setting acl on sysvol skipped") logger.info("Setting acl on sysvol skipped")
secretsdb_self_join(secrets_ldb, domain=names.domain, secretsdb_self_join(secrets_ldb, domain=names.domain,
realm=names.realm, dnsdomain=names.dnsdomain, realm=names.realm, dnsdomain=names.dnsdomain,
netbiosname=names.netbiosname, domainsid=names.domainsid, netbiosname=names.netbiosname, domainsid=names.domainsid,
machinepass=machinepass, secure_channel_type=SEC_CHAN_BDC) machinepass=machinepass, secure_channel_type=SEC_CHAN_BDC)
# Now set up the right msDS-SupportedEncryptionTypes into the DB # Now set up the right msDS-SupportedEncryptionTypes into the DB
# In future, this might be determined from some configuration # In future, this might be determined from some configuration
@ -1974,7 +1978,7 @@ def provision_fill(samdb, secrets_ldb, logger, names, paths,
# fix any dangling GUIDs from the provision # fix any dangling GUIDs from the provision
logger.info("Fixing provision GUIDs") logger.info("Fixing provision GUIDs")
chk = dbcheck(samdb, samdb_schema=samdb, verbose=False, fix=True, yes=True, chk = dbcheck(samdb, samdb_schema=samdb, verbose=False, fix=True, yes=True,
quiet=True) quiet=True)
samdb.transaction_start() samdb.transaction_start()
try: try:
# a small number of GUIDs are missing because of ordering issues in the # a small number of GUIDs are missing because of ordering issues in the
@ -1991,7 +1995,7 @@ def provision_fill(samdb, secrets_ldb, logger, names, paths,
'ipsecNegotiationPolicyReference', 'ipsecNegotiationPolicyReference',
'ipsecNFAReference']) 'ipsecNFAReference'])
if chk.check_database(DN=names.schemadn, scope=ldb.SCOPE_SUBTREE, if chk.check_database(DN=names.schemadn, scope=ldb.SCOPE_SUBTREE,
attrs=['attributeId', 'governsId']) != 0: attrs=['attributeId', 'governsId']) != 0:
raise ProvisioningError("Duplicate attributeId or governsId in schema. Must be fixed manually!!") raise ProvisioningError("Duplicate attributeId or governsId in schema. Must be fixed manually!!")
except: except:
samdb.transaction_cancel() samdb.transaction_cancel()
@ -2030,7 +2034,7 @@ def sanitize_server_role(role):
def provision_fake_ypserver(logger, samdb, domaindn, netbiosname, nisdomain, def provision_fake_ypserver(logger, samdb, domaindn, netbiosname, nisdomain,
maxuid, maxgid): maxuid, maxgid):
"""Create AD entries for the fake ypserver. """Create AD entries for the fake ypserver.
This is needed for being able to manipulate posix attrs via ADUC. This is needed for being able to manipulate posix attrs via ADUC.
@ -2067,7 +2071,7 @@ def determine_host_ip(logger, lp, hostip=None):
hostip = hostips[0] hostip = hostips[0]
if len(hostips) > 1: if len(hostips) > 1:
logger.warning("More than one IPv4 address found. Using %s", logger.warning("More than one IPv4 address found. Using %s",
hostip) hostip)
if hostip == "127.0.0.1": if hostip == "127.0.0.1":
hostip = None hostip = None
if hostip is None: if hostip is None:
@ -2089,21 +2093,21 @@ def determine_host_ip6(logger, lp, hostip6=None):
return hostip6 return hostip6
def provision(logger, session_info, smbconf=None, def provision(logger, session_info, smbconf=None,
targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None, targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None,
domaindn=None, schemadn=None, configdn=None, serverdn=None, domaindn=None, schemadn=None, configdn=None, serverdn=None,
domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None, domain=None, hostname=None, hostip=None, hostip6=None, domainsid=None,
next_rid=1000, dc_rid=None, adminpass=None, ldapadminpass=None, next_rid=1000, dc_rid=None, adminpass=None, ldapadminpass=None,
krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None, krbtgtpass=None, domainguid=None, policyguid=None, policyguid_dc=None,
dns_backend=None, dns_forwarder=None, dnspass=None, dns_backend=None, dns_forwarder=None, dnspass=None,
invocationid=None, machinepass=None, ntdsguid=None, invocationid=None, machinepass=None, ntdsguid=None,
root=None, nobody=None, users=None, backup=None, aci=None, root=None, nobody=None, users=None, backup=None, aci=None,
serverrole=None, dom_for_fun_level=None, backend_type=None, serverrole=None, dom_for_fun_level=None, backend_type=None,
sitename=None, ol_mmr_urls=None, ol_olc=None, slapd_path=None, sitename=None, ol_mmr_urls=None, ol_olc=None, slapd_path=None,
useeadb=False, am_rodc=False, lp=None, use_ntvfs=False, useeadb=False, am_rodc=False, lp=None, use_ntvfs=False,
use_rfc2307=False, maxuid=None, maxgid=None, skip_sysvolacl=True, use_rfc2307=False, maxuid=None, maxgid=None, skip_sysvolacl=True,
ldap_backend_forced_uri=None, nosync=False, ldap_dryrun_mode=False, ldap_backend_forced_uri=None, nosync=False, ldap_dryrun_mode=False,
ldap_backend_extra_port=None, base_schema=None, ldap_backend_extra_port=None, base_schema=None,
plaintext_secrets=False, backend_store=None): plaintext_secrets=False, backend_store=None):
"""Provision samba4 """Provision samba4
:note: caution, this wipes all existing data! :note: caution, this wipes all existing data!
@ -2186,9 +2190,9 @@ def provision(logger, session_info, smbconf=None,
lp = samba.param.LoadParm() lp = samba.param.LoadParm()
lp.load(smbconf) lp.load(smbconf)
names = guess_names(lp=lp, hostname=hostname, domain=domain, names = guess_names(lp=lp, hostname=hostname, domain=domain,
dnsdomain=realm, serverrole=serverrole, domaindn=domaindn, dnsdomain=realm, serverrole=serverrole, domaindn=domaindn,
configdn=configdn, schemadn=schemadn, serverdn=serverdn, configdn=configdn, schemadn=schemadn, serverdn=serverdn,
sitename=sitename, rootdn=rootdn, domain_names_forced=(samdb_fill == FILL_DRS)) sitename=sitename, rootdn=rootdn, domain_names_forced=(samdb_fill == FILL_DRS))
paths = provision_paths_from_lp(lp, names.dnsdomain) paths = provision_paths_from_lp(lp, names.dnsdomain)
paths.bind_gid = bind_gid paths.bind_gid = bind_gid
@ -2219,35 +2223,35 @@ def provision(logger, session_info, smbconf=None,
ldapi_url = "ldapi://%s" % urllib_quote(paths.s4_ldapi_path, safe="") ldapi_url = "ldapi://%s" % urllib_quote(paths.s4_ldapi_path, safe="")
schema = Schema(domainsid, invocationid=invocationid, schema = Schema(domainsid, invocationid=invocationid,
schemadn=names.schemadn, base_schema=base_schema) schemadn=names.schemadn, base_schema=base_schema)
if backend_type == "ldb": if backend_type == "ldb":
provision_backend = LDBBackend(backend_type, paths=paths, provision_backend = LDBBackend(backend_type, paths=paths,
lp=lp, lp=lp,
names=names, logger=logger) names=names, logger=logger)
elif backend_type == "existing": elif backend_type == "existing":
# If support for this is ever added back, then the URI will need to be # If support for this is ever added back, then the URI will need to be
# specified again # specified again
provision_backend = ExistingBackend(backend_type, paths=paths, provision_backend = ExistingBackend(backend_type, paths=paths,
lp=lp, lp=lp,
names=names, logger=logger, names=names, logger=logger,
ldap_backend_forced_uri=ldap_backend_forced_uri) ldap_backend_forced_uri=ldap_backend_forced_uri)
elif backend_type == "fedora-ds": elif backend_type == "fedora-ds":
provision_backend = FDSBackend(backend_type, paths=paths, provision_backend = FDSBackend(backend_type, paths=paths,
lp=lp, lp=lp,
names=names, logger=logger, domainsid=domainsid, names=names, logger=logger, domainsid=domainsid,
schema=schema, hostname=hostname, ldapadminpass=ldapadminpass, schema=schema, hostname=hostname, ldapadminpass=ldapadminpass,
slapd_path=slapd_path, slapd_path=slapd_path,
root=root) root=root)
elif backend_type == "openldap": elif backend_type == "openldap":
provision_backend = OpenLDAPBackend(backend_type, paths=paths, provision_backend = OpenLDAPBackend(backend_type, paths=paths,
lp=lp, lp=lp,
names=names, logger=logger, domainsid=domainsid, names=names, logger=logger, domainsid=domainsid,
schema=schema, hostname=hostname, ldapadminpass=ldapadminpass, schema=schema, hostname=hostname, ldapadminpass=ldapadminpass,
slapd_path=slapd_path, ol_mmr_urls=ol_mmr_urls, slapd_path=slapd_path, ol_mmr_urls=ol_mmr_urls,
ldap_backend_extra_port=ldap_backend_extra_port, ldap_backend_extra_port=ldap_backend_extra_port,
ldap_dryrun_mode=ldap_dryrun_mode, nosync=nosync, ldap_dryrun_mode=ldap_dryrun_mode, nosync=nosync,
ldap_backend_forced_uri=ldap_backend_forced_uri) ldap_backend_forced_uri=ldap_backend_forced_uri)
else: else:
raise ValueError("Unknown LDAP backend type selected") raise ValueError("Unknown LDAP backend type selected")
@ -2262,8 +2266,8 @@ def provision(logger, session_info, smbconf=None,
logger.info("Setting up secrets.ldb") logger.info("Setting up secrets.ldb")
secrets_ldb = setup_secretsdb(paths, secrets_ldb = setup_secretsdb(paths,
session_info=session_info, session_info=session_info,
backend_credentials=provision_backend.credentials, lp=lp) backend_credentials=provision_backend.credentials, lp=lp)
try: try:
logger.info("Setting up the registry") logger.info("Setting up the registry")
@ -2306,18 +2310,18 @@ def provision(logger, session_info, smbconf=None,
if samdb_fill == FILL_FULL: if samdb_fill == FILL_FULL:
provision_fill(samdb, secrets_ldb, logger, names, paths, provision_fill(samdb, secrets_ldb, logger, names, paths,
schema=schema, targetdir=targetdir, samdb_fill=samdb_fill, schema=schema, targetdir=targetdir, samdb_fill=samdb_fill,
hostip=hostip, hostip6=hostip6, hostip=hostip, hostip6=hostip6,
next_rid=next_rid, dc_rid=dc_rid, adminpass=adminpass, next_rid=next_rid, dc_rid=dc_rid, adminpass=adminpass,
krbtgtpass=krbtgtpass, krbtgtpass=krbtgtpass,
policyguid=policyguid, policyguid_dc=policyguid_dc, policyguid=policyguid, policyguid_dc=policyguid_dc,
invocationid=invocationid, machinepass=machinepass, invocationid=invocationid, machinepass=machinepass,
ntdsguid=ntdsguid, dns_backend=dns_backend, ntdsguid=ntdsguid, dns_backend=dns_backend,
dnspass=dnspass, serverrole=serverrole, dnspass=dnspass, serverrole=serverrole,
dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc, dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc,
lp=lp, use_ntvfs=use_ntvfs, lp=lp, use_ntvfs=use_ntvfs,
skip_sysvolacl=skip_sysvolacl, skip_sysvolacl=skip_sysvolacl,
backend_store=backend_store) backend_store=backend_store)
if not is_heimdal_built(): if not is_heimdal_built():
create_kdc_conf(paths.kdcconf, realm, domain, os.path.dirname(lp.get("log file"))) create_kdc_conf(paths.kdcconf, realm, domain, os.path.dirname(lp.get("log file")))
@ -2404,33 +2408,33 @@ def provision(logger, session_info, smbconf=None,
if use_rfc2307: if use_rfc2307:
provision_fake_ypserver(logger=logger, samdb=samdb, provision_fake_ypserver(logger=logger, samdb=samdb,
domaindn=names.domaindn, netbiosname=names.netbiosname, domaindn=names.domaindn, netbiosname=names.netbiosname,
nisdomain=names.domain.lower(), maxuid=maxuid, maxgid=maxgid) nisdomain=names.domain.lower(), maxuid=maxuid, maxgid=maxgid)
return result return result
def provision_become_dc(smbconf=None, targetdir=None, def provision_become_dc(smbconf=None, targetdir=None,
realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None, realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None,
serverdn=None, domain=None, hostname=None, domainsid=None, serverdn=None, domain=None, hostname=None, domainsid=None,
adminpass=None, krbtgtpass=None, domainguid=None, policyguid=None, adminpass=None, krbtgtpass=None, domainguid=None, policyguid=None,
policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None, policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None,
dns_backend=None, root=None, nobody=None, users=None, dns_backend=None, root=None, nobody=None, users=None,
backup=None, serverrole=None, ldap_backend=None, backup=None, serverrole=None, ldap_backend=None,
ldap_backend_type=None, sitename=None, debuglevel=1, use_ntvfs=False): ldap_backend_type=None, sitename=None, debuglevel=1, use_ntvfs=False):
logger = logging.getLogger("provision") logger = logging.getLogger("provision")
samba.set_debug_level(debuglevel) samba.set_debug_level(debuglevel)
res = provision(logger, system_session(), res = provision(logger, system_session(),
smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS, smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS,
realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn, realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn,
configdn=configdn, serverdn=serverdn, domain=domain, configdn=configdn, serverdn=serverdn, domain=domain,
hostname=hostname, hostip=None, domainsid=domainsid, hostname=hostname, hostip=None, domainsid=domainsid,
machinepass=machinepass, machinepass=machinepass,
serverrole="active directory domain controller", serverrole="active directory domain controller",
sitename=sitename, dns_backend=dns_backend, dnspass=dnspass, sitename=sitename, dns_backend=dns_backend, dnspass=dnspass,
use_ntvfs=use_ntvfs) use_ntvfs=use_ntvfs)
res.lp.set("debuglevel", str(debuglevel)) res.lp.set("debuglevel", str(debuglevel))
return res return res

View File

@ -49,8 +49,8 @@ class SlapdAlreadyRunning(Exception):
def __init__(self, uri): def __init__(self, uri):
self.ldapi_uri = uri self.ldapi_uri = uri
super(SlapdAlreadyRunning, self).__init__("Another slapd Instance " super(SlapdAlreadyRunning, self).__init__("Another slapd Instance "
"seems already running on this host, listening to %s." % "seems already running on this host, listening to %s." %
self.ldapi_uri) self.ldapi_uri)
class BackendResult(object): class BackendResult(object):
@ -83,7 +83,7 @@ class LDAPBackendResult(BackendResult):
class ProvisionBackend(object): class ProvisionBackend(object):
def __init__(self, backend_type, paths=None, lp=None, def __init__(self, backend_type, paths=None, lp=None,
names=None, logger=None): names=None, logger=None):
"""Provision a backend for samba4""" """Provision a backend for samba4"""
self.paths = paths self.paths = paths
self.lp = lp self.lp = lp
@ -137,18 +137,18 @@ class LDBBackend(ProvisionBackend):
class ExistingBackend(ProvisionBackend): class ExistingBackend(ProvisionBackend):
def __init__(self, backend_type, paths=None, lp=None, def __init__(self, backend_type, paths=None, lp=None,
names=None, logger=None, ldapi_uri=None): names=None, logger=None, ldapi_uri=None):
super(ExistingBackend, self).__init__(backend_type=backend_type, super(ExistingBackend, self).__init__(backend_type=backend_type,
paths=paths, lp=lp, paths=paths, lp=lp,
names=names, logger=logger, names=names, logger=logger,
ldap_backend_forced_uri=ldapi_uri) ldap_backend_forced_uri=ldapi_uri)
def init(self): def init(self):
# Check to see that this 'existing' LDAP backend in fact exists # Check to see that this 'existing' LDAP backend in fact exists
ldapi_db = Ldb(self.ldapi_uri) ldapi_db = Ldb(self.ldapi_uri)
ldapi_db.search(base="", scope=SCOPE_BASE, ldapi_db.search(base="", scope=SCOPE_BASE,
expression="(objectClass=OpenLDAProotDSE)") expression="(objectClass=OpenLDAProotDSE)")
# For now, assume existing backends at least emulate OpenLDAP # For now, assume existing backends at least emulate OpenLDAP
self.ldap_backend_type = "openldap" self.ldap_backend_type = "openldap"
@ -163,8 +163,8 @@ class LDAPBackend(ProvisionBackend):
ldap_backend_forced_uri=None, ldap_dryrun_mode=False): ldap_backend_forced_uri=None, ldap_dryrun_mode=False):
super(LDAPBackend, self).__init__(backend_type=backend_type, super(LDAPBackend, self).__init__(backend_type=backend_type,
paths=paths, lp=lp, paths=paths, lp=lp,
names=names, logger=logger) names=names, logger=logger)
self.domainsid = domainsid self.domainsid = domainsid
self.schema = schema self.schema = schema
@ -198,7 +198,7 @@ class LDAPBackend(ProvisionBackend):
try: try:
ldapi_db = Ldb(self.ldap_uri) ldapi_db = Ldb(self.ldap_uri)
ldapi_db.search(base="", scope=SCOPE_BASE, ldapi_db.search(base="", scope=SCOPE_BASE,
expression="(objectClass=OpenLDAProotDSE)") expression="(objectClass=OpenLDAProotDSE)")
try: try:
f = open(self.slapd_pid, "r") f = open(self.slapd_pid, "r")
except IOError as err: except IOError as err:
@ -221,7 +221,7 @@ class LDAPBackend(ProvisionBackend):
raise ProvisioningError("Warning: LDAP-Backend must be setup with path to slapd, e.g. --slapd-path=\"/usr/local/libexec/slapd\"!") raise ProvisioningError("Warning: LDAP-Backend must be setup with path to slapd, e.g. --slapd-path=\"/usr/local/libexec/slapd\"!")
if not os.path.exists(self.slapd_path): if not os.path.exists(self.slapd_path):
self.logger.warning("Path (%s) to slapd does not exist!", self.logger.warning("Path (%s) to slapd does not exist!",
self.slapd_path) self.slapd_path)
if not os.path.isdir(self.ldapdir): if not os.path.isdir(self.ldapdir):
os.makedirs(self.ldapdir, 0o700) os.makedirs(self.ldapdir, 0o700)
@ -266,7 +266,7 @@ class LDAPBackend(ProvisionBackend):
# subprocess context around, to kill this off at the successful # subprocess context around, to kill this off at the successful
# end of the script # end of the script
self.slapd = subprocess.Popen(self.slapd_provision_command, self.slapd = subprocess.Popen(self.slapd_provision_command,
close_fds=True, shell=False) close_fds=True, shell=False)
count = 0 count = 0
while self.slapd.poll() is None: while self.slapd.poll() is None:
@ -275,7 +275,7 @@ class LDAPBackend(ProvisionBackend):
time.sleep(1) time.sleep(1)
ldapi_db = Ldb(self.ldap_uri, lp=self.lp, credentials=self.credentials) ldapi_db = Ldb(self.ldap_uri, lp=self.lp, credentials=self.credentials)
ldapi_db.search(base="", scope=SCOPE_BASE, ldapi_db.search(base="", scope=SCOPE_BASE,
expression="(objectClass=OpenLDAProotDSE)") expression="(objectClass=OpenLDAProotDSE)")
# If we have got here, then we must have a valid connection to # If we have got here, then we must have a valid connection to
# the LDAP server! # the LDAP server!
return return
@ -306,25 +306,25 @@ class LDAPBackend(ProvisionBackend):
def post_setup(self): def post_setup(self):
return LDAPBackendResult(self.slapd_command_escaped, return LDAPBackendResult(self.slapd_command_escaped,
self.ldapdir) self.ldapdir)
class OpenLDAPBackend(LDAPBackend): class OpenLDAPBackend(LDAPBackend):
def __init__(self, backend_type, paths=None, lp=None, def __init__(self, backend_type, paths=None, lp=None,
credentials=None, names=None, logger=None, domainsid=None, credentials=None, names=None, logger=None, domainsid=None,
schema=None, hostname=None, ldapadminpass=None, slapd_path=None, schema=None, hostname=None, ldapadminpass=None, slapd_path=None,
ldap_backend_extra_port=None, ldap_dryrun_mode=False, ldap_backend_extra_port=None, ldap_dryrun_mode=False,
ol_mmr_urls=None, nosync=False, ldap_backend_forced_uri=None): ol_mmr_urls=None, nosync=False, ldap_backend_forced_uri=None):
from samba.provision import setup_path from samba.provision import setup_path
super(OpenLDAPBackend, self).__init__( backend_type=backend_type, super(OpenLDAPBackend, self).__init__( backend_type=backend_type,
paths=paths, lp=lp, paths=paths, lp=lp,
names=names, logger=logger, names=names, logger=logger,
domainsid=domainsid, schema=schema, hostname=hostname, domainsid=domainsid, schema=schema, hostname=hostname,
ldapadminpass=ldapadminpass, slapd_path=slapd_path, ldapadminpass=ldapadminpass, slapd_path=slapd_path,
ldap_backend_extra_port=ldap_backend_extra_port, ldap_backend_extra_port=ldap_backend_extra_port,
ldap_backend_forced_uri=ldap_backend_forced_uri, ldap_backend_forced_uri=ldap_backend_forced_uri,
ldap_dryrun_mode=ldap_dryrun_mode) ldap_dryrun_mode=ldap_dryrun_mode)
self.ol_mmr_urls = ol_mmr_urls self.ol_mmr_urls = ol_mmr_urls
self.nosync = nosync self.nosync = nosync
@ -557,14 +557,14 @@ class OpenLDAPBackend(LDAPBackend):
server_port_string = "ldap://0.0.0.0:%d" % self.ldap_backend_extra_port server_port_string = "ldap://0.0.0.0:%d" % self.ldap_backend_extra_port
else: else:
server_port_string = "ldap://%s.%s:%d" (self.names.hostname, server_port_string = "ldap://%s.%s:%d" (self.names.hostname,
self.names.dnsdomain, self.ldap_backend_extra_port) self.names.dnsdomain, self.ldap_backend_extra_port)
else: else:
server_port_string = "" server_port_string = ""
# Prepare the 'result' information - the commands to return in # Prepare the 'result' information - the commands to return in
# particular # particular
self.slapd_provision_command = [self.slapd_path, "-F" + self.olcdir, self.slapd_provision_command = [self.slapd_path, "-F" + self.olcdir,
"-h"] "-h"]
# copy this command so we have two version, one with -d0 and only # copy this command so we have two version, one with -d0 and only
# ldapi (or the forced ldap_uri), and one with all the listen commands # ldapi (or the forced ldap_uri), and one with all the listen commands
@ -619,13 +619,13 @@ class FDSBackend(LDAPBackend):
from samba.provision import setup_path from samba.provision import setup_path
super(FDSBackend, self).__init__(backend_type=backend_type, super(FDSBackend, self).__init__(backend_type=backend_type,
paths=paths, lp=lp, paths=paths, lp=lp,
names=names, logger=logger, names=names, logger=logger,
domainsid=domainsid, schema=schema, hostname=hostname, domainsid=domainsid, schema=schema, hostname=hostname,
ldapadminpass=ldapadminpass, slapd_path=slapd_path, ldapadminpass=ldapadminpass, slapd_path=slapd_path,
ldap_backend_extra_port=ldap_backend_extra_port, ldap_backend_extra_port=ldap_backend_extra_port,
ldap_backend_forced_uri=ldap_backend_forced_uri, ldap_backend_forced_uri=ldap_backend_forced_uri,
ldap_dryrun_mode=ldap_dryrun_mode) ldap_dryrun_mode=ldap_dryrun_mode)
self.root = root self.root = root
self.setup_ds_path = setup_ds_path self.setup_ds_path = setup_ds_path
@ -635,13 +635,13 @@ class FDSBackend(LDAPBackend):
self.fedoradsinf = os.path.join(self.ldapdir, "fedorads.inf") self.fedoradsinf = os.path.join(self.ldapdir, "fedorads.inf")
self.partitions_ldif = os.path.join(self.ldapdir, self.partitions_ldif = os.path.join(self.ldapdir,
"fedorads-partitions.ldif") "fedorads-partitions.ldif")
self.sasl_ldif = os.path.join(self.ldapdir, "fedorads-sasl.ldif") self.sasl_ldif = os.path.join(self.ldapdir, "fedorads-sasl.ldif")
self.dna_ldif = os.path.join(self.ldapdir, "fedorads-dna.ldif") self.dna_ldif = os.path.join(self.ldapdir, "fedorads-dna.ldif")
self.pam_ldif = os.path.join(self.ldapdir, "fedorads-pam.ldif") self.pam_ldif = os.path.join(self.ldapdir, "fedorads-pam.ldif")
self.refint_ldif = os.path.join(self.ldapdir, "fedorads-refint.ldif") self.refint_ldif = os.path.join(self.ldapdir, "fedorads-refint.ldif")
self.linked_attrs_ldif = os.path.join(self.ldapdir, self.linked_attrs_ldif = os.path.join(self.ldapdir,
"fedorads-linked-attributes.ldif") "fedorads-linked-attributes.ldif")
self.index_ldif = os.path.join(self.ldapdir, "fedorads-index.ldif") self.index_ldif = os.path.join(self.ldapdir, "fedorads-index.ldif")
self.samba_ldif = os.path.join(self.ldapdir, "fedorads-samba.ldif") self.samba_ldif = os.path.join(self.ldapdir, "fedorads-samba.ldif")
@ -650,10 +650,10 @@ class FDSBackend(LDAPBackend):
self.samba3_ldif = os.path.join(self.ldapdir, "samba3.ldif") self.samba3_ldif = os.path.join(self.ldapdir, "samba3.ldif")
self.retcode = subprocess.call(["bin/oLschema2ldif", self.retcode = subprocess.call(["bin/oLschema2ldif",
"-I", self.samba3_schema, "-I", self.samba3_schema,
"-O", self.samba3_ldif, "-O", self.samba3_ldif,
"-b", self.names.domaindn], "-b", self.names.domaindn],
close_fds=True, shell=False) close_fds=True, shell=False)
if self.retcode != 0: if self.retcode != 0:
raise Exception("Unable to convert Samba 3 schema.") raise Exception("Unable to convert Samba 3 schema.")
@ -684,7 +684,7 @@ class FDSBackend(LDAPBackend):
"SERVERPORT": serverport}) "SERVERPORT": serverport})
setup_file(setup_path("fedorads-partitions.ldif"), setup_file(setup_path("fedorads-partitions.ldif"),
self.partitions_ldif, self.partitions_ldif,
{"CONFIGDN": self.names.configdn, {"CONFIGDN": self.names.configdn,
"SCHEMADN": self.names.schemadn, "SCHEMADN": self.names.schemadn,
"SAMBADN": self.sambadn, "SAMBADN": self.sambadn,
@ -771,7 +771,7 @@ class FDSBackend(LDAPBackend):
f = open(setup_path(mapping), 'r') f = open(setup_path(mapping), 'r')
try: try:
backend_schema_data = self.schema.convert_to_openldap("fedora-ds", backend_schema_data = self.schema.convert_to_openldap("fedora-ds",
f.read()) f.read())
finally: finally:
f.close() f.close()
assert backend_schema_data is not None assert backend_schema_data is not None
@ -784,19 +784,21 @@ class FDSBackend(LDAPBackend):
self.credentials.set_bind_dn(self.names.ldapmanagerdn) self.credentials.set_bind_dn(self.names.ldapmanagerdn)
# Destory the target directory, or else setup-ds.pl will complain # Destory the target directory, or else setup-ds.pl will complain
fedora_ds_dir = os.path.join(self.ldapdir, fedora_ds_dir = \
"slapd-" + self.ldap_instance) os.path.join(self.ldapdir,
"slapd-" + self.ldap_instance)
shutil.rmtree(fedora_ds_dir, True) shutil.rmtree(fedora_ds_dir, True)
self.slapd_provision_command = [self.slapd_path, "-D", fedora_ds_dir, self.slapd_provision_command = [self.slapd_path, "-D", fedora_ds_dir,
"-i", self.slapd_pid] "-i", self.slapd_pid]
# In the 'provision' command line, stay in the foreground so we can # In the 'provision' command line, stay in the foreground so we can
# easily kill it # easily kill it
self.slapd_provision_command.append("-d0") self.slapd_provision_command.append("-d0")
#the command for the final run is the normal script #the command for the final run is the normal script
self.slapd_command = [os.path.join(self.ldapdir, self.slapd_command = \
"slapd-" + self.ldap_instance, "start-slapd")] [os.path.join(self.ldapdir,
"slapd-" + self.ldap_instance, "start-slapd")]
# If we were just looking for crashes up to this point, it's a # If we were just looking for crashes up to this point, it's a
# good time to exit before we realise we don't have Fedora DS on # good time to exit before we realise we don't have Fedora DS on
@ -809,11 +811,11 @@ class FDSBackend(LDAPBackend):
raise ProvisioningError("Fedora DS LDAP-Backend must be setup with path to setup-ds, e.g. --setup-ds-path=\"/usr/sbin/setup-ds.pl\"!") raise ProvisioningError("Fedora DS LDAP-Backend must be setup with path to setup-ds, e.g. --setup-ds-path=\"/usr/sbin/setup-ds.pl\"!")
if not os.path.exists(self.setup_ds_path): if not os.path.exists(self.setup_ds_path):
self.logger.warning("Path (%s) to slapd does not exist!", self.logger.warning("Path (%s) to slapd does not exist!",
self.setup_ds_path) self.setup_ds_path)
# Run the Fedora DS setup utility # Run the Fedora DS setup utility
retcode = subprocess.call([self.setup_ds_path, "--silent", "--file", retcode = subprocess.call([self.setup_ds_path, "--silent", "--file",
self.fedoradsinf], close_fds=True, shell=False) self.fedoradsinf], close_fds=True, shell=False)
if retcode != 0: if retcode != 0:
raise ProvisioningError("setup-ds failed") raise ProvisioningError("setup-ds failed")
@ -839,4 +841,4 @@ class FDSBackend(LDAPBackend):
m.dn = ldb.Dn(ldapi_db, dnstring) m.dn = ldb.Dn(ldapi_db, dnstring)
ldapi_db.modify(m) ldapi_db.modify(m)
return LDAPBackendResult(self.credentials, self.slapd_command_escaped, return LDAPBackendResult(self.credentials, self.slapd_command_escaped,
self.ldapdir) self.ldapdir)

View File

@ -141,7 +141,7 @@ class SOARecord(dnsp.DnssrvRpcRecord):
class SRVRecord(dnsp.DnssrvRpcRecord): class SRVRecord(dnsp.DnssrvRpcRecord):
def __init__(self, target, port, priority=0, weight=100, serial=1, ttl=900, def __init__(self, target, port, priority=0, weight=100, serial=1, ttl=900,
rank=dnsp.DNS_RANK_ZONE): rank=dnsp.DNS_RANK_ZONE):
super(SRVRecord, self).__init__() super(SRVRecord, self).__init__()
self.wType = dnsp.DNS_TYPE_SRV self.wType = dnsp.DNS_TYPE_SRV
self.rank = rank self.rank = rank
@ -314,8 +314,9 @@ def add_dns_container(samdb, domaindn, prefix, domain_sid, dnsadmins_sid, forest
# CN=MicrosoftDNS,<PREFIX>,<DOMAINDN> # CN=MicrosoftDNS,<PREFIX>,<DOMAINDN>
msg = ldb.Message(ldb.Dn(samdb, "CN=MicrosoftDNS,%s,%s" % (prefix, domaindn))) msg = ldb.Message(ldb.Dn(samdb, "CN=MicrosoftDNS,%s,%s" % (prefix, domaindn)))
msg["objectClass"] = ["top", "container"] msg["objectClass"] = ["top", "container"]
msg["nTSecurityDescriptor"] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_ADD, msg["nTSecurityDescriptor"] = \
"nTSecurityDescriptor") ldb.MessageElement(sd_val, ldb.FLAG_MOD_ADD,
"nTSecurityDescriptor")
samdb.add(msg) samdb.add(msg)
@ -492,8 +493,10 @@ def add_domain_record(samdb, domaindn, prefix, dnsdomain, domainsid, dnsadmins_s
props.append(ndr_pack(AgingEnabledTimeProperty())) props.append(ndr_pack(AgingEnabledTimeProperty()))
msg = ldb.Message(ldb.Dn(samdb, "DC=%s,CN=MicrosoftDNS,%s,%s" % (dnsdomain, prefix, domaindn))) msg = ldb.Message(ldb.Dn(samdb, "DC=%s,CN=MicrosoftDNS,%s,%s" % (dnsdomain, prefix, domaindn)))
msg["objectClass"] = ["top", "dnsZone"] msg["objectClass"] = ["top", "dnsZone"]
msg["ntSecurityDescriptor"] = ldb.MessageElement(ndr_pack(sec), ldb.FLAG_MOD_ADD, msg["ntSecurityDescriptor"] = \
"nTSecurityDescriptor") ldb.MessageElement(ndr_pack(sec),
ldb.FLAG_MOD_ADD,
"nTSecurityDescriptor")
msg["dNSProperty"] = ldb.MessageElement(props, ldb.FLAG_MOD_ADD, "dNSProperty") msg["dNSProperty"] = ldb.MessageElement(props, ldb.FLAG_MOD_ADD, "dNSProperty")
samdb.add(msg) samdb.add(msg)
@ -507,7 +510,7 @@ def add_msdcs_record(samdb, forestdn, prefix, dnsforest):
def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname, def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname,
hostip, hostip6): hostip, hostip6):
fqdn_hostname = "%s.%s" % (hostname, dnsdomain) fqdn_hostname = "%s.%s" % (hostname, dnsdomain)
@ -517,39 +520,39 @@ def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname,
# DC=@ record # DC=@ record
add_at_record(samdb, domain_container_dn, "DC=@", hostname, dnsdomain, add_at_record(samdb, domain_container_dn, "DC=@", hostname, dnsdomain,
hostip, hostip6) hostip, hostip6)
# DC=<HOSTNAME> record # DC=<HOSTNAME> record
add_host_record(samdb, domain_container_dn, "DC=%s" % hostname, hostip, add_host_record(samdb, domain_container_dn, "DC=%s" % hostname, hostip,
hostip6) hostip6)
# DC=_kerberos._tcp record # DC=_kerberos._tcp record
add_srv_record(samdb, domain_container_dn, "DC=_kerberos._tcp", add_srv_record(samdb, domain_container_dn, "DC=_kerberos._tcp",
fqdn_hostname, 88) fqdn_hostname, 88)
# DC=_kerberos._tcp.<SITENAME>._sites record # DC=_kerberos._tcp.<SITENAME>._sites record
add_srv_record(samdb, domain_container_dn, "DC=_kerberos._tcp.%s._sites" % add_srv_record(samdb, domain_container_dn, "DC=_kerberos._tcp.%s._sites" %
site, fqdn_hostname, 88) site, fqdn_hostname, 88)
# DC=_kerberos._udp record # DC=_kerberos._udp record
add_srv_record(samdb, domain_container_dn, "DC=_kerberos._udp", add_srv_record(samdb, domain_container_dn, "DC=_kerberos._udp",
fqdn_hostname, 88) fqdn_hostname, 88)
# DC=_kpasswd._tcp record # DC=_kpasswd._tcp record
add_srv_record(samdb, domain_container_dn, "DC=_kpasswd._tcp", add_srv_record(samdb, domain_container_dn, "DC=_kpasswd._tcp",
fqdn_hostname, 464) fqdn_hostname, 464)
# DC=_kpasswd._udp record # DC=_kpasswd._udp record
add_srv_record(samdb, domain_container_dn, "DC=_kpasswd._udp", add_srv_record(samdb, domain_container_dn, "DC=_kpasswd._udp",
fqdn_hostname, 464) fqdn_hostname, 464)
# DC=_ldap._tcp record # DC=_ldap._tcp record
add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp", fqdn_hostname, add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp", fqdn_hostname,
389) 389)
# DC=_ldap._tcp.<SITENAME>._sites record # DC=_ldap._tcp.<SITENAME>._sites record
add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp.%s._sites" % add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp.%s._sites" %
site, fqdn_hostname, 389) site, fqdn_hostname, 389)
# FIXME: The number of SRV records depend on the various roles this DC has. # FIXME: The number of SRV records depend on the various roles this DC has.
# _gc and _msdcs records are added if the we are the forest dc and not subdomain dc # _gc and _msdcs records are added if the we are the forest dc and not subdomain dc
@ -558,11 +561,11 @@ def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname,
# DC=_gc._tcp record # DC=_gc._tcp record
add_srv_record(samdb, domain_container_dn, "DC=_gc._tcp", fqdn_hostname, add_srv_record(samdb, domain_container_dn, "DC=_gc._tcp", fqdn_hostname,
3268) 3268)
# DC=_gc._tcp.<SITENAME>,_sites record # DC=_gc._tcp.<SITENAME>,_sites record
add_srv_record(samdb, domain_container_dn, "DC=_gc._tcp.%s._sites" % site, add_srv_record(samdb, domain_container_dn, "DC=_gc._tcp.%s._sites" % site,
fqdn_hostname, 3268) fqdn_hostname, 3268)
# DC=_msdcs record # DC=_msdcs record
add_ns_glue_record(samdb, domain_container_dn, "DC=_msdcs", fqdn_hostname) add_ns_glue_record(samdb, domain_container_dn, "DC=_msdcs", fqdn_hostname)
@ -574,13 +577,13 @@ def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname,
# DC=_ldap._tcp.<SITENAME>._sites.DomainDnsZones # DC=_ldap._tcp.<SITENAME>._sites.DomainDnsZones
add_srv_record(samdb, domain_container_dn, add_srv_record(samdb, domain_container_dn,
"DC=_ldap._tcp.%s._sites.DomainDnsZones" % site, fqdn_hostname, "DC=_ldap._tcp.%s._sites.DomainDnsZones" % site, fqdn_hostname,
389) 389)
# DC=_ldap._tcp.<SITENAME>._sites.ForestDnsZones # DC=_ldap._tcp.<SITENAME>._sites.ForestDnsZones
add_srv_record(samdb, domain_container_dn, add_srv_record(samdb, domain_container_dn,
"DC=_ldap._tcp.%s._sites.ForestDnsZones" % site, fqdn_hostname, "DC=_ldap._tcp.%s._sites.ForestDnsZones" % site, fqdn_hostname,
389) 389)
# DC=_ldap._tcp.DomainDnsZones # DC=_ldap._tcp.DomainDnsZones
add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp.DomainDnsZones", add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp.DomainDnsZones",
@ -592,11 +595,11 @@ def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname,
# DC=DomainDnsZones # DC=DomainDnsZones
add_host_record(samdb, domain_container_dn, "DC=DomainDnsZones", hostip, add_host_record(samdb, domain_container_dn, "DC=DomainDnsZones", hostip,
hostip6) hostip6)
# DC=ForestDnsZones # DC=ForestDnsZones
add_host_record(samdb, domain_container_dn, "DC=ForestDnsZones", hostip, add_host_record(samdb, domain_container_dn, "DC=ForestDnsZones", hostip,
hostip6) hostip6)
def add_dc_msdcs_records(samdb, forestdn, prefix, site, dnsforest, hostname, def add_dc_msdcs_records(samdb, forestdn, prefix, site, dnsforest, hostname,
@ -610,46 +613,46 @@ def add_dc_msdcs_records(samdb, forestdn, prefix, site, dnsforest, hostname,
# DC=@ record # DC=@ record
add_at_record(samdb, forest_container_dn, "DC=@", hostname, dnsforest, add_at_record(samdb, forest_container_dn, "DC=@", hostname, dnsforest,
None, None) None, None)
# DC=_kerberos._tcp.dc record # DC=_kerberos._tcp.dc record
add_srv_record(samdb, forest_container_dn, "DC=_kerberos._tcp.dc", add_srv_record(samdb, forest_container_dn, "DC=_kerberos._tcp.dc",
fqdn_hostname, 88) fqdn_hostname, 88)
# DC=_kerberos._tcp.<SITENAME>._sites.dc record # DC=_kerberos._tcp.<SITENAME>._sites.dc record
add_srv_record(samdb, forest_container_dn, add_srv_record(samdb, forest_container_dn,
"DC=_kerberos._tcp.%s._sites.dc" % site, fqdn_hostname, 88) "DC=_kerberos._tcp.%s._sites.dc" % site, fqdn_hostname, 88)
# DC=_ldap._tcp.dc record # DC=_ldap._tcp.dc record
add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.dc", add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.dc",
fqdn_hostname, 389) fqdn_hostname, 389)
# DC=_ldap._tcp.<SITENAME>._sites.dc record # DC=_ldap._tcp.<SITENAME>._sites.dc record
add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.%s._sites.dc" % add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.%s._sites.dc" %
site, fqdn_hostname, 389) site, fqdn_hostname, 389)
# DC=_ldap._tcp.<SITENAME>._sites.gc record # DC=_ldap._tcp.<SITENAME>._sites.gc record
add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.%s._sites.gc" % add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.%s._sites.gc" %
site, fqdn_hostname, 3268) site, fqdn_hostname, 3268)
# DC=_ldap._tcp.gc record # DC=_ldap._tcp.gc record
add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.gc", add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.gc",
fqdn_hostname, 3268) fqdn_hostname, 3268)
# DC=_ldap._tcp.pdc record # DC=_ldap._tcp.pdc record
add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.pdc", add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.pdc",
fqdn_hostname, 389) fqdn_hostname, 389)
# DC=gc record # DC=gc record
add_host_record(samdb, forest_container_dn, "DC=gc", hostip, hostip6) add_host_record(samdb, forest_container_dn, "DC=gc", hostip, hostip6)
# DC=_ldap._tcp.<DOMAINGUID>.domains record # DC=_ldap._tcp.<DOMAINGUID>.domains record
add_srv_record(samdb, forest_container_dn, add_srv_record(samdb, forest_container_dn,
"DC=_ldap._tcp.%s.domains" % domainguid, fqdn_hostname, 389) "DC=_ldap._tcp.%s.domains" % domainguid, fqdn_hostname, 389)
# DC=<NTDSGUID> # DC=<NTDSGUID>
add_cname_record(samdb, forest_container_dn, "DC=%s" % ntdsguid, add_cname_record(samdb, forest_container_dn, "DC=%s" % ntdsguid,
fqdn_hostname) fqdn_hostname)
def secretsdb_setup_dns(secretsdb, names, private_dir, binddns_dir, realm, def secretsdb_setup_dns(secretsdb, names, private_dir, binddns_dir, realm,
@ -824,7 +827,7 @@ def create_samdb_copy(samdb, logger, paths, names, domainsid, domainguid):
"DOMAINSID" : str(domainsid), "DOMAINSID" : str(domainsid),
"DESCRIPTOR" : descr}) "DESCRIPTOR" : descr})
setup_add_ldif(dom_ldb, setup_add_ldif(dom_ldb,
setup_path("provision_basedn_options.ldif"), None) setup_path("provision_basedn_options.ldif"), None)
except: except:
logger.error( logger.error(
@ -850,9 +853,9 @@ def create_samdb_copy(samdb, logger, paths, names, domainsid, domainguid):
metadata_file = "metadata.tdb" metadata_file = "metadata.tdb"
try: try:
os.link(os.path.join(samldb_dir, metadata_file), os.link(os.path.join(samldb_dir, metadata_file),
os.path.join(dns_samldb_dir, metadata_file)) os.path.join(dns_samldb_dir, metadata_file))
os.link(os.path.join(private_dir, domainzone_file), os.link(os.path.join(private_dir, domainzone_file),
os.path.join(dns_dir, domainzone_file)) os.path.join(dns_dir, domainzone_file))
if forestzone_file: if forestzone_file:
os.link(os.path.join(private_dir, forestzone_file), os.link(os.path.join(private_dir, forestzone_file),
os.path.join(dns_dir, forestzone_file)) os.path.join(dns_dir, forestzone_file))
@ -873,10 +876,10 @@ def create_samdb_copy(samdb, logger, paths, names, domainsid, domainguid):
pfile = partfile[nc] pfile = partfile[nc]
if backend_store == "mdb": if backend_store == "mdb":
mdb_copy(os.path.join(private_dir, pfile), mdb_copy(os.path.join(private_dir, pfile),
os.path.join(dns_dir, pfile)) os.path.join(dns_dir, pfile))
else: else:
tdb_copy(os.path.join(private_dir, pfile), tdb_copy(os.path.join(private_dir, pfile),
os.path.join(dns_dir, pfile)) os.path.join(dns_dir, pfile))
except: except:
logger.error( logger.error(
"Failed to setup database for BIND, AD based DNS cannot be used") "Failed to setup database for BIND, AD based DNS cannot be used")
@ -980,7 +983,7 @@ def create_named_conf(paths, realm, dnsdomain, dns_backend, logger):
def create_named_txt(path, realm, dnsdomain, dnsname, binddns_dir, def create_named_txt(path, realm, dnsdomain, dnsname, binddns_dir,
keytab_name): keytab_name):
"""Write out a file containing zone statements suitable for inclusion in a """Write out a file containing zone statements suitable for inclusion in a
named.conf file (including GSS-TSIG configuration). named.conf file (including GSS-TSIG configuration).
@ -1030,7 +1033,7 @@ def create_dns_partitions(samdb, domainsid, names, domaindn, forestdn,
dnsadmins_sid, fill_level): dnsadmins_sid, fill_level):
# Set up additional partitions (DomainDnsZones, ForstDnsZones) # Set up additional partitions (DomainDnsZones, ForstDnsZones)
setup_dns_partitions(samdb, domainsid, domaindn, forestdn, setup_dns_partitions(samdb, domainsid, domaindn, forestdn,
names.configdn, names.serverdn, fill_level) names.configdn, names.serverdn, fill_level)
# Set up MicrosoftDNS containers # Set up MicrosoftDNS containers
add_dns_container(samdb, domaindn, "DC=DomainDnsZones", domainsid, add_dns_container(samdb, domaindn, "DC=DomainDnsZones", domainsid,
@ -1089,8 +1092,8 @@ def fill_dns_data_partitions(samdb, domainsid, site, domaindn, forestdn,
def setup_ad_dns(samdb, secretsdb, names, paths, lp, logger, def setup_ad_dns(samdb, secretsdb, names, paths, lp, logger,
dns_backend, os_level, dnspass=None, hostip=None, hostip6=None, dns_backend, os_level, dnspass=None, hostip=None, hostip6=None,
targetdir=None, fill_level=FILL_FULL, backend_store=None): targetdir=None, fill_level=FILL_FULL, backend_store=None):
"""Provision DNS information (assuming GC role) """Provision DNS information (assuming GC role)
:param samdb: LDB object connected to sam.ldb file :param samdb: LDB object connected to sam.ldb file
@ -1190,9 +1193,9 @@ def setup_ad_dns(samdb, secretsdb, names, paths, lp, logger,
def setup_bind9_dns(samdb, secretsdb, names, paths, lp, logger, def setup_bind9_dns(samdb, secretsdb, names, paths, lp, logger,
dns_backend, os_level, site=None, dnspass=None, hostip=None, dns_backend, os_level, site=None, dnspass=None, hostip=None,
hostip6=None, targetdir=None, key_version_number=None, hostip6=None, targetdir=None, key_version_number=None,
backend_store=None): backend_store=None):
"""Provision DNS information (assuming BIND9 backend in DC role) """Provision DNS information (assuming BIND9 backend in DC role)
:param samdb: LDB object connected to sam.ldb file :param samdb: LDB object connected to sam.ldb file

View File

@ -160,7 +160,7 @@ def remove_dns_references(samdb, logger, dnsHostName, ignore_no_name=False):
if len(a_recs) != orig_num_recs: if len(a_recs) != orig_num_recs:
logger.info("updating %s keeping %d values, removing %s values" % \ logger.info("updating %s keeping %d values, removing %s values" % \
(a_name, len(a_recs), orig_num_recs - len(a_recs))) (a_name, len(a_recs), orig_num_recs - len(a_recs)))
samdb.dns_replace(a_name, a_recs) samdb.dns_replace(a_name, a_recs)
remove_hanging_dns_references(samdb, logger, dnsHostNameUpper, zones) remove_hanging_dns_references(samdb, logger, dnsHostNameUpper, zones)
@ -305,7 +305,7 @@ def offline_remove_ntds_dc(samdb,
try: try:
msgs = samdb.search(base=ntds_dn, expression="objectClass=ntdsDSA", msgs = samdb.search(base=ntds_dn, expression="objectClass=ntdsDSA",
attrs=["objectGUID"], scope=ldb.SCOPE_BASE) attrs=["objectGUID"], scope=ldb.SCOPE_BASE)
except LdbError as e5: except LdbError as e5:
(enum, estr) = e5.args (enum, estr) = e5.args
if enum == ldb.ERR_NO_SUCH_OBJECT: if enum == ldb.ERR_NO_SUCH_OBJECT:
@ -388,7 +388,7 @@ def remove_dc(samdb, logger, dc_name):
attrs=[], attrs=[],
expression="(&(objectClass=server)" expression="(&(objectClass=server)"
"(cn=%s))" "(cn=%s))"
% ldb.binary_encode(dc_name)) % ldb.binary_encode(dc_name))
except LdbError as e3: except LdbError as e3:
(enum, estr) = e3.args (enum, estr) = e3.args
raise DemoteException("Failure checking if %s is an server " raise DemoteException("Failure checking if %s is an server "

View File

@ -60,8 +60,8 @@ class SamDB(samba.Ldb):
self.url = url self.url = url
super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir, super(SamDB, self).__init__(url=url, lp=lp, modules_dir=modules_dir,
session_info=session_info, credentials=credentials, flags=flags, session_info=session_info, credentials=credentials, flags=flags,
options=options) options=options)
if global_schema: if global_schema:
dsdb._dsdb_set_global_schema(self) dsdb._dsdb_set_global_schema(self)
@ -76,7 +76,7 @@ class SamDB(samba.Ldb):
self.url = url self.url = url
super(SamDB, self).connect(url=url, flags=flags, super(SamDB, self).connect(url=url, flags=flags,
options=options) options=options)
def am_rodc(self): def am_rodc(self):
'''return True if we are an RODC''' '''return True if we are an RODC'''
@ -200,8 +200,8 @@ pwdLastSet: 0
# The new user record. Note the reliance on the SAMLDB module which # The new user record. Note the reliance on the SAMLDB module which
# fills in the default informations # fills in the default informations
ldbmessage = {"dn": group_dn, ldbmessage = {"dn": group_dn,
"sAMAccountName": groupname, "sAMAccountName": groupname,
"objectClass": "group"} "objectClass": "group"}
if grouptype is not None: if grouptype is not None:
ldbmessage["groupType"] = normalise_int32(grouptype) ldbmessage["groupType"] = normalise_int32(grouptype)
@ -237,7 +237,7 @@ pwdLastSet: 0
self.transaction_start() self.transaction_start()
try: try:
targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression=groupfilter, attrs=[]) expression=groupfilter, attrs=[])
if len(targetgroup) == 0: if len(targetgroup) == 0:
raise Exception('Unable to find group "%s"' % groupname) raise Exception('Unable to find group "%s"' % groupname)
assert(len(targetgroup) == 1) assert(len(targetgroup) == 1)
@ -264,7 +264,7 @@ pwdLastSet: 0
self.transaction_start() self.transaction_start()
try: try:
targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, targetgroup = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression=groupfilter, attrs=['member']) expression=groupfilter, attrs=['member'])
if len(targetgroup) == 0: if len(targetgroup) == 0:
raise Exception('Unable to find group "%s"' % groupname) raise Exception('Unable to find group "%s"' % groupname)
assert(len(targetgroup) == 1) assert(len(targetgroup) == 1)
@ -324,15 +324,15 @@ member: %s
self.transaction_commit() self.transaction_commit()
def newuser(self, username, password, def newuser(self, username, password,
force_password_change_at_next_login_req=False, force_password_change_at_next_login_req=False,
useusernameascn=False, userou=None, surname=None, givenname=None, useusernameascn=False, userou=None, surname=None, givenname=None,
initials=None, profilepath=None, scriptpath=None, homedrive=None, initials=None, profilepath=None, scriptpath=None, homedrive=None,
homedirectory=None, jobtitle=None, department=None, company=None, homedirectory=None, jobtitle=None, department=None, company=None,
description=None, mailaddress=None, internetaddress=None, description=None, mailaddress=None, internetaddress=None,
telephonenumber=None, physicaldeliveryoffice=None, sd=None, telephonenumber=None, physicaldeliveryoffice=None, sd=None,
setpassword=True, uidnumber=None, gidnumber=None, gecos=None, setpassword=True, uidnumber=None, gidnumber=None, gecos=None,
loginshell=None, uid=None, nisdomain=None, unixhome=None, loginshell=None, uid=None, nisdomain=None, unixhome=None,
smartcard_required=False): smartcard_required=False):
"""Adds a new user with additional parameters """Adds a new user with additional parameters
:param username: Name of the new user :param username: Name of the new user
@ -451,7 +451,7 @@ member: %s
ldbmessage2 = None ldbmessage2 = None
if any(map(lambda b: b is not None, (uid, uidnumber, gidnumber, gecos, if any(map(lambda b: b is not None, (uid, uidnumber, gidnumber, gecos,
loginshell, nisdomain, unixhome))): loginshell, nisdomain, unixhome))):
ldbmessage2 = ldb.Message() ldbmessage2 = ldb.Message()
ldbmessage2.dn = ldb.Dn(self, user_dn) ldbmessage2.dn = ldb.Dn(self, user_dn)
if uid is not None: if uid is not None:
@ -576,7 +576,7 @@ member: %s
self.transaction_commit() self.transaction_commit()
def setpassword(self, search_filter, password, def setpassword(self, search_filter, password,
force_change_at_next_login=False, username=None): force_change_at_next_login=False, username=None):
"""Sets the password for a user """Sets the password for a user
:param search_filter: LDAP filter to find the user (eg :param search_filter: LDAP filter to find the user (eg
@ -630,8 +630,8 @@ unicodePwd:: %s
self.transaction_start() self.transaction_start()
try: try:
res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE, res = self.search(base=self.domain_dn(), scope=ldb.SCOPE_SUBTREE,
expression=search_filter, expression=search_filter,
attrs=["userAccountControl", "accountExpires"]) attrs=["userAccountControl", "accountExpires"])
if len(res) == 0: if len(res) == 0:
raise Exception('Unable to find user "%s"' % search_filter) raise Exception('Unable to find user "%s"' % search_filter)
assert(len(res) == 1) assert(len(res) == 1)
@ -674,7 +674,7 @@ accountExpires: %u
return dsdb._samdb_get_domain_sid(self) return dsdb._samdb_get_domain_sid(self)
domain_sid = property(get_domain_sid, set_domain_sid, domain_sid = property(get_domain_sid, set_domain_sid,
"SID for the domain") "SID for the domain")
def set_invocation_id(self, invocation_id): def set_invocation_id(self, invocation_id):
"""Set the invocation id for this SamDB handle. """Set the invocation id for this SamDB handle.
@ -688,16 +688,16 @@ accountExpires: %u
return dsdb._samdb_ntds_invocation_id(self) return dsdb._samdb_ntds_invocation_id(self)
invocation_id = property(get_invocation_id, set_invocation_id, invocation_id = property(get_invocation_id, set_invocation_id,
"Invocation ID GUID") "Invocation ID GUID")
def get_oid_from_attid(self, attid): def get_oid_from_attid(self, attid):
return dsdb._dsdb_get_oid_from_attid(self, attid) return dsdb._dsdb_get_oid_from_attid(self, attid)
def get_attid_from_lDAPDisplayName(self, ldap_display_name, def get_attid_from_lDAPDisplayName(self, ldap_display_name,
is_schema_nc=False): is_schema_nc=False):
'''return the attribute ID for a LDAP attribute as an integer as found in DRSUAPI''' '''return the attribute ID for a LDAP attribute as an integer as found in DRSUAPI'''
return dsdb._dsdb_get_attid_from_lDAPDisplayName(self, return dsdb._dsdb_get_attid_from_lDAPDisplayName(self,
ldap_display_name, is_schema_nc) ldap_display_name, is_schema_nc)
def get_syntax_oid_from_lDAPDisplayName(self, ldap_display_name): def get_syntax_oid_from_lDAPDisplayName(self, ldap_display_name):
'''return the syntax OID for a LDAP attribute as a string''' '''return the syntax OID for a LDAP attribute as a string'''
@ -802,7 +802,7 @@ schemaUpdateNow: 1
res = self.search(expression="objectClass=attributeSchema", res = self.search(expression="objectClass=attributeSchema",
controls=["search_options:1:2"], controls=["search_options:1:2"],
attrs=["attributeID", attrs=["attributeID",
"lDAPDisplayName"]) "lDAPDisplayName"])
if len(res) > 0: if len(res) > 0:
for e in res: for e in res:
strDisplay = str(e.get("lDAPDisplayName")) strDisplay = str(e.get("lDAPDisplayName"))
@ -839,7 +839,7 @@ schemaUpdateNow: 1
return None return None
def set_attribute_replmetadata_version(self, dn, att, value, def set_attribute_replmetadata_version(self, dn, att, value,
addifnotexist=False): addifnotexist=False):
res = self.search(expression="distinguishedName=%s" % dn, res = self.search(expression="distinguishedName=%s" % dn,
scope=ldb.SCOPE_SUBTREE, scope=ldb.SCOPE_SUBTREE,
controls=["search_options:1:2"], controls=["search_options:1:2"],
@ -887,9 +887,10 @@ schemaUpdateNow: 1
replBlob = ndr_pack(repl) replBlob = ndr_pack(repl)
msg = ldb.Message() msg = ldb.Message()
msg.dn = res[0].dn msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, msg["replPropertyMetaData"] = \
ldb.FLAG_MOD_REPLACE, ldb.MessageElement(replBlob,
"replPropertyMetaData") ldb.FLAG_MOD_REPLACE,
"replPropertyMetaData")
self.modify(msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"]) self.modify(msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
def write_prefixes_from_schema(self): def write_prefixes_from_schema(self):
@ -988,11 +989,14 @@ schemaUpdateNow: 1
m.dn = ldb.Dn(self, "CN=Directory Service,CN=Windows NT,CN=Services,%s" m.dn = ldb.Dn(self, "CN=Directory Service,CN=Windows NT,CN=Services,%s"
% self.get_config_basedn().get_linearized()) % self.get_config_basedn().get_linearized())
if dsheuristics is not None: if dsheuristics is not None:
m["dSHeuristics"] = ldb.MessageElement(dsheuristics, m["dSHeuristics"] = \
ldb.FLAG_MOD_REPLACE, "dSHeuristics") ldb.MessageElement(dsheuristics,
ldb.FLAG_MOD_REPLACE,
"dSHeuristics")
else: else:
m["dSHeuristics"] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, m["dSHeuristics"] = \
"dSHeuristics") ldb.MessageElement([], ldb.FLAG_MOD_DELETE,
"dSHeuristics")
self.modify(m) self.modify(m)
def get_dsheuristics(self): def get_dsheuristics(self):

View File

@ -65,8 +65,8 @@ class Schema(object):
# the schema files (and corresponding object version) that we know about # the schema files (and corresponding object version) that we know about
base_schemas = { base_schemas = {
"2008_R2_old" : ("MS-AD_Schema_2K8_R2_Attributes.txt", "2008_R2_old" : ("MS-AD_Schema_2K8_R2_Attributes.txt",
"MS-AD_Schema_2K8_R2_Classes.txt", "MS-AD_Schema_2K8_R2_Classes.txt",
47), 47),
"2008_R2" : ("Attributes_for_AD_DS__Windows_Server_2008_R2.ldf", "2008_R2" : ("Attributes_for_AD_DS__Windows_Server_2008_R2.ldf",
"Classes_for_AD_DS__Windows_Server_2008_R2.ldf", "Classes_for_AD_DS__Windows_Server_2008_R2.ldf",
47), 47),
@ -114,7 +114,7 @@ class Schema(object):
self.schema_data += open(file, 'r').read() self.schema_data += open(file, 'r').read()
self.schema_data = substitute_var(self.schema_data, self.schema_data = substitute_var(self.schema_data,
{"SCHEMADN": schemadn}) {"SCHEMADN": schemadn})
check_all_substituted(self.schema_data) check_all_substituted(self.schema_data)
schema_version = str(Schema.get_version(base_schema)) schema_version = str(Schema.get_version(base_schema))
@ -248,4 +248,4 @@ def ldb_with_schema(schemadn="cn=schema,cn=configuration,dc=example,dc=com",
else: else:
domainsid = security.dom_sid(domainsid) domainsid = security.dom_sid(domainsid)
return Schema(domainsid, schemadn=schemadn, return Schema(domainsid, schemadn=schemadn,
override_prefixmap=override_prefixmap) override_prefixmap=override_prefixmap)

View File

@ -55,7 +55,7 @@ def create_site(samdb, configDn, siteName):
""" """
ret = samdb.search(base=configDn, scope=ldb.SCOPE_SUBTREE, ret = samdb.search(base=configDn, scope=ldb.SCOPE_SUBTREE,
expression='(&(objectclass=Site)(cn=%s))' % siteName) expression='(&(objectclass=Site)(cn=%s))' % siteName)
if len(ret) != 0: if len(ret) != 0:
raise SiteAlreadyExistsException('A site with the name %s already exists' % siteName) raise SiteAlreadyExistsException('A site with the name %s already exists' % siteName)

View File

@ -57,7 +57,7 @@ class RemotedTestCase(unittest.TestCase):
def error(self, label): def error(self, label):
raise NotImplementedError("%s on RemotedTestCases is not permitted." % raise NotImplementedError("%s on RemotedTestCases is not permitted." %
label) label)
def setUp(self): def setUp(self):
self.error("setUp") self.error("setUp")

View File

@ -93,7 +93,7 @@ class AuthLogTests(samba.tests.auth_log_base.AuthLogTestBase):
self.assertEquals("Authentication", msg["type"]) self.assertEquals("Authentication", msg["type"])
self.assertEquals("NT_STATUS_OK", msg["Authentication"]["status"]) self.assertEquals("NT_STATUS_OK", msg["Authentication"]["status"])
self._assert_ncacn_np_serviceDescription(binding, self._assert_ncacn_np_serviceDescription(binding,
msg["Authentication"]["serviceDescription"]) msg["Authentication"]["serviceDescription"])
self.assertEquals(authTypes[1], self.assertEquals(authTypes[1],
msg["Authentication"]["authDescription"]) msg["Authentication"]["authDescription"])
@ -101,7 +101,7 @@ class AuthLogTests(samba.tests.auth_log_base.AuthLogTestBase):
msg = messages[1] msg = messages[1]
self.assertEquals("Authorization", msg["type"]) self.assertEquals("Authorization", msg["type"])
self._assert_ncacn_np_serviceDescription(binding, self._assert_ncacn_np_serviceDescription(binding,
msg["Authorization"]["serviceDescription"]) msg["Authorization"]["serviceDescription"])
self.assertEquals(authTypes[2], msg["Authorization"]["authType"]) self.assertEquals(authTypes[2], msg["Authorization"]["authType"])
self.assertEquals("SMB", msg["Authorization"]["transportProtection"]) self.assertEquals("SMB", msg["Authorization"]["transportProtection"])
self.assertTrue(self.is_guid(msg["Authorization"]["sessionId"])) self.assertTrue(self.is_guid(msg["Authorization"]["sessionId"]))
@ -161,7 +161,7 @@ class AuthLogTests(samba.tests.auth_log_base.AuthLogTestBase):
msg = messages[2] msg = messages[2]
self.assertEquals("Authorization", msg["type"]) self.assertEquals("Authorization", msg["type"])
self._assert_ncacn_np_serviceDescription(binding, self._assert_ncacn_np_serviceDescription(binding,
msg["Authorization"]["serviceDescription"]) msg["Authorization"]["serviceDescription"])
self.assertEquals(authTypes[3], msg["Authorization"]["authType"]) self.assertEquals(authTypes[3], msg["Authorization"]["authType"])
self.assertEquals("SMB", msg["Authorization"]["transportProtection"]) self.assertEquals("SMB", msg["Authorization"]["transportProtection"])
self.assertTrue(self.is_guid(msg["Authorization"]["sessionId"])) self.assertTrue(self.is_guid(msg["Authorization"]["sessionId"]))
@ -486,7 +486,7 @@ class AuthLogTests(samba.tests.auth_log_base.AuthLogTestBase):
creds = self.insta_creds(template=self.get_credentials()) creds = self.insta_creds(template=self.get_credentials())
creds.set_bind_dn("%s\\%s" % (creds.get_domain(), creds.set_bind_dn("%s\\%s" % (creds.get_domain(),
creds.get_username())) creds.get_username()))
self.samdb = SamDB(url="ldaps://%s" % os.environ["SERVER"], self.samdb = SamDB(url="ldaps://%s" % os.environ["SERVER"],
lp=self.get_loadparm(), lp=self.get_loadparm(),
@ -517,7 +517,7 @@ class AuthLogTests(samba.tests.auth_log_base.AuthLogTestBase):
creds = self.insta_creds(template=self.get_credentials()) creds = self.insta_creds(template=self.get_credentials())
creds.set_password("badPassword") creds.set_password("badPassword")
creds.set_bind_dn("%s\\%s" % (creds.get_domain(), creds.set_bind_dn("%s\\%s" % (creds.get_domain(),
creds.get_username())) creds.get_username()))
thrown = False thrown = False
try: try:

View File

@ -30,24 +30,24 @@ class SubstituteVarTestCase(TestCase):
def test_nothing(self): def test_nothing(self):
self.assertEquals("foo bar", self.assertEquals("foo bar",
samba.substitute_var("foo bar", {"bar": "bla"})) samba.substitute_var("foo bar", {"bar": "bla"}))
def test_replace(self): def test_replace(self):
self.assertEquals("foo bla", self.assertEquals("foo bla",
samba.substitute_var("foo ${bar}", {"bar": "bla"})) samba.substitute_var("foo ${bar}", {"bar": "bla"}))
def test_broken(self): def test_broken(self):
self.assertEquals("foo ${bdkjfhsdkfh sdkfh ", self.assertEquals("foo ${bdkjfhsdkfh sdkfh ",
samba.substitute_var("foo ${bdkjfhsdkfh sdkfh ", {"bar": "bla"})) samba.substitute_var("foo ${bdkjfhsdkfh sdkfh ", {"bar": "bla"}))
def test_unknown_var(self): def test_unknown_var(self):
self.assertEquals("foo ${bla} gsff", self.assertEquals("foo ${bla} gsff",
samba.substitute_var("foo ${bla} gsff", {"bar": "bla"})) samba.substitute_var("foo ${bla} gsff", {"bar": "bla"}))
def test_check_all_substituted(self): def test_check_all_substituted(self):
samba.check_all_substituted("nothing to see here") samba.check_all_substituted("nothing to see here")
self.assertRaises(Exception, samba.check_all_substituted, self.assertRaises(Exception, samba.check_all_substituted,
"Not subsituted: ${FOOBAR}") "Not subsituted: ${FOOBAR}")
class ArcfourTestCase(TestCase): class ArcfourTestCase(TestCase):
@ -73,7 +73,7 @@ class LdbExtensionTests(TestCaseInTempDir):
try: try:
l.add({"dn": "foo=dc", "bar": "bla"}) l.add({"dn": "foo=dc", "bar": "bla"})
self.assertEquals(b"bla", self.assertEquals(b"bla",
l.searchone(basedn=ldb.Dn(l, "foo=dc"), attribute="bar")) l.searchone(basedn=ldb.Dn(l, "foo=dc"), attribute="bar"))
finally: finally:
del l del l
os.unlink(path) os.unlink(path)

View File

@ -28,33 +28,33 @@ class BareTestCase(samba.tests.TestCase):
def test_bare(self): def test_bare(self):
# Connect to the echo pipe # Connect to the echo pipe
x = ClientConnection("ncalrpc:localhost[DEFAULT]", x = ClientConnection("ncalrpc:localhost[DEFAULT]",
("60a15ec5-4de8-11d7-a637-005056a20182", 1), ("60a15ec5-4de8-11d7-a637-005056a20182", 1),
lp_ctx=samba.tests.env_loadparm()) lp_ctx=samba.tests.env_loadparm())
self.assertEquals(b"\x01\x00\x00\x00", x.request(0, chr(0) * 4)) self.assertEquals(b"\x01\x00\x00\x00", x.request(0, chr(0) * 4))
def test_two_contexts(self): def test_two_contexts(self):
x = ClientConnection("ncalrpc:localhost[DEFAULT]", x = ClientConnection("ncalrpc:localhost[DEFAULT]",
("12345778-1234-abcd-ef00-0123456789ac", 1), ("12345778-1234-abcd-ef00-0123456789ac", 1),
lp_ctx=samba.tests.env_loadparm()) lp_ctx=samba.tests.env_loadparm())
y = ClientConnection("ncalrpc:localhost", y = ClientConnection("ncalrpc:localhost",
("60a15ec5-4de8-11d7-a637-005056a20182", 1), ("60a15ec5-4de8-11d7-a637-005056a20182", 1),
basis_connection=x, lp_ctx=samba.tests.env_loadparm()) basis_connection=x, lp_ctx=samba.tests.env_loadparm())
self.assertEquals(24, len(x.request(0, chr(0) * 8))) self.assertEquals(24, len(x.request(0, chr(0) * 8)))
self.assertEquals(b"\x01\x00\x00\x00", y.request(0, chr(0) * 4)) self.assertEquals(b"\x01\x00\x00\x00", y.request(0, chr(0) * 4))
def test_bare_tcp(self): def test_bare_tcp(self):
# Connect to the echo pipe # Connect to the echo pipe
x = ClientConnection("ncacn_ip_tcp:%s" % os.environ["SERVER"], x = ClientConnection("ncacn_ip_tcp:%s" % os.environ["SERVER"],
("60a15ec5-4de8-11d7-a637-005056a20182", 1), ("60a15ec5-4de8-11d7-a637-005056a20182", 1),
lp_ctx=samba.tests.env_loadparm()) lp_ctx=samba.tests.env_loadparm())
self.assertEquals(b"\x01\x00\x00\x00", x.request(0, chr(0) * 4)) self.assertEquals(b"\x01\x00\x00\x00", x.request(0, chr(0) * 4))
def test_two_contexts_tcp(self): def test_two_contexts_tcp(self):
x = ClientConnection("ncacn_ip_tcp:%s" % os.environ["SERVER"], x = ClientConnection("ncacn_ip_tcp:%s" % os.environ["SERVER"],
("12345778-1234-abcd-ef00-0123456789ac", 1), ("12345778-1234-abcd-ef00-0123456789ac", 1),
lp_ctx=samba.tests.env_loadparm()) lp_ctx=samba.tests.env_loadparm())
y = ClientConnection("ncacn_ip_tcp:%s" % os.environ["SERVER"], y = ClientConnection("ncacn_ip_tcp:%s" % os.environ["SERVER"],
("60a15ec5-4de8-11d7-a637-005056a20182", 1), ("60a15ec5-4de8-11d7-a637-005056a20182", 1),
basis_connection=x, lp_ctx=samba.tests.env_loadparm()) basis_connection=x, lp_ctx=samba.tests.env_loadparm())
self.assertEquals(24, len(x.request(0, chr(0) * 8))) self.assertEquals(24, len(x.request(0, chr(0) * 8)))
self.assertEquals(b"\x01\x00\x00\x00", y.request(0, chr(0) * 4)) self.assertEquals(b"\x01\x00\x00\x00", y.request(0, chr(0) * 4))

View File

@ -68,9 +68,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
# self.assertEquals(rep.u._pad1, '\0' * 2) # self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -113,9 +113,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
# self.assertEquals(rep.u._pad1, '\0' * 2) # self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -135,9 +135,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
# self.assertEquals(rep.u._pad1, '\0' * 2) # self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -366,7 +366,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id, self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id,
auth_length=0) auth_length=0)
self.assertEquals(rep.u.reject_reason, self.assertEquals(rep.u.reject_reason,
dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
self.assertEquals(rep.u.num_versions, 1) self.assertEquals(rep.u.num_versions, 1)
self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers) self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers)
self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor) self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor)
@ -381,7 +381,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id, self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id,
auth_length=0) auth_length=0)
self.assertEquals(rep.u.reject_reason, self.assertEquals(rep.u.reject_reason,
dcerpc.DCERPC_BIND_NAK_REASON_PROTOCOL_VERSION_NOT_SUPPORTED) dcerpc.DCERPC_BIND_NAK_REASON_PROTOCOL_VERSION_NOT_SUPPORTED)
self.assertEquals(rep.u.num_versions, 1) self.assertEquals(rep.u.num_versions, 1)
self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers) self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers)
self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor) self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor)
@ -412,9 +412,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -432,7 +432,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id, self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id,
auth_length=0) auth_length=0)
self.assertEquals(rep.u.reject_reason, self.assertEquals(rep.u.reject_reason,
dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
self.assertEquals(rep.u.num_versions, 1) self.assertEquals(rep.u.num_versions, 1)
self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers) self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers)
self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor) self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor)
@ -452,7 +452,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id, self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id,
auth_length=0) auth_length=0)
self.assertEquals(rep.u.reject_reason, self.assertEquals(rep.u.reject_reason,
dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
self.assertEquals(rep.u.num_versions, 1) self.assertEquals(rep.u.num_versions, 1)
self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers) self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers)
self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor) self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor)
@ -488,9 +488,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -541,9 +541,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -561,9 +561,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -611,9 +611,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -631,9 +631,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -669,9 +669,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -693,7 +693,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id, self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id,
auth_length=0) auth_length=0)
self.assertEquals(rep.u.reject_reason, self.assertEquals(rep.u.reject_reason,
dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
self.assertEquals(rep.u.num_versions, 1) self.assertEquals(rep.u.num_versions, 1)
self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers) self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers)
self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor) self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor)
@ -731,9 +731,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -792,9 +792,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -854,9 +854,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -883,9 +883,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -932,9 +932,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -958,9 +958,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -997,9 +997,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1036,9 +1036,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1082,14 +1082,14 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 2) self.assertEquals(rep.u.num_results, 2)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.ctx_list[1].result, self.assertEquals(rep.u.ctx_list[1].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[1].reason, self.assertEquals(rep.u.ctx_list[1].reason,
dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1119,14 +1119,14 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 2) self.assertEquals(rep.u.num_results, 2)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.ctx_list[1].result, self.assertEquals(rep.u.ctx_list[1].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[1].reason, self.assertEquals(rep.u.ctx_list[1].reason,
dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1169,14 +1169,14 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 2) self.assertEquals(rep.u.num_results, 2)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.ctx_list[1].result, self.assertEquals(rep.u.ctx_list[1].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[1].reason, self.assertEquals(rep.u.ctx_list[1].reason,
dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1233,14 +1233,14 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 2) self.assertEquals(rep.u.num_results, 2)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.ctx_list[1].result, self.assertEquals(rep.u.ctx_list[1].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[1].reason, self.assertEquals(rep.u.ctx_list[1].reason,
dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1270,14 +1270,14 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 2) self.assertEquals(rep.u.num_results, 2)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.ctx_list[1].result, self.assertEquals(rep.u.ctx_list[1].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[1].reason, self.assertEquals(rep.u.ctx_list[1].reason,
dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_TRANSFER_SYNTAXES_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[1].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1321,7 +1321,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK) dcerpc.DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK)
self.assertEquals(rep.u.ctx_list[0].reason, features) self.assertEquals(rep.u.ctx_list[0].reason, features)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1358,7 +1358,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK) dcerpc.DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK)
self.assertEquals(rep.u.ctx_list[0].reason, features1) self.assertEquals(rep.u.ctx_list[0].reason, features1)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1393,9 +1393,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION) dcerpc.DCERPC_BIND_ACK_RESULT_PROVIDER_REJECTION)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED) dcerpc.DCERPC_BIND_ACK_REASON_ABSTRACT_SYNTAX_NOT_SUPPORTED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1428,7 +1428,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id, self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id,
auth_length=0) auth_length=0)
self.assertEquals(rep.u.reject_reason, self.assertEquals(rep.u.reject_reason,
dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
self.assertEquals(rep.u.num_versions, 1) self.assertEquals(rep.u.num_versions, 1)
self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers) self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers)
self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor) self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor)
@ -1467,7 +1467,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK) dcerpc.DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK)
self.assertEquals(rep.u.ctx_list[0].reason, features) self.assertEquals(rep.u.ctx_list[0].reason, features)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1503,13 +1503,13 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK) dcerpc.DCERPC_BIND_ACK_RESULT_NEGOTIATE_ACK)
self.assertEquals(rep.u.ctx_list[0].reason, features1) self.assertEquals(rep.u.ctx_list[0].reason, features1)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, zero_syntax)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
def _test_auth_type_level_bind_nak(self, auth_type, auth_level, creds=None, def _test_auth_type_level_bind_nak(self, auth_type, auth_level, creds=None,
reason=dcerpc.DCERPC_BIND_NAK_REASON_INVALID_AUTH_TYPE): reason=dcerpc.DCERPC_BIND_NAK_REASON_INVALID_AUTH_TYPE):
ndr32 = base.transfer_syntax_ndr() ndr32 = base.transfer_syntax_ndr()
tsf1_list = [ndr32] tsf1_list = [ndr32]
@ -1525,10 +1525,10 @@ class TestDCERPC_BIND(RawDCERPCTest):
if creds is not None: if creds is not None:
# We always start with DCERPC_AUTH_LEVEL_INTEGRITY # We always start with DCERPC_AUTH_LEVEL_INTEGRITY
auth_context = self.get_auth_context_creds(creds, auth_context = self.get_auth_context_creds(creds,
auth_type=auth_type, auth_type=auth_type,
auth_level=auth_level, auth_level=auth_level,
auth_context_id=auth_context_id, auth_context_id=auth_context_id,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY) g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY)
from_server = "" from_server = ""
(finished, to_server) = auth_context["gensec"].update(from_server) (finished, to_server) = auth_context["gensec"].update(from_server)
self.assertFalse(finished) self.assertFalse(finished)
@ -1566,11 +1566,11 @@ class TestDCERPC_BIND(RawDCERPCTest):
def _test_auth_none_level_bind(self, auth_level, def _test_auth_none_level_bind(self, auth_level,
reason=dcerpc.DCERPC_BIND_NAK_REASON_INVALID_AUTH_TYPE): reason=dcerpc.DCERPC_BIND_NAK_REASON_INVALID_AUTH_TYPE):
return self._test_auth_type_level_bind_nak(auth_type=dcerpc.DCERPC_AUTH_LEVEL_NONE, return self._test_auth_type_level_bind_nak(auth_type=dcerpc.DCERPC_AUTH_LEVEL_NONE,
auth_level=auth_level, reason=reason) auth_level=auth_level, reason=reason)
def test_auth_none_none_bind(self): def test_auth_none_none_bind(self):
return self._test_auth_none_level_bind(dcerpc.DCERPC_AUTH_LEVEL_NONE, return self._test_auth_none_level_bind(dcerpc.DCERPC_AUTH_LEVEL_NONE,
reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
def test_auth_none_connect_bind(self): def test_auth_none_connect_bind(self):
return self._test_auth_none_level_bind(dcerpc.DCERPC_AUTH_LEVEL_CONNECT) return self._test_auth_none_level_bind(dcerpc.DCERPC_AUTH_LEVEL_CONNECT)
@ -1589,15 +1589,15 @@ class TestDCERPC_BIND(RawDCERPCTest):
def test_auth_none_0_bind(self): def test_auth_none_0_bind(self):
return self._test_auth_none_level_bind(0, return self._test_auth_none_level_bind(0,
reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
def test_auth_none_7_bind(self): def test_auth_none_7_bind(self):
return self._test_auth_none_level_bind(7, return self._test_auth_none_level_bind(7,
reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
def test_auth_none_255_bind(self): def test_auth_none_255_bind(self):
return self._test_auth_none_level_bind(255, return self._test_auth_none_level_bind(255,
reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
def _test_auth_none_level_request(self, auth_level): def _test_auth_none_level_request(self, auth_level):
ndr32 = base.transfer_syntax_ndr() ndr32 = base.transfer_syntax_ndr()
@ -1628,9 +1628,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(len(rep.u.auth_info), 0) self.assertEquals(len(rep.u.auth_info), 0)
@ -1717,9 +1717,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1748,9 +1748,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -1875,9 +1875,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertEquals(rep.u.auth_info, '\0' * 0) self.assertEquals(rep.u.auth_info, '\0' * 0)
@ -2525,10 +2525,10 @@ class TestDCERPC_BIND(RawDCERPCTest):
ctx = self.prepare_presentation(abstract, ndr32) ctx = self.prepare_presentation(abstract, ndr32)
req1 = self.generate_request(call_id = 1, req1 = self.generate_request(call_id = 1,
pfc_flags=dcerpc.DCERPC_PFC_FLAG_FIRST, pfc_flags=dcerpc.DCERPC_PFC_FLAG_FIRST,
context_id=ctx.context_id, context_id=ctx.context_id,
opnum=0, opnum=0,
stub="") stub="")
self.send_pdu(req1) self.send_pdu(req1)
rep = self.recv_pdu(timeout=0.1) rep = self.recv_pdu(timeout=0.1)
self.assertIsNone(rep) self.assertIsNone(rep)
@ -2542,9 +2542,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
# And now try a new request # And now try a new request
req2 = self.generate_request(call_id = 2, req2 = self.generate_request(call_id = 2,
context_id=ctx.context_id, context_id=ctx.context_id,
opnum=0, opnum=0,
stub="") stub="")
self.send_pdu(req2) self.send_pdu(req2)
rep = self.recv_pdu() rep = self.recv_pdu()
self.verify_pdu(rep, dcerpc.DCERPC_PKT_FAULT, req1.call_id, self.verify_pdu(rep, dcerpc.DCERPC_PKT_FAULT, req1.call_id,
@ -2573,10 +2573,10 @@ class TestDCERPC_BIND(RawDCERPCTest):
pfc_flags=pfc_flags) pfc_flags=pfc_flags)
req1 = self.generate_request(call_id = 1, req1 = self.generate_request(call_id = 1,
pfc_flags=dcerpc.DCERPC_PFC_FLAG_FIRST, pfc_flags=dcerpc.DCERPC_PFC_FLAG_FIRST,
context_id=ctx.context_id, context_id=ctx.context_id,
opnum=0, opnum=0,
stub="") stub="")
self.send_pdu(req1) self.send_pdu(req1)
rep = self.recv_pdu(timeout=0.1) rep = self.recv_pdu(timeout=0.1)
self.assertIsNone(rep) self.assertIsNone(rep)
@ -2590,9 +2590,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
# And now try a new request # And now try a new request
req2 = self.generate_request(call_id = 2, req2 = self.generate_request(call_id = 2,
context_id=ctx.context_id-1, context_id=ctx.context_id-1,
opnum=0, opnum=0,
stub="") stub="")
self.send_pdu(req2) self.send_pdu(req2)
rep = self.recv_pdu() rep = self.recv_pdu()
self.verify_pdu(rep, dcerpc.DCERPC_PKT_FAULT, req2.call_id, self.verify_pdu(rep, dcerpc.DCERPC_PKT_FAULT, req2.call_id,
@ -2654,9 +2654,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -2687,9 +2687,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -2804,9 +2804,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -2837,9 +2837,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -2921,9 +2921,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3004,9 +3004,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3094,9 +3094,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3125,9 +3125,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3255,9 +3255,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3286,9 +3286,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3411,9 +3411,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.assertEquals(rep.u._pad1, '\0' * 2) self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3496,9 +3496,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3583,9 +3583,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3664,9 +3664,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3752,9 +3752,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3840,9 +3840,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3938,9 +3938,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -3984,9 +3984,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -4084,7 +4084,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id, self.verify_pdu(rep, dcerpc.DCERPC_PKT_BIND_NAK, req.call_id,
auth_length=0) auth_length=0)
self.assertEquals(rep.u.reject_reason, self.assertEquals(rep.u.reject_reason,
dcerpc.DCERPC_BIND_NAK_REASON_PROTOCOL_VERSION_NOT_SUPPORTED) dcerpc.DCERPC_BIND_NAK_REASON_PROTOCOL_VERSION_NOT_SUPPORTED)
self.assertEquals(rep.u.num_versions, 1) self.assertEquals(rep.u.num_versions, 1)
self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers) self.assertEquals(rep.u.versions[0].rpc_vers, req.rpc_vers)
self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor) self.assertEquals(rep.u.versions[0].rpc_vers_minor, req.rpc_vers_minor)
@ -4155,9 +4155,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -4268,9 +4268,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -4386,9 +4386,9 @@ class TestDCERPC_BIND(RawDCERPCTest):
#self.assertEquals(rep.u._pad1, '\0' * 2) #self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ndr32)
self.assertNotEquals(len(rep.u.auth_info), 0) self.assertNotEquals(len(rep.u.auth_info), 0)
a = self.parse_auth(rep.u.auth_info) a = self.parse_auth(rep.u.auth_info)
@ -4443,7 +4443,7 @@ class TestDCERPC_BIND(RawDCERPCTest):
return auth_context["gensec"] return auth_context["gensec"]
def _test_spnego_level_bind_nak(self, auth_level, def _test_spnego_level_bind_nak(self, auth_level,
reason=dcerpc.DCERPC_BIND_NAK_REASON_INVALID_CHECKSUM): reason=dcerpc.DCERPC_BIND_NAK_REASON_INVALID_CHECKSUM):
c = self.get_user_creds() c = self.get_user_creds()
return self._test_auth_type_level_bind_nak(auth_type=dcerpc.DCERPC_AUTH_TYPE_SPNEGO, return self._test_auth_type_level_bind_nak(auth_type=dcerpc.DCERPC_AUTH_TYPE_SPNEGO,
auth_level=auth_level, creds=c, reason=reason) auth_level=auth_level, creds=c, reason=reason)
@ -4540,91 +4540,91 @@ class TestDCERPC_BIND(RawDCERPCTest):
def test_spnego_none_bind(self): def test_spnego_none_bind(self):
return self._test_spnego_level_bind_nak(dcerpc.DCERPC_AUTH_LEVEL_NONE, return self._test_spnego_level_bind_nak(dcerpc.DCERPC_AUTH_LEVEL_NONE,
reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
def test_spnego_call_bind(self): def test_spnego_call_bind(self):
return self._test_spnego_level_bind_nak(dcerpc.DCERPC_AUTH_LEVEL_CALL, return self._test_spnego_level_bind_nak(dcerpc.DCERPC_AUTH_LEVEL_CALL,
reason=dcerpc.DCERPC_BIND_NAK_REASON_INVALID_CHECKSUM) reason=dcerpc.DCERPC_BIND_NAK_REASON_INVALID_CHECKSUM)
def test_spnego_0_bind(self): def test_spnego_0_bind(self):
return self._test_spnego_level_bind_nak(0, return self._test_spnego_level_bind_nak(0,
reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
def test_spnego_7_bind(self): def test_spnego_7_bind(self):
return self._test_spnego_level_bind_nak(7, return self._test_spnego_level_bind_nak(7,
reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
def test_spnego_255_bind(self): def test_spnego_255_bind(self):
return self._test_spnego_level_bind_nak(255, return self._test_spnego_level_bind_nak(255,
reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED) reason=dcerpc.DCERPC_BIND_NAK_REASON_NOT_SPECIFIED)
def test_spnego_connect_bind_none(self): def test_spnego_connect_bind_none(self):
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT) g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT)
def test_spnego_connect_bind_sign(self): def test_spnego_connect_bind_sign(self):
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY) g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY)
def test_spnego_connect_bind_seal(self): def test_spnego_connect_bind_seal(self):
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY) g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY)
def test_spnego_packet_bind_none(self): def test_spnego_packet_bind_none(self):
# DCERPC_AUTH_LEVEL_PACKET is handled as alias of # DCERPC_AUTH_LEVEL_PACKET is handled as alias of
# DCERPC_AUTH_LEVEL_INTEGRITY # DCERPC_AUTH_LEVEL_INTEGRITY
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PACKET, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PACKET,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT, g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT,
request_fault=dcerpc.DCERPC_FAULT_SEC_PKG_ERROR) request_fault=dcerpc.DCERPC_FAULT_SEC_PKG_ERROR)
def test_spnego_packet_bind_sign(self): def test_spnego_packet_bind_sign(self):
# DCERPC_AUTH_LEVEL_PACKET is handled as alias of # DCERPC_AUTH_LEVEL_PACKET is handled as alias of
# DCERPC_AUTH_LEVEL_INTEGRITY # DCERPC_AUTH_LEVEL_INTEGRITY
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PACKET, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PACKET,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY, g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY,
request_fault=dcerpc.DCERPC_NCA_S_OP_RNG_ERROR, request_fault=dcerpc.DCERPC_NCA_S_OP_RNG_ERROR,
response_fault_flags=dcerpc.DCERPC_PFC_FLAG_DID_NOT_EXECUTE) response_fault_flags=dcerpc.DCERPC_PFC_FLAG_DID_NOT_EXECUTE)
def test_spnego_packet_bind_sign(self): def test_spnego_packet_bind_sign(self):
# DCERPC_AUTH_LEVEL_PACKET is handled as alias of # DCERPC_AUTH_LEVEL_PACKET is handled as alias of
# DCERPC_AUTH_LEVEL_INTEGRITY # DCERPC_AUTH_LEVEL_INTEGRITY
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PACKET, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PACKET,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY, g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY,
request_fault=dcerpc.DCERPC_NCA_S_OP_RNG_ERROR, request_fault=dcerpc.DCERPC_NCA_S_OP_RNG_ERROR,
response_fault_flags=dcerpc.DCERPC_PFC_FLAG_DID_NOT_EXECUTE) response_fault_flags=dcerpc.DCERPC_PFC_FLAG_DID_NOT_EXECUTE)
def test_spnego_integrity_bind_none(self): def test_spnego_integrity_bind_none(self):
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT, g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT,
request_fault=dcerpc.DCERPC_FAULT_SEC_PKG_ERROR) request_fault=dcerpc.DCERPC_FAULT_SEC_PKG_ERROR)
def test_spnego_integrity_bind_sign(self): def test_spnego_integrity_bind_sign(self):
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY, g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY,
request_fault=dcerpc.DCERPC_NCA_S_OP_RNG_ERROR, request_fault=dcerpc.DCERPC_NCA_S_OP_RNG_ERROR,
response_fault_flags=dcerpc.DCERPC_PFC_FLAG_DID_NOT_EXECUTE) response_fault_flags=dcerpc.DCERPC_PFC_FLAG_DID_NOT_EXECUTE)
def test_spnego_integrity_bind_seal(self): def test_spnego_integrity_bind_seal(self):
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY, g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY,
request_fault=dcerpc.DCERPC_NCA_S_OP_RNG_ERROR, request_fault=dcerpc.DCERPC_NCA_S_OP_RNG_ERROR,
response_fault_flags=dcerpc.DCERPC_PFC_FLAG_DID_NOT_EXECUTE) response_fault_flags=dcerpc.DCERPC_PFC_FLAG_DID_NOT_EXECUTE)
def test_spnego_privacy_bind_none(self): def test_spnego_privacy_bind_none(self):
# This fails... # This fails...
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT, g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_CONNECT,
alter_fault=dcerpc.DCERPC_FAULT_SEC_PKG_ERROR) alter_fault=dcerpc.DCERPC_FAULT_SEC_PKG_ERROR)
def test_spnego_privacy_bind_sign(self): def test_spnego_privacy_bind_sign(self):
# This fails... # This fails...
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY, g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_INTEGRITY,
alter_fault=dcerpc.DCERPC_FAULT_SEC_PKG_ERROR) alter_fault=dcerpc.DCERPC_FAULT_SEC_PKG_ERROR)
def test_spnego_privacy_bind_seal(self): def test_spnego_privacy_bind_seal(self):
return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY, return self._test_spnego_level_bind(auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY,
g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY) g_auth_level=dcerpc.DCERPC_AUTH_LEVEL_PRIVACY)

View File

@ -189,9 +189,9 @@ class RawDCERPCTest(TestCase):
# self.assertEquals(rep.u._pad1, '\0' * port_pad) # self.assertEquals(rep.u._pad1, '\0' * port_pad)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
samba.dcerpc.dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) samba.dcerpc.dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
samba.dcerpc.dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) samba.dcerpc.dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ctx.transfer_syntaxes[0]) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ctx.transfer_syntaxes[0])
ack = rep ack = rep
if auth_context is None: if auth_context is None:
@ -242,9 +242,9 @@ class RawDCERPCTest(TestCase):
# self.assertEquals(rep.u._pad1, '\0' * 2) # self.assertEquals(rep.u._pad1, '\0' * 2)
self.assertEquals(rep.u.num_results, 1) self.assertEquals(rep.u.num_results, 1)
self.assertEquals(rep.u.ctx_list[0].result, self.assertEquals(rep.u.ctx_list[0].result,
samba.dcerpc.dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE) samba.dcerpc.dcerpc.DCERPC_BIND_ACK_RESULT_ACCEPTANCE)
self.assertEquals(rep.u.ctx_list[0].reason, self.assertEquals(rep.u.ctx_list[0].reason,
samba.dcerpc.dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED) samba.dcerpc.dcerpc.DCERPC_BIND_ACK_REASON_NOT_SPECIFIED)
self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ctx.transfer_syntaxes[0]) self.assertNDRSyntaxEquals(rep.u.ctx_list[0].syntax, ctx.transfer_syntaxes[0])
self.assertNotEquals(rep.auth_length, 0) self.assertNotEquals(rep.auth_length, 0)
self.assertGreater(len(rep.u.auth_info), samba.dcerpc.dcerpc.DCERPC_AUTH_TRAILER_LENGTH) self.assertGreater(len(rep.u.auth_info), samba.dcerpc.dcerpc.DCERPC_AUTH_TRAILER_LENGTH)
@ -687,10 +687,10 @@ class RawDCERPCTest(TestCase):
self.assertEqual(p.pfc_flags, pfc_flags) self.assertEqual(p.pfc_flags, pfc_flags)
self.assertEqual(p.drep, drep) self.assertEqual(p.drep, drep)
self.assertGreaterEqual(p.frag_length, self.assertGreaterEqual(p.frag_length,
samba.dcerpc.dcerpc.DCERPC_NCACN_PAYLOAD_OFFSET) samba.dcerpc.dcerpc.DCERPC_NCACN_PAYLOAD_OFFSET)
if len(ai) > samba.dcerpc.dcerpc.DCERPC_AUTH_TRAILER_LENGTH: if len(ai) > samba.dcerpc.dcerpc.DCERPC_AUTH_TRAILER_LENGTH:
self.assertEqual(p.auth_length, self.assertEqual(p.auth_length,
len(ai) - samba.dcerpc.dcerpc.DCERPC_AUTH_TRAILER_LENGTH) len(ai) - samba.dcerpc.dcerpc.DCERPC_AUTH_TRAILER_LENGTH)
elif auth_length is not None: elif auth_length is not None:
self.assertEqual(p.auth_length, auth_length) self.assertEqual(p.auth_length, auth_length)
else: else:

View File

@ -30,11 +30,11 @@ class WinregTests(RpcInterfaceTestCase):
def get_hklm(self): def get_hklm(self):
return self.conn.OpenHKLM(None, return self.conn.OpenHKLM(None,
winreg.KEY_QUERY_VALUE | winreg.KEY_ENUMERATE_SUB_KEYS) winreg.KEY_QUERY_VALUE | winreg.KEY_ENUMERATE_SUB_KEYS)
def test_hklm(self): def test_hklm(self):
handle = self.conn.OpenHKLM(None, handle = self.conn.OpenHKLM(None,
winreg.KEY_QUERY_VALUE | winreg.KEY_ENUMERATE_SUB_KEYS) winreg.KEY_QUERY_VALUE | winreg.KEY_ENUMERATE_SUB_KEYS)
self.conn.CloseKey(handle) self.conn.CloseKey(handle)
def test_getversion(self): def test_getversion(self):
@ -45,7 +45,7 @@ class WinregTests(RpcInterfaceTestCase):
def test_getkeyinfo(self): def test_getkeyinfo(self):
handle = self.conn.OpenHKLM(None, handle = self.conn.OpenHKLM(None,
winreg.KEY_QUERY_VALUE | winreg.KEY_ENUMERATE_SUB_KEYS) winreg.KEY_QUERY_VALUE | winreg.KEY_ENUMERATE_SUB_KEYS)
x = self.conn.QueryInfoKey(handle, winreg.String()) x = self.conn.QueryInfoKey(handle, winreg.String())
self.assertEquals(9, len(x)) # should return a 9-tuple self.assertEquals(9, len(x)) # should return a 9-tuple
self.conn.CloseKey(handle) self.conn.CloseKey(handle)

View File

@ -57,12 +57,12 @@ class SrvsvcTests(RpcInterfaceTestCase):
name = share.name name = share.name
share.comment = "now sucessfully modified " share.comment = "now sucessfully modified "
parm_error = self.pipe.NetShareSetInfo(self.server_unc, name, parm_error = self.pipe.NetShareSetInfo(self.server_unc, name,
502, share, parm_error) 502, share, parm_error)
def test_NetShareDel(self): def test_NetShareDel(self):
self.skipTest("Dangerous test") self.skipTest("Dangerous test")
share = self.getDummyShareObject() share = self.getDummyShareObject()
parm_error = 0x00000000 parm_error = 0x00000000
self.expectFailure("NetShareAdd doesn't work properly from Python", self.expectFailure("NetShareAdd doesn't work properly from Python",
self.conn.NetShareAdd, self.server_unc, 502, share, parm_error) self.conn.NetShareAdd, self.server_unc, 502, share, parm_error)
self.conn.NetShareDel(self.server_unc, share.name, 0) self.conn.NetShareDel(self.server_unc, share.name, 0)

View File

@ -1044,8 +1044,8 @@ class TestZones(DNSTest):
def ldap_get_zone_settings(self): def ldap_get_zone_settings(self):
records = self.samdb.search(base=self.zone_dn, scope=ldb.SCOPE_BASE, records = self.samdb.search(base=self.zone_dn, scope=ldb.SCOPE_BASE,
expression="(&(objectClass=dnsZone)" + expression="(&(objectClass=dnsZone)" +
"(name={}))".format(self.zone), "(name={}))".format(self.zone),
attrs=["dNSProperty"]) attrs=["dNSProperty"])
self.assertEqual(len(records), 1) self.assertEqual(len(records), 1)
props = [ndr_unpack(dnsp.DnsProperty, r) props = [ndr_unpack(dnsp.DnsProperty, r)
@ -1525,11 +1525,11 @@ class TestRPCRoundtrip(DNSTest):
self.check_query_txt(prefix, txt) self.check_query_txt(prefix, txt)
self.assertIsNotNone( self.assertIsNotNone(
dns_record_match(self.rpc_conn, dns_record_match(self.rpc_conn,
self.server_ip, self.server_ip,
self.get_dns_domain(), self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()), "%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, dnsp.DNS_TYPE_TXT,
'"\\"This is a test\\"" "" ""')) '"\\"This is a test\\"" "" ""'))
prefix, txt = 'pad2textrec', ['"This is a test"', '', '', 'more text'] prefix, txt = 'pad2textrec', ['"This is a test"', '', '', 'more text']
p = self.make_txt_update(prefix, txt) p = self.make_txt_update(prefix, txt)
@ -1670,9 +1670,9 @@ class TestRPCRoundtrip(DNSTest):
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK) self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, ['NULL']) self.check_query_txt(prefix, ['NULL'])
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip, self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(), self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()), "%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"NULL"')) dnsp.DNS_TYPE_TXT, '"NULL"'))
prefix, txt = 'nulltextrec2', ['NULL\x00BYTE', 'NULL\x00BYTE'] prefix, txt = 'nulltextrec2', ['NULL\x00BYTE', 'NULL\x00BYTE']
p = self.make_txt_update(prefix, txt) p = self.make_txt_update(prefix, txt)
@ -1681,9 +1681,9 @@ class TestRPCRoundtrip(DNSTest):
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK) self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, ['NULL', 'NULL']) self.check_query_txt(prefix, ['NULL', 'NULL'])
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip, self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(), self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()), "%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"NULL" "NULL"')) dnsp.DNS_TYPE_TXT, '"NULL" "NULL"'))
def test_update_add_null_char_rpc_to_dns(self): def test_update_add_null_char_rpc_to_dns(self):
prefix = 'rpcnulltextrec' prefix = 'rpcnulltextrec'
@ -1726,9 +1726,9 @@ class TestRPCRoundtrip(DNSTest):
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK) self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt) self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip, self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(), self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()), "%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"HIGH\xFFBYTE"')) dnsp.DNS_TYPE_TXT, '"HIGH\xFFBYTE"'))
def test_update_add_hex_rpc_to_dns(self): def test_update_add_hex_rpc_to_dns(self):
prefix, txt = 'hextextrec', ['HIGH\xFFBYTE'] prefix, txt = 'hextextrec', ['HIGH\xFFBYTE']
@ -1772,9 +1772,9 @@ class TestRPCRoundtrip(DNSTest):
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK) self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt) self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip, self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(), self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()), "%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"Th\\\\=is=is a test"')) dnsp.DNS_TYPE_TXT, '"Th\\\\=is=is a test"'))
# This test fails against Windows as it eliminates slashes in RPC # This test fails against Windows as it eliminates slashes in RPC
# One typical use for a slash is in records like 'var=value' to # One typical use for a slash is in records like 'var=value' to
@ -1823,10 +1823,10 @@ class TestRPCRoundtrip(DNSTest):
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK) self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt) self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip, self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(), self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()), "%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"\\"This is a test\\""' + dnsp.DNS_TYPE_TXT, '"\\"This is a test\\""' +
' "\\"and this is a test, too\\""')) ' "\\"and this is a test, too\\""'))
def test_update_add_two_rpc_to_dns(self): def test_update_add_two_rpc_to_dns(self):
prefix, txt = 'textrec2', ['"This is a test"', prefix, txt = 'textrec2', ['"This is a test"',
@ -1835,8 +1835,8 @@ class TestRPCRoundtrip(DNSTest):
name = "%s.%s" % (prefix, self.get_dns_domain()) name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT, rec = data_to_dns_record(dnsp.DNS_TYPE_TXT,
'"\\"This is a test\\""' + '"\\"This is a test\\""' +
' "\\"and this is a test, too\\""') ' "\\"and this is a test, too\\""')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF() add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec add_rec_buf.rec = rec
try: try:
@ -1873,9 +1873,9 @@ class TestRPCRoundtrip(DNSTest):
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK) self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt) self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip, self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(), self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()), "%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '')) dnsp.DNS_TYPE_TXT, ''))
def test_update_add_empty_rpc_to_dns(self): def test_update_add_empty_rpc_to_dns(self):
prefix, txt = 'rpcemptytextrec', [] prefix, txt = 'rpcemptytextrec', []

View File

@ -158,21 +158,21 @@ class SmbDotConfTests(TestCase):
# registry shares appears to need sudo # registry shares appears to need sudo
self._set_arbitrary(['bin/testparm'], self._set_arbitrary(['bin/testparm'],
exceptions = ['client lanman auth', exceptions = ['client lanman auth',
'client plaintext auth', 'client plaintext auth',
'registry shares', 'registry shares',
'smb ports', 'smb ports',
'rpc server dynamic port range', 'rpc server dynamic port range',
'name resolve order']) 'name resolve order'])
self._test_empty(['bin/testparm']) self._test_empty(['bin/testparm'])
def test_default_s4(self): def test_default_s4(self):
self._test_default(['bin/samba-tool', 'testparm']) self._test_default(['bin/samba-tool', 'testparm'])
self._set_defaults(['bin/samba-tool', 'testparm']) self._set_defaults(['bin/samba-tool', 'testparm'])
self._set_arbitrary(['bin/samba-tool', 'testparm'], self._set_arbitrary(['bin/samba-tool', 'testparm'],
exceptions = ['smb ports', exceptions = ['smb ports',
'rpc server dynamic port range', 'rpc server dynamic port range',
'name resolve order']) 'name resolve order'])
self._test_empty(['bin/samba-tool', 'testparm']) self._test_empty(['bin/samba-tool', 'testparm'])
def _test_default(self, program): def _test_default(self, program):
@ -194,9 +194,15 @@ class SmbDotConfTests(TestCase):
section = "test" section = "test"
else: else:
self.fail("%s has no valid context" % param) self.fail("%s has no valid context" % param)
p = subprocess.Popen(program + ["-s", self.smbconf, p = subprocess.Popen(program + ["-s",
"--section-name", section, "--parameter-name", param], self.smbconf,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.topdir).communicate() "--section-name",
section,
"--parameter-name",
param],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self.topdir).communicate()
result = p[0].decode().upper().strip() result = p[0].decode().upper().strip()
if result != default.upper(): if result != default.upper():
if not (result == "" and default == '""'): if not (result == "" and default == '""'):
@ -205,7 +211,7 @@ class SmbDotConfTests(TestCase):
if len(failset) > 0: if len(failset) > 0:
self.fail(self._format_message(failset, self.fail(self._format_message(failset,
"Parameters that do not have matching defaults:")) "Parameters that do not have matching defaults:"))
def _set_defaults(self, program): def _set_defaults(self, program):
failset = set() failset = set()
@ -224,10 +230,17 @@ class SmbDotConfTests(TestCase):
section = "test" section = "test"
else: else:
self.fail("%s has no valid context" % param) self.fail("%s has no valid context" % param)
p = subprocess.Popen(program + ["-s", self.smbconf, p = subprocess.Popen(program + ["-s",
"--section-name", section, "--parameter-name", param, self.smbconf,
"--option", "%s = %s" % (param, default)], "--section-name",
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.topdir).communicate() section,
"--parameter-name",
param,
"--option",
"%s = %s" % (param, default)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self.topdir).communicate()
result = p[0].decode().upper().strip() result = p[0].decode().upper().strip()
if result != default.upper(): if result != default.upper():
if not (result == "" and default == '""'): if not (result == "" and default == '""'):
@ -236,7 +249,7 @@ class SmbDotConfTests(TestCase):
if len(failset) > 0: if len(failset) > 0:
self.fail(self._format_message(failset, self.fail(self._format_message(failset,
"Parameters that do not have matching defaults:")) "Parameters that do not have matching defaults:"))
def _set_arbitrary(self, program, exceptions=None): def _set_arbitrary(self, program, exceptions=None):
arbitrary = {'string': 'string', 'boolean': 'yes', 'integer': '5', arbitrary = {'string': 'string', 'boolean': 'yes', 'integer': '5',
@ -283,10 +296,17 @@ class SmbDotConfTests(TestCase):
if value_to_use is None: if value_to_use is None:
self.fail("%s has an invalid type" % param) self.fail("%s has an invalid type" % param)
p = subprocess.Popen(program + ["-s", self.smbconf, p = subprocess.Popen(program + ["-s",
"--section-name", section, "--parameter-name", param, self.smbconf,
"--option", "%s = %s" % (param, value_to_use)], "--section-name",
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.topdir).communicate() section,
"--parameter-name",
param,
"--option",
"%s = %s" % (param, value_to_use)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self.topdir).communicate()
result = p[0].decode().upper().strip() result = p[0].decode().upper().strip()
if result != value_to_use.upper(): if result != value_to_use.upper():
# currently no way to distinguish command lists # currently no way to distinguish command lists
@ -315,9 +335,14 @@ class SmbDotConfTests(TestCase):
finally: finally:
g.close() g.close()
p = subprocess.Popen(program + ["-s", tempconf, "--suppress-prompt", p = subprocess.Popen(program + ["-s",
"--option", "%s = %s" % (param, value_to_use)], tempconf,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.topdir).communicate() "--suppress-prompt",
"--option",
"%s = %s" % (param, value_to_use)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self.topdir).communicate()
os.unlink(tempconf) os.unlink(tempconf)
@ -348,11 +373,15 @@ class SmbDotConfTests(TestCase):
if len(failset) > 0: if len(failset) > 0:
self.fail(self._format_message(failset, self.fail(self._format_message(failset,
"Parameters that were unexpectedly not set:")) "Parameters that were unexpectedly not set:"))
def _test_empty(self, program): def _test_empty(self, program):
p = subprocess.Popen(program + ["-s", self.blankconf, "--suppress-prompt"], p = subprocess.Popen(program + ["-s",
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.topdir).communicate() self.blankconf,
"--suppress-prompt"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=self.topdir).communicate()
output = "" output = ""
for line in p[0].decode().splitlines(): for line in p[0].decode().splitlines():

View File

@ -575,8 +575,8 @@ class DsdbTests(TestCase):
msg = ldb.Message() msg = ldb.Message()
msg.dn = kept_dn msg.dn = kept_dn
msg["manager"] = ldb.MessageElement("<SID=%s>" % removed_sid, msg["manager"] = ldb.MessageElement("<SID=%s>" % removed_sid,
ldb.FLAG_MOD_ADD, ldb.FLAG_MOD_ADD,
"manager") "manager")
try: try:
self.samdb.modify(msg) self.samdb.modify(msg)
self.fail("No exception should get LDB_ERR_CONSTRAINT_VIOLATION") self.fail("No exception should get LDB_ERR_CONSTRAINT_VIOLATION")
@ -589,8 +589,8 @@ class DsdbTests(TestCase):
msg = ldb.Message() msg = ldb.Message()
msg.dn = kept_dn msg.dn = kept_dn
msg["manager"] = ldb.MessageElement("<GUID=%s>" % removed_guid, msg["manager"] = ldb.MessageElement("<GUID=%s>" % removed_guid,
ldb.FLAG_MOD_ADD, ldb.FLAG_MOD_ADD,
"manager") "manager")
try: try:
self.samdb.modify(msg) self.samdb.modify(msg)
self.fail("No exception should get LDB_ERR_CONSTRAINT_VIOLATION") self.fail("No exception should get LDB_ERR_CONSTRAINT_VIOLATION")

View File

@ -52,4 +52,4 @@ class KerberosOptionTests(samba.tests.TestCase):
def test_parse_invalid(self): def test_parse_invalid(self):
self.assertRaises(optparse.OptionValueError, self.assertRaises(optparse.OptionValueError,
parse_kerberos_arg, "blah?", "--kerberos") parse_kerberos_arg, "blah?", "--kerberos")

View File

@ -48,11 +48,11 @@ class GPOTests(tests.TestCase):
ds_paths = [None, 'CN=%s,%s' % (guid, dspath)] ds_paths = [None, 'CN=%s,%s' % (guid, dspath)]
for i in range(0, len(gpos)): for i in range(0, len(gpos)):
self.assertEquals(gpos[i].name, names[i], self.assertEquals(gpos[i].name, names[i],
'The gpo name did not match expected name %s' % gpos[i].name) 'The gpo name did not match expected name %s' % gpos[i].name)
self.assertEquals(gpos[i].file_sys_path, file_sys_paths[i], self.assertEquals(gpos[i].file_sys_path, file_sys_paths[i],
'file_sys_path did not match expected %s' % gpos[i].file_sys_path) 'file_sys_path did not match expected %s' % gpos[i].file_sys_path)
self.assertEquals(gpos[i].ds_path, ds_paths[i], self.assertEquals(gpos[i].ds_path, ds_paths[i],
'ds_path did not match expected %s' % gpos[i].ds_path) 'ds_path did not match expected %s' % gpos[i].ds_path)
def test_gpo_ads_does_not_segfault(self): def test_gpo_ads_does_not_segfault(self):
@ -72,12 +72,12 @@ class GPOTests(tests.TestCase):
with open(os.path.join(gpo_path, 'GPT.INI'), 'w') as gpt: with open(os.path.join(gpo_path, 'GPT.INI'), 'w') as gpt:
gpt.write(gpt_data % 42) gpt.write(gpt_data % 42)
self.assertEquals(gpo.gpo_get_sysvol_gpt_version(gpo_path)[1], 42, self.assertEquals(gpo.gpo_get_sysvol_gpt_version(gpo_path)[1], 42,
'gpo_get_sysvol_gpt_version() did not return the expected version') 'gpo_get_sysvol_gpt_version() did not return the expected version')
with open(os.path.join(gpo_path, 'GPT.INI'), 'w') as gpt: with open(os.path.join(gpo_path, 'GPT.INI'), 'w') as gpt:
gpt.write(gpt_data % old_vers) gpt.write(gpt_data % old_vers)
self.assertEquals(gpo.gpo_get_sysvol_gpt_version(gpo_path)[1], old_vers, self.assertEquals(gpo.gpo_get_sysvol_gpt_version(gpo_path)[1], old_vers,
'gpo_get_sysvol_gpt_version() did not return the expected version') 'gpo_get_sysvol_gpt_version() did not return the expected version')
def test_check_refresh_gpo_list(self): def test_check_refresh_gpo_list(self):
cache = self.lp.cache_path('gpo_cache') cache = self.lp.cache_path('gpo_cache')
@ -110,7 +110,7 @@ class GPOTests(tests.TestCase):
'{31B2F340-016D-11D2-945F-00C04FB984F9}/GPT.INI' '{31B2F340-016D-11D2-945F-00C04FB984F9}/GPT.INI'
result = check_safe_path(before) result = check_safe_path(before)
self.assertEquals(result, after, 'check_safe_path() didn\'t' \ self.assertEquals(result, after, 'check_safe_path() didn\'t' \
' correctly convert \\ to /') ' correctly convert \\ to /')
def test_gpt_ext_register(self): def test_gpt_ext_register(self):
this_path = os.path.dirname(os.path.realpath(__file__)) this_path = os.path.dirname(os.path.realpath(__file__))
@ -123,14 +123,14 @@ class GPOTests(tests.TestCase):
self.assertTrue(ret, 'Failed to register a gp ext') self.assertTrue(ret, 'Failed to register a gp ext')
gp_exts = list_gp_extensions(self.lp.configfile) gp_exts = list_gp_extensions(self.lp.configfile)
self.assertTrue(ext_guid in gp_exts.keys(), self.assertTrue(ext_guid in gp_exts.keys(),
'Failed to list gp exts') 'Failed to list gp exts')
self.assertEquals(gp_exts[ext_guid]['DllName'], ext_path, self.assertEquals(gp_exts[ext_guid]['DllName'], ext_path,
'Failed to list gp exts') 'Failed to list gp exts')
unregister_gp_extension(ext_guid) unregister_gp_extension(ext_guid)
gp_exts = list_gp_extensions(self.lp.configfile) gp_exts = list_gp_extensions(self.lp.configfile)
self.assertTrue(ext_guid not in gp_exts.keys(), self.assertTrue(ext_guid not in gp_exts.keys(),
'Failed to unregister gp exts') 'Failed to unregister gp exts')
self.assertTrue(check_guid(ext_guid), 'Failed to parse valid guid') self.assertTrue(check_guid(ext_guid), 'Failed to parse valid guid')
self.assertFalse(check_guid('AAAAAABBBBBBBCCC'), 'Parsed invalid guid') self.assertFalse(check_guid('AAAAAABBBBBBBCCC'), 'Parsed invalid guid')
@ -143,9 +143,9 @@ class GPOTests(tests.TestCase):
lp, parser = parse_gpext_conf(self.lp.configfile) lp, parser = parse_gpext_conf(self.lp.configfile)
self.assertTrue('test_section' in parser.sections(), self.assertTrue('test_section' in parser.sections(),
'test_section not found in gpext.conf') 'test_section not found in gpext.conf')
self.assertEquals(parser.get('test_section', 'test_var'), ext_guid, self.assertEquals(parser.get('test_section', 'test_var'), ext_guid,
'Failed to find test variable in gpext.conf') 'Failed to find test variable in gpext.conf')
parser.remove_section('test_section') parser.remove_section('test_section')
atomic_write_conf(lp, parser) atomic_write_conf(lp, parser)

View File

@ -45,7 +45,7 @@ MULTISITE_LDIF = os.path.join(os.environ['SRCDIR_ABS'],
# UNCONNECTED_LDIF is a single site, unconnected 5DC database that was # UNCONNECTED_LDIF is a single site, unconnected 5DC database that was
# created using samba-tool domain join in testenv. # created using samba-tool domain join in testenv.
UNCONNECTED_LDIF = os.path.join(os.environ['SRCDIR_ABS'], UNCONNECTED_LDIF = os.path.join(os.environ['SRCDIR_ABS'],
"testdata/unconnected-intrasite.ldif") "testdata/unconnected-intrasite.ldif")
MULTISITE_LDIF_DSAS = ( MULTISITE_LDIF_DSAS = (
("CN=WIN08,CN=Servers,CN=Site-4,CN=Sites,CN=Configuration,DC=ad,DC=samba,DC=example,DC=com", ("CN=WIN08,CN=Servers,CN=Site-4,CN=Sites,CN=Configuration,DC=ad,DC=samba,DC=example,DC=com",

View File

@ -42,14 +42,14 @@ class NetCmdTestCase(samba.tests.TestCase):
yield path, cmd yield path, cmd
subcmds = getattr(cmd, "subcommands", {}) subcmds = getattr(cmd, "subcommands", {})
todo.extend([(path + " " + k, v) for (k, v) in todo.extend([(path + " " + k, v) for (k, v) in
subcmds.items()]) subcmds.items()])
class TestParmTests(NetCmdTestCase): class TestParmTests(NetCmdTestCase):
def test_no_client_ip(self): def test_no_client_ip(self):
out, err = self.run_netcmd(cmd_testparm, ["--client-name=foo"], out, err = self.run_netcmd(cmd_testparm, ["--client-name=foo"],
retcode=-1) retcode=-1)
self.assertEquals("", out) self.assertEquals("", out)
self.assertEquals( self.assertEquals(
"ERROR: Both a DNS name and an IP address are " "ERROR: Both a DNS name and an IP address are "
@ -75,7 +75,7 @@ class CommandTests(NetCmdTestCase):
missing.append(path) missing.append(path)
if missing: if missing:
self.fail("The following commands do not have a synopsis set: %r" % self.fail("The following commands do not have a synopsis set: %r" %
missing) missing)
def test_short_description_everywhere(self): def test_short_description_everywhere(self):
missing = [] missing = []

View File

@ -27,8 +27,8 @@ class PolicyTests(TestCase):
def test_get_gpo_flags(self): def test_get_gpo_flags(self):
self.assertEquals(["GPO_FLAG_USER_DISABLE"], self.assertEquals(["GPO_FLAG_USER_DISABLE"],
policy.get_gpo_flags(policy.GPO_FLAG_USER_DISABLE)) policy.get_gpo_flags(policy.GPO_FLAG_USER_DISABLE))
def test_get_gplink_options(self): def test_get_gplink_options(self):
self.assertEquals(["GPLINK_OPT_DISABLE"], self.assertEquals(["GPLINK_OPT_DISABLE"],
policy.get_gplink_options(policy.GPLINK_OPT_DISABLE)) policy.get_gplink_options(policy.GPLINK_OPT_DISABLE))

View File

@ -322,7 +322,7 @@ class PosixAclMappingTests(TestCaseInTempDir):
nwrap_module_fn_prefix = os.getenv('NSS_WRAPPER_MODULE_FN_PREFIX') nwrap_module_fn_prefix = os.getenv('NSS_WRAPPER_MODULE_FN_PREFIX')
nwrap_winbind_active = (nwrap_module_so_path != "" and nwrap_winbind_active = (nwrap_module_so_path != "" and
nwrap_module_fn_prefix == "winbind") nwrap_module_fn_prefix == "winbind")
LA_sid = security.dom_sid(str(domsid)+"-"+str(security.DOMAIN_RID_ADMINISTRATOR)) LA_sid = security.dom_sid(str(domsid)+"-"+str(security.DOMAIN_RID_ADMINISTRATOR))
BA_sid = security.dom_sid(security.SID_BUILTIN_ADMINISTRATORS) BA_sid = security.dom_sid(security.SID_BUILTIN_ADMINISTRATORS)
@ -665,7 +665,7 @@ class PosixAclMappingTests(TestCaseInTempDir):
domsid = passdb.get_global_sam_sid() domsid = passdb.get_global_sam_sid()
session_info = self.get_session_info(domsid) session_info = self.get_session_info(domsid)
setntacl(self.lp, self.tempf, acl, str(domsid), use_ntvfs=False, setntacl(self.lp, self.tempf, acl, str(domsid), use_ntvfs=False,
session_info=session_info) session_info=session_info)
facl = getntacl(self.lp, self.tempf) facl = getntacl(self.lp, self.tempf)
self.assertEquals(facl.as_sddl(domsid),acl) self.assertEquals(facl.as_sddl(domsid),acl)
posix_acl = smbd.get_sys_acl(self.tempf, smb_acl.SMB_ACL_TYPE_ACCESS) posix_acl = smbd.get_sys_acl(self.tempf, smb_acl.SMB_ACL_TYPE_ACCESS)
@ -674,7 +674,7 @@ class PosixAclMappingTests(TestCaseInTempDir):
nwrap_module_fn_prefix = os.getenv('NSS_WRAPPER_MODULE_FN_PREFIX') nwrap_module_fn_prefix = os.getenv('NSS_WRAPPER_MODULE_FN_PREFIX')
nwrap_winbind_active = (nwrap_module_so_path != "" and nwrap_winbind_active = (nwrap_module_so_path != "" and
nwrap_module_fn_prefix == "winbind") nwrap_module_fn_prefix == "winbind")
LA_sid = security.dom_sid(str(domsid)+"-"+str(security.DOMAIN_RID_ADMINISTRATOR)) LA_sid = security.dom_sid(str(domsid)+"-"+str(security.DOMAIN_RID_ADMINISTRATOR))
BA_sid = security.dom_sid(security.SID_BUILTIN_ADMINISTRATORS) BA_sid = security.dom_sid(security.SID_BUILTIN_ADMINISTRATORS)

View File

@ -66,7 +66,7 @@ class ProvisionTestCase(samba.tests.TestCaseInTempDir):
ldb = setup_secretsdb(paths, None, None, lp=env_loadparm()) ldb = setup_secretsdb(paths, None, None, lp=env_loadparm())
try: try:
self.assertEquals("LSA Secrets", self.assertEquals("LSA Secrets",
ldb.searchone(basedn="CN=LSA Secrets", attribute="CN").decode('utf8')) ldb.searchone(basedn="CN=LSA Secrets", attribute="CN").decode('utf8'))
finally: finally:
del ldb del ldb
os.unlink(path) os.unlink(path)
@ -123,9 +123,9 @@ class SanitizeServerRoleTests(TestCase):
def test_same(self): def test_same(self):
self.assertEquals("standalone server", self.assertEquals("standalone server",
sanitize_server_role("standalone server")) sanitize_server_role("standalone server"))
self.assertEquals("member server", self.assertEquals("member server",
sanitize_server_role("member server")) sanitize_server_role("member server"))
def test_invalid(self): def test_invalid(self):
self.assertRaises(ValueError, sanitize_server_role, "foo") self.assertRaises(ValueError, sanitize_server_role, "foo")
@ -187,7 +187,7 @@ class ProvisionResultTests(TestCase):
result.adminpass = "geheim" result.adminpass = "geheim"
entries = self.report_logger(result) entries = self.report_logger(result)
self.assertEquals(entries[1], self.assertEquals(entries[1],
("INFO", 'Admin password: geheim')) ("INFO", 'Admin password: geheim'))
class DetermineNetbiosNameTests(TestCase): class DetermineNetbiosNameTests(TestCase):

View File

@ -32,7 +32,7 @@ class IdmapDbTestCase(TestCase):
def setUp(self): def setUp(self):
super(IdmapDbTestCase, self).setUp() super(IdmapDbTestCase, self).setUp()
self.idmapdb = IdmapDatabase(os.path.join(DATADIR, self.idmapdb = IdmapDatabase(os.path.join(DATADIR,
"winbindd_idmap")) "winbindd_idmap"))
def test_user_hwm(self): def test_user_hwm(self):
self.assertEquals(10000, self.idmapdb.get_user_hwm()) self.assertEquals(10000, self.idmapdb.get_user_hwm())

View File

@ -57,10 +57,10 @@ class MapBaseTestCase(TestCaseInTempDir):
"@LIST": "rootdse,paged_results,server_sort,asq,samldb,password_hash,operational,objectguid,rdn_name,samba3sam,samba3sid,show_deleted_ignore,dsdb_flags_ignore,partition"}) "@LIST": "rootdse,paged_results,server_sort,asq,samldb,password_hash,operational,objectguid,rdn_name,samba3sam,samba3sid,show_deleted_ignore,dsdb_flags_ignore,partition"})
ldb.add({"dn": "@PARTITION", ldb.add({"dn": "@PARTITION",
"partition": ["%s" % (s4.basedn_casefold), "partition": ["%s" % (s4.basedn_casefold),
"%s" % (s3.basedn_casefold)], "%s" % (s3.basedn_casefold)],
"replicateEntries": ["@ATTRIBUTES", "@INDEXLIST"], "replicateEntries": ["@ATTRIBUTES", "@INDEXLIST"],
"modules": "*:"}) "modules": "*:"})
def setUp(self): def setUp(self):
self.lp = env_loadparm() self.lp = env_loadparm()
@ -182,8 +182,8 @@ class Samba3SamTestCase(MapBaseTestCase):
"""Looking up by objectClass""" """Looking up by objectClass"""
msg = self.ldb.search(expression="(|(objectClass=user)(cn=Administrator))") msg = self.ldb.search(expression="(|(objectClass=user)(cn=Administrator))")
self.assertEquals(set([str(m.dn) for m in msg]), self.assertEquals(set([str(m.dn) for m in msg]),
set(["unixName=Administrator,ou=Users,dc=vernstok,dc=nl", set(["unixName=Administrator,ou=Users,dc=vernstok,dc=nl",
"unixName=nobody,ou=Users,dc=vernstok,dc=nl"])) "unixName=nobody,ou=Users,dc=vernstok,dc=nl"]))
def test_s3sam_modify(self): def test_s3sam_modify(self):
# Adding a record that will be fallbacked # Adding a record that will be fallbacked
@ -202,8 +202,8 @@ class Samba3SamTestCase(MapBaseTestCase):
# #
# #
msg = self.ldb.search(expression="(cn=Foo)", base="cn=Foo", msg = self.ldb.search(expression="(cn=Foo)", base="cn=Foo",
scope=SCOPE_BASE, scope=SCOPE_BASE,
attrs=['foo','blah','cn','showInAdvancedViewOnly']) attrs=['foo','blah','cn','showInAdvancedViewOnly'])
self.assertEquals(len(msg), 1) self.assertEquals(len(msg), 1)
self.assertEquals(str(msg[0]["showInAdvancedViewOnly"]), "TRUE") self.assertEquals(str(msg[0]["showInAdvancedViewOnly"]), "TRUE")
self.assertEquals(str(msg[0]["foo"]), "bar") self.assertEquals(str(msg[0]["foo"]), "bar")
@ -211,10 +211,10 @@ class Samba3SamTestCase(MapBaseTestCase):
# Adding record that will be mapped # Adding record that will be mapped
self.ldb.add({"dn": "cn=Niemand,cn=Users,dc=vernstok,dc=nl", self.ldb.add({"dn": "cn=Niemand,cn=Users,dc=vernstok,dc=nl",
"objectClass": "user", "objectClass": "user",
"unixName": "bin", "unixName": "bin",
"sambaUnicodePwd": "geheim", "sambaUnicodePwd": "geheim",
"cn": "Niemand"}) "cn": "Niemand"})
# Checking for existence of record (remote) # Checking for existence of record (remote)
msg = self.ldb.search(expression="(unixName=bin)", msg = self.ldb.search(expression="(unixName=bin)",
@ -225,7 +225,7 @@ class Samba3SamTestCase(MapBaseTestCase):
# Checking for existence of record (local && remote) # Checking for existence of record (local && remote)
msg = self.ldb.search(expression="(&(unixName=bin)(sambaUnicodePwd=geheim))", msg = self.ldb.search(expression="(&(unixName=bin)(sambaUnicodePwd=geheim))",
attrs=['unixName','cn','dn', 'sambaUnicodePwd']) attrs=['unixName','cn','dn', 'sambaUnicodePwd'])
self.assertEquals(len(msg), 1) # TODO: should check with more records self.assertEquals(len(msg), 1) # TODO: should check with more records
self.assertEquals(str(msg[0]["cn"]), "Niemand") self.assertEquals(str(msg[0]["cn"]), "Niemand")
self.assertEquals(str(msg[0]["unixName"]), "bin") self.assertEquals(str(msg[0]["unixName"]), "bin")
@ -233,7 +233,7 @@ class Samba3SamTestCase(MapBaseTestCase):
# Checking for existence of record (local || remote) # Checking for existence of record (local || remote)
msg = self.ldb.search(expression="(|(unixName=bin)(sambaUnicodePwd=geheim))", msg = self.ldb.search(expression="(|(unixName=bin)(sambaUnicodePwd=geheim))",
attrs=['unixName','cn','dn', 'sambaUnicodePwd']) attrs=['unixName','cn','dn', 'sambaUnicodePwd'])
#print "got %d replies" % len(msg) #print "got %d replies" % len(msg)
self.assertEquals(len(msg), 1) # TODO: should check with more records self.assertEquals(len(msg), 1) # TODO: should check with more records
self.assertEquals(str(msg[0]["cn"]), "Niemand") self.assertEquals(str(msg[0]["cn"]), "Niemand")
@ -244,7 +244,7 @@ class Samba3SamTestCase(MapBaseTestCase):
msg = self.samba3.db.search(expression="(cn=Niemand)") msg = self.samba3.db.search(expression="(cn=Niemand)")
self.assertTrue(len(msg) >= 1) self.assertTrue(len(msg) >= 1)
self.assertEquals(str(msg[0]["sambaSID"]), self.assertEquals(str(msg[0]["sambaSID"]),
"S-1-5-21-4231626423-2410014848-2360679739-2001") "S-1-5-21-4231626423-2410014848-2360679739-2001")
self.assertEquals(str(msg[0]["displayName"]), "Niemand") self.assertEquals(str(msg[0]["displayName"]), "Niemand")
# Adding attribute... # Adding attribute...
@ -407,7 +407,7 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-1052
# Search remote record by local DN # Search remote record by local DN
dn = self.samba4.dn("cn=A") dn = self.samba4.dn("cn=A")
res = self.ldb.search(dn, scope=SCOPE_BASE, res = self.ldb.search(dn, scope=SCOPE_BASE,
attrs=["dnsHostName", "lastLogon"]) attrs=["dnsHostName", "lastLogon"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn) self.assertEquals(str(res[0].dn), dn)
self.assertTrue(not "dnsHostName" in res[0]) self.assertTrue(not "dnsHostName" in res[0])
@ -416,7 +416,7 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-1052
# Search remote record by remote DN # Search remote record by remote DN
dn = self.samba3.dn("cn=A") dn = self.samba3.dn("cn=A")
res = self.samba3.db.search(dn, scope=SCOPE_BASE, res = self.samba3.db.search(dn, scope=SCOPE_BASE,
attrs=["dnsHostName", "lastLogon", "sambaLogonTime"]) attrs=["dnsHostName", "lastLogon", "sambaLogonTime"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn) self.assertEquals(str(res[0].dn), dn)
self.assertTrue(not "dnsHostName" in res[0]) self.assertTrue(not "dnsHostName" in res[0])
@ -426,7 +426,7 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-1052
# Search split record by local DN # Search split record by local DN
dn = self.samba4.dn("cn=X") dn = self.samba4.dn("cn=X")
res = self.ldb.search(dn, scope=SCOPE_BASE, res = self.ldb.search(dn, scope=SCOPE_BASE,
attrs=["dnsHostName", "lastLogon"]) attrs=["dnsHostName", "lastLogon"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn) self.assertEquals(str(res[0].dn), dn)
self.assertEquals(str(res[0]["dnsHostName"]), "x") self.assertEquals(str(res[0]["dnsHostName"]), "x")
@ -435,7 +435,7 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-1052
# Search split record by remote DN # Search split record by remote DN
dn = self.samba3.dn("cn=X") dn = self.samba3.dn("cn=X")
res = self.samba3.db.search(dn, scope=SCOPE_BASE, res = self.samba3.db.search(dn, scope=SCOPE_BASE,
attrs=["dnsHostName", "lastLogon", "sambaLogonTime"]) attrs=["dnsHostName", "lastLogon", "sambaLogonTime"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn) self.assertEquals(str(res[0].dn), dn)
self.assertTrue(not "dnsHostName" in res[0]) self.assertTrue(not "dnsHostName" in res[0])
@ -446,7 +446,7 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-1052
# Search by ignored attribute # Search by ignored attribute
res = self.ldb.search(expression="(revision=x)", scope=SCOPE_DEFAULT, res = self.ldb.search(expression="(revision=x)", scope=SCOPE_DEFAULT,
attrs=["dnsHostName", "lastLogon"]) attrs=["dnsHostName", "lastLogon"])
self.assertEquals(len(res), 2) self.assertEquals(len(res), 2)
res = sorted(res, key=attrgetter('dn')) res = sorted(res, key=attrgetter('dn'))
self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X")) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=X"))
@ -458,7 +458,7 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-1052
# Search by kept attribute # Search by kept attribute
res = self.ldb.search(expression="(description=y)", res = self.ldb.search(expression="(description=y)",
scope=SCOPE_DEFAULT, attrs=["dnsHostName", "lastLogon"]) scope=SCOPE_DEFAULT, attrs=["dnsHostName", "lastLogon"])
self.assertEquals(len(res), 2) self.assertEquals(len(res), 2)
res = sorted(res, key=attrgetter('dn')) res = sorted(res, key=attrgetter('dn'))
self.assertEquals(str(res[0].dn), self.samba4.dn("cn=C")) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=C"))
@ -505,7 +505,7 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-1052
# In most cases, this even works when the mapping is missing # In most cases, this even works when the mapping is missing
# a `convert_operator' by enumerating the remote db. # a `convert_operator' by enumerating the remote db.
res = self.ldb.search(expression="(primaryGroupID=512)", res = self.ldb.search(expression="(primaryGroupID=512)",
attrs=["dnsHostName", "lastLogon", "primaryGroupID"]) attrs=["dnsHostName", "lastLogon", "primaryGroupID"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), self.samba4.dn("cn=A")) self.assertEquals(str(res[0].dn), self.samba4.dn("cn=A"))
self.assertTrue(not "dnsHostName" in res[0]) self.assertTrue(not "dnsHostName" in res[0])
@ -815,10 +815,10 @@ objectSid: S-1-5-21-4231626423-2410014848-2360679739-1052
# Add local record # Add local record
dn = "cn=test,dc=idealx,dc=org" dn = "cn=test,dc=idealx,dc=org"
self.ldb.add({"dn": dn, self.ldb.add({"dn": dn,
"cn": "test", "cn": "test",
"foo": "bar", "foo": "bar",
"revision": "1", "revision": "1",
"description": "test"}) "description": "test"})
# Check it's there # Check it's there
attrs = ["foo", "revision", "description"] attrs = ["foo", "revision", "description"]
res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs) res = self.ldb.search(dn, scope=SCOPE_BASE, attrs=attrs)
@ -876,13 +876,13 @@ description: foo
dn = self.samba4.dn("cn=test") dn = self.samba4.dn("cn=test")
dn2 = self.samba3.dn("cn=test") dn2 = self.samba3.dn("cn=test")
self.samba3.db.add({"dn": dn2, self.samba3.db.add({"dn": dn2,
"cn": "test", "cn": "test",
"description": "foo", "description": "foo",
"sambaBadPasswordCount": "3", "sambaBadPasswordCount": "3",
"sambaNextRid": "1001"}) "sambaNextRid": "1001"})
# Check it's there # Check it's there
res = self.samba3.db.search(dn2, scope=SCOPE_BASE, res = self.samba3.db.search(dn2, scope=SCOPE_BASE,
attrs=["description", "sambaBadPasswordCount", "sambaNextRid"]) attrs=["description", "sambaBadPasswordCount", "sambaNextRid"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn2) self.assertEquals(str(res[0].dn), dn2)
self.assertEquals(str(res[0]["description"]), "foo") self.assertEquals(str(res[0]["description"]), "foo")
@ -911,7 +911,7 @@ badPwdCount: 4
self.ldb.modify_ldif(ldif) self.ldb.modify_ldif(ldif)
# Check in mapped db # Check in mapped db
res = self.ldb.search(dn, scope=SCOPE_BASE, res = self.ldb.search(dn, scope=SCOPE_BASE,
attrs=["description", "badPwdCount", "nextRid"]) attrs=["description", "badPwdCount", "nextRid"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn) self.assertEquals(str(res[0].dn), dn)
self.assertEquals(str(res[0]["description"]), "test") self.assertEquals(str(res[0]["description"]), "test")
@ -919,7 +919,7 @@ badPwdCount: 4
self.assertEquals(str(res[0]["nextRid"]), "1001") self.assertEquals(str(res[0]["nextRid"]), "1001")
# Check in remote db # Check in remote db
res = self.samba3.db.search(dn2, scope=SCOPE_BASE, res = self.samba3.db.search(dn2, scope=SCOPE_BASE,
attrs=["description", "sambaBadPasswordCount", "sambaNextRid"]) attrs=["description", "sambaBadPasswordCount", "sambaNextRid"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn2) self.assertEquals(str(res[0].dn), dn2)
self.assertEquals(str(res[0]["description"]), "test") self.assertEquals(str(res[0]["description"]), "test")
@ -932,7 +932,7 @@ badPwdCount: 4
# Check in mapped db # Check in mapped db
dn = dn2 dn = dn2
res = self.ldb.search(dn, scope=SCOPE_BASE, res = self.ldb.search(dn, scope=SCOPE_BASE,
attrs=["description", "badPwdCount", "nextRid"]) attrs=["description", "badPwdCount", "nextRid"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn) self.assertEquals(str(res[0].dn), dn)
self.assertEquals(str(res[0]["description"]), "test") self.assertEquals(str(res[0]["description"]), "test")
@ -941,7 +941,7 @@ badPwdCount: 4
# Check in remote db # Check in remote db
dn2 = self.samba3.dn("cn=toast") dn2 = self.samba3.dn("cn=toast")
res = self.samba3.db.search(dn2, scope=SCOPE_BASE, res = self.samba3.db.search(dn2, scope=SCOPE_BASE,
attrs=["description", "sambaBadPasswordCount", "sambaNextRid"]) attrs=["description", "sambaBadPasswordCount", "sambaNextRid"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn2) self.assertEquals(str(res[0].dn), dn2)
self.assertEquals(str(res[0]["description"]), "test") self.assertEquals(str(res[0]["description"]), "test")
@ -963,10 +963,10 @@ badPwdCount: 4
dn = self.samba4.dn("cn=test") dn = self.samba4.dn("cn=test")
dn2 = self.samba3.dn("cn=test") dn2 = self.samba3.dn("cn=test")
self.samba3.db.add({"dn": dn2, self.samba3.db.add({"dn": dn2,
"cn": "test", "cn": "test",
"description": "foo", "description": "foo",
"sambaBadPasswordCount": "3", "sambaBadPasswordCount": "3",
"sambaNextRid": "1001"}) "sambaNextRid": "1001"})
# Modify local data of remote record # Modify local data of remote record
ldif = """ ldif = """
@ -1104,8 +1104,8 @@ revision: 2
# Check in remote db # Check in remote db
dn2 = self.samba3.dn("cn=toast") dn2 = self.samba3.dn("cn=toast")
res = self.samba3.db.search(dn2, scope=SCOPE_BASE, res = self.samba3.db.search(dn2, scope=SCOPE_BASE,
attrs=["description", "sambaBadPasswordCount", "sambaNextRid", attrs=["description", "sambaBadPasswordCount", "sambaNextRid",
"revision"]) "revision"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0].dn), dn2) self.assertEquals(str(res[0].dn), dn2)
self.assertEquals(str(res[0]["description"]), "test") self.assertEquals(str(res[0]["description"]), "test")

View File

@ -179,9 +179,9 @@ class ComputerCmdTestCase(SambaToolCmdTest):
dsdb.ATYPE_WORKSTATION_TRUST) dsdb.ATYPE_WORKSTATION_TRUST)
computerlist = self.samdb.search(base=self.samdb.domain_dn(), computerlist = self.samdb.search(base=self.samdb.domain_dn(),
scope=ldb.SCOPE_SUBTREE, scope=ldb.SCOPE_SUBTREE,
expression=search_filter, expression=search_filter,
attrs=["samaccountname"]) attrs=["samaccountname"])
self.assertTrue(len(computerlist) > 0, "no computers found in samdb") self.assertTrue(len(computerlist) > 0, "no computers found in samdb")
@ -278,11 +278,11 @@ class ComputerCmdTestCase(SambaToolCmdTest):
samaccountname = "%s$" % name samaccountname = "%s$" % name
search_filter = ("(&(sAMAccountName=%s)(objectCategory=%s,%s))" % search_filter = ("(&(sAMAccountName=%s)(objectCategory=%s,%s))" %
(ldb.binary_encode(samaccountname), (ldb.binary_encode(samaccountname),
"CN=Computer,CN=Schema,CN=Configuration", "CN=Computer,CN=Schema,CN=Configuration",
self.samdb.domain_dn())) self.samdb.domain_dn()))
computerlist = self.samdb.search(base=self.samdb.domain_dn(), computerlist = self.samdb.search(base=self.samdb.domain_dn(),
scope=ldb.SCOPE_SUBTREE, scope=ldb.SCOPE_SUBTREE,
expression=search_filter, attrs=[]) expression=search_filter, attrs=[])
if computerlist: if computerlist:
return computerlist[0] return computerlist[0]
else: else:

View File

@ -26,7 +26,7 @@ class ForestCmdTestCase(SambaToolCmdTest):
def setUp(self): def setUp(self):
super(ForestCmdTestCase, self).setUp() super(ForestCmdTestCase, self).setUp()
self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"], self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"]))
self.domain_dn = self.samdb.domain_dn() self.domain_dn = self.samdb.domain_dn()
def tearDown(self): def tearDown(self):
@ -43,10 +43,10 @@ class ForestCmdTestCase(SambaToolCmdTest):
def test_display(self): def test_display(self):
"""Tests that we can display forest settings""" """Tests that we can display forest settings"""
(result, out, err) = self.runsublevelcmd("forest", ("directory_service", (result, out, err) = self.runsublevelcmd("forest", ("directory_service",
"show"), "show"),
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err) self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages") self.assertEquals(err,"","Shouldn't be any error messages")
@ -56,10 +56,10 @@ class ForestCmdTestCase(SambaToolCmdTest):
"""Test that we can modify the dsheuristics setting""" """Test that we can modify the dsheuristics setting"""
(result, out, err) = self.runsublevelcmd("forest", ("directory_service", (result, out, err) = self.runsublevelcmd("forest", ("directory_service",
"dsheuristics"), "0000002", "dsheuristics"), "0000002",
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err) self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages") self.assertEquals(err,"","Shouldn't be any error messages")

View File

@ -30,11 +30,11 @@ class FsmoCmdTestCase(SambaToolCmdTest):
# Check that the output is sensible # Check that the output is sensible
samdb = self.getSamDB("-H", "ldap://%s" % os.environ["SERVER"], samdb = self.getSamDB("-H", "ldap://%s" % os.environ["SERVER"],
"-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"])) "-U%s%%%s" % (os.environ["USERNAME"], os.environ["PASSWORD"]))
try: try:
res = samdb.search(base=ldb.Dn(samdb, "CN=Infrastructure,DC=DomainDnsZones") + samdb.get_default_basedn(), res = samdb.search(base=ldb.Dn(samdb, "CN=Infrastructure,DC=DomainDnsZones") + samdb.get_default_basedn(),
scope=ldb.SCOPE_BASE, attrs=["fsmoRoleOwner"]) scope=ldb.SCOPE_BASE, attrs=["fsmoRoleOwner"])
self.assertTrue("DomainDnsZonesMasterRole owner: " + res[0]["fsmoRoleOwner"][0] in out) self.assertTrue("DomainDnsZonesMasterRole owner: " + res[0]["fsmoRoleOwner"][0] in out)
except ldb.LdbError as e: except ldb.LdbError as e:

View File

@ -32,7 +32,7 @@ class GroupCmdTestCase(SambaToolCmdTest):
def setUp(self): def setUp(self):
super(GroupCmdTestCase, self).setUp() super(GroupCmdTestCase, self).setUp()
self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"], self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"]))
self.groups = [] self.groups = []
self.groups.append(self._randomGroup({"name": "testgroup1"})) self.groups.append(self._randomGroup({"name": "testgroup1"}))
self.groups.append(self._randomGroup({"name": "testgroup2"})) self.groups.append(self._randomGroup({"name": "testgroup2"}))
@ -85,7 +85,7 @@ class GroupCmdTestCase(SambaToolCmdTest):
"--description=%s" % group["description"], "--description=%s" % group["description"],
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err) self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","There shouldn't be any error message") self.assertEquals(err,"","There shouldn't be any error message")
@ -199,8 +199,8 @@ class GroupCmdTestCase(SambaToolCmdTest):
def _find_group(self, name): def _find_group(self, name):
search_filter = ("(&(sAMAccountName=%s)(objectCategory=%s,%s))" % search_filter = ("(&(sAMAccountName=%s)(objectCategory=%s,%s))" %
(ldb.binary_encode(name), (ldb.binary_encode(name),
"CN=Group,CN=Schema,CN=Configuration", "CN=Group,CN=Schema,CN=Configuration",
self.samdb.domain_dn())) self.samdb.domain_dn()))
grouplist = self.samdb.search(base=self.samdb.domain_dn(), grouplist = self.samdb.search(base=self.samdb.domain_dn(),
scope=ldb.SCOPE_SUBTREE, scope=ldb.SCOPE_SUBTREE,
expression=search_filter, expression=search_filter,

View File

@ -31,7 +31,7 @@ class OUCmdTestCase(SambaToolCmdTest):
def setUp(self): def setUp(self):
super(OUCmdTestCase, self).setUp() super(OUCmdTestCase, self).setUp()
self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"], self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"]))
self.ous = [] self.ous = []
self.ous.append(self._randomOU({"name": "testou1"})) self.ous.append(self._randomOU({"name": "testou1"}))
self.ous.append(self._randomOU({"name": "testou2"})) self.ous.append(self._randomOU({"name": "testou2"}))
@ -159,7 +159,7 @@ class OUCmdTestCase(SambaToolCmdTest):
"Renamed ou '%s' still exists" % ou["name"]) "Renamed ou '%s' still exists" % ou["name"])
found = self._find_ou(newouname) found = self._find_ou(newouname)
self.assertIsNotNone(found, self.assertIsNotNone(found,
"Renamed ou '%s' does not exist" % newouname) "Renamed ou '%s' does not exist" % newouname)
(result, out, err) = self.runsubcmd("ou", "rename", (result, out, err) = self.runsubcmd("ou", "rename",
"OU=%s" % newouname, "OU=%s" % newouname,
@ -262,8 +262,8 @@ class OUCmdTestCase(SambaToolCmdTest):
def _find_ou(self, name): def _find_ou(self, name):
search_filter = ("(&(name=%s)(objectCategory=%s,%s))" % search_filter = ("(&(name=%s)(objectCategory=%s,%s))" %
(ldb.binary_encode(name), (ldb.binary_encode(name),
"CN=Organizational-Unit,CN=Schema,CN=Configuration", "CN=Organizational-Unit,CN=Schema,CN=Configuration",
self.samdb.domain_dn())) self.samdb.domain_dn()))
oulist = self.samdb.search(base=self.samdb.domain_dn(), oulist = self.samdb.search(base=self.samdb.domain_dn(),
scope=ldb.SCOPE_SUBTREE, scope=ldb.SCOPE_SUBTREE,
expression=search_filter, expression=search_filter,

View File

@ -35,7 +35,7 @@ class RodcCmdTestCase(SambaToolCmdTest):
self.creds.guess(self.lp) self.creds.guess(self.lp)
self.session = system_session() self.session = system_session()
self.ldb = SamDB("ldap://" + os.environ["DC_SERVER"], self.ldb = SamDB("ldap://" + os.environ["DC_SERVER"],
session_info=self.session, credentials=self.creds,lp=self.lp) session_info=self.session, credentials=self.creds,lp=self.lp)
self.base_dn = self.ldb.domain_dn() self.base_dn = self.ldb.domain_dn()

View File

@ -26,7 +26,7 @@ class SchemaCmdTestCase(SambaToolCmdTest):
def setUp(self): def setUp(self):
super(SchemaCmdTestCase, self).setUp() super(SchemaCmdTestCase, self).setUp()
self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"], self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"]))
def tearDown(self): def tearDown(self):
super(SchemaCmdTestCase, self).tearDown() super(SchemaCmdTestCase, self).tearDown()
@ -34,10 +34,10 @@ class SchemaCmdTestCase(SambaToolCmdTest):
def test_display_attribute(self): def test_display_attribute(self):
"""Tests that we can display schema attributes""" """Tests that we can display schema attributes"""
(result, out, err) = self.runsublevelcmd("schema", ("attribute", (result, out, err) = self.runsublevelcmd("schema", ("attribute",
"show"), "uid", "show"), "uid",
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err) self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages") self.assertEquals(err,"","Shouldn't be any error messages")
@ -46,40 +46,40 @@ class SchemaCmdTestCase(SambaToolCmdTest):
def test_modify_attribute_searchflags(self): def test_modify_attribute_searchflags(self):
"""Tests that we can modify searchFlags of an attribute""" """Tests that we can modify searchFlags of an attribute"""
(result, out, err) = self.runsublevelcmd("schema", ("attribute", (result, out, err) = self.runsublevelcmd("schema", ("attribute",
"modify"), "uid", "--searchflags=9", "modify"), "uid", "--searchflags=9",
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdFail(result, 'Unknown flag 9, please see --help') self.assertCmdFail(result, 'Unknown flag 9, please see --help')
(result, out, err) = self.runsublevelcmd("schema", ("attribute", (result, out, err) = self.runsublevelcmd("schema", ("attribute",
"modify"), "uid", "--searchflags=fATTINDEX", "modify"), "uid", "--searchflags=fATTINDEX",
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err) self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages") self.assertEquals(err,"","Shouldn't be any error messages")
self.assertIn("modified cn=uid,CN=Schema,CN=Configuration,DC=samba,DC=example,DC=com", out) self.assertIn("modified cn=uid,CN=Schema,CN=Configuration,DC=samba,DC=example,DC=com", out)
(result, out, err) = self.runsublevelcmd("schema", ("attribute", (result, out, err) = self.runsublevelcmd("schema", ("attribute",
"modify"), "uid", "modify"), "uid",
"--searchflags=fATTINDEX,fSUBTREEATTINDEX", "--searchflags=fATTINDEX,fSUBTREEATTINDEX",
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err) self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages") self.assertEquals(err,"","Shouldn't be any error messages")
self.assertIn("modified cn=uid,CN=Schema,CN=Configuration,DC=samba,DC=example,DC=com", out) self.assertIn("modified cn=uid,CN=Schema,CN=Configuration,DC=samba,DC=example,DC=com", out)
(result, out, err) = self.runsublevelcmd("schema", ("attribute", (result, out, err) = self.runsublevelcmd("schema", ("attribute",
"modify"), "uid", "modify"), "uid",
"--searchflags=fAtTiNdEx,fPRESERVEONDELETE", "--searchflags=fAtTiNdEx,fPRESERVEONDELETE",
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err) self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages") self.assertEquals(err,"","Shouldn't be any error messages")
@ -88,10 +88,10 @@ class SchemaCmdTestCase(SambaToolCmdTest):
def test_show_oc_attribute(self): def test_show_oc_attribute(self):
"""Tests that we can modify searchFlags of an attribute""" """Tests that we can modify searchFlags of an attribute"""
(result, out, err) = self.runsublevelcmd("schema", ("attribute", (result, out, err) = self.runsublevelcmd("schema", ("attribute",
"show_oc"), "cn", "show_oc"), "cn",
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err) self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages") self.assertEquals(err,"","Shouldn't be any error messages")
@ -101,10 +101,10 @@ class SchemaCmdTestCase(SambaToolCmdTest):
def test_display_objectclass(self): def test_display_objectclass(self):
"""Tests that we can display schema objectclasses""" """Tests that we can display schema objectclasses"""
(result, out, err) = self.runsublevelcmd("schema", ("objectclass", (result, out, err) = self.runsublevelcmd("schema", ("objectclass",
"show"), "person", "show"), "person",
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err) self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages") self.assertEquals(err,"","Shouldn't be any error messages")

View File

@ -36,7 +36,7 @@ class UserCmdTestCase(SambaToolCmdTest):
def setUp(self): def setUp(self):
super(UserCmdTestCase, self).setUp() super(UserCmdTestCase, self).setUp()
self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"], self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"]))
self.users = [] self.users = []
self.users.append(self._randomUser({"name": "sambatool1", "company": "comp1"})) self.users.append(self._randomUser({"name": "sambatool1", "company": "comp1"}))
self.users.append(self._randomUser({"name": "sambatool2", "company": "comp1"})) self.users.append(self._randomUser({"name": "sambatool2", "company": "comp1"}))
@ -217,16 +217,16 @@ class UserCmdTestCase(SambaToolCmdTest):
for a in cache_attrs.keys(): for a in cache_attrs.keys():
v = cache_attrs[a].get("value", "") v = cache_attrs[a].get("value", "")
self.assertMatch(out, "%s: %s" % (a, v), self.assertMatch(out, "%s: %s" % (a, v),
"syncpasswords --cache-ldb-initialize: %s: %s out[%s]" % (a, v, out)) "syncpasswords --cache-ldb-initialize: %s: %s out[%s]" % (a, v, out))
(result, out, err) = self.runsubcmd("user", "syncpasswords", "--no-wait") (result, out, err) = self.runsubcmd("user", "syncpasswords", "--no-wait")
self.assertCmdSuccess(result, out, err, "Ensure syncpasswords --no-wait runs") self.assertCmdSuccess(result, out, err, "Ensure syncpasswords --no-wait runs")
self.assertEqual(err,"","syncpasswords --no-wait") self.assertEqual(err,"","syncpasswords --no-wait")
self.assertMatch(out, "dirsync_loop(): results 0", self.assertMatch(out, "dirsync_loop(): results 0",
"syncpasswords --no-wait: 'dirsync_loop(): results 0': out[%s]" % (out)) "syncpasswords --no-wait: 'dirsync_loop(): results 0': out[%s]" % (out))
for user in self.users: for user in self.users:
self.assertMatch(out, "sAMAccountName: %s" % (user["name"]), self.assertMatch(out, "sAMAccountName: %s" % (user["name"]),
"syncpasswords --no-wait: 'sAMAccountName': %s out[%s]" % (user["name"], out)) "syncpasswords --no-wait: 'sAMAccountName': %s out[%s]" % (user["name"], out))
for user in self.users: for user in self.users:
newpasswd = self.randomPass() newpasswd = self.randomPass()
@ -249,24 +249,24 @@ class UserCmdTestCase(SambaToolCmdTest):
self.assertCmdSuccess(result, out, err, "Ensure syncpasswords --no-wait runs") self.assertCmdSuccess(result, out, err, "Ensure syncpasswords --no-wait runs")
self.assertEqual(err,"","syncpasswords --no-wait") self.assertEqual(err,"","syncpasswords --no-wait")
self.assertMatch(out, "dirsync_loop(): results 0", self.assertMatch(out, "dirsync_loop(): results 0",
"syncpasswords --no-wait: 'dirsync_loop(): results 0': out[%s]" % (out)) "syncpasswords --no-wait: 'dirsync_loop(): results 0': out[%s]" % (out))
self.assertMatch(out, "sAMAccountName: %s" % (user["name"]), self.assertMatch(out, "sAMAccountName: %s" % (user["name"]),
"syncpasswords --no-wait: 'sAMAccountName': %s out[%s]" % (user["name"], out)) "syncpasswords --no-wait: 'sAMAccountName': %s out[%s]" % (user["name"], out))
self.assertMatch(out, "# unicodePwd::: REDACTED SECRET ATTRIBUTE", self.assertMatch(out, "# unicodePwd::: REDACTED SECRET ATTRIBUTE",
"getpassword '# unicodePwd::: REDACTED SECRET ATTRIBUTE': out[%s]" % out) "getpassword '# unicodePwd::: REDACTED SECRET ATTRIBUTE': out[%s]" % out)
self.assertMatch(out, "unicodePwd:: %s" % unicodePwd, self.assertMatch(out, "unicodePwd:: %s" % unicodePwd,
"getpassword unicodePwd: out[%s]" % out) "getpassword unicodePwd: out[%s]" % out)
self.assertMatch(out, "# supplementalCredentials::: REDACTED SECRET ATTRIBUTE", self.assertMatch(out, "# supplementalCredentials::: REDACTED SECRET ATTRIBUTE",
"getpassword '# supplementalCredentials::: REDACTED SECRET ATTRIBUTE': out[%s]" % out) "getpassword '# supplementalCredentials::: REDACTED SECRET ATTRIBUTE': out[%s]" % out)
self.assertMatch(out, "supplementalCredentials:: ", self.assertMatch(out, "supplementalCredentials:: ",
"getpassword supplementalCredentials: out[%s]" % out) "getpassword supplementalCredentials: out[%s]" % out)
if "virtualSambaGPG:: " in out: if "virtualSambaGPG:: " in out:
self.assertMatch(out, "virtualClearTextUTF8:: %s" % virtualClearTextUTF8, self.assertMatch(out, "virtualClearTextUTF8:: %s" % virtualClearTextUTF8,
"getpassword virtualClearTextUTF8: out[%s]" % out) "getpassword virtualClearTextUTF8: out[%s]" % out)
self.assertMatch(out, "virtualClearTextUTF16:: %s" % virtualClearTextUTF16, self.assertMatch(out, "virtualClearTextUTF16:: %s" % virtualClearTextUTF16,
"getpassword virtualClearTextUTF16: out[%s]" % out) "getpassword virtualClearTextUTF16: out[%s]" % out)
self.assertMatch(out, "virtualSSHA: ", self.assertMatch(out, "virtualSSHA: ",
"getpassword virtualSSHA: out[%s]" % out) "getpassword virtualSSHA: out[%s]" % out)
(result, out, err) = self.runsubcmd("user", "getpassword", (result, out, err) = self.runsubcmd("user", "getpassword",
user["name"], user["name"],
@ -276,19 +276,19 @@ class UserCmdTestCase(SambaToolCmdTest):
self.assertEqual(err,"","getpassword without url") self.assertEqual(err,"","getpassword without url")
self.assertMatch(out, "Got password OK", "getpassword without url") self.assertMatch(out, "Got password OK", "getpassword without url")
self.assertMatch(out, "sAMAccountName: %s" % (user["name"]), self.assertMatch(out, "sAMAccountName: %s" % (user["name"]),
"getpassword: 'sAMAccountName': %s out[%s]" % (user["name"], out)) "getpassword: 'sAMAccountName': %s out[%s]" % (user["name"], out))
self.assertMatch(out, "unicodePwd:: %s" % unicodePwd, self.assertMatch(out, "unicodePwd:: %s" % unicodePwd,
"getpassword unicodePwd: out[%s]" % out) "getpassword unicodePwd: out[%s]" % out)
self.assertMatch(out, "supplementalCredentials:: ", self.assertMatch(out, "supplementalCredentials:: ",
"getpassword supplementalCredentials: out[%s]" % out) "getpassword supplementalCredentials: out[%s]" % out)
self._verify_supplementalCredentials(out.replace("\nGot password OK\n", "")) self._verify_supplementalCredentials(out.replace("\nGot password OK\n", ""))
if "virtualSambaGPG:: " in out: if "virtualSambaGPG:: " in out:
self.assertMatch(out, "virtualClearTextUTF8:: %s" % virtualClearTextUTF8, self.assertMatch(out, "virtualClearTextUTF8:: %s" % virtualClearTextUTF8,
"getpassword virtualClearTextUTF8: out[%s]" % out) "getpassword virtualClearTextUTF8: out[%s]" % out)
self.assertMatch(out, "virtualClearTextUTF16:: %s" % virtualClearTextUTF16, self.assertMatch(out, "virtualClearTextUTF16:: %s" % virtualClearTextUTF16,
"getpassword virtualClearTextUTF16: out[%s]" % out) "getpassword virtualClearTextUTF16: out[%s]" % out)
self.assertMatch(out, "virtualSSHA: ", self.assertMatch(out, "virtualSSHA: ",
"getpassword virtualSSHA: out[%s]" % out) "getpassword virtualSSHA: out[%s]" % out)
for user in self.users: for user in self.users:
newpasswd = self.randomPass() newpasswd = self.randomPass()
@ -373,7 +373,7 @@ class UserCmdTestCase(SambaToolCmdTest):
"--attributes=sAMAccountName,company", "--attributes=sAMAccountName,company",
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.assertCmdSuccess(result, out, err, "Error running show") self.assertCmdSuccess(result, out, err, "Error running show")
expected_out = """dn: CN=%s %s,CN=Users,%s expected_out = """dn: CN=%s %s,CN=Users,%s
@ -585,8 +585,8 @@ sAMAccountName: %s
def _find_user(self, name): def _find_user(self, name):
search_filter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb.binary_encode(name), "CN=Person,CN=Schema,CN=Configuration", self.samdb.domain_dn()) search_filter = "(&(sAMAccountName=%s)(objectCategory=%s,%s))" % (ldb.binary_encode(name), "CN=Person,CN=Schema,CN=Configuration", self.samdb.domain_dn())
userlist = self.samdb.search(base=self.samdb.domain_dn(), userlist = self.samdb.search(base=self.samdb.domain_dn(),
scope=ldb.SCOPE_SUBTREE, scope=ldb.SCOPE_SUBTREE,
expression=search_filter, attrs=[]) expression=search_filter, attrs=[])
if userlist: if userlist:
return userlist[0] return userlist[0]
else: else:

View File

@ -33,7 +33,7 @@ class UserCheckPwdTestCase(SambaToolCmdTest):
def setUp(self): def setUp(self):
super(UserCheckPwdTestCase, self).setUp() super(UserCheckPwdTestCase, self).setUp()
self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"], self.samdb = self.getSamDB("-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"])) "-U%s%%%s" % (os.environ["DC_USERNAME"], os.environ["DC_PASSWORD"]))
self.old_min_pwd_age = self.samdb.get_minPwdAge() self.old_min_pwd_age = self.samdb.get_minPwdAge()
self.samdb.set_minPwdAge("0") self.samdb.set_minPwdAge("0")

View File

@ -126,7 +126,7 @@ class UserCmdCryptShaTestCase(SambaToolCmdTest):
self.ldb.modify( self.ldb.modify(
msg, msg,
controls=["local_oid:%s:0" % controls=["local_oid:%s:0" %
dsdb.DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID]) dsdb.DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID])
# gpg decryption not enabled. # gpg decryption not enabled.
# both virtual attributes specified, no rounds option # both virtual attributes specified, no rounds option

View File

@ -68,7 +68,7 @@ class UserCmdWdigestTestCase(SambaToolCmdTest):
self.samdb = self.getSamDB( self.samdb = self.getSamDB(
"-H", "ldap://%s" % os.environ["DC_SERVER"], "-H", "ldap://%s" % os.environ["DC_SERVER"],
"-U%s%%%s" % (os.environ["DC_USERNAME"], "-U%s%%%s" % (os.environ["DC_USERNAME"],
os.environ["DC_PASSWORD"])) os.environ["DC_PASSWORD"]))
self.dns_domain = self.samdb.domain_dns_name() self.dns_domain = self.samdb.domain_dns_name()
res = self.samdb.search( res = self.samdb.search(
base=self.samdb.get_config_basedn(), base=self.samdb.get_config_basedn(),

View File

@ -74,7 +74,7 @@ class SecurityDescriptorTests(samba.tests.TestCase):
def test_from_sddl_invalidtype2(self): def test_from_sddl_invalidtype2(self):
sddl = "O:AOG:DAD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)" sddl = "O:AOG:DAD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)"
self.assertRaises(TypeError, security.descriptor.from_sddl, sddl, self.assertRaises(TypeError, security.descriptor.from_sddl, sddl,
"S-2-0-0") "S-2-0-0")
def test_as_sddl(self): def test_as_sddl(self):
text = "O:AOG:DAD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)" text = "O:AOG:DAD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)"
@ -139,11 +139,11 @@ class PrivilegeTests(samba.tests.TestCase):
def test_privilege_name(self): def test_privilege_name(self):
self.assertEquals("SeShutdownPrivilege", self.assertEquals("SeShutdownPrivilege",
security.privilege_name(security.SEC_PRIV_SHUTDOWN)) security.privilege_name(security.SEC_PRIV_SHUTDOWN))
def test_privilege_id(self): def test_privilege_id(self):
self.assertEquals(security.SEC_PRIV_SHUTDOWN, self.assertEquals(security.SEC_PRIV_SHUTDOWN,
security.privilege_id("SeShutdownPrivilege")) security.privilege_id("SeShutdownPrivilege"))
class CheckAccessTests(samba.tests.TestCase): class CheckAccessTests(samba.tests.TestCase):

View File

@ -49,9 +49,9 @@ class SMBTests(samba.tests.TestCase):
def test_list(self): def test_list(self):
ls = [f['name'] for f in self.conn.list(addom)] ls = [f['name'] for f in self.conn.list(addom)]
self.assertIn('scripts', ls, self.assertIn('scripts', ls,
msg='"scripts" directory not found in sysvol') msg='"scripts" directory not found in sysvol')
self.assertIn('Policies',ls, self.assertIn('Policies',ls,
msg='"Policies" directory not found in sysvol') msg='"Policies" directory not found in sysvol')
def test_unlink(self): def test_unlink(self):
""" """
@ -67,7 +67,7 @@ class SMBTests(samba.tests.TestCase):
contents = self.conn.loadfile(test_file) contents = self.conn.loadfile(test_file)
self.assertEquals(contents.decode('utf8'), test_contents, self.assertEquals(contents.decode('utf8'), test_contents,
msg='contents of test file did not match what was written') msg='contents of test file did not match what was written')
# with python2 this will save/load str type (with embedded nulls) # with python2 this will save/load str type (with embedded nulls)
# with python3 this will save/load bytes type # with python3 this will save/load bytes type
@ -76,7 +76,7 @@ class SMBTests(samba.tests.TestCase):
contents = self.conn.loadfile(test_file) contents = self.conn.loadfile(test_file)
self.assertEquals(contents, test_literal_bytes_embed_nulls, self.assertEquals(contents, test_literal_bytes_embed_nulls,
msg='contents of test file did not match what was written') msg='contents of test file did not match what was written')
# python3 only this will save/load unicode # python3 only this will save/load unicode
def test_save_load_utfcontents(self): def test_save_load_utfcontents(self):
@ -85,7 +85,7 @@ class SMBTests(samba.tests.TestCase):
contents = self.conn.loadfile(test_file) contents = self.conn.loadfile(test_file)
self.assertEquals(contents.decode('utf8'), utf_contents, self.assertEquals(contents.decode('utf8'), utf_contents,
msg='contents of test file did not match what was written') msg='contents of test file did not match what was written')
# with python2 this will save/load str type # with python2 this will save/load str type
# with python3 this will save/load bytes type # with python3 this will save/load bytes type
@ -94,4 +94,4 @@ class SMBTests(samba.tests.TestCase):
contents = self.conn.loadfile(test_file) contents = self.conn.loadfile(test_file)
self.assertEquals(contents, binary_contents, self.assertEquals(contents, binary_contents,
msg='contents of test file did not match what was written') msg='contents of test file did not match what was written')

View File

@ -151,7 +151,7 @@ class TestSource(TestCase):
def _format_message(self, dict_, message): def _format_message(self, dict_, message):
files = ["%s: %s" % (f, ', '.join([str(i + 1) for i in lines])) files = ["%s: %s" % (f, ', '.join([str(i + 1) for i in lines]))
for f, lines in dict_.items()] for f, lines in dict_.items()]
files.sort() files.sort()
return message + '\n\n %s' % ('\n '.join(files)) return message + '\n\n %s' % ('\n '.join(files))
@ -170,8 +170,8 @@ class TestSource(TestCase):
self._push_file(tabs, fname, line_no) self._push_file(tabs, fname, line_no)
if tabs: if tabs:
self.fail(self._format_message(tabs, self.fail(self._format_message(tabs,
'Tab characters were found in the following source files.' 'Tab characters were found in the following source files.'
'\nThey should either be replaced by "\\t" or by spaces:')) '\nThey should either be replaced by "\\t" or by spaces:'))
def test_unix_newlines(self): def test_unix_newlines(self):
"""Check for unix new lines.""" """Check for unix new lines."""
@ -181,7 +181,7 @@ class TestSource(TestCase):
self._push_file(illegal_newlines, fname, line_no) self._push_file(illegal_newlines, fname, line_no)
if illegal_newlines: if illegal_newlines:
self.fail(self._format_message(illegal_newlines, self.fail(self._format_message(illegal_newlines,
'Non-unix newlines were found in the following source files:')) 'Non-unix newlines were found in the following source files:'))
def test_trailing_whitespace(self): def test_trailing_whitespace(self):
"""Check that there is not trailing whitespace in Python files.""" """Check that there is not trailing whitespace in Python files."""
@ -191,7 +191,7 @@ class TestSource(TestCase):
self._push_file(trailing_whitespace, fname, line_no) self._push_file(trailing_whitespace, fname, line_no)
if trailing_whitespace: if trailing_whitespace:
self.fail(self._format_message(trailing_whitespace, self.fail(self._format_message(trailing_whitespace,
'Trailing whitespace was found in the following source files.')) 'Trailing whitespace was found in the following source files.'))
def test_shebang_lines(self): def test_shebang_lines(self):
"""Check that files with shebang lines and only those are executable.""" """Check that files with shebang lines and only those are executable."""
@ -208,7 +208,7 @@ class TestSource(TestCase):
self._push_file(files_without_shebang, fname, line_no) self._push_file(files_without_shebang, fname, line_no)
if files_with_shebang: if files_with_shebang:
self.fail(self._format_message(files_with_shebang, self.fail(self._format_message(files_with_shebang,
'Files with shebang line that are not executable:')) 'Files with shebang line that are not executable:'))
if files_without_shebang: if files_without_shebang:
self.fail(self._format_message(files_without_shebang, self.fail(self._format_message(files_without_shebang,
'Files without shebang line that are executable:')) 'Files without shebang line that are executable:'))

View File

@ -46,10 +46,10 @@ class SubunitOptions(optparse.OptionGroup):
def __init__(self, parser): def __init__(self, parser):
optparse.OptionGroup.__init__(self, parser, "Subunit Options") optparse.OptionGroup.__init__(self, parser, "Subunit Options")
self.add_option('-l', '--list', dest='listtests', default=False, self.add_option('-l', '--list', dest='listtests', default=False,
help='List tests rather than running them.', help='List tests rather than running them.',
action="store_true") action="store_true")
self.add_option('--load-list', dest='load_list', default=None, self.add_option('--load-list', dest='load_list', default=None,
help='Specify a filename containing the test ids to use.') help='Specify a filename containing the test ids to use.')
class TestProgram(BaseTestProgram): class TestProgram(BaseTestProgram):

View File

@ -37,4 +37,4 @@ class WinsUpgradeTests(LdbTestCase):
def test_version(self): def test_version(self):
import_wins(self.ldb, {}) import_wins(self.ldb, {})
self.assertEquals("VERSION", self.assertEquals("VERSION",
str(self.ldb.search(expression="(objectClass=winsMaxVersion)")[0]["cn"])) str(self.ldb.search(expression="(objectClass=winsMaxVersion)")[0]["cn"]))

View File

@ -137,7 +137,7 @@ class UpdateSecretsTests(samba.tests.TestCaseInTempDir):
# Test that updating an already up-to-date secretsdb works fine # Test that updating an already up-to-date secretsdb works fine
self.secretsdb = self._getCurrentFormatDb() self.secretsdb = self._getCurrentFormatDb()
self.assertEquals(None, self.assertEquals(None,
update_secrets(self.referencedb, self.secretsdb, dummymessage)) update_secrets(self.referencedb, self.secretsdb, dummymessage))
def test_update_modules(self): def test_update_modules(self):
empty_db = self._getEmptyDb() empty_db = self._getEmptyDb()

View File

@ -26,12 +26,12 @@ from samba.credentials import Credentials
from samba.auth import system_session from samba.auth import system_session
from samba.provision import getpolicypath,find_provision_key_parameters from samba.provision import getpolicypath,find_provision_key_parameters
from samba.upgradehelpers import (get_paths, get_ldbs, from samba.upgradehelpers import (get_paths, get_ldbs,
identic_rename, identic_rename,
updateOEMInfo, getOEMInfo, update_gpo, updateOEMInfo, getOEMInfo, update_gpo,
delta_update_basesamdb, delta_update_basesamdb,
update_dns_account_password, update_dns_account_password,
search_constructed_attrs_stored, search_constructed_attrs_stored,
increment_calculated_keyversion_number) increment_calculated_keyversion_number)
from samba.tests import env_loadparm, TestCaseInTempDir from samba.tests import env_loadparm, TestCaseInTempDir
from samba.tests.provision import create_dummy_secretsdb from samba.tests.provision import create_dummy_secretsdb
import ldb import ldb
@ -82,8 +82,8 @@ class UpgradeProvisionWithLdbTestCase(TestCaseInTempDir):
self.paths = paths self.paths = paths
self.ldbs = get_ldbs(paths, self.creds, system_session(), self.lp) self.ldbs = get_ldbs(paths, self.creds, system_session(), self.lp)
self.names = find_provision_key_parameters(self.ldbs.sam, self.names = find_provision_key_parameters(self.ldbs.sam,
self.ldbs.secrets, self.ldbs.idmap, paths, smb_conf_path, self.ldbs.secrets, self.ldbs.idmap, paths, smb_conf_path,
self.lp) self.lp)
self.referencedb = create_dummy_secretsdb( self.referencedb = create_dummy_secretsdb(
os.path.join(self.tempdir, "ref.ldb")) os.path.join(self.tempdir, "ref.ldb"))
@ -104,7 +104,7 @@ class UpgradeProvisionWithLdbTestCase(TestCaseInTempDir):
self.names.rootdn, self.names.rootdn,
hash) hash)
self.assertEqual(self.ldbs.sam.get_attribute_replmetadata_version(dn, self.assertEqual(self.ldbs.sam.get_attribute_replmetadata_version(dn,
"unicodePwd"), "unicodePwd"),
140) 140)
# This function should not decrement the version # This function should not decrement the version
hash[dn.lower()] = 130 hash[dn.lower()] = 130
@ -113,7 +113,7 @@ class UpgradeProvisionWithLdbTestCase(TestCaseInTempDir):
self.names.rootdn, self.names.rootdn,
hash) hash)
self.assertEqual(self.ldbs.sam.get_attribute_replmetadata_version(dn, self.assertEqual(self.ldbs.sam.get_attribute_replmetadata_version(dn,
"unicodePwd"), "unicodePwd"),
140) 140)
def test_identic_rename(self): def test_identic_rename(self):
@ -122,7 +122,7 @@ class UpgradeProvisionWithLdbTestCase(TestCaseInTempDir):
guestDN = ldb.Dn(self.ldbs.sam, "CN=Guest,CN=Users,%s" % rootdn) guestDN = ldb.Dn(self.ldbs.sam, "CN=Guest,CN=Users,%s" % rootdn)
identic_rename(self.ldbs.sam, guestDN) identic_rename(self.ldbs.sam, guestDN)
res = self.ldbs.sam.search(expression="(name=Guest)", base=rootdn, res = self.ldbs.sam.search(expression="(name=Guest)", base=rootdn,
scope=ldb.SCOPE_SUBTREE, attrs=["dn"]) scope=ldb.SCOPE_SUBTREE, attrs=["dn"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertEquals(str(res[0]["dn"]), "CN=Guest,CN=Users,%s" % rootdn) self.assertEquals(str(res[0]["dn"]), "CN=Guest,CN=Users,%s" % rootdn)
@ -134,7 +134,7 @@ class UpgradeProvisionWithLdbTestCase(TestCaseInTempDir):
def test_update_gpo_simple(self): def test_update_gpo_simple(self):
dir = getpolicypath(self.paths.sysvol, self.names.dnsdomain, dir = getpolicypath(self.paths.sysvol, self.names.dnsdomain,
self.names.policyid) self.names.policyid)
shutil.rmtree(dir) shutil.rmtree(dir)
self.assertFalse(os.path.isdir(dir)) self.assertFalse(os.path.isdir(dir))
update_gpo(self.paths, self.ldbs.sam, self.names, self.lp, dummymessage) update_gpo(self.paths, self.ldbs.sam, self.names, self.lp, dummymessage)
@ -147,7 +147,7 @@ class UpgradeProvisionWithLdbTestCase(TestCaseInTempDir):
os.mkdir(path) os.mkdir(path)
os.mkdir(os.path.join(path, self.names.dnsdomain)) os.mkdir(os.path.join(path, self.names.dnsdomain))
os.mkdir(os.path.join(os.path.join(path, self.names.dnsdomain), os.mkdir(os.path.join(os.path.join(path, self.names.dnsdomain),
"Policies")) "Policies"))
update_gpo(self.paths, self.ldbs.sam, self.names, self.lp, dummymessage) update_gpo(self.paths, self.ldbs.sam, self.names, self.lp, dummymessage)
shutil.rmtree(path) shutil.rmtree(path)
self.paths.sysvol = save self.paths.sysvol = save
@ -160,7 +160,7 @@ class UpgradeProvisionWithLdbTestCase(TestCaseInTempDir):
def test_update_dns_account(self): def test_update_dns_account(self):
update_dns_account_password(self.ldbs.sam, self.ldbs.secrets, update_dns_account_password(self.ldbs.sam, self.ldbs.secrets,
self.names) self.names)
def test_updateOEMInfo(self): def test_updateOEMInfo(self):
realm = self.lp.get("realm") realm = self.lp.get("realm")

View File

@ -49,7 +49,7 @@ class XattrTests(TestCase):
open(tempf, 'w').write("empty") open(tempf, 'w').write("empty")
try: try:
samba.xattr_native.wrap_setxattr(tempf, "user.unittests", samba.xattr_native.wrap_setxattr(tempf, "user.unittests",
ndr_pack(ntacl)) ndr_pack(ntacl))
except IOError: except IOError:
raise SkipTest("the filesystem where the tests are runned do not support XATTR") raise SkipTest("the filesystem where the tests are runned do not support XATTR")
os.unlink(tempf) os.unlink(tempf)
@ -76,7 +76,7 @@ class XattrTests(TestCase):
open(tempf, 'w').write("empty") open(tempf, 'w').write("empty")
try: try:
samba.xattr_tdb.wrap_setxattr(eadb_path, samba.xattr_tdb.wrap_setxattr(eadb_path,
tempf, "user.unittests", ndr_pack(ntacl)) tempf, "user.unittests", ndr_pack(ntacl))
finally: finally:
os.unlink(tempf) os.unlink(tempf)
os.unlink(eadb_path) os.unlink(eadb_path)
@ -88,8 +88,8 @@ class XattrTests(TestCase):
open(tempf, 'w').write("empty") open(tempf, 'w').write("empty")
try: try:
self.assertRaises(IOError, samba.xattr_tdb.wrap_setxattr, self.assertRaises(IOError, samba.xattr_tdb.wrap_setxattr,
os.path.join("nonexistent", "eadb.tdb"), tempf, os.path.join("nonexistent", "eadb.tdb"), tempf,
"user.unittests", ndr_pack(ntacl)) "user.unittests", ndr_pack(ntacl))
finally: finally:
os.unlink(tempf) os.unlink(tempf)
@ -100,9 +100,9 @@ class XattrTests(TestCase):
open(tempf, 'w').write("empty") open(tempf, 'w').write("empty")
try: try:
samba.xattr_tdb.wrap_setxattr(eadb_path, tempf, "user.unittests", samba.xattr_tdb.wrap_setxattr(eadb_path, tempf, "user.unittests",
reftxt) reftxt)
text = samba.xattr_tdb.wrap_getxattr(eadb_path, tempf, text = samba.xattr_tdb.wrap_getxattr(eadb_path, tempf,
"user.unittests") "user.unittests")
self.assertEquals(text, reftxt) self.assertEquals(text, reftxt)
finally: finally:
os.unlink(tempf) os.unlink(tempf)
@ -116,7 +116,7 @@ class XattrTests(TestCase):
open(tempf, 'w').write("empty") open(tempf, 'w').write("empty")
try: try:
samba.posix_eadb.wrap_setxattr(eadb_path, samba.posix_eadb.wrap_setxattr(eadb_path,
tempf, "user.unittests", ndr_pack(ntacl)) tempf, "user.unittests", ndr_pack(ntacl))
finally: finally:
os.unlink(tempf) os.unlink(tempf)
os.unlink(eadb_path) os.unlink(eadb_path)
@ -128,9 +128,9 @@ class XattrTests(TestCase):
open(tempf, 'w').write("empty") open(tempf, 'w').write("empty")
try: try:
samba.posix_eadb.wrap_setxattr(eadb_path, tempf, "user.unittests", samba.posix_eadb.wrap_setxattr(eadb_path, tempf, "user.unittests",
reftxt) reftxt)
text = samba.posix_eadb.wrap_getxattr(eadb_path, tempf, text = samba.posix_eadb.wrap_getxattr(eadb_path, tempf,
"user.unittests") "user.unittests")
self.assertEquals(text, reftxt) self.assertEquals(text, reftxt)
finally: finally:
os.unlink(tempf) os.unlink(tempf)

View File

@ -60,17 +60,17 @@ def import_sam_policy(samdb, policy, logger):
if 'min password length' in policy: if 'min password length' in policy:
m['a01'] = ldb.MessageElement(str(policy['min password length']), m['a01'] = ldb.MessageElement(str(policy['min password length']),
ldb.FLAG_MOD_REPLACE, 'minPwdLength') ldb.FLAG_MOD_REPLACE, 'minPwdLength')
if 'password history' in policy: if 'password history' in policy:
m['a02'] = ldb.MessageElement(str(policy['password history']), m['a02'] = ldb.MessageElement(str(policy['password history']),
ldb.FLAG_MOD_REPLACE, 'pwdHistoryLength') ldb.FLAG_MOD_REPLACE, 'pwdHistoryLength')
if 'minimum password age' in policy: if 'minimum password age' in policy:
min_pw_age_unix = policy['minimum password age'] min_pw_age_unix = policy['minimum password age']
min_pw_age_nt = int(-min_pw_age_unix * (1e7)) min_pw_age_nt = int(-min_pw_age_unix * (1e7))
m['a03'] = ldb.MessageElement(str(min_pw_age_nt), ldb.FLAG_MOD_REPLACE, m['a03'] = ldb.MessageElement(str(min_pw_age_nt), ldb.FLAG_MOD_REPLACE,
'minPwdAge') 'minPwdAge')
if 'maximum password age' in policy: if 'maximum password age' in policy:
max_pw_age_unix = policy['maximum password age'] max_pw_age_unix = policy['maximum password age']
@ -87,7 +87,7 @@ def import_sam_policy(samdb, policy, logger):
lockout_duration_nt = unix2nttime(lockout_duration_mins * 60) lockout_duration_nt = unix2nttime(lockout_duration_mins * 60)
m['a05'] = ldb.MessageElement(str(lockout_duration_nt), m['a05'] = ldb.MessageElement(str(lockout_duration_nt),
ldb.FLAG_MOD_REPLACE, 'lockoutDuration') ldb.FLAG_MOD_REPLACE, 'lockoutDuration')
try: try:
samdb.modify(m) samdb.modify(m)
@ -96,7 +96,7 @@ def import_sam_policy(samdb, policy, logger):
def add_posix_attrs(logger, samdb, sid, name, nisdomain, xid_type, home=None, def add_posix_attrs(logger, samdb, sid, name, nisdomain, xid_type, home=None,
shell=None, pgid=None): shell=None, pgid=None):
"""Add posix attributes for the user/group """Add posix attributes for the user/group
:param samdb: Samba4 sam.ldb database :param samdb: Samba4 sam.ldb database
@ -192,11 +192,11 @@ def add_idmap_entry(idmapdb, sid, xid, xid_type, logger):
else: else:
try: try:
idmapdb.add({"dn": "CN=%s" % str(sid), idmapdb.add({"dn": "CN=%s" % str(sid),
"cn": str(sid), "cn": str(sid),
"objectClass": "sidMap", "objectClass": "sidMap",
"objectSid": ndr_pack(sid), "objectSid": ndr_pack(sid),
"type": xid_type, "type": xid_type,
"xidNumber": str(xid)}) "xidNumber": str(xid)})
except ldb.LdbError as e: except ldb.LdbError as e:
logger.warn( logger.warn(
'Could not add idmap entry for sid=%s, id=%s, type=%s (%s)', 'Could not add idmap entry for sid=%s, id=%s, type=%s (%s)',
@ -279,18 +279,18 @@ def add_group_from_mapping_entry(samdb, groupmap, logger):
m.dn.add_base(samdb.get_default_basedn()) m.dn.add_base(samdb.get_default_basedn())
m['objectClass'] = ldb.MessageElement('group', ldb.FLAG_MOD_ADD, 'objectClass') m['objectClass'] = ldb.MessageElement('group', ldb.FLAG_MOD_ADD, 'objectClass')
m['objectSid'] = ldb.MessageElement(ndr_pack(groupmap.sid), ldb.FLAG_MOD_ADD, m['objectSid'] = ldb.MessageElement(ndr_pack(groupmap.sid), ldb.FLAG_MOD_ADD,
'objectSid') 'objectSid')
m['sAMAccountName'] = ldb.MessageElement(groupmap.nt_name, ldb.FLAG_MOD_ADD, m['sAMAccountName'] = ldb.MessageElement(groupmap.nt_name, ldb.FLAG_MOD_ADD,
'sAMAccountName') 'sAMAccountName')
if groupmap.comment: if groupmap.comment:
m['description'] = ldb.MessageElement(groupmap.comment, ldb.FLAG_MOD_ADD, m['description'] = ldb.MessageElement(groupmap.comment, ldb.FLAG_MOD_ADD,
'description') 'description')
# Fix up incorrect 'well known' groups that are actually builtin (per test above) to be aliases # Fix up incorrect 'well known' groups that are actually builtin (per test above) to be aliases
if groupmap.sid_name_use == lsa.SID_NAME_ALIAS or groupmap.sid_name_use == lsa.SID_NAME_WKN_GRP: if groupmap.sid_name_use == lsa.SID_NAME_ALIAS or groupmap.sid_name_use == lsa.SID_NAME_WKN_GRP:
m['groupType'] = ldb.MessageElement(str(dsdb.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP), m['groupType'] = ldb.MessageElement(str(dsdb.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP),
ldb.FLAG_MOD_ADD, 'groupType') ldb.FLAG_MOD_ADD, 'groupType')
try: try:
samdb.add(m, controls=["relax:0"]) samdb.add(m, controls=["relax:0"])
@ -408,8 +408,8 @@ def get_posix_attr_from_ldap_backend(logger, ldb_object, base_dn, user, attr):
""" """
try: try:
msg = ldb_object.search(base_dn, scope=ldb.SCOPE_SUBTREE, msg = ldb_object.search(base_dn, scope=ldb.SCOPE_SUBTREE,
expression=("(&(objectClass=posixAccount)(uid=%s))" expression=("(&(objectClass=posixAccount)(uid=%s))"
% (user)), attrs=[attr]) % (user)), attrs=[attr])
except ldb.LdbError as e: except ldb.LdbError as e:
raise ProvisioningError("Failed to retrieve attribute %s for user %s, the error is: %s" % (attr, user, e)) raise ProvisioningError("Failed to retrieve attribute %s for user %s, the error is: %s" % (attr, user, e))
else: else:
@ -422,7 +422,7 @@ def get_posix_attr_from_ldap_backend(logger, ldb_object, base_dn, user, attr):
def upgrade_from_samba3(samba3, logger, targetdir, session_info=None, def upgrade_from_samba3(samba3, logger, targetdir, session_info=None,
useeadb=False, dns_backend=None, use_ntvfs=False): useeadb=False, dns_backend=None, use_ntvfs=False):
"""Upgrade from samba3 database to samba4 AD database """Upgrade from samba3 database to samba4 AD database
:param samba3: samba3 object :param samba3: samba3 object
@ -448,7 +448,7 @@ def upgrade_from_samba3(samba3, logger, targetdir, session_info=None,
if not domainname: if not domainname:
domainname = secrets_db.domains()[0] domainname = secrets_db.domains()[0]
logger.warning("No workgroup specified in smb.conf file, assuming '%s'", logger.warning("No workgroup specified in smb.conf file, assuming '%s'",
domainname) domainname)
if not realm: if not realm:
if serverrole == "ROLE_DOMAIN_BDC" or serverrole == "ROLE_DOMAIN_PDC": if serverrole == "ROLE_DOMAIN_BDC" or serverrole == "ROLE_DOMAIN_PDC":
@ -456,7 +456,7 @@ def upgrade_from_samba3(samba3, logger, targetdir, session_info=None,
else: else:
realm = domainname.upper() realm = domainname.upper()
logger.warning("No realm specified in smb.conf file, assuming '%s'", logger.warning("No realm specified in smb.conf file, assuming '%s'",
realm) realm)
# Find machine account and password # Find machine account and password
next_rid = 1000 next_rid = 1000
@ -840,9 +840,9 @@ Please fix this account before attempting to upgrade again
if result.server_role == "active directory domain controller": if result.server_role == "active directory domain controller":
setsysvolacl(result.samdb, result.paths.netlogon, result.paths.sysvol, setsysvolacl(result.samdb, result.paths.netlogon, result.paths.sysvol,
result.paths.root_uid, result.paths.root_gid, result.paths.root_uid, result.paths.root_gid,
security.dom_sid(result.domainsid), result.names.dnsdomain, security.dom_sid(result.domainsid), result.names.dnsdomain,
result.names.domaindn, result.lp, use_ntvfs) result.names.domaindn, result.lp, use_ntvfs)
# FIXME: import_registry(registry.Registry(), samba3.get_registry()) # FIXME: import_registry(registry.Registry(), samba3.get_registry())
# FIXME: shares # FIXME: shares

View File

@ -33,9 +33,9 @@ from samba import Ldb, version, ntacls
from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE
import ldb import ldb
from samba.provision import (provision_paths_from_lp, from samba.provision import (provision_paths_from_lp,
getpolicypath, set_gpos_acl, create_gpo_struct, getpolicypath, set_gpos_acl, create_gpo_struct,
provision, ProvisioningError, provision, ProvisioningError,
setsysvolacl, secretsdb_self_join) setsysvolacl, secretsdb_self_join)
from samba.provision.common import FILL_FULL from samba.provision.common import FILL_FULL
from samba.dcerpc import xattr, drsblobs, security from samba.dcerpc import xattr, drsblobs, security
from samba.dcerpc.misc import SEC_CHAN_BDC from samba.dcerpc.misc import SEC_CHAN_BDC
@ -58,13 +58,13 @@ PROVISION = 0x08
CHANGEALL = 0xff CHANGEALL = 0xff
hashAttrNotCopied = set(["dn", "whenCreated", "whenChanged", "objectGUID", hashAttrNotCopied = set(["dn", "whenCreated", "whenChanged", "objectGUID",
"uSNCreated", "replPropertyMetaData", "uSNChanged", "parentGUID", "uSNCreated", "replPropertyMetaData", "uSNChanged", "parentGUID",
"objectCategory", "distinguishedName", "nTMixedDomain", "objectCategory", "distinguishedName", "nTMixedDomain",
"showInAdvancedViewOnly", "instanceType", "msDS-Behavior-Version", "showInAdvancedViewOnly", "instanceType", "msDS-Behavior-Version",
"nextRid", "cn", "versionNumber", "lmPwdHistory", "pwdLastSet", "nextRid", "cn", "versionNumber", "lmPwdHistory", "pwdLastSet",
"ntPwdHistory", "unicodePwd","dBCSPwd", "supplementalCredentials", "ntPwdHistory", "unicodePwd","dBCSPwd", "supplementalCredentials",
"gPCUserExtensionNames", "gPCMachineExtensionNames","maxPwdAge", "secret", "gPCUserExtensionNames", "gPCMachineExtensionNames","maxPwdAge", "secret",
"possibleInferiors", "privilege", "sAMAccountType"]) "possibleInferiors", "privilege", "sAMAccountType"])
class ProvisionLDB(object): class ProvisionLDB(object):
@ -252,19 +252,19 @@ def newprovision(names, session, smbconf, provdir, logger, base_schema=None):
os.mkdir(provdir) os.mkdir(provdir)
logger.info("Provision stored in %s", provdir) logger.info("Provision stored in %s", provdir)
return provision(logger, session, smbconf=smbconf, return provision(logger, session, smbconf=smbconf,
targetdir=provdir, samdb_fill=FILL_FULL, realm=names.realm, targetdir=provdir, samdb_fill=FILL_FULL, realm=names.realm,
domain=names.domain, domainguid=names.domainguid, domain=names.domain, domainguid=names.domainguid,
domainsid=names.domainsid, ntdsguid=names.ntdsguid, domainsid=names.domainsid, ntdsguid=names.ntdsguid,
policyguid=names.policyid, policyguid_dc=names.policyid_dc, policyguid=names.policyid, policyguid_dc=names.policyid_dc,
hostname=names.netbiosname.lower(), hostip=None, hostip6=None, hostname=names.netbiosname.lower(), hostip=None, hostip6=None,
invocationid=names.invocation, adminpass=names.adminpass, invocationid=names.invocation, adminpass=names.adminpass,
krbtgtpass=None, machinepass=None, dnspass=None, root=None, krbtgtpass=None, machinepass=None, dnspass=None, root=None,
nobody=None, users=None, nobody=None, users=None,
serverrole="domain controller", serverrole="domain controller",
backend_type=None, ldapadminpass=None, ol_mmr_urls=None, backend_type=None, ldapadminpass=None, ol_mmr_urls=None,
slapd_path=None, slapd_path=None,
dom_for_fun_level=names.domainlevel, dns_backend=names.dns_backend, dom_for_fun_level=names.domainlevel, dns_backend=names.dns_backend,
useeadb=True, use_ntvfs=True, base_schema=base_schema) useeadb=True, use_ntvfs=True, base_schema=base_schema)
def dn_sort(x, y): def dn_sort(x, y):
@ -584,24 +584,24 @@ def update_machine_account_password(samdb, secrets_ldb, names):
machinepass = samba.generate_random_machine_password(128, 255) machinepass = samba.generate_random_machine_password(128, 255)
mputf16 = machinepass.encode('utf-16-le') mputf16 = machinepass.encode('utf-16-le')
msg["clearTextPassword"] = ldb.MessageElement(mputf16, msg["clearTextPassword"] = ldb.MessageElement(mputf16,
ldb.FLAG_MOD_REPLACE, ldb.FLAG_MOD_REPLACE,
"clearTextPassword") "clearTextPassword")
samdb.modify(msg) samdb.modify(msg)
res = samdb.search(expression=("samAccountName=%s$" % names.netbiosname), res = samdb.search(expression=("samAccountName=%s$" % names.netbiosname),
attrs=["msDs-keyVersionNumber"]) attrs=["msDs-keyVersionNumber"])
assert(len(res) == 1) assert(len(res) == 1)
kvno = int(str(res[0]["msDs-keyVersionNumber"])) kvno = int(str(res[0]["msDs-keyVersionNumber"]))
secChanType = int(secrets_msg[0]["secureChannelType"][0]) secChanType = int(secrets_msg[0]["secureChannelType"][0])
secretsdb_self_join(secrets_ldb, domain=names.domain, secretsdb_self_join(secrets_ldb, domain=names.domain,
realm=names.realm, realm=names.realm,
domainsid=names.domainsid, domainsid=names.domainsid,
dnsdomain=names.dnsdomain, dnsdomain=names.dnsdomain,
netbiosname=names.netbiosname, netbiosname=names.netbiosname,
machinepass=machinepass, machinepass=machinepass,
key_version_number=kvno, key_version_number=kvno,
secure_channel_type=secChanType) secure_channel_type=secChanType)
else: else:
raise ProvisioningError("Unable to find a Secure Channel" raise ProvisioningError("Unable to find a Secure Channel"
"of type SEC_CHAN_BDC") "of type SEC_CHAN_BDC")
@ -625,13 +625,13 @@ def update_dns_account_password(samdb, secrets_ldb, names):
machinepass = samba.generate_random_password(128, 255) machinepass = samba.generate_random_password(128, 255)
mputf16 = machinepass.encode('utf-16-le') mputf16 = machinepass.encode('utf-16-le')
msg["clearTextPassword"] = ldb.MessageElement(mputf16, msg["clearTextPassword"] = ldb.MessageElement(mputf16,
ldb.FLAG_MOD_REPLACE, ldb.FLAG_MOD_REPLACE,
"clearTextPassword") "clearTextPassword")
samdb.modify(msg) samdb.modify(msg)
res = samdb.search(expression=expression, res = samdb.search(expression=expression,
attrs=["msDs-keyVersionNumber"]) attrs=["msDs-keyVersionNumber"])
assert(len(res) == 1) assert(len(res) == 1)
kvno = str(res[0]["msDs-keyVersionNumber"]) kvno = str(res[0]["msDs-keyVersionNumber"])
@ -640,8 +640,8 @@ def update_dns_account_password(samdb, secrets_ldb, names):
ldb.FLAG_MOD_REPLACE, ldb.FLAG_MOD_REPLACE,
"secret") "secret")
msg["msDS-KeyVersionNumber"] = ldb.MessageElement(kvno, msg["msDS-KeyVersionNumber"] = ldb.MessageElement(kvno,
ldb.FLAG_MOD_REPLACE, ldb.FLAG_MOD_REPLACE,
"msDS-KeyVersionNumber") "msDS-KeyVersionNumber")
secrets_ldb.modify(msg) secrets_ldb.modify(msg)
@ -779,8 +779,8 @@ def print_provision_ranges(dic, limit_print, dest, samdb_path, invocationid):
if obj["num"] > limit_print: if obj["num"] > limit_print:
dt = _glue.nttime2string(_glue.unix2nttime(k*60)) dt = _glue.nttime2string(_glue.unix2nttime(k*60))
print("%s # of modification: %d \tmin: %d max: %d" % (dt , obj["num"], print("%s # of modification: %d \tmin: %d max: %d" % (dt , obj["num"],
obj["min"], obj["min"],
obj["max"])) obj["max"]))
if hash_ts[k]["num"] > 600: if hash_ts[k]["num"] > 600:
kept_record.append(k) kept_record.append(k)
@ -801,7 +801,7 @@ def print_provision_ranges(dic, limit_print, dest, samdb_path, invocationid):
obj = hash_ts[k] obj = hash_ts[k]
if obj.get("skipped") is None: if obj.get("skipped") is None:
ldif = "%slastProvisionUSN: %d-%d;%s\n" % (ldif, obj["min"], ldif = "%slastProvisionUSN: %d-%d;%s\n" % (ldif, obj["min"],
obj["max"], id) obj["max"], id)
if ldif != "": if ldif != "":
file = tempfile.mktemp(dir=dest, prefix="usnprov", suffix=".ldif") file = tempfile.mktemp(dir=dest, prefix="usnprov", suffix=".ldif")

View File

@ -61,7 +61,7 @@ def __call__(environ, start_response):
if name == "": if name == "":
if have_swat: if have_swat:
start_response('301 Redirect', start_response('301 Redirect',
[('Location', urljoin(application_uri(environ), 'swat')),]) [('Location', urljoin(application_uri(environ), 'swat')),])
return [] return []
else: else:
return render_placeholder(environ, start_response) return render_placeholder(environ, start_response)

View File

@ -27,10 +27,10 @@ def copyattrs(frompath, topath):
# Get the xattr attributes if any # Get the xattr attributes if any
try: try:
attribute = samba.xattr_native.wrap_getxattr(frompath, attribute = samba.xattr_native.wrap_getxattr(frompath,
xattr.XATTR_NTACL_NAME) xattr.XATTR_NTACL_NAME)
samba.xattr_native.wrap_setxattr(topath, samba.xattr_native.wrap_setxattr(topath,
xattr.XATTR_NTACL_NAME, xattr.XATTR_NTACL_NAME,
attribute) attribute)
except Exception: except Exception:
pass pass
# FIXME:Catch a specific exception # FIXME:Catch a specific exception

View File

@ -132,10 +132,10 @@ tasks = {
# We split out this so the isolated ad_dc tests do not wait for ad_dc_ntvfs tests (which are long) # We split out this so the isolated ad_dc tests do not wait for ad_dc_ntvfs tests (which are long)
"samba-fileserver" : [ ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"), "samba-fileserver" : [ ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"),
("configure", "./configure.developer --without-ad-dc --without-ldap --without-ads --without-json-audit --with-selftest-prefix=./bin/ab" + samba_configure_params, "text/plain"), ("configure", "./configure.developer --without-ad-dc --without-ldap --without-ads --without-json-audit --with-selftest-prefix=./bin/ab" + samba_configure_params, "text/plain"),
("make", "make -j", "text/plain"), ("make", "make -j", "text/plain"),
("test", "make test FAIL_IMMEDIATELY=1 TESTS='--include-env=fileserver'", "text/plain"), ("test", "make test FAIL_IMMEDIATELY=1 TESTS='--include-env=fileserver'", "text/plain"),
("check-clean-tree", "script/clean-source-tree.sh", "text/plain")], ("check-clean-tree", "script/clean-source-tree.sh", "text/plain")],
# We split out this so the isolated ad_dc tests do not wait for ad_dc_ntvfs tests (which are long) # We split out this so the isolated ad_dc tests do not wait for ad_dc_ntvfs tests (which are long)
"samba-ad-dc" : [ ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"), "samba-ad-dc" : [ ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"),
@ -152,10 +152,10 @@ tasks = {
# We split out this so the isolated ad_dc tests do not wait for ad_dc_ntvfs tests (which are long) # We split out this so the isolated ad_dc tests do not wait for ad_dc_ntvfs tests (which are long)
"samba-ad-dc-2" : [ ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"), "samba-ad-dc-2" : [ ("random-sleep", "script/random-sleep.sh 60 600", "text/plain"),
("configure", "./configure.developer --with-selftest-prefix=./bin/ab" + samba_configure_params, "text/plain"), ("configure", "./configure.developer --with-selftest-prefix=./bin/ab" + samba_configure_params, "text/plain"),
("make", "make -j", "text/plain"), ("make", "make -j", "text/plain"),
("test", "make test FAIL_IMMEDIATELY=1 TESTS='--include-env=chgdcpass --include-env=vampire_2000_dc --include-env=fl2000dc'", "text/plain"), ("test", "make test FAIL_IMMEDIATELY=1 TESTS='--include-env=chgdcpass --include-env=vampire_2000_dc --include-env=fl2000dc'", "text/plain"),
("check-clean-tree", "script/clean-source-tree.sh", "text/plain")], ("check-clean-tree", "script/clean-source-tree.sh", "text/plain")],
"samba-test-only" : [ ("configure", "./configure.developer --with-selftest-prefix=./bin/ab --abi-check-disable" + samba_configure_params, "text/plain"), "samba-test-only" : [ ("configure", "./configure.developer --with-selftest-prefix=./bin/ab --abi-check-disable" + samba_configure_params, "text/plain"),
("make", "make -j", "text/plain"), ("make", "make -j", "text/plain"),
@ -491,7 +491,7 @@ class buildlist(object):
rebase_remote, rebase_remote,
rebase_remote, rebase_branch rebase_remote, rebase_branch
), ),
"test/plain" ) ] "test/plain" ) ]
self.retry = builder('retry', retry_task, cp=False) self.retry = builder('retry', retry_task, cp=False)
self.need_retry = False self.need_retry = False
@ -656,7 +656,7 @@ def rebase_tree(rebase_url, rebase_branch = "master"):
dir=test_master, output=True) dir=test_master, output=True)
if diff == '': if diff == '':
do_print("No differences between HEAD and %s/%s - exiting" % do_print("No differences between HEAD and %s/%s - exiting" %
(rebase_remote, rebase_branch)) (rebase_remote, rebase_branch))
sys.exit(0) sys.exit(0)
run_cmd("git describe %s/%s" % run_cmd("git describe %s/%s" %
(rebase_remote, rebase_branch), (rebase_remote, rebase_branch),

View File

@ -17,7 +17,7 @@ parser.add_option("", "--autogen", help="run autogen before each build",action="
parser.add_option("", "--autogen-command", help="command to use for autogen (default ./autogen.sh)", parser.add_option("", "--autogen-command", help="command to use for autogen (default ./autogen.sh)",
type='str', default="./autogen.sh") type='str', default="./autogen.sh")
parser.add_option("", "--configure", help="run configure.developer before each build", parser.add_option("", "--configure", help="run configure.developer before each build",
action="store_true", default=False) action="store_true", default=False)
parser.add_option("", "--configure-command", help="the command for configure (default ./configure.developer)", parser.add_option("", "--configure-command", help="the command for configure (default ./configure.developer)",
type='str', default="./configure.developer") type='str', default="./configure.developer")
parser.add_option("", "--build-command", help="the command to build the tree (default 'make -j')", parser.add_option("", "--build-command", help="the command to build the tree (default 'make -j')",

View File

@ -36,7 +36,7 @@ parser.add_option("-f", "--file", dest="filename",
parser.add_option("-o", "--output", dest="output", parser.add_option("-o", "--output", dest="output",
help='output file', metavar="FILE") help='output file', metavar="FILE")
parser.add_option("--mode", type="choice", metavar="<FUNCTIONS|S3PROTO|LIBPROTO|PARAMDEFS|PARAMTABLE>", parser.add_option("--mode", type="choice", metavar="<FUNCTIONS|S3PROTO|LIBPROTO|PARAMDEFS|PARAMTABLE>",
choices=["FUNCTIONS", "S3PROTO", "LIBPROTO", "PARAMDEFS", "PARAMTABLE"], default="FUNCTIONS") choices=["FUNCTIONS", "S3PROTO", "LIBPROTO", "PARAMDEFS", "PARAMTABLE"], default="FUNCTIONS")
parser.add_option("--scope", metavar="<GLOBAL|LOCAL>", parser.add_option("--scope", metavar="<GLOBAL|LOCAL>",
choices = ["GLOBAL", "LOCAL"], default="GLOBAL") choices = ["GLOBAL", "LOCAL"], default="GLOBAL")

View File

@ -174,7 +174,7 @@ def parse_results(msg_ops, statistics, fh):
exitcode = 1 exitcode = 1
else: else:
raise AssertionError("Recognized but unhandled result %r" % raise AssertionError("Recognized but unhandled result %r" %
result) result)
elif command == "testsuite": elif command == "testsuite":
msg_ops.start_testsuite(arg.strip()) msg_ops.start_testsuite(arg.strip())
elif command == "progress": elif command == "progress":
@ -515,7 +515,7 @@ class PerfFilterOps(unittest.TestResult):
class PlainFormatter(TestsuiteEnabledTestResult): class PlainFormatter(TestsuiteEnabledTestResult):
def __init__(self, verbose, immediate, statistics, def __init__(self, verbose, immediate, statistics,
totaltests=None): totaltests=None):
super(PlainFormatter, self).__init__() super(PlainFormatter, self).__init__()
self.verbose = verbose self.verbose = verbose
self.immediate = immediate self.immediate = immediate

View File

@ -32,8 +32,8 @@ f = open(config_h, 'r')
try: try:
lines = f.readlines() lines = f.readlines()
config_hash = dict((x[0], ' '.join(x[1:])) config_hash = dict((x[0], ' '.join(x[1:]))
for x in map(lambda line: line.strip().split(' ')[1:], for x in map(lambda line: line.strip().split(' ')[1:],
filter(lambda line: (line[0:7] == '#define') and (len(line.split(' ')) > 2), lines))) filter(lambda line: (line[0:7] == '#define') and (len(line.split(' ')) > 2), lines)))
finally: finally:
f.close() f.close()

View File

@ -49,8 +49,8 @@ f = open(config_h, 'r')
try: try:
lines = f.readlines() lines = f.readlines()
config_hash = dict((x[0], ' '.join(x[1:])) config_hash = dict((x[0], ' '.join(x[1:]))
for x in map(lambda line: line.strip().split(' ')[1:], for x in map(lambda line: line.strip().split(' ')[1:],
filter(lambda line: (line[0:7] == '#define') and (len(line.split(' ')) > 2), lines))) filter(lambda line: (line[0:7] == '#define') and (len(line.split(' ')) > 2), lines)))
finally: finally:
f.close() f.close()
@ -68,20 +68,20 @@ plantestsuite("samba3.local_s3", "nt4_dc:local", [os.path.join(samba3srcdir, "sc
plantestsuite("samba3.blackbox.registry.upgrade", "nt4_dc:local", [os.path.join(samba3srcdir, "script/tests/test_registry_upgrade.sh"), net, dbwrap_tool]) plantestsuite("samba3.blackbox.registry.upgrade", "nt4_dc:local", [os.path.join(samba3srcdir, "script/tests/test_registry_upgrade.sh"), net, dbwrap_tool])
tests = ["FDPASS", "LOCK1", "LOCK2", "LOCK3", "LOCK4", "LOCK5", "LOCK6", "LOCK7", "LOCK9", tests = ["FDPASS", "LOCK1", "LOCK2", "LOCK3", "LOCK4", "LOCK5", "LOCK6", "LOCK7", "LOCK9",
"UNLINK", "BROWSE", "ATTR", "TRANS2", "TORTURE", "UNLINK", "BROWSE", "ATTR", "TRANS2", "TORTURE",
"OPLOCK1", "OPLOCK2", "OPLOCK4", "STREAMERROR", "OPLOCK1", "OPLOCK2", "OPLOCK4", "STREAMERROR",
"DIR", "DIR1", "DIR-CREATETIME", "TCON", "TCONDEV", "RW1", "RW2", "RW3", "LARGE_READX", "RW-SIGNING", "DIR", "DIR1", "DIR-CREATETIME", "TCON", "TCONDEV", "RW1", "RW2", "RW3", "LARGE_READX", "RW-SIGNING",
"OPEN", "XCOPY", "RENAME", "DELETE", "DELETE-LN", "WILDDELETE", "PROPERTIES", "W2K", "OPEN", "XCOPY", "RENAME", "DELETE", "DELETE-LN", "WILDDELETE", "PROPERTIES", "W2K",
"TCON2", "IOCTL", "CHKPATH", "FDSESS", "CHAIN1", "CHAIN2", "OWNER-RIGHTS", "TCON2", "IOCTL", "CHKPATH", "FDSESS", "CHAIN1", "CHAIN2", "OWNER-RIGHTS",
"CHAIN3", "PIDHIGH", "CLI_SPLICE", "CHAIN3", "PIDHIGH", "CLI_SPLICE",
"UID-REGRESSION-TEST", "SHORTNAME-TEST", "UID-REGRESSION-TEST", "SHORTNAME-TEST",
"CASE-INSENSITIVE-CREATE", "SMB2-BASIC", "NTTRANS-FSCTL", "SMB2-NEGPROT", "CASE-INSENSITIVE-CREATE", "SMB2-BASIC", "NTTRANS-FSCTL", "SMB2-NEGPROT",
"SMB2-SESSION-REAUTH", "SMB2-SESSION-RECONNECT", "SMB2-FTRUNCATE", "SMB2-SESSION-REAUTH", "SMB2-SESSION-RECONNECT", "SMB2-FTRUNCATE",
"SMB2-ANONYMOUS", "SMB2-DIR-FSYNC", "SMB2-ANONYMOUS", "SMB2-DIR-FSYNC",
"CLEANUP1", "CLEANUP1",
"CLEANUP2", "CLEANUP2",
"CLEANUP4", "CLEANUP4",
"BAD-NBT-SESSION"] "BAD-NBT-SESSION"]
for t in tests: for t in tests:
plantestsuite("samba3.smbtorture_s3.plain(fileserver).%s" % t, "fileserver", [os.path.join(samba3srcdir, "script/tests/test_smbtorture_s3.sh"), t, '//$SERVER_IP/tmp', '$USERNAME', '$PASSWORD', smbtorture3, "", "-l $LOCAL_PATH"]) plantestsuite("samba3.smbtorture_s3.plain(fileserver).%s" % t, "fileserver", [os.path.join(samba3srcdir, "script/tests/test_smbtorture_s3.sh"), t, '//$SERVER_IP/tmp', '$USERNAME', '$PASSWORD', smbtorture3, "", "-l $LOCAL_PATH"])
@ -131,7 +131,7 @@ for s in shares:
plansmbtorture4testsuite(t, "simpleserver", "//%s/%s %s" % ('$SERVER_IP', s, ' -U$USERNAME%$PASSWORD'), description=s) plansmbtorture4testsuite(t, "simpleserver", "//%s/%s %s" % ('$SERVER_IP', s, ' -U$USERNAME%$PASSWORD'), description=s)
posix_tests = ["POSIX", "POSIX-APPEND", "POSIX-SYMLINK-ACL", "POSIX-SYMLINK-EA", "POSIX-OFD-LOCK", posix_tests = ["POSIX", "POSIX-APPEND", "POSIX-SYMLINK-ACL", "POSIX-SYMLINK-EA", "POSIX-OFD-LOCK",
"POSIX-STREAM-DELETE", "WINDOWS-BAD-SYMLINK" ] "POSIX-STREAM-DELETE", "WINDOWS-BAD-SYMLINK" ]
for t in posix_tests: for t in posix_tests:
plantestsuite("samba3.smbtorture_s3.plain(nt4_dc).%s" % t, "nt4_dc", [os.path.join(samba3srcdir, "script/tests/test_smbtorture_s3.sh"), t, '//$SERVER_IP/posix_share', '$USERNAME', '$PASSWORD', smbtorture3, "", "-l $LOCAL_PATH"]) plantestsuite("samba3.smbtorture_s3.plain(nt4_dc).%s" % t, "nt4_dc", [os.path.join(samba3srcdir, "script/tests/test_smbtorture_s3.sh"), t, '//$SERVER_IP/posix_share', '$USERNAME', '$PASSWORD', smbtorture3, "", "-l $LOCAL_PATH"])
@ -226,19 +226,19 @@ t = "--krb5auth=$DOMAIN/$DC_USERNAME%$DC_PASSWORD"
plantestsuite("samba3.wbinfo_simple.(%s:local).%s" % (env, t), "%s:local" % env, [os.path.join(srcdir(), "nsswitch/tests/test_wbinfo_simple.sh"), t]) plantestsuite("samba3.wbinfo_simple.(%s:local).%s" % (env, t), "%s:local" % env, [os.path.join(srcdir(), "nsswitch/tests/test_wbinfo_simple.sh"), t])
plantestsuite("samba3.wbinfo_name_lookup", env, plantestsuite("samba3.wbinfo_name_lookup", env,
[ os.path.join(srcdir(), [ os.path.join(srcdir(),
"nsswitch/tests/test_wbinfo_name_lookup.sh"), "nsswitch/tests/test_wbinfo_name_lookup.sh"),
'$DOMAIN', '$REALM', '$DC_USERNAME' ]) '$DOMAIN', '$REALM', '$DC_USERNAME' ])
env = "ad_member:local" env = "ad_member:local"
plantestsuite("samba3.wbinfo_user_info", env, plantestsuite("samba3.wbinfo_user_info", env,
[ os.path.join(srcdir(), [ os.path.join(srcdir(),
"nsswitch/tests/test_wbinfo_user_info.sh"), "nsswitch/tests/test_wbinfo_user_info.sh"),
'$DOMAIN', '$REALM', '$DOMAIN', 'alice', 'alice', 'jane', 'jane.doe' ]) '$DOMAIN', '$REALM', '$DOMAIN', 'alice', 'alice', 'jane', 'jane.doe' ])
env = "fl2008r2dc:local" env = "fl2008r2dc:local"
plantestsuite("samba3.wbinfo_user_info", env, plantestsuite("samba3.wbinfo_user_info", env,
[ os.path.join(srcdir(), [ os.path.join(srcdir(),
"nsswitch/tests/test_wbinfo_user_info.sh"), "nsswitch/tests/test_wbinfo_user_info.sh"),
'$TRUST_DOMAIN', '$TRUST_REALM', '$DOMAIN', 'alice', 'alice', 'jane', 'jane.doe' ]) '$TRUST_DOMAIN', '$TRUST_REALM', '$DOMAIN', 'alice', 'alice', 'jane', 'jane.doe' ])
env = "ad_member" env = "ad_member"
@ -603,7 +603,7 @@ for s in signseal_options:
options = binding_string + " -U$USERNAME%$PASSWORD" options = binding_string + " -U$USERNAME%$PASSWORD"
plansmbtorture4testsuite(test, "nt4_dc", options, 'over ncacn_np with [%s%s%s] ' % (a, s, e)) plansmbtorture4testsuite(test, "nt4_dc", options, 'over ncacn_np with [%s%s%s] ' % (a, s, e))
plantestsuite("samba3.blackbox.rpcclient over ncacn_np with [%s%s%s] " % (a, s, e), "nt4_dc:local", [os.path.join(samba3srcdir, "script/tests/test_rpcclient.sh"), plantestsuite("samba3.blackbox.rpcclient over ncacn_np with [%s%s%s] " % (a, s, e), "nt4_dc:local", [os.path.join(samba3srcdir, "script/tests/test_rpcclient.sh"),
"none", options, configuration]) "none", options, configuration])
# We should try more combinations in future, but this is all # We should try more combinations in future, but this is all
# the pre-calculated credentials cache supports at the moment # the pre-calculated credentials cache supports at the moment
@ -628,7 +628,7 @@ for s in signseal_options:
"$PREFIX/ktest/krb5_ccache-3", binding_string, "-k", configuration]) "$PREFIX/ktest/krb5_ccache-3", binding_string, "-k", configuration])
plantestsuite("samba3.blackbox.rpcclient_samlogon", "ad_member:local", [os.path.join(samba3srcdir, "script/tests/test_rpcclient_samlogon.sh"), plantestsuite("samba3.blackbox.rpcclient_samlogon", "ad_member:local", [os.path.join(samba3srcdir, "script/tests/test_rpcclient_samlogon.sh"),
"$DC_USERNAME", "$DC_PASSWORD", "ncacn_np:$DC_SERVER", configuration]) "$DC_USERNAME", "$DC_PASSWORD", "ncacn_np:$DC_SERVER", configuration])
plantestsuite("samba3.blackbox.sharesec", "simpleserver:local", plantestsuite("samba3.blackbox.sharesec", "simpleserver:local",
[os.path.join(samba3srcdir, "script/tests/test_sharesec.sh"), [os.path.join(samba3srcdir, "script/tests/test_sharesec.sh"),
configuration, os.path.join(bindir(), "sharesec"), "tmp"]) configuration, os.path.join(bindir(), "sharesec"), "tmp"])

View File

@ -78,38 +78,38 @@ def parseCommandLine():
parser.set_defaults(config_file="/etc/samba/smb.conf") parser.set_defaults(config_file="/etc/samba/smb.conf")
parser.add_option("--client-username", dest="client_username",\ parser.add_option("--client-username", dest="client_username",\
help="User name for the client. [default: foo]") help="User name for the client. [default: foo]")
parser.add_option("--client-password", dest="client_password",\ parser.add_option("--client-password", dest="client_password",\
help="Password the client will send. [default: secret]") help="Password the client will send. [default: secret]")
parser.add_option("--client-domain", dest="client_domain",\ parser.add_option("--client-domain", dest="client_domain",\
help="Domain the client authenticates for. [default: FOO]") help="Domain the client authenticates for. [default: FOO]")
parser.add_option("--client-helper", dest="client_helper",\ parser.add_option("--client-helper", dest="client_helper",\
help="Helper mode for the ntlm_auth client. [default: ntlmssp-client-1]") help="Helper mode for the ntlm_auth client. [default: ntlmssp-client-1]")
parser.add_option("--client-use-cached-creds", dest="client_use_cached_creds",\ parser.add_option("--client-use-cached-creds", dest="client_use_cached_creds",\
help="Use winbindd credentials cache (rather than default username/pw)", action="store_true") help="Use winbindd credentials cache (rather than default username/pw)", action="store_true")
parser.add_option("--target-hostname", dest="target_hostname",\ parser.add_option("--target-hostname", dest="target_hostname",\
help="Target hostname for kerberos") help="Target hostname for kerberos")
parser.add_option("--target-service", dest="target_service",\ parser.add_option("--target-service", dest="target_service",\
help="Target service for kerberos") help="Target service for kerberos")
parser.add_option("--server-username", dest="server_username",\ parser.add_option("--server-username", dest="server_username",\
help="User name server uses for local auth. [default: foo]") help="User name server uses for local auth. [default: foo]")
parser.add_option("--server-password", dest="server_password",\ parser.add_option("--server-password", dest="server_password",\
help="Password server uses for local auth. [default: secret]") help="Password server uses for local auth. [default: secret]")
parser.add_option("--server-domain", dest="server_domain",\ parser.add_option("--server-domain", dest="server_domain",\
help="Domain server uses for local auth. [default: FOO]") help="Domain server uses for local auth. [default: FOO]")
parser.add_option("--server-helper", dest="server_helper",\ parser.add_option("--server-helper", dest="server_helper",\
help="Helper mode for the ntlm_auth server. [default: squid-2.5-server]") help="Helper mode for the ntlm_auth server. [default: squid-2.5-server]")
parser.add_option("--server-use-winbindd", dest="server_use_winbindd",\ parser.add_option("--server-use-winbindd", dest="server_use_winbindd",\
help="Use winbindd to check the password (rather than default username/pw)", action="store_true") help="Use winbindd to check the password (rather than default username/pw)", action="store_true")
parser.add_option("--require-membership-of", dest="sid",\ parser.add_option("--require-membership-of", dest="sid",\
help="Require that the user is a member of this group to authenticate.") help="Require that the user is a member of this group to authenticate.")
parser.add_option("-s", "--configfile", dest="config_file",\ parser.add_option("-s", "--configfile", dest="config_file",\
help="Path to smb.conf file. [default:/etc/samba/smb.conf") help="Path to smb.conf file. [default:/etc/samba/smb.conf")
(opts, args) = parser.parse_args() (opts, args) = parser.parse_args()
if len(args) != 1: if len(args) != 1:

View File

@ -137,9 +137,9 @@ class AclAddTests(AclTests):
# add admins to the Domain Admins group # add admins to the Domain Admins group
self.ldb_admin.add_remove_group_members("Domain Admins", [self.usr_admin_owner], self.ldb_admin.add_remove_group_members("Domain Admins", [self.usr_admin_owner],
add_members_operation=True) add_members_operation=True)
self.ldb_admin.add_remove_group_members("Domain Admins", [self.usr_admin_not_owner], self.ldb_admin.add_remove_group_members("Domain Admins", [self.usr_admin_not_owner],
add_members_operation=True) add_members_operation=True)
self.ldb_owner = self.get_ldb_connection(self.usr_admin_owner, self.user_pass) self.ldb_owner = self.get_ldb_connection(self.usr_admin_owner, self.user_pass)
self.ldb_notowner = self.get_ldb_connection(self.usr_admin_not_owner, self.user_pass) self.ldb_notowner = self.get_ldb_connection(self.usr_admin_not_owner, self.user_pass)
@ -165,7 +165,7 @@ class AclAddTests(AclTests):
# Make sure top OU is deleted (and so everything under it) # Make sure top OU is deleted (and so everything under it)
def assert_top_ou_deleted(self): def assert_top_ou_deleted(self):
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s,%s)" % ( expression="(distinguishedName=%s,%s)" % (
"OU=test_add_ou1", self.base_dn)) "OU=test_add_ou1", self.base_dn))
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
@ -233,14 +233,14 @@ class AclAddTests(AclTests):
self.fail() self.fail()
# Make sure we HAVE created the one of two objects -- user # Make sure we HAVE created the one of two objects -- user
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s,%s)" % expression="(distinguishedName=%s,%s)" %
("CN=test_add_user1,OU=test_add_ou2,OU=test_add_ou1", ("CN=test_add_user1,OU=test_add_ou2,OU=test_add_ou1",
self.base_dn)) self.base_dn))
self.assertNotEqual(len(res), 0) self.assertNotEqual(len(res), 0)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s,%s)" % expression="(distinguishedName=%s,%s)" %
("CN=test_add_group1,OU=test_add_ou2,OU=test_add_ou1", ("CN=test_add_group1,OU=test_add_ou2,OU=test_add_ou1",
self.base_dn) ) self.base_dn) )
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
def test_add_u4(self): def test_add_u4(self):
@ -255,7 +255,7 @@ class AclAddTests(AclTests):
res = self.ldb_admin.search(self.base_dn, expression="(distinguishedName=%s,%s)" % ("CN=test_add_user1,OU=test_add_ou2,OU=test_add_ou1", self.base_dn)) res = self.ldb_admin.search(self.base_dn, expression="(distinguishedName=%s,%s)" % ("CN=test_add_user1,OU=test_add_ou2,OU=test_add_ou1", self.base_dn))
self.assertTrue(len(res) > 0) self.assertTrue(len(res) > 0)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s,%s)" % ("CN=test_add_group1,OU=test_add_ou2,OU=test_add_ou1", self.base_dn)) expression="(distinguishedName=%s,%s)" % ("CN=test_add_group1,OU=test_add_ou2,OU=test_add_ou1", self.base_dn))
self.assertTrue(len(res) > 0) self.assertTrue(len(res) > 0)
def test_add_anonymous(self): def test_add_anonymous(self):
@ -319,7 +319,7 @@ replace: displayName
displayName: test_changed""" displayName: test_changed"""
self.ldb_user.modify_ldif(ldif) self.ldb_user.modify_ldif(ldif)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % self.get_user_dn("test_modify_user1")) expression="(distinguishedName=%s)" % self.get_user_dn("test_modify_user1"))
self.assertEqual(res[0]["displayName"][0], "test_changed") self.assertEqual(res[0]["displayName"][0], "test_changed")
# Second test object -- Group # Second test object -- Group
print("Testing modify on Group object") print("Testing modify on Group object")
@ -364,8 +364,8 @@ replace: displayName
displayName: test_changed""" displayName: test_changed"""
self.ldb_user.modify_ldif(ldif) self.ldb_user.modify_ldif(ldif)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % expression="(distinguishedName=%s)" %
self.get_user_dn("test_modify_user1")) self.get_user_dn("test_modify_user1"))
self.assertEqual(res[0]["displayName"][0], "test_changed") self.assertEqual(res[0]["displayName"][0], "test_changed")
# Modify on attribute you do not have rights for granted # Modify on attribute you do not have rights for granted
ldif = """ ldif = """
@ -393,8 +393,8 @@ replace: displayName
displayName: test_changed""" displayName: test_changed"""
self.ldb_user.modify_ldif(ldif) self.ldb_user.modify_ldif(ldif)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % expression="(distinguishedName=%s)" %
str("CN=test_modify_group1,CN=Users," + self.base_dn)) str("CN=test_modify_group1,CN=Users," + self.base_dn))
self.assertEqual(res[0]["displayName"][0], "test_changed") self.assertEqual(res[0]["displayName"][0], "test_changed")
# Modify on attribute you do not have rights for granted # Modify on attribute you do not have rights for granted
ldif = """ ldif = """
@ -437,8 +437,8 @@ replace: displayName
displayName: test_changed""" displayName: test_changed"""
self.ldb_user.modify_ldif(ldif) self.ldb_user.modify_ldif(ldif)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % str("OU=test_modify_ou1," expression="(distinguishedName=%s)" % str("OU=test_modify_ou1,"
+ self.base_dn)) + self.base_dn))
self.assertEqual(res[0]["displayName"][0], "test_changed") self.assertEqual(res[0]["displayName"][0], "test_changed")
# Modify on attribute you do not have rights for granted # Modify on attribute you do not have rights for granted
ldif = """ ldif = """
@ -561,7 +561,7 @@ Member: """ + self.get_user_dn(self.user_with_sm)
self.sd_utils.dacl_add_ace("CN=test_modify_group2,CN=Users," + self.base_dn, mod) self.sd_utils.dacl_add_ace("CN=test_modify_group2,CN=Users," + self.base_dn, mod)
self.ldb_user2.modify_ldif(ldif) self.ldb_user2.modify_ldif(ldif)
res = self.ldb_admin.search( self.base_dn, expression="(distinguishedName=%s)" \ res = self.ldb_admin.search( self.base_dn, expression="(distinguishedName=%s)" \
% ("CN=test_modify_group2,CN=Users," + self.base_dn), attrs=["Member"]) % ("CN=test_modify_group2,CN=Users," + self.base_dn), attrs=["Member"])
self.assertEqual(res[0]["Member"][0], self.get_user_dn(self.user_with_sm)) self.assertEqual(res[0]["Member"][0], self.get_user_dn(self.user_with_sm))
#but not other users #but not other users
ldif = """ ldif = """
@ -611,7 +611,7 @@ add: Member
Member: """ + self.get_user_dn(self.user_with_wp) Member: """ + self.get_user_dn(self.user_with_wp)
self.ldb_user.modify_ldif(ldif) self.ldb_user.modify_ldif(ldif)
res = self.ldb_admin.search( self.base_dn, expression="(distinguishedName=%s)" \ res = self.ldb_admin.search( self.base_dn, expression="(distinguishedName=%s)" \
% ("CN=test_modify_group2,CN=Users," + self.base_dn), attrs=["Member"]) % ("CN=test_modify_group2,CN=Users," + self.base_dn), attrs=["Member"])
self.assertEqual(res[0]["Member"][0], self.get_user_dn(self.user_with_wp)) self.assertEqual(res[0]["Member"][0], self.get_user_dn(self.user_with_wp))
ldif = """ ldif = """
dn: CN=test_modify_group2,CN=Users,""" + self.base_dn + """ dn: CN=test_modify_group2,CN=Users,""" + self.base_dn + """
@ -625,7 +625,7 @@ add: Member
Member: CN=test_modify_user2,CN=Users,""" + self.base_dn Member: CN=test_modify_user2,CN=Users,""" + self.base_dn
self.ldb_user.modify_ldif(ldif) self.ldb_user.modify_ldif(ldif)
res = self.ldb_admin.search( self.base_dn, expression="(distinguishedName=%s)" \ res = self.ldb_admin.search( self.base_dn, expression="(distinguishedName=%s)" \
% ("CN=test_modify_group2,CN=Users," + self.base_dn), attrs=["Member"]) % ("CN=test_modify_group2,CN=Users," + self.base_dn), attrs=["Member"])
self.assertEqual(res[0]["Member"][0], "CN=test_modify_user2,CN=Users," + self.base_dn) self.assertEqual(res[0]["Member"][0], "CN=test_modify_user2,CN=Users," + self.base_dn)
def test_modify_anonymous(self): def test_modify_anonymous(self):
@ -680,7 +680,7 @@ class AclSearchTests(AclTests):
def create_clean_ou(self, object_dn): def create_clean_ou(self, object_dn):
""" Base repeating setup for unittests to follow """ """ Base repeating setup for unittests to follow """
res = self.ldb_admin.search(base=self.base_dn, scope=SCOPE_SUBTREE, \ res = self.ldb_admin.search(base=self.base_dn, scope=SCOPE_SUBTREE, \
expression="distinguishedName=%s" % object_dn) expression="distinguishedName=%s" % object_dn)
# Make sure top testing OU has been deleted before starting the test # Make sure top testing OU has been deleted before starting the test
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
self.ldb_admin.create_ou(object_dn) self.ldb_admin.create_ou(object_dn)
@ -1119,7 +1119,7 @@ class AclDeleteTests(AclTests):
# Try to delete User object # Try to delete User object
self.ldb_user.delete(user_dn) self.ldb_user.delete(user_dn)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % user_dn) expression="(distinguishedName=%s)" % user_dn)
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
def test_delete_u3(self): def test_delete_u3(self):
@ -1132,7 +1132,7 @@ class AclDeleteTests(AclTests):
# Try to delete User object # Try to delete User object
self.ldb_user.delete(user_dn) self.ldb_user.delete(user_dn)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % user_dn) expression="(distinguishedName=%s)" % user_dn)
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
def test_delete_anonymous(self): def test_delete_anonymous(self):
@ -1215,10 +1215,10 @@ class AclRenameTests(AclTests):
# Rename 'User object' having WP to AU # Rename 'User object' having WP to AU
self.ldb_user.rename(user_dn, rename_user_dn) self.ldb_user.rename(user_dn, rename_user_dn)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % user_dn) expression="(distinguishedName=%s)" % user_dn)
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % rename_user_dn) expression="(distinguishedName=%s)" % rename_user_dn)
self.assertNotEqual(len(res), 0) self.assertNotEqual(len(res), 0)
def test_rename_u3(self): def test_rename_u3(self):
@ -1235,10 +1235,10 @@ class AclRenameTests(AclTests):
# Rename 'User object' having WP to AU # Rename 'User object' having WP to AU
self.ldb_user.rename(user_dn, rename_user_dn) self.ldb_user.rename(user_dn, rename_user_dn)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % user_dn) expression="(distinguishedName=%s)" % user_dn)
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % rename_user_dn) expression="(distinguishedName=%s)" % rename_user_dn)
self.assertNotEqual(len(res), 0) self.assertNotEqual(len(res), 0)
def test_rename_u4(self): def test_rename_u4(self):
@ -1258,10 +1258,10 @@ class AclRenameTests(AclTests):
# Rename 'User object' having SD and CC to AU # Rename 'User object' having SD and CC to AU
self.ldb_user.rename(user_dn, rename_user_dn) self.ldb_user.rename(user_dn, rename_user_dn)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % user_dn) expression="(distinguishedName=%s)" % user_dn)
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % rename_user_dn) expression="(distinguishedName=%s)" % rename_user_dn)
self.assertNotEqual(len(res), 0) self.assertNotEqual(len(res), 0)
def test_rename_u5(self): def test_rename_u5(self):
@ -1282,10 +1282,10 @@ class AclRenameTests(AclTests):
# Rename 'User object' having SD and CC to AU # Rename 'User object' having SD and CC to AU
self.ldb_user.rename(user_dn, rename_user_dn) self.ldb_user.rename(user_dn, rename_user_dn)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % user_dn) expression="(distinguishedName=%s)" % user_dn)
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % rename_user_dn) expression="(distinguishedName=%s)" % rename_user_dn)
self.assertNotEqual(len(res), 0) self.assertNotEqual(len(res), 0)
def test_rename_u6(self): def test_rename_u6(self):
@ -1308,10 +1308,10 @@ class AclRenameTests(AclTests):
# Rename 'User object' having SD and CC to AU # Rename 'User object' having SD and CC to AU
self.ldb_user.rename(user_dn, rename_user_dn) self.ldb_user.rename(user_dn, rename_user_dn)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % user_dn) expression="(distinguishedName=%s)" % user_dn)
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % rename_user_dn) expression="(distinguishedName=%s)" % rename_user_dn)
self.assertNotEqual(len(res), 0) self.assertNotEqual(len(res), 0)
def test_rename_u7(self): def test_rename_u7(self):
@ -1333,10 +1333,10 @@ class AclRenameTests(AclTests):
# Rename 'User object' having SD and CC to AU # Rename 'User object' having SD and CC to AU
self.ldb_user.rename(user_dn, rename_user_dn) self.ldb_user.rename(user_dn, rename_user_dn)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % user_dn) expression="(distinguishedName=%s)" % user_dn)
self.assertEqual(len(res), 0) self.assertEqual(len(res), 0)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(distinguishedName=%s)" % rename_user_dn) expression="(distinguishedName=%s)" % rename_user_dn)
self.assertNotEqual(len(res), 0) self.assertNotEqual(len(res), 0)
def test_rename_u8(self): def test_rename_u8(self):
@ -1792,7 +1792,7 @@ class AclUndeleteTests(AclTests):
self.ldb_admin.newuser(self.regular_user, self.user_pass) self.ldb_admin.newuser(self.regular_user, self.user_pass)
self.ldb_admin.add_remove_group_members("Domain Admins", [self.regular_user], self.ldb_admin.add_remove_group_members("Domain Admins", [self.regular_user],
add_members_operation=True) add_members_operation=True)
self.ldb_user = self.get_ldb_connection(self.regular_user, self.user_pass) self.ldb_user = self.get_ldb_connection(self.regular_user, self.user_pass)
self.sid = self.sd_utils.get_object_sid(self.get_user_dn(self.regular_user)) self.sid = self.sd_utils.get_object_sid(self.get_user_dn(self.regular_user))
@ -1822,7 +1822,7 @@ class AclUndeleteTests(AclTests):
guid = res[0]["objectGUID"][0] guid = res[0]["objectGUID"][0]
self.ldb_admin.delete(self.get_user_dn(new_user)) self.ldb_admin.delete(self.get_user_dn(new_user))
res = self.ldb_admin.search(base="<GUID=%s>" % self.GUID_string(guid), res = self.ldb_admin.search(base="<GUID=%s>" % self.GUID_string(guid),
scope=SCOPE_BASE, controls=["show_deleted:1"]) scope=SCOPE_BASE, controls=["show_deleted:1"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
return str(res[0].dn) return str(res[0].dn)
@ -1975,8 +1975,8 @@ class AclSPNTests(AclTests):
ctx.managedby = admin_dn ctx.managedby = admin_dn
ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT | ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION | samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT) samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
ctx.secure_channel_type = misc.SEC_CHAN_RODC ctx.secure_channel_type = misc.SEC_CHAN_RODC

View File

@ -73,7 +73,7 @@ class UserTests(samba.tests.TestCase):
for x in range(1, 1000): for x in range(1, 1000):
samdb = SamDB(host, credentials=creds, samdb = SamDB(host, credentials=creds,
session_info=system_session(self.lp), lp=self.lp) session_info=system_session(self.lp), lp=self.lp)
samdb.search(base=samdb.domain_dn(), samdb.search(base=samdb.domain_dn(),
scope=SCOPE_BASE, attrs=["*"]) scope=SCOPE_BASE, attrs=["*"])

View File

@ -91,12 +91,12 @@ class BasicDeleteTests(BaseDeleteTests):
print("Checking for preserved attributes list") print("Checking for preserved attributes list")
preserved_list = ["nTSecurityDescriptor", "attributeID", "attributeSyntax", "dNReferenceUpdate", "dNSHostName", preserved_list = ["nTSecurityDescriptor", "attributeID", "attributeSyntax", "dNReferenceUpdate", "dNSHostName",
"flatName", "governsID", "groupType", "instanceType", "lDAPDisplayName", "legacyExchangeDN", "flatName", "governsID", "groupType", "instanceType", "lDAPDisplayName", "legacyExchangeDN",
"isDeleted", "isRecycled", "lastKnownParent", "msDS-LastKnownRDN", "mS-DS-CreatorSID", "isDeleted", "isRecycled", "lastKnownParent", "msDS-LastKnownRDN", "mS-DS-CreatorSID",
"mSMQOwnerID", "nCName", "objectClass", "distinguishedName", "objectGUID", "objectSid", "mSMQOwnerID", "nCName", "objectClass", "distinguishedName", "objectGUID", "objectSid",
"oMSyntax", "proxiedObjectName", "name", "replPropertyMetaData", "sAMAccountName", "oMSyntax", "proxiedObjectName", "name", "replPropertyMetaData", "sAMAccountName",
"securityIdentifier", "sIDHistory", "subClassOf", "systemFlags", "trustPartner", "trustDirection", "securityIdentifier", "sIDHistory", "subClassOf", "systemFlags", "trustPartner", "trustDirection",
"trustType", "trustAttributes", "userAccountControl", "uSNChanged", "uSNCreated", "whenCreated"] "trustType", "trustAttributes", "userAccountControl", "uSNChanged", "uSNCreated", "whenCreated"]
for a in liveObj: for a in liveObj:
if a in preserved_list: if a in preserved_list:
@ -153,21 +153,21 @@ class BasicDeleteTests(BaseDeleteTests):
try: try:
res = self.ldb.search("cn=ldaptestcontainer," + self.base_dn, res = self.ldb.search("cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, attrs=[]) scope=SCOPE_BASE, attrs=[])
self.fail() self.fail()
except LdbError as e2: except LdbError as e2:
(num, _) = e2.args (num, _) = e2.args
self.assertEquals(num, ERR_NO_SUCH_OBJECT) self.assertEquals(num, ERR_NO_SUCH_OBJECT)
try: try:
res = self.ldb.search("cn=entry1,cn=ldaptestcontainer," + self.base_dn, res = self.ldb.search("cn=entry1,cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, attrs=[]) scope=SCOPE_BASE, attrs=[])
self.fail() self.fail()
except LdbError as e3: except LdbError as e3:
(num, _) = e3.args (num, _) = e3.args
self.assertEquals(num, ERR_NO_SUCH_OBJECT) self.assertEquals(num, ERR_NO_SUCH_OBJECT)
try: try:
res = self.ldb.search("cn=entry2,cn=ldaptestcontainer," + self.base_dn, res = self.ldb.search("cn=entry2,cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, attrs=[]) scope=SCOPE_BASE, attrs=[])
self.fail() self.fail()
except LdbError as e4: except LdbError as e4:
(num, _) = e4.args (num, _) = e4.args
@ -180,7 +180,7 @@ class BasicDeleteTests(BaseDeleteTests):
# Performs some protected object delete testing # Performs some protected object delete testing
res = self.ldb.search(base="", expression="", scope=SCOPE_BASE, res = self.ldb.search(base="", expression="", scope=SCOPE_BASE,
attrs=["dsServiceName", "dNSHostName"]) attrs=["dsServiceName", "dNSHostName"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
# Delete failing since DC's nTDSDSA object is protected # Delete failing since DC's nTDSDSA object is protected
@ -192,7 +192,7 @@ class BasicDeleteTests(BaseDeleteTests):
self.assertEquals(num, ERR_UNWILLING_TO_PERFORM) self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
res = self.ldb.search(self.base_dn, attrs=["rIDSetReferences"], res = self.ldb.search(self.base_dn, attrs=["rIDSetReferences"],
expression="(&(objectClass=computer)(dNSHostName=" + res[0]["dNSHostName"][0] + "))") expression="(&(objectClass=computer)(dNSHostName=" + res[0]["dNSHostName"][0] + "))")
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
# Deletes failing since DC's rIDSet object is protected # Deletes failing since DC's rIDSet object is protected
@ -238,7 +238,7 @@ class BasicDeleteTests(BaseDeleteTests):
self.assertEquals(num, ERR_NOT_ALLOWED_ON_NON_LEAF) self.assertEquals(num, ERR_NOT_ALLOWED_ON_NON_LEAF)
res = self.ldb.search("cn=Partitions," + self.configuration_dn, attrs=[], res = self.ldb.search("cn=Partitions," + self.configuration_dn, attrs=[],
expression="(nCName=%s)" % self.base_dn) expression="(nCName=%s)" % self.base_dn)
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
try: try:

View File

@ -126,7 +126,7 @@ class SimpleDirsyncTests(DirsyncBaseTests):
# add admins to the Domain Admins group # add admins to the Domain Admins group
self.ldb_admin.add_remove_group_members("Domain Admins", [self.admin_user], self.ldb_admin.add_remove_group_members("Domain Admins", [self.admin_user],
add_members_operation=True) add_members_operation=True)
def tearDown(self): def tearDown(self):
super(SimpleDirsyncTests, self).tearDown() super(SimpleDirsyncTests, self).tearDown()
@ -151,8 +151,8 @@ class SimpleDirsyncTests(DirsyncBaseTests):
res = self.ldb_dirsync.search(self.base_dn, expression="samaccountname=*", controls=["dirsync:1:0:1"]) res = self.ldb_dirsync.search(self.base_dn, expression="samaccountname=*", controls=["dirsync:1:0:1"])
try: try:
self.ldb_simple.search(self.base_dn, self.ldb_simple.search(self.base_dn,
expression="samaccountname=*", expression="samaccountname=*",
controls=["dirsync:1:0:1"]) controls=["dirsync:1:0:1"])
except LdbError as l: except LdbError as l:
self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1) self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1)
@ -176,48 +176,48 @@ class SimpleDirsyncTests(DirsyncBaseTests):
self.ldb_dirsync = self.get_ldb_connection(self.dirsync_user, self.user_pass) self.ldb_dirsync = self.get_ldb_connection(self.dirsync_user, self.user_pass)
try: try:
self.ldb_simple.search(self.base_dn, self.ldb_simple.search(self.base_dn,
expression="samaccountname=*", expression="samaccountname=*",
controls=["dirsync:1:0:1"]) controls=["dirsync:1:0:1"])
except LdbError as l: except LdbError as l:
print(l) print(l)
self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1) self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1)
try: try:
self.ldb_simple.search("CN=Users,%s" % self.base_dn, self.ldb_simple.search("CN=Users,%s" % self.base_dn,
expression="samaccountname=*", expression="samaccountname=*",
controls=["dirsync:1:0:1"]) controls=["dirsync:1:0:1"])
except LdbError as l: except LdbError as l:
print(l) print(l)
self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1) self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1)
try: try:
self.ldb_simple.search("CN=Users,%s" % self.base_dn, self.ldb_simple.search("CN=Users,%s" % self.base_dn,
expression="samaccountname=*", expression="samaccountname=*",
controls=["dirsync:1:1:1"]) controls=["dirsync:1:1:1"])
except LdbError as l: except LdbError as l:
print(l) print(l)
self.assertTrue(str(l).find("LDAP_UNWILLING_TO_PERFORM") != -1) self.assertTrue(str(l).find("LDAP_UNWILLING_TO_PERFORM") != -1)
try: try:
self.ldb_dirsync.search("CN=Users,%s" % self.base_dn, self.ldb_dirsync.search("CN=Users,%s" % self.base_dn,
expression="samaccountname=*", expression="samaccountname=*",
controls=["dirsync:1:0:1"]) controls=["dirsync:1:0:1"])
except LdbError as l: except LdbError as l:
print(l) print(l)
self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1) self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1)
try: try:
self.ldb_admin.search("CN=Users,%s" % self.base_dn, self.ldb_admin.search("CN=Users,%s" % self.base_dn,
expression="samaccountname=*", expression="samaccountname=*",
controls=["dirsync:1:0:1"]) controls=["dirsync:1:0:1"])
except LdbError as l: except LdbError as l:
print(l) print(l)
self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1) self.assertTrue(str(l).find("LDAP_INSUFFICIENT_ACCESS_RIGHTS") != -1)
try: try:
self.ldb_admin.search("CN=Users,%s" % self.base_dn, self.ldb_admin.search("CN=Users,%s" % self.base_dn,
expression="samaccountname=*", expression="samaccountname=*",
controls=["dirsync:1:1:1"]) controls=["dirsync:1:1:1"])
except LdbError as l: except LdbError as l:
print(l) print(l)
self.assertTrue(str(l).find("LDAP_UNWILLING_TO_PERFORM") != -1) self.assertTrue(str(l).find("LDAP_UNWILLING_TO_PERFORM") != -1)
@ -278,8 +278,8 @@ class SimpleDirsyncTests(DirsyncBaseTests):
controls=["dirsync:1:0:1"]) controls=["dirsync:1:0:1"])
count = len(res.msgs[0]) count = len(res.msgs[0])
res2 = self.ldb_admin.search(self.base_dn, res2 = self.ldb_admin.search(self.base_dn,
expression="samaccountname=Administrator", expression="samaccountname=Administrator",
controls=["dirsync:1:0:1"]) controls=["dirsync:1:0:1"])
count2 = len(res2.msgs[0]) count2 = len(res2.msgs[0])
self.assertEqual(count, count2) self.assertEqual(count, count2)
@ -463,8 +463,8 @@ class SimpleDirsyncTests(DirsyncBaseTests):
# Let's search for members # Let's search for members
self.ldb_simple = self.get_ldb_connection(self.simple_user, self.user_pass) self.ldb_simple = self.get_ldb_connection(self.simple_user, self.user_pass)
res = self.ldb_simple.search(self.base_dn, res = self.ldb_simple.search(self.base_dn,
expression="(name=Administrators)", expression="(name=Administrators)",
controls=["dirsync:1:1:1"]) controls=["dirsync:1:1:1"])
self.assertTrue(len(res[0].get("member")) > 0) self.assertTrue(len(res[0].get("member")) > 0)
size = len(res[0].get("member")) size = len(res[0].get("member"))
@ -475,11 +475,11 @@ class SimpleDirsyncTests(DirsyncBaseTests):
ctl[3] = "10000" ctl[3] = "10000"
control1 = str(":".join(ctl)) control1 = str(":".join(ctl))
self.ldb_admin.add_remove_group_members("Administrators", [self.simple_user], self.ldb_admin.add_remove_group_members("Administrators", [self.simple_user],
add_members_operation=True) add_members_operation=True)
res = self.ldb_simple.search(self.base_dn, res = self.ldb_simple.search(self.base_dn,
expression="(name=Administrators)", expression="(name=Administrators)",
controls=[control1]) controls=[control1])
self.assertEqual(len(res[0].get("member")), size + 1) self.assertEqual(len(res[0].get("member")), size + 1)
ctl = str(res.controls[0]).split(":") ctl = str(res.controls[0]).split(":")
@ -490,17 +490,17 @@ class SimpleDirsyncTests(DirsyncBaseTests):
# remove the user from the group # remove the user from the group
self.ldb_admin.add_remove_group_members("Administrators", [self.simple_user], self.ldb_admin.add_remove_group_members("Administrators", [self.simple_user],
add_members_operation=False) add_members_operation=False)
res = self.ldb_simple.search(self.base_dn, res = self.ldb_simple.search(self.base_dn,
expression="(name=Administrators)", expression="(name=Administrators)",
controls=[control1]) controls=[control1])
self.assertEqual(len(res[0].get("member")), size ) self.assertEqual(len(res[0].get("member")), size )
self.ldb_admin.newgroup("testgroup") self.ldb_admin.newgroup("testgroup")
self.ldb_admin.add_remove_group_members("testgroup", [self.simple_user], self.ldb_admin.add_remove_group_members("testgroup", [self.simple_user],
add_members_operation=True) add_members_operation=True)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(name=testgroup)", expression="(name=testgroup)",
@ -530,7 +530,7 @@ class SimpleDirsyncTests(DirsyncBaseTests):
control1 = str(":".join(ctl)) control1 = str(":".join(ctl))
self.ldb_admin.add_remove_group_members("testgroup", [self.simple_user], self.ldb_admin.add_remove_group_members("testgroup", [self.simple_user],
add_members_operation=False) add_members_operation=False)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(name=testgroup)", expression="(name=testgroup)",
@ -608,9 +608,9 @@ class ExtendedDirsyncTests(SimpleDirsyncTests):
ctl[3] = "10000" ctl[3] = "10000"
control1 = str(":".join(ctl)) control1 = str(":".join(ctl))
self.ldb_admin.add_remove_group_members("Administrators", [self.simple_user], self.ldb_admin.add_remove_group_members("Administrators", [self.simple_user],
add_members_operation=True) add_members_operation=True)
self.ldb_admin.add_remove_group_members("Administrators", [self.dirsync_user], self.ldb_admin.add_remove_group_members("Administrators", [self.dirsync_user],
add_members_operation=True) add_members_operation=True)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
@ -626,7 +626,7 @@ class ExtendedDirsyncTests(SimpleDirsyncTests):
# remove the user from the group # remove the user from the group
self.ldb_admin.add_remove_group_members("Administrators", [self.simple_user], self.ldb_admin.add_remove_group_members("Administrators", [self.simple_user],
add_members_operation=False) add_members_operation=False)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(name=Administrators)", expression="(name=Administrators)",
@ -642,7 +642,7 @@ class ExtendedDirsyncTests(SimpleDirsyncTests):
control2 = str(":".join(ctl)) control2 = str(":".join(ctl))
self.ldb_admin.add_remove_group_members("Administrators", [self.dirsync_user], self.ldb_admin.add_remove_group_members("Administrators", [self.dirsync_user],
add_members_operation=False) add_members_operation=False)
res = self.ldb_admin.search(self.base_dn, res = self.ldb_admin.search(self.base_dn,
expression="(name=Administrators)", expression="(name=Administrators)",
@ -668,8 +668,8 @@ class ExtendedDirsyncTests(SimpleDirsyncTests):
# Specify LDAP_DIRSYNC_OBJECT_SECURITY # Specify LDAP_DIRSYNC_OBJECT_SECURITY
res = self.ldb_simple.search(self.base_dn, res = self.ldb_simple.search(self.base_dn,
expression="(&(objectClass=organizationalUnit)(!(isDeleted=*)))", expression="(&(objectClass=organizationalUnit)(!(isDeleted=*)))",
controls=["dirsync:1:1:1"]) controls=["dirsync:1:1:1"])
guid = None guid = None
for e in res: for e in res:
@ -689,8 +689,8 @@ class ExtendedDirsyncTests(SimpleDirsyncTests):
delete_force(self.ldb_admin, ouname) delete_force(self.ldb_admin, ouname)
res = self.ldb_simple.search(self.base_dn, res = self.ldb_simple.search(self.base_dn,
expression="(objectClass=organizationalUnit)", expression="(objectClass=organizationalUnit)",
controls=[control1]) controls=[control1])
self.assertEqual(len(res), 1) self.assertEqual(len(res), 1)
guid2 = str(ndr_unpack(misc.GUID,res[0].get("objectGUID")[0])) guid2 = str(ndr_unpack(misc.GUID,res[0].get("objectGUID")[0]))
self.assertEqual(guid2, guid) self.assertEqual(guid2, guid)

View File

@ -43,11 +43,11 @@ from ldb import timestring
from samba import Ldb from samba import Ldb
from samba.samdb import SamDB from samba.samdb import SamDB
from samba.dsdb import (UF_NORMAL_ACCOUNT, from samba.dsdb import (UF_NORMAL_ACCOUNT,
UF_WORKSTATION_TRUST_ACCOUNT, UF_WORKSTATION_TRUST_ACCOUNT,
UF_PASSWD_NOTREQD, UF_ACCOUNTDISABLE, ATYPE_NORMAL_ACCOUNT, UF_PASSWD_NOTREQD, UF_ACCOUNTDISABLE, ATYPE_NORMAL_ACCOUNT,
ATYPE_WORKSTATION_TRUST, SYSTEM_FLAG_DOMAIN_DISALLOW_MOVE, ATYPE_WORKSTATION_TRUST, SYSTEM_FLAG_DOMAIN_DISALLOW_MOVE,
SYSTEM_FLAG_CONFIG_ALLOW_RENAME, SYSTEM_FLAG_CONFIG_ALLOW_MOVE, SYSTEM_FLAG_CONFIG_ALLOW_RENAME, SYSTEM_FLAG_CONFIG_ALLOW_MOVE,
SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE) SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE)
from samba.ndr import ndr_pack, ndr_unpack from samba.ndr import ndr_pack, ndr_unpack
from samba.dcerpc import security, lsa from samba.dcerpc import security, lsa
@ -216,7 +216,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("top", FLAG_MOD_DELETE, m["objectClass"] = MessageElement("top", FLAG_MOD_DELETE,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
res = ldb.search("cn=ldaptestuser,cn=users," + self.base_dn, res = ldb.search("cn=ldaptestuser,cn=users," + self.base_dn,
@ -229,7 +229,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("person", FLAG_MOD_DELETE, m["objectClass"] = MessageElement("person", FLAG_MOD_DELETE,
"objectClass") "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -241,7 +241,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("computer", FLAG_MOD_DELETE, m["objectClass"] = MessageElement("computer", FLAG_MOD_DELETE,
"objectClass") "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -253,7 +253,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("X", FLAG_MOD_ADD, m["objectClass"] = MessageElement("X", FLAG_MOD_ADD,
"objectClass") "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -267,7 +267,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("user", FLAG_MOD_ADD, m["objectClass"] = MessageElement("user", FLAG_MOD_ADD,
"objectClass") "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -279,7 +279,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("person", FLAG_MOD_ADD, m["objectClass"] = MessageElement("person", FLAG_MOD_ADD,
"objectClass") "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -291,7 +291,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_ADD, m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_ADD,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
# This does not work since object class "leaf" is not auxiliary nor it # This does not work since object class "leaf" is not auxiliary nor it
@ -299,7 +299,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("leaf", FLAG_MOD_ADD, m["objectClass"] = MessageElement("leaf", FLAG_MOD_ADD,
"objectClass") "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -311,13 +311,13 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement(["top", "person", "bootableDevice"], m["objectClass"] = MessageElement(["top", "person", "bootableDevice"],
FLAG_MOD_REPLACE, "objectClass") FLAG_MOD_REPLACE, "objectClass")
ldb.modify(m) ldb.modify(m)
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement(["person", "bootableDevice"], m["objectClass"] = MessageElement(["person", "bootableDevice"],
FLAG_MOD_REPLACE, "objectClass") FLAG_MOD_REPLACE, "objectClass")
ldb.modify(m) ldb.modify(m)
# This does not work since object class "leaf" is not auxiliary nor it # This does not work since object class "leaf" is not auxiliary nor it
@ -325,7 +325,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement(["top", "person", "bootableDevice", m["objectClass"] = MessageElement(["top", "person", "bootableDevice",
"leaf"], FLAG_MOD_REPLACE, "objectClass") "leaf"], FLAG_MOD_REPLACE, "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -354,7 +354,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement(["top", "computer"], FLAG_MOD_REPLACE, m["objectClass"] = MessageElement(["top", "computer"], FLAG_MOD_REPLACE,
"objectClass") "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -366,7 +366,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_DELETE, m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_DELETE,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
res = ldb.search("cn=ldaptestuser,cn=users," + self.base_dn, res = ldb.search("cn=ldaptestuser,cn=users," + self.base_dn,
@ -377,14 +377,14 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_ADD, m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_ADD,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
# Add an attribute specific to the "bootableDevice" class # Add an attribute specific to the "bootableDevice" class
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["bootParameter"] = MessageElement("test", FLAG_MOD_ADD, m["bootParameter"] = MessageElement("test", FLAG_MOD_ADD,
"bootParameter") "bootParameter")
ldb.modify(m) ldb.modify(m)
# Classes can be removed unless attributes of them are used. Now there # Classes can be removed unless attributes of them are used. Now there
@ -392,7 +392,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_DELETE, m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_DELETE,
"objectClass") "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -404,14 +404,14 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["bootParameter"] = MessageElement("test", FLAG_MOD_DELETE, m["bootParameter"] = MessageElement("test", FLAG_MOD_DELETE,
"bootParameter") "bootParameter")
ldb.modify(m) ldb.modify(m)
# Classes can be removed unless attributes of them are used. # Classes can be removed unless attributes of them are used.
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_DELETE, m["objectClass"] = MessageElement("bootableDevice", FLAG_MOD_DELETE,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
delete_force(self.ldb, "cn=ldaptestuser,cn=users," + self.base_dn) delete_force(self.ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
@ -425,7 +425,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("container", FLAG_MOD_ADD, m["objectClass"] = MessageElement("container", FLAG_MOD_ADD,
"objectClass") "objectClass")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -438,13 +438,13 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("inetOrgPerson", FLAG_MOD_ADD, m["objectClass"] = MessageElement("inetOrgPerson", FLAG_MOD_ADD,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("inetOrgPerson", FLAG_MOD_DELETE, m["objectClass"] = MessageElement("inetOrgPerson", FLAG_MOD_DELETE,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
# Replace top-most structural class to "inetOrgPerson" and reset it # Replace top-most structural class to "inetOrgPerson" and reset it
@ -452,20 +452,20 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("inetOrgPerson", FLAG_MOD_REPLACE, m["objectClass"] = MessageElement("inetOrgPerson", FLAG_MOD_REPLACE,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("user", FLAG_MOD_REPLACE, m["objectClass"] = MessageElement("user", FLAG_MOD_REPLACE,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
# Add a new auxiliary object class "posixAccount" to "ldaptestuser" # Add a new auxiliary object class "posixAccount" to "ldaptestuser"
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("posixAccount", FLAG_MOD_ADD, m["objectClass"] = MessageElement("posixAccount", FLAG_MOD_ADD,
"objectClass") "objectClass")
ldb.modify(m) ldb.modify(m)
# Be sure that "top" is the first and the (most) structural object class # Be sure that "top" is the first and the (most) structural object class
@ -517,7 +517,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=Test Secret,cn=system," + self.base_dn) m.dn = Dn(ldb, "cn=Test Secret,cn=system," + self.base_dn)
m["description"] = MessageElement("desc", FLAG_MOD_REPLACE, m["description"] = MessageElement("desc", FLAG_MOD_REPLACE,
"description") "description")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -544,7 +544,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestcontainer," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestcontainer," + self.base_dn)
m["isCriticalSystemObject"] = MessageElement("TRUE", FLAG_MOD_REPLACE, m["isCriticalSystemObject"] = MessageElement("TRUE", FLAG_MOD_REPLACE,
"isCriticalSystemObject") "isCriticalSystemObject")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -581,7 +581,7 @@ class BasicTests(samba.tests.TestCase):
self.assertEquals(num, ERR_NO_SUCH_OBJECT) self.assertEquals(num, ERR_NO_SUCH_OBJECT)
delete_force(self.ldb, "cn=ldaptestgroup,cn=thisdoesnotexist123," delete_force(self.ldb, "cn=ldaptestgroup,cn=thisdoesnotexist123,"
+ self.base_dn) + self.base_dn)
try: try:
self.ldb.add({ self.ldb.add({
@ -619,7 +619,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["thisdoesnotexist"] = MessageElement("x", FLAG_MOD_REPLACE, m["thisdoesnotexist"] = MessageElement("x", FLAG_MOD_REPLACE,
"thisdoesnotexist") "thisdoesnotexist")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -688,7 +688,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestobject," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestobject," + self.base_dn)
m["ipProtocolNumber"] = MessageElement([], FLAG_MOD_DELETE, m["ipProtocolNumber"] = MessageElement([], FLAG_MOD_DELETE,
"ipProtocolNumber") "ipProtocolNumber")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -700,7 +700,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestobject," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestobject," + self.base_dn)
m["ipProtocolNumber"] = MessageElement([], FLAG_MOD_REPLACE, m["ipProtocolNumber"] = MessageElement([], FLAG_MOD_REPLACE,
"ipProtocolNumber") "ipProtocolNumber")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -729,7 +729,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["sAMAccountName"] = MessageElement(["nam1","nam2"], FLAG_MOD_REPLACE, m["sAMAccountName"] = MessageElement(["nam1","nam2"], FLAG_MOD_REPLACE,
"sAMAccountName") "sAMAccountName")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -740,13 +740,13 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["sAMAccountName"] = MessageElement("testgroupXX", FLAG_MOD_REPLACE, m["sAMAccountName"] = MessageElement("testgroupXX", FLAG_MOD_REPLACE,
"sAMAccountName") "sAMAccountName")
ldb.modify(m) ldb.modify(m)
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["sAMAccountName"] = MessageElement("testgroupXX2", FLAG_MOD_ADD, m["sAMAccountName"] = MessageElement("testgroupXX2", FLAG_MOD_ADD,
"sAMAccountName") "sAMAccountName")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -1062,7 +1062,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["instanceType"] = MessageElement("0", FLAG_MOD_REPLACE, m["instanceType"] = MessageElement("0", FLAG_MOD_REPLACE,
"instanceType") "instanceType")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -1073,7 +1073,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["instanceType"] = MessageElement([], FLAG_MOD_REPLACE, m["instanceType"] = MessageElement([], FLAG_MOD_REPLACE,
"instanceType") "instanceType")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -1112,7 +1112,7 @@ class BasicTests(samba.tests.TestCase):
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["objectClass"] = MessageElement("group", 0, "objectClass") m["objectClass"] = MessageElement("group", 0, "objectClass")
m["dn"] = MessageElement("cn=ldaptestgroup,cn=users," + self.base_dn, 0, m["dn"] = MessageElement("cn=ldaptestgroup,cn=users," + self.base_dn, 0,
"dn") "dn")
try: try:
ldb.add(m) ldb.add(m)
self.fail() self.fail()
@ -1132,7 +1132,7 @@ class BasicTests(samba.tests.TestCase):
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertTrue("distinguishedName" in res[0]) self.assertTrue("distinguishedName" in res[0])
self.assertTrue(Dn(ldb, res[0]["distinguishedName"][0]) self.assertTrue(Dn(ldb, res[0]["distinguishedName"][0])
== Dn(ldb, "cn=ldaptestgroup, cn=users," + self.base_dn)) == Dn(ldb, "cn=ldaptestgroup, cn=users," + self.base_dn))
# The "dn" shortcut isn't supported # The "dn" shortcut isn't supported
m = Message() m = Message()
@ -1349,7 +1349,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["name"] = MessageElement("cn=ldaptestuser", FLAG_MOD_REPLACE, m["name"] = MessageElement("cn=ldaptestuser", FLAG_MOD_REPLACE,
"name") "name")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -1360,7 +1360,7 @@ class BasicTests(samba.tests.TestCase):
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["cn"] = MessageElement("ldaptestuser", m["cn"] = MessageElement("ldaptestuser",
FLAG_MOD_REPLACE, "cn") FLAG_MOD_REPLACE, "cn")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -1692,8 +1692,8 @@ replace: description
""") """)
res2 = ldb.search("cn=ldaptestcontainer," + self.base_dn, res2 = ldb.search("cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, scope=SCOPE_BASE,
attrs=["uSNCreated", "uSNChanged", "description"]) attrs=["uSNCreated", "uSNChanged", "description"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertFalse("description" in res2[0]) self.assertFalse("description" in res2[0])
self.assertEqual(res[0]["usnCreated"], res2[0]["usnCreated"]) self.assertEqual(res[0]["usnCreated"], res2[0]["usnCreated"])
@ -1708,8 +1708,8 @@ description: test
""") """)
res3 = ldb.search("cn=ldaptestcontainer," + self.base_dn, res3 = ldb.search("cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, scope=SCOPE_BASE,
attrs=["uSNCreated", "uSNChanged", "description"]) attrs=["uSNCreated", "uSNChanged", "description"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertTrue("description" in res3[0]) self.assertTrue("description" in res3[0])
self.assertEqual("test", str(res3[0]["description"][0])) self.assertEqual("test", str(res3[0]["description"][0]))
@ -1725,8 +1725,8 @@ description: test
""") """)
res4 = ldb.search("cn=ldaptestcontainer," + self.base_dn, res4 = ldb.search("cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, scope=SCOPE_BASE,
attrs=["uSNCreated", "uSNChanged", "description"]) attrs=["uSNCreated", "uSNChanged", "description"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertTrue("description" in res4[0]) self.assertTrue("description" in res4[0])
self.assertEqual("test", str(res4[0]["description"][0])) self.assertEqual("test", str(res4[0]["description"][0]))
@ -1742,8 +1742,8 @@ description: test2
""") """)
res5 = ldb.search("cn=ldaptestcontainer," + self.base_dn, res5 = ldb.search("cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, scope=SCOPE_BASE,
attrs=["uSNCreated", "uSNChanged", "description"]) attrs=["uSNCreated", "uSNChanged", "description"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertTrue("description" in res5[0]) self.assertTrue("description" in res5[0])
self.assertEqual("test2", str(res5[0]["description"][0])) self.assertEqual("test2", str(res5[0]["description"][0]))
@ -1758,8 +1758,8 @@ description: test2
""") """)
res6 = ldb.search("cn=ldaptestcontainer," + self.base_dn, res6 = ldb.search("cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, scope=SCOPE_BASE,
attrs=["uSNCreated", "uSNChanged", "description"]) attrs=["uSNCreated", "uSNChanged", "description"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertFalse("description" in res6[0]) self.assertFalse("description" in res6[0])
self.assertEqual(res[0]["usnCreated"], res6[0]["usnCreated"]) self.assertEqual(res[0]["usnCreated"], res6[0]["usnCreated"])
@ -1773,8 +1773,8 @@ description: test3
""") """)
res7 = ldb.search("cn=ldaptestcontainer," + self.base_dn, res7 = ldb.search("cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, scope=SCOPE_BASE,
attrs=["uSNCreated", "uSNChanged", "description"]) attrs=["uSNCreated", "uSNChanged", "description"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertTrue("description" in res7[0]) self.assertTrue("description" in res7[0])
self.assertEqual("test3", str(res7[0]["description"][0])) self.assertEqual("test3", str(res7[0]["description"][0]))
@ -1788,8 +1788,8 @@ delete: description
""") """)
res8 = ldb.search("cn=ldaptestcontainer," + self.base_dn, res8 = ldb.search("cn=ldaptestcontainer," + self.base_dn,
scope=SCOPE_BASE, scope=SCOPE_BASE,
attrs=["uSNCreated", "uSNChanged", "description"]) attrs=["uSNCreated", "uSNChanged", "description"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertFalse("description" in res8[0]) self.assertFalse("description" in res8[0])
self.assertEqual(res[0]["usnCreated"], res8[0]["usnCreated"]) self.assertEqual(res[0]["usnCreated"], res8[0]["usnCreated"])
@ -1836,7 +1836,7 @@ delete: description
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["memberOf"] = MessageElement("cn=ldaptestgroup,cn=users," + self.base_dn, m["memberOf"] = MessageElement("cn=ldaptestgroup,cn=users," + self.base_dn,
FLAG_MOD_ADD, "memberOf") FLAG_MOD_ADD, "memberOf")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -1847,13 +1847,13 @@ delete: description
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["member"] = MessageElement("cn=ldaptestuser,cn=users," + self.base_dn, m["member"] = MessageElement("cn=ldaptestuser,cn=users," + self.base_dn,
FLAG_MOD_ADD, "member") FLAG_MOD_ADD, "member")
ldb.modify(m) ldb.modify(m)
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["memberOf"] = MessageElement("cn=ldaptestgroup,cn=users," + self.base_dn, m["memberOf"] = MessageElement("cn=ldaptestgroup,cn=users," + self.base_dn,
FLAG_MOD_REPLACE, "memberOf") FLAG_MOD_REPLACE, "memberOf")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -1864,7 +1864,7 @@ delete: description
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
m["memberOf"] = MessageElement("cn=ldaptestgroup,cn=users," + self.base_dn, m["memberOf"] = MessageElement("cn=ldaptestgroup,cn=users," + self.base_dn,
FLAG_MOD_DELETE, "memberOf") FLAG_MOD_DELETE, "memberOf")
try: try:
ldb.modify(m) ldb.modify(m)
self.fail() self.fail()
@ -1875,7 +1875,7 @@ delete: description
m = Message() m = Message()
m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn) m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
m["member"] = MessageElement("cn=ldaptestuser,cn=users," + self.base_dn, m["member"] = MessageElement("cn=ldaptestuser,cn=users," + self.base_dn,
FLAG_MOD_DELETE, "member") FLAG_MOD_DELETE, "member")
ldb.modify(m) ldb.modify(m)
# This should yield no results since the member attribute for # This should yield no results since the member attribute for
@ -1954,10 +1954,10 @@ delete: description
"cN": "LDAPtestCOMPUTER"}) "cN": "LDAPtestCOMPUTER"})
ldb.add({"dn": "cn=ldaptest2computer,cn=computers," + self.base_dn, ldb.add({"dn": "cn=ldaptest2computer,cn=computers," + self.base_dn,
"objectClass": "computer", "objectClass": "computer",
"cn": "LDAPtest2COMPUTER", "cn": "LDAPtest2COMPUTER",
"userAccountControl": str(UF_WORKSTATION_TRUST_ACCOUNT), "userAccountControl": str(UF_WORKSTATION_TRUST_ACCOUNT),
"displayname": "ldap testy"}) "displayname": "ldap testy"})
try: try:
ldb.add({"dn": "cn=ldaptestcomputer3,cn=computers," + self.base_dn, ldb.add({"dn": "cn=ldaptestcomputer3,cn=computers," + self.base_dn,
@ -2351,8 +2351,8 @@ member: cn=ldaptestuser2,cn=users,""" + self.base_dn + """
# Testing subtree ldb.search for (&(cn=ldaptestuser4)(objectClass=user)) in (just renamed from) cn=ldaptestcontainer," + self.base_dn # Testing subtree ldb.search for (&(cn=ldaptestuser4)(objectClass=user)) in (just renamed from) cn=ldaptestcontainer," + self.base_dn
try: try:
res = ldb.search("cn=ldaptestcontainer," + self.base_dn, res = ldb.search("cn=ldaptestcontainer," + self.base_dn,
expression="(&(cn=ldaptestuser4)(objectClass=user))", expression="(&(cn=ldaptestuser4)(objectClass=user))",
scope=SCOPE_SUBTREE) scope=SCOPE_SUBTREE)
self.fail(res) self.fail(res)
except LdbError as e102: except LdbError as e102:
(num, _) = e102.args (num, _) = e102.args
@ -2361,7 +2361,7 @@ member: cn=ldaptestuser2,cn=users,""" + self.base_dn + """
# Testing one-level ldb.search for (&(cn=ldaptestuser4)(objectClass=user)) in (just renamed from) cn=ldaptestcontainer," + self.base_dn # Testing one-level ldb.search for (&(cn=ldaptestuser4)(objectClass=user)) in (just renamed from) cn=ldaptestcontainer," + self.base_dn
try: try:
res = ldb.search("cn=ldaptestcontainer," + self.base_dn, res = ldb.search("cn=ldaptestcontainer," + self.base_dn,
expression="(&(cn=ldaptestuser4)(objectClass=user))", scope=SCOPE_ONELEVEL) expression="(&(cn=ldaptestuser4)(objectClass=user))", scope=SCOPE_ONELEVEL)
self.fail() self.fail()
except LdbError as e103: except LdbError as e103:
(num, _) = e103.args (num, _) = e103.args
@ -3184,13 +3184,13 @@ class BaseDnTests(samba.tests.TestCase):
def test_netlogon_highestcommitted_usn(self): def test_netlogon_highestcommitted_usn(self):
"""Testing for netlogon and highestCommittedUSN via LDAP""" """Testing for netlogon and highestCommittedUSN via LDAP"""
res = self.ldb.search("", scope=SCOPE_BASE, res = self.ldb.search("", scope=SCOPE_BASE,
attrs=["netlogon", "highestCommittedUSN"]) attrs=["netlogon", "highestCommittedUSN"])
self.assertEquals(len(res), 0) self.assertEquals(len(res), 0)
def test_namingContexts(self): def test_namingContexts(self):
"""Testing for namingContexts in rootDSE""" """Testing for namingContexts in rootDSE"""
res = self.ldb.search("", scope=SCOPE_BASE, res = self.ldb.search("", scope=SCOPE_BASE,
attrs=["namingContexts", "defaultNamingContext", "schemaNamingContext", "configurationNamingContext"]) attrs=["namingContexts", "defaultNamingContext", "schemaNamingContext", "configurationNamingContext"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
ncs = set([]) ncs = set([])
@ -3228,7 +3228,7 @@ class BaseDnTests(samba.tests.TestCase):
self.assertTrue(int(res[0]["domainControllerFunctionality"][0]) >= int(res[0]["domainFunctionality"][0])) self.assertTrue(int(res[0]["domainControllerFunctionality"][0]) >= int(res[0]["domainFunctionality"][0]))
res2 = self.ldb.search("", scope=SCOPE_BASE, res2 = self.ldb.search("", scope=SCOPE_BASE,
attrs=["dsServiceName", "serverName"]) attrs=["dsServiceName", "serverName"])
self.assertEquals(len(res2), 1) self.assertEquals(len(res2), 1)
self.assertEquals(len(res2[0]["dsServiceName"]), 1) self.assertEquals(len(res2[0]["dsServiceName"]), 1)

View File

@ -74,14 +74,14 @@ class SchemaTests(samba.tests.TestCase):
def setUp(self): def setUp(self):
super(SchemaTests, self).setUp() super(SchemaTests, self).setUp()
self.ldb = SamDB(host, credentials=creds, self.ldb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp, options=ldb_options) session_info=system_session(lp), lp=lp, options=ldb_options)
self.base_dn = self.ldb.domain_dn() self.base_dn = self.ldb.domain_dn()
self.schema_dn = self.ldb.get_schema_basedn().get_linearized() self.schema_dn = self.ldb.get_schema_basedn().get_linearized()
def test_generated_schema(self): def test_generated_schema(self):
"""Testing we can read the generated schema via LDAP""" """Testing we can read the generated schema via LDAP"""
res = self.ldb.search("cn=aggregate,"+self.schema_dn, scope=SCOPE_BASE, res = self.ldb.search("cn=aggregate,"+self.schema_dn, scope=SCOPE_BASE,
attrs=["objectClasses", "attributeTypes", "dITContentRules"]) attrs=["objectClasses", "attributeTypes", "dITContentRules"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.assertTrue("dITContentRules" in res[0]) self.assertTrue("dITContentRules" in res[0])
self.assertTrue("objectClasses" in res[0]) self.assertTrue("objectClasses" in res[0])
@ -843,7 +843,7 @@ attributeId: """ + attributeID + """
# linkID generation isn't available before 2003 # linkID generation isn't available before 2003
res = self.ldb.search(base="", expression="", scope=SCOPE_BASE, res = self.ldb.search(base="", expression="", scope=SCOPE_BASE,
attrs=["domainControllerFunctionality"]) attrs=["domainControllerFunctionality"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
dc_level = int(res[0]["domainControllerFunctionality"][0]) dc_level = int(res[0]["domainControllerFunctionality"][0])
if dc_level < DS_DOMAIN_FUNCTION_2003: if dc_level < DS_DOMAIN_FUNCTION_2003:
@ -1343,10 +1343,10 @@ class SchemaTests_msDS_IntId(samba.tests.TestCase):
def setUp(self): def setUp(self):
super(SchemaTests_msDS_IntId, self).setUp() super(SchemaTests_msDS_IntId, self).setUp()
self.ldb = SamDB(host, credentials=creds, self.ldb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp, options=ldb_options) session_info=system_session(lp), lp=lp, options=ldb_options)
res = self.ldb.search(base="", expression="", scope=SCOPE_BASE, res = self.ldb.search(base="", expression="", scope=SCOPE_BASE,
attrs=["schemaNamingContext", "defaultNamingContext", attrs=["schemaNamingContext", "defaultNamingContext",
"forestFunctionality"]) "forestFunctionality"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.schema_dn = res[0]["schemaNamingContext"][0] self.schema_dn = res[0]["schemaNamingContext"][0]
self.base_dn = res[0]["defaultNamingContext"][0] self.base_dn = res[0]["defaultNamingContext"][0]
@ -1626,7 +1626,7 @@ class SchemaTests_msDS_isRODC(samba.tests.TestCase):
def setUp(self): def setUp(self):
super(SchemaTests_msDS_isRODC, self).setUp() super(SchemaTests_msDS_isRODC, self).setUp()
self.ldb = SamDB(host, credentials=creds, self.ldb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp, options=ldb_options) session_info=system_session(lp), lp=lp, options=ldb_options)
res = self.ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["defaultNamingContext"]) res = self.ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["defaultNamingContext"])
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
self.base_dn = res[0]["defaultNamingContext"][0] self.base_dn = res[0]["defaultNamingContext"][0]

View File

@ -48,7 +48,7 @@ class SyntaxTests(samba.tests.TestCase):
def setUp(self): def setUp(self):
super(SyntaxTests, self).setUp() super(SyntaxTests, self).setUp()
self.ldb = samba.tests.connect_samdb(host, credentials=creds, self.ldb = samba.tests.connect_samdb(host, credentials=creds,
session_info=system_session(lp), lp=lp) session_info=system_session(lp), lp=lp)
self.base_dn = self.ldb.domain_dn() self.base_dn = self.ldb.domain_dn()
self.schema_dn = self.ldb.get_schema_basedn().get_linearized() self.schema_dn = self.ldb.get_schema_basedn().get_linearized()
self._setup_dn_string_test() self._setup_dn_string_test()
@ -195,31 +195,31 @@ name: """ + object_name + """
# add object with correct value # add object with correct value
object_name1 = "obj-DN-String1" + time.strftime("%s", time.gmtime()) object_name1 = "obj-DN-String1" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name, ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name,
self.dn_string_attribute, ": S:5:ABCDE:" + self.base_dn) self.dn_string_attribute, ": S:5:ABCDE:" + self.base_dn)
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
# search by specifying the DN part only # search by specifying the DN part only
res = self.ldb.search(base=self.base_dn, res = self.ldb.search(base=self.base_dn,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="(%s=%s)" % (self.dn_string_attribute, self.base_dn)) expression="(%s=%s)" % (self.dn_string_attribute, self.base_dn))
self.assertEquals(len(res), 0) self.assertEquals(len(res), 0)
# search by specifying the string part only # search by specifying the string part only
res = self.ldb.search(base=self.base_dn, res = self.ldb.search(base=self.base_dn,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="(%s=S:5:ABCDE)" % self.dn_string_attribute) expression="(%s=S:5:ABCDE)" % self.dn_string_attribute)
self.assertEquals(len(res), 0) self.assertEquals(len(res), 0)
# search by DN+Stirng # search by DN+Stirng
res = self.ldb.search(base=self.base_dn, res = self.ldb.search(base=self.base_dn,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="(%s=S:5:ABCDE:%s)" % (self.dn_string_attribute, self.base_dn)) expression="(%s=S:5:ABCDE:%s)" % (self.dn_string_attribute, self.base_dn))
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
# add object with wrong format # add object with wrong format
object_name2 = "obj-DN-String2" + time.strftime("%s", time.gmtime()) object_name2 = "obj-DN-String2" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name2, self.dn_string_class_name, self.dn_string_class_ldap_display_name, ldif = self._get_object_ldif(object_name2, self.dn_string_class_name, self.dn_string_class_ldap_display_name,
self.dn_string_attribute, ": S:5:ABCD:" + self.base_dn) self.dn_string_attribute, ": S:5:ABCD:" + self.base_dn)
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e: except LdbError as e:
@ -228,7 +228,7 @@ name: """ + object_name + """
# add object with the same dn but with different string value in case # add object with the same dn but with different string value in case
ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name, ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name,
self.dn_string_attribute, ": S:5:abcde:" + self.base_dn) self.dn_string_attribute, ": S:5:abcde:" + self.base_dn)
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e1: except LdbError as e1:
@ -237,7 +237,7 @@ name: """ + object_name + """
# add object with the same dn but with different string value # add object with the same dn but with different string value
ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name, ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name,
self.dn_string_attribute, ": S:5:FGHIJ:" + self.base_dn) self.dn_string_attribute, ": S:5:FGHIJ:" + self.base_dn)
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e2: except LdbError as e2:
@ -246,7 +246,7 @@ name: """ + object_name + """
# add object with the same dn but with different dn and string value # add object with the same dn but with different dn and string value
ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name, ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name,
self.dn_string_attribute, ": S:5:FGHIJ:" + self.schema_dn) self.dn_string_attribute, ": S:5:FGHIJ:" + self.schema_dn)
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e3: except LdbError as e3:
@ -255,7 +255,7 @@ name: """ + object_name + """
# add object with the same dn but with different dn value # add object with the same dn but with different dn value
ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name, ldif = self._get_object_ldif(object_name1, self.dn_string_class_name, self.dn_string_class_ldap_display_name,
self.dn_string_attribute, ": S:5:ABCDE:" + self.schema_dn) self.dn_string_attribute, ": S:5:ABCDE:" + self.schema_dn)
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e4: except LdbError as e4:
@ -265,7 +265,7 @@ name: """ + object_name + """
# add object with GUID instead of DN # add object with GUID instead of DN
object_name3 = "obj-DN-String3" + time.strftime("%s", time.gmtime()) object_name3 = "obj-DN-String3" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name3, self.dn_string_class_name, self.dn_string_class_ldap_display_name, ldif = self._get_object_ldif(object_name3, self.dn_string_class_name, self.dn_string_class_ldap_display_name,
self.dn_string_attribute, ": S:5:ABCDE:<GUID=%s>" % str(uuid.uuid4())) self.dn_string_attribute, ": S:5:ABCDE:<GUID=%s>" % str(uuid.uuid4()))
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e5: except LdbError as e5:
@ -275,7 +275,7 @@ name: """ + object_name + """
# add object with SID instead of DN # add object with SID instead of DN
object_name4 = "obj-DN-String4" + time.strftime("%s", time.gmtime()) object_name4 = "obj-DN-String4" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name4, self.dn_string_class_name, self.dn_string_class_ldap_display_name, ldif = self._get_object_ldif(object_name4, self.dn_string_class_name, self.dn_string_class_ldap_display_name,
self.dn_string_attribute, ": S:5:ABCDE:<SID=%s>" % self.ldb.get_domain_sid()) self.dn_string_attribute, ": S:5:ABCDE:<SID=%s>" % self.ldb.get_domain_sid())
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e6: except LdbError as e6:
@ -285,7 +285,7 @@ name: """ + object_name + """
# add object with random string instead of DN # add object with random string instead of DN
object_name5 = "obj-DN-String5" + time.strftime("%s", time.gmtime()) object_name5 = "obj-DN-String5" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name5, self.dn_string_class_name, self.dn_string_class_ldap_display_name, ldif = self._get_object_ldif(object_name5, self.dn_string_class_name, self.dn_string_class_ldap_display_name,
self.dn_string_attribute, ": S:5:ABCDE:randomSTRING") self.dn_string_attribute, ": S:5:ABCDE:randomSTRING")
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e7: except LdbError as e7:
@ -296,31 +296,31 @@ name: """ + object_name + """
# add obeject with correct value # add obeject with correct value
object_name1 = "obj-DN-Binary1" + time.strftime("%s", time.gmtime()) object_name1 = "obj-DN-Binary1" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name1, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name, ldif = self._get_object_ldif(object_name1, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name,
self.dn_binary_attribute, ": B:4:1234:" + self.base_dn) self.dn_binary_attribute, ": B:4:1234:" + self.base_dn)
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
# search by specifyingthe DN part # search by specifyingthe DN part
res = self.ldb.search(base=self.base_dn, res = self.ldb.search(base=self.base_dn,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="(%s=%s)" % (self.dn_binary_attribute, self.base_dn)) expression="(%s=%s)" % (self.dn_binary_attribute, self.base_dn))
self.assertEquals(len(res), 0) self.assertEquals(len(res), 0)
# search by specifying the binary part # search by specifying the binary part
res = self.ldb.search(base=self.base_dn, res = self.ldb.search(base=self.base_dn,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="(%s=B:4:1234)" % self.dn_binary_attribute) expression="(%s=B:4:1234)" % self.dn_binary_attribute)
self.assertEquals(len(res), 0) self.assertEquals(len(res), 0)
# search by DN+Binary # search by DN+Binary
res = self.ldb.search(base=self.base_dn, res = self.ldb.search(base=self.base_dn,
scope=SCOPE_SUBTREE, scope=SCOPE_SUBTREE,
expression="(%s=B:4:1234:%s)" % (self.dn_binary_attribute, self.base_dn)) expression="(%s=B:4:1234:%s)" % (self.dn_binary_attribute, self.base_dn))
self.assertEquals(len(res), 1) self.assertEquals(len(res), 1)
# add object with wrong format - 5 bytes instead of 4, 8, 16, 32... # add object with wrong format - 5 bytes instead of 4, 8, 16, 32...
object_name2 = "obj-DN-Binary2" + time.strftime("%s", time.gmtime()) object_name2 = "obj-DN-Binary2" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name2, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name, ldif = self._get_object_ldif(object_name2, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name,
self.dn_binary_attribute, ": B:5:67890:" + self.base_dn) self.dn_binary_attribute, ": B:5:67890:" + self.base_dn)
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e8: except LdbError as e8:
@ -329,7 +329,7 @@ name: """ + object_name + """
# add object with the same dn but with different binary value # add object with the same dn but with different binary value
ldif = self._get_object_ldif(object_name1, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name, ldif = self._get_object_ldif(object_name1, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name,
self.dn_binary_attribute, ": B:4:5678:" + self.base_dn) self.dn_binary_attribute, ": B:4:5678:" + self.base_dn)
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e9: except LdbError as e9:
@ -338,7 +338,7 @@ name: """ + object_name + """
# add object with the same dn but with different binary and dn value # add object with the same dn but with different binary and dn value
ldif = self._get_object_ldif(object_name1, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name, ldif = self._get_object_ldif(object_name1, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name,
self.dn_binary_attribute, ": B:4:5678:" + self.schema_dn) self.dn_binary_attribute, ": B:4:5678:" + self.schema_dn)
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e10: except LdbError as e10:
@ -347,7 +347,7 @@ name: """ + object_name + """
# add object with the same dn but with different dn value # add object with the same dn but with different dn value
ldif = self._get_object_ldif(object_name1, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name, ldif = self._get_object_ldif(object_name1, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name,
self.dn_binary_attribute, ": B:4:1234:" + self.schema_dn) self.dn_binary_attribute, ": B:4:1234:" + self.schema_dn)
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e11: except LdbError as e11:
@ -357,7 +357,7 @@ name: """ + object_name + """
# add object with GUID instead of DN # add object with GUID instead of DN
object_name3 = "obj-DN-Binary3" + time.strftime("%s", time.gmtime()) object_name3 = "obj-DN-Binary3" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name3, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name, ldif = self._get_object_ldif(object_name3, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name,
self.dn_binary_attribute, ": B:4:1234:<GUID=%s>" % str(uuid.uuid4())) self.dn_binary_attribute, ": B:4:1234:<GUID=%s>" % str(uuid.uuid4()))
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e12: except LdbError as e12:
@ -367,7 +367,7 @@ name: """ + object_name + """
# add object with SID instead of DN # add object with SID instead of DN
object_name4 = "obj-DN-Binary4" + time.strftime("%s", time.gmtime()) object_name4 = "obj-DN-Binary4" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name4, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name, ldif = self._get_object_ldif(object_name4, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name,
self.dn_binary_attribute, ": B:4:1234:<SID=%s>" % self.ldb.get_domain_sid()) self.dn_binary_attribute, ": B:4:1234:<SID=%s>" % self.ldb.get_domain_sid())
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e13: except LdbError as e13:
@ -377,7 +377,7 @@ name: """ + object_name + """
# add object with random string instead of DN # add object with random string instead of DN
object_name5 = "obj-DN-Binary5" + time.strftime("%s", time.gmtime()) object_name5 = "obj-DN-Binary5" + time.strftime("%s", time.gmtime())
ldif = self._get_object_ldif(object_name5, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name, ldif = self._get_object_ldif(object_name5, self.dn_binary_class_name, self.dn_binary_class_ldap_display_name,
self.dn_binary_attribute, ": B:4:1234:randomSTRING") self.dn_binary_attribute, ": B:4:1234:randomSTRING")
try: try:
self.ldb.add_ldif(ldif) self.ldb.add_ldif(ldif)
except LdbError as e14: except LdbError as e14:

View File

@ -44,8 +44,8 @@ class BasePasswordTestCase(PasswordTestCase):
if mode == "absent": if mode == "absent":
self.assertFalse(name in res[0], self.assertFalse(name in res[0],
msg="attr[%s] not missing on dn[%s]" % msg="attr[%s] not missing on dn[%s]" %
(name, res[0].dn)) (name, res[0].dn))
return return
self.assertTrue(name in res[0], self.assertTrue(name in res[0],
@ -294,7 +294,7 @@ userPassword: """ + userpass + """
configuration_dn = self.ldb.get_config_basedn().get_linearized() configuration_dn = self.ldb.get_config_basedn().get_linearized()
res = self.ldb.search(base_dn, res = self.ldb.search(base_dn,
scope=SCOPE_BASE, attrs=["lockoutDuration", "lockOutObservationWindow", "lockoutThreshold"]) scope=SCOPE_BASE, attrs=["lockoutDuration", "lockOutObservationWindow", "lockoutThreshold"])
if "lockoutDuration" in res[0]: if "lockoutDuration" in res[0]:
lockoutDuration = res[0]["lockoutDuration"][0] lockoutDuration = res[0]["lockoutDuration"][0]

View File

@ -158,7 +158,7 @@ add: userPassword
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["unicodePwd"] = MessageElement("XXXXXXXXXXXXXXXX", FLAG_MOD_REPLACE, m["unicodePwd"] = MessageElement("XXXXXXXXXXXXXXXX", FLAG_MOD_REPLACE,
"unicodePwd") "unicodePwd")
try: try:
self.ldb.modify(m) self.ldb.modify(m)
self.fail() self.fail()
@ -191,7 +191,7 @@ unicodePwd: YYYYYYYYYYYYYYYY
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["unicodePwd"] = MessageElement("\"thatsAcomplPASS2\"".encode('utf-16-le'), m["unicodePwd"] = MessageElement("\"thatsAcomplPASS2\"".encode('utf-16-le'),
FLAG_MOD_REPLACE, "unicodePwd") FLAG_MOD_REPLACE, "unicodePwd")
self.ldb.modify(m) self.ldb.modify(m)
def test_unicodePwd_clear_change(self): def test_unicodePwd_clear_change(self):
@ -245,7 +245,7 @@ unicodePwd:: """ + base64.b64encode("\"thatsAcomplPASS2\"".encode('utf-16-le')).
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["dBCSPwd"] = MessageElement("XXXXXXXXXXXXXXXX", FLAG_MOD_REPLACE, m["dBCSPwd"] = MessageElement("XXXXXXXXXXXXXXXX", FLAG_MOD_REPLACE,
"dBCSPwd") "dBCSPwd")
try: try:
self.ldb.modify(m) self.ldb.modify(m)
self.fail() self.fail()
@ -279,7 +279,7 @@ dBCSPwd: YYYYYYYYYYYYYYYY
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["userPassword"] = MessageElement("thatsAcomplPASS2", FLAG_MOD_REPLACE, m["userPassword"] = MessageElement("thatsAcomplPASS2", FLAG_MOD_REPLACE,
"userPassword") "userPassword")
self.ldb.modify(m) self.ldb.modify(m)
def test_userPassword_clear_change(self): def test_userPassword_clear_change(self):
@ -336,7 +336,7 @@ userPassword: thatsAcomplPASS2
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["clearTextPassword"] = MessageElement("thatsAcomplPASS2".encode('utf-16-le'), m["clearTextPassword"] = MessageElement("thatsAcomplPASS2".encode('utf-16-le'),
FLAG_MOD_REPLACE, "clearTextPassword") FLAG_MOD_REPLACE, "clearTextPassword")
self.ldb.modify(m) self.ldb.modify(m)
# this passes against s4 # this passes against s4
except LdbError as e10: except LdbError as e10:
@ -884,11 +884,11 @@ userPassword: thatsAcomplPASS4
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["userPassword"] = MessageElement("myPassword", FLAG_MOD_ADD, m["userPassword"] = MessageElement("myPassword", FLAG_MOD_ADD,
"userPassword") "userPassword")
self.ldb.modify(m) self.ldb.modify(m)
res = self.ldb.search("cn=testuser,cn=users," + self.base_dn, res = self.ldb.search("cn=testuser,cn=users," + self.base_dn,
scope=SCOPE_BASE, attrs=["userPassword"]) scope=SCOPE_BASE, attrs=["userPassword"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertTrue("userPassword" in res[0]) self.assertTrue("userPassword" in res[0])
self.assertEquals(res[0]["userPassword"][0], "myPassword") self.assertEquals(res[0]["userPassword"][0], "myPassword")
@ -896,11 +896,11 @@ userPassword: thatsAcomplPASS4
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["userPassword"] = MessageElement("myPassword2", FLAG_MOD_REPLACE, m["userPassword"] = MessageElement("myPassword2", FLAG_MOD_REPLACE,
"userPassword") "userPassword")
self.ldb.modify(m) self.ldb.modify(m)
res = self.ldb.search("cn=testuser,cn=users," + self.base_dn, res = self.ldb.search("cn=testuser,cn=users," + self.base_dn,
scope=SCOPE_BASE, attrs=["userPassword"]) scope=SCOPE_BASE, attrs=["userPassword"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertTrue("userPassword" in res[0]) self.assertTrue("userPassword" in res[0])
self.assertEquals(res[0]["userPassword"][0], "myPassword2") self.assertEquals(res[0]["userPassword"][0], "myPassword2")
@ -908,11 +908,11 @@ userPassword: thatsAcomplPASS4
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["userPassword"] = MessageElement([], FLAG_MOD_DELETE, m["userPassword"] = MessageElement([], FLAG_MOD_DELETE,
"userPassword") "userPassword")
self.ldb.modify(m) self.ldb.modify(m)
res = self.ldb.search("cn=testuser,cn=users," + self.base_dn, res = self.ldb.search("cn=testuser,cn=users," + self.base_dn,
scope=SCOPE_BASE, attrs=["userPassword"]) scope=SCOPE_BASE, attrs=["userPassword"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertFalse("userPassword" in res[0]) self.assertFalse("userPassword" in res[0])
@ -922,11 +922,11 @@ userPassword: thatsAcomplPASS4
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["userPassword"] = MessageElement("myPassword3", FLAG_MOD_REPLACE, m["userPassword"] = MessageElement("myPassword3", FLAG_MOD_REPLACE,
"userPassword") "userPassword")
self.ldb.modify(m) self.ldb.modify(m)
res = self.ldb.search("cn=testuser,cn=users," + self.base_dn, res = self.ldb.search("cn=testuser,cn=users," + self.base_dn,
scope=SCOPE_BASE, attrs=["userPassword"]) scope=SCOPE_BASE, attrs=["userPassword"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertTrue("userPassword" in res[0]) self.assertTrue("userPassword" in res[0])
self.assertEquals(res[0]["userPassword"][0], "myPassword3") self.assertEquals(res[0]["userPassword"][0], "myPassword3")
@ -937,11 +937,11 @@ userPassword: thatsAcomplPASS4
m = Message() m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["userPassword"] = MessageElement("myPassword4", FLAG_MOD_REPLACE, m["userPassword"] = MessageElement("myPassword4", FLAG_MOD_REPLACE,
"userPassword") "userPassword")
self.ldb.modify(m) self.ldb.modify(m)
res = self.ldb.search("cn=testuser,cn=users," + self.base_dn, res = self.ldb.search("cn=testuser,cn=users," + self.base_dn,
scope=SCOPE_BASE, attrs=["userPassword"]) scope=SCOPE_BASE, attrs=["userPassword"])
self.assertTrue(len(res) == 1) self.assertTrue(len(res) == 1)
self.assertTrue("userPassword" in res[0]) self.assertTrue("userPassword" in res[0])
self.assertEquals(res[0]["userPassword"][0], "myPassword4") self.assertEquals(res[0]["userPassword"][0], "myPassword4")
@ -967,7 +967,7 @@ userPassword: thatsAcomplPASS4
m = Message() m = Message()
m.dn = Dn(ldb1, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(ldb1, "cn=testuser,cn=users," + self.base_dn)
m["userPassword"] = MessageElement("thatsAcomplPASS1", FLAG_MOD_REPLACE, m["userPassword"] = MessageElement("thatsAcomplPASS1", FLAG_MOD_REPLACE,
"userPassword") "userPassword")
ldb1.modify(m) ldb1.modify(m)
res = ldb1.search("cn=testuser,cn=users," + self.base_dn, res = ldb1.search("cn=testuser,cn=users," + self.base_dn,
@ -1005,7 +1005,7 @@ userPassword: thatsAcomplPASS4
m = Message() m = Message()
m.dn = Dn(ldb2, "cn=testuser,cn=users," + self.base_dn) m.dn = Dn(ldb2, "cn=testuser,cn=users," + self.base_dn)
m["userPassword"] = MessageElement("thatsAcomplPASS2", FLAG_MOD_REPLACE, m["userPassword"] = MessageElement("thatsAcomplPASS2", FLAG_MOD_REPLACE,
"userPassword") "userPassword")
ldb2.modify(m) ldb2.modify(m)
res = ldb2.search("cn=testuser,cn=users," + self.base_dn, res = ldb2.search("cn=testuser,cn=users," + self.base_dn,

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More