s4-join: fixed DNS hostname
[mdw/samba.git] / source4 / scripting / python / samba / join.py
1 #!/usr/bin/env python
2 #
3 # python join code
4 # Copyright Andrew Tridgell 2010
5 # Copyright Andrew Bartlett 2010
6 #
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.
11 #
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.
16 #
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/>.
19 #
20
21 """Joining a domain."""
22
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
29 from samba.credentials import Credentials, DONT_USE_KERBEROS
30 from samba.provision import secretsdb_self_join, provision, FILL_DRS
31 from samba.schema import Schema
32 from samba.net import Net
33 import logging
34 import talloc
35
36 # this makes debugging easier
37 talloc.enable_null_tracking()
38
39 class DCJoinException(Exception):
40
41     def __init__(self, msg):
42         super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
43
44
45 class dc_join(object):
46     '''perform a DC join'''
47
48     def __init__(ctx, server=None, creds=None, lp=None, site=None,
49             netbios_name=None, targetdir=None, domain=None):
50         ctx.creds = creds
51         ctx.lp = lp
52         ctx.site = site
53         ctx.netbios_name = netbios_name
54         ctx.targetdir = targetdir
55
56         ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
57         ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
58
59         if server is not None:
60             ctx.server = server
61         else:
62             print("Finding a writeable DC for domain '%s'" % domain)
63             ctx.server = ctx.find_dc(domain)
64             print("Found DC %s" % ctx.server)
65
66         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
67                           session_info=system_session(),
68                           credentials=ctx.creds, lp=ctx.lp)
69
70         try:
71             ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
72         except ldb.LdbError, (enum, estr):
73             raise DCJoinException(estr)
74
75
76         ctx.myname = netbios_name
77         ctx.samname = "%s$" % ctx.myname
78         ctx.base_dn = str(ctx.samdb.get_default_basedn())
79         ctx.root_dn = str(ctx.samdb.get_root_basedn())
80         ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
81         ctx.config_dn = str(ctx.samdb.get_config_basedn())
82         ctx.domsid = ctx.samdb.get_domain_sid()
83         ctx.domain_name = ctx.get_domain_name()
84
85         lp.set("workgroup", ctx.domain_name)
86         print("workgroup is %s" % ctx.domain_name)
87
88         ctx.dc_ntds_dn = ctx.get_dsServiceName()
89         ctx.dc_dnsHostName = ctx.get_dnsHostName()
90         ctx.behavior_version = ctx.get_behavior_version()
91
92         ctx.acct_pass = samba.generate_random_password(32, 40)
93
94         # work out the DNs of all the objects we will be adding
95         ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
96         ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
97         topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
98         if ctx.dn_exists(topology_base):
99             ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
100         else:
101             ctx.topology_dn = None
102
103         ctx.dnsdomain = ctx.samdb.domain_dns_name()
104         ctx.dnsforest = ctx.samdb.forest_dns_name()
105         ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
106
107         ctx.realm = ctx.dnsdomain
108         lp.set("realm", ctx.realm)
109
110         print("realm is %s" % ctx.realm)
111
112         ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
113
114         ctx.tmp_samdb = None
115
116         ctx.SPNs = [ "HOST/%s" % ctx.myname,
117                      "HOST/%s" % ctx.dnshostname,
118                      "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
119
120         # these elements are optional
121         ctx.never_reveal_sid = None
122         ctx.reveal_sid = None
123         ctx.connection_dn = None
124         ctx.RODC = False
125         ctx.krbtgt_dn = None
126         ctx.drsuapi = None
127         ctx.managedby = None
128
129
130     def del_noerror(ctx, dn, recursive=False):
131         if recursive:
132             try:
133                 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
134             except Exception:
135                 return
136             for r in res:
137                 ctx.del_noerror(r.dn, recursive=True)
138         try:
139             ctx.samdb.delete(dn)
140             print "Deleted %s" % dn
141         except Exception:
142             pass
143
144     def cleanup_old_join(ctx):
145         '''remove any DNs from a previous join'''
146         try:
147             # find the krbtgt link
148             print("checking samaccountname")
149             res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
150                                    expression='samAccountName=%s' % ldb.binary_encode(ctx.samname),
151                                    attrs=["msDS-krbTgtLink"])
152             if res:
153                 ctx.del_noerror(res[0].dn, recursive=True)
154             if ctx.connection_dn is not None:
155                 ctx.del_noerror(ctx.connection_dn)
156             if ctx.krbtgt_dn is not None:
157                 ctx.del_noerror(ctx.krbtgt_dn)
158             ctx.del_noerror(ctx.ntds_dn)
159             ctx.del_noerror(ctx.server_dn, recursive=True)
160             if ctx.topology_dn:
161                 ctx.del_noerror(ctx.topology_dn)
162             if res:
163                 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
164                 ctx.del_noerror(ctx.new_krbtgt_dn)
165         except Exception:
166             pass
167
168     def find_dc(ctx, domain):
169         '''find a writeable DC for the given domain'''
170         try:
171             ctx.cldap_ret = ctx.net.finddc(domain, nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
172         except Exception:
173             raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
174         if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
175             ctx.site = ctx.cldap_ret.client_site
176         return ctx.cldap_ret.pdc_dns_name
177
178
179     def get_dsServiceName(ctx):
180         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
181         return res[0]["dsServiceName"][0]
182
183     def get_behavior_version(ctx):
184         res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
185         if "msDS-Behavior-Version" in res[0]:
186             return int(res[0]["msDS-Behavior-Version"][0])
187         else:
188             return samba.dsdb.DS_DOMAIN_FUNCTION_2000
189
190     def get_dnsHostName(ctx):
191         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
192         return res[0]["dnsHostName"][0]
193
194     def get_domain_name(ctx):
195         '''get netbios name of the domain from the partitions record'''
196         partitions_dn = ctx.samdb.get_partitions_dn()
197         res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
198                                expression='ncName=%s' % ctx.samdb.get_default_basedn())
199         return res[0]["nETBIOSName"][0]
200
201     def get_mysid(ctx):
202         '''get the SID of the connected user. Only works with w2k8 and later,
203            so only used for RODC join'''
204         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
205         binsid = res[0]["tokenGroups"][0]
206         return ctx.samdb.schema_format_value("objectSID", binsid)
207
208     def dn_exists(ctx, dn):
209         '''check if a DN exists'''
210         try:
211             res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
212         except ldb.LdbError, (enum, estr):
213             if enum == ldb.ERR_NO_SUCH_OBJECT:
214                 return False
215             raise
216         return True
217
218     def add_krbtgt_account(ctx):
219         '''RODCs need a special krbtgt account'''
220         print "Adding %s" % ctx.krbtgt_dn
221         rec = {
222             "dn" : ctx.krbtgt_dn,
223             "objectclass" : "user",
224             "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
225                                        samba.dsdb.UF_ACCOUNTDISABLE),
226             "showinadvancedviewonly" : "TRUE",
227             "description" : "krbtgt for %s" % ctx.samname}
228         ctx.samdb.add(rec, ["rodc_join:1:1"])
229
230         # now we need to search for the samAccountName attribute on the krbtgt DN,
231         # as this will have been magically set to the krbtgt number
232         res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
233         ctx.krbtgt_name = res[0]["samAccountName"][0]
234
235         print "Got krbtgt_name=%s" % ctx.krbtgt_name
236
237         m = ldb.Message()
238         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
239         m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
240                                                   ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
241         ctx.samdb.modify(m)
242
243         ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
244         print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
245         ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
246
247     def drsuapi_connect(ctx):
248         '''make a DRSUAPI connection to the server'''
249         binding_options = "seal"
250         if int(ctx.lp.get("log level")) >= 5:
251             binding_options += ",print"
252         binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
253         ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
254         (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
255
256     def create_tmp_samdb(ctx):
257         '''create a temporary samdb object for schema queries'''
258         ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
259                                 schemadn=ctx.schema_dn)
260         ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
261                               credentials=ctx.creds, lp=ctx.lp, global_schema=False,
262                               am_rodc=False)
263         ctx.tmp_samdb.set_schema(ctx.tmp_schema)
264
265     def build_DsReplicaAttribute(ctx, attrname, attrvalue):
266         '''build a DsReplicaAttributeCtr object'''
267         r = drsuapi.DsReplicaAttribute()
268         r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
269         r.value_ctr = 1
270
271
272     def DsAddEntry(ctx, rec):
273         '''add a record via the DRSUAPI DsAddEntry call'''
274         if ctx.drsuapi is None:
275             ctx.drsuapi_connect()
276         if ctx.tmp_samdb is None:
277             ctx.create_tmp_samdb()
278
279         id = drsuapi.DsReplicaObjectIdentifier()
280         id.dn = rec['dn']
281
282         attrs = []
283         for a in rec:
284             if a == 'dn':
285                 continue
286             if not isinstance(rec[a], list):
287                 v = [rec[a]]
288             else:
289                 v = rec[a]
290             rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
291             attrs.append(rattr)
292
293         attribute_ctr = drsuapi.DsReplicaAttributeCtr()
294         attribute_ctr.num_attributes = len(attrs)
295         attribute_ctr.attributes = attrs
296
297         object = drsuapi.DsReplicaObject()
298         object.identifier = id
299         object.attribute_ctr = attribute_ctr
300
301         first_object = drsuapi.DsReplicaObjectListItem()
302         first_object.object = object
303
304         req2 = drsuapi.DsAddEntryRequest2()
305         req2.first_object = first_object
306
307         (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
308         if ctr.err_ver != 1:
309             raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
310         if ctr.err_data.status != (0, 'WERR_OK'):
311             print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
312                                                                 ctr.err_data.info.extended_err))
313             raise RuntimeError("DsAddEntry failed")
314
315     def join_add_objects(ctx):
316         '''add the various objects needed for the join'''
317         print "Adding %s" % ctx.acct_dn
318         rec = {
319             "dn" : ctx.acct_dn,
320             "objectClass": "computer",
321             "displayname": ctx.samname,
322             "samaccountname" : ctx.samname,
323             "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
324             "dnshostname" : ctx.dnshostname}
325         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
326             rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
327         if ctx.managedby:
328             rec["managedby"] = ctx.managedby
329         if ctx.never_reveal_sid:
330             rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
331         if ctx.reveal_sid:
332             rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
333         ctx.samdb.add(rec)
334
335         if ctx.krbtgt_dn:
336             ctx.add_krbtgt_account()
337
338         print "Adding %s" % ctx.server_dn
339         rec = {
340             "dn": ctx.server_dn,
341             "objectclass" : "server",
342             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
343                                 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
344                                 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
345             "serverReference" : ctx.acct_dn,
346             "dnsHostName" : ctx.dnshostname}
347         ctx.samdb.add(rec)
348
349         # FIXME: the partition (NC) assignment has to be made dynamic
350         print "Adding %s" % ctx.ntds_dn
351         rec = {
352             "dn" : ctx.ntds_dn,
353             "objectclass" : "nTDSDSA",
354             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
355             "dMDLocation" : ctx.schema_dn}
356
357         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
358             rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
359
360         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
361             rec["msDS-HasDomainNCs"] = ctx.base_dn
362
363         if ctx.RODC:
364             rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
365             rec["msDS-HasFullReplicaNCs"] = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
366             rec["options"] = "37"
367             ctx.samdb.add(rec, ["rodc_join:1:1"])
368         else:
369             rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
370             rec["HasMasterNCs"]      = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
371             if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
372                 rec["msDS-HasMasterNCs"] = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
373             rec["options"] = "1"
374             rec["invocationId"] = ndr_pack(misc.GUID(str(uuid.uuid4())))
375             ctx.DsAddEntry(rec)
376
377         # find the GUID of our NTDS DN
378         res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
379         ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
380
381         if ctx.connection_dn is not None:
382             print "Adding %s" % ctx.connection_dn
383             rec = {
384                 "dn" : ctx.connection_dn,
385                 "objectclass" : "nTDSConnection",
386                 "enabledconnection" : "TRUE",
387                 "options" : "65",
388                 "fromServer" : ctx.dc_ntds_dn}
389             ctx.samdb.add(rec)
390
391         if ctx.topology_dn:
392             print "Adding %s" % ctx.topology_dn
393             rec = {
394                 "dn" : ctx.topology_dn,
395                 "objectclass" : "msDFSR-Member",
396                 "msDFSR-ComputerReference" : ctx.acct_dn,
397                 "serverReference" : ctx.ntds_dn}
398             ctx.samdb.add(rec)
399
400         print "Adding SPNs to %s" % ctx.acct_dn
401         m = ldb.Message()
402         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
403         for i in range(len(ctx.SPNs)):
404             ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
405         m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
406                                                        ldb.FLAG_MOD_ADD,
407                                                        "servicePrincipalName")
408         ctx.samdb.modify(m)
409
410         print "Setting account password for %s" % ctx.samname
411         ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ldb.binary_encode(ctx.samname),
412                               ctx.acct_pass,
413                               force_change_at_next_login=False,
414                               username=ctx.samname)
415         res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-keyVersionNumber"])
416         ctx.key_version_number = int(res[0]["msDS-keyVersionNumber"][0])
417
418         print("Enabling account")
419         m = ldb.Message()
420         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
421         m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
422                                                      ldb.FLAG_MOD_REPLACE,
423                                                      "userAccountControl")
424         ctx.samdb.modify(m)
425
426     def join_provision(ctx):
427         '''provision the local SAM'''
428
429         print "Calling bare provision"
430
431         logger = logging.getLogger("provision")
432         logger.addHandler(logging.StreamHandler(sys.stdout))
433         smbconf = ctx.lp.configfile
434
435         presult = provision(logger, system_session(), None,
436                             smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
437                             realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
438                             schemadn=ctx.schema_dn,
439                             configdn=ctx.config_dn,
440                             serverdn=ctx.server_dn, domain=ctx.domain_name,
441                             hostname=ctx.myname, domainsid=ctx.domsid,
442                             machinepass=ctx.acct_pass, serverrole="domain controller",
443                             sitename=ctx.site, lp=ctx.lp)
444         print "Provision OK for domain DN %s" % presult.domaindn
445         ctx.local_samdb = presult.samdb
446         ctx.lp          = presult.lp
447         ctx.paths       = presult.paths
448
449
450     def join_replicate(ctx):
451         '''replicate the SAM'''
452
453         print "Starting replication"
454         ctx.local_samdb.transaction_start()
455         try:
456             source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
457             destination_dsa_guid = ctx.ntds_guid
458
459             if ctx.RODC:
460                 repl_creds = Credentials()
461                 repl_creds.guess(ctx.lp)
462                 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
463                 repl_creds.set_username(ctx.samname)
464                 repl_creds.set_password(ctx.acct_pass)
465             else:
466                 repl_creds = ctx.creds
467
468             binding_options = "seal"
469             if int(ctx.lp.get("log level")) >= 5:
470                 binding_options += ",print"
471             repl = drs_utils.drs_Replicate(
472                 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
473                 ctx.lp, repl_creds, ctx.local_samdb)
474
475             repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
476                     destination_dsa_guid, schema=True, rodc=ctx.RODC,
477                     replica_flags=ctx.replica_flags)
478             repl.replicate(ctx.config_dn, source_dsa_invocation_id,
479                     destination_dsa_guid, rodc=ctx.RODC,
480                     replica_flags=ctx.replica_flags)
481             repl.replicate(ctx.base_dn, source_dsa_invocation_id,
482                     destination_dsa_guid, rodc=ctx.RODC,
483                     replica_flags=ctx.domain_replica_flags)
484             if ctx.RODC:
485                 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
486                         destination_dsa_guid,
487                         exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
488                 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
489                         destination_dsa_guid,
490                         exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
491
492             print "Committing SAM database"
493         except:
494             ctx.local_samdb.transaction_cancel()
495             raise
496         else:
497             ctx.local_samdb.transaction_commit()
498
499
500     def join_finalise(ctx):
501         '''finalise the join, mark us synchronised and setup secrets db'''
502
503         print "Setting isSynchronized and dsServiceName"
504         m = ldb.Message()
505         m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
506         m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
507         m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
508                                                 ldb.FLAG_MOD_REPLACE, "dsServiceName")
509         ctx.local_samdb.modify(m)
510
511         secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
512
513         print "Setting up secrets database"
514         secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
515                             realm=ctx.realm,
516                             dnsdomain=ctx.dnsdomain,
517                             netbiosname=ctx.myname,
518                             domainsid=security.dom_sid(ctx.domsid),
519                             machinepass=ctx.acct_pass,
520                             secure_channel_type=ctx.secure_channel_type,
521                             key_version_number=ctx.key_version_number)
522
523     def do_join(ctx):
524         ctx.cleanup_old_join()
525         try:
526             ctx.join_add_objects()
527             ctx.join_provision()
528             ctx.join_replicate()
529             ctx.join_finalise()
530         except Exception:
531             print "Join failed - cleaning up"
532             ctx.cleanup_old_join()
533             raise
534
535
536 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
537               targetdir=None, domain=None, domain_critical_only=False):
538     """join as a RODC"""
539
540     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
541
542     ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
543
544     # setup some defaults for accounts that should be replicated to this RODC
545     ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
546                              "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
547                              "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
548                              "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
549                              "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
550     ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
551
552     mysid = ctx.get_mysid()
553     admin_dn = "<SID=%s>" % mysid
554     ctx.managedby = admin_dn
555
556     ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
557                               samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
558                               samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
559
560     ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
561                       "RestrictedKrbHost/%s" % ctx.dnshostname ])
562
563     ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
564     ctx.secure_channel_type = misc.SEC_CHAN_RODC
565     ctx.RODC = True
566     ctx.replica_flags  =  (drsuapi.DRSUAPI_DRS_INIT_SYNC |
567                            drsuapi.DRSUAPI_DRS_PER_SYNC |
568                            drsuapi.DRSUAPI_DRS_GET_ANC |
569                            drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
570                            drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
571                            drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
572     ctx.domain_replica_flags = ctx.replica_flags
573     if domain_critical_only:
574         ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
575
576     ctx.do_join()
577
578
579     print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
580
581
582 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
583             targetdir=None, domain=None, domain_critical_only=False):
584     """join as a DC"""
585     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
586
587     ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
588
589     ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
590     ctx.secure_channel_type = misc.SEC_CHAN_BDC
591
592     ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
593                          drsuapi.DRSUAPI_DRS_INIT_SYNC |
594                          drsuapi.DRSUAPI_DRS_PER_SYNC |
595                          drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
596                          drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
597     ctx.domain_replica_flags = ctx.replica_flags
598     if domain_critical_only:
599         ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
600
601     ctx.do_join()
602     print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)