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