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