90ad7c6eafc5ee7da8bd80e87966ec1c687b184c
[samba.git] / python / samba / remove_dc.py
1 # Unix SMB/CIFS implementation.
2 # Copyright Matthieu Patou <mat@matws.net> 2011
3 # Copyright Andrew Bartlett <abartlet@samba.org> 2008-2015
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18
19 import ldb
20 from ldb import LdbError
21 from samba.ndr import ndr_unpack
22 from samba.dcerpc import misc, dnsp
23 from samba.dcerpc.dnsp import DNS_TYPE_NS, DNS_TYPE_A, DNS_TYPE_AAAA, \
24     DNS_TYPE_CNAME, DNS_TYPE_SRV, DNS_TYPE_PTR
25
26 class DemoteException(Exception):
27     """Base element for demote errors"""
28
29     def __init__(self, value):
30         self.value = value
31
32     def __str__(self):
33         return "DemoteException: " + self.value
34
35
36 def remove_sysvol_references(samdb, logger, dc_name):
37     # DNs under the Configuration DN:
38     realm = samdb.domain_dns_name()
39     for s in ("CN=Enterprise,CN=Microsoft System Volumes,CN=System",
40               "CN=%s,CN=Microsoft System Volumes,CN=System" % realm):
41         dn = ldb.Dn(samdb, s)
42
43         # This is verbose, but it is the safe, escape-proof way
44         # to add a base and add an arbitrary RDN.
45         if dn.add_base(samdb.get_config_basedn()) == False:
46             raise DemoteException("Failed constructing DN %s by adding base %s" \
47                                   % (dn, samdb.get_config_basedn()))
48         if dn.add_child("CN=X") == False:
49             raise DemoteException("Failed constructing DN %s by adding child CN=X"\
50                                       % (dn))
51         dn.set_component(0, "CN", dc_name)
52         try:
53             logger.info("Removing Sysvol reference: %s" % dn)
54             samdb.delete(dn)
55         except ldb.LdbError as (enum, estr):
56             if enum == ldb.ERR_NO_SUCH_OBJECT:
57                 pass
58             else:
59                 raise
60
61     # DNs under the Domain DN:
62     for s in ("CN=Domain System Volumes (SYSVOL share),CN=File Replication Service,CN=System",
63               "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System"):
64         # This is verbose, but it is the safe, escape-proof way
65         # to add a base and add an arbitrary RDN.
66         dn = ldb.Dn(samdb, s)
67         if dn.add_base(samdb.get_default_basedn()) == False:
68             raise DemoteException("Failed constructing DN %s by adding base" % \
69                                   (dn, samdb.get_default_basedn()))
70         if dn.add_child("CN=X") == False:
71             raise DemoteException("Failed constructing DN %s by adding child %s"\
72                                   % (dn, rdn))
73         dn.set_component(0, "CN", dc_name)
74
75         try:
76             logger.info("Removing Sysvol reference: %s" % dn)
77             samdb.delete(dn)
78         except ldb.LdbError as (enum, estr):
79             if enum == ldb.ERR_NO_SUCH_OBJECT:
80                 pass
81             else:
82                 raise
83
84
85 def remove_dns_references(samdb, logger, dnsHostName):
86
87     # Check we are using in-database DNS
88     zones = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
89                          expression="(&(objectClass=dnsZone)(!(dc=RootDNSServers)))",
90                          attrs=[],
91                          controls=["search_options:0:2"])
92     if len(zones) == 0:
93         return
94
95     dnsHostNameUpper = dnsHostName.upper()
96
97     try:
98         primary_recs = samdb.dns_lookup(dnsHostName)
99     except RuntimeError as (enum, estr):
100         if enum == 0x000025F2: #WERR_DNS_ERROR_NAME_DOES_NOT_EXIST
101               return
102         raise DemoteException("lookup of %s failed: %s" % (dnsHostName, estr))
103     samdb.dns_replace(dnsHostName, [])
104
105     res = samdb.search("",
106                        scope=ldb.SCOPE_BASE, attrs=["namingContexts"])
107     assert len(res) == 1
108     ncs = res[0]["namingContexts"]
109
110     # Work out the set of names we will likely have an A record on by
111     # default.  This is by default all the partitions of type
112     # domainDNS.  By finding the canocial name of all the partitions,
113     # we find the likely candidates.  We only remove the record if it
114     # maches the IP that was used by the dnsHostName.  This avoids us
115     # needing to look a the dns_update_list file from in the demote
116     # script.
117
118     def dns_name_from_dn(dn):
119         # The canonical string of DC=example,DC=com is
120         # example.com/
121         #
122         # The canonical string of CN=Configuration,DC=example,DC=com
123         # is example.com/Configuration
124         return ldb.Dn(samdb, dn).canonical_str().split('/', 1)[0]
125
126     # By using a set here, duplicates via (eg) example.com/Configuration
127     # do not matter, they become just example.com
128     a_names_to_remove_from \
129         = set(dns_name_from_dn(dn) for dn in ncs)
130
131     def a_rec_to_remove(dnsRecord):
132         if dnsRecord.wType == DNS_TYPE_A or dnsRecord.wType == DNS_TYPE_AAAA:
133             for rec in primary_recs:
134                 if rec.wType == dnsRecord.wType and rec.data == dnsRecord.data:
135                     return True
136         return False
137
138     for a_name in a_names_to_remove_from:
139         try:
140             logger.debug("checking for DNS records to remove on %s" % a_name)
141             a_recs = samdb.dns_lookup(a_name)
142         except RuntimeError as (enum, estr):
143             if enum == 0x000025F2: #WERR_DNS_ERROR_NAME_DOES_NOT_EXIST
144                 return
145             raise DemoteException("lookup of %s failed: %s" % (a_name, estr))
146
147         orig_num_recs = len(a_recs)
148         a_recs = [ r for r in a_recs if not a_rec_to_remove(r) ]
149
150         if len(a_recs) != orig_num_recs:
151             logger.info("updating %s keeping %d values, removing %s values" % \
152                 (a_name, len(a_recs), orig_num_recs - len(a_recs)))
153             samdb.dns_replace(a_name, a_recs)
154
155     # Find all the CNAME, NS, PTR and SRV records that point at the
156     # name we are removing
157
158     def to_remove(value):
159         dnsRecord = ndr_unpack(dnsp.DnssrvRpcRecord, value)
160         if dnsRecord.wType == DNS_TYPE_NS \
161            or dnsRecord.wType == DNS_TYPE_CNAME \
162            or dnsRecord.wType == DNS_TYPE_PTR:
163             if dnsRecord.data.upper() == dnsHostNameUpper:
164                 return True
165         elif dnsRecord.wType == DNS_TYPE_SRV:
166             if dnsRecord.data.nameTarget.upper() == dnsHostNameUpper:
167                 return True
168         return False
169
170     for zone in zones:
171         logger.debug("checking %s" % zone.dn)
172         records = samdb.search(base=zone.dn, scope=ldb.SCOPE_SUBTREE,
173                                expression="(&(objectClass=dnsNode)"
174                                "(!(dNSTombstoned=TRUE)))",
175                                attrs=["dnsRecord"])
176         for record in records:
177             try:
178                 values = record["dnsRecord"]
179             except KeyError:
180                 next
181             orig_num_values = len(values)
182
183             # Remove references to dnsHostName in A, AAAA, NS, CNAME and SRV
184             values = [ ndr_unpack(dnsp.DnssrvRpcRecord, v)
185                        for v in values if not to_remove(v) ]
186
187             if len(values) != orig_num_values:
188                 logger.info("updating %s keeping %d values, removing %s values" \
189                             % (record.dn, len(values),
190                                orig_num_values - len(values)))
191
192                 # This requires the values to be unpacked, so this
193                 # has been done in the list comprehension above
194                 samdb.dns_replace_by_dn(record.dn, values)
195
196 def offline_remove_server(samdb, logger,
197                           server_dn,
198                           remove_computer_obj=False,
199                           remove_server_obj=False,
200                           remove_sysvol_obj=False,
201                           remove_dns_names=False,
202                           remove_dns_account=False):
203     res = samdb.search("",
204                        scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
205     assert len(res) == 1
206     my_serviceName = res[0]["dsServiceName"][0]
207
208     # Confirm this is really a server object
209     msgs = samdb.search(base=server_dn,
210                         attrs=["serverReference", "cn",
211                                "dnsHostName"],
212                         scope=ldb.SCOPE_BASE,
213                         expression="(objectClass=server)")
214     msg = msgs[0]
215     dc_name = str(msgs[0]["cn"][0])
216
217     try:
218         computer_dn = ldb.Dn(samdb, msgs[0]["serverReference"][0])
219     except KeyError:
220         computer_dn = None
221
222     try:
223         dnsHostName = msgs[0]["dnsHostName"][0]
224     except KeyError:
225         dnsHostName = None
226
227     if remove_server_obj:
228         # Remove the server DN
229         samdb.delete(server_dn)
230
231     if computer_dn is not None:
232         computer_msgs = samdb.search(base=computer_dn,
233                                      expression="objectclass=computer",
234                                      attrs=["msDS-KrbTgtLink",
235                                             "rIDSetReferences",
236                                             "cn"],
237                                      scope=ldb.SCOPE_BASE)
238         if "rIDSetReferences" in computer_msgs[0]:
239             rid_set_dn = str(computer_msgs[0]["rIDSetReferences"][0])
240             logger.info("Removing RID Set: %s" % rid_set_dn)
241             samdb.delete(rid_set_dn)
242         if "msDS-KrbTgtLink" in computer_msgs[0]:
243             krbtgt_link_dn = str(computer_msgs[0]["msDS-KrbTgtLink"][0])
244             logger.info("Removing RODC KDC account: %s" % krbtgt_link_dn)
245             samdb.delete(krbtgt_link_dn)
246
247         if remove_computer_obj:
248             # Delete the computer tree
249             logger.info("Removing computer account: %s (and any child objects)" % computer_dn)
250             samdb.delete(computer_dn, ["tree_delete:0"])
251
252         if "dnsHostName" in msgs[0]:
253             dnsHostName = msgs[0]["dnsHostName"][0]
254
255     if remove_dns_account:
256         res = samdb.search(expression="(&(objectclass=user)(cn=dns-%s)(servicePrincipalName=DNS/%s))" %
257                            (ldb.binary_encode(dc_name), dnsHostName),
258                            attrs=[], scope=ldb.SCOPE_SUBTREE,
259                            base=samdb.get_default_basedn())
260         if len(res) == 1:
261             logger.info("Removing Samba-specific DNS service account: %s" % res[0].dn)
262             samdb.delete(res[0].dn)
263
264     if dnsHostName is not None and remove_dns_names:
265         remove_dns_references(samdb, logger, dnsHostName)
266
267     if remove_sysvol_obj:
268         remove_sysvol_references(samdb, logger, dc_name)
269
270 def offline_remove_ntds_dc(samdb,
271                            logger,
272                            ntds_dn,
273                            remove_computer_obj=False,
274                            remove_server_obj=False,
275                            remove_connection_obj=False,
276                            seize_stale_fsmo=False,
277                            remove_sysvol_obj=False,
278                            remove_dns_names=False,
279                            remove_dns_account=False):
280     res = samdb.search("",
281                        scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
282     assert len(res) == 1
283     my_serviceName = ldb.Dn(samdb, res[0]["dsServiceName"][0])
284     server_dn = ntds_dn.parent()
285
286     if my_serviceName == ntds_dn:
287         raise DemoteException("Refusing to demote our own DSA: %s " % my_serviceName)
288
289     try:
290         msgs = samdb.search(base=ntds_dn, expression="objectClass=ntdsDSA",
291                         attrs=["objectGUID"], scope=ldb.SCOPE_BASE)
292     except LdbError as (enum, estr):
293         if enum == ldb.ERR_NO_SUCH_OBJECT:
294               raise DemoteException("Given DN %s doesn't exist" % ntds_dn)
295         else:
296             raise
297     if (len(msgs) == 0):
298         raise DemoteException("%s is not an ntdsda in %s"
299                               % (ntds_dn, samdb.domain_dns_name()))
300
301     msg = msgs[0]
302     if (msg.dn.get_rdn_name() != "CN" or
303         msg.dn.get_rdn_value() != "NTDS Settings"):
304         raise DemoteException("Given DN (%s) wasn't the NTDS Settings DN" %
305                               ntds_dn)
306
307     ntds_guid = ndr_unpack(misc.GUID, msg["objectGUID"][0])
308
309     if remove_connection_obj:
310         # Find any nTDSConnection objects with that DC as the fromServer.
311         # We use the GUID to avoid issues with any () chars in a server
312         # name.
313         stale_connections = samdb.search(base=samdb.get_config_basedn(),
314                                          expression="(&(objectclass=nTDSConnection)"
315                                          "(fromServer=<GUID=%s>))" % ntds_guid)
316         for conn in stale_connections:
317             logger.info("Removing nTDSConnection: %s" % conn.dn)
318             samdb.delete(conn.dn)
319
320     if seize_stale_fsmo:
321         stale_fsmo_roles = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
322                                         expression="(fsmoRoleOwner=<GUID=%s>))"
323                                         % ntds_guid,
324                                         controls=["search_options:0:2"])
325         # Find any FSMO roles they have, give them to this server
326
327         for role in stale_fsmo_roles:
328             val = str(my_serviceName)
329             m = ldb.Message()
330             m.dn = role.dn
331             m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_REPLACE,
332                                             'fsmoRoleOwner')
333             logger.warning("Seizing FSMO role on: %s (now owned by %s)"
334                            % (role.dn, my_serviceName))
335             samdb.modify(m)
336
337     # Remove the NTDS setting tree
338     try:
339         logger.info("Removing nTDSDSA: %s (and any children)" % ntds_dn)
340         samdb.delete(ntds_dn, ["tree_delete:0"])
341     except LdbError as (enum, estr):
342         raise DemoteException("Failed to remove the DCs NTDS DSA object: %s"
343                               % estr)
344
345     offline_remove_server(samdb, logger, server_dn,
346                           remove_computer_obj=remove_computer_obj,
347                           remove_server_obj=remove_server_obj,
348                           remove_sysvol_obj=remove_sysvol_obj,
349                           remove_dns_names=remove_dns_names,
350                           remove_dns_account=remove_dns_account)
351
352
353 def remove_dc(samdb, logger, dc_name):
354
355     # TODO: Check if this is the last server (covered mostly by
356     # refusing to remove our own name)
357
358     samdb.transaction_start()
359
360     msgs = samdb.search(base=samdb.get_config_basedn(),
361                         attrs=["serverReference"],
362                         expression="(&(objectClass=server)(cn=%s))"
363                     % ldb.binary_encode(dc_name))
364     if (len(msgs) == 0):
365         raise DemoteException("%s is not an AD DC in %s"
366                               % (dc_name, samdb.domain_dns_name()))
367     server_dn = msgs[0].dn
368
369     ntds_dn = ldb.Dn(samdb, "CN=NTDS Settings")
370     ntds_dn.add_base(msgs[0].dn)
371
372     # Confirm this is really an ntdsDSA object
373     try:
374         msgs = samdb.search(base=ntds_dn, attrs=[], scope=ldb.SCOPE_BASE,
375                             expression="(objectClass=ntdsdsa)")
376     except LdbError as (enum, estr):
377         if enum == ldb.ERR_NO_SUCH_OBJECT:
378             offline_remove_server(samdb, logger,
379                                   msgs[0].dn,
380                                   remove_computer_obj=True,
381                                   remove_server_obj=True,
382                                   remove_sysvol_obj=True,
383                                   remove_dns_names=True,
384                                   remove_dns_account=True)
385
386             samdb.transaction_commit()
387             return
388         else:
389             pass
390
391     offline_remove_ntds_dc(samdb, logger,
392                            msgs[0].dn,
393                            remove_computer_obj=True,
394                            remove_server_obj=True,
395                            remove_connection_obj=True,
396                            seize_stale_fsmo=True,
397                            remove_sysvol_obj=True,
398                            remove_dns_names=True,
399                            remove_dns_account=True)
400
401     samdb.transaction_commit()
402
403
404
405 def offline_remove_dc_RemoveDsServer(samdb, ntds_dn):
406
407     samdb.start_transaction()
408
409     offline_remove_ntds_dc(samdb, ntds_dn, None)
410
411     samdb.commit_transaction()