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