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