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