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