s4-subdomain: don't delete account DN not created in subdomain join
[ddiss/samba.git] / source4 / scripting / python / samba / join.py
1 #!/usr/bin/env python
2 #
3 # python join code
4 # Copyright Andrew Tridgell 2010
5 # Copyright Andrew Bartlett 2010
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 """Joining a domain."""
22
23 from samba.auth import system_session
24 from samba.samdb import SamDB
25 from samba import gensec, Ldb, drs_utils
26 import ldb, samba, sys, os, uuid
27 from samba.ndr import ndr_pack
28 from samba.dcerpc import security, drsuapi, misc, nbt, lsa, drsblobs
29 from samba.credentials import Credentials, DONT_USE_KERBEROS
30 from samba.provision import secretsdb_self_join, provision, provision_fill, FILL_DRS, FILL_SUBDOMAIN
31 from samba.schema import Schema
32 from samba.net import Net
33 from samba.dcerpc import security
34 import logging
35 import talloc
36 import random
37
38 # this makes debugging easier
39 talloc.enable_null_tracking()
40
41 class DCJoinException(Exception):
42
43     def __init__(self, msg):
44         super(DCJoinException, self).__init__("Can't join, error: %s" % msg)
45
46
47 class dc_join(object):
48     '''perform a DC join'''
49
50     def __init__(ctx, server=None, creds=None, lp=None, site=None,
51             netbios_name=None, targetdir=None, domain=None):
52         ctx.creds = creds
53         ctx.lp = lp
54         ctx.site = site
55         ctx.netbios_name = netbios_name
56         ctx.targetdir = targetdir
57
58         ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
59         ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
60
61         if server is not None:
62             ctx.server = server
63         else:
64             print("Finding a writeable DC for domain '%s'" % domain)
65             ctx.server = ctx.find_dc(domain)
66             print("Found DC %s" % ctx.server)
67
68         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
69                           session_info=system_session(),
70                           credentials=ctx.creds, lp=ctx.lp)
71
72         try:
73             ctx.samdb.search(scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
74         except ldb.LdbError, (enum, estr):
75             raise DCJoinException(estr)
76
77
78         ctx.myname = netbios_name
79         ctx.samname = "%s$" % ctx.myname
80         ctx.base_dn = str(ctx.samdb.get_default_basedn())
81         ctx.root_dn = str(ctx.samdb.get_root_basedn())
82         ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
83         ctx.config_dn = str(ctx.samdb.get_config_basedn())
84         ctx.domsid = ctx.samdb.get_domain_sid()
85         ctx.domain_name = ctx.get_domain_name()
86         ctx.invocation_id = misc.GUID(str(uuid.uuid4()))
87
88         ctx.dc_ntds_dn = ctx.get_dsServiceName()
89         ctx.dc_dnsHostName = ctx.get_dnsHostName()
90         ctx.behavior_version = ctx.get_behavior_version()
91
92         ctx.acct_pass = samba.generate_random_password(32, 40)
93
94         # work out the DNs of all the objects we will be adding
95         ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
96         ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
97         topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
98         if ctx.dn_exists(topology_base):
99             ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
100         else:
101             ctx.topology_dn = None
102
103         ctx.dnsdomain = ctx.samdb.domain_dns_name()
104         ctx.dnsforest = ctx.samdb.forest_dns_name()
105         ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
106
107         ctx.realm = ctx.dnsdomain
108
109         ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
110
111         ctx.tmp_samdb = None
112
113         ctx.SPNs = [ "HOST/%s" % ctx.myname,
114                      "HOST/%s" % ctx.dnshostname,
115                      "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
116
117         # these elements are optional
118         ctx.never_reveal_sid = None
119         ctx.reveal_sid = None
120         ctx.connection_dn = None
121         ctx.RODC = False
122         ctx.krbtgt_dn = None
123         ctx.drsuapi = None
124         ctx.managedby = None
125         ctx.subdomain = False
126         ctx.domguid = None
127
128
129     def del_noerror(ctx, dn, recursive=False):
130         if recursive:
131             try:
132                 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
133             except Exception:
134                 return
135             for r in res:
136                 ctx.del_noerror(r.dn, recursive=True)
137         try:
138             ctx.samdb.delete(dn)
139             print "Deleted %s" % dn
140         except Exception:
141             pass
142
143     def cleanup_old_join(ctx):
144         '''remove any DNs from a previous join'''
145         try:
146             # find the krbtgt link
147             print("checking samaccountname")
148             if ctx.subdomain:
149                 res = None
150             else:
151                 res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
152                                        expression='samAccountName=%s' % ldb.binary_encode(ctx.samname),
153                                        attrs=["msDS-krbTgtLink"])
154                 if res:
155                     ctx.del_noerror(res[0].dn, recursive=True)
156             if ctx.connection_dn is not None:
157                 ctx.del_noerror(ctx.connection_dn)
158             if ctx.krbtgt_dn is not None:
159                 ctx.del_noerror(ctx.krbtgt_dn)
160             ctx.del_noerror(ctx.ntds_dn)
161             ctx.del_noerror(ctx.server_dn, recursive=True)
162             if ctx.topology_dn:
163                 ctx.del_noerror(ctx.topology_dn)
164             if ctx.partition_dn:
165                 ctx.del_noerror(ctx.partition_dn)
166             if res:
167                 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
168                 ctx.del_noerror(ctx.new_krbtgt_dn)
169
170             if ctx.subdomain:
171                 binding_options = "sign"
172                 lsaconn = lsa.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
173                                      ctx.lp, ctx.creds)
174
175                 objectAttr = lsa.ObjectAttribute()
176                 objectAttr.sec_qos = lsa.QosInfo()
177
178                 pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
179                                                  objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
180
181                 name = lsa.String()
182                 name.string = ctx.realm
183                 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
184
185                 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
186
187                 name = lsa.String()
188                 name.string = ctx.domain_name
189                 info = lsaconn.QueryTrustedDomainInfoByName(pol_handle, name, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
190
191                 lsaconn.DeleteTrustedDomain(pol_handle, info.info_ex.sid)
192
193         except Exception:
194             pass
195
196     def find_dc(ctx, domain):
197         '''find a writeable DC for the given domain'''
198         try:
199             ctx.cldap_ret = ctx.net.finddc(domain, nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
200         except Exception:
201             raise Exception("Failed to find a writeable DC for domain '%s'" % domain)
202         if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
203             ctx.site = ctx.cldap_ret.client_site
204         return ctx.cldap_ret.pdc_dns_name
205
206
207     def get_dsServiceName(ctx):
208         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
209         return res[0]["dsServiceName"][0]
210
211     def get_behavior_version(ctx):
212         res = ctx.samdb.search(base=ctx.base_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
213         if "msDS-Behavior-Version" in res[0]:
214             return int(res[0]["msDS-Behavior-Version"][0])
215         else:
216             return samba.dsdb.DS_DOMAIN_FUNCTION_2000
217
218     def get_dnsHostName(ctx):
219         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
220         return res[0]["dnsHostName"][0]
221
222     def get_domain_name(ctx):
223         '''get netbios name of the domain from the partitions record'''
224         partitions_dn = ctx.samdb.get_partitions_dn()
225         res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
226                                expression='ncName=%s' % ctx.samdb.get_default_basedn())
227         return res[0]["nETBIOSName"][0]
228
229     def get_parent_partition_dn(ctx):
230         '''get the parent domain partition DN from parent DNS name'''
231         res = ctx.samdb.search(base=ctx.config_dn, attrs=[],
232                                expression='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
233                                (ctx.parent_dnsdomain, ldb.OID_COMPARATOR_AND, samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN))
234         return str(res[0].dn)
235
236     def get_mysid(ctx):
237         '''get the SID of the connected user. Only works with w2k8 and later,
238            so only used for RODC join'''
239         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
240         binsid = res[0]["tokenGroups"][0]
241         return ctx.samdb.schema_format_value("objectSID", binsid)
242
243     def dn_exists(ctx, dn):
244         '''check if a DN exists'''
245         try:
246             res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[])
247         except ldb.LdbError, (enum, estr):
248             if enum == ldb.ERR_NO_SUCH_OBJECT:
249                 return False
250             raise
251         return True
252
253     def add_krbtgt_account(ctx):
254         '''RODCs need a special krbtgt account'''
255         print "Adding %s" % ctx.krbtgt_dn
256         rec = {
257             "dn" : ctx.krbtgt_dn,
258             "objectclass" : "user",
259             "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
260                                        samba.dsdb.UF_ACCOUNTDISABLE),
261             "showinadvancedviewonly" : "TRUE",
262             "description" : "krbtgt for %s" % ctx.samname}
263         ctx.samdb.add(rec, ["rodc_join:1:1"])
264
265         # now we need to search for the samAccountName attribute on the krbtgt DN,
266         # as this will have been magically set to the krbtgt number
267         res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
268         ctx.krbtgt_name = res[0]["samAccountName"][0]
269
270         print "Got krbtgt_name=%s" % ctx.krbtgt_name
271
272         m = ldb.Message()
273         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
274         m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
275                                                   ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
276         ctx.samdb.modify(m)
277
278         ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
279         print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
280         ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
281
282     def drsuapi_connect(ctx):
283         '''make a DRSUAPI connection to the server'''
284         binding_options = "seal"
285         if int(ctx.lp.get("log level")) >= 5:
286             binding_options += ",print"
287         binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
288         ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
289         (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
290
291     def create_tmp_samdb(ctx):
292         '''create a temporary samdb object for schema queries'''
293         ctx.tmp_schema = Schema(security.dom_sid(ctx.domsid),
294                                 schemadn=ctx.schema_dn)
295         ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
296                               credentials=ctx.creds, lp=ctx.lp, global_schema=False,
297                               am_rodc=False)
298         ctx.tmp_samdb.set_schema(ctx.tmp_schema)
299
300     def build_DsReplicaAttribute(ctx, attrname, attrvalue):
301         '''build a DsReplicaAttributeCtr object'''
302         r = drsuapi.DsReplicaAttribute()
303         r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
304         r.value_ctr = 1
305
306
307     def DsAddEntry(ctx, rec):
308         '''add a record via the DRSUAPI DsAddEntry call'''
309         if ctx.drsuapi is None:
310             ctx.drsuapi_connect()
311         if ctx.tmp_samdb is None:
312             ctx.create_tmp_samdb()
313
314         id = drsuapi.DsReplicaObjectIdentifier()
315         id.dn = rec['dn']
316
317         attrs = []
318         for a in rec:
319             if a == 'dn':
320                 continue
321             if not isinstance(rec[a], list):
322                 v = [rec[a]]
323             else:
324                 v = rec[a]
325             rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
326             attrs.append(rattr)
327
328         attribute_ctr = drsuapi.DsReplicaAttributeCtr()
329         attribute_ctr.num_attributes = len(attrs)
330         attribute_ctr.attributes = attrs
331
332         object = drsuapi.DsReplicaObject()
333         object.identifier = id
334         object.attribute_ctr = attribute_ctr
335
336         first_object = drsuapi.DsReplicaObjectListItem()
337         first_object.object = object
338
339         req2 = drsuapi.DsAddEntryRequest2()
340         req2.first_object = first_object
341
342         (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
343         if ctr.err_ver != 1:
344             raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
345         if ctr.err_data.status != (0, 'WERR_OK'):
346             print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
347                                                                 ctr.err_data.info.extended_err))
348             raise RuntimeError("DsAddEntry failed")
349
350     def join_add_ntdsdsa(ctx):
351         '''add the ntdsdsa object'''
352         # FIXME: the partition (NC) assignment has to be made dynamic
353         print "Adding %s" % ctx.ntds_dn
354         rec = {
355             "dn" : ctx.ntds_dn,
356             "objectclass" : "nTDSDSA",
357             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
358             "dMDLocation" : ctx.schema_dn}
359
360         if ctx.subdomain:
361             # the local subdomain NC doesn't exist at this time
362             # so we have to add the base_dn NC later
363             nc_list = [ ctx.config_dn, ctx.schema_dn ]
364         else:
365             nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
366
367         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
368             rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
369
370         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003 and not ctx.subdomain:
371             rec["msDS-HasDomainNCs"] = ctx.base_dn
372
373         if ctx.RODC:
374             rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
375             rec["msDS-HasFullReplicaNCs"] = nc_list
376             rec["options"] = "37"
377             ctx.samdb.add(rec, ["rodc_join:1:1"])
378         else:
379             rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
380             rec["HasMasterNCs"]      = nc_list
381             if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
382                 rec["msDS-HasMasterNCs"] = nc_list
383             rec["options"] = "1"
384             rec["invocationId"] = ndr_pack(ctx.invocation_id)
385             if ctx.subdomain:
386                 ctx.samdb.add(rec, ['relax:0'])
387             else:
388                 ctx.DsAddEntry(rec)
389
390         # find the GUID of our NTDS DN
391         res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
392         ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
393
394
395     def join_modify_ntdsdsa(ctx):
396         '''modify the ntdsdsa object to add local partitions'''
397         print "Modifying %s using system privileges" % ctx.ntds_dn
398
399         # this works around the Enterprise Admins ACL on the NTDSDSA object
400         system_session_info = system_session()
401         ctx.samdb.set_session_info(system_session_info)
402
403         m = ldb.Message()
404         m.dn = ldb.Dn(ctx.samdb, ctx.ntds_dn)
405         m["HasMasterNCs"] = ldb.MessageElement(ctx.base_dn, ldb.FLAG_MOD_ADD, "HasMasterNCs")
406         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
407             m["msDS-HasDomainNCs"] = ldb.MessageElement(ctx.base_dn, ldb.FLAG_MOD_ADD, "msDS-HasDomainNCs")
408             m["msDS-HasMasterNCs"] = ldb.MessageElement(ctx.base_dn, ldb.FLAG_MOD_ADD, "msDS-HasMasterNCs")
409         ctx.samdb.modify(m, controls=['relax:0'])
410
411     def join_add_objects(ctx):
412         '''add the various objects needed for the join'''
413         if ctx.acct_dn:
414             print "Adding %s" % ctx.acct_dn
415             rec = {
416                 "dn" : ctx.acct_dn,
417                 "objectClass": "computer",
418                 "displayname": ctx.samname,
419                 "samaccountname" : ctx.samname,
420                 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
421                 "dnshostname" : ctx.dnshostname}
422             if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
423                 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
424             if ctx.managedby:
425                 rec["managedby"] = ctx.managedby
426             if ctx.never_reveal_sid:
427                 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
428             if ctx.reveal_sid:
429                 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
430             ctx.samdb.add(rec)
431
432         if ctx.krbtgt_dn:
433             ctx.add_krbtgt_account()
434
435         print "Adding %s" % ctx.server_dn
436         rec = {
437             "dn": ctx.server_dn,
438             "objectclass" : "server",
439             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
440                                 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
441                                 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
442             "dnsHostName" : ctx.dnshostname}
443
444         if ctx.acct_dn:
445             rec["serverReference"] = ctx.acct_dn
446
447         ctx.samdb.add(rec)
448
449         if ctx.subdomain:
450             # the rest is done after replication
451             ctx.ntds_guid = None
452             return
453
454         ctx.join_add_ntdsdsa()
455
456         if ctx.connection_dn is not None:
457             print "Adding %s" % ctx.connection_dn
458             rec = {
459                 "dn" : ctx.connection_dn,
460                 "objectclass" : "nTDSConnection",
461                 "enabledconnection" : "TRUE",
462                 "options" : "65",
463                 "fromServer" : ctx.dc_ntds_dn}
464             ctx.samdb.add(rec)
465
466         if ctx.topology_dn and ctx.acct_dn:
467             print "Adding %s" % ctx.topology_dn
468             rec = {
469                 "dn" : ctx.topology_dn,
470                 "objectclass" : "msDFSR-Member",
471                 "msDFSR-ComputerReference" : ctx.acct_dn,
472                 "serverReference" : ctx.ntds_dn}
473             ctx.samdb.add(rec)
474
475         if ctx.acct_dn:
476             print "Adding SPNs to %s" % ctx.acct_dn
477             m = ldb.Message()
478             m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
479             for i in range(len(ctx.SPNs)):
480                 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
481             m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
482                                                            ldb.FLAG_MOD_ADD,
483                                                            "servicePrincipalName")
484             ctx.samdb.modify(m)
485
486             print "Setting account password for %s" % ctx.samname
487             ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ldb.binary_encode(ctx.samname),
488                                   ctx.acct_pass,
489                                   force_change_at_next_login=False,
490                                   username=ctx.samname)
491             res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-keyVersionNumber"])
492             ctx.key_version_number = int(res[0]["msDS-keyVersionNumber"][0])
493
494             print("Enabling account")
495             m = ldb.Message()
496             m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
497             m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
498                                                          ldb.FLAG_MOD_REPLACE,
499                                                          "userAccountControl")
500             ctx.samdb.modify(m)
501
502
503     def join_add_objects2(ctx):
504         '''add the various objects needed for the join, for subdomains post replication'''
505
506         if not ctx.subdomain:
507             return
508
509         print "Adding %s" % ctx.partition_dn
510         # NOTE: windows sends a ntSecurityDescriptor here, we
511         # let it default
512         rec = {
513             "dn" : ctx.partition_dn,
514             "objectclass" : "crossRef",
515             "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
516             "nCName" : ctx.base_dn,
517             "nETBIOSName" : ctx.domain_name,
518             "dnsRoot": ctx.dnsdomain,
519             "trustParent" : ctx.parent_partition_dn,
520             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
521         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
522             rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
523         ctx.DsAddEntry(rec)
524
525
526     def join_provision(ctx):
527         '''provision the local SAM'''
528
529         print "Calling bare provision"
530
531         logger = logging.getLogger("provision")
532         logger.addHandler(logging.StreamHandler(sys.stdout))
533         smbconf = ctx.lp.configfile
534
535         presult = provision(logger, system_session(), None,
536                             smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
537                             realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
538                             schemadn=ctx.schema_dn,
539                             configdn=ctx.config_dn,
540                             serverdn=ctx.server_dn, domain=ctx.domain_name,
541                             hostname=ctx.myname, domainsid=ctx.domsid,
542                             domainguid=ctx.domguid,
543                             machinepass=ctx.acct_pass, serverrole="domain controller",
544                             sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid)
545         print "Provision OK for domain DN %s" % presult.domaindn
546         ctx.local_samdb = presult.samdb
547         ctx.lp          = presult.lp
548         ctx.paths       = presult.paths
549         ctx.names       = presult.names
550
551     def join_provision_own_domain(ctx):
552         '''provision the local SAM'''
553
554         # we now operate exclusively on the local database, which
555         # we need to reopen in order to get the newly created schema
556         print("Reconnecting to local samdb")
557         ctx.samdb = SamDB(url=ctx.local_samdb.url,
558                           session_info=system_session(),
559                           lp=ctx.local_samdb.lp,
560                           global_schema=False)
561         ctx.samdb.set_invocation_id(str(ctx.invocation_id))
562         ctx.local_samdb = ctx.samdb
563
564         ctx.join_add_ntdsdsa()
565
566         print("Calling own domain provision")
567
568         logger = logging.getLogger("provision")
569         logger.addHandler(logging.StreamHandler(sys.stdout))
570
571         secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
572
573         presult = provision_fill(ctx.local_samdb, secrets_ldb,
574                                  logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
575                                  domainguid=ctx.domguid,
576                                  targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
577                                  machinepass=ctx.acct_pass, serverrole="domain controller",
578                                  lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6)
579         print("Provision OK for domain %s" % ctx.names.dnsdomain)
580
581
582     def join_replicate(ctx):
583         '''replicate the SAM'''
584
585         print "Starting replication"
586         ctx.local_samdb.transaction_start()
587         try:
588             source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
589             if ctx.ntds_guid is None:
590                 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
591             else:
592                 destination_dsa_guid = ctx.ntds_guid
593
594             if ctx.RODC:
595                 repl_creds = Credentials()
596                 repl_creds.guess(ctx.lp)
597                 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
598                 repl_creds.set_username(ctx.samname)
599                 repl_creds.set_password(ctx.acct_pass)
600             else:
601                 repl_creds = ctx.creds
602
603             binding_options = "seal"
604             if int(ctx.lp.get("log level")) >= 5:
605                 binding_options += ",print"
606             repl = drs_utils.drs_Replicate(
607                 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
608                 ctx.lp, repl_creds, ctx.local_samdb)
609
610             repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
611                     destination_dsa_guid, schema=True, rodc=ctx.RODC,
612                     replica_flags=ctx.replica_flags)
613             repl.replicate(ctx.config_dn, source_dsa_invocation_id,
614                     destination_dsa_guid, rodc=ctx.RODC,
615                     replica_flags=ctx.replica_flags)
616             if not ctx.subdomain:
617                 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
618                                destination_dsa_guid, rodc=ctx.RODC,
619                                replica_flags=ctx.domain_replica_flags)
620             if ctx.RODC:
621                 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
622                         destination_dsa_guid,
623                         exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
624                 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
625                         destination_dsa_guid,
626                         exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
627
628             print "Committing SAM database"
629         except:
630             ctx.local_samdb.transaction_cancel()
631             raise
632         else:
633             ctx.local_samdb.transaction_commit()
634
635
636     def join_finalise(ctx):
637         '''finalise the join, mark us synchronised and setup secrets db'''
638
639         print "Setting isSynchronized and dsServiceName"
640         m = ldb.Message()
641         m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
642         m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
643         m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
644                                                 ldb.FLAG_MOD_REPLACE, "dsServiceName")
645         ctx.local_samdb.modify(m)
646
647         if ctx.subdomain:
648             return
649
650         secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
651
652         print "Setting up secrets database"
653         secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
654                             realm=ctx.realm,
655                             dnsdomain=ctx.dnsdomain,
656                             netbiosname=ctx.myname,
657                             domainsid=security.dom_sid(ctx.domsid),
658                             machinepass=ctx.acct_pass,
659                             secure_channel_type=ctx.secure_channel_type,
660                             key_version_number=ctx.key_version_number)
661
662     def join_setup_trusts(ctx):
663         '''provision the local SAM'''
664
665         def arcfour_encrypt(key, data):
666             from Crypto.Cipher import ARC4
667             c = ARC4.new(key)
668             return c.encrypt(data)
669
670         def string_to_array(string):
671             blob = [0] * len(string)
672
673             for i in range(len(string)):
674                 blob[i] = ord(string[i])
675
676             return blob
677
678         print "Setup domain trusts with server %s" % ctx.server
679         binding_options = ""  # why doesn't signing work gere? w2k8r2 claims no session key
680         lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
681                              ctx.lp, ctx.creds)
682
683         objectAttr = lsa.ObjectAttribute()
684         objectAttr.sec_qos = lsa.QosInfo()
685
686         pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
687                                          objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
688
689         info = lsa.TrustDomainInfoInfoEx()
690         info.domain_name.string = ctx.dnsdomain
691         info.netbios_name.string = ctx.domain_name
692         info.sid = security.dom_sid(ctx.domsid)
693         info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
694         info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
695         info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
696
697         try:
698             oldname = lsa.String()
699             oldname.string = ctx.dnsdomain
700             oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
701                                                            lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
702             print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
703             lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
704         except RuntimeError:
705             pass
706
707         password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
708
709         clear_value = drsblobs.AuthInfoClear()
710         clear_value.size = len(password_blob)
711         clear_value.password = password_blob
712
713         clear_authentication_information = drsblobs.AuthenticationInformation()
714         clear_authentication_information.LastUpdateTime = 0
715         clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
716         clear_authentication_information.AuthInfo = clear_value
717
718         version_value = drsblobs.AuthInfoVersion()
719         version_value.version = 1
720
721         version = drsblobs.AuthenticationInformation()
722         version.LastUpdateTime = 0
723         version.AuthType = lsa.TRUST_AUTH_TYPE_VERSION
724         version.AuthInfo = version_value
725
726         authentication_information_array = drsblobs.AuthenticationInformationArray()
727         authentication_information_array.count = 2
728         authentication_information_array.array = [clear_authentication_information, version]
729
730         outgoing = drsblobs.trustAuthInOutBlob()
731         outgoing.count = 1
732         outgoing.current = authentication_information_array
733
734         trustpass = drsblobs.trustDomainPasswords()
735         confounder = [3] * 512
736
737         for i in range(512):
738             confounder[i] = random.randint(0, 255)
739
740         trustpass.confounder = confounder
741
742         trustpass.outgoing = outgoing
743         trustpass.incoming = outgoing
744
745         trustpass_blob = ndr_pack(trustpass)
746
747         encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
748
749         auth_blob = lsa.DATA_BUF2()
750         auth_blob.size = len(encrypted_trustpass)
751         auth_blob.data = string_to_array(encrypted_trustpass)
752
753         auth_info = lsa.TrustDomainInfoAuthInfoInternal()
754         auth_info.auth_blob = auth_blob
755
756         trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
757                                                          info,
758                                                          auth_info,
759                                                          security.SEC_STD_DELETE)
760
761         rec = {
762             "dn" : "cn=%s,cn=system,%s" % (ctx.parent_dnsdomain, ctx.base_dn),
763             "objectclass" : "trustedDomain",
764             "trustType" : str(info.trust_type),
765             "trustAttributes" : str(info.trust_attributes),
766             "trustDirection" : str(info.trust_direction),
767             "flatname" : ctx.parent_domain_name,
768             "trustPartner" : ctx.parent_dnsdomain,
769             "trustAuthIncoming" : ndr_pack(outgoing),
770             "trustAuthOutgoing" : ndr_pack(outgoing)
771             }
772         ctx.local_samdb.add(rec)
773
774         rec = {
775             "dn" : "cn=%s$,cn=users,%s" % (ctx.parent_domain_name, ctx.base_dn),
776             "objectclass" : "user",
777             "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
778             "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
779             }
780         ctx.local_samdb.add(rec)
781
782
783     def do_join(ctx):
784         ctx.cleanup_old_join()
785         try:
786             ctx.join_add_objects()
787             ctx.join_provision()
788             ctx.join_add_objects2()
789             ctx.join_replicate()
790             if ctx.subdomain:
791                 ctx.join_provision_own_domain()
792                 ctx.join_setup_trusts()
793                 ctx.join_modify_ntdsdsa()
794             ctx.join_finalise()
795         except Exception:
796             print "Join failed - cleaning up"
797             #ctx.cleanup_old_join()
798             raise
799
800
801 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
802               targetdir=None, domain=None, domain_critical_only=False):
803     """join as a RODC"""
804
805     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
806
807     lp.set("workgroup", ctx.domain_name)
808     print("workgroup is %s" % ctx.domain_name)
809
810     lp.set("realm", ctx.realm)
811     print("realm is %s" % ctx.realm)
812
813     ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
814
815     # setup some defaults for accounts that should be replicated to this RODC
816     ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
817                              "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
818                              "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
819                              "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
820                              "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
821     ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
822
823     mysid = ctx.get_mysid()
824     admin_dn = "<SID=%s>" % mysid
825     ctx.managedby = admin_dn
826
827     ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
828                               samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
829                               samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
830
831     ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
832                       "RestrictedKrbHost/%s" % ctx.dnshostname ])
833
834     ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
835     ctx.secure_channel_type = misc.SEC_CHAN_RODC
836     ctx.RODC = True
837     ctx.replica_flags  =  (drsuapi.DRSUAPI_DRS_INIT_SYNC |
838                            drsuapi.DRSUAPI_DRS_PER_SYNC |
839                            drsuapi.DRSUAPI_DRS_GET_ANC |
840                            drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
841                            drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
842                            drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
843     ctx.domain_replica_flags = ctx.replica_flags
844     if domain_critical_only:
845         ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
846
847     ctx.do_join()
848
849
850     print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
851
852
853 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
854             targetdir=None, domain=None, domain_critical_only=False):
855     """join as a DC"""
856     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
857
858     lp.set("workgroup", ctx.domain_name)
859     print("workgroup is %s" % ctx.domain_name)
860
861     lp.set("realm", ctx.realm)
862     print("realm is %s" % ctx.realm)
863
864     ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
865
866     ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
867     ctx.secure_channel_type = misc.SEC_CHAN_BDC
868
869     ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
870                          drsuapi.DRSUAPI_DRS_INIT_SYNC |
871                          drsuapi.DRSUAPI_DRS_PER_SYNC |
872                          drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
873                          drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
874     ctx.domain_replica_flags = ctx.replica_flags
875     if domain_critical_only:
876         ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
877
878     ctx.do_join()
879     print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
880
881 def join_subdomain(server=None, creds=None, lp=None, site=None, netbios_name=None,
882                    targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None):
883     """join as a DC"""
884     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain)
885     ctx.subdomain = True
886     ctx.parent_domain_name = ctx.domain_name
887     ctx.domain_name = netbios_domain
888     ctx.realm = dnsdomain
889     ctx.parent_dnsdomain = ctx.dnsdomain
890     ctx.parent_partition_dn = ctx.get_parent_partition_dn()
891     ctx.dnsdomain = dnsdomain
892     ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
893     ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
894     ctx.domsid = str(security.random_sid())
895     ctx.domguid = str(uuid.uuid4())
896     ctx.acct_dn = None
897     ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
898     ctx.trustdom_pass = samba.generate_random_password(128, 128)
899
900     ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
901
902     ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
903     ctx.secure_channel_type = misc.SEC_CHAN_BDC
904
905     ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
906                          drsuapi.DRSUAPI_DRS_INIT_SYNC |
907                          drsuapi.DRSUAPI_DRS_PER_SYNC |
908                          drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
909                          drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
910     ctx.domain_replica_flags = ctx.replica_flags
911
912     ctx.do_join()
913     print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)