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