dbcheck: added confirm_all support for remaining checks
[metze/samba/wip.git] / source4 / scripting / python / samba / dbchecker.py
1 #!/usr/bin/env python
2 #
3 # Samba4 AD database checker
4 #
5 # Copyright (C) Andrew Tridgell 2011
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 import ldb
22 from samba import dsdb
23 from samba import common
24 from samba.dcerpc import misc
25
26
27 class dsdb_DN(object):
28     '''a class to manipulate DN components'''
29
30     def __init__(self, samdb, dnstring, syntax_oid):
31         if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_STRING_DN ]:
32             colons = dnstring.split(':')
33             if len(colons) < 4:
34                 raise Exception("invalid DN prefix")
35             prefix_len = 4 + len(colons[1]) + int(colons[1])
36             self.prefix = dnstring[0:prefix_len]
37             self.dnstring = dnstring[prefix_len:]
38         else:
39             self.dnstring = dnstring
40             self.prefix = ''
41         try:
42             self.dn = ldb.Dn(samdb, self.dnstring)
43         except Exception, msg:
44             print("ERROR: bad DN string '%s'" % self.dnstring)
45             raise
46
47     def __str__(self):
48         return self.prefix + str(self.dn.extended_str(mode=1))
49
50 class dbcheck(object):
51     """check a SAM database for errors"""
52
53     def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False, yes=False, quiet=False):
54         self.samdb = samdb
55         self.samdb_schema = (samdb_schema or samdb)
56         self.verbose = verbose
57         self.fix = fix
58         self.yes = yes
59         self.quiet = quiet
60         self.remove_all_unknown_attributes = False
61         self.remove_all_empty_attributes = False
62         self.fix_all_normalisation = False
63         self.fix_all_DN_GUIDs = False
64         self.remove_all_deleted_DN_links = False
65         self.fix_all_target_mismatch = False
66
67     def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
68         '''perform a database check, returning the number of errors found'''
69
70         res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
71         self.report('Checking %u objects' % len(res))
72         error_count = 0
73         for object in res:
74             error_count += self.check_object(object.dn, attrs=attrs)
75         if error_count != 0 and not self.fix:
76             self.report("Please use --fix to fix these errors")
77         self.report('Checked %u objects (%u errors)' % (len(res), error_count))
78
79         return error_count
80
81
82     def report(self, msg):
83         '''print a message unless quiet is set'''
84         if not self.quiet:
85             print(msg)
86
87
88     ################################################################
89     # a local confirm function that obeys the --fix and --yes options
90     def confirm(self, msg, allow_all=False, forced=False):
91         '''confirm a change'''
92         if not self.fix:
93             return False
94         if self.quiet:
95             return self.yes
96         if self.yes:
97             forced = True
98         return common.confirm(msg, forced=forced, allow_all=allow_all)
99
100     ################################################################
101     # a local confirm function with support for 'all'
102     def confirm_all(self, msg, all_attr):
103         '''confirm a change with support for "all" '''
104         if not self.fix:
105             return False
106         if self.quiet:
107             return self.yes
108         if getattr(self, all_attr) == 'NONE':
109             return False
110         if getattr(self, all_attr) == 'ALL':
111             forced = True
112         else:
113             forced = self.yes
114         c = common.confirm(msg, forced=forced, allow_all=True)
115         if c == 'ALL':
116             setattr(self, all_attr, 'ALL')
117             return True
118         if c == 'NONE':
119             setattr(self, all_attr, 'NONE')
120             return True
121         return c
122
123
124     ################################################################
125     # handle empty attributes
126     def err_empty_attribute(self, dn, attrname):
127         '''fix empty attributes'''
128         self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
129         if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
130             self.report("Not fixing empty attribute %s" % attrname)
131             return
132
133         m = ldb.Message()
134         m.dn = dn
135         m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
136         if self.verbose:
137             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
138         try:
139             self.samdb.modify(m, controls=["relax:0"], validate=False)
140         except Exception, msg:
141             self.report("Failed to remove empty attribute %s : %s" % (attrname, msg))
142             return
143         self.report("Removed empty attribute %s" % attrname)
144
145
146     ################################################################
147     # handle normalisation mismatches
148     def err_normalise_mismatch(self, dn, attrname, values):
149         '''fix attribute normalisation errors'''
150         self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
151         mod_list = []
152         for val in values:
153             normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
154             if len(normalised) != 1:
155                 self.report("Unable to normalise value '%s'" % val)
156                 mod_list.append((val, ''))
157             elif (normalised[0] != val):
158                 self.report("value '%s' should be '%s'" % (val, normalised[0]))
159                 mod_list.append((val, normalised[0]))
160         if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
161             self.report("Not fixing attribute %s" % attrname)
162             return
163
164         m = ldb.Message()
165         m.dn = dn
166         for i in range(0, len(mod_list)):
167             (val, nval) = mod_list[i]
168             m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
169             if nval != '':
170                 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
171
172         if self.verbose:
173             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
174         try:
175             self.samdb.modify(m, controls=["relax:0"], validate=False)
176         except Exception, msg:
177             self.report("Failed to normalise attribute %s : %s" % (attrname, msg))
178             return
179         self.report("Normalised attribute %s" % attrname)
180
181     def is_deleted_objects_dn(self, dsdb_dn):
182         '''see if a dsdb_DN is the special Deleted Objects DN'''
183         return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
184
185
186     ################################################################
187     # handle a missing GUID extended DN component
188     def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
189         self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
190         controls=["extended_dn:1:1"]
191         if self.is_deleted_objects_dn(dsdb_dn):
192             controls.append("show_deleted:1")
193         try:
194             res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
195                                     attrs=[], controls=controls)
196         except ldb.LdbError, (enum, estr):
197             self.report("unable to find object for DN %s - cannot fix (%s)" % (dsdb_dn.dn, estr))
198             return
199         dsdb_dn.dn = res[0].dn
200
201         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
202             self.report("Not fixing %s" % errstr)
203             return
204         m = ldb.Message()
205         m.dn = dn
206         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
207         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
208         if self.verbose:
209             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
210         try:
211             self.samdb.modify(m)
212         except Exception, msg:
213             self.report("Failed to fix %s on attribute %s : %s" % (errstr, attrname, msg))
214             return
215         self.report("Fixed %s on attribute %s" % (errstr, attrname))
216
217
218     ################################################################
219     # handle a DN pointing to a deleted object
220     def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
221         self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
222         self.report("Target GUID points at deleted DN %s" % correct_dn)
223         if not self.confirm_all('Remove DN?', 'remove_all_deleted_DN_links'):
224             self.report("Not removing")
225             return
226         m = ldb.Message()
227         m.dn = dn
228         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
229         if self.verbose:
230             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
231         try:
232             self.samdb.modify(m)
233         except Exception, msg:
234             self.report("Failed to remove deleted DN attribute %s : %s" % (attrname, msg))
235             return
236         self.report("Removed deleted DN on attribute %s" % attrname)
237
238
239     ################################################################
240     # handle a DN string being incorrect
241     def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
242         self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
243         dsdb_dn.dn = correct_dn
244
245         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
246             self.report("Not fixing %s" % errstr)
247             return
248         m = ldb.Message()
249         m.dn = dn
250         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
251         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
252         if self.verbose:
253             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
254         try:
255             self.samdb.modify(m)
256         except Exception, msg:
257             self.report("Failed to fix incorrect DN string on attribute %s : %s" % (attrname, msg))
258             return
259         self.report("Fixed incorrect DN string on attribute %s" % (attrname))
260
261     ################################################################
262     # handle an unknown attribute error
263     def err_unknown_attribute(self, obj, attrname):
264         '''handle an unknown attribute error'''
265         self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
266         if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
267             self.report("Not removing %s" % attrname)
268             return
269         m = ldb.Message()
270         m.dn = obj.dn
271         m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
272         if self.verbose:
273             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
274         try:
275             self.samdb.modify(m, controls=["relax:0"])
276         except Exception, msg:
277             self.report("Failed to remove unknown attribute %s : %s" % (attrname, msg))
278             return
279         self.report("Removed unknown attribute %s" % (attrname))
280
281
282     ################################################################
283     # specialised checking for a dn attribute
284     def check_dn(self, obj, attrname, syntax_oid):
285         '''check a DN attribute for correctness'''
286         error_count = 0
287         for val in obj[attrname]:
288             dsdb_dn = dsdb_DN(self.samdb, val, syntax_oid)
289
290             # all DNs should have a GUID component
291             guid = dsdb_dn.dn.get_extended_component("GUID")
292             if guid is None:
293                 error_count += 1
294                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "missing GUID")
295                 continue
296
297             guidstr = str(misc.GUID(guid))
298
299             # check its the right GUID
300             try:
301                 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
302                                         attrs=['isDeleted'], controls=["extended_dn:1:1", "show_deleted:1"])
303             except ldb.LdbError, (enum, estr):
304                 error_count += 1
305                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
306                 continue
307
308             # the target DN might be deleted
309             if ((not self.is_deleted_objects_dn(dsdb_dn)) and
310                 'isDeleted' in res[0] and
311                 res[0]['isDeleted'][0].upper() == "TRUE"):
312                 # note that we don't check this for the special wellKnownObjects prefix
313                 # for Deleted Objects, as we expect that to be deleted
314                 error_count += 1
315                 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
316                 continue
317
318             # check the DN matches in string form
319             if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
320                 error_count += 1
321                 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
322                                             res[0].dn, "incorrect string version of DN")
323                 continue
324
325         return error_count
326
327
328
329     ################################################################
330     # check one object - calls to individual error handlers above
331     def check_object(self, dn, attrs=['*']):
332         '''check one object'''
333         if self.verbose:
334             self.report("Checking object %s" % dn)
335         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"], attrs=attrs)
336         if len(res) != 1:
337             self.report("Object %s disappeared during check" % dn)
338             return 1
339         obj = res[0]
340         error_count = 0
341         for attrname in obj:
342             if attrname == 'dn':
343                 continue
344
345             # check for empty attributes
346             for val in obj[attrname]:
347                 if val == '':
348                     self.err_empty_attribute(dn, attrname)
349                     error_count += 1
350                     continue
351
352             # get the syntax oid for the attribute, so we can can have
353             # special handling for some specific attribute types
354             try:
355                 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
356             except Exception, msg:
357                 self.err_unknown_attribute(obj, attrname)
358                 error_count += 1
359                 continue
360
361             if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
362                                dsdb.DSDB_SYNTAX_STRING_DN, ldb.LDB_SYNTAX_DN ]:
363                 # it's some form of DN, do specialised checking on those
364                 error_count += self.check_dn(obj, attrname, syntax_oid)
365
366             # check for incorrectly normalised attributes
367             for val in obj[attrname]:
368                 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
369                 if len(normalised) != 1 or normalised[0] != val:
370                     self.err_normalise_mismatch(dn, attrname, obj[attrname])
371                     error_count += 1
372                     break
373         return error_count