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