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