s3: smbd: have_file_open_below() fails to enumerate open files below an open director...
[Samba.git] / python / samba / join.py
blobcdfe45207cf811353e5f71ce1dcfd24017827e8b
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 import descriptor
33 from samba.net import Net
34 from samba.provision.sambadns import setup_bind9_dns
35 from samba import read_and_sub_file
36 from base64 import b64encode
37 import logging
38 import talloc
39 import random
40 import time
42 # this makes debugging easier
43 talloc.enable_null_tracking()
45 class DCJoinException(Exception):
47 def __init__(self, msg):
48 super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
51 class dc_join(object):
52 """Perform a DC join."""
54 def __init__(ctx, logger=None, server=None, creds=None, lp=None, site=None,
55 netbios_name=None, targetdir=None, domain=None,
56 machinepass=None, use_ntvfs=False, dns_backend=None,
57 promote_existing=False, clone_only=False):
58 ctx.clone_only=clone_only
60 ctx.logger = logger
61 ctx.creds = creds
62 ctx.lp = lp
63 ctx.site = site
64 ctx.targetdir = targetdir
65 ctx.use_ntvfs = use_ntvfs
67 ctx.promote_existing = promote_existing
68 ctx.promote_from_dn = None
70 ctx.nc_list = []
71 ctx.full_nc_list = []
73 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
74 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
76 if server is not None:
77 ctx.server = server
78 else:
79 ctx.logger.info("Finding a writeable DC for domain '%s'" % domain)
80 ctx.server = ctx.find_dc(domain)
81 ctx.logger.info("Found DC %s" % ctx.server)
83 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
84 session_info=system_session(),
85 credentials=ctx.creds, lp=ctx.lp)
87 try:
88 ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
89 except ldb.LdbError, (enum, estr):
90 raise DCJoinException(estr)
93 ctx.base_dn = str(ctx.samdb.get_default_basedn())
94 ctx.root_dn = str(ctx.samdb.get_root_basedn())
95 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
96 ctx.config_dn = str(ctx.samdb.get_config_basedn())
97 ctx.domsid = security.dom_sid(ctx.samdb.get_domain_sid())
98 ctx.forestsid = ctx.domsid
99 ctx.domain_name = ctx.get_domain_name()
100 ctx.forest_domain_name = ctx.get_forest_domain_name()
101 ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
103 ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName()
104 ctx.dc_dnsHostName = ctx.get_dnsHostName()
105 ctx.behavior_version = ctx.get_behavior_version()
107 if machinepass is not None:
108 ctx.acct_pass = machinepass
109 else:
110 ctx.acct_pass = samba.generate_random_password(32, 40)
112 ctx.dnsdomain = ctx.samdb.domain_dns_name()
113 if clone_only:
114 # As we don't want to create or delete these DNs, we set them to None
115 ctx.server_dn = None
116 ctx.ntds_dn = None
117 ctx.acct_dn = None
118 ctx.myname = ctx.server.split('.')[0]
119 ctx.ntds_guid = None
120 else:
121 # work out the DNs of all the objects we will be adding
122 ctx.myname = netbios_name
123 ctx.samname = "%s$" % ctx.myname
124 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
125 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
126 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
127 ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
128 ctx.dnsforest = ctx.samdb.forest_dns_name()
130 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
131 if ctx.dn_exists(topology_base):
132 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
133 else:
134 ctx.topology_dn = None
136 ctx.SPNs = [ "HOST/%s" % ctx.myname,
137 "HOST/%s" % ctx.dnshostname,
138 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
140 ctx.domaindns_zone = 'DC=DomainDnsZones,%s' % ctx.base_dn
141 ctx.forestdns_zone = 'DC=ForestDnsZones,%s' % ctx.root_dn
143 res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
144 attrs=[],
145 base=ctx.samdb.get_partitions_dn(),
146 expression="(&(objectClass=crossRef)(ncName=%s))" % ctx.domaindns_zone)
147 if dns_backend is None:
148 ctx.dns_backend = "NONE"
149 else:
150 if len(res_domaindns) == 0:
151 ctx.dns_backend = "NONE"
152 print "NO DNS zone information found in source domain, not replicating DNS"
153 else:
154 ctx.dns_backend = dns_backend
156 ctx.realm = ctx.dnsdomain
158 ctx.tmp_samdb = None
160 # these elements are optional
161 ctx.never_reveal_sid = None
162 ctx.reveal_sid = None
163 ctx.connection_dn = None
164 ctx.RODC = False
165 ctx.krbtgt_dn = None
166 ctx.drsuapi = None
167 ctx.managedby = None
168 ctx.subdomain = False
169 ctx.adminpass = None
171 def del_noerror(ctx, dn, recursive=False):
172 if recursive:
173 try:
174 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
175 except Exception:
176 return
177 for r in res:
178 ctx.del_noerror(r.dn, recursive=True)
179 try:
180 ctx.samdb.delete(dn)
181 print "Deleted %s" % dn
182 except Exception:
183 pass
185 def cleanup_old_join(ctx):
186 """Remove any DNs from a previous join."""
187 try:
188 # find the krbtgt link
189 print("checking sAMAccountName")
190 if ctx.subdomain:
191 res = None
192 else:
193 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
194 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
195 attrs=["msDS-krbTgtLink"])
196 if res:
197 ctx.del_noerror(res[0].dn, recursive=True)
199 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
200 expression='(&(sAMAccountName=%s)(servicePrincipalName=%s))' % (ldb.binary_encode("dns-%s" % ctx.myname), ldb.binary_encode("dns/%s" % ctx.dnshostname)),
201 attrs=[])
202 if res:
203 ctx.del_noerror(res[0].dn, recursive=True)
205 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
206 expression='(sAMAccountName=%s)' % ldb.binary_encode("dns-%s" % ctx.myname),
207 attrs=[])
208 if res:
209 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)))
211 if ctx.connection_dn is not None:
212 ctx.del_noerror(ctx.connection_dn)
213 if ctx.krbtgt_dn is not None:
214 ctx.del_noerror(ctx.krbtgt_dn)
215 ctx.del_noerror(ctx.ntds_dn)
216 ctx.del_noerror(ctx.server_dn, recursive=True)
217 if ctx.topology_dn:
218 ctx.del_noerror(ctx.topology_dn)
219 if ctx.partition_dn:
220 ctx.del_noerror(ctx.partition_dn)
221 if res:
222 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
223 ctx.del_noerror(ctx.new_krbtgt_dn)
225 if ctx.subdomain:
226 binding_options = "sign"
227 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
228 ctx.lp, ctx.creds)
230 objectAttr = lsa.ObjectAttribute()
231 objectAttr.sec_qos = lsa.QosInfo()
233 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
234 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
236 name = lsa.String()
237 name.string = ctx.realm
238 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
240 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
242 name = lsa.String()
243 name.string = ctx.forest_domain_name
244 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
246 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
248 except Exception:
249 pass
251 def promote_possible(ctx):
252 """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
253 if ctx.subdomain:
254 # This shouldn't happen
255 raise Exception("Can not promote into a subdomain")
257 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
258 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
259 attrs=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
260 if len(res) == 0:
261 raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname)
262 if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]:
263 raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname)
264 if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0):
265 raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname)
267 ctx.promote_from_dn = res[0].dn
270 def find_dc(ctx, domain):
271 """find a writeable DC for the given domain"""
272 try:
273 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
274 except Exception:
275 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
276 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
277 ctx.site = ctx.cldap_ret.client_site
278 return ctx.cldap_ret.pdc_dns_name
281 def get_behavior_version(ctx):
282 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
283 if "msDS-Behavior-Version" in res[0]:
284 return int(res[0]["msDS-Behavior-Version"][0])
285 else:
286 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
288 def get_dnsHostName(ctx):
289 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
290 return res[0]["dnsHostName"][0]
292 def get_domain_name(ctx):
293 '''get netbios name of the domain from the partitions record'''
294 partitions_dn = ctx.samdb.get_partitions_dn()
295 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
296 expression='ncName=%s' % ctx.samdb.get_default_basedn())
297 return res[0]["nETBIOSName"][0]
299 def get_forest_domain_name(ctx):
300 '''get netbios name of the domain from the partitions record'''
301 partitions_dn = ctx.samdb.get_partitions_dn()
302 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
303 expression='ncName=%s' % ctx.samdb.get_root_basedn())
304 return res[0]["nETBIOSName"][0]
306 def get_parent_partition_dn(ctx):
307 '''get the parent domain partition DN from parent DNS name'''
308 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
309 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
310 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
311 return str(res[0].dn)
313 def get_naming_master(ctx):
314 '''get the parent domain partition DN from parent DNS name'''
315 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
316 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
317 if not 'fSMORoleOwner' in res[0]:
318 raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
319 try:
320 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
321 except KeyError:
322 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0])
324 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
325 return master_host
327 def get_mysid(ctx):
328 '''get the SID of the connected user. Only works with w2k8 and later,
329 so only used for RODC join'''
330 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
331 binsid = res[0]["tokenGroups"][0]
332 return ctx.samdb.schema_format_value("objectSID", binsid)
334 def dn_exists(ctx, dn):
335 '''check if a DN exists'''
336 try:
337 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
338 except ldb.LdbError, (enum, estr):
339 if enum == ldb.ERR_NO_SUCH_OBJECT:
340 return False
341 raise
342 return True
344 def add_krbtgt_account(ctx):
345 '''RODCs need a special krbtgt account'''
346 print "Adding %s" % ctx.krbtgt_dn
347 rec = {
348 "dn" : ctx.krbtgt_dn,
349 "objectclass" : "user",
350 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
351 samba.dsdb.UF_ACCOUNTDISABLE),
352 "showinadvancedviewonly" : "TRUE",
353 "description" : "krbtgt for %s" % ctx.samname}
354 ctx.samdb.add(rec, ["rodc_join:1:1"])
356 # now we need to search for the samAccountName attribute on the krbtgt DN,
357 # as this will have been magically set to the krbtgt number
358 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
359 ctx.krbtgt_name = res[0]["samAccountName"][0]
361 print "Got krbtgt_name=%s" % ctx.krbtgt_name
363 m = ldb.Message()
364 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
365 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
366 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
367 ctx.samdb.modify(m)
369 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
370 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
371 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
373 def drsuapi_connect(ctx):
374 '''make a DRSUAPI connection to the naming master'''
375 binding_options = "seal"
376 if int(ctx.lp.get("log level")) >= 4:
377 binding_options += ",print"
378 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
379 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
380 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
382 def create_tmp_samdb(ctx):
383 '''create a temporary samdb object for schema queries'''
384 ctx.tmp_schema = Schema(ctx.domsid,
385 schemadn=ctx.schema_dn)
386 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
387 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
388 am_rodc=False)
389 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
391 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
392 '''build a DsReplicaAttributeCtr object'''
393 r = drsuapi.DsReplicaAttribute()
394 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
395 r.value_ctr = 1
398 def DsAddEntry(ctx, recs):
399 '''add a record via the DRSUAPI DsAddEntry call'''
400 if ctx.drsuapi is None:
401 ctx.drsuapi_connect()
402 if ctx.tmp_samdb is None:
403 ctx.create_tmp_samdb()
405 objects = []
406 for rec in recs:
407 id = drsuapi.DsReplicaObjectIdentifier()
408 id.dn = rec['dn']
410 attrs = []
411 for a in rec:
412 if a == 'dn':
413 continue
414 if not isinstance(rec[a], list):
415 v = [rec[a]]
416 else:
417 v = rec[a]
418 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
419 attrs.append(rattr)
421 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
422 attribute_ctr.num_attributes = len(attrs)
423 attribute_ctr.attributes = attrs
425 object = drsuapi.DsReplicaObject()
426 object.identifier = id
427 object.attribute_ctr = attribute_ctr
429 list_object = drsuapi.DsReplicaObjectListItem()
430 list_object.object = object
431 objects.append(list_object)
433 req2 = drsuapi.DsAddEntryRequest2()
434 req2.first_object = objects[0]
435 prev = req2.first_object
436 for o in objects[1:]:
437 prev.next_object = o
438 prev = o
440 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
441 if level == 2:
442 if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
443 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
444 raise RuntimeError("DsAddEntry failed")
445 if ctr.extended_err != (0, 'WERR_OK'):
446 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
447 raise RuntimeError("DsAddEntry failed")
448 if level == 3:
449 if ctr.err_ver != 1:
450 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
451 if ctr.err_data.status != (0, 'WERR_OK'):
452 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
453 ctr.err_data.info.extended_err))
454 raise RuntimeError("DsAddEntry failed")
455 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
456 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
457 raise RuntimeError("DsAddEntry failed")
459 return ctr.objects
461 def join_ntdsdsa_obj(ctx):
462 '''return the ntdsdsa object to add'''
464 print "Adding %s" % ctx.ntds_dn
465 rec = {
466 "dn" : ctx.ntds_dn,
467 "objectclass" : "nTDSDSA",
468 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
469 "dMDLocation" : ctx.schema_dn}
471 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
473 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
474 rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
476 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
477 rec["msDS-HasDomainNCs"] = ctx.base_dn
479 if ctx.RODC:
480 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
481 rec["msDS-HasFullReplicaNCs"] = ctx.full_nc_list
482 rec["options"] = "37"
483 else:
484 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
485 rec["HasMasterNCs"] = []
486 for nc in nc_list:
487 if nc in ctx.full_nc_list:
488 rec["HasMasterNCs"].append(nc)
489 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
490 rec["msDS-HasMasterNCs"] = ctx.full_nc_list
491 rec["options"] = "1"
492 rec["invocationId"] = ndr_pack(ctx.invocation_id)
494 return rec
496 def join_add_ntdsdsa(ctx):
497 '''add the ntdsdsa object'''
499 rec = ctx.join_ntdsdsa_obj()
500 if ctx.RODC:
501 ctx.samdb.add(rec, ["rodc_join:1:1"])
502 else:
503 ctx.DsAddEntry([rec])
505 # find the GUID of our NTDS DN
506 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
507 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
509 def join_add_objects(ctx):
510 '''add the various objects needed for the join'''
511 if ctx.acct_dn:
512 print "Adding %s" % ctx.acct_dn
513 rec = {
514 "dn" : ctx.acct_dn,
515 "objectClass": "computer",
516 "displayname": ctx.samname,
517 "samaccountname" : ctx.samname,
518 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
519 "dnshostname" : ctx.dnshostname}
520 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
521 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
522 elif ctx.promote_existing:
523 rec['msDS-SupportedEncryptionTypes'] = []
524 if ctx.managedby:
525 rec["managedby"] = ctx.managedby
526 elif ctx.promote_existing:
527 rec["managedby"] = []
529 if ctx.never_reveal_sid:
530 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
531 elif ctx.promote_existing:
532 rec["msDS-NeverRevealGroup"] = []
534 if ctx.reveal_sid:
535 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
536 elif ctx.promote_existing:
537 rec["msDS-RevealOnDemandGroup"] = []
539 if ctx.promote_existing:
540 if ctx.promote_from_dn != ctx.acct_dn:
541 ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn)
542 ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE))
543 else:
544 ctx.samdb.add(rec)
546 if ctx.krbtgt_dn:
547 ctx.add_krbtgt_account()
549 if ctx.server_dn:
550 print "Adding %s" % ctx.server_dn
551 rec = {
552 "dn": ctx.server_dn,
553 "objectclass" : "server",
554 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
555 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
556 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
557 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
558 # windows seems to add the dnsHostName later
559 "dnsHostName" : ctx.dnshostname}
561 if ctx.acct_dn:
562 rec["serverReference"] = ctx.acct_dn
564 ctx.samdb.add(rec)
566 if ctx.subdomain:
567 # the rest is done after replication
568 ctx.ntds_guid = None
569 return
571 if ctx.ntds_dn:
572 ctx.join_add_ntdsdsa()
574 if ctx.connection_dn is not None:
575 print "Adding %s" % ctx.connection_dn
576 rec = {
577 "dn" : ctx.connection_dn,
578 "objectclass" : "nTDSConnection",
579 "enabledconnection" : "TRUE",
580 "options" : "65",
581 "fromServer" : ctx.dc_ntds_dn}
582 ctx.samdb.add(rec)
584 if ctx.acct_dn:
585 print "Adding SPNs to %s" % ctx.acct_dn
586 m = ldb.Message()
587 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
588 for i in range(len(ctx.SPNs)):
589 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
590 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
591 ldb.FLAG_MOD_REPLACE,
592 "servicePrincipalName")
593 ctx.samdb.modify(m)
595 # The account password set operation should normally be done over
596 # LDAP. Windows 2000 DCs however allow this only with SSL
597 # connections which are hard to set up and otherwise refuse with
598 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
599 # over SAMR.
600 print "Setting account password for %s" % ctx.samname
601 try:
602 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
603 % ldb.binary_encode(ctx.samname),
604 ctx.acct_pass,
605 force_change_at_next_login=False,
606 username=ctx.samname)
607 except ldb.LdbError, (num, _):
608 if num != ldb.ERR_UNWILLING_TO_PERFORM:
609 pass
610 ctx.net.set_password(account_name=ctx.samname,
611 domain_name=ctx.domain_name,
612 newpassword=ctx.acct_pass)
614 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
615 attrs=["msDS-KeyVersionNumber"])
616 if "msDS-KeyVersionNumber" in res[0]:
617 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
618 else:
619 ctx.key_version_number = None
621 print("Enabling account")
622 m = ldb.Message()
623 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
624 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
625 ldb.FLAG_MOD_REPLACE,
626 "userAccountControl")
627 ctx.samdb.modify(m)
629 if ctx.dns_backend.startswith("BIND9_"):
630 ctx.dnspass = samba.generate_random_password(128, 255)
632 recs = ctx.samdb.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"),
633 {"DNSDOMAIN": ctx.dnsdomain,
634 "DOMAINDN": ctx.base_dn,
635 "HOSTNAME" : ctx.myname,
636 "DNSPASS_B64": b64encode(ctx.dnspass),
637 "DNSNAME" : ctx.dnshostname}))
638 for changetype, msg in recs:
639 assert changetype == ldb.CHANGETYPE_NONE
640 dns_acct_dn = msg["dn"]
641 print "Adding DNS account %s with dns/ SPN" % msg["dn"]
643 # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP)
644 del msg["clearTextPassword"]
645 # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP
646 del msg["isCriticalSystemObject"]
647 # Disable account until password is set
648 msg["userAccountControl"] = str(samba.dsdb.UF_NORMAL_ACCOUNT |
649 samba.dsdb.UF_ACCOUNTDISABLE)
650 try:
651 ctx.samdb.add(msg)
652 except ldb.LdbError, (num, _):
653 if num != ldb.ERR_ENTRY_ALREADY_EXISTS:
654 raise
656 # The account password set operation should normally be done over
657 # LDAP. Windows 2000 DCs however allow this only with SSL
658 # connections which are hard to set up and otherwise refuse with
659 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
660 # over SAMR.
661 print "Setting account password for dns-%s" % ctx.myname
662 try:
663 ctx.samdb.setpassword("(&(objectClass=user)(samAccountName=dns-%s))"
664 % ldb.binary_encode(ctx.myname),
665 ctx.dnspass,
666 force_change_at_next_login=False,
667 username=ctx.samname)
668 except ldb.LdbError, (num, _):
669 if num != ldb.ERR_UNWILLING_TO_PERFORM:
670 raise
671 ctx.net.set_password(account_name="dns-%s" % ctx.myname,
672 domain_name=ctx.domain_name,
673 newpassword=ctx.dnspass)
675 res = ctx.samdb.search(base=dns_acct_dn, scope=ldb.SCOPE_BASE,
676 attrs=["msDS-KeyVersionNumber"])
677 if "msDS-KeyVersionNumber" in res[0]:
678 ctx.dns_key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
679 else:
680 ctx.dns_key_version_number = None
682 def join_add_objects2(ctx):
683 """add the various objects needed for the join, for subdomains post replication"""
685 print "Adding %s" % ctx.partition_dn
686 name_map = {'SubdomainAdmins': "%s-%s" % (str(ctx.domsid), security.DOMAIN_RID_ADMINS)}
687 sd_binary = descriptor.get_paritions_crossref_subdomain_descriptor(ctx.forestsid, name_map=name_map)
688 rec = {
689 "dn" : ctx.partition_dn,
690 "objectclass" : "crossRef",
691 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
692 "nCName" : ctx.base_dn,
693 "nETBIOSName" : ctx.domain_name,
694 "dnsRoot": ctx.dnsdomain,
695 "trustParent" : ctx.parent_partition_dn,
696 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN),
697 "ntSecurityDescriptor" : sd_binary,
700 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
701 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
703 rec2 = ctx.join_ntdsdsa_obj()
705 objects = ctx.DsAddEntry([rec, rec2])
706 if len(objects) != 2:
707 raise DCJoinException("Expected 2 objects from DsAddEntry")
709 ctx.ntds_guid = objects[1].guid
711 print("Replicating partition DN")
712 ctx.repl.replicate(ctx.partition_dn,
713 misc.GUID("00000000-0000-0000-0000-000000000000"),
714 ctx.ntds_guid,
715 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
716 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
718 print("Replicating NTDS DN")
719 ctx.repl.replicate(ctx.ntds_dn,
720 misc.GUID("00000000-0000-0000-0000-000000000000"),
721 ctx.ntds_guid,
722 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
723 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
725 def join_provision(ctx):
726 """Provision the local SAM."""
728 print "Calling bare provision"
730 smbconf = ctx.lp.configfile
732 presult = provision(ctx.logger, system_session(), smbconf=smbconf,
733 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
734 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
735 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
736 serverdn=ctx.server_dn, domain=ctx.domain_name,
737 hostname=ctx.myname, domainsid=ctx.domsid,
738 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
739 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
740 use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend)
741 print "Provision OK for domain DN %s" % presult.domaindn
742 ctx.local_samdb = presult.samdb
743 ctx.lp = presult.lp
744 ctx.paths = presult.paths
745 ctx.names = presult.names
747 # Fix up the forestsid, it may be different if we are joining as a subdomain
748 ctx.names.forestsid = ctx.forestsid
750 def join_provision_own_domain(ctx):
751 """Provision the local SAM."""
753 # we now operate exclusively on the local database, which
754 # we need to reopen in order to get the newly created schema
755 print("Reconnecting to local samdb")
756 ctx.samdb = SamDB(url=ctx.local_samdb.url,
757 session_info=system_session(),
758 lp=ctx.local_samdb.lp,
759 global_schema=False)
760 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
761 ctx.local_samdb = ctx.samdb
763 ctx.logger.info("Finding domain GUID from ncName")
764 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
765 controls=["extended_dn:1:1", "reveal_internals:0"])
767 if 'nCName' not in res[0]:
768 raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx.partition_dn, ctx.samdb.url))
770 try:
771 ctx.names.domainguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
772 except KeyError:
773 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res[0]['ncName'][0])
775 ctx.logger.info("Got domain GUID %s" % ctx.names.domainguid)
777 ctx.logger.info("Calling own domain provision")
779 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
781 presult = provision_fill(ctx.local_samdb, secrets_ldb,
782 ctx.logger, ctx.names, ctx.paths,
783 dom_for_fun_level=DS_DOMAIN_FUNCTION_2003,
784 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
785 machinepass=ctx.acct_pass, serverrole="active directory domain controller",
786 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
787 dns_backend=ctx.dns_backend, adminpass=ctx.adminpass)
788 print("Provision OK for domain %s" % ctx.names.dnsdomain)
790 def join_replicate(ctx):
791 """Replicate the SAM."""
793 print "Starting replication"
794 ctx.local_samdb.transaction_start()
795 try:
796 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
797 if ctx.ntds_guid is None:
798 print("Using DS_BIND_GUID_W2K3")
799 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
800 else:
801 destination_dsa_guid = ctx.ntds_guid
803 if ctx.RODC:
804 repl_creds = Credentials()
805 repl_creds.guess(ctx.lp)
806 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
807 repl_creds.set_username(ctx.samname)
808 repl_creds.set_password(ctx.acct_pass)
809 else:
810 repl_creds = ctx.creds
812 binding_options = "seal"
813 if int(ctx.lp.get("log level")) >= 5:
814 binding_options += ",print"
815 repl = drs_utils.drs_Replicate(
816 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
817 ctx.lp, repl_creds, ctx.local_samdb, ctx.invocation_id)
819 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
820 destination_dsa_guid, schema=True, rodc=ctx.RODC,
821 replica_flags=ctx.replica_flags)
822 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
823 destination_dsa_guid, rodc=ctx.RODC,
824 replica_flags=ctx.replica_flags)
825 if not ctx.subdomain:
826 # Replicate first the critical object for the basedn
827 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
828 print "Replicating critical objects from the base DN of the domain"
829 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
830 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
831 destination_dsa_guid, rodc=ctx.RODC,
832 replica_flags=ctx.domain_replica_flags)
833 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
834 else:
835 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
836 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
837 destination_dsa_guid, rodc=ctx.RODC,
838 replica_flags=ctx.domain_replica_flags)
839 print "Done with always replicated NC (base, config, schema)"
841 for nc in (ctx.domaindns_zone, ctx.forestdns_zone):
842 if nc in ctx.nc_list:
843 print "Replicating %s" % (str(nc))
844 repl.replicate(nc, source_dsa_invocation_id,
845 destination_dsa_guid, rodc=ctx.RODC,
846 replica_flags=ctx.replica_flags)
848 # FIXME At this point we should add an entry in the forestdns and domaindns NC
849 # (those under CN=Partions,DC=...)
850 # in order to indicate that we hold a replica for this NC
852 if ctx.RODC:
853 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
854 destination_dsa_guid,
855 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
856 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
857 destination_dsa_guid,
858 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
859 ctx.repl = repl
860 ctx.source_dsa_invocation_id = source_dsa_invocation_id
861 ctx.destination_dsa_guid = destination_dsa_guid
863 print "Committing SAM database"
864 except:
865 ctx.local_samdb.transaction_cancel()
866 raise
867 else:
868 ctx.local_samdb.transaction_commit()
870 def send_DsReplicaUpdateRefs(ctx, dn):
871 r = drsuapi.DsReplicaUpdateRefsRequest1()
872 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
873 r.naming_context.dn = str(dn)
874 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
875 r.naming_context.sid = security.dom_sid("S-0-0")
876 r.dest_dsa_guid = ctx.ntds_guid
877 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
878 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
879 if not ctx.RODC:
880 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
882 if ctx.drsuapi:
883 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
885 def join_finalise(ctx):
886 """Finalise the join, mark us synchronised and setup secrets db."""
888 # FIXME we shouldn't do this in all cases
890 # If for some reasons we joined in another site than the one of
891 # DC we just replicated from then we don't need to send the updatereplicateref
892 # as replication between sites is time based and on the initiative of the
893 # requesting DC
894 if not ctx.clone_only:
895 ctx.logger.info("Sending DsReplicaUpdateRefs for all the replicated partitions")
896 for nc in ctx.nc_list:
897 ctx.send_DsReplicaUpdateRefs(nc)
899 if not ctx.clone_only and ctx.RODC:
900 print "Setting RODC invocationId"
901 ctx.local_samdb.set_invocation_id(str(ctx.invocation_id))
902 ctx.local_samdb.set_opaque_integer("domainFunctionality",
903 ctx.behavior_version)
904 m = ldb.Message()
905 m.dn = ldb.Dn(ctx.local_samdb, "%s" % ctx.ntds_dn)
906 m["invocationId"] = ldb.MessageElement(ndr_pack(ctx.invocation_id),
907 ldb.FLAG_MOD_REPLACE,
908 "invocationId")
909 ctx.local_samdb.modify(m)
911 # Note: as RODC the invocationId is only stored
912 # on the RODC itself, the other DCs never see it.
914 # Thats is why we fix up the replPropertyMetaData stamp
915 # for the 'invocationId' attribute, we need to change
916 # the 'version' to '0', this is what windows 2008r2 does as RODC
918 # This means if the object on a RWDC ever gets a invocationId
919 # attribute, it will have version '1' (or higher), which will
920 # will overwrite the RODC local value.
921 ctx.local_samdb.set_attribute_replmetadata_version(m.dn,
922 "invocationId",
925 ctx.logger.info("Setting isSynchronized and dsServiceName")
926 m = ldb.Message()
927 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
928 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
930 # We want to appear to be the server we just cloned
931 if ctx.clone_only:
932 guid = ctx.samdb.get_ntds_GUID()
933 else:
934 guid = ctx.ntds_guid
936 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(guid),
937 ldb.FLAG_MOD_REPLACE, "dsServiceName")
938 ctx.local_samdb.modify(m)
940 if ctx.clone_only or ctx.subdomain:
941 return
943 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
945 ctx.logger.info("Setting up secrets database")
946 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
947 realm=ctx.realm,
948 dnsdomain=ctx.dnsdomain,
949 netbiosname=ctx.myname,
950 domainsid=ctx.domsid,
951 machinepass=ctx.acct_pass,
952 secure_channel_type=ctx.secure_channel_type,
953 key_version_number=ctx.key_version_number)
955 if ctx.dns_backend.startswith("BIND9_"):
956 setup_bind9_dns(ctx.local_samdb, secrets_ldb,
957 ctx.names, ctx.paths, ctx.lp, ctx.logger,
958 dns_backend=ctx.dns_backend,
959 dnspass=ctx.dnspass, os_level=ctx.behavior_version,
960 targetdir=ctx.targetdir,
961 key_version_number=ctx.dns_key_version_number)
963 def join_setup_trusts(ctx):
964 """provision the local SAM."""
966 def arcfour_encrypt(key, data):
967 from Crypto.Cipher import ARC4
968 c = ARC4.new(key)
969 return c.encrypt(data)
971 def string_to_array(string):
972 blob = [0] * len(string)
974 for i in range(len(string)):
975 blob[i] = ord(string[i])
977 return blob
979 print "Setup domain trusts with server %s" % ctx.server
980 binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key
981 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
982 ctx.lp, ctx.creds)
984 objectAttr = lsa.ObjectAttribute()
985 objectAttr.sec_qos = lsa.QosInfo()
987 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
988 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
990 info = lsa.TrustDomainInfoInfoEx()
991 info.domain_name.string = ctx.dnsdomain
992 info.netbios_name.string = ctx.domain_name
993 info.sid = ctx.domsid
994 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
995 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
996 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
998 try:
999 oldname = lsa.String()
1000 oldname.string = ctx.dnsdomain
1001 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
1002 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
1003 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
1004 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
1005 except RuntimeError:
1006 pass
1008 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
1010 clear_value = drsblobs.AuthInfoClear()
1011 clear_value.size = len(password_blob)
1012 clear_value.password = password_blob
1014 clear_authentication_information = drsblobs.AuthenticationInformation()
1015 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
1016 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
1017 clear_authentication_information.AuthInfo = clear_value
1019 authentication_information_array = drsblobs.AuthenticationInformationArray()
1020 authentication_information_array.count = 1
1021 authentication_information_array.array = [clear_authentication_information]
1023 outgoing = drsblobs.trustAuthInOutBlob()
1024 outgoing.count = 1
1025 outgoing.current = authentication_information_array
1027 trustpass = drsblobs.trustDomainPasswords()
1028 confounder = [3] * 512
1030 for i in range(512):
1031 confounder[i] = random.randint(0, 255)
1033 trustpass.confounder = confounder
1035 trustpass.outgoing = outgoing
1036 trustpass.incoming = outgoing
1038 trustpass_blob = ndr_pack(trustpass)
1040 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
1042 auth_blob = lsa.DATA_BUF2()
1043 auth_blob.size = len(encrypted_trustpass)
1044 auth_blob.data = string_to_array(encrypted_trustpass)
1046 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
1047 auth_info.auth_blob = auth_blob
1049 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
1050 info,
1051 auth_info,
1052 security.SEC_STD_DELETE)
1054 rec = {
1055 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
1056 "objectclass" : "trustedDomain",
1057 "trustType" : str(info.trust_type),
1058 "trustAttributes" : str(info.trust_attributes),
1059 "trustDirection" : str(info.trust_direction),
1060 "flatname" : ctx.forest_domain_name,
1061 "trustPartner" : ctx.dnsforest,
1062 "trustAuthIncoming" : ndr_pack(outgoing),
1063 "trustAuthOutgoing" : ndr_pack(outgoing),
1064 "securityIdentifier" : ndr_pack(ctx.forestsid)
1066 ctx.local_samdb.add(rec)
1068 rec = {
1069 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
1070 "objectclass" : "user",
1071 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
1072 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le'),
1073 "samAccountName" : "%s$" % ctx.forest_domain_name
1075 ctx.local_samdb.add(rec)
1078 def do_join(ctx):
1079 # nc_list is the list of naming context (NC) for which we will
1080 # replicate in and send a updateRef command to the partner DC
1082 # full_nc_list is the list of naming context (NC) we hold
1083 # read/write copies of. These are not subsets of each other.
1084 ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
1085 ctx.full_nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
1087 if ctx.subdomain and ctx.dns_backend != "NONE":
1088 ctx.full_nc_list += [ctx.domaindns_zone]
1090 elif not ctx.subdomain:
1091 ctx.nc_list += [ctx.base_dn]
1093 if ctx.dns_backend != "NONE":
1094 ctx.nc_list += [ctx.domaindns_zone]
1095 ctx.nc_list += [ctx.forestdns_zone]
1096 ctx.full_nc_list += [ctx.domaindns_zone]
1097 ctx.full_nc_list += [ctx.forestdns_zone]
1099 if not ctx.clone_only:
1100 if ctx.promote_existing:
1101 ctx.promote_possible()
1102 else:
1103 ctx.cleanup_old_join()
1105 try:
1106 if not ctx.clone_only:
1107 ctx.join_add_objects()
1108 ctx.join_provision()
1109 ctx.join_replicate()
1110 if (not ctx.clone_only and ctx.subdomain):
1111 ctx.join_add_objects2()
1112 ctx.join_provision_own_domain()
1113 ctx.join_setup_trusts()
1114 ctx.join_finalise()
1115 except:
1116 print "Join failed - cleaning up"
1117 if not ctx.clone_only:
1118 ctx.cleanup_old_join()
1119 raise
1122 def join_RODC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1123 targetdir=None, domain=None, domain_critical_only=False,
1124 machinepass=None, use_ntvfs=False, dns_backend=None,
1125 promote_existing=False):
1126 """Join as a RODC."""
1128 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1129 machinepass, use_ntvfs, dns_backend, promote_existing)
1131 lp.set("workgroup", ctx.domain_name)
1132 logger.info("workgroup is %s" % ctx.domain_name)
1134 lp.set("realm", ctx.realm)
1135 logger.info("realm is %s" % ctx.realm)
1137 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
1139 # setup some defaults for accounts that should be replicated to this RODC
1140 ctx.never_reveal_sid = [
1141 "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
1142 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
1143 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
1144 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
1145 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS]
1146 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
1148 mysid = ctx.get_mysid()
1149 admin_dn = "<SID=%s>" % mysid
1150 ctx.managedby = admin_dn
1152 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
1153 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1154 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
1156 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
1157 "RestrictedKrbHost/%s" % ctx.dnshostname ])
1159 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
1160 ctx.secure_channel_type = misc.SEC_CHAN_RODC
1161 ctx.RODC = True
1162 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
1163 drsuapi.DRSUAPI_DRS_PER_SYNC |
1164 drsuapi.DRSUAPI_DRS_GET_ANC |
1165 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
1166 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1167 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
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()
1174 logger.info("Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid))
1177 def join_DC(logger=None, server=None, creds=None, lp=None, site=None, netbios_name=None,
1178 targetdir=None, domain=None, domain_critical_only=False,
1179 machinepass=None, use_ntvfs=False, dns_backend=None,
1180 promote_existing=False):
1181 """Join as a DC."""
1182 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, domain,
1183 machinepass, use_ntvfs, dns_backend, promote_existing)
1185 lp.set("workgroup", ctx.domain_name)
1186 logger.info("workgroup is %s" % ctx.domain_name)
1188 lp.set("realm", ctx.realm)
1189 logger.info("realm is %s" % ctx.realm)
1191 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1193 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1194 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1196 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1197 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1198 drsuapi.DRSUAPI_DRS_PER_SYNC |
1199 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1200 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1201 ctx.domain_replica_flags = ctx.replica_flags
1202 if domain_critical_only:
1203 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1205 ctx.do_join()
1206 logger.info("Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))
1208 def join_clone(logger=None, server=None, creds=None, lp=None,
1209 targetdir=None, domain=None, include_secrets=False):
1210 """Join as a DC."""
1211 ctx = dc_join(logger, server, creds, lp, site=None, netbios_name=None, targetdir=targetdir, domain=domain,
1212 machinepass=None, use_ntvfs=False, dns_backend="NONE", promote_existing=False, clone_only=True)
1214 lp.set("workgroup", ctx.domain_name)
1215 logger.info("workgroup is %s" % ctx.domain_name)
1217 lp.set("realm", ctx.realm)
1218 logger.info("realm is %s" % ctx.realm)
1220 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1221 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1222 drsuapi.DRSUAPI_DRS_PER_SYNC |
1223 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1224 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1225 if not include_secrets:
1226 ctx.replica_flags |= drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING
1227 ctx.domain_replica_flags = ctx.replica_flags
1229 ctx.do_join()
1230 logger.info("Cloned domain %s (SID %s)" % (ctx.domain_name, ctx.domsid))
1232 def join_subdomain(logger=None, server=None, creds=None, lp=None, site=None,
1233 netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
1234 netbios_domain=None, machinepass=None, adminpass=None, use_ntvfs=False,
1235 dns_backend=None):
1236 """Join as a DC."""
1237 ctx = dc_join(logger, server, creds, lp, site, netbios_name, targetdir, parent_domain,
1238 machinepass, use_ntvfs, dns_backend)
1239 ctx.subdomain = True
1240 if adminpass is None:
1241 ctx.adminpass = samba.generate_random_password(12, 32)
1242 else:
1243 ctx.adminpass = adminpass
1244 ctx.parent_domain_name = ctx.domain_name
1245 ctx.domain_name = netbios_domain
1246 ctx.realm = dnsdomain
1247 ctx.parent_dnsdomain = ctx.dnsdomain
1248 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1249 ctx.dnsdomain = dnsdomain
1250 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1251 ctx.naming_master = ctx.get_naming_master()
1252 if ctx.naming_master != ctx.server:
1253 logger.info("Reconnecting to naming master %s" % ctx.naming_master)
1254 ctx.server = ctx.naming_master
1255 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1256 session_info=system_session(),
1257 credentials=ctx.creds, lp=ctx.lp)
1258 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=['dnsHostName'],
1259 controls=[])
1260 ctx.server = res[0]["dnsHostName"]
1261 logger.info("DNS name of new naming master is %s" % ctx.server)
1263 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1264 ctx.forestsid = ctx.domsid
1265 ctx.domsid = security.random_sid()
1266 ctx.acct_dn = None
1267 ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
1268 ctx.trustdom_pass = samba.generate_random_password(128, 128)
1270 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1272 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1273 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1275 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1276 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1277 drsuapi.DRSUAPI_DRS_PER_SYNC |
1278 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1279 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1280 ctx.domain_replica_flags = ctx.replica_flags
1282 ctx.do_join()
1283 ctx.logger.info("Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid))