s4-join: fixed SPNs, invocationId and dnshostname and python join
[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 import samba.getopt as options
22 from samba.auth import system_session
23 from samba.samdb import SamDB
24 from samba import gensec, Ldb, drs_utils
25 import ldb, samba, sys, os, uuid
26 from samba.ndr import ndr_pack, ndr_unpack, ndr_print
27 from samba.dcerpc import security, drsuapi, misc, netlogon, nbt
28 from samba.credentials import Credentials, DONT_USE_KERBEROS
29 from samba.provision import secretsdb_self_join, provision, FILL_DRS, find_setup_dir
30 from samba.schema import Schema
31 from samba.net import Net
32 import logging
33 from samba.dsdb import DS_DOMAIN_FUNCTION_2008_R2
34 import talloc
35
36 # this makes debugging easier
37 talloc.enable_null_tracking()
38
39 class dc_join:
40     '''perform a DC join'''
41
42     def __init__(ctx, server=None, creds=None, lp=None, site=None, netbios_name=None,
43                  targetdir=None, domain=None):
44         ctx.creds = creds
45         ctx.lp = lp
46         ctx.site = site
47         ctx.netbios_name = netbios_name
48         ctx.targetdir = targetdir
49
50         ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
51         ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
52
53         if server is not None:
54             ctx.server = server
55         else:
56             print("Finding a writeable DC for domain '%s'" % domain)
57             ctx.server = ctx.find_dc(domain)
58             print("Found DC %s" % ctx.server)
59
60         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
61                           session_info=system_session(),
62                           credentials=ctx.creds, lp=ctx.lp)
63
64         ctx.myname = netbios_name
65         ctx.samname = "%s$" % ctx.myname
66         ctx.base_dn = str(ctx.samdb.get_default_basedn())
67         ctx.root_dn = str(ctx.samdb.get_root_basedn())
68         ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
69         ctx.config_dn = str(ctx.samdb.get_config_basedn())
70         ctx.domsid = ctx.samdb.get_domain_sid()
71         ctx.domain_name = ctx.get_domain_name()
72
73         lp.set("realm", ctx.domain_name)
74
75         ctx.dc_ntds_dn = ctx.get_dsServiceName()
76         ctx.dc_dnsHostName = ctx.get_dnsHostName()
77         ctx.acct_pass = samba.generate_random_password(12, 32)
78         ctx.mysid = ctx.get_mysid()
79
80         # work out the DNs of all the objects we will be adding
81         ctx.admin_dn = "<SID=%s>" % ctx.mysid
82         ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
83         ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
84         ctx.topology_dn = "CN=%s,CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % (ctx.myname, ctx.base_dn)
85
86         ctx.dnsdomain = ldb.Dn(ctx.samdb, ctx.base_dn).canonical_str().split('/')[0]
87         ctx.realm = ctx.dnsdomain
88         ctx.dnshostname = "%s.%s" % (ctx.myname.lower(), ctx.dnsdomain)
89
90         ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
91
92         ctx.setup_dir = find_setup_dir()
93         ctx.tmp_samdb = None
94
95         ctx.SPNs = [ "HOST/%s" % ctx.myname,
96                      "HOST/%s" % ctx.dnshostname,
97                      "GC/%s/%s" % (ctx.dnshostname, ctx.dnsdomain) ]
98
99         # these elements are optional
100         ctx.never_reveal_sid = None
101         ctx.reveal_sid = None
102         ctx.connection_dn = None
103         ctx.RODC = False
104         ctx.krbtgt_dn = None
105         ctx.drsuapi = None
106         ctx.managedby = None
107
108
109     def del_noerror(ctx, dn, recursive=False):
110         if recursive:
111             try:
112                 res = ctx.samdb.search(base=dn, scope=ldb.SCOPE_ONELEVEL, attrs=["dn"])
113             except:
114                 return
115             for r in res:
116                 ctx.del_noerror(r.dn, recursive=True)
117         try:
118             ctx.samdb.delete(dn)
119             print "Deleted %s" % dn
120         except:
121             pass
122
123     def cleanup_old_join(ctx):
124         '''remove any DNs from a previous join'''
125         try:
126             # find the krbtgt link
127             print("checking samaccountname")
128             res = ctx.samdb.search(base=ctx.samdb.get_default_basedn(),
129                                    expression='samAccountName=%s' % ctx.samname,
130                                    attrs=["msDS-krbTgtLink"])
131             if res:
132                 ctx.del_noerror(res[0].dn, recursive=True)
133             if ctx.connection_dn is not None:
134                 ctx.del_noerror(ctx.connection_dn)
135             if ctx.krbtgt_dn is not None:
136                 ctx.del_noerror(ctx.krbtgt_dn)
137             ctx.del_noerror(ctx.ntds_dn)
138             ctx.del_noerror(ctx.server_dn, recursive=True)
139             ctx.del_noerror(ctx.topology_dn)
140             if res:
141                 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
142                 ctx.del_noerror(ctx.new_krbtgt_dn)
143         except:
144             pass
145
146     def find_dc(ctx, domain):
147         '''find a writeable DC for the given domain'''
148         try:
149             ctx.cldap_ret = ctx.net.finddc(domain, nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
150         except Exception, reason:
151             print("Failed to find a writeable DC for domain '%s': %s" % (domain, reason))
152             sys.exit(1)
153         if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
154             ctx.site = ctx.cldap_ret.client_site
155         return ctx.cldap_ret.pdc_dns_name
156
157
158     def get_dsServiceName(ctx):
159         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
160         return res[0]["dsServiceName"][0]
161
162     def get_dnsHostName(ctx):
163         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
164         return res[0]["dnsHostName"][0]
165
166     def get_domain_name(ctx):
167         '''get netbios name of the domain from the partitions record'''
168         partitions_dn = ctx.samdb.get_partitions_dn()
169         res = ctx.samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
170                                expression='ncName=%s' % ctx.samdb.get_default_basedn())
171         return res[0]["nETBIOSName"][0]
172
173     def get_mysid(ctx):
174         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
175         binsid = res[0]["tokenGroups"][0]
176         return ctx.samdb.schema_format_value("objectSID", binsid)
177
178     def add_krbtgt_account(ctx):
179         '''RODCs need a special krbtgt account'''
180         print "Adding %s" % ctx.krbtgt_dn
181         rec = {
182             "dn" : ctx.krbtgt_dn,
183             "objectclass" : "user",
184             "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
185                                        samba.dsdb.UF_ACCOUNTDISABLE),
186             "showinadvancedviewonly" : "TRUE",
187             "description" : "krbtgt for %s" % ctx.samname}
188         ctx.samdb.add(rec, ["rodc_join:1:1"])
189
190         # now we need to search for the samAccountName attribute on the krbtgt DN,
191         # as this will have been magically set to the krbtgt number
192         res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
193         ctx.krbtgt_name = res[0]["samAccountName"][0]
194
195         print "Got krbtgt_name=%s" % ctx.krbtgt_name
196
197         m = ldb.Message()
198         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
199         m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
200                                                   ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
201         ctx.samdb.modify(m)
202
203         ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
204         print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
205         ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
206
207     def drsuapi_connect(ctx):
208         '''make a DRSUAPI connection to the server'''
209         binding_string = "ncacn_ip_tcp:%s[seal]" % ctx.server
210         ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
211         ctx.drsuapi_handle = drs_utils.drs_DsBind(ctx.drsuapi)
212
213     def create_tmp_samdb(ctx):
214         '''create a temporary samdb object for schema queries'''
215         def setup_path(file):
216             return os.path.join(ctx.setup_dir, file)
217         ctx.tmp_schema = Schema(setup_path, security.dom_sid(ctx.domsid),
218                                 schemadn=ctx.schema_dn)
219         ctx.tmp_samdb = SamDB(session_info=system_session(), url=None, auto_connect=False,
220                               credentials=ctx.creds, lp=ctx.lp, global_schema=False,
221                               am_rodc=False)
222         ctx.tmp_samdb.set_schema(ctx.tmp_schema)
223
224     def build_DsReplicaAttribute(ctx, attrname, attrvalue):
225         '''build a DsReplicaAttributeCtr object'''
226         r = drsuapi.DsReplicaAttribute()
227         r.attid = ctx.tmp_samdb.get_attid_from_lDAPDisplayName(attrname)
228         r.value_ctr = 1
229
230
231     def DsAddEntry(ctx, rec):
232         '''add a record via the DRSUAPI DsAddEntry call'''
233         if ctx.drsuapi is None:
234             ctx.drsuapi_connect()
235         if ctx.tmp_samdb is None:
236             ctx.create_tmp_samdb()
237
238         id = drsuapi.DsReplicaObjectIdentifier()
239         id.dn = rec['dn']
240
241         attrs = []
242         for a in rec:
243             if a == 'dn':
244                 continue
245             if not isinstance(rec[a], list):
246                 v = [rec[a]]
247             else:
248                 v = rec[a]
249             rattr = ctx.tmp_samdb.dsdb_DsReplicaAttribute(ctx.tmp_samdb, a, v)
250             attrs.append(rattr)
251
252         attribute_ctr = drsuapi.DsReplicaAttributeCtr()
253         attribute_ctr.num_attributes = len(attrs)
254         attribute_ctr.attributes = attrs
255
256         object = drsuapi.DsReplicaObject()
257         object.identifier = id
258         object.attribute_ctr = attribute_ctr
259
260         first_object = drsuapi.DsReplicaObjectListItem()
261         first_object.object = object
262
263         req2 = drsuapi.DsAddEntryRequest2()
264         req2.first_object = first_object
265
266         # this dies
267         (level, ctr) = ctx.drsuapi.DsAddEntry(ctx.drsuapi_handle, 2, req2)
268
269
270     def join_add_objects(ctx):
271         '''add the various objects needed for the join'''
272         print "Adding %s" % ctx.acct_dn
273         rec = {
274             "dn" : ctx.acct_dn,
275             "objectClass": "computer",
276             "displayname": ctx.samname,
277             "samaccountname" : ctx.samname,
278             "userAccountControl" : str(ctx.userAccountControl),
279             "dnshostname" : ctx.dnshostname,
280             "msDS-SupportedEncryptionTypes" : str(samba.dsdb.ENC_ALL_TYPES)}
281         if ctx.managedby:
282             rec["managedby"] = ctx.managedby
283         if ctx.never_reveal_sid:
284             rec["msDS-NeverRevealGroup"] = ctx.never_reveal_sid
285         if ctx.reveal_sid:
286             rec["msDS-RevealOnDemandGroup"] = ctx.reveal_sid
287         ctx.samdb.add(rec)
288
289         if ctx.krbtgt_dn:
290             ctx.add_krbtgt_account()
291
292         print "Adding %s" % ctx.server_dn
293         rec = {
294             "dn": ctx.server_dn,
295             "objectclass" : "server",
296             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
297                                 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
298                                 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
299             "serverReference" : ctx.acct_dn,
300             "dnsHostName" : ctx.dnshostname}
301         ctx.samdb.add(rec)
302
303         # FIXME: the partition (NC) assignment has to be made dynamic
304         print "Adding %s" % ctx.ntds_dn
305         rec = {
306             "dn" : ctx.ntds_dn,
307             "objectclass" : "nTDSDSA",
308             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
309             "dMDLocation" : ctx.schema_dn,
310             "msDS-Behavior-Version" : str(DS_DOMAIN_FUNCTION_2008_R2),
311             "msDS-HasDomainNCs" : ctx.base_dn }
312
313         if ctx.RODC:
314             rec["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx.schema_dn
315             rec["msDS-HasFullReplicaNCs"] = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
316             rec["options"] = "37"
317             ctx.samdb.add(rec, ["rodc_join:1:1"])
318         else:
319             rec["objectCategory"] = "CN=NTDS-DSA,%s" % ctx.schema_dn
320             rec["HasMasterNCs"]      = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
321             rec["msDS-HasMasterNCs"] = [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]
322             rec["options"] = "1"
323             rec["invocationId"] = ndr_pack(misc.GUID(str(uuid.uuid4())))
324             ctx.DsAddEntry(rec)
325
326         # find the GUID of our NTDS DN
327         res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
328         ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
329
330         if ctx.connection_dn is not None:
331             print "Adding %s" % ctx.connection_dn
332             rec = {
333                 "dn" : ctx.connection_dn,
334                 "objectclass" : "nTDSConnection",
335                 "enabledconnection" : "TRUE",
336                 "options" : "65",
337                 "fromServer" : ctx.dc_ntds_dn}
338             ctx.samdb.add(rec)
339
340         print "Adding %s" % ctx.topology_dn
341         rec = {
342             "dn" : ctx.topology_dn,
343             "objectclass" : "msDFSR-Member",
344             "msDFSR-ComputerReference" : ctx.acct_dn,
345             "serverReference" : ctx.ntds_dn}
346         ctx.samdb.add(rec)
347
348         print "Adding SPNs to %s" % ctx.acct_dn
349         m = ldb.Message()
350         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
351         for i in range(len(ctx.SPNs)):
352             ctx.SPNs[i] = ctx.SPNs[i].replace("$NTDSGUID", str(ctx.ntds_guid))
353         m["servicePrincipalName"] = ldb.MessageElement(ctx.SPNs,
354                                                        ldb.FLAG_MOD_ADD,
355                                                        "servicePrincipalName")
356         ctx.samdb.modify(m)
357
358         print "Setting account password for %s" % ctx.samname
359         ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ctx.samname,
360                               ctx.acct_pass,
361                               force_change_at_next_login=False,
362                               username=ctx.samname)
363         res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-keyVersionNumber"])
364         ctx.key_version_number = res[0]["msDS-keyVersionNumber"]
365
366
367     def join_provision(ctx):
368         '''provision the local SAM'''
369
370         print "Calling bare provision"
371
372         logger = logging.getLogger("provision")
373         logger.addHandler(logging.StreamHandler(sys.stdout))
374         smbconf = ctx.lp.configfile
375
376         presult = provision(ctx.setup_dir, logger, system_session(), None,
377                             smbconf=smbconf, targetdir=ctx.targetdir, samdb_fill=FILL_DRS,
378                             realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
379                             schemadn=ctx.schema_dn,
380                             configdn=ctx.config_dn,
381                             serverdn=ctx.server_dn, domain=ctx.domain_name,
382                             hostname=ctx.myname, hostip="127.0.0.1", domainsid=ctx.domsid,
383                             machinepass=ctx.acct_pass, serverrole="domain controller",
384                             sitename=ctx.site)
385         print "Provision OK for domain DN %s" % presult.domaindn
386         ctx.local_samdb = presult.samdb
387         ctx.lp          = presult.lp
388         ctx.paths       = presult.paths
389
390
391     def join_replicate(ctx):
392         '''replicate the SAM'''
393
394         print "Starting replication"
395         ctx.local_samdb.transaction_start()
396
397         source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
398
399         acct_creds = Credentials()
400         acct_creds.guess(ctx.lp)
401         acct_creds.set_kerberos_state(DONT_USE_KERBEROS)
402         acct_creds.set_username(ctx.samname)
403         acct_creds.set_password(ctx.acct_pass)
404
405         repl = drs_utils.drs_Replicate("ncacn_ip_tcp:%s[seal]" % ctx.server, ctx.lp, acct_creds, ctx.local_samdb)
406
407         repl.replicate(ctx.schema_dn, source_dsa_invocation_id, ctx.ntds_guid, schema=True, rodc=ctx.RODC)
408         repl.replicate(ctx.config_dn, source_dsa_invocation_id, ctx.ntds_guid, rodc=ctx.RODC)
409         repl.replicate(ctx.base_dn, source_dsa_invocation_id, ctx.ntds_guid, rodc=ctx.RODC)
410         if ctx.RODC:
411             repl.replicate(ctx.acct_dn, source_dsa_invocation_id, ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
412             repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id, ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
413
414         print "Committing SAM database"
415         ctx.local_samdb.transaction_commit()
416
417
418     def join_finalise(ctx):
419         '''finalise the join, mark us synchronised and setup secrets db'''
420
421         print "Setting isSynchronized"
422         m = ldb.Message()
423         m.dn = ldb.Dn(ctx.samdb, '@ROOTDSE')
424         m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
425         ctx.samdb.modify(m)
426
427         secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
428
429         print "Setting up secrets database"
430         secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
431                             realm=ctx.realm,
432                             dnsdomain=ctx.dnsdomain,
433                             netbiosname=ctx.myname,
434                             domainsid=security.dom_sid(ctx.domsid),
435                             machinepass=ctx.acct_pass,
436                             secure_channel_type=ctx.secure_channel_type,
437                             key_version_number=ctx.key_version_number)
438
439     def do_join(ctx):
440         ctx.cleanup_old_join()
441         try:
442             ctx.join_add_objects()
443             ctx.join_provision()
444             ctx.join_replicate()
445             ctx.join_finalise()
446         except:
447             print "Join failed - cleaning up"
448             ctx.cleanup_old_join()
449             raise
450
451
452 def join_RODC(server=None, creds=None, lp=None, site=None, netbios_name=None,
453               targetdir=None, domain=None):
454     """join as a RODC"""
455
456     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
457
458     ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
459
460     # setup some defaults for accounts that should be replicated to this RODC
461     ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
462                              "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
463                              "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
464                              "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
465                              "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
466     ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
467
468     ctx.managedby = ctx.admin_dn
469
470     ctx.userAccountControl = (samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
471                               samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
472                               samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT)
473
474     ctx.SPNs.extend([ "RestrictedKrbHost/%s" % ctx.myname,
475                       "RestrictedKrbHost/%s" % ctx.dnshostname ])
476
477     ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
478     ctx.secure_channel_type = misc.SEC_CHAN_RODC
479     ctx.RODC = True
480     ctx.do_join()
481     print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
482
483
484 def join_DC(server=None, creds=None, lp=None, site=None, netbios_name=None,
485             targetdir=None, domain=None):
486     """join as a DC"""
487     ctx = dc_join(server, creds, lp, site, netbios_name, targetdir, domain)
488
489     ctx.userAccountControl = samba.dsdb.UF_SERVER_TRUST_ACCOUNT | samba.dsdb.UF_TRUSTED_FOR_DELEGATION
490
491     ctx.SPNs.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx.dnsdomain)
492     ctx.secure_channel_type = misc.SEC_CHAN_BDC
493
494     ctx.do_join()
495     print "Joined domain %s (SID %s) as an DC" % (ctx.domain_name, ctx.domsid)