s4-dbcheck: Allow forcing an override of an old @MODULES record
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / dbchecker.py
blob91ae0b68ea6308d829261c6cbe28fea4f078cd09
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/>.
20 import ldb
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):
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
51 self.fix_rmd_flags = False
52 self.seize_fsmo_role = False
53 self.move_to_lost_and_found = False
54 self.fix_instancetype = False
55 self.in_transaction = in_transaction
56 self.infrastructure_dn = ldb.Dn(samdb, "CN=Infrastructure," + samdb.domain_dn())
57 self.naming_dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn())
58 self.schema_dn = samdb.get_schema_basedn()
59 self.rid_dn = ldb.Dn(samdb, "CN=RID Manager$,CN=System," + samdb.domain_dn())
60 self.ntds_dsa = samdb.get_dsServiceName()
62 res = self.samdb.search(base=self.ntds_dsa, scope=ldb.SCOPE_BASE, attrs=['msDS-hasMasterNCs'])
63 if "msDS-hasMasterNCs" in res[0]:
64 self.write_ncs = res[0]["msDS-hasMasterNCs"]
65 else:
66 self.write_ncs = None
68 def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
69 '''perform a database check, returning the number of errors found'''
71 res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
72 self.report('Checking %u objects' % len(res))
73 error_count = 0
75 for object in res:
76 error_count += self.check_object(object.dn, attrs=attrs)
78 if DN is None:
79 error_count += self.check_rootdse()
81 if error_count != 0 and not self.fix:
82 self.report("Please use --fix to fix these errors")
84 self.report('Checked %u objects (%u errors)' % (len(res), error_count))
85 return error_count
87 def report(self, msg):
88 '''print a message unless quiet is set'''
89 if not self.quiet:
90 print(msg)
92 def confirm(self, msg, allow_all=False, forced=False):
93 '''confirm a change'''
94 if not self.fix:
95 return False
96 if self.quiet:
97 return self.yes
98 if self.yes:
99 forced = True
100 return common.confirm(msg, forced=forced, allow_all=allow_all)
102 ################################################################
103 # a local confirm function with support for 'all'
104 def confirm_all(self, msg, all_attr):
105 '''confirm a change with support for "all" '''
106 if not self.fix:
107 return False
108 if self.quiet:
109 return self.yes
110 if getattr(self, all_attr) == 'NONE':
111 return False
112 if getattr(self, all_attr) == 'ALL':
113 forced = True
114 else:
115 forced = self.yes
116 c = common.confirm(msg, forced=forced, allow_all=True)
117 if c == 'ALL':
118 setattr(self, all_attr, 'ALL')
119 return True
120 if c == 'NONE':
121 setattr(self, all_attr, 'NONE')
122 return False
123 return c
125 def do_modify(self, m, controls, msg, validate=True):
126 '''perform a modify with optional verbose output'''
127 if self.verbose:
128 self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
129 try:
130 controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
131 self.samdb.modify(m, controls=controls, validate=validate)
132 except Exception, err:
133 self.report("%s : %s" % (msg, err))
134 return False
135 return True
137 def do_rename(self, from_dn, to_rdn, to_base, controls, msg):
138 '''perform a modify with optional verbose output'''
139 if self.verbose:
140 self.report("""dn: %s
141 changeType: modrdn
142 newrdn: %s
143 deleteOldRdn: 1
144 newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
145 try:
146 to_dn = to_rdn + to_base
147 controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
148 self.samdb.rename(from_dn, to_dn, controls=controls)
149 except Exception, err:
150 self.report("%s : %s" % (msg, err))
151 return False
152 return True
154 def err_empty_attribute(self, dn, attrname):
155 '''fix empty attributes'''
156 self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
157 if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
158 self.report("Not fixing empty attribute %s" % attrname)
159 return
161 m = ldb.Message()
162 m.dn = dn
163 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
164 if self.do_modify(m, ["relax:0", "show_recycled:1"],
165 "Failed to remove empty attribute %s" % attrname, validate=False):
166 self.report("Removed empty attribute %s" % attrname)
168 def err_normalise_mismatch(self, dn, attrname, values):
169 '''fix attribute normalisation errors'''
170 self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
171 mod_list = []
172 for val in values:
173 normalised = self.samdb.dsdb_normalise_attributes(
174 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)
183 return
185 m = ldb.Message()
186 m.dn = dn
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)
190 if nval != '':
191 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD,
192 attrname)
194 if self.do_modify(m, ["relax:0", "show_recycled:1"],
195 "Failed to normalise attribute %s" % attrname,
196 validate=False):
197 self.report("Normalised attribute %s" % attrname)
199 def err_normalise_mismatch_replace(self, dn, attrname, values):
200 '''fix attribute normalisation errors'''
201 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, values)
202 self.report("ERROR: Normalisation error for attribute '%s' in '%s'" % (attrname, dn))
203 self.report("Values/Order of values do/does not match: %s/%s!" % (values, list(normalised)))
204 if list(normalised) == values:
205 return
206 if not self.confirm_all("Fix normalisation for '%s' from '%s'?" % (attrname, dn), 'fix_all_normalisation'):
207 self.report("Not fixing attribute '%s'" % attrname)
208 return
210 m = ldb.Message()
211 m.dn = dn
212 m[attrname] = ldb.MessageElement(normalised, ldb.FLAG_MOD_REPLACE, attrname)
214 if self.do_modify(m, ["relax:0", "show_recycled:1"],
215 "Failed to normalise attribute %s" % attrname,
216 validate=False):
217 self.report("Normalised attribute %s" % attrname)
219 def is_deleted_objects_dn(self, dsdb_dn):
220 '''see if a dsdb_Dn is the special Deleted Objects DN'''
221 return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
223 def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
224 """handle a DN pointing to a deleted object"""
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 link?', '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_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
234 "Failed to remove deleted DN attribute %s" % attrname):
235 self.report("Removed deleted DN on attribute %s" % attrname)
237 def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
238 """handle a missing target DN (both GUID and DN string form are missing)"""
239 # check if its a backlink
240 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
241 if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1:
242 self.report("Not removing dangling forward link")
243 return
244 self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
246 def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
247 """handle a missing GUID extended DN component"""
248 self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
249 controls=["extended_dn:1:1", "show_recycled:1"]
250 try:
251 res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
252 attrs=[], controls=controls)
253 except ldb.LdbError, (enum, estr):
254 self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
255 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
256 return
257 if len(res) == 0:
258 self.report("unable to find object for DN %s" % dsdb_dn.dn)
259 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
260 return
261 dsdb_dn.dn = res[0].dn
263 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
264 self.report("Not fixing %s" % errstr)
265 return
266 m = ldb.Message()
267 m.dn = dn
268 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
269 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
271 if self.do_modify(m, ["show_recycled:1"],
272 "Failed to fix %s on attribute %s" % (errstr, attrname)):
273 self.report("Fixed %s on attribute %s" % (errstr, attrname))
275 def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
276 """handle a DN string being incorrect"""
277 self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
278 dsdb_dn.dn = correct_dn
280 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
281 self.report("Not fixing %s" % errstr)
282 return
283 m = ldb.Message()
284 m.dn = dn
285 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
286 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
287 if self.do_modify(m, ["show_recycled:1"],
288 "Failed to fix incorrect DN string on attribute %s" % attrname):
289 self.report("Fixed incorrect DN string on attribute %s" % (attrname))
291 def err_unknown_attribute(self, obj, attrname):
292 '''handle an unknown attribute error'''
293 self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
294 if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
295 self.report("Not removing %s" % attrname)
296 return
297 m = ldb.Message()
298 m.dn = obj.dn
299 m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
300 if self.do_modify(m, ["relax:0", "show_recycled:1"],
301 "Failed to remove unknown attribute %s" % attrname):
302 self.report("Removed unknown attribute %s" % (attrname))
304 def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
305 '''handle a missing backlink value'''
306 self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
307 if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
308 self.report("Not fixing missing backlink %s" % backlink_name)
309 return
310 m = ldb.Message()
311 m.dn = obj.dn
312 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
313 m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
314 if self.do_modify(m, ["show_recycled:1"],
315 "Failed to fix missing backlink %s" % backlink_name):
316 self.report("Fixed missing backlink %s" % (backlink_name))
318 def err_incorrect_rmd_flags(self, obj, attrname, revealed_dn):
319 '''handle a incorrect RMD_FLAGS value'''
320 rmd_flags = int(revealed_dn.dn.get_extended_component("RMD_FLAGS"))
321 self.report("ERROR: incorrect RMD_FLAGS value %u for attribute '%s' in %s for link %s" % (rmd_flags, attrname, obj.dn, revealed_dn.dn.extended_str()))
322 if not self.confirm_all('Fix incorrect RMD_FLAGS %u' % rmd_flags, 'fix_rmd_flags'):
323 self.report("Not fixing incorrect RMD_FLAGS %u" % rmd_flags)
324 return
325 m = ldb.Message()
326 m.dn = obj.dn
327 m['old_value'] = ldb.MessageElement(str(revealed_dn), ldb.FLAG_MOD_DELETE, attrname)
328 if self.do_modify(m, ["show_recycled:1", "reveal_internals:0", "show_deleted:0"],
329 "Failed to fix incorrect RMD_FLAGS %u" % rmd_flags):
330 self.report("Fixed incorrect RMD_FLAGS %u" % (rmd_flags))
332 def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
333 '''handle a orphaned backlink value'''
334 self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
335 if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
336 self.report("Not removing orphaned backlink %s" % link_name)
337 return
338 m = ldb.Message()
339 m.dn = obj.dn
340 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
341 if self.do_modify(m, ["show_recycled:1", "relax:0"],
342 "Failed to fix orphaned backlink %s" % link_name):
343 self.report("Fixed orphaned backlink %s" % (link_name))
345 def err_no_fsmoRoleOwner(self, obj):
346 '''handle a missing fSMORoleOwner'''
347 self.report("ERROR: fSMORoleOwner not found for role %s" % (obj.dn))
348 res = self.samdb.search("",
349 scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
350 assert len(res) == 1
351 serviceName = res[0]["dsServiceName"][0]
352 if not self.confirm_all('Sieze role %s onto current DC by adding fSMORoleOwner=%s' % (obj.dn, serviceName), 'seize_fsmo_role'):
353 self.report("Not Siezing role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
354 return
355 m = ldb.Message()
356 m.dn = obj.dn
357 m['value'] = ldb.MessageElement(serviceName, ldb.FLAG_MOD_ADD, 'fSMORoleOwner')
358 if self.do_modify(m, [],
359 "Failed to sieze role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName)):
360 self.report("Siezed role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
362 def err_missing_parent(self, obj):
363 '''handle a missing parent'''
364 self.report("ERROR: parent object not found for %s" % (obj.dn))
365 if not self.confirm_all('Move object %s into LostAndFound?' % (obj.dn), 'move_to_lost_and_found'):
366 self.report('Not moving object %s into LostAndFound' % (obj.dn))
367 return
369 keep_transaction = True
370 self.samdb.transaction_start()
371 try:
372 nc_root = self.samdb.get_nc_root(obj.dn);
373 lost_and_found = self.samdb.get_wellknown_dn(nc_root, dsdb.DS_GUID_LOSTANDFOUND_CONTAINER)
374 new_dn = ldb.Dn(self.samdb, str(obj.dn))
375 new_dn.remove_base_components(len(new_dn) - 1)
376 if self.do_rename(obj.dn, new_dn, lost_and_found, ["show_deleted:0", "relax:0"],
377 "Failed to rename object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found)):
378 self.report("Renamed object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found))
380 m = ldb.Message()
381 m.dn = obj.dn
382 m['lastKnownParent'] = ldb.MessageElement(str(obj.dn.parent()), ldb.FLAG_MOD_REPLACE, 'lastKnownParent')
384 if self.do_modify(m, [],
385 "Failed to set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found)):
386 self.report("Set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found))
387 keep_transaction = True
388 except:
389 self.samdb.transaction_cancel()
390 raise
392 if keep_transaction:
393 self.samdb.transaction_commit()
394 else:
395 self.samdb.transaction_cancel()
398 def err_wrong_instancetype(self, obj, calculated_instancetype):
399 '''handle a wrong instanceType'''
400 self.report("ERROR: wrong instanceType %s on %s, should be %d" % (obj["instanceType"], obj.dn, calculated_instancetype))
401 if not self.confirm_all('Change instanceType from %s to %d on %s?' % (obj["instanceType"], calculated_instancetype, obj.dn), 'fix_instancetype'):
402 self.report('Not changing instanceType from %s to %d on %s' % (obj["instanceType"], calculated_instancetype, obj.dn))
403 return
405 m = ldb.Message()
406 m.dn = obj.dn
407 m['value'] = ldb.MessageElement(str(calculated_instancetype), ldb.FLAG_MOD_REPLACE, 'instanceType')
408 if self.do_modify(m, ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK_MODIFY_RO_REPLICA],
409 "Failed to correct missing instanceType on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype)):
410 self.report("Corrected instancetype on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype))
412 def find_revealed_link(self, dn, attrname, guid):
413 '''return a revealed link in an object'''
414 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[attrname],
415 controls=["show_deleted:0", "extended_dn:0", "reveal_internals:0"])
416 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
417 for val in res[0][attrname]:
418 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
419 guid2 = dsdb_dn.dn.get_extended_component("GUID")
420 if guid == guid2:
421 return dsdb_dn
422 return None
424 def check_dn(self, obj, attrname, syntax_oid):
425 '''check a DN attribute for correctness'''
426 error_count = 0
427 for val in obj[attrname]:
428 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
430 # all DNs should have a GUID component
431 guid = dsdb_dn.dn.get_extended_component("GUID")
432 if guid is None:
433 error_count += 1
434 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn,
435 "missing GUID")
436 continue
438 guidstr = str(misc.GUID(guid))
440 attrs = ['isDeleted']
441 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
442 reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
443 if reverse_link_name is not None:
444 attrs.append(reverse_link_name)
446 # check its the right GUID
447 try:
448 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
449 attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
450 except ldb.LdbError, (enum, estr):
451 error_count += 1
452 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
453 continue
455 # now we have two cases - the source object might or might not be deleted
456 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
457 target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
459 # the target DN is not allowed to be deleted, unless the target DN is the
460 # special Deleted Objects container
461 if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
462 error_count += 1
463 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
464 continue
466 # check the DN matches in string form
467 if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
468 error_count += 1
469 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
470 res[0].dn, "incorrect string version of DN")
471 continue
473 if is_deleted and not target_is_deleted and reverse_link_name is not None:
474 revealed_dn = self.find_revealed_link(obj.dn, attrname, guid)
475 rmd_flags = revealed_dn.dn.get_extended_component("RMD_FLAGS")
476 if rmd_flags is not None and (int(rmd_flags) & 1) == 0:
477 # the RMD_FLAGS for this link should be 1, as the target is deleted
478 self.err_incorrect_rmd_flags(obj, attrname, revealed_dn)
479 continue
481 # check the reverse_link is correct if there should be one
482 if reverse_link_name is not None:
483 match_count = 0
484 if reverse_link_name in res[0]:
485 for v in res[0][reverse_link_name]:
486 if v == obj.dn.extended_str():
487 match_count += 1
488 if match_count != 1:
489 error_count += 1
490 if linkID & 1:
491 self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
492 else:
493 self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
494 continue
496 return error_count
499 def get_originating_time(self, val, attid):
500 '''Read metadata properties and return the originating time for
501 a given attributeId.
503 :return: the originating time or 0 if not found
506 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
507 obj = repl.ctr
509 for o in repl.ctr.array:
510 if o.attid == attid:
511 return o.originating_change_time
513 return 0
515 def process_metadata(self, val):
516 '''Read metadata properties and list attributes in it'''
518 list_att = []
520 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
521 obj = repl.ctr
523 for o in repl.ctr.array:
524 att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
525 list_att.append(att.lower())
527 return list_att
530 def fix_metadata(self, dn, attr):
531 '''re-write replPropertyMetaData elements for a single attribute for a
532 object. This is used to fix missing replPropertyMetaData elements'''
533 res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
534 controls = ["search_options:1:2", "show_recycled:1"])
535 msg = res[0]
536 nmsg = ldb.Message()
537 nmsg.dn = dn
538 nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
539 if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
540 "Failed to fix metadata for attribute %s" % attr):
541 self.report("Fixed metadata for attribute %s" % attr)
543 def is_fsmo_role(self, dn):
544 if dn == self.samdb.domain_dn:
545 return True
546 if dn == self.infrastructure_dn:
547 return True
548 if dn == self.naming_dn:
549 return True
550 if dn == self.schema_dn:
551 return True
552 if dn == self.rid_dn:
553 return True
555 return False
557 def calculate_instancetype(self, dn):
558 instancetype = 0
559 nc_root = self.samdb.get_nc_root(dn)
560 if dn == nc_root:
561 instancetype |= dsdb.INSTANCE_TYPE_IS_NC_HEAD
562 try:
563 self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE, attrs=[], controls=["show_recycled:1"])
564 except ldb.LdbError, (enum, estr):
565 if enum != ldb.ERR_NO_SUCH_OBJECT:
566 raise
567 else:
568 instancetype |= dsdb.INSTANCE_TYPE_NC_ABOVE
570 if self.write_ncs is not None and str(nc_root) in self.write_ncs:
571 instancetype |= dsdb.INSTANCE_TYPE_WRITE
573 return instancetype
575 def check_object(self, dn, attrs=['*']):
576 '''check one object'''
577 if self.verbose:
578 self.report("Checking object %s" % dn)
579 if '*' in attrs:
580 attrs.append("replPropertyMetaData")
582 try:
583 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
584 controls=["extended_dn:1:1", "show_recycled:1", "show_deleted:1"],
585 attrs=attrs)
586 except ldb.LdbError, (enum, estr):
587 if enum == ldb.ERR_NO_SUCH_OBJECT:
588 if self.in_transaction:
589 self.report("ERROR: Object %s disappeared during check" % dn)
590 return 1
591 return 0
592 raise
593 if len(res) != 1:
594 self.report("ERROR: Object %s failed to load during check" % dn)
595 return 1
596 obj = res[0]
597 error_count = 0
598 list_attrs_from_md = []
599 list_attrs_seen = []
600 got_repl_property_meta_data = False
602 for attrname in obj:
603 if attrname == 'dn':
604 continue
606 if str(attrname).lower() == 'replpropertymetadata':
607 list_attrs_from_md = self.process_metadata(obj[attrname])
608 got_repl_property_meta_data = True
609 continue
611 if str(attrname).lower() == 'objectclass':
612 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, list(obj[attrname]))
613 if list(normalised) != list(obj[attrname]):
614 self.err_normalise_mismatch_replace(dn, attrname, list(obj[attrname]))
615 error_count += 1
616 continue
618 # check for empty attributes
619 for val in obj[attrname]:
620 if val == '':
621 self.err_empty_attribute(dn, attrname)
622 error_count += 1
623 continue
625 # get the syntax oid for the attribute, so we can can have
626 # special handling for some specific attribute types
627 try:
628 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
629 except Exception, msg:
630 self.err_unknown_attribute(obj, attrname)
631 error_count += 1
632 continue
634 flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
635 if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
636 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
637 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
638 list_attrs_seen.append(str(attrname).lower())
640 if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
641 dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
642 # it's some form of DN, do specialised checking on those
643 error_count += self.check_dn(obj, attrname, syntax_oid)
645 # check for incorrectly normalised attributes
646 for val in obj[attrname]:
647 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
648 if len(normalised) != 1 or normalised[0] != val:
649 self.err_normalise_mismatch(dn, attrname, obj[attrname])
650 error_count += 1
651 break
653 if str(attrname).lower() == "instancetype":
654 calculated_instancetype = self.calculate_instancetype(dn)
655 if len(obj["instanceType"]) != 1 or obj["instanceType"][0] != str(calculated_instancetype):
656 self.err_wrong_instancetype(obj, calculated_instancetype)
658 show_dn = True
659 if got_repl_property_meta_data:
660 rdn = (str(dn).split(","))[0]
661 if rdn == "CN=Deleted Objects":
662 isDeletedAttId = 131120
663 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
665 expectedTimeDo = 2650466015990000000
666 originating = self.get_originating_time(obj["replPropertyMetaData"], isDeletedAttId)
667 if originating != expectedTimeDo:
668 if self.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn), 'fix_time_metadata'):
669 nmsg = ldb.Message()
670 nmsg.dn = dn
671 nmsg["isDeleted"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isDeleted")
672 error_count += 1
673 self.samdb.modify(nmsg, controls=["provision:0"])
675 else:
676 self.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn))
677 for att in list_attrs_seen:
678 if not att in list_attrs_from_md:
679 if show_dn:
680 self.report("On object %s" % dn)
681 show_dn = False
682 error_count += 1
683 self.report("ERROR: Attribute %s not present in replication metadata" % att)
684 if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
685 self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
686 continue
687 self.fix_metadata(dn, att)
689 if self.is_fsmo_role(dn):
690 if "fSMORoleOwner" not in obj:
691 self.err_no_fsmoRoleOwner(obj)
692 error_count += 1
694 try:
695 if dn != self.samdb.get_root_basedn():
696 res = self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE,
697 controls=["show_recycled:1", "show_deleted:1"])
698 except ldb.LdbError, (enum, estr):
699 if enum == ldb.ERR_NO_SUCH_OBJECT:
700 self.err_missing_parent(obj)
701 error_count += 1
702 else:
703 raise
705 return error_count
707 ################################################################
708 # check special @ROOTDSE attributes
709 def check_rootdse(self):
710 '''check the @ROOTDSE special object'''
711 dn = ldb.Dn(self.samdb, '@ROOTDSE')
712 if self.verbose:
713 self.report("Checking object %s" % dn)
714 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
715 if len(res) != 1:
716 self.report("Object %s disappeared during check" % dn)
717 return 1
718 obj = res[0]
719 error_count = 0
721 # check that the dsServiceName is in GUID form
722 if not 'dsServiceName' in obj:
723 self.report('ERROR: dsServiceName missing in @ROOTDSE')
724 return error_count+1
726 if not obj['dsServiceName'][0].startswith('<GUID='):
727 self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
728 error_count += 1
729 if not self.confirm('Change dsServiceName to GUID form?'):
730 return error_count
731 res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
732 scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
733 guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
734 m = ldb.Message()
735 m.dn = dn
736 m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
737 ldb.FLAG_MOD_REPLACE, 'dsServiceName')
738 if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
739 self.report("Changed dsServiceName to GUID form")
740 return error_count
743 ###############################################
744 # re-index the database
745 def reindex_database(self):
746 '''re-index the whole database'''
747 m = ldb.Message()
748 m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
749 m['add'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
750 m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
751 return self.do_modify(m, [], 're-indexed database', validate=False)
753 ###############################################
754 # reset @MODULES
755 def reset_modules(self):
756 '''reset @MODULES to that needed for current sam.ldb (to read a very old database)'''
757 m = ldb.Message()
758 m.dn = ldb.Dn(self.samdb, "@MODULES")
759 m['@LIST'] = ldb.MessageElement('samba_dsdb', ldb.FLAG_MOD_REPLACE, '@LIST')
760 return self.do_modify(m, [], 'reset @MODULES on database', validate=False)