2 # Copyright Andrew Tridgell 2010
3 # Copyright Andrew Bartlett 2010
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 """Joining a domain."""
21 from samba.auth import system_session
22 from samba.samdb import SamDB
23 from samba import gensec, Ldb, drs_utils
24 import ldb, samba, sys, uuid
25 from samba.ndr import ndr_pack
26 from samba.dcerpc import security, drsuapi, misc, nbt, lsa, drsblobs
27 from samba.credentials import Credentials, DONT_USE_KERBEROS
28 from samba.provision import secretsdb_self_join, provision, provision_fill, FILL_DRS, FILL_SUBDOMAIN
29 from samba.schema import Schema
30 from samba.net import Net
36 # this makes debugging easier
37 talloc.enable_null_tracking()
39 class DCJoinException(Exception):
41 def __init__(self, msg):
42 super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
45 class dc_join(object):
46 '''perform a DC join'''
48 def __init__(ctx, server=None, creds=None, lp=None, site=None,
49 netbios_name=None, targetdir=None, domain=None,
50 machinepass=None, use_ntvfs=False):
54 ctx.netbios_name = netbios_name
55 ctx.targetdir = targetdir
56 ctx.use_ntvfs = use_ntvfs
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.samdb.get_dsServiceName()
90 ctx.dc_dnsHostName = ctx.get_dnsHostName()
91 ctx.behavior_version = ctx.get_behavior_version()
93 if machinepass is not None:
94 ctx.acct_pass = machinepass
96 ctx.acct_pass = samba.generate_random_password(32, 40)
98 # work out the DNs of all the objects we will be adding
99 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
100 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
101 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
102 if ctx.dn_exists(topology_base):
103 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
105 ctx.topology_dn = None
107 ctx.dnsdomain = ctx.samdb.domain_dns_name()
108 ctx.dnsforest = ctx.samdb.forest_dns_name()
109 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
111 ctx.realm = ctx.dnsdomain
113 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
117 ctx.SPNs = [ "HOST/%s" % ctx.myname,
118 "HOST/%s" % ctx.dnshostname,
119 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
121 # these elements are optional
122 ctx.never_reveal_sid = None
123 ctx.reveal_sid = None
124 ctx.connection_dn = None
129 ctx.subdomain = False
131 def del_noerror(ctx, dn, recursive=False):
134 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
138 ctx.del_noerror(r.dn, recursive=True)
141 print "Deleted %s" % dn
145 def cleanup_old_join(ctx):
146 '''remove any DNs from a previous join'''
148 # find the krbtgt link
149 print("checking sAMAccountName")
153 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
154 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
155 attrs=["msDS-krbTgtLink"])
157 ctx.del_noerror(res[0].dn, recursive=True)
158 if ctx.connection_dn is not None:
159 ctx.del_noerror(ctx.connection_dn)
160 if ctx.krbtgt_dn is not None:
161 ctx.del_noerror(ctx.krbtgt_dn)
162 ctx.del_noerror(ctx.ntds_dn)
163 ctx.del_noerror(ctx.server_dn, recursive=True)
165 ctx.del_noerror(ctx.topology_dn)
167 ctx.del_noerror(ctx.partition_dn)
169 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
170 ctx.del_noerror(ctx.new_krbtgt_dn)
173 binding_options = "sign"
174 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
177 objectAttr = lsa.ObjectAttribute()
178 objectAttr.sec_qos = lsa.QosInfo()
180 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
181 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
184 name.string = ctx.realm
185 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
187 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
190 name.string = ctx.forest_domain_name
191 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
193 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
198 def find_dc(ctx, domain):
199 '''find a writeable DC for the given domain'''
201 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
203 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
204 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
205 ctx.site = ctx.cldap_ret.client_site
206 return ctx.cldap_ret.pdc_dns_name
209 def get_behavior_version(ctx):
210 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
211 if "msDS-Behavior-Version" in res[0]:
212 return int(res[0]["msDS-Behavior-Version"][0])
214 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
216 def get_dnsHostName(ctx):
217 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
218 return res[0]["dnsHostName"][0]
220 def get_domain_name(ctx):
221 '''get netbios name of the domain from the partitions record'''
222 partitions_dn = ctx.samdb.get_partitions_dn()
223 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
224 expression='ncName=%s' % ctx.samdb.get_default_basedn())
225 return res[0]["nETBIOSName"][0]
227 def get_forest_domain_name(ctx):
228 '''get netbios name of the domain from the partitions record'''
229 partitions_dn = ctx.samdb.get_partitions_dn()
230 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
231 expression='ncName=%s' % ctx.samdb.get_root_basedn())
232 return res[0]["nETBIOSName"][0]
234 def get_parent_partition_dn(ctx):
235 '''get the parent domain partition DN from parent DNS name'''
236 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
237 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
238 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
239 return str(res[0].dn)
241 def get_naming_master(ctx):
242 '''get the parent domain partition DN from parent DNS name'''
243 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
244 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
245 if not 'fSMORoleOwner' in res[0]:
246 raise DCJoinException("Can't find naming master on partition DN %s" % ctx.partition_dn)
247 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
248 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
252 '''get the SID of the connected user. Only works with w2k8 and later,
253 so only used for RODC join'''
254 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
255 binsid = res[0]["tokenGroups"][0]
256 return ctx.samdb.schema_format_value("objectSID", binsid)
258 def dn_exists(ctx, dn):
259 '''check if a DN exists'''
261 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
262 except ldb.LdbError, (enum, estr):
263 if enum == ldb.ERR_NO_SUCH_OBJECT:
268 def add_krbtgt_account(ctx):
269 '''RODCs need a special krbtgt account'''
270 print "Adding %s" % ctx.krbtgt_dn
272 "dn" : ctx.krbtgt_dn,
273 "objectclass" : "user",
274 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
275 samba.dsdb.UF_ACCOUNTDISABLE),
276 "showinadvancedviewonly" : "TRUE",
277 "description" : "krbtgt for %s" % ctx.samname}
278 ctx.samdb.add(rec, ["rodc_join:1:1"])
280 # now we need to search for the samAccountName attribute on the krbtgt DN,
281 # as this will have been magically set to the krbtgt number
282 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
283 ctx.krbtgt_name = res[0]["samAccountName"][0]
285 print "Got krbtgt_name=%s" % ctx.krbtgt_name
288 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
289 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
290 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
293 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
294 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
295 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
297 def drsuapi_connect(ctx):
298 '''make a DRSUAPI connection to the naming master'''
299 binding_options = "seal"
300 if int(ctx.lp.get("log level")) >= 4:
301 binding_options += ",print"
302 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
303 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
304 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
306 def create_tmp_samdb(ctx):
307 '''create a temporary samdb object for schema queries'''
308 ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
309 schemadn=ctx.schema_dn)
310 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
311 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
313 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
315 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
316 '''build a DsReplicaAttributeCtr object'''
317 r = drsuapi.DsReplicaAttribute()
318 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
322 def DsAddEntry(ctx, recs):
323 '''add a record via the DRSUAPI DsAddEntry call'''
324 if ctx.drsuapi is None:
325 ctx.drsuapi_connect()
326 if ctx.tmp_samdb is None:
327 ctx.create_tmp_samdb()
331 id = drsuapi.DsReplicaObjectIdentifier()
338 if not isinstance(rec[a], list):
342 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
345 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
346 attribute_ctr.num_attributes = len(attrs)
347 attribute_ctr.attributes = attrs
349 object = drsuapi.DsReplicaObject()
350 object.identifier = id
351 object.attribute_ctr = attribute_ctr
353 list_object = drsuapi.DsReplicaObjectListItem()
354 list_object.object = object
355 objects.append(list_object)
357 req2 = drsuapi.DsAddEntryRequest2()
358 req2.first_object = objects[0]
359 prev = req2.first_object
360 for o in objects[1:]:
364 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
366 if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
367 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
368 raise RuntimeError("DsAddEntry failed")
369 if ctr.extended_err != (0, 'WERR_OK'):
370 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
371 raise RuntimeError("DsAddEntry failed")
374 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
375 if ctr.err_data.status != (0, 'WERR_OK'):
376 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
377 ctr.err_data.info.extended_err))
378 raise RuntimeError("DsAddEntry failed")
379 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
380 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
381 raise RuntimeError("DsAddEntry failed")
385 def join_add_ntdsdsa(ctx):
386 '''add the ntdsdsa object'''
387 # FIXME: the partition (NC) assignment has to be made dynamic
388 print "Adding %s" % ctx.ntds_dn
391 "objectclass" : "nTDSDSA",
392 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
393 "dMDLocation" : ctx.schema_dn}
395 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
397 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
398 rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
400 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
401 rec["msDS-HasDomainNCs"] = ctx.base_dn
404 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
405 rec["msDS-HasFullReplicaNCs"] = nc_list
406 rec["options"] = "37"
407 ctx.samdb.add(rec, ["rodc_join:1:1"])
409 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
410 rec["HasMasterNCs"] = nc_list
411 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
412 rec["msDS-HasMasterNCs"] = nc_list
414 rec["invocationId"] = ndr_pack(ctx.invocation_id)
415 ctx.DsAddEntry([rec])
417 # find the GUID of our NTDS DN
418 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
419 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
421 def join_add_objects(ctx):
422 '''add the various objects needed for the join'''
424 print "Adding %s" % ctx.acct_dn
427 "objectClass": "computer",
428 "displayname": ctx.samname,
429 "samaccountname" : ctx.samname,
430 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
431 "dnshostname" : ctx.dnshostname}
432 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
433 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
435 rec["managedby"] = ctx.managedby
436 if ctx.never_reveal_sid:
437 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
439 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
443 ctx.add_krbtgt_account()
445 print "Adding %s" % ctx.server_dn
448 "objectclass" : "server",
449 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
450 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
451 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
452 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
453 # windows seems to add the dnsHostName later
454 "dnsHostName" : ctx.dnshostname}
457 rec["serverReference"] = ctx.acct_dn
462 # the rest is done after replication
466 ctx.join_add_ntdsdsa()
468 if ctx.connection_dn is not None:
469 print "Adding %s" % ctx.connection_dn
471 "dn" : ctx.connection_dn,
472 "objectclass" : "nTDSConnection",
473 "enabledconnection" : "TRUE",
475 "fromServer" : ctx.dc_ntds_dn}
479 print "Adding SPNs to %s" % ctx.acct_dn
481 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
482 for i in range(len(ctx.SPNs)):
483 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
484 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
486 "servicePrincipalName")
489 # The account password set operation should normally be done over
490 # LDAP. Windows 2000 DCs however allow this only with SSL
491 # connections which are hard to set up and otherwise refuse with
492 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
494 print "Setting account password for %s" % ctx.samname
496 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
497 % ldb.binary_encode(ctx.samname),
499 force_change_at_next_login=False,
500 username=ctx.samname)
501 except ldb.LdbError, (num, _):
502 if num != ldb.ERR_UNWILLING_TO_PERFORM:
504 ctx.net.set_password(account_name=ctx.samname,
505 domain_name=ctx.domain_name,
506 newpassword=ctx.acct_pass)
508 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
509 attrs=["msDS-KeyVersionNumber"])
510 if "msDS-KeyVersionNumber" in res[0]:
511 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
513 ctx.key_version_number = None
515 print("Enabling account")
517 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
518 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
519 ldb.FLAG_MOD_REPLACE,
520 "userAccountControl")
523 def join_add_objects2(ctx):
524 '''add the various objects needed for the join, for subdomains post replication'''
526 print "Adding %s" % ctx.partition_dn
527 # NOTE: windows sends a ntSecurityDescriptor here, we
530 "dn" : ctx.partition_dn,
531 "objectclass" : "crossRef",
532 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
533 "nCName" : ctx.base_dn,
534 "nETBIOSName" : ctx.domain_name,
535 "dnsRoot": ctx.dnsdomain,
536 "trustParent" : ctx.parent_partition_dn,
537 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
538 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
539 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
543 "objectclass" : "nTDSDSA",
544 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
545 "dMDLocation" : ctx.schema_dn}
547 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
549 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
550 rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
552 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
553 rec2["msDS-HasDomainNCs"] = ctx.base_dn
555 rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
556 rec2["HasMasterNCs"] = nc_list
557 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
558 rec2["msDS-HasMasterNCs"] = nc_list
559 rec2["options"] = "1"
560 rec2["invocationId"] = ndr_pack(ctx.invocation_id)
562 objects = ctx.DsAddEntry([rec, rec2])
563 if len(objects) != 2:
564 raise DCJoinException("Expected 2 objects from DsAddEntry")
566 ctx.ntds_guid = objects[1].guid
568 print("Replicating partition DN")
569 ctx.repl.replicate(ctx.partition_dn,
570 misc.GUID("00000000-0000-0000-0000-000000000000"),
572 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
573 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
575 print("Replicating NTDS DN")
576 ctx.repl.replicate(ctx.ntds_dn,
577 misc.GUID("00000000-0000-0000-0000-000000000000"),
579 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
580 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
582 def join_provision(ctx):
583 '''provision the local SAM'''
585 print "Calling bare provision"
587 logger = logging.getLogger("provision")
588 logger.addHandler(logging.StreamHandler(sys.stdout))
589 smbconf = ctx.lp.configfile
591 presult = provision(logger, system_session(), None, smbconf=smbconf,
592 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
593 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
594 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
595 serverdn=ctx.server_dn, domain=ctx.domain_name,
596 hostname=ctx.myname, domainsid=ctx.domsid,
597 machinepass=ctx.acct_pass, serverrole="domain controller",
598 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
599 use_ntvfs=ctx.use_ntvfs, dns_backend="NONE")
600 print "Provision OK for domain DN %s" % presult.domaindn
601 ctx.local_samdb = presult.samdb
603 ctx.paths = presult.paths
604 ctx.names = presult.names
606 def join_provision_own_domain(ctx):
607 '''provision the local SAM'''
609 # we now operate exclusively on the local database, which
610 # we need to reopen in order to get the newly created schema
611 print("Reconnecting to local samdb")
612 ctx.samdb = SamDB(url=ctx.local_samdb.url,
613 session_info=system_session(),
614 lp=ctx.local_samdb.lp,
616 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
617 ctx.local_samdb = ctx.samdb
619 print("Finding domain GUID from ncName")
620 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
621 controls=["extended_dn:1:1"])
622 domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
623 print("Got domain GUID %s" % domguid)
625 print("Calling own domain provision")
627 logger = logging.getLogger("provision")
628 logger.addHandler(logging.StreamHandler(sys.stdout))
630 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
632 presult = provision_fill(ctx.local_samdb, secrets_ldb,
633 logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
635 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
636 machinepass=ctx.acct_pass, serverrole="domain controller",
637 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
638 dns_backend="BIND9_DLZ")
639 print("Provision OK for domain %s" % ctx.names.dnsdomain)
641 def join_replicate(ctx):
642 '''replicate the SAM'''
644 print "Starting replication"
645 ctx.local_samdb.transaction_start()
647 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
648 if ctx.ntds_guid is None:
649 print("Using DS_BIND_GUID_W2K3")
650 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
652 destination_dsa_guid = ctx.ntds_guid
655 repl_creds = Credentials()
656 repl_creds.guess(ctx.lp)
657 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
658 repl_creds.set_username(ctx.samname)
659 repl_creds.set_password(ctx.acct_pass)
661 repl_creds = ctx.creds
663 binding_options = "seal"
664 if int(ctx.lp.get("log level")) >= 5:
665 binding_options += ",print"
666 repl = drs_utils.drs_Replicate(
667 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
668 ctx.lp, repl_creds, ctx.local_samdb)
670 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
671 destination_dsa_guid, schema=True, rodc=ctx.RODC,
672 replica_flags=ctx.replica_flags)
673 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
674 destination_dsa_guid, rodc=ctx.RODC,
675 replica_flags=ctx.replica_flags)
676 if not ctx.subdomain:
677 # Replicate first the critical object for the basedn
678 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
679 print "Replicating critical objects from the base DN of the domain"
680 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
681 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
682 destination_dsa_guid, rodc=ctx.RODC,
683 replica_flags=ctx.domain_replica_flags)
684 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
686 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
687 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
688 destination_dsa_guid, rodc=ctx.RODC,
689 replica_flags=ctx.domain_replica_flags)
691 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
692 destination_dsa_guid,
693 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
694 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
695 destination_dsa_guid,
696 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
698 ctx.source_dsa_invocation_id = source_dsa_invocation_id
699 ctx.destination_dsa_guid = destination_dsa_guid
701 print "Committing SAM database"
703 ctx.local_samdb.transaction_cancel()
706 ctx.local_samdb.transaction_commit()
708 def send_DsReplicaUpdateRefs(ctx, dn):
709 r = drsuapi.DsReplicaUpdateRefsRequest1()
710 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
711 r.naming_context.dn = str(dn)
712 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
713 r.naming_context.sid = security.dom_sid("S-0-0")
714 r.dest_dsa_guid = ctx.ntds_guid
715 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
716 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
718 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
721 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
723 def join_finalise(ctx):
724 '''finalise the join, mark us synchronised and setup secrets db'''
726 print "Sending DsReplicateUpdateRefs for all the partitions"
727 ctx.send_DsReplicaUpdateRefs(ctx.schema_dn)
728 ctx.send_DsReplicaUpdateRefs(ctx.config_dn)
729 ctx.send_DsReplicaUpdateRefs(ctx.base_dn)
731 print "Setting isSynchronized and dsServiceName"
733 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
734 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
735 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
736 ldb.FLAG_MOD_REPLACE, "dsServiceName")
737 ctx.local_samdb.modify(m)
742 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
744 print "Setting up secrets database"
745 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
747 dnsdomain=ctx.dnsdomain,
748 netbiosname=ctx.myname,
749 domainsid=security.dom_sid(ctx.domsid),
750 machinepass=ctx.acct_pass,
751 secure_channel_type=ctx.secure_channel_type,
752 key_version_number=ctx.key_version_number)
754 def join_setup_trusts(ctx):
755 '''provision the local SAM'''
757 def arcfour_encrypt(key, data):
758 from Crypto.Cipher import ARC4
760 return c.encrypt(data)
762 def string_to_array(string):
763 blob = [0] * len(string)
765 for i in range(len(string)):
766 blob[i] = ord(string[i])
770 print "Setup domain trusts with server %s" % ctx.server
771 binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key
772 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
775 objectAttr = lsa.ObjectAttribute()
776 objectAttr.sec_qos = lsa.QosInfo()
778 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
779 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
781 info = lsa.TrustDomainInfoInfoEx()
782 info.domain_name.string = ctx.dnsdomain
783 info.netbios_name.string = ctx.domain_name
784 info.sid = security.dom_sid(ctx.domsid)
785 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
786 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
787 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
790 oldname = lsa.String()
791 oldname.string = ctx.dnsdomain
792 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
793 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
794 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
795 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
799 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
801 clear_value = drsblobs.AuthInfoClear()
802 clear_value.size = len(password_blob)
803 clear_value.password = password_blob
805 clear_authentication_information = drsblobs.AuthenticationInformation()
806 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
807 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
808 clear_authentication_information.AuthInfo = clear_value
810 authentication_information_array = drsblobs.AuthenticationInformationArray()
811 authentication_information_array.count = 1
812 authentication_information_array.array = [clear_authentication_information]
814 outgoing = drsblobs.trustAuthInOutBlob()
816 outgoing.current = authentication_information_array
818 trustpass = drsblobs.trustDomainPasswords()
819 confounder = [3] * 512
822 confounder[i] = random.randint(0, 255)
824 trustpass.confounder = confounder
826 trustpass.outgoing = outgoing
827 trustpass.incoming = outgoing
829 trustpass_blob = ndr_pack(trustpass)
831 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
833 auth_blob = lsa.DATA_BUF2()
834 auth_blob.size = len(encrypted_trustpass)
835 auth_blob.data = string_to_array(encrypted_trustpass)
837 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
838 auth_info.auth_blob = auth_blob
840 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
843 security.SEC_STD_DELETE)
846 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
847 "objectclass" : "trustedDomain",
848 "trustType" : str(info.trust_type),
849 "trustAttributes" : str(info.trust_attributes),
850 "trustDirection" : str(info.trust_direction),
851 "flatname" : ctx.forest_domain_name,
852 "trustPartner" : ctx.dnsforest,
853 "trustAuthIncoming" : ndr_pack(outgoing),
854 "trustAuthOutgoing" : ndr_pack(outgoing)
856 ctx.local_samdb.add(rec)
859 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
860 "objectclass" : "user",
861 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
862 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
864 ctx.local_samdb.add(rec)
868 ctx.cleanup_old_join()
870 ctx.join_add_objects()
874 ctx.join_add_objects2()
875 ctx.join_provision_own_domain()
876 ctx.join_setup_trusts()
879 print "Join failed - cleaning up"
880 ctx.cleanup_old_join()
884 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
885 targetdir=None, domain=None, domain_critical_only=False,
886 machinepass=None, use_ntvfs=False):
889 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
890 machinepass, use_ntvfs)
892 lp.set("workgroup", ctx.domain_name)
893 print("workgroup is %s" % ctx.domain_name)
895 lp.set("realm", ctx.realm)
896 print("realm is %s" % ctx.realm)
898 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
900 # setup some defaults for accounts that should be replicated to this RODC
901 ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
902 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
903 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
904 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
905 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
906 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
908 mysid = ctx.get_mysid()
909 admin_dn = "<SID=%s>" % mysid
910 ctx.managedby = admin_dn
912 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
913 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
914 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
916 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
917 "RestrictedKrbHost/%s" % ctx.dnshostname ])
919 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
920 ctx.secure_channel_type = misc.SEC_CHAN_RODC
922 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
923 drsuapi.DRSUAPI_DRS_PER_SYNC |
924 drsuapi.DRSUAPI_DRS_GET_ANC |
925 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
926 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
927 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
928 ctx.domain_replica_flags = ctx.replica_flags
929 if domain_critical_only:
930 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
935 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
938 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
939 targetdir=None, domain=None, domain_critical_only=False,
940 machinepass=None, use_ntvfs=False):
942 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
943 machinepass, use_ntvfs)
945 lp.set("workgroup", ctx.domain_name)
946 print("workgroup is %s" % ctx.domain_name)
948 lp.set("realm", ctx.realm)
949 print("realm is %s" % ctx.realm)
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
962 if domain_critical_only:
963 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
966 print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
968 def join_subdomain(server=None, creds=None, lp=None, site=None, netbios_name=None,
969 targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None,
970 machinepass=None, use_ntvfs=False):
972 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain,
973 machinepass, use_ntvfs)
975 ctx.parent_domain_name = ctx.domain_name
976 ctx.domain_name = netbios_domain
977 ctx.realm = dnsdomain
978 ctx.parent_dnsdomain = ctx.dnsdomain
979 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
980 ctx.dnsdomain = dnsdomain
981 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
982 ctx.naming_master = ctx.get_naming_master()
983 if ctx.naming_master != ctx.server:
984 print("Reconnecting to naming master %s" % ctx.naming_master)
985 ctx.server = ctx.naming_master
986 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
987 session_info=system_session(),
988 credentials=ctx.creds, lp=ctx.lp)
990 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
991 ctx.domsid = str(security.random_sid())
993 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
994 ctx.trustdom_pass = samba.generate_random_password(128, 128)
996 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
998 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
999 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1001 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1002 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1003 drsuapi.DRSUAPI_DRS_PER_SYNC |
1004 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1005 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1006 ctx.domain_replica_flags = ctx.replica_flags
1009 print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)