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