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