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, 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
38 # this makes debugging easier
39 talloc.enable_null_tracking()
41 class DCJoinException(Exception):
43 def __init__(self, msg):
44 super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
47 class dc_join(object):
48 '''perform a DC join'''
50 def __init__(ctx, server=None, creds=None, lp=None, site=None,
51 netbios_name=None, targetdir=None, domain=None):
55 ctx.netbios_name = netbios_name
56 ctx.targetdir = targetdir
58 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
59 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
61 if server is not None:
64 print("Finding a writeable DC for domain '%s'" % domain)
65 ctx.server = ctx.find_dc(domain)
66 print("Found DC %s" % ctx.server)
68 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
69 session_info=system_session(),
70 credentials=ctx.creds, lp=ctx.lp)
73 ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
74 except ldb.LdbError, (enum, estr):
75 raise DCJoinException(estr)
78 ctx.myname = netbios_name
79 ctx.samname = "%s$" % ctx.myname
80 ctx.base_dn = str(ctx.samdb.get_default_basedn())
81 ctx.root_dn = str(ctx.samdb.get_root_basedn())
82 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
83 ctx.config_dn = str(ctx.samdb.get_config_basedn())
84 ctx.domsid = ctx.samdb.get_domain_sid()
85 ctx.domain_name = ctx.get_domain_name()
86 ctx.forest_domain_name = ctx.get_forest_domain_name()
87 ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
89 ctx.dc_ntds_dn = ctx.get_dsServiceName()
90 ctx.dc_dnsHostName = ctx.get_dnsHostName()
91 ctx.behavior_version = ctx.get_behavior_version()
93 ctx.acct_pass = samba.generate_random_password(32, 40)
95 # work out the DNs of all the objects we will be adding
96 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
97 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
98 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
99 if ctx.dn_exists(topology_base):
100 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
102 ctx.topology_dn = None
104 ctx.dnsdomain = ctx.samdb.domain_dns_name()
105 ctx.dnsforest = ctx.samdb.forest_dns_name()
106 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
108 ctx.realm = ctx.dnsdomain
110 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
114 ctx.SPNs = [ "HOST/%s" % ctx.myname,
115 "HOST/%s" % ctx.dnshostname,
116 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
118 # these elements are optional
119 ctx.never_reveal_sid = None
120 ctx.reveal_sid = None
121 ctx.connection_dn = None
126 ctx.subdomain = False
128 def del_noerror(ctx, dn, recursive=False):
131 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
135 ctx.del_noerror(r.dn, recursive=True)
138 print "Deleted %s" % dn
142 def cleanup_old_join(ctx):
143 '''remove any DNs from a previous join'''
145 # find the krbtgt link
146 print("checking samaccountname")
150 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
151 expression='samAccountName=%s' % ldb.binary_encode(ctx.samname),
152 attrs=["msDS-krbTgtLink"])
154 ctx.del_noerror(res[0].dn, recursive=True)
155 if ctx.connection_dn is not None:
156 ctx.del_noerror(ctx.connection_dn)
157 if ctx.krbtgt_dn is not None:
158 ctx.del_noerror(ctx.krbtgt_dn)
159 ctx.del_noerror(ctx.ntds_dn)
160 ctx.del_noerror(ctx.server_dn, recursive=True)
162 ctx.del_noerror(ctx.topology_dn)
164 ctx.del_noerror(ctx.partition_dn)
166 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
167 ctx.del_noerror(ctx.new_krbtgt_dn)
170 binding_options = "sign"
171 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
174 objectAttr = lsa.ObjectAttribute()
175 objectAttr.sec_qos = lsa.QosInfo()
177 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
178 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
181 name.string = ctx.realm
182 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
184 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
187 name.string = ctx.forest_domain_name
188 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
190 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
195 def find_dc(ctx, domain):
196 '''find a writeable DC for the given domain'''
198 ctx.cldap_ret = ctx.net.finddc(domain, nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
200 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
201 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
202 ctx.site = ctx.cldap_ret.client_site
203 return ctx.cldap_ret.pdc_dns_name
206 def get_dsServiceName(ctx):
207 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
208 return res[0]["dsServiceName"][0]
210 def get_behavior_version(ctx):
211 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
212 if "msDS-Behavior-Version" in res[0]:
213 return int(res[0]["msDS-Behavior-Version"][0])
215 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
217 def get_dnsHostName(ctx):
218 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
219 return res[0]["dnsHostName"][0]
221 def get_domain_name(ctx):
222 '''get netbios name of the domain from the partitions record'''
223 partitions_dn = ctx.samdb.get_partitions_dn()
224 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
225 expression='ncName=%s' % ctx.samdb.get_default_basedn())
226 return res[0]["nETBIOSName"][0]
228 def get_forest_domain_name(ctx):
229 '''get netbios name of the domain from the partitions record'''
230 partitions_dn = ctx.samdb.get_partitions_dn()
231 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
232 expression='ncName=%s' % ctx.samdb.get_root_basedn())
233 return res[0]["nETBIOSName"][0]
235 def get_parent_partition_dn(ctx):
236 '''get the parent domain partition DN from parent DNS name'''
237 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
238 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
239 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
240 return str(res[0].dn)
242 def get_naming_master(ctx):
243 '''get the parent domain partition DN from parent DNS name'''
244 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
245 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
246 if not 'fSMORoleOwner' in res[0]:
247 raise DCJoinException("Can't find naming master on partition DN %s" % ctx.partition_dn)
248 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
249 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
253 '''get the SID of the connected user. Only works with w2k8 and later,
254 so only used for RODC join'''
255 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
256 binsid = res[0]["tokenGroups"][0]
257 return ctx.samdb.schema_format_value("objectSID", binsid)
259 def dn_exists(ctx, dn):
260 '''check if a DN exists'''
262 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
263 except ldb.LdbError, (enum, estr):
264 if enum == ldb.ERR_NO_SUCH_OBJECT:
269 def add_krbtgt_account(ctx):
270 '''RODCs need a special krbtgt account'''
271 print "Adding %s" % ctx.krbtgt_dn
273 "dn" : ctx.krbtgt_dn,
274 "objectclass" : "user",
275 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
276 samba.dsdb.UF_ACCOUNTDISABLE),
277 "showinadvancedviewonly" : "TRUE",
278 "description" : "krbtgt for %s" % ctx.samname}
279 ctx.samdb.add(rec, ["rodc_join:1:1"])
281 # now we need to search for the samAccountName attribute on the krbtgt DN,
282 # as this will have been magically set to the krbtgt number
283 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
284 ctx.krbtgt_name = res[0]["samAccountName"][0]
286 print "Got krbtgt_name=%s" % ctx.krbtgt_name
289 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
290 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
291 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
294 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
295 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
296 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
298 def drsuapi_connect(ctx):
299 '''make a DRSUAPI connection to the naming master'''
300 binding_options = "seal"
301 if int(ctx.lp.get("log level")) >= 4:
302 binding_options += ",print"
303 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
304 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
305 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
307 def create_tmp_samdb(ctx):
308 '''create a temporary samdb object for schema queries'''
309 ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
310 schemadn=ctx.schema_dn)
311 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
312 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
314 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
316 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
317 '''build a DsReplicaAttributeCtr object'''
318 r = drsuapi.DsReplicaAttribute()
319 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
323 def DsAddEntry(ctx, recs):
324 '''add a record via the DRSUAPI DsAddEntry call'''
325 if ctx.drsuapi is None:
326 ctx.drsuapi_connect()
327 if ctx.tmp_samdb is None:
328 ctx.create_tmp_samdb()
332 id = drsuapi.DsReplicaObjectIdentifier()
339 if not isinstance(rec[a], list):
343 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
346 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
347 attribute_ctr.num_attributes = len(attrs)
348 attribute_ctr.attributes = attrs
350 object = drsuapi.DsReplicaObject()
351 object.identifier = id
352 object.attribute_ctr = attribute_ctr
354 list_object = drsuapi.DsReplicaObjectListItem()
355 list_object.object = object
356 objects.append(list_object)
358 req2 = drsuapi.DsAddEntryRequest2()
359 req2.first_object = objects[0]
360 prev = req2.first_object
361 for o in objects[1:]:
365 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
367 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
368 if ctr.err_data.status != (0, 'WERR_OK'):
369 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
370 ctr.err_data.info.extended_err))
371 raise RuntimeError("DsAddEntry failed")
372 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
373 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
374 raise RuntimeError("DsAddEntry failed")
377 def join_add_ntdsdsa(ctx):
378 '''add the ntdsdsa object'''
379 # FIXME: the partition (NC) assignment has to be made dynamic
380 print "Adding %s" % ctx.ntds_dn
383 "objectclass" : "nTDSDSA",
384 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
385 "dMDLocation" : ctx.schema_dn}
387 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
389 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
390 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
392 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
393 rec["msDS-HasDomainNCs"] = ctx.base_dn
396 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
397 rec["msDS-HasFullReplicaNCs"] = nc_list
398 rec["options"] = "37"
399 ctx.samdb.add(rec, ["rodc_join:1:1"])
401 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
402 rec["HasMasterNCs"] = nc_list
403 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
404 rec["msDS-HasMasterNCs"] = nc_list
406 rec["invocationId"] = ndr_pack(ctx.invocation_id)
407 ctx.DsAddEntry([rec])
409 # find the GUID of our NTDS DN
410 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
411 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
413 def join_add_objects(ctx):
414 '''add the various objects needed for the join'''
416 print "Adding %s" % ctx.acct_dn
419 "objectClass": "computer",
420 "displayname": ctx.samname,
421 "samaccountname" : ctx.samname,
422 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
423 "dnshostname" : ctx.dnshostname}
424 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
425 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
427 rec["managedby"] = ctx.managedby
428 if ctx.never_reveal_sid:
429 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
431 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
435 ctx.add_krbtgt_account()
437 print "Adding %s" % ctx.server_dn
440 "objectclass" : "server",
441 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
442 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
443 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
444 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
445 # windows seems to add the dnsHostName later
446 "dnsHostName" : ctx.dnshostname}
449 rec["serverReference"] = ctx.acct_dn
454 # the rest is done after replication
458 ctx.join_add_ntdsdsa()
460 if ctx.connection_dn is not None:
461 print "Adding %s" % ctx.connection_dn
463 "dn" : ctx.connection_dn,
464 "objectclass" : "nTDSConnection",
465 "enabledconnection" : "TRUE",
467 "fromServer" : ctx.dc_ntds_dn}
471 print "Adding SPNs to %s" % ctx.acct_dn
473 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
474 for i in range(len(ctx.SPNs)):
475 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
476 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
478 "servicePrincipalName")
481 print "Setting account password for %s" % ctx.samname
482 ctx.samdb.setpassword("(&(objectClass=computer)(sAMAccountName=%s))" % ldb.binary_encode(ctx.samname),
484 force_change_at_next_login=False,
485 username=ctx.samname)
486 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-keyVersionNumber"])
487 ctx.key_version_number = int(res[0]["msDS-keyVersionNumber"][0])
489 print("Enabling account")
491 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
492 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
493 ldb.FLAG_MOD_REPLACE,
494 "userAccountControl")
497 def join_add_objects2(ctx):
498 '''add the various objects needed for the join, for subdomains post replication'''
500 print "Adding %s" % ctx.partition_dn
501 # NOTE: windows sends a ntSecurityDescriptor here, we
504 "dn" : ctx.partition_dn,
505 "objectclass" : "crossRef",
506 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
507 "nCName" : ctx.base_dn,
508 "nETBIOSName" : ctx.domain_name,
509 "dnsRoot": ctx.dnsdomain,
510 "trustParent" : ctx.parent_partition_dn,
511 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
512 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
513 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
517 "objectclass" : "nTDSDSA",
518 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
519 "dMDLocation" : ctx.schema_dn}
521 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
523 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
524 rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
526 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
527 rec2["msDS-HasDomainNCs"] = ctx.base_dn
529 rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
530 rec2["HasMasterNCs"] = nc_list
531 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
532 rec2["msDS-HasMasterNCs"] = nc_list
533 rec2["options"] = "1"
534 rec2["invocationId"] = ndr_pack(ctx.invocation_id)
536 objects = ctx.DsAddEntry([rec, rec2])
537 if len(objects) != 2:
538 raise DCJoinException("Expected 2 objects from DsAddEntry")
540 ctx.ntds_guid = objects[1].guid
542 print("Replicating partition DN")
543 ctx.repl.replicate(ctx.partition_dn,
544 misc.GUID("00000000-0000-0000-0000-000000000000"),
546 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
547 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
549 print("Replicating NTDS DN")
550 ctx.repl.replicate(ctx.ntds_dn,
551 misc.GUID("00000000-0000-0000-0000-000000000000"),
553 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
554 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
556 def join_provision(ctx):
557 '''provision the local SAM'''
559 print "Calling bare provision"
561 logger = logging.getLogger("provision")
562 logger.addHandler(logging.StreamHandler(sys.stdout))
563 smbconf = ctx.lp.configfile
565 presult = provision(logger, system_session(), None,
566 smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
567 realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
568 schemadn=ctx.schema_dn,
569 configdn=ctx.config_dn,
570 serverdn=ctx.server_dn, domain=ctx.domain_name,
571 hostname=ctx.myname, domainsid=ctx.domsid,
572 machinepass=ctx.acct_pass, serverrole="domain controller",
573 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
575 print "Provision OK for domain DN %s" % presult.domaindn
576 ctx.local_samdb = presult.samdb
578 ctx.paths = presult.paths
579 ctx.names = presult.names
581 def join_provision_own_domain(ctx):
582 '''provision the local SAM'''
584 # we now operate exclusively on the local database, which
585 # we need to reopen in order to get the newly created schema
586 print("Reconnecting to local samdb")
587 ctx.samdb = SamDB(url=ctx.local_samdb.url,
588 session_info=system_session(),
589 lp=ctx.local_samdb.lp,
591 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
592 ctx.local_samdb = ctx.samdb
594 print("Finding domain GUID from ncName")
595 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
596 controls=["extended_dn:1:1"])
597 domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
598 print("Got domain GUID %s" % domguid)
600 print("Calling own domain provision")
602 logger = logging.getLogger("provision")
603 logger.addHandler(logging.StreamHandler(sys.stdout))
605 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
607 presult = provision_fill(ctx.local_samdb, secrets_ldb,
608 logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
610 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
611 machinepass=ctx.acct_pass, serverrole="domain controller",
612 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
613 dns_backend="BIND9_FLATFILE")
614 print("Provision OK for domain %s" % ctx.names.dnsdomain)
616 def join_replicate(ctx):
617 '''replicate the SAM'''
619 print "Starting replication"
620 ctx.local_samdb.transaction_start()
622 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
623 if ctx.ntds_guid is None:
624 print("Using DS_BIND_GUID_W2K3")
625 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
627 destination_dsa_guid = ctx.ntds_guid
630 repl_creds = Credentials()
631 repl_creds.guess(ctx.lp)
632 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
633 repl_creds.set_username(ctx.samname)
634 repl_creds.set_password(ctx.acct_pass)
636 repl_creds = ctx.creds
638 binding_options = "seal"
639 if int(ctx.lp.get("log level")) >= 5:
640 binding_options += ",print"
641 repl = drs_utils.drs_Replicate(
642 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
643 ctx.lp, repl_creds, ctx.local_samdb)
645 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
646 destination_dsa_guid, schema=True, rodc=ctx.RODC,
647 replica_flags=ctx.replica_flags)
648 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
649 destination_dsa_guid, rodc=ctx.RODC,
650 replica_flags=ctx.replica_flags)
651 if not ctx.subdomain:
652 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
653 destination_dsa_guid, rodc=ctx.RODC,
654 replica_flags=ctx.domain_replica_flags)
656 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
657 destination_dsa_guid,
658 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
659 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
660 destination_dsa_guid,
661 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
663 ctx.source_dsa_invocation_id = source_dsa_invocation_id
664 ctx.destination_dsa_guid = destination_dsa_guid
666 print "Committing SAM database"
668 ctx.local_samdb.transaction_cancel()
671 ctx.local_samdb.transaction_commit()
673 def send_DsReplicaUpdateRefs(ctx, dn):
674 r = drsuapi.DsReplicaUpdateRefsRequest1()
675 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
676 r.naming_context.dn = str(dn)
677 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
678 r.naming_context.sid = security.dom_sid("S-0-0")
679 r.dest_dsa_guid = ctx.ntds_guid
680 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
681 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
683 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
686 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
688 def join_finalise(ctx):
689 '''finalise the join, mark us synchronised and setup secrets db'''
691 print "Sending DsReplicateUpdateRefs for all the partitions"
692 ctx.send_DsReplicaUpdateRefs(ctx.schema_dn)
693 ctx.send_DsReplicaUpdateRefs(ctx.config_dn)
694 ctx.send_DsReplicaUpdateRefs(ctx.base_dn)
696 print "Setting isSynchronized and dsServiceName"
698 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
699 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
700 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
701 ldb.FLAG_MOD_REPLACE, "dsServiceName")
702 ctx.local_samdb.modify(m)
707 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
709 print "Setting up secrets database"
710 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
712 dnsdomain=ctx.dnsdomain,
713 netbiosname=ctx.myname,
714 domainsid=security.dom_sid(ctx.domsid),
715 machinepass=ctx.acct_pass,
716 secure_channel_type=ctx.secure_channel_type,
717 key_version_number=ctx.key_version_number)
719 def join_setup_trusts(ctx):
720 '''provision the local SAM'''
722 def arcfour_encrypt(key, data):
723 from Crypto.Cipher import ARC4
725 return c.encrypt(data)
727 def string_to_array(string):
728 blob = [0] * len(string)
730 for i in range(len(string)):
731 blob[i] = ord(string[i])
735 print "Setup domain trusts with server %s" % ctx.server
736 binding_options = "" # why doesn't signing work gere? w2k8r2 claims no session key
737 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
740 objectAttr = lsa.ObjectAttribute()
741 objectAttr.sec_qos = lsa.QosInfo()
743 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
744 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
746 info = lsa.TrustDomainInfoInfoEx()
747 info.domain_name.string = ctx.dnsdomain
748 info.netbios_name.string = ctx.domain_name
749 info.sid = security.dom_sid(ctx.domsid)
750 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
751 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
752 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
755 oldname = lsa.String()
756 oldname.string = ctx.dnsdomain
757 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
758 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
759 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
760 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
764 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
766 clear_value = drsblobs.AuthInfoClear()
767 clear_value.size = len(password_blob)
768 clear_value.password = password_blob
770 clear_authentication_information = drsblobs.AuthenticationInformation()
771 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
772 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
773 clear_authentication_information.AuthInfo = clear_value
775 authentication_information_array = drsblobs.AuthenticationInformationArray()
776 authentication_information_array.count = 1
777 authentication_information_array.array = [clear_authentication_information]
779 outgoing = drsblobs.trustAuthInOutBlob()
781 outgoing.current = authentication_information_array
783 trustpass = drsblobs.trustDomainPasswords()
784 confounder = [3] * 512
787 confounder[i] = random.randint(0, 255)
789 trustpass.confounder = confounder
791 trustpass.outgoing = outgoing
792 trustpass.incoming = outgoing
794 trustpass_blob = ndr_pack(trustpass)
796 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
798 auth_blob = lsa.DATA_BUF2()
799 auth_blob.size = len(encrypted_trustpass)
800 auth_blob.data = string_to_array(encrypted_trustpass)
802 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
803 auth_info.auth_blob = auth_blob
805 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
808 security.SEC_STD_DELETE)
811 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
812 "objectclass" : "trustedDomain",
813 "trustType" : str(info.trust_type),
814 "trustAttributes" : str(info.trust_attributes),
815 "trustDirection" : str(info.trust_direction),
816 "flatname" : ctx.forest_domain_name,
817 "trustPartner" : ctx.dnsforest,
818 "trustAuthIncoming" : ndr_pack(outgoing),
819 "trustAuthOutgoing" : ndr_pack(outgoing)
821 ctx.local_samdb.add(rec)
824 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
825 "objectclass" : "user",
826 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
827 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
829 ctx.local_samdb.add(rec)
833 ctx.cleanup_old_join()
835 ctx.join_add_objects()
839 ctx.join_add_objects2()
840 ctx.join_provision_own_domain()
841 ctx.join_setup_trusts()
844 print "Join failed - cleaning up"
845 ctx.cleanup_old_join()
849 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
850 targetdir=None, domain=None, domain_critical_only=False):
853 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
855 lp.set("workgroup", ctx.domain_name)
856 print("workgroup is %s" % ctx.domain_name)
858 lp.set("realm", ctx.realm)
859 print("realm is %s" % ctx.realm)
861 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
863 # setup some defaults for accounts that should be replicated to this RODC
864 ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
865 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
866 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
867 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
868 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
869 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
871 mysid = ctx.get_mysid()
872 admin_dn = "<SID=%s>" % mysid
873 ctx.managedby = admin_dn
875 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
876 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
877 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
879 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
880 "RestrictedKrbHost/%s" % ctx.dnshostname ])
882 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
883 ctx.secure_channel_type = misc.SEC_CHAN_RODC
885 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
886 drsuapi.DRSUAPI_DRS_PER_SYNC |
887 drsuapi.DRSUAPI_DRS_GET_ANC |
888 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
889 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
890 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
891 ctx.domain_replica_flags = ctx.replica_flags
892 if domain_critical_only:
893 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
898 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
901 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
902 targetdir=None, domain=None, domain_critical_only=False):
904 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
906 lp.set("workgroup", ctx.domain_name)
907 print("workgroup is %s" % ctx.domain_name)
909 lp.set("realm", ctx.realm)
910 print("realm is %s" % ctx.realm)
912 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
914 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
915 ctx.secure_channel_type = misc.SEC_CHAN_BDC
917 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
918 drsuapi.DRSUAPI_DRS_INIT_SYNC |
919 drsuapi.DRSUAPI_DRS_PER_SYNC |
920 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
921 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
922 ctx.domain_replica_flags = ctx.replica_flags
923 if domain_critical_only:
924 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
927 print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
929 def join_subdomain(server=None, creds=None, lp=None, site=None, netbios_name=None,
930 targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None):
932 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain)
934 ctx.parent_domain_name = ctx.domain_name
935 ctx.domain_name = netbios_domain
936 ctx.realm = dnsdomain
937 ctx.parent_dnsdomain = ctx.dnsdomain
938 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
939 ctx.dnsdomain = dnsdomain
940 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
941 ctx.naming_master = ctx.get_naming_master()
942 if ctx.naming_master != ctx.server:
943 print("Reconnecting to naming master %s" % ctx.naming_master)
944 ctx.server = ctx.naming_master
945 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
946 session_info=system_session(),
947 credentials=ctx.creds, lp=ctx.lp)
949 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
950 ctx.domsid = str(security.random_sid())
952 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
953 ctx.trustdom_pass = samba.generate_random_password(128, 128)
955 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
957 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
958 ctx.secure_channel_type = misc.SEC_CHAN_BDC
960 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
961 drsuapi.DRSUAPI_DRS_INIT_SYNC |
962 drsuapi.DRSUAPI_DRS_PER_SYNC |
963 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
964 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
965 ctx.domain_replica_flags = ctx.replica_flags
968 print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)