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