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
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.credentials import Credentials, DONT_USE_KERBEROS
28 from samba.provision import secretsdb_self_join, provision, provision_fill, FILL_DRS, FILL_SUBDOMAIN
29 from samba.provision.common import setup_path
30 from samba.schema import Schema
31 from samba.net import Net
32 from samba.provision.sambadns import setup_bind9_dns
33 from samba import read_and_sub_file
34 from base64 import b64encode
40 # this makes debugging easier
41 talloc.enable_null_tracking()
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):
60 ctx.netbios_name = netbios_name
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.myname = netbios_name
91 ctx.samname = "%s$" % ctx.myname
92 ctx.base_dn = str(ctx.samdb.get_default_basedn())
93 ctx.root_dn = str(ctx.samdb.get_root_basedn())
94 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
95 ctx.config_dn = str(ctx.samdb.get_config_basedn())
96 ctx.domsid = ctx.samdb.get_domain_sid()
97 ctx.domain_name = ctx.get_domain_name()
98 ctx.forest_domain_name = ctx.get_forest_domain_name()
99 ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
101 ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName()
102 ctx.dc_dnsHostName = ctx.get_dnsHostName()
103 ctx.behavior_version = ctx.get_behavior_version()
105 if machinepass is not None:
106 ctx.acct_pass = machinepass
108 ctx.acct_pass = samba.generate_random_password(32, 40)
110 # work out the DNs of all the objects we will be adding
111 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
112 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
113 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
114 if ctx.dn_exists(topology_base):
115 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
117 ctx.topology_dn = None
119 ctx.dnsdomain = ctx.samdb.domain_dns_name()
120 ctx.dnsforest = ctx.samdb.forest_dns_name()
121 ctx.domaindns_zone = 'DC=DomainDnsZones,%s' % ctx.base_dn
122 ctx.forestdns_zone = 'DC=ForestDnsZones,%s' % ctx.base_dn
124 res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
126 base=ctx.samdb.get_partitions_dn(),
127 expression="(&(objectClass=crossRef)(ncName=%s))" % ctx.domaindns_zone)
128 if dns_backend is None:
129 ctx.dns_backend = "NONE"
131 if len(res_domaindns) == 0:
132 ctx.dns_backend = "NONE"
133 print "NO DNS zone information found in source domain, not replicating DNS"
135 ctx.dns_backend = dns_backend
137 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
139 ctx.realm = ctx.dnsdomain
141 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
145 ctx.SPNs = [ "HOST/%s" % ctx.myname,
146 "HOST/%s" % ctx.dnshostname,
147 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
149 # these elements are optional
150 ctx.never_reveal_sid = None
151 ctx.reveal_sid = None
152 ctx.connection_dn = None
157 ctx.subdomain = False
160 def del_noerror(ctx, dn, recursive=False):
163 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
167 ctx.del_noerror(r.dn, recursive=True)
170 print "Deleted %s" % dn
174 def cleanup_old_join(ctx):
175 """Remove any DNs from a previous join."""
177 # find the krbtgt link
178 print("checking sAMAccountName")
182 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
183 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
184 attrs=["msDS-krbTgtLink"])
186 ctx.del_noerror(res[0].dn, recursive=True)
188 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
189 expression='(&(sAMAccountName=%s)(servicePrincipalName=%s))' % (ldb.binary_encode("dns-%s" % ctx.myname), ldb.binary_encode("dns/%s" % ctx.dnshostname)),
192 ctx.del_noerror(res[0].dn, recursive=True)
194 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
195 expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname),
198 raise RuntimeError("Not removing account %s which looks like a Samba DNS service account but does not have servicePrincipalName=%s" % (ldb.binary_encode("dns-%s" % ctx.myname), ldb.binary_encode("dns/%s" % ctx.dnshostname)))
200 if ctx.connection_dn is not None:
201 ctx.del_noerror(ctx.connection_dn)
202 if ctx.krbtgt_dn is not None:
203 ctx.del_noerror(ctx.krbtgt_dn)
204 ctx.del_noerror(ctx.ntds_dn)
205 ctx.del_noerror(ctx.server_dn, recursive=True)
207 ctx.del_noerror(ctx.topology_dn)
209 ctx.del_noerror(ctx.partition_dn)
211 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
212 ctx.del_noerror(ctx.new_krbtgt_dn)
215 binding_options = "sign"
216 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
219 objectAttr = lsa.ObjectAttribute()
220 objectAttr.sec_qos = lsa.QosInfo()
222 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
223 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
226 name.string = ctx.realm
227 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
229 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
232 name.string = ctx.forest_domain_name
233 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
235 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
240 def promote_possible(ctx):
241 """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
243 # This shouldn't happen
244 raise Exception("Can not promote into a subdomain")
246 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
247 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
248 attrs=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
250 raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname)
251 if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]:
252 raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname)
253 if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0):
254 raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname)
256 ctx.promote_from_dn = res[0].dn
259 def find_dc(ctx, domain):
260 """find a writeable DC for the given domain"""
262 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
264 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
265 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
266 ctx.site = ctx.cldap_ret.client_site
267 return ctx.cldap_ret.pdc_dns_name
270 def get_behavior_version(ctx):
271 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
272 if "msDS-Behavior-Version" in res[0]:
273 return int(res[0]["msDS-Behavior-Version"][0])
275 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
277 def get_dnsHostName(ctx):
278 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
279 return res[0]["dnsHostName"][0]
281 def get_domain_name(ctx):
282 '''get netbios name of the domain from the partitions record'''
283 partitions_dn = ctx.samdb.get_partitions_dn()
284 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
285 expression='ncName=%s' % ctx.samdb.get_default_basedn())
286 return res[0]["nETBIOSName"][0]
288 def get_forest_domain_name(ctx):
289 '''get netbios name of the domain from the partitions record'''
290 partitions_dn = ctx.samdb.get_partitions_dn()
291 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
292 expression='ncName=%s' % ctx.samdb.get_root_basedn())
293 return res[0]["nETBIOSName"][0]
295 def get_parent_partition_dn(ctx):
296 '''get the parent domain partition DN from parent DNS name'''
297 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
298 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
299 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
300 return str(res[0].dn)
302 def get_naming_master(ctx):
303 '''get the parent domain partition DN from parent DNS name'''
304 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
305 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
306 if not 'fSMORoleOwner' in res[0]:
307 raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
309 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
311 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0])
313 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
317 '''get the SID of the connected user. Only works with w2k8 and later,
318 so only used for RODC join'''
319 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
320 binsid = res[0]["tokenGroups"][0]
321 return ctx.samdb.schema_format_value("objectSID", binsid)
323 def dn_exists(ctx, dn):
324 '''check if a DN exists'''
326 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
327 except ldb.LdbError, (enum, estr):
328 if enum == ldb.ERR_NO_SUCH_OBJECT:
333 def add_krbtgt_account(ctx):
334 '''RODCs need a special krbtgt account'''
335 print "Adding %s" % ctx.krbtgt_dn
337 "dn" : ctx.krbtgt_dn,
338 "objectclass" : "user",
339 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
340 samba.dsdb.UF_ACCOUNTDISABLE),
341 "showinadvancedviewonly" : "TRUE",
342 "description" : "krbtgt for %s" % ctx.samname}
343 ctx.samdb.add(rec, ["rodc_join:1:1"])
345 # now we need to search for the samAccountName attribute on the krbtgt DN,
346 # as this will have been magically set to the krbtgt number
347 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
348 ctx.krbtgt_name = res[0]["samAccountName"][0]
350 print "Got krbtgt_name=%s" % ctx.krbtgt_name
353 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
354 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
355 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
358 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
359 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
360 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
362 def drsuapi_connect(ctx):
363 '''make a DRSUAPI connection to the naming master'''
364 binding_options = "seal"
365 if int(ctx.lp.get("log level")) >= 4:
366 binding_options += ",print"
367 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
368 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
369 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
371 def create_tmp_samdb(ctx):
372 '''create a temporary samdb object for schema queries'''
373 ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
374 schemadn=ctx.schema_dn)
375 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
376 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
378 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
380 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
381 '''build a DsReplicaAttributeCtr object'''
382 r = drsuapi.DsReplicaAttribute()
383 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
387 def DsAddEntry(ctx, recs):
388 '''add a record via the DRSUAPI DsAddEntry call'''
389 if ctx.drsuapi is None:
390 ctx.drsuapi_connect()
391 if ctx.tmp_samdb is None:
392 ctx.create_tmp_samdb()
396 id = drsuapi.DsReplicaObjectIdentifier()
403 if not isinstance(rec[a], list):
407 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
410 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
411 attribute_ctr.num_attributes = len(attrs)
412 attribute_ctr.attributes = attrs
414 object = drsuapi.DsReplicaObject()
415 object.identifier = id
416 object.attribute_ctr = attribute_ctr
418 list_object = drsuapi.DsReplicaObjectListItem()
419 list_object.object = object
420 objects.append(list_object)
422 req2 = drsuapi.DsAddEntryRequest2()
423 req2.first_object = objects[0]
424 prev = req2.first_object
425 for o in objects[1:]:
429 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
431 if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
432 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
433 raise RuntimeError("DsAddEntry failed")
434 if ctr.extended_err != (0, 'WERR_OK'):
435 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
436 raise RuntimeError("DsAddEntry failed")
439 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
440 if ctr.err_data.status != (0, 'WERR_OK'):
441 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
442 ctr.err_data.info.extended_err))
443 raise RuntimeError("DsAddEntry failed")
444 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
445 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
446 raise RuntimeError("DsAddEntry failed")
450 def join_add_ntdsdsa(ctx):
451 '''add the ntdsdsa object'''
453 print "Adding %s" % ctx.ntds_dn
456 "objectclass" : "nTDSDSA",
457 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
458 "dMDLocation" : ctx.schema_dn}
460 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
462 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
463 rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
465 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
466 rec["msDS-HasDomainNCs"] = ctx.base_dn
469 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
470 rec["msDS-HasFullReplicaNCs"] = ctx.nc_list
471 rec["options"] = "37"
472 ctx.samdb.add(rec, ["rodc_join:1:1"])
474 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
475 rec["HasMasterNCs"] = nc_list
476 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
477 rec["msDS-HasMasterNCs"] = ctx.nc_list
479 rec["invocationId"] = ndr_pack(ctx.invocation_id)
480 ctx.DsAddEntry([rec])
482 # find the GUID of our NTDS DN
483 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
484 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
486 def join_add_objects(ctx):
487 '''add the various objects needed for the join'''
489 print "Adding %s" % ctx.acct_dn
492 "objectClass": "computer",
493 "displayname": ctx.samname,
494 "samaccountname" : ctx.samname,
495 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
496 "dnshostname" : ctx.dnshostname}
497 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
498 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
499 elif ctx.promote_existing:
500 rec['msDS-SupportedEncryptionTypes'] = []
502 rec["managedby"] = ctx.managedby
503 elif ctx.promote_existing:
504 rec["managedby"] = []
506 if ctx.never_reveal_sid:
507 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
508 elif ctx.promote_existing:
509 rec["msDS-NeverRevealGroup"] = []
512 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
513 elif ctx.promote_existing:
514 rec["msDS-RevealOnDemandGroup"] = []
516 if ctx.promote_existing:
517 if ctx.promote_from_dn != ctx.acct_dn:
518 ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn)
519 ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE))
524 ctx.add_krbtgt_account()
526 print "Adding %s" % ctx.server_dn
529 "objectclass" : "server",
530 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
531 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
532 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
533 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
534 # windows seems to add the dnsHostName later
535 "dnsHostName" : ctx.dnshostname}
538 rec["serverReference"] = ctx.acct_dn
543 # the rest is done after replication
547 ctx.join_add_ntdsdsa()
549 if ctx.connection_dn is not None:
550 print "Adding %s" % ctx.connection_dn
552 "dn" : ctx.connection_dn,
553 "objectclass" : "nTDSConnection",
554 "enabledconnection" : "TRUE",
556 "fromServer" : ctx.dc_ntds_dn}
560 print "Adding SPNs to %s" % ctx.acct_dn
562 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
563 for i in range(len(ctx.SPNs)):
564 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
565 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
566 ldb.FLAG_MOD_REPLACE,
567 "servicePrincipalName")
570 # The account password set operation should normally be done over
571 # LDAP. Windows 2000 DCs however allow this only with SSL
572 # connections which are hard to set up and otherwise refuse with
573 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
575 print "Setting account password for %s" % ctx.samname
577 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
578 % ldb.binary_encode(ctx.samname),
580 force_change_at_next_login=False,
581 username=ctx.samname)
582 except ldb.LdbError, (num, _):
583 if num != ldb.ERR_UNWILLING_TO_PERFORM:
585 ctx.net.set_password(account_name=ctx.samname,
586 domain_name=ctx.domain_name,
587 newpassword=ctx.acct_pass)
589 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
590 attrs=["msDS-KeyVersionNumber"])
591 if "msDS-KeyVersionNumber" in res[0]:
592 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
594 ctx.key_version_number = None
596 print("Enabling account")
598 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
599 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
600 ldb.FLAG_MOD_REPLACE,
601 "userAccountControl")
604 if ctx.dns_backend.startswith("BIND9_"):
605 ctx.dnspass = samba.generate_random_password(128, 255)
607 recs = ctx.samdb.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"),
608 {"DNSDOMAIN": ctx.dnsdomain,
609 "DOMAINDN": ctx.base_dn,
610 "HOSTNAME" : ctx.myname,
611 "DNSPASS_B64": b64encode(ctx.dnspass),
612 "DNSNAME" : ctx.dnshostname}))
613 for changetype, msg in recs:
614 assert changetype == ldb.CHANGETYPE_NONE
615 print "Adding DNS account %s with dns/ SPN" % msg["dn"]
617 # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP)
618 del msg["clearTextPassword"]
619 # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP
620 del msg["isCriticalSystemObject"]
623 dns_acct_dn = msg["dn"]
624 except ldb.LdbError, (num, _):
625 if num != ldb.ERR_ENTRY_ALREADY_EXISTS:
628 # The account password set operation should normally be done over
629 # LDAP. Windows 2000 DCs however allow this only with SSL
630 # connections which are hard to set up and otherwise refuse with
631 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
633 print "Setting account password for %s" % ctx.samname
635 ctx.samdb.setpassword("(&(objectClass=user)(samAccountName=dns-%s))"
636 % ldb.binary_encode(ctx.myname),
638 force_change_at_next_login=False,
639 username=ctx.samname)
640 except ldb.LdbError, (num, _):
641 if num != ldb.ERR_UNWILLING_TO_PERFORM:
643 ctx.net.set_password(account_name="dns-" % ctx.myname,
644 domain_name=ctx.domain_name,
645 newpassword=ctx.dnspass)
647 res = ctx.samdb.search(base=dns_acct_dn, scope=ldb.SCOPE_BASE,
648 attrs=["msDS-KeyVersionNumber"])
649 if "msDS-KeyVersionNumber" in res[0]:
650 ctx.dns_key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
652 ctx.dns_key_version_number = None
654 def join_add_objects2(ctx):
655 """add the various objects needed for the join, for subdomains post replication"""
657 print "Adding %s" % ctx.partition_dn
658 # NOTE: windows sends a ntSecurityDescriptor here, we
661 "dn" : ctx.partition_dn,
662 "objectclass" : "crossRef",
663 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
664 "nCName" : ctx.base_dn,
665 "nETBIOSName" : ctx.domain_name,
666 "dnsRoot": ctx.dnsdomain,
667 "trustParent" : ctx.parent_partition_dn,
668 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
669 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
670 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
674 "objectclass" : "nTDSDSA",
675 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
676 "dMDLocation" : ctx.schema_dn}
678 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
680 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
681 rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
683 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
684 rec2["msDS-HasDomainNCs"] = ctx.base_dn
686 rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
687 rec2["HasMasterNCs"] = nc_list
688 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
689 rec2["msDS-HasMasterNCs"] = ctx.nc_list
690 rec2["options"] = "1"
691 rec2["invocationId"] = ndr_pack(ctx.invocation_id)
693 objects = ctx.DsAddEntry([rec, rec2])
694 if len(objects) != 2:
695 raise DCJoinException("Expected 2 objects from DsAddEntry")
697 ctx.ntds_guid = objects[1].guid
699 print("Replicating partition DN")
700 ctx.repl.replicate(ctx.partition_dn,
701 misc.GUID("00000000-0000-0000-0000-000000000000"),
703 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
704 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
706 print("Replicating NTDS DN")
707 ctx.repl.replicate(ctx.ntds_dn,
708 misc.GUID("00000000-0000-0000-0000-000000000000"),
710 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
711 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
713 def join_provision(ctx):
714 """Provision the local SAM."""
716 print "Calling bare provision"
718 smbconf = ctx.lp.configfile
720 presult = provision(ctx.logger, system_session(), None, smbconf=smbconf,
721 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
722 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
723 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
724 serverdn=ctx.server_dn, domain=ctx.domain_name,
725 hostname=ctx.myname, domainsid=ctx.domsid,
726 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
727 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
728 use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend)
729 print "Provision OK for domain DN %s" % presult.domaindn
730 ctx.local_samdb = presult.samdb
732 ctx.paths = presult.paths
733 ctx.names = presult.names
735 def join_provision_own_domain(ctx):
736 """Provision the local SAM."""
738 # we now operate exclusively on the local database, which
739 # we need to reopen in order to get the newly created schema
740 print("Reconnecting to local samdb")
741 ctx.samdb = SamDB(url=ctx.local_samdb.url,
742 session_info=system_session(),
743 lp=ctx.local_samdb.lp,
745 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
746 ctx.local_samdb = ctx.samdb
748 ctx.logger.info("Finding domain GUID from ncName")
749 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
750 controls=["extended_dn:1:1", "reveal_internals:0"])
752 if 'nCName' not in res[0]:
753 raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
756 domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
758 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['ncName'][0])
760 ctx.logger.info("Got domain GUID %s" % domguid)
762 ctx.logger.info("Calling own domain provision")
764 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
766 presult = provision_fill(ctx.local_samdb, secrets_ldb,
767 ctx.logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
769 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
770 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
771 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
772 dns_backend=ctx.dns_backend, adminpass=ctx.adminpass)
773 print("Provision OK for domain %s" % ctx.names.dnsdomain)
775 def join_replicate(ctx):
776 """Replicate the SAM."""
778 print "Starting replication"
779 ctx.local_samdb.transaction_start()
781 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
782 if ctx.ntds_guid is None:
783 print("Using DS_BIND_GUID_W2K3")
784 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
786 destination_dsa_guid = ctx.ntds_guid
789 repl_creds = Credentials()
790 repl_creds.guess(ctx.lp)
791 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
792 repl_creds.set_username(ctx.samname)
793 repl_creds.set_password(ctx.acct_pass)
795 repl_creds = ctx.creds
797 binding_options = "seal"
798 if int(ctx.lp.get("log level")) >= 5:
799 binding_options += ",print"
800 repl = drs_utils.drs_Replicate(
801 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
802 ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id)
804 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
805 destination_dsa_guid, schema=True, rodc=ctx.RODC,
806 replica_flags=ctx.replica_flags)
807 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
808 destination_dsa_guid, rodc=ctx.RODC,
809 replica_flags=ctx.replica_flags)
810 if not ctx.subdomain:
811 # Replicate first the critical object for the basedn
812 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
813 print "Replicating critical objects from the base DN of the domain"
814 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
815 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
816 destination_dsa_guid, rodc=ctx.RODC,
817 replica_flags=ctx.domain_replica_flags)
818 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
820 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
821 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
822 destination_dsa_guid, rodc=ctx.RODC,
823 replica_flags=ctx.domain_replica_flags)
824 print "Done with always replicated NC (base, config, schema)"
826 for nc in (ctx.domaindns_zone, ctx.forestdns_zone):
827 if nc in ctx.nc_list:
828 print "Replicating %s" % (str(nc))
829 repl.replicate(nc, source_dsa_invocation_id,
830 destination_dsa_guid, rodc=ctx.RODC,
831 replica_flags=ctx.replica_flags)
833 if 'DC=ForestDnsZones,%s' % ctx.root_dn in ctx.nc_list:
834 repl.replicate('DC=ForestDnsZones,%s' % ctx.root_dn, source_dsa_invocation_id,
835 destination_dsa_guid, rodc=ctx.RODC,
836 replica_flags=ctx.replica_flags)
837 # FIXME At this point we should add an entry in the forestdns and domaindns NC
838 # (those under CN=Partions,DC=...)
839 # in order to indicate that we hold a replica for this NC
842 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
843 destination_dsa_guid,
844 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
845 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
846 destination_dsa_guid,
847 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
849 ctx.source_dsa_invocation_id = source_dsa_invocation_id
850 ctx.destination_dsa_guid = destination_dsa_guid
852 print "Committing SAM database"
854 ctx.local_samdb.transaction_cancel()
857 ctx.local_samdb.transaction_commit()
859 def send_DsReplicaUpdateRefs(ctx, dn):
860 r = drsuapi.DsReplicaUpdateRefsRequest1()
861 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
862 r.naming_context.dn = str(dn)
863 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
864 r.naming_context.sid = security.dom_sid("S-0-0")
865 r.dest_dsa_guid = ctx.ntds_guid
866 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
867 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
869 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
872 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
874 def join_finalise(ctx):
875 """Finalise the join, mark us synchronised and setup secrets db."""
877 # FIXME we shouldn't do this in all cases
878 # If for some reasons we joined in another site than the one of
879 # DC we just replicated from then we don't need to send the updatereplicateref
880 # as replication between sites is time based and on the initiative of the
882 ctx.logger.info("Sending DsReplicateUpdateRefs for all the replicated partitions")
883 for nc in ctx.full_nc_list:
884 ctx.send_DsReplicaUpdateRefs(nc)
887 print "Setting RODC invocationId"
888 ctx.local_samdb.set_invocation_id(str(ctx.invocation_id))
889 ctx.local_samdb.set_opaque_integer("domainFunctionality",
890 ctx.behavior_version)
892 m.dn = ldb.Dn(ctx.local_samdb, "%s" % ctx.ntds_dn)
893 m["invocationId"] = ldb.MessageElement(ndr_pack(ctx.invocation_id),
894 ldb.FLAG_MOD_REPLACE,
896 ctx.local_samdb.modify(m)
898 # Note: as RODC the invocationId is only stored
899 # on the RODC itself, the other DCs never see it.
901 # Thats is why we fix up the replPropertyMetaData stamp
902 # for the 'invocationId' attribute, we need to change
903 # the 'version' to '0', this is what windows 2008r2 does as RODC
905 # This means if the object on a RWDC ever gets a invocationId
906 # attribute, it will have version '1' (or higher), which will
907 # will overwrite the RODC local value.
908 ctx.local_samdb.set_attribute_replmetadata_version(m.dn,
912 ctx.logger.info("Setting isSynchronized and dsServiceName")
914 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
915 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
916 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
917 ldb.FLAG_MOD_REPLACE, "dsServiceName")
918 ctx.local_samdb.modify(m)
923 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
925 ctx.logger.info("Setting up secrets database")
926 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
928 dnsdomain=ctx.dnsdomain,
929 netbiosname=ctx.myname,
930 domainsid=security.dom_sid(ctx.domsid),
931 machinepass=ctx.acct_pass,
932 secure_channel_type=ctx.secure_channel_type,
933 key_version_number=ctx.key_version_number)
935 if ctx.dns_backend.startswith("BIND9_"):
936 setup_bind9_dns(ctx.local_samdb, secrets_ldb, security.dom_sid(ctx.domsid),
937 ctx.names, ctx.paths, ctx.lp, ctx.logger,
938 dns_backend=ctx.dns_backend,
939 dnspass=ctx.dnspass, os_level=ctx.behavior_version,
940 targetdir=ctx.targetdir,
941 key_version_number=ctx.dns_key_version_number)
943 def join_setup_trusts(ctx):
944 """provision the local SAM."""
946 def arcfour_encrypt(key, data):
947 from Crypto.Cipher import ARC4
949 return c.encrypt(data)
951 def string_to_array(string):
952 blob = [0] * len(string)
954 for i in range(len(string)):
955 blob[i] = ord(string[i])
959 print "Setup domain trusts with server %s" % ctx.server
960 binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key
961 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
964 objectAttr = lsa.ObjectAttribute()
965 objectAttr.sec_qos = lsa.QosInfo()
967 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
968 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
970 info = lsa.TrustDomainInfoInfoEx()
971 info.domain_name.string = ctx.dnsdomain
972 info.netbios_name.string = ctx.domain_name
973 info.sid = security.dom_sid(ctx.domsid)
974 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
975 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
976 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
979 oldname = lsa.String()
980 oldname.string = ctx.dnsdomain
981 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
982 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
983 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
984 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
988 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
990 clear_value = drsblobs.AuthInfoClear()
991 clear_value.size = len(password_blob)
992 clear_value.password = password_blob
994 clear_authentication_information = drsblobs.AuthenticationInformation()
995 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
996 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
997 clear_authentication_information.AuthInfo = clear_value
999 authentication_information_array = drsblobs.AuthenticationInformationArray()
1000 authentication_information_array.count = 1
1001 authentication_information_array.array = [clear_authentication_information]
1003 outgoing = drsblobs.trustAuthInOutBlob()
1005 outgoing.current = authentication_information_array
1007 trustpass = drsblobs.trustDomainPasswords()
1008 confounder = [3] * 512
1010 for i in range(512):
1011 confounder[i] = random.randint(0, 255)
1013 trustpass.confounder = confounder
1015 trustpass.outgoing = outgoing
1016 trustpass.incoming = outgoing
1018 trustpass_blob = ndr_pack(trustpass)
1020 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
1022 auth_blob = lsa.DATA_BUF2()
1023 auth_blob.size = len(encrypted_trustpass)
1024 auth_blob.data = string_to_array(encrypted_trustpass)
1026 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
1027 auth_info.auth_blob = auth_blob
1029 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
1032 security.SEC_STD_DELETE)
1035 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
1036 "objectclass" : "trustedDomain",
1037 "trustType" : str(info.trust_type),
1038 "trustAttributes" : str(info.trust_attributes),
1039 "trustDirection" : str(info.trust_direction),
1040 "flatname" : ctx.forest_domain_name,
1041 "trustPartner" : ctx.dnsforest,
1042 "trustAuthIncoming" : ndr_pack(outgoing),
1043 "trustAuthOutgoing" : ndr_pack(outgoing)
1045 ctx.local_samdb.add(rec)
1048 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
1049 "objectclass" : "user",
1050 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
1051 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
1053 ctx.local_samdb.add(rec)
1057 # full_nc_list is the list of naming context (NC) for which we will
1058 # send a updateRef command to the partner DC
1059 ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
1060 ctx.full_nc_list = [ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
1062 if not ctx.subdomain:
1063 ctx.nc_list += [ctx.base_dn]
1064 if ctx.dns_backend != "NONE":
1065 ctx.nc_list += [ctx.domaindns_zone]
1067 if ctx.dns_backend != "NONE":
1068 if not ctx.subdomain:
1069 ctx.full_nc_list += ['DC=DomainDnsZones,%s' % ctx.base_dn]
1070 ctx.full_nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
1071 ctx.nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
1073 if ctx.promote_existing:
1074 ctx.promote_possible()
1076 ctx.cleanup_old_join()
1079 ctx.join_add_objects()
1080 ctx.join_provision()
1081 ctx.join_replicate()
1083 ctx.join_add_objects2()
1084 ctx.join_provision_own_domain()
1085 ctx.join_setup_trusts()
1088 print "Join failed - cleaning up"
1089 ctx.cleanup_old_join()
1093 def join_RODC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1094 targetdir=None, domain=None, domain_critical_only=False,
1095 machinepass=None, use_ntvfs=False, dns_backend=None,
1096 promote_existing=False):
1097 """Join as a RODC."""
1099 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1100 machinepass, use_ntvfs, dns_backend, promote_existing)
1102 lp.set("workgroup", ctx.domain_name)
1103 logger.info("workgroup is %s" % ctx.domain_name)
1105 lp.set("realm", ctx.realm)
1106 logger.info("realm is %s" % ctx.realm)
1108 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
1110 # setup some defaults for accounts that should be replicated to this RODC
1111 ctx.never_reveal_sid = [
1112 "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
1113 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
1114 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
1115 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
1116 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS]
1117 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
1119 mysid = ctx.get_mysid()
1120 admin_dn = "<SID=%s>" % mysid
1121 ctx.managedby = admin_dn
1123 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
1124 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1125 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
1127 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
1128 "RestrictedKrbHost/%s" % ctx.dnshostname ])
1130 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
1131 ctx.secure_channel_type = misc.SEC_CHAN_RODC
1133 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
1134 drsuapi.DRSUAPI_DRS_PER_SYNC |
1135 drsuapi.DRSUAPI_DRS_GET_ANC |
1136 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
1137 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1138 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
1139 ctx.domain_replica_flags = ctx.replica_flags
1140 if domain_critical_only:
1141 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1145 logger.info("Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid))
1148 def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1149 targetdir=None, domain=None, domain_critical_only=False,
1150 machinepass=None, use_ntvfs=False, dns_backend=None,
1151 promote_existing=False):
1153 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1154 machinepass, use_ntvfs, dns_backend, promote_existing)
1156 lp.set("workgroup", ctx.domain_name)
1157 logger.info("workgroup is %s" % ctx.domain_name)
1159 lp.set("realm", ctx.realm)
1160 logger.info("realm is %s" % ctx.realm)
1162 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1164 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1165 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1167 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1168 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1169 drsuapi.DRSUAPI_DRS_PER_SYNC |
1170 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1171 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1172 ctx.domain_replica_flags = ctx.replica_flags
1173 if domain_critical_only:
1174 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1177 logger.info("Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
1179 def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None,
1180 netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
1181 netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False,
1184 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, parent_domain,
1185 machinepass, use_ntvfs, dns_backend)
1186 ctx.subdomain = True
1187 if adminpass is None:
1188 ctx.adminpass = samba.generate_random_password(12, 32)
1190 ctx.adminpass = adminpass
1191 ctx.parent_domain_name = ctx.domain_name
1192 ctx.domain_name = netbios_domain
1193 ctx.realm = dnsdomain
1194 ctx.parent_dnsdomain = ctx.dnsdomain
1195 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1196 ctx.dnsdomain = dnsdomain
1197 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1198 ctx.naming_master = ctx.get_naming_master()
1199 if ctx.naming_master != ctx.server:
1200 logger.info("Reconnecting to naming master %s" % ctx.naming_master)
1201 ctx.server = ctx.naming_master
1202 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1203 session_info=system_session(),
1204 credentials=ctx.creds, lp=ctx.lp)
1206 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1207 ctx.domsid = str(security.random_sid())
1209 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
1210 ctx.trustdom_pass = samba.generate_random_password(128, 128)
1212 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1214 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1215 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1217 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1218 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1219 drsuapi.DRSUAPI_DRS_PER_SYNC |
1220 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1221 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1222 ctx.domain_replica_flags = ctx.replica_flags
1225 ctx.logger.info("Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))