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 res = samdb.search("",
198 scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
200 my_serviceName = res[0]["dsServiceName"][0]
202 # Confirm this is really a server object
203 msgs = samdb.search(base=server_dn,
204 attrs=["serverReference", "cn",
206 scope=ldb.SCOPE_BASE,
207 expression="(objectClass=server)")
209 dc_name = str(msgs[0]["cn"][0])
212 computer_dn = ldb.Dn(samdb, msgs[0]["serverReference"][0])
217 dnsHostName = msgs[0]["dnsHostName"][0]
221 if remove_server_obj:
222 # Remove the server DN
223 samdb.delete(server_dn)
225 if computer_dn is not None:
226 computer_msgs = samdb.search(base=computer_dn,
227 expression="objectclass=computer",
228 attrs=["msDS-KrbTgtLink",
230 scope=ldb.SCOPE_BASE)
231 if "rIDSetReferences" in computer_msgs[0]:
232 samdb.delete(computer_msgs[0]["rIDSetReferences"][0])
233 if "msDS-KrbTgtLink" in computer_msgs[0]:
234 samdb.delete(computer_msgs[0]["msDS-KrbTgtLink"][0])
236 if remove_computer_obj:
237 # Delete the computer tree
238 samdb.delete(computer_dn, ["tree_delete:0"])
240 if "dnsHostName" in msgs[0]:
241 dnsHostName = msgs[0]["dnsHostName"][0]
243 if dnsHostName is not None and remove_dns_names:
244 remove_dns_references(samdb, dnsHostName)
246 if remove_sysvol_obj:
247 remove_sysvol_references(samdb, dc_name)
249 def offline_remove_ntds_dc(samdb, ntds_dn,
250 remove_computer_obj=False,
251 remove_server_obj=False,
252 remove_connection_obj=False,
253 seize_stale_fsmo=False,
254 remove_sysvol_obj=False,
255 remove_dns_names=False):
256 res = samdb.search("",
257 scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
259 my_serviceName = ldb.Dn(samdb, res[0]["dsServiceName"][0])
260 server_dn = ntds_dn.parent()
262 if my_serviceName == ntds_dn:
263 raise DemoteException("Refusing to demote our own DSA: %s " % my_serviceName)
266 msgs = samdb.search(base=ntds_dn, expression="objectClass=ntdsDSA",
267 attrs=["objectGUID"], scope=ldb.SCOPE_BASE)
268 except LdbError as (enum, estr):
269 if enum == ldb.ERR_NO_SUCH_OBJECT:
270 raise DemoteException("Given DN %s doesn't exist" % ntds_dn)
274 raise DemoteException("%s is not an ntdsda in %s"
275 % (ntds_dn, samdb.domain_dns_name()))
278 if (msg.dn.get_rdn_name() != "CN" or
279 msg.dn.get_rdn_value() != "NTDS Settings"):
280 raise DemoteException("Given DN (%s) wasn't the NTDS Settings DN" %
283 ntds_guid = ndr_unpack(misc.GUID, msg["objectGUID"][0])
285 if remove_connection_obj:
286 # Find any nTDSConnection objects with that DC as the fromServer.
287 # We use the GUID to avoid issues with any () chars in a server
289 stale_connections = samdb.search(base=samdb.get_config_basedn(),
290 expression="(&(objectclass=nTDSConnection)"
291 "(fromServer=<GUID=%s>))" % ntds_guid)
292 for conn in stale_connections:
293 samdb.delete(conn.dn)
296 stale_fsmo_roles = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
297 expression="(fsmoRoleOwner=<GUID=%s>))"
299 controls=["search_options:0:2"])
300 # Find any FSMO roles they have, give them to this server
302 for role in stale_fsmo_roles:
303 val = str(my_serviceName)
306 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_REPLACE,
310 # Remove the NTDS setting tree
312 samdb.delete(ntds_dn, ["tree_delete:0"])
313 except LdbError as (enum, estr):
314 raise DemoteException("Failed to remove the DCs NTDS DSA object: %s"
317 offline_remove_server(samdb, server_dn,
318 remove_computer_obj=remove_computer_obj,
319 remove_server_obj=remove_server_obj,
320 remove_sysvol_obj=remove_sysvol_obj,
321 remove_dns_names=remove_dns_names)
324 def remove_dc(samdb, dc_name):
326 # TODO: Check if this is the last server (covered mostly by
327 # refusing to remove our own name)
329 samdb.transaction_start()
331 msgs = samdb.search(base=samdb.get_config_basedn(),
332 attrs=["serverReference"],
333 expression="(&(objectClass=server)(cn=%s))"
334 % ldb.binary_encode(dc_name))
336 raise DemoteException("%s is not an AD DC in %s"
337 % (dc_name, samdb.domain_dns_name()))
338 server_dn = msgs[0].dn
340 ntds_dn = ldb.Dn(samdb, "CN=NTDS Settings")
341 ntds_dn.add_base(msgs[0].dn)
343 # Confirm this is really an ntdsDSA object
345 msgs = samdb.search(base=ntds_dn, attrs=[], scope=ldb.SCOPE_BASE,
346 expression="(objectClass=ntdsdsa)")
347 except LdbError as (enum, estr):
348 if enum == ldb.ERR_NO_SUCH_OBJECT:
349 offline_remove_server(samdb, msgs[0].dn,
350 remove_computer_obj=True,
351 remove_server_obj=True,
352 remove_sysvol_obj=True,
353 remove_dns_names=True)
355 samdb.transaction_commit()
360 offline_remove_ntds_dc(samdb, msgs[0].dn,
361 remove_computer_obj=True,
362 remove_server_obj=True,
363 remove_connection_obj=True,
364 seize_stale_fsmo=True,
365 remove_sysvol_obj=True,
366 remove_dns_names=True)
368 samdb.transaction_commit()
372 def offline_remove_dc_RemoveDsServer(samdb, ntds_dn):
374 samdb.start_transaction()
376 offline_remove_ntds_dc(samdb, ntds_dn)
378 samdb.commit_transaction()