s4-provision Add initial support for joining as a new subdomain
[nivanova/samba-autobuild/.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.invocation_id = misc.GUID(str(uuid.uuid4()))
88
89         ctx.dc_ntds_dn = ctx.get_dsServiceName()
90         ctx.dc_dnsHostName = ctx.get_dnsHostName()
91         ctx.behavior_version = ctx.get_behavior_version()
92
93         ctx.acct_pass = samba.generate_random_password(32, 40)
94
95         # work out the DNs of all the objects we will be adding
96         ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
97         ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
98         topology_base = "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx.base_dn
99         if ctx.dn_exists(topology_base):
100             ctx.topology_dn = "CN=%s,%s" % (ctx.myname, topology_base)
101         else:
102             ctx.topology_dn = None
103
104         ctx.dnsdomain = ctx.samdb.domain_dns_name()
105         ctx.dnsforest = ctx.samdb.forest_dns_name()
106         ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
107
108         ctx.realm = ctx.dnsdomain
109
110         ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
111
112         ctx.tmp_samdb = None
113
114         ctx.SPNs = [ "HOST/%s" % ctx.myname,
115                      "HOST/%s" % ctx.dnshostname,
116                      "GC/%s/%s" % (ctx.dnshostname, ctx.dnsforest) ]
117
118         # these elements are optional
119         ctx.never_reveal_sid = None
120         ctx.reveal_sid = None
121         ctx.connection_dn = None
122         ctx.RODC = False
123         ctx.krbtgt_dn = None
124         ctx.drsuapi = None
125         ctx.managedby = None
126         ctx.subdomain = False
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, recs):
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         objects = []
315         for rec in recs:
316             id = drsuapi.DsReplicaObjectIdentifier()
317             id.dn = rec['dn']
318
319             attrs = []
320             for a in rec:
321                 if a == 'dn':
322                     continue
323                 if not isinstance(rec[a], list):
324                     v = [rec[a]]
325                 else:
326                     v = rec[a]
327                 rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
328                 attrs.append(rattr)
329
330             attribute_ctr = drsuapi.DsReplicaAttributeCtr()
331             attribute_ctr.num_attributes = len(attrs)
332             attribute_ctr.attributes = attrs
333
334             object = drsuapi.DsReplicaObject()
335             object.identifier = id
336             object.attribute_ctr = attribute_ctr
337
338             list_object = drsuapi.DsReplicaObjectListItem()
339             list_object.object = object
340             objects.append(list_object)
341
342         req2 = drsuapi.DsAddEntryRequest2()
343         req2.first_object = objects[0]
344         prev = req2.first_object
345         for o in objects[1:]:
346             prev.next_object = o
347             prev = o
348
349         (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
350         if ctr.err_ver != 1:
351             raise RuntimeError("expected err_ver 1, got %u" % ctr.err_ver)
352         if ctr.err_data.status != (0, 'WERR_OK'):
353             print("DsAddEntry failed with status %s info %s" % (ctr.err_data.status,
354                                                                 ctr.err_data.info.extended_err))
355             raise RuntimeError("DsAddEntry failed")
356         if ctr.err_data.dir_err != drsuapi.DRSUAPI_DIRERR_OK:
357             print("DsAddEntry failed with dir_err %u" % ctr.err_data.dir_err)
358             raise RuntimeError("DsAddEntry failed")
359         return ctr.objects
360
361
362     def join_add_ntdsdsa(ctx):
363         '''add the ntdsdsa object'''
364         # FIXME: the partition (NC) assignment has to be made dynamic
365         print "Adding %s" % ctx.ntds_dn
366         rec = {
367             "dn" : ctx.ntds_dn,
368             "objectclass" : "nTDSDSA",
369             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
370             "dMDLocation" : ctx.schema_dn}
371
372         nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
373
374         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
375             rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
376
377         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
378             rec["msDS-HasDomainNCs"] = ctx.base_dn
379
380         if ctx.RODC:
381             rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
382             rec["msDS-HasFullReplicaNCs"] = nc_list
383             rec["options"] = "37"
384             ctx.samdb.add(rec, ["rodc_join:1:1"])
385         else:
386             rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
387             rec["HasMasterNCs"]      = nc_list
388             if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
389                 rec["msDS-HasMasterNCs"] = nc_list
390             rec["options"] = "1"
391             rec["invocationId"] = ndr_pack(ctx.invocation_id)
392             ctx.DsAddEntry([rec])
393
394         # find the GUID of our NTDS DN
395         res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
396         ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
397
398
399     def join_add_objects(ctx):
400         '''add the various objects needed for the join'''
401         if ctx.acct_dn:
402             print "Adding %s" % ctx.acct_dn
403             rec = {
404                 "dn" : ctx.acct_dn,
405                 "objectClass": "computer",
406                 "displayname": ctx.samname,
407                 "samaccountname" : ctx.samname,
408                 "userAccountControl" : str(ctx.userAccountControl | samba.dsdb.UF_ACCOUNTDISABLE),
409                 "dnshostname" : ctx.dnshostname}
410             if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2008:
411                 rec['msDS-SupportedEncryptionTypes'] = str(samba.dsdb.ENC_ALL_TYPES)
412             if ctx.managedby:
413                 rec["managedby"] = ctx.managedby
414             if ctx.never_reveal_sid:
415                 rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
416             if ctx.reveal_sid:
417                 rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
418             ctx.samdb.add(rec)
419
420         if ctx.krbtgt_dn:
421             ctx.add_krbtgt_account()
422
423         print "Adding %s" % ctx.server_dn
424         rec = {
425             "dn": ctx.server_dn,
426             "objectclass" : "server",
427             # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
428             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
429                                 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
430                                 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
431             # windows seems to add the dnsHostName later
432             "dnsHostName" : ctx.dnshostname}
433
434         if ctx.acct_dn:
435             rec["serverReference"] = ctx.acct_dn
436
437         ctx.samdb.add(rec)
438
439         if ctx.subdomain:
440             # the rest is done after replication
441             ctx.ntds_guid = None
442             return
443
444         ctx.join_add_ntdsdsa()
445
446         if ctx.connection_dn is not None:
447             print "Adding %s" % ctx.connection_dn
448             rec = {
449                 "dn" : ctx.connection_dn,
450                 "objectclass" : "nTDSConnection",
451                 "enabledconnection" : "TRUE",
452                 "options" : "65",
453                 "fromServer" : ctx.dc_ntds_dn}
454             ctx.samdb.add(rec)
455
456         if ctx.topology_dn and ctx.acct_dn:
457             print "Adding %s" % ctx.topology_dn
458             rec = {
459                 "dn" : ctx.topology_dn,
460                 "objectclass" : "msDFSR-Member",
461                 "msDFSR-ComputerReference" : ctx.acct_dn,
462                 "serverReference" : ctx.ntds_dn}
463             ctx.samdb.add(rec)
464
465         if ctx.acct_dn:
466             print "Adding SPNs to %s" % ctx.acct_dn
467             m = ldb.Message()
468             m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
469             for i in range(len(ctx.SPNs)):
470                 ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
471             m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
472                                                            ldb.FLAG_MOD_ADD,
473                                                            "servicePrincipalName")
474             ctx.samdb.modify(m)
475
476             print "Setting account password for %s" % ctx.samname
477             ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ldb.binary_encode(ctx.samname),
478                                   ctx.acct_pass,
479                                   force_change_at_next_login=False,
480                                   username=ctx.samname)
481             res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-keyVersionNumber"])
482             ctx.key_version_number = int(res[0]["msDS-keyVersionNumber"][0])
483
484             print("Enabling account")
485             m = ldb.Message()
486             m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
487             m["userAccountControl"] = ldb.MessageElement(str(ctx.userAccountControl),
488                                                          ldb.FLAG_MOD_REPLACE,
489                                                          "userAccountControl")
490             ctx.samdb.modify(m)
491
492
493     def join_add_objects2(ctx):
494         '''add the various objects needed for the join, for subdomains post replication'''
495
496         print "Adding %s" % ctx.partition_dn
497         # NOTE: windows sends a ntSecurityDescriptor here, we
498         # let it default
499         rec = {
500             "dn" : ctx.partition_dn,
501             "objectclass" : "crossRef",
502             "objectCategory" : "CN=Cross-Ref,%s" % ctx.schema_dn,
503             "nCName" : ctx.base_dn,
504             "nETBIOSName" : ctx.domain_name,
505             "dnsRoot": ctx.dnsdomain,
506             "trustParent" : ctx.parent_partition_dn,
507             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CR_NTDS_NC|samba.dsdb.SYSTEM_FLAG_CR_NTDS_DOMAIN)}
508         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
509             rec["msDS-Behavior-Version"] = str(ctx.behavior_version)
510
511         rec2 = {
512             "dn" : ctx.ntds_dn,
513             "objectclass" : "nTDSDSA",
514             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
515             "dMDLocation" : ctx.schema_dn}
516
517         nc_list = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
518
519         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
520             rec2["msDS-Behavior-Version"] = str(ctx.behavior_version)
521
522         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
523             rec2["msDS-HasDomainNCs"] = ctx.base_dn
524
525         rec2["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
526         rec2["HasMasterNCs"]      = nc_list
527         if ctx.behavior_version >= samba.dsdb.DS_DOMAIN_FUNCTION_2003:
528             rec2["msDS-HasMasterNCs"] = nc_list
529         rec2["options"] = "1"
530         rec2["invocationId"] = ndr_pack(ctx.invocation_id)
531
532         objects = ctx.DsAddEntry([rec, rec2])
533         if len(objects) != 2:
534             raise DCJoinException("Expected 2 objects from DsAddEntry")
535
536         ctx.ntds_guid = objects[1].guid
537
538         print("Replicating partition DN")
539         ctx.repl.replicate(ctx.partition_dn,
540                            misc.GUID("00000000-0000-0000-0000-000000000000"),
541                            ctx.ntds_guid,
542                            exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
543                            replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
544
545         print("Replicating NTDS DN")
546         ctx.repl.replicate(ctx.ntds_dn,
547                            misc.GUID("00000000-0000-0000-0000-000000000000"),
548                            ctx.ntds_guid,
549                            exop=drsuapi.DRSUAPI_EXOP_REPL_OBJ,
550                            replica_flags=drsuapi.DRSUAPI_DRS_WRIT_REP)
551
552     def join_provision(ctx):
553         '''provision the local SAM'''
554
555         print "Calling bare provision"
556
557         logger = logging.getLogger("provision")
558         logger.addHandler(logging.StreamHandler(sys.stdout))
559         smbconf = ctx.lp.configfile
560
561         presult = provision(logger, system_session(), None,
562                             smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
563                             realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
564                             schemadn=ctx.schema_dn,
565                             configdn=ctx.config_dn,
566                             serverdn=ctx.server_dn, domain=ctx.domain_name,
567                             hostname=ctx.myname, domainsid=ctx.domsid,
568                             machinepass=ctx.acct_pass, serverrole="domain controller",
569                             sitename=ctx.site, lp=ctx.lp, ntdsguid=ctx.ntds_guid)
570         print "Provision OK for domain DN %s" % presult.domaindn
571         ctx.local_samdb = presult.samdb
572         ctx.lp          = presult.lp
573         ctx.paths       = presult.paths
574         ctx.names       = presult.names
575
576     def join_provision_own_domain(ctx):
577         '''provision the local SAM'''
578
579         # we now operate exclusively on the local database, which
580         # we need to reopen in order to get the newly created schema
581         print("Reconnecting to local samdb")
582         ctx.samdb = SamDB(url=ctx.local_samdb.url,
583                           session_info=system_session(),
584                           lp=ctx.local_samdb.lp,
585                           global_schema=False)
586         ctx.samdb.set_invocation_id(str(ctx.invocation_id))
587         ctx.local_samdb = ctx.samdb
588
589         print("Finding domain GUID from ncName")
590         res = ctx.local_samdb.search(base=ctx.partition_dn, scope=ldb.SCOPE_BASE, attrs=['ncName'],
591                                      controls=["extended_dn:1:1"])
592         domguid = str(misc.GUID(ldb.Dn(ctx.samdb, res[0]['ncName'][0]).get_extended_component('GUID')))
593         print("Got domain GUID %s" % domguid)
594
595         print("Calling own domain provision")
596
597         logger = logging.getLogger("provision")
598         logger.addHandler(logging.StreamHandler(sys.stdout))
599
600         secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
601
602         presult = provision_fill(ctx.local_samdb, secrets_ldb,
603                                  logger, ctx.names, ctx.paths, domainsid=security.dom_sid(ctx.domsid),
604                                  domainguid=domguid,
605                                  targetdir=ctx.targetdir, samdb_fill=FILL_SUBDOMAIN,
606                                  machinepass=ctx.acct_pass, serverrole="domain controller",
607                                  lp=ctx.lp, hostip=ctx.names.hostip, hostip6=ctx.names.hostip6)
608         print("Provision OK for domain %s" % ctx.names.dnsdomain)
609
610
611     def join_replicate(ctx):
612         '''replicate the SAM'''
613
614         print "Starting replication"
615         ctx.local_samdb.transaction_start()
616         try:
617             source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
618             if ctx.ntds_guid is None:
619                 print("Using DS_BIND_GUID_W2K3")
620                 destination_dsa_guid = misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID_W2K3)
621             else:
622                 destination_dsa_guid = ctx.ntds_guid
623
624             if ctx.RODC:
625                 repl_creds = Credentials()
626                 repl_creds.guess(ctx.lp)
627                 repl_creds.set_kerberos_state(DONT_USE_KERBEROS)
628                 repl_creds.set_username(ctx.samname)
629                 repl_creds.set_password(ctx.acct_pass)
630             else:
631                 repl_creds = ctx.creds
632
633             binding_options = "seal"
634             if int(ctx.lp.get("log level")) >= 5:
635                 binding_options += ",print"
636             repl = drs_utils.drs_Replicate(
637                 "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options),
638                 ctx.lp, repl_creds, ctx.local_samdb)
639
640             repl.replicate(ctx.schema_dn, source_dsa_invocation_id,
641                     destination_dsa_guid, schema=True, rodc=ctx.RODC,
642                     replica_flags=ctx.replica_flags)
643             repl.replicate(ctx.config_dn, source_dsa_invocation_id,
644                     destination_dsa_guid, rodc=ctx.RODC,
645                     replica_flags=ctx.replica_flags)
646             if not ctx.subdomain:
647                 repl.replicate(ctx.base_dn, source_dsa_invocation_id,
648                                destination_dsa_guid, rodc=ctx.RODC,
649                                replica_flags=ctx.domain_replica_flags)
650             if ctx.RODC:
651                 repl.replicate(ctx.acct_dn, source_dsa_invocation_id,
652                         destination_dsa_guid,
653                         exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
654                 repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id,
655                         destination_dsa_guid,
656                         exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
657             ctx.repl = repl
658             ctx.source_dsa_invocation_id = source_dsa_invocation_id
659             ctx.destination_dsa_guid = destination_dsa_guid
660
661             print "Committing SAM database"
662         except:
663             ctx.local_samdb.transaction_cancel()
664             raise
665         else:
666             ctx.local_samdb.transaction_commit()
667
668
669     def join_finalise(ctx):
670         '''finalise the join, mark us synchronised and setup secrets db'''
671
672         print "Setting isSynchronized and dsServiceName"
673         m = ldb.Message()
674         m.dn = ldb.Dn(ctx.local_samdb, '@ROOTDSE')
675         m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
676         m["dsServiceName"] = ldb.MessageElement("<GUID=%s>" % str(ctx.ntds_guid),
677                                                 ldb.FLAG_MOD_REPLACE, "dsServiceName")
678         ctx.local_samdb.modify(m)
679
680         if ctx.subdomain:
681             return
682
683         secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
684
685         print "Setting up secrets database"
686         secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
687                             realm=ctx.realm,
688                             dnsdomain=ctx.dnsdomain,
689                             netbiosname=ctx.myname,
690                             domainsid=security.dom_sid(ctx.domsid),
691                             machinepass=ctx.acct_pass,
692                             secure_channel_type=ctx.secure_channel_type,
693                             key_version_number=ctx.key_version_number)
694
695     def join_setup_trusts(ctx):
696         '''provision the local SAM'''
697
698         def arcfour_encrypt(key, data):
699             from Crypto.Cipher import ARC4
700             c = ARC4.new(key)
701             return c.encrypt(data)
702
703         def string_to_array(string):
704             blob = [0] * len(string)
705
706             for i in range(len(string)):
707                 blob[i] = ord(string[i])
708
709             return blob
710
711         print "Setup domain trusts with server %s" % ctx.server
712         binding_options = ""  # why doesn't signing work gere? w2k8r2 claims no session key
713         lsaconn = lsa.lsarpc("ncacn_np:%s[%s]" % (ctx.server, binding_options),
714                              ctx.lp, ctx.creds)
715
716         objectAttr = lsa.ObjectAttribute()
717         objectAttr.sec_qos = lsa.QosInfo()
718
719         pol_handle = lsaconn.OpenPolicy2(''.decode('utf-8'),
720                                          objectAttr, security.SEC_FLAG_MAXIMUM_ALLOWED)
721
722         info = lsa.TrustDomainInfoInfoEx()
723         info.domain_name.string = ctx.dnsdomain
724         info.netbios_name.string = ctx.domain_name
725         info.sid = security.dom_sid(ctx.domsid)
726         info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND | lsa.LSA_TRUST_DIRECTION_OUTBOUND
727         info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
728         info.trust_attributes = lsa.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
729
730         try:
731             oldname = lsa.String()
732             oldname.string = ctx.dnsdomain
733             oldinfo = lsaconn.QueryTrustedDomainInfoByName(pol_handle, oldname,
734                                                            lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
735             print("Removing old trust record for %s (SID %s)" % (ctx.dnsdomain, oldinfo.info_ex.sid))
736             lsaconn.DeleteTrustedDomain(pol_handle, oldinfo.info_ex.sid)
737         except RuntimeError:
738             pass
739
740         password_blob = string_to_array(ctx.trustdom_pass.encode('utf-16-le'))
741
742         clear_value = drsblobs.AuthInfoClear()
743         clear_value.size = len(password_blob)
744         clear_value.password = password_blob
745
746         clear_authentication_information = drsblobs.AuthenticationInformation()
747         clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
748         clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
749         clear_authentication_information.AuthInfo = clear_value
750
751         authentication_information_array = drsblobs.AuthenticationInformationArray()
752         authentication_information_array.count = 1
753         authentication_information_array.array = [clear_authentication_information]
754
755         outgoing = drsblobs.trustAuthInOutBlob()
756         outgoing.count = 1
757         outgoing.current = authentication_information_array
758
759         trustpass = drsblobs.trustDomainPasswords()
760         confounder = [3] * 512
761
762         for i in range(512):
763             confounder[i] = random.randint(0, 255)
764
765         trustpass.confounder = confounder
766
767         trustpass.outgoing = outgoing
768         trustpass.incoming = outgoing
769
770         trustpass_blob = ndr_pack(trustpass)
771
772         encrypted_trustpass = arcfour_encrypt(lsaconn.session_key, trustpass_blob)
773
774         auth_blob = lsa.DATA_BUF2()
775         auth_blob.size = len(encrypted_trustpass)
776         auth_blob.data = string_to_array(encrypted_trustpass)
777
778         auth_info = lsa.TrustDomainInfoAuthInfoInternal()
779         auth_info.auth_blob = auth_blob
780
781         trustdom_handle = lsaconn.CreateTrustedDomainEx2(pol_handle,
782                                                          info,
783                                                          auth_info,
784                                                          security.SEC_STD_DELETE)
785
786         rec = {
787             "dn" : "cn=%s,cn=system,%s" % (ctx.parent_dnsdomain, ctx.base_dn),
788             "objectclass" : "trustedDomain",
789             "trustType" : str(info.trust_type),
790             "trustAttributes" : str(info.trust_attributes),
791             "trustDirection" : str(info.trust_direction),
792             "flatname" : ctx.parent_domain_name,
793             "trustPartner" : ctx.parent_dnsdomain,
794             "trustAuthIncoming" : ndr_pack(outgoing),
795             "trustAuthOutgoing" : ndr_pack(outgoing)
796             }
797         ctx.local_samdb.add(rec)
798
799         rec = {
800             "dn" : "cn=%s$,cn=users,%s" % (ctx.parent_domain_name, ctx.base_dn),
801             "objectclass" : "user",
802             "userAccountControl" : str(samba.dsdb.UF_INTERDOMAIN_TRUST_ACCOUNT),
803             "clearTextPassword" : ctx.trustdom_pass.encode('utf-16-le')
804             }
805         ctx.local_samdb.add(rec)
806
807
808     def do_join(ctx):
809         ctx.cleanup_old_join()
810         try:
811             ctx.join_add_objects()
812             ctx.join_provision()
813             ctx.join_replicate()
814             if ctx.subdomain:
815                 ctx.join_add_objects2()
816                 ctx.join_provision_own_domain()
817                 ctx.join_setup_trusts()
818             ctx.join_finalise()
819         except Exception:
820             print "Join failed - cleaning up"
821             #ctx.cleanup_old_join()
822             raise
823
824
825 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
826               targetdir=None, domain=None, domain_critical_only=False):
827     """join as a RODC"""
828
829     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
830
831     lp.set("workgroup", ctx.domain_name)
832     print("workgroup is %s" % ctx.domain_name)
833
834     lp.set("realm", ctx.realm)
835     print("realm is %s" % ctx.realm)
836
837     ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
838
839     # setup some defaults for accounts that should be replicated to this RODC
840     ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
841                              "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
842                              "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
843                              "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
844                              "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
845     ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
846
847     mysid = ctx.get_mysid()
848     admin_dn = "<SID=%s>" % mysid
849     ctx.managedby = admin_dn
850
851     ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
852                               samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
853                               samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
854
855     ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
856                       "RestrictedKrbHost/%s" % ctx.dnshostname ])
857
858     ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
859     ctx.secure_channel_type = misc.SEC_CHAN_RODC
860     ctx.RODC = True
861     ctx.replica_flags  =  (drsuapi.DRSUAPI_DRS_INIT_SYNC |
862                            drsuapi.DRSUAPI_DRS_PER_SYNC |
863                            drsuapi.DRSUAPI_DRS_GET_ANC |
864                            drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
865                            drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
866                            drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
867     ctx.domain_replica_flags = ctx.replica_flags
868     if domain_critical_only:
869         ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
870
871     ctx.do_join()
872
873
874     print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
875
876
877 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
878             targetdir=None, domain=None, domain_critical_only=False):
879     """join as a DC"""
880     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
881
882     lp.set("workgroup", ctx.domain_name)
883     print("workgroup is %s" % ctx.domain_name)
884
885     lp.set("realm", ctx.realm)
886     print("realm is %s" % ctx.realm)
887
888     ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
889
890     ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
891     ctx.secure_channel_type = misc.SEC_CHAN_BDC
892
893     ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
894                          drsuapi.DRSUAPI_DRS_INIT_SYNC |
895                          drsuapi.DRSUAPI_DRS_PER_SYNC |
896                          drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
897                          drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
898     ctx.domain_replica_flags = ctx.replica_flags
899     if domain_critical_only:
900         ctx.domain_replica_flags |= drsuapi.DRSUAPI_DRS_CRITICAL_ONLY
901
902     ctx.do_join()
903     print "Joined domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)
904
905 def join_subdomain(server=None, creds=None, lp=None, site=None, netbios_name=None,
906                    targetdir=None, parent_domain=None, dnsdomain=None, netbios_domain=None):
907     """join as a DC"""
908     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, parent_domain)
909     ctx.subdomain = True
910     ctx.parent_domain_name = ctx.domain_name
911     ctx.domain_name = netbios_domain
912     ctx.realm = dnsdomain
913     ctx.parent_dnsdomain = ctx.dnsdomain
914     ctx.parent_partition_dn = ctx.get_parent_partition_dn()
915     ctx.dnsdomain = dnsdomain
916     ctx.partition_dn = "CN=%s,CN=Partitions,%s" % (ctx.domain_name, ctx.config_dn)
917     ctx.base_dn = samba.dn_from_dns_name(dnsdomain)
918     ctx.domsid = str(security.random_sid())
919     ctx.acct_dn = None
920     ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
921     ctx.trustdom_pass = samba.generate_random_password(128, 128)
922
923     ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
924
925     ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
926     ctx.secure_channel_type = misc.SEC_CHAN_BDC
927
928     ctx.replica_flags = (drsuapi.DRSUAPI_DRS_WRIT_REP |
929                          drsuapi.DRSUAPI_DRS_INIT_SYNC |
930                          drsuapi.DRSUAPI_DRS_PER_SYNC |
931                          drsuapi.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
932                          drsuapi.DRSUAPI_DRS_NEVER_SYNCED)
933     ctx.domain_replica_flags = ctx.replica_flags
934
935     ctx.do_join()
936     print "Created domain %s (SID %s) as a DC" % (ctx.domain_name, ctx.domsid)