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/>.
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
28 class DemoteException(Exception):
29 """Base element for demote errors"""
31 def __init__(self, value):
35 return "DemoteException: " + self.value
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):
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"\
53 dn.set_component(0, "CN", dc_name)
55 logger.info("Removing Sysvol reference: %s" % dn)
57 except ldb.LdbError as e:
59 if enum == ldb.ERR_NO_SUCH_OBJECT:
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.
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)
79 logger.info("Removing Sysvol reference: %s" % dn)
81 except ldb.LdbError as e1:
82 (enum, estr) = e1.args
83 if enum == ldb.ERR_NO_SUCH_OBJECT:
89 def remove_dns_references(samdb, logger, dnsHostName, ignore_no_name=False):
91 # Check we are using in-database DNS
92 zones = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
93 expression="(&(objectClass=dnsZone)(!(dc=RootDNSServers)))",
95 controls=["search_options:0:2"])
99 dnsHostNameUpper = dnsHostName.upper()
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):
108 remove_hanging_dns_references(samdb, logger,
112 raise DemoteException("lookup of %s failed: %s" % (dnsHostName, estr))
113 samdb.dns_replace(dnsHostName, [])
115 res = samdb.search("",
116 scope=ldb.SCOPE_BASE, attrs=["namingContexts"])
118 ncs = res[0]["namingContexts"]
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
128 def dns_name_from_dn(dn):
129 # The canonical string of DC=example,DC=com is
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]
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)
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:
148 for a_name in a_names_to_remove_from:
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:
156 raise DemoteException("lookup of %s failed: %s" % (a_name, estr))
158 orig_num_recs = len(a_recs)
159 a_recs = [r for r in a_recs if not a_rec_to_remove(r) ]
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)
166 remove_hanging_dns_references(samdb, logger, dnsHostNameUpper, zones)
169 def remove_hanging_dns_references(samdb, logger, dnsHostNameUpper, zones):
171 # Find all the CNAME, NS, PTR and SRV records that point at the
172 # name we are removing
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:
181 elif dnsRecord.wType == DNS_TYPE_SRV:
182 if dnsRecord.data.nameTarget.upper() == dnsHostNameUpper:
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)))",
192 for record in records:
194 orig_values = record["dnsRecord"]
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) ]
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)))
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)
212 def offline_remove_server(samdb, logger,
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"])
222 my_serviceName = res[0]["dsServiceName"][0]
224 # Confirm this is really a server object
225 msgs = samdb.search(base=server_dn,
226 attrs=["serverReference", "cn",
228 scope=ldb.SCOPE_BASE,
229 expression="(objectClass=server)")
231 dc_name = str(msgs[0]["cn"][0])
234 computer_dn = ldb.Dn(samdb, msgs[0]["serverReference"][0].decode('utf8'))
239 dnsHostName = msgs[0]["dnsHostName"][0]
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"])
248 if computer_dn is not None:
249 computer_msgs = samdb.search(base=computer_dn,
250 expression="objectclass=computer",
251 attrs=["msDS-KrbTgtLink",
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)
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"])
269 if "dnsHostName" in msgs[0]:
270 dnsHostName = msgs[0]["dnsHostName"][0]
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())
278 logger.info("Removing Samba-specific DNS service account: %s" % res[0].dn)
279 samdb.delete(res[0].dn)
281 if dnsHostName is not None and remove_dns_names:
282 remove_dns_references(samdb, logger, dnsHostName)
284 if remove_sysvol_obj:
285 remove_sysvol_references(samdb, logger, dc_name)
287 def offline_remove_ntds_dc(samdb,
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"])
300 my_serviceName = ldb.Dn(samdb, res[0]["dsServiceName"][0].decode('utf8'))
301 server_dn = ntds_dn.parent()
303 if my_serviceName == ntds_dn:
304 raise DemoteException("Refusing to demote our own DSA: %s " % my_serviceName)
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)
316 raise DemoteException("%s is not an ntdsda in %s"
317 % (ntds_dn, samdb.domain_dns_name()))
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" %
325 ntds_guid = ndr_unpack(misc.GUID, msg["objectGUID"][0])
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
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)
339 stale_fsmo_roles = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
340 expression="(fsmoRoleOwner=<GUID=%s>))"
342 controls=["search_options:0:2"])
343 # Find any FSMO roles they have, give them to this server
345 for role in stale_fsmo_roles:
346 val = str(my_serviceName)
349 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_REPLACE,
351 logger.warning("Seizing FSMO role on: %s (now owned by %s)"
352 % (role.dn, my_serviceName))
355 # Remove the NTDS setting tree
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"
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)
372 def remove_dc(samdb, logger, dc_name):
374 # TODO: Check if this is the last server (covered mostly by
375 # refusing to remove our own name)
377 samdb.transaction_start()
381 # Allow the name to be a the nTDS-DSA GUID
383 ntds_guid = uuid.UUID(hex=dc_name)
384 ntds_dn = "<GUID=%s>" % ntds_guid
387 server_msgs = samdb.search(base=samdb.get_config_basedn(),
389 expression="(&(objectClass=server)"
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 "
396 % (dc_name, samdb.domain_dns_name()), estr)
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
404 ntds_dn = ldb.Dn(samdb, "CN=NTDS Settings")
405 ntds_dn.add_base(server_dn)
408 # Confirm this is really an ntdsDSA object
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:
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)
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()))
430 offline_remove_server(samdb, logger,
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)
438 offline_remove_ntds_dc(samdb, logger,
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)
448 samdb.transaction_commit()
452 def offline_remove_dc_RemoveDsServer(samdb, ntds_dn):
454 samdb.start_transaction()
456 offline_remove_ntds_dc(samdb, ntds_dn, None)
458 samdb.commit_transaction()