samba-tool: allow dbcheck to correct the originating_change_time of the deleted objec...
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / dbchecker.py
blob6792538f7583d4862a9b33f3e675baef97e48c19
1 #!/usr/bin/env python
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/>.
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 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, quiet=False):
34 self.samdb = samdb
35 self.dict_oid_name = None
36 self.samdb_schema = (samdb_schema or samdb)
37 self.verbose = verbose
38 self.fix = fix
39 self.yes = yes
40 self.quiet = quiet
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
52 def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
53 '''perform a database check, returning the number of errors found'''
55 res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
56 self.report('Checking %u objects' % len(res))
57 error_count = 0
59 for object in res:
60 error_count += self.check_object(object.dn, attrs=attrs)
62 if DN is None:
63 error_count += self.check_rootdse()
65 if error_count != 0 and not self.fix:
66 self.report("Please use --fix to fix these errors")
69 self.report('Checked %u objects (%u errors)' % (len(res), error_count))
71 return error_count
74 def report(self, msg):
75 '''print a message unless quiet is set'''
76 if not self.quiet:
77 print(msg)
80 ################################################################
81 # a local confirm function that obeys the --fix and --yes options
82 def confirm(self, msg, allow_all=False, forced=False):
83 '''confirm a change'''
84 if not self.fix:
85 return False
86 if self.quiet:
87 return self.yes
88 if self.yes:
89 forced = True
90 return common.confirm(msg, forced=forced, allow_all=allow_all)
92 ################################################################
93 # a local confirm function with support for 'all'
94 def confirm_all(self, msg, all_attr):
95 '''confirm a change with support for "all" '''
96 if not self.fix:
97 return False
98 if self.quiet:
99 return self.yes
100 if getattr(self, all_attr) == 'NONE':
101 return False
102 if getattr(self, all_attr) == 'ALL':
103 forced = True
104 else:
105 forced = self.yes
106 c = common.confirm(msg, forced=forced, allow_all=True)
107 if c == 'ALL':
108 setattr(self, all_attr, 'ALL')
109 return True
110 if c == 'NONE':
111 setattr(self, all_attr, 'NONE')
112 return True
113 return c
116 def do_modify(self, m, controls, msg, validate=True):
117 '''perform a modify with optional verbose output'''
118 if self.verbose:
119 self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
120 try:
121 self.samdb.modify(m, controls=controls, validate=validate)
122 except Exception, err:
123 self.report("%s : %s" % (msg, err))
124 return False
125 return True
128 ################################################################
129 # handle empty attributes
130 def err_empty_attribute(self, dn, attrname):
131 '''fix empty attributes'''
132 self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
133 if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
134 self.report("Not fixing empty attribute %s" % attrname)
135 return
137 m = ldb.Message()
138 m.dn = dn
139 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
140 if self.do_modify(m, ["relax:0", "show_recycled:1"],
141 "Failed to remove empty attribute %s" % attrname, validate=False):
142 self.report("Removed empty attribute %s" % attrname)
145 ################################################################
146 # handle normalisation mismatches
147 def err_normalise_mismatch(self, dn, attrname, values):
148 '''fix attribute normalisation errors'''
149 self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
150 mod_list = []
151 for val in values:
152 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
153 if len(normalised) != 1:
154 self.report("Unable to normalise value '%s'" % val)
155 mod_list.append((val, ''))
156 elif (normalised[0] != val):
157 self.report("value '%s' should be '%s'" % (val, normalised[0]))
158 mod_list.append((val, normalised[0]))
159 if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
160 self.report("Not fixing attribute %s" % attrname)
161 return
163 m = ldb.Message()
164 m.dn = dn
165 for i in range(0, len(mod_list)):
166 (val, nval) = mod_list[i]
167 m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
168 if nval != '':
169 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD, attrname)
171 if self.do_modify(m, ["relax:0", "show_recycled:1"],
172 "Failed to normalise attribute %s" % attrname,
173 validate=False):
174 self.report("Normalised attribute %s" % attrname)
176 def is_deleted_objects_dn(self, dsdb_dn):
177 '''see if a dsdb_Dn is the special Deleted Objects DN'''
178 return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
181 ################################################################
182 # handle a DN pointing to a deleted object
183 def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
184 self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
185 self.report("Target GUID points at deleted DN %s" % correct_dn)
186 if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
187 self.report("Not removing")
188 return
189 m = ldb.Message()
190 m.dn = dn
191 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
192 if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
193 "Failed to remove deleted DN attribute %s" % attrname):
194 self.report("Removed deleted DN on attribute %s" % attrname)
196 ################################################################
197 # handle a missing target DN (both GUID and DN string form are missing)
198 def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
199 # check if its a backlink
200 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
201 if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1:
202 self.report("Not removing dangling forward link")
203 return
204 self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
207 ################################################################
208 # handle a missing GUID extended DN component
209 def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
210 self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
211 controls=["extended_dn:1:1", "show_recycled:1"]
212 try:
213 res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
214 attrs=[], controls=controls)
215 except ldb.LdbError, (enum, estr):
216 self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
217 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
218 return
219 if len(res) == 0:
220 self.report("unable to find object for DN %s" % dsdb_dn.dn)
221 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
222 return
223 dsdb_dn.dn = res[0].dn
225 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
226 self.report("Not fixing %s" % errstr)
227 return
228 m = ldb.Message()
229 m.dn = dn
230 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
231 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
233 if self.do_modify(m, ["show_recycled:1"],
234 "Failed to fix %s on attribute %s" % (errstr, attrname)):
235 self.report("Fixed %s on attribute %s" % (errstr, attrname))
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
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_recycled:1"],
252 "Failed to fix incorrect DN string on attribute %s" % attrname):
253 self.report("Fixed incorrect DN string on attribute %s" % (attrname))
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_recycled:1"],
267 "Failed to remove unknown attribute %s" % attrname):
268 self.report("Removed unknown attribute %s" % (attrname))
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_recycled:1"],
284 "Failed to fix missing backlink %s" % backlink_name):
285 self.report("Fixed missing backlink %s" % (backlink_name))
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_recycled:1", "relax:0"],
300 "Failed to fix orphaned backlink %s" % link_name):
301 self.report("Fixed orphaned backlink %s" % (link_name))
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)
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
319 guidstr = str(misc.GUID(guid))
321 attrs=['isDeleted']
322 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
323 reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
324 if reverse_link_name is not None:
325 attrs.append(reverse_link_name)
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_recycled: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
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'
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
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
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 linkID & 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
369 return error_count
372 def get_originating_time(self, val, attid):
373 '''Read metadata properties and return the originating time for
374 a given attributeId.
376 :return: the originating time or 0 if not found
379 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
380 obj = repl.ctr
382 for o in repl.ctr.array:
383 if o.attid == attid:
384 return o.originating_change_time
386 return 0
388 def process_metadata(self, val):
389 '''Read metadata properties and list attributes in it'''
391 list_att = []
393 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
394 obj = repl.ctr
396 for o in repl.ctr.array:
397 att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
398 list_att.append(att.lower())
400 return list_att
403 def fix_metadata(self, dn, attr):
404 '''re-write replPropertyMetaData elements for a single attribute for a
405 object. This is used to fix missing replPropertyMetaData elements'''
406 res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
407 controls = ["search_options:1:2", "show_recycled:1"])
408 msg = res[0]
409 nmsg = ldb.Message()
410 nmsg.dn = dn
411 nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
412 if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
413 "Failed to fix metadata for attribute %s" % attr):
414 self.report("Fixed metadata for attribute %s" % attr)
417 ################################################################
418 # check one object - calls to individual error handlers above
419 def check_object(self, dn, attrs=['*']):
420 '''check one object'''
421 if self.verbose:
422 self.report("Checking object %s" % dn)
423 if '*' in attrs:
424 attrs.append("replPropertyMetaData")
426 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
427 controls=["extended_dn:1:1", "show_recycled:1", "show_deleted:1"],
428 attrs=attrs)
429 if len(res) != 1:
430 self.report("Object %s disappeared during check" % dn)
431 return 1
432 obj = res[0]
433 error_count = 0
434 list_attrs_from_md = []
435 list_attrs_seen = []
436 got_repl_property_meta_data = False
438 for attrname in obj:
439 if attrname == 'dn':
440 continue
442 if str(attrname).lower() == 'replpropertymetadata':
443 list_attrs_from_md = self.process_metadata(obj[attrname])
444 got_repl_property_meta_data = True
445 continue
448 # check for empty attributes
449 for val in obj[attrname]:
450 if val == '':
451 self.err_empty_attribute(dn, attrname)
452 error_count += 1
453 continue
455 # get the syntax oid for the attribute, so we can can have
456 # special handling for some specific attribute types
457 try:
458 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
459 except Exception, msg:
460 self.err_unknown_attribute(obj, attrname)
461 error_count += 1
462 continue
464 flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
465 if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
466 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
467 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
468 list_attrs_seen.append(str(attrname).lower())
470 if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
471 dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
472 # it's some form of DN, do specialised checking on those
473 error_count += self.check_dn(obj, attrname, syntax_oid)
475 # check for incorrectly normalised attributes
476 for val in obj[attrname]:
477 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
478 if len(normalised) != 1 or normalised[0] != val:
479 self.err_normalise_mismatch(dn, attrname, obj[attrname])
480 error_count += 1
481 break
483 show_dn = True
484 if got_repl_property_meta_data:
485 rdn = (str(dn).split(","))[0]
486 if rdn == "CN=Deleted Objects":
487 isDeletedAttId = 131120
488 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
490 expectedTimeDo = 2650466015990000000
491 originating = self.get_originating_time(obj["replPropertyMetaData"], isDeletedAttId)
492 if originating != expectedTimeDo:
493 if self.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn), 'fix_time_metadata'):
494 nmsg = ldb.Message()
495 nmsg.dn = dn
496 nmsg["isDeleted"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isDeleted")
497 error_count += 1
498 self.samdb.modify(nmsg, controls=["provision:0"])
500 else:
501 self.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn))
502 for att in list_attrs_seen:
503 if not att in list_attrs_from_md:
504 if show_dn:
505 self.report("On object %s" % dn)
506 show_dn = False
507 error_count += 1
508 self.report("ERROR: Attribute %s not present in replication metadata" % att)
509 if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
510 self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
511 continue
512 self.fix_metadata(dn, att)
514 return error_count
516 ################################################################
517 # check special @ROOTDSE attributes
518 def check_rootdse(self):
519 '''check the @ROOTDSE special object'''
520 dn = ldb.Dn(self.samdb, '@ROOTDSE')
521 if self.verbose:
522 self.report("Checking object %s" % dn)
523 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
524 if len(res) != 1:
525 self.report("Object %s disappeared during check" % dn)
526 return 1
527 obj = res[0]
528 error_count = 0
530 # check that the dsServiceName is in GUID form
531 if not 'dsServiceName' in obj:
532 self.report('ERROR: dsServiceName missing in @ROOTDSE')
533 return error_count+1
535 if not obj['dsServiceName'][0].startswith('<GUID='):
536 self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
537 error_count += 1
538 if not self.confirm('Change dsServiceName to GUID form?'):
539 return error_count
540 res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
541 scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
542 guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
543 m = ldb.Message()
544 m.dn = dn
545 m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
546 ldb.FLAG_MOD_REPLACE, 'dsServiceName')
547 if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
548 self.report("Changed dsServiceName to GUID form")
549 return error_count
552 ###############################################
553 # re-index the database
554 def reindex_database(self):
555 '''re-index the whole database'''
556 m = ldb.Message()
557 m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
558 m['add'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
559 m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
560 return self.do_modify(m, [], 're-indexed database', validate=False)