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