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