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