dbcheck: check for unknown attributes and offer to remove them
[kai/samba.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
62     def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
63         '''perform a database check, returning the number of errors found'''
64
65         res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
66         self.report('Checking %u objects' % len(res))
67         error_count = 0
68         for object in res:
69             error_count += self.check_object(object.dn, attrs=attrs)
70         if error_count != 0 and not self.fix:
71             self.report("Please use --fix to fix these errors")
72         self.report('Checked %u objects (%u errors)' % (len(res), error_count))
73
74         return error_count
75
76
77     def report(self, msg):
78         '''print a message unless quiet is set'''
79         if not self.quiet:
80             print(msg)
81
82
83     ################################################################
84     # a local confirm function that obeys the --fix and --yes options
85     def confirm(self, msg, allow_all=False, forced=False):
86         '''confirm a change'''
87         if not self.fix:
88             return False
89         if self.quiet:
90             return self.yes
91         if self.yes:
92             forced = True
93         return common.confirm(msg, forced=forced, allow_all=allow_all)
94
95     ################################################################
96     # a local confirm function with support for 'all'
97     def confirm_all(self, msg, all_attr):
98         '''confirm a change with support for "all" '''
99         if not self.fix:
100             return False
101         if self.quiet:
102             return self.yes
103         forced = self.yes or getattr(self, all_attr)
104         c = common.confirm(msg, forced=forced, allow_all=True)
105         if c == 'ALL':
106             setattr(self, all_attr, True)
107             return True
108         return c
109
110
111     ################################################################
112     # handle empty attributes
113     def err_empty_attribute(self, dn, attrname):
114         '''fix empty attributes'''
115         self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
116         if not self.confirm('Remove empty attribute %s from %s?' % (attrname, dn)):
117             self.report("Not fixing empty attribute %s" % attrname)
118             return
119
120         m = ldb.Message()
121         m.dn = dn
122         m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
123         if self.verbose:
124             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
125         try:
126             self.samdb.modify(m, controls=["relax:0"], validate=False)
127         except Exception, msg:
128             self.report("Failed to remove empty attribute %s : %s" % (attrname, msg))
129             return
130         self.report("Removed empty attribute %s" % attrname)
131
132
133     ################################################################
134     # handle normalisation mismatches
135     def err_normalise_mismatch(self, dn, attrname, values):
136         '''fix attribute normalisation errors'''
137         self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
138         mod_list = []
139         for val in values:
140             normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
141             if len(normalised) != 1:
142                 self.report("Unable to normalise value '%s'" % val)
143                 mod_list.append((val, ''))
144             elif (normalised[0] != val):
145                 self.report("value '%s' should be '%s'" % (val, normalised[0]))
146                 mod_list.append((val, normalised[0]))
147         if not self.confirm('Fix normalisation for %s from %s?' % (attrname, dn)):
148             self.report("Not fixing attribute %s" % attrname)
149             return
150
151         m = ldb.Message()
152         m.dn = dn
153         for i in range(0, len(mod_list)):
154             (val, nval) = mod_list[i]
155             m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
156             if nval != '':
157                 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
158
159         if self.verbose:
160             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
161         try:
162             self.samdb.modify(m, controls=["relax:0"], validate=False)
163         except Exception, msg:
164             self.report("Failed to normalise attribute %s : %s" % (attrname, msg))
165             return
166         self.report("Normalised attribute %s" % attrname)
167
168     def is_deleted_objects_dn(self, dsdb_dn):
169         '''see if a dsdb_DN is the special Deleted Objects DN'''
170         return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
171
172
173     ################################################################
174     # handle a missing GUID extended DN component
175     def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
176         self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
177         controls=["extended_dn:1:1"]
178         if self.is_deleted_objects_dn(dsdb_dn):
179             controls.append("show_deleted:1")
180         try:
181             res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
182                                     attrs=[], controls=controls)
183         except ldb.LdbError, (enum, estr):
184             self.report("unable to find object for DN %s - cannot fix (%s)" % (dsdb_dn.dn, estr))
185             return
186         dsdb_dn.dn = res[0].dn
187
188         if not self.confirm('Change DN to %s?' % str(dsdb_dn)):
189             self.report("Not fixing %s" % errstr)
190             return
191         m = ldb.Message()
192         m.dn = dn
193         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
194         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
195         if self.verbose:
196             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
197         try:
198             self.samdb.modify(m)
199         except Exception, msg:
200             self.report("Failed to fix %s on attribute %s : %s" % (errstr, attrname, msg))
201             return
202         self.report("Fixed %s on attribute %s" % (errstr, attrname))
203
204
205     ################################################################
206     # handle a DN pointing to a deleted object
207     def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
208         self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
209         self.report("Target GUID points at deleted DN %s" % correct_dn)
210         if not self.confirm('Remove DN?'):
211             self.report("Not removing")
212             return
213         m = ldb.Message()
214         m.dn = dn
215         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
216         if self.verbose:
217             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
218         try:
219             self.samdb.modify(m)
220         except Exception, msg:
221             self.report("Failed to remove deleted DN attribute %s : %s" % (attrname, msg))
222             return
223         self.report("Removed deleted DN on attribute %s" % attrname)
224
225
226     ################################################################
227     # handle a DN string being incorrect
228     def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
229         self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
230         dsdb_dn.dn = correct_dn
231
232         if not self.confirm('Change DN to %s?' % str(dsdb_dn)):
233             self.report("Not fixing %s" % errstr)
234             return
235         m = ldb.Message()
236         m.dn = dn
237         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
238         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
239         if self.verbose:
240             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
241         try:
242             self.samdb.modify(m)
243         except Exception, msg:
244             self.report("Failed to fix incorrect DN string on attribute %s : %s" % (attrname, msg))
245             return
246         self.report("Fixed incorrect DN string on attribute %s" % (attrname))
247
248     ################################################################
249     # handle an unknown attribute error
250     def err_unknown_attribute(self, obj, attrname):
251         '''handle an unknown attribute error'''
252         self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
253         if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
254             self.report("Not removing %s" % attrname)
255             return
256         m = ldb.Message()
257         m.dn = obj.dn
258         m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
259         if self.verbose:
260             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
261         try:
262             self.samdb.modify(m, controls=["relax:0"])
263         except Exception, msg:
264             self.report("Failed to remove unknown attribute %s : %s" % (attrname, msg))
265             return
266         self.report("Removed unknown attribute %s" % (attrname))
267
268
269     ################################################################
270     # specialised checking for a dn attribute
271     def check_dn(self, obj, attrname, syntax_oid):
272         '''check a DN attribute for correctness'''
273         error_count = 0
274         for val in obj[attrname]:
275             dsdb_dn = dsdb_DN(self.samdb, val, syntax_oid)
276
277             # all DNs should have a GUID component
278             guid = dsdb_dn.dn.get_extended_component("GUID")
279             if guid is None:
280                 error_count += 1
281                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "missing GUID")
282                 continue
283
284             guidstr = str(misc.GUID(guid))
285
286             # check its the right GUID
287             try:
288                 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
289                                         attrs=['isDeleted'], controls=["extended_dn:1:1", "show_deleted:1"])
290             except ldb.LdbError, (enum, estr):
291                 error_count += 1
292                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
293                 continue
294
295             # the target DN might be deleted
296             if ((not self.is_deleted_objects_dn(dsdb_dn)) and
297                 'isDeleted' in res[0] and
298                 res[0]['isDeleted'][0].upper() == "TRUE"):
299                 # note that we don't check this for the special wellKnownObjects prefix
300                 # for Deleted Objects, as we expect that to be deleted
301                 error_count += 1
302                 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
303                 continue
304
305             # check the DN matches in string form
306             if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
307                 error_count += 1
308                 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
309                                             res[0].dn, "incorrect string version of DN")
310                 continue
311
312         return error_count
313
314
315
316     ################################################################
317     # check one object - calls to individual error handlers above
318     def check_object(self, dn, attrs=['*']):
319         '''check one object'''
320         if self.verbose:
321             self.report("Checking object %s" % dn)
322         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"], attrs=attrs)
323         if len(res) != 1:
324             self.report("Object %s disappeared during check" % dn)
325             return 1
326         obj = res[0]
327         error_count = 0
328         for attrname in obj:
329             if attrname == 'dn':
330                 continue
331
332             # check for empty attributes
333             for val in obj[attrname]:
334                 if val == '':
335                     self.err_empty_attribute(dn, attrname)
336                     error_count += 1
337                     continue
338
339             # get the syntax oid for the attribute, so we can can have
340             # special handling for some specific attribute types
341             try:
342                 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
343             except Exception, msg:
344                 self.err_unknown_attribute(obj, attrname)
345                 error_count += 1
346                 continue
347
348             if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
349                                dsdb.DSDB_SYNTAX_STRING_DN, ldb.LDB_SYNTAX_DN ]:
350                 # it's some form of DN, do specialised checking on those
351                 error_count += self.check_dn(obj, attrname, syntax_oid)
352
353             # check for incorrectly normalised attributes
354             for val in obj[attrname]:
355                 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
356                 if len(normalised) != 1 or normalised[0] != val:
357                     self.err_normalise_mismatch(dn, attrname, obj[attrname])
358                     error_count += 1
359                     break
360         return error_count