1 # Samba4 AD database checker
3 # Copyright (C) Andrew Tridgell 2011
4 # Copyright (C) Matthieu Patou <mat@matws.net> 2011
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 from samba import dsdb
22 from samba import common
23 from samba.dcerpc import misc
24 from samba.ndr import ndr_unpack
25 from samba.dcerpc import drsblobs
26 from samba.common import dsdb_Dn
29 class dbcheck(object):
30 """check a SAM database for errors"""
32 def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False,
33 yes=False, quiet=False, in_transaction=False):
35 self.dict_oid_name = None
36 self.samdb_schema = (samdb_schema or samdb)
37 self.verbose = verbose
41 self.remove_all_unknown_attributes = False
42 self.remove_all_empty_attributes = False
43 self.fix_all_normalisation = False
44 self.fix_all_DN_GUIDs = False
45 self.remove_all_deleted_DN_links = False
46 self.fix_all_target_mismatch = False
47 self.fix_all_metadata = False
48 self.fix_time_metadata = False
49 self.fix_all_missing_backlinks = False
50 self.fix_all_orphaned_backlinks = False
51 self.in_transaction = in_transaction
53 def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
54 '''perform a database check, returning the number of errors found'''
56 res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
57 self.report('Checking %u objects' % len(res))
61 error_count += self.check_object(object.dn, attrs=attrs)
64 error_count += self.check_rootdse()
66 if error_count != 0 and not self.fix:
67 self.report("Please use --fix to fix these errors")
69 self.report('Checked %u objects (%u errors)' % (len(res), error_count))
72 def report(self, msg):
73 '''print a message unless quiet is set'''
77 def confirm(self, msg, allow_all=False, forced=False):
78 '''confirm a change'''
85 return common.confirm(msg, forced=forced, allow_all=allow_all)
87 ################################################################
88 # a local confirm function with support for 'all'
89 def confirm_all(self, msg, all_attr):
90 '''confirm a change with support for "all" '''
95 if getattr(self, all_attr) == 'NONE':
97 if getattr(self, all_attr) == 'ALL':
101 c = common.confirm(msg, forced=forced, allow_all=True)
103 setattr(self, all_attr, 'ALL')
106 setattr(self, all_attr, 'NONE')
110 def do_modify(self, m, controls, msg, validate=True):
111 '''perform a modify with optional verbose output'''
113 self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
115 self.samdb.modify(m, controls=controls, validate=validate)
116 except Exception, err:
117 self.report("%s : %s" % (msg, err))
121 def err_empty_attribute(self, dn, attrname):
122 '''fix empty attributes'''
123 self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
124 if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
125 self.report("Not fixing empty attribute %s" % attrname)
130 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
131 if self.do_modify(m, ["relax:0", "show_recycled:1"],
132 "Failed to remove empty attribute %s" % attrname, validate=False):
133 self.report("Removed empty attribute %s" % attrname)
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))
140 normalised = self.samdb.dsdb_normalise_attributes(
141 self.samdb_schema, attrname, [val])
142 if len(normalised) != 1:
143 self.report("Unable to normalise value '%s'" % val)
144 mod_list.append((val, ''))
145 elif (normalised[0] != val):
146 self.report("value '%s' should be '%s'" % (val, normalised[0]))
147 mod_list.append((val, normalised[0]))
148 if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
149 self.report("Not fixing attribute %s" % attrname)
154 for i in range(0, len(mod_list)):
155 (val, nval) = mod_list[i]
156 m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
158 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD,
161 if self.do_modify(m, ["relax:0", "show_recycled:1"],
162 "Failed to normalise attribute %s" % attrname,
164 self.report("Normalised attribute %s" % attrname)
166 def err_normalise_mismatch_replace(self, dn, attrname, values):
167 '''fix attribute normalisation errors'''
168 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, values)
169 self.report("ERROR: Normalisation error for attribute '%s' in '%s'" % (attrname, dn))
170 self.report("Values/Order of values do/does not match: %s/%s!" % (values, list(normalised)))
171 if list(normalised) == values:
173 if not self.confirm_all("Fix normalisation for '%s' from '%s'?" % (attrname, dn), 'fix_all_normalisation'):
174 self.report("Not fixing attribute '%s'" % attrname)
179 m[attrname] = ldb.MessageElement(normalised, ldb.FLAG_MOD_REPLACE, attrname)
181 if self.do_modify(m, ["relax:0", "show_recycled:1"],
182 "Failed to normalise attribute %s" % attrname,
184 self.report("Normalised attribute %s" % attrname)
186 def is_deleted_objects_dn(self, dsdb_dn):
187 '''see if a dsdb_Dn is the special Deleted Objects DN'''
188 return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
190 def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
191 """handle a DN pointing to a deleted object"""
192 self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
193 self.report("Target GUID points at deleted DN %s" % correct_dn)
194 if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
195 self.report("Not removing")
199 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
200 if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
201 "Failed to remove deleted DN attribute %s" % attrname):
202 self.report("Removed deleted DN on attribute %s" % attrname)
204 def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
205 """handle a missing target DN (both GUID and DN string form are missing)"""
206 # check if its a backlink
207 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
208 if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1:
209 self.report("Not removing dangling forward link")
211 self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
213 def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
214 """handle a missing GUID extended DN component"""
215 self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
216 controls=["extended_dn:1:1", "show_recycled:1"]
218 res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
219 attrs=[], controls=controls)
220 except ldb.LdbError, (enum, estr):
221 self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
222 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
225 self.report("unable to find object for DN %s" % dsdb_dn.dn)
226 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
228 dsdb_dn.dn = res[0].dn
230 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
231 self.report("Not fixing %s" % errstr)
235 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
236 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
238 if self.do_modify(m, ["show_recycled:1"],
239 "Failed to fix %s on attribute %s" % (errstr, attrname)):
240 self.report("Fixed %s on attribute %s" % (errstr, attrname))
242 def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
243 """handle a DN string being incorrect"""
244 self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
245 dsdb_dn.dn = correct_dn
247 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
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)
254 if self.do_modify(m, ["show_recycled:1"],
255 "Failed to fix incorrect DN string on attribute %s" % attrname):
256 self.report("Fixed incorrect DN string on attribute %s" % (attrname))
258 def err_unknown_attribute(self, obj, attrname):
259 '''handle an unknown attribute error'''
260 self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
261 if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
262 self.report("Not removing %s" % attrname)
266 m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
267 if self.do_modify(m, ["relax:0", "show_recycled:1"],
268 "Failed to remove unknown attribute %s" % attrname):
269 self.report("Removed unknown attribute %s" % (attrname))
271 def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
272 '''handle a missing backlink value'''
273 self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
274 if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
275 self.report("Not fixing missing backlink %s" % backlink_name)
279 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
280 m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
281 if self.do_modify(m, ["show_recycled:1"],
282 "Failed to fix missing backlink %s" % backlink_name):
283 self.report("Fixed missing backlink %s" % (backlink_name))
285 def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
286 '''handle a orphaned backlink value'''
287 self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
288 if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
289 self.report("Not removing orphaned backlink %s" % link_name)
293 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
294 if self.do_modify(m, ["show_recycled:1", "relax:0"],
295 "Failed to fix orphaned backlink %s" % link_name):
296 self.report("Fixed orphaned backlink %s" % (link_name))
298 def check_dn(self, obj, attrname, syntax_oid):
299 '''check a DN attribute for correctness'''
301 for val in obj[attrname]:
302 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
304 # all DNs should have a GUID component
305 guid = dsdb_dn.dn.get_extended_component("GUID")
308 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn,
312 guidstr = str(misc.GUID(guid))
314 attrs = ['isDeleted']
315 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
316 reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
317 if reverse_link_name is not None:
318 attrs.append(reverse_link_name)
320 # check its the right GUID
322 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
323 attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
324 except ldb.LdbError, (enum, estr):
326 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
329 # now we have two cases - the source object might or might not be deleted
330 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
331 target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
333 # the target DN is not allowed to be deleted, unless the target DN is the
334 # special Deleted Objects container
335 if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
337 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
340 # check the DN matches in string form
341 if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
343 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
344 res[0].dn, "incorrect string version of DN")
347 # check the reverse_link is correct if there should be one
348 if reverse_link_name is not None:
350 if reverse_link_name in res[0]:
351 for v in res[0][reverse_link_name]:
352 if v == obj.dn.extended_str():
357 self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
359 self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
365 def get_originating_time(self, val, attid):
366 '''Read metadata properties and return the originating time for
369 :return: the originating time or 0 if not found
372 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
375 for o in repl.ctr.array:
377 return o.originating_change_time
381 def process_metadata(self, val):
382 '''Read metadata properties and list attributes in it'''
386 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
389 for o in repl.ctr.array:
390 att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
391 list_att.append(att.lower())
396 def fix_metadata(self, dn, attr):
397 '''re-write replPropertyMetaData elements for a single attribute for a
398 object. This is used to fix missing replPropertyMetaData elements'''
399 res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
400 controls = ["search_options:1:2", "show_recycled:1"])
404 nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
405 if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
406 "Failed to fix metadata for attribute %s" % attr):
407 self.report("Fixed metadata for attribute %s" % attr)
409 def check_object(self, dn, attrs=['*']):
410 '''check one object'''
412 self.report("Checking object %s" % dn)
414 attrs.append("replPropertyMetaData")
417 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
418 controls=["extended_dn:1:1", "show_recycled:1", "show_deleted:1"],
420 except ldb.LdbError, (enum, estr):
421 if enum == ldb.ERR_NO_SUCH_OBJECT:
422 if self.in_transaction:
423 self.report("ERROR: Object %s disappeared during check" % dn)
428 self.report("ERROR: Object %s failed to load during check" % dn)
432 list_attrs_from_md = []
434 got_repl_property_meta_data = False
440 if str(attrname).lower() == 'replpropertymetadata':
441 list_attrs_from_md = self.process_metadata(obj[attrname])
442 got_repl_property_meta_data = True
445 if str(attrname).lower() == 'objectclass':
446 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, list(obj[attrname]))
447 if list(normalised) != list(obj[attrname]):
448 self.err_normalise_mismatch_replace(dn, attrname, list(obj[attrname]))
452 # check for empty attributes
453 for val in obj[attrname]:
455 self.err_empty_attribute(dn, attrname)
459 # get the syntax oid for the attribute, so we can can have
460 # special handling for some specific attribute types
462 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
463 except Exception, msg:
464 self.err_unknown_attribute(obj, attrname)
468 flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
469 if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
470 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
471 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
472 list_attrs_seen.append(str(attrname).lower())
474 if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
475 dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
476 # it's some form of DN, do specialised checking on those
477 error_count += self.check_dn(obj, attrname, syntax_oid)
479 # check for incorrectly normalised attributes
480 for val in obj[attrname]:
481 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
482 if len(normalised) != 1 or normalised[0] != val:
483 self.err_normalise_mismatch(dn, attrname, obj[attrname])
488 if got_repl_property_meta_data:
489 rdn = (str(dn).split(","))[0]
490 if rdn == "CN=Deleted Objects":
491 isDeletedAttId = 131120
492 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
494 expectedTimeDo = 2650466015990000000
495 originating = self.get_originating_time(obj["replPropertyMetaData"], isDeletedAttId)
496 if originating != expectedTimeDo:
497 if self.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn), 'fix_time_metadata'):
500 nmsg["isDeleted"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isDeleted")
502 self.samdb.modify(nmsg, controls=["provision:0"])
505 self.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn))
506 for att in list_attrs_seen:
507 if not att in list_attrs_from_md:
509 self.report("On object %s" % dn)
512 self.report("ERROR: Attribute %s not present in replication metadata" % att)
513 if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
514 self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
516 self.fix_metadata(dn, att)
520 ################################################################
521 # check special @ROOTDSE attributes
522 def check_rootdse(self):
523 '''check the @ROOTDSE special object'''
524 dn = ldb.Dn(self.samdb, '@ROOTDSE')
526 self.report("Checking object %s" % dn)
527 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
529 self.report("Object %s disappeared during check" % dn)
534 # check that the dsServiceName is in GUID form
535 if not 'dsServiceName' in obj:
536 self.report('ERROR: dsServiceName missing in @ROOTDSE')
539 if not obj['dsServiceName'][0].startswith('<GUID='):
540 self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
542 if not self.confirm('Change dsServiceName to GUID form?'):
544 res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
545 scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
546 guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
549 m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
550 ldb.FLAG_MOD_REPLACE, 'dsServiceName')
551 if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
552 self.report("Changed dsServiceName to GUID form")
556 ###############################################
557 # re-index the database
558 def reindex_database(self):
559 '''re-index the whole database'''
561 m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
562 m['add'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
563 m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
564 return self.do_modify(m, [], 're-indexed database', validate=False)