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 import samba.getopt as options
22 from samba.auth import system_session
23 from samba.samdb import SamDB
24 from samba import gensec, Ldb, drs_utils
25 import ldb, samba, sys, os, uuid
26 from samba.ndr import ndr_pack, ndr_unpack, ndr_print
27 from samba.dcerpc import security, drsuapi, misc, netlogon, nbt
28 from samba.credentials import Credentials, DONT_USE_KERBEROS
29 from samba.provision import secretsdb_self_join, provision, FILL_DRS, find_setup_dir
30 from samba.schema import Schema
31 from samba.net import Net
33 from samba.dsdb import DS_DOMAIN_FUNCTION_2008_R2
36 # this makes debugging easier
37 talloc.enable_null_tracking()
40 '''perform a DC join'''
42 def __init__(ctx, server=None, creds=None, lp=None, site=None, netbios_name=None,
43 targetdir=None, domain=None):
47 ctx.netbios_name = netbios_name
48 ctx.targetdir = targetdir
50 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
51 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
53 if server is not None:
56 print("Finding a writeable DC for domain '%s'" % domain)
57 ctx.server = ctx.find_dc(domain)
58 print("Found DC %s" % ctx.server)
60 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
61 session_info=system_session(),
62 credentials=ctx.creds, lp=ctx.lp)
64 ctx.myname = netbios_name
65 ctx.samname = "%s$" % ctx.myname
66 ctx.base_dn = str(ctx.samdb.get_default_basedn())
67 ctx.root_dn = str(ctx.samdb.get_root_basedn())
68 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
69 ctx.config_dn = str(ctx.samdb.get_config_basedn())
70 ctx.domsid = ctx.samdb.get_domain_sid()
71 ctx.domain_name = ctx.get_domain_name()
73 lp.set("realm", ctx.domain_name)
75 ctx.dc_ntds_dn = ctx.get_dsServiceName()
76 ctx.dc_dnsHostName = ctx.get_dnsHostName()
77 ctx.acct_pass = samba.generate_random_password(12, 32)
78 ctx.mysid = ctx.get_mysid()
80 # work out the DNs of all the objects we will be adding
81 ctx.admin_dn = "<SID=%s>" % ctx.mysid
82 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
83 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
84 ctx.topology_dn = "CN=%s,CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % (ctx.myname, ctx.base_dn)
86 ctx.dnsdomain = ldb.Dn(ctx.samdb, ctx.base_dn).canonical_str().split('/')[0]
87 ctx.realm = ctx.dnsdomain
88 ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
90 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
92 ctx.setup_dir = find_setup_dir()
95 ctx.SPNs = [ "HOST/%s" % ctx.myname,
96 "HOST/%s" % ctx.dnshostname,
97 "GC/%s/%s" % (ctx.dnshostname, ctx.dnsdomain) ]
99 # these elements are optional
100 ctx.never_reveal_sid = None
101 ctx.reveal_sid = None
102 ctx.connection_dn = None
109 def del_noerror(ctx, dn, recursive=False):
112 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
116 ctx.del_noerror(r.dn, recursive=True)
119 print "Deleted %s" % dn
123 def cleanup_old_join(ctx):
124 '''remove any DNs from a previous join'''
126 # find the krbtgt link
127 print("checking samaccountname")
128 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
129 expression='samAccountName=%s' % ctx.samname,
130 attrs=["msDS-krbTgtLink"])
132 ctx.del_noerror(res[0].dn, recursive=True)
133 if ctx.connection_dn is not None:
134 ctx.del_noerror(ctx.connection_dn)
135 if ctx.krbtgt_dn is not None:
136 ctx.del_noerror(ctx.krbtgt_dn)
137 ctx.del_noerror(ctx.ntds_dn)
138 ctx.del_noerror(ctx.server_dn, recursive=True)
139 ctx.del_noerror(ctx.topology_dn)
141 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
142 ctx.del_noerror(ctx.new_krbtgt_dn)
146 def find_dc(ctx, domain):
147 '''find a writeable DC for the given domain'''
149 ctx.cldap_ret = ctx.net.finddc(domain, nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
150 except Exception, reason:
151 print("Failed to find a writeable DC for domain '%s': %s" % (domain, reason))
153 if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
154 ctx.site = ctx.cldap_ret.client_site
155 return ctx.cldap_ret.pdc_dns_name
158 def get_dsServiceName(ctx):
159 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
160 return res[0]["dsServiceName"][0]
162 def get_dnsHostName(ctx):
163 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
164 return res[0]["dnsHostName"][0]
166 def get_domain_name(ctx):
167 '''get netbios name of the domain from the partitions record'''
168 partitions_dn = ctx.samdb.get_partitions_dn()
169 res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
170 expression='ncName=%s' % ctx.samdb.get_default_basedn())
171 return res[0]["nETBIOSName"][0]
174 res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
175 binsid = res[0]["tokenGroups"][0]
176 return ctx.samdb.schema_format_value("objectSID", binsid)
178 def add_krbtgt_account(ctx):
179 '''RODCs need a special krbtgt account'''
180 print "Adding %s" % ctx.krbtgt_dn
182 "dn" : ctx.krbtgt_dn,
183 "objectclass" : "user",
184 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
185 samba.dsdb.UF_ACCOUNTDISABLE),
186 "showinadvancedviewonly" : "TRUE",
187 "description" : "krbtgt for %s" % ctx.samname}
188 ctx.samdb.add(rec, ["rodc_join:1:1"])
190 # now we need to search for the samAccountName attribute on the krbtgt DN,
191 # as this will have been magically set to the krbtgt number
192 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
193 ctx.krbtgt_name = res[0]["samAccountName"][0]
195 print "Got krbtgt_name=%s" % ctx.krbtgt_name
198 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
199 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
200 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
203 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
204 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
205 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
207 def drsuapi_connect(ctx):
208 '''make a DRSUAPI connection to the server'''
209 binding_string = "ncacn_ip_tcp:%s[seal]" % ctx.server
210 ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
211 ctx.drsuapi_handle = drs_utils.drs_DsBind(ctx.drsuapi)
213 def create_tmp_samdb(ctx):
214 '''create a temporary samdb object for schema queries'''
215 def setup_path(file):
216 return os.path.join(ctx.setup_dir, file)
217 ctx.tmp_schema = Schema(setup_path, security.dom_sid(ctx.domsid),
218 schemadn=ctx.schema_dn)
219 ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
220 credentials=ctx.creds, lp=ctx.lp, global_schema=False,
222 ctx.tmp_samdb.set_schema(ctx.tmp_schema)
224 def build_DsReplicaAttribute(ctx, attrname, attrvalue):
225 '''build a DsReplicaAttributeCtr object'''
226 r = drsuapi.DsReplicaAttribute()
227 r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
231 def DsAddEntry(ctx, rec):
232 '''add a record via the DRSUAPI DsAddEntry call'''
233 if ctx.drsuapi is None:
234 ctx.drsuapi_connect()
235 if ctx.tmp_samdb is None:
236 ctx.create_tmp_samdb()
238 id = drsuapi.DsReplicaObjectIdentifier()
245 if not isinstance(rec[a], list):
249 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
252 attribute_ctr = drsuapi.DsReplicaAttributeCtr()
253 attribute_ctr.num_attributes = len(attrs)
254 attribute_ctr.attributes = attrs
256 object = drsuapi.DsReplicaObject()
257 object.identifier = id
258 object.attribute_ctr = attribute_ctr
260 first_object = drsuapi.DsReplicaObjectListItem()
261 first_object.object = object
263 req2 = drsuapi.DsAddEntryRequest2()
264 req2.first_object = first_object
267 (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
270 def join_add_objects(ctx):
271 '''add the various objects needed for the join'''
272 print "Adding %s" % ctx.acct_dn
275 "objectClass": "computer",
276 "displayname": ctx.samname,
277 "samaccountname" : ctx.samname,
278 "userAccountControl" : str(ctx.userAccountControl),
279 "dnshostname" : ctx.dnshostname,
280 "msDS-SupportedEncryptionTypes" : str(samba.dsdb.ENC_ALL_TYPES)}
282 rec["managedby"] = ctx.managedby
283 if ctx.never_reveal_sid:
284 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
286 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
290 ctx.add_krbtgt_account()
292 print "Adding %s" % ctx.server_dn
295 "objectclass" : "server",
296 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
297 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
298 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
299 "serverReference" : ctx.acct_dn,
300 "dnsHostName" : ctx.dnshostname}
303 # FIXME: the partition (NC) assignment has to be made dynamic
304 print "Adding %s" % ctx.ntds_dn
307 "objectclass" : "nTDSDSA",
308 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
309 "dMDLocation" : ctx.schema_dn,
310 "msDS-Behavior-Version" : str(DS_DOMAIN_FUNCTION_2008_R2),
311 "msDS-HasDomainNCs" : ctx.base_dn }
314 rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
315 rec["msDS-HasFullReplicaNCs"] = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
316 rec["options"] = "37"
317 ctx.samdb.add(rec, ["rodc_join:1:1"])
319 rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
320 rec["HasMasterNCs"] = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
321 rec["msDS-HasMasterNCs"] = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
323 rec["invocationId"] = ndr_pack(misc.GUID(str(uuid.uuid4())))
326 # find the GUID of our NTDS DN
327 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
328 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
330 if ctx.connection_dn is not None:
331 print "Adding %s" % ctx.connection_dn
333 "dn" : ctx.connection_dn,
334 "objectclass" : "nTDSConnection",
335 "enabledconnection" : "TRUE",
337 "fromServer" : ctx.dc_ntds_dn}
340 print "Adding %s" % ctx.topology_dn
342 "dn" : ctx.topology_dn,
343 "objectclass" : "msDFSR-Member",
344 "msDFSR-ComputerReference" : ctx.acct_dn,
345 "serverReference" : ctx.ntds_dn}
348 print "Adding SPNs to %s" % ctx.acct_dn
350 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
351 for i in range(len(ctx.SPNs)):
352 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
353 m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
355 "servicePrincipalName")
358 print "Setting account password for %s" % ctx.samname
359 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ctx.samname,
361 force_change_at_next_login=False,
362 username=ctx.samname)
363 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-keyVersionNumber"])
364 ctx.key_version_number = res[0]["msDS-keyVersionNumber"]
367 def join_provision(ctx):
368 '''provision the local SAM'''
370 print "Calling bare provision"
372 logger = logging.getLogger("provision")
373 logger.addHandler(logging.StreamHandler(sys.stdout))
374 smbconf = ctx.lp.configfile
376 presult = provision(ctx.setup_dir, logger, system_session(), None,
377 smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
378 realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
379 schemadn=ctx.schema_dn,
380 configdn=ctx.config_dn,
381 serverdn=ctx.server_dn, domain=ctx.domain_name,
382 hostname=ctx.myname, hostip="127.0.0.1", domainsid=ctx.domsid,
383 machinepass=ctx.acct_pass, serverrole="domain controller",
385 print "Provision OK for domain DN %s" % presult.domaindn
386 ctx.local_samdb = presult.samdb
388 ctx.paths = presult.paths
391 def join_replicate(ctx):
392 '''replicate the SAM'''
394 print "Starting replication"
395 ctx.local_samdb.transaction_start()
397 source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
399 acct_creds = Credentials()
400 acct_creds.guess(ctx.lp)
401 acct_creds.set_kerberos_state(DONT_USE_KERBEROS)
402 acct_creds.set_username(ctx.samname)
403 acct_creds.set_password(ctx.acct_pass)
405 repl = drs_utils.drs_Replicate("ncacn_ip_tcp:%s[seal]" % ctx.server, ctx.lp, acct_creds, ctx.local_samdb)
407 repl.replicate(ctx.schema_dn, source_dsa_invocation_id, ctx.ntds_guid, schema=True, rodc=ctx.RODC)
408 repl.replicate(ctx.config_dn, source_dsa_invocation_id, ctx.ntds_guid, rodc=ctx.RODC)
409 repl.replicate(ctx.base_dn, source_dsa_invocation_id, ctx.ntds_guid, rodc=ctx.RODC)
411 repl.replicate(ctx.acct_dn, source_dsa_invocation_id, ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
412 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id, ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
414 print "Committing SAM database"
415 ctx.local_samdb.transaction_commit()
418 def join_finalise(ctx):
419 '''finalise the join, mark us synchronised and setup secrets db'''
421 print "Setting isSynchronized"
423 m.dn = ldb.Dn(ctx.samdb, '@ROOTDSE')
424 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
427 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
429 print "Setting up secrets database"
430 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
432 dnsdomain=ctx.dnsdomain,
433 netbiosname=ctx.myname,
434 domainsid=security.dom_sid(ctx.domsid),
435 machinepass=ctx.acct_pass,
436 secure_channel_type=ctx.secure_channel_type,
437 key_version_number=ctx.key_version_number)
440 ctx.cleanup_old_join()
442 ctx.join_add_objects()
447 print "Join failed - cleaning up"
448 ctx.cleanup_old_join()
452 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
453 targetdir=None, domain=None):
456 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
458 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
460 # setup some defaults for accounts that should be replicated to this RODC
461 ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
462 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
463 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
464 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
465 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
466 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
468 ctx.managedby = ctx.admin_dn
470 ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
471 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
472 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
474 ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
475 "RestrictedKrbHost/%s" % ctx.dnshostname ])
477 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
478 ctx.secure_channel_type = misc.SEC_CHAN_RODC
481 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
484 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
485 targetdir=None, domain=None):
487 ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
489 ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
491 ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
492 ctx.secure_channel_type = misc.SEC_CHAN_BDC
495 print "Joined domain %s (SID %s) as an DC" % (ctx.domain_name, ctx.domsid)