本文整理汇总了Python中samba.samdb.SamDB.add方法的典型用法代码示例。如果您正苦于以下问题:Python SamDB.add方法的具体用法?Python SamDB.add怎么用?Python SamDB.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类samba.samdb.SamDB
的用法示例。
在下文中一共展示了SamDB.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_dont_create_db_existing_tdb_file
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
def test_dont_create_db_existing_tdb_file(self):
existing_name = self.tempdir + "/existing.db"
initial = SamDB(url="tdb://" + existing_name, flags=0)
dn = "dn=,cn=test_dont_create_db_existing_tdb_file"
initial.add({
"dn": dn,
"cn": "test_dont_create_db_existing_tdb_file"
})
cn = initial.searchone("cn", dn)
self.assertEquals(b"test_dont_create_db_existing_tdb_file", cn)
second = SamDB(url="tdb://" + existing_name)
cn = second.searchone("cn", dn)
self.assertEquals(b"test_dont_create_db_existing_tdb_file", cn)
示例2: test_add_replicated_objects
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
def test_add_replicated_objects(self):
for o in (
{
'dn': "ou=%s1,%s" % (self.tag, self.base_dn),
"objectclass": "organizationalUnit"
},
{
'dn': "cn=%s2,%s" % (self.tag, self.base_dn),
"objectclass": "user"
},
{
'dn': "cn=%s3,%s" % (self.tag, self.base_dn),
"objectclass": "group"
},
{
'dn': "cn=%s4,%s" % (self.tag, self.service),
"objectclass": "NTDSConnection",
'enabledConnection': 'TRUE',
'fromServer': self.base_dn,
'options': '0'
},
):
try:
self.samdb.add(o)
self.fail("Failed to fail to add %s" % o['dn'])
except ldb.LdbError as e:
(ecode, emsg) = e.args
if ecode != ldb.ERR_REFERRAL:
print(emsg)
self.fail("Adding %s: ldb error: %s %s, wanted referral" %
(o['dn'], ecode, emsg))
else:
m = re.search(r'(ldap://[^>]+)>', emsg)
if m is None:
self.fail("referral seems not to refer to anything")
address = m.group(1)
try:
tmpdb = SamDB(address, credentials=CREDS,
session_info=system_session(LP), lp=LP)
tmpdb.add(o)
tmpdb.delete(o['dn'])
except ldb.LdbError as e:
self.fail("couldn't modify referred location %s" %
address)
if address.lower().startswith(self.samdb.domain_dns_name()):
self.fail("referral address did not give a specific DC")
示例3: AuthLogPassChangeTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class AuthLogPassChangeTests(samba.tests.auth_log_base.AuthLogTestBase):
def setUp(self):
super(AuthLogPassChangeTests, self).setUp()
self.remoteAddress = os.environ["CLIENT_IP"]
self.server_ip = os.environ["SERVER_IP"]
host = "ldap://%s" % os.environ["SERVER"]
self.ldb = SamDB(url=host,
session_info=system_session(),
credentials=self.get_credentials(),
lp=self.get_loadparm())
print("ldb %s" % type(self.ldb))
# Gets back the basedn
base_dn = self.ldb.domain_dn()
print("base_dn %s" % base_dn)
# permit password changes during this test
PasswordCommon.allow_password_changes(self, self.ldb)
self.base_dn = self.ldb.domain_dn()
# (Re)adds the test user USER_NAME with password USER_PASS
delete_force(self.ldb, "cn=" + USER_NAME + ",cn=users," + self.base_dn)
self.ldb.add({
"dn": "cn=" + USER_NAME + ",cn=users," + self.base_dn,
"objectclass": "user",
"sAMAccountName": USER_NAME,
"userPassword": USER_PASS
})
# discard any auth log messages for the password setup
self.discardMessages()
def tearDown(self):
super(AuthLogPassChangeTests, self).tearDown()
def test_admin_change_password(self):
def isLastExpectedMessage(msg):
return ((msg["type"] == "Authentication") and
(msg["Authentication"]["status"] == "NT_STATUS_OK") and
(msg["Authentication"]["serviceDescription"] ==
"SAMR Password Change") and
(msg["Authentication"]["authDescription"] ==
"samr_ChangePasswordUser3"))
creds = self.insta_creds(template=self.get_credentials())
lp = self.get_loadparm()
net = Net(creds, lp, server=self.server_ip)
password = "newPassword!!42"
net.change_password(newpassword=password.encode('utf-8'),
username=USER_NAME,
oldpassword=USER_PASS)
messages = self.waitForMessages(isLastExpectedMessage)
print("Received %d messages" % len(messages))
self.assertEquals(8,
len(messages),
"Did not receive the expected number of messages")
def test_admin_change_password_new_password_fails_restriction(self):
def isLastExpectedMessage(msg):
return ((msg["type"] == "Authentication") and
(msg["Authentication"]["status"] ==
"NT_STATUS_PASSWORD_RESTRICTION") and
(msg["Authentication"]["serviceDescription"] ==
"SAMR Password Change") and
(msg["Authentication"]["authDescription"] ==
"samr_ChangePasswordUser3"))
creds = self.insta_creds(template=self.get_credentials())
lp = self.get_loadparm()
net = Net(creds, lp, server=self.server_ip)
password = "newPassword"
exception_thrown = False
try:
net.change_password(newpassword=password.encode('utf-8'),
oldpassword=USER_PASS,
username=USER_NAME)
except Exception:
exception_thrown = True
self.assertEquals(True, exception_thrown,
"Expected exception not thrown")
messages = self.waitForMessages(isLastExpectedMessage)
self.assertEquals(8,
len(messages),
"Did not receive the expected number of messages")
def test_admin_change_password_unknown_user(self):
def isLastExpectedMessage(msg):
return ((msg["type"] == "Authentication") and
(msg["Authentication"]["status"] ==
"NT_STATUS_NO_SUCH_USER") and
#.........这里部分代码省略.........
示例4: PasswordTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class PasswordTests(PasswordTestCase):
def setUp(self):
super(PasswordTests, self).setUp()
self.ldb = SamDB(url=host, session_info=system_session(lp), credentials=creds, lp=lp)
# Gets back the basedn
base_dn = self.ldb.domain_dn()
# Gets back the configuration basedn
configuration_dn = self.ldb.get_config_basedn().get_linearized()
# permit password changes during this test
self.allow_password_changes()
self.base_dn = self.ldb.domain_dn()
# (Re)adds the test user "testuser" with no password atm
delete_force(self.ldb, "cn=testuser,cn=users," + self.base_dn)
self.ldb.add({
"dn": "cn=testuser,cn=users," + self.base_dn,
"objectclass": "user",
"sAMAccountName": "testuser"})
# Tests a password change when we don't have any password yet with a
# wrong old password
try:
self.ldb.modify_ldif("""
dn: cn=testuser,cn=users,""" + self.base_dn + """
changetype: modify
delete: userPassword
userPassword: noPassword
add: userPassword
userPassword: thatsAcomplPASS2
""")
self.fail()
except LdbError as e:
(num, msg) = e.args
self.assertEquals(num, ERR_CONSTRAINT_VIOLATION)
# Windows (2008 at least) seems to have some small bug here: it
# returns "0000056A" on longer (always wrong) previous passwords.
self.assertTrue('00000056' in msg)
# Sets the initial user password with a "special" password change
# I think that this internally is a password set operation and it can
# only be performed by someone which has password set privileges on the
# account (at least in s4 we do handle it like that).
self.ldb.modify_ldif("""
dn: cn=testuser,cn=users,""" + self.base_dn + """
changetype: modify
delete: userPassword
add: userPassword
userPassword: thatsAcomplPASS1
""")
# But in the other way around this special syntax doesn't work
try:
self.ldb.modify_ldif("""
dn: cn=testuser,cn=users,""" + self.base_dn + """
changetype: modify
delete: userPassword
userPassword: thatsAcomplPASS1
add: userPassword
""")
self.fail()
except LdbError as e1:
(num, _) = e1.args
self.assertEquals(num, ERR_CONSTRAINT_VIOLATION)
# Enables the user account
self.ldb.enable_account("(sAMAccountName=testuser)")
# Open a second LDB connection with the user credentials. Use the
# command line credentials for informations like the domain, the realm
# and the workstation.
creds2 = Credentials()
creds2.set_username("testuser")
creds2.set_password("thatsAcomplPASS1")
creds2.set_domain(creds.get_domain())
creds2.set_realm(creds.get_realm())
creds2.set_workstation(creds.get_workstation())
creds2.set_gensec_features(creds2.get_gensec_features()
| gensec.FEATURE_SEAL)
self.ldb2 = SamDB(url=host, credentials=creds2, lp=lp)
def test_unicodePwd_hash_set(self):
"""Performs a password hash set operation on 'unicodePwd' which should be prevented"""
# Notice: Direct hash password sets should never work
m = Message()
m.dn = Dn(self.ldb, "cn=testuser,cn=users," + self.base_dn)
m["unicodePwd"] = MessageElement("XXXXXXXXXXXXXXXX", FLAG_MOD_REPLACE,
"unicodePwd")
try:
self.ldb.modify(m)
self.fail()
except LdbError as e2:
(num, _) = e2.args
self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
#.........这里部分代码省略.........
示例5: AuditLogDsdbTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class AuditLogDsdbTests(AuditLogTestBase):
def setUp(self):
self.message_type = MSG_DSDB_LOG
self.event_type = DSDB_EVENT_NAME
super(AuditLogDsdbTests, self).setUp()
self.remoteAddress = os.environ["CLIENT_IP"]
self.server_ip = os.environ["SERVER_IP"]
host = "ldap://%s" % os.environ["SERVER"]
self.ldb = SamDB(url=host,
session_info=system_session(),
credentials=self.get_credentials(),
lp=self.get_loadparm())
self.server = os.environ["SERVER"]
# Gets back the basedn
self.base_dn = self.ldb.domain_dn()
# Get the old "dSHeuristics" if it was set
dsheuristics = self.ldb.get_dsheuristics()
# Set the "dSHeuristics" to activate the correct "userPassword"
# behaviour
self.ldb.set_dsheuristics("000000001")
# Reset the "dSHeuristics" as they were before
self.addCleanup(self.ldb.set_dsheuristics, dsheuristics)
# Get the old "minPwdAge"
minPwdAge = self.ldb.get_minPwdAge()
# Set it temporarily to "0"
self.ldb.set_minPwdAge("0")
self.base_dn = self.ldb.domain_dn()
# Reset the "minPwdAge" as it was before
self.addCleanup(self.ldb.set_minPwdAge, minPwdAge)
# (Re)adds the test user USER_NAME with password USER_PASS
delete_force(self.ldb, "cn=" + USER_NAME + ",cn=users," + self.base_dn)
self.ldb.add({
"dn": "cn=" + USER_NAME + ",cn=users," + self.base_dn,
"objectclass": "user",
"sAMAccountName": USER_NAME,
"userPassword": USER_PASS
})
#
# Discard the messages from the setup code
#
def discardSetupMessages(self, dn):
self.waitForMessages(2, dn=dn)
self.discardMessages()
def tearDown(self):
self.discardMessages()
super(AuditLogDsdbTests, self).tearDown()
def haveExpectedTxn(self, expected):
if self.context["txnMessage"] is not None:
txn = self.context["txnMessage"]["dsdbTransaction"]
if txn["transactionId"] == expected:
return True
return False
def waitForTransaction(self, expected, connection=None):
"""Wait for a transaction message to arrive
The connection is passed through to keep the connection alive
until all the logging messages have been received.
"""
self.connection = connection
start_time = time.time()
while not self.haveExpectedTxn(expected):
self.msg_ctx.loop_once(0.1)
if time.time() - start_time > 1:
self.connection = None
return ""
self.connection = None
return self.context["txnMessage"]
def test_net_change_password(self):
dn = "CN=" + USER_NAME + ",CN=Users," + self.base_dn
self.discardSetupMessages(dn)
creds = self.insta_creds(template=self.get_credentials())
lp = self.get_loadparm()
net = Net(creds, lp, server=self.server)
password = "newPassword!!42"
net.change_password(newpassword=password.encode('utf-8'),
username=USER_NAME,
oldpassword=USER_PASS)
#.........这里部分代码省略.........
示例6: VLVTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class VLVTests(samba.tests.TestCase):
def create_user(self, i, n, prefix='vlvtest', suffix='', attrs=None):
name = "%s%d%s" % (prefix, i, suffix)
user = {
'cn': name,
"objectclass": "user",
'givenName': "abcdefghijklmnopqrstuvwxyz"[i % 26],
"roomNumber": "%sbc" % (n - i),
"carLicense": "后来经",
"employeeNumber": "%s%sx" % (abs(i * (99 - i)), '\n' * (i & 255)),
"accountExpires": "%s" % (10 ** 9 + 1000000 * i),
"msTSExpireDate4": "19%02d0101010000.0Z" % (i % 100),
"flags": str(i * (n - i)),
"serialNumber": "abc %s%s%s" % ('AaBb |-/'[i & 7],
' 3z}'[i & 3],
'"@'[i & 1],),
}
# _user_broken_attrs tests are broken due to problems outside
# of VLV.
_user_broken_attrs = {
# Sort doesn't look past a NUL byte.
"photo": "\x00%d" % (n - i),
"audio": "%sn octet string %s%s ♫♬\x00lalala" % ('Aa'[i & 1],
chr(i & 255), i),
"displayNamePrintable": "%d\x00%c" % (i, i & 255),
"adminDisplayName": "%d\x00b" % (n-i),
"title": "%d%sb" % (n - i, '\x00' * i),
"comment": "Favourite colour is %d" % (n % (i + 1)),
# Names that vary only in case. Windows returns
# equivalent addresses in the order they were put
# in ('a st', 'A st',...).
"street": "%s st" % (chr(65 | (i & 14) | ((i & 1) * 32))),
}
if attrs is not None:
user.update(attrs)
user['dn'] = "cn=%s,%s" % (user['cn'], self.ou)
if opts.skip_attr_regex:
match = re.compile(opts.skip_attr_regex).search
for k in user.keys():
if match(k):
del user[k]
self.users.append(user)
self.ldb.add(user)
return user
def setUp(self):
super(VLVTests, self).setUp()
self.ldb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp)
self.base_dn = self.ldb.domain_dn()
self.ou = "ou=vlv,%s" % self.base_dn
if opts.delete_in_setup:
try:
self.ldb.delete(self.ou, ['tree_delete:1'])
except ldb.LdbError as e:
print("tried deleting %s, got error %s" % (self.ou, e))
self.ldb.add({
"dn": self.ou,
"objectclass": "organizationalUnit"})
self.users = []
for i in range(N_ELEMENTS):
self.create_user(i, N_ELEMENTS)
attrs = self.users[0].keys()
self.binary_sorted_keys = ['audio',
'photo',
"msTSExpireDate4",
'serialNumber',
"displayNamePrintable"]
self.numeric_sorted_keys = ['flags',
'accountExpires']
self.timestamp_keys = ['msTSExpireDate4']
self.int64_keys = set(['accountExpires'])
self.locale_sorted_keys = [x for x in attrs if
x not in (self.binary_sorted_keys +
self.numeric_sorted_keys)]
# don't try spaces, etc in cn
self.delicate_keys = ['cn']
def tearDown(self):
super(VLVTests, self).tearDown()
if not opts.delete_in_setup:
self.ldb.delete(self.ou, ['tree_delete:1'])
def get_full_list(self, attr, include_cn=False):
"""Fetch the whole list sorted on the attribute, using the VLV.
#.........这里部分代码省略.........
示例7: PassWordHashTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class PassWordHashTests(TestCase):
def setUp(self):
super(PassWordHashTests, self).setUp()
# Add a user to ldb, this will exercise the password_hash code
# and calculate the appropriate supplemental credentials
def add_user(self, options=None, clear_text=False):
self.lp = samba.tests.env_loadparm()
# set any needed options
if options is not None:
for (option,value) in options:
self.lp.set(option, value)
self.creds = Credentials()
self.session = system_session()
self.ldb = SamDB(
session_info=self.session,
credentials=self.creds,
lp=self.lp)
# Gets back the basedn
base_dn = self.ldb.domain_dn()
# Gets back the configuration basedn
configuration_dn = self.ldb.get_config_basedn().get_linearized()
# Get the old "dSHeuristics" if it was set
dsheuristics = self.ldb.get_dsheuristics()
# Set the "dSHeuristics" to activate the correct "userPassword"
# behaviour
self.ldb.set_dsheuristics("000000001")
# Reset the "dSHeuristics" as they were before
self.addCleanup(self.ldb.set_dsheuristics, dsheuristics)
# Get the old "minPwdAge"
minPwdAge = self.ldb.get_minPwdAge()
# Set it temporarily to "0"
self.ldb.set_minPwdAge("0")
self.base_dn = self.ldb.domain_dn()
# Reset the "minPwdAge" as it was before
self.addCleanup(self.ldb.set_minPwdAge, minPwdAge)
account_control = 0
if clear_text:
# get the current pwdProperties
pwdProperties = self.ldb.get_pwdProperties()
# enable clear text properties
props = int(pwdProperties)
props |= DOMAIN_PASSWORD_STORE_CLEARTEXT
self.ldb.set_pwdProperties(str(props))
# Restore the value on exit.
self.addCleanup(self.ldb.set_pwdProperties, pwdProperties)
account_control |= UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED
# (Re)adds the test user USER_NAME with password USER_PASS
# and userPrincipalName UPN
delete_force(self.ldb, "cn=" + USER_NAME + ",cn=users," + self.base_dn)
self.ldb.add({
"dn": "cn=" + USER_NAME + ",cn=users," + self.base_dn,
"objectclass": "user",
"sAMAccountName": USER_NAME,
"userPassword": USER_PASS,
"userPrincipalName": UPN,
"userAccountControl": str(account_control)
})
# Get the supplemental credentials for the user under test
def get_supplemental_creds(self):
base = "cn=" + USER_NAME + ",cn=users," + self.base_dn
res = self.ldb.search(scope=ldb.SCOPE_BASE,
base=base,
attrs=["supplementalCredentials"])
self.assertIs( True, len(res) > 0)
obj = res[0]
sc_blob = obj["supplementalCredentials"][0]
sc = ndr_unpack(drsblobs.supplementalCredentialsBlob, sc_blob)
return sc
# Calculate and validate a Wdigest value
def check_digest(self, user, realm, password, digest):
expected = calc_digest( user, realm, password)
actual = binascii.hexlify(bytearray(digest))
error = "Digest expected[%s], actual[%s], " \
"user[%s], realm[%s], pass[%s]" % \
(expected, actual, user, realm, password)
self.assertEquals(expected, actual, error)
# Check all of the 29 expected WDigest values
#
def check_wdigests(self, digests):
self.assertEquals(29, digests.num_hashes)
self.check_digest(USER_NAME,
self.lp.get("workgroup"),
#.........这里部分代码省略.........
示例8: test_rid_set_dbcheck_after_seize
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
def test_rid_set_dbcheck_after_seize(self):
"""Perform a join against the RID manager and assert we have a RID Set.
We seize the RID master role, then using dbcheck, we assert that we can
detect out of range users (and then bump the RID set as required)."""
fsmo_dn = ldb.Dn(self.ldb_dc1, "CN=RID Manager$,CN=System," + self.ldb_dc1.domain_dn())
(fsmo_owner, fsmo_not_owner) = self._determine_fSMORoleOwner(fsmo_dn)
targetdir = self._test_join(fsmo_owner['dns_name'], "RIDALLOCTEST7")
try:
# Connect to the database
ldb_url = "tdb://%s" % os.path.join(targetdir, "private/sam.ldb")
smbconf = os.path.join(targetdir, "etc/smb.conf")
lp = self.get_loadparm()
new_ldb = SamDB(ldb_url, credentials=self.get_credentials(),
session_info=system_session(lp), lp=lp)
# 1. Get server name
res = new_ldb.search(base=ldb.Dn(new_ldb, new_ldb.get_serverName()),
scope=ldb.SCOPE_BASE, attrs=["serverReference"])
# 2. Get server reference
server_ref_dn = ldb.Dn(new_ldb, res[0]['serverReference'][0])
# 3. Assert we get the RID Set
res = new_ldb.search(base=server_ref_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDSetReferences'])
self.assertTrue("rIDSetReferences" in res[0])
rid_set_dn = ldb.Dn(new_ldb, res[0]["rIDSetReferences"][0])
# 4. Seize the RID Manager role
(result, out, err) = self.runsubcmd("fsmo", "seize", "--role", "rid", "-H", ldb_url, "-s", smbconf, "--force")
self.assertCmdSuccess(result, out, err)
self.assertEquals(err,"","Shouldn't be any error messages")
# 5. Add a new user (triggers RID set work)
new_ldb.newuser("ridalloctestuser", "[email protected]!")
# 6. Now fetch the RID SET
rid_set_res = new_ldb.search(base=rid_set_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDNextRid',
'rIDAllocationPool'])
next_pool = int(rid_set_res[0]["rIDAllocationPool"][0])
last_rid = (0xFFFFFFFF00000000 & next_pool) >> 32
# 7. Add user above the ridNextRid and at almost the end of the range.
#
m = ldb.Message()
m.dn = ldb.Dn(new_ldb, "CN=ridsettestuser2,CN=Users")
m.dn.add_base(new_ldb.get_default_basedn())
m['objectClass'] = ldb.MessageElement('user', ldb.FLAG_MOD_ADD, 'objectClass')
m['objectSid'] = ldb.MessageElement(ndr_pack(security.dom_sid(str(new_ldb.get_domain_sid()) + "-%d" % (last_rid - 3))),
ldb.FLAG_MOD_ADD,
'objectSid')
new_ldb.add(m, controls=["relax:0"])
# 8. Add user above the ridNextRid and at the end of the range
m = ldb.Message()
m.dn = ldb.Dn(new_ldb, "CN=ridsettestuser3,CN=Users")
m.dn.add_base(new_ldb.get_default_basedn())
m['objectClass'] = ldb.MessageElement('user', ldb.FLAG_MOD_ADD, 'objectClass')
m['objectSid'] = ldb.MessageElement(ndr_pack(security.dom_sid(str(new_ldb.get_domain_sid()) + "-%d" % last_rid)),
ldb.FLAG_MOD_ADD,
'objectSid')
new_ldb.add(m, controls=["relax:0"])
chk = dbcheck(new_ldb, verbose=False, fix=True, yes=True, quiet=True)
# Should have fixed two errors (wrong ridNextRid)
self.assertEqual(chk.check_database(DN=rid_set_dn, scope=ldb.SCOPE_BASE), 2)
# 9. Assert we get didn't show any other errors
chk = dbcheck(new_ldb, verbose=False, fix=False, quiet=True)
# 10. Add another user (checks RID rollover)
# We have seized the role, so we can do that.
new_ldb.newuser("ridalloctestuser3", "[email protected]!")
rid_set_res = new_ldb.search(base=rid_set_dn,
scope=ldb.SCOPE_BASE, attrs=['rIDNextRid',
'rIDAllocationPool'])
next_pool = int(rid_set_res[0]["rIDAllocationPool"][0])
self.assertNotEqual(last_rid, (0xFFFFFFFF00000000 & next_pool) >> 32, "rid pool should have changed")
finally:
self._test_force_demote(fsmo_owner['dns_name'], "RIDALLOCTEST7")
shutil.rmtree(targetdir, ignore_errors=True)
示例9: LATests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class LATests(samba.tests.TestCase):
def setUp(self):
super(LATests, self).setUp()
self.samdb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp)
self.base_dn = self.samdb.domain_dn()
self.ou = "OU=la,%s" % self.base_dn
if opts.delete_in_setup:
try:
self.samdb.delete(self.ou, ['tree_delete:1'])
except ldb.LdbError as e:
print("tried deleting %s, got error %s" % (self.ou, e))
self.samdb.add({'objectclass': 'organizationalUnit',
'dn': self.ou})
def tearDown(self):
super(LATests, self).tearDown()
if not opts.no_cleanup:
self.samdb.delete(self.ou, ['tree_delete:1'])
def add_object(self, cn, objectclass, more_attrs={}):
dn = "CN=%s,%s" % (cn, self.ou)
attrs = {'cn': cn,
'objectclass': objectclass,
'dn': dn}
attrs.update(more_attrs)
self.samdb.add(attrs)
return dn
def add_objects(self, n, objectclass, prefix=None, more_attrs={}):
if prefix is None:
prefix = objectclass
dns = []
for i in range(n):
dns.append(self.add_object("%s%d" % (prefix, i + 1),
objectclass,
more_attrs=more_attrs))
return dns
def add_linked_attribute(self, src, dest, attr='member',
controls=None):
m = ldb.Message()
m.dn = ldb.Dn(self.samdb, src)
m[attr] = ldb.MessageElement(dest, ldb.FLAG_MOD_ADD, attr)
self.samdb.modify(m, controls=controls)
def remove_linked_attribute(self, src, dest, attr='member',
controls=None):
m = ldb.Message()
m.dn = ldb.Dn(self.samdb, src)
m[attr] = ldb.MessageElement(dest, ldb.FLAG_MOD_DELETE, attr)
self.samdb.modify(m, controls=controls)
def replace_linked_attribute(self, src, dest, attr='member',
controls=None):
m = ldb.Message()
m.dn = ldb.Dn(self.samdb, src)
m[attr] = ldb.MessageElement(dest, ldb.FLAG_MOD_REPLACE, attr)
self.samdb.modify(m, controls=controls)
def attr_search(self, obj, attr, scope=ldb.SCOPE_BASE, **controls):
if opts.no_reveal_internals:
if 'reveal_internals' in controls:
del controls['reveal_internals']
controls = ['%s:%d' % (k, int(v)) for k, v in controls.items()]
res = self.samdb.search(obj,
scope=scope,
attrs=[attr],
controls=controls)
return res
def assert_links(self, obj, expected, attr, msg='', **kwargs):
res = self.attr_search(obj, attr, **kwargs)
if len(expected) == 0:
if attr in res[0]:
self.fail("found attr '%s' in %s" % (attr, res[0]))
return
try:
results = list([x[attr] for x in res][0])
except KeyError:
self.fail("missing attr '%s' on %s" % (attr, obj))
expected = sorted(expected)
results = sorted(results)
if expected != results:
print(msg)
print("expected %s" % expected)
print("received %s" % results)
self.assertEqual(results, expected)
def assert_back_links(self, obj, expected, attr='memberOf', **kwargs):
#.........这里部分代码省略.........
示例10: UserTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class UserTests(samba.tests.TestCase):
def add_if_possible(self, *args, **kwargs):
"""In these tests sometimes things are left in the database
deliberately, so we don't worry if we fail to add them a second
time."""
try:
self.ldb.add(*args, **kwargs)
except LdbError:
pass
def setUp(self):
super(UserTests, self).setUp()
self.state = GlobalState # the class itself, not an instance
self.lp = lp
self.ldb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp)
self.base_dn = self.ldb.domain_dn()
self.ou = "OU=pid%s,%s" % (os.getpid(), self.base_dn)
self.ou_users = "OU=users,%s" % self.ou
self.ou_groups = "OU=groups,%s" % self.ou
self.ou_computers = "OU=computers,%s" % self.ou
for dn in (self.ou, self.ou_users, self.ou_groups,
self.ou_computers):
self.add_if_possible({
"dn": dn,
"objectclass": "organizationalUnit"})
def tearDown(self):
super(UserTests, self).tearDown()
def test_00_00_do_nothing(self):
# this gives us an idea of the overhead
pass
def _prepare_n_groups(self, n):
self.state.n_groups = n
for i in range(n):
self.add_if_possible({
"dn": "cn=g%d,%s" % (i, self.ou_groups),
"objectclass": "group"})
def _add_users(self, start, end):
for i in range(start, end):
self.ldb.add({
"dn": "cn=u%d,%s" % (i, self.ou_users),
"objectclass": "user"})
def _test_join(self):
tmpdir = tempfile.mkdtemp()
if '://' in host:
server = host.split('://', 1)[1]
else:
server = host
cmd = cmd_sambatool.subcommands['domain'].subcommands['join']
result = cmd._run("samba-tool domain join",
creds.get_realm(),
"dc", "-U%s%%%s" % (creds.get_username(),
creds.get_password()),
'--targetdir=%s' % tmpdir,
'--server=%s' % server)
shutil.rmtree(tmpdir)
def _test_unindexed_search(self):
expressions = [
('(&(objectclass=user)(description='
'Built-in account for adminstering the computer/domain))'),
'(description=Built-in account for adminstering the computer/domain)',
'(objectCategory=*)',
'(samaccountname=Administrator*)'
]
for expression in expressions:
t = time.time()
for i in range(10):
self.ldb.search(self.ou,
expression=expression,
scope=SCOPE_SUBTREE,
attrs=['cn'])
print('%d %s took %s' % (i, expression,
time.time() - t), file=sys.stderr)
def _test_indexed_search(self):
expressions = ['(objectclass=group)',
'(samaccountname=Administrator)'
]
for expression in expressions:
t = time.time()
for i in range(100):
self.ldb.search(self.ou,
expression=expression,
scope=SCOPE_SUBTREE,
attrs=['cn'])
print('%d runs %s took %s' % (i, expression,
time.time() - t), file=sys.stderr)
def _test_add_many_users(self, n=BATCH_SIZE):
s = self.state.next_user_id
e = s + n
#.........这里部分代码省略.........
示例11: UserTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class UserTests(samba.tests.TestCase):
def add_if_possible(self, *args, **kwargs):
"""In these tests sometimes things are left in the database
deliberately, so we don't worry if we fail to add them a second
time."""
try:
self.ldb.add(*args, **kwargs)
except LdbError:
pass
def setUp(self):
super(UserTests, self).setUp()
self.state = GlobalState # the class itself, not an instance
self.lp = lp
self.ldb = SamDB(host, credentials=creds,
session_info=system_session(lp), lp=lp)
self.base_dn = self.ldb.domain_dn()
self.ou = "OU=pid%s,%s" % (os.getpid(), self.base_dn)
self.ou_users = "OU=users,%s" % self.ou
self.ou_groups = "OU=groups,%s" % self.ou
self.ou_computers = "OU=computers,%s" % self.ou
for dn in (self.ou, self.ou_users, self.ou_groups,
self.ou_computers):
self.add_if_possible({
"dn": dn,
"objectclass": "organizationalUnit"})
def tearDown(self):
super(UserTests, self).tearDown()
def test_00_00_do_nothing(self):
# this gives us an idea of the overhead
pass
def _prepare_n_groups(self, n):
self.state.n_groups = n
for i in range(n):
self.add_if_possible({
"dn": "cn=g%d,%s" % (i, self.ou_groups),
"objectclass": "group"})
def _add_users(self, start, end):
for i in range(start, end):
self.ldb.add({
"dn": "cn=u%d,%s" % (i, self.ou_users),
"objectclass": "user"})
def _add_users_ldif(self, start, end):
lines = []
for i in range(start, end):
lines.append("dn: cn=u%d,%s" % (i, self.ou_users))
lines.append("objectclass: user")
lines.append("")
self.ldb.add_ldif('\n'.join(lines))
def _test_unindexed_search(self):
expressions = [
('(&(objectclass=user)(description='
'Built-in account for adminstering the computer/domain))'),
'(description=Built-in account for adminstering the computer/domain)',
'(objectCategory=*)',
'(samaccountname=Administrator*)'
]
for expression in expressions:
t = time.time()
for i in range(50):
self.ldb.search(self.ou,
expression=expression,
scope=SCOPE_SUBTREE,
attrs=['cn'])
print >> sys.stderr, '%d %s took %s' % (i, expression,
time.time() - t)
def _test_indexed_search(self):
expressions = ['(objectclass=group)',
'(samaccountname=Administrator)'
]
for expression in expressions:
t = time.time()
for i in range(10000):
self.ldb.search(self.ou,
expression=expression,
scope=SCOPE_SUBTREE,
attrs=['cn'])
print >> sys.stderr, '%d runs %s took %s' % (i, expression,
time.time() - t)
def _test_complex_search(self):
classes = ['samaccountname', 'objectCategory', 'dn', 'member']
values = ['*', '*t*', 'g*', 'user']
comparators = ['=', '<=', '>='] # '~=' causes error
maybe_not = ['!(', '']
joiners = ['&', '|']
# The number of permuations is 18432, which is not huge but
# would take hours to search. So we take a sample.
all_permutations = list(itertools.product(joiners,
classes, classes,
#.........这里部分代码省略.........
示例12: AuthLogTestsNetLogon
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class AuthLogTestsNetLogon(samba.tests.auth_log_base.AuthLogTestBase):
def setUp(self):
super(AuthLogTestsNetLogon, self).setUp()
self.lp = samba.tests.env_loadparm()
self.creds = Credentials()
self.session = system_session()
self.ldb = SamDB(
session_info=self.session,
credentials=self.creds,
lp=self.lp)
self.domain = os.environ["DOMAIN"]
self.netbios_name = "NetLogonGood"
self.machinepass = "abcdefghij"
self.remoteAddress = AS_SYSTEM_MAGIC_PATH_TOKEN
self.base_dn = self.ldb.domain_dn()
self.dn = ("cn=%s,cn=users,%s" %
(self.netbios_name, self.base_dn))
utf16pw = unicode(
'"' + self.machinepass.encode('utf-8') + '"', 'utf-8'
).encode('utf-16-le')
self.ldb.add({
"dn": self.dn,
"objectclass": "computer",
"sAMAccountName": "%s$" % self.netbios_name,
"userAccountControl":
str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
"unicodePwd": utf16pw})
def tearDown(self):
super(AuthLogTestsNetLogon, self).tearDown()
delete_force(self.ldb, self.dn)
def _test_netlogon(self, binding, checkFunction):
def isLastExpectedMessage(msg):
return (
msg["type"] == "Authorization" and
msg["Authorization"]["serviceDescription"] == "DCE/RPC" and
msg["Authorization"]["authType"] == "schannel" and
msg["Authorization"]["transportProtection"] == "SEAL")
if binding:
binding = "[schannel,%s]" % binding
else:
binding = "[schannel]"
machine_creds = Credentials()
machine_creds.guess(self.get_loadparm())
machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
machine_creds.set_password(self.machinepass)
machine_creds.set_username(self.netbios_name + "$")
netlogon_conn = netlogon.netlogon("ncalrpc:%s" % binding,
self.get_loadparm(),
machine_creds)
messages = self.waitForMessages(isLastExpectedMessage, netlogon_conn)
checkFunction(messages)
def netlogon_check(self, messages):
expected_messages = 5
self.assertEquals(expected_messages,
len(messages),
"Did not receive the expected number of messages")
# Check the first message it should be an Authorization
msg = messages[0]
self.assertEquals("Authorization", msg["type"])
self.assertEquals("DCE/RPC",
msg["Authorization"]["serviceDescription"])
self.assertEquals("ncalrpc", msg["Authorization"]["authType"])
self.assertEquals("NONE", msg["Authorization"]["transportProtection"])
self.assertTrue(self.is_guid(msg["Authorization"]["sessionId"]))
# Check the fourth message it should be a NETLOGON Authentication
msg = messages[3]
self.assertEquals("Authentication", msg["type"])
self.assertEquals("NETLOGON",
msg["Authentication"]["serviceDescription"])
self.assertEquals("ServerAuthenticate",
msg["Authentication"]["authDescription"])
self.assertEquals("NT_STATUS_OK",
msg["Authentication"]["status"])
self.assertEquals("HMAC-SHA256",
msg["Authentication"]["passwordType"])
def test_netlogon(self):
self._test_netlogon("SEAL", self.netlogon_check)
示例13: DsdbTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class DsdbTests(TestCase):
def setUp(self):
super(DsdbTests, self).setUp()
self.lp = samba.tests.env_loadparm()
self.creds = Credentials()
self.creds.guess(self.lp)
self.session = system_session()
self.samdb = SamDB(session_info=self.session,
credentials=self.creds,
lp=self.lp)
# Create a test user
user_name = "dsdb-user-" + str(uuid.uuid4().hex[0:6])
user_pass = samba.generate_random_password(32, 32)
user_description = "Test user for dsdb test"
base_dn = self.samdb.domain_dn()
self.account_dn = "cn=" + user_name + ",cn=Users," + base_dn
self.samdb.newuser(username=user_name,
password=user_pass,
description=user_description)
# Cleanup (teardown)
self.addCleanup(delete_force, self.samdb, self.account_dn)
def test_get_oid_from_attrid(self):
oid = self.samdb.get_oid_from_attid(591614)
self.assertEquals(oid, "1.2.840.113556.1.4.1790")
def test_error_replpropertymetadata(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
ctr = repl.ctr
for o in ctr.array:
# Search for Description
if o.attid == 13:
old_version = o.version
o.version = o.version + 1
replBlob = ndr_pack(repl)
msg = ldb.Message()
msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, "replPropertyMetaData")
self.assertRaises(ldb.LdbError, self.samdb.modify, msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
def test_error_replpropertymetadata_nochange(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
replBlob = ndr_pack(repl)
msg = ldb.Message()
msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, "replPropertyMetaData")
self.assertRaises(ldb.LdbError, self.samdb.modify, msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
def test_error_replpropertymetadata_allow_sort(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
replBlob = ndr_pack(repl)
msg = ldb.Message()
msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, "replPropertyMetaData")
self.samdb.modify(msg, ["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"])
def test_twoatt_replpropertymetadata(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData", "uSNChanged"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
ctr = repl.ctr
for o in ctr.array:
# Search for Description
if o.attid == 13:
old_version = o.version
o.version = o.version + 1
o.local_usn = int(str(res[0]["uSNChanged"])) + 1
replBlob = ndr_pack(repl)
msg = ldb.Message()
msg.dn = res[0].dn
msg["replPropertyMetaData"] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, "replPropertyMetaData")
msg["description"] = ldb.MessageElement("new val", ldb.FLAG_MOD_REPLACE, "description")
self.assertRaises(ldb.LdbError, self.samdb.modify, msg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"])
def test_set_replpropertymetadata(self):
res = self.samdb.search(scope=ldb.SCOPE_SUBTREE,
base=self.account_dn,
attrs=["replPropertyMetaData", "uSNChanged"])
repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
res[0]["replPropertyMetaData"][0])
ctr = repl.ctr
for o in ctr.array:
#.........这里部分代码省略.........
示例14: PyCredentialsTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
#.........这里部分代码省略.........
pwd.data = filler + [ord(x) for x in encoded]
self.machine_creds.encrypt_netr_crypt_password(pwd)
c.netr_ServerPasswordSet2(self.server,
self.machine_creds.get_workstation(),
SEC_CHAN_WKSTA,
self.machine_name,
authenticator,
pwd)
self.machine_pass = newpass
self.machine_creds.set_password(newpass)
# Establish sealed schannel netlogon connection over TCP/IP
#
def get_netlogon_connection(self):
return netlogon.netlogon("ncacn_ip_tcp:%s[schannel,seal]" % self.server,
self.lp,
self.machine_creds)
#
# Create the machine account
def create_machine_account(self):
self.machine_pass = samba.generate_random_password(32, 32)
self.machine_name = MACHINE_NAME
self.machine_dn = "cn=%s,%s" % (self.machine_name, self.ldb.domain_dn())
# remove the account if it exists, this will happen if a previous test
# run failed
delete_force(self.ldb, self.machine_dn)
utf16pw = unicode(
'"' + self.machine_pass.encode('utf-8') + '"', 'utf-8'
).encode('utf-16-le')
self.ldb.add({
"dn": self.machine_dn,
"objectclass": "computer",
"sAMAccountName": "%s$" % self.machine_name,
"userAccountControl":
str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
"unicodePwd": utf16pw})
self.machine_creds = Credentials()
self.machine_creds.guess(self.get_loadparm())
self.machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
self.machine_creds.set_kerberos_state(DONT_USE_KERBEROS)
self.machine_creds.set_password(self.machine_pass)
self.machine_creds.set_username(self.machine_name + "$")
self.machine_creds.set_workstation(self.machine_name)
#
# Create a test user account
def create_user_account(self):
self.user_pass = samba.generate_random_password(32, 32)
self.user_name = USER_NAME
self.user_dn = "cn=%s,%s" % (self.user_name, self.ldb.domain_dn())
# remove the account if it exists, this will happen if a previous test
# run failed
delete_force(self.ldb, self.user_dn)
utf16pw = unicode(
'"' + self.user_pass.encode('utf-8') + '"', 'utf-8'
).encode('utf-16-le')
self.ldb.add({
"dn": self.user_dn,
"objectclass": "user",
示例15: RodcTests
# 需要导入模块: from samba.samdb import SamDB [as 别名]
# 或者: from samba.samdb.SamDB import add [as 别名]
class RodcTests(samba.tests.TestCase):
def setUp(self):
super(RodcTests, self).setUp()
self.samdb = SamDB(HOST, credentials=CREDS,
session_info=system_session(LP), lp=LP)
self.base_dn = self.samdb.domain_dn()
root = self.samdb.search(base='', scope=ldb.SCOPE_BASE,
attrs=['dsServiceName'])
self.service = root[0]['dsServiceName'][0]
self.tag = uuid.uuid4().hex
def test_add_replicated_objects(self):
for o in (
{
'dn': "ou=%s1,%s" % (self.tag, self.base_dn),
"objectclass": "organizationalUnit"
},
{
'dn': "cn=%s2,%s" % (self.tag, self.base_dn),
"objectclass": "user"
},
{
'dn': "cn=%s3,%s" % (self.tag, self.base_dn),
"objectclass": "group"
},
{
'dn': "cn=%s4,%s" % (self.tag, self.service),
"objectclass": "NTDSConnection",
'enabledConnection': 'TRUE',
'fromServer': self.base_dn,
'options': '0'
},
):
try:
self.samdb.add(o)
self.fail("Failed to fail to add %s" % o['dn'])
except ldb.LdbError as e:
(ecode, emsg) = e.args
if ecode != ldb.ERR_REFERRAL:
print(emsg)
self.fail("Adding %s: ldb error: %s %s, wanted referral" %
(o['dn'], ecode, emsg))
else:
m = re.search(r'(ldap://[^>]+)>', emsg)
if m is None:
self.fail("referral seems not to refer to anything")
address = m.group(1)
try:
tmpdb = SamDB(address, credentials=CREDS,
session_info=system_session(LP), lp=LP)
tmpdb.add(o)
tmpdb.delete(o['dn'])
except ldb.LdbError as e:
self.fail("couldn't modify referred location %s" %
address)
if address.lower().startswith(self.samdb.domain_dns_name()):
self.fail("referral address did not give a specific DC")
def test_modify_replicated_attributes(self):
# some timestamp ones
dn = 'CN=Guest,CN=Users,' + self.base_dn
value = 'hallooo'
for attr in ['carLicense', 'middleName']:
msg = ldb.Message()
msg.dn = ldb.Dn(self.samdb, dn)
msg[attr] = ldb.MessageElement(value,
ldb.FLAG_MOD_REPLACE,
attr)
try:
self.samdb.modify(msg)
self.fail("Failed to fail to modify %s %s" % (dn, attr))
except ldb.LdbError as e1:
(ecode, emsg) = e1.args
if ecode != ldb.ERR_REFERRAL:
self.fail("Failed to REFER when trying to modify %s %s" %
(dn, attr))
else:
m = re.search(r'(ldap://[^>]+)>', emsg)
if m is None:
self.fail("referral seems not to refer to anything")
address = m.group(1)
try:
tmpdb = SamDB(address, credentials=CREDS,
session_info=system_session(LP), lp=LP)
tmpdb.modify(msg)
except ldb.LdbError as e:
self.fail("couldn't modify referred location %s" %
address)
if address.lower().startswith(self.samdb.domain_dns_name()):
self.fail("referral address did not give a specific DC")
def test_modify_nonreplicated_attributes(self):
# some timestamp ones
#.........这里部分代码省略.........