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 # this makes debugging easier
43 talloc.enable_null_tracking()
45 class DCJoinException(Exception):
47 def __init__(self, msg):
48 super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
51 class dc_join(object):
52 """Perform a DC join."""
54 def __init__(ctx, logger=None, server=None, creds=None, lp=None, site=None,
55 netbios_name=None, targetdir=None, domain=None,
56 machinepass=None, use_ntvfs=False, dns_backend=None,
57 promote_existing=False, clone_only=False):
58 ctx.clone_only=clone_only
64 ctx.targetdir = targetdir
65 ctx.use_ntvfs = use_ntvfs
67 ctx.promote_existing = promote_existing
68 ctx.promote_from_dn = None
73 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
74 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
76 if server is not None:
79 ctx.logger.info("Finding a writeable DC for domain '%s'" % domain)
80 ctx.server = ctx.find_dc(domain)
81 ctx.logger.info("Found DC %s" % ctx.server)
83 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
84 session_info=system_session(),
85 credentials=ctx.creds, lp=ctx.lp)
88 ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
89 except ldb.LdbError, (enum, estr):
90 raise DCJoinException(estr)
93 ctx.base_dn = str(ctx.samdb.get_default_basedn())
94 ctx.root_dn = str(ctx.samdb.get_root_basedn())
95 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
96 ctx.config_dn = str(ctx.samdb.get_config_basedn())
97 ctx.domsid = security.dom_sid(ctx.samdb.get_domain_sid())
98 ctx.forestsid = ctx.domsid
99 ctx.domain_name = ctx.get_domain_name()
100 ctx.forest_domain_name = ctx.get_forest_domain_name()
101 ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
103 ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName()
104 ctx.dc_dnsHostName = ctx.get_dnsHostName()
105 ctx.behavior_version = ctx.get_behavior_version()
107 if machinepass is not None:
108 ctx.acct_pass = machinepass
110 ctx.acct_pass = samba.generate_random_password(32, 40)
112 ctx.dnsdomain = ctx.samdb.domain_dns_name()
114 # As we don't want to create or delete these DNs, we set them to None
118 ctx.myname = ctx.server.split('.')[0]
122 ctx.remote_dc_ntds_guid = ctx.samdb.get_ntds_GUID()
124 # work out the DNs of all the objects we will be adding
125 ctx.myname = netbios_name
126 ctx.samname = "%s$" % ctx.myname
127 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
128 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
129 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
130 ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
131 ctx.dnsforest = ctx.samdb.forest_dns_name()
133 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
134 if ctx.dn_exists(topology_base):
135 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
137 ctx.topology_dn = None
139 ctx.SPNs = [ "HOST/%s" % ctx.myname,
140 "HOST/%s" % ctx.dnshostname,
141 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
143 ctx.domaindns_zone = 'DC=DomainDnsZones,%s' % ctx.base_dn
144 ctx.forestdns_zone = 'DC=ForestDnsZones,%s' % ctx.root_dn
146 res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
148 base=ctx.samdb.get_partitions_dn(),
149 expression="(&(objectClass=crossRef)(ncName=%s))" % ctx.domaindns_zone)
150 if dns_backend is None:
151 ctx.dns_backend = "NONE"
153 if len(res_domaindns) == 0:
154 ctx.dns_backend = "NONE"
155 print "NO DNS zone information found in source domain, not replicating DNS"
157 ctx.dns_backend = dns_backend
159 ctx.realm = ctx.dnsdomain
163 # these elements are optional
164 ctx.never_reveal_sid = None
165 ctx.reveal_sid = None
166 ctx.connection_dn = None
171 ctx.subdomain = False
173 ctx.partition_dn = None
175 def del_noerror(ctx, dn, recursive=False):
178 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
182 ctx.del_noerror(r.dn, recursive=True)
185 print "Deleted %s" % dn
189 def cleanup_old_accounts(ctx):
190 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
191 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
192 attrs=["msDS-krbTgtLink", "objectSID"])
196 creds = Credentials()
199 creds.set_machine_account(ctx.lp)
200 machine_samdb = SamDB(url="ldap://%s" % ctx.server,
201 session_info=system_session(),
202 credentials=creds, lp=ctx.lp)
206 token_res = machine_samdb.search(scope=ldb.SCOPE_BASE, base="", attrs=["tokenGroups"])
207 if token_res[0]["tokenGroups"][0] \
208 == res[0]["objectSID"][0]:
209 raise DCJoinException("Not removing account %s which "
210 "looks like a Samba DC account "
211 "maching the password we already have. "
212 "To override, remove secrets.ldb and secrets.tdb"
215 ctx.del_noerror(res[0].dn, recursive=True)
217 if "msDS-Krbtgtlink" in res[0]:
218 new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
219 del_noerror(ctx.new_krbtgt_dn)
221 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
222 expression='(&(sAMAccountName=%s)(servicePrincipalName=%s))' %
223 (ldb.binary_encode("dns-%s" % ctx.myname),
224 ldb.binary_encode("dns/%s" % ctx.dnshostname)),
227 ctx.del_noerror(res[0].dn, recursive=True)
229 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
230 expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname),
233 raise DCJoinException("Not removing account %s which looks like "
234 "a Samba DNS service account but does not "
235 "have servicePrincipalName=%s" %
236 (ldb.binary_encode("dns-%s" % ctx.myname),
237 ldb.binary_encode("dns/%s" % ctx.dnshostname)))
240 def cleanup_old_join(ctx):
241 """Remove any DNs from a previous join."""
242 # find the krbtgt link
243 if not ctx.subdomain:
244 ctx.cleanup_old_accounts()
246 if ctx.connection_dn is not None:
247 ctx.del_noerror(ctx.connection_dn)
248 if ctx.krbtgt_dn is not None:
249 ctx.del_noerror(ctx.krbtgt_dn)
250 ctx.del_noerror(ctx.ntds_dn)
251 ctx.del_noerror(ctx.server_dn, recursive=True)
253 ctx.del_noerror(ctx.topology_dn)
255 ctx.del_noerror(ctx.partition_dn)
258 binding_options = "sign"
259 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
262 objectAttr = lsa.ObjectAttribute()
263 objectAttr.sec_qos = lsa.QosInfo()
265 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
266 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
269 name.string = ctx.realm
270 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
272 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
275 name.string = ctx.forest_domain_name
276 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
278 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
281 def promote_possible(ctx):
282 """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
284 # This shouldn't happen
285 raise Exception("Can not promote into a subdomain")
287 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
288 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
289 attrs=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
291 raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname)
292 if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]:
293 raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname)
294 if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0):
295 raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname)
297 ctx.promote_from_dn = res[0].dn
300 def find_dc(ctx, domain):
301 """find a writeable DC for the given domain"""
303 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
305 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
306 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
307 ctx.site = ctx.cldap_ret.client_site
308 return ctx.cldap_ret.pdc_dns_name
311 def get_behavior_version(ctx):
312 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
313 if "msDS-Behavior-Version" in res[0]:
314 return int(res[0]["msDS-Behavior-Version"][0])
316 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
318 def get_dnsHostName(ctx):
319 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
320 return res[0]["dnsHostName"][0]
322 def get_domain_name(ctx):
323 '''get netbios name of the domain from the partitions record'''
324 partitions_dn = ctx.samdb.get_partitions_dn()
325 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
326 expression='ncName=%s' % ctx.samdb.get_default_basedn())
327 return res[0]["nETBIOSName"][0]
329 def get_forest_domain_name(ctx):
330 '''get netbios name of the domain from the partitions record'''
331 partitions_dn = ctx.samdb.get_partitions_dn()
332 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
333 expression='ncName=%s' % ctx.samdb.get_root_basedn())
334 return res[0]["nETBIOSName"][0]
336 def get_parent_partition_dn(ctx):
337 '''get the parent domain partition DN from parent DNS name'''
338 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
339 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
340 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
341 return str(res[0].dn)
343 def get_naming_master(ctx):
344 '''get the parent domain partition DN from parent DNS name'''
345 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
346 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
347 if not 'fSMORoleOwner' in res[0]:
348 raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
350 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
352 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0])
354 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
358 '''get the SID of the connected user. Only works with w2k8 and later,
359 so only used for RODC join'''
360 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
361 binsid = res[0]["tokenGroups"][0]
362 return ctx.samdb.schema_format_value("objectSID", binsid)
364 def dn_exists(ctx, dn):
365 '''check if a DN exists'''
367 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
368 except ldb.LdbError, (enum, estr):
369 if enum == ldb.ERR_NO_SUCH_OBJECT:
374 def add_krbtgt_account(ctx):
375 '''RODCs need a special krbtgt account'''
376 print "Adding %s" % ctx.krbtgt_dn
378 "dn" : ctx.krbtgt_dn,
379 "objectclass" : "user",
380 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
381 samba.dsdb.UF_ACCOUNTDISABLE),
382 "showinadvancedviewonly" : "TRUE",
383 "description" : "krbtgt for %s" % ctx.samname}
384 ctx.samdb.add(rec, ["rodc_join:1:1"])
386 # now we need to search for the samAccountName attribute on the krbtgt DN,
387 # as this will have been magically set to the krbtgt number
388 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
389 ctx.krbtgt_name = res[0]["samAccountName"][0]
391 print "Got krbtgt_name=%s" % ctx.krbtgt_name
394 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
395 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
396 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
399 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
400 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
401 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
403 def drsuapi_connect(ctx):
404 '''make a DRSUAPI connection to the naming master'''
405 binding_options = "seal"
406 if int(ctx.lp.get("log level")) >= 4:
407 binding_options += ",print"
408 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
409 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
410 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
412 def create_tmp_samdb(ctx):
413 '''create a temporary samdb object for schema queries'''
414 ctx.tmp_schema = Schema(ctx.domsid,
415 schemadn=ctx.schema_dn)
416 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
417 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
419 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
421 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
422 '''build a DsReplicaAttributeCtr object'''
423 r = drsuapi.DsReplicaAttribute()
424 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
428 def DsAddEntry(ctx, recs):
429 '''add a record via the DRSUAPI DsAddEntry call'''
430 if ctx.drsuapi is None:
431 ctx.drsuapi_connect()
432 if ctx.tmp_samdb is None:
433 ctx.create_tmp_samdb()
437 id = drsuapi.DsReplicaObjectIdentifier()
444 if not isinstance(rec[a], list):
448 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
451 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
452 attribute_ctr.num_attributes = len(attrs)
453 attribute_ctr.attributes = attrs
455 object = drsuapi.DsReplicaObject()
456 object.identifier = id
457 object.attribute_ctr = attribute_ctr
459 list_object = drsuapi.DsReplicaObjectListItem()
460 list_object.object = object
461 objects.append(list_object)
463 req2 = drsuapi.DsAddEntryRequest2()
464 req2.first_object = objects[0]
465 prev = req2.first_object
466 for o in objects[1:]:
470 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
472 if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
473 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
474 raise RuntimeError("DsAddEntry failed")
475 if ctr.extended_err != (0, 'WERR_OK'):
476 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
477 raise RuntimeError("DsAddEntry failed")
480 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
481 if ctr.err_data.status != (0, 'WERR_OK'):
482 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
483 ctr.err_data.info.extended_err))
484 raise RuntimeError("DsAddEntry failed")
485 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
486 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
487 raise RuntimeError("DsAddEntry failed")
491 def join_ntdsdsa_obj(ctx):
492 '''return the ntdsdsa object to add'''
494 print "Adding %s" % ctx.ntds_dn
497 "objectclass" : "nTDSDSA",
498 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
499 "dMDLocation" : ctx.schema_dn}
501 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
503 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
504 rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
506 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
507 rec["msDS-HasDomainNCs"] = ctx.base_dn
510 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
511 rec["msDS-HasFullReplicaNCs"] = ctx.full_nc_list
512 rec["options"] = "37"
514 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
515 rec["HasMasterNCs"] = []
517 if nc in ctx.full_nc_list:
518 rec["HasMasterNCs"].append(nc)
519 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
520 rec["msDS-HasMasterNCs"] = ctx.full_nc_list
522 rec["invocationId"] = ndr_pack(ctx.invocation_id)
526 def join_add_ntdsdsa(ctx):
527 '''add the ntdsdsa object'''
529 rec = ctx.join_ntdsdsa_obj()
531 ctx.samdb.add(rec, ["rodc_join:1:1"])
533 ctx.DsAddEntry([rec])
535 # find the GUID of our NTDS DN
536 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
537 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
539 def join_add_objects(ctx):
540 '''add the various objects needed for the join'''
542 print "Adding %s" % ctx.acct_dn
545 "objectClass": "computer",
546 "displayname": ctx.samname,
547 "samaccountname" : ctx.samname,
548 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
549 "dnshostname" : ctx.dnshostname}
550 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
551 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
552 elif ctx.promote_existing:
553 rec['msDS-SupportedEncryptionTypes'] = []
555 rec["managedby"] = ctx.managedby
556 elif ctx.promote_existing:
557 rec["managedby"] = []
559 if ctx.never_reveal_sid:
560 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
561 elif ctx.promote_existing:
562 rec["msDS-NeverRevealGroup"] = []
565 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
566 elif ctx.promote_existing:
567 rec["msDS-RevealOnDemandGroup"] = []
569 if ctx.promote_existing:
570 if ctx.promote_from_dn != ctx.acct_dn:
571 ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn)
572 ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE))
577 ctx.add_krbtgt_account()
580 print "Adding %s" % ctx.server_dn
583 "objectclass" : "server",
584 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
585 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
586 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
587 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
588 # windows seems to add the dnsHostName later
589 "dnsHostName" : ctx.dnshostname}
592 rec["serverReference"] = ctx.acct_dn
597 # the rest is done after replication
602 ctx.join_add_ntdsdsa()
604 if ctx.connection_dn is not None:
605 print "Adding %s" % ctx.connection_dn
607 "dn" : ctx.connection_dn,
608 "objectclass" : "nTDSConnection",
609 "enabledconnection" : "TRUE",
611 "fromServer" : ctx.dc_ntds_dn}
615 print "Adding SPNs to %s" % ctx.acct_dn
617 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
618 for i in range(len(ctx.SPNs)):
619 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
620 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
621 ldb.FLAG_MOD_REPLACE,
622 "servicePrincipalName")
625 # The account password set operation should normally be done over
626 # LDAP. Windows 2000 DCs however allow this only with SSL
627 # connections which are hard to set up and otherwise refuse with
628 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
630 print "Setting account password for %s" % ctx.samname
632 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
633 % ldb.binary_encode(ctx.samname),
635 force_change_at_next_login=False,
636 username=ctx.samname)
637 except ldb.LdbError, (num, _):
638 if num != ldb.ERR_UNWILLING_TO_PERFORM:
640 ctx.net.set_password(account_name=ctx.samname,
641 domain_name=ctx.domain_name,
642 newpassword=ctx.acct_pass)
644 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
645 attrs=["msDS-KeyVersionNumber"])
646 if "msDS-KeyVersionNumber" in res[0]:
647 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
649 ctx.key_version_number = None
651 print("Enabling account")
653 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
654 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
655 ldb.FLAG_MOD_REPLACE,
656 "userAccountControl")
659 if ctx.dns_backend.startswith("BIND9_"):
660 ctx.dnspass = samba.generate_random_password(128, 255)
662 recs = ctx.samdb.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"),
663 {"DNSDOMAIN": ctx.dnsdomain,
664 "DOMAINDN": ctx.base_dn,
665 "HOSTNAME" : ctx.myname,
666 "DNSPASS_B64": b64encode(ctx.dnspass),
667 "DNSNAME" : ctx.dnshostname}))
668 for changetype, msg in recs:
669 assert changetype == ldb.CHANGETYPE_NONE
670 dns_acct_dn = msg["dn"]
671 print "Adding DNS account %s with dns/ SPN" % msg["dn"]
673 # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP)
674 del msg["clearTextPassword"]
675 # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP
676 del msg["isCriticalSystemObject"]
677 # Disable account until password is set
678 msg["userAccountControl"] = str(samba.dsdb.UF_NORMAL_ACCOUNT |
679 samba.dsdb.UF_ACCOUNTDISABLE)
682 except ldb.LdbError, (num, _):
683 if num != ldb.ERR_ENTRY_ALREADY_EXISTS:
686 # The account password set operation should normally be done over
687 # LDAP. Windows 2000 DCs however allow this only with SSL
688 # connections which are hard to set up and otherwise refuse with
689 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
691 print "Setting account password for dns-%s" % ctx.myname
693 ctx.samdb.setpassword("(&(objectClass=user)(samAccountName=dns-%s))"
694 % ldb.binary_encode(ctx.myname),
696 force_change_at_next_login=False,
697 username=ctx.samname)
698 except ldb.LdbError, (num, _):
699 if num != ldb.ERR_UNWILLING_TO_PERFORM:
701 ctx.net.set_password(account_name="dns-%s" % ctx.myname,
702 domain_name=ctx.domain_name,
703 newpassword=ctx.dnspass)
705 res = ctx.samdb.search(base=dns_acct_dn, scope=ldb.SCOPE_BASE,
706 attrs=["msDS-KeyVersionNumber"])
707 if "msDS-KeyVersionNumber" in res[0]:
708 ctx.dns_key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
710 ctx.dns_key_version_number = None
712 def join_add_objects2(ctx):
713 """add the various objects needed for the join, for subdomains post replication"""
715 print "Adding %s" % ctx.partition_dn
716 name_map = {'SubdomainAdmins': "%s-%s" % (str(ctx.domsid), security.DOMAIN_RID_ADMINS)}
717 sd_binary = descriptor.get_paritions_crossref_subdomain_descriptor(ctx.forestsid, name_map=name_map)
719 "dn" : ctx.partition_dn,
720 "objectclass" : "crossRef",
721 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
722 "nCName" : ctx.base_dn,
723 "nETBIOSName" : ctx.domain_name,
724 "dnsRoot": ctx.dnsdomain,
725 "trustParent" : ctx.parent_partition_dn,
726 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN),
727 "ntSecurityDescriptor" : sd_binary,
730 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
731 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
733 rec2 = ctx.join_ntdsdsa_obj()
735 objects = ctx.DsAddEntry([rec, rec2])
736 if len(objects) != 2:
737 raise DCJoinException("Expected 2 objects from DsAddEntry")
739 ctx.ntds_guid = objects[1].guid
741 print("Replicating partition DN")
742 ctx.repl.replicate(ctx.partition_dn,
743 misc.GUID("00000000-0000-0000-0000-000000000000"),
745 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
746 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
748 print("Replicating NTDS DN")
749 ctx.repl.replicate(ctx.ntds_dn,
750 misc.GUID("00000000-0000-0000-0000-000000000000"),
752 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
753 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
755 def join_provision(ctx):
756 """Provision the local SAM."""
758 print "Calling bare provision"
760 smbconf = ctx.lp.configfile
762 presult = provision(ctx.logger, system_session(), smbconf=smbconf,
763 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
764 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
765 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
766 serverdn=ctx.server_dn, domain=ctx.domain_name,
767 hostname=ctx.myname, domainsid=ctx.domsid,
768 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
769 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
770 use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend)
771 print "Provision OK for domain DN %s" % presult.domaindn
772 ctx.local_samdb = presult.samdb
774 ctx.paths = presult.paths
775 ctx.names = presult.names
777 # Fix up the forestsid, it may be different if we are joining as a subdomain
778 ctx.names.forestsid = ctx.forestsid
780 def join_provision_own_domain(ctx):
781 """Provision the local SAM."""
783 # we now operate exclusively on the local database, which
784 # we need to reopen in order to get the newly created schema
785 print("Reconnecting to local samdb")
786 ctx.samdb = SamDB(url=ctx.local_samdb.url,
787 session_info=system_session(),
788 lp=ctx.local_samdb.lp,
790 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
791 ctx.local_samdb = ctx.samdb
793 ctx.logger.info("Finding domain GUID from ncName")
794 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
795 controls=["extended_dn:1:1", "reveal_internals:0"])
797 if 'nCName' not in res[0]:
798 raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
801 ctx.names.domainguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
803 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['ncName'][0])
805 ctx.logger.info("Got domain GUID %s" % ctx.names.domainguid)
807 ctx.logger.info("Calling own domain provision")
809 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
811 presult = provision_fill(ctx.local_samdb, secrets_ldb,
812 ctx.logger, ctx.names, ctx.paths,
813 dom_for_fun_level=DS_DOMAIN_FUNCTION_2003,
814 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
815 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
816 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
817 dns_backend=ctx.dns_backend, adminpass=ctx.adminpass)
818 print("Provision OK for domain %s" % ctx.names.dnsdomain)
820 def join_replicate(ctx):
821 """Replicate the SAM."""
823 print "Starting replication"
824 ctx.local_samdb.transaction_start()
826 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
827 if ctx.ntds_guid is None:
828 print("Using DS_BIND_GUID_W2K3")
829 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
831 destination_dsa_guid = ctx.ntds_guid
834 repl_creds = Credentials()
835 repl_creds.guess(ctx.lp)
836 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
837 repl_creds.set_username(ctx.samname)
838 repl_creds.set_password(ctx.acct_pass)
840 repl_creds = ctx.creds
842 binding_options = "seal"
843 if int(ctx.lp.get("log level")) >= 5:
844 binding_options += ",print"
845 repl = drs_utils.drs_Replicate(
846 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
847 ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id)
849 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
850 destination_dsa_guid, schema=True, rodc=ctx.RODC,
851 replica_flags=ctx.replica_flags)
852 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
853 destination_dsa_guid, rodc=ctx.RODC,
854 replica_flags=ctx.replica_flags)
855 if not ctx.subdomain:
856 # Replicate first the critical object for the basedn
857 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
858 print "Replicating critical objects from the base DN of the domain"
859 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
860 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
861 destination_dsa_guid, rodc=ctx.RODC,
862 replica_flags=ctx.domain_replica_flags)
863 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
865 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
866 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
867 destination_dsa_guid, rodc=ctx.RODC,
868 replica_flags=ctx.domain_replica_flags)
869 print "Done with always replicated NC (base, config, schema)"
871 for nc in (ctx.domaindns_zone, ctx.forestdns_zone):
872 if nc in ctx.nc_list:
873 print "Replicating %s" % (str(nc))
874 repl.replicate(nc, source_dsa_invocation_id,
875 destination_dsa_guid, rodc=ctx.RODC,
876 replica_flags=ctx.replica_flags)
878 # FIXME At this point we should add an entry in the forestdns and domaindns NC
879 # (those under CN=Partions,DC=...)
880 # in order to indicate that we hold a replica for this NC
883 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
884 destination_dsa_guid,
885 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
886 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
887 destination_dsa_guid,
888 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
890 ctx.source_dsa_invocation_id = source_dsa_invocation_id
891 ctx.destination_dsa_guid = destination_dsa_guid
893 print "Committing SAM database"
895 ctx.local_samdb.transaction_cancel()
898 ctx.local_samdb.transaction_commit()
900 def send_DsReplicaUpdateRefs(ctx, dn):
901 r = drsuapi.DsReplicaUpdateRefsRequest1()
902 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
903 r.naming_context.dn = str(dn)
904 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
905 r.naming_context.sid = security.dom_sid("S-0-0")
906 r.dest_dsa_guid = ctx.ntds_guid
907 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
908 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
910 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
913 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
915 def join_finalise(ctx):
916 """Finalise the join, mark us synchronised and setup secrets db."""
918 # FIXME we shouldn't do this in all cases
920 # If for some reasons we joined in another site than the one of
921 # DC we just replicated from then we don't need to send the updatereplicateref
922 # as replication between sites is time based and on the initiative of the
924 if not ctx.clone_only:
925 ctx.logger.info("Sending DsReplicaUpdateRefs for all the replicated partitions")
926 for nc in ctx.nc_list:
927 ctx.send_DsReplicaUpdateRefs(nc)
929 if not ctx.clone_only and ctx.RODC:
930 print "Setting RODC invocationId"
931 ctx.local_samdb.set_invocation_id(str(ctx.invocation_id))
932 ctx.local_samdb.set_opaque_integer("domainFunctionality",
933 ctx.behavior_version)
935 m.dn = ldb.Dn(ctx.local_samdb, "%s" % ctx.ntds_dn)
936 m["invocationId"] = ldb.MessageElement(ndr_pack(ctx.invocation_id),
937 ldb.FLAG_MOD_REPLACE,
939 ctx.local_samdb.modify(m)
941 # Note: as RODC the invocationId is only stored
942 # on the RODC itself, the other DCs never see it.
944 # Thats is why we fix up the replPropertyMetaData stamp
945 # for the 'invocationId' attribute, we need to change
946 # the 'version' to '0', this is what windows 2008r2 does as RODC
948 # This means if the object on a RWDC ever gets a invocationId
949 # attribute, it will have version '1' (or higher), which will
950 # will overwrite the RODC local value.
951 ctx.local_samdb.set_attribute_replmetadata_version(m.dn,
955 ctx.logger.info("Setting isSynchronized and dsServiceName")
957 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
958 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
960 # We want to appear to be the server we just cloned
962 guid = ctx.remote_dc_ntds_guid
966 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(guid),
967 ldb.FLAG_MOD_REPLACE, "dsServiceName")
968 ctx.local_samdb.modify(m)
970 if ctx.clone_only or ctx.subdomain:
973 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
975 ctx.logger.info("Setting up secrets database")
976 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
978 dnsdomain=ctx.dnsdomain,
979 netbiosname=ctx.myname,
980 domainsid=ctx.domsid,
981 machinepass=ctx.acct_pass,
982 secure_channel_type=ctx.secure_channel_type,
983 key_version_number=ctx.key_version_number)
985 if ctx.dns_backend.startswith("BIND9_"):
986 setup_bind9_dns(ctx.local_samdb, secrets_ldb,
987 ctx.names, ctx.paths, ctx.lp, ctx.logger,
988 dns_backend=ctx.dns_backend,
989 dnspass=ctx.dnspass, os_level=ctx.behavior_version,
990 targetdir=ctx.targetdir,
991 key_version_number=ctx.dns_key_version_number)
993 def join_setup_trusts(ctx):
994 """provision the local SAM."""
996 print "Setup domain trusts with server %s" % ctx.server
997 binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key
998 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
1001 objectAttr = lsa.ObjectAttribute()
1002 objectAttr.sec_qos = lsa.QosInfo()
1004 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
1005 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
1007 info = lsa.TrustDomainInfoInfoEx()
1008 info.domain_name.string = ctx.dnsdomain
1009 info.netbios_name.string = ctx.domain_name
1010 info.sid = ctx.domsid
1011 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
1012 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
1013 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
1016 oldname = lsa.String()
1017 oldname.string = ctx.dnsdomain
1018 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
1019 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
1020 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
1021 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
1022 except RuntimeError:
1025 password_blob = string_to_byte_array(ctx.trustdom_pass.encode('utf-16-le'))
1027 clear_value = drsblobs.AuthInfoClear()
1028 clear_value.size = len(password_blob)
1029 clear_value.password = password_blob
1031 clear_authentication_information = drsblobs.AuthenticationInformation()
1032 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
1033 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
1034 clear_authentication_information.AuthInfo = clear_value
1036 authentication_information_array = drsblobs.AuthenticationInformationArray()
1037 authentication_information_array.count = 1
1038 authentication_information_array.array = [clear_authentication_information]
1040 outgoing = drsblobs.trustAuthInOutBlob()
1042 outgoing.current = authentication_information_array
1044 trustpass = drsblobs.trustDomainPasswords()
1045 confounder = [3] * 512
1047 for i in range(512):
1048 confounder[i] = random.randint(0, 255)
1050 trustpass.confounder = confounder
1052 trustpass.outgoing = outgoing
1053 trustpass.incoming = outgoing
1055 trustpass_blob = ndr_pack(trustpass)
1057 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
1059 auth_blob = lsa.DATA_BUF2()
1060 auth_blob.size = len(encrypted_trustpass)
1061 auth_blob.data = string_to_byte_array(encrypted_trustpass)
1063 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
1064 auth_info.auth_blob = auth_blob
1066 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
1069 security.SEC_STD_DELETE)
1072 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
1073 "objectclass" : "trustedDomain",
1074 "trustType" : str(info.trust_type),
1075 "trustAttributes" : str(info.trust_attributes),
1076 "trustDirection" : str(info.trust_direction),
1077 "flatname" : ctx.forest_domain_name,
1078 "trustPartner" : ctx.dnsforest,
1079 "trustAuthIncoming" : ndr_pack(outgoing),
1080 "trustAuthOutgoing" : ndr_pack(outgoing),
1081 "securityIdentifier" : ndr_pack(ctx.forestsid)
1083 ctx.local_samdb.add(rec)
1086 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
1087 "objectclass" : "user",
1088 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
1089 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le'),
1090 "samAccountName" : "%s$" % ctx.forest_domain_name
1092 ctx.local_samdb.add(rec)
1096 # nc_list is the list of naming context (NC) for which we will
1097 # replicate in and send a updateRef command to the partner DC
1099 # full_nc_list is the list of naming context (NC) we hold
1100 # read/write copies of. These are not subsets of each other.
1101 ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
1102 ctx.full_nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
1104 if ctx.subdomain and ctx.dns_backend != "NONE":
1105 ctx.full_nc_list += [ctx.domaindns_zone]
1107 elif not ctx.subdomain:
1108 ctx.nc_list += [ctx.base_dn]
1110 if ctx.dns_backend != "NONE":
1111 ctx.nc_list += [ctx.domaindns_zone]
1112 ctx.nc_list += [ctx.forestdns_zone]
1113 ctx.full_nc_list += [ctx.domaindns_zone]
1114 ctx.full_nc_list += [ctx.forestdns_zone]
1116 if not ctx.clone_only:
1117 if ctx.promote_existing:
1118 ctx.promote_possible()
1120 ctx.cleanup_old_join()
1123 if not ctx.clone_only:
1124 ctx.join_add_objects()
1125 ctx.join_provision()
1126 ctx.join_replicate()
1127 if (not ctx.clone_only and ctx.subdomain):
1128 ctx.join_add_objects2()
1129 ctx.join_provision_own_domain()
1130 ctx.join_setup_trusts()
1134 print "Join failed - cleaning up"
1137 if not ctx.clone_only:
1138 ctx.cleanup_old_join()
1142 def join_RODC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1143 targetdir=None, domain=None, domain_critical_only=False,
1144 machinepass=None, use_ntvfs=False, dns_backend=None,
1145 promote_existing=False):
1146 """Join as a RODC."""
1148 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1149 machinepass, use_ntvfs, dns_backend, promote_existing)
1151 lp.set("workgroup", ctx.domain_name)
1152 logger.info("workgroup is %s" % ctx.domain_name)
1154 lp.set("realm", ctx.realm)
1155 logger.info("realm is %s" % ctx.realm)
1157 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
1159 # setup some defaults for accounts that should be replicated to this RODC
1160 ctx.never_reveal_sid = [
1161 "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
1162 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
1163 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
1164 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
1165 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS]
1166 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
1168 mysid = ctx.get_mysid()
1169 admin_dn = "<SID=%s>" % mysid
1170 ctx.managedby = admin_dn
1172 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
1173 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1174 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
1176 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
1177 "RestrictedKrbHost/%s" % ctx.dnshostname ])
1179 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
1180 ctx.secure_channel_type = misc.SEC_CHAN_RODC
1182 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
1183 drsuapi.DRSUAPI_DRS_PER_SYNC |
1184 drsuapi.DRSUAPI_DRS_GET_ANC |
1185 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
1186 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1187 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
1188 ctx.domain_replica_flags = ctx.replica_flags
1189 if domain_critical_only:
1190 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1194 logger.info("Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid))
1197 def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1198 targetdir=None, domain=None, domain_critical_only=False,
1199 machinepass=None, use_ntvfs=False, dns_backend=None,
1200 promote_existing=False):
1202 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1203 machinepass, use_ntvfs, dns_backend, promote_existing)
1205 lp.set("workgroup", ctx.domain_name)
1206 logger.info("workgroup is %s" % ctx.domain_name)
1208 lp.set("realm", ctx.realm)
1209 logger.info("realm is %s" % ctx.realm)
1211 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1213 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1214 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1216 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1217 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1218 drsuapi.DRSUAPI_DRS_PER_SYNC |
1219 drsuapi.DRSUAPI_DRS_GET_ANC |
1220 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1221 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1222 ctx.domain_replica_flags = ctx.replica_flags
1223 if domain_critical_only:
1224 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1227 logger.info("Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
1229 def join_clone(logger=None, server=None, creds=None, lp=None,
1230 targetdir=None, domain=None, include_secrets=False):
1232 ctx = dc_join(logger, server, creds, lp, site=None, netbios_name=None, targetdir=targetdir, domain=domain,
1233 machinepass=None, use_ntvfs=False, dns_backend="NONE", promote_existing=False, clone_only=True)
1235 lp.set("workgroup", ctx.domain_name)
1236 logger.info("workgroup is %s" % ctx.domain_name)
1238 lp.set("realm", ctx.realm)
1239 logger.info("realm is %s" % ctx.realm)
1241 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1242 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1243 drsuapi.DRSUAPI_DRS_PER_SYNC |
1244 drsuapi.DRSUAPI_DRS_GET_ANC |
1245 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1246 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1247 if not include_secrets:
1248 ctx.replica_flags |= drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING
1249 ctx.domain_replica_flags = ctx.replica_flags
1252 logger.info("Cloned domain %s (SID %s)" % (ctx.domain_name, ctx.domsid))
1254 def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None,
1255 netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
1256 netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False,
1259 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, parent_domain,
1260 machinepass, use_ntvfs, dns_backend)
1261 ctx.subdomain = True
1262 if adminpass is None:
1263 ctx.adminpass = samba.generate_random_password(12, 32)
1265 ctx.adminpass = adminpass
1266 ctx.parent_domain_name = ctx.domain_name
1267 ctx.domain_name = netbios_domain
1268 ctx.realm = dnsdomain
1269 ctx.parent_dnsdomain = ctx.dnsdomain
1270 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1271 ctx.dnsdomain = dnsdomain
1272 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1273 ctx.naming_master = ctx.get_naming_master()
1274 if ctx.naming_master != ctx.server:
1275 logger.info("Reconnecting to naming master %s" % ctx.naming_master)
1276 ctx.server = ctx.naming_master
1277 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1278 session_info=system_session(),
1279 credentials=ctx.creds, lp=ctx.lp)
1280 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=['dnsHostName'],
1282 ctx.server = res[0]["dnsHostName"]
1283 logger.info("DNS name of new naming master is %s" % ctx.server)
1285 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1286 ctx.forestsid = ctx.domsid
1287 ctx.domsid = security.random_sid()
1289 ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
1290 ctx.trustdom_pass = samba.generate_random_password(128, 128)
1292 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1294 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1295 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1297 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1298 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1299 drsuapi.DRSUAPI_DRS_PER_SYNC |
1300 drsuapi.DRSUAPI_DRS_GET_ANC |
1301 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1302 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1303 ctx.domain_replica_flags = ctx.replica_flags
1306 ctx.logger.info("Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))