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
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.invocation_id = misc.GUID(str(uuid.uuid4()))
88 ctx.dc_ntds_dn = ctx.get_dsServiceName()
89 ctx.dc_dnsHostName = ctx.get_dnsHostName()
90 ctx.behavior_version = ctx.get_behavior_version()
92 ctx.acct_pass = samba.generate_random_password(32, 40)
94 # work out the DNs of all the objects we will be adding
95 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
96 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
97 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
98 if ctx.dn_exists(topology_base):
99 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
101 ctx.topology_dn = None
103 ctx.dnsdomain = ctx.samdb.domain_dns_name()
104 ctx.dnsforest = ctx.samdb.forest_dns_name()
105 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
107 ctx.realm = ctx.dnsdomain
109 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
113 ctx.SPNs = [ "HOST/%s" % ctx.myname,
114 "HOST/%s" % ctx.dnshostname,
115 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
117 # these elements are optional
118 ctx.never_reveal_sid = None
119 ctx.reveal_sid = None
120 ctx.connection_dn = None
125 ctx.subdomain = False
129 def del_noerror(ctx, dn, recursive=False):
132 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
136 ctx.del_noerror(r.dn, recursive=True)
139 print "Deleted %s" % dn
143 def cleanup_old_join(ctx):
144 '''remove any DNs from a previous join'''
146 # find the krbtgt link
147 print("checking samaccountname")
151 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
152 expression='samAccountName=%s' % ldb.binary_encode(ctx.samname),
153 attrs=["msDS-krbTgtLink"])
155 ctx.del_noerror(res[0].dn, recursive=True)
156 if ctx.connection_dn is not None:
157 ctx.del_noerror(ctx.connection_dn)
158 if ctx.krbtgt_dn is not None:
159 ctx.del_noerror(ctx.krbtgt_dn)
160 ctx.del_noerror(ctx.ntds_dn)
161 ctx.del_noerror(ctx.server_dn, recursive=True)
163 ctx.del_noerror(ctx.topology_dn)
165 ctx.del_noerror(ctx.partition_dn)
167 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
168 ctx.del_noerror(ctx.new_krbtgt_dn)
171 binding_options = "sign"
172 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
175 objectAttr = lsa.ObjectAttribute()
176 objectAttr.sec_qos = lsa.QosInfo()
178 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
179 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
182 name.string = ctx.realm
183 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
185 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
188 name.string = ctx.domain_name
189 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
191 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
196 def find_dc(ctx, domain):
197 '''find a writeable DC for the given domain'''
199 ctx.cldap_ret = ctx.net.finddc(domain, nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
201 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
202 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
203 ctx.site = ctx.cldap_ret.client_site
204 return ctx.cldap_ret.pdc_dns_name
207 def get_dsServiceName(ctx):
208 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
209 return res[0]["dsServiceName"][0]
211 def get_behavior_version(ctx):
212 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
213 if "msDS-Behavior-Version" in res[0]:
214 return int(res[0]["msDS-Behavior-Version"][0])
216 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
218 def get_dnsHostName(ctx):
219 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
220 return res[0]["dnsHostName"][0]
222 def get_domain_name(ctx):
223 '''get netbios name of the domain from the partitions record'''
224 partitions_dn = ctx.samdb.get_partitions_dn()
225 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
226 expression='ncName=%s' % ctx.samdb.get_default_basedn())
227 return res[0]["nETBIOSName"][0]
229 def get_parent_partition_dn(ctx):
230 '''get the parent domain partition DN from parent DNS name'''
231 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
232 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
233 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
234 return str(res[0].dn)
237 '''get the SID of the connected user. Only works with w2k8 and later,
238 so only used for RODC join'''
239 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
240 binsid = res[0]["tokenGroups"][0]
241 return ctx.samdb.schema_format_value("objectSID", binsid)
243 def dn_exists(ctx, dn):
244 '''check if a DN exists'''
246 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
247 except ldb.LdbError, (enum, estr):
248 if enum == ldb.ERR_NO_SUCH_OBJECT:
253 def add_krbtgt_account(ctx):
254 '''RODCs need a special krbtgt account'''
255 print "Adding %s" % ctx.krbtgt_dn
257 "dn" : ctx.krbtgt_dn,
258 "objectclass" : "user",
259 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
260 samba.dsdb.UF_ACCOUNTDISABLE),
261 "showinadvancedviewonly" : "TRUE",
262 "description" : "krbtgt for %s" % ctx.samname}
263 ctx.samdb.add(rec, ["rodc_join:1:1"])
265 # now we need to search for the samAccountName attribute on the krbtgt DN,
266 # as this will have been magically set to the krbtgt number
267 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
268 ctx.krbtgt_name = res[0]["samAccountName"][0]
270 print "Got krbtgt_name=%s" % ctx.krbtgt_name
273 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
274 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
275 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
278 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
279 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
280 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
282 def drsuapi_connect(ctx):
283 '''make a DRSUAPI connection to the server'''
284 binding_options = "seal"
285 if int(ctx.lp.get("log level")) >= 5:
286 binding_options += ",print"
287 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
288 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
289 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
291 def create_tmp_samdb(ctx):
292 '''create a temporary samdb object for schema queries'''
293 ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
294 schemadn=ctx.schema_dn)
295 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
296 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
298 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
300 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
301 '''build a DsReplicaAttributeCtr object'''
302 r = drsuapi.DsReplicaAttribute()
303 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
307 def DsAddEntry(ctx, rec):
308 '''add a record via the DRSUAPI DsAddEntry call'''
309 if ctx.drsuapi is None:
310 ctx.drsuapi_connect()
311 if ctx.tmp_samdb is None:
312 ctx.create_tmp_samdb()
314 id = drsuapi.DsReplicaObjectIdentifier()
321 if not isinstance(rec[a], list):
325 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
328 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
329 attribute_ctr.num_attributes = len(attrs)
330 attribute_ctr.attributes = attrs
332 object = drsuapi.DsReplicaObject()
333 object.identifier = id
334 object.attribute_ctr = attribute_ctr
336 first_object = drsuapi.DsReplicaObjectListItem()
337 first_object.object = object
339 req2 = drsuapi.DsAddEntryRequest2()
340 req2.first_object = first_object
342 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
344 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
345 if ctr.err_data.status != (0, 'WERR_OK'):
346 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
347 ctr.err_data.info.extended_err))
348 raise RuntimeError("DsAddEntry failed")
350 def join_add_ntdsdsa(ctx):
351 '''add the ntdsdsa object'''
352 # FIXME: the partition (NC) assignment has to be made dynamic
353 print "Adding %s" % ctx.ntds_dn
356 "objectclass" : "nTDSDSA",
357 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
358 "dMDLocation" : ctx.schema_dn}
361 # the local subdomain NC doesn't exist at this time
362 # so we have to add the base_dn NC later
363 nc_list = [ ctx.config_dn, ctx.schema_dn ]
365 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
367 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
368 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
370 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003 and not ctx.subdomain:
371 rec["msDS-HasDomainNCs"] = ctx.base_dn
374 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
375 rec["msDS-HasFullReplicaNCs"] = nc_list
376 rec["options"] = "37"
377 ctx.samdb.add(rec, ["rodc_join:1:1"])
379 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
380 rec["HasMasterNCs"] = nc_list
381 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
382 rec["msDS-HasMasterNCs"] = nc_list
384 rec["invocationId"] = ndr_pack(ctx.invocation_id)
386 ctx.samdb.add(rec, ['relax:0'])
390 # find the GUID of our NTDS DN
391 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
392 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
395 def join_modify_ntdsdsa(ctx):
396 '''modify the ntdsdsa object to add local partitions'''
397 print "Modifying %s using system privileges" % ctx.ntds_dn
399 # this works around the Enterprise Admins ACL on the NTDSDSA object
400 system_session_info = system_session()
401 ctx.samdb.set_session_info(system_session_info)
404 m.dn = ldb.Dn(ctx.samdb, ctx.ntds_dn)
405 m["HasMasterNCs"] = ldb.MessageElement(ctx.base_dn, ldb.FLAG_MOD_ADD, "HasMasterNCs")
406 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
407 m["msDS-HasDomainNCs"] = ldb.MessageElement(ctx.base_dn, ldb.FLAG_MOD_ADD, "msDS-HasDomainNCs")
408 m["msDS-HasMasterNCs"] = ldb.MessageElement(ctx.base_dn, ldb.FLAG_MOD_ADD, "msDS-HasMasterNCs")
409 ctx.samdb.modify(m, controls=['relax:0'])
411 def join_add_objects(ctx):
412 '''add the various objects needed for the join'''
414 print "Adding %s" % ctx.acct_dn
417 "objectClass": "computer",
418 "displayname": ctx.samname,
419 "samaccountname" : ctx.samname,
420 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
421 "dnshostname" : ctx.dnshostname}
422 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
423 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
425 rec["managedby"] = ctx.managedby
426 if ctx.never_reveal_sid:
427 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
429 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
433 ctx.add_krbtgt_account()
435 print "Adding %s" % ctx.server_dn
438 "objectclass" : "server",
439 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
440 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
441 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
442 "dnsHostName" : ctx.dnshostname}
445 rec["serverReference"] = ctx.acct_dn
450 # the rest is done after replication
454 ctx.join_add_ntdsdsa()
456 if ctx.connection_dn is not None:
457 print "Adding %s" % ctx.connection_dn
459 "dn" : ctx.connection_dn,
460 "objectclass" : "nTDSConnection",
461 "enabledconnection" : "TRUE",
463 "fromServer" : ctx.dc_ntds_dn}
466 if ctx.topology_dn and ctx.acct_dn:
467 print "Adding %s" % ctx.topology_dn
469 "dn" : ctx.topology_dn,
470 "objectclass" : "msDFSR-Member",
471 "msDFSR-ComputerReference" : ctx.acct_dn,
472 "serverReference" : ctx.ntds_dn}
476 print "Adding SPNs to %s" % ctx.acct_dn
478 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
479 for i in range(len(ctx.SPNs)):
480 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
481 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
483 "servicePrincipalName")
486 print "Setting account password for %s" % ctx.samname
487 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ldb.binary_encode(ctx.samname),
489 force_change_at_next_login=False,
490 username=ctx.samname)
491 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-keyVersionNumber"])
492 ctx.key_version_number = int(res[0]["msDS-keyVersionNumber"][0])
494 print("Enabling account")
496 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
497 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
498 ldb.FLAG_MOD_REPLACE,
499 "userAccountControl")
503 def join_add_objects2(ctx):
504 '''add the various objects needed for the join, for subdomains post replication'''
506 if not ctx.subdomain:
509 print "Adding %s" % ctx.partition_dn
510 # NOTE: windows sends a ntSecurityDescriptor here, we
513 "dn" : ctx.partition_dn,
514 "objectclass" : "crossRef",
515 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
516 "nCName" : ctx.base_dn,
517 "nETBIOSName" : ctx.domain_name,
518 "dnsRoot": ctx.dnsdomain,
519 "trustParent" : ctx.parent_partition_dn,
520 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
521 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
522 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
526 def join_provision(ctx):
527 '''provision the local SAM'''
529 print "Calling bare provision"
531 logger = logging.getLogger("provision")
532 logger.addHandler(logging.StreamHandler(sys.stdout))
533 smbconf = ctx.lp.configfile
535 presult = provision(logger, system_session(), None,
536 smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
537 realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
538 schemadn=ctx.schema_dn,
539 configdn=ctx.config_dn,
540 serverdn=ctx.server_dn, domain=ctx.domain_name,
541 hostname=ctx.myname, domainsid=ctx.domsid,
542 domainguid=ctx.domguid,
543 machinepass=ctx.acct_pass, serverrole="domain controller",
544 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid)
545 print "Provision OK for domain DN %s" % presult.domaindn
546 ctx.local_samdb = presult.samdb
548 ctx.paths = presult.paths
549 ctx.names = presult.names
551 def join_provision_own_domain(ctx):
552 '''provision the local SAM'''
554 # we now operate exclusively on the local database, which
555 # we need to reopen in order to get the newly created schema
556 print("Reconnecting to local samdb")
557 ctx.samdb = SamDB(url=ctx.local_samdb.url,
558 session_info=system_session(),
559 lp=ctx.local_samdb.lp,
561 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
562 ctx.local_samdb = ctx.samdb
564 ctx.join_add_ntdsdsa()
566 print("Calling own domain provision")
568 logger = logging.getLogger("provision")
569 logger.addHandler(logging.StreamHandler(sys.stdout))
571 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
573 presult = provision_fill(ctx.local_samdb, secrets_ldb,
574 logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
575 domainguid=ctx.domguid,
576 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
577 machinepass=ctx.acct_pass, serverrole="domain controller",
578 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6)
579 print("Provision OK for domain %s" % ctx.names.dnsdomain)
582 def join_replicate(ctx):
583 '''replicate the SAM'''
585 print "Starting replication"
586 ctx.local_samdb.transaction_start()
588 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
589 if ctx.ntds_guid is None:
590 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
592 destination_dsa_guid = ctx.ntds_guid
595 repl_creds = Credentials()
596 repl_creds.guess(ctx.lp)
597 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
598 repl_creds.set_username(ctx.samname)
599 repl_creds.set_password(ctx.acct_pass)
601 repl_creds = ctx.creds
603 binding_options = "seal"
604 if int(ctx.lp.get("log level")) >= 5:
605 binding_options += ",print"
606 repl = drs_utils.drs_Replicate(
607 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
608 ctx.lp, repl_creds, ctx.local_samdb)
610 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
611 destination_dsa_guid, schema=True, rodc=ctx.RODC,
612 replica_flags=ctx.replica_flags)
613 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
614 destination_dsa_guid, rodc=ctx.RODC,
615 replica_flags=ctx.replica_flags)
616 if not ctx.subdomain:
617 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
618 destination_dsa_guid, rodc=ctx.RODC,
619 replica_flags=ctx.domain_replica_flags)
621 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
622 destination_dsa_guid,
623 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
624 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
625 destination_dsa_guid,
626 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
628 print "Committing SAM database"
630 ctx.local_samdb.transaction_cancel()
633 ctx.local_samdb.transaction_commit()
636 def join_finalise(ctx):
637 '''finalise the join, mark us synchronised and setup secrets db'''
639 print "Setting isSynchronized and dsServiceName"
641 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
642 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
643 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
644 ldb.FLAG_MOD_REPLACE, "dsServiceName")
645 ctx.local_samdb.modify(m)
650 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
652 print "Setting up secrets database"
653 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
655 dnsdomain=ctx.dnsdomain,
656 netbiosname=ctx.myname,
657 domainsid=security.dom_sid(ctx.domsid),
658 machinepass=ctx.acct_pass,
659 secure_channel_type=ctx.secure_channel_type,
660 key_version_number=ctx.key_version_number)
662 def join_setup_trusts(ctx):
663 '''provision the local SAM'''
665 def arcfour_encrypt(key, data):
666 from Crypto.Cipher import ARC4
668 return c.encrypt(data)
670 def string_to_array(string):
671 blob = [0] * len(string)
673 for i in range(len(string)):
674 blob[i] = ord(string[i])
678 print "Setup domain trusts with server %s" % ctx.server
679 binding_options = "" # why doesn't signing work gere? w2k8r2 claims no session key
680 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
683 objectAttr = lsa.ObjectAttribute()
684 objectAttr.sec_qos = lsa.QosInfo()
686 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
687 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
689 info = lsa.TrustDomainInfoInfoEx()
690 info.domain_name.string = ctx.dnsdomain
691 info.netbios_name.string = ctx.domain_name
692 info.sid = security.dom_sid(ctx.domsid)
693 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
694 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
695 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
698 oldname = lsa.String()
699 oldname.string = ctx.dnsdomain
700 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
701 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
702 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
703 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
707 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
709 clear_value = drsblobs.AuthInfoClear()
710 clear_value.size = len(password_blob)
711 clear_value.password = password_blob
713 clear_authentication_information = drsblobs.AuthenticationInformation()
714 clear_authentication_information.LastUpdateTime = 0
715 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
716 clear_authentication_information.AuthInfo = clear_value
718 version_value = drsblobs.AuthInfoVersion()
719 version_value.version = 1
721 version = drsblobs.AuthenticationInformation()
722 version.LastUpdateTime = 0
723 version.AuthType = lsa.TRUST_AUTH_TYPE_VERSION
724 version.AuthInfo = version_value
726 authentication_information_array = drsblobs.AuthenticationInformationArray()
727 authentication_information_array.count = 2
728 authentication_information_array.array = [clear_authentication_information, version]
730 outgoing = drsblobs.trustAuthInOutBlob()
732 outgoing.current = authentication_information_array
734 trustpass = drsblobs.trustDomainPasswords()
735 confounder = [3] * 512
738 confounder[i] = random.randint(0, 255)
740 trustpass.confounder = confounder
742 trustpass.outgoing = outgoing
743 trustpass.incoming = outgoing
745 trustpass_blob = ndr_pack(trustpass)
747 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
749 auth_blob = lsa.DATA_BUF2()
750 auth_blob.size = len(encrypted_trustpass)
751 auth_blob.data = string_to_array(encrypted_trustpass)
753 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
754 auth_info.auth_blob = auth_blob
756 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
759 security.SEC_STD_DELETE)
762 "dn" : "cn=%s,cn=system,%s" % (ctx.parent_dnsdomain, ctx.base_dn),
763 "objectclass" : "trustedDomain",
764 "trustType" : str(info.trust_type),
765 "trustAttributes" : str(info.trust_attributes),
766 "trustDirection" : str(info.trust_direction),
767 "flatname" : ctx.parent_domain_name,
768 "trustPartner" : ctx.parent_dnsdomain,
769 "trustAuthIncoming" : ndr_pack(outgoing),
770 "trustAuthOutgoing" : ndr_pack(outgoing)
772 ctx.local_samdb.add(rec)
775 "dn" : "cn=%s$,cn=users,%s" % (ctx.parent_domain_name, ctx.base_dn),
776 "objectclass" : "user",
777 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
778 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
780 ctx.local_samdb.add(rec)
784 ctx.cleanup_old_join()
786 ctx.join_add_objects()
788 ctx.join_add_objects2()
791 ctx.join_provision_own_domain()
792 ctx.join_setup_trusts()
793 ctx.join_modify_ntdsdsa()
796 print "Join failed - cleaning up"
797 #ctx.cleanup_old_join()
801 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
802 targetdir=None, domain=None, domain_critical_only=False):
805 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
807 lp.set("workgroup", ctx.domain_name)
808 print("workgroup is %s" % ctx.domain_name)
810 lp.set("realm", ctx.realm)
811 print("realm is %s" % ctx.realm)
813 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
815 # setup some defaults for accounts that should be replicated to this RODC
816 ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
817 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
818 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
819 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
820 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
821 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
823 mysid = ctx.get_mysid()
824 admin_dn = "<SID=%s>" % mysid
825 ctx.managedby = admin_dn
827 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
828 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
829 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
831 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
832 "RestrictedKrbHost/%s" % ctx.dnshostname ])
834 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
835 ctx.secure_channel_type = misc.SEC_CHAN_RODC
837 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
838 drsuapi.DRSUAPI_DRS_PER_SYNC |
839 drsuapi.DRSUAPI_DRS_GET_ANC |
840 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
841 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
842 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
843 ctx.domain_replica_flags = ctx.replica_flags
844 if domain_critical_only:
845 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
850 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
853 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
854 targetdir=None, domain=None, domain_critical_only=False):
856 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
858 lp.set("workgroup", ctx.domain_name)
859 print("workgroup is %s" % ctx.domain_name)
861 lp.set("realm", ctx.realm)
862 print("realm is %s" % ctx.realm)
864 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
866 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
867 ctx.secure_channel_type = misc.SEC_CHAN_BDC
869 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
870 drsuapi.DRSUAPI_DRS_INIT_SYNC |
871 drsuapi.DRSUAPI_DRS_PER_SYNC |
872 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
873 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
874 ctx.domain_replica_flags = ctx.replica_flags
875 if domain_critical_only:
876 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
879 print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
881 def join_subdomain(server=None, creds=None, lp=None, site=None, netbios_name=None,
882 targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None):
884 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain)
886 ctx.parent_domain_name = ctx.domain_name
887 ctx.domain_name = netbios_domain
888 ctx.realm = dnsdomain
889 ctx.parent_dnsdomain = ctx.dnsdomain
890 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
891 ctx.dnsdomain = dnsdomain
892 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
893 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
894 ctx.domsid = str(security.random_sid())
895 ctx.domguid = str(uuid.uuid4())
897 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
898 ctx.trustdom_pass = samba.generate_random_password(128, 128)
900 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
902 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
903 ctx.secure_channel_type = misc.SEC_CHAN_BDC
905 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
906 drsuapi.DRSUAPI_DRS_INIT_SYNC |
907 drsuapi.DRSUAPI_DRS_PER_SYNC |
908 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
909 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
910 ctx.domain_replica_flags = ctx.replica_flags
913 print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)