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