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/>.
23 from samba import dsdb
24 from samba import common
25 from samba.dcerpc import misc
26 from samba.ndr import ndr_unpack, ndr_pack
27 from samba.dcerpc import drsblobs
28 from samba.common import dsdb_Dn
29 from samba.dcerpc import security
30 from samba.descriptor import get_wellknown_sds, get_diff_sds
31 from samba.auth import system_session, admin_session
34 class dbcheck(object):
35 """check a SAM database for errors"""
37 def __init__(self, samdb, samdb_schema=None, verbose=False, fix=False,
38 yes=False, quiet=False, in_transaction=False,
39 reset_well_known_acls=False):
41 self.dict_oid_name = None
42 self.samdb_schema = (samdb_schema or samdb)
43 self.verbose = verbose
47 self.remove_all_unknown_attributes = False
48 self.remove_all_empty_attributes = False
49 self.fix_all_normalisation = False
50 self.fix_all_DN_GUIDs = False
51 self.fix_all_binary_dn = False
52 self.remove_all_deleted_DN_links = False
53 self.fix_all_target_mismatch = False
54 self.fix_all_metadata = False
55 self.fix_time_metadata = False
56 self.fix_all_missing_backlinks = False
57 self.fix_all_orphaned_backlinks = False
58 self.fix_rmd_flags = False
59 self.fix_ntsecuritydescriptor = False
60 self.fix_ntsecuritydescriptor_owner_group = False
61 self.seize_fsmo_role = False
62 self.move_to_lost_and_found = False
63 self.fix_instancetype = False
64 self.fix_replmetadata_zero_invocationid = False
65 self.fix_deleted_deleted_objects = False
66 self.reset_well_known_acls = reset_well_known_acls
67 self.reset_all_well_known_acls = False
68 self.in_transaction = in_transaction
69 self.infrastructure_dn = ldb.Dn(samdb, "CN=Infrastructure," + samdb.domain_dn())
70 self.naming_dn = ldb.Dn(samdb, "CN=Partitions,%s" % samdb.get_config_basedn())
71 self.schema_dn = samdb.get_schema_basedn()
72 self.rid_dn = ldb.Dn(samdb, "CN=RID Manager$,CN=System," + samdb.domain_dn())
73 self.ntds_dsa = ldb.Dn(samdb, samdb.get_dsServiceName())
74 self.class_schemaIDGUID = {}
75 self.wellknown_sds = get_wellknown_sds(self.samdb)
79 res = samdb.search(base="CN=DnsAdmins,CN=Users,%s" % samdb.domain_dn(), scope=ldb.SCOPE_BASE,
81 dnsadmins_sid = ndr_unpack(security.dom_sid, res[0]["objectSid"][0])
82 self.name_map['DnsAdmins'] = str(dnsadmins_sid)
83 except ldb.LdbError, (enum, estr):
84 if enum != ldb.ERR_NO_SUCH_OBJECT:
88 self.system_session_info = system_session()
89 self.admin_session_info = admin_session(None, samdb.get_domain_sid())
91 res = self.samdb.search(base=self.ntds_dsa, scope=ldb.SCOPE_BASE, attrs=['msDS-hasMasterNCs', 'hasMasterNCs'])
92 if "msDS-hasMasterNCs" in res[0]:
93 self.write_ncs = res[0]["msDS-hasMasterNCs"]
95 # If the Forest Level is less than 2003 then there is no
96 # msDS-hasMasterNCs, so we fall back to hasMasterNCs
97 # no need to merge as all the NCs that are in hasMasterNCs must
98 # also be in msDS-hasMasterNCs (but not the opposite)
99 if "hasMasterNCs" in res[0]:
100 self.write_ncs = res[0]["hasMasterNCs"]
102 self.write_ncs = None
104 res = self.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=['namingContexts'])
106 ncs = res[0]["namingContexts"]
107 self.deleted_objects_containers = []
110 dn = self.samdb.get_wellknown_dn(ldb.Dn(self.samdb, nc),
111 dsdb.DS_GUID_DELETED_OBJECTS_CONTAINER)
112 self.deleted_objects_containers.append(dn)
120 def check_database(self, DN=None, scope=ldb.SCOPE_SUBTREE, controls=[], attrs=['*']):
121 '''perform a database check, returning the number of errors found'''
123 res = self.samdb.search(base=DN, scope=scope, attrs=['dn'], controls=controls)
124 self.report('Checking %u objects' % len(res))
128 error_count += self.check_object(object.dn, attrs=attrs)
131 error_count += self.check_rootdse()
133 if error_count != 0 and not self.fix:
134 self.report("Please use --fix to fix these errors")
136 self.report('Checked %u objects (%u errors)' % (len(res), error_count))
139 def report(self, msg):
140 '''print a message unless quiet is set'''
144 def confirm(self, msg, allow_all=False, forced=False):
145 '''confirm a change'''
152 return common.confirm(msg, forced=forced, allow_all=allow_all)
154 ################################################################
155 # a local confirm function with support for 'all'
156 def confirm_all(self, msg, all_attr):
157 '''confirm a change with support for "all" '''
162 if getattr(self, all_attr) == 'NONE':
164 if getattr(self, all_attr) == 'ALL':
168 c = common.confirm(msg, forced=forced, allow_all=True)
170 setattr(self, all_attr, 'ALL')
173 setattr(self, all_attr, 'NONE')
177 def do_modify(self, m, controls, msg, validate=True):
178 '''perform a modify with optional verbose output'''
180 self.report(self.samdb.write_ldif(m, ldb.CHANGETYPE_MODIFY))
182 controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
183 self.samdb.modify(m, controls=controls, validate=validate)
184 except Exception, err:
185 self.report("%s : %s" % (msg, err))
189 def do_rename(self, from_dn, to_rdn, to_base, controls, msg):
190 '''perform a modify with optional verbose output'''
192 self.report("""dn: %s
196 newSuperior: %s""" % (str(from_dn), str(to_rdn), str(to_base)))
198 to_dn = to_rdn + to_base
199 controls = controls + ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK]
200 self.samdb.rename(from_dn, to_dn, controls=controls)
201 except Exception, err:
202 self.report("%s : %s" % (msg, err))
206 def err_empty_attribute(self, dn, attrname):
207 '''fix empty attributes'''
208 self.report("ERROR: Empty attribute %s in %s" % (attrname, dn))
209 if not self.confirm_all('Remove empty attribute %s from %s?' % (attrname, dn), 'remove_all_empty_attributes'):
210 self.report("Not fixing empty attribute %s" % attrname)
215 m[attrname] = ldb.MessageElement('', ldb.FLAG_MOD_DELETE, attrname)
216 if self.do_modify(m, ["relax:0", "show_recycled:1"],
217 "Failed to remove empty attribute %s" % attrname, validate=False):
218 self.report("Removed empty attribute %s" % attrname)
220 def err_normalise_mismatch(self, dn, attrname, values):
221 '''fix attribute normalisation errors'''
222 self.report("ERROR: Normalisation error for attribute %s in %s" % (attrname, dn))
225 normalised = self.samdb.dsdb_normalise_attributes(
226 self.samdb_schema, attrname, [val])
227 if len(normalised) != 1:
228 self.report("Unable to normalise value '%s'" % val)
229 mod_list.append((val, ''))
230 elif (normalised[0] != val):
231 self.report("value '%s' should be '%s'" % (val, normalised[0]))
232 mod_list.append((val, normalised[0]))
233 if not self.confirm_all('Fix normalisation for %s from %s?' % (attrname, dn), 'fix_all_normalisation'):
234 self.report("Not fixing attribute %s" % attrname)
239 for i in range(0, len(mod_list)):
240 (val, nval) = mod_list[i]
241 m['value_%u' % i] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
243 m['normv_%u' % i] = ldb.MessageElement(nval, ldb.FLAG_MOD_ADD,
246 if self.do_modify(m, ["relax:0", "show_recycled:1"],
247 "Failed to normalise attribute %s" % attrname,
249 self.report("Normalised attribute %s" % attrname)
251 def err_normalise_mismatch_replace(self, dn, attrname, values):
252 '''fix attribute normalisation errors'''
253 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, values)
254 self.report("ERROR: Normalisation error for attribute '%s' in '%s'" % (attrname, dn))
255 self.report("Values/Order of values do/does not match: %s/%s!" % (values, list(normalised)))
256 if list(normalised) == values:
258 if not self.confirm_all("Fix normalisation for '%s' from '%s'?" % (attrname, dn), 'fix_all_normalisation'):
259 self.report("Not fixing attribute '%s'" % attrname)
264 m[attrname] = ldb.MessageElement(normalised, ldb.FLAG_MOD_REPLACE, attrname)
266 if self.do_modify(m, ["relax:0", "show_recycled:1"],
267 "Failed to normalise attribute %s" % attrname,
269 self.report("Normalised attribute %s" % attrname)
271 def is_deleted_objects_dn(self, dsdb_dn):
272 '''see if a dsdb_Dn is the special Deleted Objects DN'''
273 return dsdb_dn.prefix == "B:32:%s:" % dsdb.DS_GUID_DELETED_OBJECTS_CONTAINER
275 def err_deleted_dn(self, dn, attrname, val, dsdb_dn, correct_dn):
276 """handle a DN pointing to a deleted object"""
277 self.report("ERROR: target DN is deleted for %s in object %s - %s" % (attrname, dn, val))
278 self.report("Target GUID points at deleted DN %s" % correct_dn)
279 if not self.confirm_all('Remove DN link?', 'remove_all_deleted_DN_links'):
280 self.report("Not removing")
284 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
285 if self.do_modify(m, ["show_recycled:1", "local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK],
286 "Failed to remove deleted DN attribute %s" % attrname):
287 self.report("Removed deleted DN on attribute %s" % attrname)
289 def err_missing_dn_GUID(self, dn, attrname, val, dsdb_dn):
290 """handle a missing target DN (both GUID and DN string form are missing)"""
291 # check if its a backlink
292 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
293 if (linkID & 1 == 0) and str(dsdb_dn).find('\\0ADEL') == -1:
294 self.report("Not removing dangling forward link")
296 self.err_deleted_dn(dn, attrname, val, dsdb_dn, dsdb_dn)
298 def err_incorrect_dn_GUID(self, dn, attrname, val, dsdb_dn, errstr):
299 """handle a missing GUID extended DN component"""
300 self.report("ERROR: %s component for %s in object %s - %s" % (errstr, attrname, dn, val))
301 controls=["extended_dn:1:1", "show_recycled:1"]
303 res = self.samdb.search(base=str(dsdb_dn.dn), scope=ldb.SCOPE_BASE,
304 attrs=[], controls=controls)
305 except ldb.LdbError, (enum, estr):
306 self.report("unable to find object for DN %s - (%s)" % (dsdb_dn.dn, estr))
307 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
310 self.report("unable to find object for DN %s" % dsdb_dn.dn)
311 self.err_missing_dn_GUID(dn, attrname, val, dsdb_dn)
313 dsdb_dn.dn = res[0].dn
315 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_DN_GUIDs'):
316 self.report("Not fixing %s" % errstr)
320 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
321 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
323 if self.do_modify(m, ["show_recycled:1"],
324 "Failed to fix %s on attribute %s" % (errstr, attrname)):
325 self.report("Fixed %s on attribute %s" % (errstr, attrname))
327 def err_incorrect_binary_dn(self, dn, attrname, val, dsdb_dn, errstr):
328 """handle an incorrect binary DN component"""
329 self.report("ERROR: %s binary component for %s in object %s - %s" % (errstr, attrname, dn, val))
330 controls=["extended_dn:1:1", "show_recycled:1"]
332 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_binary_dn'):
333 self.report("Not fixing %s" % errstr)
337 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
338 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
340 if self.do_modify(m, ["show_recycled:1"],
341 "Failed to fix %s on attribute %s" % (errstr, attrname)):
342 self.report("Fixed %s on attribute %s" % (errstr, attrname))
344 def err_dn_target_mismatch(self, dn, attrname, val, dsdb_dn, correct_dn, errstr):
345 """handle a DN string being incorrect"""
346 self.report("ERROR: incorrect DN string component for %s in object %s - %s" % (attrname, dn, val))
347 dsdb_dn.dn = correct_dn
349 if not self.confirm_all('Change DN to %s?' % str(dsdb_dn), 'fix_all_target_mismatch'):
350 self.report("Not fixing %s" % errstr)
354 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
355 m['new_value'] = ldb.MessageElement(str(dsdb_dn), ldb.FLAG_MOD_ADD, attrname)
356 if self.do_modify(m, ["show_recycled:1"],
357 "Failed to fix incorrect DN string on attribute %s" % attrname):
358 self.report("Fixed incorrect DN string on attribute %s" % (attrname))
360 def err_unknown_attribute(self, obj, attrname):
361 '''handle an unknown attribute error'''
362 self.report("ERROR: unknown attribute '%s' in %s" % (attrname, obj.dn))
363 if not self.confirm_all('Remove unknown attribute %s' % attrname, 'remove_all_unknown_attributes'):
364 self.report("Not removing %s" % attrname)
368 m['old_value'] = ldb.MessageElement([], ldb.FLAG_MOD_DELETE, attrname)
369 if self.do_modify(m, ["relax:0", "show_recycled:1"],
370 "Failed to remove unknown attribute %s" % attrname):
371 self.report("Removed unknown attribute %s" % (attrname))
373 def err_missing_backlink(self, obj, attrname, val, backlink_name, target_dn):
374 '''handle a missing backlink value'''
375 self.report("ERROR: missing backlink attribute '%s' in %s for link %s in %s" % (backlink_name, target_dn, attrname, obj.dn))
376 if not self.confirm_all('Fix missing backlink %s' % backlink_name, 'fix_all_missing_backlinks'):
377 self.report("Not fixing missing backlink %s" % backlink_name)
381 m['old_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
382 m['new_value'] = ldb.MessageElement(val, ldb.FLAG_MOD_ADD, attrname)
383 if self.do_modify(m, ["show_recycled:1"],
384 "Failed to fix missing backlink %s" % backlink_name):
385 self.report("Fixed missing backlink %s" % (backlink_name))
387 def err_incorrect_rmd_flags(self, obj, attrname, revealed_dn):
388 '''handle a incorrect RMD_FLAGS value'''
389 rmd_flags = int(revealed_dn.dn.get_extended_component("RMD_FLAGS"))
390 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()))
391 if not self.confirm_all('Fix incorrect RMD_FLAGS %u' % rmd_flags, 'fix_rmd_flags'):
392 self.report("Not fixing incorrect RMD_FLAGS %u" % rmd_flags)
396 m['old_value'] = ldb.MessageElement(str(revealed_dn), ldb.FLAG_MOD_DELETE, attrname)
397 if self.do_modify(m, ["show_recycled:1", "reveal_internals:0", "show_deleted:0"],
398 "Failed to fix incorrect RMD_FLAGS %u" % rmd_flags):
399 self.report("Fixed incorrect RMD_FLAGS %u" % (rmd_flags))
401 def err_orphaned_backlink(self, obj, attrname, val, link_name, target_dn):
402 '''handle a orphaned backlink value'''
403 self.report("ERROR: orphaned backlink attribute '%s' in %s for link %s in %s" % (attrname, obj.dn, link_name, target_dn))
404 if not self.confirm_all('Remove orphaned backlink %s' % link_name, 'fix_all_orphaned_backlinks'):
405 self.report("Not removing orphaned backlink %s" % link_name)
409 m['value'] = ldb.MessageElement(val, ldb.FLAG_MOD_DELETE, attrname)
410 if self.do_modify(m, ["show_recycled:1", "relax:0"],
411 "Failed to fix orphaned backlink %s" % link_name):
412 self.report("Fixed orphaned backlink %s" % (link_name))
414 def err_no_fsmoRoleOwner(self, obj):
415 '''handle a missing fSMORoleOwner'''
416 self.report("ERROR: fSMORoleOwner not found for role %s" % (obj.dn))
417 res = self.samdb.search("",
418 scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
420 serviceName = res[0]["dsServiceName"][0]
421 if not self.confirm_all('Sieze role %s onto current DC by adding fSMORoleOwner=%s' % (obj.dn, serviceName), 'seize_fsmo_role'):
422 self.report("Not Siezing role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
426 m['value'] = ldb.MessageElement(serviceName, ldb.FLAG_MOD_ADD, 'fSMORoleOwner')
427 if self.do_modify(m, [],
428 "Failed to sieze role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName)):
429 self.report("Siezed role %s onto current DC by adding fSMORoleOwner=%s" % (obj.dn, serviceName))
431 def err_missing_parent(self, obj):
432 '''handle a missing parent'''
433 self.report("ERROR: parent object not found for %s" % (obj.dn))
434 if not self.confirm_all('Move object %s into LostAndFound?' % (obj.dn), 'move_to_lost_and_found'):
435 self.report('Not moving object %s into LostAndFound' % (obj.dn))
438 keep_transaction = True
439 self.samdb.transaction_start()
441 nc_root = self.samdb.get_nc_root(obj.dn);
442 lost_and_found = self.samdb.get_wellknown_dn(nc_root, dsdb.DS_GUID_LOSTANDFOUND_CONTAINER)
443 new_dn = ldb.Dn(self.samdb, str(obj.dn))
444 new_dn.remove_base_components(len(new_dn) - 1)
445 if self.do_rename(obj.dn, new_dn, lost_and_found, ["show_deleted:0", "relax:0"],
446 "Failed to rename object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found)):
447 self.report("Renamed object %s into lostAndFound at %s" % (obj.dn, new_dn + lost_and_found))
451 m['lastKnownParent'] = ldb.MessageElement(str(obj.dn.parent()), ldb.FLAG_MOD_REPLACE, 'lastKnownParent')
453 if self.do_modify(m, [],
454 "Failed to set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found)):
455 self.report("Set lastKnownParent on lostAndFound object at %s" % (new_dn + lost_and_found))
456 keep_transaction = True
458 self.samdb.transaction_cancel()
462 self.samdb.transaction_commit()
464 self.samdb.transaction_cancel()
467 def err_wrong_instancetype(self, obj, calculated_instancetype):
468 '''handle a wrong instanceType'''
469 self.report("ERROR: wrong instanceType %s on %s, should be %d" % (obj["instanceType"], obj.dn, calculated_instancetype))
470 if not self.confirm_all('Change instanceType from %s to %d on %s?' % (obj["instanceType"], calculated_instancetype, obj.dn), 'fix_instancetype'):
471 self.report('Not changing instanceType from %s to %d on %s' % (obj["instanceType"], calculated_instancetype, obj.dn))
476 m['value'] = ldb.MessageElement(str(calculated_instancetype), ldb.FLAG_MOD_REPLACE, 'instanceType')
477 if self.do_modify(m, ["local_oid:%s:0" % dsdb.DSDB_CONTROL_DBCHECK_MODIFY_RO_REPLICA],
478 "Failed to correct missing instanceType on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype)):
479 self.report("Corrected instancetype on %s by setting instanceType=%d" % (obj.dn, calculated_instancetype))
481 def find_revealed_link(self, dn, attrname, guid):
482 '''return a revealed link in an object'''
483 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=[attrname],
484 controls=["show_deleted:0", "extended_dn:0", "reveal_internals:0"])
485 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
486 for val in res[0][attrname]:
487 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
488 guid2 = dsdb_dn.dn.get_extended_component("GUID")
493 def check_dn(self, obj, attrname, syntax_oid):
494 '''check a DN attribute for correctness'''
496 for val in obj[attrname]:
497 dsdb_dn = dsdb_Dn(self.samdb, val, syntax_oid)
499 # all DNs should have a GUID component
500 guid = dsdb_dn.dn.get_extended_component("GUID")
503 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn,
507 guidstr = str(misc.GUID(guid))
509 attrs = ['isDeleted']
511 if (str(attrname).lower() == 'msds-hasinstantiatedncs') and (obj.dn == self.ntds_dsa):
512 fixing_msDS_HasInstantiatedNCs = True
513 attrs.append("instanceType")
515 fixing_msDS_HasInstantiatedNCs = False
517 linkID = self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)
518 reverse_link_name = self.samdb_schema.get_backlink_from_lDAPDisplayName(attrname)
519 if reverse_link_name is not None:
520 attrs.append(reverse_link_name)
522 # check its the right GUID
524 res = self.samdb.search(base="<GUID=%s>" % guidstr, scope=ldb.SCOPE_BASE,
525 attrs=attrs, controls=["extended_dn:1:1", "show_recycled:1"])
526 except ldb.LdbError, (enum, estr):
528 self.err_incorrect_dn_GUID(obj.dn, attrname, val, dsdb_dn, "incorrect GUID")
531 if fixing_msDS_HasInstantiatedNCs:
532 dsdb_dn.prefix = "B:8:%08X:" % int(res[0]['instanceType'][0])
533 dsdb_dn.binary = "%08X" % int(res[0]['instanceType'][0])
535 if str(dsdb_dn) != val:
537 self.err_incorrect_binary_dn(obj.dn, attrname, val, dsdb_dn, "incorrect instanceType part of Binary DN")
540 # now we have two cases - the source object might or might not be deleted
541 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
542 target_is_deleted = 'isDeleted' in res[0] and res[0]['isDeleted'][0].upper() == 'TRUE'
544 # the target DN is not allowed to be deleted, unless the target DN is the
545 # special Deleted Objects container
546 if target_is_deleted and not is_deleted and not self.is_deleted_objects_dn(dsdb_dn):
548 self.err_deleted_dn(obj.dn, attrname, val, dsdb_dn, res[0].dn)
551 # check the DN matches in string form
552 if res[0].dn.extended_str() != dsdb_dn.dn.extended_str():
554 self.err_dn_target_mismatch(obj.dn, attrname, val, dsdb_dn,
555 res[0].dn, "incorrect string version of DN")
558 if is_deleted and not target_is_deleted and reverse_link_name is not None:
559 revealed_dn = self.find_revealed_link(obj.dn, attrname, guid)
560 rmd_flags = revealed_dn.dn.get_extended_component("RMD_FLAGS")
561 if rmd_flags is not None and (int(rmd_flags) & 1) == 0:
562 # the RMD_FLAGS for this link should be 1, as the target is deleted
563 self.err_incorrect_rmd_flags(obj, attrname, revealed_dn)
566 # check the reverse_link is correct if there should be one
567 if reverse_link_name is not None:
569 if reverse_link_name in res[0]:
570 for v in res[0][reverse_link_name]:
571 if v == obj.dn.extended_str():
576 self.err_orphaned_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
578 self.err_missing_backlink(obj, attrname, val, reverse_link_name, dsdb_dn.dn)
584 def get_originating_time(self, val, attid):
585 '''Read metadata properties and return the originating time for
588 :return: the originating time or 0 if not found
591 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
594 for o in repl.ctr.array:
596 return o.originating_change_time
600 def process_metadata(self, val):
601 '''Read metadata properties and list attributes in it'''
605 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob, str(val))
608 for o in repl.ctr.array:
609 att = self.samdb_schema.get_lDAPDisplayName_by_attid(o.attid)
610 list_att.append(att.lower())
615 def fix_metadata(self, dn, attr):
616 '''re-write replPropertyMetaData elements for a single attribute for a
617 object. This is used to fix missing replPropertyMetaData elements'''
618 res = self.samdb.search(base = dn, scope=ldb.SCOPE_BASE, attrs = [attr],
619 controls = ["search_options:1:2", "show_recycled:1"])
623 nmsg[attr] = ldb.MessageElement(msg[attr], ldb.FLAG_MOD_REPLACE, attr)
624 if self.do_modify(nmsg, ["relax:0", "provision:0", "show_recycled:1"],
625 "Failed to fix metadata for attribute %s" % attr):
626 self.report("Fixed metadata for attribute %s" % attr)
628 def ace_get_effective_inherited_type(self, ace):
629 if ace.flags & security.SEC_ACE_FLAG_INHERIT_ONLY:
633 if ace.type == security.SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT:
635 elif ace.type == security.SEC_ACE_TYPE_ACCESS_DENIED_OBJECT:
637 elif ace.type == security.SEC_ACE_TYPE_SYSTEM_AUDIT_OBJECT:
639 elif ace.type == security.SEC_ACE_TYPE_SYSTEM_ALARM_OBJECT:
645 if not ace.object.flags & security.SEC_ACE_INHERITED_OBJECT_TYPE_PRESENT:
648 return str(ace.object.inherited_type)
650 def lookup_class_schemaIDGUID(self, cls):
651 if cls in self.class_schemaIDGUID:
652 return self.class_schemaIDGUID[cls]
654 flt = "(&(ldapDisplayName=%s)(objectClass=classSchema))" % cls
655 res = self.samdb.search(base=self.schema_dn,
657 attrs=["schemaIDGUID"])
658 t = str(ndr_unpack(misc.GUID, res[0]["schemaIDGUID"][0]))
660 self.class_schemaIDGUID[cls] = t
663 def process_sd(self, dn, obj):
664 sd_attr = "nTSecurityDescriptor"
665 sd_val = obj[sd_attr]
667 sd = ndr_unpack(security.descriptor, str(sd_val))
669 is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE'
671 # we don't fix deleted objects
674 sd_clean = security.descriptor()
675 sd_clean.owner_sid = sd.owner_sid
676 sd_clean.group_sid = sd.group_sid
677 sd_clean.type = sd.type
678 sd_clean.revision = sd.revision
681 last_inherited_type = None
684 if sd.sacl is not None:
686 for i in range(0, len(aces)):
689 if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
690 sd_clean.sacl_add(ace)
693 t = self.ace_get_effective_inherited_type(ace)
697 if last_inherited_type is not None:
698 if t != last_inherited_type:
699 # if it inherited from more than
700 # one type it's very likely to be broken
702 # If not the recalculation will calculate
707 last_inherited_type = t
710 if sd.dacl is not None:
712 for i in range(0, len(aces)):
715 if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE:
716 sd_clean.dacl_add(ace)
719 t = self.ace_get_effective_inherited_type(ace)
723 if last_inherited_type is not None:
724 if t != last_inherited_type:
725 # if it inherited from more than
726 # one type it's very likely to be broken
728 # If not the recalculation will calculate
733 last_inherited_type = t
736 return (sd_clean, sd)
738 if last_inherited_type is None:
744 cls = obj["objectClass"][-1]
749 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
750 attrs=["isDeleted", "objectClass"],
751 controls=["show_recycled:1"])
753 is_deleted = 'isDeleted' in o and o['isDeleted'][0].upper() == 'TRUE'
755 # we don't fix deleted objects
757 cls = o["objectClass"][-1]
759 t = self.lookup_class_schemaIDGUID(cls)
761 if t != last_inherited_type:
763 return (sd_clean, sd)
768 def err_wrong_sd(self, dn, sd, sd_broken):
769 '''re-write the SD due to incorrect inherited ACEs'''
770 sd_attr = "nTSecurityDescriptor"
771 sd_val = ndr_pack(sd)
772 sd_flags = security.SECINFO_DACL | security.SECINFO_SACL
774 if not self.confirm_all('Fix %s on %s?' % (sd_attr, dn), 'fix_ntsecuritydescriptor'):
775 self.report('Not fixing %s on %s\n' % (sd_attr, dn))
780 nmsg[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
781 if self.do_modify(nmsg, ["sd_flags:1:%d" % sd_flags],
782 "Failed to fix attribute %s" % sd_attr):
783 self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
785 def err_wrong_default_sd(self, dn, sd, sd_old, diff):
786 '''re-write the SD due to not matching the default (optional mode for fixing an incorrect provision)'''
787 sd_attr = "nTSecurityDescriptor"
788 sd_val = ndr_pack(sd)
789 sd_old_val = ndr_pack(sd_old)
790 sd_flags = security.SECINFO_DACL | security.SECINFO_SACL
791 if sd.owner_sid is not None:
792 sd_flags |= security.SECINFO_OWNER
793 if sd.group_sid is not None:
794 sd_flags |= security.SECINFO_GROUP
796 if not self.confirm_all('Reset %s on %s back to provision default?\n%s' % (sd_attr, dn, diff), 'reset_all_well_known_acls'):
797 self.report('Not resetting %s on %s\n' % (sd_attr, dn))
802 m[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
803 if self.do_modify(m, ["sd_flags:1:%d" % sd_flags],
804 "Failed to reset attribute %s" % sd_attr):
805 self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
807 def err_missing_sd_owner(self, dn, sd):
808 '''re-write the SD due to a missing owner or group'''
809 sd_attr = "nTSecurityDescriptor"
810 sd_val = ndr_pack(sd)
811 sd_flags = security.SECINFO_OWNER | security.SECINFO_GROUP
813 if not self.confirm_all('Fix missing owner or group in %s on %s?' % (sd_attr, dn), 'fix_ntsecuritydescriptor_owner_group'):
814 self.report('Not fixing missing owner or group %s on %s\n' % (sd_attr, dn))
819 nmsg[sd_attr] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_REPLACE, sd_attr)
821 # By setting the session_info to admin_session_info and
822 # setting the security.SECINFO_OWNER | security.SECINFO_GROUP
823 # flags we cause the descriptor module to set the correct
824 # owner and group on the SD, replacing the None/NULL values
825 # for owner_sid and group_sid currently present.
827 # The admin_session_info matches that used in provision, and
828 # is the best guess we can make for an existing object that
829 # hasn't had something specifically set.
831 # This is important for the dns related naming contexts.
832 self.samdb.set_session_info(self.admin_session_info)
833 if self.do_modify(nmsg, ["sd_flags:1:%d" % sd_flags],
834 "Failed to fix metadata for attribute %s" % sd_attr):
835 self.report("Fixed attribute '%s' of '%s'\n" % (sd_attr, dn))
836 self.samdb.set_session_info(self.system_session_info)
839 def has_replmetadata_zero_invocationid(self, dn, repl_meta_data):
840 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
845 # Search for a zero invocationID
846 if o.originating_invocation_id != misc.GUID("00000000-0000-0000-0000-000000000000"):
850 self.report('''ERROR: on replPropertyMetaData of %s, the instanceType on attribute 0x%08x,
851 version %d changed at %s is 00000000-0000-0000-0000-000000000000,
852 but should be non-zero. Proposed fix is to set to our invocationID (%s).'''
853 % (dn, o.attid, o.version,
854 time.ctime(samba.nttime2unix(o.originating_change_time)),
855 self.samdb.get_invocation_id()))
860 def err_replmetadata_zero_invocationid(self, dn, attr, repl_meta_data):
861 repl = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
864 now = samba.unix2nttime(int(time.time()))
867 # Search for a zero invocationID
868 if o.originating_invocation_id != misc.GUID("00000000-0000-0000-0000-000000000000"):
872 seq = self.samdb.sequence_number(ldb.SEQ_NEXT)
873 o.version = o.version + 1
874 o.originating_change_time = now
875 o.originating_invocation_id = misc.GUID(self.samdb.get_invocation_id())
876 o.originating_usn = seq
880 replBlob = ndr_pack(repl)
884 if not self.confirm_all('Fix %s on %s by setting originating_invocation_id on some elements to our invocationID %s?'
885 % (attr, dn, self.samdb.get_invocation_id()), 'fix_replmetadata_zero_invocationid'):
886 self.report('Not fixing %s on %s\n' % (attr, dn))
891 nmsg[attr] = ldb.MessageElement(replBlob, ldb.FLAG_MOD_REPLACE, attr)
892 if self.do_modify(nmsg, ["local_oid:1.3.6.1.4.1.7165.4.3.14:0"],
893 "Failed to fix attribute %s" % attr):
894 self.report("Fixed attribute '%s' of '%s'\n" % (attr, dn))
897 def is_deleted_deleted_objects(self, obj):
899 if "description" not in obj:
900 self.report("ERROR: description not present on Deleted Objects container %s" % obj.dn)
902 if "showInAdvancedViewOnly" not in obj:
903 self.report("ERROR: showInAdvancedViewOnly not present on Deleted Objects container %s" % obj.dn)
905 if "objectCategory" not in obj:
906 self.report("ERROR: objectCategory not present on Deleted Objects container %s" % obj.dn)
908 if "isCriticalSystemObject" not in obj:
909 self.report("ERROR: isCriticalSystemObject not present on Deleted Objects container %s" % obj.dn)
911 if "isRecycled" in obj:
912 self.report("ERROR: isRecycled present on Deleted Objects container %s" % obj.dn)
917 def err_deleted_deleted_objects(self, obj):
919 nmsg.dn = dn = obj.dn
921 if "description" not in obj:
922 nmsg["description"] = ldb.MessageElement("Container for deleted objects", ldb.FLAG_MOD_REPLACE, "description")
923 if "showInAdvancedViewOnly" not in obj:
924 nmsg["showInAdvancedViewOnly"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "showInAdvancedViewOnly")
925 if "objectCategory" not in obj:
926 nmsg["objectCategory"] = ldb.MessageElement("CN=Container,%s" % self.schema_dn, ldb.FLAG_MOD_REPLACE, "objectCategory")
927 if "isCriticalSystemObject" not in obj:
928 nmsg["isCriticalSystemObject"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isCriticalSystemObject")
929 if "isRecycled" in obj:
930 nmsg["isRecycled"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_DELETE, "isRecycled")
932 if not self.confirm_all('Fix Deleted Objects container %s by restoring default attributes?'
933 % (dn), 'fix_deleted_deleted_objects'):
934 self.report('Not fixing missing/incorrect attributes on %s\n' % (dn))
937 if self.do_modify(nmsg, ["relax:0"],
938 "Failed to fix Deleted Objects container %s" % dn):
939 self.report("Fixed Deleted Objects container '%s'\n" % (dn))
942 def is_fsmo_role(self, dn):
943 if dn == self.samdb.domain_dn:
945 if dn == self.infrastructure_dn:
947 if dn == self.naming_dn:
949 if dn == self.schema_dn:
951 if dn == self.rid_dn:
956 def calculate_instancetype(self, dn):
958 nc_root = self.samdb.get_nc_root(dn)
960 instancetype |= dsdb.INSTANCE_TYPE_IS_NC_HEAD
962 self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE, attrs=[], controls=["show_recycled:1"])
963 except ldb.LdbError, (enum, estr):
964 if enum != ldb.ERR_NO_SUCH_OBJECT:
967 instancetype |= dsdb.INSTANCE_TYPE_NC_ABOVE
969 if self.write_ncs is not None and str(nc_root) in self.write_ncs:
970 instancetype |= dsdb.INSTANCE_TYPE_WRITE
974 def get_wellknown_sd(self, dn):
975 for [sd_dn, descriptor_fn] in self.wellknown_sds:
977 domain_sid = security.dom_sid(self.samdb.get_domain_sid())
978 return ndr_unpack(security.descriptor,
979 descriptor_fn(domain_sid,
980 name_map=self.name_map))
984 def check_object(self, dn, attrs=['*']):
985 '''check one object'''
987 self.report("Checking object %s" % dn)
989 attrs.append("replPropertyMetaData")
993 sd_flags |= security.SECINFO_OWNER
994 sd_flags |= security.SECINFO_GROUP
995 sd_flags |= security.SECINFO_DACL
996 sd_flags |= security.SECINFO_SACL
998 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
1003 "sd_flags:1:%d" % sd_flags,
1006 except ldb.LdbError, (enum, estr):
1007 if enum == ldb.ERR_NO_SUCH_OBJECT:
1008 if self.in_transaction:
1009 self.report("ERROR: Object %s disappeared during check" % dn)
1014 self.report("ERROR: Object %s failed to load during check" % dn)
1018 list_attrs_from_md = []
1019 list_attrs_seen = []
1020 got_repl_property_meta_data = False
1022 for attrname in obj:
1023 if attrname == 'dn':
1026 if str(attrname).lower() == 'replpropertymetadata':
1027 if self.has_replmetadata_zero_invocationid(dn, obj[attrname]):
1029 self.err_replmetadata_zero_invocationid(dn, attrname, obj[attrname])
1030 # We don't continue, as we may also have other fixes for this attribute
1031 # based on what other attributes we see.
1033 list_attrs_from_md = self.process_metadata(obj[attrname])
1034 got_repl_property_meta_data = True
1037 if str(attrname).lower() == 'ntsecuritydescriptor':
1038 (sd, sd_broken) = self.process_sd(dn, obj)
1039 if sd_broken is not None:
1040 self.err_wrong_sd(dn, sd, sd_broken)
1044 if sd.owner_sid is None or sd.group_sid is None:
1045 self.err_missing_sd_owner(dn, sd)
1049 if self.reset_well_known_acls:
1051 well_known_sd = self.get_wellknown_sd(dn)
1055 current_sd = ndr_unpack(security.descriptor,
1056 str(obj[attrname][0]))
1058 diff = get_diff_sds(well_known_sd, current_sd, security.dom_sid(self.samdb.get_domain_sid()))
1060 self.err_wrong_default_sd(dn, well_known_sd, current_sd, diff)
1065 if str(attrname).lower() == 'objectclass':
1066 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, list(obj[attrname]))
1067 if list(normalised) != list(obj[attrname]):
1068 self.err_normalise_mismatch_replace(dn, attrname, list(obj[attrname]))
1072 # check for empty attributes
1073 for val in obj[attrname]:
1075 self.err_empty_attribute(dn, attrname)
1079 # get the syntax oid for the attribute, so we can can have
1080 # special handling for some specific attribute types
1082 syntax_oid = self.samdb_schema.get_syntax_oid_from_lDAPDisplayName(attrname)
1083 except Exception, msg:
1084 self.err_unknown_attribute(obj, attrname)
1088 flag = self.samdb_schema.get_systemFlags_from_lDAPDisplayName(attrname)
1089 if (not flag & dsdb.DS_FLAG_ATTR_NOT_REPLICATED
1090 and not flag & dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED
1091 and not self.samdb_schema.get_linkId_from_lDAPDisplayName(attrname)):
1092 list_attrs_seen.append(str(attrname).lower())
1094 if syntax_oid in [ dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_OR_NAME,
1095 dsdb.DSDB_SYNTAX_STRING_DN, ldb.SYNTAX_DN ]:
1096 # it's some form of DN, do specialised checking on those
1097 error_count += self.check_dn(obj, attrname, syntax_oid)
1099 # check for incorrectly normalised attributes
1100 for val in obj[attrname]:
1101 normalised = self.samdb.dsdb_normalise_attributes(self.samdb_schema, attrname, [val])
1102 if len(normalised) != 1 or normalised[0] != val:
1103 self.err_normalise_mismatch(dn, attrname, obj[attrname])
1107 if str(attrname).lower() == "instancetype":
1108 calculated_instancetype = self.calculate_instancetype(dn)
1109 if len(obj["instanceType"]) != 1 or obj["instanceType"][0] != str(calculated_instancetype):
1111 self.err_wrong_instancetype(obj, calculated_instancetype)
1114 if got_repl_property_meta_data:
1115 rdn = (str(dn).split(","))[0]
1116 if rdn == "CN=Deleted Objects":
1117 isDeletedAttId = 131120
1118 # It's 29/12/9999 at 23:59:59 UTC as specified in MS-ADTS 7.1.1.4.2 Deleted Objects Container
1120 expectedTimeDo = 2650466015990000000
1121 originating = self.get_originating_time(obj["replPropertyMetaData"], isDeletedAttId)
1122 if originating != expectedTimeDo:
1123 if self.confirm_all("Fix isDeleted originating_change_time on '%s'" % str(dn), 'fix_time_metadata'):
1124 nmsg = ldb.Message()
1126 nmsg["isDeleted"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isDeleted")
1128 self.samdb.modify(nmsg, controls=["provision:0"])
1131 self.report("Not fixing isDeleted originating_change_time on '%s'" % str(dn))
1132 for att in list_attrs_seen:
1133 if not att in list_attrs_from_md:
1135 self.report("On object %s" % dn)
1138 self.report("ERROR: Attribute %s not present in replication metadata" % att)
1139 if not self.confirm_all("Fix missing replPropertyMetaData element '%s'" % att, 'fix_all_metadata'):
1140 self.report("Not fixing missing replPropertyMetaData element '%s'" % att)
1142 self.fix_metadata(dn, att)
1144 if self.is_fsmo_role(dn):
1145 if "fSMORoleOwner" not in obj:
1146 self.err_no_fsmoRoleOwner(obj)
1150 if dn != self.samdb.get_root_basedn():
1151 res = self.samdb.search(base=dn.parent(), scope=ldb.SCOPE_BASE,
1152 controls=["show_recycled:1", "show_deleted:1"])
1153 except ldb.LdbError, (enum, estr):
1154 if enum == ldb.ERR_NO_SUCH_OBJECT:
1155 self.err_missing_parent(obj)
1160 if dn in self.deleted_objects_containers and '*' in attrs:
1161 if self.is_deleted_deleted_objects(obj):
1162 self.err_deleted_deleted_objects(obj)
1167 ################################################################
1168 # check special @ROOTDSE attributes
1169 def check_rootdse(self):
1170 '''check the @ROOTDSE special object'''
1171 dn = ldb.Dn(self.samdb, '@ROOTDSE')
1173 self.report("Checking object %s" % dn)
1174 res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE)
1176 self.report("Object %s disappeared during check" % dn)
1181 # check that the dsServiceName is in GUID form
1182 if not 'dsServiceName' in obj:
1183 self.report('ERROR: dsServiceName missing in @ROOTDSE')
1184 return error_count+1
1186 if not obj['dsServiceName'][0].startswith('<GUID='):
1187 self.report('ERROR: dsServiceName not in GUID form in @ROOTDSE')
1189 if not self.confirm('Change dsServiceName to GUID form?'):
1191 res = self.samdb.search(base=ldb.Dn(self.samdb, obj['dsServiceName'][0]),
1192 scope=ldb.SCOPE_BASE, attrs=['objectGUID'])
1193 guid_str = str(ndr_unpack(misc.GUID, res[0]['objectGUID'][0]))
1196 m['dsServiceName'] = ldb.MessageElement("<GUID=%s>" % guid_str,
1197 ldb.FLAG_MOD_REPLACE, 'dsServiceName')
1198 if self.do_modify(m, [], "Failed to change dsServiceName to GUID form", validate=False):
1199 self.report("Changed dsServiceName to GUID form")
1203 ###############################################
1204 # re-index the database
1205 def reindex_database(self):
1206 '''re-index the whole database'''
1208 m.dn = ldb.Dn(self.samdb, "@ATTRIBUTES")
1209 m['add'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_ADD, 'force_reindex')
1210 m['delete'] = ldb.MessageElement('NONE', ldb.FLAG_MOD_DELETE, 'force_reindex')
1211 return self.do_modify(m, [], 're-indexed database', validate=False)
1213 ###############################################
1215 def reset_modules(self):
1216 '''reset @MODULES to that needed for current sam.ldb (to read a very old database)'''
1218 m.dn = ldb.Dn(self.samdb, "@MODULES")
1219 m['@LIST'] = ldb.MessageElement('samba_dsdb', ldb.FLAG_MOD_REPLACE, '@LIST')
1220 return self.do_modify(m, [], 'reset @MODULES on database', validate=False)