3 # Samba4 AD database checker
5 # Copyright (C) Andrew Tridgell 2011
6 # Copyright (C) Matthieu Patou <mat@matws.net> 2011
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.
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.
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/>.
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
30 class dsdb_DN(object):
31 '''a class to manipulate DN components'''
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(':')
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:]
42 self.dnstring = dnstring
45 self.dn = ldb.Dn(samdb, self.dnstring)
46 except Exception, msg:
47 print("ERROR: bad DN string '%s'" % self.dnstring)
51 return self.prefix + str(self.dn.extended_str(mode=1))
53 class dbcheck(object):
54 """check a SAM database for errors"""
56 def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False, yes=False, quiet=False):
58 self.dict_oid_name = None
59 self.samdb_schema = (samdb_schema or samdb)
60 self.verbose = verbose
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
74 def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
75 '''perform a database check, returning the number of errors found'''
77 res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
78 self.report('Checking %u objects' % len(res))
82 error_count += self.check_object(object.dn, attrs=attrs)
85 error_count += self.check_rootdse()
87 if error_count != 0 and not self.fix:
88 self.report("Please use --fix to fix these errors")
91 self.report('Checked %u objects (%u errors)' % (len(res), error_count))
96 def report(self, msg):
97 '''print a message unless quiet is set'''
102 ################################################################
103 # a local confirm function that obeys the --fix and --yes options
104 def confirm(self, msg, allow_all=False, forced=False):
105 '''confirm a change'''
112 return common.confirm(msg, forced=forced, allow_all=allow_all)
114 ################################################################
115 # a local confirm function with support for 'all'
116 def confirm_all(self, msg, all_attr):
117 '''confirm a change with support for "all" '''
122 if getattr(self, all_attr) == 'NONE':
124 if getattr(self, all_attr) == 'ALL':
128 c = common.confirm(msg, forced=forced, allow_all=True)
130 setattr(self, all_attr, 'ALL')
133 setattr(self, all_attr, 'NONE')
138 def do_modify(self, m, controls, msg, validate=True):
139 '''perform a modify with optional verbose output'''
141 self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
143 self.samdb.modify(m, controls=controls, validate=validate)
144 except Exception, err:
145 self.report("%s : %s" % (msg, err))
150 ################################################################
151 # handle empty attributes
152 def err_empty_attribute(self, dn, attrname):
153 '''fix empty attributes'''
154 self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
155 if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
156 self.report("Not fixing empty attribute %s" % attrname)
161 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
162 if self.do_modify(m, ["relax:0", "show_recycled:1"],
163 "Failed to remove empty attribute %s" % attrname, validate=False):
164 self.report("Removed empty attribute %s" % attrname)
167 ################################################################
168 # handle normalisation mismatches
169 def err_normalise_mismatch(self, dn, attrname, values):
170 '''fix attribute normalisation errors'''
171 self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
174 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
175 if len(normalised) != 1:
176 self.report("Unable to normalise value '%s'" % val)
177 mod_list.append((val, ''))
178 elif (normalised[0] != val):
179 self.report("value '%s' should be '%s'" % (val, normalised[0]))
180 mod_list.append((val, normalised[0]))
181 if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
182 self.report("Not fixing attribute %s" % attrname)
187 for i in range(0, len(mod_list)):
188 (val, nval) = mod_list[i]
189 m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
191 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
193 if self.do_modify(m, ["relax:0", "show_recycled:1"],
194 "Failed to normalise attribute %s" % attrname,
196 self.report("Normalised attribute %s" % attrname)
198 def is_deleted_objects_dn(self, dsdb_dn):
199 '''see if a dsdb_DN is the special Deleted Objects DN'''
200 return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
203 ################################################################
204 # handle a DN pointing to a deleted object
205 def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
206 self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
207 self.report("Target GUID points at deleted DN %s" % correct_dn)
208 if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
209 self.report("Not removing")
213 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
214 if self.do_modify(m, ["show_recycled:1", "%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
215 "Failed to remove deleted DN attribute %s" % attrname):
216 self.report("Removed deleted DN on attribute %s" % attrname)
218 ################################################################
219 # handle a missing target DN (both GUID and DN string form are missing)
220 def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
221 # check if its a backlink
222 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
223 if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1:
224 self.report("Not removing dangling forward link")
226 self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
229 ################################################################
230 # handle a missing GUID extended DN component
231 def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
232 self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
233 controls=["extended_dn:1:1", "show_recycled:1"]
235 res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
236 attrs=[], controls=controls)
237 except ldb.LdbError, (enum, estr):
238 self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
239 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
242 self.report("unable to find object for DN %s" % dsdb_dn.dn)
243 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
245 dsdb_dn.dn = res[0].dn
247 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
248 self.report("Not fixing %s" % errstr)
252 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
253 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
255 if self.do_modify(m, ["show_recycled:1"],
256 "Failed to fix %s on attribute %s" % (errstr, attrname)):
257 self.report("Fixed %s on attribute %s" % (errstr, attrname))
260 ################################################################
261 # handle a DN string being incorrect
262 def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
263 self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
264 dsdb_dn.dn = correct_dn
266 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
267 self.report("Not fixing %s" % errstr)
271 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
272 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
273 if self.do_modify(m, ["show_recycled:1"],
274 "Failed to fix incorrect DN string on attribute %s" % attrname):
275 self.report("Fixed incorrect DN string on attribute %s" % (attrname))
277 ################################################################
278 # handle an unknown attribute error
279 def err_unknown_attribute(self, obj, attrname):
280 '''handle an unknown attribute error'''
281 self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
282 if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
283 self.report("Not removing %s" % attrname)
287 m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
288 if self.do_modify(m, ["relax:0", "show_recycled:1"],
289 "Failed to remove unknown attribute %s" % attrname):
290 self.report("Removed unknown attribute %s" % (attrname))
293 ################################################################
294 # handle a missing backlink
295 def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
296 '''handle a missing backlink value'''
297 self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
298 if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
299 self.report("Not fixing missing backlink %s" % backlink_name)
303 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
304 m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
305 if self.do_modify(m, ["show_recycled:1"],
306 "Failed to fix missing backlink %s" % backlink_name):
307 self.report("Fixed missing backlink %s" % (backlink_name))
310 ################################################################
311 # handle a orphaned backlink
312 def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
313 '''handle a orphaned backlink value'''
314 self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
315 if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
316 self.report("Not removing orphaned backlink %s" % link_name)
320 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
321 if self.do_modify(m, ["show_recycled:1", "relax:0"],
322 "Failed to fix orphaned backlink %s" % link_name):
323 self.report("Fixed orphaned backlink %s" % (link_name))
326 ################################################################
327 # specialised checking for a dn attribute
328 def check_dn(self, obj, attrname, syntax_oid):
329 '''check a DN attribute for correctness'''
331 for val in obj[attrname]:
332 dsdb_dn = dsdb_DN(self.samdb, val, syntax_oid)
334 # all DNs should have a GUID component
335 guid = dsdb_dn.dn.get_extended_component("GUID")
338 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "missing GUID")
341 guidstr = str(misc.GUID(guid))
344 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
345 reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
346 if reverse_link_name is not None:
347 attrs.append(reverse_link_name)
349 # check its the right GUID
351 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
352 attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
353 except ldb.LdbError, (enum, estr):
355 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
358 # now we have two cases - the source object might or might not be deleted
359 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
360 target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
362 # the target DN is not allowed to be deleted, unless the target DN is the
363 # special Deleted Objects container
364 if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
366 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
369 # check the DN matches in string form
370 if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
372 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
373 res[0].dn, "incorrect string version of DN")
376 # check the reverse_link is correct if there should be one
377 if reverse_link_name is not None:
379 if reverse_link_name in res[0]:
380 for v in res[0][reverse_link_name]:
381 if v == obj.dn.extended_str():
386 self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
388 self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
394 def process_metadata(self, val):
395 '''Read metadata properties and list attributes in it'''
399 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
402 for o in repl.ctr.array:
403 att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
404 list_att.append(att.lower())
409 def fix_metadata(self, dn, attr):
410 '''re-write replPropertyMetaData elements for a single attribute for a
411 object. This is used to fix missing replPropertyMetaData elements'''
412 res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
413 controls = ["search_options:1:2", "show_recycled:1"])
417 nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
418 if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
419 "Failed to fix metadata for attribute %s" % attr):
420 self.report("Fixed metadata for attribute %s" % attr)
423 ################################################################
424 # check one object - calls to individual error handlers above
425 def check_object(self, dn, attrs=['*']):
426 '''check one object'''
428 self.report("Checking object %s" % dn)
430 attrs.append("replPropertyMetaData")
432 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
433 controls=["extended_dn:1:1", "show_recycled:1"],
436 self.report("Object %s disappeared during check" % dn)
440 list_attrs_from_md = []
442 got_repl_property_meta_data = False
448 if str(attrname).lower() == 'replpropertymetadata':
449 list_attrs_from_md = self.process_metadata(obj[attrname])
450 got_repl_property_meta_data = True
454 # check for empty attributes
455 for val in obj[attrname]:
457 self.err_empty_attribute(dn, attrname)
461 # get the syntax oid for the attribute, so we can can have
462 # special handling for some specific attribute types
464 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
465 except Exception, msg:
466 self.err_unknown_attribute(obj, attrname)
470 flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
471 if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
472 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
473 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
474 list_attrs_seen.append(str(attrname).lower())
476 if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
477 dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
478 # it's some form of DN, do specialised checking on those
479 error_count += self.check_dn(obj, attrname, syntax_oid)
481 # check for incorrectly normalised attributes
482 for val in obj[attrname]:
483 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
484 if len(normalised) != 1 or normalised[0] != val:
485 self.err_normalise_mismatch(dn, attrname, obj[attrname])
490 if got_repl_property_meta_data:
491 for att in list_attrs_seen:
492 if not att in list_attrs_from_md:
494 self.report("On object %s" % dn)
497 self.report("ERROR: Attribute %s not present in replication metadata" % att)
498 if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
499 self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
501 self.fix_metadata(dn, att)
505 ################################################################
506 # check special @ROOTDSE attributes
507 def check_rootdse(self):
508 '''check the @ROOTDSE special object'''
509 dn = ldb.Dn(self.samdb, '@ROOTDSE')
511 self.report("Checking object %s" % dn)
512 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
514 self.report("Object %s disappeared during check" % dn)
519 # check that the dsServiceName is in GUID form
520 if not 'dsServiceName' in obj:
521 self.report('ERROR: dsServiceName missing in @ROOTDSE')
524 if not obj['dsServiceName'][0].startswith('<GUID='):
525 self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
527 if not self.confirm('Change dsServiceName to GUID form?'):
529 res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
530 scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
531 guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
534 m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
535 ldb.FLAG_MOD_REPLACE, 'dsServiceName')
536 if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
537 self.report("Changed dsServiceName to GUID form")
541 ###############################################
542 # re-index the database
543 def reindex_database(self):
544 '''re-index the whole database'''
546 m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
547 m['add'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
548 m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
549 return self.do_modify(m, [], 're-indexed database', validate=False)