s4 provision: DNS backend should be set by caller
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / join.py
blob6a8ac97f1c3ebcd11c92e5ab63c56d0d3d47cbf4
1 #!/usr/bin/env python
3 # python join code
4 # Copyright Andrew Tridgell 2010
5 # Copyright Andrew Bartlett 2010
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 """Joining a domain."""
23 from samba.auth import system_session
24 from samba.samdb import SamDB
25 from samba import gensec, Ldb, drs_utils
26 import ldb, samba, sys, os, uuid
27 from samba.ndr import ndr_pack
28 from samba.dcerpc import security, drsuapi, misc, nbt, lsa, drsblobs
29 from samba.credentials import Credentials, DONT_USE_KERBEROS
30 from samba.provision import secretsdb_self_join, provision, provision_fill, FILL_DRS, FILL_SUBDOMAIN
31 from samba.schema import Schema
32 from samba.net import Net
33 from samba.dcerpc import security
34 import logging
35 import talloc
36 import random
37 import time
39 # this makes debugging easier
40 talloc.enable_null_tracking()
42 class DCJoinException(Exception):
44 def __init__(self, msg):
45 super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
48 class dc_join(object):
49 '''perform a DC join'''
51 def __init__(ctx, server=None, creds=None, lp=None, site=None,
52 netbios_name=None, targetdir=None, domain=None):
53 ctx.creds = creds
54 ctx.lp = lp
55 ctx.site = site
56 ctx.netbios_name = netbios_name
57 ctx.targetdir = targetdir
59 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
60 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
62 if server is not None:
63 ctx.server = server
64 else:
65 print("Finding a writeable DC for domain '%s'" % domain)
66 ctx.server = ctx.find_dc(domain)
67 print("Found DC %s" % ctx.server)
69 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
70 session_info=system_session(),
71 credentials=ctx.creds, lp=ctx.lp)
73 try:
74 ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
75 except ldb.LdbError, (enum, estr):
76 raise DCJoinException(estr)
79 ctx.myname = netbios_name
80 ctx.samname = "%s$" % ctx.myname
81 ctx.base_dn = str(ctx.samdb.get_default_basedn())
82 ctx.root_dn = str(ctx.samdb.get_root_basedn())
83 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
84 ctx.config_dn = str(ctx.samdb.get_config_basedn())
85 ctx.domsid = ctx.samdb.get_domain_sid()
86 ctx.domain_name = ctx.get_domain_name()
87 ctx.forest_domain_name = ctx.get_forest_domain_name()
88 ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
90 ctx.dc_ntds_dn = ctx.get_dsServiceName()
91 ctx.dc_dnsHostName = ctx.get_dnsHostName()
92 ctx.behavior_version = ctx.get_behavior_version()
94 ctx.acct_pass = samba.generate_random_password(32, 40)
96 # work out the DNs of all the objects we will be adding
97 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
98 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
99 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
100 if ctx.dn_exists(topology_base):
101 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
102 else:
103 ctx.topology_dn = None
105 ctx.dnsdomain = ctx.samdb.domain_dns_name()
106 ctx.dnsforest = ctx.samdb.forest_dns_name()
107 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
109 ctx.realm = ctx.dnsdomain
111 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
113 ctx.tmp_samdb = None
115 ctx.SPNs = [ "HOST/%s" % ctx.myname,
116 "HOST/%s" % ctx.dnshostname,
117 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
119 # these elements are optional
120 ctx.never_reveal_sid = None
121 ctx.reveal_sid = None
122 ctx.connection_dn = None
123 ctx.RODC = False
124 ctx.krbtgt_dn = None
125 ctx.drsuapi = None
126 ctx.managedby = None
127 ctx.subdomain = False
130 def del_noerror(ctx, dn, recursive=False):
131 if recursive:
132 try:
133 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
134 except Exception:
135 return
136 for r in res:
137 ctx.del_noerror(r.dn, recursive=True)
138 try:
139 ctx.samdb.delete(dn)
140 print "Deleted %s" % dn
141 except Exception:
142 pass
144 def cleanup_old_join(ctx):
145 '''remove any DNs from a previous join'''
146 try:
147 # find the krbtgt link
148 print("checking samaccountname")
149 if ctx.subdomain:
150 res = None
151 else:
152 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
153 expression='samAccountName=%s' % ldb.binary_encode(ctx.samname),
154 attrs=["msDS-krbTgtLink"])
155 if res:
156 ctx.del_noerror(res[0].dn, recursive=True)
157 if ctx.connection_dn is not None:
158 ctx.del_noerror(ctx.connection_dn)
159 if ctx.krbtgt_dn is not None:
160 ctx.del_noerror(ctx.krbtgt_dn)
161 ctx.del_noerror(ctx.ntds_dn)
162 ctx.del_noerror(ctx.server_dn, recursive=True)
163 if ctx.topology_dn:
164 ctx.del_noerror(ctx.topology_dn)
165 if ctx.partition_dn:
166 ctx.del_noerror(ctx.partition_dn)
167 if res:
168 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
169 ctx.del_noerror(ctx.new_krbtgt_dn)
171 if ctx.subdomain:
172 binding_options = "sign"
173 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
174 ctx.lp, ctx.creds)
176 objectAttr = lsa.ObjectAttribute()
177 objectAttr.sec_qos = lsa.QosInfo()
179 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
180 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
182 name = lsa.String()
183 name.string = ctx.realm
184 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
186 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
188 name = lsa.String()
189 name.string = ctx.forest_domain_name
190 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
192 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
194 except Exception:
195 pass
197 def find_dc(ctx, domain):
198 '''find a writeable DC for the given domain'''
199 try:
200 ctx.cldap_ret = ctx.net.finddc(domain, nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
201 except Exception:
202 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
203 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
204 ctx.site = ctx.cldap_ret.client_site
205 return ctx.cldap_ret.pdc_dns_name
208 def get_dsServiceName(ctx):
209 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
210 return res[0]["dsServiceName"][0]
212 def get_behavior_version(ctx):
213 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
214 if "msDS-Behavior-Version" in res[0]:
215 return int(res[0]["msDS-Behavior-Version"][0])
216 else:
217 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
219 def get_dnsHostName(ctx):
220 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
221 return res[0]["dnsHostName"][0]
223 def get_domain_name(ctx):
224 '''get netbios name of the domain from the partitions record'''
225 partitions_dn = ctx.samdb.get_partitions_dn()
226 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
227 expression='ncName=%s' % ctx.samdb.get_default_basedn())
228 return res[0]["nETBIOSName"][0]
230 def get_forest_domain_name(ctx):
231 '''get netbios name of the domain from the partitions record'''
232 partitions_dn = ctx.samdb.get_partitions_dn()
233 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
234 expression='ncName=%s' % ctx.samdb.get_root_basedn())
235 return res[0]["nETBIOSName"][0]
237 def get_parent_partition_dn(ctx):
238 '''get the parent domain partition DN from parent DNS name'''
239 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
240 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
241 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
242 return str(res[0].dn)
244 def get_naming_master(ctx):
245 '''get the parent domain partition DN from parent DNS name'''
246 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
247 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
248 if not 'fSMORoleOwner' in res[0]:
249 raise DCJoinException("Can't find naming master on partition DN %s" % ctx.partition_dn)
250 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
251 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
252 return master_host
254 def get_mysid(ctx):
255 '''get the SID of the connected user. Only works with w2k8 and later,
256 so only used for RODC join'''
257 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
258 binsid = res[0]["tokenGroups"][0]
259 return ctx.samdb.schema_format_value("objectSID", binsid)
261 def dn_exists(ctx, dn):
262 '''check if a DN exists'''
263 try:
264 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
265 except ldb.LdbError, (enum, estr):
266 if enum == ldb.ERR_NO_SUCH_OBJECT:
267 return False
268 raise
269 return True
271 def add_krbtgt_account(ctx):
272 '''RODCs need a special krbtgt account'''
273 print "Adding %s" % ctx.krbtgt_dn
274 rec = {
275 "dn" : ctx.krbtgt_dn,
276 "objectclass" : "user",
277 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
278 samba.dsdb.UF_ACCOUNTDISABLE),
279 "showinadvancedviewonly" : "TRUE",
280 "description" : "krbtgt for %s" % ctx.samname}
281 ctx.samdb.add(rec, ["rodc_join:1:1"])
283 # now we need to search for the samAccountName attribute on the krbtgt DN,
284 # as this will have been magically set to the krbtgt number
285 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
286 ctx.krbtgt_name = res[0]["samAccountName"][0]
288 print "Got krbtgt_name=%s" % ctx.krbtgt_name
290 m = ldb.Message()
291 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
292 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
293 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
294 ctx.samdb.modify(m)
296 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
297 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
298 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
300 def drsuapi_connect(ctx):
301 '''make a DRSUAPI connection to the naming master'''
302 binding_options = "seal"
303 if int(ctx.lp.get("log level")) >= 4:
304 binding_options += ",print"
305 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
306 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
307 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
309 def create_tmp_samdb(ctx):
310 '''create a temporary samdb object for schema queries'''
311 ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
312 schemadn=ctx.schema_dn)
313 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
314 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
315 am_rodc=False)
316 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
318 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
319 '''build a DsReplicaAttributeCtr object'''
320 r = drsuapi.DsReplicaAttribute()
321 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
322 r.value_ctr = 1
325 def DsAddEntry(ctx, recs):
326 '''add a record via the DRSUAPI DsAddEntry call'''
327 if ctx.drsuapi is None:
328 ctx.drsuapi_connect()
329 if ctx.tmp_samdb is None:
330 ctx.create_tmp_samdb()
332 objects = []
333 for rec in recs:
334 id = drsuapi.DsReplicaObjectIdentifier()
335 id.dn = rec['dn']
337 attrs = []
338 for a in rec:
339 if a == 'dn':
340 continue
341 if not isinstance(rec[a], list):
342 v = [rec[a]]
343 else:
344 v = rec[a]
345 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
346 attrs.append(rattr)
348 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
349 attribute_ctr.num_attributes = len(attrs)
350 attribute_ctr.attributes = attrs
352 object = drsuapi.DsReplicaObject()
353 object.identifier = id
354 object.attribute_ctr = attribute_ctr
356 list_object = drsuapi.DsReplicaObjectListItem()
357 list_object.object = object
358 objects.append(list_object)
360 req2 = drsuapi.DsAddEntryRequest2()
361 req2.first_object = objects[0]
362 prev = req2.first_object
363 for o in objects[1:]:
364 prev.next_object = o
365 prev = o
367 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
368 if ctr.err_ver != 1:
369 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
370 if ctr.err_data.status != (0, 'WERR_OK'):
371 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
372 ctr.err_data.info.extended_err))
373 raise RuntimeError("DsAddEntry failed")
374 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
375 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
376 raise RuntimeError("DsAddEntry failed")
377 return ctr.objects
380 def join_add_ntdsdsa(ctx):
381 '''add the ntdsdsa object'''
382 # FIXME: the partition (NC) assignment has to be made dynamic
383 print "Adding %s" % ctx.ntds_dn
384 rec = {
385 "dn" : ctx.ntds_dn,
386 "objectclass" : "nTDSDSA",
387 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
388 "dMDLocation" : ctx.schema_dn}
390 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
392 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
393 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
395 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
396 rec["msDS-HasDomainNCs"] = ctx.base_dn
398 if ctx.RODC:
399 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
400 rec["msDS-HasFullReplicaNCs"] = nc_list
401 rec["options"] = "37"
402 ctx.samdb.add(rec, ["rodc_join:1:1"])
403 else:
404 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
405 rec["HasMasterNCs"] = nc_list
406 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
407 rec["msDS-HasMasterNCs"] = nc_list
408 rec["options"] = "1"
409 rec["invocationId"] = ndr_pack(ctx.invocation_id)
410 ctx.DsAddEntry([rec])
412 # find the GUID of our NTDS DN
413 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
414 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
417 def join_add_objects(ctx):
418 '''add the various objects needed for the join'''
419 if ctx.acct_dn:
420 print "Adding %s" % ctx.acct_dn
421 rec = {
422 "dn" : ctx.acct_dn,
423 "objectClass": "computer",
424 "displayname": ctx.samname,
425 "samaccountname" : ctx.samname,
426 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
427 "dnshostname" : ctx.dnshostname}
428 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
429 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
430 if ctx.managedby:
431 rec["managedby"] = ctx.managedby
432 if ctx.never_reveal_sid:
433 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
434 if ctx.reveal_sid:
435 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
436 ctx.samdb.add(rec)
438 if ctx.krbtgt_dn:
439 ctx.add_krbtgt_account()
441 print "Adding %s" % ctx.server_dn
442 rec = {
443 "dn": ctx.server_dn,
444 "objectclass" : "server",
445 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
446 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
447 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
448 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
449 # windows seems to add the dnsHostName later
450 "dnsHostName" : ctx.dnshostname}
452 if ctx.acct_dn:
453 rec["serverReference"] = ctx.acct_dn
455 ctx.samdb.add(rec)
457 if ctx.subdomain:
458 # the rest is done after replication
459 ctx.ntds_guid = None
460 return
462 ctx.join_add_ntdsdsa()
464 if ctx.connection_dn is not None:
465 print "Adding %s" % ctx.connection_dn
466 rec = {
467 "dn" : ctx.connection_dn,
468 "objectclass" : "nTDSConnection",
469 "enabledconnection" : "TRUE",
470 "options" : "65",
471 "fromServer" : ctx.dc_ntds_dn}
472 ctx.samdb.add(rec)
474 if ctx.topology_dn and ctx.acct_dn:
475 print "Adding %s" % ctx.topology_dn
476 rec = {
477 "dn" : ctx.topology_dn,
478 "objectclass" : "msDFSR-Member",
479 "msDFSR-ComputerReference" : ctx.acct_dn,
480 "serverReference" : ctx.ntds_dn}
481 ctx.samdb.add(rec)
483 if ctx.acct_dn:
484 print "Adding SPNs to %s" % ctx.acct_dn
485 m = ldb.Message()
486 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
487 for i in range(len(ctx.SPNs)):
488 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
489 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
490 ldb.FLAG_MOD_ADD,
491 "servicePrincipalName")
492 ctx.samdb.modify(m)
494 print "Setting account password for %s" % ctx.samname
495 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ldb.binary_encode(ctx.samname),
496 ctx.acct_pass,
497 force_change_at_next_login=False,
498 username=ctx.samname)
499 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-keyVersionNumber"])
500 ctx.key_version_number = int(res[0]["msDS-keyVersionNumber"][0])
502 print("Enabling account")
503 m = ldb.Message()
504 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
505 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
506 ldb.FLAG_MOD_REPLACE,
507 "userAccountControl")
508 ctx.samdb.modify(m)
511 def join_add_objects2(ctx):
512 '''add the various objects needed for the join, for subdomains post replication'''
514 print "Adding %s" % ctx.partition_dn
515 # NOTE: windows sends a ntSecurityDescriptor here, we
516 # let it default
517 rec = {
518 "dn" : ctx.partition_dn,
519 "objectclass" : "crossRef",
520 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
521 "nCName" : ctx.base_dn,
522 "nETBIOSName" : ctx.domain_name,
523 "dnsRoot": ctx.dnsdomain,
524 "trustParent" : ctx.parent_partition_dn,
525 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
526 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
527 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
529 rec2 = {
530 "dn" : ctx.ntds_dn,
531 "objectclass" : "nTDSDSA",
532 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
533 "dMDLocation" : ctx.schema_dn}
535 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
537 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
538 rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
540 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
541 rec2["msDS-HasDomainNCs"] = ctx.base_dn
543 rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
544 rec2["HasMasterNCs"] = nc_list
545 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
546 rec2["msDS-HasMasterNCs"] = nc_list
547 rec2["options"] = "1"
548 rec2["invocationId"] = ndr_pack(ctx.invocation_id)
550 objects = ctx.DsAddEntry([rec, rec2])
551 if len(objects) != 2:
552 raise DCJoinException("Expected 2 objects from DsAddEntry")
554 ctx.ntds_guid = objects[1].guid
556 print("Replicating partition DN")
557 ctx.repl.replicate(ctx.partition_dn,
558 misc.GUID("00000000-0000-0000-0000-000000000000"),
559 ctx.ntds_guid,
560 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
561 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
563 print("Replicating NTDS DN")
564 ctx.repl.replicate(ctx.ntds_dn,
565 misc.GUID("00000000-0000-0000-0000-000000000000"),
566 ctx.ntds_guid,
567 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
568 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
570 def join_provision(ctx):
571 '''provision the local SAM'''
573 print "Calling bare provision"
575 logger = logging.getLogger("provision")
576 logger.addHandler(logging.StreamHandler(sys.stdout))
577 smbconf = ctx.lp.configfile
579 presult = provision(logger, system_session(), None,
580 smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
581 realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
582 schemadn=ctx.schema_dn,
583 configdn=ctx.config_dn,
584 serverdn=ctx.server_dn, domain=ctx.domain_name,
585 hostname=ctx.myname, domainsid=ctx.domsid,
586 machinepass=ctx.acct_pass, serverrole="domain controller",
587 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
588 dns_backend="NONE")
589 print "Provision OK for domain DN %s" % presult.domaindn
590 ctx.local_samdb = presult.samdb
591 ctx.lp = presult.lp
592 ctx.paths = presult.paths
593 ctx.names = presult.names
595 def join_provision_own_domain(ctx):
596 '''provision the local SAM'''
598 # we now operate exclusively on the local database, which
599 # we need to reopen in order to get the newly created schema
600 print("Reconnecting to local samdb")
601 ctx.samdb = SamDB(url=ctx.local_samdb.url,
602 session_info=system_session(),
603 lp=ctx.local_samdb.lp,
604 global_schema=False)
605 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
606 ctx.local_samdb = ctx.samdb
608 print("Finding domain GUID from ncName")
609 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
610 controls=["extended_dn:1:1"])
611 domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
612 print("Got domain GUID %s" % domguid)
614 print("Calling own domain provision")
616 logger = logging.getLogger("provision")
617 logger.addHandler(logging.StreamHandler(sys.stdout))
619 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
621 presult = provision_fill(ctx.local_samdb, secrets_ldb,
622 logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
623 domainguid=domguid,
624 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
625 machinepass=ctx.acct_pass, serverrole="domain controller",
626 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
627 dns_backend="BIND9_FLATFILE")
628 print("Provision OK for domain %s" % ctx.names.dnsdomain)
631 def join_replicate(ctx):
632 '''replicate the SAM'''
634 print "Starting replication"
635 ctx.local_samdb.transaction_start()
636 try:
637 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
638 if ctx.ntds_guid is None:
639 print("Using DS_BIND_GUID_W2K3")
640 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
641 else:
642 destination_dsa_guid = ctx.ntds_guid
644 if ctx.RODC:
645 repl_creds = Credentials()
646 repl_creds.guess(ctx.lp)
647 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
648 repl_creds.set_username(ctx.samname)
649 repl_creds.set_password(ctx.acct_pass)
650 else:
651 repl_creds = ctx.creds
653 binding_options = "seal"
654 if int(ctx.lp.get("log level")) >= 5:
655 binding_options += ",print"
656 repl = drs_utils.drs_Replicate(
657 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
658 ctx.lp, repl_creds, ctx.local_samdb)
660 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
661 destination_dsa_guid, schema=True, rodc=ctx.RODC,
662 replica_flags=ctx.replica_flags)
663 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
664 destination_dsa_guid, rodc=ctx.RODC,
665 replica_flags=ctx.replica_flags)
666 if not ctx.subdomain:
667 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
668 destination_dsa_guid, rodc=ctx.RODC,
669 replica_flags=ctx.domain_replica_flags)
670 if ctx.RODC:
671 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
672 destination_dsa_guid,
673 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
674 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
675 destination_dsa_guid,
676 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
677 ctx.repl = repl
678 ctx.source_dsa_invocation_id = source_dsa_invocation_id
679 ctx.destination_dsa_guid = destination_dsa_guid
681 print "Committing SAM database"
682 except:
683 ctx.local_samdb.transaction_cancel()
684 raise
685 else:
686 ctx.local_samdb.transaction_commit()
689 def join_finalise(ctx):
690 '''finalise the join, mark us synchronised and setup secrets db'''
692 print "Setting isSynchronized and dsServiceName"
693 m = ldb.Message()
694 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
695 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
696 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
697 ldb.FLAG_MOD_REPLACE, "dsServiceName")
698 ctx.local_samdb.modify(m)
700 if ctx.subdomain:
701 return
703 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
705 print "Setting up secrets database"
706 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
707 realm=ctx.realm,
708 dnsdomain=ctx.dnsdomain,
709 netbiosname=ctx.myname,
710 domainsid=security.dom_sid(ctx.domsid),
711 machinepass=ctx.acct_pass,
712 secure_channel_type=ctx.secure_channel_type,
713 key_version_number=ctx.key_version_number)
715 def join_setup_trusts(ctx):
716 '''provision the local SAM'''
718 def arcfour_encrypt(key, data):
719 from Crypto.Cipher import ARC4
720 c = ARC4.new(key)
721 return c.encrypt(data)
723 def string_to_array(string):
724 blob = [0] * len(string)
726 for i in range(len(string)):
727 blob[i] = ord(string[i])
729 return blob
731 print "Setup domain trusts with server %s" % ctx.server
732 binding_options = "" # why doesn't signing work gere? w2k8r2 claims no session key
733 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
734 ctx.lp, ctx.creds)
736 objectAttr = lsa.ObjectAttribute()
737 objectAttr.sec_qos = lsa.QosInfo()
739 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
740 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
742 info = lsa.TrustDomainInfoInfoEx()
743 info.domain_name.string = ctx.dnsdomain
744 info.netbios_name.string = ctx.domain_name
745 info.sid = security.dom_sid(ctx.domsid)
746 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
747 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
748 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
750 try:
751 oldname = lsa.String()
752 oldname.string = ctx.dnsdomain
753 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
754 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
755 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
756 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
757 except RuntimeError:
758 pass
760 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
762 clear_value = drsblobs.AuthInfoClear()
763 clear_value.size = len(password_blob)
764 clear_value.password = password_blob
766 clear_authentication_information = drsblobs.AuthenticationInformation()
767 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
768 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
769 clear_authentication_information.AuthInfo = clear_value
771 authentication_information_array = drsblobs.AuthenticationInformationArray()
772 authentication_information_array.count = 1
773 authentication_information_array.array = [clear_authentication_information]
775 outgoing = drsblobs.trustAuthInOutBlob()
776 outgoing.count = 1
777 outgoing.current = authentication_information_array
779 trustpass = drsblobs.trustDomainPasswords()
780 confounder = [3] * 512
782 for i in range(512):
783 confounder[i] = random.randint(0, 255)
785 trustpass.confounder = confounder
787 trustpass.outgoing = outgoing
788 trustpass.incoming = outgoing
790 trustpass_blob = ndr_pack(trustpass)
792 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
794 auth_blob = lsa.DATA_BUF2()
795 auth_blob.size = len(encrypted_trustpass)
796 auth_blob.data = string_to_array(encrypted_trustpass)
798 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
799 auth_info.auth_blob = auth_blob
801 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
802 info,
803 auth_info,
804 security.SEC_STD_DELETE)
806 rec = {
807 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
808 "objectclass" : "trustedDomain",
809 "trustType" : str(info.trust_type),
810 "trustAttributes" : str(info.trust_attributes),
811 "trustDirection" : str(info.trust_direction),
812 "flatname" : ctx.forest_domain_name,
813 "trustPartner" : ctx.dnsforest,
814 "trustAuthIncoming" : ndr_pack(outgoing),
815 "trustAuthOutgoing" : ndr_pack(outgoing)
817 ctx.local_samdb.add(rec)
819 rec = {
820 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
821 "objectclass" : "user",
822 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
823 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
825 ctx.local_samdb.add(rec)
828 def do_join(ctx):
829 ctx.cleanup_old_join()
830 try:
831 ctx.join_add_objects()
832 ctx.join_provision()
833 ctx.join_replicate()
834 if ctx.subdomain:
835 ctx.join_add_objects2()
836 ctx.join_provision_own_domain()
837 ctx.join_setup_trusts()
838 ctx.join_finalise()
839 except Exception:
840 print "Join failed - cleaning up"
841 ctx.cleanup_old_join()
842 raise
845 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
846 targetdir=None, domain=None, domain_critical_only=False):
847 """join as a RODC"""
849 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
851 lp.set("workgroup", ctx.domain_name)
852 print("workgroup is %s" % ctx.domain_name)
854 lp.set("realm", ctx.realm)
855 print("realm is %s" % ctx.realm)
857 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
859 # setup some defaults for accounts that should be replicated to this RODC
860 ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
861 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
862 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
863 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
864 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
865 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
867 mysid = ctx.get_mysid()
868 admin_dn = "<SID=%s>" % mysid
869 ctx.managedby = admin_dn
871 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
872 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
873 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
875 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
876 "RestrictedKrbHost/%s" % ctx.dnshostname ])
878 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
879 ctx.secure_channel_type = misc.SEC_CHAN_RODC
880 ctx.RODC = True
881 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
882 drsuapi.DRSUAPI_DRS_PER_SYNC |
883 drsuapi.DRSUAPI_DRS_GET_ANC |
884 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
885 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
886 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
887 ctx.domain_replica_flags = ctx.replica_flags
888 if domain_critical_only:
889 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
891 ctx.do_join()
894 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
897 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
898 targetdir=None, domain=None, domain_critical_only=False):
899 """join as a DC"""
900 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
902 lp.set("workgroup", ctx.domain_name)
903 print("workgroup is %s" % ctx.domain_name)
905 lp.set("realm", ctx.realm)
906 print("realm is %s" % ctx.realm)
908 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
910 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
911 ctx.secure_channel_type = misc.SEC_CHAN_BDC
913 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
914 drsuapi.DRSUAPI_DRS_INIT_SYNC |
915 drsuapi.DRSUAPI_DRS_PER_SYNC |
916 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
917 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
918 ctx.domain_replica_flags = ctx.replica_flags
919 if domain_critical_only:
920 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
922 ctx.do_join()
923 print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
925 def join_subdomain(server=None, creds=None, lp=None, site=None, netbios_name=None,
926 targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None):
927 """join as a DC"""
928 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain)
929 ctx.subdomain = True
930 ctx.parent_domain_name = ctx.domain_name
931 ctx.domain_name = netbios_domain
932 ctx.realm = dnsdomain
933 ctx.parent_dnsdomain = ctx.dnsdomain
934 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
935 ctx.dnsdomain = dnsdomain
936 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
937 ctx.naming_master = ctx.get_naming_master()
938 if ctx.naming_master != ctx.server:
939 print("Reconnecting to naming master %s" % ctx.naming_master)
940 ctx.server = ctx.naming_master
941 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
942 session_info=system_session(),
943 credentials=ctx.creds, lp=ctx.lp)
945 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
946 ctx.domsid = str(security.random_sid())
947 ctx.acct_dn = None
948 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
949 ctx.trustdom_pass = samba.generate_random_password(128, 128)
951 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
953 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
954 ctx.secure_channel_type = misc.SEC_CHAN_BDC
956 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
957 drsuapi.DRSUAPI_DRS_INIT_SYNC |
958 drsuapi.DRSUAPI_DRS_PER_SYNC |
959 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
960 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
961 ctx.domain_replica_flags = ctx.replica_flags
963 ctx.do_join()
964 print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)