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