samba-tool domain demote: Remove dns-SERVER object as well
[amitay/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                           remove_dns_account=False):
198     res = samdb.search("",
199                        scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
200     assert len(res) == 1
201     my_serviceName = res[0]["dsServiceName"][0]
202
203     # Confirm this is really a server object
204     msgs = samdb.search(base=server_dn,
205                         attrs=["serverReference", "cn",
206                                "dnsHostName"],
207                         scope=ldb.SCOPE_BASE,
208                         expression="(objectClass=server)")
209     msg = msgs[0]
210     dc_name = str(msgs[0]["cn"][0])
211
212     try:
213         computer_dn = ldb.Dn(samdb, msgs[0]["serverReference"][0])
214     except KeyError:
215         computer_dn = None
216
217     try:
218         dnsHostName = msgs[0]["dnsHostName"][0]
219     except KeyError:
220         dnsHostName = None
221
222     if remove_server_obj:
223         # Remove the server DN
224         samdb.delete(server_dn)
225
226     if computer_dn is not None:
227         computer_msgs = samdb.search(base=computer_dn,
228                                      expression="objectclass=computer",
229                                      attrs=["msDS-KrbTgtLink",
230                                             "rIDSetReferences",
231                                             "cn"],
232                                      scope=ldb.SCOPE_BASE)
233         if "rIDSetReferences" in computer_msgs[0]:
234             samdb.delete(computer_msgs[0]["rIDSetReferences"][0])
235         if "msDS-KrbTgtLink" in computer_msgs[0]:
236             samdb.delete(computer_msgs[0]["msDS-KrbTgtLink"][0])
237
238         if remove_computer_obj:
239             # Delete the computer tree
240             samdb.delete(computer_dn, ["tree_delete:0"])
241
242         if "dnsHostName" in msgs[0]:
243             dnsHostName = msgs[0]["dnsHostName"][0]
244
245     if remove_dns_account:
246         res = samdb.search(expression="(&(objectclass=user)(cn=dns-%s)(servicePrincipalName=DNS/%s))" %
247                            (ldb.binary_encode(dc_name), dnsHostName),
248                            attrs=[], scope=ldb.SCOPE_SUBTREE,
249                            base=samdb.get_default_basedn())
250         if len(res) == 1:
251             samdb.delete(res[0].dn)
252
253     if dnsHostName is not None and remove_dns_names:
254         remove_dns_references(samdb, dnsHostName)
255
256     if remove_sysvol_obj:
257         remove_sysvol_references(samdb, dc_name)
258
259 def offline_remove_ntds_dc(samdb, ntds_dn,
260                            remove_computer_obj=False,
261                            remove_server_obj=False,
262                            remove_connection_obj=False,
263                            seize_stale_fsmo=False,
264                            remove_sysvol_obj=False,
265                            remove_dns_names=False,
266                            remove_dns_account=False):
267     res = samdb.search("",
268                        scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
269     assert len(res) == 1
270     my_serviceName = ldb.Dn(samdb, res[0]["dsServiceName"][0])
271     server_dn = ntds_dn.parent()
272
273     if my_serviceName == ntds_dn:
274         raise DemoteException("Refusing to demote our own DSA: %s " % my_serviceName)
275
276     try:
277         msgs = samdb.search(base=ntds_dn, expression="objectClass=ntdsDSA",
278                         attrs=["objectGUID"], scope=ldb.SCOPE_BASE)
279     except LdbError as (enum, estr):
280         if enum == ldb.ERR_NO_SUCH_OBJECT:
281               raise DemoteException("Given DN %s doesn't exist" % ntds_dn)
282         else:
283             raise
284     if (len(msgs) == 0):
285         raise DemoteException("%s is not an ntdsda in %s"
286                               % (ntds_dn, samdb.domain_dns_name()))
287
288     msg = msgs[0]
289     if (msg.dn.get_rdn_name() != "CN" or
290         msg.dn.get_rdn_value() != "NTDS Settings"):
291         raise DemoteException("Given DN (%s) wasn't the NTDS Settings DN" %
292                               ntds_dn)
293
294     ntds_guid = ndr_unpack(misc.GUID, msg["objectGUID"][0])
295
296     if remove_connection_obj:
297         # Find any nTDSConnection objects with that DC as the fromServer.
298         # We use the GUID to avoid issues with any () chars in a server
299         # name.
300         stale_connections = samdb.search(base=samdb.get_config_basedn(),
301                                          expression="(&(objectclass=nTDSConnection)"
302                                          "(fromServer=<GUID=%s>))" % ntds_guid)
303         for conn in stale_connections:
304             samdb.delete(conn.dn)
305
306     if seize_stale_fsmo:
307         stale_fsmo_roles = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
308                                         expression="(fsmoRoleOwner=<GUID=%s>))"
309                                         % ntds_guid,
310                                         controls=["search_options:0:2"])
311         # Find any FSMO roles they have, give them to this server
312
313         for role in stale_fsmo_roles:
314             val = str(my_serviceName)
315             m = ldb.Message()
316             m.dn = role.dn
317             m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_REPLACE,
318                                             'fsmoRoleOwner')
319             samdb.modify(m)
320
321     # Remove the NTDS setting tree
322     try:
323         samdb.delete(ntds_dn, ["tree_delete:0"])
324     except LdbError as (enum, estr):
325         raise DemoteException("Failed to remove the DCs NTDS DSA object: %s"
326                               % estr)
327
328     offline_remove_server(samdb, server_dn,
329                           remove_computer_obj=remove_computer_obj,
330                           remove_server_obj=remove_server_obj,
331                           remove_sysvol_obj=remove_sysvol_obj,
332                           remove_dns_names=remove_dns_names,
333                           remove_dns_account=remove_dns_account)
334
335
336 def remove_dc(samdb, dc_name):
337
338     # TODO: Check if this is the last server (covered mostly by
339     # refusing to remove our own name)
340
341     samdb.transaction_start()
342
343     msgs = samdb.search(base=samdb.get_config_basedn(),
344                         attrs=["serverReference"],
345                         expression="(&(objectClass=server)(cn=%s))"
346                     % ldb.binary_encode(dc_name))
347     if (len(msgs) == 0):
348         raise DemoteException("%s is not an AD DC in %s"
349                               % (dc_name, samdb.domain_dns_name()))
350     server_dn = msgs[0].dn
351
352     ntds_dn = ldb.Dn(samdb, "CN=NTDS Settings")
353     ntds_dn.add_base(msgs[0].dn)
354
355     # Confirm this is really an ntdsDSA object
356     try:
357         msgs = samdb.search(base=ntds_dn, attrs=[], scope=ldb.SCOPE_BASE,
358                             expression="(objectClass=ntdsdsa)")
359     except LdbError as (enum, estr):
360         if enum == ldb.ERR_NO_SUCH_OBJECT:
361             offline_remove_server(samdb, msgs[0].dn,
362                                   remove_computer_obj=True,
363                                   remove_server_obj=True,
364                                   remove_sysvol_obj=True,
365                                   remove_dns_names=True,
366                                   remove_dns_account=True)
367
368             samdb.transaction_commit()
369             return
370         else:
371             pass
372
373     offline_remove_ntds_dc(samdb, msgs[0].dn,
374                            remove_computer_obj=True,
375                            remove_server_obj=True,
376                            remove_connection_obj=True,
377                            seize_stale_fsmo=True,
378                            remove_sysvol_obj=True,
379                            remove_dns_names=True,
380                            remove_dns_account=True)
381
382     samdb.transaction_commit()
383
384
385
386 def offline_remove_dc_RemoveDsServer(samdb, ntds_dn):
387
388     samdb.start_transaction()
389
390     offline_remove_ntds_dc(samdb, ntds_dn)
391
392     samdb.commit_transaction()