s4-join: Setup correct DNS configuration
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / join.py
blob9ef7d3dd1737658719ae69fa7efa2bedd35efac3
1 # python join code
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.schema import Schema
30 from samba.net import Net
31 from samba.provision.sambadns import setup_bind9_dns
32 import logging
33 import talloc
34 import random
35 import time
37 # this makes debugging easier
38 talloc.enable_null_tracking()
40 class DCJoinException(Exception):
42 def __init__(self, msg):
43 super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
46 class dc_join(object):
47 '''perform a DC join'''
49 def __init__(ctx, server=None, creds=None, lp=None, site=None,
50 netbios_name=None, targetdir=None, domain=None,
51 machinepass=None, use_ntvfs=False, dns_backend=None):
52 ctx.creds = creds
53 ctx.lp = lp
54 ctx.site = site
55 ctx.netbios_name = netbios_name
56 ctx.targetdir = targetdir
57 ctx.use_ntvfs = use_ntvfs
58 if dns_backend is None:
59 ctx.dns_backend = "NONE"
60 else:
61 ctx.dns_backend = dns_backend
63 ctx.nc_list = []
64 ctx.full_nc_list = []
66 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
67 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
69 if server is not None:
70 ctx.server = server
71 else:
72 print("Finding a writeable DC for domain '%s'" % domain)
73 ctx.server = ctx.find_dc(domain)
74 print("Found DC %s" % ctx.server)
76 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
77 session_info=system_session(),
78 credentials=ctx.creds, lp=ctx.lp)
80 try:
81 ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
82 except ldb.LdbError, (enum, estr):
83 raise DCJoinException(estr)
86 ctx.myname = netbios_name
87 ctx.samname = "%s$" % ctx.myname
88 ctx.base_dn = str(ctx.samdb.get_default_basedn())
89 ctx.root_dn = str(ctx.samdb.get_root_basedn())
90 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
91 ctx.config_dn = str(ctx.samdb.get_config_basedn())
92 ctx.domsid = ctx.samdb.get_domain_sid()
93 ctx.domain_name = ctx.get_domain_name()
94 ctx.forest_domain_name = ctx.get_forest_domain_name()
95 ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
97 ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName()
98 ctx.dc_dnsHostName = ctx.get_dnsHostName()
99 ctx.behavior_version = ctx.get_behavior_version()
101 if machinepass is not None:
102 ctx.acct_pass = machinepass
103 else:
104 ctx.acct_pass = samba.generate_random_password(32, 40)
106 # work out the DNs of all the objects we will be adding
107 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
108 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
109 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
110 if ctx.dn_exists(topology_base):
111 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
112 else:
113 ctx.topology_dn = None
115 ctx.dnsdomain = ctx.samdb.domain_dns_name()
116 ctx.dnsforest = ctx.samdb.forest_dns_name()
117 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
119 ctx.realm = ctx.dnsdomain
121 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
123 ctx.tmp_samdb = None
125 ctx.SPNs = [ "HOST/%s" % ctx.myname,
126 "HOST/%s" % ctx.dnshostname,
127 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
129 # these elements are optional
130 ctx.never_reveal_sid = None
131 ctx.reveal_sid = None
132 ctx.connection_dn = None
133 ctx.RODC = False
134 ctx.krbtgt_dn = None
135 ctx.drsuapi = None
136 ctx.managedby = None
137 ctx.subdomain = False
139 def del_noerror(ctx, dn, recursive=False):
140 if recursive:
141 try:
142 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
143 except Exception:
144 return
145 for r in res:
146 ctx.del_noerror(r.dn, recursive=True)
147 try:
148 ctx.samdb.delete(dn)
149 print "Deleted %s" % dn
150 except Exception:
151 pass
153 def cleanup_old_join(ctx):
154 '''remove any DNs from a previous join'''
155 try:
156 # find the krbtgt link
157 print("checking sAMAccountName")
158 if ctx.subdomain:
159 res = None
160 else:
161 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
162 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
163 attrs=["msDS-krbTgtLink"])
164 if res:
165 ctx.del_noerror(res[0].dn, recursive=True)
166 if ctx.connection_dn is not None:
167 ctx.del_noerror(ctx.connection_dn)
168 if ctx.krbtgt_dn is not None:
169 ctx.del_noerror(ctx.krbtgt_dn)
170 ctx.del_noerror(ctx.ntds_dn)
171 ctx.del_noerror(ctx.server_dn, recursive=True)
172 if ctx.topology_dn:
173 ctx.del_noerror(ctx.topology_dn)
174 if ctx.partition_dn:
175 ctx.del_noerror(ctx.partition_dn)
176 if res:
177 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
178 ctx.del_noerror(ctx.new_krbtgt_dn)
180 if ctx.subdomain:
181 binding_options = "sign"
182 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
183 ctx.lp, ctx.creds)
185 objectAttr = lsa.ObjectAttribute()
186 objectAttr.sec_qos = lsa.QosInfo()
188 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
189 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
191 name = lsa.String()
192 name.string = ctx.realm
193 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
195 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
197 name = lsa.String()
198 name.string = ctx.forest_domain_name
199 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
201 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
203 except Exception:
204 pass
206 def find_dc(ctx, domain):
207 '''find a writeable DC for the given domain'''
208 try:
209 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
210 except Exception:
211 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
212 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
213 ctx.site = ctx.cldap_ret.client_site
214 return ctx.cldap_ret.pdc_dns_name
217 def get_behavior_version(ctx):
218 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
219 if "msDS-Behavior-Version" in res[0]:
220 return int(res[0]["msDS-Behavior-Version"][0])
221 else:
222 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
224 def get_dnsHostName(ctx):
225 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
226 return res[0]["dnsHostName"][0]
228 def get_domain_name(ctx):
229 '''get netbios name of the domain from the partitions record'''
230 partitions_dn = ctx.samdb.get_partitions_dn()
231 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
232 expression='ncName=%s' % ctx.samdb.get_default_basedn())
233 return res[0]["nETBIOSName"][0]
235 def get_forest_domain_name(ctx):
236 '''get netbios name of the domain from the partitions record'''
237 partitions_dn = ctx.samdb.get_partitions_dn()
238 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
239 expression='ncName=%s' % ctx.samdb.get_root_basedn())
240 return res[0]["nETBIOSName"][0]
242 def get_parent_partition_dn(ctx):
243 '''get the parent domain partition DN from parent DNS name'''
244 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
245 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
246 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
247 return str(res[0].dn)
249 def get_naming_master(ctx):
250 '''get the parent domain partition DN from parent DNS name'''
251 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
252 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
253 if not 'fSMORoleOwner' in res[0]:
254 raise DCJoinException("Can't find naming master on partition DN %s" % ctx.partition_dn)
255 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
256 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
257 return master_host
259 def get_mysid(ctx):
260 '''get the SID of the connected user. Only works with w2k8 and later,
261 so only used for RODC join'''
262 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
263 binsid = res[0]["tokenGroups"][0]
264 return ctx.samdb.schema_format_value("objectSID", binsid)
266 def dn_exists(ctx, dn):
267 '''check if a DN exists'''
268 try:
269 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
270 except ldb.LdbError, (enum, estr):
271 if enum == ldb.ERR_NO_SUCH_OBJECT:
272 return False
273 raise
274 return True
276 def add_krbtgt_account(ctx):
277 '''RODCs need a special krbtgt account'''
278 print "Adding %s" % ctx.krbtgt_dn
279 rec = {
280 "dn" : ctx.krbtgt_dn,
281 "objectclass" : "user",
282 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
283 samba.dsdb.UF_ACCOUNTDISABLE),
284 "showinadvancedviewonly" : "TRUE",
285 "description" : "krbtgt for %s" % ctx.samname}
286 ctx.samdb.add(rec, ["rodc_join:1:1"])
288 # now we need to search for the samAccountName attribute on the krbtgt DN,
289 # as this will have been magically set to the krbtgt number
290 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
291 ctx.krbtgt_name = res[0]["samAccountName"][0]
293 print "Got krbtgt_name=%s" % ctx.krbtgt_name
295 m = ldb.Message()
296 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
297 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
298 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
299 ctx.samdb.modify(m)
301 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
302 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
303 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
305 def drsuapi_connect(ctx):
306 '''make a DRSUAPI connection to the naming master'''
307 binding_options = "seal"
308 if int(ctx.lp.get("log level")) >= 4:
309 binding_options += ",print"
310 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
311 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
312 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
314 def create_tmp_samdb(ctx):
315 '''create a temporary samdb object for schema queries'''
316 ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
317 schemadn=ctx.schema_dn)
318 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
319 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
320 am_rodc=False)
321 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
323 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
324 '''build a DsReplicaAttributeCtr object'''
325 r = drsuapi.DsReplicaAttribute()
326 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
327 r.value_ctr = 1
330 def DsAddEntry(ctx, recs):
331 '''add a record via the DRSUAPI DsAddEntry call'''
332 if ctx.drsuapi is None:
333 ctx.drsuapi_connect()
334 if ctx.tmp_samdb is None:
335 ctx.create_tmp_samdb()
337 objects = []
338 for rec in recs:
339 id = drsuapi.DsReplicaObjectIdentifier()
340 id.dn = rec['dn']
342 attrs = []
343 for a in rec:
344 if a == 'dn':
345 continue
346 if not isinstance(rec[a], list):
347 v = [rec[a]]
348 else:
349 v = rec[a]
350 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
351 attrs.append(rattr)
353 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
354 attribute_ctr.num_attributes = len(attrs)
355 attribute_ctr.attributes = attrs
357 object = drsuapi.DsReplicaObject()
358 object.identifier = id
359 object.attribute_ctr = attribute_ctr
361 list_object = drsuapi.DsReplicaObjectListItem()
362 list_object.object = object
363 objects.append(list_object)
365 req2 = drsuapi.DsAddEntryRequest2()
366 req2.first_object = objects[0]
367 prev = req2.first_object
368 for o in objects[1:]:
369 prev.next_object = o
370 prev = o
372 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
373 if level == 2:
374 if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
375 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
376 raise RuntimeError("DsAddEntry failed")
377 if ctr.extended_err != (0, 'WERR_OK'):
378 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
379 raise RuntimeError("DsAddEntry failed")
380 if level == 3:
381 if ctr.err_ver != 1:
382 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
383 if ctr.err_data.status != (0, 'WERR_OK'):
384 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
385 ctr.err_data.info.extended_err))
386 raise RuntimeError("DsAddEntry failed")
387 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
388 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
389 raise RuntimeError("DsAddEntry failed")
391 return ctr.objects
393 def join_add_ntdsdsa(ctx):
394 '''add the ntdsdsa object'''
395 # FIXME: the partition (NC) assignment has to be made dynamic
396 print "Adding %s" % ctx.ntds_dn
397 rec = {
398 "dn" : ctx.ntds_dn,
399 "objectclass" : "nTDSDSA",
400 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
401 "dMDLocation" : ctx.schema_dn}
403 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
405 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
406 rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
408 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
409 rec["msDS-HasDomainNCs"] = ctx.base_dn
411 if ctx.RODC:
412 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
413 rec["msDS-HasFullReplicaNCs"] = ctx.nc_list
414 rec["options"] = "37"
415 ctx.samdb.add(rec, ["rodc_join:1:1"])
416 else:
417 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
418 rec["HasMasterNCs"] = nc_list
419 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
420 rec["msDS-HasMasterNCs"] = ctx.nc_list
421 rec["options"] = "1"
422 rec["invocationId"] = ndr_pack(ctx.invocation_id)
423 ctx.DsAddEntry([rec])
425 # find the GUID of our NTDS DN
426 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
427 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
429 def join_add_objects(ctx):
430 '''add the various objects needed for the join'''
431 if ctx.acct_dn:
432 print "Adding %s" % ctx.acct_dn
433 rec = {
434 "dn" : ctx.acct_dn,
435 "objectClass": "computer",
436 "displayname": ctx.samname,
437 "samaccountname" : ctx.samname,
438 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
439 "dnshostname" : ctx.dnshostname}
440 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
441 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
442 if ctx.managedby:
443 rec["managedby"] = ctx.managedby
444 if ctx.never_reveal_sid:
445 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
446 if ctx.reveal_sid:
447 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
448 ctx.samdb.add(rec)
450 if ctx.krbtgt_dn:
451 ctx.add_krbtgt_account()
453 print "Adding %s" % ctx.server_dn
454 rec = {
455 "dn": ctx.server_dn,
456 "objectclass" : "server",
457 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
458 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
459 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
460 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
461 # windows seems to add the dnsHostName later
462 "dnsHostName" : ctx.dnshostname}
464 if ctx.acct_dn:
465 rec["serverReference"] = ctx.acct_dn
467 ctx.samdb.add(rec)
469 if ctx.subdomain:
470 # the rest is done after replication
471 ctx.ntds_guid = None
472 return
474 ctx.join_add_ntdsdsa()
476 if ctx.connection_dn is not None:
477 print "Adding %s" % ctx.connection_dn
478 rec = {
479 "dn" : ctx.connection_dn,
480 "objectclass" : "nTDSConnection",
481 "enabledconnection" : "TRUE",
482 "options" : "65",
483 "fromServer" : ctx.dc_ntds_dn}
484 ctx.samdb.add(rec)
486 if ctx.acct_dn:
487 print "Adding SPNs to %s" % ctx.acct_dn
488 m = ldb.Message()
489 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
490 for i in range(len(ctx.SPNs)):
491 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
492 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
493 ldb.FLAG_MOD_ADD,
494 "servicePrincipalName")
495 ctx.samdb.modify(m)
497 # The account password set operation should normally be done over
498 # LDAP. Windows 2000 DCs however allow this only with SSL
499 # connections which are hard to set up and otherwise refuse with
500 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
501 # over SAMR.
502 print "Setting account password for %s" % ctx.samname
503 try:
504 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
505 % ldb.binary_encode(ctx.samname),
506 ctx.acct_pass,
507 force_change_at_next_login=False,
508 username=ctx.samname)
509 except ldb.LdbError, (num, _):
510 if num != ldb.ERR_UNWILLING_TO_PERFORM:
511 pass
512 ctx.net.set_password(account_name=ctx.samname,
513 domain_name=ctx.domain_name,
514 newpassword=ctx.acct_pass)
516 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
517 attrs=["msDS-KeyVersionNumber"])
518 if "msDS-KeyVersionNumber" in res[0]:
519 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
520 else:
521 ctx.key_version_number = None
523 print("Enabling account")
524 m = ldb.Message()
525 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
526 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
527 ldb.FLAG_MOD_REPLACE,
528 "userAccountControl")
529 ctx.samdb.modify(m)
531 def join_add_objects2(ctx):
532 '''add the various objects needed for the join, for subdomains post replication'''
534 print "Adding %s" % ctx.partition_dn
535 # NOTE: windows sends a ntSecurityDescriptor here, we
536 # let it default
537 rec = {
538 "dn" : ctx.partition_dn,
539 "objectclass" : "crossRef",
540 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
541 "nCName" : ctx.base_dn,
542 "nETBIOSName" : ctx.domain_name,
543 "dnsRoot": ctx.dnsdomain,
544 "trustParent" : ctx.parent_partition_dn,
545 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
546 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
547 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
549 rec2 = {
550 "dn" : ctx.ntds_dn,
551 "objectclass" : "nTDSDSA",
552 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
553 "dMDLocation" : ctx.schema_dn}
555 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
557 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
558 rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
560 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
561 rec2["msDS-HasDomainNCs"] = ctx.base_dn
563 rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
564 rec2["HasMasterNCs"] = nc_list
565 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
566 rec2["msDS-HasMasterNCs"] = ctx.nc_list
567 rec2["options"] = "1"
568 rec2["invocationId"] = ndr_pack(ctx.invocation_id)
570 objects = ctx.DsAddEntry([rec, rec2])
571 if len(objects) != 2:
572 raise DCJoinException("Expected 2 objects from DsAddEntry")
574 ctx.ntds_guid = objects[1].guid
576 print("Replicating partition DN")
577 ctx.repl.replicate(ctx.partition_dn,
578 misc.GUID("00000000-0000-0000-0000-000000000000"),
579 ctx.ntds_guid,
580 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
581 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
583 print("Replicating NTDS DN")
584 ctx.repl.replicate(ctx.ntds_dn,
585 misc.GUID("00000000-0000-0000-0000-000000000000"),
586 ctx.ntds_guid,
587 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
588 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
590 def join_provision(ctx):
591 '''provision the local SAM'''
593 print "Calling bare provision"
595 logger = logging.getLogger("provision")
596 logger.addHandler(logging.StreamHandler(sys.stdout))
597 smbconf = ctx.lp.configfile
599 presult = provision(logger, system_session(), None, smbconf=smbconf,
600 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
601 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
602 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
603 serverdn=ctx.server_dn, domain=ctx.domain_name,
604 hostname=ctx.myname, domainsid=ctx.domsid,
605 machinepass=ctx.acct_pass, serverrole="domain controller",
606 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
607 use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend)
608 print "Provision OK for domain DN %s" % presult.domaindn
609 ctx.local_samdb = presult.samdb
610 ctx.lp = presult.lp
611 ctx.paths = presult.paths
612 ctx.names = presult.names
614 def join_provision_own_domain(ctx):
615 '''provision the local SAM'''
617 # we now operate exclusively on the local database, which
618 # we need to reopen in order to get the newly created schema
619 print("Reconnecting to local samdb")
620 ctx.samdb = SamDB(url=ctx.local_samdb.url,
621 session_info=system_session(),
622 lp=ctx.local_samdb.lp,
623 global_schema=False)
624 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
625 ctx.local_samdb = ctx.samdb
627 print("Finding domain GUID from ncName")
628 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
629 controls=["extended_dn:1:1"])
630 domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
631 print("Got domain GUID %s" % domguid)
633 print("Calling own domain provision")
635 logger = logging.getLogger("provision")
636 logger.addHandler(logging.StreamHandler(sys.stdout))
638 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
640 presult = provision_fill(ctx.local_samdb, secrets_ldb,
641 logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
642 domainguid=domguid,
643 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
644 machinepass=ctx.acct_pass, serverrole="domain controller",
645 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
646 dns_backend=ctx.dns_backend)
647 print("Provision OK for domain %s" % ctx.names.dnsdomain)
649 def join_replicate(ctx):
650 '''replicate the SAM'''
652 print "Starting replication"
653 ctx.local_samdb.transaction_start()
654 try:
655 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
656 if ctx.ntds_guid is None:
657 print("Using DS_BIND_GUID_W2K3")
658 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
659 else:
660 destination_dsa_guid = ctx.ntds_guid
662 if ctx.RODC:
663 repl_creds = Credentials()
664 repl_creds.guess(ctx.lp)
665 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
666 repl_creds.set_username(ctx.samname)
667 repl_creds.set_password(ctx.acct_pass)
668 else:
669 repl_creds = ctx.creds
671 binding_options = "seal"
672 if int(ctx.lp.get("log level")) >= 5:
673 binding_options += ",print"
674 repl = drs_utils.drs_Replicate(
675 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
676 ctx.lp, repl_creds, ctx.local_samdb)
678 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
679 destination_dsa_guid, schema=True, rodc=ctx.RODC,
680 replica_flags=ctx.replica_flags)
681 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
682 destination_dsa_guid, rodc=ctx.RODC,
683 replica_flags=ctx.replica_flags)
684 if not ctx.subdomain:
685 # Replicate first the critical object for the basedn
686 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
687 print "Replicating critical objects from the base DN of the domain"
688 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
689 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
690 destination_dsa_guid, rodc=ctx.RODC,
691 replica_flags=ctx.domain_replica_flags)
692 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
693 else:
694 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
695 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
696 destination_dsa_guid, rodc=ctx.RODC,
697 replica_flags=ctx.domain_replica_flags)
699 if 'DC=DomainDnsZones,%s' % ctx.base_dn in ctx.nc_list:
700 repl.replicate('DC=DomainDnsZones,%s' % ctx.base_dn, source_dsa_invocation_id,
701 destination_dsa_guid, rodc=ctx.RODC,
702 replica_flags=ctx.replica_flags)
704 if 'DC=ForestDnsZones,%s' % ctx.root_dn in ctx.nc_list:
705 repl.replicate('DC=ForestDnsZones,%s' % ctx.root_dn, source_dsa_invocation_id,
706 destination_dsa_guid, rodc=ctx.RODC,
707 replica_flags=ctx.replica_flags)
709 if ctx.RODC:
710 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
711 destination_dsa_guid,
712 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
713 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
714 destination_dsa_guid,
715 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
716 ctx.repl = repl
717 ctx.source_dsa_invocation_id = source_dsa_invocation_id
718 ctx.destination_dsa_guid = destination_dsa_guid
720 print "Committing SAM database"
721 except:
722 ctx.local_samdb.transaction_cancel()
723 raise
724 else:
725 ctx.local_samdb.transaction_commit()
727 def send_DsReplicaUpdateRefs(ctx, dn):
728 r = drsuapi.DsReplicaUpdateRefsRequest1()
729 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
730 r.naming_context.dn = str(dn)
731 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
732 r.naming_context.sid = security.dom_sid("S-0-0")
733 r.dest_dsa_guid = ctx.ntds_guid
734 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
735 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
736 if not ctx.RODC:
737 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
739 if ctx.drsuapi:
740 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
742 def join_finalise(ctx):
743 '''finalise the join, mark us synchronised and setup secrets db'''
745 logger = logging.getLogger("provision")
746 logger.addHandler(logging.StreamHandler(sys.stdout))
748 print "Sending DsReplicateUpdateRefs for all the partitions"
749 for nc in ctx.full_nc_list:
750 ctx.send_DsReplicaUpdateRefs(nc)
752 print "Setting isSynchronized and dsServiceName"
753 m = ldb.Message()
754 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
755 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
756 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
757 ldb.FLAG_MOD_REPLACE, "dsServiceName")
758 ctx.local_samdb.modify(m)
760 if ctx.subdomain:
761 return
763 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
765 print "Setting up secrets database"
766 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
767 realm=ctx.realm,
768 dnsdomain=ctx.dnsdomain,
769 netbiosname=ctx.myname,
770 domainsid=security.dom_sid(ctx.domsid),
771 machinepass=ctx.acct_pass,
772 secure_channel_type=ctx.secure_channel_type,
773 key_version_number=ctx.key_version_number)
775 if ctx.dns_backend.startswith("BIND9_"):
776 dnspass = samba.generate_random_password(128, 255)
778 setup_bind9_dns(ctx.local_samdb, secrets_ldb, security.dom_sid(ctx.domsid),
779 ctx.names, ctx.paths, ctx.lp, logger,
780 dns_backend=ctx.dns_backend,
781 dnspass=dnspass, os_level=ctx.behavior_version,
782 targetdir=ctx.targetdir)
784 def join_setup_trusts(ctx):
785 '''provision the local SAM'''
787 def arcfour_encrypt(key, data):
788 from Crypto.Cipher import ARC4
789 c = ARC4.new(key)
790 return c.encrypt(data)
792 def string_to_array(string):
793 blob = [0] * len(string)
795 for i in range(len(string)):
796 blob[i] = ord(string[i])
798 return blob
800 print "Setup domain trusts with server %s" % ctx.server
801 binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key
802 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
803 ctx.lp, ctx.creds)
805 objectAttr = lsa.ObjectAttribute()
806 objectAttr.sec_qos = lsa.QosInfo()
808 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
809 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
811 info = lsa.TrustDomainInfoInfoEx()
812 info.domain_name.string = ctx.dnsdomain
813 info.netbios_name.string = ctx.domain_name
814 info.sid = security.dom_sid(ctx.domsid)
815 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
816 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
817 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
819 try:
820 oldname = lsa.String()
821 oldname.string = ctx.dnsdomain
822 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
823 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
824 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
825 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
826 except RuntimeError:
827 pass
829 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
831 clear_value = drsblobs.AuthInfoClear()
832 clear_value.size = len(password_blob)
833 clear_value.password = password_blob
835 clear_authentication_information = drsblobs.AuthenticationInformation()
836 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
837 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
838 clear_authentication_information.AuthInfo = clear_value
840 authentication_information_array = drsblobs.AuthenticationInformationArray()
841 authentication_information_array.count = 1
842 authentication_information_array.array = [clear_authentication_information]
844 outgoing = drsblobs.trustAuthInOutBlob()
845 outgoing.count = 1
846 outgoing.current = authentication_information_array
848 trustpass = drsblobs.trustDomainPasswords()
849 confounder = [3] * 512
851 for i in range(512):
852 confounder[i] = random.randint(0, 255)
854 trustpass.confounder = confounder
856 trustpass.outgoing = outgoing
857 trustpass.incoming = outgoing
859 trustpass_blob = ndr_pack(trustpass)
861 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
863 auth_blob = lsa.DATA_BUF2()
864 auth_blob.size = len(encrypted_trustpass)
865 auth_blob.data = string_to_array(encrypted_trustpass)
867 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
868 auth_info.auth_blob = auth_blob
870 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
871 info,
872 auth_info,
873 security.SEC_STD_DELETE)
875 rec = {
876 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
877 "objectclass" : "trustedDomain",
878 "trustType" : str(info.trust_type),
879 "trustAttributes" : str(info.trust_attributes),
880 "trustDirection" : str(info.trust_direction),
881 "flatname" : ctx.forest_domain_name,
882 "trustPartner" : ctx.dnsforest,
883 "trustAuthIncoming" : ndr_pack(outgoing),
884 "trustAuthOutgoing" : ndr_pack(outgoing)
886 ctx.local_samdb.add(rec)
888 rec = {
889 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
890 "objectclass" : "user",
891 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
892 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
894 ctx.local_samdb.add(rec)
897 def do_join(ctx):
898 ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
899 ctx.full_nc_list = [ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
901 if not ctx.subdomain:
902 ctx.nc_list += [ctx.base_dn]
903 if ctx.dns_backend != "NONE":
904 ctx.nc_list += ['DC=DomainDnsZones,%s' % ctx.base_dn]
906 if ctx.dns_backend != "NONE":
907 ctx.full_nc_list += ['DC=DomainDnsZones,%s' % ctx.base_dn]
908 ctx.full_nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
909 ctx.nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
912 ctx.cleanup_old_join()
913 try:
914 ctx.join_add_objects()
915 ctx.join_provision()
916 ctx.join_replicate()
917 if ctx.subdomain:
918 ctx.join_add_objects2()
919 ctx.join_provision_own_domain()
920 ctx.join_setup_trusts()
921 ctx.join_finalise()
922 except:
923 print "Join failed - cleaning up"
924 ctx.cleanup_old_join()
925 raise
928 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
929 targetdir=None, domain=None, domain_critical_only=False,
930 machinepass=None, use_ntvfs=False, dns_backend=None):
931 """join as a RODC"""
933 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
934 machinepass, use_ntvfs, dns_backend)
936 lp.set("workgroup", ctx.domain_name)
937 print("workgroup is %s" % ctx.domain_name)
939 lp.set("realm", ctx.realm)
940 print("realm is %s" % ctx.realm)
942 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
944 # setup some defaults for accounts that should be replicated to this RODC
945 ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
946 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
947 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
948 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
949 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
950 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
952 mysid = ctx.get_mysid()
953 admin_dn = "<SID=%s>" % mysid
954 ctx.managedby = admin_dn
956 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
957 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
958 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
960 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
961 "RestrictedKrbHost/%s" % ctx.dnshostname ])
963 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
964 ctx.secure_channel_type = misc.SEC_CHAN_RODC
965 ctx.RODC = True
966 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
967 drsuapi.DRSUAPI_DRS_PER_SYNC |
968 drsuapi.DRSUAPI_DRS_GET_ANC |
969 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
970 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
971 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
972 ctx.domain_replica_flags = ctx.replica_flags
973 if domain_critical_only:
974 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
976 ctx.do_join()
979 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
982 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
983 targetdir=None, domain=None, domain_critical_only=False,
984 machinepass=None, use_ntvfs=False, dns_backend=None):
985 """join as a DC"""
986 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
987 machinepass, use_ntvfs, dns_backend)
989 lp.set("workgroup", ctx.domain_name)
990 print("workgroup is %s" % ctx.domain_name)
992 lp.set("realm", ctx.realm)
993 print("realm is %s" % ctx.realm)
995 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
997 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
998 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1000 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1001 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1002 drsuapi.DRSUAPI_DRS_PER_SYNC |
1003 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1004 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1005 ctx.domain_replica_flags = ctx.replica_flags
1006 if domain_critical_only:
1007 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1009 ctx.do_join()
1010 print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
1012 def join_subdomain(server=None, creds=None, lp=None, site=None, netbios_name=None,
1013 targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None,
1014 machinepass=None, use_ntvfs=False, dns_backend=None):
1015 """join as a DC"""
1016 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain,
1017 machinepass, use_ntvfs, dns_backend)
1018 ctx.subdomain = True
1019 ctx.parent_domain_name = ctx.domain_name
1020 ctx.domain_name = netbios_domain
1021 ctx.realm = dnsdomain
1022 ctx.parent_dnsdomain = ctx.dnsdomain
1023 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1024 ctx.dnsdomain = dnsdomain
1025 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1026 ctx.naming_master = ctx.get_naming_master()
1027 if ctx.naming_master != ctx.server:
1028 print("Reconnecting to naming master %s" % ctx.naming_master)
1029 ctx.server = ctx.naming_master
1030 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1031 session_info=system_session(),
1032 credentials=ctx.creds, lp=ctx.lp)
1034 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1035 ctx.domsid = str(security.random_sid())
1036 ctx.acct_dn = None
1037 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
1038 ctx.trustdom_pass = samba.generate_random_password(128, 128)
1040 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1042 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1043 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1045 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1046 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1047 drsuapi.DRSUAPI_DRS_PER_SYNC |
1048 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1049 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1050 ctx.domain_replica_flags = ctx.replica_flags
1052 ctx.do_join()
1053 print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)