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