s4:python/samba/join.py - use constant for DC function level
[ab/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 import samba.getopt as options
22 from samba.auth import system_session
23 from samba.samdb import SamDB
24 from samba import gensec, Ldb
25 import ldb, samba, sys
26 from samba.ndr import ndr_pack, ndr_unpack, ndr_print
27 from samba.dcerpc import security
28 from samba.dcerpc import drsuapi, misc, netlogon, nbt
29 from samba.credentials import Credentials, DONT_USE_KERBEROS
30 from samba.provision import secretsdb_self_join, provision, FILL_DRS, find_setup_dir
31 from samba.net import Net
32 import logging
33 from samba.drs_utils import drs_Replicate
34 from samba.dsdb import DS_DOMAIN_FUNCTION_2008_R2
35
36 # this makes debugging easier
37 samba.talloc_enable_null_tracking()
38
39 class join_ctx:
40     '''hold join context variables'''
41     pass
42
43 def join_rodc(server=None, creds=None, lp=None, site=None, netbios_name=None,
44               targetdir=None, domain=None):
45     """join as a RODC"""
46
47     def del_noerror(samdb, dn):
48         try:
49             samdb.delete(dn)
50             print "Deleted %s" % dn
51         except:
52             pass
53
54     def cleanup_old_join(ctx):
55         '''remove any DNs from a previous join'''
56         try:
57             # find the krbtgt link
58             res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-krbTgtLink"])
59             del_noerror(ctx.samdb, ctx.acct_dn)
60             del_noerror(ctx.samdb, ctx.connection_dn)
61             del_noerror(ctx.samdb, ctx.krbtgt_dn)
62             del_noerror(ctx.samdb, ctx.ntds_dn)
63             del_noerror(ctx.samdb, ctx.server_dn)
64             del_noerror(ctx.samdb, ctx.topology_dn)
65             ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
66             del_noerror(ctx.samdb, ctx.new_krbtgt_dn)
67         except:
68             pass
69
70     def find_dc(ctx, domain):
71         '''find a writeable DC for the given domain'''
72         ctx.cldap_ret = ctx.net.finddc(domain, nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE)
73         if ctx.cldap_ret.client_site is not None and ctx.cldap_ret.client_site != "":
74             ctx.site = ctx.cldap_ret.client_site
75         return ctx.cldap_ret.pdc_dns_name;
76
77
78     def get_dsServiceName(samdb):
79         res = samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
80         return res[0]["dsServiceName"][0]
81
82     def get_dnsHostName(samdb):
83         res = samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
84         return res[0]["dnsHostName"][0]
85
86     def get_domain_name(samdb):
87         '''get netbios name of the domain from the partitions record'''
88         partitions_dn = samdb.get_partitions_dn()
89         res = samdb.search(base=partitions_dn, scope=ldb.SCOPE_ONELEVEL, attrs=["nETBIOSName"],
90                            expression='ncName=%s' % samdb.get_default_basedn())
91         return res[0]["nETBIOSName"][0]
92
93     def get_mysid(samdb):
94         res = samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
95         binsid = res[0]["tokenGroups"][0]
96         return samdb.schema_format_value("objectSID", binsid)
97
98     def join_add_objects(ctx):
99         '''add the various objects needed for the join'''
100         print "Adding %s" % ctx.acct_dn
101         rec = {
102             "dn" : ctx.acct_dn,
103             "objectClass": "computer",
104             "displayname": ctx.samname,
105             "samaccountname" : ctx.samname,
106             "useraccountcontrol" : str(samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
107                                        samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
108                                        samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT),
109             "managedby" : ctx.admin_dn,
110             "dnshostname" : ctx.dnshostname,
111             "msDS-NeverRevealGroup" : ctx.never_reveal_sid,
112             "msDS-RevealOnDemandGroup" : ctx.reveal_sid}
113         ctx.samdb.add(rec)
114
115         print "Adding %s" % ctx.krbtgt_dn
116         rec = {
117             "dn" : ctx.krbtgt_dn,
118             "objectclass" : "user",
119             "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
120                                        samba.dsdb.UF_ACCOUNTDISABLE),
121             "showinadvancedviewonly" : "TRUE",
122             "description" : "tricky account"}
123         ctx.samdb.add(rec, ["rodc_join:1:1"])
124
125         # now we need to search for the samAccountName attribute on the krbtgt DN,
126         # as this will have been magically set to the krbtgt number
127         res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
128         ctx.krbtgt_name = res[0]["samAccountName"][0]
129
130         print "Got krbtgt_name=%s" % ctx.krbtgt_name
131
132         m = ldb.Message()
133         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
134         m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
135                                                   ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
136         ctx.samdb.modify(m)
137
138         ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
139         print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
140         ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
141
142         print "Adding %s" % ctx.server_dn
143         rec = {
144             "dn": ctx.server_dn,
145             "objectclass" : "server",
146             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
147                                 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
148                                 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
149             "serverReference" : ctx.acct_dn,
150             "dnsHostName" : ctx.dnshostname}
151         ctx.samdb.add(rec)
152
153         print "Adding %s" % ctx.ntds_dn
154         rec = {
155             "dn" : ctx.ntds_dn,
156             "objectclass" : "nTDSDSA",
157             "objectCategory" : "CN=NTDS-DSA-RO,%s" % ctx.schema_dn,
158             "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
159             "dMDLocation" : ctx.schema_dn,
160             "options" : "37",
161             "msDS-Behavior-Version" : str(DS_DOMAIN_FUNCTION_2008_R2),
162             "msDS-HasDomainNCs" : ctx.base_dn,
163             "msDS-HasFullReplicaNCs" : [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]}
164         ctx.samdb.add(rec, ["rodc_join:1:1"])
165
166         # find the GUID of our NTDS DN
167         res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
168         ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
169
170         print "Adding %s" % ctx.connection_dn
171         rec = {
172             "dn" : ctx.connection_dn,
173             "objectclass" : "nTDSConnection",
174             "enabledconnection" : "TRUE",
175             "options" : "65",
176             "fromServer" : ctx.dc_ntds_dn}
177         ctx.samdb.add(rec)
178
179         print "Adding %s" % ctx.topology_dn
180         rec = {
181             "dn" : ctx.topology_dn,
182             "objectclass" : "msDFSR-Member",
183             "msDFSR-ComputerReference" : ctx.acct_dn,
184             "serverReference" : ctx.ntds_dn}
185         ctx.samdb.add(rec)
186
187         print "Adding HOST SPNs to %s" % ctx.acct_dn
188         m = ldb.Message()
189         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
190         SPNs = [ "HOST/%s" % ctx.myname,
191                  "HOST/%s" % ctx.dnshostname ]
192         m["servicePrincipalName"] = ldb.MessageElement(SPNs,
193                                                        ldb.FLAG_MOD_ADD,
194                                                        "servicePrincipalName")
195         ctx.samdb.modify(m)
196
197         print "Adding RestrictedKrbHost SPNs to %s" % ctx.acct_dn
198         m = ldb.Message()
199         m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
200         SPNs = [ "RestrictedKrbHost/%s" % ctx.myname,
201                  "RestrictedKrbHost/%s" % ctx.dnshostname ]
202         m["servicePrincipalName"] = ldb.MessageElement(SPNs,
203                                                        ldb.FLAG_MOD_ADD,
204                                                        "servicePrincipalName")
205         ctx.samdb.modify(m)
206
207         print "Setting account password for %s" % ctx.samname
208         ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ctx.samname,
209                               ctx.acct_pass,
210                               force_change_at_next_login=False,
211                               username=ctx.samname)
212
213
214     def join_provision(ctx):
215         '''provision the local SAM'''
216
217         print "Calling bare provision"
218
219         setup_dir = find_setup_dir()
220         logger = logging.getLogger("provision")
221         logger.addHandler(logging.StreamHandler(sys.stdout))
222         smbconf = lp.configfile
223
224         presult = provision(setup_dir, logger, system_session(), None,
225                             smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS,
226                             realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
227                             schemadn=ctx.schema_dn,
228                             configdn=ctx.config_dn,
229                             serverdn=ctx.server_dn, domain=ctx.domain_name,
230                             hostname=ctx.myname, hostip="127.0.0.1", domainsid=ctx.domsid,
231                             machinepass=ctx.acct_pass, serverrole="domain controller",
232                             sitename=ctx.site)
233         print "Provision OK for domain DN %s" % presult.domaindn
234         ctx.local_samdb = presult.samdb
235         ctx.lp          = presult.lp
236         ctx.paths       = presult.paths
237
238
239     def join_replicate(ctx):
240         '''replicate the SAM'''
241
242         print "Starting replication"
243         ctx.local_samdb.transaction_start()
244
245         source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
246
247         acct_creds = Credentials()
248         acct_creds.guess(ctx.lp)
249         acct_creds.set_kerberos_state(DONT_USE_KERBEROS)
250         acct_creds.set_username(ctx.samname)
251         acct_creds.set_password(ctx.acct_pass)
252
253         repl = drs_Replicate("ncacn_ip_tcp:%s[seal]" % ctx.server, ctx.lp, acct_creds, ctx.local_samdb)
254
255         repl.replicate(ctx.schema_dn, source_dsa_invocation_id, ctx.ntds_guid, schema=True)
256         repl.replicate(ctx.config_dn, source_dsa_invocation_id, ctx.ntds_guid)
257         repl.replicate(ctx.base_dn, source_dsa_invocation_id, ctx.ntds_guid)
258         repl.replicate(ctx.acct_dn, source_dsa_invocation_id, ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET)
259         repl.replicate(ctx.new_krbtgt_dn, source_dsa_invocation_id, ctx.ntds_guid, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET)
260
261         print "Committing SAM database"
262         ctx.local_samdb.transaction_commit()
263
264
265     def join_finalise(ctx):
266         '''finalise the join, mark us synchronised and setup secrets db'''
267
268         print "Setting isSynchronized"
269         m = ldb.Message()
270         m.dn = ldb.Dn(ctx.samdb, '@ROOTDSE')
271         m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
272         ctx.samdb.modify(m)
273
274         secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
275
276         print "Setting up secrets database"
277         secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
278                             realm=ctx.realm,
279                             dnsdomain=ctx.dnsdomain,
280                             netbiosname=ctx.myname,
281                             domainsid=security.dom_sid(ctx.domsid),
282                             machinepass=ctx.acct_pass,
283                             secure_channel_type=misc.SEC_CHAN_RODC)
284
285
286
287     # main join code
288     ctx = join_ctx()
289     ctx.creds = creds
290     ctx.lp = lp
291     ctx.site = site
292     ctx.netbios_name = netbios_name
293     ctx.targetdir = targetdir
294
295     ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
296     ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
297
298     if server is not None:
299         ctx.server = server
300     else:
301         ctx.server = find_dc(ctx, domain)
302
303     ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
304                       session_info=system_session(),
305                       credentials=ctx.creds, lp=ctx.lp)
306
307     ctx.myname = netbios_name
308     ctx.samname = "%s$" % ctx.myname
309     ctx.base_dn = str(ctx.samdb.get_default_basedn())
310     ctx.root_dn = str(ctx.samdb.get_root_basedn())
311     ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
312     ctx.config_dn = str(ctx.samdb.get_config_basedn())
313     ctx.domsid = ctx.samdb.get_domain_sid()
314     ctx.domain_name = get_domain_name(ctx.samdb)
315
316     lp.set("realm", ctx.domain_name)
317
318     ctx.dc_ntds_dn = get_dsServiceName(ctx.samdb)
319     ctx.dc_dnsHostName = get_dnsHostName(ctx.samdb)
320     ctx.acct_pass = samba.generate_random_password(12, 32)
321     ctx.mysid = get_mysid(ctx.samdb)
322
323     # work out the DNs of all the objects we will be adding
324     ctx.admin_dn = "<SID=%s>" % ctx.mysid
325     ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
326     ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
327     ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
328     ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
329     ctx.topology_dn = "CN=%s,CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % (ctx.myname, ctx.base_dn)
330
331     # setup some defaults for accounts that should be replicated to this RODC
332     ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
333                              "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
334                              "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
335                              "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
336                              "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
337     ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
338
339     ctx.dnsdomain = ldb.Dn(ctx.samdb, ctx.base_dn).canonical_str().split('/')[0]
340     ctx.realm = ctx.dnsdomain
341     ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
342
343     ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
344
345     cleanup_old_join(ctx)
346     try:
347         join_add_objects(ctx)
348         join_provision(ctx)
349         join_replicate(ctx)
350         join_finalise(ctx)
351     except:
352         print "Join failed - cleaning up"
353         cleanup_old_join(ctx)
354         raise
355
356     print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)
357