s4-dns: dlz_bind9: Create dns-HOSTNAME account disabled
[Samba.git] / python / samba / join.py
blobf8ede5df5b464d7ea9d55bbbd104b1618e2e686b
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.dsdb import DS_DOMAIN_FUNCTION_2003
28 from samba.credentials import Credentials, DONT_USE_KERBEROS
29 from samba.provision import secretsdb_self_join, provision, provision_fill, FILL_DRS, FILL_SUBDOMAIN
30 from samba.provision.common import setup_path
31 from samba.schema import Schema
32 from samba.net import Net
33 from samba.provision.sambadns import setup_bind9_dns
34 from samba import read_and_sub_file
35 from base64 import b64encode
36 import logging
37 import talloc
38 import random
39 import time
41 # this makes debugging easier
42 talloc.enable_null_tracking()
44 class DCJoinException(Exception):
46 def __init__(self, msg):
47 super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
50 class dc_join(object):
51 """Perform a DC join."""
53 def __init__(ctx, logger=None, server=None, creds=None, lp=None, site=None,
54 netbios_name=None, targetdir=None, domain=None,
55 machinepass=None, use_ntvfs=False, dns_backend=None,
56 promote_existing=False):
57 ctx.logger = logger
58 ctx.creds = creds
59 ctx.lp = lp
60 ctx.site = site
61 ctx.netbios_name = netbios_name
62 ctx.targetdir = targetdir
63 ctx.use_ntvfs = use_ntvfs
65 ctx.promote_existing = promote_existing
66 ctx.promote_from_dn = None
68 ctx.nc_list = []
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:
74 ctx.server = server
75 else:
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)
84 try:
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
107 else:
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)
116 else:
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.root_dn
124 res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
125 attrs=[],
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"
130 else:
131 if len(res_domaindns) == 0:
132 ctx.dns_backend = "NONE"
133 print "NO DNS zone information found in source domain, not replicating DNS"
134 else:
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)
143 ctx.tmp_samdb = None
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
153 ctx.RODC = False
154 ctx.krbtgt_dn = None
155 ctx.drsuapi = None
156 ctx.managedby = None
157 ctx.subdomain = False
158 ctx.adminpass = None
160 def del_noerror(ctx, dn, recursive=False):
161 if recursive:
162 try:
163 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
164 except Exception:
165 return
166 for r in res:
167 ctx.del_noerror(r.dn, recursive=True)
168 try:
169 ctx.samdb.delete(dn)
170 print "Deleted %s" % dn
171 except Exception:
172 pass
174 def cleanup_old_join(ctx):
175 """Remove any DNs from a previous join."""
176 try:
177 # find the krbtgt link
178 print("checking sAMAccountName")
179 if ctx.subdomain:
180 res = None
181 else:
182 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
183 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
184 attrs=["msDS-krbTgtLink"])
185 if res:
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)),
190 attrs=[])
191 if res:
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),
196 attrs=[])
197 if res:
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)
206 if ctx.topology_dn:
207 ctx.del_noerror(ctx.topology_dn)
208 if ctx.partition_dn:
209 ctx.del_noerror(ctx.partition_dn)
210 if res:
211 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
212 ctx.del_noerror(ctx.new_krbtgt_dn)
214 if ctx.subdomain:
215 binding_options = "sign"
216 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
217 ctx.lp, ctx.creds)
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)
225 name = lsa.String()
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)
231 name = lsa.String()
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)
237 except Exception:
238 pass
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"""
242 if ctx.subdomain:
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"])
249 if len(res) == 0:
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"""
261 try:
262 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
263 except Exception:
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])
274 else:
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))
308 try:
309 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
310 except KeyError:
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)
314 return master_host
316 def get_mysid(ctx):
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'''
325 try:
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:
329 return False
330 raise
331 return True
333 def add_krbtgt_account(ctx):
334 '''RODCs need a special krbtgt account'''
335 print "Adding %s" % ctx.krbtgt_dn
336 rec = {
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
352 m = ldb.Message()
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")
356 ctx.samdb.modify(m)
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,
377 am_rodc=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)
384 r.value_ctr = 1
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()
394 objects = []
395 for rec in recs:
396 id = drsuapi.DsReplicaObjectIdentifier()
397 id.dn = rec['dn']
399 attrs = []
400 for a in rec:
401 if a == 'dn':
402 continue
403 if not isinstance(rec[a], list):
404 v = [rec[a]]
405 else:
406 v = rec[a]
407 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
408 attrs.append(rattr)
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:]:
426 prev.next_object = o
427 prev = o
429 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
430 if level == 2:
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")
437 if level == 3:
438 if ctr.err_ver != 1:
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")
448 return ctr.objects
450 def join_add_ntdsdsa(ctx):
451 '''add the ntdsdsa object'''
453 print "Adding %s" % ctx.ntds_dn
454 rec = {
455 "dn" : 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
468 if ctx.RODC:
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"])
473 else:
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
478 rec["options"] = "1"
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'''
488 if ctx.acct_dn:
489 print "Adding %s" % ctx.acct_dn
490 rec = {
491 "dn" : 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'] = []
501 if ctx.managedby:
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"] = []
511 if ctx.reveal_sid:
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))
520 else:
521 ctx.samdb.add(rec)
523 if ctx.krbtgt_dn:
524 ctx.add_krbtgt_account()
526 print "Adding %s" % ctx.server_dn
527 rec = {
528 "dn": 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}
537 if ctx.acct_dn:
538 rec["serverReference"] = ctx.acct_dn
540 ctx.samdb.add(rec)
542 if ctx.subdomain:
543 # the rest is done after replication
544 ctx.ntds_guid = None
545 return
547 ctx.join_add_ntdsdsa()
549 if ctx.connection_dn is not None:
550 print "Adding %s" % ctx.connection_dn
551 rec = {
552 "dn" : ctx.connection_dn,
553 "objectclass" : "nTDSConnection",
554 "enabledconnection" : "TRUE",
555 "options" : "65",
556 "fromServer" : ctx.dc_ntds_dn}
557 ctx.samdb.add(rec)
559 if ctx.acct_dn:
560 print "Adding SPNs to %s" % ctx.acct_dn
561 m = ldb.Message()
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")
568 ctx.samdb.modify(m)
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
574 # over SAMR.
575 print "Setting account password for %s" % ctx.samname
576 try:
577 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
578 % ldb.binary_encode(ctx.samname),
579 ctx.acct_pass,
580 force_change_at_next_login=False,
581 username=ctx.samname)
582 except ldb.LdbError, (num, _):
583 if num != ldb.ERR_UNWILLING_TO_PERFORM:
584 pass
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])
593 else:
594 ctx.key_version_number = None
596 print("Enabling account")
597 m = ldb.Message()
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")
602 ctx.samdb.modify(m)
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 dns_acct_dn = msg["dn"]
616 print "Adding DNS account %s with dns/ SPN" % msg["dn"]
618 # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP)
619 del msg["clearTextPassword"]
620 # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP
621 del msg["isCriticalSystemObject"]
622 # Disable account until password is set
623 msg["userAccountControl"] = str(samba.dsdb.UF_NORMAL_ACCOUNT |
624 samba.dsdb.UF_ACCOUNTDISABLE)
625 try:
626 ctx.samdb.add(msg)
627 except ldb.LdbError, (num, _):
628 if num != ldb.ERR_ENTRY_ALREADY_EXISTS:
629 raise
631 # The account password set operation should normally be done over
632 # LDAP. Windows 2000 DCs however allow this only with SSL
633 # connections which are hard to set up and otherwise refuse with
634 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
635 # over SAMR.
636 print "Setting account password for dns-%s" % ctx.myname
637 try:
638 ctx.samdb.setpassword("(&(objectClass=user)(samAccountName=dns-%s))"
639 % ldb.binary_encode(ctx.myname),
640 ctx.dnspass,
641 force_change_at_next_login=False,
642 username=ctx.samname)
643 except ldb.LdbError, (num, _):
644 if num != ldb.ERR_UNWILLING_TO_PERFORM:
645 raise
646 ctx.net.set_password(account_name="dns-%s" % ctx.myname,
647 domain_name=ctx.domain_name,
648 newpassword=ctx.dnspass)
650 res = ctx.samdb.search(base=dns_acct_dn, scope=ldb.SCOPE_BASE,
651 attrs=["msDS-KeyVersionNumber"])
652 if "msDS-KeyVersionNumber" in res[0]:
653 ctx.dns_key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
654 else:
655 ctx.dns_key_version_number = None
657 def join_add_objects2(ctx):
658 """add the various objects needed for the join, for subdomains post replication"""
660 print "Adding %s" % ctx.partition_dn
661 # NOTE: windows sends a ntSecurityDescriptor here, we
662 # let it default
663 rec = {
664 "dn" : ctx.partition_dn,
665 "objectclass" : "crossRef",
666 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
667 "nCName" : ctx.base_dn,
668 "nETBIOSName" : ctx.domain_name,
669 "dnsRoot": ctx.dnsdomain,
670 "trustParent" : ctx.parent_partition_dn,
671 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
672 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
673 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
675 rec2 = {
676 "dn" : ctx.ntds_dn,
677 "objectclass" : "nTDSDSA",
678 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
679 "dMDLocation" : ctx.schema_dn}
681 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
683 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
684 rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
686 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
687 rec2["msDS-HasDomainNCs"] = ctx.base_dn
689 rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
690 rec2["HasMasterNCs"] = nc_list
691 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
692 rec2["msDS-HasMasterNCs"] = ctx.nc_list
693 rec2["options"] = "1"
694 rec2["invocationId"] = ndr_pack(ctx.invocation_id)
696 objects = ctx.DsAddEntry([rec, rec2])
697 if len(objects) != 2:
698 raise DCJoinException("Expected 2 objects from DsAddEntry")
700 ctx.ntds_guid = objects[1].guid
702 print("Replicating partition DN")
703 ctx.repl.replicate(ctx.partition_dn,
704 misc.GUID("00000000-0000-0000-0000-000000000000"),
705 ctx.ntds_guid,
706 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
707 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
709 print("Replicating NTDS DN")
710 ctx.repl.replicate(ctx.ntds_dn,
711 misc.GUID("00000000-0000-0000-0000-000000000000"),
712 ctx.ntds_guid,
713 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
714 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
716 def join_provision(ctx):
717 """Provision the local SAM."""
719 print "Calling bare provision"
721 smbconf = ctx.lp.configfile
723 presult = provision(ctx.logger, system_session(), smbconf=smbconf,
724 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
725 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
726 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
727 serverdn=ctx.server_dn, domain=ctx.domain_name,
728 hostname=ctx.myname, domainsid=ctx.domsid,
729 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
730 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
731 use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend)
732 print "Provision OK for domain DN %s" % presult.domaindn
733 ctx.local_samdb = presult.samdb
734 ctx.lp = presult.lp
735 ctx.paths = presult.paths
736 ctx.names = presult.names
738 def join_provision_own_domain(ctx):
739 """Provision the local SAM."""
741 # we now operate exclusively on the local database, which
742 # we need to reopen in order to get the newly created schema
743 print("Reconnecting to local samdb")
744 ctx.samdb = SamDB(url=ctx.local_samdb.url,
745 session_info=system_session(),
746 lp=ctx.local_samdb.lp,
747 global_schema=False)
748 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
749 ctx.local_samdb = ctx.samdb
751 ctx.logger.info("Finding domain GUID from ncName")
752 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
753 controls=["extended_dn:1:1", "reveal_internals:0"])
755 if 'nCName' not in res[0]:
756 raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
758 try:
759 domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
760 except KeyError:
761 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['ncName'][0])
763 ctx.logger.info("Got domain GUID %s" % domguid)
765 ctx.logger.info("Calling own domain provision")
767 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
769 presult = provision_fill(ctx.local_samdb, secrets_ldb,
770 ctx.logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
771 domainguid=domguid,
772 dom_for_fun_level=DS_DOMAIN_FUNCTION_2003,
773 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
774 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
775 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
776 dns_backend=ctx.dns_backend, adminpass=ctx.adminpass)
777 print("Provision OK for domain %s" % ctx.names.dnsdomain)
779 def join_replicate(ctx):
780 """Replicate the SAM."""
782 print "Starting replication"
783 ctx.local_samdb.transaction_start()
784 try:
785 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
786 if ctx.ntds_guid is None:
787 print("Using DS_BIND_GUID_W2K3")
788 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
789 else:
790 destination_dsa_guid = ctx.ntds_guid
792 if ctx.RODC:
793 repl_creds = Credentials()
794 repl_creds.guess(ctx.lp)
795 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
796 repl_creds.set_username(ctx.samname)
797 repl_creds.set_password(ctx.acct_pass)
798 else:
799 repl_creds = ctx.creds
801 binding_options = "seal"
802 if int(ctx.lp.get("log level")) >= 5:
803 binding_options += ",print"
804 repl = drs_utils.drs_Replicate(
805 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
806 ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id)
808 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
809 destination_dsa_guid, schema=True, rodc=ctx.RODC,
810 replica_flags=ctx.replica_flags)
811 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
812 destination_dsa_guid, rodc=ctx.RODC,
813 replica_flags=ctx.replica_flags)
814 if not ctx.subdomain:
815 # Replicate first the critical object for the basedn
816 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
817 print "Replicating critical objects from the base DN of the domain"
818 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
819 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
820 destination_dsa_guid, rodc=ctx.RODC,
821 replica_flags=ctx.domain_replica_flags)
822 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
823 else:
824 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
825 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
826 destination_dsa_guid, rodc=ctx.RODC,
827 replica_flags=ctx.domain_replica_flags)
828 print "Done with always replicated NC (base, config, schema)"
830 for nc in (ctx.domaindns_zone, ctx.forestdns_zone):
831 if nc in ctx.nc_list:
832 print "Replicating %s" % (str(nc))
833 repl.replicate(nc, source_dsa_invocation_id,
834 destination_dsa_guid, rodc=ctx.RODC,
835 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
841 if ctx.RODC:
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)
848 ctx.repl = repl
849 ctx.source_dsa_invocation_id = source_dsa_invocation_id
850 ctx.destination_dsa_guid = destination_dsa_guid
852 print "Committing SAM database"
853 except:
854 ctx.local_samdb.transaction_cancel()
855 raise
856 else:
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
868 if not ctx.RODC:
869 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
871 if ctx.drsuapi:
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
881 # requesting DC
882 ctx.logger.info("Sending DsReplicaUpdateRefs for all the replicated partitions")
883 for nc in ctx.nc_list:
884 ctx.send_DsReplicaUpdateRefs(nc)
886 if ctx.RODC:
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)
891 m = ldb.Message()
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,
895 "invocationId")
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,
909 "invocationId",
912 ctx.logger.info("Setting isSynchronized and dsServiceName")
913 m = ldb.Message()
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)
920 if ctx.subdomain:
921 return
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,
927 realm=ctx.realm,
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
948 c = ARC4.new(key)
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])
957 return blob
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),
962 ctx.lp, ctx.creds)
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
978 try:
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)
985 except RuntimeError:
986 pass
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()
1004 outgoing.count = 1
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,
1030 info,
1031 auth_info,
1032 security.SEC_STD_DELETE)
1034 rec = {
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)
1047 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)
1056 def do_join(ctx):
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 ]
1061 if not ctx.subdomain:
1062 ctx.nc_list += [ctx.base_dn]
1063 if ctx.dns_backend != "NONE":
1064 ctx.nc_list += [ctx.domaindns_zone]
1066 if ctx.dns_backend != "NONE":
1067 ctx.nc_list += [ctx.forestdns_zone]
1069 if ctx.promote_existing:
1070 ctx.promote_possible()
1071 else:
1072 ctx.cleanup_old_join()
1074 try:
1075 ctx.join_add_objects()
1076 ctx.join_provision()
1077 ctx.join_replicate()
1078 if ctx.subdomain:
1079 ctx.join_add_objects2()
1080 ctx.join_provision_own_domain()
1081 ctx.join_setup_trusts()
1082 ctx.join_finalise()
1083 except:
1084 print "Join failed - cleaning up"
1085 ctx.cleanup_old_join()
1086 raise
1089 def join_RODC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1090 targetdir=None, domain=None, domain_critical_only=False,
1091 machinepass=None, use_ntvfs=False, dns_backend=None,
1092 promote_existing=False):
1093 """Join as a RODC."""
1095 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1096 machinepass, use_ntvfs, dns_backend, promote_existing)
1098 lp.set("workgroup", ctx.domain_name)
1099 logger.info("workgroup is %s" % ctx.domain_name)
1101 lp.set("realm", ctx.realm)
1102 logger.info("realm is %s" % ctx.realm)
1104 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
1106 # setup some defaults for accounts that should be replicated to this RODC
1107 ctx.never_reveal_sid = [
1108 "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
1109 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
1110 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
1111 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
1112 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS]
1113 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
1115 mysid = ctx.get_mysid()
1116 admin_dn = "<SID=%s>" % mysid
1117 ctx.managedby = admin_dn
1119 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
1120 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1121 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
1123 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
1124 "RestrictedKrbHost/%s" % ctx.dnshostname ])
1126 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
1127 ctx.secure_channel_type = misc.SEC_CHAN_RODC
1128 ctx.RODC = True
1129 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
1130 drsuapi.DRSUAPI_DRS_PER_SYNC |
1131 drsuapi.DRSUAPI_DRS_GET_ANC |
1132 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
1133 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1134 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
1135 ctx.domain_replica_flags = ctx.replica_flags
1136 if domain_critical_only:
1137 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1139 ctx.do_join()
1141 logger.info("Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid))
1144 def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1145 targetdir=None, domain=None, domain_critical_only=False,
1146 machinepass=None, use_ntvfs=False, dns_backend=None,
1147 promote_existing=False):
1148 """Join as a DC."""
1149 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1150 machinepass, use_ntvfs, dns_backend, promote_existing)
1152 lp.set("workgroup", ctx.domain_name)
1153 logger.info("workgroup is %s" % ctx.domain_name)
1155 lp.set("realm", ctx.realm)
1156 logger.info("realm is %s" % ctx.realm)
1158 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1160 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1161 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1163 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1164 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1165 drsuapi.DRSUAPI_DRS_PER_SYNC |
1166 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1167 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1168 ctx.domain_replica_flags = ctx.replica_flags
1169 if domain_critical_only:
1170 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1172 ctx.do_join()
1173 logger.info("Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
1175 def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None,
1176 netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
1177 netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False,
1178 dns_backend=None):
1179 """Join as a DC."""
1180 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, parent_domain,
1181 machinepass, use_ntvfs, dns_backend)
1182 ctx.subdomain = True
1183 if adminpass is None:
1184 ctx.adminpass = samba.generate_random_password(12, 32)
1185 else:
1186 ctx.adminpass = adminpass
1187 ctx.parent_domain_name = ctx.domain_name
1188 ctx.domain_name = netbios_domain
1189 ctx.realm = dnsdomain
1190 ctx.parent_dnsdomain = ctx.dnsdomain
1191 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1192 ctx.dnsdomain = dnsdomain
1193 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1194 ctx.naming_master = ctx.get_naming_master()
1195 if ctx.naming_master != ctx.server:
1196 logger.info("Reconnecting to naming master %s" % ctx.naming_master)
1197 ctx.server = ctx.naming_master
1198 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1199 session_info=system_session(),
1200 credentials=ctx.creds, lp=ctx.lp)
1201 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=['dnsHostName'],
1202 controls=[])
1203 ctx.server = res[0]["dnsHostName"]
1204 logger.info("DNS name of new naming master is %s" % ctx.server)
1206 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1207 ctx.domsid = str(security.random_sid())
1208 ctx.acct_dn = None
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
1224 ctx.do_join()
1225 ctx.logger.info("Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))