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, 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):
59 ctx.netbios_name = netbios_name
60 ctx.targetdir = targetdir
61 ctx.use_ntvfs = use_ntvfs
63 ctx.promote_existing = promote_existing
64 ctx.promote_from_dn = None
69 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
70 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
72 if server is not None:
75 print("Finding a writeable DC for domain '%s'" % domain)
76 ctx.server = ctx.find_dc(domain)
77 print("Found DC %s" % ctx.server)
79 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
80 session_info=system_session(),
81 credentials=ctx.creds, lp=ctx.lp)
84 ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
85 except ldb.LdbError, (enum, estr):
86 raise DCJoinException(estr)
89 ctx.myname = netbios_name
90 ctx.samname = "%s$" % ctx.myname
91 ctx.base_dn = str(ctx.samdb.get_default_basedn())
92 ctx.root_dn = str(ctx.samdb.get_root_basedn())
93 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
94 ctx.config_dn = str(ctx.samdb.get_config_basedn())
95 ctx.domsid = ctx.samdb.get_domain_sid()
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 # work out the DNs of all the objects we will be adding
110 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
111 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
112 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
113 if ctx.dn_exists(topology_base):
114 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
116 ctx.topology_dn = None
118 ctx.dnsdomain = ctx.samdb.domain_dns_name()
119 ctx.dnsforest = ctx.samdb.forest_dns_name()
120 ctx.domaindns_zone = 'DC=DomainDnsZones,%s' % ctx.base_dn
121 ctx.forestdns_zone = 'DC=ForestDnsZones,%s' % ctx.base_dn
123 res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
125 base=ctx.samdb.get_partitions_dn(),
126 expression="(&(objectClass=crossRef)(ncName=%s))" % ctx.domaindns_zone)
127 if dns_backend is None:
128 ctx.dns_backend = "NONE"
130 if len(res_domaindns) == 0:
131 ctx.dns_backend = "NONE"
132 print "NO DNS zone information found in source domain, not replicating DNS"
134 ctx.dns_backend = dns_backend
136 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
138 ctx.realm = ctx.dnsdomain
140 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
144 ctx.SPNs = [ "HOST/%s" % ctx.myname,
145 "HOST/%s" % ctx.dnshostname,
146 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
148 # these elements are optional
149 ctx.never_reveal_sid = None
150 ctx.reveal_sid = None
151 ctx.connection_dn = None
156 ctx.subdomain = False
158 def del_noerror(ctx, dn, recursive=False):
161 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
165 ctx.del_noerror(r.dn, recursive=True)
168 print "Deleted %s" % dn
172 def cleanup_old_join(ctx):
173 """Remove any DNs from a previous join."""
175 # find the krbtgt link
176 print("checking sAMAccountName")
180 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
181 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
182 attrs=["msDS-krbTgtLink"])
184 ctx.del_noerror(res[0].dn, recursive=True)
186 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
187 expression='(&(sAMAccountName=%s)(servicePrincipalName=%s))' % (ldb.binary_encode("dns-%s" % ctx.myname), ldb.binary_encode("dns/%s" % ctx.dnshostname)),
190 ctx.del_noerror(res[0].dn, recursive=True)
192 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
193 expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname),
196 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)))
198 if ctx.connection_dn is not None:
199 ctx.del_noerror(ctx.connection_dn)
200 if ctx.krbtgt_dn is not None:
201 ctx.del_noerror(ctx.krbtgt_dn)
202 ctx.del_noerror(ctx.ntds_dn)
203 ctx.del_noerror(ctx.server_dn, recursive=True)
205 ctx.del_noerror(ctx.topology_dn)
207 ctx.del_noerror(ctx.partition_dn)
209 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
210 ctx.del_noerror(ctx.new_krbtgt_dn)
213 binding_options = "sign"
214 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
217 objectAttr = lsa.ObjectAttribute()
218 objectAttr.sec_qos = lsa.QosInfo()
220 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
221 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
224 name.string = ctx.realm
225 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
227 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
230 name.string = ctx.forest_domain_name
231 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
233 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
238 def promote_possible(ctx):
239 """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
241 # This shouldn't happen
242 raise Exception("Can not promote into a subdomain")
244 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
245 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
246 attrs=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
248 raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname)
249 if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]:
250 raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname)
251 if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0):
252 raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname)
254 ctx.promote_from_dn = res[0].dn
257 def find_dc(ctx, domain):
258 """find a writeable DC for the given domain"""
260 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
262 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
263 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
264 ctx.site = ctx.cldap_ret.client_site
265 return ctx.cldap_ret.pdc_dns_name
268 def get_behavior_version(ctx):
269 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
270 if "msDS-Behavior-Version" in res[0]:
271 return int(res[0]["msDS-Behavior-Version"][0])
273 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
275 def get_dnsHostName(ctx):
276 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
277 return res[0]["dnsHostName"][0]
279 def get_domain_name(ctx):
280 '''get netbios name of the domain from the partitions record'''
281 partitions_dn = ctx.samdb.get_partitions_dn()
282 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
283 expression='ncName=%s' % ctx.samdb.get_default_basedn())
284 return res[0]["nETBIOSName"][0]
286 def get_forest_domain_name(ctx):
287 '''get netbios name of the domain from the partitions record'''
288 partitions_dn = ctx.samdb.get_partitions_dn()
289 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
290 expression='ncName=%s' % ctx.samdb.get_root_basedn())
291 return res[0]["nETBIOSName"][0]
293 def get_parent_partition_dn(ctx):
294 '''get the parent domain partition DN from parent DNS name'''
295 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
296 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
297 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
298 return str(res[0].dn)
300 def get_naming_master(ctx):
301 '''get the parent domain partition DN from parent DNS name'''
302 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
303 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
304 if not 'fSMORoleOwner' in res[0]:
305 raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
307 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
309 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0])
311 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
315 '''get the SID of the connected user. Only works with w2k8 and later,
316 so only used for RODC join'''
317 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
318 binsid = res[0]["tokenGroups"][0]
319 return ctx.samdb.schema_format_value("objectSID", binsid)
321 def dn_exists(ctx, dn):
322 '''check if a DN exists'''
324 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
325 except ldb.LdbError, (enum, estr):
326 if enum == ldb.ERR_NO_SUCH_OBJECT:
331 def add_krbtgt_account(ctx):
332 '''RODCs need a special krbtgt account'''
333 print "Adding %s" % ctx.krbtgt_dn
335 "dn" : ctx.krbtgt_dn,
336 "objectclass" : "user",
337 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
338 samba.dsdb.UF_ACCOUNTDISABLE),
339 "showinadvancedviewonly" : "TRUE",
340 "description" : "krbtgt for %s" % ctx.samname}
341 ctx.samdb.add(rec, ["rodc_join:1:1"])
343 # now we need to search for the samAccountName attribute on the krbtgt DN,
344 # as this will have been magically set to the krbtgt number
345 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
346 ctx.krbtgt_name = res[0]["samAccountName"][0]
348 print "Got krbtgt_name=%s" % ctx.krbtgt_name
351 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
352 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
353 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
356 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
357 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
358 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
360 def drsuapi_connect(ctx):
361 '''make a DRSUAPI connection to the naming master'''
362 binding_options = "seal"
363 if int(ctx.lp.get("log level")) >= 4:
364 binding_options += ",print"
365 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
366 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
367 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
369 def create_tmp_samdb(ctx):
370 '''create a temporary samdb object for schema queries'''
371 ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
372 schemadn=ctx.schema_dn)
373 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
374 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
376 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
378 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
379 '''build a DsReplicaAttributeCtr object'''
380 r = drsuapi.DsReplicaAttribute()
381 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
385 def DsAddEntry(ctx, recs):
386 '''add a record via the DRSUAPI DsAddEntry call'''
387 if ctx.drsuapi is None:
388 ctx.drsuapi_connect()
389 if ctx.tmp_samdb is None:
390 ctx.create_tmp_samdb()
394 id = drsuapi.DsReplicaObjectIdentifier()
401 if not isinstance(rec[a], list):
405 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
408 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
409 attribute_ctr.num_attributes = len(attrs)
410 attribute_ctr.attributes = attrs
412 object = drsuapi.DsReplicaObject()
413 object.identifier = id
414 object.attribute_ctr = attribute_ctr
416 list_object = drsuapi.DsReplicaObjectListItem()
417 list_object.object = object
418 objects.append(list_object)
420 req2 = drsuapi.DsAddEntryRequest2()
421 req2.first_object = objects[0]
422 prev = req2.first_object
423 for o in objects[1:]:
427 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
429 if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
430 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
431 raise RuntimeError("DsAddEntry failed")
432 if ctr.extended_err != (0, 'WERR_OK'):
433 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
434 raise RuntimeError("DsAddEntry failed")
437 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
438 if ctr.err_data.status != (0, 'WERR_OK'):
439 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
440 ctr.err_data.info.extended_err))
441 raise RuntimeError("DsAddEntry failed")
442 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
443 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
444 raise RuntimeError("DsAddEntry failed")
448 def join_add_ntdsdsa(ctx):
449 '''add the ntdsdsa object'''
451 print "Adding %s" % ctx.ntds_dn
454 "objectclass" : "nTDSDSA",
455 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
456 "dMDLocation" : ctx.schema_dn}
458 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
460 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
461 rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
463 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
464 rec["msDS-HasDomainNCs"] = ctx.base_dn
467 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
468 rec["msDS-HasFullReplicaNCs"] = ctx.nc_list
469 rec["options"] = "37"
470 ctx.samdb.add(rec, ["rodc_join:1:1"])
472 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
473 rec["HasMasterNCs"] = nc_list
474 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
475 rec["msDS-HasMasterNCs"] = ctx.nc_list
477 rec["invocationId"] = ndr_pack(ctx.invocation_id)
478 ctx.DsAddEntry([rec])
480 # find the GUID of our NTDS DN
481 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
482 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
484 def join_add_objects(ctx):
485 '''add the various objects needed for the join'''
487 print "Adding %s" % ctx.acct_dn
490 "objectClass": "computer",
491 "displayname": ctx.samname,
492 "samaccountname" : ctx.samname,
493 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
494 "dnshostname" : ctx.dnshostname}
495 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
496 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
497 elif ctx.promote_existing:
498 rec['msDS-SupportedEncryptionTypes'] = []
500 rec["managedby"] = ctx.managedby
501 elif ctx.promote_existing:
502 rec["managedby"] = []
504 if ctx.never_reveal_sid:
505 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
506 elif ctx.promote_existing:
507 rec["msDS-NeverRevealGroup"] = []
510 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
511 elif ctx.promote_existing:
512 rec["msDS-RevealOnDemandGroup"] = []
514 if ctx.promote_existing:
515 if ctx.promote_from_dn != ctx.acct_dn:
516 ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn)
517 ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE))
522 ctx.add_krbtgt_account()
524 print "Adding %s" % ctx.server_dn
527 "objectclass" : "server",
528 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
529 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
530 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
531 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
532 # windows seems to add the dnsHostName later
533 "dnsHostName" : ctx.dnshostname}
536 rec["serverReference"] = ctx.acct_dn
541 # the rest is done after replication
545 ctx.join_add_ntdsdsa()
547 if ctx.connection_dn is not None:
548 print "Adding %s" % ctx.connection_dn
550 "dn" : ctx.connection_dn,
551 "objectclass" : "nTDSConnection",
552 "enabledconnection" : "TRUE",
554 "fromServer" : ctx.dc_ntds_dn}
558 print "Adding SPNs to %s" % ctx.acct_dn
560 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
561 for i in range(len(ctx.SPNs)):
562 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
563 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
564 ldb.FLAG_MOD_REPLACE,
565 "servicePrincipalName")
568 # The account password set operation should normally be done over
569 # LDAP. Windows 2000 DCs however allow this only with SSL
570 # connections which are hard to set up and otherwise refuse with
571 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
573 print "Setting account password for %s" % ctx.samname
575 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
576 % ldb.binary_encode(ctx.samname),
578 force_change_at_next_login=False,
579 username=ctx.samname)
580 except ldb.LdbError, (num, _):
581 if num != ldb.ERR_UNWILLING_TO_PERFORM:
583 ctx.net.set_password(account_name=ctx.samname,
584 domain_name=ctx.domain_name,
585 newpassword=ctx.acct_pass)
587 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
588 attrs=["msDS-KeyVersionNumber"])
589 if "msDS-KeyVersionNumber" in res[0]:
590 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
592 ctx.key_version_number = None
594 print("Enabling account")
596 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
597 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
598 ldb.FLAG_MOD_REPLACE,
599 "userAccountControl")
602 if ctx.dns_backend.startswith("BIND9_"):
603 ctx.dnspass = samba.generate_random_password(128, 255)
605 recs = ctx.samdb.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"),
606 {"DNSDOMAIN": ctx.dnsdomain,
607 "DOMAINDN": ctx.base_dn,
608 "HOSTNAME" : ctx.myname,
609 "DNSPASS_B64": b64encode(ctx.dnspass),
610 "DNSNAME" : ctx.dnshostname}))
611 for changetype, msg in recs:
612 assert changetype == ldb.CHANGETYPE_NONE
613 print "Adding DNS account %s with dns/ SPN" % msg["dn"]
615 # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP)
616 del msg["clearTextPassword"]
617 # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP
618 del msg["isCriticalSystemObject"]
621 dns_acct_dn = msg["dn"]
622 except ldb.LdbError, (num, _):
623 if num != ldb.ERR_ENTRY_ALREADY_EXISTS:
626 # The account password set operation should normally be done over
627 # LDAP. Windows 2000 DCs however allow this only with SSL
628 # connections which are hard to set up and otherwise refuse with
629 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
631 print "Setting account password for %s" % ctx.samname
633 ctx.samdb.setpassword("(&(objectClass=user)(samAccountName=dns-%s))"
634 % ldb.binary_encode(ctx.myname),
636 force_change_at_next_login=False,
637 username=ctx.samname)
638 except ldb.LdbError, (num, _):
639 if num != ldb.ERR_UNWILLING_TO_PERFORM:
641 ctx.net.set_password(account_name="dns-" % ctx.myname,
642 domain_name=ctx.domain_name,
643 newpassword=ctx.dnspass)
645 res = ctx.samdb.search(base=dns_acct_dn, scope=ldb.SCOPE_BASE,
646 attrs=["msDS-KeyVersionNumber"])
647 if "msDS-KeyVersionNumber" in res[0]:
648 ctx.dns_key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
650 ctx.dns_key_version_number = None
652 def join_add_objects2(ctx):
653 """add the various objects needed for the join, for subdomains post replication"""
655 print "Adding %s" % ctx.partition_dn
656 # NOTE: windows sends a ntSecurityDescriptor here, we
659 "dn" : ctx.partition_dn,
660 "objectclass" : "crossRef",
661 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
662 "nCName" : ctx.base_dn,
663 "nETBIOSName" : ctx.domain_name,
664 "dnsRoot": ctx.dnsdomain,
665 "trustParent" : ctx.parent_partition_dn,
666 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
667 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
668 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
672 "objectclass" : "nTDSDSA",
673 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
674 "dMDLocation" : ctx.schema_dn}
676 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
678 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
679 rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
681 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
682 rec2["msDS-HasDomainNCs"] = ctx.base_dn
684 rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
685 rec2["HasMasterNCs"] = nc_list
686 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
687 rec2["msDS-HasMasterNCs"] = ctx.nc_list
688 rec2["options"] = "1"
689 rec2["invocationId"] = ndr_pack(ctx.invocation_id)
691 objects = ctx.DsAddEntry([rec, rec2])
692 if len(objects) != 2:
693 raise DCJoinException("Expected 2 objects from DsAddEntry")
695 ctx.ntds_guid = objects[1].guid
697 print("Replicating partition DN")
698 ctx.repl.replicate(ctx.partition_dn,
699 misc.GUID("00000000-0000-0000-0000-000000000000"),
701 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
702 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
704 print("Replicating NTDS DN")
705 ctx.repl.replicate(ctx.ntds_dn,
706 misc.GUID("00000000-0000-0000-0000-000000000000"),
708 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
709 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
711 def join_provision(ctx):
712 """Provision the local SAM."""
714 print "Calling bare provision"
716 logger = logging.getLogger("provision")
717 logger.addHandler(logging.StreamHandler(sys.stdout))
718 smbconf = ctx.lp.configfile
720 presult = provision(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="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 print("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"])
751 domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
752 print("Got domain GUID %s" % domguid)
754 print("Calling own domain provision")
756 logger = logging.getLogger("provision")
757 logger.addHandler(logging.StreamHandler(sys.stdout))
759 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
761 presult = provision_fill(ctx.local_samdb, secrets_ldb,
762 logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
764 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
765 machinepass=ctx.acct_pass, serverrole="domain controller",
766 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
767 dns_backend=ctx.dns_backend)
768 print("Provision OK for domain %s" % ctx.names.dnsdomain)
770 def join_replicate(ctx):
771 """Replicate the SAM."""
773 print "Starting replication"
774 ctx.local_samdb.transaction_start()
776 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
777 if ctx.ntds_guid is None:
778 print("Using DS_BIND_GUID_W2K3")
779 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
781 destination_dsa_guid = ctx.ntds_guid
784 repl_creds = Credentials()
785 repl_creds.guess(ctx.lp)
786 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
787 repl_creds.set_username(ctx.samname)
788 repl_creds.set_password(ctx.acct_pass)
790 repl_creds = ctx.creds
792 binding_options = "seal"
793 if int(ctx.lp.get("log level")) >= 5:
794 binding_options += ",print"
795 repl = drs_utils.drs_Replicate(
796 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
797 ctx.lp, repl_creds, ctx.local_samdb)
799 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
800 destination_dsa_guid, schema=True, rodc=ctx.RODC,
801 replica_flags=ctx.replica_flags)
802 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
803 destination_dsa_guid, rodc=ctx.RODC,
804 replica_flags=ctx.replica_flags)
805 if not ctx.subdomain:
806 # Replicate first the critical object for the basedn
807 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
808 print "Replicating critical objects from the base DN of the domain"
809 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
810 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
811 destination_dsa_guid, rodc=ctx.RODC,
812 replica_flags=ctx.domain_replica_flags)
813 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
815 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
816 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
817 destination_dsa_guid, rodc=ctx.RODC,
818 replica_flags=ctx.domain_replica_flags)
819 print "Done with always replicated NC (base, config, schema)"
821 for nc in (ctx.domaindns_zone, ctx.forestdns_zone):
822 if nc in ctx.nc_list:
823 print "Replicating %s" % (str(nc))
824 repl.replicate(nc, source_dsa_invocation_id,
825 destination_dsa_guid, rodc=ctx.RODC,
826 replica_flags=ctx.replica_flags)
828 if 'DC=ForestDnsZones,%s' % ctx.root_dn in ctx.nc_list:
829 repl.replicate('DC=ForestDnsZones,%s' % ctx.root_dn, source_dsa_invocation_id,
830 destination_dsa_guid, rodc=ctx.RODC,
831 replica_flags=ctx.replica_flags)
832 # FIXME At this point we should add an entry in the forestdns and domaindns NC
833 # (those under CN=Partions,DC=...)
834 # in order to indicate that we hold a replica for this NC
837 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
838 destination_dsa_guid,
839 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
840 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
841 destination_dsa_guid,
842 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
844 ctx.source_dsa_invocation_id = source_dsa_invocation_id
845 ctx.destination_dsa_guid = destination_dsa_guid
847 print "Committing SAM database"
849 ctx.local_samdb.transaction_cancel()
852 ctx.local_samdb.transaction_commit()
854 def send_DsReplicaUpdateRefs(ctx, dn):
855 r = drsuapi.DsReplicaUpdateRefsRequest1()
856 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
857 r.naming_context.dn = str(dn)
858 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
859 r.naming_context.sid = security.dom_sid("S-0-0")
860 r.dest_dsa_guid = ctx.ntds_guid
861 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
862 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
864 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
867 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
869 def join_finalise(ctx):
870 """Finalise the join, mark us synchronised and setup secrets db."""
872 logger = logging.getLogger("provision")
873 logger.addHandler(logging.StreamHandler(sys.stdout))
875 # FIXME we shouldn't do this in all cases
876 # If for some reasons we joined in another site than the one of
877 # DC we just replicated from then we don't need to send the updatereplicateref
878 # as replication between sites is time based and on the initiative of the
880 print "Sending DsReplicateUpdateRefs for all the replicated partitions"
881 for nc in ctx.full_nc_list:
882 ctx.send_DsReplicaUpdateRefs(nc)
885 print "Setting RODC invocationId"
886 ctx.local_samdb.set_invocation_id(str(ctx.invocation_id))
887 ctx.local_samdb.set_opaque_integer("domainFunctionality",
888 ctx.behavior_version)
890 m.dn = ldb.Dn(ctx.local_samdb, "%s" % ctx.ntds_dn)
891 m["invocationId"] = ldb.MessageElement(ndr_pack(ctx.invocation_id),
892 ldb.FLAG_MOD_REPLACE,
894 ctx.local_samdb.modify(m)
896 # Note: as RODC the invocationId is only stored
897 # on the RODC itself, the other DCs never see it.
899 # Thats is why we fix up the replPropertyMetaData stamp
900 # for the 'invocationId' attribute, we need to change
901 # the 'version' to '0', this is what windows 2008r2 does as RODC
903 # This means if the object on a RWDC ever gets a invocationId
904 # attribute, it will have version '1' (or higher), which will
905 # will overwrite the RODC local value.
906 ctx.local_samdb.set_attribute_replmetadata_version(m.dn,
910 print "Setting isSynchronized and dsServiceName"
912 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
913 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
914 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
915 ldb.FLAG_MOD_REPLACE, "dsServiceName")
916 ctx.local_samdb.modify(m)
921 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
923 print "Setting up secrets database"
924 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
926 dnsdomain=ctx.dnsdomain,
927 netbiosname=ctx.myname,
928 domainsid=security.dom_sid(ctx.domsid),
929 machinepass=ctx.acct_pass,
930 secure_channel_type=ctx.secure_channel_type,
931 key_version_number=ctx.key_version_number)
933 if ctx.dns_backend.startswith("BIND9_"):
934 setup_bind9_dns(ctx.local_samdb, secrets_ldb, security.dom_sid(ctx.domsid),
935 ctx.names, ctx.paths, ctx.lp, logger,
936 dns_backend=ctx.dns_backend,
937 dnspass=ctx.dnspass, os_level=ctx.behavior_version,
938 targetdir=ctx.targetdir,
939 key_version_number=ctx.dns_key_version_number)
941 def join_setup_trusts(ctx):
942 """provision the local SAM."""
944 def arcfour_encrypt(key, data):
945 from Crypto.Cipher import ARC4
947 return c.encrypt(data)
949 def string_to_array(string):
950 blob = [0] * len(string)
952 for i in range(len(string)):
953 blob[i] = ord(string[i])
957 print "Setup domain trusts with server %s" % ctx.server
958 binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key
959 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
962 objectAttr = lsa.ObjectAttribute()
963 objectAttr.sec_qos = lsa.QosInfo()
965 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
966 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
968 info = lsa.TrustDomainInfoInfoEx()
969 info.domain_name.string = ctx.dnsdomain
970 info.netbios_name.string = ctx.domain_name
971 info.sid = security.dom_sid(ctx.domsid)
972 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
973 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
974 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
977 oldname = lsa.String()
978 oldname.string = ctx.dnsdomain
979 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
980 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
981 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
982 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
986 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
988 clear_value = drsblobs.AuthInfoClear()
989 clear_value.size = len(password_blob)
990 clear_value.password = password_blob
992 clear_authentication_information = drsblobs.AuthenticationInformation()
993 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
994 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
995 clear_authentication_information.AuthInfo = clear_value
997 authentication_information_array = drsblobs.AuthenticationInformationArray()
998 authentication_information_array.count = 1
999 authentication_information_array.array = [clear_authentication_information]
1001 outgoing = drsblobs.trustAuthInOutBlob()
1003 outgoing.current = authentication_information_array
1005 trustpass = drsblobs.trustDomainPasswords()
1006 confounder = [3] * 512
1008 for i in range(512):
1009 confounder[i] = random.randint(0, 255)
1011 trustpass.confounder = confounder
1013 trustpass.outgoing = outgoing
1014 trustpass.incoming = outgoing
1016 trustpass_blob = ndr_pack(trustpass)
1018 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
1020 auth_blob = lsa.DATA_BUF2()
1021 auth_blob.size = len(encrypted_trustpass)
1022 auth_blob.data = string_to_array(encrypted_trustpass)
1024 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
1025 auth_info.auth_blob = auth_blob
1027 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
1030 security.SEC_STD_DELETE)
1033 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
1034 "objectclass" : "trustedDomain",
1035 "trustType" : str(info.trust_type),
1036 "trustAttributes" : str(info.trust_attributes),
1037 "trustDirection" : str(info.trust_direction),
1038 "flatname" : ctx.forest_domain_name,
1039 "trustPartner" : ctx.dnsforest,
1040 "trustAuthIncoming" : ndr_pack(outgoing),
1041 "trustAuthOutgoing" : ndr_pack(outgoing)
1043 ctx.local_samdb.add(rec)
1046 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
1047 "objectclass" : "user",
1048 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
1049 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
1051 ctx.local_samdb.add(rec)
1055 # full_nc_list is the list of naming context (NC) for which we will
1056 # send a updateRef command to the partner DC
1057 ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
1058 ctx.full_nc_list = [ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
1060 if not ctx.subdomain:
1061 ctx.nc_list += [ctx.base_dn]
1062 if ctx.dns_backend != "NONE":
1063 ctx.nc_list += [ctx.domaindns_zone]
1065 if ctx.dns_backend != "NONE":
1066 ctx.full_nc_list += ['DC=DomainDnsZones,%s' % ctx.base_dn]
1067 ctx.full_nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
1068 ctx.nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
1070 if ctx.promote_existing:
1071 ctx.promote_possible()
1073 ctx.cleanup_old_join()
1076 ctx.join_add_objects()
1077 ctx.join_provision()
1078 ctx.join_replicate()
1080 ctx.join_add_objects2()
1081 ctx.join_provision_own_domain()
1082 ctx.join_setup_trusts()
1085 print "Join failed - cleaning up"
1086 ctx.cleanup_old_join()
1090 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
1091 targetdir=None, domain=None, domain_critical_only=False,
1092 machinepass=None, use_ntvfs=False, dns_backend=None,
1093 promote_existing=False):
1094 """Join as a RODC."""
1096 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
1097 machinepass, use_ntvfs, dns_backend, promote_existing)
1099 lp.set("workgroup", ctx.domain_name)
1100 print("workgroup is %s" % ctx.domain_name)
1102 lp.set("realm", ctx.realm)
1103 print("realm is %s" % ctx.realm)
1105 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
1107 # setup some defaults for accounts that should be replicated to this RODC
1108 ctx.never_reveal_sid = [
1109 "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
1110 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
1111 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
1112 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
1113 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS]
1114 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
1116 mysid = ctx.get_mysid()
1117 admin_dn = "<SID=%s>" % mysid
1118 ctx.managedby = admin_dn
1120 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
1121 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1122 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
1124 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
1125 "RestrictedKrbHost/%s" % ctx.dnshostname ])
1127 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
1128 ctx.secure_channel_type = misc.SEC_CHAN_RODC
1130 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
1131 drsuapi.DRSUAPI_DRS_PER_SYNC |
1132 drsuapi.DRSUAPI_DRS_GET_ANC |
1133 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
1134 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1135 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
1136 ctx.domain_replica_flags = ctx.replica_flags
1137 if domain_critical_only:
1138 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1142 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
1145 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
1146 targetdir=None, domain=None, domain_critical_only=False,
1147 machinepass=None, use_ntvfs=False, dns_backend=None,
1148 promote_existing=False):
1150 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
1151 machinepass, use_ntvfs, dns_backend, promote_existing)
1153 lp.set("workgroup", ctx.domain_name)
1154 print("workgroup is %s" % ctx.domain_name)
1156 lp.set("realm", ctx.realm)
1157 print("realm is %s" % ctx.realm)
1159 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1161 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1162 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1164 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1165 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1166 drsuapi.DRSUAPI_DRS_PER_SYNC |
1167 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1168 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1169 ctx.domain_replica_flags = ctx.replica_flags
1170 if domain_critical_only:
1171 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1174 print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
1176 def join_subdomain(server=None, creds=None, lp=None, site=None,
1177 netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
1178 netbios_domain=None, machinepass=None, use_ntvfs=False,
1181 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain,
1182 machinepass, use_ntvfs, dns_backend)
1183 ctx.subdomain = True
1184 ctx.parent_domain_name = ctx.domain_name
1185 ctx.domain_name = netbios_domain
1186 ctx.realm = dnsdomain
1187 ctx.parent_dnsdomain = ctx.dnsdomain
1188 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1189 ctx.dnsdomain = dnsdomain
1190 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1191 ctx.naming_master = ctx.get_naming_master()
1192 if ctx.naming_master != ctx.server:
1193 print("Reconnecting to naming master %s" % ctx.naming_master)
1194 ctx.server = ctx.naming_master
1195 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1196 session_info=system_session(),
1197 credentials=ctx.creds, lp=ctx.lp)
1199 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1200 ctx.domsid = str(security.random_sid())
1202 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
1203 ctx.trustdom_pass = samba.generate_random_password(128, 128)
1205 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1207 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1208 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1210 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1211 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1212 drsuapi.DRSUAPI_DRS_PER_SYNC |
1213 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1214 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1215 ctx.domain_replica_flags = ctx.replica_flags
1218 print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)