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
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):
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:
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)
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.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
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")
349 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
350 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
351 raise RuntimeError("DsAddEntry failed")
354 def join_add_ntdsdsa(ctx):
355 '''add the ntdsdsa object'''
356 # FIXME: the partition (NC) assignment has to be made dynamic
357 print "Adding %s" % ctx.ntds_dn
360 "objectclass" : "nTDSDSA",
361 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
362 "dMDLocation" : ctx.schema_dn}
365 # the local subdomain NC doesn't exist at this time
366 # so we have to add the base_dn NC later
367 nc_list = [ ctx.config_dn, ctx.schema_dn ]
369 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
371 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
372 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
374 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003 and not ctx.subdomain:
375 rec["msDS-HasDomainNCs"] = ctx.base_dn
378 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
379 rec["msDS-HasFullReplicaNCs"] = nc_list
380 rec["options"] = "37"
381 ctx.samdb.add(rec, ["rodc_join:1:1"])
383 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
384 rec["HasMasterNCs"] = nc_list
385 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
386 rec["msDS-HasMasterNCs"] = nc_list
388 rec["invocationId"] = ndr_pack(ctx.invocation_id)
390 ctx.samdb.add(rec, ['relax:0'])
394 # find the GUID of our NTDS DN
395 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
396 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
399 def join_modify_ntdsdsa(ctx):
400 '''modify the ntdsdsa object to add local partitions'''
401 print "Modifying %s using system privileges" % ctx.ntds_dn
403 # this works around the Enterprise Admins ACL on the NTDSDSA object
404 system_session_info = system_session()
405 ctx.samdb.set_session_info(system_session_info)
408 m.dn = ldb.Dn(ctx.samdb, ctx.ntds_dn)
409 m["HasMasterNCs"] = ldb.MessageElement(ctx.base_dn, ldb.FLAG_MOD_ADD, "HasMasterNCs")
410 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
411 m["msDS-HasDomainNCs"] = ldb.MessageElement(ctx.base_dn, ldb.FLAG_MOD_ADD, "msDS-HasDomainNCs")
412 m["msDS-HasMasterNCs"] = ldb.MessageElement(ctx.base_dn, ldb.FLAG_MOD_ADD, "msDS-HasMasterNCs")
413 ctx.samdb.modify(m, controls=['relax:0'])
415 def join_add_objects(ctx):
416 '''add the various objects needed for the join'''
418 print "Adding %s" % ctx.acct_dn
421 "objectClass": "computer",
422 "displayname": ctx.samname,
423 "samaccountname" : ctx.samname,
424 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
425 "dnshostname" : ctx.dnshostname}
426 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
427 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
429 rec["managedby"] = ctx.managedby
430 if ctx.never_reveal_sid:
431 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
433 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
437 ctx.add_krbtgt_account()
439 print "Adding %s" % ctx.server_dn
442 "objectclass" : "server",
443 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
444 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
445 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
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}
470 if ctx.topology_dn and ctx.acct_dn:
471 print "Adding %s" % ctx.topology_dn
473 "dn" : ctx.topology_dn,
474 "objectclass" : "msDFSR-Member",
475 "msDFSR-ComputerReference" : ctx.acct_dn,
476 "serverReference" : ctx.ntds_dn}
480 print "Adding SPNs to %s" % ctx.acct_dn
482 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
483 for i in range(len(ctx.SPNs)):
484 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
485 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
487 "servicePrincipalName")
490 print "Setting account password for %s" % ctx.samname
491 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ldb.binary_encode(ctx.samname),
493 force_change_at_next_login=False,
494 username=ctx.samname)
495 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-keyVersionNumber"])
496 ctx.key_version_number = int(res[0]["msDS-keyVersionNumber"][0])
498 print("Enabling account")
500 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
501 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
502 ldb.FLAG_MOD_REPLACE,
503 "userAccountControl")
507 def join_add_objects2(ctx):
508 '''add the various objects needed for the join, for subdomains post replication'''
510 if not ctx.subdomain:
513 print "Adding %s" % ctx.partition_dn
514 # NOTE: windows sends a ntSecurityDescriptor here, we
517 "dn" : ctx.partition_dn,
518 "objectclass" : "crossRef",
519 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
520 "nCName" : ctx.base_dn,
521 "nETBIOSName" : ctx.domain_name,
522 "dnsRoot": ctx.dnsdomain,
523 "trustParent" : ctx.parent_partition_dn,
524 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
525 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
526 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
530 def join_provision(ctx):
531 '''provision the local SAM'''
533 print "Calling bare provision"
535 logger = logging.getLogger("provision")
536 logger.addHandler(logging.StreamHandler(sys.stdout))
537 smbconf = ctx.lp.configfile
539 presult = provision(logger, system_session(), None,
540 smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
541 realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
542 schemadn=ctx.schema_dn,
543 configdn=ctx.config_dn,
544 serverdn=ctx.server_dn, domain=ctx.domain_name,
545 hostname=ctx.myname, domainsid=ctx.domsid,
546 machinepass=ctx.acct_pass, serverrole="domain controller",
547 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid)
548 print "Provision OK for domain DN %s" % presult.domaindn
549 ctx.local_samdb = presult.samdb
551 ctx.paths = presult.paths
552 ctx.names = presult.names
554 def join_provision_own_domain(ctx):
555 '''provision the local SAM'''
557 # we now operate exclusively on the local database, which
558 # we need to reopen in order to get the newly created schema
559 print("Reconnecting to local samdb")
560 ctx.samdb = SamDB(url=ctx.local_samdb.url,
561 session_info=system_session(),
562 lp=ctx.local_samdb.lp,
564 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
565 ctx.local_samdb = ctx.samdb
567 print("Finding domain GUID from ncName")
568 res = ctx.samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
569 controls=["extended_dn:1:1"])
570 domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
571 print("Got domain GUID %s" % domguid)
574 ctx.join_add_ntdsdsa()
576 print("Calling own domain provision")
578 logger = logging.getLogger("provision")
579 logger.addHandler(logging.StreamHandler(sys.stdout))
581 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
583 presult = provision_fill(ctx.local_samdb, secrets_ldb,
584 logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
586 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
587 machinepass=ctx.acct_pass, serverrole="domain controller",
588 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6)
589 print("Provision OK for domain %s" % ctx.names.dnsdomain)
592 def join_replicate(ctx):
593 '''replicate the SAM'''
595 print "Starting replication"
596 ctx.local_samdb.transaction_start()
598 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
599 if ctx.ntds_guid is None:
600 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
602 destination_dsa_guid = ctx.ntds_guid
605 repl_creds = Credentials()
606 repl_creds.guess(ctx.lp)
607 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
608 repl_creds.set_username(ctx.samname)
609 repl_creds.set_password(ctx.acct_pass)
611 repl_creds = ctx.creds
613 binding_options = "seal"
614 if int(ctx.lp.get("log level")) >= 5:
615 binding_options += ",print"
616 repl = drs_utils.drs_Replicate(
617 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
618 ctx.lp, repl_creds, ctx.local_samdb)
620 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
621 destination_dsa_guid, schema=True, rodc=ctx.RODC,
622 replica_flags=ctx.replica_flags)
623 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
624 destination_dsa_guid, rodc=ctx.RODC,
625 replica_flags=ctx.replica_flags)
626 if not ctx.subdomain:
627 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
628 destination_dsa_guid, rodc=ctx.RODC,
629 replica_flags=ctx.domain_replica_flags)
631 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
632 destination_dsa_guid,
633 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
634 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
635 destination_dsa_guid,
636 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
638 print "Committing SAM database"
640 ctx.local_samdb.transaction_cancel()
643 ctx.local_samdb.transaction_commit()
646 def join_finalise(ctx):
647 '''finalise the join, mark us synchronised and setup secrets db'''
649 print "Setting isSynchronized and dsServiceName"
651 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
652 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
653 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
654 ldb.FLAG_MOD_REPLACE, "dsServiceName")
655 ctx.local_samdb.modify(m)
660 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
662 print "Setting up secrets database"
663 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
665 dnsdomain=ctx.dnsdomain,
666 netbiosname=ctx.myname,
667 domainsid=security.dom_sid(ctx.domsid),
668 machinepass=ctx.acct_pass,
669 secure_channel_type=ctx.secure_channel_type,
670 key_version_number=ctx.key_version_number)
672 def join_setup_trusts(ctx):
673 '''provision the local SAM'''
675 def arcfour_encrypt(key, data):
676 from Crypto.Cipher import ARC4
678 return c.encrypt(data)
680 def string_to_array(string):
681 blob = [0] * len(string)
683 for i in range(len(string)):
684 blob[i] = ord(string[i])
688 print "Setup domain trusts with server %s" % ctx.server
689 binding_options = "" # why doesn't signing work gere? w2k8r2 claims no session key
690 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
693 objectAttr = lsa.ObjectAttribute()
694 objectAttr.sec_qos = lsa.QosInfo()
696 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
697 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
699 info = lsa.TrustDomainInfoInfoEx()
700 info.domain_name.string = ctx.dnsdomain
701 info.netbios_name.string = ctx.domain_name
702 info.sid = security.dom_sid(ctx.domsid)
703 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
704 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
705 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
708 oldname = lsa.String()
709 oldname.string = ctx.dnsdomain
710 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
711 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
712 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
713 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
717 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
719 clear_value = drsblobs.AuthInfoClear()
720 clear_value.size = len(password_blob)
721 clear_value.password = password_blob
723 clear_authentication_information = drsblobs.AuthenticationInformation()
724 clear_authentication_information.LastUpdateTime = 0
725 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
726 clear_authentication_information.AuthInfo = clear_value
728 version_value = drsblobs.AuthInfoVersion()
729 version_value.version = 1
731 version = drsblobs.AuthenticationInformation()
732 version.LastUpdateTime = 0
733 version.AuthType = lsa.TRUST_AUTH_TYPE_VERSION
734 version.AuthInfo = version_value
736 authentication_information_array = drsblobs.AuthenticationInformationArray()
737 authentication_information_array.count = 2
738 authentication_information_array.array = [clear_authentication_information, version]
740 outgoing = drsblobs.trustAuthInOutBlob()
742 outgoing.current = authentication_information_array
744 trustpass = drsblobs.trustDomainPasswords()
745 confounder = [3] * 512
748 confounder[i] = random.randint(0, 255)
750 trustpass.confounder = confounder
752 trustpass.outgoing = outgoing
753 trustpass.incoming = outgoing
755 trustpass_blob = ndr_pack(trustpass)
757 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
759 auth_blob = lsa.DATA_BUF2()
760 auth_blob.size = len(encrypted_trustpass)
761 auth_blob.data = string_to_array(encrypted_trustpass)
763 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
764 auth_info.auth_blob = auth_blob
766 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
769 security.SEC_STD_DELETE)
772 "dn" : "cn=%s,cn=system,%s" % (ctx.parent_dnsdomain, ctx.base_dn),
773 "objectclass" : "trustedDomain",
774 "trustType" : str(info.trust_type),
775 "trustAttributes" : str(info.trust_attributes),
776 "trustDirection" : str(info.trust_direction),
777 "flatname" : ctx.parent_domain_name,
778 "trustPartner" : ctx.parent_dnsdomain,
779 "trustAuthIncoming" : ndr_pack(outgoing),
780 "trustAuthOutgoing" : ndr_pack(outgoing)
782 ctx.local_samdb.add(rec)
785 "dn" : "cn=%s$,cn=users,%s" % (ctx.parent_domain_name, ctx.base_dn),
786 "objectclass" : "user",
787 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
788 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
790 ctx.local_samdb.add(rec)
794 ctx.cleanup_old_join()
796 ctx.join_add_objects()
798 ctx.join_add_objects2()
801 ctx.join_provision_own_domain()
802 ctx.join_setup_trusts()
803 ctx.join_modify_ntdsdsa()
806 print "Join failed - cleaning up"
807 #ctx.cleanup_old_join()
811 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
812 targetdir=None, domain=None, domain_critical_only=False):
815 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
817 lp.set("workgroup", ctx.domain_name)
818 print("workgroup is %s" % ctx.domain_name)
820 lp.set("realm", ctx.realm)
821 print("realm is %s" % ctx.realm)
823 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
825 # setup some defaults for accounts that should be replicated to this RODC
826 ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
827 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
828 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
829 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
830 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
831 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
833 mysid = ctx.get_mysid()
834 admin_dn = "<SID=%s>" % mysid
835 ctx.managedby = admin_dn
837 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
838 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
839 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
841 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
842 "RestrictedKrbHost/%s" % ctx.dnshostname ])
844 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
845 ctx.secure_channel_type = misc.SEC_CHAN_RODC
847 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
848 drsuapi.DRSUAPI_DRS_PER_SYNC |
849 drsuapi.DRSUAPI_DRS_GET_ANC |
850 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
851 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
852 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
853 ctx.domain_replica_flags = ctx.replica_flags
854 if domain_critical_only:
855 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
860 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
863 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
864 targetdir=None, domain=None, domain_critical_only=False):
866 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
868 lp.set("workgroup", ctx.domain_name)
869 print("workgroup is %s" % ctx.domain_name)
871 lp.set("realm", ctx.realm)
872 print("realm is %s" % ctx.realm)
874 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
876 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
877 ctx.secure_channel_type = misc.SEC_CHAN_BDC
879 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
880 drsuapi.DRSUAPI_DRS_INIT_SYNC |
881 drsuapi.DRSUAPI_DRS_PER_SYNC |
882 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
883 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
884 ctx.domain_replica_flags = ctx.replica_flags
885 if domain_critical_only:
886 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
889 print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
891 def join_subdomain(server=None, creds=None, lp=None, site=None, netbios_name=None,
892 targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None):
894 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain)
896 ctx.parent_domain_name = ctx.domain_name
897 ctx.domain_name = netbios_domain
898 ctx.realm = dnsdomain
899 ctx.parent_dnsdomain = ctx.dnsdomain
900 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
901 ctx.dnsdomain = dnsdomain
902 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
903 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
904 ctx.domsid = str(security.random_sid())
906 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
907 ctx.trustdom_pass = samba.generate_random_password(128, 128)
909 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
911 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
912 ctx.secure_channel_type = misc.SEC_CHAN_BDC
914 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
915 drsuapi.DRSUAPI_DRS_INIT_SYNC |
916 drsuapi.DRSUAPI_DRS_PER_SYNC |
917 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
918 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
919 ctx.domain_replica_flags = ctx.replica_flags
922 print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)