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 base64 import b64encode
42 class DCJoinException(Exception):
44 def __init__(self, msg):
45 super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
48 class dc_join(object):
49 """Perform a DC join."""
51 def __init__(ctx, logger=None, server=None, creds=None, lp=None, site=None,
52 netbios_name=None, targetdir=None, domain=None,
53 machinepass=None, use_ntvfs=False, dns_backend=None,
54 promote_existing=False, clone_only=False):
55 ctx.clone_only=clone_only
61 ctx.targetdir = targetdir
62 ctx.use_ntvfs = use_ntvfs
64 ctx.promote_existing = promote_existing
65 ctx.promote_from_dn = None
70 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
71 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
73 if server is not None:
76 ctx.logger.info("Finding a writeable DC for domain '%s'" % domain)
77 ctx.server = ctx.find_dc(domain)
78 ctx.logger.info("Found DC %s" % ctx.server)
80 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
81 session_info=system_session(),
82 credentials=ctx.creds, lp=ctx.lp)
85 ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
86 except ldb.LdbError, (enum, estr):
87 raise DCJoinException(estr)
90 ctx.base_dn = str(ctx.samdb.get_default_basedn())
91 ctx.root_dn = str(ctx.samdb.get_root_basedn())
92 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
93 ctx.config_dn = str(ctx.samdb.get_config_basedn())
94 ctx.domsid = security.dom_sid(ctx.samdb.get_domain_sid())
95 ctx.forestsid = ctx.domsid
96 ctx.domain_name = ctx.get_domain_name()
97 ctx.forest_domain_name = ctx.get_forest_domain_name()
98 ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
100 ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName()
101 ctx.dc_dnsHostName = ctx.get_dnsHostName()
102 ctx.behavior_version = ctx.get_behavior_version()
104 if machinepass is not None:
105 ctx.acct_pass = machinepass
107 ctx.acct_pass = samba.generate_random_password(32, 40)
109 ctx.dnsdomain = ctx.samdb.domain_dns_name()
111 # As we don't want to create or delete these DNs, we set them to None
115 ctx.myname = ctx.server.split('.')[0]
119 ctx.remote_dc_ntds_guid = ctx.samdb.get_ntds_GUID()
121 # work out the DNs of all the objects we will be adding
122 ctx.myname = netbios_name
123 ctx.samname = "%s$" % ctx.myname
124 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
125 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
126 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
127 ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
128 ctx.dnsforest = ctx.samdb.forest_dns_name()
130 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
131 if ctx.dn_exists(topology_base):
132 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
134 ctx.topology_dn = None
136 ctx.SPNs = [ "HOST/%s" % ctx.myname,
137 "HOST/%s" % ctx.dnshostname,
138 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
140 ctx.domaindns_zone = 'DC=DomainDnsZones,%s' % ctx.base_dn
141 ctx.forestdns_zone = 'DC=ForestDnsZones,%s' % ctx.root_dn
143 expr = "(&(objectClass=crossRef)(ncName=%s))" % ldb.binary_encode(ctx.domaindns_zone)
144 res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
146 base=ctx.samdb.get_partitions_dn(),
148 if dns_backend is None:
149 ctx.dns_backend = "NONE"
151 if len(res_domaindns) == 0:
152 ctx.dns_backend = "NONE"
153 print "NO DNS zone information found in source domain, not replicating DNS"
155 ctx.dns_backend = dns_backend
157 ctx.realm = ctx.dnsdomain
161 # these elements are optional
162 ctx.never_reveal_sid = None
163 ctx.reveal_sid = None
164 ctx.connection_dn = None
169 ctx.subdomain = False
171 ctx.partition_dn = None
173 def del_noerror(ctx, dn, recursive=False):
176 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
180 ctx.del_noerror(r.dn, recursive=True)
183 print "Deleted %s" % dn
187 def cleanup_old_accounts(ctx):
188 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
189 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
190 attrs=["msDS-krbTgtLink", "objectSID"])
194 creds = Credentials()
197 creds.set_machine_account(ctx.lp)
198 machine_samdb = SamDB(url="ldap://%s" % ctx.server,
199 session_info=system_session(),
200 credentials=creds, lp=ctx.lp)
204 token_res = machine_samdb.search(scope=ldb.SCOPE_BASE, base="", attrs=["tokenGroups"])
205 if token_res[0]["tokenGroups"][0] \
206 == res[0]["objectSID"][0]:
207 raise DCJoinException("Not removing account %s which "
208 "looks like a Samba DC account "
209 "maching the password we already have. "
210 "To override, remove secrets.ldb and secrets.tdb"
213 ctx.del_noerror(res[0].dn, recursive=True)
215 if "msDS-Krbtgtlink" in res[0]:
216 new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
217 del_noerror(ctx.new_krbtgt_dn)
219 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
220 expression='(&(sAMAccountName=%s)(servicePrincipalName=%s))' %
221 (ldb.binary_encode("dns-%s" % ctx.myname),
222 ldb.binary_encode("dns/%s" % ctx.dnshostname)),
225 ctx.del_noerror(res[0].dn, recursive=True)
227 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
228 expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname),
231 raise DCJoinException("Not removing account %s which looks like "
232 "a Samba DNS service account but does not "
233 "have servicePrincipalName=%s" %
234 (ldb.binary_encode("dns-%s" % ctx.myname),
235 ldb.binary_encode("dns/%s" % ctx.dnshostname)))
238 def cleanup_old_join(ctx):
239 """Remove any DNs from a previous join."""
240 # find the krbtgt link
241 if not ctx.subdomain:
242 ctx.cleanup_old_accounts()
244 if ctx.connection_dn is not None:
245 ctx.del_noerror(ctx.connection_dn)
246 if ctx.krbtgt_dn is not None:
247 ctx.del_noerror(ctx.krbtgt_dn)
248 ctx.del_noerror(ctx.ntds_dn)
249 ctx.del_noerror(ctx.server_dn, recursive=True)
251 ctx.del_noerror(ctx.topology_dn)
253 ctx.del_noerror(ctx.partition_dn)
256 binding_options = "sign"
257 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
260 objectAttr = lsa.ObjectAttribute()
261 objectAttr.sec_qos = lsa.QosInfo()
263 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
264 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
267 name.string = ctx.realm
268 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
270 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
273 name.string = ctx.forest_domain_name
274 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
276 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
279 def promote_possible(ctx):
280 """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
282 # This shouldn't happen
283 raise Exception("Can not promote into a subdomain")
285 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
286 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
287 attrs=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
289 raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname)
290 if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]:
291 raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname)
292 if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0):
293 raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname)
295 ctx.promote_from_dn = res[0].dn
298 def find_dc(ctx, domain):
299 """find a writeable DC for the given domain"""
301 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
303 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
304 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
305 ctx.site = ctx.cldap_ret.client_site
306 return ctx.cldap_ret.pdc_dns_name
309 def get_behavior_version(ctx):
310 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
311 if "msDS-Behavior-Version" in res[0]:
312 return int(res[0]["msDS-Behavior-Version"][0])
314 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
316 def get_dnsHostName(ctx):
317 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
318 return res[0]["dnsHostName"][0]
320 def get_domain_name(ctx):
321 '''get netbios name of the domain from the partitions record'''
322 partitions_dn = ctx.samdb.get_partitions_dn()
323 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
324 expression='ncName=%s' % ldb.binary_encode(str(ctx.samdb.get_default_basedn())))
325 return res[0]["nETBIOSName"][0]
327 def get_forest_domain_name(ctx):
328 '''get netbios name of the domain from the partitions record'''
329 partitions_dn = ctx.samdb.get_partitions_dn()
330 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
331 expression='ncName=%s' % ldb.binary_encode(str(ctx.samdb.get_root_basedn())))
332 return res[0]["nETBIOSName"][0]
334 def get_parent_partition_dn(ctx):
335 '''get the parent domain partition DN from parent DNS name'''
336 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
337 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
338 (ldb.binary_encode(ctx.parent_dnsdomain),
339 ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
340 return str(res[0].dn)
342 def get_naming_master(ctx):
343 '''get the parent domain partition DN from parent DNS name'''
344 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
345 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
346 if not 'fSMORoleOwner' in res[0]:
347 raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
349 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
351 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0])
353 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
357 '''get the SID of the connected user. Only works with w2k8 and later,
358 so only used for RODC join'''
359 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
360 binsid = res[0]["tokenGroups"][0]
361 return ctx.samdb.schema_format_value("objectSID", binsid)
363 def dn_exists(ctx, dn):
364 '''check if a DN exists'''
366 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
367 except ldb.LdbError, (enum, estr):
368 if enum == ldb.ERR_NO_SUCH_OBJECT:
373 def add_krbtgt_account(ctx):
374 '''RODCs need a special krbtgt account'''
375 print "Adding %s" % ctx.krbtgt_dn
377 "dn" : ctx.krbtgt_dn,
378 "objectclass" : "user",
379 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
380 samba.dsdb.UF_ACCOUNTDISABLE),
381 "showinadvancedviewonly" : "TRUE",
382 "description" : "krbtgt for %s" % ctx.samname}
383 ctx.samdb.add(rec, ["rodc_join:1:1"])
385 # now we need to search for the samAccountName attribute on the krbtgt DN,
386 # as this will have been magically set to the krbtgt number
387 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
388 ctx.krbtgt_name = res[0]["samAccountName"][0]
390 print "Got krbtgt_name=%s" % ctx.krbtgt_name
393 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
394 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
395 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
398 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
399 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
400 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
402 def drsuapi_connect(ctx):
403 '''make a DRSUAPI connection to the naming master'''
404 binding_options = "seal"
405 if int(ctx.lp.get("log level")) >= 4:
406 binding_options += ",print"
407 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
408 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
409 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
411 def create_tmp_samdb(ctx):
412 '''create a temporary samdb object for schema queries'''
413 ctx.tmp_schema = Schema(ctx.domsid,
414 schemadn=ctx.schema_dn)
415 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
416 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
418 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
420 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
421 '''build a DsReplicaAttributeCtr object'''
422 r = drsuapi.DsReplicaAttribute()
423 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
427 def DsAddEntry(ctx, recs):
428 '''add a record via the DRSUAPI DsAddEntry call'''
429 if ctx.drsuapi is None:
430 ctx.drsuapi_connect()
431 if ctx.tmp_samdb is None:
432 ctx.create_tmp_samdb()
436 id = drsuapi.DsReplicaObjectIdentifier()
443 if not isinstance(rec[a], list):
447 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
450 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
451 attribute_ctr.num_attributes = len(attrs)
452 attribute_ctr.attributes = attrs
454 object = drsuapi.DsReplicaObject()
455 object.identifier = id
456 object.attribute_ctr = attribute_ctr
458 list_object = drsuapi.DsReplicaObjectListItem()
459 list_object.object = object
460 objects.append(list_object)
462 req2 = drsuapi.DsAddEntryRequest2()
463 req2.first_object = objects[0]
464 prev = req2.first_object
465 for o in objects[1:]:
469 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
471 if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
472 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
473 raise RuntimeError("DsAddEntry failed")
474 if ctr.extended_err != (0, 'WERR_OK'):
475 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
476 raise RuntimeError("DsAddEntry failed")
479 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
480 if ctr.err_data.status != (0, 'WERR_OK'):
481 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
482 ctr.err_data.info.extended_err))
483 raise RuntimeError("DsAddEntry failed")
484 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
485 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
486 raise RuntimeError("DsAddEntry failed")
490 def join_ntdsdsa_obj(ctx):
491 '''return the ntdsdsa object to add'''
493 print "Adding %s" % ctx.ntds_dn
496 "objectclass" : "nTDSDSA",
497 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
498 "dMDLocation" : ctx.schema_dn}
500 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
502 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
503 rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
505 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
506 rec["msDS-HasDomainNCs"] = ctx.base_dn
509 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
510 rec["msDS-HasFullReplicaNCs"] = ctx.full_nc_list
511 rec["options"] = "37"
513 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
514 rec["HasMasterNCs"] = []
516 if nc in ctx.full_nc_list:
517 rec["HasMasterNCs"].append(nc)
518 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
519 rec["msDS-HasMasterNCs"] = ctx.full_nc_list
521 rec["invocationId"] = ndr_pack(ctx.invocation_id)
525 def join_add_ntdsdsa(ctx):
526 '''add the ntdsdsa object'''
528 rec = ctx.join_ntdsdsa_obj()
530 ctx.samdb.add(rec, ["rodc_join:1:1"])
532 ctx.DsAddEntry([rec])
534 # find the GUID of our NTDS DN
535 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
536 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
538 def join_add_objects(ctx):
539 '''add the various objects needed for the join'''
541 print "Adding %s" % ctx.acct_dn
544 "objectClass": "computer",
545 "displayname": ctx.samname,
546 "samaccountname" : ctx.samname,
547 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
548 "dnshostname" : ctx.dnshostname}
549 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
550 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
551 elif ctx.promote_existing:
552 rec['msDS-SupportedEncryptionTypes'] = []
554 rec["managedby"] = ctx.managedby
555 elif ctx.promote_existing:
556 rec["managedby"] = []
558 if ctx.never_reveal_sid:
559 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
560 elif ctx.promote_existing:
561 rec["msDS-NeverRevealGroup"] = []
564 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
565 elif ctx.promote_existing:
566 rec["msDS-RevealOnDemandGroup"] = []
568 if ctx.promote_existing:
569 if ctx.promote_from_dn != ctx.acct_dn:
570 ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn)
571 ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE))
576 ctx.add_krbtgt_account()
579 print "Adding %s" % ctx.server_dn
582 "objectclass" : "server",
583 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
584 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
585 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
586 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
587 # windows seems to add the dnsHostName later
588 "dnsHostName" : ctx.dnshostname}
591 rec["serverReference"] = ctx.acct_dn
596 # the rest is done after replication
601 ctx.join_add_ntdsdsa()
603 if ctx.connection_dn is not None:
604 print "Adding %s" % ctx.connection_dn
606 "dn" : ctx.connection_dn,
607 "objectclass" : "nTDSConnection",
608 "enabledconnection" : "TRUE",
610 "fromServer" : ctx.dc_ntds_dn}
614 print "Adding SPNs to %s" % ctx.acct_dn
616 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
617 for i in range(len(ctx.SPNs)):
618 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
619 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
620 ldb.FLAG_MOD_REPLACE,
621 "servicePrincipalName")
624 # The account password set operation should normally be done over
625 # LDAP. Windows 2000 DCs however allow this only with SSL
626 # connections which are hard to set up and otherwise refuse with
627 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
629 print "Setting account password for %s" % ctx.samname
631 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
632 % ldb.binary_encode(ctx.samname),
634 force_change_at_next_login=False,
635 username=ctx.samname)
636 except ldb.LdbError, (num, _):
637 if num != ldb.ERR_UNWILLING_TO_PERFORM:
639 ctx.net.set_password(account_name=ctx.samname,
640 domain_name=ctx.domain_name,
641 newpassword=ctx.acct_pass)
643 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
644 attrs=["msDS-KeyVersionNumber"])
645 if "msDS-KeyVersionNumber" in res[0]:
646 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
648 ctx.key_version_number = None
650 print("Enabling account")
652 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
653 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
654 ldb.FLAG_MOD_REPLACE,
655 "userAccountControl")
658 if ctx.dns_backend.startswith("BIND9_"):
659 ctx.dnspass = samba.generate_random_password(128, 255)
661 recs = ctx.samdb.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"),
662 {"DNSDOMAIN": ctx.dnsdomain,
663 "DOMAINDN": ctx.base_dn,
664 "HOSTNAME" : ctx.myname,
665 "DNSPASS_B64": b64encode(ctx.dnspass),
666 "DNSNAME" : ctx.dnshostname}))
667 for changetype, msg in recs:
668 assert changetype == ldb.CHANGETYPE_NONE
669 dns_acct_dn = msg["dn"]
670 print "Adding DNS account %s with dns/ SPN" % msg["dn"]
672 # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP)
673 del msg["clearTextPassword"]
674 # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP
675 del msg["isCriticalSystemObject"]
676 # Disable account until password is set
677 msg["userAccountControl"] = str(samba.dsdb.UF_NORMAL_ACCOUNT |
678 samba.dsdb.UF_ACCOUNTDISABLE)
681 except ldb.LdbError, (num, _):
682 if num != ldb.ERR_ENTRY_ALREADY_EXISTS:
685 # The account password set operation should normally be done over
686 # LDAP. Windows 2000 DCs however allow this only with SSL
687 # connections which are hard to set up and otherwise refuse with
688 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
690 print "Setting account password for dns-%s" % ctx.myname
692 ctx.samdb.setpassword("(&(objectClass=user)(samAccountName=dns-%s))"
693 % ldb.binary_encode(ctx.myname),
695 force_change_at_next_login=False,
696 username=ctx.samname)
697 except ldb.LdbError, (num, _):
698 if num != ldb.ERR_UNWILLING_TO_PERFORM:
700 ctx.net.set_password(account_name="dns-%s" % ctx.myname,
701 domain_name=ctx.domain_name,
702 newpassword=ctx.dnspass)
704 res = ctx.samdb.search(base=dns_acct_dn, scope=ldb.SCOPE_BASE,
705 attrs=["msDS-KeyVersionNumber"])
706 if "msDS-KeyVersionNumber" in res[0]:
707 ctx.dns_key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
709 ctx.dns_key_version_number = None
711 def join_add_objects2(ctx):
712 """add the various objects needed for the join, for subdomains post replication"""
714 print "Adding %s" % ctx.partition_dn
715 name_map = {'SubdomainAdmins': "%s-%s" % (str(ctx.domsid), security.DOMAIN_RID_ADMINS)}
716 sd_binary = descriptor.get_paritions_crossref_subdomain_descriptor(ctx.forestsid, name_map=name_map)
718 "dn" : ctx.partition_dn,
719 "objectclass" : "crossRef",
720 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
721 "nCName" : ctx.base_dn,
722 "nETBIOSName" : ctx.domain_name,
723 "dnsRoot": ctx.dnsdomain,
724 "trustParent" : ctx.parent_partition_dn,
725 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN),
726 "ntSecurityDescriptor" : sd_binary,
729 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
730 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
732 rec2 = ctx.join_ntdsdsa_obj()
734 objects = ctx.DsAddEntry([rec, rec2])
735 if len(objects) != 2:
736 raise DCJoinException("Expected 2 objects from DsAddEntry")
738 ctx.ntds_guid = objects[1].guid
740 print("Replicating partition DN")
741 ctx.repl.replicate(ctx.partition_dn,
742 misc.GUID("00000000-0000-0000-0000-000000000000"),
744 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
745 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
747 print("Replicating NTDS DN")
748 ctx.repl.replicate(ctx.ntds_dn,
749 misc.GUID("00000000-0000-0000-0000-000000000000"),
751 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
752 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
754 def join_provision(ctx):
755 """Provision the local SAM."""
757 print "Calling bare provision"
759 smbconf = ctx.lp.configfile
761 presult = provision(ctx.logger, system_session(), smbconf=smbconf,
762 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
763 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
764 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
765 serverdn=ctx.server_dn, domain=ctx.domain_name,
766 hostname=ctx.myname, domainsid=ctx.domsid,
767 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
768 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
769 use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend)
770 print "Provision OK for domain DN %s" % presult.domaindn
771 ctx.local_samdb = presult.samdb
773 ctx.paths = presult.paths
774 ctx.names = presult.names
776 # Fix up the forestsid, it may be different if we are joining as a subdomain
777 ctx.names.forestsid = ctx.forestsid
779 def join_provision_own_domain(ctx):
780 """Provision the local SAM."""
782 # we now operate exclusively on the local database, which
783 # we need to reopen in order to get the newly created schema
784 print("Reconnecting to local samdb")
785 ctx.samdb = SamDB(url=ctx.local_samdb.url,
786 session_info=system_session(),
787 lp=ctx.local_samdb.lp,
789 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
790 ctx.local_samdb = ctx.samdb
792 ctx.logger.info("Finding domain GUID from ncName")
793 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
794 controls=["extended_dn:1:1", "reveal_internals:0"])
796 if 'nCName' not in res[0]:
797 raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
800 ctx.names.domainguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
802 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['ncName'][0])
804 ctx.logger.info("Got domain GUID %s" % ctx.names.domainguid)
806 ctx.logger.info("Calling own domain provision")
808 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
810 presult = provision_fill(ctx.local_samdb, secrets_ldb,
811 ctx.logger, ctx.names, ctx.paths,
812 dom_for_fun_level=DS_DOMAIN_FUNCTION_2003,
813 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
814 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
815 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
816 dns_backend=ctx.dns_backend, adminpass=ctx.adminpass)
817 print("Provision OK for domain %s" % ctx.names.dnsdomain)
819 def join_replicate(ctx):
820 """Replicate the SAM."""
822 print "Starting replication"
823 ctx.local_samdb.transaction_start()
825 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
826 if ctx.ntds_guid is None:
827 print("Using DS_BIND_GUID_W2K3")
828 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
830 destination_dsa_guid = ctx.ntds_guid
833 repl_creds = Credentials()
834 repl_creds.guess(ctx.lp)
835 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
836 repl_creds.set_username(ctx.samname)
837 repl_creds.set_password(ctx.acct_pass)
839 repl_creds = ctx.creds
841 binding_options = "seal"
842 if int(ctx.lp.get("log level")) >= 5:
843 binding_options += ",print"
844 repl = drs_utils.drs_Replicate(
845 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
846 ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id)
848 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
849 destination_dsa_guid, schema=True, rodc=ctx.RODC,
850 replica_flags=ctx.replica_flags)
851 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
852 destination_dsa_guid, rodc=ctx.RODC,
853 replica_flags=ctx.replica_flags)
854 if not ctx.subdomain:
855 # Replicate first the critical object for the basedn
856 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
857 print "Replicating critical objects from the base DN of the domain"
858 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
859 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
860 destination_dsa_guid, rodc=ctx.RODC,
861 replica_flags=ctx.domain_replica_flags)
862 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
864 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
865 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
866 destination_dsa_guid, rodc=ctx.RODC,
867 replica_flags=ctx.domain_replica_flags)
868 print "Done with always replicated NC (base, config, schema)"
870 for nc in (ctx.domaindns_zone, ctx.forestdns_zone):
871 if nc in ctx.nc_list:
872 print "Replicating %s" % (str(nc))
873 repl.replicate(nc, source_dsa_invocation_id,
874 destination_dsa_guid, rodc=ctx.RODC,
875 replica_flags=ctx.replica_flags)
877 # FIXME At this point we should add an entry in the forestdns and domaindns NC
878 # (those under CN=Partions,DC=...)
879 # in order to indicate that we hold a replica for this NC
882 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
883 destination_dsa_guid,
884 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
885 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
886 destination_dsa_guid,
887 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
889 ctx.source_dsa_invocation_id = source_dsa_invocation_id
890 ctx.destination_dsa_guid = destination_dsa_guid
892 print "Committing SAM database"
894 ctx.local_samdb.transaction_cancel()
897 ctx.local_samdb.transaction_commit()
899 def send_DsReplicaUpdateRefs(ctx, dn):
900 r = drsuapi.DsReplicaUpdateRefsRequest1()
901 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
902 r.naming_context.dn = str(dn)
903 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
904 r.naming_context.sid = security.dom_sid("S-0-0")
905 r.dest_dsa_guid = ctx.ntds_guid
906 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
907 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
909 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
912 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
914 def join_finalise(ctx):
915 """Finalise the join, mark us synchronised and setup secrets db."""
917 # FIXME we shouldn't do this in all cases
919 # If for some reasons we joined in another site than the one of
920 # DC we just replicated from then we don't need to send the updatereplicateref
921 # as replication between sites is time based and on the initiative of the
923 if not ctx.clone_only:
924 ctx.logger.info("Sending DsReplicaUpdateRefs for all the replicated partitions")
925 for nc in ctx.nc_list:
926 ctx.send_DsReplicaUpdateRefs(nc)
928 if not ctx.clone_only and ctx.RODC:
929 print "Setting RODC invocationId"
930 ctx.local_samdb.set_invocation_id(str(ctx.invocation_id))
931 ctx.local_samdb.set_opaque_integer("domainFunctionality",
932 ctx.behavior_version)
934 m.dn = ldb.Dn(ctx.local_samdb, "%s" % ctx.ntds_dn)
935 m["invocationId"] = ldb.MessageElement(ndr_pack(ctx.invocation_id),
936 ldb.FLAG_MOD_REPLACE,
938 ctx.local_samdb.modify(m)
940 # Note: as RODC the invocationId is only stored
941 # on the RODC itself, the other DCs never see it.
943 # Thats is why we fix up the replPropertyMetaData stamp
944 # for the 'invocationId' attribute, we need to change
945 # the 'version' to '0', this is what windows 2008r2 does as RODC
947 # This means if the object on a RWDC ever gets a invocationId
948 # attribute, it will have version '1' (or higher), which will
949 # will overwrite the RODC local value.
950 ctx.local_samdb.set_attribute_replmetadata_version(m.dn,
954 ctx.logger.info("Setting isSynchronized and dsServiceName")
956 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
957 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
959 # We want to appear to be the server we just cloned
961 guid = ctx.remote_dc_ntds_guid
965 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(guid),
966 ldb.FLAG_MOD_REPLACE, "dsServiceName")
967 ctx.local_samdb.modify(m)
969 if ctx.clone_only or ctx.subdomain:
972 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
974 ctx.logger.info("Setting up secrets database")
975 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
977 dnsdomain=ctx.dnsdomain,
978 netbiosname=ctx.myname,
979 domainsid=ctx.domsid,
980 machinepass=ctx.acct_pass,
981 secure_channel_type=ctx.secure_channel_type,
982 key_version_number=ctx.key_version_number)
984 if ctx.dns_backend.startswith("BIND9_"):
985 setup_bind9_dns(ctx.local_samdb, secrets_ldb,
986 ctx.names, ctx.paths, ctx.lp, ctx.logger,
987 dns_backend=ctx.dns_backend,
988 dnspass=ctx.dnspass, os_level=ctx.behavior_version,
989 targetdir=ctx.targetdir,
990 key_version_number=ctx.dns_key_version_number)
992 def join_setup_trusts(ctx):
993 """provision the local SAM."""
995 print "Setup domain trusts with server %s" % ctx.server
996 binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key
997 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
1000 objectAttr = lsa.ObjectAttribute()
1001 objectAttr.sec_qos = lsa.QosInfo()
1003 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
1004 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
1006 info = lsa.TrustDomainInfoInfoEx()
1007 info.domain_name.string = ctx.dnsdomain
1008 info.netbios_name.string = ctx.domain_name
1009 info.sid = ctx.domsid
1010 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
1011 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
1012 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
1015 oldname = lsa.String()
1016 oldname.string = ctx.dnsdomain
1017 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
1018 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
1019 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
1020 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
1021 except RuntimeError:
1024 password_blob = string_to_byte_array(ctx.trustdom_pass.encode('utf-16-le'))
1026 clear_value = drsblobs.AuthInfoClear()
1027 clear_value.size = len(password_blob)
1028 clear_value.password = password_blob
1030 clear_authentication_information = drsblobs.AuthenticationInformation()
1031 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
1032 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
1033 clear_authentication_information.AuthInfo = clear_value
1035 authentication_information_array = drsblobs.AuthenticationInformationArray()
1036 authentication_information_array.count = 1
1037 authentication_information_array.array = [clear_authentication_information]
1039 outgoing = drsblobs.trustAuthInOutBlob()
1041 outgoing.current = authentication_information_array
1043 trustpass = drsblobs.trustDomainPasswords()
1044 confounder = [3] * 512
1046 for i in range(512):
1047 confounder[i] = random.randint(0, 255)
1049 trustpass.confounder = confounder
1051 trustpass.outgoing = outgoing
1052 trustpass.incoming = outgoing
1054 trustpass_blob = ndr_pack(trustpass)
1056 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
1058 auth_blob = lsa.DATA_BUF2()
1059 auth_blob.size = len(encrypted_trustpass)
1060 auth_blob.data = string_to_byte_array(encrypted_trustpass)
1062 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
1063 auth_info.auth_blob = auth_blob
1065 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
1068 security.SEC_STD_DELETE)
1071 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
1072 "objectclass" : "trustedDomain",
1073 "trustType" : str(info.trust_type),
1074 "trustAttributes" : str(info.trust_attributes),
1075 "trustDirection" : str(info.trust_direction),
1076 "flatname" : ctx.forest_domain_name,
1077 "trustPartner" : ctx.dnsforest,
1078 "trustAuthIncoming" : ndr_pack(outgoing),
1079 "trustAuthOutgoing" : ndr_pack(outgoing),
1080 "securityIdentifier" : ndr_pack(ctx.forestsid)
1082 ctx.local_samdb.add(rec)
1085 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
1086 "objectclass" : "user",
1087 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
1088 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le'),
1089 "samAccountName" : "%s$" % ctx.forest_domain_name
1091 ctx.local_samdb.add(rec)
1095 # nc_list is the list of naming context (NC) for which we will
1096 # replicate in and send a updateRef command to the partner DC
1098 # full_nc_list is the list of naming context (NC) we hold
1099 # read/write copies of. These are not subsets of each other.
1100 ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
1101 ctx.full_nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
1103 if ctx.subdomain and ctx.dns_backend != "NONE":
1104 ctx.full_nc_list += [ctx.domaindns_zone]
1106 elif not ctx.subdomain:
1107 ctx.nc_list += [ctx.base_dn]
1109 if ctx.dns_backend != "NONE":
1110 ctx.nc_list += [ctx.domaindns_zone]
1111 ctx.nc_list += [ctx.forestdns_zone]
1112 ctx.full_nc_list += [ctx.domaindns_zone]
1113 ctx.full_nc_list += [ctx.forestdns_zone]
1115 if not ctx.clone_only:
1116 if ctx.promote_existing:
1117 ctx.promote_possible()
1119 ctx.cleanup_old_join()
1122 if not ctx.clone_only:
1123 ctx.join_add_objects()
1124 ctx.join_provision()
1125 ctx.join_replicate()
1126 if (not ctx.clone_only and ctx.subdomain):
1127 ctx.join_add_objects2()
1128 ctx.join_provision_own_domain()
1129 ctx.join_setup_trusts()
1133 print "Join failed - cleaning up"
1136 if not ctx.clone_only:
1137 ctx.cleanup_old_join()
1141 def join_RODC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1142 targetdir=None, domain=None, domain_critical_only=False,
1143 machinepass=None, use_ntvfs=False, dns_backend=None,
1144 promote_existing=False):
1145 """Join as a RODC."""
1147 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1148 machinepass, use_ntvfs, dns_backend, promote_existing)
1150 lp.set("workgroup", ctx.domain_name)
1151 logger.info("workgroup is %s" % ctx.domain_name)
1153 lp.set("realm", ctx.realm)
1154 logger.info("realm is %s" % ctx.realm)
1156 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
1158 # setup some defaults for accounts that should be replicated to this RODC
1159 ctx.never_reveal_sid = [
1160 "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
1161 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
1162 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
1163 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
1164 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS]
1165 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
1167 mysid = ctx.get_mysid()
1168 admin_dn = "<SID=%s>" % mysid
1169 ctx.managedby = admin_dn
1171 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
1172 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1173 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
1175 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
1176 "RestrictedKrbHost/%s" % ctx.dnshostname ])
1178 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
1179 ctx.secure_channel_type = misc.SEC_CHAN_RODC
1181 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
1182 drsuapi.DRSUAPI_DRS_PER_SYNC |
1183 drsuapi.DRSUAPI_DRS_GET_ANC |
1184 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
1185 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1186 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
1187 ctx.domain_replica_flags = ctx.replica_flags
1188 if domain_critical_only:
1189 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1193 logger.info("Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid))
1196 def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1197 targetdir=None, domain=None, domain_critical_only=False,
1198 machinepass=None, use_ntvfs=False, dns_backend=None,
1199 promote_existing=False):
1201 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1202 machinepass, use_ntvfs, dns_backend, promote_existing)
1204 lp.set("workgroup", ctx.domain_name)
1205 logger.info("workgroup is %s" % ctx.domain_name)
1207 lp.set("realm", ctx.realm)
1208 logger.info("realm is %s" % ctx.realm)
1210 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1212 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1213 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1215 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1216 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1217 drsuapi.DRSUAPI_DRS_PER_SYNC |
1218 drsuapi.DRSUAPI_DRS_GET_ANC |
1219 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1220 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1221 ctx.domain_replica_flags = ctx.replica_flags
1222 if domain_critical_only:
1223 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1226 logger.info("Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
1228 def join_clone(logger=None, server=None, creds=None, lp=None,
1229 targetdir=None, domain=None, include_secrets=False):
1231 ctx = dc_join(logger, server, creds, lp, site=None, netbios_name=None, targetdir=targetdir, domain=domain,
1232 machinepass=None, use_ntvfs=False, dns_backend="NONE", promote_existing=False, clone_only=True)
1234 lp.set("workgroup", ctx.domain_name)
1235 logger.info("workgroup is %s" % ctx.domain_name)
1237 lp.set("realm", ctx.realm)
1238 logger.info("realm is %s" % ctx.realm)
1240 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1241 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1242 drsuapi.DRSUAPI_DRS_PER_SYNC |
1243 drsuapi.DRSUAPI_DRS_GET_ANC |
1244 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1245 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1246 if not include_secrets:
1247 ctx.replica_flags |= drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING
1248 ctx.domain_replica_flags = ctx.replica_flags
1251 logger.info("Cloned domain %s (SID %s)" % (ctx.domain_name, ctx.domsid))
1253 def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None,
1254 netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
1255 netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False,
1258 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, parent_domain,
1259 machinepass, use_ntvfs, dns_backend)
1260 ctx.subdomain = True
1261 if adminpass is None:
1262 ctx.adminpass = samba.generate_random_password(12, 32)
1264 ctx.adminpass = adminpass
1265 ctx.parent_domain_name = ctx.domain_name
1266 ctx.domain_name = netbios_domain
1267 ctx.realm = dnsdomain
1268 ctx.parent_dnsdomain = ctx.dnsdomain
1269 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1270 ctx.dnsdomain = dnsdomain
1271 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1272 ctx.naming_master = ctx.get_naming_master()
1273 if ctx.naming_master != ctx.server:
1274 logger.info("Reconnecting to naming master %s" % ctx.naming_master)
1275 ctx.server = ctx.naming_master
1276 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1277 session_info=system_session(),
1278 credentials=ctx.creds, lp=ctx.lp)
1279 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=['dnsHostName'],
1281 ctx.server = res[0]["dnsHostName"]
1282 logger.info("DNS name of new naming master is %s" % ctx.server)
1284 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1285 ctx.forestsid = ctx.domsid
1286 ctx.domsid = security.random_sid()
1288 ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
1289 ctx.trustdom_pass = samba.generate_random_password(128, 128)
1291 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1293 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1294 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1296 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1297 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1298 drsuapi.DRSUAPI_DRS_PER_SYNC |
1299 drsuapi.DRSUAPI_DRS_GET_ANC |
1300 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1301 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1302 ctx.domain_replica_flags = ctx.replica_flags
1305 ctx.logger.info("Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))