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