5ddc5db1ad833c064f0082e2167d53a3407db82f
[mat/samba.git] / source4 / scripting / python / samba / join.py
1 # python join code
2 # Copyright Andrew Tridgell 2010
3 # Copyright Andrew Bartlett 2010
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18
19 """Joining a domain."""
20
21 from samba.auth import system_session
22 from samba.samdb import SamDB
23 from samba import gensec, Ldb, drs_utils
24 import ldb, samba, sys, uuid
25 from samba.ndr import ndr_pack
26 from samba.dcerpc import security, drsuapi, misc, nbt, lsa, drsblobs
27 from samba.credentials import Credentials, DONT_USE_KERBEROS
28 from samba.provision import secretsdb_self_join, provision, provision_fill, FILL_DRS, FILL_SUBDOMAIN
29 from samba.schema import Schema
30 from samba.net import Net
31 from samba.provision.sambadns import setup_bind9_dns
32 import logging
33 import talloc
34 import random
35 import time
36
37 # this makes debugging easier
38 talloc.enable_null_tracking()
39
40 class DCJoinException(Exception):
41
42     def __init__(self, msg):
43         super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
44
45
46 class dc_join(object):
47     """Perform a DC join."""
48
49     def __init__(ctx, server=None, creds=None, lp=None, site=None,
50                  netbios_name=None, targetdir=None, domain=None,
51                  machinepass=None, use_ntvfs=False, dns_backend=None,
52                  promote_existing=False):
53         ctx.creds = creds
54         ctx.lp = lp
55         ctx.site = site
56         ctx.netbios_name = netbios_name
57         ctx.targetdir = targetdir
58         ctx.use_ntvfs = use_ntvfs
59
60         ctx.promote_existing = promote_existing
61         ctx.promote_from_dn = None
62
63         ctx.nc_list = []
64         ctx.full_nc_list = []
65
66         ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
67         ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
68
69         if server is not None:
70             ctx.server = server
71         else:
72             print("Finding a writeable DC for domain '%s'" % domain)
73             ctx.server = ctx.find_dc(domain)
74             print("Found DC %s" % ctx.server)
75
76         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
77                           session_info=system_session(),
78                           credentials=ctx.creds, lp=ctx.lp)
79
80         try:
81             ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
82         except ldb.LdbError, (enum, estr):
83             raise DCJoinException(estr)
84
85
86         ctx.myname = netbios_name
87         ctx.samname = "%s$" % ctx.myname
88         ctx.base_dn = str(ctx.samdb.get_default_basedn())
89         ctx.root_dn = str(ctx.samdb.get_root_basedn())
90         ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
91         ctx.config_dn = str(ctx.samdb.get_config_basedn())
92         ctx.domsid = ctx.samdb.get_domain_sid()
93         ctx.domain_name = ctx.get_domain_name()
94         ctx.forest_domain_name = ctx.get_forest_domain_name()
95         ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
96
97         ctx.dc_ntds_dn = ctx.samdb.get_dsServiceName()
98         ctx.dc_dnsHostName = ctx.get_dnsHostName()
99         ctx.behavior_version = ctx.get_behavior_version()
100
101         if machinepass is not None:
102             ctx.acct_pass = machinepass
103         else:
104             ctx.acct_pass = samba.generate_random_password(32, 40)
105
106         # work out the DNs of all the objects we will be adding
107         ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
108         ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
109         topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
110         if ctx.dn_exists(topology_base):
111             ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
112         else:
113             ctx.topology_dn = None
114
115         ctx.dnsdomain = ctx.samdb.domain_dns_name()
116         ctx.dnsforest = ctx.samdb.forest_dns_name()
117         ctx.domaindns_zone = 'DC=DomainDnsZones,%s' % ctx.base_dn
118
119         res_domaindns = ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL,
120                                          attrs=[],
121                                          base=ctx.samdb.get_partitions_dn(),
122                                          expression="(&(objectClass=crossRef)(ncName=%s))" % ctx.domaindns_zone)
123         if dns_backend is None:
124             ctx.dns_backend = "NONE"
125         else:
126             if len(res_domaindns) == 0:
127                 ctx.dns_backend = "NONE"
128                 print "NO DNS zone information found in source domain, not replicating DNS"
129             else:
130                 ctx.dns_backend = dns_backend
131
132         ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
133
134         ctx.realm = ctx.dnsdomain
135
136         ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
137
138         ctx.tmp_samdb = None
139
140         ctx.SPNs = [ "HOST/%s" % ctx.myname,
141                      "HOST/%s" % ctx.dnshostname,
142                      "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
143
144         # these elements are optional
145         ctx.never_reveal_sid = None
146         ctx.reveal_sid = None
147         ctx.connection_dn = None
148         ctx.RODC = False
149         ctx.krbtgt_dn = None
150         ctx.drsuapi = None
151         ctx.managedby = None
152         ctx.subdomain = False
153
154     def del_noerror(ctx, dn, recursive=False):
155         if recursive:
156             try:
157                 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
158             except Exception:
159                 return
160             for r in res:
161                 ctx.del_noerror(r.dn, recursive=True)
162         try:
163             ctx.samdb.delete(dn)
164             print "Deleted %s" % dn
165         except Exception:
166             pass
167
168     def cleanup_old_join(ctx):
169         """Remove any DNs from a previous join."""
170         try:
171             # find the krbtgt link
172             print("checking sAMAccountName")
173             if ctx.subdomain:
174                 res = None
175             else:
176                 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
177                                        expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
178                                        attrs=["msDS-krbTgtLink"])
179                 if res:
180                     ctx.del_noerror(res[0].dn, recursive=True)
181             if ctx.connection_dn is not None:
182                 ctx.del_noerror(ctx.connection_dn)
183             if ctx.krbtgt_dn is not None:
184                 ctx.del_noerror(ctx.krbtgt_dn)
185             ctx.del_noerror(ctx.ntds_dn)
186             ctx.del_noerror(ctx.server_dn, recursive=True)
187             if ctx.topology_dn:
188                 ctx.del_noerror(ctx.topology_dn)
189             if ctx.partition_dn:
190                 ctx.del_noerror(ctx.partition_dn)
191             if res:
192                 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
193                 ctx.del_noerror(ctx.new_krbtgt_dn)
194
195             if ctx.subdomain:
196                 binding_options = "sign"
197                 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
198                                      ctx.lp, ctx.creds)
199
200                 objectAttr = lsa.ObjectAttribute()
201                 objectAttr.sec_qos = lsa.QosInfo()
202
203                 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
204                                                  objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
205
206                 name = lsa.String()
207                 name.string = ctx.realm
208                 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
209
210                 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
211
212                 name = lsa.String()
213                 name.string = ctx.forest_domain_name
214                 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
215
216                 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
217
218         except Exception:
219             pass
220
221     def promote_possible(ctx):
222         """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
223         if ctx.subdomain:
224             # This shouldn't happen
225             raise Exception("Can not promote into a subdomain")
226
227         res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
228                                expression='sAMAccountName=%s' % ldb.binary_encode(ctx.samname),
229                                attrs=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
230         if len(res) == 0:
231             raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx.samname)
232         if "msDS-krbTgtLink" in res[0] or "serverReferenceBL" in res[0] or "rIDSetReferences" in res[0]:
233             raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx.samname)
234         if (int(res[0]["userAccountControl"][0]) & (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT|samba.dsdb.UF_SERVER_TRUST_ACCOUNT) == 0):
235             raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx.samname)
236
237         ctx.promote_from_dn = res[0].dn
238
239
240     def find_dc(ctx, domain):
241         """find a writeable DC for the given domain"""
242         try:
243             ctx.cldap_ret = ctx.net.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
244         except Exception:
245             raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
246         if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
247             ctx.site = ctx.cldap_ret.client_site
248         return ctx.cldap_ret.pdc_dns_name
249
250
251     def get_behavior_version(ctx):
252         res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
253         if "msDS-Behavior-Version" in res[0]:
254             return int(res[0]["msDS-Behavior-Version"][0])
255         else:
256             return samba.dsdb.DS_DOMAIN_FUNCTION_2000
257
258     def get_dnsHostName(ctx):
259         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
260         return res[0]["dnsHostName"][0]
261
262     def get_domain_name(ctx):
263         '''get netbios name of the domain from the partitions record'''
264         partitions_dn = ctx.samdb.get_partitions_dn()
265         res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
266                                expression='ncName=%s' % ctx.samdb.get_default_basedn())
267         return res[0]["nETBIOSName"][0]
268
269     def get_forest_domain_name(ctx):
270         '''get netbios name of the domain from the partitions record'''
271         partitions_dn = ctx.samdb.get_partitions_dn()
272         res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
273                                expression='ncName=%s' % ctx.samdb.get_root_basedn())
274         return res[0]["nETBIOSName"][0]
275
276     def get_parent_partition_dn(ctx):
277         '''get the parent domain partition DN from parent DNS name'''
278         res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
279                                expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
280                                (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
281         return str(res[0].dn)
282
283     def get_naming_master(ctx):
284         '''get the parent domain partition DN from parent DNS name'''
285         res = ctx.samdb.search(base='CN=Partitions,%s' % ctx.config_dn, attrs=['fSMORoleOwner'],
286                                scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
287         if not 'fSMORoleOwner' in res[0]:
288             raise DCJoinException("Can't find naming master on partition DN %s" % ctx.partition_dn)
289         master_guid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
290         master_host = '%s._msdcs.%s' % (master_guid, ctx.dnsforest)
291         return master_host
292
293     def get_mysid(ctx):
294         '''get the SID of the connected user. Only works with w2k8 and later,
295            so only used for RODC join'''
296         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
297         binsid = res[0]["tokenGroups"][0]
298         return ctx.samdb.schema_format_value("objectSID", binsid)
299
300     def dn_exists(ctx, dn):
301         '''check if a DN exists'''
302         try:
303             res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
304         except ldb.LdbError, (enum, estr):
305             if enum == ldb.ERR_NO_SUCH_OBJECT:
306                 return False
307             raise
308         return True
309
310     def add_krbtgt_account(ctx):
311         '''RODCs need a special krbtgt account'''
312         print "Adding %s" % ctx.krbtgt_dn
313         rec = {
314             "dn" : ctx.krbtgt_dn,
315             "objectclass" : "user",
316             "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
317                                        samba.dsdb.UF_ACCOUNTDISABLE),
318             "showinadvancedviewonly" : "TRUE",
319             "description" : "krbtgt for %s" % ctx.samname}
320         ctx.samdb.add(rec, ["rodc_join:1:1"])
321
322         # now we need to search for the samAccountName attribute on the krbtgt DN,
323         # as this will have been magically set to the krbtgt number
324         res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
325         ctx.krbtgt_name = res[0]["samAccountName"][0]
326
327         print "Got krbtgt_name=%s" % ctx.krbtgt_name
328
329         m = ldb.Message()
330         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
331         m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
332                                                   ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
333         ctx.samdb.modify(m)
334
335         ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
336         print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
337         ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
338
339     def drsuapi_connect(ctx):
340         '''make a DRSUAPI connection to the naming master'''
341         binding_options = "seal"
342         if int(ctx.lp.get("log level")) >= 4:
343             binding_options += ",print"
344         binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
345         ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
346         (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
347
348     def create_tmp_samdb(ctx):
349         '''create a temporary samdb object for schema queries'''
350         ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
351                                 schemadn=ctx.schema_dn)
352         ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
353                               credentials=ctx.creds, lp=ctx.lp, global_schema=False,
354                               am_rodc=False)
355         ctx.tmp_samdb.set_schema(ctx.tmp_schema)
356
357     def build_DsReplicaAttribute(ctx, attrname, attrvalue):
358         '''build a DsReplicaAttributeCtr object'''
359         r = drsuapi.DsReplicaAttribute()
360         r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
361         r.value_ctr = 1
362
363
364     def DsAddEntry(ctx, recs):
365         '''add a record via the DRSUAPI DsAddEntry call'''
366         if ctx.drsuapi is None:
367             ctx.drsuapi_connect()
368         if ctx.tmp_samdb is None:
369             ctx.create_tmp_samdb()
370
371         objects = []
372         for rec in recs:
373             id = drsuapi.DsReplicaObjectIdentifier()
374             id.dn = rec['dn']
375
376             attrs = []
377             for a in rec:
378                 if a == 'dn':
379                     continue
380                 if not isinstance(rec[a], list):
381                     v = [rec[a]]
382                 else:
383                     v = rec[a]
384                 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
385                 attrs.append(rattr)
386
387             attribute_ctr = drsuapi.DsReplicaAttributeCtr()
388             attribute_ctr.num_attributes = len(attrs)
389             attribute_ctr.attributes = attrs
390
391             object = drsuapi.DsReplicaObject()
392             object.identifier = id
393             object.attribute_ctr = attribute_ctr
394
395             list_object = drsuapi.DsReplicaObjectListItem()
396             list_object.object = object
397             objects.append(list_object)
398
399         req2 = drsuapi.DsAddEntryRequest2()
400         req2.first_object = objects[0]
401         prev = req2.first_object
402         for o in objects[1:]:
403             prev.next_object = o
404             prev = o
405
406         (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
407         if level == 2:
408             if ctr.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
409                 print("DsAddEntry failed with dir_err %u" % ctr.dir_err)
410                 raise RuntimeError("DsAddEntry failed")
411             if ctr.extended_err != (0, 'WERR_OK'):
412                 print("DsAddEntry failed with status %s info %s" % (ctr.extended_err))
413                 raise RuntimeError("DsAddEntry failed")
414         if level == 3:
415             if ctr.err_ver != 1:
416                 raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
417             if ctr.err_data.status != (0, 'WERR_OK'):
418                 print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
419                                                                     ctr.err_data.info.extended_err))
420                 raise RuntimeError("DsAddEntry failed")
421             if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
422                 print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
423                 raise RuntimeError("DsAddEntry failed")
424
425         return ctr.objects
426
427     def join_add_ntdsdsa(ctx):
428         '''add the ntdsdsa object'''
429         # FIXME: the partition (NC) assignment has to be made dynamic
430         print "Adding %s" % ctx.ntds_dn
431         rec = {
432             "dn" : ctx.ntds_dn,
433             "objectclass" : "nTDSDSA",
434             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
435             "dMDLocation" : ctx.schema_dn}
436
437         nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
438
439         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
440             rec["msDS-Behavior-Version"] = str(samba.dsdb.DS_DOMAIN_FUNCTION_2008_R2)
441
442         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
443             rec["msDS-HasDomainNCs"] = ctx.base_dn
444
445         if ctx.RODC:
446             rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
447             rec["msDS-HasFullReplicaNCs"] = ctx.nc_list
448             rec["options"] = "37"
449             ctx.samdb.add(rec, ["rodc_join:1:1"])
450         else:
451             rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
452             rec["HasMasterNCs"]      = nc_list
453             if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
454                 rec["msDS-HasMasterNCs"] = ctx.nc_list
455             rec["options"] = "1"
456             rec["invocationId"] = ndr_pack(ctx.invocation_id)
457             ctx.DsAddEntry([rec])
458
459         # find the GUID of our NTDS DN
460         res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
461         ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
462
463     def join_add_objects(ctx):
464         '''add the various objects needed for the join'''
465         if ctx.acct_dn:
466             print "Adding %s" % ctx.acct_dn
467             rec = {
468                 "dn" : ctx.acct_dn,
469                 "objectClass": "computer",
470                 "displayname": ctx.samname,
471                 "samaccountname" : ctx.samname,
472                 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
473                 "dnshostname" : ctx.dnshostname}
474             if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
475                 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
476             elif ctx.promote_existing:
477                 rec['msDS-SupportedEncryptionTypes'] = []
478             if ctx.managedby:
479                 rec["managedby"] = ctx.managedby
480             elif ctx.promote_existing:
481                 rec["managedby"] = []
482
483             if ctx.never_reveal_sid:
484                 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
485             elif ctx.promote_existing:
486                 rec["msDS-NeverRevealGroup"] = []
487
488             if ctx.reveal_sid:
489                 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
490             elif ctx.promote_existing:
491                 rec["msDS-RevealOnDemandGroup"] = []
492
493             if ctx.promote_existing:
494                 if ctx.promote_from_dn != ctx.acct_dn:
495                     ctx.samdb.rename(ctx.promote_from_dn, ctx.acct_dn)
496                 ctx.samdb.modify(ldb.Message.from_dict(ctx.samdb, rec, ldb.FLAG_MOD_REPLACE))
497             else:
498                 ctx.samdb.add(rec)
499
500         if ctx.krbtgt_dn:
501             ctx.add_krbtgt_account()
502
503         print "Adding %s" % ctx.server_dn
504         rec = {
505             "dn": ctx.server_dn,
506             "objectclass" : "server",
507             # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
508             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
509                                 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
510                                 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
511             # windows seems to add the dnsHostName later
512             "dnsHostName" : ctx.dnshostname}
513
514         if ctx.acct_dn:
515             rec["serverReference"] = ctx.acct_dn
516
517         ctx.samdb.add(rec)
518
519         if ctx.subdomain:
520             # the rest is done after replication
521             ctx.ntds_guid = None
522             return
523
524         ctx.join_add_ntdsdsa()
525
526         if ctx.connection_dn is not None:
527             print "Adding %s" % ctx.connection_dn
528             rec = {
529                 "dn" : ctx.connection_dn,
530                 "objectclass" : "nTDSConnection",
531                 "enabledconnection" : "TRUE",
532                 "options" : "65",
533                 "fromServer" : ctx.dc_ntds_dn}
534             ctx.samdb.add(rec)
535
536         if ctx.acct_dn:
537             print "Adding SPNs to %s" % ctx.acct_dn
538             m = ldb.Message()
539             m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
540             for i in range(len(ctx.SPNs)):
541                 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
542             m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
543                                                            ldb.FLAG_MOD_REPLACE,
544                                                            "servicePrincipalName")
545             ctx.samdb.modify(m)
546
547             # The account password set operation should normally be done over
548             # LDAP. Windows 2000 DCs however allow this only with SSL
549             # connections which are hard to set up and otherwise refuse with
550             # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
551             # over SAMR.
552             print "Setting account password for %s" % ctx.samname
553             try:
554                 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
555                                       % ldb.binary_encode(ctx.samname),
556                                       ctx.acct_pass,
557                                       force_change_at_next_login=False,
558                                       username=ctx.samname)
559             except ldb.LdbError, (num, _):
560                 if num != ldb.ERR_UNWILLING_TO_PERFORM:
561                     pass
562                 ctx.net.set_password(account_name=ctx.samname,
563                                      domain_name=ctx.domain_name,
564                                      newpassword=ctx.acct_pass)
565
566             res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE,
567                                    attrs=["msDS-KeyVersionNumber"])
568             if "msDS-KeyVersionNumber" in res[0]:
569                 ctx.key_version_number = int(res[0]["msDS-KeyVersionNumber"][0])
570             else:
571                 ctx.key_version_number = None
572
573             print("Enabling account")
574             m = ldb.Message()
575             m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
576             m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
577                                                          ldb.FLAG_MOD_REPLACE,
578                                                          "userAccountControl")
579             ctx.samdb.modify(m)
580
581     def join_add_objects2(ctx):
582         """add the various objects needed for the join, for subdomains post replication"""
583
584         print "Adding %s" % ctx.partition_dn
585         # NOTE: windows sends a ntSecurityDescriptor here, we
586         # let it default
587         rec = {
588             "dn" : ctx.partition_dn,
589             "objectclass" : "crossRef",
590             "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
591             "nCName" : ctx.base_dn,
592             "nETBIOSName" : ctx.domain_name,
593             "dnsRoot": ctx.dnsdomain,
594             "trustParent" : ctx.parent_partition_dn,
595             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
596         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
597             rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
598
599         rec2 = {
600             "dn" : ctx.ntds_dn,
601             "objectclass" : "nTDSDSA",
602             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
603             "dMDLocation" : ctx.schema_dn}
604
605         nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
606
607         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
608             rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
609
610         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
611             rec2["msDS-HasDomainNCs"] = ctx.base_dn
612
613         rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
614         rec2["HasMasterNCs"]      = nc_list
615         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
616             rec2["msDS-HasMasterNCs"] = ctx.nc_list
617         rec2["options"] = "1"
618         rec2["invocationId"] = ndr_pack(ctx.invocation_id)
619
620         objects = ctx.DsAddEntry([rec, rec2])
621         if len(objects) != 2:
622             raise DCJoinException("Expected 2 objects from DsAddEntry")
623
624         ctx.ntds_guid = objects[1].guid
625
626         print("Replicating partition DN")
627         ctx.repl.replicate(ctx.partition_dn,
628                            misc.GUID("00000000-0000-0000-0000-000000000000"),
629                            ctx.ntds_guid,
630                            exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
631                            replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
632
633         print("Replicating NTDS DN")
634         ctx.repl.replicate(ctx.ntds_dn,
635                            misc.GUID("00000000-0000-0000-0000-000000000000"),
636                            ctx.ntds_guid,
637                            exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
638                            replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
639
640     def join_provision(ctx):
641         """Provision the local SAM."""
642
643         print "Calling bare provision"
644
645         logger = logging.getLogger("provision")
646         logger.addHandler(logging.StreamHandler(sys.stdout))
647         smbconf = ctx.lp.configfile
648
649         presult = provision(logger, system_session(), None, smbconf=smbconf,
650                 targetdir=ctx.targetdir, samdb_fill=FILL_DRS, realm=ctx.realm,
651                 rootdn=ctx.root_dn, domaindn=ctx.base_dn,
652                 schemadn=ctx.schema_dn, configdn=ctx.config_dn,
653                 serverdn=ctx.server_dn, domain=ctx.domain_name,
654                 hostname=ctx.myname, domainsid=ctx.domsid,
655                 machinepass=ctx.acct_pass, serverrole="domain controller",
656                 sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid,
657                 use_ntvfs=ctx.use_ntvfs, dns_backend=ctx.dns_backend)
658         print "Provision OK for domain DN %s" % presult.domaindn
659         ctx.local_samdb = presult.samdb
660         ctx.lp          = presult.lp
661         ctx.paths       = presult.paths
662         ctx.names       = presult.names
663
664     def join_provision_own_domain(ctx):
665         """Provision the local SAM."""
666
667         # we now operate exclusively on the local database, which
668         # we need to reopen in order to get the newly created schema
669         print("Reconnecting to local samdb")
670         ctx.samdb = SamDB(url=ctx.local_samdb.url,
671                           session_info=system_session(),
672                           lp=ctx.local_samdb.lp,
673                           global_schema=False)
674         ctx.samdb.set_invocation_id(str(ctx.invocation_id))
675         ctx.local_samdb = ctx.samdb
676
677         print("Finding domain GUID from ncName")
678         res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
679                                      controls=["extended_dn:1:1"])
680         domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
681         print("Got domain GUID %s" % domguid)
682
683         print("Calling own domain provision")
684
685         logger = logging.getLogger("provision")
686         logger.addHandler(logging.StreamHandler(sys.stdout))
687
688         secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
689
690         presult = provision_fill(ctx.local_samdb, secrets_ldb,
691                                  logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
692                                  domainguid=domguid,
693                                  targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
694                                  machinepass=ctx.acct_pass, serverrole="domain controller",
695                                  lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6,
696                                  dns_backend=ctx.dns_backend)
697         print("Provision OK for domain %s" % ctx.names.dnsdomain)
698
699     def join_replicate(ctx):
700         """Replicate the SAM."""
701
702         print "Starting replication"
703         ctx.local_samdb.transaction_start()
704         try:
705             source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
706             if ctx.ntds_guid is None:
707                 print("Using DS_BIND_GUID_W2K3")
708                 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
709             else:
710                 destination_dsa_guid = ctx.ntds_guid
711
712             if ctx.RODC:
713                 repl_creds = Credentials()
714                 repl_creds.guess(ctx.lp)
715                 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
716                 repl_creds.set_username(ctx.samname)
717                 repl_creds.set_password(ctx.acct_pass)
718             else:
719                 repl_creds = ctx.creds
720
721             binding_options = "seal"
722             if int(ctx.lp.get("log level")) >= 5:
723                 binding_options += ",print"
724             repl = drs_utils.drs_Replicate(
725                 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
726                 ctx.lp, repl_creds, ctx.local_samdb)
727
728             repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
729                     destination_dsa_guid, schema=True, rodc=ctx.RODC,
730                     replica_flags=ctx.replica_flags)
731             repl.replicate(ctx.config_dn, source_dsa_invocation_id,
732                     destination_dsa_guid, rodc=ctx.RODC,
733                     replica_flags=ctx.replica_flags)
734             if not ctx.subdomain:
735                 # Replicate first the critical object for the basedn
736                 if not ctx.domain_replica_flags & drsuapi.DRSUAPI_DRS_CRITICAL_ONLY:
737                     print "Replicating critical objects from the base DN of the domain"
738                     ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
739                     repl.replicate(ctx.base_dn, source_dsa_invocation_id,
740                                 destination_dsa_guid, rodc=ctx.RODC,
741                                 replica_flags=ctx.domain_replica_flags)
742                     ctx.domain_replica_flags ^= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi.DRSUAPI_DRS_GET_ANC
743                 else:
744                     ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_GET_ANC
745                 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
746                                destination_dsa_guid, rodc=ctx.RODC,
747                                replica_flags=ctx.domain_replica_flags)
748
749             if ctx.domaindns_zone in ctx.nc_list:
750                 repl.replicate(ctx.domaindns_zone, source_dsa_invocation_id,
751                                destination_dsa_guid, rodc=ctx.RODC,
752                                replica_flags=ctx.replica_flags)
753
754             if 'DC=ForestDnsZones,%s' % ctx.root_dn in ctx.nc_list:
755                 repl.replicate('DC=ForestDnsZones,%s' % ctx.root_dn, source_dsa_invocation_id,
756                                destination_dsa_guid, rodc=ctx.RODC,
757                                replica_flags=ctx.replica_flags)
758
759             if ctx.RODC:
760                 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
761                         destination_dsa_guid,
762                         exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
763                 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
764                         destination_dsa_guid,
765                         exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
766             ctx.repl = repl
767             ctx.source_dsa_invocation_id = source_dsa_invocation_id
768             ctx.destination_dsa_guid = destination_dsa_guid
769
770             print "Committing SAM database"
771         except:
772             ctx.local_samdb.transaction_cancel()
773             raise
774         else:
775             ctx.local_samdb.transaction_commit()
776
777     def send_DsReplicaUpdateRefs(ctx, dn):
778         r = drsuapi.DsReplicaUpdateRefsRequest1()
779         r.naming_context = drsuapi.DsReplicaObjectIdentifier()
780         r.naming_context.dn = str(dn)
781         r.naming_context.guid = misc.GUID("00000000-0000-0000-0000-000000000000")
782         r.naming_context.sid = security.dom_sid("S-0-0")
783         r.dest_dsa_guid = ctx.ntds_guid
784         r.dest_dsa_dns_name = "%s._msdcs.%s" % (str(ctx.ntds_guid), ctx.dnsforest)
785         r.options = drsuapi.DRSUAPI_DRS_ADD_REF | drsuapi.DRSUAPI_DRS_DEL_REF
786         if not ctx.RODC:
787             r.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
788
789         if ctx.drsuapi:
790             ctx.drsuapi.DsReplicaUpdateRefs(ctx.drsuapi_handle, 1, r)
791
792     def join_finalise(ctx):
793         """Finalise the join, mark us synchronised and setup secrets db."""
794
795         logger = logging.getLogger("provision")
796         logger.addHandler(logging.StreamHandler(sys.stdout))
797
798         print "Sending DsReplicateUpdateRefs for all the partitions"
799         for nc in ctx.full_nc_list:
800             ctx.send_DsReplicaUpdateRefs(nc)
801
802         if ctx.RODC:
803             print "Setting RODC invocationId"
804             ctx.local_samdb.set_invocation_id(str(ctx.invocation_id))
805             ctx.local_samdb.set_opaque_integer("domainFunctionality",
806                                                ctx.behavior_version)
807             m = ldb.Message()
808             m.dn = ldb.Dn(ctx.local_samdb, "%s" % ctx.ntds_dn)
809             m["invocationId"] = ldb.MessageElement(ndr_pack(ctx.invocation_id),
810                                                    ldb.FLAG_MOD_REPLACE,
811                                                    "invocationId")
812             ctx.local_samdb.modify(m)
813
814             # Note: as RODC the invocationId is only stored
815             # on the RODC itself, the other DCs never see it.
816             #
817             # Thats is why we fix up the replPropertyMetaData stamp
818             # for the 'invocationId' attribute, we need to change
819             # the 'version' to '0', this is what windows 2008r2 does as RODC
820             #
821             # This means if the object on a RWDC ever gets a invocationId
822             # attribute, it will have version '1' (or higher), which will
823             # will overwrite the RODC local value.
824             ctx.local_samdb.set_attribute_replmetadata_version(m.dn,
825                                                                "invocationId",
826                                                                0)
827
828         print "Setting isSynchronized and dsServiceName"
829         m = ldb.Message()
830         m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
831         m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
832         m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
833                                                 ldb.FLAG_MOD_REPLACE, "dsServiceName")
834         ctx.local_samdb.modify(m)
835
836         if ctx.subdomain:
837             return
838
839         secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
840
841         print "Setting up secrets database"
842         secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
843                             realm=ctx.realm,
844                             dnsdomain=ctx.dnsdomain,
845                             netbiosname=ctx.myname,
846                             domainsid=security.dom_sid(ctx.domsid),
847                             machinepass=ctx.acct_pass,
848                             secure_channel_type=ctx.secure_channel_type,
849                             key_version_number=ctx.key_version_number)
850
851         if ctx.dns_backend.startswith("BIND9_"):
852             dnspass = samba.generate_random_password(128, 255)
853
854             setup_bind9_dns(ctx.local_samdb, secrets_ldb, security.dom_sid(ctx.domsid),
855                             ctx.names, ctx.paths, ctx.lp, logger,
856                             dns_backend=ctx.dns_backend,
857                             dnspass=dnspass, os_level=ctx.behavior_version,
858                             targetdir=ctx.targetdir)
859
860     def join_setup_trusts(ctx):
861         """provision the local SAM."""
862
863         def arcfour_encrypt(key, data):
864             from Crypto.Cipher import ARC4
865             c = ARC4.new(key)
866             return c.encrypt(data)
867
868         def string_to_array(string):
869             blob = [0] * len(string)
870
871             for i in range(len(string)):
872                 blob[i] = ord(string[i])
873
874             return blob
875
876         print "Setup domain trusts with server %s" % ctx.server
877         binding_options = ""  # why doesn't signing work here? w2k8r2 claims no session key
878         lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
879                              ctx.lp, ctx.creds)
880
881         objectAttr = lsa.ObjectAttribute()
882         objectAttr.sec_qos = lsa.QosInfo()
883
884         pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
885                                          objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
886
887         info = lsa.TrustDomainInfoInfoEx()
888         info.domain_name.string = ctx.dnsdomain
889         info.netbios_name.string = ctx.domain_name
890         info.sid = security.dom_sid(ctx.domsid)
891         info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
892         info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
893         info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
894
895         try:
896             oldname = lsa.String()
897             oldname.string = ctx.dnsdomain
898             oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
899                                                            lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
900             print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
901             lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
902         except RuntimeError:
903             pass
904
905         password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
906
907         clear_value = drsblobs.AuthInfoClear()
908         clear_value.size = len(password_blob)
909         clear_value.password = password_blob
910
911         clear_authentication_information = drsblobs.AuthenticationInformation()
912         clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
913         clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
914         clear_authentication_information.AuthInfo = clear_value
915
916         authentication_information_array = drsblobs.AuthenticationInformationArray()
917         authentication_information_array.count = 1
918         authentication_information_array.array = [clear_authentication_information]
919
920         outgoing = drsblobs.trustAuthInOutBlob()
921         outgoing.count = 1
922         outgoing.current = authentication_information_array
923
924         trustpass = drsblobs.trustDomainPasswords()
925         confounder = [3] * 512
926
927         for i in range(512):
928             confounder[i] = random.randint(0, 255)
929
930         trustpass.confounder = confounder
931
932         trustpass.outgoing = outgoing
933         trustpass.incoming = outgoing
934
935         trustpass_blob = ndr_pack(trustpass)
936
937         encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
938
939         auth_blob = lsa.DATA_BUF2()
940         auth_blob.size = len(encrypted_trustpass)
941         auth_blob.data = string_to_array(encrypted_trustpass)
942
943         auth_info = lsa.TrustDomainInfoAuthInfoInternal()
944         auth_info.auth_blob = auth_blob
945
946         trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
947                                                          info,
948                                                          auth_info,
949                                                          security.SEC_STD_DELETE)
950
951         rec = {
952             "dn" : "cn=%s,cn=system,%s" % (ctx.dnsforest, ctx.base_dn),
953             "objectclass" : "trustedDomain",
954             "trustType" : str(info.trust_type),
955             "trustAttributes" : str(info.trust_attributes),
956             "trustDirection" : str(info.trust_direction),
957             "flatname" : ctx.forest_domain_name,
958             "trustPartner" : ctx.dnsforest,
959             "trustAuthIncoming" : ndr_pack(outgoing),
960             "trustAuthOutgoing" : ndr_pack(outgoing)
961             }
962         ctx.local_samdb.add(rec)
963
964         rec = {
965             "dn" : "cn=%s$,cn=users,%s" % (ctx.forest_domain_name, ctx.base_dn),
966             "objectclass" : "user",
967             "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
968             "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
969             }
970         ctx.local_samdb.add(rec)
971
972
973     def do_join(ctx):
974         ctx.nc_list = [ ctx.config_dn, ctx.schema_dn ]
975         ctx.full_nc_list = [ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
976
977         if not ctx.subdomain:
978             ctx.nc_list += [ctx.base_dn]
979             if ctx.dns_backend != "NONE":
980                 ctx.nc_list += [ctx.domaindns_zone]
981
982         if ctx.dns_backend != "NONE":
983             ctx.full_nc_list += ['DC=DomainDnsZones,%s' % ctx.base_dn]
984             ctx.full_nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
985             ctx.nc_list += ['DC=ForestDnsZones,%s' % ctx.root_dn]
986
987         if ctx.promote_existing:
988             ctx.promote_possible()
989         else:
990             ctx.cleanup_old_join()
991
992         try:
993             ctx.join_add_objects()
994             ctx.join_provision()
995             ctx.join_replicate()
996             if ctx.subdomain:
997                 ctx.join_add_objects2()
998                 ctx.join_provision_own_domain()
999                 ctx.join_setup_trusts()
1000             ctx.join_finalise()
1001         except:
1002             print "Join failed - cleaning up"
1003             ctx.cleanup_old_join()
1004             raise
1005
1006
1007 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
1008               targetdir=None, domain=None, domain_critical_only=False,
1009               machinepass=None, use_ntvfs=False, dns_backend=None,
1010               promote_existing=False):
1011     """Join as a RODC."""
1012
1013     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
1014                   machinepass, use_ntvfs, dns_backend, promote_existing)
1015
1016     lp.set("workgroup", ctx.domain_name)
1017     print("workgroup is %s" % ctx.domain_name)
1018
1019     lp.set("realm", ctx.realm)
1020     print("realm is %s" % ctx.realm)
1021
1022     ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
1023
1024     # setup some defaults for accounts that should be replicated to this RODC
1025     ctx.never_reveal_sid = [
1026         "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
1027         "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
1028         "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
1029         "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
1030         "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS]
1031     ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
1032
1033     mysid = ctx.get_mysid()
1034     admin_dn = "<SID=%s>" % mysid
1035     ctx.managedby = admin_dn
1036
1037     ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
1038                               samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1039                               samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
1040
1041     ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
1042                       "RestrictedKrbHost/%s" % ctx.dnshostname ])
1043
1044     ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
1045     ctx.secure_channel_type = misc.SEC_CHAN_RODC
1046     ctx.RODC = True
1047     ctx.replica_flags  =  (drsuapi.DRSUAPI_DRS_INIT_SYNC |
1048                            drsuapi.DRSUAPI_DRS_PER_SYNC |
1049                            drsuapi.DRSUAPI_DRS_GET_ANC |
1050                            drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
1051                            drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1052                            drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
1053     ctx.domain_replica_flags = ctx.replica_flags
1054     if domain_critical_only:
1055         ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1056
1057     ctx.do_join()
1058
1059     print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
1060
1061
1062 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
1063             targetdir=None, domain=None, domain_critical_only=False,
1064             machinepass=None, use_ntvfs=False, dns_backend=None,
1065             promote_existing=False):
1066     """Join as a DC."""
1067     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain,
1068                   machinepass, use_ntvfs, dns_backend, promote_existing)
1069
1070     lp.set("workgroup", ctx.domain_name)
1071     print("workgroup is %s" % ctx.domain_name)
1072
1073     lp.set("realm", ctx.realm)
1074     print("realm is %s" % ctx.realm)
1075
1076     ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1077
1078     ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1079     ctx.secure_channel_type = misc.SEC_CHAN_BDC
1080
1081     ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1082                          drsuapi.DRSUAPI_DRS_INIT_SYNC |
1083                          drsuapi.DRSUAPI_DRS_PER_SYNC |
1084                          drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1085                          drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1086     ctx.domain_replica_flags = ctx.replica_flags
1087     if domain_critical_only:
1088         ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
1089
1090     ctx.do_join()
1091     print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
1092
1093 def join_subdomain(server=None, creds=None, lp=None, site=None,
1094         netbios_name=None, targetdir=None, parent_domain=None, dnsdomain=None,
1095         netbios_domain=None, machinepass=None, use_ntvfs=False,
1096         dns_backend=None):
1097     """Join as a DC."""
1098     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain,
1099                   machinepass, use_ntvfs, dns_backend)
1100     ctx.subdomain = True
1101     ctx.parent_domain_name = ctx.domain_name
1102     ctx.domain_name = netbios_domain
1103     ctx.realm = dnsdomain
1104     ctx.parent_dnsdomain = ctx.dnsdomain
1105     ctx.parent_partition_dn = ctx.get_parent_partition_dn()
1106     ctx.dnsdomain = dnsdomain
1107     ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
1108     ctx.naming_master = ctx.get_naming_master()
1109     if ctx.naming_master != ctx.server:
1110         print("Reconnecting to naming master %s" % ctx.naming_master)
1111         ctx.server = ctx.naming_master
1112         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
1113                           session_info=system_session(),
1114                           credentials=ctx.creds, lp=ctx.lp)
1115
1116     ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
1117     ctx.domsid = str(security.random_sid())
1118     ctx.acct_dn = None
1119     ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
1120     ctx.trustdom_pass = samba.generate_random_password(128, 128)
1121
1122     ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
1123
1124     ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
1125     ctx.secure_channel_type = misc.SEC_CHAN_BDC
1126
1127     ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
1128                          drsuapi.DRSUAPI_DRS_INIT_SYNC |
1129                          drsuapi.DRSUAPI_DRS_PER_SYNC |
1130                          drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1131                          drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
1132     ctx.domain_replica_flags = ctx.replica_flags
1133
1134     ctx.do_join()
1135     print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)