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