dbcheck: added checks for missing and orphansed backlinks
[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 # Copyright (C) Matthieu Patou <mat@matws.net> 2011
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21
22 import ldb
23 from samba import dsdb
24 from samba import common
25 from samba.dcerpc import misc
26 from samba.ndr import ndr_unpack
27 from samba.dcerpc import drsblobs
28
29
30 class dsdb_DN(object):
31     '''a class to manipulate DN components'''
32
33     def __init__(self, samdb, dnstring, syntax_oid):
34         if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_STRING_DN ]:
35             colons = dnstring.split(':')
36             if len(colons) < 4:
37                 raise Exception("invalid DN prefix")
38             prefix_len = 4 + len(colons[1]) + int(colons[1])
39             self.prefix = dnstring[0:prefix_len]
40             self.dnstring = dnstring[prefix_len:]
41         else:
42             self.dnstring = dnstring
43             self.prefix = ''
44         try:
45             self.dn = ldb.Dn(samdb, self.dnstring)
46         except Exception, msg:
47             print("ERROR: bad DN string '%s'" % self.dnstring)
48             raise
49
50     def __str__(self):
51         return self.prefix + str(self.dn.extended_str(mode=1))
52
53 class dbcheck(object):
54     """check a SAM database for errors"""
55
56     def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False, yes=False, quiet=False):
57         self.samdb = samdb
58         self.dict_oid_name = None
59         self.samdb_schema = (samdb_schema or samdb)
60         self.verbose = verbose
61         self.fix = fix
62         self.yes = yes
63         self.quiet = quiet
64         self.remove_all_unknown_attributes = False
65         self.remove_all_empty_attributes = False
66         self.fix_all_normalisation = False
67         self.fix_all_DN_GUIDs = False
68         self.remove_all_deleted_DN_links = False
69         self.fix_all_target_mismatch = False
70         self.fix_all_metadata = False
71         self.fix_all_missing_backlinks = False
72         self.fix_all_orphaned_backlinks = False
73
74     def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
75         '''perform a database check, returning the number of errors found'''
76
77         res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
78         self.report('Checking %u objects' % len(res))
79         error_count = 0
80         for object in res:
81             error_count += self.check_object(object.dn, attrs=attrs)
82         if error_count != 0 and not self.fix:
83             self.report("Please use --fix to fix these errors")
84         self.report('Checked %u objects (%u errors)' % (len(res), error_count))
85
86         return error_count
87
88
89     def report(self, msg):
90         '''print a message unless quiet is set'''
91         if not self.quiet:
92             print(msg)
93
94
95     ################################################################
96     # a local confirm function that obeys the --fix and --yes options
97     def confirm(self, msg, allow_all=False, forced=False):
98         '''confirm a change'''
99         if not self.fix:
100             return False
101         if self.quiet:
102             return self.yes
103         if self.yes:
104             forced = True
105         return common.confirm(msg, forced=forced, allow_all=allow_all)
106
107     ################################################################
108     # a local confirm function with support for 'all'
109     def confirm_all(self, msg, all_attr):
110         '''confirm a change with support for "all" '''
111         if not self.fix:
112             return False
113         if self.quiet:
114             return self.yes
115         if getattr(self, all_attr) == 'NONE':
116             return False
117         if getattr(self, all_attr) == 'ALL':
118             forced = True
119         else:
120             forced = self.yes
121         c = common.confirm(msg, forced=forced, allow_all=True)
122         if c == 'ALL':
123             setattr(self, all_attr, 'ALL')
124             return True
125         if c == 'NONE':
126             setattr(self, all_attr, 'NONE')
127             return True
128         return c
129
130
131     def do_modify(self, m, controls, msg, validate=True):
132         '''perform a modify with optional verbose output'''
133         if self.verbose:
134             self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
135         try:
136             self.samdb.modify(m, controls=controls, validate=validate)
137         except Exception, err:
138             self.report("%s : %s" % (msg, err))
139             return False
140         return True
141
142
143     ################################################################
144     # handle empty attributes
145     def err_empty_attribute(self, dn, attrname):
146         '''fix empty attributes'''
147         self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
148         if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
149             self.report("Not fixing empty attribute %s" % attrname)
150             return
151
152         m = ldb.Message()
153         m.dn = dn
154         m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
155         if self.do_modify(m, ["relax:0", "show_deleted:1"],
156                           "Failed to remove empty attribute %s" % attrname, validate=False):
157             self.report("Removed empty attribute %s" % attrname)
158
159
160     ################################################################
161     # handle normalisation mismatches
162     def err_normalise_mismatch(self, dn, attrname, values):
163         '''fix attribute normalisation errors'''
164         self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
165         mod_list = []
166         for val in values:
167             normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
168             if len(normalised) != 1:
169                 self.report("Unable to normalise value '%s'" % val)
170                 mod_list.append((val, ''))
171             elif (normalised[0] != val):
172                 self.report("value '%s' should be '%s'" % (val, normalised[0]))
173                 mod_list.append((val, normalised[0]))
174         if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
175             self.report("Not fixing attribute %s" % attrname)
176             return
177
178         m = ldb.Message()
179         m.dn = dn
180         for i in range(0, len(mod_list)):
181             (val, nval) = mod_list[i]
182             m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
183             if nval != '':
184                 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
185
186         if self.do_modify(m, ["relax:0", "show_deleted:1"],
187                           "Failed to normalise attribute %s" % attrname,
188                           validate=False):
189             self.report("Normalised attribute %s" % attrname)
190
191     def is_deleted_objects_dn(self, dsdb_dn):
192         '''see if a dsdb_DN is the special Deleted Objects DN'''
193         return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
194
195
196     ################################################################
197     # handle a missing GUID extended DN component
198     def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
199         self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
200         controls=["extended_dn:1:1", "show_deleted:1"]
201         try:
202             res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
203                                     attrs=[], controls=controls)
204         except ldb.LdbError, (enum, estr):
205             self.report("unable to find object for DN %s - cannot fix (%s)" % (dsdb_dn.dn, estr))
206             return
207         dsdb_dn.dn = res[0].dn
208
209         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
210             self.report("Not fixing %s" % errstr)
211             return
212         m = ldb.Message()
213         m.dn = dn
214         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
215         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
216
217         if self.do_modify(m, ["show_deleted:1"],
218                           "Failed to fix %s on attribute %s" % (errstr, attrname)):
219             self.report("Fixed %s on attribute %s" % (errstr, attrname))
220
221
222     ################################################################
223     # handle a DN pointing to a deleted object
224     def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
225         self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
226         self.report("Target GUID points at deleted DN %s" % correct_dn)
227         if not self.confirm_all('Remove DN?', 'remove_all_deleted_DN_links'):
228             self.report("Not removing")
229             return
230         m = ldb.Message()
231         m.dn = dn
232         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
233         if self.do_modify(m, ["show_deleted:1"],
234                           "Failed to remove deleted DN attribute %s" % attrname):
235             self.report("Removed deleted DN on attribute %s" % attrname)
236
237
238     ################################################################
239     # handle a DN string being incorrect
240     def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
241         self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
242         dsdb_dn.dn = correct_dn
243
244         if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
245             self.report("Not fixing %s" % errstr)
246             return
247         m = ldb.Message()
248         m.dn = dn
249         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
250         m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
251         if self.do_modify(m, ["show_deleted:1"],
252                           "Failed to fix incorrect DN string on attribute %s" % attrname):
253             self.report("Fixed incorrect DN string on attribute %s" % (attrname))
254
255     ################################################################
256     # handle an unknown attribute error
257     def err_unknown_attribute(self, obj, attrname):
258         '''handle an unknown attribute error'''
259         self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
260         if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
261             self.report("Not removing %s" % attrname)
262             return
263         m = ldb.Message()
264         m.dn = obj.dn
265         m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
266         if self.do_modify(m, ["relax:0", "show_deleted:1"],
267                           "Failed to remove unknown attribute %s" % attrname):
268             self.report("Removed unknown attribute %s" % (attrname))
269
270
271     ################################################################
272     # handle a missing backlink
273     def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
274         '''handle a missing backlink value'''
275         self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
276         if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
277             self.report("Not fixing missing backlink %s" % backlink_name)
278             return
279         m = ldb.Message()
280         m.dn = obj.dn
281         m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
282         m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
283         if self.do_modify(m, ["show_deleted:1"],
284                           "Failed to fix missing backlink %s" % backlink_name):
285             self.report("Fixed missing backlink %s" % (backlink_name))
286
287
288     ################################################################
289     # handle a orphaned backlink
290     def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
291         '''handle a orphaned backlink value'''
292         self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
293         if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
294             self.report("Not removing orphaned backlink %s" % link_name)
295             return
296         m = ldb.Message()
297         m.dn = obj.dn
298         m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
299         if self.do_modify(m, ["show_deleted:1", "relax:0"],
300                           "Failed to fix orphaned backlink %s" % link_name):
301             self.report("Fixed orphaned backlink %s" % (link_name))
302
303
304     ################################################################
305     # specialised checking for a dn attribute
306     def check_dn(self, obj, attrname, syntax_oid):
307         '''check a DN attribute for correctness'''
308         error_count = 0
309         for val in obj[attrname]:
310             dsdb_dn = dsdb_DN(self.samdb, val, syntax_oid)
311
312             # all DNs should have a GUID component
313             guid = dsdb_dn.dn.get_extended_component("GUID")
314             if guid is None:
315                 error_count += 1
316                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "missing GUID")
317                 continue
318
319             guidstr = str(misc.GUID(guid))
320
321             attrs=['isDeleted']
322             linkkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
323             reverse_link_name = self.samdb.get_backlink_from_lDAPDisplayName(attrname)
324             if reverse_link_name is not None:
325                 attrs.append(reverse_link_name)
326
327             # check its the right GUID
328             try:
329                 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
330                                         attrs=attrs, controls=["extended_dn:1:1", "show_deleted:1"])
331             except ldb.LdbError, (enum, estr):
332                 error_count += 1
333                 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
334                 continue
335
336             # now we have two cases - the source object might or might not be deleted
337             is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
338             target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
339
340             # the target DN is not allowed to be deleted, unless the target DN is the
341             # special Deleted Objects container
342             if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
343                 error_count += 1
344                 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
345                 continue
346
347             # check the DN matches in string form
348             if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
349                 error_count += 1
350                 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
351                                             res[0].dn, "incorrect string version of DN")
352                 continue
353
354             # check the reverse_link is correct if there should be one
355             if reverse_link_name is not None:
356                 match_count = 0
357                 if reverse_link_name in res[0]:
358                     for v in res[0][reverse_link_name]:
359                         if v == obj.dn.extended_str():
360                             match_count += 1
361                 if match_count != 1:
362                     error_count += 1
363                     if linkkID & 1:
364                         self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
365                     else:
366                         self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
367                     continue
368
369         return error_count
370
371
372     def process_metadata(self, val):
373         '''Read metadata properties and list attributes in it'''
374
375         list_att = []
376
377         repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
378         obj = repl.ctr
379
380         for o in repl.ctr.array:
381             att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
382             list_att.append(att.lower())
383
384         return list_att
385
386
387     def fix_metadata(self, dn, attr):
388         '''re-write replPropertyMetaData elements for a single attribute for a
389         object. This is used to fix missing replPropertyMetaData elements'''
390         res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
391                                 controls = ["search_options:1:2", "show_deleted:1"])
392         msg = res[0]
393         nmsg = ldb.Message()
394         nmsg.dn = dn
395         nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
396         if self.do_modify(nmsg, ["relax:0", "provision:0", "show_deleted:1"],
397                           "Failed to fix metadata for attribute %s" % attr):
398             self.report("Fixed metadata for attribute %s" % attr)
399
400
401     ################################################################
402     # check one object - calls to individual error handlers above
403     def check_object(self, dn, attrs=['*']):
404         '''check one object'''
405         if self.verbose:
406             self.report("Checking object %s" % dn)
407         if '*' in attrs:
408             attrs.append("replPropertyMetaData")
409
410         res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
411                                 controls=["extended_dn:1:1", "show_deleted:1"],
412                                 attrs=attrs)
413         if len(res) != 1:
414             self.report("Object %s disappeared during check" % dn)
415             return 1
416         obj = res[0]
417         error_count = 0
418         list_attrs_from_md = []
419         list_attrs_seen = []
420
421         for attrname in obj:
422             if attrname == 'dn':
423                 continue
424
425             if str(attrname).lower() == 'replpropertymetadata':
426                 list_attrs_from_md = self.process_metadata(obj[attrname])
427                 continue
428
429
430             # check for empty attributes
431             for val in obj[attrname]:
432                 if val == '':
433                     self.err_empty_attribute(dn, attrname)
434                     error_count += 1
435                     continue
436
437             # get the syntax oid for the attribute, so we can can have
438             # special handling for some specific attribute types
439             try:
440                 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
441             except Exception, msg:
442                 self.err_unknown_attribute(obj, attrname)
443                 error_count += 1
444                 continue
445
446             flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
447             if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
448                 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
449                 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
450                 list_attrs_seen.append(str(attrname).lower())
451
452             if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
453                                dsdb.DSDB_SYNTAX_STRING_DN, ldb.LDB_SYNTAX_DN ]:
454                 # it's some form of DN, do specialised checking on those
455                 error_count += self.check_dn(obj, attrname, syntax_oid)
456
457             # check for incorrectly normalised attributes
458             for val in obj[attrname]:
459                 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
460                 if len(normalised) != 1 or normalised[0] != val:
461                     self.err_normalise_mismatch(dn, attrname, obj[attrname])
462                     error_count += 1
463                     break
464
465         show_dn = True
466         for att in list_attrs_seen:
467             if not att in list_attrs_from_md:
468                 if show_dn:
469                     self.report("On object %s" % dn)
470                     show_dn = False
471                 error_count += 1
472                 self.report("ERROR: Attribute %s not present in replication metadata" % att)
473                 if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
474                     self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
475                     continue
476                 self.fix_metadata(dn, att)
477
478         return error_count
479
480     ###############################################
481     # re-index the database
482     def reindex_database(self):
483         '''re-index the whole database'''
484         m = ldb.Message()
485         m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
486         m['add']    = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
487         m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
488         return self.do_modify(m, [], 're-indexed database', validate=False)