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