from samba.auth import system_session
from samba.samdb import SamDB
from samba import gensec, Ldb, drs_utils, arcfour_encrypt, string_to_byte_array
-import ldb, samba, sys, uuid
+import ldb
+import samba
+import sys
+import uuid
from samba.ndr import ndr_pack, ndr_unpack
from samba.dcerpc import security, drsuapi, misc, nbt, lsa, drsblobs, dnsserver, dnsp
from samba.dsdb import DS_DOMAIN_FUNCTION_2003
import talloc
import random
import time
+import re
+import os
+import tempfile
+
class DCJoinException(Exception):
super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
-class dc_join(object):
+class DCJoinContext(object):
"""Perform a DC join."""
def __init__(ctx, logger=None, server=None, creds=None, lp=None, site=None,
netbios_name=None, targetdir=None, domain=None,
machinepass=None, use_ntvfs=False, dns_backend=None,
- promote_existing=False, clone_only=False,
- plaintext_secrets=False):
+ promote_existing=False, plaintext_secrets=False,
+ backend_store=None, forced_local_samdb=None):
if site is None:
site = "Default-First-Site-Name"
- ctx.clone_only=clone_only
-
ctx.logger = logger
ctx.creds = creds
ctx.lp = lp
ctx.targetdir = targetdir
ctx.use_ntvfs = use_ntvfs
ctx.plaintext_secrets = plaintext_secrets
+ ctx.backend_store = backend_store
ctx.promote_existing = promote_existing
ctx.promote_from_dn = None
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"])
(enum, estr) = e4.args
raise DCJoinException(estr)
-
ctx.base_dn = str(ctx.samdb.get_default_basedn())
ctx.root_dn = str(ctx.samdb.get_root_basedn())
ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
ctx.acct_pass = samba.generate_random_machine_password(128, 255)
ctx.dnsdomain = ctx.samdb.domain_dns_name()
- if clone_only:
- # As we don't want to create or delete these DNs, we set them to None
- ctx.server_dn = None
- ctx.ntds_dn = None
- ctx.acct_dn = None
- ctx.myname = ctx.server.split('.')[0]
- ctx.ntds_guid = None
- ctx.rid_manager_dn = None
- # Save this early
- ctx.remote_dc_ntds_guid = ctx.samdb.get_ntds_GUID()
- else:
+ # the following are all dependent on the new DC's netbios_name (which
+ # we expect to always be specified, except when cloning a DC)
+ if netbios_name:
# work out the DNs of all the objects we will be adding
ctx.myname = netbios_name
ctx.samname = "%s$" % ctx.myname
else:
ctx.topology_dn = None
- ctx.SPNs = [ "HOST/%s" % ctx.myname,
+ ctx.SPNs = ["HOST/%s" % ctx.myname,
"HOST/%s" % ctx.dnshostname,
- "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
+ "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest)]
res_rid_manager = ctx.samdb.search(scope=ldb.SCOPE_BASE,
attrs=["rIDManagerReference"],
creds.set_kerberos_state(ctx.creds.get_kerberos_state())
machine_samdb = SamDB(url="ldap://%s" % ctx.server,
session_info=system_session(),
- credentials=creds, lp=ctx.lp)
+ credentials=creds, lp=ctx.lp)
except:
pass
else:
if token_res[0]["tokenGroups"][0] \
== res[0]["objectSID"][0]:
raise DCJoinException("Not removing account %s which "
- "looks like a Samba DC account "
- "maching the password we already have. "
- "To override, remove secrets.ldb and secrets.tdb"
- % ctx.samname)
+ "looks like a Samba DC account "
+ "matching the password we already have. "
+ "To override, remove secrets.ldb and secrets.tdb"
+ % ctx.samname)
ctx.del_noerror(res[0].dn, recursive=True)
res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname),
- attrs=[])
+ attrs=[])
if res:
raise DCJoinException("Not removing account %s which looks like "
- "a Samba DNS service account but does not "
- "have servicePrincipalName=%s" %
- (ldb.binary_encode("dns-%s" % ctx.myname),
- ldb.binary_encode("dns/%s" % ctx.dnshostname)))
-
+ "a Samba DNS service account but does not "
+ "have servicePrincipalName=%s" %
+ (ldb.binary_encode("dns-%s" % ctx.myname),
+ ldb.binary_encode("dns/%s" % ctx.dnshostname)))
def cleanup_old_join(ctx, force=False):
"""Remove any DNs from a previous join."""
if ctx.dns_cname_dn:
ctx.del_noerror(ctx.dns_cname_dn)
-
-
def promote_possible(ctx):
"""confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
if ctx.subdomain:
raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname)
if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]:
raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname)
- if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0):
+ if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
+ samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0):
raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname)
ctx.promote_from_dn = res[0].dn
-
def find_dc(ctx, domain):
"""find a writeable DC for the given domain"""
try:
ctx.site = ctx.cldap_ret.client_site
return ctx.cldap_ret.pdc_dns_name
-
def get_behavior_version(ctx):
res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
if "msDS-Behavior-Version" in res[0]:
'''get the parent domain partition DN from parent DNS name'''
res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
- if not 'fSMORoleOwner' in res[0]:
+ if 'fSMORoleOwner' not in res[0]:
raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
try:
- master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
+ master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0].decode('utf8')).get_extended_component('GUID')))
except KeyError:
raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0])
'''RODCs need a special krbtgt account'''
print("Adding %s" % ctx.krbtgt_dn)
rec = {
- "dn" : ctx.krbtgt_dn,
- "objectclass" : "user",
- "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
+ "dn": ctx.krbtgt_dn,
+ "objectclass": "user",
+ "useraccountcontrol": str(samba.dsdb.UF_NORMAL_ACCOUNT |
samba.dsdb.UF_ACCOUNTDISABLE),
- "showinadvancedviewonly" : "TRUE",
- "description" : "krbtgt for %s" % ctx.samname}
+ "showinadvancedviewonly": "TRUE",
+ "description": "krbtgt for %s" % ctx.samname}
ctx.samdb.add(rec, ["rodc_join:1:1"])
# now we need to search for the samAccountName attribute on the krbtgt DN,
r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
r.value_ctr = 1
-
def DsAddEntry(ctx, recs):
'''add a record via the DRSUAPI DsAddEntry call'''
if ctx.drsuapi is None:
print("Adding %s" % ctx.ntds_dn)
rec = {
- "dn" : ctx.ntds_dn,
- "objectclass" : "nTDSDSA",
- "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
- "dMDLocation" : ctx.schema_dn}
+ "dn": ctx.ntds_dn,
+ "objectclass": "nTDSDSA",
+ "systemFlags": str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
+ "dMDLocation": ctx.schema_dn}
- nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
+ nc_list = [ctx.base_dn, ctx.config_dn, ctx.schema_dn]
if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
'''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)
rec = {
- "dn" : ctx.acct_dn,
+ "dn": ctx.acct_dn,
"objectClass": "computer",
"displayname": ctx.samname,
- "samaccountname" : ctx.samname,
- "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
- "dnshostname" : ctx.dnshostname}
+ "samaccountname": ctx.samname,
+ "userAccountControl": str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
+ "dnshostname": ctx.dnshostname}
if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
elif ctx.promote_existing:
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()
print("Adding %s" % ctx.server_dn)
rec = {
"dn": ctx.server_dn,
- "objectclass" : "server",
+ "objectclass": "server",
# windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
- "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
+ "systemFlags": str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
# windows seems to add the dnsHostName later
- "dnsHostName" : ctx.dnshostname}
+ "dnsHostName": ctx.dnshostname}
if ctx.acct_dn:
rec["serverReference"] = ctx.acct_dn
# TODO Is this supposed to be for the schema partition too?
expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.domaindns_zone)
domain = (ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
- attrs=[],
- base=ctx.samdb.get_partitions_dn(),
- expression=expr), ctx.domaindns_zone)
+ attrs=[],
+ base=ctx.samdb.get_partitions_dn(),
+ expression=expr), ctx.domaindns_zone)
expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.forestdns_zone)
forest = (ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
- attrs=[],
- base=ctx.samdb.get_partitions_dn(),
- expression=expr), ctx.forestdns_zone)
+ attrs=[],
+ base=ctx.samdb.get_partitions_dn(),
+ expression=expr), ctx.forestdns_zone)
for part, zone in (domain, forest):
if zone not in ctx.nc_list:
if ctx.connection_dn is not None:
print("Adding %s" % ctx.connection_dn)
rec = {
- "dn" : ctx.connection_dn,
- "objectclass" : "nTDSConnection",
- "enabledconnection" : "TRUE",
- "options" : "65",
- "fromServer" : ctx.dc_ntds_dn}
+ "dn": ctx.connection_dn,
+ "objectclass": "nTDSConnection",
+ "enabledconnection": "TRUE",
+ "options": "65",
+ "fromServer": ctx.dc_ntds_dn}
ctx.samdb.add(rec)
if ctx.acct_dn:
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')),
- "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"]
name_map = {'SubdomainAdmins': "%s-%s" % (str(ctx.domsid), security.DOMAIN_RID_ADMINS)}
sd_binary = descriptor.get_paritions_crossref_subdomain_descriptor(ctx.forestsid, name_map=name_map)
rec = {
- "dn" : ctx.partition_dn,
- "objectclass" : "crossRef",
- "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
- "nCName" : ctx.base_dn,
- "nETBIOSName" : ctx.domain_name,
+ "dn": ctx.partition_dn,
+ "objectclass": "crossRef",
+ "objectCategory": "CN=Cross-Ref,%s" % ctx.schema_dn,
+ "nCName": ctx.base_dn,
+ "nETBIOSName": ctx.domain_name,
"dnsRoot": ctx.dnsdomain,
- "trustParent" : ctx.parent_partition_dn,
- "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN),
- "ntSecurityDescriptor" : sd_binary,
+ "trustParent": ctx.parent_partition_dn,
+ "systemFlags": str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC |samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN),
+ "ntSecurityDescriptor": sd_binary,
}
if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
smbconf = ctx.lp.configfile
presult = provision(ctx.logger, system_session(), smbconf=smbconf,
- targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
- rootdn=ctx.root_dn, domaindn=ctx.base_dn,
- schemadn=ctx.schema_dn, configdn=ctx.config_dn,
- serverdn=ctx.server_dn, domain=ctx.domain_name,
- hostname=ctx.myname, domainsid=ctx.domsid,
- machinepass=ctx.acct_pass, serverrole="active directory domain controller",
- sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
- use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend,
- plaintext_secrets=ctx.plaintext_secrets)
+ targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
+ rootdn=ctx.root_dn, domaindn=ctx.base_dn,
+ schemadn=ctx.schema_dn, configdn=ctx.config_dn,
+ serverdn=ctx.server_dn, domain=ctx.domain_name,
+ hostname=ctx.myname, domainsid=ctx.domsid,
+ machinepass=ctx.acct_pass, serverrole="active directory domain controller",
+ sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
+ 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
raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
try:
- ctx.names.domainguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
+ ctx.names.domainguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0].decode('utf8')).get_extended_component('GUID')))
except KeyError:
raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['ncName'][0])
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,
- replica_flags=ctx.replica_flags)
+ destination_dsa_guid, schema=True, rodc=ctx.RODC,
+ replica_flags=ctx.replica_flags)
repl.replicate(ctx.config_dn, 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 not ctx.subdomain:
# Replicate first the critical object for the basedn
if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
print("Replicating critical objects from the base DN of the domain")
ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
repl.replicate(ctx.base_dn, source_dsa_invocation_id,
- destination_dsa_guid, rodc=ctx.RODC,
- replica_flags=ctx.domain_replica_flags)
+ destination_dsa_guid, rodc=ctx.RODC,
+ replica_flags=ctx.domain_replica_flags)
ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
repl.replicate(ctx.base_dn, source_dsa_invocation_id,
destination_dsa_guid, 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,
- destination_dsa_guid,
- exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
+ destination_dsa_guid,
+ exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
- destination_dsa_guid,
- exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
- elif ctx.rid_manager_dn != None:
+ destination_dsa_guid,
+ exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
+ elif ctx.rid_manager_dn is not None:
# Try and get a RID Set if we can. This is only possible against the RID Master. Warn otherwise.
try:
repl.replicate(ctx.rid_manager_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
cname_target = "%s.%s" % (name, zone)
IPs = samba.interface_ips(ctx.lp, ctx.force_all_ips)
- ctx.logger.info("Adding %d remote DNS records for %s.%s" % \
+ ctx.logger.info("Adding %d remote DNS records for %s.%s" %
(len(IPs), name, zone))
binding_options = "sign"
dns_conn = dnsserver.dnsserver("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
- ctx.lp, ctx.creds)
-
+ ctx.lp, ctx.creds)
name_found = True
% (security.SECINFO_OWNER
| security.SECINFO_GROUP)])
-
# Add record
ctx.logger.info("Adding DNS CNAME record %s.%s for %s"
% (msdcs_cname, msdcs_zone, cname_target))
ctx.logger.info("All other DNS records (like _ldap SRV records) " +
"will be created samba_dnsupdate on first startup")
-
def join_replicate_new_dns_records(ctx):
for nc in (ctx.domaindns_zone, ctx.forestdns_zone):
if nc in ctx.nc_list:
replica_flags=ctx.replica_flags,
full_sync=False)
-
-
def join_finalise(ctx):
"""Finalise the join, mark us synchronised and setup secrets db."""
# DC we just replicated from then we don't need to send the updatereplicateref
# as replication between sites is time based and on the initiative of the
# requesting DC
- if not ctx.clone_only:
- ctx.logger.info("Sending DsReplicaUpdateRefs for all the replicated partitions")
- for nc in ctx.nc_list:
- ctx.send_DsReplicaUpdateRefs(nc)
+ ctx.logger.info("Sending DsReplicaUpdateRefs for all the replicated partitions")
+ for nc in ctx.nc_list:
+ ctx.send_DsReplicaUpdateRefs(nc)
- if not ctx.clone_only and ctx.RODC:
+ if ctx.RODC:
print("Setting RODC invocationId")
ctx.local_samdb.set_invocation_id(str(ctx.invocation_id))
ctx.local_samdb.set_opaque_integer("domainFunctionality",
m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
- # We want to appear to be the server we just cloned
- if ctx.clone_only:
- guid = ctx.remote_dc_ntds_guid
- else:
- guid = ctx.ntds_guid
-
+ guid = ctx.ntds_guid
m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(guid),
ldb.FLAG_MOD_REPLACE, "dsServiceName")
ctx.local_samdb.modify(m)
- if ctx.clone_only or ctx.subdomain:
+ if ctx.subdomain:
return
secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
security.SEC_STD_DELETE)
rec = {
- "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
- "objectclass" : "trustedDomain",
- "trustType" : str(info.trust_type),
- "trustAttributes" : str(info.trust_attributes),
- "trustDirection" : str(info.trust_direction),
- "flatname" : ctx.forest_domain_name,
- "trustPartner" : ctx.dnsforest,
- "trustAuthIncoming" : ndr_pack(outgoing),
- "trustAuthOutgoing" : ndr_pack(outgoing),
- "securityIdentifier" : ndr_pack(ctx.forestsid)
- }
+ "dn": "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
+ "objectclass": "trustedDomain",
+ "trustType": str(info.trust_type),
+ "trustAttributes": str(info.trust_attributes),
+ "trustDirection": str(info.trust_direction),
+ "flatname": ctx.forest_domain_name,
+ "trustPartner": ctx.dnsforest,
+ "trustAuthIncoming": ndr_pack(outgoing),
+ "trustAuthOutgoing": ndr_pack(outgoing),
+ "securityIdentifier": ndr_pack(ctx.forestsid)
+ }
ctx.local_samdb.add(rec)
rec = {
- "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
- "objectclass" : "user",
- "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
- "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le'),
- "samAccountName" : "%s$" % ctx.forest_domain_name
- }
+ "dn": "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
+ "objectclass": "user",
+ "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)
-
- def do_join(ctx):
+ def build_nc_lists(ctx):
# nc_list is the list of naming context (NC) for which we will
# replicate in and send a updateRef command to the partner DC
# full_nc_list is the list of naming context (NC) we hold
# read/write copies of. These are not subsets of each other.
- ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
- ctx.full_nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
+ ctx.nc_list = [ctx.config_dn, ctx.schema_dn]
+ ctx.full_nc_list = [ctx.base_dn, ctx.config_dn, ctx.schema_dn]
if ctx.subdomain and ctx.dns_backend != "NONE":
ctx.full_nc_list += [ctx.domaindns_zone]
ctx.full_nc_list += [ctx.domaindns_zone]
ctx.full_nc_list += [ctx.forestdns_zone]
- if not ctx.clone_only:
- if ctx.promote_existing:
- ctx.promote_possible()
- else:
- ctx.cleanup_old_join()
+ def do_join(ctx):
+ ctx.build_nc_lists()
+
+ if ctx.promote_existing:
+ ctx.promote_possible()
+ else:
+ ctx.cleanup_old_join()
try:
- if not ctx.clone_only:
- ctx.join_add_objects()
+ ctx.join_add_objects()
ctx.join_provision()
ctx.join_replicate()
- if (not ctx.clone_only and ctx.subdomain):
+ if ctx.subdomain:
ctx.join_add_objects2()
ctx.join_provision_own_domain()
ctx.join_setup_trusts()
- if not ctx.clone_only and ctx.dns_backend != "NONE":
+ if ctx.dns_backend != "NONE":
ctx.join_add_dns_records()
ctx.join_replicate_new_dns_records()
print("Join failed - cleaning up")
except IOError:
pass
- if not ctx.clone_only:
- ctx.cleanup_old_join()
+ ctx.cleanup_old_join()
raise
def join_RODC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
targetdir=None, domain=None, domain_critical_only=False,
machinepass=None, use_ntvfs=False, dns_backend=None,
- promote_existing=False, plaintext_secrets=False):
+ promote_existing=False, plaintext_secrets=False,
+ backend_store=None):
"""Join as a RODC."""
- ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
- machinepass, use_ntvfs, dns_backend, promote_existing,
- plaintext_secrets)
+ ctx = DCJoinContext(logger, server, creds, lp, site, netbios_name,
+ targetdir, domain, machinepass, use_ntvfs, dns_backend,
+ promote_existing, plaintext_secrets,
+ backend_store=backend_store)
lp.set("workgroup", ctx.domain_name)
logger.info("workgroup is %s" % ctx.domain_name)
samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
- ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
- "RestrictedKrbHost/%s" % ctx.dnshostname ])
+ ctx.SPNs.extend(["RestrictedKrbHost/%s" % ctx.myname,
+ "RestrictedKrbHost/%s" % ctx.dnshostname])
ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
ctx.secure_channel_type = misc.SEC_CHAN_RODC
ctx.RODC = True
- ctx.replica_flags |= ( drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
+ ctx.replica_flags |= (drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
ctx.domain_replica_flags = ctx.replica_flags
if domain_critical_only:
def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
targetdir=None, domain=None, domain_critical_only=False,
machinepass=None, use_ntvfs=False, dns_backend=None,
- promote_existing=False, plaintext_secrets=False):
+ promote_existing=False, plaintext_secrets=False,
+ backend_store=None):
"""Join as a DC."""
- ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
- machinepass, use_ntvfs, dns_backend, promote_existing,
- plaintext_secrets)
+ ctx = DCJoinContext(logger, server, creds, lp, site, netbios_name,
+ targetdir, domain, machinepass, use_ntvfs, dns_backend,
+ promote_existing, plaintext_secrets,
+ backend_store=backend_store)
lp.set("workgroup", ctx.domain_name)
logger.info("workgroup is %s" % ctx.domain_name)
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):
- """Join as a DC."""
- ctx = dc_join(logger, server, creds, lp, site=None, netbios_name=None, targetdir=targetdir, domain=domain,
- machinepass=None, use_ntvfs=False, dns_backend="NONE", promote_existing=False, clone_only=True)
+ targetdir=None, domain=None, include_secrets=False,
+ dns_backend="NONE"):
+ """Creates a local clone of a remote DC."""
+ ctx = DCCloneContext(logger, server, creds, lp, targetdir=targetdir,
+ domain=domain, dns_backend=dns_backend,
+ include_secrets=include_secrets)
lp.set("workgroup", ctx.domain_name)
logger.info("workgroup is %s" % ctx.domain_name)
lp.set("realm", ctx.realm)
logger.info("realm is %s" % ctx.realm)
- ctx.replica_flags |= (drsuapi.DRSUAPI_DRS_WRIT_REP |
- drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS)
- if not include_secrets:
- ctx.replica_flags |= drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING
- ctx.domain_replica_flags = ctx.replica_flags
-
ctx.do_join()
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,
- dns_backend=None, plaintext_secrets=False):
+ netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
+ netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False,
+ dns_backend=None, plaintext_secrets=False,
+ backend_store=None):
"""Join as a DC."""
- ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, parent_domain,
- machinepass, use_ntvfs, dns_backend, plaintext_secrets)
+ ctx = DCJoinContext(logger, server, creds, lp, site, netbios_name,
+ targetdir, parent_domain, machinepass, use_ntvfs,
+ dns_backend, plaintext_secrets,
+ backend_store=backend_store)
ctx.subdomain = True
if adminpass is None:
ctx.adminpass = samba.generate_random_password(12, 32)
ctx.do_join()
ctx.logger.info("Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
+
+
+class DCCloneContext(DCJoinContext):
+ """Clones a remote DC."""
+
+ def __init__(ctx, logger=None, server=None, creds=None, lp=None,
+ targetdir=None, domain=None, dns_backend=None,
+ include_secrets=False):
+ super(DCCloneContext, ctx).__init__(logger, server, creds, lp,
+ targetdir=targetdir, domain=domain,
+ dns_backend=dns_backend)
+
+ # As we don't want to create or delete these DNs, we set them to None
+ ctx.server_dn = None
+ ctx.ntds_dn = None
+ ctx.acct_dn = None
+ ctx.myname = ctx.server.split('.')[0]
+ ctx.ntds_guid = None
+ ctx.rid_manager_dn = None
+
+ # Save this early
+ ctx.remote_dc_ntds_guid = ctx.samdb.get_ntds_GUID()
+
+ ctx.replica_flags |= (drsuapi.DRSUAPI_DRS_WRIT_REP |
+ drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS)
+ if not include_secrets:
+ ctx.replica_flags |= drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING
+ ctx.domain_replica_flags = ctx.replica_flags
+
+ def join_finalise(ctx):
+ ctx.logger.info("Setting isSynchronized and dsServiceName")
+ m = ldb.Message()
+ m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
+ m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE,
+ "isSynchronized")
+
+ # We want to appear to be the server we just cloned
+ guid = ctx.remote_dc_ntds_guid
+ m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(guid),
+ ldb.FLAG_MOD_REPLACE,
+ "dsServiceName")
+ ctx.local_samdb.modify(m)
+
+ def do_join(ctx):
+ ctx.build_nc_lists()
+
+ # When cloning a DC, we just want to provision a DC locally, then
+ # grab the remote DC's entire DB via DRS replication
+ 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