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, 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)
54 except ldb.LdbError as (enum, estr):
55 if enum == ldb.ERR_NO_SUCH_OBJECT:
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.
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"\
72 dn.set_component(0, "CN", dc_name)
75 except ldb.LdbError as (enum, estr):
76 if enum == ldb.ERR_NO_SUCH_OBJECT:
82 def remove_dns_references(samdb, dnsHostName):
84 # Check we are using in-database DNS
85 zones = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
86 expression="(&(objectClass=dnsZone)(!(dc=RootDNSServers)))",
88 controls=["search_options:0:2"])
92 dnsHostNameUpper = dnsHostName.upper()
95 primary_recs = samdb.dns_lookup(dnsHostName)
96 except RuntimeError as (enum, estr):
97 if enum == 0x000025F2: #WERR_DNS_ERROR_NAME_DOES_NOT_EXIST
99 raise DemoteException("lookup of %s failed: %s" % (dnsHostName, estr))
100 samdb.dns_replace(dnsHostName, [])
102 res = samdb.search("",
103 scope=ldb.SCOPE_BASE, attrs=["namingContexts"])
105 ncs = res[0]["namingContexts"]
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
115 def dns_name_from_dn(dn):
116 # The canonical string of DC=example,DC=com is
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]
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)
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:
135 for a_name in a_names_to_remove_from:
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
142 raise DemoteException("lookup of %s failed: %s" % (a_name, estr))
144 orig_num_recs = len(a_recs)
145 a_recs = [ r for r in a_recs if not a_rec_to_remove(r) ]
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)
152 # Find all the CNAME, NS, PTR and SRV records that point at the
153 # name we are removing
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:
162 elif dnsRecord.wType == DNS_TYPE_SRV:
163 if dnsRecord.data.nameTarget.upper() == dnsHostNameUpper:
168 print "checking %s" % zone.dn
169 records = samdb.search(base=zone.dn, scope=ldb.SCOPE_SUBTREE,
170 expression="(&(objectClass=dnsNode)"
171 "(!(dNSTombstoned=TRUE)))",
173 for record in records:
175 values = record["dnsRecord"]
178 orig_num_values = len(values)
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) ]
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))
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)
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"])
201 my_serviceName = res[0]["dsServiceName"][0]
203 # Confirm this is really a server object
204 msgs = samdb.search(base=server_dn,
205 attrs=["serverReference", "cn",
207 scope=ldb.SCOPE_BASE,
208 expression="(objectClass=server)")
210 dc_name = str(msgs[0]["cn"][0])
213 computer_dn = ldb.Dn(samdb, msgs[0]["serverReference"][0])
218 dnsHostName = msgs[0]["dnsHostName"][0]
222 if remove_server_obj:
223 # Remove the server DN
224 samdb.delete(server_dn)
226 if computer_dn is not None:
227 computer_msgs = samdb.search(base=computer_dn,
228 expression="objectclass=computer",
229 attrs=["msDS-KrbTgtLink",
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])
238 if remove_computer_obj:
239 # Delete the computer tree
240 samdb.delete(computer_dn, ["tree_delete:0"])
242 if "dnsHostName" in msgs[0]:
243 dnsHostName = msgs[0]["dnsHostName"][0]
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())
251 samdb.delete(res[0].dn)
253 if dnsHostName is not None and remove_dns_names:
254 remove_dns_references(samdb, dnsHostName)
256 if remove_sysvol_obj:
257 remove_sysvol_references(samdb, dc_name)
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"])
270 my_serviceName = ldb.Dn(samdb, res[0]["dsServiceName"][0])
271 server_dn = ntds_dn.parent()
273 if my_serviceName == ntds_dn:
274 raise DemoteException("Refusing to demote our own DSA: %s " % my_serviceName)
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)
285 raise DemoteException("%s is not an ntdsda in %s"
286 % (ntds_dn, samdb.domain_dns_name()))
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" %
294 ntds_guid = ndr_unpack(misc.GUID, msg["objectGUID"][0])
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
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)
307 stale_fsmo_roles = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
308 expression="(fsmoRoleOwner=<GUID=%s>))"
310 controls=["search_options:0:2"])
311 # Find any FSMO roles they have, give them to this server
313 for role in stale_fsmo_roles:
314 val = str(my_serviceName)
317 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_REPLACE,
321 # Remove the NTDS setting tree
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"
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)
336 def remove_dc(samdb, dc_name):
338 # TODO: Check if this is the last server (covered mostly by
339 # refusing to remove our own name)
341 samdb.transaction_start()
343 msgs = samdb.search(base=samdb.get_config_basedn(),
344 attrs=["serverReference"],
345 expression="(&(objectClass=server)(cn=%s))"
346 % ldb.binary_encode(dc_name))
348 raise DemoteException("%s is not an AD DC in %s"
349 % (dc_name, samdb.domain_dns_name()))
350 server_dn = msgs[0].dn
352 ntds_dn = ldb.Dn(samdb, "CN=NTDS Settings")
353 ntds_dn.add_base(msgs[0].dn)
355 # Confirm this is really an ntdsDSA object
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)
368 samdb.transaction_commit()
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)
382 samdb.transaction_commit()
386 def offline_remove_dc_RemoveDsServer(samdb, ntds_dn):
388 samdb.start_transaction()
390 offline_remove_ntds_dc(samdb, ntds_dn)
392 samdb.commit_transaction()