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