samba-tool domain demote: Add --remove-other-dead-server
[nivanova/samba-autobuild/.git] / python / samba / remove_dc.py
1 # Unix SMB/CIFS implementation.
2 # Copyright Matthieu Patou <mat@matws.net> 2011
3 # Copyright Andrew Bartlett <abartlet@samba.org> 2008-2015
4 #
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.
9 #
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.
14 #
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/>.
17 #
18
19 import ldb
20 from samba.ndr import ndr_unpack
21 from samba.dcerpc import misc
22
23
24 def remove_sysvol_references(samdb, rdn):
25     realm = samdb.domain_dns_name()
26     for s in ("CN=Enterprise,CN=Microsoft System Volumes,CN=System,CN=Configuration",
27               "CN=%s,CN=Microsoft System Volumes,CN=System,CN=Configuration" % realm,
28               "CN=Domain System Volumes (SYSVOL share),CN=File Replication Service,CN=System"):
29         try:
30             samdb.delete(ldb.Dn(samdb,
31                                 "%s,%s,%s" % (str(rdn), s, str(samdb.get_root_basedn()))))
32         except ldb.LdbError, l:
33             pass
34
35 def remove_dns_references(samdb, dnsHostName):
36
37     # Check we are using in-database DNS
38     zones = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
39                          expression="(&(objectClass=dnsZone)(!(dc=RootDNSServers)))",
40                          attrs=[],
41                          controls=["search_options:0:2"])
42     if len(zones) == 0:
43         return
44
45     try:
46         rec = samdb.dns_lookup(dnsHostName)
47     except RuntimeError as (enum, estr):
48         if enum == 0x000025F2: #WERR_DNS_ERROR_NAME_DOES_NOT_EXIST
49               return
50         raise demoteException("lookup of %s failed: %s" % (dnsHostName, estr))
51     samdb.dns_replace(dnsHostName, [])
52
53 def offline_remove_dc(samdb, ntds_dn,
54                       remove_computer_obj=False,
55                       remove_server_obj=False,
56                       remove_connection_obj=False,
57                       seize_stale_fsmo=False,
58                       remove_sysvol_obj=False,
59                       remove_dns_names=False):
60     res = samdb.search("",
61                        scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
62     assert len(res) == 1
63     my_serviceName = res[0]["dsServiceName"][0]
64     server_dn = ntds_dn.parent()
65
66     # Confirm this is really a server object
67     msgs = samdb.search(base=server_dn,
68                         attrs=["serverReference", "cn",
69                                "dnsHostName"],
70                         scope=ldb.SCOPE_BASE,
71                         expression="(objectClass=server)")
72     msg = msgs[0]
73     dc_name = msgs[0]["cn"]
74
75     try:
76         computer_dn = ldb.Dn(samdb, msgs[0]["serverReference"][0])
77     except KeyError:
78         computer_dn = None
79
80     try:
81         dnsHostName = msgs[0]["dnsHostName"][0]
82     except KeyError:
83         dnsHostName = None
84
85     ntds_dn = msg.dn
86     ntds_dn.add_child(ldb.Dn(samdb, "CN=NTDS Settings"))
87     msgs = samdb.search(base=ntds_dn, expression="objectClass=ntdsDSA",
88                         attrs=["objectGUID"])
89     msg = msgs[0]
90     ntds_guid = ndr_unpack(misc.GUID, msg["objectGUID"][0])
91
92     if remove_connection_obj:
93         # Find any nTDSConnection objects with that DC as the fromServer.
94         # We use the GUID to avoid issues with any () chars in a server
95         # name.
96         stale_connections = samdb.search(base=samdb.get_config_basedn(),
97                                          expression="(&(objectclass=nTDSConnection)(fromServer=<GUID=%s>))" % ntds_guid)
98         for conn in stale_connections:
99             samdb.delete(conn.dn)
100
101     if seize_stale_fsmo:
102         stale_fsmo_roles = samdb.search(base="", scope=ldb.SCOPE_SUBTREE,
103                                         expression="(fsmoRoleOwner=<GUID=%s>))" % ntds_guid,
104                                         controls=["search_options:0:2"])
105         # Find any FSMO roles they have, give them to this server
106
107         for role in stale_fsmo_roles:
108             val = str(my_serviceName)
109             m = ldb.Message()
110             m.dn = role.dn
111             m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_REPLACE, 'fsmoRoleOwner')
112             samdb.modify(mod)
113
114     # Remove the NTDS setting tree
115     samdb.delete(ntds_dn, ["tree_delete:0"])
116
117     if remove_server_obj:
118         # Remove the server DN
119         samdb.delete(server_dn)
120
121     if computer_dn is not None:
122         computer_msgs = samdb.search(base=computer_dn,
123                                      expression="objectclass=computer",
124                                      attrs=["msDS-KrbTgtLink",
125                                             "rIDSetReferences"],
126                                      scope=ldb.SCOPE_BASE)
127         if "rIDSetReferences" in computer_msgs[0]:
128             samdb.delete(computer_msgs[0]["rIDSetReferences"][0])
129         if "msDS-KrbTgtLink" in computer_msgs[0]:
130             samdb.delete(computer_msgs[0]["msDS-KrbTgtLink"][0])
131
132         if remove_computer_obj:
133             # Delete the computer tree
134             samdb.delete(computer_dn, ["tree_delete:0"])
135
136         if "dnsHostName" in msgs[0]:
137             dnsHostName = msgs[0]["dnsHostName"][0]
138
139     if dnsHostName is not None and remove_dns_names:
140         remove_dns_references(samdb, dnsHostName)
141
142     if remove_sysvol_obj:
143         remove_sysvol_references(samdb, "CN=%s" % dc_name)
144
145
146 def remove_dc(samdb, dc_name):
147
148     # TODO: Check if this is the last server
149
150     samdb.transaction_start()
151
152     msgs = samdb.search(base=samdb.get_config_basedn(),
153                         attrs=["serverReference"],
154                         expression="(&(objectClass=server)(cn=%s))"
155                         % ldb.binary_encode(dc_name))
156     server_dn = msgs[0].dn
157
158     ntds_dn = ldb.Dn(samdb, "CN=NTDS Settings")
159     ntds_dn.add_base(msgs[0].dn)
160
161     # Confirm this is really an ntdsDSA object
162     msgs = samdb.search(base=ntds_dn, attrs=[], scope=ldb.SCOPE_BASE,
163                         expression="(objectClass=ntdsdsa)")
164
165     offline_remove_dc(samdb, msgs[0].dn,
166                       remove_computer_obj=True,
167                       remove_server_obj=True,
168                       remove_connection_obj=True,
169                       seize_stale_fsmo=True,
170                       remove_sysvol_obj=True,
171                       remove_dns_names=True)
172
173     samdb.transaction_commit()
174
175
176
177 def offline_remove_dc_RemoveDsServer(samdb, ntds_dn):
178
179     samdb.start_transaction()
180
181     offline_remove_dc(samdb, ntds_dn)
182
183     samdb.commit_transaction()