2 # Copyright Andrew Tridgell 2010
3 # Copyright Andrew Bartlett 2010
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 """Joining a domain."""
21 from samba.auth import system_session
22 from samba.samdb import SamDB
23 from samba import gensec, Ldb, drs_utils, arcfour_encrypt, string_to_byte_array
24 import ldb, samba, sys, uuid
25 from samba.ndr import ndr_pack
26 from samba.dcerpc import security, drsuapi, misc, nbt, lsa, drsblobs
27 from samba.dsdb import DS_DOMAIN_FUNCTION_2003
28 from samba.credentials import Credentials, DONT_USE_KERBEROS
29 from samba.provision import secretsdb_self_join, provision, provision_fill, FILL_DRS, FILL_SUBDOMAIN
30 from samba.provision.common import setup_path
31 from samba.schema import Schema
32 from samba import descriptor
33 from samba.net import Net
34 from samba.provision.sambadns import setup_bind9_dns
35 from samba import read_and_sub_file
36 from samba import werror
37 from base64 import b64encode
43 class DCJoinException(Exception):
45 def __init__(self, msg):
46 super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
49 class dc_join(object):
50 """Perform a DC join."""
52 def __init__(ctx, logger=None, server=None, creds=None, lp=None, site=None,
53 netbios_name=None, targetdir=None, domain=None,
54 machinepass=None, use_ntvfs=False, dns_backend=None,
55 promote_existing=False, clone_only=False):
57 site = "Default-First-Site-Name"
59 ctx.clone_only=clone_only
65 ctx.targetdir = targetdir
66 ctx.use_ntvfs = use_ntvfs
68 ctx.promote_existing = promote_existing
69 ctx.promote_from_dn = None
74 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
75 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
77 if server is not None:
80 ctx.logger.info("Finding a writeable DC for domain '%s'" % domain)
81 ctx.server = ctx.find_dc(domain)
82 ctx.logger.info("Found DC %s" % ctx.server)
84 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
85 session_info=system_session(),
86 credentials=ctx.creds, lp=ctx.lp)
89 ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
90 except ldb.LdbError, (enum, estr):
91 raise DCJoinException(estr)
94 ctx.base_dn = str(ctx.samdb.get_default_basedn())
95 ctx.root_dn = str(ctx.samdb.get_root_basedn())
96 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
97 ctx.config_dn = str(ctx.samdb.get_config_basedn())
98 ctx.domsid = security.dom_sid(ctx.samdb.get_domain_sid())
99 ctx.forestsid = ctx.domsid
100 ctx.domain_name = ctx.get_domain_name()
101 ctx.forest_domain_name = ctx.get_forest_domain_name()
102 ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
104 ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName()
105 ctx.dc_dnsHostName = ctx.get_dnsHostName()
106 ctx.behavior_version = ctx.get_behavior_version()
108 if machinepass is not None:
109 ctx.acct_pass = machinepass
111 ctx.acct_pass = samba.generate_random_machine_password(128, 255)
113 ctx.dnsdomain = ctx.samdb.domain_dns_name()
115 # As we don't want to create or delete these DNs, we set them to None
119 ctx.myname = ctx.server.split('.')[0]
121 ctx.rid_manager_dn = None
124 ctx.remote_dc_ntds_guid = ctx.samdb.get_ntds_GUID()
126 # work out the DNs of all the objects we will be adding
127 ctx.myname = netbios_name
128 ctx.samname = "%s$" % ctx.myname
129 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
130 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
131 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
132 ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
133 ctx.dnsforest = ctx.samdb.forest_dns_name()
135 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
136 if ctx.dn_exists(topology_base):
137 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
139 ctx.topology_dn = None
141 ctx.SPNs = [ "HOST/%s" % ctx.myname,
142 "HOST/%s" % ctx.dnshostname,
143 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
145 res_rid_manager = ctx.samdb.search(scope=ldb.SCOPE_BASE,
146 attrs=["rIDManagerReference"],
149 ctx.rid_manager_dn = res_rid_manager[0]["rIDManagerReference"][0]
151 ctx.domaindns_zone = 'DC=DomainDnsZones,%s' % ctx.base_dn
152 ctx.forestdns_zone = 'DC=ForestDnsZones,%s' % ctx.root_dn
154 expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.domaindns_zone)
155 res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
157 base=ctx.samdb.get_partitions_dn(),
159 if dns_backend is None:
160 ctx.dns_backend = "NONE"
162 if len(res_domaindns) == 0:
163 ctx.dns_backend = "NONE"
164 print "NO DNS zone information found in source domain, not replicating DNS"
166 ctx.dns_backend = dns_backend
168 ctx.realm = ctx.dnsdomain
172 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
173 drsuapi.DRSUAPI_DRS_PER_SYNC |
174 drsuapi.DRSUAPI_DRS_GET_ANC |
175 drsuapi.DRSUAPI_DRS_GET_NC_SIZE |
176 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
178 # these elements are optional
179 ctx.never_reveal_sid = None
180 ctx.reveal_sid = None
181 ctx.connection_dn = None
186 ctx.subdomain = False
188 ctx.partition_dn = None
190 def del_noerror(ctx, dn, recursive=False):
193 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
197 ctx.del_noerror(r.dn, recursive=True)
200 print "Deleted %s" % dn
204 def cleanup_old_accounts(ctx, force=False):
205 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
206 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
207 attrs=["msDS-krbTgtLink", "objectSID"])
212 creds = Credentials()
215 creds.set_machine_account(ctx.lp)
216 creds.set_kerberos_state(ctx.creds.get_kerberos_state())
217 machine_samdb = SamDB(url="ldap://%s" % ctx.server,
218 session_info=system_session(),
219 credentials=creds, lp=ctx.lp)
223 token_res = machine_samdb.search(scope=ldb.SCOPE_BASE, base="", attrs=["tokenGroups"])
224 if token_res[0]["tokenGroups"][0] \
225 == res[0]["objectSID"][0]:
226 raise DCJoinException("Not removing account %s which "
227 "looks like a Samba DC account "
228 "maching the password we already have. "
229 "To override, remove secrets.ldb and secrets.tdb"
232 ctx.del_noerror(res[0].dn, recursive=True)
234 if "msDS-Krbtgtlink" in res[0]:
235 new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
236 ctx.del_noerror(ctx.new_krbtgt_dn)
238 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
239 expression='(&(sAMAccountName=%s)(servicePrincipalName=%s))' %
240 (ldb.binary_encode("dns-%s" % ctx.myname),
241 ldb.binary_encode("dns/%s" % ctx.dnshostname)),
244 ctx.del_noerror(res[0].dn, recursive=True)
246 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
247 expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname),
250 raise DCJoinException("Not removing account %s which looks like "
251 "a Samba DNS service account but does not "
252 "have servicePrincipalName=%s" %
253 (ldb.binary_encode("dns-%s" % ctx.myname),
254 ldb.binary_encode("dns/%s" % ctx.dnshostname)))
257 def cleanup_old_join(ctx, force=False):
258 """Remove any DNs from a previous join."""
259 # find the krbtgt link
260 if not ctx.subdomain:
261 ctx.cleanup_old_accounts(force=force)
263 if ctx.connection_dn is not None:
264 ctx.del_noerror(ctx.connection_dn)
265 if ctx.krbtgt_dn is not None:
266 ctx.del_noerror(ctx.krbtgt_dn)
267 ctx.del_noerror(ctx.ntds_dn)
268 ctx.del_noerror(ctx.server_dn, recursive=True)
270 ctx.del_noerror(ctx.topology_dn)
272 ctx.del_noerror(ctx.partition_dn)
275 binding_options = "sign"
276 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
279 objectAttr = lsa.ObjectAttribute()
280 objectAttr.sec_qos = lsa.QosInfo()
282 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
283 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
286 name.string = ctx.realm
287 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
289 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
292 name.string = ctx.forest_domain_name
293 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
295 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
298 def promote_possible(ctx):
299 """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
301 # This shouldn't happen
302 raise Exception("Can not promote into a subdomain")
304 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
305 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
306 attrs=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
308 raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname)
309 if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]:
310 raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname)
311 if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0):
312 raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname)
314 ctx.promote_from_dn = res[0].dn
317 def find_dc(ctx, domain):
318 """find a writeable DC for the given domain"""
320 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
322 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
323 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
324 ctx.site = ctx.cldap_ret.client_site
325 return ctx.cldap_ret.pdc_dns_name
328 def get_behavior_version(ctx):
329 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
330 if "msDS-Behavior-Version" in res[0]:
331 return int(res[0]["msDS-Behavior-Version"][0])
333 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
335 def get_dnsHostName(ctx):
336 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
337 return res[0]["dnsHostName"][0]
339 def get_domain_name(ctx):
340 '''get netbios name of the domain from the partitions record'''
341 partitions_dn = ctx.samdb.get_partitions_dn()
342 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
343 expression='ncName=%s' % ldb.binary_encode(str(ctx.samdb.get_default_basedn())))
344 return res[0]["nETBIOSName"][0]
346 def get_forest_domain_name(ctx):
347 '''get netbios name of the domain from the partitions record'''
348 partitions_dn = ctx.samdb.get_partitions_dn()
349 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
350 expression='ncName=%s' % ldb.binary_encode(str(ctx.samdb.get_root_basedn())))
351 return res[0]["nETBIOSName"][0]
353 def get_parent_partition_dn(ctx):
354 '''get the parent domain partition DN from parent DNS name'''
355 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
356 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
357 (ldb.binary_encode(ctx.parent_dnsdomain),
358 ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
359 return str(res[0].dn)
361 def get_naming_master(ctx):
362 '''get the parent domain partition DN from parent DNS name'''
363 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
364 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
365 if not 'fSMORoleOwner' in res[0]:
366 raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
368 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
370 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0])
372 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
376 '''get the SID of the connected user. Only works with w2k8 and later,
377 so only used for RODC join'''
378 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
379 binsid = res[0]["tokenGroups"][0]
380 return ctx.samdb.schema_format_value("objectSID", binsid)
382 def dn_exists(ctx, dn):
383 '''check if a DN exists'''
385 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
386 except ldb.LdbError, (enum, estr):
387 if enum == ldb.ERR_NO_SUCH_OBJECT:
392 def add_krbtgt_account(ctx):
393 '''RODCs need a special krbtgt account'''
394 print "Adding %s" % ctx.krbtgt_dn
396 "dn" : ctx.krbtgt_dn,
397 "objectclass" : "user",
398 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
399 samba.dsdb.UF_ACCOUNTDISABLE),
400 "showinadvancedviewonly" : "TRUE",
401 "description" : "krbtgt for %s" % ctx.samname}
402 ctx.samdb.add(rec, ["rodc_join:1:1"])
404 # now we need to search for the samAccountName attribute on the krbtgt DN,
405 # as this will have been magically set to the krbtgt number
406 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
407 ctx.krbtgt_name = res[0]["samAccountName"][0]
409 print "Got krbtgt_name=%s" % ctx.krbtgt_name
412 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
413 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
414 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
417 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
418 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
419 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
421 def drsuapi_connect(ctx):
422 '''make a DRSUAPI connection to the naming master'''
423 binding_options = "seal"
424 if ctx.lp.log_level() >= 4:
425 binding_options += ",print"
426 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
427 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
428 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
430 def create_tmp_samdb(ctx):
431 '''create a temporary samdb object for schema queries'''
432 ctx.tmp_schema = Schema(ctx.domsid,
433 schemadn=ctx.schema_dn)
434 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
435 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
437 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
439 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
440 '''build a DsReplicaAttributeCtr object'''
441 r = drsuapi.DsReplicaAttribute()
442 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
446 def DsAddEntry(ctx, recs):
447 '''add a record via the DRSUAPI DsAddEntry call'''
448 if ctx.drsuapi is None:
449 ctx.drsuapi_connect()
450 if ctx.tmp_samdb is None:
451 ctx.create_tmp_samdb()
455 id = drsuapi.DsReplicaObjectIdentifier()
462 if not isinstance(rec[a], list):
466 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
469 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
470 attribute_ctr.num_attributes = len(attrs)
471 attribute_ctr.attributes = attrs
473 object = drsuapi.DsReplicaObject()
474 object.identifier = id
475 object.attribute_ctr = attribute_ctr
477 list_object = drsuapi.DsReplicaObjectListItem()
478 list_object.object = object
479 objects.append(list_object)
481 req2 = drsuapi.DsAddEntryRequest2()
482 req2.first_object = objects[0]
483 prev = req2.first_object
484 for o in objects[1:]:
488 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
490 if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
491 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
492 raise RuntimeError("DsAddEntry failed")
493 if ctr.extended_err[0] != werror.WERR_SUCCESS:
494 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
495 raise RuntimeError("DsAddEntry failed")
498 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
499 if ctr.err_data.status[0] != werror.WERR_SUCCESS:
500 if ctr.err_data.info is None:
501 print("DsAddEntry failed with status %s, info omitted" % (ctr.err_data.status[1]))
503 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status[1],
504 ctr.err_data.info.extended_err))
505 raise RuntimeError("DsAddEntry failed")
506 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
507 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
508 raise RuntimeError("DsAddEntry failed")
512 def join_ntdsdsa_obj(ctx):
513 '''return the ntdsdsa object to add'''
515 print "Adding %s" % ctx.ntds_dn
518 "objectclass" : "nTDSDSA",
519 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
520 "dMDLocation" : ctx.schema_dn}
522 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
524 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
525 rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
527 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
528 rec["msDS-HasDomainNCs"] = ctx.base_dn
531 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
532 rec["msDS-HasFullReplicaNCs"] = ctx.full_nc_list
533 rec["options"] = "37"
535 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
536 rec["HasMasterNCs"] = []
538 if nc in ctx.full_nc_list:
539 rec["HasMasterNCs"].append(nc)
540 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
541 rec["msDS-HasMasterNCs"] = ctx.full_nc_list
543 rec["invocationId"] = ndr_pack(ctx.invocation_id)
547 def join_add_ntdsdsa(ctx):
548 '''add the ntdsdsa object'''
550 rec = ctx.join_ntdsdsa_obj()
552 ctx.samdb.add(rec, ["rodc_join:1:1"])
554 ctx.DsAddEntry([rec])
556 # find the GUID of our NTDS DN
557 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
558 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
560 def join_add_objects(ctx):
561 '''add the various objects needed for the join'''
563 print "Adding %s" % ctx.acct_dn
566 "objectClass": "computer",
567 "displayname": ctx.samname,
568 "samaccountname" : ctx.samname,
569 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
570 "dnshostname" : ctx.dnshostname}
571 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
572 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
573 elif ctx.promote_existing:
574 rec['msDS-SupportedEncryptionTypes'] = []
576 rec["managedby"] = ctx.managedby
577 elif ctx.promote_existing:
578 rec["managedby"] = []
580 if ctx.never_reveal_sid:
581 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
582 elif ctx.promote_existing:
583 rec["msDS-NeverRevealGroup"] = []
586 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
587 elif ctx.promote_existing:
588 rec["msDS-RevealOnDemandGroup"] = []
590 if ctx.promote_existing:
591 if ctx.promote_from_dn != ctx.acct_dn:
592 ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn)
593 ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE))
598 ctx.add_krbtgt_account()
601 print "Adding %s" % ctx.server_dn
604 "objectclass" : "server",
605 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
606 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
607 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
608 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
609 # windows seems to add the dnsHostName later
610 "dnsHostName" : ctx.dnshostname}
613 rec["serverReference"] = ctx.acct_dn
618 # the rest is done after replication
623 ctx.join_add_ntdsdsa()
625 # Add the Replica-Locations or RO-Replica-Locations attributes
626 # TODO Is this supposed to be for the schema partition too?
627 expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.domaindns_zone)
628 domain = (ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
630 base=ctx.samdb.get_partitions_dn(),
631 expression=expr), ctx.domaindns_zone)
633 expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.forestdns_zone)
634 forest = (ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
636 base=ctx.samdb.get_partitions_dn(),
637 expression=expr), ctx.forestdns_zone)
639 for part, zone in (domain, forest):
640 if zone not in ctx.nc_list:
646 attr = "msDS-NC-Replica-Locations"
648 attr = "msDS-NC-RO-Replica-Locations"
650 m[attr] = ldb.MessageElement(ctx.ntds_dn,
651 ldb.FLAG_MOD_ADD, attr)
654 if ctx.connection_dn is not None:
655 print "Adding %s" % ctx.connection_dn
657 "dn" : ctx.connection_dn,
658 "objectclass" : "nTDSConnection",
659 "enabledconnection" : "TRUE",
661 "fromServer" : ctx.dc_ntds_dn}
665 print "Adding SPNs to %s" % ctx.acct_dn
667 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
668 for i in range(len(ctx.SPNs)):
669 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
670 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
671 ldb.FLAG_MOD_REPLACE,
672 "servicePrincipalName")
675 # The account password set operation should normally be done over
676 # LDAP. Windows 2000 DCs however allow this only with SSL
677 # connections which are hard to set up and otherwise refuse with
678 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
680 print "Setting account password for %s" % ctx.samname
682 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
683 % ldb.binary_encode(ctx.samname),
685 force_change_at_next_login=False,
686 username=ctx.samname)
687 except ldb.LdbError, (num, _):
688 if num != ldb.ERR_UNWILLING_TO_PERFORM:
690 ctx.net.set_password(account_name=ctx.samname,
691 domain_name=ctx.domain_name,
692 newpassword=ctx.acct_pass.encode('utf-8'))
694 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
695 attrs=["msDS-KeyVersionNumber"])
696 if "msDS-KeyVersionNumber" in res[0]:
697 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
699 ctx.key_version_number = None
701 print("Enabling account")
703 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
704 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
705 ldb.FLAG_MOD_REPLACE,
706 "userAccountControl")
709 if ctx.dns_backend.startswith("BIND9_"):
710 ctx.dnspass = samba.generate_random_password(128, 255)
712 recs = ctx.samdb.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"),
713 {"DNSDOMAIN": ctx.dnsdomain,
714 "DOMAINDN": ctx.base_dn,
715 "HOSTNAME" : ctx.myname,
716 "DNSPASS_B64": b64encode(ctx.dnspass.encode('utf-16-le')),
717 "DNSNAME" : ctx.dnshostname}))
718 for changetype, msg in recs:
719 assert changetype == ldb.CHANGETYPE_NONE
720 dns_acct_dn = msg["dn"]
721 print "Adding DNS account %s with dns/ SPN" % msg["dn"]
723 # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP)
724 del msg["clearTextPassword"]
725 # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP
726 del msg["isCriticalSystemObject"]
727 # Disable account until password is set
728 msg["userAccountControl"] = str(samba.dsdb.UF_NORMAL_ACCOUNT |
729 samba.dsdb.UF_ACCOUNTDISABLE)
732 except ldb.LdbError, (num, _):
733 if num != ldb.ERR_ENTRY_ALREADY_EXISTS:
736 # The account password set operation should normally be done over
737 # LDAP. Windows 2000 DCs however allow this only with SSL
738 # connections which are hard to set up and otherwise refuse with
739 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
741 print "Setting account password for dns-%s" % ctx.myname
743 ctx.samdb.setpassword("(&(objectClass=user)(samAccountName=dns-%s))"
744 % ldb.binary_encode(ctx.myname),
746 force_change_at_next_login=False,
747 username=ctx.samname)
748 except ldb.LdbError, (num, _):
749 if num != ldb.ERR_UNWILLING_TO_PERFORM:
751 ctx.net.set_password(account_name="dns-%s" % ctx.myname,
752 domain_name=ctx.domain_name,
753 newpassword=ctx.dnspass)
755 res = ctx.samdb.search(base=dns_acct_dn, scope=ldb.SCOPE_BASE,
756 attrs=["msDS-KeyVersionNumber"])
757 if "msDS-KeyVersionNumber" in res[0]:
758 ctx.dns_key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
760 ctx.dns_key_version_number = None
762 def join_add_objects2(ctx):
763 """add the various objects needed for the join, for subdomains post replication"""
765 print "Adding %s" % ctx.partition_dn
766 name_map = {'SubdomainAdmins': "%s-%s" % (str(ctx.domsid), security.DOMAIN_RID_ADMINS)}
767 sd_binary = descriptor.get_paritions_crossref_subdomain_descriptor(ctx.forestsid, name_map=name_map)
769 "dn" : ctx.partition_dn,
770 "objectclass" : "crossRef",
771 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
772 "nCName" : ctx.base_dn,
773 "nETBIOSName" : ctx.domain_name,
774 "dnsRoot": ctx.dnsdomain,
775 "trustParent" : ctx.parent_partition_dn,
776 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN),
777 "ntSecurityDescriptor" : sd_binary,
780 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
781 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
783 rec2 = ctx.join_ntdsdsa_obj()
785 objects = ctx.DsAddEntry([rec, rec2])
786 if len(objects) != 2:
787 raise DCJoinException("Expected 2 objects from DsAddEntry")
789 ctx.ntds_guid = objects[1].guid
791 print("Replicating partition DN")
792 ctx.repl.replicate(ctx.partition_dn,
793 misc.GUID("00000000-0000-0000-0000-000000000000"),
795 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
796 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
798 print("Replicating NTDS DN")
799 ctx.repl.replicate(ctx.ntds_dn,
800 misc.GUID("00000000-0000-0000-0000-000000000000"),
802 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
803 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
805 def join_provision(ctx):
806 """Provision the local SAM."""
808 print "Calling bare provision"
810 smbconf = ctx.lp.configfile
812 presult = provision(ctx.logger, system_session(), smbconf=smbconf,
813 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
814 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
815 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
816 serverdn=ctx.server_dn, domain=ctx.domain_name,
817 hostname=ctx.myname, domainsid=ctx.domsid,
818 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
819 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
820 use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend)
821 print "Provision OK for domain DN %s" % presult.domaindn
822 ctx.local_samdb = presult.samdb
824 ctx.paths = presult.paths
825 ctx.names = presult.names
827 # Fix up the forestsid, it may be different if we are joining as a subdomain
828 ctx.names.forestsid = ctx.forestsid
830 def join_provision_own_domain(ctx):
831 """Provision the local SAM."""
833 # we now operate exclusively on the local database, which
834 # we need to reopen in order to get the newly created schema
835 print("Reconnecting to local samdb")
836 ctx.samdb = SamDB(url=ctx.local_samdb.url,
837 session_info=system_session(),
838 lp=ctx.local_samdb.lp,
840 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
841 ctx.local_samdb = ctx.samdb
843 ctx.logger.info("Finding domain GUID from ncName")
844 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
845 controls=["extended_dn:1:1", "reveal_internals:0"])
847 if 'nCName' not in res[0]:
848 raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
851 ctx.names.domainguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
853 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['ncName'][0])
855 ctx.logger.info("Got domain GUID %s" % ctx.names.domainguid)
857 ctx.logger.info("Calling own domain provision")
859 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
861 presult = provision_fill(ctx.local_samdb, secrets_ldb,
862 ctx.logger, ctx.names, ctx.paths,
863 dom_for_fun_level=DS_DOMAIN_FUNCTION_2003,
864 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
865 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
866 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
867 dns_backend=ctx.dns_backend, adminpass=ctx.adminpass)
868 print("Provision OK for domain %s" % ctx.names.dnsdomain)
870 def join_replicate(ctx):
871 """Replicate the SAM."""
873 print "Starting replication"
874 ctx.local_samdb.transaction_start()
876 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
877 if ctx.ntds_guid is None:
878 print("Using DS_BIND_GUID_W2K3")
879 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
881 destination_dsa_guid = ctx.ntds_guid
884 repl_creds = Credentials()
885 repl_creds.guess(ctx.lp)
886 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
887 repl_creds.set_username(ctx.samname)
888 repl_creds.set_password(ctx.acct_pass.encode('utf-8'))
890 repl_creds = ctx.creds
892 binding_options = "seal"
893 if ctx.lp.log_level() >= 5:
894 binding_options += ",print"
895 repl = drs_utils.drs_Replicate(
896 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
897 ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id)
899 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
900 destination_dsa_guid, schema=True, rodc=ctx.RODC,
901 replica_flags=ctx.replica_flags)
902 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
903 destination_dsa_guid, rodc=ctx.RODC,
904 replica_flags=ctx.replica_flags)
905 if not ctx.subdomain:
906 # Replicate first the critical object for the basedn
907 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
908 print "Replicating critical objects from the base DN of the domain"
909 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
910 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
911 destination_dsa_guid, rodc=ctx.RODC,
912 replica_flags=ctx.domain_replica_flags)
913 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
914 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
915 destination_dsa_guid, rodc=ctx.RODC,
916 replica_flags=ctx.domain_replica_flags)
917 print "Done with always replicated NC (base, config, schema)"
919 # At this point we should already have an entry in the ForestDNS
920 # and DomainDNS NC (those under CN=Partions,DC=...) in order to
921 # indicate that we hold a replica for this NC.
922 for nc in (ctx.domaindns_zone, ctx.forestdns_zone):
923 if nc in ctx.nc_list:
924 print "Replicating %s" % (str(nc))
925 repl.replicate(nc, source_dsa_invocation_id,
926 destination_dsa_guid, rodc=ctx.RODC,
927 replica_flags=ctx.replica_flags)
930 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
931 destination_dsa_guid,
932 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
933 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
934 destination_dsa_guid,
935 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
936 elif ctx.rid_manager_dn != None:
937 # Try and get a RID Set if we can. This is only possible against the RID Master. Warn otherwise.
939 repl.replicate(ctx.rid_manager_dn, source_dsa_invocation_id,
940 destination_dsa_guid,
941 exop=drsuapi.DRSUAPI_EXOP_FSMO_RID_ALLOC)
942 except samba.DsExtendedError, (enum, estr):
943 if enum == drsuapi.DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER:
944 print "WARNING: Unable to replicate own RID Set, as server %s (the server we joined) is not the RID Master." % ctx.server
945 print "NOTE: This is normal and expected, Samba will be able to create users after it contacts the RID Master at first startup."
950 ctx.source_dsa_invocation_id = source_dsa_invocation_id
951 ctx.destination_dsa_guid = destination_dsa_guid
953 print "Committing SAM database"
955 ctx.local_samdb.transaction_cancel()
958 ctx.local_samdb.transaction_commit()
960 def send_DsReplicaUpdateRefs(ctx, dn):
961 r = drsuapi.DsReplicaUpdateRefsRequest1()
962 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
963 r.naming_context.dn = str(dn)
964 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
965 r.naming_context.sid = security.dom_sid("S-0-0")
966 r.dest_dsa_guid = ctx.ntds_guid
967 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
968 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
970 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
972 if ctx.drsuapi is None:
973 ctx.drsuapi_connect()
975 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
977 def join_finalise(ctx):
978 """Finalise the join, mark us synchronised and setup secrets db."""
980 # FIXME we shouldn't do this in all cases
982 # If for some reasons we joined in another site than the one of
983 # DC we just replicated from then we don't need to send the updatereplicateref
984 # as replication between sites is time based and on the initiative of the
986 if not ctx.clone_only:
987 ctx.logger.info("Sending DsReplicaUpdateRefs for all the replicated partitions")
988 for nc in ctx.nc_list:
989 ctx.send_DsReplicaUpdateRefs(nc)
991 if not ctx.clone_only and ctx.RODC:
992 print "Setting RODC invocationId"
993 ctx.local_samdb.set_invocation_id(str(ctx.invocation_id))
994 ctx.local_samdb.set_opaque_integer("domainFunctionality",
995 ctx.behavior_version)
997 m.dn = ldb.Dn(ctx.local_samdb, "%s" % ctx.ntds_dn)
998 m["invocationId"] = ldb.MessageElement(ndr_pack(ctx.invocation_id),
999 ldb.FLAG_MOD_REPLACE,
1001 ctx.local_samdb.modify(m)
1003 # Note: as RODC the invocationId is only stored
1004 # on the RODC itself, the other DCs never see it.
1006 # Thats is why we fix up the replPropertyMetaData stamp
1007 # for the 'invocationId' attribute, we need to change
1008 # the 'version' to '0', this is what windows 2008r2 does as RODC
1010 # This means if the object on a RWDC ever gets a invocationId
1011 # attribute, it will have version '1' (or higher), which will
1012 # will overwrite the RODC local value.
1013 ctx.local_samdb.set_attribute_replmetadata_version(m.dn,
1017 ctx.logger.info("Setting isSynchronized and dsServiceName")
1019 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
1020 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
1022 # We want to appear to be the server we just cloned
1024 guid = ctx.remote_dc_ntds_guid
1026 guid = ctx.ntds_guid
1028 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(guid),
1029 ldb.FLAG_MOD_REPLACE, "dsServiceName")
1030 ctx.local_samdb.modify(m)
1032 if ctx.clone_only or ctx.subdomain:
1035 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
1037 ctx.logger.info("Setting up secrets database")
1038 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
1040 dnsdomain=ctx.dnsdomain,
1041 netbiosname=ctx.myname,
1042 domainsid=ctx.domsid,
1043 machinepass=ctx.acct_pass,
1044 secure_channel_type=ctx.secure_channel_type,
1045 key_version_number=ctx.key_version_number)
1047 if ctx.dns_backend.startswith("BIND9_"):
1048 setup_bind9_dns(ctx.local_samdb, secrets_ldb,
1049 ctx.names, ctx.paths, ctx.lp, ctx.logger,
1050 dns_backend=ctx.dns_backend,
1051 dnspass=ctx.dnspass, os_level=ctx.behavior_version,
1052 targetdir=ctx.targetdir,
1053 key_version_number=ctx.dns_key_version_number)
1055 def join_setup_trusts(ctx):
1056 """provision the local SAM."""
1058 print "Setup domain trusts with server %s" % ctx.server
1059 binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key
1060 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
1063 objectAttr = lsa.ObjectAttribute()
1064 objectAttr.sec_qos = lsa.QosInfo()
1066 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
1067 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
1069 info = lsa.TrustDomainInfoInfoEx()
1070 info.domain_name.string = ctx.dnsdomain
1071 info.netbios_name.string = ctx.domain_name
1072 info.sid = ctx.domsid
1073 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
1074 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
1075 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
1078 oldname = lsa.String()
1079 oldname.string = ctx.dnsdomain
1080 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
1081 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
1082 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
1083 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
1084 except RuntimeError:
1087 password_blob = string_to_byte_array(ctx.trustdom_pass.encode('utf-16-le'))
1089 clear_value = drsblobs.AuthInfoClear()
1090 clear_value.size = len(password_blob)
1091 clear_value.password = password_blob
1093 clear_authentication_information = drsblobs.AuthenticationInformation()
1094 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
1095 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
1096 clear_authentication_information.AuthInfo = clear_value
1098 authentication_information_array = drsblobs.AuthenticationInformationArray()
1099 authentication_information_array.count = 1
1100 authentication_information_array.array = [clear_authentication_information]
1102 outgoing = drsblobs.trustAuthInOutBlob()
1104 outgoing.current = authentication_information_array
1106 trustpass = drsblobs.trustDomainPasswords()
1107 confounder = [3] * 512
1109 for i in range(512):
1110 confounder[i] = random.randint(0, 255)
1112 trustpass.confounder = confounder
1114 trustpass.outgoing = outgoing
1115 trustpass.incoming = outgoing
1117 trustpass_blob = ndr_pack(trustpass)
1119 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
1121 auth_blob = lsa.DATA_BUF2()
1122 auth_blob.size = len(encrypted_trustpass)
1123 auth_blob.data = string_to_byte_array(encrypted_trustpass)
1125 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
1126 auth_info.auth_blob = auth_blob
1128 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
1131 security.SEC_STD_DELETE)
1134 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
1135 "objectclass" : "trustedDomain",
1136 "trustType" : str(info.trust_type),
1137 "trustAttributes" : str(info.trust_attributes),
1138 "trustDirection" : str(info.trust_direction),
1139 "flatname" : ctx.forest_domain_name,
1140 "trustPartner" : ctx.dnsforest,
1141 "trustAuthIncoming" : ndr_pack(outgoing),
1142 "trustAuthOutgoing" : ndr_pack(outgoing),
1143 "securityIdentifier" : ndr_pack(ctx.forestsid)
1145 ctx.local_samdb.add(rec)
1148 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
1149 "objectclass" : "user",
1150 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
1151 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le'),
1152 "samAccountName" : "%s$" % ctx.forest_domain_name
1154 ctx.local_samdb.add(rec)
1158 # nc_list is the list of naming context (NC) for which we will
1159 # replicate in and send a updateRef command to the partner DC
1161 # full_nc_list is the list of naming context (NC) we hold
1162 # read/write copies of. These are not subsets of each other.
1163 ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
1164 ctx.full_nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
1166 if ctx.subdomain and ctx.dns_backend != "NONE":
1167 ctx.full_nc_list += [ctx.domaindns_zone]
1169 elif not ctx.subdomain:
1170 ctx.nc_list += [ctx.base_dn]
1172 if ctx.dns_backend != "NONE":
1173 ctx.nc_list += [ctx.domaindns_zone]
1174 ctx.nc_list += [ctx.forestdns_zone]
1175 ctx.full_nc_list += [ctx.domaindns_zone]
1176 ctx.full_nc_list += [ctx.forestdns_zone]
1178 if not ctx.clone_only:
1179 if ctx.promote_existing:
1180 ctx.promote_possible()
1182 ctx.cleanup_old_join()
1185 if not ctx.clone_only:
1186 ctx.join_add_objects()
1187 ctx.join_provision()
1188 ctx.join_replicate()
1189 if (not ctx.clone_only and ctx.subdomain):
1190 ctx.join_add_objects2()
1191 ctx.join_provision_own_domain()
1192 ctx.join_setup_trusts()
1196 print "Join failed - cleaning up"
1199 if not ctx.clone_only:
1200 ctx.cleanup_old_join()
1204 def join_RODC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1205 targetdir=None, domain=None, domain_critical_only=False,
1206 machinepass=None, use_ntvfs=False, dns_backend=None,
1207 promote_existing=False):
1208 """Join as a RODC."""
1210 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1211 machinepass, use_ntvfs, dns_backend, promote_existing)
1213 lp.set("workgroup", ctx.domain_name)
1214 logger.info("workgroup is %s" % ctx.domain_name)
1216 lp.set("realm", ctx.realm)
1217 logger.info("realm is %s" % ctx.realm)
1219 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
1221 # setup some defaults for accounts that should be replicated to this RODC
1222 ctx.never_reveal_sid = [
1223 "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
1224 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
1225 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
1226 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
1227 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS]
1228 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
1230 mysid = ctx.get_mysid()
1231 admin_dn = "<SID=%s>" % mysid
1232 ctx.managedby = admin_dn
1234 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
1235 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1236 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
1238 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
1239 "RestrictedKrbHost/%s" % ctx.dnshostname ])
1241 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
1242 ctx.secure_channel_type = misc.SEC_CHAN_RODC
1244 ctx.replica_flags |= ( drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1245 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
1246 ctx.domain_replica_flags = ctx.replica_flags
1247 if domain_critical_only:
1248 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1252 logger.info("Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid))
1255 def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1256 targetdir=None, domain=None, domain_critical_only=False,
1257 machinepass=None, use_ntvfs=False, dns_backend=None,
1258 promote_existing=False):
1260 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1261 machinepass, use_ntvfs, dns_backend, promote_existing)
1263 lp.set("workgroup", ctx.domain_name)
1264 logger.info("workgroup is %s" % ctx.domain_name)
1266 lp.set("realm", ctx.realm)
1267 logger.info("realm is %s" % ctx.realm)
1269 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1271 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1272 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1274 ctx.replica_flags |= (drsuapi.DRSUAPI_DRS_WRIT_REP |
1275 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS)
1276 ctx.domain_replica_flags = ctx.replica_flags
1277 if domain_critical_only:
1278 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1281 logger.info("Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
1283 def join_clone(logger=None, server=None, creds=None, lp=None,
1284 targetdir=None, domain=None, include_secrets=False):
1286 ctx = dc_join(logger, server, creds, lp, site=None, netbios_name=None, targetdir=targetdir, domain=domain,
1287 machinepass=None, use_ntvfs=False, dns_backend="NONE", promote_existing=False, clone_only=True)
1289 lp.set("workgroup", ctx.domain_name)
1290 logger.info("workgroup is %s" % ctx.domain_name)
1292 lp.set("realm", ctx.realm)
1293 logger.info("realm is %s" % ctx.realm)
1295 ctx.replica_flags |= (drsuapi.DRSUAPI_DRS_WRIT_REP |
1296 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS)
1297 if not include_secrets:
1298 ctx.replica_flags |= drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING
1299 ctx.domain_replica_flags = ctx.replica_flags
1302 logger.info("Cloned domain %s (SID %s)" % (ctx.domain_name, ctx.domsid))
1304 def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None,
1305 netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
1306 netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False,
1309 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, parent_domain,
1310 machinepass, use_ntvfs, dns_backend)
1311 ctx.subdomain = True
1312 if adminpass is None:
1313 ctx.adminpass = samba.generate_random_password(12, 32)
1315 ctx.adminpass = adminpass
1316 ctx.parent_domain_name = ctx.domain_name
1317 ctx.domain_name = netbios_domain
1318 ctx.realm = dnsdomain
1319 ctx.parent_dnsdomain = ctx.dnsdomain
1320 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1321 ctx.dnsdomain = dnsdomain
1322 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1323 ctx.naming_master = ctx.get_naming_master()
1324 if ctx.naming_master != ctx.server:
1325 logger.info("Reconnecting to naming master %s" % ctx.naming_master)
1326 ctx.server = ctx.naming_master
1327 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1328 session_info=system_session(),
1329 credentials=ctx.creds, lp=ctx.lp)
1330 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=['dnsHostName'],
1332 ctx.server = res[0]["dnsHostName"]
1333 logger.info("DNS name of new naming master is %s" % ctx.server)
1335 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1336 ctx.forestsid = ctx.domsid
1337 ctx.domsid = security.random_sid()
1339 ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
1340 # Windows uses 240 bytes as UTF16 so we do
1341 ctx.trustdom_pass = samba.generate_random_machine_password(120, 120)
1343 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1345 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1346 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1348 ctx.replica_flags |= (drsuapi.DRSUAPI_DRS_WRIT_REP |
1349 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS)
1350 ctx.domain_replica_flags = ctx.replica_flags
1353 ctx.logger.info("Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))