import talloc
import random
import time
+import re
+import os
+import tempfile
class DCJoinException(Exception):
netbios_name=None, targetdir=None, domain=None,
machinepass=None, use_ntvfs=False, dns_backend=None,
promote_existing=False, plaintext_secrets=False,
- backend_store=None):
+ backend_store=None, forced_local_samdb=None):
if site is None:
site = "Default-First-Site-Name"
ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
- if server is not None:
- ctx.server = server
- else:
- ctx.logger.info("Finding a writeable DC for domain '%s'" % domain)
- ctx.server = ctx.find_dc(domain)
- ctx.logger.info("Found DC %s" % ctx.server)
+ ctx.server = server
+ ctx.forced_local_samdb = forced_local_samdb
- ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
- session_info=system_session(),
- credentials=ctx.creds, lp=ctx.lp)
+ if forced_local_samdb:
+ ctx.samdb = forced_local_samdb
+ ctx.server = ctx.samdb.url
+ else:
+ if not ctx.server:
+ ctx.logger.info("Finding a writeable DC for domain '%s'" % domain)
+ ctx.server = ctx.find_dc(domain)
+ ctx.logger.info("Found DC %s" % ctx.server)
+ ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
+ session_info=system_session(),
+ credentials=ctx.creds, lp=ctx.lp)
try:
ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
'''add the ntdsdsa object'''
rec = ctx.join_ntdsdsa_obj()
- if ctx.RODC:
+ if ctx.forced_local_samdb:
+ ctx.samdb.add(rec, controls=["relax:0"])
+ elif ctx.RODC:
ctx.samdb.add(rec, ["rodc_join:1:1"])
else:
ctx.DsAddEntry([rec])
res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
- def join_add_objects(ctx):
+ def join_add_objects(ctx, specified_sid=None):
'''add the various objects needed for the join'''
if ctx.acct_dn:
print("Adding %s" % ctx.acct_dn)
elif ctx.promote_existing:
rec["msDS-RevealOnDemandGroup"] = []
+ if specified_sid:
+ rec["objectSid"] = ndr_pack(specified_sid)
+
if ctx.promote_existing:
if ctx.promote_from_dn != ctx.acct_dn:
ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn)
ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE))
else:
- ctx.samdb.add(rec)
+ controls = None
+ if specified_sid is not None:
+ controls = ["relax:0"]
+ ctx.samdb.add(rec, controls=controls)
if ctx.krbtgt_dn:
ctx.add_krbtgt_account()
ctx.dnspass = samba.generate_random_password(128, 255)
recs = ctx.samdb.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"),
- {"DNSDOMAIN": ctx.dnsdomain,
- "DOMAINDN": ctx.base_dn,
- "HOSTNAME" : ctx.myname,
- "DNSPASS_B64": b64encode(ctx.dnspass.encode('utf-16-le')).decode('utf8'),
- "DNSNAME" : ctx.dnshostname}))
+ {"DNSDOMAIN": ctx.dnsdomain,
+ "DOMAINDN": ctx.base_dn,
+ "HOSTNAME" : ctx.myname,
+ "DNSPASS_B64": b64encode(ctx.dnspass.encode('utf-16-le')).decode('utf8'),
+ "DNSNAME" : ctx.dnshostname}))
for changetype, msg in recs:
assert changetype == ldb.CHANGETYPE_NONE
dns_acct_dn = msg["dn"]
use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend,
plaintext_secrets=ctx.plaintext_secrets,
backend_store=ctx.backend_store
- )
+ )
print("Provision OK for domain DN %s" % presult.domaindn)
ctx.local_samdb = presult.samdb
ctx.lp = presult.lp
dns_backend=ctx.dns_backend, adminpass=ctx.adminpass)
print("Provision OK for domain %s" % ctx.names.dnsdomain)
+ def create_replicator(ctx, repl_creds, binding_options):
+ '''Creates a new DRS object for managing replications'''
+ return drs_utils.drs_Replicate(
+ "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
+ ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id)
+
def join_replicate(ctx):
"""Replicate the SAM."""
binding_options = "seal"
if ctx.lp.log_level() >= 9:
binding_options += ",print"
- repl = drs_utils.drs_Replicate(
- "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
- ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id)
+
+ repl = ctx.create_replicator(repl_creds, binding_options)
repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
destination_dsa_guid, schema=True, rodc=ctx.RODC,
if nc in ctx.nc_list:
print("Replicating %s" % (str(nc)))
repl.replicate(nc, source_dsa_invocation_id,
- destination_dsa_guid, rodc=ctx.RODC,
- replica_flags=ctx.replica_flags)
+ destination_dsa_guid, rodc=ctx.RODC,
+ replica_flags=ctx.replica_flags)
if ctx.RODC:
repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
client_version = dnsserver.DNS_CLIENT_VERSION_LONGHORN
record_type = dnsp.DNS_TYPE_A
select_flags = dnsserver.DNS_RPC_VIEW_AUTHORITY_DATA |\
- dnsserver.DNS_RPC_VIEW_NO_CHILDREN
+ dnsserver.DNS_RPC_VIEW_NO_CHILDREN
zone = ctx.dnsdomain
msdcs_zone = "_msdcs.%s" % ctx.dnsforest
"trustAuthIncoming" : ndr_pack(outgoing),
"trustAuthOutgoing" : ndr_pack(outgoing),
"securityIdentifier" : ndr_pack(ctx.forestsid)
- }
+ }
ctx.local_samdb.add(rec)
rec = {
"userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
"clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le'),
"samAccountName" : "%s$" % ctx.forest_domain_name
- }
+ }
ctx.local_samdb.add(rec)
ctx.join_provision()
ctx.join_replicate()
ctx.join_finalise()
+
+
+# Used to create a renamed backup of a DC. Renaming the domain means that the
+# cloned/backup DC can be started without interfering with the production DC.
+class DCCloneAndRenameContext(DCCloneContext):
+ """Clones a remote DC, renaming the domain along the way."""
+
+ def __init__(ctx, new_base_dn, new_domain_name, new_realm, logger=None,
+ server=None, creds=None, lp=None, targetdir=None, domain=None,
+ dns_backend=None, include_secrets=True):
+ super(DCCloneAndRenameContext, ctx).__init__(logger, server, creds, lp,
+ targetdir=targetdir,
+ domain=domain,
+ dns_backend=dns_backend,
+ include_secrets=include_secrets)
+ # store the new DN (etc) that we want the cloned DB to use
+ ctx.new_base_dn = new_base_dn
+ ctx.new_domain_name = new_domain_name
+ ctx.new_realm = new_realm
+
+ def create_replicator(ctx, repl_creds, binding_options):
+ """Creates a new DRS object for managing replications"""
+
+ # We want to rename all the domain objects, and the simplest way to do
+ # this is during replication. This is because the base DN of the top-
+ # level replicated object will flow through to all the objects below it
+ binding_str = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
+ return drs_utils.drs_ReplicateRenamer(binding_str, ctx.lp, repl_creds,
+ ctx.local_samdb,
+ ctx.invocation_id,
+ ctx.base_dn, ctx.new_base_dn)
+
+ def create_non_global_lp(ctx, global_lp):
+ '''Creates a non-global LoadParm based on the global LP's settings'''
+
+ # the samba code shares a global LoadParm by default. Here we create a
+ # new LoadParm that retains the global settings, but any changes we
+ # make to it won't automatically affect the rest of the samba code.
+ # The easiest way to do this is to dump the global settings to a
+ # temporary smb.conf file, and then load the temp file into a new
+ # non-global LoadParm
+ fd, tmp_file = tempfile.mkstemp()
+ global_lp.dump(False, tmp_file)
+ local_lp = samba.param.LoadParm(filename_for_non_global_lp=tmp_file)
+ os.remove(tmp_file)
+ return local_lp
+
+ def rename_dn(ctx, dn_str):
+ '''Uses string substitution to replace the base DN'''
+ old_base_dn = ctx.base_dn
+ return re.sub('%s$' % old_base_dn, ctx.new_base_dn, dn_str)
+
+ # we want to override the normal DCCloneContext's join_provision() so that
+ # use the new domain DNs during the provision. We do this because:
+ # - it sets up smb.conf/secrets.ldb with the new realm/workgroup values
+ # - it sets up a default SAM DB that uses the new Schema DNs (without which
+ # we couldn't apply the renamed DRS objects during replication)
+ def join_provision(ctx):
+ """Provision the local (renamed) SAM."""
+
+ print("Provisioning the new (renamed) domain...")
+
+ # the provision() calls make_smbconf() which uses lp.dump()/lp.load()
+ # to create a new smb.conf. By default, it uses the global LoadParm to
+ # do this, and so it would overwrite the realm/domain values globally.
+ # We still need the global LoadParm to retain the old domain's details,
+ # so we can connect to (and clone) the existing DC.
+ # So, copy the global settings into a non-global LoadParm, which we can
+ # then pass into provision(). This generates a new smb.conf correctly,
+ # without overwriting the global realm/domain values just yet.
+ non_global_lp = ctx.create_non_global_lp(ctx.lp)
+
+ # do the provision with the new/renamed domain DN values
+ presult = provision(ctx.logger, system_session(),
+ targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
+ realm=ctx.new_realm, lp=non_global_lp,
+ rootdn=ctx.rename_dn(ctx.root_dn), domaindn=ctx.new_base_dn,
+ schemadn=ctx.rename_dn(ctx.schema_dn),
+ configdn=ctx.rename_dn(ctx.config_dn),
+ domain=ctx.new_domain_name, domainsid=ctx.domsid,
+ serverrole="active directory domain controller",
+ dns_backend=ctx.dns_backend)
+
+ print("Provision OK for renamed domain DN %s" % presult.domaindn)
+ ctx.local_samdb = presult.samdb
+ ctx.paths = presult.paths