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
28 from samba.common import dsdb_Dn
30 class dbcheck(object):
31 """check a SAM database for errors"""
33 def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False, yes=False,
34 quiet=False, in_transaction=False):
36 self.dict_oid_name = None
37 self.samdb_schema = (samdb_schema or samdb)
38 self.verbose = verbose
42 self.remove_all_unknown_attributes = False
43 self.remove_all_empty_attributes = False
44 self.fix_all_normalisation = False
45 self.fix_all_DN_GUIDs = False
46 self.remove_all_deleted_DN_links = False
47 self.fix_all_target_mismatch = False
48 self.fix_all_metadata = False
49 self.fix_time_metadata = False
50 self.fix_all_missing_backlinks = False
51 self.fix_all_orphaned_backlinks = False
52 self.in_transaction = in_transaction
54 def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
55 '''perform a database check, returning the number of errors found'''
57 res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
58 self.report('Checking %u objects' % len(res))
62 error_count += self.check_object(object.dn, attrs=attrs)
65 error_count += self.check_rootdse()
67 if error_count != 0 and not self.fix:
68 self.report("Please use --fix to fix these errors")
71 self.report('Checked %u objects (%u errors)' % (len(res), error_count))
76 def report(self, msg):
77 '''print a message unless quiet is set'''
82 ################################################################
83 # a local confirm function that obeys the --fix and --yes options
84 def confirm(self, msg, allow_all=False, forced=False):
85 '''confirm a change'''
92 return common.confirm(msg, forced=forced, allow_all=allow_all)
94 ################################################################
95 # a local confirm function with support for 'all'
96 def confirm_all(self, msg, all_attr):
97 '''confirm a change with support for "all" '''
102 if getattr(self, all_attr) == 'NONE':
104 if getattr(self, all_attr) == 'ALL':
108 c = common.confirm(msg, forced=forced, allow_all=True)
110 setattr(self, all_attr, 'ALL')
113 setattr(self, all_attr, 'NONE')
118 def do_modify(self, m, controls, msg, validate=True):
119 '''perform a modify with optional verbose output'''
121 self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
123 self.samdb.modify(m, controls=controls, validate=validate)
124 except Exception, err:
125 self.report("%s : %s" % (msg, err))
130 ################################################################
131 # handle empty attributes
132 def err_empty_attribute(self, dn, attrname):
133 '''fix empty attributes'''
134 self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
135 if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
136 self.report("Not fixing empty attribute %s" % attrname)
141 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
142 if self.do_modify(m, ["relax:0", "show_recycled:1"],
143 "Failed to remove empty attribute %s" % attrname, validate=False):
144 self.report("Removed empty attribute %s" % attrname)
147 ################################################################
148 # handle normalisation mismatches
149 def err_normalise_mismatch(self, dn, attrname, values):
150 '''fix attribute normalisation errors'''
151 self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
154 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
155 if len(normalised) != 1:
156 self.report("Unable to normalise value '%s'" % val)
157 mod_list.append((val, ''))
158 elif (normalised[0] != val):
159 self.report("value '%s' should be '%s'" % (val, normalised[0]))
160 mod_list.append((val, normalised[0]))
161 if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
162 self.report("Not fixing attribute %s" % attrname)
167 for i in range(0, len(mod_list)):
168 (val, nval) = mod_list[i]
169 m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
171 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
173 if self.do_modify(m, ["relax:0", "show_recycled:1"],
174 "Failed to normalise attribute %s" % attrname,
176 self.report("Normalised attribute %s" % attrname)
178 def is_deleted_objects_dn(self, dsdb_dn):
179 '''see if a dsdb_Dn is the special Deleted Objects DN'''
180 return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
183 ################################################################
184 # handle a DN pointing to a deleted object
185 def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
186 self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
187 self.report("Target GUID points at deleted DN %s" % correct_dn)
188 if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
189 self.report("Not removing")
193 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
194 if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
195 "Failed to remove deleted DN attribute %s" % attrname):
196 self.report("Removed deleted DN on attribute %s" % attrname)
198 ################################################################
199 # handle a missing target DN (both GUID and DN string form are missing)
200 def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
201 # check if its a backlink
202 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
203 if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1:
204 self.report("Not removing dangling forward link")
206 self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
209 ################################################################
210 # handle a missing GUID extended DN component
211 def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
212 self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
213 controls=["extended_dn:1:1", "show_recycled:1"]
215 res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
216 attrs=[], controls=controls)
217 except ldb.LdbError, (enum, estr):
218 self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
219 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
222 self.report("unable to find object for DN %s" % dsdb_dn.dn)
223 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
225 dsdb_dn.dn = res[0].dn
227 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
228 self.report("Not fixing %s" % errstr)
232 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
233 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
235 if self.do_modify(m, ["show_recycled:1"],
236 "Failed to fix %s on attribute %s" % (errstr, attrname)):
237 self.report("Fixed %s on attribute %s" % (errstr, attrname))
240 ################################################################
241 # handle a DN string being incorrect
242 def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
243 self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
244 dsdb_dn.dn = correct_dn
246 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
247 self.report("Not fixing %s" % errstr)
251 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
252 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
253 if self.do_modify(m, ["show_recycled:1"],
254 "Failed to fix incorrect DN string on attribute %s" % attrname):
255 self.report("Fixed incorrect DN string on attribute %s" % (attrname))
257 ################################################################
258 # handle an unknown attribute error
259 def err_unknown_attribute(self, obj, attrname):
260 '''handle an unknown attribute error'''
261 self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
262 if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
263 self.report("Not removing %s" % attrname)
267 m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
268 if self.do_modify(m, ["relax:0", "show_recycled:1"],
269 "Failed to remove unknown attribute %s" % attrname):
270 self.report("Removed unknown attribute %s" % (attrname))
273 ################################################################
274 # handle a missing backlink
275 def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
276 '''handle a missing backlink value'''
277 self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
278 if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
279 self.report("Not fixing missing backlink %s" % backlink_name)
283 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
284 m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
285 if self.do_modify(m, ["show_recycled:1"],
286 "Failed to fix missing backlink %s" % backlink_name):
287 self.report("Fixed missing backlink %s" % (backlink_name))
290 ################################################################
291 # handle a orphaned backlink
292 def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
293 '''handle a orphaned backlink value'''
294 self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
295 if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
296 self.report("Not removing orphaned backlink %s" % link_name)
300 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
301 if self.do_modify(m, ["show_recycled:1", "relax:0"],
302 "Failed to fix orphaned backlink %s" % link_name):
303 self.report("Fixed orphaned backlink %s" % (link_name))
306 ################################################################
307 # specialised checking for a dn attribute
308 def check_dn(self, obj, attrname, syntax_oid):
309 '''check a DN attribute for correctness'''
311 for val in obj[attrname]:
312 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
314 # all DNs should have a GUID component
315 guid = dsdb_dn.dn.get_extended_component("GUID")
318 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "missing GUID")
321 guidstr = str(misc.GUID(guid))
324 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
325 reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
326 if reverse_link_name is not None:
327 attrs.append(reverse_link_name)
329 # check its the right GUID
331 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
332 attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
333 except ldb.LdbError, (enum, estr):
335 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
338 # now we have two cases - the source object might or might not be deleted
339 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
340 target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
342 # the target DN is not allowed to be deleted, unless the target DN is the
343 # special Deleted Objects container
344 if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
346 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
349 # check the DN matches in string form
350 if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
352 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
353 res[0].dn, "incorrect string version of DN")
356 # check the reverse_link is correct if there should be one
357 if reverse_link_name is not None:
359 if reverse_link_name in res[0]:
360 for v in res[0][reverse_link_name]:
361 if v == obj.dn.extended_str():
366 self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
368 self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
374 def get_originating_time(self, val, attid):
375 '''Read metadata properties and return the originating time for
378 :return: the originating time or 0 if not found
381 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
384 for o in repl.ctr.array:
386 return o.originating_change_time
390 def process_metadata(self, val):
391 '''Read metadata properties and list attributes in it'''
395 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
398 for o in repl.ctr.array:
399 att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
400 list_att.append(att.lower())
405 def fix_metadata(self, dn, attr):
406 '''re-write replPropertyMetaData elements for a single attribute for a
407 object. This is used to fix missing replPropertyMetaData elements'''
408 res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
409 controls = ["search_options:1:2", "show_recycled:1"])
413 nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
414 if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
415 "Failed to fix metadata for attribute %s" % attr):
416 self.report("Fixed metadata for attribute %s" % attr)
419 ################################################################
420 # check one object - calls to individual error handlers above
421 def check_object(self, dn, attrs=['*']):
422 '''check one object'''
424 self.report("Checking object %s" % dn)
426 attrs.append("replPropertyMetaData")
429 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
430 controls=["extended_dn:1:1", "show_recycled:1", "show_deleted:1"],
432 except ldb.LdbError, (enum, estr):
433 if enum == ldb.ERR_NO_SUCH_OBJECT:
434 if self.in_transaction:
435 self.report("ERROR: Object %s disappeared during check" % dn)
440 self.report("ERROR: Object %s failed to load during check" % dn)
444 list_attrs_from_md = []
446 got_repl_property_meta_data = False
452 if str(attrname).lower() == 'replpropertymetadata':
453 list_attrs_from_md = self.process_metadata(obj[attrname])
454 got_repl_property_meta_data = True
458 # check for empty attributes
459 for val in obj[attrname]:
461 self.err_empty_attribute(dn, attrname)
465 # get the syntax oid for the attribute, so we can can have
466 # special handling for some specific attribute types
468 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
469 except Exception, msg:
470 self.err_unknown_attribute(obj, attrname)
474 flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
475 if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
476 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
477 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
478 list_attrs_seen.append(str(attrname).lower())
480 if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
481 dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
482 # it's some form of DN, do specialised checking on those
483 error_count += self.check_dn(obj, attrname, syntax_oid)
485 # check for incorrectly normalised attributes
486 for val in obj[attrname]:
487 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
488 if len(normalised) != 1 or normalised[0] != val:
489 self.err_normalise_mismatch(dn, attrname, obj[attrname])
494 if got_repl_property_meta_data:
495 rdn = (str(dn).split(","))[0]
496 if rdn == "CN=Deleted Objects":
497 isDeletedAttId = 131120
498 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
500 expectedTimeDo = 2650466015990000000
501 originating = self.get_originating_time(obj["replPropertyMetaData"], isDeletedAttId)
502 if originating != expectedTimeDo:
503 if self.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn), 'fix_time_metadata'):
506 nmsg["isDeleted"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isDeleted")
508 self.samdb.modify(nmsg, controls=["provision:0"])
511 self.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn))
512 for att in list_attrs_seen:
513 if not att in list_attrs_from_md:
515 self.report("On object %s" % dn)
518 self.report("ERROR: Attribute %s not present in replication metadata" % att)
519 if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
520 self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
522 self.fix_metadata(dn, att)
526 ################################################################
527 # check special @ROOTDSE attributes
528 def check_rootdse(self):
529 '''check the @ROOTDSE special object'''
530 dn = ldb.Dn(self.samdb, '@ROOTDSE')
532 self.report("Checking object %s" % dn)
533 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
535 self.report("Object %s disappeared during check" % dn)
540 # check that the dsServiceName is in GUID form
541 if not 'dsServiceName' in obj:
542 self.report('ERROR: dsServiceName missing in @ROOTDSE')
545 if not obj['dsServiceName'][0].startswith('<GUID='):
546 self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
548 if not self.confirm('Change dsServiceName to GUID form?'):
550 res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
551 scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
552 guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
555 m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
556 ldb.FLAG_MOD_REPLACE, 'dsServiceName')
557 if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
558 self.report("Changed dsServiceName to GUID form")
562 ###############################################
563 # re-index the database
564 def reindex_database(self):
565 '''re-index the whole database'''
567 m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
568 m['add'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
569 m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
570 return self.do_modify(m, [], 're-indexed database', validate=False)