samba-tool domain demote: Remove all references to the demoted host, even in DNS
[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, 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             samdb.delete(dn)
54         except ldb.LdbError as (enum, estr):
55             if enum == ldb.ERR_NO_SUCH_OBJECT:
56                 pass
57             else:
58                 raise
59
60     # DNs under the Domain DN:
61     for s in ("CN=Domain System Volumes (SYSVOL share),CN=File Replication Service,CN=System",
62               "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System"):
63         # This is verbose, but it is the safe, escape-proof way
64         # to add a base and add an arbitrary RDN.
65         dn = ldb.Dn(samdb, s)
66         if dn.add_base(samdb.get_default_basedn()) == False:
67             raise DemoteException("Failed constructing DN %s by adding base" % \
68                                   (dn, samdb.get_default_basedn()))
69         if dn.add_child("CN=X") == False:
70             raise DemoteException("Failed constructing DN %s by adding child %s"\
71                                   % (dn, rdn))
72         dn.set_component(0, "CN", dc_name)
73         try:
74             samdb.delete(dn)
75         except ldb.LdbError as (enum, estr):
76             if enum == ldb.ERR_NO_SUCH_OBJECT:
77                 pass
78             else:
79                 raise
80
81
82 def remove_dns_references(samdb, dnsHostName):
83
84     # Check we are using in-database DNS
85     zones = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
86                          expression="(&(objectClass=dnsZone)(!(dc=RootDNSServers)))",
87                          attrs=[],
88                          controls=["search_options:0:2"])
89     if len(zones) == 0:
90         return
91
92     dnsHostNameUpper = dnsHostName.upper()
93
94     try:
95         primary_recs = samdb.dns_lookup(dnsHostName)
96     except RuntimeError as (enum, estr):
97         if enum == 0x000025F2: #WERR_DNS_ERROR_NAME_DOES_NOT_EXIST
98               return
99         raise DemoteException("lookup of %s failed: %s" % (dnsHostName, estr))
100     samdb.dns_replace(dnsHostName, [])
101
102     res = samdb.search("",
103                        scope=ldb.SCOPE_BASE, attrs=["namingContexts"])
104     assert len(res) == 1
105     ncs = res[0]["namingContexts"]
106
107     # Work out the set of names we will likely have an A record on by
108     # default.  This is by default all the partitions of type
109     # domainDNS.  By finding the canocial name of all the partitions,
110     # we find the likely candidates.  We only remove the record if it
111     # maches the IP that was used by the dnsHostName.  This avoids us
112     # needing to look a the dns_update_list file from in the demote
113     # script.
114
115     def dns_name_from_dn(dn):
116         # The canonical string of DC=example,DC=com is
117         # example.com/
118         #
119         # The canonical string of CN=Configuration,DC=example,DC=com
120         # is example.com/Configuration
121         return ldb.Dn(samdb, dn).canonical_str().split('/', 1)[0]
122
123     # By using a set here, duplicates via (eg) example.com/Configuration
124     # do not matter, they become just example.com
125     a_names_to_remove_from \
126         = set(dns_name_from_dn(dn) for dn in ncs)
127
128     def a_rec_to_remove(dnsRecord):
129         if dnsRecord.wType == DNS_TYPE_A or dnsRecord.wType == DNS_TYPE_AAAA:
130             for rec in primary_recs:
131                 if rec.wType == dnsRecord.wType and rec.data == dnsRecord.data:
132                     return True
133         return False
134
135     for a_name in a_names_to_remove_from:
136         try:
137             logger.debug("checking for DNS records to remove on %s" % a_name)
138             a_recs = samdb.dns_lookup(a_name)
139         except RuntimeError as (enum, estr):
140             if enum == 0x000025F2: #WERR_DNS_ERROR_NAME_DOES_NOT_EXIST
141                 return
142             raise DemoteException("lookup of %s failed: %s" % (a_name, estr))
143
144         orig_num_recs = len(a_recs)
145         a_recs = [ r for r in a_recs if not a_rec_to_remove(r) ]
146
147         if len(a_recs) != orig_num_recs:
148             print "updating %s keeping %d values, removing %s values" % \
149                 (a_name, len(a_recs), orig_num_recs - len(a_recs))
150             samdb.dns_replace(a_name, a_recs)
151
152     # Find all the CNAME, NS, PTR and SRV records that point at the
153     # name we are removing
154
155     def to_remove(value):
156         dnsRecord = ndr_unpack(dnsp.DnssrvRpcRecord, value)
157         if dnsRecord.wType == DNS_TYPE_NS \
158            or dnsRecord.wType == DNS_TYPE_CNAME \
159            or dnsRecord.wType == DNS_TYPE_PTR:
160             if dnsRecord.data.upper() == dnsHostNameUpper:
161                 return True
162         elif dnsRecord.wType == DNS_TYPE_SRV:
163             if dnsRecord.data.nameTarget.upper() == dnsHostNameUpper:
164                 return True
165         return False
166
167     for zone in zones:
168         print "checking %s" % zone.dn
169         records = samdb.search(base=zone.dn, scope=ldb.SCOPE_SUBTREE,
170                                expression="(&(objectClass=dnsNode)"
171                                "(!(dNSTombstoned=TRUE)))",
172                                attrs=["dnsRecord"])
173         for record in records:
174             try:
175                 values = record["dnsRecord"]
176             except KeyError:
177                 next
178             orig_num_values = len(values)
179
180             # Remove references to dnsHostName in A, AAAA, NS, CNAME and SRV
181             values = [ ndr_unpack(dnsp.DnssrvRpcRecord, v)
182                        for v in values if not to_remove(v) ]
183
184             if len(values) != orig_num_values:
185                 print "updating %s keeping %d values, removing %s values" \
186                     % (record.dn, len(values), orig_num_values - len(values))
187
188                 # This requires the values to be unpacked, so this
189                 # has been done in the list comprehension above
190                 samdb.dns_replace_by_dn(record.dn, values)
191
192 def offline_remove_server(samdb, server_dn,
193                           remove_computer_obj=False,
194                           remove_server_obj=False,
195                           remove_sysvol_obj=False,
196                           remove_dns_names=False):
197     res = samdb.search("",
198                        scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
199     assert len(res) == 1
200     my_serviceName = res[0]["dsServiceName"][0]
201
202     # Confirm this is really a server object
203     msgs = samdb.search(base=server_dn,
204                         attrs=["serverReference", "cn",
205                                "dnsHostName"],
206                         scope=ldb.SCOPE_BASE,
207                         expression="(objectClass=server)")
208     msg = msgs[0]
209     dc_name = str(msgs[0]["cn"][0])
210
211     try:
212         computer_dn = ldb.Dn(samdb, msgs[0]["serverReference"][0])
213     except KeyError:
214         computer_dn = None
215
216     try:
217         dnsHostName = msgs[0]["dnsHostName"][0]
218     except KeyError:
219         dnsHostName = None
220
221     if remove_server_obj:
222         # Remove the server DN
223         samdb.delete(server_dn)
224
225     if computer_dn is not None:
226         computer_msgs = samdb.search(base=computer_dn,
227                                      expression="objectclass=computer",
228                                      attrs=["msDS-KrbTgtLink",
229                                             "rIDSetReferences"],
230                                      scope=ldb.SCOPE_BASE)
231         if "rIDSetReferences" in computer_msgs[0]:
232             samdb.delete(computer_msgs[0]["rIDSetReferences"][0])
233         if "msDS-KrbTgtLink" in computer_msgs[0]:
234             samdb.delete(computer_msgs[0]["msDS-KrbTgtLink"][0])
235
236         if remove_computer_obj:
237             # Delete the computer tree
238             samdb.delete(computer_dn, ["tree_delete:0"])
239
240         if "dnsHostName" in msgs[0]:
241             dnsHostName = msgs[0]["dnsHostName"][0]
242
243     if dnsHostName is not None and remove_dns_names:
244         remove_dns_references(samdb, dnsHostName)
245
246     if remove_sysvol_obj:
247         remove_sysvol_references(samdb, dc_name)
248
249 def offline_remove_ntds_dc(samdb, ntds_dn,
250                            remove_computer_obj=False,
251                            remove_server_obj=False,
252                            remove_connection_obj=False,
253                            seize_stale_fsmo=False,
254                            remove_sysvol_obj=False,
255                            remove_dns_names=False):
256     res = samdb.search("",
257                        scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
258     assert len(res) == 1
259     my_serviceName = ldb.Dn(samdb, res[0]["dsServiceName"][0])
260     server_dn = ntds_dn.parent()
261
262     if my_serviceName == ntds_dn:
263         raise DemoteException("Refusing to demote our own DSA: %s " % my_serviceName)
264
265     try:
266         msgs = samdb.search(base=ntds_dn, expression="objectClass=ntdsDSA",
267                         attrs=["objectGUID"], scope=ldb.SCOPE_BASE)
268     except LdbError as (enum, estr):
269         if enum == ldb.ERR_NO_SUCH_OBJECT:
270               raise DemoteException("Given DN %s doesn't exist" % ntds_dn)
271         else:
272             raise
273     if (len(msgs) == 0):
274         raise DemoteException("%s is not an ntdsda in %s"
275                               % (ntds_dn, samdb.domain_dns_name()))
276
277     msg = msgs[0]
278     if (msg.dn.get_rdn_name() != "CN" or
279         msg.dn.get_rdn_value() != "NTDS Settings"):
280         raise DemoteException("Given DN (%s) wasn't the NTDS Settings DN" %
281                               ntds_dn)
282
283     ntds_guid = ndr_unpack(misc.GUID, msg["objectGUID"][0])
284
285     if remove_connection_obj:
286         # Find any nTDSConnection objects with that DC as the fromServer.
287         # We use the GUID to avoid issues with any () chars in a server
288         # name.
289         stale_connections = samdb.search(base=samdb.get_config_basedn(),
290                                          expression="(&(objectclass=nTDSConnection)"
291                                          "(fromServer=<GUID=%s>))" % ntds_guid)
292         for conn in stale_connections:
293             samdb.delete(conn.dn)
294
295     if seize_stale_fsmo:
296         stale_fsmo_roles = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
297                                         expression="(fsmoRoleOwner=<GUID=%s>))"
298                                         % ntds_guid,
299                                         controls=["search_options:0:2"])
300         # Find any FSMO roles they have, give them to this server
301
302         for role in stale_fsmo_roles:
303             val = str(my_serviceName)
304             m = ldb.Message()
305             m.dn = role.dn
306             m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_REPLACE,
307                                             'fsmoRoleOwner')
308             samdb.modify(m)
309
310     # Remove the NTDS setting tree
311     try:
312         samdb.delete(ntds_dn, ["tree_delete:0"])
313     except LdbError as (enum, estr):
314         raise DemoteException("Failed to remove the DCs NTDS DSA object: %s"
315                               % estr)
316
317     offline_remove_server(samdb, server_dn,
318                           remove_computer_obj=remove_computer_obj,
319                           remove_server_obj=remove_server_obj,
320                           remove_sysvol_obj=remove_sysvol_obj,
321                           remove_dns_names=remove_dns_names)
322
323
324 def remove_dc(samdb, dc_name):
325
326     # TODO: Check if this is the last server (covered mostly by
327     # refusing to remove our own name)
328
329     samdb.transaction_start()
330
331     msgs = samdb.search(base=samdb.get_config_basedn(),
332                         attrs=["serverReference"],
333                         expression="(&(objectClass=server)(cn=%s))"
334                     % ldb.binary_encode(dc_name))
335     if (len(msgs) == 0):
336         raise DemoteException("%s is not an AD DC in %s"
337                               % (dc_name, samdb.domain_dns_name()))
338     server_dn = msgs[0].dn
339
340     ntds_dn = ldb.Dn(samdb, "CN=NTDS Settings")
341     ntds_dn.add_base(msgs[0].dn)
342
343     # Confirm this is really an ntdsDSA object
344     try:
345         msgs = samdb.search(base=ntds_dn, attrs=[], scope=ldb.SCOPE_BASE,
346                             expression="(objectClass=ntdsdsa)")
347     except LdbError as (enum, estr):
348         if enum == ldb.ERR_NO_SUCH_OBJECT:
349             offline_remove_server(samdb, msgs[0].dn,
350                                   remove_computer_obj=True,
351                                   remove_server_obj=True,
352                                   remove_sysvol_obj=True,
353                                   remove_dns_names=True)
354
355             samdb.transaction_commit()
356             return
357         else:
358             pass
359
360     offline_remove_ntds_dc(samdb, msgs[0].dn,
361                            remove_computer_obj=True,
362                            remove_server_obj=True,
363                            remove_connection_obj=True,
364                            seize_stale_fsmo=True,
365                            remove_sysvol_obj=True,
366                            remove_dns_names=True)
367
368     samdb.transaction_commit()
369
370
371
372 def offline_remove_dc_RemoveDsServer(samdb, ntds_dn):
373
374     samdb.start_transaction()
375
376     offline_remove_ntds_dc(samdb, ntds_dn)
377
378     samdb.commit_transaction()