1 # Unix SMB/CIFS implementation.
2 # Copyright Matthieu Patou <mat@matws.net> 2011
3 # Copyright Andrew Bartlett <abartlet@samba.org> 2008-2015
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.
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.
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/>.
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
26 class DemoteException(Exception):
27 """Base element for demote errors"""
29 def __init__(self, value):
33 return "DemoteException: " + self.value
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):
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"\
51 dn.set_component(0, "CN", dc_name)
53 logger.info("Removing Sysvol reference: %s" % dn)
55 except ldb.LdbError as (enum, estr):
56 if enum == ldb.ERR_NO_SUCH_OBJECT:
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.
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"\
73 dn.set_component(0, "CN", dc_name)
76 logger.info("Removing Sysvol reference: %s" % dn)
78 except ldb.LdbError as (enum, estr):
79 if enum == ldb.ERR_NO_SUCH_OBJECT:
85 def remove_dns_references(samdb, logger, dnsHostName):
87 # Check we are using in-database DNS
88 zones = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
89 expression="(&(objectClass=dnsZone)(!(dc=RootDNSServers)))",
91 controls=["search_options:0:2"])
95 dnsHostNameUpper = dnsHostName.upper()
98 primary_recs = samdb.dns_lookup(dnsHostName)
99 except RuntimeError as (enum, estr):
100 if enum == 0x000025F2: #WERR_DNS_ERROR_NAME_DOES_NOT_EXIST
102 raise DemoteException("lookup of %s failed: %s" % (dnsHostName, estr))
103 samdb.dns_replace(dnsHostName, [])
105 res = samdb.search("",
106 scope=ldb.SCOPE_BASE, attrs=["namingContexts"])
108 ncs = res[0]["namingContexts"]
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
118 def dns_name_from_dn(dn):
119 # The canonical string of DC=example,DC=com is
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]
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)
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:
138 for a_name in a_names_to_remove_from:
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
145 raise DemoteException("lookup of %s failed: %s" % (a_name, estr))
147 orig_num_recs = len(a_recs)
148 a_recs = [ r for r in a_recs if not a_rec_to_remove(r) ]
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)
155 # Find all the CNAME, NS, PTR and SRV records that point at the
156 # name we are removing
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:
165 elif dnsRecord.wType == DNS_TYPE_SRV:
166 if dnsRecord.data.nameTarget.upper() == dnsHostNameUpper:
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)))",
176 for record in records:
178 values = record["dnsRecord"]
181 orig_num_values = len(values)
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) ]
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)))
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)
196 def offline_remove_server(samdb, logger,
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"])
206 my_serviceName = res[0]["dsServiceName"][0]
208 # Confirm this is really a server object
209 msgs = samdb.search(base=server_dn,
210 attrs=["serverReference", "cn",
212 scope=ldb.SCOPE_BASE,
213 expression="(objectClass=server)")
215 dc_name = str(msgs[0]["cn"][0])
218 computer_dn = ldb.Dn(samdb, msgs[0]["serverReference"][0])
223 dnsHostName = msgs[0]["dnsHostName"][0]
227 if remove_server_obj:
228 # Remove the server DN
229 samdb.delete(server_dn)
231 if computer_dn is not None:
232 computer_msgs = samdb.search(base=computer_dn,
233 expression="objectclass=computer",
234 attrs=["msDS-KrbTgtLink",
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)
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"])
252 if "dnsHostName" in msgs[0]:
253 dnsHostName = msgs[0]["dnsHostName"][0]
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())
261 logger.info("Removing Samba-specific DNS service account: %s" % res[0].dn)
262 samdb.delete(res[0].dn)
264 if dnsHostName is not None and remove_dns_names:
265 remove_dns_references(samdb, logger, dnsHostName)
267 if remove_sysvol_obj:
268 remove_sysvol_references(samdb, logger, dc_name)
270 def offline_remove_ntds_dc(samdb,
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"])
283 my_serviceName = ldb.Dn(samdb, res[0]["dsServiceName"][0])
284 server_dn = ntds_dn.parent()
286 if my_serviceName == ntds_dn:
287 raise DemoteException("Refusing to demote our own DSA: %s " % my_serviceName)
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)
298 raise DemoteException("%s is not an ntdsda in %s"
299 % (ntds_dn, samdb.domain_dns_name()))
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" %
307 ntds_guid = ndr_unpack(misc.GUID, msg["objectGUID"][0])
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
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)
321 stale_fsmo_roles = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
322 expression="(fsmoRoleOwner=<GUID=%s>))"
324 controls=["search_options:0:2"])
325 # Find any FSMO roles they have, give them to this server
327 for role in stale_fsmo_roles:
328 val = str(my_serviceName)
331 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_REPLACE,
333 logger.warning("Seizing FSMO role on: %s (now owned by %s)"
334 % (role.dn, my_serviceName))
337 # Remove the NTDS setting tree
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"
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)
353 def remove_dc(samdb, logger, dc_name):
355 # TODO: Check if this is the last server (covered mostly by
356 # refusing to remove our own name)
358 samdb.transaction_start()
360 msgs = samdb.search(base=samdb.get_config_basedn(),
361 attrs=["serverReference"],
362 expression="(&(objectClass=server)(cn=%s))"
363 % ldb.binary_encode(dc_name))
365 raise DemoteException("%s is not an AD DC in %s"
366 % (dc_name, samdb.domain_dns_name()))
367 server_dn = msgs[0].dn
369 ntds_dn = ldb.Dn(samdb, "CN=NTDS Settings")
370 ntds_dn.add_base(msgs[0].dn)
372 # Confirm this is really an ntdsDSA object
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,
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)
386 samdb.transaction_commit()
391 offline_remove_ntds_dc(samdb, logger,
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)
401 samdb.transaction_commit()
405 def offline_remove_dc_RemoveDsServer(samdb, ntds_dn):
407 samdb.start_transaction()
409 offline_remove_ntds_dc(samdb, ntds_dn, None)
411 samdb.commit_transaction()