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

PEP8: fix E302: expected 2 blank lines, found 1

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:20:39 +12:00 committed by Douglas Bagnall
parent 542e91ef92
commit 211c9a5f85
180 changed files with 480 additions and 0 deletions

View File

@ -252,6 +252,7 @@ else:
SOURCE_EXTENSIONS = [ '.C', '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]
def DirectoryOfThisScript():
return os.path.dirname( os.path.abspath( __file__ ) )

View File

@ -46,6 +46,7 @@ creds_user2 = copy.deepcopy(creds)
creds_user3 = copy.deepcopy(creds)
creds_user4 = copy.deepcopy(creds)
class BindTests(samba.tests.TestCase):
info_dc = None

View File

@ -22,6 +22,8 @@ from ldb import SCOPE_BASE, SCOPE_SUBTREE, SCOPE_ONELEVEL
# This should be fixed to work inline with Windows.
# The literal strings are in the case Windows uses.
# Windows appear to preserve casing of the RDN and uppercase the other keys.
class MatchRulesTests(samba.tests.TestCase):
def setUp(self):
super(MatchRulesTests, self).setUp()
@ -943,6 +945,7 @@ class MatchRulesTests(samba.tests.TestCase):
expression="memberOf:1.2.840.113556.1.4.1941:=cn=g1,%s" % self.ou_groups)
self.assertEqual(len(res1), 0)
class MatchRuleConditionTests(samba.tests.TestCase):
def setUp(self):
super(MatchRuleConditionTests, self).setUp()

View File

@ -22,6 +22,7 @@ MDB_INDEX_OBJ = {
"@IDX_DN_GUID": [b"GUID"]
}
def tempdir():
import tempfile
try:
@ -685,6 +686,8 @@ class SimpleLdb(LdbBaseTest):
self.assertRaises(ldb.LdbError, lambda: l.search("", ldb.SCOPE_SUBTREE, "&(dc=*)(dn=*)", ["dc"]))
# Run the SimpleLdb tests against an lmdb backend
class SimpleLdbLmdb(SimpleLdb):
def setUp(self):
@ -695,6 +698,7 @@ class SimpleLdbLmdb(SimpleLdb):
def tearDown(self):
super(SimpleLdbLmdb, self).tearDown()
class SearchTests(LdbBaseTest):
def tearDown(self):
shutil.rmtree(self.testdir)
@ -1367,6 +1371,7 @@ class IndexedSearchTests(SearchTests):
"@IDXATTR": [b"x", b"y", b"ou"]})
self.IDX = True
class IndexedCheckSearchTests(IndexedSearchTests):
"""Test searches using the index, to ensure the index doesn't
break things (full scan disabled)"""
@ -1375,6 +1380,7 @@ class IndexedCheckSearchTests(IndexedSearchTests):
self.IDXCHECK = True
super(IndexedCheckSearchTests, self).setUp()
class IndexedSearchDnFilterTests(SearchTests):
"""Test searches using the index, to ensure the index doesn't
break things"""
@ -1389,6 +1395,7 @@ class IndexedSearchDnFilterTests(SearchTests):
"@IDXATTR": [b"x", b"y", b"ou"]})
self.IDX = True
class IndexedAndOneLevelSearchTests(SearchTests):
"""Test searches using the index including @IDXONE, to ensure
the index doesn't break things"""
@ -1401,6 +1408,7 @@ class IndexedAndOneLevelSearchTests(SearchTests):
self.IDX = True
self.IDXONE = True
class IndexedCheckedAndOneLevelSearchTests(IndexedAndOneLevelSearchTests):
"""Test searches using the index including @IDXONE, to ensure
the index doesn't break things (full scan disabled)"""
@ -1409,6 +1417,7 @@ class IndexedCheckedAndOneLevelSearchTests(IndexedAndOneLevelSearchTests):
self.IDXCHECK = True
super(IndexedCheckedAndOneLevelSearchTests, self).setUp()
class IndexedAndOneLevelDNFilterSearchTests(SearchTests):
"""Test searches using the index including @IDXONE, to ensure
the index doesn't break things"""
@ -1427,6 +1436,7 @@ class IndexedAndOneLevelDNFilterSearchTests(SearchTests):
self.IDX = True
self.IDXONE = True
class GUIDIndexedSearchTests(SearchTests):
"""Test searches using the index, to ensure the index doesn't
break things"""
@ -1460,6 +1470,7 @@ class GUIDIndexedDNFilterSearchTests(SearchTests):
self.IDX = True
self.IDXGUID = True
class GUIDAndOneLevelIndexedSearchTests(SearchTests):
"""Test searches using the index including @IDXONE, to ensure
the index doesn't break things"""
@ -1479,6 +1490,7 @@ class GUIDAndOneLevelIndexedSearchTests(SearchTests):
self.IDXGUID = True
self.IDXONE = True
class GUIDIndexedSearchTestsLmdb(GUIDIndexedSearchTests):
def setUp(self):
@ -1719,6 +1731,7 @@ class AddModifyTestsLmdb(AddModifyTests):
def tearDown(self):
super(AddModifyTestsLmdb, self).tearDown()
class IndexedAddModifyTests(AddModifyTests):
"""Test searches using the index, to ensure the index doesn't
break things"""
@ -1798,6 +1811,7 @@ class IndexedAddModifyTests(AddModifyTests):
"x": "z", "y": "a",
"objectUUID": b"0123456789abcde2"})
class GUIDIndexedAddModifyTests(IndexedAddModifyTests):
"""Test searches using the index, to ensure the index doesn't
break things"""
@ -1822,6 +1836,7 @@ class GUIDTransIndexedAddModifyTests(GUIDIndexedAddModifyTests):
self.l.transaction_commit()
super(GUIDTransIndexedAddModifyTests, self).tearDown()
class TransIndexedAddModifyTests(IndexedAddModifyTests):
"""Test index behaviour insdie the transaction"""
@ -1833,6 +1848,7 @@ class TransIndexedAddModifyTests(IndexedAddModifyTests):
self.l.transaction_commit()
super(TransIndexedAddModifyTests, self).tearDown()
class GuidIndexedAddModifyTestsLmdb(GUIDIndexedAddModifyTests):
def setUp(self):
@ -1842,6 +1858,7 @@ class GuidIndexedAddModifyTestsLmdb(GUIDIndexedAddModifyTests):
def tearDown(self):
super(GuidIndexedAddModifyTestsLmdb, self).tearDown()
class GuidTransIndexedAddModifyTestsLmdb(GUIDTransIndexedAddModifyTests):
def setUp(self):
@ -1851,6 +1868,7 @@ class GuidTransIndexedAddModifyTestsLmdb(GUIDTransIndexedAddModifyTests):
def tearDown(self):
super(GuidTransIndexedAddModifyTestsLmdb, self).tearDown()
class BadIndexTests(LdbBaseTest):
def setUp(self):
super(BadIndexTests, self).setUp()
@ -2011,6 +2029,7 @@ class GUIDBadIndexTests(BadIndexTests):
super(GUIDBadIndexTests, self).setUp()
class DnTests(TestCase):
def setUp(self):
@ -2253,6 +2272,7 @@ class DnTests(TestCase):
dn = ldb.Dn(self.ldb, '')
self.assertTrue(dn.is_null())
class LdbMsgTests(TestCase):
def setUp(self):
@ -2621,6 +2641,7 @@ class ModuleTests(TestCase):
l = ldb.Ldb(self.filename)
self.assertEqual(["init"], ops)
class LdbResultTests(LdbBaseTest):
def setUp(self):

View File

@ -11,6 +11,7 @@ import gc
import talloc
import _test_pytalloc
def dummy_func():
pass
@ -109,6 +110,7 @@ class TallocComparisonTests(unittest.TestCase):
self.assertFalse(obj1 >= obj2)
self.assertFalse(obj1 > obj2)
class TallocBaseComparisonTests(unittest.TestCase):
def test_compare_same(self):

View File

@ -27,6 +27,7 @@ import gc
import _tevent
class BackendListTests(TestCase):
def test_backend_list(self):

View File

@ -26,9 +26,11 @@ sys.path.insert(0, "bin/python")
from samba.dcerpc import samr, security
def display_lsa_string(str):
return str.string
def FillUserInfo(samr, dom_handle, users, level):
"""fill a user array with user information from samrQueryUserInfo"""
for i in range(len(users)):
@ -39,6 +41,7 @@ def FillUserInfo(samr, dom_handle, users, level):
users[i] = info
samr.Close(user_handle)
def toArray((handle, array, num_entries)):
ret = []
for x in range(num_entries):
@ -51,16 +54,19 @@ def test_Connect(samr):
print "Testing samr_Connect"
return samr.Connect2(None, security.SEC_FLAG_MAXIMUM_ALLOWED)
def test_LookupDomain(samr, handle, domain):
"""test the samr_LookupDomain interface"""
print "Testing samr_LookupDomain"
return samr.LookupDomain(handle, domain)
def test_OpenDomain(samr, handle, sid):
"""test the samr_OpenDomain interface"""
print "Testing samr_OpenDomain"
return samr.OpenDomain(handle, security.SEC_FLAG_MAXIMUM_ALLOWED, sid)
def test_EnumDomainUsers(samr, dom_handle):
"""test the samr_EnumDomainUsers interface"""
print "Testing samr_EnumDomainUsers"
@ -69,6 +75,7 @@ def test_EnumDomainUsers(samr, dom_handle):
for idx, user in users:
print "\t%s\t(%d)" % (user.string, idx)
def test_EnumDomainGroups(samr, dom_handle):
"""test the samr_EnumDomainGroups interface"""
print "Testing samr_EnumDomainGroups"
@ -77,11 +84,13 @@ def test_EnumDomainGroups(samr, dom_handle):
for idx, group in groups:
print "\t%s\t(%d)" % (group.string, idx)
def test_domain_ops(samr, dom_handle):
"""test domain specific ops"""
test_EnumDomainUsers(samr, dom_handle)
test_EnumDomainGroups(samr, dom_handle)
def test_EnumDomains(samr, handle):
"""test the samr_EnumDomains interface"""
print "Testing samr_EnumDomains"

View File

@ -32,6 +32,7 @@ binding = args[0]
print "Connecting to " + binding
conn = winreg.winreg(binding, sambaopts.get_loadparm())
def list_values(key):
(num_values, max_valnamelen, max_valbufsize) = conn.QueryInfoKey(key, winreg.String())[4:8]
for i in range(num_values):
@ -53,6 +54,7 @@ def list_values(key):
# printf("\t\t0x%llx (%lld)\n", v.value, v.value)
# }
def list_path(key, path):
count = 0
(num_subkeys, max_subkeylen, max_subkeysize) = conn.QueryInfoKey(key, winreg.String())[1:4]

View File

@ -305,6 +305,8 @@ def setup_file(template, fname, subst_vars=None):
f.close()
MAX_NETBIOS_NAME_LEN = 15
def is_valid_netbios_char(c):
return (c.isalnum() or c in " !#$%&'()-.@^_{}~")
@ -364,9 +366,11 @@ def dn_from_dns_name(dnsdomain):
"""return a DN from a DNS name domain/forest root"""
return "DC=" + ",DC=".join(dnsdomain.split("."))
def current_unix_time():
return int(time.time())
def string_to_byte_array(string):
blob = [0] * len(string)
@ -375,6 +379,7 @@ def string_to_byte_array(string):
return blob
def arcfour_encrypt(key, data):
from samba.crypto import arcfour_crypt_blob
return arcfour_crypt_blob(data, key)

View File

@ -34,6 +34,7 @@ import re
# Descriptors of naming contexts and other important objects
def sddl2binary(sddl_in, domain_sid, name_map):
sddl = "%s" % sddl_in
@ -43,12 +44,14 @@ def sddl2binary(sddl_in, domain_sid, name_map):
sec = security.descriptor.from_sddl(sddl, domain_sid)
return ndr_pack(sec)
def get_empty_descriptor(domain_sid, name_map={}):
sddl = ""
return sddl2binary(sddl, domain_sid, name_map)
# "get_schema_descriptor" is located in "schema.py"
def get_config_descriptor(domain_sid, name_map={}):
sddl = "O:EAG:EAD:(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)" \
"(OA;;CR;1131f6ab-9c07-11d1-f79f-00c04fc2dcd2;;ED)" \
@ -67,6 +70,7 @@ def get_config_descriptor(domain_sid, name_map={}):
"(OU;SA;CR;45ec5156-db7e-47bb-b53f-dbeb2d03c40f;;WD)"
return sddl2binary(sddl, domain_sid, name_map)
def get_config_partitions_descriptor(domain_sid, name_map={}):
sddl = "D:" \
"(A;;LCLORC;;;AU)" \
@ -84,6 +88,7 @@ def get_config_partitions_descriptor(domain_sid, name_map={}):
"(AU;CISA;WPCRCCDCWOWDSDDT;;;WD)"
return sddl2binary(sddl, domain_sid, name_map)
def get_config_sites_descriptor(domain_sid, name_map={}):
sddl = "D:" \
"(A;;RPLCLORC;;;AU)" \
@ -98,6 +103,7 @@ def get_config_sites_descriptor(domain_sid, name_map={}):
"(OU;CIIOSA;WP;3e10944c-c354-11d0-aff8-0000f80367c1;b7b13124-b82e-11d0-afee-0000f80367c1;WD)"
return sddl2binary(sddl, domain_sid, name_map)
def get_config_ntds_quotas_descriptor(domain_sid, name_map={}):
sddl = "D:" \
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;EA)" \
@ -105,6 +111,7 @@ def get_config_ntds_quotas_descriptor(domain_sid, name_map={}):
"(OA;;CR;4ecc03fe-ffc0-4947-b630-eb672a8a9dbc;;WD)"
return sddl2binary(sddl, domain_sid, name_map)
def get_config_delete_protected1_descriptor(domain_sid, name_map={}):
sddl = "D:AI" \
"(A;;RPLCLORC;;;AU)" \
@ -112,6 +119,7 @@ def get_config_delete_protected1_descriptor(domain_sid, name_map={}):
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)"
return sddl2binary(sddl, domain_sid, name_map)
def get_config_delete_protected1wd_descriptor(domain_sid, name_map={}):
sddl = "D:AI" \
"(A;;RPLCLORC;;;WD)" \
@ -119,6 +127,7 @@ def get_config_delete_protected1wd_descriptor(domain_sid, name_map={}):
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)"
return sddl2binary(sddl, domain_sid, name_map)
def get_config_delete_protected2_descriptor(domain_sid, name_map={}):
sddl = "D:AI" \
"(A;;RPLCLORC;;;AU)" \
@ -126,6 +135,7 @@ def get_config_delete_protected2_descriptor(domain_sid, name_map={}):
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)"
return sddl2binary(sddl, domain_sid, name_map)
def get_domain_descriptor(domain_sid, name_map={}):
sddl = "O:BAG:BAD:AI(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)" \
"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;bf967aba-0de6-11d0-a285-00aa003049e2;RU)" \
@ -178,6 +188,7 @@ def get_domain_descriptor(domain_sid, name_map={}):
"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)"
return sddl2binary(sddl, domain_sid, name_map)
def get_domain_infrastructure_descriptor(domain_sid, name_map={}):
sddl = "D:" \
"(A;;RPLCLORC;;;AU)" \
@ -187,6 +198,7 @@ def get_domain_infrastructure_descriptor(domain_sid, name_map={}):
"(AU;SA;WPCR;;;WD)"
return sddl2binary(sddl, domain_sid, name_map)
def get_domain_builtin_descriptor(domain_sid, name_map={}):
sddl = "D:" \
"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)" \
@ -243,6 +255,7 @@ def get_domain_builtin_descriptor(domain_sid, name_map={}):
"(AU;SA;WPWOWD;;;WD)"
return sddl2binary(sddl, domain_sid, name_map)
def get_domain_computers_descriptor(domain_sid, name_map={}):
sddl = "D:" \
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)" \
@ -256,6 +269,7 @@ def get_domain_computers_descriptor(domain_sid, name_map={}):
"S:"
return sddl2binary(sddl, domain_sid, name_map)
def get_domain_users_descriptor(domain_sid, name_map={}):
sddl = "D:" \
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)" \
@ -268,6 +282,7 @@ def get_domain_users_descriptor(domain_sid, name_map={}):
"S:"
return sddl2binary(sddl, domain_sid, name_map)
def get_managed_service_accounts_descriptor(domain_sid, name_map={}):
sddl = "D:" \
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)" \
@ -279,6 +294,7 @@ def get_managed_service_accounts_descriptor(domain_sid, name_map={}):
"S:"
return sddl2binary(sddl, domain_sid, name_map)
def get_domain_controllers_descriptor(domain_sid, name_map={}):
sddl = "D:" \
"(A;;RPLCLORC;;;AU)" \
@ -290,6 +306,7 @@ def get_domain_controllers_descriptor(domain_sid, name_map={}):
"(AU;CISA;WP;;;WD)"
return sddl2binary(sddl, domain_sid, name_map)
def get_domain_delete_protected1_descriptor(domain_sid, name_map={}):
sddl = "D:AI" \
"(A;;RPLCLORC;;;AU)" \
@ -297,6 +314,7 @@ def get_domain_delete_protected1_descriptor(domain_sid, name_map={}):
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)"
return sddl2binary(sddl, domain_sid, name_map)
def get_domain_delete_protected2_descriptor(domain_sid, name_map={}):
sddl = "D:AI" \
"(A;;RPLCLORC;;;AU)" \
@ -304,6 +322,7 @@ def get_domain_delete_protected2_descriptor(domain_sid, name_map={}):
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)"
return sddl2binary(sddl, domain_sid, name_map)
def get_dns_partition_descriptor(domain_sid, name_map={}):
sddl = "O:SYG:BAD:AI" \
"(OA;CIIO;RP;4c164200-20c0-11d0-a768-00aa006e0529;4828cc14-1437-45bc-9b07-ad6f015e5f28;RU)" \
@ -358,12 +377,14 @@ def get_dns_partition_descriptor(domain_sid, name_map={}):
"(AU;SA;CR;;;DU)(AU;SA;CR;;;BA)(AU;SA;WPWOWD;;;WD)"
return sddl2binary(sddl, domain_sid, name_map)
def get_dns_forest_microsoft_dns_descriptor(domain_sid, name_map={}):
sddl = "O:SYG:SYD:AI" \
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)" \
"(A;CI;RPWPCRCCDCLCRCWOWDSDDTSW;;;ED)"
return sddl2binary(sddl, domain_sid, name_map)
def get_dns_domain_microsoft_dns_descriptor(domain_sid, name_map={}):
sddl = "O:SYG:SYD:AI" \
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;DA)" \
@ -372,6 +393,7 @@ def get_dns_domain_microsoft_dns_descriptor(domain_sid, name_map={}):
"(A;CI;RPWPCRCCDCLCRCWOWDSDDTSW;;;ED)"
return sddl2binary(sddl, domain_sid, name_map)
def get_paritions_crossref_subdomain_descriptor(domain_sid, name_map={}):
sddl = "O:SubdomainAdminsG:SubdomainAdminsD:AI" \
"(A;;RPWPCRCCLCLORCWOWDSW;;;SubdomainAdmins)" \
@ -379,6 +401,7 @@ def get_paritions_crossref_subdomain_descriptor(domain_sid, name_map={}):
"(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)"
return sddl2binary(sddl, domain_sid, name_map)
def get_wellknown_sds(samdb):
# Then subcontainers
@ -445,6 +468,7 @@ def get_wellknown_sds(samdb):
return subcontainers
def chunck_acl(acl):
"""Return separate ACE of an ACL

View File

@ -23,6 +23,7 @@ from samba.dcerpc import dnsserver, dnsp
# to overcome the bug in pidl generated python bindings.
#
class ARecord(dnsserver.DNS_RPC_RECORD):
def __init__(self, ip_addr, serial=1, ttl=900, rank=dnsp.DNS_RANK_ZONE,
node_flag=0):

View File

@ -27,6 +27,7 @@ import samba, ldb
from samba.dcerpc.drsuapi import DRSUAPI_ATTID_name
import re
class drsException(Exception):
"""Base element for drs errors"""

View File

@ -39,6 +39,7 @@ import samba
samba.ensure_third_party_module("dns", "dnspython")
import dns.resolver
def uint32(v):
return ctypes.c_uint32(v).value

View File

@ -32,6 +32,7 @@ except ImportError:
def import_file(name, location):
return imp.load_source(name, location)
def get_gp_ext_from_module(name, mod):
if mod:
for k, v in vars(mod).items():
@ -39,6 +40,7 @@ def get_gp_ext_from_module(name, mod):
return v
return None
def get_gp_client_side_extensions(logger, smb_conf):
user_exts = []
machine_exts = []

View File

@ -18,6 +18,7 @@
import os.path
from samba.gpclass import gp_ext_setter, gp_inf_ext
class inf_to_kdc_tdb(gp_ext_setter):
def mins_to_hours(self):
return '%d' % (int(self.val) / 60)
@ -47,6 +48,7 @@ class inf_to_kdc_tdb(gp_ext_setter):
def __str__(self):
return 'Kerberos Policy'
class inf_to_ldb(gp_ext_setter):
'''This class takes the .inf file parameter (essentially a GPO file mapped
to a GUID), hashmaps it to the Samba parameter, which then uses an ldb
@ -105,6 +107,7 @@ class inf_to_ldb(gp_ext_setter):
def __str__(self):
return 'System Access'
class gp_sec_ext(gp_inf_ext):
'''This class does the following two things:
1) Identifies the GPO if it has a certain kind of filepath,

View File

@ -43,6 +43,7 @@ except ImportError:
ENFORCE = 2
UNAPPLY = 3
class gp_log:
''' Log settings overwritten by gpo apply
The gp_log is an xml file that stores a history of gpo changes (and the
@ -255,6 +256,7 @@ class gp_log:
''' Write gp_log changes to disk '''
self.gpostore.store(self.username, etree.tostring(self.gpdb, 'utf-8'))
class GPOStorage:
def __init__(self, log_file):
if os.path.isfile(log_file):
@ -292,6 +294,7 @@ class GPOStorage:
def __del__(self):
self.log.close()
class gp_ext(object):
__metaclass__ = ABCMeta
@ -325,6 +328,7 @@ class gp_ext(object):
def __str__(self):
pass
class gp_ext_setter():
__metaclass__ = ABCMeta
@ -351,6 +355,7 @@ class gp_ext_setter():
def __str__(self):
pass
class gp_inf_ext(gp_ext):
@abstractmethod
def list(self, rootpath):
@ -398,6 +403,8 @@ class gp_inf_ext(gp_ext):
pass
''' Fetch the hostname of a writable DC '''
def get_dc_hostname(creds, lp):
net = Net(creds=creds, lp=lp)
cldap_ret = net.finddc(domain=lp.get('realm'), flags=(nbt.NBT_SERVER_LDAP |
@ -405,6 +412,8 @@ def get_dc_hostname(creds, lp):
return cldap_ret.pdc_dns_name
''' Fetch a list of GUIDs for applicable GPOs '''
def get_gpo_list(dc_hostname, creds, lp):
gpos = []
ads = gpo.ADS_STRUCT(dc_hostname, lp, creds)
@ -441,6 +450,7 @@ def check_safe_path(path):
return os.path.join(*dirs)
raise OSError(path)
def check_refresh_gpo_list(dc_hostname, lp, creds, gpos):
conn = smb.SMB(dc_hostname, 'sysvol', lp=lp, creds=creds, sign=True)
cache_path = lp.cache_path('gpo_cache')
@ -449,12 +459,14 @@ def check_refresh_gpo_list(dc_hostname, lp, creds, gpos):
continue
cache_gpo_dir(conn, cache_path, check_safe_path(gpo.file_sys_path))
def gpo_version(lp, path):
# gpo.gpo_get_sysvol_gpt_version() reads the GPT.INI from a local file,
# read from the gpo client cache.
gpt_path = lp.cache_path(os.path.join('gpo_cache', path))
return int(gpo.gpo_get_sysvol_gpt_version(gpt_path)[1])
def apply_gp(lp, creds, test_ldb, logger, store, gp_extensions):
gp_db = store.get_gplog(creds.get_username())
dc_hostname = get_dc_hostname(creds, lp)
@ -491,6 +503,7 @@ def apply_gp(lp, creds, test_ldb, logger, store, gp_extensions):
store.store(guid, '%i' % version)
store.commit()
def unapply_log(gp_db):
while True:
item = gp_db.apply_log_pop()
@ -499,6 +512,7 @@ def unapply_log(gp_db):
else:
break
def unapply_gp(lp, creds, test_ldb, logger, store, gp_extensions):
gp_db = store.get_gplog(creds.get_username())
gp_db.state(GPOSTATE.UNAPPLY)
@ -511,6 +525,7 @@ def unapply_gp(lp, creds, test_ldb, logger, store, gp_extensions):
gp_db.delete(str(attr_obj), attr[0])
gp_db.commit()
def parse_gpext_conf(smb_conf):
lp = LoadParm()
if smb_conf is not None:
@ -522,12 +537,14 @@ def parse_gpext_conf(smb_conf):
parser.read(ext_conf)
return lp, parser
def atomic_write_conf(lp, parser):
ext_conf = lp.state_path('gpext.conf')
with NamedTemporaryFile(delete=False, dir=os.path.dirname(ext_conf)) as f:
parser.write(f)
os.rename(f.name, ext_conf)
def check_guid(guid):
# Check for valid guid with curly braces
if guid[0] != '{' or guid[-1] != '}' or len(guid) != 38:
@ -538,6 +555,7 @@ def check_guid(guid):
return False
return True
def register_gp_extension(guid, name, path,
smb_conf=None, machine=True, user=True):
# Check that the module exists
@ -558,6 +576,7 @@ def register_gp_extension(guid, name, path,
return True
def list_gp_extensions(smb_conf=None):
_, parser = parse_gpext_conf(smb_conf)
results = {}
@ -571,6 +590,7 @@ def list_gp_extensions(smb_conf=None):
results[guid]['UserPolicy'] = not int(parser.get(guid, 'NoUserPolicy'))
return results
def unregister_gp_extension(guid, smb_conf=None):
if not check_guid(guid):
return False

View File

@ -675,6 +675,7 @@ def transpose_dict_matrix(m):
m2.setdefault(k2, {})[k1] = dist
return m2
def full_matrix(rows,
utf8=False,
colour=None,

View File

@ -19,6 +19,7 @@
from __future__ import absolute_import
from .samdb import SamDB
class Hostconfig(object):
"""Aggregate object that contains all information about the configuration
of a Samba host."""

View File

@ -23,6 +23,7 @@ __docformat__ = "restructuredText"
import ldb
import samba
class IDmapDB(samba.Ldb):
"""The IDmap database."""

View File

@ -47,6 +47,7 @@ import re
import os
import tempfile
class DCJoinException(Exception):
def __init__(self, msg):
@ -1500,6 +1501,7 @@ def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_na
ctx.do_join()
logger.info("Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
def join_clone(logger=None, server=None, creds=None, lp=None,
targetdir=None, domain=None, include_secrets=False,
dns_backend="NONE"):
@ -1518,6 +1520,7 @@ def join_clone(logger=None, server=None, creds=None, lp=None,
logger.info("Cloned domain %s (SID %s)" % (ctx.domain_name, ctx.domsid))
return ctx
def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None,
netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False,

View File

@ -21,6 +21,7 @@ from __future__ import print_function
import re
def __read_folded_line(f, buffer):
"""Read a line from an LDIF file, unfolding it"""
line = buffer
@ -57,6 +58,7 @@ def __read_folded_line(f, buffer):
# Will not match options after the attribute type.
attr_type_re = re.compile("^([A-Za-z][A-Za-z0-9-]*):")
def __read_raw_entries(f):
"""Read an LDIF entry, only unfolding lines"""
@ -91,6 +93,7 @@ def __read_raw_entries(f):
if l == "":
break
def fix_dn(dn):
"""Fix a string DN to use ${CONFIGDN}"""
@ -100,6 +103,7 @@ def fix_dn(dn):
else:
return dn
def __write_ldif_one(entry):
"""Write out entry as LDIF"""
out = []
@ -113,6 +117,7 @@ def __write_ldif_one(entry):
return "\n".join(out)
def __transform_entry(entry):
"""Perform required transformations to the Microsoft-provided LDIF"""
@ -164,6 +169,7 @@ def __transform_entry(entry):
return entry
def read_ms_ldif(filename):
"""Read and transform Microsoft-provided LDIF file."""

View File

@ -87,6 +87,7 @@ multivalued_attrs = set(["auxiliaryclass", "maycontain", "mustcontain", "posssup
"systemauxiliaryclass", "systemmaycontain", "systemmustcontain",
"systemposssuperiors"])
def __read_folded_line(f, buffer):
""" reads a line from an LDIF file, unfolding it"""
line = buffer
@ -174,6 +175,7 @@ def fix_dn(dn):
else:
return dn
def __convert_bitfield(key, value):
"""Evaluate the OR expression in 'value'"""
assert(isinstance(value, string_types))
@ -193,6 +195,7 @@ def __convert_bitfield(key, value):
return str(o)
def __write_ldif_one(entry):
"""Write out entry as LDIF"""
out = []
@ -213,6 +216,7 @@ def __write_ldif_one(entry):
return "\n".join(out)
def __transform_entry(entry, objectClass):
"""Perform transformations required to convert the LDIF-like schema
file entries to LDIF, including Samba-specific stuff."""
@ -286,6 +290,7 @@ def __transform_entry(entry, objectClass):
return entry
def __parse_schema_file(filename, objectClass):
"""Load and transform a schema file."""

View File

@ -26,11 +26,13 @@ import os
import markdown
import xml.etree.ElementTree as ET
def innertext(tag):
return (tag.text or '') + \
''.join(innertext(e) for e in tag) + \
(tag.tail or '')
def read_ms_markdown(in_file, out_folder):
"""Read Github documentation-derived schema files."""

View File

@ -55,6 +55,7 @@ def ndr_print(object):
raise TypeError("%r is not a NDR object" % object)
return ndr_print()
def ndr_pack_in(object, bigendian=False, ndr64=False):
"""Pack the input of an NDR function object.

View File

@ -23,10 +23,13 @@ from ldb import LdbError
import sys, traceback
import textwrap
class Option(optparse.Option):
pass
# This help formatter does text wrapping and preserves newlines
class PlainHelpFormatter(optparse.IndentedHelpFormatter):
def format_description(self, description=""):
desc_width = self.width - self.current_indent
@ -47,6 +50,7 @@ class PlainHelpFormatter(optparse.IndentedHelpFormatter):
else:
return ""
class Command(object):
"""A samba-tool command."""

View File

@ -435,6 +435,7 @@ class cmd_computer_list(Command):
for msg in res:
self.outf.write("%s\n" % msg.get("samaccountname", idx=0))
class cmd_computer_show(Command):
"""Display a computer AD object.
@ -521,6 +522,7 @@ attribute.
computer_ldif = samdb.write_ldif(msg, ldb.CHANGETYPE_NONE)
self.outf.write(computer_ldif)
class cmd_computer_move(Command):
"""Move a computer to an organizational unit/container."""

View File

@ -41,6 +41,7 @@ from samba.dcerpc import dnsp, dnsserver
from samba.dnsserver import ARecord, AAAARecord, PTRRecord, CNameRecord, NSRecord, MXRecord, SOARecord, SRVRecord, TXTRecord
def dns_connect(server, lp, creds):
if server.lower() == 'localhost':
server = '127.0.0.1'

View File

@ -143,6 +143,7 @@ common_ntvfs_options = [
action="store_true")
]
def get_testparm_var(testparm, smbconf, varname):
errfile = open(os.devnull, 'w')
p = subprocess.Popen([testparm, '-s', '-l',
@ -1276,6 +1277,7 @@ class cmd_domain_level(Command):
else:
raise CommandError("invalid argument: '%s' (choose from 'show', 'raise')" % subcommand)
class cmd_domain_passwordsettings_show(Command):
"""Display current password settings for the domain."""
@ -1343,6 +1345,7 @@ class cmd_domain_passwordsettings_show(Command):
self.message("Account lockout threshold (attempts): %d" % cur_account_lockout_threshold)
self.message("Reset account lockout after (mins): %d" % cur_reset_account_lockout_after)
class cmd_domain_passwordsettings_set(Command):
"""Set password settings.
@ -1540,6 +1543,7 @@ class cmd_domain_passwordsettings_set(Command):
msgs.append("All changes applied successfully!")
self.message("\n".join(msgs))
class cmd_domain_passwordsettings(SuperCommand):
"""Manage password policy settings."""
@ -1548,6 +1552,7 @@ class cmd_domain_passwordsettings(SuperCommand):
subcommands["show"] = cmd_domain_passwordsettings_show()
subcommands["set"] = cmd_domain_passwordsettings_set()
class cmd_domain_classicupgrade(Command):
"""Upgrade from Samba classic (NT4-like) database to Samba AD DC database.
@ -1696,10 +1701,12 @@ class cmd_domain_samba3upgrade(cmd_domain_classicupgrade):
hidden = True
class LocalDCCredentialsOptions(options.CredentialsOptions):
def __init__(self, parser):
options.CredentialsOptions.__init__(self, parser, special_name="local-dc")
class DomainTrustCommand(Command):
"""List domain trusts."""
@ -2086,6 +2093,7 @@ class DomainTrustCommand(Command):
d.domain_sid, collision_string))
return
class cmd_domain_trust_list(DomainTrustCommand):
"""List domain trusts."""
@ -2132,6 +2140,7 @@ class cmd_domain_trust_list(DomainTrustCommand):
"Name[%s]" % self.netr_DomainTrust_to_name(t)))
return
class cmd_domain_trust_show(DomainTrustCommand):
"""Show trusted domain details."""
@ -2238,6 +2247,7 @@ class cmd_domain_trust_show(DomainTrustCommand):
return
class cmd_domain_trust_create(DomainTrustCommand):
"""Create a domain or forest trust."""
@ -2785,6 +2795,7 @@ class cmd_domain_trust_create(DomainTrustCommand):
self.outf.write("Success.\n")
return
class cmd_domain_trust_delete(DomainTrustCommand):
"""Delete a domain trust."""
@ -2946,6 +2957,7 @@ class cmd_domain_trust_delete(DomainTrustCommand):
return
class cmd_domain_trust_validate(DomainTrustCommand):
"""Validate a domain trust."""
@ -3124,6 +3136,7 @@ class cmd_domain_trust_validate(DomainTrustCommand):
return
class cmd_domain_trust_namespaces(DomainTrustCommand):
"""Manage forest trust namespaces."""
@ -3869,6 +3882,7 @@ class cmd_domain_trust_namespaces(DomainTrustCommand):
tln=local_tdo_info.domain_name.string)
return
class cmd_domain_tombstones_expunge(Command):
"""Expunge tombstones from the database.
@ -3953,12 +3967,14 @@ class cmd_domain_trust(SuperCommand):
subcommands["validate"] = cmd_domain_trust_validate()
subcommands["namespaces"] = cmd_domain_trust_namespaces()
class cmd_domain_tombstones(SuperCommand):
"""Domain tombstone and recycled object management."""
subcommands = {}
subcommands["expunge"] = cmd_domain_tombstones_expunge()
class ldif_schema_update:
"""Helper class for applying LDIF schema updates"""
@ -4014,6 +4030,7 @@ class ldif_schema_update:
return 1
class cmd_domain_schema_upgrade(Command):
"""Domain schema upgrading"""
@ -4264,6 +4281,7 @@ class cmd_domain_schema_upgrade(Command):
if error_encountered:
raise CommandError('Failed to upgrade schema')
class cmd_domain_functional_prep(Command):
"""Domain functional level preparation"""
@ -4370,6 +4388,7 @@ class cmd_domain_functional_prep(Command):
if error_encountered:
raise CommandError('Failed to perform functional prep')
class cmd_domain(SuperCommand):
"""Domain management."""

View File

@ -48,6 +48,7 @@ def drsuapi_connect(ctx):
except Exception as e:
raise CommandError("DRS connection to %s failed" % ctx.server, e)
def samdb_connect(ctx):
'''make a ldap connection to the server'''
try:
@ -57,6 +58,7 @@ def samdb_connect(ctx):
except Exception as e:
raise CommandError("LDAP connection to %s failed" % ctx.server, e)
def drs_errmsg(werr):
'''return "was successful" or an error string'''
(ecode, estring) = werr
@ -86,6 +88,7 @@ def drs_parse_ntds_dn(ntds_dn):
DEFAULT_SHOWREPL_FORMAT = 'classic'
class cmd_drs_showrepl(Command):
"""Show replication status."""

View File

@ -27,6 +27,7 @@ from samba.netcmd import (
Option
)
class cmd_forest_show(Command):
"""Display forest settings.
@ -74,6 +75,7 @@ class cmd_forest_show(Command):
except KeyError:
self.outf.write("%s: <NO VALUE>\n" % attr)
class cmd_forest_set(Command):
"""Modify forest settings.
@ -129,6 +131,7 @@ class cmd_forest_show_directory_service(cmd_forest_show):
objectdn = "CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration"
attributes = ['dsheuristics']
class cmd_forest_set_directory_service_dsheuristics(cmd_forest_set):
"""Set the value of dsheuristics on the Directory Service.
@ -148,6 +151,7 @@ class cmd_forest_set_directory_service_dsheuristics(cmd_forest_set):
objectdn = "CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration"
attribute = 'dsheuristics'
class cmd_forest_directory_service(SuperCommand):
"""Forest configuration partition management."""
@ -155,6 +159,7 @@ class cmd_forest_directory_service(SuperCommand):
subcommands["show"] = cmd_forest_show_directory_service()
subcommands["dsheuristics"] = cmd_forest_set_directory_service_dsheuristics()
class cmd_forest(SuperCommand):
"""Forest management."""

View File

@ -31,6 +31,7 @@ from samba.netcmd import (
)
from samba.samdb import SamDB
def get_fsmo_roleowner(samdb, roledn, role):
"""Gets the owner of an FSMO role
@ -151,6 +152,7 @@ def transfer_dns_role(outf, sambaopts, credopts, role, samdb):
outf.write("This DC already has the '%s' FSMO role\n" % role)
return False
def transfer_role(outf, role, samdb):
"""Transfer standard FSMO role. """
@ -213,6 +215,7 @@ def transfer_role(outf, role, samdb):
outf.write("This DC already has the '%s' FSMO role\n" % role)
return False
class cmd_fsmo_seize(Command):
"""Seize the role."""
@ -474,6 +477,7 @@ class cmd_fsmo_show(Command):
except CommandError as e:
self.message("%s: * %s" % (long_name, e.message))
class cmd_fsmo_transfer(Command):
"""Transfer the role."""

View File

@ -305,6 +305,7 @@ attr_flags = smb.FILE_ATTRIBUTE_SYSTEM | \
smb.FILE_ATTRIBUTE_ARCHIVE | \
smb.FILE_ATTRIBUTE_HIDDEN
def copy_directory_remote_to_local(conn, remotedir, localdir):
if not os.path.isdir(localdir):
os.mkdir(localdir)

View File

@ -359,6 +359,7 @@ class cmd_group_list(Command):
for msg in res:
self.outf.write("%s\n" % msg.get("samaccountname", idx=0))
class cmd_group_list_members(Command):
"""List all members of an AD group.
@ -422,6 +423,7 @@ samba-tool group listmembers \"Domain Users\" -H ldap://samba.samdom.example.com
except Exception as e:
raise CommandError('Failed to list members of "%s" group ' % groupname, e)
class cmd_group_move(Command):
"""Move a group to an organizational unit/container.
@ -501,6 +503,7 @@ class cmd_group_move(Command):
self.outf.write('Moved group "%s" into "%s"\n' %
(groupname, full_new_parent_dn))
class cmd_group_show(Command):
"""Display a group AD object.
@ -580,6 +583,7 @@ Example3 shows how to display a users objectGUID and member attributes.
user_ldif = samdb.write_ldif(msg, ldb.CHANGETYPE_NONE)
self.outf.write(user_ldif)
class cmd_group(SuperCommand):
"""Group management."""

View File

@ -40,6 +40,7 @@ from samba.netcmd import (
global summary
summary = {}
class LDAPBase(object):
def __init__(self, host, creds, lp,
@ -262,6 +263,7 @@ class LDAPBase(object):
except KeyError:
pass
class Descriptor(object):
def __init__(self, connection, dn, outf=sys.stdout, errf=sys.stderr):
self.outf = outf
@ -380,6 +382,7 @@ class Descriptor(object):
res += 8 * " " + ace + "\n"
return (self_aces == [] and other_aces == [], res)
class LDAPObject(object):
def __init__(self, connection, dn, summary, filter_list,
outf=sys.stdout, errf=sys.stderr):

View File

@ -21,6 +21,7 @@ from samba import getopt as options
from samba.netcmd import SuperCommand
class cache_loader(dict):
"""
We only load subcommand tools if they are actually used.

View File

@ -24,6 +24,7 @@ from samba.netcmd import (
Command,
)
class cmd_time(Command):
"""Retrieve the time on a server.

View File

@ -116,6 +116,7 @@ class cmd_dosinfo_get(Command):
if dosinfo:
self.outf.write(ndr_print(dosinfo))
class cmd_ntacl_get(Command):
"""Get ACLs of a file."""
synopsis = "%prog <file> [options]"
@ -238,6 +239,7 @@ class cmd_ntacl_sysvolreset(Command):
lp.get("realm").lower(), samdb.domain_dn(),
lp, use_ntvfs=use_ntvfs)
class cmd_ntacl_sysvolcheck(Command):
"""Check sysvol ACLs match defaults (including correct ACLs on GPOs)."""
synopsis = "%prog <file> [options]"

View File

@ -30,6 +30,7 @@ from samba.samdb import SamDB
from samba import dsdb
from operator import attrgetter
class cmd_rename(Command):
"""Rename an organizational unit.
@ -93,6 +94,7 @@ class cmd_rename(Command):
self.outf.write('Renamed ou "%s" to "%s"\n' % (full_old_ou_dn,
full_new_ou_dn))
class cmd_move(Command):
"""Move an organizational unit.
@ -160,6 +162,7 @@ class cmd_move(Command):
self.outf.write('Moved ou "%s" into "%s"\n' %
(full_old_ou_dn, full_new_parent_dn))
class cmd_create(Command):
"""Create an organizational unit.
@ -209,6 +212,7 @@ class cmd_create(Command):
self.outf.write('Created ou "%s"\n' % full_ou_dn)
class cmd_listobjects(Command):
"""List all objects in an organizational unit.
@ -278,6 +282,7 @@ class cmd_listobjects(Command):
raise CommandError('Failed to list contents of ou "%s"' %
full_ou_dn, e)
class cmd_list(Command):
"""List all organizational units.
@ -322,6 +327,7 @@ class cmd_list(Command):
msg.dn.remove_base_components(len(domain_dn))
self.outf.write("%s\n" % str(msg.dn))
class cmd_delete(Command):
"""Delete an organizational unit.

View File

@ -32,6 +32,7 @@ import samba.getopt as options
from samba.netcmd import Command, CommandError, Option
from samba.messaging import Messaging
class cmd_processes(Command):
"""List processes (to aid debugging on systems without setproctitle)."""

View File

@ -25,6 +25,7 @@ from samba.dcerpc import misc, drsuapi
from samba.drs_utils import drs_Replicate
import sys
class RODCException(Exception):
def __init__(self, value):
self.value = value
@ -32,12 +33,15 @@ class RODCException(Exception):
def __str__(self):
return "%s: %s" % (self.__class__.__name__, self.value)
class NamingError(RODCException):
pass
class ReplicationError(RODCException):
pass
class cmd_rodc_preload(Command):
"""Preload accounts for an RODC. Multiple accounts may be requested."""

View File

@ -28,6 +28,7 @@ from samba.netcmd import (
Option
)
class cmd_schema_attribute_modify(Command):
"""Modify attribute settings in the schema partition.
@ -128,6 +129,7 @@ class cmd_schema_attribute_modify(Command):
samdb.set_schema_update_now()
self.outf.write("modified %s" % attr_dn)
class cmd_schema_attribute_show(Command):
"""Show details about an attribute from the schema.
@ -203,6 +205,7 @@ class cmd_schema_attribute_show(Command):
user_ldif = samdb.write_ldif(res[0], ldb.CHANGETYPE_NONE)
self.outf.write(user_ldif)
class cmd_schema_attribute_show_oc(Command):
"""Show what objectclasses MAY or MUST contain an attribute.
@ -293,6 +296,7 @@ class cmd_schema_objectclass_show(Command):
user_ldif = samdb.write_ldif(msg, ldb.CHANGETYPE_NONE)
self.outf.write(user_ldif)
class cmd_schema_attribute(SuperCommand):
"""Query and manage attributes in the schema partition."""
subcommands = {}
@ -300,11 +304,13 @@ class cmd_schema_attribute(SuperCommand):
subcommands["show"] = cmd_schema_attribute_show()
subcommands["show_oc"] = cmd_schema_attribute_show_oc()
class cmd_schema_objectclass(SuperCommand):
"""Query and manage objectclasses in the schema partition."""
subcommands = {}
subcommands["show"] = cmd_schema_objectclass_show()
class cmd_schema(SuperCommand):
"""Schema querying and management."""

View File

@ -221,6 +221,7 @@ class cmd_sites_subnet(SuperCommand):
"set-site": cmd_sites_subnet_set_site(),
}
class cmd_sites(SuperCommand):
"""Sites management."""
subcommands = {}

View File

@ -37,6 +37,7 @@ import samba
import samba.getopt as options
from samba.netcmd import Command, CommandError, Option
class cmd_testparm(Command):
"""Syntax check the configuration file."""

View File

@ -95,17 +95,20 @@ if get_random_bytes_fn is None:
except ImportError as e:
pass
def check_random():
if get_random_bytes_fn is not None:
return None
return "Crypto.Random or M2Crypto.Rand required"
def get_random_bytes(num):
random_reason = check_random()
if random_reason is not None:
raise ImportError(random_reason)
return get_random_bytes_fn(num)
def get_crypt_value(alg, utf8pw, rounds=0):
algs = {
"5": {"length": 43},
@ -139,6 +142,8 @@ def get_crypt_value(alg, utf8pw, rounds=0):
# i.e. options = "rounds=20;other=ignored;" will return 20
# if the rounds option is not found or the value is not a number, 0 is returned
# which indicates that the default number of rounds should be used.
def get_rounds(options):
if not options:
return 0
@ -204,6 +209,7 @@ virtual_attributes_help += "Possible supported virtual attributes: %s" % ", ".jo
if len(disabled_virtual_attributes) != 0:
virtual_attributes_help += "Unsupported virtual attributes: %s" % ", ".join(sorted(disabled_virtual_attributes.keys()))
class cmd_user_create(Command):
"""Create a new user.
@ -854,6 +860,7 @@ Example3 shows how an administrator would reset TestUser3 user's password to pas
raise CommandError("%s: %s" % (command, msg))
self.outf.write("Changed password OK\n")
class GetPasswordCommand(Command):
def __init__(self):
@ -1312,6 +1319,7 @@ class GetPasswordCommand(Command):
return password_attrs
class cmd_user_getpassword(GetPasswordCommand):
"""Get the password fields of a user/computer account.
@ -1464,6 +1472,7 @@ samba-tool user getpassword --filter=samaccountname=TestUser3 --attributes=msDS-
self.outf.write("%s" % ldif)
self.outf.write("Got password OK\n")
class cmd_user_syncpasswords(GetPasswordCommand):
"""Sync the password of user accounts.
@ -2296,6 +2305,7 @@ samba-tool user syncpasswords --terminate \\
update_pid(None)
return
class cmd_user_edit(Command):
"""Modify User AD object.
@ -2429,6 +2439,7 @@ LDAP server using the 'nano' editor.
self.outf.write("Modified User '%s' successfully\n" % username)
class cmd_user_show(Command):
"""Display a user AD object.
@ -2507,6 +2518,7 @@ Example3 shows how to display a users objectSid and memberOf attributes.
user_ldif = samdb.write_ldif(msg, ldb.CHANGETYPE_NONE)
self.outf.write(user_ldif)
class cmd_user_move(Command):
"""Move a user to an organizational unit/container.
@ -2586,6 +2598,7 @@ class cmd_user_move(Command):
self.outf.write('Moved user "%s" into "%s"\n' %
(username, full_new_parent_dn))
class cmd_user(SuperCommand):
"""User management."""

View File

@ -80,6 +80,7 @@ def checkset_backend(lp, backend, eadbfile):
else:
raise XattrBackendError("Invalid xattr backend choice %s" %backend)
def getdosinfo(lp, file):
try:
attribute = samba.xattr_native.wrap_getxattr(file,
@ -89,6 +90,7 @@ def getdosinfo(lp, file):
return ndr_unpack(xattr.DOSATTRIB, attribute)
def getntacl(lp, file, backend=None, eadbfile=None, direct_db_access=True, service=None):
if direct_db_access:
(backend_obj, dbname) = checkset_backend(lp, backend, eadbfile)

View File

@ -709,6 +709,7 @@ def guess_names(lp=None, hostname=None, domain=None, dnsdomain=None,
return names
def make_smbconf(smbconf, hostname, domain, realm, targetdir,
serverrole=None, eadb=False, use_ntvfs=False, lp=None,
global_param=None):
@ -1061,6 +1062,7 @@ def setup_privileges(path, session_info, lp):
privilege_ldb.erase()
privilege_ldb.load_ldif_file_add(setup_path("provision_privilege.ldif"))
def setup_encrypted_secrets_key(path):
"""Setup the encrypted secrets key file.
@ -1582,6 +1584,7 @@ SYSVOL_ACL = "O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI
POLICIES_ACL = "O:LAG:BAD:P(A;OICI;0x001f01ff;;;BA)(A;OICI;0x001200a9;;;SO)(A;OICI;0x001f01ff;;;SY)(A;OICI;0x001200a9;;;AU)(A;OICI;0x001301bf;;;PA)"
SYSVOL_SERVICE = "sysvol"
def set_dir_acl(path, acl, lp, domsid, use_ntvfs, passdb, service=SYSVOL_SERVICE):
setntacl(lp, path, acl, domsid, use_ntvfs=use_ntvfs, skip_invalid_chown=True, passdb=passdb, service=service)
for root, dirs, files in os.walk(path, topdown=False):
@ -1729,12 +1732,14 @@ def setsysvolacl(samdb, netlogon, sysvol, uid, gid, domainsid, dnsdomain,
# Set acls on Policy folder and policies folders
set_gpos_acl(sysvol, dnsdomain, domainsid, domaindn, samdb, lp, use_ntvfs, passdb=s4_passdb)
def acl_type(direct_db_access):
if direct_db_access:
return "DB"
else:
return "VFS"
def check_dir_acl(path, acl, lp, domainsid, direct_db_access):
fsacl = getntacl(lp, path, direct_db_access=direct_db_access, service=SYSVOL_SERVICE)
fsacl_sddl = fsacl.as_sddl(domainsid)
@ -2053,6 +2058,7 @@ def provision_fake_ypserver(logger, samdb, domaindn, netbiosname, nisdomain,
else:
samdb.transaction_commit()
def directory_create_or_exists(path, mode=0o755):
if not os.path.exists(path):
try:
@ -2063,6 +2069,7 @@ def directory_create_or_exists(path, mode=0o755):
else:
raise ProvisioningError("Failed to create directory %s: %s" % (path, e.strerror))
def determine_host_ip(logger, lp, hostip=None):
if hostip is None:
logger.info("Looking up IPv4 addresses")
@ -2079,6 +2086,7 @@ def determine_host_ip(logger, lp, hostip=None):
return hostip
def determine_host_ip6(logger, lp, hostip6=None):
if hostip6 is None:
logger.info("Looking up IPv6 addresses")
@ -2092,6 +2100,7 @@ def determine_host_ip6(logger, lp, hostip6=None):
return hostip6
def provision(logger, session_info, smbconf=None,
targetdir=None, samdb_fill=FILL_FULL, realm=None, rootdn=None,
domaindn=None, schemadn=None, configdn=None, serverdn=None,

View File

@ -23,6 +23,7 @@ from samba.provision.kerberos_implementation import (
from samba import is_heimdal_built
import os
def create_kdc_conf(kdcconf, realm, domain, logdir):
if is_heimdal_built():

View File

@ -61,6 +61,7 @@ from samba.provision.common import (
from samba.samdb import get_default_backend_store
def get_domainguid(samdb, domaindn):
res = samdb.search(base=domaindn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
domainguid = str(ndr_unpack(misc.GUID, res[0]["objectGUID"][0]))
@ -390,6 +391,7 @@ def add_rootservers(samdb, domaindn, prefix):
msg["dnsRecord"] = ldb.MessageElement(record, ldb.FLAG_MOD_ADD, "dnsRecord")
samdb.add(msg)
def add_at_record(samdb, container_dn, prefix, hostname, dnsdomain, hostip, hostip6):
fqdn_hostname = "%s.%s" % (hostname, dnsdomain)

View File

@ -25,6 +25,7 @@ from samba.dcerpc import misc, dnsp
from samba.dcerpc.dnsp import DNS_TYPE_NS, DNS_TYPE_A, DNS_TYPE_AAAA, \
DNS_TYPE_CNAME, DNS_TYPE_SRV, DNS_TYPE_PTR
class DemoteException(Exception):
"""Base element for demote errors"""
@ -284,6 +285,7 @@ def offline_remove_server(samdb, logger,
if remove_sysvol_obj:
remove_sysvol_references(samdb, logger, dc_name)
def offline_remove_ntds_dc(samdb,
logger,
ntds_dn,

View File

@ -29,6 +29,7 @@ import tdb
import samba.samba3.passdb
from samba.samba3 import param as s3param
def fetch_uint32(db, key):
try:
data = db[key]
@ -134,6 +135,7 @@ IDMAP_USER_PREFIX = b"UID "
# idmap version determines auto-conversion
IDMAP_VERSION_V2 = 2
class IdmapDatabase(DbDatabase):
"""Samba 3 ID map database reader."""

View File

@ -41,6 +41,7 @@ __docformat__ = "restructuredText"
def get_default_backend_store():
return "tdb"
class SamDB(samba.Ldb):
"""The SAM database."""

View File

@ -32,6 +32,7 @@ from samba import dsdb
from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL
import os
def get_schema_descriptor(domain_sid, name_map={}):
sddl = "O:SAG:SAD:AI(OA;;CR;e12b56b6-0a95-11d1-adbb-00c04fd8d5cd;;SA)" \
"(OA;;CR;1131f6aa-9c07-11d1-f79f-00c04fc2dcd2;;ED)" \

View File

@ -24,6 +24,7 @@ import ldb
from ldb import FLAG_MOD_ADD, FLAG_MOD_REPLACE, LdbError
from sites import SiteNotFoundException
class SubnetException(Exception):
"""Base element for Subnet errors"""
pass
@ -129,6 +130,7 @@ def delete_subnet(samdb, configDn, subnet_name):
samdb.delete(dnsubnet)
def rename_subnet(samdb, configDn, subnet_name, new_name):
"""Rename a subnet.
@ -164,6 +166,7 @@ def rename_subnet(samdb, configDn, subnet_name, new_name):
else:
raise
def set_subnet_site(samdb, configDn, subnet_name, site_name):
"""Assign a subnet to a site.

View File

@ -22,6 +22,7 @@ import samba
import subprocess
import os
def tdb_copy(file1, file2, readonly=False):
"""Copy tdb file using tdbbackup utility and rename it
"""

View File

@ -58,6 +58,7 @@ except ImportError:
HEXDUMP_FILTER = bytearray([x if ((len(repr(chr(x))) == 3) and (x < 127)) else ord('.') for x in range(256)])
class TestCase(unittest.TestCase):
"""A Samba test case."""
@ -320,6 +321,7 @@ def env_get_var_value(var_name, allow_missing=False):
cmdline_credentials = None
class RpcInterfaceTestCase(TestCase):
"""DCE/RPC Test case."""
@ -359,6 +361,7 @@ class BlackboxProcessError(Exception):
return s
class BlackboxTestCase(TestCaseInTempDir):
"""Base test case for blackbox tests."""
@ -490,6 +493,7 @@ def delete_force(samdb, dn, **kwargs):
(num, errstr) = error.args
assert num == ldb.ERR_NO_SUCH_OBJECT, "ldb.delete() failed: %s" % errstr
def create_test_ou(samdb, name):
"""Creates a unique OU for the test"""

View File

@ -24,6 +24,7 @@ the functionality, that's already done in other tests.
from samba import auth
import samba.tests
class AuthSystemSessionTests(samba.tests.TestCase):
def setUp(self):
@ -57,6 +58,7 @@ class AuthSystemSessionTests(samba.tests.TestCase):
self.assertTrue(self.system_session.security_token.is_system())
self.assertFalse(self.system_session.security_token.is_anonymous())
class AuthAdminSessionTests(samba.tests.TestCase):
def setUp(self):

View File

@ -25,6 +25,7 @@ from samba.samdb import SamDB
import ldb
import shutil, os
class SambaDnsUpdateTests(samba.tests.BlackboxTestCase):
"""Blackbox test case for samba_dnsupdate."""

View File

@ -23,6 +23,7 @@ import samba
from samba import arcfour_encrypt, string_to_byte_array
from samba.tests import TestCase, TestCaseInTempDir
class SubstituteVarTestCase(TestCase):
def test_empty(self):
@ -49,6 +50,7 @@ class SubstituteVarTestCase(TestCase):
self.assertRaises(Exception, samba.check_all_substituted,
"Not subsituted: ${FOOBAR}")
class ArcfourTestCase(TestCase):
def test_arcfour_direct(self):
@ -58,6 +60,7 @@ class ArcfourTestCase(TestCase):
crypt_calculated = arcfour_encrypt(key, plain)
self.assertEquals(crypt_expected, crypt_calculated)
class StringToByteArrayTestCase(TestCase):
def test_byte_array(self):
@ -65,6 +68,7 @@ class StringToByteArrayTestCase(TestCase):
calculated = string_to_byte_array('\xda\x91Z\xb0l\xd7\xb9\xcf\x99')
self.assertEquals(expected, calculated)
class LdbExtensionTests(TestCaseInTempDir):
def test_searchone(self):

View File

@ -28,6 +28,7 @@ import binascii
from samba.compat import PY3
from samba.dcerpc import misc
class CredentialsTests(samba.tests.TestCaseInTempDir):
def setUp(self):

View File

@ -23,6 +23,7 @@ from samba.ndr import ndr_unpack, ndr_pack
import talloc
import gc
class ArrayTests(samba.tests.TestCase):
def setUp(self):

View File

@ -23,6 +23,7 @@ import os
from samba.dcerpc import ClientConnection
import samba.tests
class BareTestCase(samba.tests.TestCase):
def test_bare(self):

View File

@ -29,6 +29,7 @@ from samba.tests import RpcInterfaceTestCase, env_get_var_value
from samba.netcmd.dns import ARecord, AAAARecord, PTRRecord, CNameRecord, NSRecord, MXRecord, SRVRecord, TXTRecord
from samba import sd_utils, descriptor
class DnsserverTests(RpcInterfaceTestCase):
@classmethod

View File

@ -20,6 +20,7 @@
from samba.dcerpc import server_id, misc, srvsvc, samr
import samba.tests
class IntegerTests(samba.tests.TestCase):
def test_uint32_into_hyper(self):

View File

@ -36,6 +36,7 @@ from samba.tests.dcerpc.raw_testcase import RawDCERPCTest
global_ndr_print = False
global_hexdump = False
class TestDCERPC_BIND(RawDCERPCTest):
def setUp(self):

View File

@ -28,6 +28,7 @@ from samba.credentials import Credentials
from samba.tests import TestCase
from samba.ndr import ndr_pack, ndr_unpack, ndr_unpack_out
class RawDCERPCTest(TestCase):
"""A raw DCE/RPC Test case."""

View File

@ -26,6 +26,7 @@ import talloc
talloc.enable_null_tracking()
class RpcTests(object):
'''test type behaviour of pidl generated python RPC code'''

View File

@ -21,6 +21,7 @@
from samba.dcerpc import unixinfo
from samba.tests import RpcInterfaceTestCase
class UnixinfoTests(RpcInterfaceTestCase):
def setUp(self):

View File

@ -22,12 +22,14 @@ import samba.dckeytab
from samba import tests
from samba.param import LoadParm
def open_bytes(filename):
if sys.version_info[0] == 3:
return open(filename, errors='ignore')
else:
return open(filename, 'rb')
class DCKeytabTests(tests.TestCase):
def setUp(self):
super(DCKeytabTests, self).setUp()

View File

@ -66,6 +66,7 @@ dns_servers = args[2:]
creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
def make_txt_record(records):
rdata_txt = dns.txt_record()
s_list = dnsp.string_list()

View File

@ -29,6 +29,7 @@ import re
VERBOSE = False
def debug(msg):
if VERBOSE:
sys.stdout.flush()
@ -85,6 +86,7 @@ class DnsHandler(SocketServer.BaseRequestHandler):
t = Timer(timeout, self.really_handle, [data, socket])
t.start()
def main():
global SERVER_ID
host, port, SERVER_ID = sys.argv[1:]

View File

@ -27,6 +27,7 @@ import re
import subprocess
import xml.etree.ElementTree as ET
class TestCase(samba.tests.TestCaseInTempDir):
def _format_message(self, parameters, message):
@ -96,6 +97,7 @@ def get_documented_tuples(sourcedir, omit_no_default=True):
yield name, default_text, context, param_type
p.close()
class SmbDotConfTests(TestCase):
# defines the cases where the defaults may differ from the documentation

View File

@ -30,6 +30,7 @@ import ldb
import samba
import uuid
class DsdbTests(TestCase):
def setUp(self):
@ -726,6 +727,7 @@ class DsdbTests(TestCase):
str(part_dn) + "," + str(domain_dn)),
self.samdb.normalize_dn_in_domain(part_dn))
class DsdbFullScanTests(TestCase):
def setUp(self):

View File

@ -25,6 +25,7 @@ import samba
import gc
import time
class DsdbLockTestCase(SamDBTestCase):
def test_db_lock1(self):
basedn = self.samdb.get_default_basedn()

View File

@ -33,6 +33,7 @@ from ldb import SCOPE_BASE, LdbError
import samba.tests
class SchemaAttributesTestCase(samba.tests.TestCase):
def setUp(self):

View File

@ -25,6 +25,7 @@ from samba.credentials import Credentials
from samba import gensec, auth
import samba.tests
class GensecTests(samba.tests.TestCase):
def setUp(self):

View File

@ -28,6 +28,7 @@ from samba.getopt import (
)
import samba.tests
class KerberosOptionTests(samba.tests.TestCase):
def test_parse_true(self):

View File

@ -26,6 +26,7 @@ poldir = r'\\addom.samba.example.com\sysvol\addom.samba.example.com\Policies'
dspath = 'CN=Policies,CN=System,DC=addom,DC=samba,DC=example,DC=com'
gpt_data = '[General]\nVersion=%d'
class GPOTests(tests.TestCase):
def setUp(self):
super(GPOTests, self).setUp()

View File

@ -25,6 +25,7 @@ from samba.join import DCJoinContext
from samba.dcerpc import drsuapi, misc, dns
from samba.credentials import Credentials
def get_logger(name="subunit"):
"""Get a logger object."""
import logging
@ -32,6 +33,7 @@ def get_logger(name="subunit"):
logger.addHandler(logging.StreamHandler(sys.stderr))
return logger
class JoinTestCase(DNSTKeyTest):
def setUp(self):
self.server = samba.tests.env_get_var_value("SERVER")

View File

@ -48,6 +48,7 @@ ENV_DSAS = {
'CN=LOCALVAMPIREDC,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=samba,DC=example,DC=com'],
}
class KCCTests(samba.tests.TestCase):
def setUp(self):
super(KCCTests, self).setUp()

View File

@ -39,6 +39,7 @@ KDC
MACHINE_NAME = "krb5credstest"
class PyKrb5CredentialsTests(TestCase):
def setUp(self):

View File

@ -26,6 +26,7 @@ import threading
import sys
import os
class LibsmbTestCase(samba.tests.TestCase):
class OpenClose(threading.Thread):

View File

@ -22,6 +22,8 @@ import os
# the python bindings for LoadParm objects map (by default) to a single global
# object in the underlying C code. E.g. if we create 2 different LoadParm
# objects in python, really they're just the same object underneath.
class LoadParmTest(TestCaseInTempDir):
def test_global_loadparm(self):

View File

@ -24,6 +24,7 @@ Tests for the C helper functions in source4/librpc/ndr/py_lsa.c
for samba.dcerpc.lsa.String
"""
class LsaStringTests(TestCase):
def test_default_constructor(self):

View File

@ -27,6 +27,7 @@ from samba.credentials import DONT_USE_KERBEROS
from samba import NTSTATUSError, ntstatus
import ctypes
class NetJoinTests(samba.tests.TestCaseInTempDir):
def setUp(self):

View File

@ -27,6 +27,7 @@ from samba.credentials import DONT_USE_KERBEROS
from samba import NTSTATUSError, ntstatus
import ctypes
class NetJoinNoSpnegoTests(samba.tests.TestCaseInTempDir):
def setUp(self):

View File

@ -18,6 +18,7 @@
import samba, os, random, sys
from samba import netbios
class NetBiosTests(samba.tests.TestCase):
def setUp(self):
super(NetBiosTests, self).setUp()

View File

@ -23,6 +23,7 @@ from samba.netcmd.testparm import cmd_testparm
from samba.netcmd.main import cmd_sambatool
import samba.tests
class NetCmdTestCase(samba.tests.TestCase):
def run_netcmd(self, cmd_klass, args, retcode=0):

View File

@ -28,6 +28,7 @@ import ctypes
Tests whether the netlogon service is running
"""
class NetlogonServiceTests(TestCase):
def setUp(self):

View File

@ -31,6 +31,7 @@ from samba.dcerpc import srvsvc, samr, lsa
Tests behaviour when NTLM is disabled
"""
class NtlmDisabledTests(TestCase):
def setUp(self):

View File

@ -20,6 +20,7 @@ import samba.tests
import pypamtest
import os
class SimplePamTests(samba.tests.TestCase):
def test_authenticate(self):
domain = os.environ["DOMAIN"]

View File

@ -20,6 +20,7 @@ import samba.tests
import pypamtest
import os
class PasswordExpirePamTests(samba.tests.TestCase):
def test_auth_expire_warning(self):
domain = os.environ["DOMAIN"]

View File

@ -45,6 +45,8 @@ UPN = "PWHash@User.Principle"
# Get named package from the passed supplemental credentials
#
# returns the package and it's position within the supplemental credentials
def get_package(sc, name):
if sc is None:
return None
@ -59,6 +61,8 @@ def get_package(sc, name):
# Calculate the MD5 password digest from the supplied user, realm and password
#
def calc_digest(user, realm, password):
data = "%s:%s:%s" % (user, realm, password)

View File

@ -34,6 +34,7 @@ from samba.ndr import ndr_unpack
from samba.dcerpc import drsblobs
import binascii
class PassWordHashFl2008Tests(PassWordHashTests):
def setUp(self):

View File

@ -37,6 +37,7 @@ import binascii
from samba.tests.pso import PasswordSettings
import samba
class PassWordHashGpgmeTests(PassWordHashTests):
def setUp(self):

View File

@ -49,9 +49,11 @@ from samba.credentials import Credentials
import binascii
import os
def attid_equal(a1, a2):
return (a1 & 0xffffffff) == (a2 & 0xffffffff)
class PassWordHashLDAPTests(PassWordHashTests):
def setUp(self):

View File

@ -23,6 +23,7 @@
from samba import check_password_quality
from samba.tests import TestCase, TestCaseInTempDir
class PasswordQualityTests(TestCase):
def test_check_password_quality(self):
self.assertFalse(check_password_quality(""),

View File

@ -21,6 +21,7 @@
import samba.tests
from samba.samdb import SamDB
class PasswordCommon:
@staticmethod

View File

@ -841,6 +841,7 @@ class SessionedPosixAclMappingTests(PosixAclMappingTests):
return auth.user_session(self.samdb, lp_ctx=self.lp, dn=dn,
session_info_flags=flags)
class UnixSessionedPosixAclMappingTests(PosixAclMappingTests):
"""
Run same test suite with session enabled.

View File

@ -30,6 +30,7 @@ from samba.provision import (
import samba.tests
from samba.tests import env_loadparm, TestCase
def create_dummy_secretsdb(path, lp=None):
"""Create a dummy secrets database for use in tests.
@ -73,6 +74,7 @@ class ProvisionTestCase(samba.tests.TestCaseInTempDir):
if os.path.exists(secrets_tdb_path):
os.unlink(secrets_tdb_path)
class FindNssTests(TestCase):
"""Test findnss() function."""

View File

@ -48,6 +48,7 @@ Integration tests for pycredentials
MACHINE_NAME = "PCTM"
USER_NAME = "PCTU"
class PyCredentialsTests(TestCase):
def setUp(self):
@ -357,6 +358,8 @@ class PyCredentialsTests(TestCase):
#
# Build the logon data required by NetrLogonSamLogonWithFlags
def samlogon_logon_info(domain_name, computer_name, creds,
flags=CLI_CRED_NTLMv2_AUTH):
@ -385,6 +388,8 @@ def samlogon_logon_info(domain_name, computer_name, creds,
#
# Build the samlogon target info.
def samlogon_target(domain_name, computer_name):
target_info = ntlmssp.AV_PAIR_LIST()
target_info.count = 3

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