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