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, dns_backend=None):
54 ctx.netbios_name = netbios_name
55 ctx.targetdir = targetdir
56 ctx.use_ntvfs = use_ntvfs
57 if dns_backend is None:
58 ctx.dns_backend = "NONE"
60 ctx.dns_backend = dns_backend
65 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
66 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
68 if server is not None:
71 print("Finding a writeable DC for domain '%s'" % domain)
72 ctx.server = ctx.find_dc(domain)
73 print("Found DC %s" % ctx.server)
75 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
76 session_info=system_session(),
77 credentials=ctx.creds, lp=ctx.lp)
80 ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
81 except ldb.LdbError, (enum, estr):
82 raise DCJoinException(estr)
85 ctx.myname = netbios_name
86 ctx.samname = "%s$" % ctx.myname
87 ctx.base_dn = str(ctx.samdb.get_default_basedn())
88 ctx.root_dn = str(ctx.samdb.get_root_basedn())
89 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
90 ctx.config_dn = str(ctx.samdb.get_config_basedn())
91 ctx.domsid = ctx.samdb.get_domain_sid()
92 ctx.domain_name = ctx.get_domain_name()
93 ctx.forest_domain_name = ctx.get_forest_domain_name()
94 ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
96 ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName()
97 ctx.dc_dnsHostName = ctx.get_dnsHostName()
98 ctx.behavior_version = ctx.get_behavior_version()
100 if machinepass is not None:
101 ctx.acct_pass = machinepass
103 ctx.acct_pass = samba.generate_random_password(32, 40)
105 # work out the DNs of all the objects we will be adding
106 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
107 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
108 topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
109 if ctx.dn_exists(topology_base):
110 ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
112 ctx.topology_dn = None
114 ctx.dnsdomain = ctx.samdb.domain_dns_name()
115 ctx.dnsforest = ctx.samdb.forest_dns_name()
116 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
118 ctx.realm = ctx.dnsdomain
120 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
124 ctx.SPNs = [ "HOST/%s" % ctx.myname,
125 "HOST/%s" % ctx.dnshostname,
126 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
128 # these elements are optional
129 ctx.never_reveal_sid = None
130 ctx.reveal_sid = None
131 ctx.connection_dn = None
136 ctx.subdomain = False
138 def del_noerror(ctx, dn, recursive=False):
141 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
145 ctx.del_noerror(r.dn, recursive=True)
148 print "Deleted %s" % dn
152 def cleanup_old_join(ctx):
153 '''remove any DNs from a previous join'''
155 # find the krbtgt link
156 print("checking sAMAccountName")
160 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
161 expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
162 attrs=["msDS-krbTgtLink"])
164 ctx.del_noerror(res[0].dn, recursive=True)
165 if ctx.connection_dn is not None:
166 ctx.del_noerror(ctx.connection_dn)
167 if ctx.krbtgt_dn is not None:
168 ctx.del_noerror(ctx.krbtgt_dn)
169 ctx.del_noerror(ctx.ntds_dn)
170 ctx.del_noerror(ctx.server_dn, recursive=True)
172 ctx.del_noerror(ctx.topology_dn)
174 ctx.del_noerror(ctx.partition_dn)
176 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
177 ctx.del_noerror(ctx.new_krbtgt_dn)
180 binding_options = "sign"
181 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
184 objectAttr = lsa.ObjectAttribute()
185 objectAttr.sec_qos = lsa.QosInfo()
187 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
188 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
191 name.string = ctx.realm
192 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
194 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
197 name.string = ctx.forest_domain_name
198 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
200 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
205 def find_dc(ctx, domain):
206 '''find a writeable DC for the given domain'''
208 ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
210 raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
211 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
212 ctx.site = ctx.cldap_ret.client_site
213 return ctx.cldap_ret.pdc_dns_name
216 def get_behavior_version(ctx):
217 res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
218 if "msDS-Behavior-Version" in res[0]:
219 return int(res[0]["msDS-Behavior-Version"][0])
221 return samba.dsdb.DS_DOMAIN_FUNCTION_2000
223 def get_dnsHostName(ctx):
224 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
225 return res[0]["dnsHostName"][0]
227 def get_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_default_basedn())
232 return res[0]["nETBIOSName"][0]
234 def get_forest_domain_name(ctx):
235 '''get netbios name of the domain from the partitions record'''
236 partitions_dn = ctx.samdb.get_partitions_dn()
237 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
238 expression='ncName=%s' % ctx.samdb.get_root_basedn())
239 return res[0]["nETBIOSName"][0]
241 def get_parent_partition_dn(ctx):
242 '''get the parent domain partition DN from parent DNS name'''
243 res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
244 expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
245 (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
246 return str(res[0].dn)
248 def get_naming_master(ctx):
249 '''get the parent domain partition DN from parent DNS name'''
250 res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
251 scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
252 if not 'fSMORoleOwner' in res[0]:
253 raise DCJoinException("Can't find naming master on partition DN %s" % ctx.partition_dn)
254 master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
255 master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
259 '''get the SID of the connected user. Only works with w2k8 and later,
260 so only used for RODC join'''
261 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
262 binsid = res[0]["tokenGroups"][0]
263 return ctx.samdb.schema_format_value("objectSID", binsid)
265 def dn_exists(ctx, dn):
266 '''check if a DN exists'''
268 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
269 except ldb.LdbError, (enum, estr):
270 if enum == ldb.ERR_NO_SUCH_OBJECT:
275 def add_krbtgt_account(ctx):
276 '''RODCs need a special krbtgt account'''
277 print "Adding %s" % ctx.krbtgt_dn
279 "dn" : ctx.krbtgt_dn,
280 "objectclass" : "user",
281 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
282 samba.dsdb.UF_ACCOUNTDISABLE),
283 "showinadvancedviewonly" : "TRUE",
284 "description" : "krbtgt for %s" % ctx.samname}
285 ctx.samdb.add(rec, ["rodc_join:1:1"])
287 # now we need to search for the samAccountName attribute on the krbtgt DN,
288 # as this will have been magically set to the krbtgt number
289 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
290 ctx.krbtgt_name = res[0]["samAccountName"][0]
292 print "Got krbtgt_name=%s" % ctx.krbtgt_name
295 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
296 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
297 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
300 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
301 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
302 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
304 def drsuapi_connect(ctx):
305 '''make a DRSUAPI connection to the naming master'''
306 binding_options = "seal"
307 if int(ctx.lp.get("log level")) >= 4:
308 binding_options += ",print"
309 binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
310 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
311 (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
313 def create_tmp_samdb(ctx):
314 '''create a temporary samdb object for schema queries'''
315 ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
316 schemadn=ctx.schema_dn)
317 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
318 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
320 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
322 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
323 '''build a DsReplicaAttributeCtr object'''
324 r = drsuapi.DsReplicaAttribute()
325 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
329 def DsAddEntry(ctx, recs):
330 '''add a record via the DRSUAPI DsAddEntry call'''
331 if ctx.drsuapi is None:
332 ctx.drsuapi_connect()
333 if ctx.tmp_samdb is None:
334 ctx.create_tmp_samdb()
338 id = drsuapi.DsReplicaObjectIdentifier()
345 if not isinstance(rec[a], list):
349 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
352 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
353 attribute_ctr.num_attributes = len(attrs)
354 attribute_ctr.attributes = attrs
356 object = drsuapi.DsReplicaObject()
357 object.identifier = id
358 object.attribute_ctr = attribute_ctr
360 list_object = drsuapi.DsReplicaObjectListItem()
361 list_object.object = object
362 objects.append(list_object)
364 req2 = drsuapi.DsAddEntryRequest2()
365 req2.first_object = objects[0]
366 prev = req2.first_object
367 for o in objects[1:]:
371 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
373 if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
374 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
375 raise RuntimeError("DsAddEntry failed")
376 if ctr.extended_err != (0, 'WERR_OK'):
377 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
378 raise RuntimeError("DsAddEntry failed")
381 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
382 if ctr.err_data.status != (0, 'WERR_OK'):
383 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
384 ctr.err_data.info.extended_err))
385 raise RuntimeError("DsAddEntry failed")
386 if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
387 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
388 raise RuntimeError("DsAddEntry failed")
392 def join_add_ntdsdsa(ctx):
393 '''add the ntdsdsa object'''
394 # FIXME: the partition (NC) assignment has to be made dynamic
395 print "Adding %s" % ctx.ntds_dn
398 "objectclass" : "nTDSDSA",
399 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
400 "dMDLocation" : ctx.schema_dn}
402 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
404 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
405 rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
407 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
408 rec["msDS-HasDomainNCs"] = ctx.base_dn
411 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
412 rec["msDS-HasFullReplicaNCs"] = ctx.nc_list
413 rec["options"] = "37"
414 ctx.samdb.add(rec, ["rodc_join:1:1"])
416 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
417 rec["HasMasterNCs"] = nc_list
418 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
419 rec["msDS-HasMasterNCs"] = ctx.nc_list
421 rec["invocationId"] = ndr_pack(ctx.invocation_id)
422 ctx.DsAddEntry([rec])
424 # find the GUID of our NTDS DN
425 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
426 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
428 def join_add_objects(ctx):
429 '''add the various objects needed for the join'''
431 print "Adding %s" % ctx.acct_dn
434 "objectClass": "computer",
435 "displayname": ctx.samname,
436 "samaccountname" : ctx.samname,
437 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
438 "dnshostname" : ctx.dnshostname}
439 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
440 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
442 rec["managedby"] = ctx.managedby
443 if ctx.never_reveal_sid:
444 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
446 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
450 ctx.add_krbtgt_account()
452 print "Adding %s" % ctx.server_dn
455 "objectclass" : "server",
456 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
457 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
458 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
459 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
460 # windows seems to add the dnsHostName later
461 "dnsHostName" : ctx.dnshostname}
464 rec["serverReference"] = ctx.acct_dn
469 # the rest is done after replication
473 ctx.join_add_ntdsdsa()
475 if ctx.connection_dn is not None:
476 print "Adding %s" % ctx.connection_dn
478 "dn" : ctx.connection_dn,
479 "objectclass" : "nTDSConnection",
480 "enabledconnection" : "TRUE",
482 "fromServer" : ctx.dc_ntds_dn}
486 print "Adding SPNs to %s" % ctx.acct_dn
488 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
489 for i in range(len(ctx.SPNs)):
490 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
491 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
493 "servicePrincipalName")
496 # The account password set operation should normally be done over
497 # LDAP. Windows 2000 DCs however allow this only with SSL
498 # connections which are hard to set up and otherwise refuse with
499 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
501 print "Setting account password for %s" % ctx.samname
503 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
504 % ldb.binary_encode(ctx.samname),
506 force_change_at_next_login=False,
507 username=ctx.samname)
508 except ldb.LdbError, (num, _):
509 if num != ldb.ERR_UNWILLING_TO_PERFORM:
511 ctx.net.set_password(account_name=ctx.samname,
512 domain_name=ctx.domain_name,
513 newpassword=ctx.acct_pass)
515 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
516 attrs=["msDS-KeyVersionNumber"])
517 if "msDS-KeyVersionNumber" in res[0]:
518 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
520 ctx.key_version_number = None
522 print("Enabling account")
524 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
525 m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
526 ldb.FLAG_MOD_REPLACE,
527 "userAccountControl")
530 def join_add_objects2(ctx):
531 '''add the various objects needed for the join, for subdomains post replication'''
533 print "Adding %s" % ctx.partition_dn
534 # NOTE: windows sends a ntSecurityDescriptor here, we
537 "dn" : ctx.partition_dn,
538 "objectclass" : "crossRef",
539 "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
540 "nCName" : ctx.base_dn,
541 "nETBIOSName" : ctx.domain_name,
542 "dnsRoot": ctx.dnsdomain,
543 "trustParent" : ctx.parent_partition_dn,
544 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
545 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
546 rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
550 "objectclass" : "nTDSDSA",
551 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
552 "dMDLocation" : ctx.schema_dn}
554 nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
556 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
557 rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
559 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
560 rec2["msDS-HasDomainNCs"] = ctx.base_dn
562 rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
563 rec2["HasMasterNCs"] = nc_list
564 if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
565 rec2["msDS-HasMasterNCs"] = ctx.nc_list
566 rec2["options"] = "1"
567 rec2["invocationId"] = ndr_pack(ctx.invocation_id)
569 objects = ctx.DsAddEntry([rec, rec2])
570 if len(objects) != 2:
571 raise DCJoinException("Expected 2 objects from DsAddEntry")
573 ctx.ntds_guid = objects[1].guid
575 print("Replicating partition DN")
576 ctx.repl.replicate(ctx.partition_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 print("Replicating NTDS DN")
583 ctx.repl.replicate(ctx.ntds_dn,
584 misc.GUID("00000000-0000-0000-0000-000000000000"),
586 exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
587 replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
589 def join_provision(ctx):
590 '''provision the local SAM'''
592 print "Calling bare provision"
594 logger = logging.getLogger("provision")
595 logger.addHandler(logging.StreamHandler(sys.stdout))
596 smbconf = ctx.lp.configfile
598 presult = provision(logger, system_session(), None, smbconf=smbconf,
599 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
600 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
601 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
602 serverdn=ctx.server_dn, domain=ctx.domain_name,
603 hostname=ctx.myname, domainsid=ctx.domsid,
604 machinepass=ctx.acct_pass, serverrole="domain controller",
605 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
606 use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend)
607 print "Provision OK for domain DN %s" % presult.domaindn
608 ctx.local_samdb = presult.samdb
610 ctx.paths = presult.paths
611 ctx.names = presult.names
613 def join_provision_own_domain(ctx):
614 '''provision the local SAM'''
616 # we now operate exclusively on the local database, which
617 # we need to reopen in order to get the newly created schema
618 print("Reconnecting to local samdb")
619 ctx.samdb = SamDB(url=ctx.local_samdb.url,
620 session_info=system_session(),
621 lp=ctx.local_samdb.lp,
623 ctx.samdb.set_invocation_id(str(ctx.invocation_id))
624 ctx.local_samdb = ctx.samdb
626 print("Finding domain GUID from ncName")
627 res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
628 controls=["extended_dn:1:1"])
629 domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
630 print("Got domain GUID %s" % domguid)
632 print("Calling own domain provision")
634 logger = logging.getLogger("provision")
635 logger.addHandler(logging.StreamHandler(sys.stdout))
637 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
639 presult = provision_fill(ctx.local_samdb, secrets_ldb,
640 logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
642 targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
643 machinepass=ctx.acct_pass, serverrole="domain controller",
644 lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
645 dns_backend="BIND9_DLZ")
646 print("Provision OK for domain %s" % ctx.names.dnsdomain)
648 def join_replicate(ctx):
649 '''replicate the SAM'''
651 print "Starting replication"
652 ctx.local_samdb.transaction_start()
654 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
655 if ctx.ntds_guid is None:
656 print("Using DS_BIND_GUID_W2K3")
657 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
659 destination_dsa_guid = ctx.ntds_guid
662 repl_creds = Credentials()
663 repl_creds.guess(ctx.lp)
664 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
665 repl_creds.set_username(ctx.samname)
666 repl_creds.set_password(ctx.acct_pass)
668 repl_creds = ctx.creds
670 binding_options = "seal"
671 if int(ctx.lp.get("log level")) >= 5:
672 binding_options += ",print"
673 repl = drs_utils.drs_Replicate(
674 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
675 ctx.lp, repl_creds, ctx.local_samdb)
677 repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
678 destination_dsa_guid, schema=True, rodc=ctx.RODC,
679 replica_flags=ctx.replica_flags)
680 repl.replicate(ctx.config_dn, source_dsa_invocation_id,
681 destination_dsa_guid, rodc=ctx.RODC,
682 replica_flags=ctx.replica_flags)
683 if not ctx.subdomain:
684 # Replicate first the critical object for the basedn
685 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
686 print "Replicating critical objects from the base DN of the domain"
687 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
688 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
689 destination_dsa_guid, rodc=ctx.RODC,
690 replica_flags=ctx.domain_replica_flags)
691 ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
693 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
694 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
695 destination_dsa_guid, rodc=ctx.RODC,
696 replica_flags=ctx.domain_replica_flags)
698 if 'DC=DomainDnsZones,%s' % ctx.base_dn in ctx.nc_list:
699 repl.replicate('DC=DomainDnsZones,%s' % ctx.base_dn, source_dsa_invocation_id,
700 destination_dsa_guid, rodc=ctx.RODC,
701 replica_flags=ctx.replica_flags)
703 if 'DC=ForestDnsZones,%s' % ctx.root_dn in ctx.nc_list:
704 repl.replicate('DC=ForestDnsZones,%s' % ctx.root_dn, source_dsa_invocation_id,
705 destination_dsa_guid, rodc=ctx.RODC,
706 replica_flags=ctx.replica_flags)
709 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
710 destination_dsa_guid,
711 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
712 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
713 destination_dsa_guid,
714 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
716 ctx.source_dsa_invocation_id = source_dsa_invocation_id
717 ctx.destination_dsa_guid = destination_dsa_guid
719 print "Committing SAM database"
721 ctx.local_samdb.transaction_cancel()
724 ctx.local_samdb.transaction_commit()
726 def send_DsReplicaUpdateRefs(ctx, dn):
727 r = drsuapi.DsReplicaUpdateRefsRequest1()
728 r.naming_context = drsuapi.DsReplicaObjectIdentifier()
729 r.naming_context.dn = str(dn)
730 r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
731 r.naming_context.sid = security.dom_sid("S-0-0")
732 r.dest_dsa_guid = ctx.ntds_guid
733 r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
734 r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
736 r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
739 ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
741 def join_finalise(ctx):
742 '''finalise the join, mark us synchronised and setup secrets db'''
744 print "Sending DsReplicateUpdateRefs for all the partitions"
745 for nc in ctx.full_nc_list:
746 ctx.send_DsReplicaUpdateRefs(nc)
748 print "Setting isSynchronized and dsServiceName"
750 m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
751 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
752 m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
753 ldb.FLAG_MOD_REPLACE, "dsServiceName")
754 ctx.local_samdb.modify(m)
759 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
761 print "Setting up secrets database"
762 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
764 dnsdomain=ctx.dnsdomain,
765 netbiosname=ctx.myname,
766 domainsid=security.dom_sid(ctx.domsid),
767 machinepass=ctx.acct_pass,
768 secure_channel_type=ctx.secure_channel_type,
769 key_version_number=ctx.key_version_number)
771 def join_setup_trusts(ctx):
772 '''provision the local SAM'''
774 def arcfour_encrypt(key, data):
775 from Crypto.Cipher import ARC4
777 return c.encrypt(data)
779 def string_to_array(string):
780 blob = [0] * len(string)
782 for i in range(len(string)):
783 blob[i] = ord(string[i])
787 print "Setup domain trusts with server %s" % ctx.server
788 binding_options = "" # why doesn't signing work here? w2k8r2 claims no session key
789 lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
792 objectAttr = lsa.ObjectAttribute()
793 objectAttr.sec_qos = lsa.QosInfo()
795 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
796 objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
798 info = lsa.TrustDomainInfoInfoEx()
799 info.domain_name.string = ctx.dnsdomain
800 info.netbios_name.string = ctx.domain_name
801 info.sid = security.dom_sid(ctx.domsid)
802 info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
803 info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
804 info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
807 oldname = lsa.String()
808 oldname.string = ctx.dnsdomain
809 oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
810 lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
811 print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
812 lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
816 password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
818 clear_value = drsblobs.AuthInfoClear()
819 clear_value.size = len(password_blob)
820 clear_value.password = password_blob
822 clear_authentication_information = drsblobs.AuthenticationInformation()
823 clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
824 clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
825 clear_authentication_information.AuthInfo = clear_value
827 authentication_information_array = drsblobs.AuthenticationInformationArray()
828 authentication_information_array.count = 1
829 authentication_information_array.array = [clear_authentication_information]
831 outgoing = drsblobs.trustAuthInOutBlob()
833 outgoing.current = authentication_information_array
835 trustpass = drsblobs.trustDomainPasswords()
836 confounder = [3] * 512
839 confounder[i] = random.randint(0, 255)
841 trustpass.confounder = confounder
843 trustpass.outgoing = outgoing
844 trustpass.incoming = outgoing
846 trustpass_blob = ndr_pack(trustpass)
848 encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
850 auth_blob = lsa.DATA_BUF2()
851 auth_blob.size = len(encrypted_trustpass)
852 auth_blob.data = string_to_array(encrypted_trustpass)
854 auth_info = lsa.TrustDomainInfoAuthInfoInternal()
855 auth_info.auth_blob = auth_blob
857 trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
860 security.SEC_STD_DELETE)
863 "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
864 "objectclass" : "trustedDomain",
865 "trustType" : str(info.trust_type),
866 "trustAttributes" : str(info.trust_attributes),
867 "trustDirection" : str(info.trust_direction),
868 "flatname" : ctx.forest_domain_name,
869 "trustPartner" : ctx.dnsforest,
870 "trustAuthIncoming" : ndr_pack(outgoing),
871 "trustAuthOutgoing" : ndr_pack(outgoing)
873 ctx.local_samdb.add(rec)
876 "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
877 "objectclass" : "user",
878 "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
879 "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
881 ctx.local_samdb.add(rec)
885 ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
886 ctx.full_nc_list = [ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
888 if not ctx.subdomain:
889 ctx.nc_list += [ctx.base_dn]
890 if ctx.dns_backend != "NONE":
891 ctx.nc_list += ['DC=DomainDnsZones,%s' % ctx.base_dn]
893 if ctx.dns_backend != "NONE":
894 ctx.full_nc_list += ['DC=DomainDnsZones,%s' % ctx.base_dn]
895 ctx.full_nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
896 ctx.nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
899 ctx.cleanup_old_join()
901 ctx.join_add_objects()
905 ctx.join_add_objects2()
906 ctx.join_provision_own_domain()
907 ctx.join_setup_trusts()
910 print "Join failed - cleaning up"
911 ctx.cleanup_old_join()
915 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
916 targetdir=None, domain=None, domain_critical_only=False,
917 machinepass=None, use_ntvfs=False, dns_backend=None):
920 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
921 machinepass, use_ntvfs, dns_backend)
923 lp.set("workgroup", ctx.domain_name)
924 print("workgroup is %s" % ctx.domain_name)
926 lp.set("realm", ctx.realm)
927 print("realm is %s" % ctx.realm)
929 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
931 # setup some defaults for accounts that should be replicated to this RODC
932 ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
933 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
934 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
935 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
936 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
937 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
939 mysid = ctx.get_mysid()
940 admin_dn = "<SID=%s>" % mysid
941 ctx.managedby = admin_dn
943 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
944 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
945 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
947 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
948 "RestrictedKrbHost/%s" % ctx.dnshostname ])
950 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
951 ctx.secure_channel_type = misc.SEC_CHAN_RODC
953 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
954 drsuapi.DRSUAPI_DRS_PER_SYNC |
955 drsuapi.DRSUAPI_DRS_GET_ANC |
956 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
957 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
958 drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
959 ctx.domain_replica_flags = ctx.replica_flags
960 if domain_critical_only:
961 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
966 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
969 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
970 targetdir=None, domain=None, domain_critical_only=False,
971 machinepass=None, use_ntvfs=False, dns_backend=None):
973 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
974 machinepass, use_ntvfs, dns_backend)
976 lp.set("workgroup", ctx.domain_name)
977 print("workgroup is %s" % ctx.domain_name)
979 lp.set("realm", ctx.realm)
980 print("realm is %s" % ctx.realm)
982 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
984 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
985 ctx.secure_channel_type = misc.SEC_CHAN_BDC
987 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
988 drsuapi.DRSUAPI_DRS_INIT_SYNC |
989 drsuapi.DRSUAPI_DRS_PER_SYNC |
990 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
991 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
992 ctx.domain_replica_flags = ctx.replica_flags
993 if domain_critical_only:
994 ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
997 print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
999 def join_subdomain(server=None, creds=None, lp=None, site=None, netbios_name=None,
1000 targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None,
1001 machinepass=None, use_ntvfs=False, dns_backend=None):
1003 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain,
1004 machinepass, use_ntvfs, dns_backend)
1005 ctx.subdomain = True
1006 ctx.parent_domain_name = ctx.domain_name
1007 ctx.domain_name = netbios_domain
1008 ctx.realm = dnsdomain
1009 ctx.parent_dnsdomain = ctx.dnsdomain
1010 ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1011 ctx.dnsdomain = dnsdomain
1012 ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1013 ctx.naming_master = ctx.get_naming_master()
1014 if ctx.naming_master != ctx.server:
1015 print("Reconnecting to naming master %s" % ctx.naming_master)
1016 ctx.server = ctx.naming_master
1017 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1018 session_info=system_session(),
1019 credentials=ctx.creds, lp=ctx.lp)
1021 ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1022 ctx.domsid = str(security.random_sid())
1024 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
1025 ctx.trustdom_pass = samba.generate_random_password(128, 128)
1027 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1029 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1030 ctx.secure_channel_type = misc.SEC_CHAN_BDC
1032 ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1033 drsuapi.DRSUAPI_DRS_INIT_SYNC |
1034 drsuapi.DRSUAPI_DRS_PER_SYNC |
1035 drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1036 drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1037 ctx.domain_replica_flags = ctx.replica_flags
1040 print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)