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