dbckecker: fix nTSecurityDescriptor values from before 4.0.0rc6 (bug #9481)
[Samba/gebeck_regimport.git] / source4 / scripting / python / samba / dbchecker.py
blob06fd82752f756c03955f726f66414bc92db1f15f
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, ndr_pack
25 from samba.dcerpc import drsblobs
26 from samba.common import dsdb_Dn
27 from samba.dcerpc import security
30 class dbcheck(object):
31 """check a SAM database for errors"""
33 def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False,
34 yes=False, quiet=False, in_transaction=False):
35 self.samdb = samdb
36 self.dict_oid_name = None
37 self.samdb_schema = (samdb_schema or samdb)
38 self.verbose = verbose
39 self.fix = fix
40 self.yes = yes
41 self.quiet = quiet
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.fix_rmd_flags = False
53 self.fix_ntsecuritydescriptor = False
54 self.seize_fsmo_role = False
55 self.move_to_lost_and_found = False
56 self.fix_instancetype = False
57 self.in_transaction = in_transaction
58 self.infrastructure_dn = ldb.Dn(samdb, "CN=Infrastructure," + samdb.domain_dn())
59 self.naming_dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn())
60 self.schema_dn = samdb.get_schema_basedn()
61 self.rid_dn = ldb.Dn(samdb, "CN=RID Manager$,CN=System," + samdb.domain_dn())
62 self.ntds_dsa = samdb.get_dsServiceName()
63 self.class_schemaIDGUID = {}
65 res = self.samdb.search(base=self.ntds_dsa, scope=ldb.SCOPE_BASE, attrs=['msDS-hasMasterNCs', 'hasMasterNCs'])
66 if "msDS-hasMasterNCs" in res[0]:
67 self.write_ncs = res[0]["msDS-hasMasterNCs"]
68 else:
69 # If the Forest Level is less than 2003 then there is no
70 # msDS-hasMasterNCs, so we fall back to hasMasterNCs
71 # no need to merge as all the NCs that are in hasMasterNCs must
72 # also be in msDS-hasMasterNCs (but not the opposite)
73 if "hasMasterNCs" in res[0]:
74 self.write_ncs = res[0]["hasMasterNCs"]
75 else:
76 self.write_ncs = None
79 def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
80 '''perform a database check, returning the number of errors found'''
82 res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
83 self.report('Checking %u objects' % len(res))
84 error_count = 0
86 for object in res:
87 error_count += self.check_object(object.dn, attrs=attrs)
89 if DN is None:
90 error_count += self.check_rootdse()
92 if error_count != 0 and not self.fix:
93 self.report("Please use --fix to fix these errors")
95 self.report('Checked %u objects (%u errors)' % (len(res), error_count))
96 return error_count
98 def report(self, msg):
99 '''print a message unless quiet is set'''
100 if not self.quiet:
101 print(msg)
103 def confirm(self, msg, allow_all=False, forced=False):
104 '''confirm a change'''
105 if not self.fix:
106 return False
107 if self.quiet:
108 return self.yes
109 if self.yes:
110 forced = True
111 return common.confirm(msg, forced=forced, allow_all=allow_all)
113 ################################################################
114 # a local confirm function with support for 'all'
115 def confirm_all(self, msg, all_attr):
116 '''confirm a change with support for "all" '''
117 if not self.fix:
118 return False
119 if self.quiet:
120 return self.yes
121 if getattr(self, all_attr) == 'NONE':
122 return False
123 if getattr(self, all_attr) == 'ALL':
124 forced = True
125 else:
126 forced = self.yes
127 c = common.confirm(msg, forced=forced, allow_all=True)
128 if c == 'ALL':
129 setattr(self, all_attr, 'ALL')
130 return True
131 if c == 'NONE':
132 setattr(self, all_attr, 'NONE')
133 return False
134 return c
136 def do_modify(self, m, controls, msg, validate=True):
137 '''perform a modify with optional verbose output'''
138 if self.verbose:
139 self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
140 try:
141 controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
142 self.samdb.modify(m, controls=controls, validate=validate)
143 except Exception, err:
144 self.report("%s : %s" % (msg, err))
145 return False
146 return True
148 def do_rename(self, from_dn, to_rdn, to_base, controls, msg):
149 '''perform a modify with optional verbose output'''
150 if self.verbose:
151 self.report("""dn: %s
152 changeType: modrdn
153 newrdn: %s
154 deleteOldRdn: 1
155 newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
156 try:
157 to_dn = to_rdn + to_base
158 controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
159 self.samdb.rename(from_dn, to_dn, controls=controls)
160 except Exception, err:
161 self.report("%s : %s" % (msg, err))
162 return False
163 return True
165 def err_empty_attribute(self, dn, attrname):
166 '''fix empty attributes'''
167 self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
168 if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
169 self.report("Not fixing empty attribute %s" % attrname)
170 return
172 m = ldb.Message()
173 m.dn = dn
174 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
175 if self.do_modify(m, ["relax:0", "show_recycled:1"],
176 "Failed to remove empty attribute %s" % attrname, validate=False):
177 self.report("Removed empty attribute %s" % attrname)
179 def err_normalise_mismatch(self, dn, attrname, values):
180 '''fix attribute normalisation errors'''
181 self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
182 mod_list = []
183 for val in values:
184 normalised = self.samdb.dsdb_normalise_attributes(
185 self.samdb_schema, attrname, [val])
186 if len(normalised) != 1:
187 self.report("Unable to normalise value '%s'" % val)
188 mod_list.append((val, ''))
189 elif (normalised[0] != val):
190 self.report("value '%s' should be '%s'" % (val, normalised[0]))
191 mod_list.append((val, normalised[0]))
192 if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
193 self.report("Not fixing attribute %s" % attrname)
194 return
196 m = ldb.Message()
197 m.dn = dn
198 for i in range(0, len(mod_list)):
199 (val, nval) = mod_list[i]
200 m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
201 if nval != '':
202 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD,
203 attrname)
205 if self.do_modify(m, ["relax:0", "show_recycled:1"],
206 "Failed to normalise attribute %s" % attrname,
207 validate=False):
208 self.report("Normalised attribute %s" % attrname)
210 def err_normalise_mismatch_replace(self, dn, attrname, values):
211 '''fix attribute normalisation errors'''
212 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, values)
213 self.report("ERROR: Normalisation error for attribute '%s' in '%s'" % (attrname, dn))
214 self.report("Values/Order of values do/does not match: %s/%s!" % (values, list(normalised)))
215 if list(normalised) == values:
216 return
217 if not self.confirm_all("Fix normalisation for '%s' from '%s'?" % (attrname, dn), 'fix_all_normalisation'):
218 self.report("Not fixing attribute '%s'" % attrname)
219 return
221 m = ldb.Message()
222 m.dn = dn
223 m[attrname] = ldb.MessageElement(normalised, ldb.FLAG_MOD_REPLACE, attrname)
225 if self.do_modify(m, ["relax:0", "show_recycled:1"],
226 "Failed to normalise attribute %s" % attrname,
227 validate=False):
228 self.report("Normalised attribute %s" % attrname)
230 def is_deleted_objects_dn(self, dsdb_dn):
231 '''see if a dsdb_Dn is the special Deleted Objects DN'''
232 return dsdb_dn.prefix == "B:32:18E2EA80684F11D2B9AA00C04F79F805:"
234 def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
235 """handle a DN pointing to a deleted object"""
236 self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
237 self.report("Target GUID points at deleted DN %s" % correct_dn)
238 if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
239 self.report("Not removing")
240 return
241 m = ldb.Message()
242 m.dn = dn
243 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
244 if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
245 "Failed to remove deleted DN attribute %s" % attrname):
246 self.report("Removed deleted DN on attribute %s" % attrname)
248 def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
249 """handle a missing target DN (both GUID and DN string form are missing)"""
250 # check if its a backlink
251 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
252 if (linkID & 1 == 0) and str(dsdb_dn).find('DEL\\0A') == -1:
253 self.report("Not removing dangling forward link")
254 return
255 self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
257 def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
258 """handle a missing GUID extended DN component"""
259 self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
260 controls=["extended_dn:1:1", "show_recycled:1"]
261 try:
262 res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
263 attrs=[], controls=controls)
264 except ldb.LdbError, (enum, estr):
265 self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
266 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
267 return
268 if len(res) == 0:
269 self.report("unable to find object for DN %s" % dsdb_dn.dn)
270 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
271 return
272 dsdb_dn.dn = res[0].dn
274 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
275 self.report("Not fixing %s" % errstr)
276 return
277 m = ldb.Message()
278 m.dn = dn
279 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
280 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
282 if self.do_modify(m, ["show_recycled:1"],
283 "Failed to fix %s on attribute %s" % (errstr, attrname)):
284 self.report("Fixed %s on attribute %s" % (errstr, attrname))
286 def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
287 """handle a DN string being incorrect"""
288 self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
289 dsdb_dn.dn = correct_dn
291 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
292 self.report("Not fixing %s" % errstr)
293 return
294 m = ldb.Message()
295 m.dn = dn
296 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
297 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
298 if self.do_modify(m, ["show_recycled:1"],
299 "Failed to fix incorrect DN string on attribute %s" % attrname):
300 self.report("Fixed incorrect DN string on attribute %s" % (attrname))
302 def err_unknown_attribute(self, obj, attrname):
303 '''handle an unknown attribute error'''
304 self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
305 if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
306 self.report("Not removing %s" % attrname)
307 return
308 m = ldb.Message()
309 m.dn = obj.dn
310 m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
311 if self.do_modify(m, ["relax:0", "show_recycled:1"],
312 "Failed to remove unknown attribute %s" % attrname):
313 self.report("Removed unknown attribute %s" % (attrname))
315 def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
316 '''handle a missing backlink value'''
317 self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
318 if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
319 self.report("Not fixing missing backlink %s" % backlink_name)
320 return
321 m = ldb.Message()
322 m.dn = obj.dn
323 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
324 m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
325 if self.do_modify(m, ["show_recycled:1"],
326 "Failed to fix missing backlink %s" % backlink_name):
327 self.report("Fixed missing backlink %s" % (backlink_name))
329 def err_incorrect_rmd_flags(self, obj, attrname, revealed_dn):
330 '''handle a incorrect RMD_FLAGS value'''
331 rmd_flags = int(revealed_dn.dn.get_extended_component("RMD_FLAGS"))
332 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()))
333 if not self.confirm_all('Fix incorrect RMD_FLAGS %u' % rmd_flags, 'fix_rmd_flags'):
334 self.report("Not fixing incorrect RMD_FLAGS %u" % rmd_flags)
335 return
336 m = ldb.Message()
337 m.dn = obj.dn
338 m['old_value'] = ldb.MessageElement(str(revealed_dn), ldb.FLAG_MOD_DELETE, attrname)
339 if self.do_modify(m, ["show_recycled:1", "reveal_internals:0", "show_deleted:0"],
340 "Failed to fix incorrect RMD_FLAGS %u" % rmd_flags):
341 self.report("Fixed incorrect RMD_FLAGS %u" % (rmd_flags))
343 def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
344 '''handle a orphaned backlink value'''
345 self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
346 if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
347 self.report("Not removing orphaned backlink %s" % link_name)
348 return
349 m = ldb.Message()
350 m.dn = obj.dn
351 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
352 if self.do_modify(m, ["show_recycled:1", "relax:0"],
353 "Failed to fix orphaned backlink %s" % link_name):
354 self.report("Fixed orphaned backlink %s" % (link_name))
356 def err_no_fsmoRoleOwner(self, obj):
357 '''handle a missing fSMORoleOwner'''
358 self.report("ERROR: fSMORoleOwner not found for role %s" % (obj.dn))
359 res = self.samdb.search("",
360 scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
361 assert len(res) == 1
362 serviceName = res[0]["dsServiceName"][0]
363 if not self.confirm_all('Sieze role %s onto current DC by adding fSMORoleOwner=%s' % (obj.dn, serviceName), 'seize_fsmo_role'):
364 self.report("Not Siezing role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
365 return
366 m = ldb.Message()
367 m.dn = obj.dn
368 m['value'] = ldb.MessageElement(serviceName, ldb.FLAG_MOD_ADD, 'fSMORoleOwner')
369 if self.do_modify(m, [],
370 "Failed to sieze role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName)):
371 self.report("Siezed role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
373 def err_missing_parent(self, obj):
374 '''handle a missing parent'''
375 self.report("ERROR: parent object not found for %s" % (obj.dn))
376 if not self.confirm_all('Move object %s into LostAndFound?' % (obj.dn), 'move_to_lost_and_found'):
377 self.report('Not moving object %s into LostAndFound' % (obj.dn))
378 return
380 keep_transaction = True
381 self.samdb.transaction_start()
382 try:
383 nc_root = self.samdb.get_nc_root(obj.dn);
384 lost_and_found = self.samdb.get_wellknown_dn(nc_root, dsdb.DS_GUID_LOSTANDFOUND_CONTAINER)
385 new_dn = ldb.Dn(self.samdb, str(obj.dn))
386 new_dn.remove_base_components(len(new_dn) - 1)
387 if self.do_rename(obj.dn, new_dn, lost_and_found, ["show_deleted:0", "relax:0"],
388 "Failed to rename object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found)):
389 self.report("Renamed object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found))
391 m = ldb.Message()
392 m.dn = obj.dn
393 m['lastKnownParent'] = ldb.MessageElement(str(obj.dn.parent()), ldb.FLAG_MOD_REPLACE, 'lastKnownParent')
395 if self.do_modify(m, [],
396 "Failed to set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found)):
397 self.report("Set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found))
398 keep_transaction = True
399 except:
400 self.samdb.transaction_cancel()
401 raise
403 if keep_transaction:
404 self.samdb.transaction_commit()
405 else:
406 self.samdb.transaction_cancel()
409 def err_wrong_instancetype(self, obj, calculated_instancetype):
410 '''handle a wrong instanceType'''
411 self.report("ERROR: wrong instanceType %s on %s, should be %d" % (obj["instanceType"], obj.dn, calculated_instancetype))
412 if not self.confirm_all('Change instanceType from %s to %d on %s?' % (obj["instanceType"], calculated_instancetype, obj.dn), 'fix_instancetype'):
413 self.report('Not changing instanceType from %s to %d on %s' % (obj["instanceType"], calculated_instancetype, obj.dn))
414 return
416 m = ldb.Message()
417 m.dn = obj.dn
418 m['value'] = ldb.MessageElement(str(calculated_instancetype), ldb.FLAG_MOD_REPLACE, 'instanceType')
419 if self.do_modify(m, ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK_MODIFY_RO_REPLICA],
420 "Failed to correct missing instanceType on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype)):
421 self.report("Corrected instancetype on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype))
423 def find_revealed_link(self, dn, attrname, guid):
424 '''return a revealed link in an object'''
425 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[attrname],
426 controls=["show_deleted:0", "extended_dn:0", "reveal_internals:0"])
427 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
428 for val in res[0][attrname]:
429 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
430 guid2 = dsdb_dn.dn.get_extended_component("GUID")
431 if guid == guid2:
432 return dsdb_dn
433 return None
435 def check_dn(self, obj, attrname, syntax_oid):
436 '''check a DN attribute for correctness'''
437 error_count = 0
438 for val in obj[attrname]:
439 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
441 # all DNs should have a GUID component
442 guid = dsdb_dn.dn.get_extended_component("GUID")
443 if guid is None:
444 error_count += 1
445 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn,
446 "missing GUID")
447 continue
449 guidstr = str(misc.GUID(guid))
451 attrs = ['isDeleted']
452 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
453 reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
454 if reverse_link_name is not None:
455 attrs.append(reverse_link_name)
457 # check its the right GUID
458 try:
459 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
460 attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
461 except ldb.LdbError, (enum, estr):
462 error_count += 1
463 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
464 continue
466 # now we have two cases - the source object might or might not be deleted
467 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
468 target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
470 # the target DN is not allowed to be deleted, unless the target DN is the
471 # special Deleted Objects container
472 if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
473 error_count += 1
474 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
475 continue
477 # check the DN matches in string form
478 if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
479 error_count += 1
480 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
481 res[0].dn, "incorrect string version of DN")
482 continue
484 if is_deleted and not target_is_deleted and reverse_link_name is not None:
485 revealed_dn = self.find_revealed_link(obj.dn, attrname, guid)
486 rmd_flags = revealed_dn.dn.get_extended_component("RMD_FLAGS")
487 if rmd_flags is not None and (int(rmd_flags) & 1) == 0:
488 # the RMD_FLAGS for this link should be 1, as the target is deleted
489 self.err_incorrect_rmd_flags(obj, attrname, revealed_dn)
490 continue
492 # check the reverse_link is correct if there should be one
493 if reverse_link_name is not None:
494 match_count = 0
495 if reverse_link_name in res[0]:
496 for v in res[0][reverse_link_name]:
497 if v == obj.dn.extended_str():
498 match_count += 1
499 if match_count != 1:
500 error_count += 1
501 if linkID & 1:
502 self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
503 else:
504 self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
505 continue
507 return error_count
510 def get_originating_time(self, val, attid):
511 '''Read metadata properties and return the originating time for
512 a given attributeId.
514 :return: the originating time or 0 if not found
517 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
518 obj = repl.ctr
520 for o in repl.ctr.array:
521 if o.attid == attid:
522 return o.originating_change_time
524 return 0
526 def process_metadata(self, val):
527 '''Read metadata properties and list attributes in it'''
529 list_att = []
531 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
532 obj = repl.ctr
534 for o in repl.ctr.array:
535 att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
536 list_att.append(att.lower())
538 return list_att
541 def fix_metadata(self, dn, attr):
542 '''re-write replPropertyMetaData elements for a single attribute for a
543 object. This is used to fix missing replPropertyMetaData elements'''
544 res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
545 controls = ["search_options:1:2", "show_recycled:1"])
546 msg = res[0]
547 nmsg = ldb.Message()
548 nmsg.dn = dn
549 nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
550 if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
551 "Failed to fix metadata for attribute %s" % attr):
552 self.report("Fixed metadata for attribute %s" % attr)
554 def ace_get_effective_inherited_type(self, ace):
555 if ace.flags & security.SEC_ACE_FLAG_INHERIT_ONLY:
556 return None
558 check = False
559 if ace.type == security.SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT:
560 check = True
561 elif ace.type == security.SEC_ACE_TYPE_ACCESS_DENIED_OBJECT:
562 check = True
563 elif ace.type == security.SEC_ACE_TYPE_SYSTEM_AUDIT_OBJECT:
564 check = True
565 elif ace.type == security.SEC_ACE_TYPE_SYSTEM_ALARM_OBJECT:
566 check = True
568 if not check:
569 return None
571 if not ace.object.flags & security.SEC_ACE_INHERITED_OBJECT_TYPE_PRESENT:
572 return None
574 return str(ace.object.inherited_type)
576 def lookup_class_schemaIDGUID(self, cls):
577 if cls in self.class_schemaIDGUID:
578 return self.class_schemaIDGUID[cls]
580 flt = "(&(ldapDisplayName=%s)(objectClass=classSchema))" % cls
581 res = self.samdb.search(base=self.schema_dn,
582 expression=flt,
583 attrs=["schemaIDGUID"])
584 t = str(ndr_unpack(misc.GUID, res[0]["schemaIDGUID"][0]))
586 self.class_schemaIDGUID[cls] = t
587 return t
589 def process_sd(self, dn, obj):
590 sd_attr = "nTSecurityDescriptor"
591 sd_val = obj[sd_attr]
593 sd = ndr_unpack(security.descriptor, str(sd_val))
595 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
596 if is_deleted:
597 # we don't fix deleted objects
598 return (sd, None)
600 sd_clean = security.descriptor()
601 sd_clean.owner_sid = sd.owner_sid
602 sd_clean.group_sid = sd.group_sid
603 sd_clean.type = sd.type
604 sd_clean.revision = sd.revision
606 broken = False
607 last_inherited_type = None
609 aces = []
610 if sd.sacl is not None:
611 aces = sd.sacl.aces
612 for i in range(0, len(aces)):
613 ace = aces[i]
615 if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
616 sd_clean.sacl_add(ace)
617 continue
619 t = self.ace_get_effective_inherited_type(ace)
620 if t is None:
621 continue
623 if last_inherited_type is not None:
624 if t != last_inherited_type:
625 # if it inherited from more than
626 # one type it's very likely to be broken
628 # If not the recalculation will calculate
629 # the same result.
630 broken = True
631 continue
633 last_inherited_type = t
635 aces = []
636 if sd.dacl is not None:
637 aces = sd.dacl.aces
638 for i in range(0, len(aces)):
639 ace = aces[i]
641 if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
642 sd_clean.dacl_add(ace)
643 continue
645 t = self.ace_get_effective_inherited_type(ace)
646 if t is None:
647 continue
649 if last_inherited_type is not None:
650 if t != last_inherited_type:
651 # if it inherited from more than
652 # one type it's very likely to be broken
654 # If not the recalculation will calculate
655 # the same result.
656 broken = True
657 continue
659 last_inherited_type = t
661 if broken:
662 return (sd_clean, sd)
664 if last_inherited_type is None:
665 # ok
666 return (sd, None)
668 cls = None
669 try:
670 cls = obj["objectClass"][-1]
671 except KeyError, e:
672 pass
674 if cls is None:
675 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
676 attrs=["isDeleted", "objectClass"],
677 controls=["show_recycled:1"])
678 o = res[0]
679 is_deleted = 'isDeleted' in o and o['isDeleted'][0].upper() == 'TRUE'
680 if is_deleted:
681 # we don't fix deleted objects
682 return (sd, None)
683 cls = o["objectClass"][-1]
685 t = self.lookup_class_schemaIDGUID(cls)
687 if t != last_inherited_type:
688 # broken
689 return (sd_clean, sd)
691 # ok
692 return (sd, None)
694 def err_wrong_sd(self, dn, sd, sd_broken):
695 '''re-write replPropertyMetaData elements for a single attribute for a
696 object. This is used to fix missing replPropertyMetaData elements'''
697 sd_attr = "nTSecurityDescriptor"
698 sd_val = ndr_pack(sd)
699 sd_flags = security.SECINFO_DACL | security.SECINFO_SACL
701 if not self.confirm_all('Fix %s on %s?' % (sd_attr, dn), 'fix_ntsecuritydescriptor'):
702 self.report('Not fixing %s on %s\n' % (sd_attr, dn))
703 return
705 nmsg = ldb.Message()
706 nmsg.dn = dn
707 nmsg[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
708 if self.do_modify(nmsg, ["sd_flags:1:%d" % sd_flags],
709 "Failed to fix metadata for attribute %s" % sd_attr):
710 self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
712 def is_fsmo_role(self, dn):
713 if dn == self.samdb.domain_dn:
714 return True
715 if dn == self.infrastructure_dn:
716 return True
717 if dn == self.naming_dn:
718 return True
719 if dn == self.schema_dn:
720 return True
721 if dn == self.rid_dn:
722 return True
724 return False
726 def calculate_instancetype(self, dn):
727 instancetype = 0
728 nc_root = self.samdb.get_nc_root(dn)
729 if dn == nc_root:
730 instancetype |= dsdb.INSTANCE_TYPE_IS_NC_HEAD
731 try:
732 self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE, attrs=[], controls=["show_recycled:1"])
733 except ldb.LdbError, (enum, estr):
734 if enum != ldb.ERR_NO_SUCH_OBJECT:
735 raise
736 else:
737 instancetype |= dsdb.INSTANCE_TYPE_NC_ABOVE
739 if self.write_ncs is not None and str(nc_root) in self.write_ncs:
740 instancetype |= dsdb.INSTANCE_TYPE_WRITE
742 return instancetype
744 def check_object(self, dn, attrs=['*']):
745 '''check one object'''
746 if self.verbose:
747 self.report("Checking object %s" % dn)
748 if '*' in attrs:
749 attrs.append("replPropertyMetaData")
751 try:
752 sd_flags = 0
753 sd_flags |= security.SECINFO_OWNER
754 sd_flags |= security.SECINFO_GROUP
755 sd_flags |= security.SECINFO_DACL
756 sd_flags |= security.SECINFO_SACL
758 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
759 controls=[
760 "extended_dn:1:1",
761 "show_recycled:1",
762 "show_deleted:1",
763 "sd_flags:1:%d" % sd_flags,
765 attrs=attrs)
766 except ldb.LdbError, (enum, estr):
767 if enum == ldb.ERR_NO_SUCH_OBJECT:
768 if self.in_transaction:
769 self.report("ERROR: Object %s disappeared during check" % dn)
770 return 1
771 return 0
772 raise
773 if len(res) != 1:
774 self.report("ERROR: Object %s failed to load during check" % dn)
775 return 1
776 obj = res[0]
777 error_count = 0
778 list_attrs_from_md = []
779 list_attrs_seen = []
780 got_repl_property_meta_data = False
782 for attrname in obj:
783 if attrname == 'dn':
784 continue
786 if str(attrname).lower() == 'replpropertymetadata':
787 list_attrs_from_md = self.process_metadata(obj[attrname])
788 got_repl_property_meta_data = True
789 continue
791 if str(attrname).lower() == 'ntsecuritydescriptor':
792 (sd, sd_broken) = self.process_sd(dn, obj)
793 if sd_broken is not None:
794 self.err_wrong_sd(dn, sd, sd_broken)
795 error_count += 1
796 continue
798 if str(attrname).lower() == 'objectclass':
799 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, list(obj[attrname]))
800 if list(normalised) != list(obj[attrname]):
801 self.err_normalise_mismatch_replace(dn, attrname, list(obj[attrname]))
802 error_count += 1
803 continue
805 # check for empty attributes
806 for val in obj[attrname]:
807 if val == '':
808 self.err_empty_attribute(dn, attrname)
809 error_count += 1
810 continue
812 # get the syntax oid for the attribute, so we can can have
813 # special handling for some specific attribute types
814 try:
815 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
816 except Exception, msg:
817 self.err_unknown_attribute(obj, attrname)
818 error_count += 1
819 continue
821 flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
822 if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
823 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
824 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
825 list_attrs_seen.append(str(attrname).lower())
827 if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
828 dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
829 # it's some form of DN, do specialised checking on those
830 error_count += self.check_dn(obj, attrname, syntax_oid)
832 # check for incorrectly normalised attributes
833 for val in obj[attrname]:
834 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
835 if len(normalised) != 1 or normalised[0] != val:
836 self.err_normalise_mismatch(dn, attrname, obj[attrname])
837 error_count += 1
838 break
840 if str(attrname).lower() == "instancetype":
841 calculated_instancetype = self.calculate_instancetype(dn)
842 if len(obj["instanceType"]) != 1 or obj["instanceType"][0] != str(calculated_instancetype):
843 self.err_wrong_instancetype(obj, calculated_instancetype)
845 show_dn = True
846 if got_repl_property_meta_data:
847 rdn = (str(dn).split(","))[0]
848 if rdn == "CN=Deleted Objects":
849 isDeletedAttId = 131120
850 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
852 expectedTimeDo = 2650466015990000000
853 originating = self.get_originating_time(obj["replPropertyMetaData"], isDeletedAttId)
854 if originating != expectedTimeDo:
855 if self.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn), 'fix_time_metadata'):
856 nmsg = ldb.Message()
857 nmsg.dn = dn
858 nmsg["isDeleted"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isDeleted")
859 error_count += 1
860 self.samdb.modify(nmsg, controls=["provision:0"])
862 else:
863 self.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn))
864 for att in list_attrs_seen:
865 if not att in list_attrs_from_md:
866 if show_dn:
867 self.report("On object %s" % dn)
868 show_dn = False
869 error_count += 1
870 self.report("ERROR: Attribute %s not present in replication metadata" % att)
871 if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
872 self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
873 continue
874 self.fix_metadata(dn, att)
876 if self.is_fsmo_role(dn):
877 if "fSMORoleOwner" not in obj:
878 self.err_no_fsmoRoleOwner(obj)
879 error_count += 1
881 try:
882 if dn != self.samdb.get_root_basedn():
883 res = self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE,
884 controls=["show_recycled:1", "show_deleted:1"])
885 except ldb.LdbError, (enum, estr):
886 if enum == ldb.ERR_NO_SUCH_OBJECT:
887 self.err_missing_parent(obj)
888 error_count += 1
889 else:
890 raise
892 return error_count
894 ################################################################
895 # check special @ROOTDSE attributes
896 def check_rootdse(self):
897 '''check the @ROOTDSE special object'''
898 dn = ldb.Dn(self.samdb, '@ROOTDSE')
899 if self.verbose:
900 self.report("Checking object %s" % dn)
901 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
902 if len(res) != 1:
903 self.report("Object %s disappeared during check" % dn)
904 return 1
905 obj = res[0]
906 error_count = 0
908 # check that the dsServiceName is in GUID form
909 if not 'dsServiceName' in obj:
910 self.report('ERROR: dsServiceName missing in @ROOTDSE')
911 return error_count+1
913 if not obj['dsServiceName'][0].startswith('<GUID='):
914 self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
915 error_count += 1
916 if not self.confirm('Change dsServiceName to GUID form?'):
917 return error_count
918 res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
919 scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
920 guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
921 m = ldb.Message()
922 m.dn = dn
923 m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
924 ldb.FLAG_MOD_REPLACE, 'dsServiceName')
925 if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
926 self.report("Changed dsServiceName to GUID form")
927 return error_count
930 ###############################################
931 # re-index the database
932 def reindex_database(self):
933 '''re-index the whole database'''
934 m = ldb.Message()
935 m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
936 m['add'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
937 m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
938 return self.do_modify(m, [], 're-indexed database', validate=False)
940 ###############################################
941 # reset @MODULES
942 def reset_modules(self):
943 '''reset @MODULES to that needed for current sam.ldb (to read a very old database)'''
944 m = ldb.Message()
945 m.dn = ldb.Dn(self.samdb, "@MODULES")
946 m['@LIST'] = ldb.MessageElement('samba_dsdb', ldb.FLAG_MOD_REPLACE, '@LIST')
947 return self.do_modify(m, [], 'reset @MODULES on database', validate=False)